Example #1
0
void adcInit(void)
{

  if(isInit)
    return;
	
  ADC_InitTypeDef ADC_InitStructure;
	ADC_CommonInitTypeDef		ADC_CommonInitStructure;
	
  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
  TIM_OCInitTypeDef TIM_OCInitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;

  // Enable TIM2, GPIOA and ADC1 clock
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
	
  //Timer configuration
  TIM_TimeBaseStructure.TIM_Period = ADC_TRIG_PERIOD;
  TIM_TimeBaseStructure.TIM_Prescaler = ADC_TRIG_PRESCALE;
  TIM_TimeBaseStructure.TIM_ClockDivision = 4;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  // TIM2 channel2 configuration in PWM mode
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OC2Init(TIM2, &TIM_OCInitStructure);
  TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);
	
  // Halt timer 2 during debug halt.
  DBGMCU_Config(DBGMCU_TIM2_STOP, ENABLE);

  adcDmaInit();

  // ADC1 configuration
  ADC_CommonStructInit(&ADC_CommonInitStructure);
  ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
	ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div8;
	ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
	ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
	ADC_CommonInit(&ADC_CommonInitStructure);	
	
	ADC_StructInit(&ADC_InitStructure);
	ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
	ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_Rising;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T2_CC2;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfConversion = 2;
  ADC_Init(ADC1, &ADC_InitStructure);

  // ADC1 channel sequence
  ADC_RegularChannelConfig(ADC1, CH_VREF, 1, ADC_SampleTime_28Cycles);
  ADC_RegularChannelConfig(ADC1, CH_VBAT, 2, ADC_SampleTime_28Cycles);

	ADC_DMARequestAfterLastTransferCmd(ADC1, ENABLE);
	ADC_VBATCmd(ENABLE);
  // Enable ADC1
  ADC_Cmd(ADC1, ENABLE);

  // Enable the DMA1 channel Interrupt
  NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream0_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_ADC_PRI;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  adcQueue = xQueueCreate(1, sizeof(AdcGroup));

  xTaskCreate(adcTask, "ADC", configMINIMAL_STACK_SIZE, NULL,
							/*priority*/3, NULL);

  isInit = true;
}
Example #2
0
void TIM2_Init()   //转向电机
{
	

	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_ICInitTypeDef TIM_ICInitStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;
	NVIC_InitTypeDef   NVIC_InitStructure; 

	/*----------------------------------------------------------------*/

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);


	GPIO_StructInit(&GPIO_InitStructure);
	/* Configure PA.06,07 as encoder input */
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	/*----------------------------------------------------------------*/	


	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //使能TIM3
	TIM_DeInit(TIM2);
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

	TIM_TimeBaseStructure.TIM_Period =4000;       
	TIM_TimeBaseStructure.TIM_Prescaler =0;	    //设置预分频:
	TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1 ;	//设置时钟分频系数:不分频
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //向上计数模式
	//TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1; 
	/*初始化TIM3定时器 */
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

	/*-----------------------------------------------------------------*/
	//编码配置                        编码模式
	TIM_EncoderInterfaceConfig(TIM2, TIM_EncoderMode_TI12, 
	                         TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);  //TIM_ICPolarity_Rising上升沿捕获
	TIM_ICStructInit(&TIM_ICInitStructure);
	TIM_ICInitStructure.TIM_ICFilter = 1;         //比较滤波器
	TIM_ICInit(TIM2, &TIM_ICInitStructure);
   
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing; 
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable; 
	TIM_OCInitStructure.TIM_Pulse = Angle_Target_Interrupt;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC3Init(TIM2, &TIM_OCInitStructure);
	TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);//禁止 TIM_CCR1 寄存器的预装载使能
	TIM_ITConfig(TIM2, TIM_IT_CC3, DISABLE);//中断使能 TIM_Cmd(TIM2, ENABLE); //开启定时器(即设置 CEN 位)




	// TIM_OCStructInit(&TIM_OCInitStructure);       //中断实现特定角度转动的配置
	// TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
	// TIM_OCInitStructure.TIM_Pulse = Angle_Target_Interrupt;
	// TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
	// TIM_OC3Init(TIM2, &TIM_OCInitStructure);
	// TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);
	// TIM_ITConfig(TIM2, TIM_IT_CC3, ENABLE);

	TIM_ClearFlag(TIM2, TIM_FLAG_CC3);
	TIM_ITConfig(TIM2, TIM_IT_Update, DISABLE);   //使能中断
	//Reset counter
	TIM2->CNT = 0;   


	TIM_Cmd(TIM2, ENABLE);   //使能定时器3

	/* Enable the TIM2 Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);   
}
Example #3
0
File: pwm.c Project: intchar90/AHRS
void TIM3_Config(void)	//PWM输出
{
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	TIM_OCInitTypeDef TIM_OCInitStructure;
	uint16_t CCR1_Val = 1000;
	uint16_t CCR2_Val = 1200;
	uint16_t CCR3_Val = 1000;
	uint16_t CCR4_Val = 1000;
	uint16_t PrescalerValue = 0;
	GPIO_InitTypeDef GPIO_InitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB,ENABLE);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
	GPIO_Init(GPIOB, &GPIO_InitStructure);	

	PrescalerValue = (uint16_t) (SystemCoreClock / 1000000) - 1;
	TIM_TimeBaseStructure.TIM_Period = 5000;                                  //周期
	TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;              //分频
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;                             //时钟分割
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	                //计数模式
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);                    //初始TIM3
	
	/*************************** 通道1 ********************************/
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //PWM2
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;   //PWM功能使能
	TIM_OCInitStructure.TIM_Pulse = CCR1_Val;                            //写比较值(占空比
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;   //置高
	TIM_OC1Init(TIM3, &TIM_OCInitStructure);
	TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
	
	/****************************** 通道2 ******************************/
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //PWM2
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = CCR2_Val;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
	TIM_OC2Init(TIM3, &TIM_OCInitStructure);
	TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
	
	/******************************* 通道3 *********************************/
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //PWM2
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = CCR3_Val;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
	TIM_OC3Init(TIM3, &TIM_OCInitStructure);
	TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
	
	/****************************** 通道4 *********************************/
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //PWM2
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = CCR4_Val;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
	TIM_OC4Init(TIM3, &TIM_OCInitStructure);
	TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
	
	TIM_ARRPreloadConfig(TIM3, ENABLE);                        //
	TIM_Cmd(TIM3, ENABLE);                                          //使能计数
}
Example #4
0
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32l1xx_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32l1xx.c file
     */     
       
  /* ------------------------- System Clocks Configuration ------------------------------*/
  /* GPIOD clock enable */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
  /* TIM3 clock enable */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  /* ------------------------- GPIO Configuration ------------------------------*/ 
  /* GPIOD Configuration: PD.00, PD.01, PD.04, PD.05 */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1| GPIO_Pin_4 | GPIO_Pin_5 ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType =  GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_40MHz;
  GPIO_Init(GPIOD, &GPIO_InitStructure); 
  /* ---------------------------------------------------------------
   TIM3 Configuration: 
   The objective is to get TIM3 counter clock at 1 KHz:
    - Prescaler = (TIM3CLK / TIM3 counter clock) - 1
   And generate 4 signals with 4 different delays:
   TIM3_CH1 delay = CCR1_Val/TIM3 counter clock = 1000 ms
   TIM3_CH2 delay = CCR2_Val/TIM3 counter clock = 500 ms
   TIM3_CH3 delay = CCR3_Val/TIM3 counter clock = 250 ms
   TIM3_CH4 delay = CCR4_Val/TIM3 counter clock = 125 ms
  --------------------------------------------------------------- */
  PrescalerValue = (uint16_t) (SystemCoreClock / 1000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 0xFFFF;          
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;       
  TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;    
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; 
  
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* Output Compare Timing Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Inactive;                   
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;  
  
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);   
  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);
  TIM_ARRPreloadConfig(TIM3, DISABLE); 

  /* Output Compare Timing Mode configuration: Channel2 */          
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;    
  TIM_OC2Init(TIM3, &TIM_OCInitStructure); 
  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel3 */          
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;  
  
  TIM_OC3Init(TIM3, &TIM_OCInitStructure);
  
  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable); 

  /* Output Compare Timing Mode configuration: Channel4 */          
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;  
  
  TIM_OC4Init(TIM3, &TIM_OCInitStructure);
  
  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable); 

  /* TIM Interrupt configuration */
  TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);
  TIM_ITConfig(TIM3, TIM_IT_CC2, ENABLE);
  TIM_ITConfig(TIM3, TIM_IT_CC3, ENABLE);
  TIM_ITConfig(TIM3, TIM_IT_CC4, ENABLE);

  /* ------------------------- NVIC Configuration ------------------------------ */
  NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Set PD.00, PD.01, PD.04 and PD.05 pins */
  GPIO_SetBits(GPIOD, GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_4 | GPIO_Pin_5);

  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);
  
  while (1)
  {}
}
Example #5
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG , ENABLE);
   
   RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC  | RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOA, ENABLE );
   
   RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM3 | RCC_APB1Periph_TIM3, ENABLE );

 
 
    volatile int i;
    int n = 1;
    
     
    GPIO_StructInit(&GPIO_InitStructure); // Reset init structure
    GPIO_StructInit(&GPIO_InitStructure2); // Reset init structure
    GPIO_StructInit(&GPIO_InitStructure3); // Reset init structure
 
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_TIM3);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_TIM3);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource8, GPIO_AF_TIM3);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource9, GPIO_AF_TIM3);
    
    //GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_TIM3);
    //GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_TIM3);

/**
	PWM
		Output	PortC 6 7 8 9
		AF TIM3				
								**/    
    

    // Setup Servo on STM32-Discovery Board to use PWM.
    GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_6 | GPIO_Pin_7| GPIO_Pin_8| GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;            // Alt Function - Push Pull
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init( GPIOC, &GPIO_InitStructure );  
    

/**
	Button
		Output PortB 4 5
						 **/

    /* GPIOA Configuration: CH1 (PB4) and CH2 (PB5) */
    GPIO_InitStructure2.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 ;
    GPIO_InitStructure2.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStructure2.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure2.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure2.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOB, &GPIO_InitStructure2);

    GPIOB->BSRRL = GPIO_Pin_4;
    GPIOB->BSRRL = GPIO_Pin_5;

/**
	Button
		Input PortA 2 3
						**/

    /* GPIOA Configuration: (PA2) and (PA3) */     //input
    GPIO_InitStructure2.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 ;
    GPIO_InitStructure2.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure2.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure2.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure2.GPIO_PuPd = GPIO_PuPd_DOWN ;
    GPIO_Init(GPIOA, &GPIO_InitStructure2); 
    
/**	
	Button A2 A3 Interrupt
	EXTI 2 3		
							**/ 

    //清空中断标志
    EXTI_ClearITPendingBit(EXTI_Line2);
    EXTI_ClearITPendingBit(EXTI_Line3);

    //选择中断管脚PA.2 PA.3 
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource2);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource3);
  //    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA,EXTI_PinSource0);
  //   SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA,EXTI_PinSource0);
    
    
    EXTI_InitStructure.EXTI_Line = EXTI_Line2  ; //选择中断线路2 
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //设置为中断请求,非事件请求
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; //设置中断触发方式为上下降沿触发
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;            //外部中断使能
    EXTI_Init(&EXTI_InitStructure);
    EXTI_GenerateSWInterrupt(EXTI_Line2);
    
    
    EXTI_InitStructure.EXTI_Line = EXTI_Line3 ; //选择中断线路2 
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //设置为中断请求,非事件请求
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; //设置中断触发方式为上下降沿触发
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;            //外部中断使能
    EXTI_Init(&EXTI_InitStructure);
    EXTI_GenerateSWInterrupt(EXTI_Line3);
   
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);      //选择中断分组2
    NVIC_InitStructure.NVIC_IRQChannel = EXTI2_IRQn  ;     //选择中断通道2
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占式中断优先级设置为0
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;        //响应式中断优先级设置为0
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;                                   //使能中断
    NVIC_Init(&NVIC_InitStructure);
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);    //选择中断分组2
    NVIC_InitStructure.NVIC_IRQChannel = EXTI3_IRQn;     //选择中断通道2
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占式中断优先级设置为0
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;        //响应式中断优先级设置为0
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;                                   //使能中断
    NVIC_Init(&NVIC_InitStructure);
    
    
