Wednesday, January 28, 2015

Sensor-based Relay Control (Lights, Heaters, Pumps, etc., etc., etc.)


A lot of automation centres around some incredibly simple control - using a sensor to turn on/off a relay. For those who don't know, a relay is one of the most useful electronic components, and can be as simple and satisfying to Arduino-enthusiasts as the first time you get that led to turn on and off (ye old blink sketch)!

A relay is an electromagnetic switch, opening and closing at the behest of a 5V signal from the Arduino, but electrically isolated so that it can be hooked to high-voltage without frying your Arduino. Long story short, used an Arduino to turn on/off something you plug into your wall. In Canada and the US we use 120V AC power in our homes, so whether you want to turn on a light switch, a blender, a coffee pot at a set time, whatever, these are the right tool for the job.

When you buy a relay, you're looking for one that states the voltages it can handle. If you want to control home electronics, you are looking for ones that say something like 125VAC and/or 250VAC. Don't worry if they say 120 VAC or 130VAC, just buy the cheapest ones. Here is a little tip... Electronic components are very sensitive to economies of scale, which means the more of something they make, the cheaper it is. Common sense sure, but what has served me well (mostly) is that if I'm buying a component for a use that others buy them for too (i.e. a relay to turn on/off house power), then the cheaper item is usually just fine. If you're looking at two relays and one is 125VAC for $3 and another is 126.34VAC for $12... get the $3 one!

There are a couple things to note about using relays, and I'll give you the easy to use option, and the harder but still easy way to use them! ;) First the harder way:

Harder (but still easy) method
a diode
Relays operate with a electromagnetic field, so when you send current through it the magnetic switch closes. Alternately, when the magnetic switch opens, it sends current through your device, which can be potentially damaging to the Arduino. A rectifying diode should be used to protect the Arduino (see sketch below). This diode allows current flow in one direction only, so make sure that the stripe is facing the positive (5V) lead.

CAUTION: All relays have a 5V pin, a ground, a higher voltage pin, a normally open (NO) pin, and a normally closed (NC) pin. There are many models out there, and the organization of these pins can be completely different depending on the model. Google the model and check the pin diagram to know which is which!

There are many examples out there that use transistors (switches) to control the relay, and while this doesn't hurt, I think it is a hold-over from non-Arduino use, where you would use a button to control the relay. For our purposes the Arduino acts as the switch, but feel free to use the Arduino to control the transistor if you like.

Easiest method
4 relay module
As I stated earlier, economies of scale can work in our favour. Available very cheaply online (eBay), you can get modules with one, two, four, six, eight, or more relays on them, for less than a single relay at your neighbourhood store! Honestly, these are the way to go, and you can reuse them over and over. These modules have the transistor, the diode, and an LED to tell you when they're on or off. They have pins that fit female jumper leads for the GND, 5V, and signal wires, and screw terminals for the high voltage pins. Get these!

Wiring
The example below is of a water level sensor, but you could use just about anything (temperature sensor, relative humidity sensor, photoresistor, photodiode, etc.).

As you can see, the water level sensor is connected to ground, 5V, and analog pin 0 (A0). The relay is connected to ground, 5V, and digital pin 4. The relay has two power cables attached to it, one with two prong power, and one with three, so that I can plug it into whichever I choose. Currently I want to use the second relay from the left, so I plugged Arduino pin 4 into the IN2 pin on the relay module. The electrical cable I'm connecting the relay to was cut like this:
Open the cord, cut the positive wire, and stick one end in the high voltage (middle) screw clamp, and the other end in the NC or NO screw clamp. If you want the Arduino to shut something off that is normally on, use NC, but to turn something on that is normally off, use the normally open, NO.
Sorry, the yellow pin 4 wire connects to the white IN2 relay wire. Sorry to be confusing, my bad!
Code
I wrote this little program to keep a heavy outflow tank full. Basically, I have a water level sensor, and when the water reaches it, the pump shuts off for 10 seconds, then turns back on.



That's it, hook it up and you're laughing! You can easily change this to a photosensor controlled light, light controlled blinds, dark controlled lights, temperature controlled heaters, etc. Have fun, and let me know if you have any questions.


Monday, January 26, 2015

Making your Raspberry Pi Wireless - Model B/B+

There are three versions of the Raspberry Pi available to date, the A, B, and B+. While there are many small changes, for the purpose of this post I thought I'd highlight the USB ports. The model A has one, the B has two, and the B+ has 4. Since I have a USB mouse and a USB keyboard attached, I've found a workaround for getting wifi on the Raspberry Pi model B. If you came here for help with the model A, I'm sorry, your only hope is a powered USB hub or to be accessing it remotely via SSH. The model B+ has four ports, so just plug your wifi dongle in and follow the last few steps of this tutorial.

What you'll need:

  • Raspberry Pi - model B or B+
  • Ethernet cable to modem
  • USB WiFi dongle (something like this)
