Turning USB Devices On and Off with a Relay Using Raspberry Pi

Raspberry-Pi
2014-05-31 12:29 (10 years ago) ytyng

I wanted to use external speakers to play music with my Raspberry Pi, but I thought it would be a waste of energy to keep the speakers powered on all the time. So, I decided to create a system that turns the power on only when needed.

You can easily achieve this with a single relay. The relay is controlled by the GPIO.

Wiring Diagram


Normally, the Raspberry Pi gets its 5V power from the Micro USB port, but I read that there is a regulator in place, and the current from the +5V pin of the GPIO is quite weak (700mA?). Conversely, the +5V of pin 2 on the GPIO can also be used as a power input, so I tried supplying power from there. However, since this bypasses the regulator, you need to be careful about overcurrent.

When I tried it, the wiring became very neat. It’s a good setup.


Test Video

From ipython, I turned GPIO7 ON to power the USB-powered speakers.


Code

Just before playing the audio, turn GPIO7 ON, and turn it OFF once the playback is finished. Here’s how it looks in a bash script.

#!/bin/bash
gpio mode 7 out
gpio write 7 1
mpg321 "$@"
gpio write 7 0

(You can install the gpio command from here.
You can install mpg321 with sudo apt-get install mpg321.)

Save this script with a name like play-music and make sure the path is set.

$ play-music music/xxxx.mp3

This will automatically turn the speakers ON → play → turn the speakers OFF.

This time, I used a physical switch relay, so there’s a "click" noise when turning the power ON/OFF. While this may not be noticeable if enclosed in a case, using a solid-state relay can help reduce the noise.

Current rating: 5
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011