/**
	Timer setting
	Tim3
					**/
    
    PrescalerValue = (uint16_t) ((SystemCoreClock /4) / 100000) - 1;
    
    // Let PWM frequency equal 100Hz.
    // Let period equal 1000. Therefore, timer runs from zero to 1000. Gives 0.1Hz resolution.
    // Solving for prescaler gives 240.
    TIM_TimeBaseStructInit( &TIM_TimeBaseInitStruct );
    TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStruct.TIM_Period = 3360 - 1;   // 0..2000
    TIM_TimeBaseInitStruct.TIM_Prescaler = 500; 
    TIM_TimeBaseInit( TIM3, &TIM_TimeBaseInitStruct );
 /**
		TIM_Prescaler = 500-1, TIM_Period = 1680-1 , TIMxCLK = 84MHz
		輸出脈波週期 = (TIM_Period + 1) * (TIM_Prescaler + 1) / TIMxCLK
		= ( 1680 - 1 +1 ) * ( 500 - 1 + 1 ) / 84000000 = 0.01s(100Hz)
																		**/   

    TIM_OCStructInit( &TIM_OCInitStruct );
    TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
    // Initial duty cycle equals 0%. Value can range from zero to 1000.
    TIM_OCInitStruct.TIM_Pulse = 3360 -1; // 0 .. 1680 (0=Always Off, 1680=Always On)
    
    
    TIM_OC1Init( TIM3, &TIM_OCInitStruct ); // Channel 1  Servo
    TIM_OC2Init( TIM3, &TIM_OCInitStruct ); // Channel 2  Servo
    TIM_OC3Init( TIM3, &TIM_OCInitStruct ); // Channel 3 PB7 Servo L
    TIM_OC4Init( TIM3, &TIM_OCInitStruct ); // Channel 4 PB8 Servo R
    TIM_Cmd( TIM3, ENABLE );

/** 
	Project Testing
						**/

  while(1)  // Do not exit
  {

//Test 1

	if(TIM3->CCR4>0){
		for(i=0;i<16000000;i++);
		TIM3->CCR4 = 0;
	}
/*
//Test 2
	TIM3->CCR4 = 168;
	for(i=0;i<16000000;i++);
	TIM3->CCR4 = 336;
	for(i=0;i<16000000;i++);
	TIM3->CCR4 = 252;
	for(i=0;i<16000000;i++);

/*
//Test 3

    if (((brightness + n) >= 3000) || ((brightness + n) <= 0))
      n = -n; // if  brightness maximum/maximum change direction
 
        brightness += n;
 
   	TIM3->CCR1 = brightness; // set brightness
    TIM3->CCR2 = 1000 - brightness; // set brightness
    TIM3->CCR3 = 3000 - brightness; // set brightness
    TIM3->CCR4 = 3000 - brightness; // set brightness
 
    for(i=0;i<10000;i++);  // delay
    //Delay(250000);
    //Delay(1000000);
    //Delay(1000000);
*/  
   }
 
  return(0); // System will implode
/**
	Others
			**/
  
  if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
  {
    if ((*(__IO uint32_t*) TESTRESULT_ADDRESS) == ALLTEST_PASS)
    {
     
      /* Waiting User Button is pressed or Test Program condition verified */
      while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)&&(TimingDelay != 0x00))
      {}
    }
    else
    {
      /* Waiting User Button is Released  or TimeOut*/
     
      while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)&&(TimingDelay != 0x00))
      {}
      if (STM_EVAL_PBGetState(BUTTON_USER) == Bit_RESET)
      {
        
      }
    }
    if (TimingDelay == 0x00)
    {
      /* Turn off LEDs available on STM32F4-Discovery ------------------------*/
      /* Waiting User Button is released */
      while (STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET)
      {}
      
      /* Unlocks the FLASH control register access */
      FLASH_Unlock();
      
      /* Move discovery kit to detect negative and positive acceleration values 
      on X, Y and Z axis */
      Accelerometer_MEMS_Test();
      
      /* USB Hardware connection */
      USB_Test();
      
      /* Audio Hardware connection */
      Audio_Test();
      
      /* Microphone MEMS Hardware connection */
      Microphone_MEMS_Test();
      
      /* Write PASS code at last word in the flash memory */
      FLASH_ProgramWord(TESTRESULT_ADDRESS, ALLTEST_PASS);
      
      while(1)
      {
        /* Toggle Green LED: signaling the End of the Test program */
        STM_EVAL_LEDToggle(LED4);
        Delay(41999/2);
      }
    }
    else
    {
      Demo_Exec();
    }
  }
  else
  {    
    Demo_Exec();
  }
}
Example #6
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* TIM Configuration */
  TIM_Config();

  /* -----------------------------------------------------------------------
    TIM3 Configuration: generate 4 PWM signals with 4 different duty cycles.
    
    In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM3CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM3CLK = HCLK / 2 = SystemCoreClock /2
          
    To get TIM3 counter clock at 28 MHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = ((SystemCoreClock /2) /28 MHz) - 1
                                              
    To get TIM3 output clock at 30 KHz, the period (ARR)) is computed as follows:
       ARR = (TIM3 counter clock / TIM3 output clock) - 1
           = 665
                  
    TIM3 Channel1 duty cycle = (TIM3_CCR1/ TIM3_ARR)* 100 = 50%
    TIM3 Channel2 duty cycle = (TIM3_CCR2/ TIM3_ARR)* 100 = 37.5%
    TIM3 Channel3 duty cycle = (TIM3_CCR3/ TIM3_ARR)* 100 = 25%
    TIM3 Channel4 duty cycle = (TIM3_CCR4/ TIM3_ARR)* 100 = 12.5%

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  ----------------------------------------------------------------------- */  

  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) ((SystemCoreClock /2) / 28000000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 665;
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* PWM1 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);

  /* PWM1 Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);

  TIM_ARRPreloadConfig(TIM3, ENABLE);

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE);

  while (1)
  {}
}
Example #7
0
void Timer1Config() {

    /* TIM1 example -------------------------------------------------
  
       TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2), since APB2 
       prescaler is different from 1.   
       TIM1CLK = 2 * PCLK2  
       PCLK2 = HCLK / 2 
       => TIM1CLK = 2 * (HCLK / 2) = HCLK = SystemCoreClock
  
       TIM1CLK = SystemCoreClock, Prescaler = 0, TIM1 counter clock = SystemCoreClock
       SystemCoreClock is set to 168 MHz for STM32F4xx devices.

       The objective is to configure TIM1 channel 3 to generate complementary PWM
       signal with a frequency equal to F KHz:
       - TIM1_Period = (SystemCoreClock / F) - 1

       The number of this repetitive requests is defined by the TIM1 Repetion counter,
       each 3 Update Requests, the TIM1 Channel 3 Duty Cycle changes to the next new 
       value defined by the aSRC_Buffer.
  
       Note: 
       SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
       Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
       function to update SystemCoreClock variable value. Otherwise, any configuration
       based on this variable will be incorrect.  
       -----------------------------------------------------------------------------*/
  
    /* Compute the value to be set in ARR regiter to generate signal frequency at 16.00 Khz */
    uhTimerPeriod = (SystemCoreClock / 16000 ) - 1;
    /* Compute CCR1 value to generate a duty cycle at 50% */
    aSRC_Buffer[0] = (uint16_t) (((uint32_t) 5 * (uhTimerPeriod - 1)) / 10);
    /* Compute CCR1 value to generate a duty cycle at 37.5% */
    aSRC_Buffer[1] = (uint16_t) (((uint32_t) 375 * (uhTimerPeriod - 1)) / 1000);
    /* Compute CCR1 value to generate a duty cycle at 25% */
    aSRC_Buffer[2] = (uint16_t) (((uint32_t) 25 * (uhTimerPeriod - 1)) / 100);

    /* TIM1 Peripheral Configuration -------------------------------------------*/
    /* TIM1 clock enable */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);

    /* Time Base configuration */

    TIM_DeInit(TIM1);
    TIM_TimeBaseStructure.TIM_Prescaler = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_Period = uhTimerPeriod;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

    /* Channel 3 Configuration in PWM mode */

    /* I think we just ned to enable channel 3 somehow, but without
       (or optionally with) actual ouput to a GPIO pin.  */

    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
    TIM_OCInitStructure.TIM_Pulse = aSRC_Buffer[0];
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
    TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

    TIM_OC3Init(TIM1, &TIM_OCInitStructure);

    /* Enable preload feature */
    TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
  
    /* TIM1 counter enable */
    TIM_Cmd(TIM1, ENABLE);
  
    /* Main Output Enable */
    TIM_CtrlPWMOutputs(TIM1, ENABLE);
}
Example #8
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* TIM Configuration */
  TIM_Config();

  /* -----------------------------------------------------------------------
    TIM3 Configuration: Output Compare Timing Mode:
    
    In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM3CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM3CLK = HCLK / 2 = SystemCoreClock /2
          
    To get TIM3 counter clock at 50 MHz, the prescaler is computed as follows:
       Prescaler = (TIM3CLK / TIM3 counter clock) - 1
       Prescaler = ((SystemCoreClock /2) /50 MHz) - 1
                                              
    CC1 update rate = TIM3 counter clock / CCR1_Val = 9.154 Hz
    ==> Toggling frequency = 4.57 Hz
    
    C2 update rate = TIM3 counter clock / CCR2_Val = 18.31 Hz
    ==> Toggling frequency = 9.15 Hz
    
    CC3 update rate = TIM3 counter clock / CCR3_Val = 36.62 Hz
    ==> Toggling frequency = 18.31 Hz
    
    CC4 update rate = TIM3 counter clock / CCR4_Val = 73.25 Hz
    ==> Toggling frequency = 36.62 Hz

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  ----------------------------------------------------------------------- */  

  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 500000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  /* Prescaler configuration */
  TIM_PrescalerConfig(TIM3, PrescalerValue, TIM_PSCReloadMode_Immediate);

  /* Output Compare Timing Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM3, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM3, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable);

  /* Output Compare Timing Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM3, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable);
   
  /* TIM Interrupts enable */
  TIM_ITConfig(TIM3, TIM_IT_CC1 | TIM_IT_CC2 | TIM_IT_CC3 | TIM_IT_CC4, ENABLE);

  /* TIM3 enable counter */
  TIM_Cmd(TIM3, ENABLE);

  while (1);
}
Example #9
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s)
       before to branch to application main. 
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */

  /* TIM Configuration */
  TIM_Config();

  /* ---------------------------------------------------------------------------
     TIM9 Configuration: Output Compare Toggle Mode:
    
    In this example TIM9 input clock (TIM9CLK) is set to 2 * APB2 clock (PCLK2), 
    since APB2 prescaler is different from 1.   
      TIM9CLK = 2 * PCLK2  
      PCLK2 = HCLK / 2 
      => TIM9CLK = HCLK = SystemCoreClock
          
    To get TIM9 counter clock at 15 MHz, the prescaler is computed as follows:
       Prescaler = (TIM9CLK / TIM9 counter clock) - 1
       Prescaler = (SystemCoreClock /15 MHz) - 1
                                              
    CC1 update rate = TIM9 counter clock / CCR1_Val = 366.2 Hz
    ==> So the TIM9 Channel 1 generates a periodic signal with 
	      a frequency equal to 183.1 Hz

    CC2 update rate = TIM9 counter clock / CCR2_Val = 732.4 Hz
    ==> So the TIM9 channel 2 generates a periodic signal with 
	      a frequency equal to 366.3 Hz

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    
  --------------------------------------------------------------------------- */   


  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) (SystemCoreClock / 15000000) - 1;

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM9, &TIM_TimeBaseStructure);

  /* Output Compare Toggle Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OC1Init(TIM9, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM9, TIM_OCPreload_Disable);

  /* Output Compare Toggle Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM9, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM9, TIM_OCPreload_Disable);

  /* TIM enable counter */
  TIM_Cmd(TIM9, ENABLE);

  /* TIM IT enable */
  TIM_ITConfig(TIM9, TIM_IT_CC1 | TIM_IT_CC2, ENABLE);

  while (1)
  {}
}
Example #10
0
/**
  * @brief  Configure the TIM2 Pins.
  * @param  None
  * @retval None
  */
