When it comes to automating the home, one of the most desired features is often the ability to switch electronic devices on and off remotely (Colon, 2020). To address this, in this chapter – which covers the fifth project in this book – we will learn how to build a wireless electronic remote control to turn an LED on when two successive clapping sounds are detected using a simple microphone (clap switch). The next two successive clapping sounds detected will turn the LED off. The importance of having a switch clap remote control is that an electronic appliance can be turned on and off from anywhere in a room. This characteristic makes it of particular interest to the elderly or people with a motor disability.
This chapter will cover the following main topics:
After completing this chapter, you will be able to apply what you have learned to projects that need to read data from an analog source, process this data to convert it to digital data, and thus be able to use it to automate processes.
The hardware components that will be needed to develop the clap switch are as follows:
These components are very common, and there will be no problems in getting them easily. On the software side, you will require the Arduino IDE and the GitHub repository for this chapter: https://github.com/PacktPublishing/DIY-Microcontroller-Projects-for-Hobbyists/tree/master/Chapter07
The Code in Action video for this chapter can be found here: https://bit.ly/3h2xjQu
To supply the power source, you can use power adapters (Figure 7.1) that fit into the breadboard rails (these power adapters or breadboard power supplies are common and can be purchased at a low price in online stores), can be jumpered to provide 3.3 or 5 volts, and include an on/off button:
Additionally, you can use a 9-volt battery. Using these batteries is one of the most common options since the 9-volt voltage is appropriate to power up projects with microcontrollers such as the Blue Pill STM32.
In this section, we are going to learn about the hardware components needed to build a clap switch using the STM32 Blue Pill and the microphone FC-04 module.
However, before we begin connecting the components, we must understand the basics of a microphone.
A clap switch uses a microphone to sense the environment while waiting for an event that will trigger an action. In this section, we will understand how to apply this functionality in a project.
We will use a generic microphone module, which is a breakout board with an electret condenser microphone (as shown in Figure 7.2):
Condenser microphones are composed of a diaphragm membrane on a plate, and both are conductors. Condensers are essentially capacitors formed of conductors and insulation between them. Therefore, when there is a smaller distance between these two conductors, a higher capacitance is obtained.
Important note
Capacitance is the property or capacity that an electronic component has to collect and store energy in the form of an electrical charge.
The microphone receives the sound, making the diaphragm vibrate. The vibration varies the distance between the conductors and changes its capacitance to produce a voltage charge, which in turn requires a lot of voltage to maintain, making traditional microphones ineffective for projects with microcontroller boards (such as the Blue Pill or the Curiosity Nano) in reducing power consumption. To address the issue of the high amount of power consumption, electret microphones were developed. Electret microphones use a unique polarized material charged during their manufacturing process, thus not requiring external voltage (Fox, 2020). With an understanding of microphone basics, we will now move on to the steps to connect a microphone to a microcontroller board.
Now we are going to connect the electronic components to the breadboard, do the wiring, and finally connect everything to the STM32 Blue Pill:
In this way, the acquisition of the analog signal that comes from the sensor will be achieved, and the microcontroller will convert it into digital.
Finally, you need to use a power source such as batteries or the ST-LINK connected to the USB port of the computer to power up the board. The ST-LINK will also serve to upload the scripts to the microcontroller board. Figure 7.7 summarizes all the hardware connections:
The previous figure shows all the connections between the STM32 Blue Pill and the electronic components. This figure summarizes the connection steps we just completed.
Figure 7.8 presents the schematics for this project:
The schematics figure shows the electric diagram for the complete project. Figure 7.9 shows how everything is connected in our do it yourself (DIY) clap switch:
Figure 7.9 shows how all the finished hardware connections will look.
Now, let's move on to the next section, which will detail the essential parts of the C code to complete the functionality of the clap switch.
In this section, we will develop the program to identify a clap sound from a microphone. This sound will turn an LED on and off. Let's get started:
As can be seen in the following code snippet, the analog reading pin will be 0 (labeled A0 on the Blue Pill), and the digital output pin will be PC13 (labeled C13 on the Blue Pill):
const int MicAnalogPin = 0;
const int LedDigitalPin = PC13;
const int ClapThreshold = 300;
Constant value variables are being used with the const keyword to assign its value. Another way to do it is with a preprocessor macro using #define, as shown in the following code snippet:
#define MicAnalogPin 0
#define LedDigitalPin PC13
#define ClapThreshold 300
The difference between both forms is that with #define, the compiler replaces all occurrences with the values before compilation to avoid memory usage in the microcontroller and will always have a global scope. In contrast, const is a constant value variable stored in the microcontroller memory and has a limited scope.
Based on best programming practices, the recommended option for type safety is the use of constant variables, given that the #define directive substitutes the macro value disregarding the scope, which can lead to data type problems. In contrast, const will always be of the same data type that was defined in its declaration.
void setup() {
Serial.begin(9600);
}
void setup() {
Serial.begin(9600);
pinMode(LedDigitalPin, OUTPUT);
pinMode(MicAnalogPin, INPUT);
}
void loop() {
int SoundValue = analogRead(MicAnalogPin);
Serial.print("Sound value: ");
Serial.println(SoundValue);
}
void loop() {
int SoundValue = analogRead(MicAnalogPin);
Serial.print("Sound value: ");
Serial.println(SoundValue);
if (SoundValue > ClapThreshold) {
Serial.println("A clap was detected");
digitalWrite(LedDigitalPin, HIGH);
delay(1000);
} else {
Serial.println("No clap detected");
digitalWrite(LedDigitalPin, LOW);
}
}
Now we have the complete code for the first sketch to detect the sound of a clap and turn on a LED. Next, we can see the complete sketch, which is available in the Chapter7/clap_switch folder in the GitHub repository.
Now that the sketch is complete, you can upload it to the Blue Pill board. To test that our project works, just give a clap to see how the LED turns on. Do not forget that the breadboard must be powered, either by batteries or connected to the computer.
So far, we have learned how to read an analog value (sound) from a microphone with a microcontroller. During the main loop, the device keeps listening to the microphone to detect whether any sound (we will assume the detected sound is a clap) is louder than the defined threshold; if so, an LED lights up. If not, the microcontroller will keep the LED off.
Next, we are going to modify the sketch to indicate to our clap switch to wait for two claps before turning on the LED. For better organization, we will create a copy of the code to compare with the original sketch or in case we need to revert to the previous version when experiencing an issue with the new code.
In this section, we will modify our program to identify two clapping sounds from the microphone. This will allow us to be more precise before activating the remote control:
const int MicAnalogPin = 0;
const int LedDigitalPin = PC13;
const int ClapThreshold = 300;
int ClapNumber = 0;
bool LedState = false;
As you can see, the clap count is set to 0, and the LED status to false (off), which means that true will be on.
void loop() {
int SoundValue = analogRead(MicAnalogPin);
if (SoundValue > ClapThreshold) {
ClapNumber++
delay(500);
}
}
This conditional block does not require an else sentence. Also, the instruction to turn on the LED has been removed. If a clap is detected, the clap counter will be incremented by 1 and will wait for a half-second pause before the Blue Pill re-senses the microphone.
void loop() {
int SoundValue = analogRead(MicAnalogPin);
if (SoundValue > ClapThreshold) {
ClapNumber++;
delay(500);
}
if (ClapNumber == 2) {
digitalWrite(LedDigitalPin, HIGH);
}
}
Now we are ready to test the new sketch on our device, compile it, and load it. We can test the code with two consecutive claps, with a short pause between them (remember the delay that we programmed).
void loop() {
int SoundValue = analogRead(MicAnalogPin);
if (SoundValue > ClapThreshold) {
ClapNumber++;
delay(500);
}
if (ClapNumber == 2) {
if (LedState) {
digitalWrite(LedDigitalPin, HIGH);
} else {
digitalWrite(LedDigitalPin, LOW);
}
ClapNumber = 0;
LedState = !LedState;
}
}
When the microcontroller detects two claps in a row, the first thing it will do is check the state of the variable that stores the LED state using the next conditional sentence, if (LedState). As it is a Boolean type variable, it can be analyzed directly into the if statement without the need for additional operators. If the variable has a TRUE value, it triggers the if block, and if it is FALSE, it executes the else block. So, the preceding code turns on the LED if the variable is TRUE and turns it off if it is FALSE. Finally, within the same condition of two claps detected, the ClapNumber variable is reset to 0 claps to restart the counter and wait for two new claps. The value of the LedState variable is changed utilizing a negation operator, inverting the value of the Boolean variable; if the state was ON, the command would turn it into OFF and vice versa.
With this previous step, our project for detecting two continuous claps and turning on an LED is complete. The full sketch is shown as follows and is also available in the Chapter7/double_clap_switch folder in the GitHub repository. With the complete sketch for detecting two continuous claps, we can already test it with its new functionality. In the beginning, the LED will be off. When you clap twice, with a short pause between them, it will light up; clapping twice again will turn it off.
Finally, we are going to add a timer to our sketch to indicate to our clap switch to wait only 30 seconds between the two claps before turning on the LED. The same as this section, we will create a copy of the code and work with the new code.
Now, we will add a timer to limit the waiting timeframe between the first and second claps:
const int MicAnalogPin = 0;
const int LedDigitalPin = PC13;
const int ClapThreshold = 300;
int ClapNumber = 0;
bool LedState = false;
unsigned long FirstClapEvent = 0;
unsigned long SecondClapEvent = 0;
These two highlighted variables will store the milliseconds when a clap is detected: one for the first time and another for the second time.
void loop() {
int SoundValue = analogRead(MicAnalogPin);
if (SoundValue > ClapThreshold) {
ClapNumber++
delay(500);
FirstClapEvent = (ClapNumber == 1) ? millis() : FirstClapEvent;
}
}
If a clap is detected, we verify whether it is the first clap; in this case, we assign the FirstClapEvent variable value to the millis() function. This function returns the milliseconds since the STM32 Blue Pill executed the sketch. Otherwise, the variable value remains the same.
void loop() {
int SoundValue = analogRead(MicAnalogPin);
if (SoundValue > ClapThreshold) {
ClapNumber++;
delay(500);
FirstClapEvent = (ClapNumber == 1) ? millis() : FirstClapEvent;
}
if (ClapNumber == 2) {
SecondClapEvent = millis();
if (SecondClapEvent - FirstClapEvent < 30000) {
if (LedState) {
digitalWrite(LedDigitalPin, HIGH);
} else {
digitalWrite(LedDigitalPin, LOW);
}
ClapNumber = 0;
LedState = !LedState;
FirstClapEvent = 0;
SecondClapEvent = 0;
}
}
}
Now we can test the code with two consecutive claps, with a 30-second timeframe between them. The full sketch is shown as follows and is also available in the GitHub repository folder: Chapter7/double_clap_switch_timer.
Now that we have completed the sketch with all its functionality, just load and execute the sketch to test and validate the functionality.
In the next section, we will learn how to test the system and provide a useful tip to improve the work with analog data.
I mentioned earlier that we were going to talk about the threshold value. In general, solutions for projects with analog read set the threshold value to 200, but as you remember, we are using a value of 300 to ensure we are reading a clap, not background noise.
If you want to know more precisely the value of your clap's sound, then you can use the example script that the IDE provides us. To access this sketch, we must go to the File menu, then to Examples, and choose Basics. In that section, we will find the AnalogReadSerial sketch, as shown in Figure 7.10:
Selecting that menu option will open the AnalogReadSerial.ino sketch:
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(0);
Serial.println(sensorValue);
delay(1);
}
The previous code introduces an instruction that we have not used so far in this project, which is Serial.println(). This code displays the data in ASCII format in a console called the serial port so that it is understandable to people and it includes a line break.
By loading and executing the script, we can open the serial monitor of our Arduino IDE to see the values that our microphone is generating (in the range 0-1023). You just need to try some test claps to find out the value of the sound of your clap and use that as a more personalized threshold.
The previous code blocks sense a microphone to detect two clap sounds and turn on and off an LED. The system waits for a 30-second timeframe between each clap sound before turning on or off the LED.
Congratulations, you have now built a wireless electronic remote control!
So, what have we learned in this project? Firstly, we learned how to connect the microphone module, LED, and resistor to the STM32 Blue Pill microcontroller board, which would be controlled by the STM32 microcontroller. We then wrote a piece of code to read an analog value and analyze it in our microcontroller. Subsequently, we sent a digital signal to turn the LED on or off depending on the embedded rules in our STM32. Lastly, we physically tested the device to understand the real-life operation.
This project gives us the skills to begin to create a remote control to automate home appliances and use them according to our needs. For example, you can add a relay module and connect it to a lamp so you can turn it on and off from the comfort of where you are without the need to reach the lamp switch.
In the next chapter, we will learn how to use the serial monitor feature to analyze the outputs that our sketch generates while it is running. We will do so by building a gas sensor project with the help of the STM32 microcontroller.
52.14.168.56