I'd like to simulate a piano key being pressed but I have a problem.
I use a Musical Instrument Shield that defines the functions noteOn(byte channel, byte note, byte attack_velocity) and noteOff(byte channel, byte note, byte release_velocity)
But the problem does not come from the shield, it's just a programming issue:
I want the note to be played only once when I press the key, and to be played another time as soon as I release and press the key again.
But if I use this:
if (digitalRead(key1)== HIGH)
{
noteOn(0, 59, 60)
}
Then the note will loop really fast, but I want it to be played only once.
I thought of using a delay like this:
if (digitalRead(key1)== HIGH)
{
noteOn(0, 59, 60)
delay (10000)
}
But that way I can't play this key (or another one) during 10sec...
TO SUM UP: I want the NoteOn to be activated only once in the If loop, and to be re-activated when the If goes false then true.
key1_val=LOW; //once its low, it wont be high till key is pressed again
Nonsense. You misspelled read.
OP: Look at the State Change Detection example. You want to do something when switch BECOMES pressed and when it BECOMES released, not when the switch IS pressed or IS released.
That requires that you compare this reading to the last reading, to see when a change occurs. When the change happens, the current state (pressed or released) defines what to do.
PaulS:
OP: Look at the State Change Detection example. You want to do something when switch BECOMES pressed and when it BECOMES released, not when the switch IS pressed or IS released.
That requires that you compare this reading to the last reading, to see when a change occurs. When the change happens, the current state (pressed or released) defines what to do.
Thank you for your answer.
I tried this: (Pouce <=> Key and EtatP <=> KeyState)
int Pouce = 6;
int EtatP;
int LastEtatP;
void setup() {
pinMode(Pouce, INPUT);
LastEtatP = LOW;
}
void loop() {
EtatP = digitalRead(Pouce);
if (EtatP != LastEtatP);
{
if (EtatP = HIGH){
noteOn(0, 59, 60);
}
LastEtatP = EtatP;
}
}
Facoupile:
I don't understand why, it should be working...
There is something going on that you don't know about.
If your loop() is fast enough it will read what is called contact bounce, and Arduino is easily so fast.
When metal contacts metal in a button/switch it is not a simple ideal instant event. There is a lot of ON and OFF in a row when you look with code or oscilloscope and there are ways to handle that.
Instead of getting you to code around the problem, put a 1 uF capacitor across the button/switch leads to eat those tiny sparks and the button/switch will behave very very close to ideal.
Here is a tutorial that gives a full understanding of buttons and switches as well as ways to handle them.
The schematic for the capacitor on switch is in the part "Hardware debounce".