void TIM_Config(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
  TIM_ICInitTypeDef  TIM_ICInitStructure;
  TIM_OCInitTypeDef  TIM_OCInitStructure;
  uint16_t PrescalerValue = 0;
  
  /* TIM2 clock enable */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

  /* GPIOA clock enable */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
  
  /* TIM2_CH1 pin (PA.00) and TIM2_CH2 pin (PA.01) configuration */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  /* Connect TIM pins to AF1 */
  GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_1);
  GPIO_PinAFConfig(GPIOA, GPIO_PinSource1, GPIO_AF_1); 
  
  /* --------------------------------------------------------------------------
    TIM2 configuration: Retrigerrable One Pulse mode
    The external signal is connected to TIM2_CH2 pin (PA.01), 
    The Rising edge is used as active edge,
    The Retrigerrable One Pulse signal is output on TIM2_CH1 pin (PA.00)
    The TIM_Pulse is defines by the TIM_Period 
         
    TIM2 input clock (TIM2CLK) is set to 2*APB1 clock (PCLK1)   
      TIM2CLK = 2*PCLK1  
      PCLK1 = HCLK  
      => TIM2CLK = HCLK  = SystemCoreClock 

    TIM2CLK = SystemCoreClock, we want to get TIM2 counter clock at 36 MHz:
     Prescaler = (TIM2CLK / TIM2 counter clock) - 1
     Prescaler = (SystemCoreClock  /36 MHz) - 1
     
    The Autoreload value is 65535 (TIM2->ARR), so the maximum frequency value 
    to trigger the TIM2 input is 36000000/65535 = 549.3 Hz.

    The pulse value is fixed to 1.82 ms:
    One Pulse value = TIM_Period / TIM2 counter clock = 1.82 ms.

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f30x.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    

  --------------------------------------------------------------------------- */

  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) ((SystemCoreClock ) / 36000000) - 1;
  
  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = PULSE_LENGTH;
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  /* Init TIM_OCInitStructure */
  TIM_OCStructInit(&TIM_OCInitStructure);
  
  /* TIM2 PWM2 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Retrigerrable_OPM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 0;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  /* TIM2 configuration in Input Capture Mode */

  TIM_ICStructInit(&TIM_ICInitStructure);

  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0;

  TIM_ICInit(TIM2, &TIM_ICInitStructure);

  /* Input Trigger selection */
  TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2);

  /* Slave Mode selection: Trigger Mode */
  TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Combined_ResetTrigger);    
}
Example #11
0
/**
  * @brief  Enabling the ADC and temperature sensor. Initializing them and defining GPIO pins.
  * @param  None
  * @retval None
  */
