引脚模式应为高电平时始终为低电平

时间:2018-08-13 11:17:11

标签: arduino

我正在使用简单的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只是闪烁

2 个答案:

答案 0 :(得分:0)

我认为您正在使用错误的功能从PIN读取状态。

 if (Serial.available())
 {
 state = Serial.parseInt();

为什么不使用https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/

您确定此条件评估为true吗?如果(Serial.available())吗?

答案 1 :(得分:0)

您使逻辑过于复杂。只需检查序列号是否可用,并打开期望值的指示灯,否则检查按钮,如果按下按钮,则关闭指示灯。在其他条件下DO NOTHING。这就是您所需要的。

// 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()
{
    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:
    else if (digitalRead(buttonPin) == HIGH)
    {
        // turn LED OFF:
        Serial.println("off");
        digitalWrite(ledPin, LOW);
    }
}