Raspberry PI: A remote controlled relay using SMS messages

Hi my dear female & male microelectronics geeks!

This time I will build an interesting object: a remote controlled relay using a Raspberry PI as SMS messages receiver and parser (and -obviously- as relay phisical controller).

I will use this stand-alone (sub)system with my meteo station system. If you want to read more about the meteo station, in the previous posts I described the I2C communication between the acquisition board (Arduino UNO) and the station controller, the model (hardware and software) of the acquisition board.
In this post we will PLAY WITH THE HIGH VOLTAGE, so… pay attention,please. 🙂
Rememeber that when we use the high voltage..the only safe thing you can consider is the GROUND, so… again, pay attention please! 🙂

Why high voltage? Well… it’s simple.
Because I would like to power on/off my meteo station via remote commands (since at the end of this “technical adventure” I will install my meteo station in a very beautiful place, but a little far from my home).
In order to do that, I would like to use a simple (sub)system, consisting of one Raspberry PI (for this purpose you can use also the less expensive model A, but in my project I will use again a Model B.Yeah, you know I love this board …but I assure you I’m preparing some surprise also with my new Olinuxino A20! 😉 ), one Itead 2-way Relay Module (bought as usual from Robot Italy), one multiple power connector bought (…from my father) at the cheapest general-purpose shop in my little city (it is called “Risparmio Casa”, in English it should be something like “Savings -for the- House”), and, last but not least, one USB 3G dongle (I used an old Huawey K3715 compatible E169, marketed by Vodafone, with a TIM sim inside) which I will use as “mobile phone” in order to receive SMS messages.

In this case I will not use it as “internet 3G dongle” because:

  1.  I want to command the power on/off even if the 3G signal is not present
  2.  Sending single SMS messages is cheaper than a flat 3G connection (in Italy, I don’t know if the situation is the same in other countries)
  3. The power consuption is lower if the dongle is not connected to 3G

Ok, let’s go with the experiment! 😉

Commanding the relay using Python

I took the inspiration for this step , from this post of the italian blog “Raspibo.org”
Let’s install something!

#sudo apt-get update
#sudo apt-get install python-rpi.gpio
#sudo apt-get install python3-rpi.gpio

Well, after this you can connect Raspberry and the Itead relay module .

GPIO18 will be used as command signal for relay, plus you will connect the Raspberry 5V/GND pins to the module Vcc/Gnd pins. This is the Fritzing schema:

Arduino rele controller_bb

Then you can modify the multiple power connector in the following mode: remove a part of external protection from the cable (pay attention in this operation, please!), then cut the 220V brown wire and connect the terminals to COM and NO pins of the relay module. NC shall be not connected. Blue and yellow/green wires shall arrive directly to the power connector.

Ok, now we can test the relay (with the 220V power NOT connected, for the moment).

Firstly we must write a script in order to initialize to LOW the GPIO18 pin at Raspberry startup. The script will be:

#!/usr/bin/env python
import Rpi.GPIO as GPIO
GPIO.setup(18, GPIO.OUT, initial=GPIO.LOW)

 Then, you can save it where you want, and you must to change the mode in order to declare the script as executable:

#chmod +x initialize_GPIO18_script.py

…But the very important thing is to add the following line to /etc/rc.local:

sudo /path_to_initialize_GPIO18_script/initialize_GPIO18_script.py

and execute a reboot of the board.

After the reboot, the GPIO18 will be correctly initialized, so you could test the relay functionality. In order to close the relay you will write the following script:

#!/usr/bin/env python
import Rpi.GPIO as GPIO
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)

and in order to open the relay you will write the following script:

#!/usr/bin/env python
import Rpi.GPIO as GPIO
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.LOW)

Note that all the executions of GPIO-related scripts will be possible only using “sudo” before the commands.

Well… if your scripts work well, open the relay (=led powered off on the Itead module): this is the safer state.

Now it’s the moment to connect the multiple power connector to the 220Volts plug on the wall….but, REMEMBER THAT THIS OPERATION CAN BE DANGEROUS AND YOU MUST USE ALL AVAILABLE PROTECTIONS in order to reduce risks. Remember that you are now playing with HIGH VOLTAGE, so PAY ATTENTION.

To test the relay behavior now you connect a lamp (or something else) to the multiple power connector and use the above scripts to power on/off it.

