我想让一个LED闪光灯在一个空隙中几次,很像良好的老BIOS-哔声,给我的程序状态的视觉反馈,我已经让我的代码工作在3个短闪光灯,但每增加一个闪光灯,我必须手动添加代码。
我想,一定有更好的方法,但我想不出来,因为函数不能在闪烁时使用延迟或循环,从而停止其余的程序.
因为我想要更好地编程,所以我想让你问,不每次添加代码,函数看起来是什么样子的?
这是我的1到3闪存的代码,我为您清理了一些代码:
flag++ // gets incremented every 100ms by interrupt no matter what...
// function to flash an LED
// each flash should be 200ms long (2 increments of 'flag')
// 200ms LED on, 200ms LED off
// given is the number of flashes and the duration till it begins
// to flash again.
void blink(int how_many_times, int duration) {
if (how_many_times >= 1) { // blink once
switch (flag) {
case 2: // 200ms
LED_ON;
break;
case 4:
LED_OFF;
break;
}
}
if (how_many_times >= 2) { // blink twice
switch (flag) {
case 6:
LED_ON;
break;
case 8:
LED_OFF;
break;
}
}
if (how_many_times >= 3) { // blink 3 times
switch (flag) {
case 10:
LED_ON;
break;
case 12:
LED_OFF;
break;
}
}
if(flag >= duration*10) { // *10 because duration is in 'seconds'
flag=0;
}
}
// to let it blink 3 times fast every 5 seconds:
blink(3, 5);发布于 2015-07-01 16:22:49
由于您希望更好地进行编程,我建议从更好地描述变量开始。例如,flag并没有真正描述该变量正在做什么。它真的很像计时器,为什么不叫它timer_100ms呢?那你就知道那个变量是干什么用的。
我还建议对case语句使用枚举,这样您所要完成的任务就会更清楚一些。例如:
/* This timer is incremented every 100ms by the interrupt. */
int timer_100ms;
void blink (int how_many_times, int duration)
{
enum
{
ELAPSED_TIME_200MS = 2,
ELAPSED_TIME_400MS = 4,
/* Fill in other values */
ELAPSED_TIME_1200MS = 12
};
if (how_many_times >= 1)
{
switch (timer_100ms)
{
case ELAPSED_TIME_200MS:
LED_ON;
break;
case ELAPSED_TIME_400MS:
LED_OFF;
break;
}
}
/* The rest of your code follows... */
}这样做可以提高代码的可读性。
尽管如此,为了使您的代码更具有可伸缩性--通过创建更多的LED闪烁而不添加更多代码--我建议从以下几个方面开始:
void blink (int number_of_blinks, int delay_between_blinks_in_seconds)
{
#define ELAPSED_TIME_200MS 2
static int blink_count = 0;
static int timer_prev_100ms = 0;
/* If the delay has been satisfied, start blinking the LED. */
if (timer_100ms >= (delay_between_blinks_in_seconds * 10))
{
/* Change the state of the LED every 200ms. */
if ((timer_100ms - timer_prev_100ms) >= ELAPSED_TIME_200MS)
{
timer_prev_100ms = timer_100ms;
if (led_is_on())
{
LED_OFF;
blink_count++;
}
else
{
LED_ON;
}
}
if (blink_count >= number_of_blinks)
{
timer_100ms = 0;
timer_prev_100ms = 0;
blink_count = 0;
}
}
}显然,您需要添加led_is_on()功能来检查用于闪存LED的引脚的状态。因为,我不知道你是怎么用你的LED连线的,我不想假设这是怎么做的。不过,它的实现非常简单。
https://stackoverflow.com/questions/31165566
复制相似问题