void temp_init(){

	//GPIO D Init
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);  //Clock Gating
	
	GPIO_InitTypeDef gpio_init_s;
	GPIO_StructInit(&gpio_init_s);
	gpio_init_s.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;// Select pin 4
	gpio_init_s.GPIO_Mode = GPIO_Mode_OUT; // Set as output
	gpio_init_s.GPIO_Speed = GPIO_Speed_100MHz; // Don't limit slew rate
	gpio_init_s.GPIO_OType = GPIO_OType_PP; // Push-pull
	gpio_init_s.GPIO_PuPd = GPIO_PuPd_NOPULL; // Not input, don't pull
	
	GPIO_Init(GPIOD, &gpio_init_s);	//Initialize GPIOD

	//ADC Init
	ADC_DeInit();
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); //Enabling Clock (Clock Gating)
	
	ADC_CommonInitTypeDef adc_common_init_s;
	adc_common_init_s.ADC_Mode = ADC_Mode_Independent;
	adc_common_init_s.ADC_Prescaler = ADC_Prescaler_Div2;
	adc_common_init_s.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
	adc_common_init_s.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
	ADC_CommonInit(&adc_common_init_s); //Initialization
	
	ADC_InitTypeDef adc_init_s;
	adc_init_s.ADC_Resolution = ADC_Resolution_12b;
	adc_init_s.ADC_ScanConvMode = DISABLE; // To ensure one sample at a time
	adc_init_s.ADC_ContinuousConvMode = DISABLE;
	adc_init_s.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
	adc_init_s.ADC_DataAlign = ADC_DataAlign_Right; // Aligns data to the right, filling empty left with 0s
	adc_init_s.ADC_NbrOfConversion = 1;
	ADC_Init(ADC1, &adc_init_s); //Initialization

	//Enable
	ADC_TempSensorVrefintCmd(ENABLE); //Enable Temperature Sensor
	ADC_Cmd(ADC1, ENABLE); //Enable ADC1
	
	//Initialize Timer 2
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

	TIM_TimeBaseInitTypeDef timerInitStructure; 
	timerInitStructure.TIM_Prescaler = 100 - 1;
	timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	timerInitStructure.TIM_Period = 500 - 1;
	timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	timerInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM2, &timerInitStructure);
	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
	TIM_Cmd(TIM2, ENABLE);
	
	//Enable interrupt control and set priority of TIM2_IRQn
	NVIC_InitTypeDef   NVIC_config_s;
	NVIC_config_s.NVIC_IRQChannel = TIM2_IRQn; //Channel
	NVIC_config_s.NVIC_IRQChannelPreemptionPriority = 0x00; //Set x higher than y
	NVIC_config_s.NVIC_IRQChannelSubPriority = 0x02; //Set x1 higher the x2
	NVIC_config_s.NVIC_IRQChannelCmd = ENABLE; //Enable
	NVIC_Init(&NVIC_config_s);
}
Example #12
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f4xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f4xx.c file
     */     
       
  /* TIM Configuration */
  TIM_Config();

  /* --------------------------------------------------------------------------
    TIM4 configuration: One Pulse mode
    The external signal is connected to TIM4_CH2 pin (PB.07), 
    The Rising edge is used as active edge,
    The One Pulse signal is output on TIM4_CH1 pin (PB.06)
    The TIM_Pulse defines the delay value 
    The (TIM_Period -  TIM_Pulse) defines the One Pulse value.
     
    TIM4 input clock (TIM4CLK) is set to 2 * APB1 clock (PCLK1), 
    since APB1 prescaler is different from 1.   
      TIM4CLK = 2 * PCLK1  
      PCLK1 = HCLK / 4 
      => TIM4CLK = HCLK / 2 = SystemCoreClock /2

    TIM2CLK = SystemCoreClock/2, we want to get TIM2 counter clock at 42 MHz:
     Prescaler = (TIM2CLK / TIM2 counter clock) - 1
     Prescaler = ((SystemCoreClock /2) /42 MHz) - 1
     
    The Autoreload value is 65535 (TIM4->ARR), so the maximum frequency value 
    to trigger the TIM4 input is 42000000/65535 = 641 Hz.

    The TIM_Pulse defines the delay value, the delay value is fixed 
    to 390 us:
    delay =  CCR1/TIM4 counter clock 
          = 16383 / 42000000 = 390 us. 
    The (TIM_Period - TIM_Pulse) defines the One Pulse value, 
    the pulse value is fixed to 1.170 ms:
    One Pulse value = (TIM_Period - TIM_Pulse) / TIM4 counter clock 
                    = (65535 - 16383) / 42000000 = 1.170 ms.

    Note: 
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.    

  --------------------------------------------------------------------------- */

  /* Compute the prescaler value */
  PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 42000000) - 1;
  
  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  /* TIM4 PWM2 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 16383;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* TIM4 configuration in Input Capture Mode */

  TIM_ICStructInit(&TIM_ICInitStructure);

  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0;

  TIM_ICInit(TIM4, &TIM_ICInitStructure);

  /* One Pulse Mode selection */
  TIM_SelectOnePulseMode(TIM4, TIM_OPMode_Single);

  /* Input Trigger selection */
  TIM_SelectInputTrigger(TIM4, TIM_TS_TI2FP2);

  /* Slave Mode selection: Trigger Mode */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Trigger);

  while (1)
  {}
}
Example #13
0
void ILI9341::configBacklightPWM()
{
  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
  TIM_OCInitTypeDef TIM_OCInitStructure;

  /* TIM Config */

  GPIO_InitTypeDef GPIO_InitStructure;

  /* TIM4 Clock Enable */

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

  /* LEDs and GPIO */

  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_Init(GPIOD, &GPIO_InitStructure);

  /*  TODO: Find the correct PIN for PWM */

  GPIO_PinAFConfig(GPIOD, GPIO_PinSource12, GPIO_AF_TIM4);

  /* PWM Setup */

  // Compute the Prescaler Value
  PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 21000000)
    - 1;
  
  /* Time base config */

  TIM_TimeBaseStructure.TIM_Period = 665;
  TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  /* PWM1 Mode configuration: Channel 1 */

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 0;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);

  /* PWM1 Mode Configuration: Channel 2 */

  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 0;

  TIM_ARRPreloadConfig(TIM4, ENABLE);

  /* TIM4 Enable Counter */

  TIM_Cmd(TIM4, ENABLE);
}
Example #14
0
ServoTim1::ServoTim1(){
	/////////////////////////////////////
	//GPIO
	/////////////////////////////////////
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE);
	GPIO_InitTypeDef gpioe9;
	GPIO_StructInit(&gpioe9);
	gpioe9.GPIO_Pin = GPIO_Pin_9;
	gpioe9.GPIO_Mode = GPIO_Mode_AF;
	gpioe9.GPIO_OType = GPIO_OType_PP;
	gpioe9.GPIO_Speed = GPIO_Speed_100MHz;
	gpioe9.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOE,&gpioe9);
	GPIO_PinAFConfig(GPIOE,GPIO_PinSource9,GPIO_AF_TIM1);
	
	GPIO_InitTypeDef gpioe11;
	GPIO_StructInit(&gpioe11);
	gpioe11.GPIO_Pin = GPIO_Pin_11;
	gpioe11.GPIO_Mode = GPIO_Mode_AF;
	gpioe11.GPIO_OType = GPIO_OType_PP;
	gpioe11.GPIO_Speed = GPIO_Speed_100MHz;
	gpioe11.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOE,&gpioe11);
	GPIO_PinAFConfig(GPIOE,GPIO_PinSource11,GPIO_AF_TIM1);
	
	GPIO_InitTypeDef gpioe13;
	GPIO_StructInit(&gpioe13);
	gpioe13.GPIO_Pin = GPIO_Pin_13;
	gpioe13.GPIO_Mode = GPIO_Mode_AF;
	gpioe13.GPIO_OType = GPIO_OType_PP;
	gpioe13.GPIO_Speed = GPIO_Speed_100MHz;
	gpioe13.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOE,&gpioe13);
	GPIO_PinAFConfig(GPIOE,GPIO_PinSource13,GPIO_AF_TIM1);
	
	GPIO_InitTypeDef gpioe14;
	GPIO_StructInit(&gpioe14);
	gpioe14.GPIO_Pin = GPIO_Pin_14;
	gpioe14.GPIO_Mode = GPIO_Mode_AF;
	gpioe14.GPIO_OType = GPIO_OType_PP;
	gpioe14.GPIO_Speed = GPIO_Speed_100MHz;
	gpioe14.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(GPIOE,&gpioe14);
	GPIO_PinAFConfig(GPIOE,GPIO_PinSource14,GPIO_AF_TIM1);
	
	/////////////////////////////////////
	//TIM
	/////////////////////////////////////
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
	TIM_TimeBaseInitTypeDef timebase;
	TIM_TimeBaseStructInit(&timebase);
	timebase.TIM_ClockDivision = TIM_CKD_DIV1;
	timebase.TIM_Prescaler = 168-1;
	timebase.TIM_Period = 15000-1;
	timebase.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM1,&timebase);
	
	TIM_OCInitTypeDef oc1def;
	TIM_OCStructInit(&oc1def);
	oc1def.TIM_OCMode = TIM_OCMode_PWM1;
	oc1def.TIM_OutputState = TIM_OutputState_Enable;
	oc1def.TIM_OCPolarity = TIM_OCPolarity_High;
	oc1def.TIM_Pulse = 1500-1;
	TIM_OC1Init(TIM1,&oc1def);
	
	TIM_OCInitTypeDef oc2def;
	TIM_OCStructInit(&oc2def);
	oc2def.TIM_OCMode = TIM_OCMode_PWM1;
	oc2def.TIM_OutputState = TIM_OutputState_Enable;
	oc2def.TIM_OCPolarity = TIM_OCPolarity_High;
	oc2def.TIM_Pulse = 1500-1;
	TIM_OC2Init(TIM1,&oc2def);
	
	TIM_OCInitTypeDef oc3def;
	TIM_OCStructInit(&oc3def);
	oc3def.TIM_OCMode = TIM_OCMode_PWM1;
	oc3def.TIM_OutputState = TIM_OutputState_Enable;
	oc3def.TIM_OCPolarity = TIM_OCPolarity_High;
	oc3def.TIM_Pulse = 1500-1;
	TIM_OC3Init(TIM1,&oc3def);
	
	TIM_OCInitTypeDef oc4def;
	TIM_OCStructInit(&oc4def);
	oc4def.TIM_OCMode = TIM_OCMode_PWM1;
	oc4def.TIM_OutputState = TIM_OutputState_Enable;
	oc4def.TIM_OCPolarity = TIM_OCPolarity_High;
	oc4def.TIM_Pulse = 1500-1;
	TIM_OC4Init(TIM1,&oc4def);
	
	TIM_OC1PreloadConfig(TIM1,TIM_OCPreload_Enable);
	TIM_OC2PreloadConfig(TIM1,TIM_OCPreload_Enable);
	TIM_OC3PreloadConfig(TIM1,TIM_OCPreload_Enable);
	TIM_OC4PreloadConfig(TIM1,TIM_OCPreload_Enable);
	
	TIM_CtrlPWMOutputs(TIM1,ENABLE);
}
void Motor_PWM_Init(Motor motor)
{
  RCC_AHBPeriphClockCmd(motor.GPIO_PWM_RCC, ENABLE);
  GPIO_InitStructure.GPIO_Pin = motor.GPIO_PWM_Pin;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(motor.GPIO_PWM_GPIOx, &GPIO_InitStructure);

  GPIO_PinAFConfig(motor.GPIO_PWM_GPIOx, motor.GPIO_PWM_PinSource, motor.GPIO_PWM_AF);

  if (motor.TIMx == TIM1) {
    RCC_APB2PeriphClockCmd(motor.TIMx_RCC, ENABLE);
  } else if (motor.TIMx == TIM2) {
    RCC_APB1PeriphClockCmd(motor.TIMx_RCC, ENABLE);
  } else {
    if (IS_RCC_APB2_PERIPH(motor.TIMx_RCC))
    {
      RCC_APB2PeriphClockCmd(motor.TIMx_RCC, ENABLE);
    }
    else
    {
      RCC_APB1PeriphClockCmd(motor.TIMx_RCC, ENABLE);
    }
  }

  TIM_TimeBaseStructure.TIM_Prescaler = 720;//PrescalerValue;
  TIM_TimeBaseStructure.TIM_Period = 100 - 1;
  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  
  TIM_TimeBaseInit(motor.TIMx, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = motor.TIMx_Mode;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = motor.speed;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
    
  switch (motor.TIMx_Channel)
  {
    case TIM_Channel_1:
      TIM_OC1Init(motor.TIMx, &TIM_OCInitStructure);
      TIM_OC1PreloadConfig(motor.TIMx, TIM_OCPreload_Enable);
      break;
    case TIM_Channel_2:
      TIM_OC2Init(motor.TIMx, &TIM_OCInitStructure);
      TIM_OC2PreloadConfig(motor.TIMx, TIM_OCPreload_Enable);
      break;
    case TIM_Channel_3:
      TIM_OC3Init(motor.TIMx, &TIM_OCInitStructure);
      TIM_OC3PreloadConfig(motor.TIMx, TIM_OCPreload_Enable);
      break;
    case TIM_Channel_4:
      TIM_OC4Init(motor.TIMx, &TIM_OCInitStructure);
      TIM_OC4PreloadConfig(motor.TIMx, TIM_OCPreload_Enable);
      break;
  }
  if (motor.TIMx == TIM1 || TIM8) {
    TIM_CtrlPWMOutputs(motor.TIMx, ENABLE);
  }
  TIM_ARRPreloadConfig(motor.TIMx, DISABLE);
  TIM_Cmd(motor.TIMx, ENABLE);
}
Example #16
0
void TIM1_Mode_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_ICInitTypeDef TIM_ICInitStructure;
	//TIM_OCInitTypeDef  TIM_OCInitStructure;
	
	/*-------------第一步-------------------------------------------------------------------------------------------------------------------*/
	//先配置下 RCC 外设时钟 这个必须的。  这里配置对应引脚的GPIO。 timer1 对应的CH1 和 CH2 分别为 PE9 和 PE11 ,所以这里配置GPIOE
	// 一个timer 对应的有四个输入通道 CH1 ~ CH4
	/*---------------------------------------------------------------------------------------------------------------------------------------*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
	
	/*-------------第二步-------------------------------------------------------------------------------------------------------------------*/
	//timer1 没有重映射的时候 CH1 和 CH2 分别对应着引脚PA8 和 PA9  怎奈何 PA9 和 PA10被用作了uart1。 所以
	//我们需要完全重映射,把CH1 和 CH2 分别对应到PE9 和 PE11。  这个做法跟以前的LPC2214不一样, 复用的引脚需要去设置这个引脚起什么作用,stm的芯片不需要
	// timer3 没有这个问题 所以不需要重映射
	/*---------------------------------------------------------------------------------------------------------------------------------------*/
	GPIO_PinRemapConfig(GPIO_FullRemap_TIM1,ENABLE);

	
	GPIO_StructInit(&GPIO_InitStructure);
	//重映射前的引脚
//	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
//	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
//	GPIO_Init(GPIOA, &GPIO_InitStructure);

	//完全重映射后的引脚
	/* Configure PE.09 11 as encoder input */
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(GPIOE, &GPIO_InitStructure);

	
	/*---------------第三步---------------------------------------------*/        
	//配置timer1, 常规设置
	//因为timer1 用的APB2(timer3用的APB1)
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
	
	
	 //使能timer1
	TIM_DeInit(TIM1);
	TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
	
	TIM_TimeBaseStructure.TIM_Period =0xffff;       //
	TIM_TimeBaseStructure.TIM_Prescaler =0;            				//设置预分频:
	TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1 ;        	//设置时钟分频系数:不分频
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  	//向上计数模式
	//TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1; 
	/*初始化TIM1定时器 */
	TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
	
	/*----------------第四步-------------------------------------------------*/
	//将timer1配置为编码模式              TIM_EncoderMode_TI12的意思是AB相都用,也可以只用一相
	//TIM_EncoderInterfaceConfig(TIM1, TIM_EncoderMode_TI12, 
	//TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);  //TIM_ICPolarity_Rising上升沿捕获    
	
	//---如果四细分的 应该上升下降沿都要计数 !!!
	TIM_EncoderInterfaceConfig(TIM1, TIM_EncoderMode_TI12, 
	TIM_ICPolarity_BothEdge, TIM_ICPolarity_BothEdge);  //TIM_ICPolarity_BothEdge上升沿或者下降沿捕获  

	//  配置AB相的 数字滤波器  
	//  这个数字滤波器很重要,滤除高频干扰,就像上次的电磁干扰 。这个芯片连这个都有,给力!!
	TIM_ICStructInit(&TIM_ICInitStructure);

	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;//配置通道1的滤波器
	TIM_ICInitStructure.TIM_ICFilter = 6;         	//比较滤波器   
	TIM_ICInit(TIM1, &TIM_ICInitStructure);

	TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;//配置通道2的滤波器
	TIM_ICInitStructure.TIM_ICFilter = 6;         	//比较滤波器
	TIM_ICInit(TIM1, &TIM_ICInitStructure);
	

	/*----------------第五步  收尾工作-------------------------------------------------*/
	TIM_ARRPreloadConfig(TIM1, ENABLE);//自动重装载配置
	// Clear all pending interrupts
	TIM_ClearFlag(TIM1, TIM_FLAG_Update);
	TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);   //使能中断
	//Reset counter
	TIM1->CNT =0;			//直接读这个counter 就是编码器的值 只有16位。 如果你想用32位的,作为程序员的你肯定能想到办法的。	
	TIM_Cmd(TIM1, ENABLE);   //使能定时器1	
}
TM_DAC_SIGNAL_Result_t TM_DAC_SIGNAL_SetCustomSignal(TM_DAC_SIGNAL_Channel_t DACx, uint16_t* Signal_Data, uint16_t Signal_Length, double frequency) {
	DAC_InitTypeDef DAC_InitStruct;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct;
	DMA_InitTypeDef DMA_InitStruct;
	TM_TIMER_PROPERTIES_t Timer_Data;

	/* Check if timer is set */
	if (!dac_timer_set[DACx]) {
		return TM_DAC_SIGNAL_Result_Error;
	}
	
	/* Check used timer */
	/* Set proper trigger */
	if (DAC_TIM[DACx] == TIM2) {
		DAC_InitStruct.DAC_Trigger = DAC_Trigger_T2_TRGO;
	} else if (DAC_TIM[DACx] == TIM4) {
		DAC_InitStruct.DAC_Trigger = DAC_Trigger_T4_TRGO;
	} else if (DAC_TIM[DACx] == TIM5) {
		DAC_InitStruct.DAC_Trigger = DAC_Trigger_T5_TRGO;
	} else if (DAC_TIM[DACx] == TIM6) {
		DAC_InitStruct.DAC_Trigger = DAC_Trigger_T6_TRGO;
	} else if (DAC_TIM[DACx] == TIM7) {
		DAC_InitStruct.DAC_Trigger = DAC_Trigger_T7_TRGO;
	} else if (DAC_TIM[DACx] == TIM8) {
		DAC_InitStruct.DAC_Trigger = DAC_Trigger_T8_TRGO;
	} else {
		/* Timer is not valid */
		return TM_DAC_SIGNAL_Result_TimerNotValid;
	}
	
	/* Get timer data */
	TM_TIMER_PROPERTIES_GetTimerProperties(DAC_TIM[DACx], &Timer_Data);
	
	/* Get period and prescaler values */
	TM_TIMER_PROPERTIES_GenerateDataForWorkingFrequency(&Timer_Data, frequency * Signal_Length);
	
	/* Check valid frequency */
	if (Timer_Data.Frequency == 0) {
		return TM_DAC_SIGNAL_Result_Error;
	}
	
	/* Enable DAC clock */
	RCC->APB1ENR |= RCC_APB1ENR_DACEN;
	/* Enable DMA1 clock */
	RCC->AHB1ENR |= RCC_AHB1ENR_DMA1EN;
	
	/* Initialize DAC */
	DAC_InitStruct.DAC_WaveGeneration = DAC_WaveGeneration_None;
	DAC_InitStruct.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
	
	/* Disable DMA */
	if (DACx == TM_DAC1) {
		/* Init DAC channel 1 */
		DAC_Init(DAC_Channel_1, &DAC_InitStruct);
	} else if (DACx == TM_DAC2) {
		/* Init DAC channel 2 */
		DAC_Init(DAC_Channel_2, &DAC_InitStruct);
	}
	
	/* Enable timer clock */
	TM_TIMER_PROPERTIES_EnableClock(DAC_TIM[DACx]);
	
	/* Time base configuration */
	TIM_TimeBaseStructInit(&TIM_TimeBaseStruct); 
	TIM_TimeBaseStruct.TIM_Period = Timer_Data.Period - 1;          
	TIM_TimeBaseStruct.TIM_Prescaler = Timer_Data.Prescaler - 1;       
	TIM_TimeBaseStruct.TIM_ClockDivision = 0;    
	TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
	
	/* Initialize timer */
	TIM_TimeBaseInit(DAC_TIM[DACx], &TIM_TimeBaseStruct);

	/* Enable TIM selection */
	TIM_SelectOutputTrigger(DAC_TIM[DACx], TIM_TRGOSource_Update);
	
	/* Set DMA options */
	DMA_InitStruct.DMA_Memory0BaseAddr = (uint32_t)Signal_Data;
	DMA_InitStruct.DMA_DIR = DMA_DIR_MemoryToPeripheral;
	DMA_InitStruct.DMA_BufferSize = Signal_Length;
	DMA_InitStruct.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
	DMA_InitStruct.DMA_MemoryInc = DMA_MemoryInc_Enable;
	DMA_InitStruct.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
	DMA_InitStruct.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
	DMA_InitStruct.DMA_Mode = DMA_Mode_Circular;
	DMA_InitStruct.DMA_Priority = DMA_Priority_High;
	DMA_InitStruct.DMA_FIFOMode = DMA_FIFOMode_Disable;         
	DMA_InitStruct.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
	DMA_InitStruct.DMA_MemoryBurst = DMA_MemoryBurst_Single;
	DMA_InitStruct.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
	
	switch (DACx) {
		case TM_DAC1:
			/* Set peripheral location = 12bit right aligned for channel 1 */
			DMA_InitStruct.DMA_PeripheralBaseAddr = (uint32_t)&DAC->DHR12R1;
		
			/* Disable DMA */
			DMA_DeInit(DAC_SIGNAL_DMA_DAC1_STREAM);
			
			/* Set channel used */
			DMA_InitStruct.DMA_Channel = DAC_SIGNAL_DMA_DAC1_CHANNEL;
		
			/* Initialize DMA */
			DMA_Init(DAC_SIGNAL_DMA_DAC1_STREAM, &DMA_InitStruct);
			
			/* Enable DMA Stream for DAC Channel 1 */
			DMA_Cmd(DAC_SIGNAL_DMA_DAC1_STREAM, ENABLE);

			/* Enable DAC Channel 1 */
			DAC_Cmd(DAC_Channel_1, ENABLE);

			/* Enable DMA for DAC Channel 1 */
			DAC_DMACmd(DAC_Channel_1, ENABLE);
			break;
		case TM_DAC2:
			/* Disable DMA */
			DMA_DeInit(DAC_SIGNAL_DMA_DAC2_STREAM);
			
			/* Set channel used */
			DMA_InitStruct.DMA_Channel = DAC_SIGNAL_DMA_DAC2_CHANNEL;
				
			/* Set peripheral location = 12bit right aligned for channel 2 */
			DMA_InitStruct.DMA_PeripheralBaseAddr = (uint32_t)&DAC->DHR12R2;
		
			/* Initialize DMA */
			DMA_Init(DAC_SIGNAL_DMA_DAC2_STREAM, &DMA_InitStruct);
			
			/* Enable DMA Stream for DAC Channel 2 */
			DMA_Cmd(DAC_SIGNAL_DMA_DAC2_STREAM, ENABLE);

			/* Enable DAC Channel 2 */
			DAC_Cmd(DAC_Channel_2, ENABLE);

			/* Enable DMA for DAC Channel 2 */
			DAC_DMACmd(DAC_Channel_2, ENABLE);
			break;
		default:
			break;
	}
	
	/* Enable timer */
	DAC_TIM[DACx]->CR1 |= TIM_CR1_CEN;
	
	/* Return OK */
	return TM_DAC_SIGNAL_Result_Ok;
}
Example #18
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */

  /* TIM1 and GPIOA clock enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 | RCC_APB2Periph_GPIOA, ENABLE);

  /* DMA clock enable */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);

  /* GPIOA Configuration: Channel 1 as alternate function push-pull */
  GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_8;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  /* TIM1 DeInit */
  TIM_DeInit(TIM1);

  /* DMA1 Channel5 Config */
  DMA_DeInit(DMA1_Channel5);

  DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)TIM1_DMAR_ADDRESS;
  DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)SRC_Buffer;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
  DMA_InitStructure.DMA_BufferSize = 3;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA1_Channel5, &DMA_InitStructure);

  /* Time base configuration */
  /* -----------------------------------------------------------------------
    TIM1 Configuration: generate 1 PWM signal using the DMA burst mode:
    The TIM1CLK frequency is set to SystemCoreClock (Hz), to get TIM1 counter
    clock at 24 MHz the Prescaler is computed as following:
     - Prescaler = (TIM1CLK / TIM1 counter clock) - 1
    SystemCoreClock is set to 72 MHz for Low-density, Medium-density, High-density
    and Connectivity line devices and to 24 MHz for Low-Density Value line and
    Medium-Density Value line devices

    The TIM1 period is 5.8 KHz: TIM1 Frequency = TIM1 counter clock/(ARR + 1)
                                               = 24 MHz / 4096 = 5.8KHz KHz
    TIM1 Channel1 duty cycle = (TIM1_CCR1/ TIM1_ARR)* 100 = 33.33%
  ----------------------------------------------------------------------- */
  TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
  TIM_TimeBaseStructure.TIM_Prescaler = (uint16_t) (SystemCoreClock / 24000000) - 1;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* TIM Configuration in PWM Mode */
  TIM_OCInitStructure.TIM_OCMode =  TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 0xFFF;
  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  /* TIM1 DMAR Base register and DMA Burst Length Config */
  TIM_DMAConfig(TIM1, TIM_DMABase_ARR, TIM_DMABurstLength_3Transfers);

  /* TIM1 DMA Update enable */
  TIM_DMACmd(TIM1, TIM_DMA_Update, ENABLE);

  /* TIM1 enable */
  TIM_Cmd(TIM1, ENABLE);

  /* TIM1 PWM Outputs Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  /* DMA1 Channel5 enable */
  DMA_Cmd(DMA1_Channel5, ENABLE);

  /* Wait until DMA1 Channel5 end of Transfer */
  while (!DMA_GetFlagStatus(DMA1_FLAG_TC5))
  {
  }

  /* Infinite loop */
  while(1)
  {
  }
}
int main( void )
{
  //konfiguracija taktova
  RCC_ADCCLKConfig(RCC_PCLK2_Div2);//konfigurisanje takta za ADC 
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);//dovodjenje takta za DMA kontroler 
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC | RCC_APB2Periph_TIM1 | RCC_APB2Periph_ADC1, ENABLE);//dovodjenje takta portu A, B, C, tajmeru TIM1 i ADC-u
  
  //konfiguracija portova - analogni ulazi
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
  
  //konfiguracija portova - bargraph tj. DIGIO konektor
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_5 | GPIO_Pin_6;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOB, &GPIO_InitStructure);
  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_13;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
   
  /* DMA1 channel1 configuration ----------------------------------------------*/
  DMA_DeInit(DMA1_Channel1);
  DMA_InitStructure.DMA_PeripheralBaseAddr = ADC1_DR_Address;//adresa izvorista za dma prenos - DATA REGISTER ADC-a
  DMA_InitStructure.DMA_MemoryBaseAddr = (u32)ADC_RegularConvertedValueTab;
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
  DMA_InitStructure.DMA_BufferSize = 4;
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
  DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
  DMA_InitStructure.DMA_Priority = DMA_Priority_High;
  DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
  DMA_Init(DMA1_Channel1, &DMA_InitStructure);
  /* Enable DMA1 channel1 */
  DMA_Cmd(DMA1_Channel1, ENABLE);
  
  /* ADC1 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
  ADC_InitStructure.ADC_ScanConvMode = ENABLE;
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_NbrOfChannel = 4;
  ADC_Init(ADC1, &ADC_InitStructure);
  ADC_RegularChannelConfig(ADC1, ADC_Channel_12, 1, ADC_SampleTime_1Cycles5);
  ADC_RegularChannelConfig(ADC1, ADC_Channel_13, 2, ADC_SampleTime_1Cycles5);
  ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 3, ADC_SampleTime_1Cycles5);
  ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 4, ADC_SampleTime_1Cycles5);
  ADC_ExternalTrigConvCmd(ADC1, ENABLE);//omogucavanje externog triger moda
  ADC_DMACmd(ADC1, ENABLE);//omogucavanje DMA prenosa za ADC
  ADC_Cmd(ADC1, ENABLE);
  
  ADC_ResetCalibration(ADC1);//adc kalibracija
  while(ADC_GetResetCalibrationStatus(ADC1));
  ADC_StartCalibration(ADC1);
  while(ADC_GetCalibrationStatus(ADC1));
 
  //konfiguracija tajmera TIM1 koji radi u PWM modu, i svoj izlaz koristi za trigerovanje ADC-a
  TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);
  TIM_TimeBaseInitStruct.TIM_Period = 150 - 1;
  TIM_TimeBaseInitStruct.TIM_Prescaler = 0;
  TIM_TimeBaseInitStruct.TIM_ClockDivision = 0x0;
  TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStruct); 
  TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStruct.TIM_Pulse = 150 / 2;
  TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OC1Init(TIM1, &TIM_OCInitStruct);
  
  TIM_Cmd(TIM1, ENABLE);//dozovla rada tajmera tek kada se konfigurisu i DMA i ADC
  TIM_CtrlPWMOutputs(TIM1, ENABLE);//generisanje PWM izlaza za tajmer 1
  
  baterija_Acc_const=0.004032;
  servo_5V_const=0.004032;
  
  
  
  
    
  
  /* Inicijalizacija. */
  InitGPIO_Pin(GPIOB, GPIO_Pin_11, GPIO_Mode_IPU, GPIO_Speed_50MHz);
  UsartInit();
  
  /* Inicijalizacija glavnog tajmera. */
  initTimerServo();//zbog ovoga se baterija meri i dok je prekidac uvucen
  
  /* Glavna masina stanja. */
  while(1)
  {
    switch (state_robot)
    {
      /* Pocetno stanje u kome se inicijalizaciju sistemi, podesava preskaler, ukljucuje UV. */ 
      case 0:  // pocetno stanje, sve inicijalizujemo i krenemo napred
        
        if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11)) // ako je ocitano Vcc, tj. krene se sa izvrsavanjem, u suprotnom ostajemo u 
                                                       // istom stanju
        {
          /* Inicijalizacija glavnog tajmera. */
          initTimer90();
          /* Inicijalizacija tajmera za proveru pozicije robota. */
          SysTick_Config( SysTick_Config( SystemCoreClock / 1000 ) );
          /* Provera koja je stategije. */
          checkStrategy();
          /* Zadavanje komandi. */
          issueCommand( START_RUNNING, MOTION_DEVICE_ADDRESS, 30 );
          waitAck( START_RUNNING, MOTION_DEVICE_ADDRESS, 30 );
          issueCommand( PRESCALER, MOTION_DEVICE_ADDRESS, 1000 );
          waitAck( PRESCALER, MOTION_DEVICE_ADDRESS, 1000 );
          issueCommand( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
          waitAck( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
          issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 30 );
          waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 30 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 25 );            
            if ( FLAG_arriveOnDest ) break;
            sleep( 100 );
          }
          state_robot++;
          sleep(100);
        }
        break;
      
      /* Blago okretanje da bi se izbegla ivica na sredini terena. */  
      case 1:
        
        if( FLAG_strategyLeft )
        {
          issueCommand( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 20 );
          waitAck( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 20 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 25 );
            if ( FLAG_arriveOnDest ) break;
            sleep( 100 );
          }
        }
        else
        {
          issueCommand( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 20 );
          waitAck( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 20 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 25 );
            if ( FLAG_arriveOnDest ) break;
            sleep( 100 );
          }
        }
        
        state_robot++;
        sleep(100);
        break;
       
      /* Blago pomeranje napred, ka sredini terena. */
      case 2:
      {
        issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 50 );
        waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 50 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;          
        }
        state_robot++;
        sleep(100);
        break;       
      }
        
      /* Blaga rotacija da bi se poravnali opet. */  
      case 3:

        if( FLAG_strategyLeft )
        {
          issueCommand( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 25 );
          waitAck( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 25 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        else
        {
          issueCommand( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 25 );
          waitAck( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 25 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }          
        }
        state_robot++;
        sleep(100);
        break;

      /* Blago pomeranje napred da bi pomerili kocke u sredinu terena.  */
      case 4:
        
        issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 10 );
        waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 10 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break;
        
      /* Vracanje unazad. */
      case 5:
        
        issueCommand( PRESCALER, MOTION_DEVICE_ADDRESS, 500 );
        waitAck( PRESCALER, MOTION_DEVICE_ADDRESS, 500 );
        issueCommand( MOVE_BACKWARD, MOTION_DEVICE_ADDRESS, 50 );
        waitAck( MOVE_BACKWARD, MOTION_DEVICE_ADDRESS, 50 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break;  
        
      /* Okretanje ka prvoj kucici, onoj daljoj od ivice terana i gasenje senzora. */
      case 6:
        
        if( FLAG_strategyLeft )
        {
          issueCommand( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 175 );
          waitAck( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 175 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        else
        {
          issueCommand( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 175 );
          waitAck( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 175 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }          
        } 
        
        issueCommand( ULTRASOUND_OFF, MOTION_DEVICE_ADDRESS, 1 );
        waitAck( ULTRASOUND_OFF, MOTION_DEVICE_ADDRESS, 1 );
        
        state_robot++;
        sleep(100);
        break;
      
      /* Zatvaranje prvih vrata. */
      case 7:
        
        issueCommand( PRESCALER, MOTION_DEVICE_ADDRESS, 700 );
        waitAck( PRESCALER, MOTION_DEVICE_ADDRESS, 700 );
        issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 100 );
        waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 100 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break;        
        
      /* Vracanje unazad. */
      case 8:
        issueCommand( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
        waitAck( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
        issueCommand( PRESCALER, MOTION_DEVICE_ADDRESS, 500 );
        waitAck( PRESCALER, MOTION_DEVICE_ADDRESS, 500 );
        issueCommand( MOVE_BACKWARD, MOTION_DEVICE_ADDRESS, 60 );
        waitAck( MOVE_BACKWARD, MOTION_DEVICE_ADDRESS, 60 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        
        state_robot++;
        sleep(100);
        break;        
       
      /* Okretanje za 180 stepeni ka pocetnoj poziciji. */
      case 9:

        //issueCommand( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
        //waitAck( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
          
        if( FLAG_strategyLeft )
        {
          issueCommand( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 180 );
          waitAck( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 180 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        else
        {
          issueCommand( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 180 );
          waitAck( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 180 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }          
        } 
        
        state_robot++;
        sleep(100);
        break; 
      
      /* Odlazak naspram druge kucice. */
      case 10:

        issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 15 );
        waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 15 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break;             
       
      /* Okretanje ka kucici. */
      case 11:

        if( FLAG_strategyLeft )
        {
          issueCommand( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 175 );
          waitAck( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 175 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        else
        {
          issueCommand( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 175 );
          waitAck( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 175 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        
        issueCommand( ULTRASOUND_OFF, MOTION_DEVICE_ADDRESS, 1 );
        waitAck( ULTRASOUND_OFF, MOTION_DEVICE_ADDRESS, 1 );
        
        state_robot++;
        sleep(100);
        break;        
        
         
      /* Zatvaranje druge kucice. */
      case 12:
        
        issueCommand( ULTRASOUND_OFF, MOTION_DEVICE_ADDRESS, 1 );
        waitAck( ULTRASOUND_OFF, MOTION_DEVICE_ADDRESS, 1 );
        issueCommand( PRESCALER, MOTION_DEVICE_ADDRESS, 700 );
        waitAck( PRESCALER, MOTION_DEVICE_ADDRESS, 700 );
        issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 60 );
        waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 60 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break; 
        
      /* Vracanje unazad. */  
      case 13:
        
        issueCommand( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
        waitAck( ULTRASOUND_ON, MOTION_DEVICE_ADDRESS, 1 );
        issueCommand( PRESCALER, MOTION_DEVICE_ADDRESS, 500 );
        waitAck( PRESCALER, MOTION_DEVICE_ADDRESS, 500 );
        issueCommand( MOVE_BACKWARD, MOTION_DEVICE_ADDRESS, 60 );
        waitAck( MOVE_BACKWARD, MOTION_DEVICE_ADDRESS, 60 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break; 
      
      /* Okretanje ka centru naseg dela terena. */  
      case 14:
        
        if( FLAG_strategyLeft )
        {
          issueCommand( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 270 );
          waitAck( ROTATE_LEFT, MOTION_DEVICE_ADDRESS, 270 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        else
        {
          issueCommand( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 270 );
          waitAck( ROTATE_RIGHT, MOTION_DEVICE_ADDRESS, 270 );
          while( TRUE )
          {
            issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
            sleep( 100 );
            if ( FLAG_arriveOnDest ) break;
          }
        }
        state_robot++;
        sleep(100);
        break; 
        
      case 15:
      
        issueCommand( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 40 );
        waitAck( MOVE_FORWARD, MOTION_DEVICE_ADDRESS, 40 );
        while( TRUE )
        {
          issueCommand( CHECK_ARRIVE, MOTION_DEVICE_ADDRESS, 1 );
          sleep( 100 );
          if ( FLAG_arriveOnDest ) break;
        }
        state_robot++;
        sleep(100);
        break; 
        
      /* Podrazumevano stanje u kome se ne radi nista. */  
      default:
        break;
    }
  }
}
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f0xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f0xx.c file
     */ 

  /* TIM Configuration */
  TIM_Config();
  
  /* TIM1 Configuration ---------------------------------------------------
   Generate 7 PWM signals with 4 different duty cycles:
   TIM1 input clock (TIM1CLK) is set to APB2 clock (PCLK2)    
    => TIM1CLK = PCLK2 = SystemCoreClock
   TIM1CLK = SystemCoreClock, Prescaler = 0, TIM1 counter clock = SystemCoreClock
   SystemCoreClock is set to 48 MHz for STM32F0xx devices
   
   The objective is to generate 7 PWM signal at 17.57 KHz:
     - TIM1_Period = (SystemCoreClock / 17570) - 1
   The channel 1 and channel 1N duty cycle is set to 50%
   The channel 2 and channel 2N duty cycle is set to 37.5%
   The channel 3 and channel 3N duty cycle is set to 25%
   The channel 4 duty cycle is set to 12.5%
   The Timer pulse is calculated as follows:
     - ChannelxPulse = DutyCycle * (TIM1_Period - 1) / 100
   
   Note: 
    SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f0xx.c file.
    Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
    function to update SystemCoreClock variable value. Otherwise, any configuration
    based on this variable will be incorrect. 
  ----------------------------------------------------------------------- */
  /* Compute the value to be set in ARR regiter to generate signal frequency at 17.57 Khz */
  TimerPeriod = (SystemCoreClock / 17570 ) - 1;
  /* Compute CCR1 value to generate a duty cycle at 50% for channel 1 and 1N */
  Channel1Pulse = (uint16_t) (((uint32_t) 5 * (TimerPeriod - 1)) / 10);
  /* Compute CCR2 value to generate a duty cycle at 37.5%  for channel 2 and 2N */
  Channel2Pulse = (uint16_t) (((uint32_t) 375 * (TimerPeriod - 1)) / 1000);
  /* Compute CCR3 value to generate a duty cycle at 25%  for channel 3 and 3N */
  Channel3Pulse = (uint16_t) (((uint32_t) 25 * (TimerPeriod - 1)) / 100);
  /* Compute CCR4 value to generate a duty cycle at 12.5%  for channel 4 */
  Channel4Pulse = (uint16_t) (((uint32_t) 125 * (TimerPeriod- 1)) / 1000);

  /* TIM1 clock enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 , ENABLE);
  
  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = TimerPeriod;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1, 2,3 and 4 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = Channel1Pulse;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel2Pulse;
  TIM_OC2Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel3Pulse;
  TIM_OC3Init(TIM1, &TIM_OCInitStructure);

  TIM_OCInitStructure.TIM_Pulse = Channel4Pulse;
  TIM_OC4Init(TIM1, &TIM_OCInitStructure);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* TIM1 Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  /* Infinite loop */
  while (1)
  {
  }
}
void pwmOutputInit(drv_pwm_output_config_t * init)
{
    GPIO_InitTypeDef GPIO_InitStructure = { 0, };
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure = { 0, };
    TIM_OCInitTypeDef TIM_OCInitStructure = { 0, };

    // Outputs
    // PWM1 TIM1_CH1 PA8
    // PWM2 TIM1_CH4 PA11
    // PWM3 TIM4_CH1 PB6
    // PWM4 TIM4_CH2 PB7
    // PWM5 TIM4_CH3 PB8
    // PWM6 TIM4_CH4 PB9

    // Output pins
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init(GPIOA, &GPIO_InitStructure);

    //GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9;

    //GPIO_Init(GPIOB, &GPIO_InitStructure);

    // Output timers
    TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);

    TIM_TimeBaseStructure.TIM_Prescaler = (36 - 1);

    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
    
    
    if (init->noEsc) {
        TIM_TimeBaseStructure.TIM_Period = (2000000 / init->motorPwmRate) - 1;
        TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
        pwm_period = 2000000 / init->motorPwmRate;
        TIM_OCInitStructure.TIM_Pulse = DUTY(10);
        TIM_OC1Init(TIM2, &TIM_OCInitStructure);
        TIM_OCInitStructure.TIM_Pulse = DUTY(20);
        TIM_OC2Init(TIM2, &TIM_OCInitStructure);
        TIM_OCInitStructure.TIM_Pulse = DUTY(30);
        TIM_OC3Init(TIM2, &TIM_OCInitStructure);
        TIM_OCInitStructure.TIM_Pulse = DUTY(40);
        TIM_OC4Init(TIM2, &TIM_OCInitStructure);
    }else if (init->useServos == true) {
        // ch1, 2 for servo
        TIM_TimeBaseStructure.TIM_Period = (2000000 / init->servoPwmRate) - 1;
        TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

        TIM_OCInitStructure.TIM_Pulse = PULSE_1p5MS;
        TIM_OC1Init(TIM1, &TIM_OCInitStructure);
        TIM_OC4Init(TIM1, &TIM_OCInitStructure);

        TIM_TimeBaseStructure.TIM_Period = (2000000 / init->escPwmRate) - 1;
        TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

        TIM_OCInitStructure.TIM_Pulse = PULSE_1MS;
        TIM_OC1Init(TIM4, &TIM_OCInitStructure);
        TIM_OC2Init(TIM4, &TIM_OCInitStructure);
        TIM_OC3Init(TIM4, &TIM_OCInitStructure);
        TIM_OC4Init(TIM4, &TIM_OCInitStructure);
    } else {
        TIM_TimeBaseStructure.TIM_Period = (2000000 / init->escPwmRate) - 1;
        TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
        TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

        TIM_OCInitStructure.TIM_Pulse = PULSE_1MS;
        TIM_OC1Init(TIM1, &TIM_OCInitStructure);
        TIM_OC4Init(TIM1, &TIM_OCInitStructure);
        TIM_OC1Init(TIM4, &TIM_OCInitStructure);
        TIM_OC2Init(TIM4, &TIM_OCInitStructure);
        TIM_OC3Init(TIM4, &TIM_OCInitStructure);
        TIM_OC4Init(TIM4, &TIM_OCInitStructure);
    }

    TIM_Cmd(TIM2, ENABLE);
    //TIM_Cmd(TIM4, ENABLE);
    TIM_CtrlPWMOutputs(TIM2, ENABLE);
    //TIM_CtrlPWMOutputs(TIM4, ENABLE);
}
Example #22
0
int pwm_init(TIM_TypeDef * timer, TIM_CHAN_TypeDef channel, int frequency, int defaultPulseWidth)
{
	static char pwmInit[4] = {0,0,0,0};
	char timerIdx = 1;

	// local variables to initialize timer2
	TIM_TimeBaseInitTypeDef timStruct;
	TIM_OCInitTypeDef timOCInitStruct;					// init structure for OC-modes
	unsigned char timClockMultiplier = 0;
	RCC_ClocksTypeDef clocks;
	int timPrescaler = 1;


	/**** configure GPIO for timer-Use ****/

	// Configure timer pin as output, alternate function, push-pull
	GPIO_InitTypeDef Gis;
	GPIO_StructInit(&Gis);
	Gis.GPIO_Mode = GPIO_Mode_AF_PP;
	Gis.GPIO_Speed = GPIO_Speed_50MHz;

	if (timer == TIM1)
	{	// Enable GPIO clock and release reset
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
		RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, DISABLE);

		switch (channel)
		{
			case TIM_CHAN1: Gis.GPIO_Pin = GPIO_Pin_8; GPIO_Init(GPIOA, &Gis); break; // PA8 -> CH1
			case TIM_CHAN2: Gis.GPIO_Pin = GPIO_Pin_9; GPIO_Init(GPIOA, &Gis); break; // PA9 -> CH2
			case TIM_CHAN3: Gis.GPIO_Pin = GPIO_Pin_10; GPIO_Init(GPIOA, &Gis); break; // PA10 -> CH3
			case TIM_CHAN4: Gis.GPIO_Pin = GPIO_Pin_11; GPIO_Init(GPIOA, &Gis); break; // PA11 -> CH4
		}

		RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
		timerIdx = 1;
	}
	else if (timer == TIM2)
	{	// Enable GPIO clock and release reset
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
		RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, DISABLE);

		switch (channel)
		{
			case TIM_CHAN1: Gis.GPIO_Pin = GPIO_Pin_0; GPIO_Init(GPIOA, &Gis); break; // PA0 -> CH1
			case TIM_CHAN2: Gis.GPIO_Pin = GPIO_Pin_1; GPIO_Init(GPIOA, &Gis); break; // PA1 -> CH2
			case TIM_CHAN3: Gis.GPIO_Pin = GPIO_Pin_2; GPIO_Init(GPIOA, &Gis); break; // PA2 -> CH3
			case TIM_CHAN4: Gis.GPIO_Pin = GPIO_Pin_3; GPIO_Init(GPIOA, &Gis); break; // PA3 -> CH4
		}

		RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
		timerIdx = 2;
	}
	else if (timer == TIM3)
	{	// Enable GPIO clock and release reset
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
		RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, DISABLE);

		switch (channel)
		{
			case TIM_CHAN1: Gis.GPIO_Pin = GPIO_Pin_6; GPIO_Init(GPIOA, &Gis); break; // PA6 -> CH1
			case TIM_CHAN2: Gis.GPIO_Pin = GPIO_Pin_7; GPIO_Init(GPIOA, &Gis); break; // PA7 -> CH2
			case TIM_CHAN3: Gis.GPIO_Pin = GPIO_Pin_0; GPIO_Init(GPIOB, &Gis); break; // PB0 -> CH3
			case TIM_CHAN4: Gis.GPIO_Pin = GPIO_Pin_1; GPIO_Init(GPIOB, &Gis); break; // PB1 -> CH4
		}

		RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
		timerIdx = 3;
	}
	else if (timer == TIM4)
	{	// Enable GPIO clock and release reset
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);
		RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, DISABLE);

		switch (channel)
		{
			case TIM_CHAN1: Gis.GPIO_Pin = GPIO_Pin_6; GPIO_Init(GPIOB, &Gis); break; // PB6 -> CH1
			case TIM_CHAN2: Gis.GPIO_Pin = GPIO_Pin_7; GPIO_Init(GPIOB, &Gis); break; // PB7 -> CH2
			case TIM_CHAN3: Gis.GPIO_Pin = GPIO_Pin_8; GPIO_Init(GPIOB, &Gis); break; // PB8 -> CH3
			case TIM_CHAN4: Gis.GPIO_Pin = GPIO_Pin_9; GPIO_Init(GPIOB, &Gis); break; // PB9 -> CH4
		}

		RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
		timerIdx = 4;
	}
	else
	{
		return -1; // timer not supported
	}


	/* reset timer before new init, only if it's not already used as PWM source */
	if (pwmInit[timerIdx-1] == 0) {
		TIM_DeInit(timer);
		pwmInit[timerIdx-1] = 1;
	}

	// RCC_APB2PeriphResetCmd(RCC_APB2Periph_TIM1, DISABLE); // is done in TIM_DeInit
	// RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM2, DISABLE); // is done in TIM_DeInit
	// RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM3, DISABLE); // is done in TIM_DeInit
	// RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM4, DISABLE); // is done in TIM_DeInit


	// if the APB1 Prescaler is bigger than 1, the PCLK1 is multiplied by 2 infront of the timer
	RCC_GetClocksFreq(&clocks);
	if(clocks.HCLK_Frequency/clocks.PCLK1_Frequency > 1)
	{ timClockMultiplier = 2; }
	else
	{ timClockMultiplier = 1; }

	// Prescaler
	// fCK_CNT = fCK_PSC/(TIM_Prescaler+1)
	// - it's important to set the prescaler properly, because timer is only a 16Bit counter with
	//   a maximum reload-value of 2^16 = 65536
	timPrescaler = (clocks.PCLK1_Frequency*timClockMultiplier) / (frequency * PWM_RESOLUTION) - 1; // e.g. 72000000/(100000*100)-1 = 6
	timStruct.TIM_Prescaler 		= timPrescaler;

	timStruct.TIM_Period = PWM_RESOLUTION;

	// timer mode is "count down"
	timStruct.TIM_CounterMode 		= TIM_CounterMode_Up;

	// TIM_ClockDivision = division ratio between the timer clock (CK_INT)
	// frequency and sampling clock used by the digital filters
	// -> not interesting for our purpose !!!
	timStruct.TIM_ClockDivision		= TIM_CKD_DIV1;

	// only valid for TIM1 and TIM8 -> STM32F10x_HD and better
	timStruct.TIM_RepetitionCounter	= 0;

	TIM_TimeBaseInit(timer,&timStruct);



	/**** pwm output settings ****/
	TIM_OCStructInit(&timOCInitStruct);						// set init structure to default values

	timOCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;        		/*!< Specifies the TIM mode.
																This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */

	timOCInitStruct.TIM_OutputState = TIM_OutputState_Enable;	/*!< Specifies the TIM Output Compare state.
																This parameter can be a value of @ref TIM_Output_Compare_state */

	if (defaultPulseWidth >= PWM_RESOLUTION) defaultPulseWidth = PWM_RESOLUTION - 1;
	if (defaultPulseWidth <= 0) defaultPulseWidth = 1;
	timOCInitStruct.TIM_Pulse = defaultPulseWidth;				/*!< Specifies the pulse value to be loaded into the Capture Compare Register.
																This parameter can be a number between 0x0000 and 0xFFFF */

	timOCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;    	/*!< Specifies the output polarity.
	                                   	   	   	   	   	   	   	This parameter can be a value of @ref TIM_Output_Compare_Polarity */

	switch (channel){
		case TIM_CHAN1: TIM_OC1Init(timer, &timOCInitStruct); break; // channel 1 init
		case TIM_CHAN2: TIM_OC2Init(timer, &timOCInitStruct); break; // channel 2 init
		case TIM_CHAN3: TIM_OC3Init(timer, &timOCInitStruct); break; // channel 3 init
		case TIM_CHAN4: TIM_OC4Init(timer, &timOCInitStruct); break; // channel 4 init
		default: return -1;
	}

	//TIM_ITConfig(timer, TIM_IT_Update, ENABLE); // Interrupt enable
	//DBGMCU_Config(DBGMCU_TIM2_STOP, ENABLE);			// stop Timer during debug break
	TIM_Cmd(timer, ENABLE);

	if (timer == TIM1) TIM_CtrlPWMOutputs(timer, ENABLE); 	// this function applies only to timer 1
															// the others timers don't need extra output activation

	// enable timer2-interrupt in interrupt controller
	//NVIC_EnableIRQ(TIM2_IRQn);
	timerIdx = 0;

	return 0;
}
Example #23
0
void initialize_pwm(void) {
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

  GPIO_InitTypeDef gp;
  gp.GPIO_Mode = GPIO_Mode_AF;
  gp.GPIO_Speed = GPIO_Speed_50MHz;
  gp.GPIO_OType = GPIO_OType_PP;
  gp.GPIO_PuPd = GPIO_PuPd_NOPULL;

  // X-Coarse
  gp.GPIO_Pin = GPIO_Pin_15;
  GPIO_Init(GPIOA, &gp);
  
  // X-Fine
  gp.GPIO_Pin = GPIO_Pin_3;
  GPIO_Init(GPIOB, &gp);

  // Y-Coarse
  gp.GPIO_Pin = GPIO_Pin_10;
  GPIO_Init(GPIOB, &gp);

  // Y-Fine
  gp.GPIO_Pin = GPIO_Pin_11;
  GPIO_Init(GPIOB, &gp);
 
  // Laser Power
  gp.GPIO_Pin = GPIO_Pin_4;
  GPIO_Init(GPIOB, &gp);
       
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

  GPIO_PinAFConfig(GPIOA, GPIO_PinSource15, GPIO_AF_2); // GPIO_AF_2 = TIM2
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource3, GPIO_AF_2); // GPIO_AF_2 = TIM2
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_2); // GPIO_AF_2 = TIM2
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_2); // GPIO_AF_2 = TIM2

  GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_1); // GPIO_AF_2 = TIM3 for PB4

  TIM_TimeBaseInitTypeDef ti;
  // Set up the timebase for the mirror channels
  ti.TIM_Prescaler = 0;
  ti.TIM_CounterMode = TIM_CounterMode_Up;
  ti.TIM_Period = 512;
  ti.TIM_ClockDivision = TIM_CKD_DIV1;
  ti.TIM_RepetitionCounter = 0;
  TIM_TimeBaseInit(TIM2, &ti);
  TIM_Cmd(TIM2, ENABLE);

  // Laser uses all the same settings, except for 8-bit instead of 9
  ti.TIM_Period = 256;
  TIM_TimeBaseInit(TIM3, &ti);
  TIM_Cmd(TIM3, ENABLE);

  TIM_OCInitTypeDef oc = {0,};
  oc.TIM_OCMode = TIM_OCMode_PWM1;
  oc.TIM_OutputState = TIM_OutputState_Enable;
  oc.TIM_OutputNState = 0;
  oc.TIM_Pulse = 0;
  oc.TIM_OCPolarity = TIM_OCPolarity_High;
  oc.TIM_OCNPolarity = 0;
  oc.TIM_OCIdleState = 0;
  oc.TIM_OCNIdleState = 0;

  TIM_OC1Init(TIM2, &oc);
  TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);

  TIM_OC2Init(TIM2, &oc);
  TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);

  TIM_OC3Init(TIM2, &oc);
  TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable);

  TIM_OC4Init(TIM2, &oc);
  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);

  // Laser power
  TIM_OC1Init(TIM3, &oc);
  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);

  // Laser enable
  gp.GPIO_Pin = GPIO_Pin_5;
  gp.GPIO_Mode = GPIO_Mode_OUT;
  gp.GPIO_Speed = GPIO_Speed_2MHz;
  gp.GPIO_OType = GPIO_OType_PP;
  gp.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOB, &gp);
}
void ResolverIn::enableResolverRead( bool on )
{
	if (on == true)
	{

		sys.physIO.doutCHEDir.setState( true ); //set CHD as output for resolver
		return;
#if 0

		//	testTIM5();

		//setup timer interrupt to generate square wave to resolver primary coil

		TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

		/* Enable TIM clock */
		RCC_APB1PeriphClockCmd( RESOLVER_TIMER_RCC, ENABLE );

		/* get CPU freq*/
		RCC_ClocksTypeDef RCC_Clocks;
		RCC_GetClocksFreq( &RCC_Clocks );

		/* Init PMW timer */
		TIM_TimeBaseStructInit( &TIM_TimeBaseStructure );
		TIM_TimeBaseStructure.TIM_Period = RCC_Clocks.HCLK_Frequency / RESOLVER_FREQ /4; //set to 10kHz. div by 4 because TIM4 runs at 1/4 of core speed
		//TIM_TimeBaseStructure.TIM_Period = 65535;
		TIM_TimeBaseStructure.TIM_Prescaler = 0;
		TIM_TimeBaseStructure.TIM_ClockDivision = 0;
		TIM_TimeBaseStructure.TIM_RepetitionCounter = 1;//reload freq
		TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
		TIM_TimeBaseInit( RESOLVER_TIMER, &TIM_TimeBaseStructure );
		TIM_SetCompare1(RESOLVER_TIMER, 0);
		/*TIM_OCInitTypeDef  TIM_OCInitStructure;
		 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
		 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable;
		 TIM_OCInitStructure.TIM_Pulse = 3000;
		 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
		 TIM_OC1Init(TIM3, &TIM_OCInitStructure);

		 TIM_OC1PreloadConfig(RESOLVER_TIMER, TIM_OCPreload_Disable);*/

		/* TIM counter enable */
		TIM_Cmd( RESOLVER_TIMER, ENABLE );

		/* TIM Interrupts enable */
		TIM_ITConfig(RESOLVER_TIMER, TIM_IT_CC1, ENABLE);

		/* Enable the TIM gloabal Interrupt */
		NVIC_InitTypeDef NVIC_InitStructure;
		NVIC_InitStructure.NVIC_IRQChannel = RESOLVER_TIMER_IRQ;
		NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; //higher value=lower priority. priority 0 used by step/dir
		NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
		NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
		NVIC_Init_GD( &NVIC_InitStructure );

#endif
	}
	else
	{
		sys.physIO.doutCHEDir.setState( false ); //set CHD as input
#if 0
				TIM_Cmd( RESOLVER_TIMER, DISABLE );
#endif
	}
}
Example #25
0
void setup_PWM( ){

 // GPIO.
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);

	GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_4 | GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF; 
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
	GPIO_Init(GPIOB, &GPIO_InitStructure);

	GPIO_PinAFConfig(GPIOB, GPIO_PinSource0, GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOB, GPIO_PinSource1, GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_TIM3);

 // Timer3.
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);	
	//u32 PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 21000000) - 1;
	//SystemCoreClock = 168000000
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	TIM_TimeBaseStructure.TIM_Period = 1000-1;
	TIM_TimeBaseStructure.TIM_Prescaler = 84-1;
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

 // PWM.
	TIM_OCInitTypeDef TIM_OCInitStructure;

	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = 0;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

	/* PWM1 Mode configuration: Channel3 (GPIOB Pin 0)*/
	TIM_OC3Init(TIM3, &TIM_OCInitStructure);
	TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);

	/* PWM1 Mode configuration: Channel4 (GPIOB Pin 1)*/
	TIM_OC4Init(TIM3, &TIM_OCInitStructure);
	TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);

	/* PWM1 Mode configuration: Channel1 (GPIOB Pin 4)*/
	TIM_OC1Init(TIM3, &TIM_OCInitStructure);
	TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);

	/* PWM1 Mode configuration: Channel2 (GPIOB Pin 5)*/
	TIM_OC2Init(TIM3, &TIM_OCInitStructure);
	TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

	TIM_Cmd(TIM3, ENABLE);

	// 4 PWM för 2st bakåt och 2st framåt till 2 motorer.
	TIM_SetCompare1(TIM3, 100); // Dutycycle 100/1000 = 1/10
	TIM_SetCompare2(TIM3, 250); // DC = 1/4
	TIM_SetCompare3(TIM3, 500); // DC = 1/2
	TIM_SetCompare4(TIM3, 750); // DC = 3/4
}
Example #26
0
/**
  * @brief  Main program
  * @param  None
  * @retval : None
  */
