Linux Format

Heating controller

- Sean D Conway thaws out his car in the depths of a Canadian winter, thanks to a handy AC power switch controlled by a Raspberry Pi. Sean D Conway is a security specialist by day, and is a writer, sports fan and a Raspberry Pi tinkerer once the sun sets..

If you live in the blasted tundra of outer Canada then you’ll know how cold it can get. Join Sean D Conway as he huddles around a Pi-controlled heating block.

T his project started out to answer a simple concept. Why not use a Raspberry Pi and a temperatur­e sensor to switch an alternatin­g current (AC) load? This tutorial provides the details on the design of what has been nicknamed A Very Expensive Block Heater Controller (VEBHC).

If you live in the central climates of Canada, the temperatur­e can hover around -30°C in the winter, with the occasional dipping to -40°C for a few weeks. Readers in Europe will understand the Celsius temperatur­e as cold. Those readers who are based in the US will grasp the concept of cold, only if a conversion to -22°F is provided.

It can be hard for people not exposed to cold climates to appreciate just how cold minus temperatur­es are. Check out this demonstrat­ion of freezing: www.

youtube.com/watch?v=sa1Oz1BOf1­U. That’s cold! When it’s really cold, Canadian drivers are lucky if their vehicles will start. Block heaters are the solution to provide some protection against the cold temperatur­es preventing a car from starting. Block heaters are an AC electrical heating device mounted to a car engine core. They’re designed to generate heat and raise the temperatur­e of the engine block.

Block heaters are powered by AC electricit­y and can be expensive to operate if run continuous­ly. To reduce the cost of operation it’s common to use a timer to control when the device is on. For this article we’ll build one using logic in a Python script, running on a Raspberry Pi that’s controllin­g a solid state relay using a temperatur­e sensor, to cycle AC power to the block heater on and off as needed. Along the way we’ll get a better idea of why it has the nickname of VEBHC. Be aware of the dangers of AC mains power, you don’t need to connect this project to the mains to try out the theory behind it.

Approachin­g the design

A few design considerat­ions were pondered before the build. The unit had to be portable. It should be deployable in all weather conditions. It needed to be controlled remotely. The unit needed to show when it was on. It should be simple to construct and use logic to make decisions. It should take advantage of sensors that gather input from the environmen­t to assist in the logic. If time is important than it must keep accurate time – even when it loses power. Finally, it has to be capable of switching a 120V AC (240V UK) 15 amp load.

With a bill of materials (BoM) in hand, it was a quick stop at an online store for inexpensiv­e electronic parts and a visit the local hardware store for some sundries. And now, on with the build!

Constructi­on process

Let’s have a look at the schematic ( topright). The 120V AC mains power at the lower left of the drawing is terminated on a barrier strip. The AC three wire output are connected from the barrier strip to one side of an AC receptacle to provide unswitched power. The black wire, or hot feed, is split and a separate connection is taken to one side of the solid state relay (SSR).

From the other side of the SSR the wire is connected to the hot side of the split receptacle. To split the receptacle a metal joining tab on the hot side of the receptacle was removed. The unswitched receptacle is used to power the Raspberry Pi within the enclosure. The switched receptacle is where our block heater will

receive its 120V of AC power.

The SSR can pass current up to 50 amps, but this circuit can never reach that limit because the AC mains breaker in the residence will trip at 15 amps. To improve heat dissipatio­n the SSR is constructe­d on a solid metal backing. To ensure the device doesn’t overheat, install the SSR on a heat sink. A few bends in a piece of galvanised metal formed a heat sink and a mounting shelf for the SSR.

The enclosure holding the Pi and the associated components is a commercial­ly available product that’s used for protecting electrical outlets around water. Regular readers will have seen the weather-proof housing in LXF232. It’s ideal for this month’s task because it provides room to mount components to a wooden board that can be positioned in the box. Keeping time The Raspberry Pi doesn’t feature a system clock. Instead, it generates and maintains time using an internal/software clock. The Pi, with its Raspbian operating system, can either use network time protocol (NTP) to obtain time from another device networked to the Pi, or it can use a program called fake-hwclock to save the clock time periodical­ly and load it at startup. The Pi internal/software clock is pretty accurate in keeping time. The author recalls reading the blog of a Pi author which suggested that the Pi clock loses six seconds over 24 hours.

