Suggested Forum Message:
Hello everyone,
I have the following code that currently works in my setup. When I press a button on the matrix keypad, it toggles a corresponding LED connected via a shift register. However, what I really want is for the LED to turn on only while I’m pressing the button and then turn off as soon as I release it, rather than toggling.
Right now, pressing a button changes the LED state (on/off), and it stays that way until I press the same button again. How can I modify the code so that the LED is lit only when the button is held down and turns off immediately when I let go of it?
Thanks in advance for any help or suggestions! #include <Keypad.h>
// Shift Register Pin Definitions
const int dataPin = 4; // DS pin (Data input)
const int latchPin = 5; // ST_CP pin (Latch pin)
const int clockPin = 6; // SH_CP pin (Clock pin)
// Matrix Keypad Settings
const byte ROWS = 4; // Number of rows
const byte COLS = 4; // Number of columns
// Row and column pins
byte rowPins[ROWS] = {A0, A1, A2, A3}; // Row pins
byte colPins[COLS] = {7, 8, 9, 10}; // Column pins
// Matrix keypad layout
char keys[ROWS][COLS] = {
{'1', '2', '3', '4'},
{'5', '6', '7', '8'},
{'9', 'A', 'B', 'C'},
{'D', 'E', 'F', 'G'}
};
// Create the Keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// 16-bit LED state for Shift Register control
uint16_t ledState = 0b0000000000000000; // 16-bit LED state
// Function prototypes
void updateShiftRegister();
void setup() {
// Set up shift register pins
pinMode(dataPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
// Start Serial Monitor
Serial.begin(9600);
updateShiftRegister(); // Update the LEDs to the initial state
}
void loop() {
char key = keypad.getKey(); // Read the pressed key
if (key) { // If a key was pressed
Serial.print("Pressed Key: ");
Serial.println(key);
// Control the LEDs based on the pressed key
int ledIndex = -1;
if (key >= '1' && key <= '8') { // Is the key between 1-8?
ledIndex = key - '1'; // Calculate LED index (0-7)
} else if (key >= '9' && key <= 'G') { // Is the key between 9 and G?
ledIndex = key - '9' + 8; // Calculate LED index (8-15)
}
if (ledIndex >= 0 && ledIndex < 16) {
// Toggle the corresponding LED
ledState ^= (1 << ledIndex);
updateShiftRegister(); // Update the shift register
}
}
}
// Function to send data to the Shift Register
void updateShiftRegister() {
digitalWrite(latchPin, LOW); // Set latch pin LOW
shiftOut(dataPin, clockPin, MSBFIRST, highByte(ledState)); // Send high byte (first 8 bits)
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(ledState)); // Send low byte (last 8 bits)
digitalWrite(latchPin, HIGH); // Set latch pin HIGH
}