#define EYE PB_0
#define HORN PB_1
#define BODY PA_4
#define Button PA_6
void flash(void);
void water(void);
void breath(void);
volatile int touchState = LOW; // 按键当前状态
int waterDelaySec = 1000; // 流水灯延迟时间
int flashDelaySec = 100; // 爆闪延迟时间
// 按键防抖参数
unsigned long lastButtonPress = 0;
const unsigned long debounceDelay = 50;
volatile byte mode = 0; // 当前模式
unsigned long lastMillis = 0; // 用于计时的全局变量
void setup(void) {
pinMode(EYE, OUTPUT);
pinMode(HORN, OUTPUT);
pinMode(BODY, OUTPUT);
analogWrite(EYE, 255); // 共阳,默认LED熄灭
analogWrite(HORN, 255); // 共阳,默认LED熄灭
analogWrite(BODY, 255); // 共阳,默认LED熄灭
pinMode(Button, INPUT_PULLUP); // 设置按键为输入, 默认拉高
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(Button), btn_pressed, RISING); // 触发中断
}
void loop(void) {
switch (mode) {
case0:
breath();
break;
case1:
water();
break;
case2:
flash();
break;
case3:
// 空闲模式
Serial.println("空闲模式, 关闭所有LED");
delay(1000);
analogWrite(EYE, 255);
analogWrite(HORN, 255);
analogWrite(BODY, 255);
break;
}
}
// 中断服务函数
void btn_pressed() {
unsignedlong currentMillis = millis();
if (currentMillis - lastButtonPress > debounceDelay){
mode = (mode + 1) % 4; // 切换模式
lastButtonPress = currentMillis;
}
}
// 流水灯
void water() {
Serial.println("开始流水灯");
staticint ledIndex = 0;
staticint ledPins[] = {EYE, HORN, BODY};
if (millis() - lastMillis >= waterDelaySec) {
Serial.println("流水灯- 切换LED");
for (int i = 0; i < 3; i++) {
analogWrite(ledPins[i], 255);
}
analogWrite(ledPins[ledIndex], 0);
ledIndex = (ledIndex + 1) % 3;
lastMillis = millis();
}
}
// 呼吸灯
void breath() {
Serial.println("开始呼吸灯");
staticint brightness = 0;
staticint fadeAmount = 5;
constint breathDelay = 20;
if (millis() - lastMillis >= breathDelay) {
Serial.println("呼吸灯- 切换亮度, brightness => " + String(brightness));
analogWrite(EYE, brightness);
analogWrite(HORN, brightness);
analogWrite(BODY, brightness);
brightness += fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
lastMillis = millis();
}
}
// 爆闪灯
void flash() {
Serial.println("开始爆闪灯");
static byte ledState = 255;
int count = 0; //爆闪5次
while (count < 5){
if (millis() - lastMillis >= flashDelaySec) {
Serial.println("爆闪灯- 切换亮灭状态");
if (ledState == 255){
ledState = 0;
} else {
ledState = 255;
}
analogWrite(EYE, ledState);
analogWrite(HORN, ledState);
analogWrite(BODY, ledState);
lastMillis = millis();
count += 1;
}
}
}