#include <Keypad.h>
// 定义Keypad的行和列数量
const byte ROWS = 4; // 四行
const byte COLS = 4; // 四列
// 定义Keypad的按键布局
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// 定义连接Keypad的GPIO引脚
byte rowPins[ROWS] = {19, 18, 5, 17}; // 将这些引脚连接到Keypad的行引脚
byte colPins[COLS] = {16, 4, 0, 2}; // 将这些引脚连接到Keypad的列引脚
// 创建Keypad对象
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// 定义外部按钮连接的引脚
const int externalButtonPin = 15; // 修改为实际连接的引脚
// 定义密码和用户ID的映射
typedef struct {
String userId;
String password;
} UserPassword;
// 定义存储用户密码的数组
UserPassword userPasswords[] = {
{"user1", "1234"},
{"user2", "5678"},
// 可以添加更多用户及其密码
};
// 用户输入的密码和ID
String enteredPassword = "";
String enteredUserId = "";
// 是否处于录入密码模式
bool isSettingPassword = false;
// 是否处于输入用户ID模式
bool isEnteringUserId = false;
void setup() {
Serial.begin(115200);
pinMode(externalButtonPin, INPUT_PULLUP); // 设置外部按钮引脚为输入,并启用上拉电阻
Serial.println("请按下外部按钮开始录入新用户。");
}
void loop() {
// 检测外部按钮是否按下
if (digitalRead(externalButtonPin) == LOW) {
// 按下外部按钮,切换到输入用户ID模式
isEnteringUserId = true;
Serial.println("进入新用户ID输入模式,请输入用户ID:");
delay(500); // 延迟一段时间,防止按钮按下时短时间内多次触发
}
if (isEnteringUserId) {
// 处于输入用户ID模式
enterUserId();
} else if (isSettingPassword) {
// 处于密码录入模式
recordUserPassword();
} else {
// 处于正常模式
// 正常模式下不做任何操作
}
}
void enterUserId() {
char key = keypad.getKey();
if (key) {
if (key == '#') {
// 按下#键表示输入完成,进入密码录入模式
isEnteringUserId = false;
isSettingPassword = true;
Serial.println("用户ID输入完成,进入密码录入模式,请输入密码:");
} else if (key == '*') {
// 按下*键表示清空输入
enteredUserId = "";
Serial.println("已清空输入的用户ID。");
} else {
// 否则将按键添加到输入中
enteredUserId += key;
Serial.print("输入的用户ID:");
Serial.println(enteredUserId);
}
}
}
void recordUserPassword() {
char key = keypad.getKey();
if (key) {
if (key == '#') {
// 按下#键表示输入完成
Serial.print("密码已录入:");
Serial.println(enteredPassword);
// 将新用户添加到系统中
addUser(enteredUserId, enteredPassword);
isSettingPassword = false;
Serial.println("退出密码录入模式。");
Serial.println("请按下外部按钮开始录入新用户。");
} else if (key == '*') {
// 按下*键表示清空输入
enteredPassword = "";
Serial.println("已清空输入的密码。");
} else {
// 否则将按键添加到输入中
enteredPassword += key;
Serial.print("输入的密码:");
Serial.println(enteredPassword);
}
}
}
void addUser(String userId, String password) {
// 将新用户添加到用户密码数组中
if (findUser(userId) == -1) {
userPasswords[sizeof(userPasswords) / sizeof(userPasswords[0])] = {userId, password};
Serial.println("新用户添加成功!");
} else {
Serial.println("用户ID已存在,添加失败!");
}
}
int findUser(String userId) {
// 在用户密码数组中查找用户ID,返回其索引,如果找不到返回-1
for (size_t i = 0; i < sizeof(userPasswords) / sizeof(userPasswords[0]); i++) {
if (userPasswords[i].userId == userId) {
return i;
}
}
return -1;
}