const int buttonPin = 2; // 按钮连接到 D2 const int motor1 = 9; // 电机驱动 IN1 const int motor2 = 10; // 电机驱动 IN2 const int motor3 = 11; // 电机驱动 IN3 const int motor4 = 12; // 电机驱动 IN4 int buttonState = 0; int lastButtonState = LOW; int fanSpeed = 0; // 0: 关闭, 1: 低速, 2: 中速, 3: 高速 unsigned long lastDebounceTime = 0; unsigned long debounceDelay = 50; void setup() { pinMode(buttonPin, INPUT_PULLUP); pinMode(motor1, OUTPUT); pinMode(motor2, OUTPUT); pinMode(motor3, OUTPUT); pinMode(motor4, OUTPUT); } void loop() { int reading = digitalRead(buttonPin); // 防抖处理 if (reading != lastButtonState) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { if (reading == LOW) { fanSpeed++; if (fanSpeed > 3) fanSpeed = 0; // 超过 3 级别则归零 } } lastButtonState = reading; // 控制风扇转速 switch (fanSpeed) { case 0: // 关闭 stopMotor(); break; case 1: // 低速 runMotor(100); break; case 2: // 中速 runMotor(150); break; case 3: // 高速 runMotor(255); break; } } // 运行电机 void runMotor(int speed) { analogWrite(motor1, speed); analogWrite(motor2, 0); analogWrite(motor3, speed); analogWrite(motor4, 0); } // 停止电机 void stopMotor() { analogWrite(motor1, 0); analogWrite(motor2, 0); analogWrite(motor3, 0); analogWrite(motor4, 0); }