Tuesday, September 27, 2016

Raspberry Pi vs Arduino

Oh My!  It has been over 4 months since my last post and some readers may be thinking that I have fallen off the planet. Not quite, but I have been very involved otherwise. Real life is intruding a lot lately and most of my hobby time has been absorbed in supporting the local maker group with teaching robotics to kids.

The robotics has gotten me very involved using Arduino systems which I had little experience with previously. That got me to thinking that a comparison of Arduino to Raspberry Pi would be good at this point.

Microcontroller vs General Purpose Computer

This is the big difference in the two. The Pi is a fully fledged general purpose computer capable of performing most of the tasks that a PC performs. It has a complete operating system, much more memory, a storage device, and a monitor and USB devices are supported. The Pi can easily multitask, running several programs at once. It also has excellent networking support, both wired and wireless.

The Arduino is a microcontroller. It has only a small amount of memory (2K RAM and 32K Flash) and runs a single program. This allows it to provide true real-time response. There is no USB support and adding networking is difficult and very limited. The advantage is that it starts up as soon as power is supplied and won’t be corrupted if power is lost. It also uses far less power and can easily run on batteries. An Arduino will happily run on 7-12 volts while the Pi must have a regulated 5V supply.

GPIO Capabilities

This is where the Arduino really shines. The Raspberry Pi provides 28 GPIO pins, but only one that provides PWM output and none that provide analog input. The typical Arduino also has 28 GPIO pins, but six of those can provide PWM output and another six can be analog inputs as well.

The Pi provides RS-232 as well as I2C, SPI, and 1-wire buses. The Arduino supports these as well.

Form Factors
Example Arduino Boards

If we ignore the original version of the Pi (which I tend to do now) there are only two form factors available – the model 2 and the zero.  The Arduino, however, is open-source, and comes in many sizes. The Uno is by far the most common, but my preferred version is the nano. I have also become quite fond of the ESP8226-01 Arduino compatible board. It may only have 2 GPIO pins, but it is extremely cheap, low power, and has built in wifi. I am starting to use it for IoT projects with great success.

Which to Choose

There is a fair amount of overlap in the capabilities of both systems, so many tasks could be performed by either device. However, there are some things that at best done with one or the other.

If you need:

  • More than 2KB of RAM
  • A very large program or multiple programs
  • A network interface that can handle multiple clients or support more than one protocol
Then you should use a Raspberry Pi.

If you need:

  • True real-time response to inputs
  • Analog inputs 
  • PWM output for motors or servos 
  • Extremely low cost solution
  • Battery powered

Then you should use an Arduino.

Yes, you can get analog input and PWM output on a raspberry Pi, but it requires additional hardware, which adds to the cost and complexity.

Sometimes you need the best of both worlds and will use a Pi and and Arduino. I have done this on one commercial project already and it worked very well.

Friday, May 6, 2016

Kano Kit

I recently received a Raspberry Pi 3 kit from Kano (kano.me) and thought I should give it a review.
The kit includes:
      ●  Raspberry Pi model 3
      ●  8GB microSD card preloaded with Kano OS, projects and games
      ●  Wireless keyboard with touchpad
      ●  Case with built-in speaker and LEDs
      ●  HDMI cable 
      ●  Power supply and cable
      ●  Wifi adapter
      ●  Illustrated user guide with stencils and stickers

The cost is $150 and as you would expect for that price, the quality is very good. I especially like the keyboard. Since this was a v3 Pi, the Wifi adapter was redundant, but that's OK - it will get used on another system. The documentation provides a detailed and illustrated, step by step guide to setting up the system, It is suitable for a very young user and that is obviously the target audience for this kit.

The cover to the case has a small speaker that doesn't appear to be amplified. There are, however, a couple of PCA9685 chips that are connected to the I2C bus and allow control of the LEDs using PWM. I will create some code to experiment with these and see what they're capable of. It would be really nice if the LEDs were RGB, but they appear to be simple blue LEDs.

Monday, February 29, 2016

Hot Tub Controller Details

By popular demand - some more details about my Hot Tub Controller project.

See the post about my Hot Tub Controller.

Controller Source Code
Can be found on github - https://github.com/tedhale/hottub.git
You can pull it from this address using the git command, or just go to this address and click the "Download Zip" button.

[Add web interface source files]

Partial parts list:
I will update this as I dig up the details for more of the parts I used.

Waterproof Case with clear cover - https://www.adafruit.com/products/905

