Control Sonoff Switches with Google Home (Part 1)

Getting into home automation doesn’t have to cost a fortune, if you’re willing to do a little bit of work!

Building your own IoT ecosystem will keep you immune from planned obsolescence, disappearing back-end services,  all while minimize vulnerabilities.  In this series, we’re going to show you how to build some devices that will let you say “Hey Google, turn off the lights!”  (Yes, just like Captain Picard from Star Trek, saying “Tea. Earl Grey. Hot.” and having your automated home make it for you, is not an impossibility. )

There are a few components needed to make this work.  The relays and the voice device, mainly, (Google Home, Siri, Alexa, Etc.) I’m starting with Google Home, since that fills an immediate need I have.

You’ll need an Internet-connected server of some sort, with a port open to the world.  A Raspberry Pi is powerful enough for this task.  It can be a remote server, if you like, even an obscure corner of an existing web site—we’ll just need to install a few PHP scripts to serve as webhooks for IFTTT.  If you’re using a Raspberry Pi, you can also host your own MQTT server.  If not, you can use a public one to get started. More on that later. First, let me introduce you to a remarkable bit of kit, the Sonoff!

The Sonoff is an Internet of Things component that you really need to be aware of:

Sold as a “WiFi Smart Switch,” its a nicely-packaged Internet-controlled relay.

Here’s a look inside:


The green terminal blocks at each end are such that you could chop a lamp cord, strip off 1/8″ of insulation, screw them in to the terminal blocks and have an Internet-controlled lamp. The yellow thing is a transformer, which, along with the capacitors and the varistor, form a 3.3v power supply that powers the device. (No USB cables and adapters needed!)

The relay is the black block with a white label, just below “worth” on the Way Cool Beans coaster.  (Way Cool Beans is the coffee shop where we dream up all of this stuff.  It’s a great place to get coffee, they do all their own roasting, by hand, on site and run their web server from a Raspberry Pi inside a glass head. They also host all of our classes. How cool is that?)

Here’s the back of the board:


There’s a couple of things that stand out here.  See those heavy solder traces?  That’s where the housecurrent (mains) power crosses the board.  The upper trace is the neutral and the lower one is the live current.  The two are nicely separated, even to the extent that there is a gap cut into the board, to keep it from shorting out.


It’s important to keep in mind that this board is designed to handle AC voltages that can kill you—never power it it up when it’s outside of its protective housing! (We’ll be programming it later, which requires you to feed it DC 3v with the case off, but that’s safe enough.) Use common sense and have a responsible adult handy, if you don’t happen to be one yet.

In the bottom left, you can see the “squiggle” of the onboard wifi antenna.

So why is this thing so special?  It’s got a built-in ESP8266! That means we can easily reprogram this thing to do all sorts of cool stuff, using open-source code that we can easily inspect and modify!  Here’s a package (Programmed with the Arduino IDE) that I absolutely adore for turning the Sonoff into a really great, easily-configured relay that we can control via MQTT!

There are a bunch of different ways to put your code onto an ESP8266, but by far, the easiest is to use the Arduino’s IDE, or “Integrated Development Environment.” Here’s a tutorial that explains how to install and configure your Arduino Environment. (Scroll down to “Installing and Configuring.”)

You’ll need to get yourself a USB to TTL Serial Adapter if you don’t have one already.  Be sure it’s set to 3.3v when programming ESP8266 devices!

Jonathan at SuperHouseTV on YouTube has an episode where he shows how to flash your own firmware onto the Sonoff.  (Jump to 17:35 to get right to that section, or watch the whole thing, if you have time.) Keep in mind that we’ll be flashing a different package onto the Sonoff.

OK – That’s going to do it for the first part of this tutorial.

Build a Raspberry Pi FM Radio Station

Is there anything the Raspberry Pi can’t do?

I came across a project that lets you turn your trusty Raspberry Pi into an honest-to-goodness FM broadcasting device that will transmit up to a hundred meters, with the only modification being the addition of a single wire to a GPIO pin as an antenna.