int main(void)
{
  /* System Clocks Configuration */
  RCC_Configuration();

  /* Configure the GPIO ports */
  GPIO_Configuration();

  /* TIM2 configuration: One Pulse mode ------------------------
     The external signal is connected to TIM2_CH2 pin (PA.01), 
     The Rising edge is used as active edge,
     The One Pulse signal is output on TIM2_CH1 pin (PA.00)
     The TIM_Pulse defines the delay value 
     The (TIM_Period -  TIM_Pulse) defines the One Pulse value.
     The TIM2CLK is fixed to 72 MHz, the Prescaler is 1, so the 
     TIM2 counter clock is 36 MHz. 
     The Autoreload value is 65535 (TIM2->ARR), so the maximum 
     frequency value to trigger the TIM2 input is 500 Hz.
     The TIM_Pulse defines the delay value, the delay value is fixed 
     to 455.08 us:
     delay =  CCR1/TIM2 counter clock = 455.08 us. 
     The (TIM_Period - TIM_Pulse) defines the One Pulse value, 
     the pulse value is fixed to 1.365ms:
     One Pulse value = (TIM_Period - TIM_Pulse)/TIM2 counter clock = 1.365 ms.
  ------------------------------------------------------------ */

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 1;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  /* TIM2 PWM2 Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 16383;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  /* TIM2 configuration in Input Capture Mode */

  TIM_ICStructInit(&TIM_ICInitStructure);

  TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0;

  TIM_ICInit(TIM2, &TIM_ICInitStructure);

  /* One Pulse Mode selection */
  TIM_SelectOnePulseMode(TIM2, TIM_OPMode_Single);

  /* Input Trigger selection */
  TIM_SelectInputTrigger(TIM2, TIM_TS_TI2FP2);

  /* Slave Mode selection: Trigger Mode */
  TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Trigger);

  while (1)
  {}
}
Example #27
0
File: pwm.c Project: intchar90/AHRS
/*定时器2比较奇葩
首先,它的两个通道的指定管脚被USART2的TX、RX占据
其次,它要负责产生一路标准的、周期为20ms的PWM波,来控制舵机
再次,它要负责捕获超声波传感器的脉宽*/
void TIM2_Config(void) //PWM正脉宽捕获
{
	u16 CCR1_Val=1000;
	u16 CCR2_Val=1400;
	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef TIM_BaseInitStructure; 
	TIM_ICInitTypeDef  TIM_ICInitStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure; 

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); 	//使能定时器2时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;				//定时器2通道1,管脚PA0
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;			  //定时器2通道2,管脚PA1
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	TIM_BaseInitStructure.TIM_Period = 20000; //20ms       //定时器2计时周期   
    TIM_BaseInitStructure.TIM_Prescaler = (uint16_t) (SystemCoreClock / 1000000) - 1; //1us       
    TIM_BaseInitStructure.TIM_ClockDivision = 0;     
    TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;    //向上计数
    TIM_TimeBaseInit(TIM2, &TIM_BaseInitStructure); 

