Re: [問題] 讓兩顆LED用不同的頻率閃爍

作者: happierway (杰夫)   2017-08-05 01:24:27
本版第一PO就獻給LED blink了 :P
我覺得在寫嵌入式系統有個很重要的觀念,就是讓結果看起來是多工就好了。
解法一:閃爍的頻率在你的PWM可以接受的範圍內的話,
可以直接用兩個PWM output控制 :)
解法二:用一個timer加上兩個LED各自的state machine,以下是其中一種實作方法:
uint16_t led_1_counter = 0;
uint16_t led_2_counter = 0;
#define led_1_ON_threshold < LED_1 暗的時間 >
#define led_1_OFF_threshold < LED_1 亮的時間 > + led_1_ON_threshold
#define led_2_ON_threshold < LED_2 暗的時間 >
#define led_2_OFF_threshold < LED_2 亮的時間 > + led_2_ON_threshold
#define LED_ON 1
#define LED_OFF 0
uint8_t led_1_action = LED_OFF;
uint8_t led_2_action = LED_OFF;
void timer_interrupt_handler()
{
led_1_counter++;
led_2_counter++;
if(led_1_counter == led_1_ON_threshold) led_1_action = LED_ON;
if(led_1_counter >= led_1_OFF_threshold)
{
led_1_counter = 0;
led_1_action = LED_OFF;
}
if(led_2_counter == led_2_ON_threshold) led_2_action = LED_ON;
if(led_2_counter >= led_2_OFF_threshold)
{
led_2_counter = 0;
led_2_action = LED_OFF;
}
}
void main()
{
// 初始化你的 timer,timer中斷時間的長短依據你的閃爍頻率調整
initialize_timer_module(&timer_interrupt_handler);
while(1)
{
if(led_1_action == LED_ON) set_LED_ON(LED_1);
else if(led_1_action == LED_OFF) set_LED_OFF(LED_1);
if(led_2_action == LED_ON) set_LED_ON(LED_2);
else if(led_2_action == LED_OFF) set_LED_OFF(LED_2);
}
}
作者: happierway (杰夫)   2017-08-05 01:30:00
作者: Lipraxde (Lipraxde)   2017-08-05 22:26:00
控制LED亮滅的部分可以放在中斷裡,回圈裡休眠省電

Links booklink

Contact Us: admin [ a t ] ucptt.com