7-Segment LCD (I2C bus) - https://www.adafruit.com/products/761
There are many colors and a couple sizes

Pushbuttons  - https://www.adafruit.com/products/481
Several colors available. They don't call these weatherproof but they seem to be pretty weather tolerant.

30A Relay (5V control) - http://www.mouser.com/Search/ProductDetail.aspx?R=JTN1AS-TMP-F-DC5V

10A Relay (5V control) - http://www.mouser.com/Search/ProductDetail.aspx?R=G5CA-1A-TP-E_DC5

Waterproof Enclosure - http://www.mouser.com/Search/ProductDetail.aspx?R=1554E2GY
for relays inside hot tub

Cable Gland (for running cable into waterproof box) - https://www.adafruit.com/products/761

2n2222 transistors

Terminal Blocks

Perf board

40 pin GPIO connector - https://www.adafruit.com/products/1979

The Raspberry Pi version 3 is now Available

The latest version of the Pi is out and as expected, it has a faster CPU. Version 2 had a 900MHz Cortex-A7 chip. Version 3 has a 1.2GHz Cortex-A53. Still quad core and a little faster, but the big difference is that the A53 is a 64-bit processor where the A7 was 32-bit. We will have to wait for an OS upgrade to take advantage of that, but I doubt having 64-bit will make much difference for most applications.

The really great upgrade is that version 3 has built in wifi (802.11n) and Bluetooth.

I should be receiving one shortly and will let you know what I do with it.

Here is some information provided by RS-Components, a great source for all things Pi.

How to set up your Raspberry Pi 3

Comparison of Raspberry Pi 3 and the Raspberry Pi 2

Fancy another slice of pi? Find out more about the Raspberry Pi 3

Tuesday, February 2, 2016

Improved Hot Tub Controller

Hot Tub Controller Circuit Board
The original version of my hot tub controller starting having some problems which ended up being caused by an animal chewing through the control cables. I never liked having that huge bundle of cables running all the way across the back of the house, so I now have a new controller in a waterproof enclosure mounted right next to the hot tub.

The controller is built to mount on top of a Raspberry Pi and does the following:
   ●  Monitor the water temperature
   ●  Turn a circulation pump and heater on to heat the water as needed
   ●  Respond to buttons that increase/decrease the desired temperature
   ●  Respond to buttons that turn the water jets on and off
   ●  Display the current temperature
   ●  Detect various failure modes and place system in safe mode
   ●  Listen for commands from a smart phone app to control hot tub
   ●  Upload data periodically to an Internet of Things service

Temperature monitoring is performed by a waterproof DS18B20 from Adafruit. It uses a simple 1-wire bus to read the data.

The display, also from Adafruit, is a 7-segment LED display and is controlled using an I2C bus.

The device is powered by a 24V DC power supply since the relays on the hot tub are controlled by a 24V signal. A 5V step down regulator provides power to the Raspberry Pi.

Relay Control with LED Indicator
Transistors are used to control the relays and screw terminals provide the connections for all the wires.

The push buttons are connected to GPIO inputs which drive interrupts. These require "debounce" conditioning and this is explained in this post.

Smart Phone app for Hot Tub

The Internet of Things support is using ThingSpeak and the method is described in this post. You can see the live data at this URL.

The system also listens on a network socket for incoming commands from a smart phone app that allows me to monitor and control the hot tub remotely. It's actually not an app, rather just a web page designed for a mobile screen. This way it can easily be used by my Android, my wife or son's iPhone, or from any web browser.

Here is a video showing the completed controller in action. 

And, yes, I really do keep my hot tub that hot. One advantage of making my own controller is that I am not limited to 104 degrees max.

Friday, November 20, 2015

ThingSpeak API for Internet of Things

There is much hype about the "Internet of Things" and the Raspberry Pi is increasingly used as an IoT controller. To describe it simply - if you have a web site accessible from anywhere that displays data from a device and/or allows control of  that device - then you are part of the Internet of Things.

I have a smart thermostat that allows me to control my heating and cooling system remotely from a smart phone app. This is one of the most commonly used IoT devices. I also have created web interfaces to some of the Raspberry Pi controlled devices in my home - alarm system, lights, sprinklers, hot tub, weather station, security cameras.

I programmed these web interfaces myself, but there are much easier ways that are actually more secure, and these use the services that support the Internet of Things. One of the easiest to use is ThingSpeak.com. Here are the steps to use this service.