…..Aufffff, I hope all worked well, and you haven’t burnt your home! 😉

Connecting the USB 3G dongle and configuring it in order to receive (and send) SMS messages

Ok, now a little more relaxed activity: we must receive SMS messages using a 3G dongle and we must to parse them in order to command the relay.

I’ve done the following steps in order to make all things work without problems (after maaaaaaaany experiments, overall tied to the files/directories permissions and to users execution policies…. 😦 ).

1. Power Off your Raspberry
2. Connect the USB 3G dongle, then power on the Raspberry. My dongle is correctly recognized by Raspbian as 3G modem on /dev/ttyUSB0 [IMPORTANT NOTE: some USB dongle -i.e. Huawey E1820- is recognized by Raspian as CD-ROM… so you should use some “howto” regarding the utility usbmodeswitch in order to correctly recognize the modem inside the dongle]
3. Install gammu and gammu-smsd. Gammu is used to send SMS message, gammu-smsd is the daemon used to receive the SMS.

#sudo apt-get install gammu 
#sudo apt-get install gammu-smsd

4. Configure the file /etc/gammu-smsdrc in the following way:

port = /dev/ttyUSB0
connection= at19200
logfile = /home/pi/log-gammu.txt
service = file 
RunOnReceive = sudo /home/pi/Script_relay/sms_relay.py
inboxpath= /home/pi/Script_relay/inbox_sms/

5. Save the file, then add the user “gammu” to “sudoers” group of your Raspberry, using the tool visudo:

#sudo visudo

It will open /etc/sudoers.rc…so you append the following line to the file :


[NOTE: you can report /home/pi/Script_relay/sms_relay.py instead of ALL, for security reasons]

6. Save the file and Reboot you Raspberry. The gammu-smsd daemon starts automatically at the end of boot process.
7. Verify that in /home/pi/gammu-log.txt there arent’t strange errors (tied to communication between Raspi and the dongle). I encountered these errors when I installed gammu-smsd without the dongle already connected. Anyway, in this case you can remove the installation and you can reinstall gammu-smsd:

#sudo apt-get –purge autoremove gammu-smsd
#sudo apt-get gammu-smsd

8. Create the filesystem used by the gammu-smsd configuration:

#mkdir /home/pi/Script_relay
#mkdir /home/pi/Script_relay/inbox_sms
#chmod 777 /home/pi/Script_relay/inbox_sms

[NOTE: I imposed the simple mode 777 in order to permit to “gammu” user to save the SMS messages in this folder -and it’s work-, but you can use some more secure access]

9. Create the code for /home/pi/Script_relay/sms_relay.py in the follwing way:

#!/usr/bin/env python
import Rpi.GPIO as GPIO
import sys
#note we don't initialize the initial value of GPIO18, we use the current status
GPIO.setup(18, GPIO.OUT)
#the filename of the SMS is passed as argument to the script from the RunOnReceive gammu-smsd option 
message=sms_file.read(160) #note that a not-parted SMS can be maximum 160 characters 
if (message.find("poweron")<>-1): 
     GPIO.output(18, GPIO.HIGH) 
elif (message.find("poweroff")<>-1): 
     GPIO.output(18, GPIO.LOW)

That’s all folks!

If all worked correctly, sending now to the dongle telephone number a SMS containing the keyword poweron you will see that the relay will be powered on, and sending an SMS containg the keyword poweroff you will see that the relay will be powered off.

…It’s a magical thing, don’t you think that? 😉


Finally…the complete relay controller

Possible improvements to the project (I give you them as exercises 🙂 )

1. Send a SMS message to a number (it should be the number of the phone which commanded the power on/off)when the relay has been powered on/off. You should modify the sms_relay.py adding a call to the gammu command line tool (find one of the many examples on internet for the usage). Note that the tool must be configured (his configuration file is /home/pi/.gammurc) with the following data:

port = /dev/ttyUSB0
connection= at19200

…But for this functionality there is a little (=big 😦 ) problem: gammu-smsd blocked the /dev/ttyUSB0, so….what could be a possible solution?

2.  Add to the /etc/gammu-smsdrc file one filter in order to accept SMS message only from YOUR phone. This is not difficult, there is a configuration parameter to add in the file (with the “white-listed” numbers)… you can find it in the gammu-smsd user guide! 🙂


