我的代码在检查按钮状态时忽略了 if 条件

My code ignores the if condition when checking the button state

提问人:Diego Rosendo Pérez 提问时间:9/30/2023 最后编辑:LoSDiego Rosendo Pérez 更新时间:9/30/2023 访问量:32

问:

我想按下我的按钮,然后 LED 将开始按顺序打开和关闭。

int buttonState = 0; 
int tDelay = 500; 
int latchPin = 11;  // output register clock
int clockPin = 9;  // shift register clock
int dataPin = 12; // Input
    
byte leds = 0; 

void updateShiftRegister()
{
  // setting latch pin low prepares register for input
  digitalWrite(latchPin, LOW);
  // writes to the register
  // Will 'pulse' the Clock pin 8 times, once for each bit
  shiftOut(dataPin, clockPin, MSBFIRST, leds);
  
  digitalWrite(latchPin, HIGH);
}

void setup()
{
  pinMode(2, INPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);  
  pinMode(clockPin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  leds = 0; 
  buttonState = digitalRead(2); // This function is used to 
  // read the digital state of a specific pin on the 
  // microcontroller. It's reading the state of pin 2.
  if (buttonState == HIGH)
  {
    updateShiftRegister(); // Switch off all LEDs
    delay(tDelay); 
    for (int i = 0; i < 6; i++)
    {
      leds = 0; // this is the change
      bitSet(leds, i); // switches one LED on
      updateShiftRegister(); 
      delay(tDelay); 
    }
  }
    else {
      updateShiftRegister(); 
  }
}

我的想法是

  1. 你按下按钮
  2. 一个 LED 亮起然后熄灭
  3. 第一个 LED 旁边的 LED 在第一个 LED 熄灭后打开和关闭,然后所有 LED 都做同样的事情

我的问题是:在我开始模拟的那一刻,LED 开始打开和关闭,但它们完全忽略了条件。问题是,如果我移除按钮,那么模拟就不起作用。if

C++ 电路 TinkerCAD

评论


答:

0赞 Coder_p54 9/30/2023 #1

简单,就这么做 if (buttonState == LOW)

buttonState 在你按下它时将是 LOW,但如果你不按下它,那么它是 HIGH,这就是你的代码不起作用的原因