[英]Using CCS Toggle LED With Button
I didn't understand what is wrong with my code.我不明白我的代码有什么问题。 Here what I am trying to do is toggle a led when I press button.
在这里,我要做的是在按下按钮时切换 LED。 And I count my button hits with
int count;
我用
int count;
计算我的按钮点击int count;
. . If the count number is even LED is high and else LED is low.
如果计数为偶数,则 LED 为高电平,否则 LED 为低电平。 But when I upload this program, LED stays on.
但是当我上传这个程序时,LED 一直亮着。 And off only while I hold the button.
并且仅在我按住按钮时关闭。
while(1){
int buttonState=input_state(pin_a0);
if(buttonState != lastButtonState){
count++;
lastButtonState=buttonState;
if(count%2==0){
output_high(pin_b0);
}
else
output_low(pin_b0);
}
delay_ms(50);
}
There is a problem in your logic.你的逻辑有问题。 You have two changes while pressing the button.
按下按钮时您有两个更改。 The first change is from 0 to 1 (pressing) and the second change is from 1 to 0 (releasing the button).
第一个变化是从 0 到 1(按下),第二个变化是从 1 到 0(释放按钮)。
Try something like:尝试类似:
if(lastButtonState == 0 && buttonState == 1)
Is your button active-high or active-low ?你的按钮是高电平有效还是低电平有效? Is your LED powered active-high or active-low?
您的 LED 是高电平有效还是低电平有效? You need to give that information.
你需要提供这些信息。 I'll give an explanation assuming LED is powered when output is low.
假设输出低时 LED 已通电,我将给出解释。 Then what follows is, assuming button is active-low, when your button is not pressed,
那么接下来是,假设按钮是低电平有效,当你的按钮没有被按下时,
buttonState = 1;
So, since所以,既然
lastButtonState = 0;
(at the start of the program, I'm assuming) (在程序开始时,我假设)
You will enter the if clause:您将输入 if 子句:
if(buttonState != lastButtonState){
...
}
This will increase your counter by one and make lastButtonState = buttonState;
这将使您的计数器增加一并使
lastButtonState = buttonState;
Since count%2
will be 1
, your pin will be output_low(pin_b0);
由于
count%2
将为1
,因此您的引脚将为output_low(pin_b0);
... So, at the start of your program, your LED will be ON. ... 因此,在您的程序开始时,您的 LED 将亮起。
If you then press the button,如果你按下按钮,
buttonState=0;
will happen and you will enter the if() clause, again.会发生,您将再次输入 if() 子句。 This will increase your counter by one.
这将使您的计数器增加一。 And then:
然后:
count%2 = 0;
Will happen.会发生。 So, you will have
所以,你会有
output_high(pin_b0);
As you can see, when you press the button, your LED will go off.如您所见,当您按下按钮时,您的 LED 将熄灭。 And on when you release the button, your LED will go on Try this:
当您松开按钮时,您的 LED 将亮起 试试这个:
while(1){
int buttonState=input_state(pin_a0);
if(buttonState != lastButtonState){
lastButtonState=buttonState;
if(buttonState == 1){
output_high(pin_b0); // LED is off
}
else
output_low(pin_b0); // LED is on
}
delay_ms(50);
}
You don't need the counter.你不需要柜台。
EDIT:编辑:
I see you have made this addition to your code:我看到您在代码中添加了以下内容:
if(buttonState==1)
count++;
This works.这有效。 Yet is harder to understand.
然而更难理解。 Try writing something easier to read.
尝试写一些更容易阅读的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.