Recently I came up with an interesting idea that finally puts to work my old dusty Raspberry Pi: home automation. More specifically, I’d like to control lights and measure current temperature and humidity in my house. Of course, lots of people did it before many times, and there are plenty of resources, tools and libraries that make it extremely easy to achieve this goal; however, they take away from you all the fun of figuring out how things actually work. Another issue is that most of existing tools are written in C, which is unsafe and cryptic. Taking these reasons into account, I decided to write all the code that controls devices from scratch in Rust, and that’s what this article is about.
Preparation and building
Before writing any code, I had to plan what exactly I wanted to control and how. In case of temperature and humidity sensors, there were many choices, but since I didn’t have any specific requirements, I just chose the cheapest and simplest model that was there: DHT-22. It cost around 7 EUR on Amazon and had a simple serial interface.
In case of lights, things were more complex. Since I rented a flat, I couldn’t change how electricity flows into bulbs, therefore I had to decline an idea of controlling ceiling lights. Instead I decided to control only a floor lamp near the couch and Christmas lights that were still hanging above the table. At first I wanted to alter the lamp and lights themselves, but since they were using plain AC power sockets, I decided to go with a “smart socket” solution where the lamp and lights plug into sockets and RPi controls the sockets.
Now, what exactly does it mean “to control power sockets with Raspberry Pi”? RPi can control things through its General Purpose I/O interface aka GPIO; that is, basically, a set of pins on the board which can either input or output 0 or 3.3VDC. The problem is that it can’t be the source of electricity for power sockets because they need 220VAC. Luckily, there are special electric switches, called “relays”, which allow you to control the flow of AC using DC signal. The simplest relay is just a coil which generates magnetic field that controls a switch. I went for this one, though it is possible to spend a bit more money and buy a solid-state relay which does not produce clicking sound when it turns off and on.
Another things which are really handy when working with RPi’s GPIO are breadboard, T-cobbler and multimeter. Breadboard makes it very easy to build circuits; T-cobbler maps GPIO ports into breadboard’s sockets and labels them; multimeter is used to debug GPIO because it measures voltage, current and resistance.
My final shopping list was:
- DHT-22 temperature and humidity sensor (7 EUR)
- 4-channel 5V relay module (10 EUR)
- Breadboard (7 EUR)
- GPIO T-Cobbler for Raspberry Pi (12 EUR)
- Set of jumper wires (7 EUR)
- Set of resistors (9 EUR)
- Couple of power sockets (6 EUR)
- Light switch (2 EUR)
- Copper wires for AC installation, screws, plastic connectors, etc. (10 EUR)
70 EUR in total. Pretty much the cost of two usual “smart” power sockets.
Below is a connection schema for the system:
Thick lines stand for AC current cables, thin ones are for DC current, just like in real life. As you can see, DHT-22 sensor needs a pull-up resistor to keep line high when no communication is in place. AC relay doesn’t need it since it’s mechanical inside and slight noise in a line won’t hurt or falsely trigger it.
Now, when everything is ready, it’s time to figure out how actually RPi can
control things. As I mentioned before, it has a set of special IO pins, called
GPIO. Usually they are accessible through a set of registers in internal memory
of MCU: you write to a specific register to enable selected pin, choose its
operational mode, enable interrupts, etc. Raspbian Linux exposes internal MCU
memory via virtual device
/dev/mem; it’s more convenient, however, to use
/dev/gpiomem for GPIO control because it doesn’t require root privileges.
Memory layout for GPIO can be found in the datasheet of your processor; in case
of my Raspberry Pi 2 Model B, it’s
Implementation of GPIO driver is straightforward: first, it opens
and maps it into RAM using
mmap; then gets access to it whenever it is
required to change operation mode of a pin or communicate through it:
This driver is limited to operating with GPIO using polling only and supporting only 32 out of 54 possible GPIO pins. This is perfectly fine for my purposes though, since it only requires 3 pins: 1 to communicate with DHT-22 and 2 to control relay.
While writing the driver I had a couple of issues that were caused by my
inattention and couldn’t be caught by Rust compiler. The first one was with
memory offsets. In the datasheet they were given for the case when memory is
accessed per byte; in the driver, however, GPIO memory was mapped into a pointer
u32 type and
offset function was used to shift it. Since
implements C-like pointer arithmetic, the memory was actually shifted 4 times
further than it should be. Luckily, it was quickly identified by testing pins
The second issue was even trickier: the driver spontaneously couldn’t open GPIO
memory device. At first I couldn’t find out why it happens: the right privileges
were set and I could open the same device using simple Python script, but not
the driver. I tried cleaning and rebuilding a couple of times and suddenly it
worked. The issue was in careless usage of Rust’s
as_ptr method for making
a pointer to a constant string containing path to the device. In contrast to
C strings, Rust strings are not null-terminated, thus depending on how compiler
packed string constants, I sometimes ended up with a path to a non-existent
&'static str into
std::ffi::CString saved the day.
Communicating with a sensor
Let’s move on to the sensor. DHT-22 implements a dead simple serial
communication protocol: according to its
MCU should pull low corresponding data pin, wait for the acknowledge from
a sensor, and then listen for the pulses sent by it. 40 bits of data should be
transferred: 16 of humidity, 16 of temperature and 8 bit of checksum. The key
thing here is time. If the driver is too late to read sensor’s input, it may end
up with incomplete or incorrect data, thus it should somehow keep running for
the time of transmission. To prevent driver’s process from being suspended by
the system during that time, it’s necessary to raise its priority and avoid
using functions that give up CPU to another process. The latter requirement
std::thread::sleep is forbidden and should be replaced with a busy
Driver’s implementation consists of
dht22::read() function and does the
following: it pulls the pin high for half a second, in case it was low after
previous transmission; then pulls the pin low for 20 msec, waits for sensor to
respond with a low signal, and reads the pulses.
0 is sent as a short high
1 as a long high pulse. Between each pair of data pulses sensor sends
low pulses that should be used as a reference time to separate short and long
high pulses. When data is read, driver checks its consistency, processes it and
returns to a user.
Exposing everything in a web interface
Last but not least is how to use the things written above. I chose to make a simple one-page web-server and run it on RPi; here’s how it looks like:
I don’t think that code for it is worth posting here, but what’s worth is a framework that made it so simple. There are plenty of Rust web frameworks, but I found Rocket to be the most documented and easy-to-use of them all.
This small project was real fun! I learned a lot about electricity, circuits, MCUs and inter-device communication. I also wrote some more or less real-world Rust, and was really surprised how simple it was to program in it and how well it worked on RPi.