Go to the ThingSpeak web site and click on "Get Started." Click on "Sign Up" to create an account and then log in. Now you can create a new "Channel" which includes 1 to 8 fields of data. Once created, the channel is assigned an API_Key which is required to update the channel. You can see this value by clicking on the "API Keys" tab.

I have created a channel named "Example" with a single data field. Data can be uploaded to this field by using the following URL:


(Yes, that is the actual API key. Feel free to post your own values, but try to keep them between 1-1000 so the chart is usable.)

You can view the public view here:  https://thingspeak.com/channels/67033

Note that you can only update once per minute using this method.

Examples in a couple dozen languages, including C and Python are available here:

Here is an example of real data - temperature and fermentation rate from my home-brewing system.

I decided to create my own API since I had all the necessary code already. This API requires the CURL library to handle the web access. To install this:
sudo apt-get update
sudo apt-get install libcurl4-openssl-dev

Here is the API that I created for updating two fields.
   Filename:   thingspeak.c
   send data to ThingSpeak IoT server
   Uses libcurl to send the data via HTTP
  13-Nov-2015   Ted Hale  created


/* system includes */
#include <stdio.h>
#include <stdlib.h>  
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include <curl/curl.h>

// Note: this function can be replaced with printf if you like.
void Log(char *format, ... );

#define TRUE 1

// the URL structure to update ThingSpeak
// https://api.thingspeak.com/update?api_key=YOUR_CHANNEL_API_KEY&field1=7
char *URLtemplate = "https://api.thingspeak.com/update?api_key=%s&%s=%s&%s=%s";

