// Arduino C++代码(适用于Arduino板,非Wokwi Pico-W MicroPython)
#include <Servo.h> // Arduino伺服电机库
#include <Keypad.h> // Arduino键盘库
// 硬件配置(Arduino引脚,非文档Pico引脚)
Servo lockServo;
const int servoPin = 9; // 伺服电机信号脚(Arduino PWM引脚)
const int redLED = 10; // 红色LED引脚
const int greenLED = 11; // 绿色LED引脚
// 4x4键盘配置
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {2,3,4,5}; // Arduino行引脚
byte colPins[COLS] = {6,7,8,12}; // Arduino列引脚
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
// 系统参数
String secretCode = "31415927";
String inputBuffer = "--------";
bool isLocked = false;
int failCount = 0;
const int maxFails = 3;
unsigned long lockdownEnd = 0;
bool isLockdown = false;
// 初始化函数
void setup() {
Serial.begin(9600);
lockServo.attach(servoPin);
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
// 初始状态:解锁
lockServo.write(0);
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, LOW);
Serial.println("State: UNLOCKED | Press * to lock");
}
// 伺服电机控制
void setLock(bool state) {
isLocked = state;
if (state) {
lockServo.write(90); // 锁定(90度)
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
Serial.println("State: LOCKED | Enter code + #");
} else {
lockServo.write(0); // 解锁(0度)
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
Serial.println("State: UNLOCKED | Press * to lock");
}
}
// 主循环
void loop() {
char pressedKey = customKeypad.getKey();
// 锁定倒计时逻辑
if (isLockdown && millis() < lockdownEnd) {
int remaining = (lockdownEnd - millis())/1000;
Serial.printf("Lockdown: %ds remaining\n", remaining);
delay(500);
return;
} else if (isLockdown) {
isLockdown = false;
failCount = 0;
Serial.println("Lockdown ended | Try again");
}
// 处理按键
if (pressedKey) {
if (!isLocked) {
// 未锁定:按*锁定
if (pressedKey == '*') setLock(true);
else Serial.println("Press * to lock");
} else {
// 已锁定:处理密码
if (pressedKey == '#') {
if (inputBuffer == secretCode) {
setLock(false);
inputBuffer = "--------";
} else {
failCount++;
inputBuffer = "--------";
Serial.printf("Wrong code! Fails: %d/%d\n", failCount, maxFails);
if (failCount >= maxFails) {
isLockdown = true;
lockdownEnd = millis() + 10000; // 锁定10秒
}
}
} else {
inputBuffer = inputBuffer.substring(1) + pressedKey;
Serial.printf("Input: %s\n", inputBuffer.c_str());
}
}
}
delay(50);
}