Hi, I am trying to make a sound monitor, so I can see if my dog is barking during the day while I’m away. I’ve got an adafruit microphone (https://www.adafruit.com/products/1063) which can be read via analogRead.
The code below works for the first iteration. The expected output is written to the serial port through “Done.” The reading shows up on thingspeak. After that, the Spark becomes unstable and the code never seems to run again. The spark will continually drop the wifi connection (flashing fast green and fast cyan). I can’t program it again without factory resetting it.
I’m a bit at a loss here. Any ideas on what I’m doing wrong?
Thanks,
Grady
byte server[] = { 184, 106, 153, 149 }; // IP Address for the ThingSpeak API
String writeAPIKey = "API KEY"; // Write API Key for a ThingSpeak Channel
TCPClient client;
void setup() {
pinMode(A4, INPUT);
Serial.begin(9600);
Serial.println("hello");
}
void loop() {
unsigned int loudness = 0;
//sample the loudness for about a minute
Serial.println("sampling");
for ( int n=0; n < 50; n++ ) {
for (int i=0; i < 10; i++) {
unsigned long startMillis = millis(); // Start of sample window
unsigned int signalMax = 0;
unsigned int signalMin = 10000;
while ( millis() - startMillis < 25 ) {
unsigned int sample = analogRead(A4); //P5
signalMax = max(signalMax, sample);
signalMin = min(signalMin, sample);
}
loudness = max(signalMax - signalMin, loudness); // max - min = peak-peak amplitude
}
Serial.println(loudness);
delay(1000);
}
if ( client.connect(server, 80) ) {
Serial.println("connected");
String tsData = "field1="+String(loudness);
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
client.print("\n\n");
client.print(tsData);
//wait for request to be processed.
delay(1000);
Serial.print("and ");
client.flush();
client.stop();
}
Serial.println("done");
}