I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.
Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.
Any help would be great!
Fixed Code: See accepted answer below.
#include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>
int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;
const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;
unsigned long debounceDelay = 50;
//****************************************************************setup*****************************************
void setup() {
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
Serial.begin(9600);
analogWrite(6,con);
mylcd.begin();
lcd.print("Welcome");
}
//************************************************************loop************************************************
void loop() {
int reading1 = digitalRead(button1Pin);
int reading2 = digitalRead(button2Pin);
if (reading1 == lastButton1State &&
reading2 == lastButton2State)
return; // do nothing if no change
delay (debounceDelay); // debounce
// re-read so we can catch both buttons down at once
reading1 = digitalRead(button1Pin);
reading2 = digitalRead(button2Pin);
// save for next time
lastButton1State = reading1;
lastButton2State = reading2;
if (reading1 == LOW && reading2 == HIGH) // first one down
btn_push = 'D';
else if (reading1 == HIGH && reading2 == LOW) // second one down
btn_push = 'U';
else if (reading1 == LOW && reading2 == LOW) // both
btn_push = 'S';
else
return; // nothing interesting
Serial.print("btn_push = ");
Serial.println(btn_push);
// page select
switch (page) {
case 0:
page0();
break;
case 1:
page1();
break;
case 2:
page2();
break;
case 3:
page3();
break;
case 4:
page4();
break;
}
}
// The rest is the same, excluding the functions that are no longer needed
==takes precedence over&&- but I too consider it bad practice to rely on C++ operator precedence.