我正在使用mplab并用C编写代码。我已经设置了我的程序,所以它有两个状态。我想要能够双击一个按钮,它在状态1和2之间切换。我用一种非常简单的方法来实现,而不是使用切换语句等。
我已经完成了所有的设置和工作,但由于我的编码方式,它将从状态1返回到状态1。
有没有一种方法可以说,如果双击按钮,则进入相反的状态?而不是:
if (state == 1)
{
state = 2;
}
if (state == 2)
{
state = 1;
}当然,以这种方式,它将进入状态2,但随后跳转到下面的代码,该代码再次将其更改回状态1。
我知道我可以设置: state = ~ state;但是我如何设置它,让它知道只有一个状态1和2?
下面是我的一些代码:
if (RC1 == 0) // if button is pressed
{
ButtonPressCounter++; // add 1 to counter
}
__delay_ms(250);
if (RC1 == 0) // if button is pressed again
{
ButtonPressCounter++; // add 1 to counter
}
while (ButtonPressCounter == 2)
{
if (state == 1)
{
state = 2;
}
if (state == 2)
{
state = 1;
}
ButtonPressCounter = 0;
}发布于 2021-08-11 12:04:00
您可以使用else来阻止在执行state == 1时执行if (state == 2)。
if (state == 1)
{
state = 2;
}
else if (state == 2) /* add "else" here */
{
state = 1;
}https://stackoverflow.com/questions/68741348
复制相似问题