莫尔斯电码在Arduino Mega 2560,使用按钮和蜂鸣器



我正在尝试用Arduino制作一个简单的莫尔斯电码,使用一个面包板、一个蜂鸣器和两个按钮。当按下按钮1时,蜂鸣器的输出应为200ms的声音信号。如果按下另一个按钮(按钮2(,蜂鸣器的输出应为400毫秒的声音信号。

此外,当按下按钮1时,程序应打印""到屏幕。类似地,打印"-"以获得更长的输出。

这是我的代码:

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);
  }
}

最新更新