Ok boys and girls, today we used the high voltage… you know that for a software and/or microelectronics engineer this is like a bungee-jumping. 😀

So, now I need only a good grappa an an italian horror (or thriller) movie of the ’70-’80 on my television.

Do you like Lucio Fulci movies?

A relaxing movie now...

A relaxing movie now…”The New York ripper” by Lucio Fulci

I know he is very famous all around the world (…except than in Italy 😦 ).

My Fulci preferred movie is “The New York Ripper” (italian title: “Lo Squartatore di New York”)…. I need a very relaxing night, after this dangerous and stressing post! 😉

Bye bye, see you soon!


Arduino and Android devices: the (not so) well known USB connection

Hi boyz and girlz (with the “worm” of embedded development inside! 🙂 ).

This time I would like to talk about a new topic (following an input from SirsLab of University of Siena), tied to the connection via USB between Android phones (or tablets) and Arduino.

The goal is to cerate a master-slave channel on the USB in order to control an Arduino from a Android app. A possible logo for this “experiment” could be the following:

Arduino+androidMhhh…Android hides behind an Arduino. What a strange idea (and what a strange logo—>produced by ML)! 😀

Ok, I say clearly that I don’t like to use an Android phone as Arduino controller, since in my honest opinion writing an Android app in order to use the USB in master mode is not so simple and immediate. I prefer to use a linux single board computer (such as Raspberry PI) to control Arduino, as you can see in my previous post(s): here and here.

But the argument is very exciting and …”I was born ready” (cit. Jack Burton of “Big trouble in Chinatown” movie)! 😉

This is the “hand-made schema” of the complete system at the end of this post (click to view the zoomed image):



First step: verify the Arduino USB connection

Well, for my experiments I used the Arduino Mega ADK board (it has onboard the USB Host Max4321 controller ), but there is another chance: you can use the dear old Arduino Uno with the Arduino USB Host Shield 2.0 from Circuits@Home (or the alternative solution from SparkFun). My Arduino Mega ADK was part of the famous “Arduino on Android Kit” bought from Robot Italy (this has been the Monica gift for my birthday! 😉 ).

In order to verify the USB host capability of the Arduino I connected a USB memory stick to the USB host port, then I downloaded the USB Host Shield 2.0 library and I inserted it in the libraries folder of Arduino IDE.

IMPORTANT ACTION:  I opened the library file settings.h and I  modified the following line (note that the default for the define is =0, meaning that you are using the USB host shield instead Arduino Mega ADK):

#define USE_UHS_MEGA_ADK 1

This step is fundamental (if using Arduino IDE 1.0.5) because otherwise all sketches using USB Host library  will give the error “OSC DID NOT START” at runtime, since the function Usb.Init() will return a -1.

Once saved the modified file, I opened the library example script called USB_desc, and after the succesful compilation and download on the Arduino ADK, I opened the Arduino serial shell at 115200 bps.

The output reported all informations about the USB memory stick (vendor, class, ID etc.).

So, we can conclude that the USB host capability of the Arduino Mega ADK is OK.

…..Pheeew, now I can take a breath (and a break). 🙂


Second step: connect to Arduino an Android phone (or tablet) supporting the “Android Accessory Mode”

This is the hard truth: not all Android devices can enable the “Accessory Mode”, the necessary capability to talk with “accessories” (in our case the Arduino Mega ADK) via the ADK protocol. In these cases only the ADB protocol could be used… but this is another story! 😉

Note that the Accessory Mode is a capability depending on the Android version installed on your phone. 😦

For example,  my old Samsung Galaxy S (GT-I9000) has a too old Android version installed, so, in order to enable the Accessory Mode, I flashed on it the latest version of Cyanogen Mod.

And, at the same time, I had no problem using a Samsung Galaxy Tab 2 with his original firmware….since the Android version is newer and it supports Accessory Mode.

IMPORTANT ACTION: In order to enter automatically in Accessory Mode (if supported by the Android version), the mandatory step is to enable the “USB Debug mode” on the phone.

I opened and compiled the ArduinoBlinkLed  sketch from the ADK examples provided in the USB Host Library.

I powered ON the Arduino and I opened the Arduino shell (…and the encourageant sentence “Android accessory started” appeared ;-)).

Then I connected the Android device to the Arduino host USB. After a moment, the screen of the device reported “Accessory Mode entered” and after this a message appeared on the device requesting to download from internet the Android app associated  to the sketch.