//--------------------------------------通道1,PWM输出------------------------------------------
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //定时器2通道1PWM输出
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;   //PWM功能使能
	TIM_OCInitStructure.TIM_Pulse = CCR1_Val;                            //写比较值(占空比
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;   //置高
	TIM_OC1Init(TIM2, &TIM_OCInitStructure);
	TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
//--------------------------------------通道2,PWM输出------------------------------------------
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;    //定时器2通道2PWM输出
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;   //PWM功能使能
	TIM_OCInitStructure.TIM_Pulse = CCR2_Val;                            //写比较值(占空比
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;   //置高
	TIM_OC2Init(TIM2, &TIM_OCInitStructure);
	TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);

//--------------------------------------通道3,输入捕获------------------------------------------
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_3; 		   //定时器2通道3输入捕获模式
   	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling; 
   	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; 
   	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; 
   	TIM_ICInitStructure.TIM_ICFilter = 0x0;     
   	TIM_ICInit(TIM2, &TIM_ICInitStructure);

//--------------------------------------通道4,输入捕获------------------------------------------
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_4; 		   //定时器2通道4输入捕获模式
   	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling; 
   	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; 
   	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; 
   	TIM_ICInitStructure.TIM_ICFilter = 0x0;     
   	TIM_ICInit(TIM2, &TIM_ICInitStructure);
	   	
	TIM_ITConfig(TIM2,TIM_IT_CC3 | TIM_IT_CC4, ENABLE); 
  	TIM_Cmd(TIM2, ENABLE); 
}
Example #28
0
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */     

  /* Initialize LEDs and Key Button mounted on STM3210X-EVAL board */       
  STM_EVAL_LEDInit(LED1);
  STM_EVAL_LEDInit(LED2);
  STM_EVAL_PBInit(BUTTON_KEY, BUTTON_MODE_GPIO);

  /* RTC Configuration */
  RTC_Configuration();

  /* Wait until Key Push button is pressed */
  while (STM_EVAL_PBGetState(BUTTON_KEY) != 0)
  {
  }

  /* Get the Frequency value */
  RCC_GetClocksFreq(&RCC_Clocks);

  /* Enable TIM5 APB1 clocks */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);

  /* Connect internally the TM5_CH4 Input Capture to the LSI clock output */
  GPIO_PinRemapConfig(GPIO_Remap_TIM5CH4_LSI, ENABLE);

  /* TIM5 Time base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
  TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);

  /* TIM5 Channel4 Input capture Mode configuration */
  TIM_ICInitStructure.TIM_Channel = TIM_Channel_4;
  TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
  TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
  TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
  TIM_ICInitStructure.TIM_ICFilter = 0;
  TIM_ICInit(TIM5, &TIM_ICInitStructure);

  /* Reinitialize the index for the interrupt */
  OperationComplete = 0;

  /* Enable the TIM5 Input Capture counter */
  TIM_Cmd(TIM5, ENABLE);
  /* Reset all TIM5 flags */
  TIM5->SR = 0;
  /* Enable the TIM5 channel 4 */
  TIM_ITConfig(TIM5, TIM_IT_CC4, ENABLE);

  /* NVIC configuration */
  NVIC_Configuration();

  /* Wait the TIM5 measuring operation to be completed */
  while (OperationComplete != 2)
  {}

  /* Compute the actual frequency of the LSI. (TIM5_CLK = 2 * PCLK1)  */
  if (PeriodValue != 0)
  {
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL)
    LsiFreq = (uint32_t)((uint32_t)(RCC_Clocks.PCLK1_Frequency) / (uint32_t)PeriodValue);