As a caveat, let me tell you that I have not yet made a functioning radio transmitter, but I’ll be building this as I write this blog post up, so, in a way, we’ll be doing this together.(Update: It works!)

(The funny thing is, the biggest problem I have with this is the lack of a radio receiver to test with.   I’m on vacation as I write this, literally in the jungles of Costa Rica.  I have my iPad and keyboard, my little Bluetooth speaker and of course my RasPi, but no radio.  I’ll try to track one down.)

I’ll be doing all of this on a Raspberry Pi (3 in my case, but that probably doesn’t matter much,) using Raspbian Linux, though that, too, probably doesn’t matter, as long as you have Python and some GPIO pins.

(Edit: It turns out that the Pi 3 does not work with the original software, but I’ve found an alternate that does, so I’ll leave what I wrote below, but strike it out.)

Ok, the first thing we do is open up a terminal and get the software we need.  In your terminal, type:

sudo apt-get install -y wget

(Just making sure you have ‘wget’ to grab files from the Internet. It will probably tell you that you already have the latest version)
Ok, that’s set, let’s create a place for our project.

cd #change to your home directory

mkdir projects

cd projects

mkdir pirateradio #get it? Pi-rate Radio?

cd pirateradio

wget http://omattos.com/pifm.tar.gz

tar -zxvf pi fm.tar.gz # uncompress the archive

So it turns out there’s a hardware difference between the Pi3 and earlier hardware, so the software package we found initially won’t work, but there’s an alternative.

Open a terminal and go to your projects directory:

cd ~/projects

(If you get a ‘not found’ error, create it with “mkdir ~/projects” and then cd into it.)

Let’s go get the source code for the project from Github, using the ‘git’ command in the terminal:

git clone https://github.com/markondej/fm_transmitter.git
cd fm_transmitter

Now we’ll make sure we have the programs we need to build the project:

sudo apt-get install make gcc g++

That will run for a bit as it installs. Finally, we run “make” to build everything:

make

Check the output of ‘make’for errors. There shouldn’t be any, hopefully. If it looks good, it’s time to test it out.
We’ll need an antenna. Ideally, it should be about 27 inches, but one of about 8 inches will do as well. Connect it to GPIO 4 on your breadboard, which should be the 4th pin down from the top, on the left side, if you are using a ‘Pi Cobbler’ and ribbon cable to connect your breadboard. The other end of the wire doesn’t get connected to anything, though you might want to pinit up, or drape it over something, to give it some height.
Next, go find yourself an FM radio and tune it to 97.3 FM.
(Don’t worry, you shouldn’t be hearing anything yet.)
Back in the terminal, type:

cd ~/projects/fm_transmitter

(Just to make sure you’re in the right place.)
Now, type:

sudo ./fm_transmitter -f 97.3 -r star_wars.wav

You should be hearing the theme to Star Wars now! You’re broadcasting!

If your radio is portable, you can now test how far your signal will reach. Let me know below how well it works!

A Morse Code Application for MQTT

1878 Bunnell Telegraph Set

[Github Repo of the Code – see makermorse.py for this script.]

Telegraphy and Morse Code were the first instantaneous long distance form of communication.  Invented in 1844, for the first time, you could communicate in real time with someone you could neither see nor hear.

Telegraphy was huge.  It was the Internet of its day.  But the truth is, it was actually pretty simple:

A telegraph is something you can build in an afternoon.  The basic principle is electro-magnetism.  If you wrap wire around an iron nail, it becomes a magnet when you run electricity through it.

A telegraph sounder like the one below works by becoming magnetic electrically, which causes a spring-loaded tapper to click against it audibly.

1878 Bunnell Telegraph Set
1878 Bunnell Telegraph Set

In the age of Internet communications, this may all seem obsolete, but there are thousands of people around the world who still communicate via Morse code, primarily over radio.  These amateur radio operators, or HAMs, as they are called, don’t need Internet to communicate around the world, so they become of vital importance in times of natural disaster, or any time other forms of communication don’t work, both with voice radio and Morse Code.

In the photo is a pair of telegraph stations manufactured by J. H. Bunnell & Co., in 1878.

