I have been working on a project of a piano keyboard using a Arduino Mega, although i have been stucked with a problem in the code. The project consists in a pushbutton that when pressed triggers a melody and a sequence of LEDs light up for each correspondent note, i have been thinking on ways to write it in the code however i haven't be able to.
Here is the code:
// Including Libraries
#include <LiquidCrystal_I2C.h>
#include "pitches.h"
///////////////////////
#define SPEAKER_PIN 8
#define bt1 7
//////////////////////
LiquidCrystal_I2C lcd(0x27,16,2);
//////////////////////
const byte buttonPins[] = { 22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,A15,A14,A13,A12 };
const int buttonTones[] = {
NOTE_C3, NOTE_CS3, NOTE_D3, NOTE_DS3, NOTE_E3, NOTE_F3, NOTE_FS3,
NOTE_G3, NOTE_GS3, NOTE_A3, NOTE_AS3, NOTE_B3,
NOTE_C4, NOTE_CS4, NOTE_D4, NOTE_DS4, NOTE_E4, NOTE_F4, NOTE_FS4,
NOTE_G4, NOTE_GS4, NOTE_A4, NOTE_AS4, NOTE_B4,
NOTE_C5, NOTE_CS5, NOTE_D5, NOTE_DS5, NOTE_E5, NOTE_F5, NOTE_FS5,
NOTE_G5, NOTE_GS5, NOTE_A5, NOTE_AS5, NOTE_B5
};
const int numTones = sizeof(buttonPins) / sizeof(buttonPins[0]);
/////////////////////
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("INITIALIZING...");
delay(2000);
for (byte i = 0; i < numTones; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, OUTPUT);
pinMode(bt1, INPUT_PULLUP);
delay(1000);
lcd.clear();
lcd.setCursor(3,0);
lcd.print("COMPLETED");
tone(SPEAKER_PIN, NOTE_C4);
delay(150);
noTone(SPEAKER_PIN);
delay(150*1.3);
tone(SPEAKER_PIN, NOTE_E4);
delay(150);
noTone(SPEAKER_PIN);
delay(150*1.3);
tone(SPEAKER_PIN, NOTE_G4);
delay(150);
noTone(SPEAKER_PIN);
delay(1500);
lcd.clear();
}
void loop() {
if (digitalRead(bt1)== 0){
}
int pitch = 0;
for (byte i = 0; i < numTones; i++) {
if (digitalRead(buttonPins[i]) == LOW) {
pitch = buttonTones[i];
}
}
if (pitch) {
tone(SPEAKER_PIN, pitch);
}
else {
noTone(SPEAKER_PIN);
}
}