#include <Arduino.h>
#define BUTTON_PIN_1 18 // 第一个按钮(原始功能)
#define BUTTON_PIN_2 16 // 第二个按钮(新增计数器功能)
#define LED_PIN 21 // LED输出引脚
#define DEBOUNCE_DELAY 50 // 防抖延时(毫秒)
// 按钮状态变量
int lastState1 = HIGH; // 按钮1前次状态
int currentState1; // 按钮1当前状态
unsigned long lastDebounceTime1 = 0; // 按钮1防抖计时
int lastState2 = HIGH; // 按钮2前次状态
int currentState2; // 按钮2当前状态
unsigned long lastDebounceTime2 = 0; // 按钮2防抖计时
bool button2Pressed = false; // 按钮2按下状态
// 二进制计数器
byte binaryCounter = 0; // 8位计数器(0-255)
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN_1, INPUT_PULLUP); // 设置按钮1为上拉输入
pinMode(BUTTON_PIN_2, INPUT_PULLUP); // 设置按钮2为上拉输入
pinMode(LED_PIN, OUTPUT); // 设置LED为输出
Serial.println("二进制计数器初始值: 0");
updateLED(); // 初始化LED状态
}
// 更新LED显示函数(根据计数器值)
void updateLED() {
digitalWrite(LED_PIN, binaryCounter & 0x01); // 只显示最低位
Serial.print("当前计数值: ");
Serial.println(binaryCounter, BIN); // 二进制格式输出
}
void loop() {
// 处理按钮1(原始功能)
currentState1 = digitalRead(BUTTON_PIN_1);
if (currentState1 != lastState1) {
lastDebounceTime1 = millis(); // 状态变化时重置防抖计时
}
if ((millis() - lastDebounceTime1) > DEBOUNCE_DELAY) {
if (currentState1 == LOW) {
digitalWrite(LED_PIN, HIGH); // 按下时点亮LED
} else {
digitalWrite(LED_PIN, LOW); // 释放时熄灭LED
}
}
lastState1 = currentState1;
// 处理按钮2(计数器递增功能)
currentState2 = digitalRead(BUTTON_PIN_2);
// 检测下降沿(按下动作)
if (lastState2 == HIGH && currentState2 == LOW) {
if ((millis() - lastDebounceTime2) > DEBOUNCE_DELAY) {
button2Pressed = true; // 标记按钮已按下
}
lastDebounceTime2 = millis();
}
// 检测上升沿(释放动作)且之前已按下
if (lastState2 == LOW && currentState2 == HIGH && button2Pressed) {
if ((millis() - lastDebounceTime2) > DEBOUNCE_DELAY) {
binaryCounter++; // 计数器加1
updateLED(); // 更新LED显示
button2Pressed = false; // 重置按下状态
}
lastDebounceTime2 = millis();
}
lastState2 = currentState2;
}