#include <Arduino.h>
const int BUTTON_PIN = 16; // 对应 esp:16
const int LED_PIN = 4; // 对应 esp:4
const int POT_PIN = 6; // 对应 esp:6(ESP32-S3 ADC1 引脚)
// PWM 配置(Arduino-ESP32 3.x)
const int PWM_FREQ = 5000;
const int PWM_RESOLUTION = 8; // 8位分辨率 (0-255)
int systemMode = 0; // 0: PWM自动呼吸灯, 1: 电位器手调亮度
bool modeChanged = true; // 启动时打印一次初始模式
// 按键消抖状态变量(低电平有效:LOW=接通,HIGH=断开)
const unsigned long DEBOUNCE_MS = 30;
int stableButtonState = HIGH; // 消抖后的稳定电平(初始为高电平断开)
int lastRawReading = HIGH; // 上一次读取的原始电平
unsigned long lastDebounceTime = 0; // 最近一次电平跳变时间
// 呼吸灯非阻塞步进变量
int breathDuty = 0;
int breathDir = 5;
unsigned long lastBreathTime = 0;
const unsigned long BREATH_STEP_MS = 20;
// 按键消抖扫描:检测到“断开(HIGH) -> 接通(LOW)”的有效按下时返回 true
bool readButtonPressed() {
int reading = digitalRead(BUTTON_PIN);
// 原始电平发生变化,重置消抖计时
if (reading != lastRawReading) {
lastDebounceTime = millis();
lastRawReading = reading;
}
// 电平持续稳定超过 DEBOUNCE_MS,才更新稳定状态
if ((millis() - lastDebounceTime) >= DEBOUNCE_MS) {
if (reading != stableButtonState) {
int prevState = stableButtonState;
stableButtonState = reading;
Serial.print("[消抖后电平变化] 当前电平: ");
Serial.println(stableButtonState == LOW ? "LOW(接通)" : "HIGH(断开)");
// 高电平(断开) -> 低电平(接通),判定为一次有效按下
if (prevState == HIGH && stableButtonState == LOW) {
return true;
}
}
}
return false;
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP); // 默认上拉为高电平(断开),按下接地为低电平(接通)
pinMode(POT_PIN, INPUT);
// Arduino-ESP32 3.x:直接绑定引脚、频率与分辨率
ledcAttach(LED_PIN, PWM_FREQ, PWM_RESOLUTION);
ledcWrite(LED_PIN, 0);
Serial.println(">>> 实验一启动:GPIO、PWM与按键消抖控制 <<<");
Serial.println("逻辑说明:LOW=按键接通(按下),HIGH=按键断开(松开)");
}
void loop() {
// 1. 每次 loop 优先检测按键消抖与模式切换
if (readButtonPressed()) {
systemMode = (systemMode + 1) % 2;
modeChanged = true;
// 切回呼吸灯模式时重置渐变起点
if (systemMode == 0) {
breathDuty = 0;
breathDir = 5;
lastBreathTime = millis();
}
}
if (modeChanged) {
modeChanged = false;
Serial.print("按键触发切换 -> 当前模式: ");
Serial.println(systemMode == 0 ? "0 (自动呼吸灯)" : "1 (电位器调光)");
}
// 2. 根据当前模式执行控制
if (systemMode == 0) {
// 模式0:非阻塞呼吸灯,不卡住按键检测
unsigned long now = millis();
if (now - lastBreathTime >= BREATH_STEP_MS) {
lastBreathTime = now;
ledcWrite(LED_PIN, breathDuty);
breathDuty += breathDir;
if (breathDuty >= 255) {
breathDuty = 255;
breathDir = -5;
} else if (breathDuty <= 0) {
breathDuty = 0;
breathDir = 5;
}
}
} else {
// 模式1:读取电位器 ADC 并映射到 LED_PIN 的 PWM 占空比
int adcVal = analogRead(POT_PIN);
int duty = map(adcVal, 0, 4095, 0, 255);
ledcWrite(LED_PIN, duty); // 注意这里用 LED_PIN,不用 PWM_CHANNEL
static unsigned long lastLog = 0;
unsigned long now = millis();
if (now - lastLog >= 500) {
Serial.printf("[电位器模式] 按键电平:%s | ADC:%d | PWM占空比:%d\n",
stableButtonState == LOW ? "LOW(接通)" : "HIGH(断开)",
adcVal, duty);
lastLog = now;
}
}
}Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1