STM8S003F3 uses a timer to calculate the square wave period

Our requirement is to use stm8 as a slave, and then use a line to receive the square wave to achieve different functions, such as turning on the red light, turning on the yellow light, turning on the buzzer, and so on.

So here comes the problem. Before, I tried to achieve different functions by sending how many square waves at a time, but in the end I found that this method didn't work. Later, I thought about the different functions that can be achieved through the square wave frequency sent by the host, that is, to know the period of the square wave sent every time.

So how to calculate the period of the square wave? I would like to thank my colleagues for giving me ideas to realize this function.

The first is to do the external interrupt of gpio. Here, set gpio PD4 in the main function. When there is a falling edge, it will enter the interrupt processing function:

GPIO_Init(GPIOD,GPIO_PIN_4, GPIO_MODE_IN_FL_IT );//接收方波初始化
EXTI_DeInit();
EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOD , EXTI_SENSITIVITY_FALL_ONLY);

The configuration of the timer timer2 in the main function is as follows:

//内部时钟为16M,因此这个设置时以10ms进入一次中断
TIM2_DeInit();  
TIM2_TimeBaseInit(TIM2_PRESCALER_16, 9999);       
TIM2_PrescalerConfig(TIM2_PRESCALER_16, TIM2_PSCRELOADMODE_UPDATE);  
TIM2_ITConfig(TIM2_IT_UPDATE, ENABLE);  
TIM2_SetCounter(0x0000);  
TIM2_Cmd(ENABLE);  
TIM2_ClearFlag(TIM2_FLAG_UPDATE);

TIM2_ITConfig( TIM2_IT_UPDATE, ENABLE);
TIM2_Cmd(ENABLE); 

In the external interrupt function of gpio, set it like this:

INTERRUPT_HANDLER(EXTI_PORTD_IRQHandler, 6)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
  //GPIO_WriteReverse(GPIOD,GPIO_PIN_3);  
  flag ^= 0x01;
  if(flag == 0)
  	test_time = 0;
  else{
	tmp_count = test_time;
  }
}

In the external interrupt handling function of timer2, set it like this:

 INTERRUPT_HANDLER(TIM2_UPD_OVF_BRK_IRQHandler, 13)
 {
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
     
     TIM2_ClearFlag( TIM2_FLAG_UPDATE);//记得要清除标志位,否则会出问题
	 test_time++;
   
 }

In this way, when the flag is 0, it will be cleared, and when it is 1, the data will be transmitted, which is equivalent to knowing the time of a cycle.

There are problems: Although this way of writing can solve the problem, there will still be problems at the beginning of the program, because the timer may go first, and the main function may be slower than the timer. At the beginning, it may be lost, but it will be stable later. .

Guess you like

Origin blog.csdn.net/smile_5me/article/details/105843646