Arduino Mega 2560 中的摩尔斯电码,使用按钮和蜂鸣器

Morse code in Arduino Mega 2560, using buttons and a buzzer

我正在尝试使用面包板、一个蜂鸣器和两个按钮在 Arduino 中制作一个简单的摩尔斯电码。按下button1时,蜂鸣器应输出200ms的声音信号。如果按下另一个按钮(button2),蜂鸣器的输出应该是400ms的声音信号。

此外,当按下 button1 时,程序应打印“.”。到屏幕。同样,为较长的输出打印“-”。

这是我的代码:

const int buttonPin1 = 10;
const int buttonPin2 = 8;
const int buzzPin = 13;


void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buzzPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  noTone(buzzPin);

  if (buttonPin1 == true) {
    Serial.println('.');
    tone(buzzPin, 1000);
    delay(200);
  }
  else if (buttonPin2 == true) {
    Serial.println('-');
    tone(buzzPin, 1000);
    delay(400);
  }
}

目前还不行,不知道是我的代码还是电路出了问题。我没有收到任何来自蜂鸣器或 Arduino 的输出。

如果有人能指导我走上正确的轨道,我将不胜感激。

谢谢。

buttonPin1 == truebuttonPin2 == truetrue 与管脚编号进行比较,而不是管脚状态。

您应该使用 digitalRead() 函数来检查引脚状态。

void loop() {
  // put your main code here, to run repeatedly:
  noTone(buzzPin);

  if (digitalRead(buttonPin1) == HIGH) { // check pin status instead of doing constant comparision
    Serial.println('.');
    tone(buzzPin, 1000);
    delay(200);
  }
  else if (digitalRead(buttonPin2) == HIGH) { // check pin status instead of doing constant comparision
    Serial.println('-');
    tone(buzzPin, 1000);
    delay(400);
  }
}