Modify your sketch from the previous Light Sensor lesson to make turn on the LED when a loud sound is detected.
Note that the Sound sensor is an analog input just like the rotary potentiometer and light sensor.
Use the "Sound Sensor" block to read the sound level value. Be sure to select the correct pin number (A2).
Create a variable to store the sound level, such as "sound"
Plot the sound level value and see how it varies when you speak, clap your hands, etc.
Turn on the LED when a loud sound is detected.
Use an "If" operator to detect when the sound level in your environment exceeds a threshold,
:if (sound > 70)
Use a threshold value that works for your environment.
Then, modify the Arduino sketch to do something different, such as:
When the sound is louder, the light gets brighter
When the sound gets louder, the light blinks faster
Use the rotary potentiometer to adjust the sound level threshold.
Create a switch that turns the LED on when you clap your hands, and off when you clap again.
"The Clapper - As Seen on TV!"
Hint: Use a variable to remember the current on/off state of the LED, and use an If block to determine the next state.
Your ideas?
Review the Arduino code that the Codecraft "Sound Sensor" block generates . ➡
What does the get_analog_A2_sound_avg() function do?
Note that the function returns a "long" data type value.
What's the difference between a long and float data type?
Click the links below to read the Arduino Language Reference:
What does sum >>= 5 do?
>> is the "bit shift right" operator.
long get_analog_A2_sound_avg(){
long sum = 0;
for(int i=0; i<32; i++){
sum += analogRead(A2);
}
sum >>= 5;
return sum;
}