#include // 定义LED引脚 const int ledPins[] = {26, 27, 28, 29, 0}; // LED引脚数组 const int numLEDs = sizeof(ledPins) / sizeof(ledPins[0]); // LED数量 // 定义按键引脚 const int buttonPin = 3; // 按键引脚 // 摩尔斯电码表 const char* morseAlphabet[] = {".-", "-...", "-.-.", "-..", ".", // A-E "..-.", "--.", "....", "..", ".---", // F-J "-.-", ".-..", "--", "-.", "---", // K-O ".--.", "--.-", ".-.", "...", "-", // P-T "..-", "...-", ".--", "-..-", "-.--", "--.."}; // U-Z // 点与划的时间 const int dotDuration = 200; const int dashDuration = dotDuration * 3; const int interElementDelay = dotDuration; const int interCharacterDelay = dashDuration; void setup() { // 初始化LED引脚 for (int i = 0; i < numLEDs; i++) { pinMode(ledPins[i], OUTPUT); digitalWrite(ledPins[i], LOW); // 初始状态关闭LED } // 初始化按键引脚 pinMode(buttonPin, INPUT); // 初始化串口通信 Serial.begin(9600); } // 发送摩尔斯电码 void sendMorseCode(const char* morse) { for (int i = 0; morse[i] != '\0'; i++) { if (morse[i] == '.') { digitalWrite(ledPins[i], HIGH); delay(dotDuration); digitalWrite(ledPins[i], LOW); } else if (morse[i] == '-') { digitalWrite(ledPins[i], HIGH); delay(dashDuration); digitalWrite(ledPins[i], LOW); } else if (morse[i] == ' ') { delay(interElementDelay); } } } // 检测按键并发送摩尔斯电码对应的字母 void loop() { if (digitalRead(buttonPin) == HIGH) { // 如果按键被按下 // 按下按键发送 "SOS" 的摩尔斯电码 for (int i = 0; i < 3; i++) { sendMorseCode(morseAlphabet[18]); // 'S' delay(interCharacterDelay); sendMorseCode(morseAlphabet[14]); // 'O' delay(interCharacterDelay); sendMorseCode(morseAlphabet[18]); // 'S' if (i < 2) { delay(interCharacterDelay); } } Serial.println("SOS"); // 串口输出 "SOS" delay(1000); // 延迟一段时间避免重复发送 } }