#else
    LsiFreq = (uint32_t)((uint32_t)(RCC_Clocks.PCLK1_Frequency * 2) / (uint32_t)PeriodValue);
#endif
  }

  /* Adjust the RTC prescaler value */
  RTC_SetPrescaler(LsiFreq - 1);

  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();

  /* Turn on LED2 */
  STM_EVAL_LEDOn(LED2);

  while (1)
  {
    /* Infinite loop */
  }

}
Example #29
0
/*******************************************************************************
* Function Name  : main
* Description    : Main program
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
#ifdef DEBUG
  debug();
#endif

  /* System Clocks Configuration */
  RCC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the GPIO ports */
  GPIO_Configuration();

  /* ---------------------------------------------------------------
    TIM2 Configuration: generate 4 signals with 4 different delays:
    TIM2CLK = 36 MHz, Prescaler = 35999, TIM2 counter clock = 1 KHz
    TIM2_CH1 delay = CCR1_Val/TIM2 counter clock = 1000 ms
    TIM2_CH2 delay = CCR2_Val/TIM2 counter clock = 500 ms
    TIM2_CH3 delay = CCR3_Val/TIM2 counter clock = 250 ms
    TIM2_CH4 delay = CCR4_Val/TIM2 counter clock = 125 ms
  --------------------------------------------------------------- */

  /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 35999;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  /* Output Compare Active Mode configuration: Channel1 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Active;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OC1Init(TIM2, &TIM_OCInitStructure);

  TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Active Mode configuration: Channel2 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR2_Val;

  TIM_OC2Init(TIM2, &TIM_OCInitStructure);

  TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Active Mode configuration: Channel3 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3_Val;

  TIM_OC3Init(TIM2, &TIM_OCInitStructure);

  TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);

  /* Output Compare Active Mode configuration: Channel4 */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR4_Val;

  TIM_OC4Init(TIM2, &TIM_OCInitStructure);

  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Disable);

  TIM_ARRPreloadConfig(TIM2, ENABLE);

  /* Set PC.06 pin */
  GPIO_SetBits(GPIOC, GPIO_Pin_6);

  /* TIM2 enable counter */
  TIM_Cmd(TIM2, ENABLE);

  while (1)
  {}
}
Example #30
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured,
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f2xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f2xx.c file
     */

  /* TIM1 Configuration */
  TIM_Config();

  /* ---------------------------------------------------------------------------
    TIM1 and Timers(TIM3 and TIM4) synchronisation in parallel mode.
     1/TIM1 is configured as Master Timer:
         - PWM Mode is used
         - The TIM1 Update event is used as Trigger Output

     2/TIM3 and TIM4 are slaves for TIM1,
         - PWM Mode is used
         - The ITR0(TIM1) is used as input trigger for both slaves
         - Gated mode is used, so starts and stops of slaves counters
           are controlled by the Master trigger output signal(update event).

    In this example TIM1 input clock (TIM1CLK) is set to 2 * APB2 clock (PCLK2),
    since APB2 prescaler is different from 1.
      TIM1CLK = 2 * PCLK2
      PCLK2 = HCLK / 2
      => TIM1CLK = HCLK = SystemCoreClock

    The TIM1 counter clock is equal to SystemCoreClock = 120 Mhz.

    The Master Timer TIM1 is running at:
    TIM1 frequency = TIM1 counter clock / (TIM1_Period + 1) = 468.750 KHz
    TIM1_Period = (TIM1 counter clock / TIM1 frequency) - 1 = 255
    and the duty cycle is equal to: TIM1_CCR1/(TIM1_ARR + 1) = 50%

    The TIM3 is running at:
    (TIM1 frequency)/ ((TIM3 period +1)* (Repetition_Counter+1)) = 31.250 KHz and
    a duty cycle equal to TIM3_CCR1/(TIM3_ARR + 1) = 33.3%

    The TIM4 is running at:
    (TIM1 frequency)/ ((TIM4 period +1)* (Repetition_Counter+1)) = 46.875 KHz and
    a duty cycle equal to TIM4_CCR1/(TIM4_ARR + 1) = 50%

    Note:
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f2xx.c file.
     Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate()
     function to update SystemCoreClock variable value. Otherwise, any configuration
     based on this variable will be incorrect.
  --------------------------------------------------------------------------- */


  /* TIM3 Peripheral Configuration ----------------------------------------*/
  /* TIM3 Slave Configuration: PWM1 Mode */
  TIM_TimeBaseStructure.TIM_Period = 2;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM3, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM3 */
  TIM_SelectSlaveMode(TIM3, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM3, TIM_TS_ITR0);

  /* TIM4 Peripheral Configuration ----------------------------------------*/
  /* TIM4 Slave Configuration: PWM1 Mode */
  TIM_TimeBaseStructure.TIM_Period = 1;
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 1;

  TIM_OC1Init(TIM4, &TIM_OCInitStructure);

  /* Slave Mode selection: TIM4 */
  TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated);
  TIM_SelectInputTrigger(TIM4, TIM_TS_ITR0);

  /* TIM1 Peripheral Configuration ----------------------------------------*/
  /* Time Base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseStructure.TIM_Period = 255;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_RepetitionCounter = 4;

  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);

  /* Channel 1 Configuration in PWM mode */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
  TIM_OCInitStructure.TIM_Pulse = 127;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
  TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
  TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;

  TIM_OC1Init(TIM1, &TIM_OCInitStructure);

  /* Automatic Output enable, Break, dead time and lock configuration*/
  TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
  TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
  TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_1;
  TIM_BDTRInitStructure.TIM_DeadTime = 5;
  TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable;
  TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;
  TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Disable;

  TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);

  /* Master Mode selection */
  TIM_SelectOutputTrigger(TIM1, TIM_TRGOSource_Update);

  /* Select the Master Slave Mode */
  TIM_SelectMasterSlaveMode(TIM1, TIM_MasterSlaveMode_Enable);

  /* TIM1 counter enable */
  TIM_Cmd(TIM1, ENABLE);

  /* TIM enable counter */
  TIM_Cmd(TIM3, ENABLE);
  TIM_Cmd(TIM4, ENABLE);

  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);

  while (1)
  {}
}