diff --git a/docs/api.md b/docs/api.md index 7c463c0..f1fe935 100644 --- a/docs/api.md +++ b/docs/api.md @@ -33,6 +33,12 @@ Represents a Modulino Buttons module. - **`PinStatus isPressed(int index)`** Returns the press status (HIGH/LOW) of the button at the specified index (_0-A, 1-B, 2-C_). +- **`PinStatus isPressed(char button)`** + Returns the press status (HIGH/LOW) of the button specified by its character ('A', 'B', 'C'). + +- **`PinStatus isPressed(const char *button)`** + Returns the press status (HIGH/LOW) of the button specified by its string ("A", "B", "C"). + - **`bool update()`** Updates the button status. Returns `true` if the status has changed, `false` otherwise. diff --git a/examples/Modulino_Buttons/Buttons_Basic/Buttons_Basic.ino b/examples/Modulino_Buttons/Buttons_Basic/Buttons_Basic.ino index f29f96b..9d5e4da 100644 --- a/examples/Modulino_Buttons/Buttons_Basic/Buttons_Basic.ino +++ b/examples/Modulino_Buttons/Buttons_Basic/Buttons_Basic.ino @@ -24,22 +24,24 @@ void setup() { // Turn on the LEDs above buttons A, B, and C buttons.setLeds(true, true, true); } + void loop() { // Check for new button events, returns true when button state changes if (buttons.update()) { - // Check which button was pressed (0=A, 1=B, 2=C) - // Also toggle the corresponding LED, for each of the three buttons - if (buttons.isPressed(0)) { + // You can use either index (0=A, 1=B, 2=C) or letter ('A', 'B', 'C') to check buttons + // Below we use the letter-based method for better readability + + if (buttons.isPressed('A')) { Serial.println("Button A pressed!"); button_a = !button_a; - } else if (buttons.isPressed(1)) { + } else if (buttons.isPressed("B")) { Serial.println("Button B pressed!"); button_b = !button_b; - } else if (buttons.isPressed(2)) { + } else if (buttons.isPressed('C')) { Serial.println("Button C pressed!"); button_c = !button_c; } - + // Update the LEDs above buttons, depending on the variables value buttons.setLeds(button_a, button_b, button_c); } diff --git a/src/Modulino.h b/src/Modulino.h index 6f62aaf..f768d24 100644 --- a/src/Modulino.h +++ b/src/Modulino.h @@ -127,6 +127,17 @@ class ModulinoButtons : public Module { PinStatus isPressed(int index) { return last_status[index] ? HIGH : LOW; } + PinStatus isPressed(char button) { + int index = buttonToIndex(button); + if (index < 0) return LOW; + return isPressed(index); + } + PinStatus isPressed(const char *button) { + if (button == nullptr || button[0] == '\0' || button[1] != '\0') { + return LOW; + } + return isPressed(button[0]); + } bool update() { uint8_t buf[3]; auto res = read((uint8_t*)buf, 3); @@ -154,6 +165,14 @@ class ModulinoButtons : public Module { } private: bool last_status[3]; + int buttonToIndex(char button) { + switch (toupper(button)) { + case 'A': return 0; + case 'B': return 1; + case 'C': return 2; + default: return -1; + } + } protected: uint8_t match[1] = { 0x7C }; // same as fw main.c };