Sorry for any grammar mistakes. It's my second language.
I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4. I connected piezo to power and ground.
When you pressed a button1 then you should hear 'c' tone, but when I pressed the second button nothing happend and I don't understand why?
Here is my code below:
const int buttonPin2 = 4;
const int buttonPin1 = 2;
const int piezopin = 6;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {
pinMode(piezopin, OUTPUT);
pinMode(buttonPin2,INPUT);
pinMode(buttonPin1, INPUT);
}
void loop() {
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);
if (buttonState1 == HIGH) {
tone(6,261.63,500);
} else {
}
if (buttonState2 == HIGH) {
tone(6,392.00,500);
} else {
}
-
1What happens when you press the first button? I assume you have a final closing brace not shown in your code above. Perhaps try writing messages to the console in each of the button pressed cases to see if it is reading the inputs correctly.AngeloQ– AngeloQ2017年02月07日 21:14:11 +00:00Commented Feb 7, 2017 at 21:14
-
4There is a free schematic tool when posting. Use it please.Bort– Bort2017年02月07日 21:23:29 +00:00Commented Feb 7, 2017 at 21:23
-
1You should add a debounce in the code for the buttons. And this is a state change code. You should try going to the Arduino website for an example code as a reference. I'm a bit rusty, but I dont think the if/else statements are right. But this is relatively straight forward basic code, lots of help around the web if you look for it.Rayray– Rayray2017年02月07日 22:12:21 +00:00Commented Feb 7, 2017 at 22:12
-
1@Rayray Nothing technically wrong with the if/else statements but the else clauses are empty so they could be removed.AngeloQ– AngeloQ2017年02月07日 23:19:37 +00:00Commented Feb 7, 2017 at 23:19
-
What is your wiring? Do you have any pull-down resistors?Nick Gammon– Nick Gammon ♦2017年02月08日 09:05:13 +00:00Commented Feb 8, 2017 at 9:05
1 Answer 1
Try calling noTone()
after the tone is played. This is a kind of "reset" for the pin.
Also, you forgot a }
at the end of your code.
If these didn't solve your code, then it most probably is an electric problem.
-
I know what was my problem. i was thinking my buttons are upright but they are not.my program is working now.thank you for your help.:-)Konrad5623– Konrad56232017年03月11日 20:31:35 +00:00Commented Mar 11, 2017 at 20:31