Hello I am new to arduino electronics. I haven't used a development board or program electronics in years. So I decided to jump back into the game and see what advances there was. And there were tons. So I was playing with some of the examples and was trying to do a particular thing. And I ran into some trouble and hoping to get some help and see what my problems are.
I am trying to use 2 buttons. One to turn the LED on and off. Which I was able to do. the other was to play Music or tones through the piezo buzzer. I got that playing. But What I ran into was when trying to combine them together. I searched google and this forum and tried so many different if, while, and for statement but could not get it to work the way I wanted. And I am not too great with C++ so that was an issue too.
What I wanted to do was have one button to turn on and off the LED. But I want the LED to turn off after a few seconds if I do not turn it off manually. I tried to add delay in my codes but it didnt work out the way I want it. And I want the music to play and loop when another button is press and to turn off when i press the button again. But it doesn't loop, I have to hold the button down for it to loop. I hope i explained everything correctly.
#include "pitches.h"
//variables
const int buttonPin = 7;
const int buttonPin2 = 4;
const int ledPin = 11;
boolean ledOn = false;
boolean currentButton = LOW;
boolean lastButton = LOW;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(buttonPin2, INPUT);
}
void loop()
{
music();
ledTime();
}
void ledTime(){
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH)
{
ledOn = !ledOn;
lastButton = HIGH;
}
lastButton = currentButton;
digitalWrite(ledPin, ledOn);
}
boolean debounce(boolean last)
{
boolean current = digitalRead(buttonPin);
if (last != current)
{ delay(5);
current = digitalRead(buttonPin);
}
return current;
}
void music(){
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };
while (digitalRead(buttonPin2) == HIGH)
{
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
//noTone(8);
}
}
}
Any help is appreciated and thank you all in advance.