Keyboard
To free up one USB port we're going to remove the keyboard (not yet though!). To do this we need to install a virtual keyboard, so that we can use the mouse to type as well. With an ethernet cable connected, open the LXTerminal prompt (or any terminal/command prompt for that matter). in the prompt type:

sudo apt-get install matchbox

To find out more about the Matchbox Virtual Keyboard, visit here.

WiFi
Once you've installed this keyboard, turn off the RPi. Disconnect the keyboard and add the WiFi USB dongle. Restart the RPi. Once the RPi is rebooted, start the WiFi Config application.


You should be confronted with this window.
Photo by Adafruit
Click on the Scan button, and double click your WiFi network when you see it.

Photo by Adafruit
Finally, enter your WiFi network password where it says PSK, and click connect.
Photo by Adafruit
You're done! I would suggest opening the browser and doing a quick search to make sure that it's working correctly. If you want to connect your WiFi via the command line instead, Adafruit has a great tutorial here.



Saturday, January 24, 2015

Setting Up A Raspberry Pi B... again!

I bought my Raspberry Pi years ago. At that time you had to jump through all sorts of hoops to get Raspbian working (a version of linux designed for the Raspberry Pi). I played with it a bit, setting up an SSH session as well as running XBMC (X-Box Media Centre). Life happens and I set it aside until now. It is really my renewed interest in Arduino that is getting me back into these things. Since the old SD card had long ago been cannibalised for something else, I bought a new one and started again. It turns out this was a good decision, as the RPi landscape has changed significantly. There is now a new (and better) site at raspberrypi.org, and most importantly NOOBS. NOOBS, I've learned, stands for New Out Of Box Software and is the software that I never new I always wanted. I'm not a hardcore programmer, having taken a couple classes tops. It is for people like me that NOOBs was made.

What you need:
  • Raspberry Pi
  • USB Mouse
  • USB Keyboard
  • Micro-USB power supply (Get one that has enough power to supply everything)
  • HDMI cable or RCA cable
  • Monitor or TV
  • SD card
  • Computer
Tutorial
I don't want to take the long-winded approach and spell out the entire tutorial when there is a great video now provided by raspberrypi.org here (I've included it below). I will mention that when it is installing you will see a dropdown at the bottom to select your locale. Do this here, so you don't need to do it in the raspi-config page that starts immediately following installation.


Note: The video doesn't go into what to set-up in the raspi-config options that pop-up when NOOBS is installed, so let me take you through this:

1. Expand filesystem - NOTHING will happen if you select this, just a friendly message saying NOOBS already took the liberty.

2. Change User Password - the default password is raspberry, so change it if you want more security.

3. Enable Boot to Desktop/Scratch - There are three options here, the default being booting to the command prompt (console text). The second is to boot to the graphical user interface (GUI), and the third to boot to the Scratch programming environment. I chose boot to GUI, solely because you can always change this option later, and I found myself always typing startx to start the GUI from the command prompt anyway!

4. Internationalisation Options - This is just to set your time options on the RPi. Ignore locale, as you should have selected it in when during the NOOBS installation. You can also select your timezone, and keyboard layout here if you want.

5. Enable Camera - the RPi has a ~$35 camera that you can buy. If you want to enable it, do it here.

6. Add to Rastrack - Rastrack is a map of all registered RPis. If you want to add yours, do it here. You can also skip this step and do it later at rastrack.co.uk. There are A LOT out there!


7. Overclock - This is a personal choice. The major issues with overclocking are overheating and instability. Basically they can reduce the lifespan of your RPi. If you want to know more, here is a great article that tests the RPi at all overclocking options and finds no problems even with the Turbo mode. I would suggest some overclocking, but if you really don't mind a slightly slower speed, there is nothing wrong with not changing it at all!

8. Advanced Options - Just as the title suggests, these options are advanced. Feel free to skip right past them. You may want to go through these to know what options are available, and if you are planning on remotely accessing your RPi at a later time, I would suggest enabling SSH.

9. About raspi-config - Info about this configuration program, but really who reads these things!

If you've made changes, select yes to reboot your system, and then, voila, congratulations!

UPDATE: I was having a lot of problems connecting to the internet, as it would work and then stop. I found somewhere that if your power supply doesn't provide enough current, this can lead to an underpowered ethernet port. I changed my power supply and voila... it connects perfectly.

A little more...
There are tons and tons of RPi projects out there that people have tutorials for, but here are some ideas of what to do now that you have your RPi running.

  • Use it as a media centre with RaspBMC.
  • Use it as a remote server, accessing it over SSH.
  • Create an oldschool gaming box with RetroPie.
  • Use it to program in python!
  • Use it to control things from robots to 3D printers! Many people don't know the RPi has a bunch of general purpose input/output (GPIO) pins you can use!
  • Use it to program Arduino microcontrollers.
  • Use it to program in Mathematica (it comes with a FREE copy!).




