Hello, i'm developing a small piano with my ArduinoUNO, and i have a problem. When i upload the code to the board, and i press the switches, the output tone is always the same. I have downloaded pitches.h library.
The code i'm using is this:
#include <pitches.h>
int sw1=2; //Switch for C
int sw2=3; //Switch for D
int sw3=4; //Switch for E
int sw4=5; //Switch for F
int sw5=6; //Switch for G
int spk=8; //Output for speaker
int val1=0;
int val2=0;
int val3=0;
int val4=0;
int val5=0;
void setup(){
pinMode(sw1,INPUT);
pinMode(sw2,INPUT);
pinMode(sw3,INPUT);
pinMode(sw4,INPUT);
pinMode(sw5,INPUT);
}
void loop(){
val1=digitalRead(sw1);
val2=digitalRead(sw2);
val3=digitalRead(sw3);
val4=digitalRead(sw4);
val5=digitalRead(sw5);
if(val1==HIGH){
tone(spk, NOTE_C3);
}else{
if(val1==LOW){
noTone(spk);
}
}
if(val2==HIGH){
tone(spk, NOTE_D3);
}else{
if(val2==LOW){
noTone(spk);
}
}
if(val3==HIGH){
tone(spk,NOTE_E3);
}else{
if(val3==LOW){
noTone(spk);
}
}
if(val4==HIGH){
tone(spk,NOTE_F3);
}else{
if(val4==LOW){
noTone(spk);
}
}
}
I have also tried to set the frequency value without using the library int A=440;
What can i do? I attach a link with a small video with the problem: MEGA
This will ensure that the HIGH/LOW level is always valid, and not "floating" as the pins are read.
You don't do anything with switch 5 yet, I assume more will be added later.
I am kind of surprised any thing plays. As soon as you reach an if condition without a key pressed you stop the tone. You may want to re-think your logic there.
Perhaps only call noTone(skp) when a key had been pressed and is then detected as not pressed; that way, key2 does not stop the tone from key1.
I use 1.0.1 IDE.
I have tried all you said me, but i have the same problem. If i write your code for 2 switches (for instance) i have the same problem and it sounds wrong. If i write the code for only one switch there's no problem with.
I have changed the conections and the other switches will be conected and programmed when the code works properly.
#include <pitches.h>
int sw1=2; //Pulsador para Do
int sw2=3; //Pulsador para Re
int sw3=4; //Pulsador para Mi
int sw4=5; //Pulsador para Fa
int sw5=6; //Pulsador para Sol
int spk=8; //Salida para el piezo
int val1=0;
int val2=0;
int val3=0;
int val4=0;
int val5=0;
int val6=0;
void setup(){
pinMode(sw1,INPUT_PULLUP);
pinMode(sw2,INPUT_PULLUP);
pinMode(sw3,INPUT_PULLUP);
pinMode(sw4,INPUT_PULLUP);
pinMode(sw5,INPUT_PULLUP);
}
void loop(){
val1=digitalRead(sw1);
val2=digitalRead(sw2);
val3=digitalRead(sw3);
val4=digitalRead(sw4);
val5=digitalRead(sw5);
if(val1==LOW){
tone(spk, NOTE_C3);
}else{
noTone(spk);
}
}