Configuring the alarm system
Now that the hardware for our project is ready, we can write down the code for the project so that we have a usable alarm system. The goal is to make the buzzer produce a sound whenever motion is detected and also to make the LED flash. However, whenever the button is pressed, the alarm will be switched off.
Here is the complete code for this project:
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We are now going to see, in more detail, the different parts of the code. It starts by declaring which pins are connected to different elements of the project, such as the alarm buzzer:
After that, in the setup()
function of the sketch, we declare these pins as either inputs or outputs, as follows:
Then, in the loop()
function of the sketch, we check whether the alarm was switched on by checking the state of the motion sensor:
Note that if we detect some motion, we immediately set the alarm_mode
variable to true. We will see how the code makes use of this variable right now.
Now, if the alarm_mode
variable is true, we have to enable the alarm, make the buzzer emit a sound, and also flash the LED. This is done by the following code snippet:
Also, if alarm_mode
is returning false, we need to deactivate the alarm immediately by stopping the sound from being emitted and shutting down the LED. This is done with the following code:
Finally, we continuously read the state of the push button. If the button is pressed, we will immediately set the alarm off:
Usually, we should take care of the bounce effect of the button in order to make sure that we don't have erratic readings when the button is pressed. However, here we only care about the button actually being pressed so we do not need to add an additional debouncing code for the button.
Note that you can find all the code for this project inside the GitHub repository of the book:
https://github.com/marcoschwartz/arduino-secret-agents
Now that we have written down the code for the project, it's time to get to the most exciting part of the chapter: testing the alarm system!