0

I'm creating a program that works like a piano. I have four button, a piezo buzz and an LCD screen. I'm having a little trouble with the buttonstate.

Here is my program, when I run it the piezo buzz doesn't stop producing sound. The way it's suppose to work is when I push the green button, the piezo is suppose to produce a C sound but it doesn't. Can anyone please tell me what I've done wrong?

code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
int buttonyellow = 3; 
int buttonred = 4;
int buttongreen = 5;
int buttonblue = 6;
int C,D,E,F; 
int buzz = 7;
int buttonstate;
void setup()
{
 lcd.begin(16, 2);
 lcd.print("hello, world!");
 Serial.begin(9600);
 pinMode(buttonyellow,INPUT);
 pinMode(buttonred,INPUT);
 pinMode(buttongreen,INPUT);
 pinMode(buttonblue,INPUT);
}
void loop()
{
 lcd.setCursor(0, 1);
 lcd.print(millis() / 1000);
 C = digitalRead(buttonyellow);
 D = digitalRead(buttonred);
 E = digitalRead(buttongreen);
 F = digitalRead(buttonblue);
 buttonstate = digitalRead(C); 
 if(buttonstate == HIGH){ 
 tone(buzz,523); 
 } else if ( buttonstate == LOW) {
 tone(buzz,1000); 
 }else{
 noTone(buzz); 
 } 
 delay(50); 
}
Juraj
18.3k4 gold badges31 silver badges49 bronze badges
asked Apr 25, 2019 at 18:23
2
  • what is buttonstate = digitalRead(C);? if (C == HIGH){ was the plan? Commented Apr 25, 2019 at 18:38
  • have a really good look at your if-else block ..... what value of buttonstate will allow noTone(buzz); to run? Commented Apr 26, 2019 at 4:24

1 Answer 1

1

As jsotola has pointed out, there is a mistake in your code. Remove the line

buttonstate = digitalRead(C)

and replace

if(buttonstate == HIGH)

with

if(C == HIGH)

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button

answered Apr 26, 2019 at 10:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.