You've hit on a very important point, and your intuition is correct for a certain type of circuit!
The reason it's digitalRead(B1) == LOW is because of this line in the setup() function:
cpp
pinMode(B1, INPUT_PULLUP);
// and similarly for B2, B3, B4, B5
Let's break down what INPUT_PULLUP does:
Internal Pull-up Resistor: The ESP32 (and many microcontrollers) have internal "pull-up" resistors that can be enabled programmatically.
How it Works:
When INPUT_PULLUP is enabled, the pin is internally connected to VCC (3.3V on the ESP32) through a resistor.
Button Not Pressed: If the button is not pressed, there's no path to Ground (GND). The pin "sees" the 3.3V through the pull-up resistor, so digitalRead() will return HIGH.
Button Pressed: You wire your push button so that one terminal is connected to the ESP32 pin and the other terminal is connected to Ground (GND). When you press the button, it creates a direct path from the pin to GND. This pulls the pin's voltage down to 0V (LOW).
So, with INPUT_PULLUP:
Button NOT Pressed = HIGH
Button PRESSED = LOW
That's why the code checks for LOW to detect a button press.
The Alternative (and why your intuition might say HIGH):
If you were not using the internal pull-up resistor, you might use an external pull-down resistor. In that scenario:
The pin is connected to GND through an external resistor.
The button is wired to connect the pin to VCC (3.3V) when pressed.
Button Not Pressed: The pin is pulled to GND by the resistor, so digitalRead() returns LOW.
Button Pressed: The pin is connected to VCC, so digitalRead() returns HIGH.
In this case, your if statement would indeed be if (digitalRead(B1) == HIGH).
Why INPUT_PULLUP is Common:
Simpler Wiring: It saves you from adding an external resistor for each button. You just need the button and a connection to GND.
Default State is Known: When not pressed, the pin is reliably HIGH, not "floating" (which can lead to unpredictable readings).
In Summary:
The code if (digitalRead(B1) == LOW && digitalRead(B2) == LOW) is correct because the pins are configured as INPUT_PULLUP. If they were configured with external pull-down resistors, the logic would be HIGH.
Good catch for thinking critically about the logic levels!
User
where would the things i type be visible
Assistant
Okay, great question! Based on the code snippets we've discussed, the typed characters would primarily be visible in two places, depending on your setup:
The Arduino IDE's Serial Monitor (or any Serial Terminal Program):
The line Serial.begin(115200); in your setup() function initializes serial communication.
The lines like Serial.println("Typed: " + typedWord); and Serial.print(typedChar); send the typed information over the USB connection to your computer.
How to see it:
Make sure your ESP32 is connected to your computer via USB.
After uploading the code, open the Serial Monitor in the Arduino IDE (Tools > Serial Monitor, or the magnifying glass icon).
Ensure the baud rate in the Serial Monitor window (bottom right) is set to 115200 (to match what's in your Serial.begin() call).
As you press the buttons according to your defined scheme, you'll see the characters appear in the Serial Monitor.
No Direct Visual Output on the ESP32 Board Itself (Yet):
The ESP32 board itself doesn't have a built-in screen (unless you bought a specific model that includes one, like an ESP32 with an integrated OLED).
The code we've discussed so far only sends data out via the serial port.
For a Truly Standalone Device (No Computer Needed for Output):
If your goal is to have a completely standalone typing device where you don't need a computer connected to see what you're typing, you'll need to add a display module to your ESP32 project. Common choices include:
OLED Displays (e.g., SSD1306, SH1106):
These are small, crisp, and relatively easy to interface with (usually via I2C or SPI).
Popular sizes are 0.96 inch or 1.3 inch.
Excellent for displaying text.
You'd need to add a library (like Adafruit_SSD1306 and Adafruit_GFX) and write code to initialize the display and print characters to it.
cpp
User
what is the purpose of the debouncer
Assistant
You've asked about a crucial concept in working with physical buttons and microcontrollers!
The purpose of a debouncer is to prevent multiple, unintended inputs from a single physical button press.
Here's why it's needed:
Mechanical Bounce:
When you press a physical button, the electrical contacts inside it don't make a clean, instantaneous connection. Instead, they "bounce" against each other for a very short period (a few milliseconds). During this bouncing, the electrical signal rapidly switches between ON and OFF (or HIGH and LOW) multiple times.
Imagine it like dropping a bouncy ball: it hits the ground (makes contact) and then bounces up and down a few times before settling. A button's contacts do something similar at a microscopic level.
Microcontroller Speed:
Your ESP32 (or any microcontroller) is extremely fast. It can read the state of a digital input pin thousands or even millions of times per second.
The Problem:
If the microcontroller reads the button pin during this "bouncing" period, it will see those rapid ON-OFF transitions as multiple separate presses. So, if you press a button intending to type a single 'A', the microcontroller might think you pressed it 3, 4, or even more times, resulting in "AAAA" appearing. This is clearly not what you want.
How a Debouncer Solves This:
A debouncer (either hardware or software) introduces a mechanism to ignore these rapid, short-lived fluctuations and only register a single, stable press.
The Bounce2 library (and other software debouncing techniques) typically works like this:
Detect Initial Change: It sees the first transition (e.g., from HIGH to LOW if using INPUT_PULLUP).
Wait and See: Instead of immediately acting on this change, it waits for a short, predefined "debounce interval" (e.g., 20-50 milliseconds).
Verify Stability: After this interval, it checks the button's state again.
If the button's state is still the same as the initial change (e.g., still LOW), it confirms that a "stable" press has occurred and registers it.
If the button's state has fluctuated back during the interval, it might ignore it or reset its timer, waiting for a more stable signal.
In the Bounce2 library:
debouncer.attach(PIN);: Initializes the debouncer for a specific pin.
: Sets how long the debouncer should wait to confirm a stable state.
User
how to do backspace
Assistant
Okay, let's add a backspace function!
We need to:
Define a button combination for "Backspace."
When this combination is detected, remove the last character from your typedWord string.
Handle the case where typedWord is already empty.
Let's use the combination we discussed earlier: Pressing B1, B2, B3, B4, and B5 simultaneously.
This is a great start and you've laid out your chord map! The main challenge with your current loop() structure is how it handles multiple key presses and the use of delay(200).
Key Issues with the Current loop():
Blocking delay(200): Every time a character is added, the ESP32 pauses for 200ms. This will:
Make the system feel very sluggish.
Miss button presses that happen during this delay.
Make it extremely difficult to type chords (multiple buttons at once) because the first button in the chord will trigger its action and the delay will prevent other buttons from being read in time.
Order of if Statements & Shadowing:
If you press B1 and B2 together (intending to type 'n'), the code will first see if (digitalRead(B1) == LOW), add 'e', delay(200), then it might see if (digitalRead(B2) == LOW), add 't', delay(200). It will likely never correctly register the 'n' chord.
Simpler chords (like single button presses) will "shadow" more complex chords that include them.
No True Debouncing for Chords: You've set up Bounce2 but aren't using its debounced output (.read(), .fell(), .rose()) for the actual character input logic. The delay(200) acts as a very crude (and problematic) debounce.
Typo: There's a delay(200);k near the 'b' chord.
Revised Approach: Non-Blocking Chord Detection on Release
The most robust way to handle this kind of chorded input is to:
Read the current debounced state of all buttons.
Form a "bitmask" representing which buttons are pressed.
When the buttons forming a chord are released, determine what that chord was and type the corresponding character.
Here's a refactored version of your code. Please fill in your actual pin numbers for B1_PIN to B6_PIN.
cpp
User
now for the actual pin connections. i have fixed 6 buttons to the arduino board and i have the esp32 board ready along with necessary jumper wires. how do i make the connections
Assistant
Okay, let's get those buttons and your OLED wired up to the ESP32!
You mentioned "fixed 6 buttons to the arduino board."
This is a key point. Are the buttons:
Just physically mounted on a piece of perfboard/protoboard that resembles an Arduino, or on an actual Arduino board but not yet wired to the Arduino's pins?
Or are they already wired to the pins of an Arduino Uno/Nano, etc.?
I'm going to assume Scenario 1: The buttons are physically mounted but you are free to wire their terminals directly to the ESP32. If they are already wired to an Arduino and you intend to use the Arduino as an intermediary, that's a much more complex setup (requiring communication between ESP32 and Arduino) and not what your current ESP32 code is designed for.
Let's proceed assuming you'll wire the buttons directly to the ESP32.
You will need:
Your ESP32 development board.
Your 6 push buttons.
Your OLED display (SSD1306 I2C version).
Jumper wires (male-to-male, male-to-female, female-to-female as needed, depending on your buttons and breadboard).
A breadboard (highly recommended for making these connections easily and without soldering).
Understanding Your Push Buttons:
Most common push buttons have 4 pins. These pins are typically connected in two pairs.
code
Pin A --- internal switch --- Pin B
| |
Pin C --- internal switch --- Pin D
Usually, A is connected to C, and B is connected to D internally. When you press the button, it connects the (A/C) side to the (B/D) side.
For wiring, you only need to use two pins that are NOT already connected. Typically, this means picking one pin from the (A/C) side and one pin from the (B/D) side. If you use a multimeter in continuity mode, you can easily test which pins are which. Often, pins on opposite sides diagonally are the ones you want.
Connection Plan:
Power OFF your ESP32 while making connections!
A. OLED Display (I2C):
Your code uses &Wire, which means I2C. Standard I2C pins for most ESP32 dev boards are:
* SDA: GPIO21
* SCL: GPIO22
OLED VCC/VDD pin -> ESP32 3V3 pin (3.3 Volts)
User
my buttons have 4 legs each
Assistant
You are absolutely right! Most common tactile push buttons (the small square or rectangular ones) do indeed have 4 legs (pins).
This doesn't change the fundamental way you wire them for a simple on/off input, but it's important to understand which two legs to use.
Here's how those 4-legged buttons typically work:
Internally, the 4 legs are connected in two pairs.
Imagine the button looking down from the top:
code
Leg A ----- Leg B
| |
(Internal (Internal
Connection) Connection)
| |
Leg C ----- Leg D
Leg A is (usually) internally connected to Leg C.
Leg B is (usually) internally connected to Leg D.
When you press the button, you create a connection between the (A/C) pair and the (B/D) pair.
What this means for wiring:
You need to pick ONE leg from the (A/C) side and ONE leg from the (B/D) side for your connections.
Correct Way:
Connect Leg A (or C) to your ESP32 GPIO pin.
Connect Leg B (or D) to GND.
(OR)
Connect Leg B (or D) to your ESP32 GPIO pin.
Connect Leg A (or C) to GND.
Incorrect Way (will result in a permanent connection or no connection):
Connecting Leg A to GPIO and Leg C to GND. (These are already connected internally, so your GPIO would always be connected to GND through the button's internal path if the button wasn't also trying to short them when pressed, or it just wouldn't work as a switch).
How to Identify the Pairs (if unsure):
Use a Multimeter (Best Method):
Set your multimeter to "Continuity" mode (it usually has a symbol like a sound wave or diode).
Touch the probes to two legs of the button without pressing the button.
If the multimeter beeps (or shows a very low resistance), those two legs are an internally connected pair.
You want to find two legs that do NOT beep when the button is not pressed, but DO beep when the button is pressed. These are the two legs you should use for your GPIO and GND connections.
// Example snippet for an OLED
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// In setup():
// if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
// Serial.println(F("SSD1306 allocation failed"));
// for(;;);
// }
// display.clearDisplay();
// display.setTextSize(1);
// display.setTextColor(SSD1306_WHITE);
// display.setCursor(0,0);
// display.println("Ready!");
// display.display();
// When typing:
// display.print(typedChar);
// display.display();
LCD Displays (e.g., 16x2 Character LCD):
These are also very common and can display characters clearly.
They often require more pins to connect than an I2C OLED, but I2C adapter backpacks are available for them.
The LiquidCrystal_I2C or LiquidCrystal library is typically used.
In summary:
With the current code: Your typed text will appear in the Serial Monitor of your computer.
For a standalone device: You'll need to add an OLED or LCD screen and modify the code to print to that screen instead of (or in addition to) the Serial Monitor.
Would you like to explore adding an OLED or LCD to your project? We can discuss which one might be better and how to wire it up and code for it!
debouncer.interval(MILLISECONDS);
debouncer.update();: This function must be called repeatedly in your loop(). It reads the button's current state and updates the internal debouncing logic (timers, state tracking).
debouncer.fell(): Returns true only once when a stable transition from HIGH to LOW (a press, for INPUT_PULLUP) has been detected after the debounce interval.
debouncer.rose(): Returns true only once when a stable transition from LOW to HIGH (a release, for INPUT_PULLUP) has been detected.
Without debouncing, your 6-button typing system would be incredibly frustrating and unreliable, as single intended presses would likely result in multiple characters being typed. The debouncer ensures that each intentional press results in only one character input (or one action).
#include <Bounce2.h> // For debouncing
// GPIO pins for buttons
#define B1_PIN 12 // Changed to B1_PIN to avoid conflict with variable names if any
#define B2_PIN 14
#define B3_PIN 27
#define B4_PIN 26
#define B5_PIN 25
#define B6_PIN 33 // Finish Typing button
// Debouncing objects
Bounce debouncerB1 = Bounce();
Bounce debouncerB2 = Bounce();
Bounce debouncerB3 = Bounce();
Bounce debouncerB4 = Bounce();
Bounce debouncerB5 = Bounce();
Bounce debouncerB6 = Bounce();
// Typed word buffer
String typedWord = "";
unsigned long lastCombinationTime = 0; // To help debounce combinations
const unsigned long COMBINATION_DEBOUNCE_DELAY = 250; // milliseconds
void setup() {
Serial.begin(115200);
// Set up buttons with pull-up resistors
pinMode(B1_PIN, INPUT_PULLUP);
pinMode(B2_PIN, INPUT_PULLUP);
pinMode(B3_PIN, INPUT_PULLUP);
pinMode(B4_PIN, INPUT_PULLUP);
pinMode(B5_PIN, INPUT_PULLUP);
pinMode(B6_PIN, INPUT_PULLUP);
// Initialize debouncers
debouncerB1.attach(B1_PIN);
debouncerB2.attach(B2_PIN);
debouncerB3.attach(B3_PIN);
debouncerB4.attach(B4_PIN);
debouncerB5.attach(B5_PIN);
debouncerB6.attach(B6_PIN);
// Debounce interval for single presses
int singlePressDebounce = 25;
debouncerB1.interval(singlePressDebounce);
debouncerB2.interval(singlePressDebounce);
debouncerB3.interval(singlePressDebounce);
debouncerB4.interval(singlePressDebounce);
debouncerB5.interval(singlePressDebounce);
debouncerB6.interval(singlePressDebounce);
Serial.println("Keyboard Ready. Press B6 to finish typing. B1-B5 for Backspace.");
}
void loop() {
// Update debouncers
debouncerB1.update();
debouncerB2.update();
debouncerB3.update();
debouncerB4.update();
debouncerB5.update();
debouncerB6.update();
// --- Check for "Finish Typing" (B6) ---
if (debouncerB6.fell()) {
Serial.print("Typed: ");
Serial.println(typedWord);
typedWord = ""; // Reset buffer
Serial.println("Buffer cleared. Ready for new input.");
return; // Exit loop iteration early
}
// --- Check for Backspace Combination (B1+B2+B3+B4+B5) ---
// This needs to be checked *before* individual button presses
// to give priority to the combination.
bool b1_is_pressed = (digitalRead(B1_PIN) == LOW);
bool b2_is_pressed = (digitalRead(B2_PIN) == LOW);
bool b3_is_pressed = (digitalRead(B3_PIN) == LOW);
bool b4_is_pressed = (digitalRead(B4_PIN) == LOW);
bool b5_is_pressed = (digitalRead(B5_PIN) == LOW);
if (b1_is_pressed && b2_is_pressed && b3_is_pressed && b4_is_pressed && b5_is_pressed) {
if (millis() - lastCombinationTime > COMBINATION_DEBOUNCE_DELAY) { // Debounce the combination
if (typedWord.length() > 0) {
typedWord.remove(typedWord.length() - 1); // Remove the last character
Serial.print("Backspace! Current: ");
Serial.println(typedWord);
} else {
Serial.println("Buffer empty, nothing to backspace.");
}
lastCombinationTime = millis();
}
// Since this is a combination, we don't want single button presses to also register
// We can add a small delay or a flag to prevent single presses right after a combo
// For simplicity, the `lastCombinationTime` check helps, but for truly robust
// chord detection, a more advanced state machine or bitmask approach is better.
// For now, let's assume if all 5 are pressed, it's backspace.
return; // Processed a combination, skip single key checks for this loop iteration
}
// --- Check for Single-Button Presses (A, E, I, O, U) ---
// Only process if enough time has passed since the last combination
// to avoid single letters firing immediately after releasing a combo key.
if (millis() - lastCombinationTime > COMBINATION_DEBOUNCE_DELAY) {
if (debouncerB1.fell()) {
typedWord += 'A';
Serial.print("Current: "); Serial.println(typedWord);
}
if (debouncerB2.fell()) {
typedWord += 'E';
Serial.print("Current: "); Serial.println(typedWord);
}
if (debouncerB3.fell()) {
typedWord += 'I';
Serial.print("Current: "); Serial.println(typedWord);
}
if (debouncerB4.fell()) {
typedWord += 'O';
Serial.print("Current: "); Serial.println(typedWord);
}
if (debouncerB5.fell()) {
typedWord += 'U';
Serial.print("Current: "); Serial.println(typedWord);
}
}
// --- Check for other combinations (e.g., 'B' = B1 + B2) ---
// This is a simplified example; robust chord detection is more complex.
// It's best to handle these after individual key presses, or use a more
// sophisticated input reading method (like reading all keys at once and making a bitmask).
// Example for 'B' (B1_PIN + B2_PIN).
// This simplistic check can be problematic if B1 or B2 alone also have actions.
// A true chorded system would read the state of all buttons *on release* or use a timer.
// For now, let's make it so it also needs a bit of debounce.
if (b1_is_pressed && b2_is_pressed && !(b3_is_pressed || b4_is_pressed || b5_is_pressed)) { // Only B1 and B2
if (millis() - lastCombinationTime > COMBINATION_DEBOUNCE_DELAY) {
typedWord += 'B';
Serial.print("Current: "); Serial.println(typedWord);
lastCombinationTime = millis();
return; // Processed a combination
}
}
// Add more combination checks here, ensuring they are distinct and handled carefully...
// For example, B1+B3 for 'C', etc.
// ...
}
Key Changes and Explanations:
Pin Naming: Changed B1 to B1_PIN etc., to make it clear these are pin numbers and avoid potential conflicts if you later create variables named B1.
Backspace Combination Logic:
bool b1_is_pressed = (digitalRead(B1_PIN) == LOW); (and so on for B2-B5). We read the current state of all 5 buttons.
if (b1_is_pressed && b2_is_pressed && b3_is_pressed && b4_is_pressed && b5_is_pressed): This checks if all five buttons are currently held down.
Order of Checks: This multi-button check is placed before the single debouncer.fell() checks. This is important because if you press all 5 buttons, you want it to register as "Backspace" and not as "A" (if B1 was the last one to make contact and debouncerB1.fell() triggers).
Combination Debouncing (lastCombinationTime and COMBINATION_DEBOUNCE_DELAY):
When you press multiple buttons for a chord (like backspace), you might not press them exactly at the same microsecond. Also, if you hold them, you don't want "Backspace" to fire repeatedly.
lastCombinationTime stores the millis() value when a combination was last processed.
if (millis() - lastCombinationTime > COMBINATION_DEBOUNCE_DELAY): This ensures that the backspace action (or any other combination) only happens if a certain amount of time has passed since the last combination. This helps prevent multiple registrations from a single chord press-and-hold.
The return; statement after processing a combination helps to ensure that single key presses (like 'A' if B1 was part of the combo) don't also fire in the same loop iteration.
String Manipulation for Backspace:
if (typedWord.length() > 0): Checks if there's anything to delete.
typedWord.remove(typedWord.length() - 1);: This is the Arduino String object function that removes characters. typedWord.length() - 1 gives the index of the last character.
Output: The code prints to the Serial Monitor when backspace occurs.
Simplified 'B' Combination: I added a very basic example for 'B' using B1_PIN and B2_PIN. Note the added check !(b3_is_pressed || b4_is_pressed || b5_is_pressed) to make it more specific to only B1 and B2. True chorded input is more complex and often involves reading all button states simultaneously to form a "bitmask" representing the chord, and then processing that bitmask on the release of the chord.
Important Considerations for Combinations:
Robust Chord Detection: The method used here for combinations (checking multiple digitalRead()s and using a simple time-based debounce) is a basic approach. For a truly fast and reliable chorded keyboard, you'd typically:
Read the state of all buttons at once.
Form a "bitmask" (e.g., a byte where each bit represents a button).
Detect when the chord is "stable" (buttons held for a brief moment) or when the chord is "released."
The lastCombinationTime helps a lot but isn't as robust as a full state machine for chording.
Accidental Single Presses: With the current logic, if you press B1, then B2, then B3, etc., quickly to form the backspace chord, individual letters might still get typed before the full chord is recognized. The return; after a combo and the millis() - lastCombinationTime check for single presses help, but it's not foolproof. The bitmask approach mentioned in one of my previous answers is the most robust way to handle this.
This should give you a functional backspace. Test it out and see how it feels! You might need to adjust COMBINATION_DEBOUNCE_DELAY.
#include <Bounce2.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <Wire.h> // Make sure Wire is included for I2C
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// === DEFINE YOUR BUTTON PINS HERE ===
#define B1_PIN 12 // Example: GPIO12 for Button 1 ('e')
#define B2_PIN 14 // Example: GPIO14 for Button 2 ('t')
#define B3_PIN 27 // Example: GPIO27 for Button 3 ('a')
#define B4_PIN 26 // Example: GPIO26 for Button 4 ('o')
#define B5_PIN 25 // Example: GPIO25 for Button 5 ('i')
#define B6_PIN 33 // Example: GPIO33 for Button 6 (' ')
Bounce debouncerB1 = Bounce();
Bounce debouncerB2 = Bounce();
Bounce debouncerB3 = Bounce();
Bounce debouncerB4 = Bounce();
Bounce debouncerB5 = Bounce();
Bounce debouncerB6 = Bounce();
String typedWord = "";
byte currentChordBitmask = 0; // Bitmask of currently pressed buttons (debounced)
byte prevChordBitmask = 0; // Previous bitmask to detect chord release
// Helper function to update the OLED display
void updateOLED() {
display.clearDisplay();
display.setCursor(0, 0);
display.print(">"); // Prompt character
display.println(typedWord);
display.display();
}
// Helper function to map a chord bitmask to a character or action
// Order is important: check for more complex chords (more buttons) first.
char getCharForChord(byte chord) {
// Special Actions (return non-printable char codes or handle directly)
// Backspace: B1+B2+B3+B4+B5 (bits 0,1,2,3,4 set = 0b00011111)
if (chord == 0b00011111) return 1; // Special code for backspace
// "Display and Clear Word": B2+B3+B4+B5 (bits 1,2,3,4 set = 0b00011110)
if (chord == 0b00011110) return 2; // Special code for "send/display and clear"
// Regular Characters
// Space: B6 (bit 5 set = 0b00100000)
if (chord == 0b00100000) return ' ';
// 4-button chords
if (chord == 0b00001111) return '.'; // B1+B2+B3+B4
if (chord == 0b00010111) return ','; // B1+B2+B3+B5
if (chord == 0b00011011) return '?'; // B1+B2+B4+B5
// 3-button chords
if (chord == 0b00000111) return 'p'; // B1+B2+B3
if (chord == 0b00001011) return 'g'; // B1+B2+B4
if (chord == 0b00010011) return 'w'; // B1+B2+B5
if (chord == 0b00001101) return 'y'; // B1+B3+B4
if (chord == 0b00010101) return 'b'; // B1+B3+B5 (Corrected typo: removed 'k' from end of line)
if (chord == 0b00011001) return 'k'; // B1+B4+B5
if (chord == 0b00001110) return 'x'; // B2+B3+B4 (Distinct from the 0b00011110 command)
if (chord == 0b00010110) return 'j'; // B2+B3+B5
if (chord == 0b00011010) return 'q'; // B2+B4+B5
if (chord == 0b00011100) return 'z'; // B3+B4+B5
// 2-button chords
if (chord == 0b00000011) return 'n'; // B1+B2
if (chord == 0b00000101) return 's'; // B1+B3
if (chord == 0b00001001) return 'r'; // B1+B4
if (chord == 0b00010001) return 'h'; // B1+B5
if (chord == 0b00000110) return 'l'; // B2+B3
if (chord == 0b00001010) return 'd'; // B2+B4
if (chord == 0b00010010) return 'c'; // B2+B5
if (chord == 0b00001100) return 'u'; // B3+B4
if (chord == 0b00010100) return 'm'; // B3+B5
if (chord == 0b00011000) return 'f'; // B4+B5
// 1-button chords
if (chord == 0b00000001) return 'e'; // B1
if (chord == 0b00000010) return 't'; // B2
if (chord == 0b00000100) return 'a'; // B3
if (chord == 0b00001000) return 'o'; // B4
if (chord == 0b00010000) return 'i'; // B5 (Corrected from 0b000010000 which is too large for a byte)
return '\0'; // No character/action defined for this chord
}
void setup() {
Serial.begin(115200);
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
display.display(); // Show initial Adafruit logo (if any)
delay(1000); // Pause for a moment
display.clearDisplay();
display.setTextSize(1); // Small text
display.setTextColor(SSD1306_WHITE);
updateOLED(); // Show the initial empty prompt
pinMode(B1_PIN, INPUT_PULLUP);
pinMode(B2_PIN, INPUT_PULLUP);
pinMode(B3_PIN, INPUT_PULLUP);
pinMode(B4_PIN, INPUT_PULLUP);
pinMode(B5_PIN, INPUT_PULLUP);
pinMode(B6_PIN, INPUT_PULLUP);
debouncerB1.attach(B1_PIN);
debouncerB2.attach(B2_PIN);
debouncerB3.attach(B3_PIN);
debouncerB4.attach(B4_PIN);
debouncerB5.attach(B5_PIN);
debouncerB6.attach(B6_PIN);
int debounceInterval = 25; // ms
debouncerB1.interval(debounceInterval);
debouncerB2.interval(debounceInterval);
debouncerB3.interval(debounceInterval);
debouncerB4.interval(debounceInterval);
debouncerB5.interval(debounceInterval);
debouncerB6.interval(debounceInterval);
Serial.println("Chord Keyboard Ready.");
}
void loop() {
// 1. Update all debouncers
debouncerB1.update();
debouncerB2.update();
debouncerB3.update();
debouncerB4.update();
debouncerB5.update();
debouncerB6.update();
// 2. Read current debounced state of all buttons into a bitmask
// Bit 0 for B1, Bit 1 for B2, ..., Bit 5 for B6
currentChordBitmask = 0; // Reset for this loop iteration
if (debouncerB1.read() == LOW) currentChordBitmask |= (1 << 0);
if (debouncerB2.read() == LOW) currentChordBitmask |= (1 << 1);
if (debouncerB3.read() == LOW) currentChordBitmask |= (1 << 2);
if (debouncerB4.read() == LOW) currentChordBitmask |= (1 << 3);
if (debouncerB5.read() == LOW) currentChordBitmask |= (1 << 4);
if (debouncerB6.read() == LOW) currentChordBitmask |= (1 << 5);
// 3. Process chords on release
// This happens when the current state is no buttons pressed (0),
// AND the previous state had some buttons pressed (prevChordBitmask != 0).
if (currentChordBitmask == 0 && prevChordBitmask != 0) {
char charToProcess = getCharForChord(prevChordBitmask); // Get char for the *released* chord
if (charToProcess != '\0') { // If a valid character or action was found
if (charToProcess == 1) { // Special Action: Backspace
if (typedWord.length() > 0) {
typedWord.remove(typedWord.length() - 1);
}
} else if (charToProcess == 2) { // Special Action: "Display and Clear Word"
Serial.print("Sent: "); Serial.println(typedWord); // Also send to serial for debugging
// Displaying is handled by updateOLED, but let's make it clear this "sends"
display.clearDisplay();
display.setCursor(0,0);
display.println("Sent:");
display.println(typedWord);
display.display();
typedWord = ""; // Clear the word
delay(1500); // Show "Sent" message for a bit
} else { // Regular character
typedWord += charToProcess;
}
updateOLED(); // Update display with new typedWord or after action
}
}
// 4. Update previous state for the next loop iteration
prevChordBitmask = currentChordBitmask;
// No delays in the main loop to keep it responsive
}
Key Changes and Explanation:
Pin Definitions: Added placeholders (B1_PIN etc.) for you to fill in.
updateOLED() Function: Encapsulates the logic to clear and redraw the text on the OLED. This keeps the main loop cleaner.
getCharForChord(byte chord) Function:
This is the heart of your input mapping. It takes a byte (the bitmask) and returns the character.
Bitmask: B1 is bit 0, B2 is bit 1, ..., B6 is bit 5.
Order Matters: Checks for chords with more buttons before chords with fewer buttons to avoid misinterpretation (e.g., B1+B2+B3 is checked before B1+B2).
Special Actions: I've used return 1; for backspace and return 2; for your "display and clear" action. These non-printable values are then handled in the loop.
Corrected the typo delay(200);k -> return 'b';
Corrected bitmask for 'i' (B5): 0b00010000.
Non-Blocking loop():
No delay() calls in the main part of the loop.
currentChordBitmask is built each cycle using debouncerBx.read().
Chord Commit on Release: The logic if (currentChordBitmask == 0 && prevChordBitmask != 0) detects when all keys that formed a chord have been released. At this point, prevChordBitmask holds the combination that was just active.
The character/action corresponding to prevChordBitmask is then processed.
OLED Update Timing:updateOLED() is called only when typedWord changes or after a special action, making the display more stable.
Serial Output: Kept Serial.println for debugging and for the "Sent" action.
How to Use:
Define your B1_PIN to B6_PIN constants at the top with the actual GPIO numbers you've wired your buttons to.
Upload the code.
To type a character/chord:
Press and hold the button(s) for that chord.
Release all buttons of the chord. The character will appear.
This "commit on release" method is generally very reliable for chorded input. It might take a little getting used to compared to typing on a standard keyboard where characters appear on press-down.
Test this thoroughly. The responsiveness should be much better, and chord detection should be accurate.
OLED GND pin -> ESP32 GND pin (Ground)
OLED SDA pin -> ESP32 GPIO21 pin
OLED SCL pin -> ESP32 GPIO22 pin
B. Push Buttons (B1 to B6):
Your code uses INPUT_PULLUP. This means:
* One side of each button will connect to an ESP32 GPIO pin.
* The other side of each button will connect to GND.
Here are the connections based on your #define statements (I'm using the example pin numbers I suggested earlier, make sure to use the actual pin numbers you put in your code!):
Button 1 (B1_PIN):
One terminal of Button 1 -> ESP32 GPIO specified for B1_PIN (e.g., GPIO12)
Other terminal of Button 1 -> ESP32 GND pin
Button 2 (B2_PIN):
One terminal of Button 2 -> ESP32 GPIO specified for B2_PIN (e.g., GPIO14)
Other terminal of Button 2 -> ESP32 GND pin
Button 3 (B3_PIN):
One terminal of Button 3 -> ESP32 GPIO specified for B3_PIN (e.g., GPIO27)
Other terminal of Button 3 -> ESP32 GND pin
Button 4 (B4_PIN):
One terminal of Button 4 -> ESP32 GPIO specified for B4_PIN (e.g., GPIO26)
Other terminal of Button 4 -> ESP32 GND pin
Button 5 (B5_PIN):
One terminal of Button 5 -> ESP32 GPIO specified for B5_PIN (e.g., GPIO25)
Other terminal of Button 5 -> ESP32 GND pin
Button 6 (B6_PIN):
One terminal of Button 6 -> ESP32 GPIO specified for B6_PIN (e.g., GPIO33)
Other terminal of Button 6 -> ESP32 GND pin
Tips for GND connections:
Your ESP32 board will have multiple GND pins. You can use any of them.
If using a breadboard, it's convenient to connect one ESP32 GND pin to the breadboard's ground rail (usually marked with a blue line). Then, you can connect all the "other terminals" of your buttons to this ground rail.
Step-by-Step on a Breadboard (Recommended):
Mount ESP32: Place your ESP32 board onto the breadboard, usually straddling the central channel.
Mount OLED: Place the OLED on the breadboard (or connect via jumper wires if it has header pins).
Mount Buttons: Place your 6 push buttons on the breadboard, ensuring each button straddles the central channel of the breadboard so its pins are in different rows.
Connect OLED Power & GND:
Jumper wire from ESP32 3V3 to OLED VCC.
Jumper wire from ESP32 GND to OLED GND.
Connect OLED I2C:
Jumper wire from ESP32 GPIO21 (SDA) to OLED SDA.
Jumper wire from ESP32 GPIO22 (SCL) to OLED SCL.
Connect Button GNDs:
If you haven't already, run a jumper wire from an ESP32 GND pin to one of the long ground rails on your breadboard.
For each of the 6 buttons, connect one of its terminals (the one intended for ground) to this ground rail using a short jumper wire.
Connect Button Signal Pins:
For Button 1, connect its other terminal to the ESP32 GPIO pin you've defined as B1_PIN in your code.
Repeat for Button 2 to B2_PIN, Button 3 to B3_PIN, and so on, up to Button 6 to B6_PIN.
Double-Check Your Connections!
Refer to your ESP32 development board's pinout diagram to correctly identify 3V3, GND, and the GPIO pins. Pin numbers printed on the board can sometimes be small or confusing.
Ensure no wires are accidentally shorting (e.g., bare wires touching).
Make sure you're using the correct terminals on the push buttons.
Once everything is wired, you can connect your ESP32 to your computer via USB, upload the code (if you haven't already or made changes), and open the Serial Monitor. Then test your buttons! You should also see output on the OLED display.
Good luck, and let me know if any part is unclear!
Breadboard Orientation:
These buttons are usually designed to straddle the central channel of a breadboard.
When placed this way, the two legs on one side of the channel are one pair, and the two legs on the other side of the channel are the other pair.
So, you would connect one wire to a leg on the "left" side of the channel and the other wire to a leg on the "right" side of the channel (relative to how the button is straddling it).
code
Breadboard Central Channel
| | | |
Leg A--o-|-o--Leg B <-- Use one from this row
| | | |
Leg C--o-|-o--Leg D <-- And one from this row
| | | | (o = pin in breadboard hole)
(- = button leg)
In this breadboard example, you'd use (A or C) and (B or D). More simply, pick one pin on one side of the button that's in the breadboard, and another pin on the opposite side of the button.
So, for each of your 6 buttons, the wiring instruction remains conceptually the same:
One chosen active leg of the button -> ESP32 GPIO pin specified in your code
The other chosen active leg of the button -> ESP32 GND pin
Just make sure the "one chosen leg" and the "other chosen leg" are from opposite internal pairs!