I'm trying to make a simple morse code in Arduino, using a breadboard, one buzzer and two buttons. When button1 is pushed, the output of the buzzer should be a sound signal for 200ms. If the other button (button2) is pushed, the output of the buzzer should be a sound signal for 400ms.
Also when button1 is pushed the program should print "." to the screen. Similarly, print "-" for the longer output.
This is my code:
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);
}
}
Currently, it does not work, and I am not sure what's incorrect if it is my code or the circuit. I am not receiving any output, either from the buzzer or in Arduino.
I would appreciate if anyone could guide me onto the right tracks.
Thanks.
buttonPin1 == true
and buttonPin2 == true
are compareing true
with the pin number, not the status of pins.
You should use digitalRead()
function to check status of pins.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.