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); 
}
2
  • what is buttonstate = digitalRead(C);? if (C == HIGH){ was the plan?
    – Juraj
    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?
    – jsotola
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.