Skip to content

Instantly share code, notes, and snippets.

@roy4801
Created November 30, 2018 08:10
Show Gist options
  • Select an option

  • Save roy4801/7e75e6f4d8af3da9da6d35060bb45368 to your computer and use it in GitHub Desktop.

Select an option

Save roy4801/7e75e6f4d8af3da9da6d35060bb45368 to your computer and use it in GitHub Desktop.
Arduino homework2 - paino
#define BTN_MAX 12
#define BTN_MIN 4
#define BTN_NUM (BTN_MAX-BTN_MIN+1)
#define SPEAKER1 2
#define SPEAKER2 3
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784
int pin[BTN_NUM] = {12, 11, 10, 9, 8, 7, 6, 5, 4};
int note[BTN_NUM] = {NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5, NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5};
int speaker[] = {SPEAKER1, SPEAKER2};
bool btnState[BTN_NUM];
bool playing[BTN_NUM];
int channel[2];
void setup()
{
for(int i = 0; i < BTN_NUM; i++)
pinMode(i, OUTPUT);
for(int i = 0; i < 2; i++)
pinMode(speaker[i], OUTPUT);
Serial.begin(9600);
for(int i = 0; i < 2; i++)
channel[i] = -1;
}
void loop()
{
// read btns
for(int i = 0; i < BTN_NUM; i++)
{
btnState[i] = digitalRead(pin[i]);
}
for(int i = 0; i < BTN_NUM; i++)
{
if(btnState[i]) // on
{
for(int j = 0; j < 2; j++)
{
if(!playing[i] && channel[j] == -1)
{
channel[j] = i;
playing[i] = true;
break;
}
}
}
else // off
{
for(int j = 0; j < 2; j++)
{
if(playing[i] && channel[j] == i)
{
channel[j] = -1;
playing[i] = false;
break;
}
}
}
}
for(int i = 0; i < 2; i++)
{
if(channel[i] != -1)
{
Serial.print("Play channel=");
Serial.println(i);
tone(speaker[i], note[channel[i]]);
// delay(1);
// noTone(speaker[i]);
}
else
noTone(speaker[i]);
}
// dbg
Serial.print(channel[0]);
Serial.print(' ');
Serial.println(channel[1]);
// for(int i = 0; i < BTN_NUM; i++)
// {
// Serial.print(btnState[i]);
// Serial.print(' ');
// }
Serial.print('\n');
// delay(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment