I'm having trouble with my buttons lagging or not registering when pressed. When I upload the following code my buttons need 3-4 clicks before they start to register and start doing what they're supposed to do. Any tips on how to fix this?
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define height 128
#define width 32
#define button D6 //digital pins 6 and 7 for my board. just put '6' and '7' for normal arduino boards.
#define button2 D7
int screen_current = 0;
int old_screen = 0;
int buttonPoll = 0;
int button2Poll = 0;
void setup() {
Serial.begin(9600);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.begin(SSD1306_SWITCHCAPVCC, 0x3c);
display.clearDisplay(); //clear the buffer
display.display();
pinMode(button, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
}
void loop() {
//debounce
buttonPoll = digitalRead(button);
if(buttonPoll == 1) {
Serial.println("PRESSED");
delay(50);
buttonPoll = digitalRead(button);
if(buttonPoll == 0) {
screen_current = old_screen + 1;
Serial.println("RELEASED");
}
}
else{
Serial.println("DO NOTHING");
delay(50);
}
//debounce button 2
button2Poll = digitalRead(button2);
if(button2Poll == 1) {
Serial.println("PRESSED");
delay(50);
button2Poll = digitalRead(button2);
if(button2Poll == 0) {
screen_current = old_screen - 1;
Serial.println("RELEASED");
}
}
else{
Serial.println("DO NOTHING");
delay(50);
}
switch(screen_current) {
case 1:
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(30, 9);
display.println("SCREEN 1");
display.display();
Serial.println("SCREEN CURRENT = ");
Serial.println(screen_current);
Serial.println("OLD SCREEN = ");
Serial.println(old_screen);
old_screen = screen_current;
break;
case 2:
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(30, 9);
display.println("SCREEN 2");
display.display();
Serial.println("SCREEN CURRENT = ");
Serial.println(screen_current);
Serial.println("OLD SCREEN = ");
Serial.println(old_screen);
old_screen = screen_current;
break;
case 3:
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(30, 9);
display.println("SCREEN 3");
display.display();
Serial.println("SCREEN CURRENT = ");
Serial.println(screen_current);
Serial.println("OLD SCREEN = ");
Serial.println(old_screen);
old_screen = screen_current;
break;
default:
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(30, 9);
display.println("SCREEN X");
display.display();
old_screen = 0;
Serial.println("SCREEN CURRENT = ");
Serial.println(screen_current);
Serial.println("OLD SCREEN = ");
Serial.println(old_screen);
break;
}
}