Use interrupt change screen

 To use an ESP32 with Arduino programming and a push button to change the screen on a display, you can follow these steps:


Connect the Push Button: Connect the push button to a digital input pin on the ESP32. Ensure that you have the necessary pull-up or pull-down resistors based on your button configuration.


Connect the Display: Connect the display to the ESP32 using the appropriate communication protocol (e.g., SPI or I2C). Refer to the documentation or datasheet of your display for the pin connections.


Install Libraries: Install the necessary libraries for your display and button. For example, you can use the "Adafruit GFX" and "Adafruit SSD1306" libraries for OLED displays and the "Bounce2" library for button debouncing.


Initialize the Display: In your Arduino sketch, initialize the display by setting up the necessary parameters and initializing the display object. Refer to the library documentation for specific initialization instructions.


Configure Button and Change Screen: In the Arduino sketch, configure the button pin as an input and set up a button interrupt or a polling mechanism to detect button presses. When a button press is detected, change the content on the display.


#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>

#include <Bounce2.h>


#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64


#define BUTTON_PIN 2

Bounce debouncer = Bounce();


Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);


void setup() {

  pinMode(BUTTON_PIN, INPUT_PULLUP);

  debouncer.attach(BUTTON_PIN);

  debouncer.interval(10);


  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  display.clearDisplay();

  display.setTextSize(2);

  display.setTextColor(WHITE);

  display.setCursor(0, 0);

  display.println("Screen 1");

  display.display();

}


void loop() {

  debouncer.update();

  if (debouncer.fell()) {

    changeScreen();

  }

}


void changeScreen() {

  // Change the content on the display based on button press

  static bool isScreen1 = true;


  if (isScreen1) {

    display.clearDisplay();

    display.setCursor(0, 0);

    display.println("Screen 2");

    display.display();

  } else {

    display.clearDisplay();

    display.setCursor(0, 0);

    display.println("Screen 1");

    display.display();

  }


  isScreen1 = !isScreen1;

}

In this example, we use the "Bounce2" library to debounce the button and the "Adafruit SSD1306" library for the display. The changeScreen() function is called when a button press is detected. It alternates between two screens on the OLED display.


Upload and Test: Upload the sketch to your ESP32 board and test the functionality. Pressing the button should toggle between the two screens on the display.


Remember to customize the code according to your specific display and button configuration. Additionally, consider implementing debouncing techniques to handle multiple button presses caused by button bouncing.





Comments

Popular Posts