Getting the Code right
I spent a full day trying to synchronise the motion sensor and the sounds. This mainly meant trying to understand the example code for the MP3 shield, to figure out how to adjust it for my purposes. This was difficult because some commands and syntax were hard for me to understand. I tried to get rid of everything unnessecary and rewright main bits in the setup and loop. But at the end of the day I didn’t manage to get it right.
Mika helped me out. We went back to buttons instead of sensors, but tried to connect just a single one and make it play any of the five tracks randomly. Eventually it worked.
We already set up the button in a way, so that exchanging it for the PIR sensor was as easy as possible. So we reversed the usual button setup: When pushed, the circuit to GND is closed, so the pin reads 0V. When not pushed, the pin reads 5V because we inserted a 100k pull-up resistor. That is because the sensor as well sends 5V as default and is pulled LOW only when motion is detected.
That way it was quite easy afterwards to exchange the push-button for the sensor. Here’s the result:
Next: The next stept will be to get a second button working. To integrate it usefully, the code should roughly say something like: “If sensor 1 is detecting motion (bike), check if sensor (pedestrians) has detected motion recently. If so, play sound.” Then again that button can be changed for a sensor.
Here’s what the main bit of the loop looks like at this point:
lastButtonState=buttonState;
buttonState=digitalRead(pirPin); //Needed to detect only the very //moment, when button is pressed initially
if (lastButtonState==HIGH){
if (buttonState == LOW) {
motion=true;
}}
if (buttonState == HIGH) {
motion=false;
} //The two possibilities
Serial.println(buttonState); //To check if pushing the button is //detected correctly
if (motion==true) {
uint8_t result = MP3player.playTrack(random(5)) //play track AND //choose one of the five
delay(3000); //delay, beacuse I dont want it to ring once every three //seconds max.
}