// structure used by the libcurl write callback function
struct url_data {
    size_t size;
    char* data;
// write callback function needed by libCurl
size_t write_data(void *ptr, size_t size, size_t nmemb, struct url_data *data) {
    size_t index = data->size;
    size_t n = (size * nmemb);
    char* tmp;

    data->size += (size * nmemb);
    tmp = realloc(data->data, data->size + 1); /* +1 for '\0' */

    if(tmp) {
        data->data = tmp;
    } else {
        if(data->data) {
        Log("wuthread> write_data Failed to allocate memory.\n");
        return 0;

    memcpy((data->data + index), ptr, n);
    data->data[data->size] = '\0';

    return size * nmemb;

// upload data to ThingSpeak
int UpdateThingSpeak(char *api_key, char *f1, char *v1, char *f2, char *v2)
 int   error = 1;
 time_t   now;
 struct tm  *dt;
 char   url[256];
 CURL  *curl;
 CURLcode res;
 struct url_data response;
 dt = gmtime(&now);
 // build the URL string
 snprintf(url, sizeof(url)-1, URLtemplate, api_key, f1, v1, f2, v2);
 // guarantee null termination of string
 url[sizeof(url)-1] = 0;
 Log("UpdateThingSpeak> send: [%s]",url);
 curl = curl_easy_init();
 if (curl) {
  response.size = 0;
  response.data = malloc(4096); /* reasonable size initial buffer */ 
  response.data[0] = '\0';
  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
  res = curl_easy_perform(curl);
  if(res != CURLE_OK)
   Log("UpdateThingSpeak> curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
   Log("URL is: [%s]",url);
   error = 1;
  } else {
   // ThingSpeak returns "0" for error, else returns sample number
   error = (strcmp(response.data,"0") == 0);
  free (response.data);
 } else {
  Log("UpdateThingSpeak> curl_easy_init failed\n");
  error = 1;
 return error;

Wednesday, November 11, 2015

Improved Alarm/Automation System

A Little History

I have been fascinated (some would say obsessed) with home automation for many years. I even had a paper published on the subject in 1978, so I experimented with many options before the Raspberry Pi came along. My first working system was based on an Atari 400. I then went through several versions based on microprocessors (like an Arduino, but much older and more primitive) but was never happy with their limitations. Eventually I was able to obtain an old PC and use parallel printer ports for digital I/O. I experimented with Linux and Windows versions and found Linux to be much better suited for what is essentially an embedded system.

The Pi Comes Along

Of course, the first project that I took on when I started working with the Raspberry Pi was a replacement for my PC based home alarm and automation system. The requirements were straight-forward:
    ● several inputs for motion detectors and door/window sensors
    ● several relay outputs for control of miscellaneous devices 
    ● serial (RS-232) port for connecting to an X10 interface
    ● socket interface for control from other computers
    ● logic to provide some limited intelligence
I describe this first version in a series of my early blog posts. Look at Sept. and Oct. 2012 to see these.

Time for an Update

Updated Alarm/Automation System
In the several years that I have worked with the Raspberry Pi I have learned a lot about the best way to do some things and applied these lessons to my updated alarm/automation system. I think the most important lesson that I learned was to make things as modular as possible. It is inevitable that I will screw up something and if the project is one large circuit board, then I may well have to scrap it and start over. However, if I break that into several smaller boards, then a screw-up will, at most, cause the rebuild of a single small circuit. Some systems fit this designs method very well while some just can not be broken up. The alarm/automation system fits this method well and consists of the following parts:
    ● Raspberry Pi (of course)
    ● Simple "hat" for the Pi to expose all the buses needed
    ● a relay board (bought, not built)
    ● control board for the relay
    ● control board for digital inputs
Each of these is described below.

The "Bus Hat"

The Bus Hat
In order to connect the various pieces to the Pi, I needed a way to access some of the buses available. I created what I call a "bus hat" to do this. This mounts on top of the Pi and provides access to the following:
    ● the I2C bus
    ● the SPI bus
    ● the 1-Wire bus
    ● RS-232 converted to proper levels
    ● 5V input to power it all
I knew that I would be using 3.3V devices, so I did not include any level converters on the I2C or SPI buses.  I did need proper voltage levels for the RS-232 serial line and that was provided by a MAX3232 chip. 

This is a very simple device since all it really does is connect specific GPIO pins to connectors for the required buses.

Bus Hat Circuit Design
My design for this bus hat is shown here. You may notice that this is a little different than most circuit diagrams you will see. I am a little embarrassed to admit that I use Power Point to create these drawings. I am mostly concerned with how the components will be laid out on the perf board, so I make a perf board grid the background image and place the components onto that and add the wiring. Power Point makes this quick and easy. If you need to make a simple and better looking wiring diagram I recommend the Fritzing app. For real PCB drawings I have used Eagle and PCB Artist.

Relay Board

Relay Board

I decided to buy a relay board online. There are quite a few of these available and the price is hard to beat. You should be able to find an 8 channel board like this for well under $10. There is no way I could even buy the components for that cheap.

Relay Control
Relay Control Circuit

To control the relays I needed 8 GPIO lines. The perfect job for the MCP23008 GPIO extender. This chip connects via I2C (there is also an SPI version) and provides 8 GPIO lines. I set them all as output and connect one to each relay control pin. One thing to be aware of - these relays require more power to operate than the Pi can generally provide. They will appear to work at first but then you try to turn on all 8 relays and the Pi will reboot due to the drop in power. The relay board will provide a pin for connecting external power to prevent this from happening. Since I was using 3.3V on the I2C bus, I added a 5V input to the relay controller to provide this power.

Input Board

Input Board Circuit
The input board provides 16 "contact closure" inputs. In other words, a switch of some kind connects two pins. This is typical of the way that motion detectors and door switches work. The input board has the GPIO pins pulled high and the external device will close a switch to connect the pin to ground.

The circuit uses an opto-isolator (sometimes called an opto-coupler) to provide protection to the GPIO pins. This is prudent since the inputs are connected to wires that run all over my house and anything could happen to put bad voltage onto those lines. I even went as far as having the opto-isolators in sockets so they could easily be replaced if they are blown. That's probably excessive, but it was easy enough to include, so I did.

Again, I used a GPIO extender. This time a MCP23017, which provides 16 GPIO pins with an I2C bus connection. Both of the extender chips I used will default to I2C bus address 0x20, so I set the address pins on this one so that it will appear on the bus at address 0x21. Note that A0 is tied high while A1 and A2 are tied low.

X10 Interface

X10 Interface

I control the X10 devices using a CM11A interface from ActiveHome. These haven't been made for a while now, but are still available on eBay. It connects via a serial port. NOTE: I had to swap send and receive from the original design of the Bus Hat to connect directly to the CM11A.

I have several X10 controllers for lighting as well as several wireless motion detectors that connect to X10 through a bridge device. These are convenient since they don't require running wires. The downside is that they use batteries. Fortunately, they are fairly efficient and only require replacing a few times a year.

Smart Phone Interface

Smart Phone User Interface

What home automation system would be complete without a smart phone app? A web interface is much more universally usable, so I went that route rather than writing a phone app. Besides, I'm an Android guy, but my other half uses an iPhone. I had no desire to go down that rabbit hole.

The web interface was created using Apache, PHP, and the socket interface to the alarm/automation system. The details on that will have to be a post of its own.