做while循环退出前成熟

Raj*_*esh 2 c avr do-while

我已经编写了用于读取开关状态的代码,如果按下#是3次则退出.

void allkeypadTest(void)
{
    static uint8_t modeKeyCount=0;

    do
    {
        uint8_t key=getKeyStatus();
        if(key)
        {
            if(key=='#')
            {
                modeKeyCount++;
                //pulseIODevice(LED1,1,500,200);
            }
            else
            {
                pulseIODevice(LED1,key-0x30,500,200);
            }
        }
     }while(modeKeyCount<3);
}
Run Code Online (Sandbox Code Playgroud)

但是一旦我输入#key一次,循环就会退出.如果按其他键,行为就可以了.但是,如果我pulseIODeviceif(key=='#')部分下取消注释,行为是正常的.pulseIODevice将在特定时间段内将LED切换一定时间并将PWM传递给它.我很困惑我的代码出了什么问题.请注意,如果未检测到任何键,getKeyStatus则返回'\0'(null)并返回1x4键盘键的ASCII值(ASCII值为3,6,9和#)

alk*_*alk 6

在检测到键状态后,您可能需要等到它恢复正常(没有按键)才能继续

要做这样的改变

uint8_t key=getKeyStatus();
Run Code Online (Sandbox Code Playgroud)

成为

uint8_t key = getKeyStatus();
while (0 != getKeyStatus())
{
  /* Do nothing. 
     Shouldn't loop too long if not abused by holding the key pressed. */
  /* if available add some milli sec delay here. */
}
Run Code Online (Sandbox Code Playgroud)

一点点更有效,甚至更准确

uint8_t key = getKeyStatus();
if ( 0 != key) 
{
  do 
  {
    /* Do nothing. 
       Shouldn't loop too long if not abused by holding the key pressed. */
    /* If available add some milli sec delay here. */
  } while (0 != getKeyStatus());
}
Run Code Online (Sandbox Code Playgroud)

背景:

要根据定义从状态的变化("按下键","键入")检测事件(此处"按下"键),您需要多次测试.