Code Example
In this demo, TIM2 is configured to generate PWM on its CH1 output. TIM1 is configured to capture
every rising edge of incoming waveform at its input capture channel CH1. When a capture event
occurs, the current time count of TIM1 is saved. By deducting the recent capture count from the
previous capture count, we can measure time period of the incoming PWM signal and hence its
frequency. If the frequency is too high, TIM1 may overflow and so we need to take care of it too. We,
thus, need to check TIM1 overflow event too.
main.c
#include "STM8S.h"
#include "lcd.h"
unsigned int overflow_count = 0;
unsigned long pulse_ticks = 0;
unsigned long start_time = 0;
unsigned long end_time = 0;
void clock_setup(void);
void GPIO_setup(void);
void TIM1_setup(void);
void TIM2_setup(void);
void lcd_print(unsigned char x_pos, unsigned char y_pos, unsigned long value);
void main()
{
unsigned long time_period = 0;
clock_setup();
GPIO_setup();
TIM1_setup();
TIM2_setup();
LCD_init();
LCD_clear_home();
LCD_goto(0, 0);
LCD_putstr("T/ms:");
delay_ms(10);
while(TRUE)
{
time_period = pulse_ticks;
lcd_print(0, 1, time_period);
delay_ms(400);
};
}
void clock_setup(void)
{
CLK_DeInit();
CLK_HSECmd(DISABLE);
CLK_LSICmd(DISABLE);
CLK_HSICmd(ENABLE);
while(CLK_GetFlagStatus(CLK_FLAG_HSIRDY) == FALSE);
CLK_ClockSwitchCmd(ENABLE);
CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV8);
Need help?
Do you have a question about the STM8 and is the answer not in the manual?
Questions and answers