pdf-icon

Arduino Quick Start

2. Devices & Examples

6. Applications

NanoH2 Button Button

NanoH2 Button sample program.

Example Program

Compilation Requirements

  • M5Stack Board Manager version >= 3.2.5
  • Development board option = M5NanoH2
cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#define pin_BtnA 9
#define DEBOUNCE_MS 20    // Debounce time
#define HOLD_MS 500       // Holding threshold

bool last_state = HIGH;
unsigned long last_time = 0;
bool is_holding = false;

void setup() {
  pinMode(pin_BtnA, INPUT_PULLUP);
  Serial.begin(115200);
}

void loop() {
  bool current_state = digitalRead(pin_BtnA);
  unsigned long now = millis();

  // Debouncing
  if (current_state != last_state && now - last_time > DEBOUNCE_MS) {
    last_state = current_state;
    last_time = now;

    if (current_state == LOW) {  // Button pressed
      Serial.println("Button A pressed");
    } else {  // Button released
      Serial.println("Button A released");
      if (!is_holding) {
        Serial.println("Button A single clicked");
      }
      is_holding = false;
    }
  }

  // Long press detection
  if (current_state == LOW && now - last_time > HOLD_MS && !is_holding) {
    is_holding = true;
    Serial.println("Button A held");
  }

  delay(5);
}

This program detects the state of the front input button on the NanoH2 and prints button events to the Serial Monitor:

On This Page