First, you will need to access the Raspberry Pi terminal. You can do this via Raspbian desktop or log in remotely using a tool like PuTTY. SSH will need to be enabled. Visit our guide on how to log into a Raspberry Pi via SSH.
Our Raspberry Pi clap switch will be activating an LED. To send the signal that turns it on, we'll need to use the GPIO pins. We'll use RPi.GPIO to control them. Run the following script to install the GPIO tools.
pip install RPi.GPIO
The clap powered mechanism will be controlled via mic input. To use audio in our script, we'll need to install pyaudio. Installation is easy, just run the following script.
sudo apt-get install python-pyaudio
The Pi will listen for claps using a microphone, I'll be using a USB mic. Connect your preferred device to the Raspberry Pi.
Depending on the ambient noise level of the room, you may find that some mics can pick up audio better than others. You can adjust the clap threshold by editing the clap script in a text editor. This project will require a degree of fine tuning both the microphone and clap script settings.
What you decide to trigger with clapping is up to you. You can choose to activate a specific device, run a program, play a certain sound, shut down your Pi, or anything else that can be triggered by a Python script. For this guide, I'll trigger an LED to illuminate on 2 claps and turn off with 4 claps.
Connect any device you need to trigger to the GPIO pins. I've included a wiring diagram of my LED setup above. Depending on the LED, you may need a resistor.
Restart the Raspberry Pi. Open a terminal or connect to the Raspberry Pi using SSH. Run the clap script with the following command.
Clap! If everything is working, the claps should register. Check the terminal for confirmation. If a clap it detected, the program will print a line of text.
sudo python clap.py
This is your opportunity to fine tune the microphone sensitivity and adjust the clap script settings. Experiment with the threshold limit to help reduce additional noise from detecting as a clap.
We'll be adding the clap script to our crontab bootup list. Open the crontab file to edit with the following command
At the bottom of the file, add the following line.
Save the file and close it. Now your Raspberry Pi will be listening for claps when it starts.
@reboot nohup python clap.py &
Once everything is finalized, restart the Raspberry Pi. This is time for the final test. When it boots, the Pi should launch the clap detection script immediately. After about 10-20 seconds—Clap!
Congratulations. You now have the power to control anything you want with the power of claps!
So you've just finished setting up your Raspberry Pi touchscreen, and it's upside-down.