Arduino LCD数字输入计数器

时间:2015-07-10 03:19:32

标签: arduino

我目前有一个arduino LCD和一个SPDT开关连接到我的主板。 SPDT的公共引脚接地,外引脚分别连接到数字输入。我的程序应该增加和减少打印到LCD屏幕的计数器。我有一个输入工作,增加计数器我不知道如何实现输入代码递减计数器。代码发布如下。

谢谢

 #include <LiquidCrystal.h>


 LiquidCrystal lcd(12, 11, 5,4,3,2); 


 const byte buttonPin = 8;    
 int counter = 0;             // set your counter to zero to begin with


 byte buttonState;             // the current reading from the input pin
 byte lastButtonState = HIGH;   // the previous reading from the input pin

 unsigned long lastDebounceTime = 0;  
 unsigned long debounceDelay = 50;   
 void setup() 
 {
 Serial.begin(9600);  
 pinMode(buttonPin, INPUT_PULLUP); 
 lcd.begin(16, 2);           //  for 2x16 lcd display
 }
 void loop() {
 // read the state of the switch into a local variable:
 byte reading = digitalRead(buttonPin);

 // check to see if you just pressed the button
 // (i.e. the input went from HIGH to LOW),  and you've waited
 // long enough since the last press to ignore any noise:

 // If the switch changed, due to noise or pressing:
 if (reading != lastButtonState) {
  // reset the debouncing timer
  lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) >= debounceDelay) {
  // whatever the reading is at, it's been there for longer
  // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
    buttonState = reading;


   if (buttonState == LOW) {   
    counter ++;
    Serial.println(counter);  
    lcd.setCursor(0, 1);
    lcd.print(counter);
  }


  }
 }
 lastButtonState = reading;
  }

1 个答案:

答案 0 :(得分:2)

您不能简单地将开关的一极连接到另一端的输入引脚。这将检测到LOW,但是当您想要在引脚上检测到HIGH时,它将处于浮动状态。将上拉电阻连接到输入引脚。

或者您可以使用pinMode(InPin,INPUT_PULLUP);

这将在内部将输入引脚拉高,然后您可以检测swithces并实现代码。