我正在运行下面给出的程序,但问题是for循环只运行一次并打开LED然后关闭。它应该运行5次。以下是代码:
void led(void)
{
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0;
}
void main(void)
{
ANSEL = 0; //Disable Analog PORTA
TRISA0 = 1; //Make RA0 as Input
TRISB = 0x00;
PORTA = 0;
PORTB = 0x01;
// RB0=0;
while(1)
{
//Switch Pressed
if(swch==0) //Check for Switch Pressed
{
__delay_ms(delay_debounce); //Switch Debounce Delay
if(swch==0) //Check again Switch Pressed
{
//Blink LED at PORT RB0
for (int i = 0; i < 2; i++)
{
led();
}
}
}
else if(swch==1)
{
//Do Nothing
}
}
return;
}
它实际上是LED打开和关闭 五 2次(见代码),它发生得如此之快,以至于它看起来像是发生过一次。这是因为在关闭再打开的位置之间没有延迟。将此小片段添加到您的代码中:
//other code...
for(int i=0;i<2;i++) // The 2 here means the LED will only flash twice!
{
led();
__delay(500);
}
// other code...
如果你扩展你在循环中做的事情,那就变成了
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0;
// No delay here before it switches back
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0;
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0;
请注意,当LED离开例程时,LED更改状态之间没有延迟。更改状态后添加另一个延迟。
void led(void)
{
RB0=~RB0;
__delay_ms(delay);
RB0=~RB0;
__delay_ms(delay);
}