Now, many people would put something like that in a nice display case and never play with it, but where’s the fun in that?

Raspberry Pi to the rescue!

The Raspberry Pi has a bank of pins known as General Purpose Input/Output (GPIO) pins that we can use to send a bit of electricity to light up an LED.  It’s not much, only around 3 volts, but we thought it might be just enough to make the sounder click.  With careful adjustment of the sounder’s springs and set screws, we were able to get a good click.

With that first test out of the way, it’s time to write some code!

I started, as all good programmers do, by Googling for some code to steal borrow to save me some of the heavy lifting.  I came across a tutorial from Cambridge University in England.  Linked from that was a Python script that would get us started.

What this script does is ask you to type something and hit enter, then it blinks it out as code on an LED.  That’s close, but to make this interesting, let’s get it hooked up to the Internet, so we can receive Morse messages from anywhere in the world!

MQTT is a server protocol that’s a lot of fun to play with.  It’s a simple way to send messages from one device to any number of other devices.  You can also do a kind of chat with it, since it’s so fast and simple.

Let’s go get the code!  On your Pi, open the terminal.

Pi Terminal
Type the following commands:


cd

This command takes you to your home directory. It’s a good place to work. Next, we’re going to go grab the code from Github:


git clone https://github.com/jimoconnell/electrobrain.git

You should see output that looks like this:

pi_s_X_desktop__jims3_1_
 Type
cd electrobrain

to change to the project’s directory. Next, type

idle ~/electrobrain/makermorse.py

to open the program in the Idle Python Editor:

Idle

Once you have the project open in Idle, try running it by hitting the F5 key on your keyboard, or by clicking “Run > Run Module” with your mouse.

You may get an error.  That’s OK, it’s probably just a missing library.  Probably the MQTT library we use.  To install Python libraries, we use a program called “pip”.  First, let’s make sure we have pip.  We ask Linux if it knows pip:

which pip

It should come back with:

/usr/bin/pip

If you just get a blank line when you hit enter, it means it isn’t installed.  Let’s install it!

sudo apt-get update
sudo apt-get install -y python-pip

OK, pip should be installed now.  We should only need to do that once.

OK, now type:

sudo pip install paho-mqtt

Now try running the script again from Idle. If everything is working, it will say:

Connected to:
     iot.eclipse.org:/test/abcd
with result code: 0

If you get that, pat yourself on the back.  (Seriously.  You’ve actually accomplished quite a bit.)

 

Now it’s time to hook something up to the Pi’s GPIO.  In the program, I’ve specified pin 25 as the one that will turn on.  Below is a diagram of the pins on a Raspberry Pi 3.  The ones on the right are on the outside edge of the board.

pi3_gpio

Get yourself your little breadboard, a resistor (220 Ohm) and an LED.  Hook it up like this diagram:

Pin25LED

Now go back to Idle and run the program again.  It should be listening, ready to blink out your code, but it’s not likely that anyone is sending a message to that channel.  Let’s go send some data!

Open a new terminal and type:

sudo apt-get update
sudo apt-get install -y mosquitto-clients

When that’s finished, we’re ready to send!

mosquitto_pub -h "iot.eclipse.org" -t "test/abcd" -m "What Hath God Wrought!"

Why “What Hath God Wrought!”?  Well, as it turns out, that was the first message sent by inventor Samuel F.B. Morse on May 24, 1844.

Did it work? (If it didn’t, feel free to leave a comment below.)

If so, try this:

mosquitto_pub -h "iot.eclipse.org" -t "test/abcd" -l

Then type one message per line and hit enter.  Each line should be sent to your LED as Morse Code!

Raspberry Pi

Raspberry_Pi_3_Model_B
raspberry-pi-572481_1920
The Raspberry Pi is what’s known as a Single Board Computer. It’s small enough to fit it in the palm of your hand, weighs almost nothing, costs around $35, but is a real, full computer, capable of serving as a workstation, a server, a media center or the heart of an automation system.

