/* piano practice reward system */
// https://wokwi.com/projects/360630061512826881
// https://forum.arduino.cc/t/how-should-one-go-about-creating-an-arduino-timer-split-in-sections-with-random-interruptions-based-on-certain-conditions/1108459
// monitor the sound sensor and develop a playing/not playing logic value
# define SOUND LOW // active low sound sensor, you know what to do
# define DETECT 3000 // milliseconds of silence to tolerate
const unsigned char rawSoundIn = 5;
const unsigned char rawSoundEcho = 6;
const unsigned char soundLED = 7;
unsigned long now; // updated at the top of loop()
void setup()
{
Serial.begin(115200);
Serial.println("\nhello world.\n");
pinMode(rawSoundIn, INPUT_PULLUP);
pinMode(rawSoundEcho, OUTPUT);
pinMode(soundLED, OUTPUT);
}
void loop()
{
now = millis(); // standard time
bool playing = soundCheck();
static unsigned char printed;
if (playing) {
if (!printed) {
Serial.println("I hear practicing!");
printed = 1;
}
}
else {
if (printed) {
Serial.println(" Hey! I hear no piano...");
printed = 0;
}
}
}
unsigned char soundCheck()
{
static unsigned long soundTime;
unsigned char soundNow = digitalRead(rawSoundIn) == SOUND;
digitalWrite(rawSoundEcho, soundNow);
if (soundNow) {
if (!soundTime) digitalWrite(soundLED, HIGH);
soundTime = now;
return 1;
}
if (soundTime && (now - soundTime > DETECT)) {
digitalWrite(soundLED, LOW);
soundTime = 0;
return 0;
}
return soundTime ? 1 : 0;
}