我正在使用简单的Arduino,我正在尝试使用串行打印打开LED灯,当我点击按钮或使用电路板上的开关时,当针脚在地面时关闭LED灯 .
此刻,我可以通过串口打开LED指示灯,但是当我点击按钮时,LED指示灯将关闭,但之后永远不会打开,而这种情况正在发生,因为状态始终处于低位并且从不切换回来高 .
这是代码:
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 3; // the number of the LED pin
int state = 0;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (Serial.available())
{
state = Serial.parseInt();
if (state == 1)
{
digitalWrite(ledPin, HIGH);
Serial.println("ON");
}
}
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW) {
state = 0;
// turn LED OFF:
Serial.println("off");
digitalWrite(ledPin, LOW);
}
// IMP : This Never runs. the state is always off therefore when i send to serial " 1" the led just blinks
else {
Serial.println("off");
}
}
因此,当我发送到串行“1”时LED始终闪烁,状态总是关闭
1 回答
我认为您正在使用错误的功能从PIN读取状态 .
为什么不使用https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/?
你确定这个条件评估为真吗? if(Serial.available())?