Friday, January 23, 2015

Measuring Temperature and Relative Humidity - DHT11/DHT22

The DHTXX (referring to the DHT11 or DHT22) are amazing little sensors, capable of measuring temperature and relative humidity in one tiny inexpensive package. From what I've read about the sensors, the temperature reading is usually pretty close to actual (requiring slight calibration), but the relative humidity reading is way off (some say twice the value it should be). I'll touch on calibrating the temperature reading, and if I can figure it out, I'll go over calibration of relative humidity as well.
The DHT22 can be purchased pretty much everywhere from SparkFun (~$10 USD) to eBay (~$3 CDN). The DHT11 is even more pervasive and inexpensive, at less than $1.50 CDN on eBay.

According to Adafruit, the differences between the devices are:

DHT11
20-80% humidity readings with 5% accuracy
0-50°C temperature readings with 2°C accuracy
1Hz sampling rate (once every second)
smaller than DHT22

DHT22
0-100% humidity readings with 2-5% accuracy
-40-125°C temperature readings with 0.5°C accuracy
0.5Hz sampling rate (once every 2 second)
bigger than DHT11

Deciding between them is up to you. For almost everything 2°C is a good accuracy, as are the temperature and humidity ranges of the DHT11. If you want a less power hungry sensor, the DHT22 is a better all-round device. From now on, I'm just going to refer to them both as DHTXX.

Arduino
I will update this post in the future if I decide to use this sensor with anything other than Arduino, but for now that's what I'm working on.

Wiring
These little sensors have four pins, but you use only three of them (see figure).
The pins are labelled 1-4 with the grating cover facing you. Pin 1 (called VCC) is the power pin, connected to either your 5V or 3.3V power supply. Even if you are running other things off of 5V (LCD screen, motor, etc.), you can connect this to the 3.3V pin. The reason for going lower voltage is two fold. One, the device consumes less power in general (less drain on battery). In fact, if you're using a 9V battery as your power supply, this sensor will then keep going long after things requiring 5V power stop working. Two, the sensor sends a voltage proportional to the temperature or humidity as data (i.e. 0V for 20% humidity, 5V for 80% humidity in the DHT11). Say the sensor can give you a range of 1024 values. How it would do this is to break the 5V up into 1024 values, and these would correspond to readings. Theoretically if you broke 3.3V into 1024 values, the sensor could read smaller changes in readings. This is a general rule for most sensors, but for all intents and purposes, it really doesn't matter which you choose. Keep in mind, that the error is way more than any sensitivity you'll gain, but it's nice to know how to do it.


As you can see above, the wiring is extremely simple. If anyone is interested, I can show you my setup with a 16x2 LCD display as well.


Coding
To start with, you'll have to download the DHTXX library. Here is a link to the one I used from Adafruit's github page or just click here for the direct download (if you trust me ;) ). Download this file to anywhere, and uncompress it if it is in a zip file. Now open the Arduino IDE and go to sketch > import library > add library... select the folder you just uncompressed, and click ok. If you get an error, just change any "-" in the folder name to "_". This is a common github problem, where Arduino IDE doesn't like the automatically generated "-" from github downloads.

Close the Arduino IDE and re-open it (a good practice). Here is my code:



I calibrated my temperature by monitoring the temperature output of the DHTxx with the glass thermometer right beside it. I noticed that my sensor was consistently ~2 degrees C off from the glass thermometer, so I changed my tCorrection value to 2. Each sensor will have a different value, so keep it at 0 until you work it out.

If there are any questions or comments, leave them below and I will try to answer them to the best of my ability!

Sunday, January 18, 2015

Short and sweet.

I've been doing a lot of automation for work lately - so I've been learning as much as I can about Arduino in as little of time as possible.  So far:

  • I have learned how to control motors, sensors, and other generalities with Arduinos (nothing too complex - as of right now seven segment LED displays scare the crap out of me!)
  • I've used three different Arduinos, including the Uno, Mega, and Pro Mini. I have some Nanos on order (because I hate dealing with TTL), and I can tell you right now, ORDER CLONES FROM CHINA!!! Honestly, eBay has been my best friend. Why spend $30+ on an Uno when you can get something identical from China for $4? It just makes sense. If I was getting a Raspberry Pi or something else closed, sure, I'd get it locally, but Arduino is open-source, so any clone is just as good as the original!
  • By all components from China too. I have a steady stream of mailed parts coming in (much to my wife's chagrin), and it is glorious. Also a pittance compared to local shopping.
  • I have also learned that small is good, but more space and less stress is better. I've done the Pro Mini thing, and I'm pretty sure that I did it wrong, but honestly, why not just go bigger anyway?
  • Soldering is both way easier, and waaaayyy harder that you think it should be. Wow, there is learning to be done here!
Thanks for coming to my site, and I should be posting some lovely documentation of projects and failings, so that you can learn, or at least enjoy the stupidity.

Cheers,
sc.