The downloaded app (reported in the Arduino sketch) is http://www.tkjelectronics.dk/uploads/ArduinoBlinkLED.apk, note that I didn’t found the sources for it… 😦

Anyway, starting the downloaded/installed app, a great button appeared on the device screen. And the result of this big effort activity is a little poor, but at the same time it’s very nice: clicking the software button, the Arduino LED 13 (the onboard led) turns ON/OFF!!! Yeahhhhhhhh! 🙂



The code on the Arduino side is (as always) very very very simple. The code on the Andoid side (the app), in order to manage the ADK protocol, in my opinion can be very difficult to be implemented, because it contains some strange instruction and construct.

In which mode I discovered it? Well… studying and compiling in the Android IDE an application similar to the “closed source” one used for my experiment. I found it in the ADK examples from Google Code or around Internet (it is called SkeletonApp) : you can download it from this link. Obviously you should compile this code in the Android IDE Eclipse in order to produce the app (i.e. the .apk file to install on your Android device).

Note that you could modify the ArduinoBlinkLed script in order to download/install from internet your own app modifying the following code:

ADK adk(&Usb, "ML Soft", // Manufacturer Name
              "ArduinoBlinkLED", // Model Name
              "Example sketch for the USB Host Shield", // Description (user-visible string)
              "1.0", // Version
              "http://YOUR_OWN_SITE_ADDRESS/SkeletonApp.apk", // URL (web page to visit if no installed apps support the accessory)
              "123456789"); // Serial Number (optional)

Ok boyz and girlz….this time we produced a very interesting  result. 😉

Now I need a very long time of relax… so I think I will launch a Debian kernel recompilation process (and in the meantime I will drink a good Grappa). 😀

Bye bye!


Olinuxino A20 micro: a new toy in Garretlabs!

…Yeahhhh!!!! 🙂

I’m always happy when my lab “boards family” grows…. and this time I bought a very interesting single board computer from Olimex, a Bulgarian company: one Olinuxino A20 micro (without NAND flash).

This is the toy (photo from Olimex blog):


As usual I bought the board from my favourite online shop: Robot Italy (this is not a commercial spot…but I would like to have some little discount from this company!).

With the board I ordered also the ad-hoc plexiglas box, some 40-pins flat cable (in order to connect some GPIO) and the SATA cable to connect a 2.5” hard disk to the board.

The board arrived in one day with Bartolini express courier (Robot Italy is very fast to ship), and these are my very first impressions about the board:

  1. The packaging is very beautiful (as we say -literally- in Italy: ” also the eye wants his part” 😉 )
  2. The board has a very solid appearance, and it seems very well designed and built
  3. The ad-hoc plexiglass box prefectly fits, and it’s very “chic”  (see point 1)

I downloaded the official Debian image from Olimex, I wrote it on a Kingston microSD (class 4) using the open source Win32 Disk Imager. Note that Olimex recommends to use a class 10 microSD…but I wanted to try with a cheaper choice. 😉

After this, I connected the HDMI cable to my 37” Panasonic TV, I connected to one USB connector the radio transmitter for my wireless cheap Trust keyboard + mouse (only 19 euros… but it’s a very good choice to be used on the sofa in order to seek youtube videos…. with the fingers by the chips and assorted fried food 😀 ) and I powered the board with the miniUSB connector.

Pushed the power ON button, first boot….a moment of real suspence….and all worked correctly!  …YES! 🙂


Ok, I tried some program preinstalled in the Debian image (such as Midori browser) and I noticed that all seems faster than same programs running on the Raspberry PI (ok, I know it’s obvious but I want to evidentiate this concept).

After this first boot I connected a wifi dongle (this dongle from Robot Italy, as usual) to the other USB connector and I rebooted the board.  The dongle is supported by Debian but, after the connection to my home WPA2 protected wifi network, I observed some problem tied to lost ping packets (approx 25% of the total number) .:-(

Mhhhhh… it could be tied to a too high power consuption, so in the next days I will try using a 6-16 volts external power supplier instead the miniUSB source (as recommended by Olimex in the user manual, in order to have the maximum efficiency with external peripherals).

For the moment that’s all, folks. After the first few steps with this board, Olinuxino A20 seems to be a great study opportunity for my natural born curiosity. 🙂

….Bye bye geeks!!!!