One of the things that makes this a great board for makers is the bank of pins along one side, known as General Purpose Input Output, or GPIO pins. The beauty of these pins lie in their simplicity—they’re simple pins that you can read from or control. For example, you can connect a simple pushbutton to two of the pins, then write some code to do something in response to it.
You can use a couple of other pins as an output. The most basic example lights up an LED, but lighting a simple LED is essentially no different than firing a relay that can turn on a light in your house, or a machine in your factory or ring an alarm bell.

We’ll be doing a lot with Raspberry Pi, so you can find all of the projects in our Raspberry Pi category.

Electrobrain

Get the Code on Github

Electrobrain

Introduction

I’ve been leading a workshop on beginning programming, Rasperry Pi using Python, and Arduino. The ages of the participants has ranged from 8 years old, (he’s 9 now,) to adult. This project aims to be a set of programs that are simple, but not simplistic, that do interesting things with the Pi and especially its GPIO pins.

The original program in this group is a status indicator that I made for my RPi3, which lives under a glass dome,http://imgur.com/3HmyNV5 as well as for the web server of waycoolbeans.com, which lives in a glass head.

I’ve also added a few other python scripts that explore the GPIO output pins. Throughout, I use Broadcom numbering in my code. You’ll see it declared as: GPIO.setmode(GPIO.BCM)

led.py

Usage:

From a command line, run the following command:

python led.py

(May be called “_led.py” in the repository. It can be safely renamed or run as is.)

Script details

A python script to creatively illuminate “LED copper wire” lights using the Raspberry Pi’s PWM GPIO pins. (As the Pi will live inside a head-shaped glass jar, it got the name “electrobrain”) Quick and crappy video may be available herebut I’m not sure if my Facebook settings will allow you to see it. image I’m starting out with a script by Alex Eames (http://RasPi.tv) that I found for working with PWM on the Raspberry Pi see: http://RasPi.tv/2013/how-to-use-soft-pwm-in-rpi-gpio-pt-2-led-dimming-and-motor-speed-control The script is a simple way to incrementally dim and brighten an LED that’s attached to (and powered by)the Pi’s PWM-capable GPIO pins.

The original demo I saw used a simple LED, but I recently happened upon some “LED Copper Wire” strings in a shop and bought them on impulse, knowing I might do something cool with them. They’re made from a pair of very thin strands of varnished wire with tiny surface-mount LEDs attached every few inches, with a blob of some sort of resin covering each LED, which both protects the LED and acts like a diffuser. The strings can be cut to desired lengths.

Strobing the LED strands has a very pleasing effect. The wires have just a bit of stiffness, so they are easy to form and keep their shape a bit.

The glass head we are using is the kind commonly used as a hat stand or for sunglasses. A quick eBay search is here.

The goal of this project is to combine several strands of lights to make a passive informational display. So far, I’ve gotten it to watch system load and have the lights go nuts when the load gets high.

morse_code.py

Usage:

From a command line, run the following command:

python morse_code.py

Script details

DJ, our 9 year old inventor and I both have a certain fascination with telegraphy and morse code, so I found a script from Cambridge University that converts text to code, then blinks out the message in Morse.

The original is here And is licensed under a Creative Commons 3 Share Alike license.

This script, when run, simply prompts the user for a string of text, thich it then flashes out on a GPIO pin.

MessageBlinker.py

Usage:

From a command line, run the following command:

python MessageBlinker.py

Script details

This script is a bit different—it listens to an MQTT server for an incoming message on the topic you specify at runtime. When it receives a message, it does a triple-blink on two GPIO pins (BCM 24 & 25) and prints out the message to the terminal:

(The first time you run it, you'll first want to install the MQTT python library with:

`sudo pip install paho-mqtt`

That's a one-time operation.)

python MessageBlinker.py

Connected with result code 0

Type a topic/channel:

test/abcd (<– Your input)

At this point, you can open another terminal, even on a different machine and install some MQTT tools:

sudo apt-get install -y mosquitto-clients

Then try:

mosquitto_pub -h iot.eclipse.org -t "test/abcd" -m "Hello World"

(This uses a public MQTT server located at iot.eclipse.org.)