#include "bsp_moto.h"


void bsp_moto_init(uint16_t div, uint16_t period)
{
	gpio_init_type  gpio_init_struct;
	tmr_output_config_type  tmr_output_struct;
	
		/* enable tmr1/gpioa/gpiob clock */
  crm_periph_clock_enable(CRM_TMR4_PERIPH_CLOCK, TRUE);
  crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
	
	gpio_init_struct.gpio_pins = GPIO_PINS_6 | GPIO_PINS_7;
  gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
  gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
  gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
  gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
	gpio_init(GPIOB, &gpio_init_struct);
	
	gpio_pin_mux_config(GPIOB, GPIO_PINS_SOURCE6, GPIO_MUX_2);
  gpio_pin_mux_config(GPIOB, GPIO_PINS_SOURCE7, GPIO_MUX_2);
	
	
	tmr_reset(TMR4);
	tmr_base_init(TMR4, period, div);
  tmr_cnt_dir_set(TMR4, TMR_COUNT_UP);
	
	tmr_output_default_para_init(&tmr_output_struct);
  tmr_output_struct.oc_mode = TMR_OUTPUT_CONTROL_PWM_MODE_A;
  tmr_output_struct.oc_output_state = TRUE;
  tmr_output_struct.oc_polarity = TMR_OUTPUT_ACTIVE_HIGH;
  tmr_output_struct.oc_idle_state = FALSE;
	
	/* channel 1 */
  tmr_output_channel_config(TMR4, TMR_SELECT_CHANNEL_1, &tmr_output_struct);
	tmr_output_channel_buffer_enable(TMR4, TMR_SELECT_CHANNEL_1, TRUE);

  /* channel 2 */
  tmr_output_channel_config(TMR4, TMR_SELECT_CHANNEL_2, &tmr_output_struct);
	tmr_output_channel_buffer_enable(TMR4, TMR_SELECT_CHANNEL_2, TRUE);
	
	tmr_period_buffer_enable(TMR4, TRUE);
  
	
  /* enable tmr1 */
  tmr_counter_enable(TMR4, TRUE);
}


void set_moto_out(uint8_t dir, uint32_t speed)
{
	if( dir == 1 )
    {
       tmr_channel_value_set(TMR4, TMR_SELECT_CHANNEL_1, 0);
       tmr_channel_value_set(TMR4, TMR_SELECT_CHANNEL_2, speed);       
    }
    else
    {
       tmr_channel_value_set(TMR4, TMR_SELECT_CHANNEL_1, speed);
       tmr_channel_value_set(TMR4, TMR_SELECT_CHANNEL_2, 0);   
    }        
}