If our PiBlock is expected to perform functions based on a schedule, then a solution to keeping more accurate time will be required. We could use the network along with the NTP software solution to ensure the clock maintains sync with a more accurate time source. NTP requires a GPS receiver or a network connection to an alternate time source to obtain the time signal. Because PiBlock may not maintain a reliable network connection when it’s outside buried under a snow bank, it might be a good idea to beef up timekeepin­g so that the halfsecond drift every hour is resolved.

The solution to maintainin­g accurate time is to provide the Pi with a Real Time Clock (RTC) to maintain time. The DS3231 add-on module is a coin-sized, battery powered RTC device, which keeps time even when the power is off. The RTC module contains a crystal oscillator that gives the Pi an occasional kick in the pants to ensure accurate time or provide accurate time when the Pi is starting up. The DS3231 module can be found in a number of shapes and sizes. The unit used for this project has five pins that fit securely on the GPIO header, starting at pin one.

The Pi doesn’t use a basic input output system (BIOS). The system configurat­ion parameters, which would be recalled from BIOS, are stored in a text file ( config.txt). Using your favourite text editor, add the following to the /boot/config.txt file to get the RTC module installed and configured: #enable RTC DS3231 dtoverlay=i2c-rtc,ds3231

Because there are no plans for NTP or the need for the fake-hwclock signals, the software for these can be removed by issuing the following at the command line: sudo apt-get purge ntp sudo apt-get purge fake-hwclock You can set the correct time zone using either the configurat­ion tool or the timezone package. Bear in mind that you only need to use one of the commands below, not both. sudo raspi-config sudo dpkg-reconfigur­e tzdata Now let’s set the date: sudo date --set ‘2018-01-26 18:26:00’ or install the package that uses an NTP source to set the date: sudo apt-get install ntpdate sudo ntpdate <replace with the URL or IP address of a time source>

Now you may be wondering why we removed the NTP software from the Pi earlier. Ntpdate is a command line tool that forces the clock to the time of a reference source. It’s a lot less work than trying to manually set the date and time. The next step is to write the time and date that was establishe­d to the RTC module: sudo hwclock -w

In researchin­g the configurat­ion we came across a suggestion that there was a potential for a shell script or the NTP daemon corrupting the RTC time. The PiBlock’s uptime at the time of writing was 50 days without a reboot. Unfortunat­ely, we don’t know if the problem exists in the version of Raspian operating system. If you determine there is an issue, use a text editor to ensure the parameter HWCLOCKACC­ESS=NO in the /etc/

default/hwclock file. The timing accuracy parameter on the DS3231 module indicates from -40°C to + 85°C temperatur­e range, timing accuracy is a plus or minus 5 PPM (+/0.432 seconds/day). Using the RTC module should take care of that errant six seconds a day that we estimated.

Structure of a python script

Here at LinuxFomat we publish articles that we think will appeal to readers who may or may not have a broad knowledge base. When writing tutorials it’s important to understand the knowledge level of the audience. If the writer’s assumption is the reader has some experience in the subject matter then the article can be written lighter on details, to make the most of the space and not bore the reader. If the reader is a novice, then articles that are light on details can prove difficult to follow, causing frustratio­n and much shaking of heads.

Nobel winning physicist Richard Feynman understood the difference between knowing something and knowing the name of something. In this article the basic details for setting up a Raspberry Pi was handled in the box on page 57.

Let’s now examine the opening of a python script. This is a chance to establish some foundation-level knowledge that can be used to build other Python scripts in future projects.

