Files
btntest/src/button.cpp
DESKTOP-PUHFO60\dsx2016 280c5ea97c Fix tactile switch wiring: GPIO22 to GND, show live pin level.
Clarify 4-pin foot pairing and debounce for bare pushbutton.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:46:31 +08:00

68 lines
1.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "button.h"
#include "pins.h"
#include <Arduino.h>
// 轻触开关:一端 → GPIO22,另一端 → GND(内部上拉,按下=LOW)
static uint32_t g_count = 0;
static bool g_stable_down = false;
static int g_stable_raw = HIGH;
static uint32_t g_change_ms = 0;
static int g_pending_raw = HIGH;
static bool g_pending = false;
static constexpr uint32_t DEBOUNCE_MS = 25;
void button_init() {
pinMode(BTN_PIN, INPUT_PULLUP);
delay(5);
g_count = 0;
g_stable_raw = digitalRead(BTN_PIN);
g_stable_down = (g_stable_raw == LOW);
g_pending = false;
g_pending_raw = g_stable_raw;
g_change_ms = millis();
Serial.printf("Button tactile GPIO%d pullup, idle=%s (wire other side to GND)\n",
BTN_PIN, g_stable_raw == HIGH ? "HIGH" : "LOW");
}
bool button_poll_press() {
const int raw = digitalRead(BTN_PIN);
const uint32_t now = millis();
if (raw != g_stable_raw) {
if (!g_pending || raw != g_pending_raw) {
g_pending = true;
g_pending_raw = raw;
g_change_ms = now;
} else if ((now - g_change_ms) >= DEBOUNCE_MS) {
g_stable_raw = g_pending_raw;
g_pending = false;
const bool down = (g_stable_raw == LOW);
if (down && !g_stable_down) {
g_stable_down = true;
g_count++;
Serial.printf("Button press count=%lu raw=%d\n", (unsigned long)g_count,
g_stable_raw);
return true;
}
g_stable_down = down;
}
} else {
g_pending = false;
}
return false;
}
uint32_t button_count() { return g_count; }
void button_reset_count() {
g_count = 0;
Serial.println("Button count reset");
}
bool button_is_down() { return g_stable_down; }
int button_raw_level() { return digitalRead(BTN_PIN); }