Hi! It's my first time trying to code and my second time messing with an Arduino. I've connected an SD card and a sound sensor, the Idea is when someone exceeds a threshold (yells) the speaker plays a sound file from the SD card.
They all work, I have played songs through the SD card, and I have connected the sound sensor that responds to the decibels. but I don't know how to code it. I've tried to combine a code that lets you play .wave files from the SD card and another code that I've used before which moves a servo motor when you clap your hands near a sound sensor. As expected that didn't work.
If you could help me with the code I'd be grateful.
The sd card is connected like this -Make an Arduino Project that Speaks / Reacts - YouTube
5V- 5V
GND-GND
CS- PIN 4
SCK- PIN13
MOSI- PIN 11
MISCO- PIN12
I soldered and wired Speaker as shown too, all works and I can play sound files.
The sound sensor connected like so- GND-GND, + TO +, and A0 to PIN A2. And it responded well.
here's the code-
#include <SD.h> //include SD module library
#include <TMRpcm.h> //include speaker control library
#define SD_ChipSelectPin 4 //define CS pin
int sound = A2;
int soundCounter = 0; // counter for the number of times sound was picked up
int soundState = 0; // current state of sound
int lastsoundState = 0; // previous state of the sound
int speaker = 9;
const int threshold = 200;
TMRpcm audio; //crete an object for speaker library
void setup() {
pinMode (sound, INPUT);
pinMode (speaker, OUTPUT);
audio.speakerPin = 9;
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
// read the sound sendor input pin:
soundState = digitalRead(INPUT);
if (soundState != lastsoundState) {
// if the state has changed, increment the counter
if (soundState == HIGH) {
soundCounter++;
Serial.println("on");
Serial.print("number of times sound is picked up: ");
Serial.println(soundCounter);
}
else
{
// if the current state is LOW then the speaker went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
int statusSensor = analogRead(sound);
if (statusSensor >= threshold){
(soundState == HIGH) ;
!SD.begin(SD_ChipSelectPin);
digitalWrite(speaker, HIGH);
audio.setVolume(6.9); //0 to 7. Set volume level
audio.play("2.wav"); //the sound file "1" will play each time the arduino powers up, or is reset
}
else{
(soundState == LOW);
digitalWrite(speaker, LOW);
}
}