Below is a framework the author uses to for pythons scripts. The [#] excluding the very first one displayed, are used to provide a reference mark for the discussion and don’t form part of the script. #!/usr/bin/python 1 ########## 2 # Name: ACswitch_control.py # Descriptio­n: measure temperatur­e from DHT22 senors in GPIO11 # Version 1.0 # Date: Feb 8, 2018 ######### import sys #system manipulati­on functions. 3 import os #handy file manipulati­on functions. import datetime import time import RPi.GPIO as GPIO 3a import Adafruit_DHT #provides the ability to 3b read the DHT series of sensors from a Raspberry Pi GPIO.setmode(GPIO.BOARD) 4 or GPIO.setmode(GPIO.BCM) try: 5 ... except KeyboardIn­terrupt: #if ctrl+c exit cleanly GPIO.cleanup() except: # this catches ALL exceptions including errors.

GPIO.cleanup() finally: #cleanup GPIO on normal exit

GPIO.cleanup()

1 #! is referred to as a shebang, and makes the script executable. Following the shebang sign post is the call to the required language interprete­r to run the code inside the script. In this case its the Python. There are different calls used for interprete­rs of perl or bash scripts.

2 This is the author’s title block template. Any informatio­n that follows a # character in the script are comments and are not executed as part of the script. The character is used to frame a title block. The title block is used to provide some identifiab­le informatio­n for the script and it purpose. It’s also a good place to provide credits, if the contents of the script have been sourced from other authors.

3 Python code is written to define how to do something. The definition­s are the instructio­ns, functions and variables used in the script. In writing Python scripts it would be nice to take advantage of code that others have written. Definition­s and statements stored in a file that can be used by the interprete­r are called modules. Note that some coders will interchang­e the word libraries when referring to modules.

Definition­s from modules can be imported into other modules or into the main module. A collection of modules can be combined into a package. A package is a directory of Python modules that are formed by the combinatio­n of a directory plus the __init__.py file. Both modules and packages use import to make them available to the interrupte­r.

4 When using the RPi.GPIO module you need to specify one of two options: BOARD or BCM. BOARD indicates the script is referencin­g the physical pins on the Raspberry Pi board by number. BCM indicates that the script is referencin­g the Broadcom SOC channel designatio­n numbers, which are often called general purpose input output (GPIO) numbers.

5 If you try to stop a Python program using a keyboard Ctrl-C, the interprete­r throws a KeyboardIn­terrupt exception. When a program ends naturally or errors out because of a problem, the program exits leaving the environmen­t in a condition that may not be favourable.

One solution is ignore the warnings by turning them off. This solution only buries the problem and doesn’t solve it. Unless code is conditione­d to handle exceptions, any ports which are in use at the time of an error or the KeyboardIn­terrupt, will stay set exactly as they were, even after the program exits.

A well-written program cleans up after itself. Exceptions can be caught by a Python catch-all tryexcept statement. RPi.GPIO provides a built-in method called GPIO.cleanup() to clean up all ports used. Deploying both in python code resets the ports used in the program back to input mode. Anatomy of VEBHC scripts Switching to a discussion that uses more general details, let’s examine the two Python scripts, called

LED_PWM_Dimmer.py and ACswitch_control.py that support the VEBHC. In the interest of saving space, the text for these scripts can be found on this month’s DVD.

The first script, LED_PWM_Dimmer.py, is designed to provide a slowly pulsing LED to indicate that the unit’s actually working. Remember that all the components are in a sealed enclosure that plugs into the AC wall receptacle. It would be nice to provide the user with some indication that the unit’s working. Like printing a rotating hash mark on a command line interface to demonstrat­e a command is working, the script produces a continuous cycle of blue LED light that appears to get brighter and dimmer but never completely goes out.

To accomplish the task, the script takes advantage of pulse width modulation (PWM) supported in the Pi. By increasing the dutycycle (in other words, how long the LED is on verses off for one cycle) for an LED and then decreasing the dutycycle, the viewer is left with the perception of an LED that continuous­ly cycles from dim to bright back to dim.

To explore Python programmin­g using a visual indicator, bread boarding a PWM circuit using a Pi is an ideal exercise for the novice. The methods (for example, definition­s and statements inside a module to perform a specific function) used for establishi­ng PWM can be found at https://sourceforg­e.net/p/raspberry-gpio

python/wiki/PWM. Perform a Google search for pulse width modulation on a Raspberry Pi and your cup will floweth over with learning resources.

The second script, ACswitch_control.py, uses the current time, a temperatur­e reading garnered from a sensor and a user override variable to determine if the solid state relay needs to be energised to provide 120V of AC power to the switched receptacle. If the time is between 3AM and 8AM and the temperatur­e is below -15°C then the Raspberry Pi will trigger the SSR to be on, provided that the override variable is not set to one. If the variable is one then the user has manually activated the AC switch.

There you have it thinkers, makers and programmer­s – the makings of a VEBHC. Actually, the design is just a solution to switching AC power. Maybe you have outdoor lights you want on or off or you need to control an electric motor. Why not throw some additional sensor in the enclosure and add your own logic to make your own controller?

 ??  ?? This diagram sums up the nature of this month’s article.
This diagram sums up the nature of this month’s article.
 ??  ??
 ??  ?? If you don’t have a schematic, get out a napkin and pen and draw one
If you don’t have a schematic, get out a napkin and pen and draw one
 ??  ?? A solid-state relay constructe­d on a metal backing for heat dissipatio­n.
A solid-state relay constructe­d on a metal backing for heat dissipatio­n.
 ??  ?? Here’s what’s lurking inside the weather-proof enclosure.
Here’s what’s lurking inside the weather-proof enclosure.

Newspapers in English

Newspapers from Australia