2015-07-10 81 views
-1

我目前有一个arduino LCD和一个SPDT开关连接到我的主板。 SPDT的公共引脚接地,外部引脚分别连接到数字输入。我的程序应该递增和递减正在打印到LCD屏幕的计数器。我有一个输入工作,递增计数器,我不知道如何实现输入代码递减计数器。代码如下。Arduino 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; 
    } 
+0

为什么代码与此不同?除了计数器的引脚和方向? – 2015-07-10 03:22:22

+0

我将如何使这个草图倒计时,因为它是一个SPDT开关,它连接到两个输入。它不能附加到一个输入。 – Marcus

+0

即使是C++,还是仅仅是Arduino? – Olaf

回答

2

你不能简单地连接开关的输入的一个极针的其他在地。这会检测到低电平,但是当你想要在引脚上检测到高电平时,它将浮空。将一个上拉电阻连接到输入引脚。

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

这会将您的输入引脚拉高到内部,然后您可以检测开关并实现代码。

+0

这是一个三叉开关,中心引脚连接到地,一个外部极连接到数字8,另一个外部极连接到数字9. – Marcus

+1

然后,虽然声明它作为输入不使用pinMode(8,INPUT),但使用pinMode (8,INPUT_PULLUP)。对于第9个引脚Ans也一样。 –

+0

为什么你需要将它连接到两个引脚?如果它没有连接到8它连接到9 ... – frarugi87