PROJECT: LED Volume Indicator
Step 1 - Build the Project

Use a sound trigger to change the brightness of an LED. The louder the noise, the brighter the LED! 

Step 2 - Upload the Code

/* Use a sound trigger to make a single LED shine brighter when * a loud noise occurs. */ void setup() { pinMode(A4,INPUT); //middle pin of the sound trigger pinMode(9,OUTPUT); //LED } void loop() { //Set the sound minimum and maximum threshold //The sensor can read 0-1023, but likely range is 250-450 const int soundMin = 250; const int soundMax = 450; //The brightness variable will be between 0-255 //soundMin becomes 0 brightness, soundMax becomes 255 brightness int brightness= map(analogRead(A4),soundMin,soundMax,0,255); //The constrain method keeps brightness variable between 0 and 255 brightness = constrain(brightness,0,255); analogWrite(9,brightness);//write the value of brightness to the LED } //Reverse the way the map is working so the light // turns off near loud noises //(c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Step 3 - Read the Walkthrough

For this program, you'll use many of the built-in Arduino functions to take a sound reading, map that reading to a brightness value, then constrain that brightness value to the range 0-255.  Each time the loop runs, a new sound reading is taken and displayed on the light.

First, set up your sound trigger's center pin as an INPUT and the LED as an OUTPUT.

The first variables you create are the integers soundMin and soundMax. They each have 'const' in front of them, which means "I'm not going to change the value of these variables throughout the code.". The value of soundMin should be the lowest reading you record in your environment. soundMax should be the loudest sound reading you'll typically record. To find these values, you can either experiment or use the component guide for taking sound readings. 

Next, create an integer variable brightness. The value of this variable will be between 0 and 255. To turn your sound readings (250-450) into brightness values (0-255), you use the map() function. In this case, you're taking the value of analogRead(A4) and forcing that value onto the scale of 0 to 255. A reading of soundMin becomes a brightness of 0 and a reading of 450 becomes a brightness of 255.

Now you'll constrain the value of the brightness variable. The sound trigger spikes above the soundMin and then drops below it when a noise occurs- it's not a pure microphone. By using constrain so that brightness can not have a value below 0 or above 255, you are sure that the code won't try to write a negative brightness to the light.

Finally, you use the analogWrite() command to send the 'brightness' brightness to pin 9.