MeSoundSensor reading


#1

I would like to increase the value of speed every time sound sensor registers a loud noise (a clap).
The readings I get from MeSoundSensor are normally around 200-400. I use if statement. if > 500, then add speed. For some reason the speed is increasing always. Any ideas please?

The simplified code is below.:
#include “MeMCore.h”

MeSoundSensor mySound(PORT_4);
MeLEDMatrix ledMx(PORT_1);
int speed = 85;

void setup() {
Serial.begin(9600);
}

void loop() {
Serial.print("Sound: “);
Serial.print(mySound.strength() );
Serial.print(” - speed: ");
Serial.println(speed);
delay(100);
if(mySound.strength() > 500);{
speed = speed + 85;
}
}

The result I get:


#2

First, you may not be aware of this but if you precede each line of code with four spaces, the listing will appear as below:

MeSoundSensor mySound(PORT_4);
MeLEDMatrix ledMx(PORT_1);
int speed = 85;

void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.print("Sound: ");
    Serial.print(mySound.strength() );  // first sound sensor read
    Serial.print(" - speed: ");
    Serial.println(speed);
    delay(100);
    if(mySound.strength() > 500);{   // second sound sensor read; semi-colon is ending the if test early
        speed = speed + 85;  // this always gets executed because the if test statement was short-circuited.
    }
}

Your error is caused by the semi-colon in your if test. The semi-colon effectively ends the if test so you will always be adding 85. Below is a more idiomatic way of writing your code. :slight_smile:

#include <Arduino.h>
#include <Wire.h>
#include <SoftSerial.h>
#include <MeMcore.h>

MeSoundSensor mySound(PORT_4);
MeLEDMatrix ledMx(PORT_1);
int speed = 85;
int volume = 0;       // variable for sound sensor reading
char msg[32];         // character array for logging message

void setup() {
    Serial.begin(9600);
}

void loop() {
    // save the sensor reading in a variable
    volume = mySound.strength();

    // create the logging message
    sprintf(msg, "Sound: %3d - speed: %d", volume, speed);

    // print the message
    Serial.println(msg);

    // increase speed if volume is over 500
    if (volume > 500) {
        speed += 85;
    }

    // sample every 100 milliseconds
    delay(100);
}

#3

Thank you for pointing out the error and for the good advice on the code!
Mattias


#4