Category Archives: Raspberry PI

A wheel centre cap

In the post about printing 3d gears, we saw that it was possible to print replacement gears for car parts. I have now received a report that the printed gear works after several weeks of in-car testing, so let us count that as a success. In fact, it was so successful that I got a request to print another part that was missing; a press-fit wheel centre cap, original as below.


The owner also wanted the logo on the replacement part. When you don’t pay, there is no limit to what you can ask for :-) Anyway, I thought we might give it a try.

First step was simply to place the original on the flatbed scanner and make an image of the logo. I could have found the logo on the web, but that is cheating. Instead the scanned image was imported into Photoshop and turned into a monochrome image and blurred/clipped and saved to a PNG file.


Then, OpenSCAD  was fired up, and the following script was edited


In the above code, the d1 to d4 parameters define measured diameters (using a caliper) on the original. d1 is the outermost diameter. Similarly h1 to h4 define the heights measured from the bottom when logo is pointing down.

The “logo()” module imports the scanned image and turns it into a 3d object. A slice of that is created by intersecting it with a “cube” (actually a cuboid). The intersection is then scaled, rotated and translated to fit the size and orientation of the printed object.

The “bottom()” module is simply a short cylinder minus the logo at bottom and a smaller cylinder on top, to create a “rim” on the bottom part.

The “teeth()” module describes the 2d profile of the teeth that grips the wheel and then performs a rotational extrude (360 degrees). This is then intersected with the result of the “cross()” module which simply defines a cross from 2 cuboids. The result is 4 teeth, separated by 90 degrees.

All in all, less than 60 lines of code. We then get this OpenSCAD model to export as an STL file.


There are many ways to process an STL file, but generally it needs to be run through a “slicer” program to generate the G-code that a printer can understand. There are many very good slicer programs, including slic3r and Cura, but recently I have been using KISSlicer, as it has many nice customization options.


After completing the slicing, we have the G-code to send to the printer. I am using OctoPrint running on a wireless Raspberry Pi to control the printer, so the G-code is sent to OctoPrint via the web browser on the PC. OctoPrint can also display the temperature of the hot end and the heated bed. All we have to do is check that the printer calibration is ok and commit the print:


When finished, we have something that closely resembles the OpenSCAD model.


When we turn the print around, we also see something that resembles the logo. It is not perfect, but it is there. One idea is to fill the void with some dark filler and sand the top surface a bit. Then it might pass :-)


A challenge with a part like this is that the printed part is relatively brittle compared to the original, so it is hoped that the teeth simply do not break off. This is why the printed teeth are made wider than in the original, where it is only the smaller teeth that grip the wheel.

Printrbot – heated bed

The break in posts on 3d printing does not indicate that nothing has happened in the time passed. On the contrary, I have been too busy exploring various smaller problems and ways to improve.   The most important improvement is the installation of the “heated bed” upgrade that has been waiting since I got the printer. I left it alone for a while because I wanted to get some experience with printing on the unheated standard bed. I think now it was a good idea, because I can see the benefits in better perspective after installing the upgrade.

So what exactly is the “heated bed”? It means that the print surface is heated by a heating element so that the plastic parts do not warp as easily (or at all). With the unheated bed there will be temperature gradients in the parts causing warping, especially when the print surface is relatively large, i.e. longer than just a couple of centimetres.  With the heated bed the temperature is more uniform through the part and you can then create more geometrically accurate parts. Since I am mostly interested in mechanical parts, it is important.


The upgrade kit contained a machined aluminium print surface (bottom right). Being machined, it also provides a flatter surface than the standard bed, which can be slightly non-flat. The other main parts are the 2 black aluminium “wings” that are needed for the X belt after removing the standard non-heated bed. At top left is the heater element with 12V wires and next to it is a sheet of heat resistant Kapton tape which will be fastened to the aluminium print surface. In the bag is a thermistor that will be used for monitoring and controlling the bed temperature. Both the thermistor and the heat element power wires connects to the board under the printer. The bag also contains delrin parts to help insulate the “wings” from the hot print surface.


On the underside of the machined print surface, there are grooves that must be electrically insulated using Kapton tape. The biggest groove will contain the soldering points on the heater element and the smaller groove is for the thermistor.  After placing the thermistor in its place, the heater element is put on top (i.e.  under it, since the print surface is upside down still). The black & white wires are for the thermistor.


Over (i.e. under) the heater plate comes a reflective sheet that is simply screwed into the corners. I added some Kapton tape pieces to secure it. I am not sure this is sheet very effective, heat is lost not only via radiation. It would make sense to let the sheet cover the whole plate also. But this is according to the kit.


What remains after this is to turn the heated bed around and connect the X-belt to the wings and then connect the wires to the board. But I also added an update of my own. Under the 4 corners of the heated bed I put a flat and a split washer so that it is possible to manually adjust the “bed level”, i.e. manually make the print surface as perpendicular as possible to the print Z-axis of the printer.  The goal is not to replace the Z probe which accounts for unlevelled beds automatically, but  to ensure the adjustments are very small.

Once installed, we have a new and shiny printer! Notice also the Raspberry Pi  Model B in the background, that is the other important upgrades that the recent weeks have seen.  Instead of connecting the printer to the main computer, the Raspberry PI is committed as a wireless printer server, running OctoPrint . OctoPrint provides a web interface, so you can access the printer via any browser, anywhere. This is now the standard mode for how I  operate the printer, it is very convenient.


Also in the background is the new power supply serving the printer. The standard laptop-style power supply that came with the printer cannot be used with the heated bed, you need a power supply with more “grunt” as the heated bed draws about 7A  at 12V.  The power supply I use is rated at 10A and seems to be working fine for the job.

Below is how OctoPrint reports the temperatures of the bed and the hotend. The bed can reach 100C in about 14-15 minutes from a starting point of ~20C which I find adequate.  100C is required for ABS, but for PLA 60C is sufficient, it achieved in about 5 minutes.


The temperature curves above are not really reflecting the standard heated bed upgrade shown above. It reflects an additional modification. I noticed that the black “wings” of the heated bed got quite warm, they acted as heat sinks and radiators, even with the delrin pieces in the kit that were supposed to insulate the “wings” from the machined print plate.  It probably has some effect, but a lot of heat is lost that way still.  The curve above shows the effect after installing the “blankets” described below.

It seems like a good idea to put a “blanket” over the wings to reduce the heat loss. I did that by designing hollow covers to go over the wings. They are designed as solid parts, but printed with “hollow” infill and 0.8 mm skin. Below is how it looked during early print, there are for parts since each of the two wing covers are split,  you cannot print a part covering the whole print surface on the same print surface…


After completion, you get this nice looking view, four parts complete with holes for screws and belt tensioners.


These parts simply “snap” onto the wings, the heat loss is now much reduced.


I am very happy with these changes. The power supply is working, the Raspberry PI with OctoPrint is the perfect way to operate the printer, it works flawlessly even with the older Raspberry PI model B. It also frees up the main computer during long prints.  The heated bed itself works fine, I can now print large parts without warping and I am also ready to consider printing ABS.

Weather camera reboot

While waiting for my next project to take off (info to come here when it happens), this is a good time to mention the impressive stability of 2 computers serving my weather station page. The machines are an old laptop and a Raspberry PI, both running Linux distros.

The graphs on that page is collected from a simple weather station with an outdoor unit located in the garden:


The outdoor unit runs on 2 AA batteries (they seem to last forever!) and contains a temperature sensor and a humidity sensor, they are located inside the Stevenson screen. On the roof of the Stevenson screen is a rain sensor plus a wind speed and wind direction sensor. The location of the outdoor unit is not ideal, and the wind direction is not to be trusted. Mostly, it is the temperature that is of interest, but wind speed and rain can sometimes be useful also.

The outdoor unit sends readings wirelessly to the indoor unit which has its own indoor temperature plus pressure sensors. The indoor unit is permanently connected via USB to an old laptop running Linux Xubuntu 11.10 .  All that laptop does is run a program that queries the indoor unit and stores the readings in an SQLite database every 5 minutes. The incredible thing is that the old laptop was last rebooted 11. May 2012, i.e. almost 3 years ago. That is stability!

The images on the weather station page are generated from the Raspberry PI based weather camera housed in a dummy surveillance camera, mounted on an old TV antenna pole. The Raspberry PI camera runs Linux Rasbian. Since performing some hardware changes 2-Jan-2015, the RPI machine has not been rebooted, it has captured images every minute for almost 90 days in a row. Not bad!


However, 2 days ago, the images suddenly stopped coming, something was wrong. After investigating, it quickly became clear that the SD card the RPI was running from had acquired a file system problem, so it crashed and a reboot didn’t work. The camera was taken down, SD card erased+reformatted and Rasbian was reinstalled. Problem solved, now the camera is running fine again with the same hardware.

The problem may have been caused by excessive writing of files to the SD card, which will eventually wear it out. To prevent similar problems in the future, I decided to install a small RAM drive based on this description.  Instead of temporarily writing the images to the SD card before copying to a disk in the house, it now writes the images to the RAM drive. A very simple fix that should increase the life expectancy of the SD card.

It will be interesting to see how long these two work-horses will run before requiring a boot!

260 000 images on a Raspberry Pi

In the previous post the op_lite object oriented database library for C++ was introduced.  I have been testing this library on Windows and Kubuntu using images from the Raspberry Pi1 Model B weather camera. The camera captures a JPEG image of size 1296×972 every minute, which means that each day there are 1440 additional images to put in the weather camera database. The database now has a viewer written in C++ based on op_lite and wxWidgets, It works fine on both Windows and Linux.

The PI weather camera has been  running steady for just about 6 months now, it has so far accumulated just over 260 000 images (database size is > 20GB) showing the daily weather plus stars at night. Today I wanted to try op_lite and the viewer on another Pi1 Model B, so I compiled the database viewer application there. This is straightforward as Raspbian is a debian derivative, just like Kubuntu.

The the 20GB database was copied from Windows across the LAN network to the PI which has a 320GB USB hard drive connected, formatted as linux ext4. The copy took a few minutes and the compilation of the software took longer, but it worked!  It shows that the database is compatible and can be freely copied around Windows/Kubuntu/Raspberry PI.

260 000 images captures on a PI1, viewed on another. It doesn’t work as fast as on a desktop, but it is certainly usable. I have a new PI2 Model B coming soon, and  it will be interesting to see how things performs there.  As the PI2 is said to be about ~6 times faster than the PI1, it should be good!


Sunny Sunday time-lapse

Today was a nice and sunny winter Sunday, with outside temperatures around -6°C.  From the weather camera capturing an image every minute, a time-lapse video covering approximately 12 hours is assembled. It shows the changing weather conditions plus a few cross country skiers enjoying themselves in the sunshine. It takes about 3.5 minutes to show. I think you also agree that the Raspberry PI weather camera does a pretty good job with the heater system keeping it in focus!

Time-lapse 25. Jan 2015


The video was created automatically by first generating a label in the bottom left corner of each image. The information about exposure and camera temperature sensors is taken from XML files generated by the on-board RPI software.

Second, 3 interpolated images between each pair of originals were created, effectively giving the impression of images taken every 15 seconds.  The XML generation, image interpolation and labelling software is home grown.

The final step was time-lapse video generation using ffmpeg.  A bash script running under Kubuntu orchestrates the whole thing,  but a very similar process can easily be achieved under e.g. Windows.

Mark2 heater board

In the Raspberry Pi Lens Heater post, the motivation for heating the RPI camera lens when operating in cold temperatures was given. A prototype version of a heater system was also presented, it has worked very well since early January. The images were significantly sharper when the lens is heated to around 15-20°C. Even well before that, the effect is significant.

Temperatures in January have been rather mild, around 0°C  (+/-5°C), but recently we had a day below -15°C  and the camera board temp sensor showed only +4°C at the lowest. Still, the star images and other details verified the heating had a good effect.

A friend showed interest in setting up a similar camera with heater, so that provided a chance to improve on the design. Clearly, the original “birds nest” implementation did leave something to be desired. My friend also wanted to accommodate 3 temperature sensors, one for the camera board (“CMOS”), one for camera house (“BODY”) and one for the outside (“OUT”). That meant an even bigger nest or something slightly smarter would be required.

After buying some parts from China via Ebay I came up with the rather obvious idea of eliminating the “nest” by assembling the components on a single board that would attach directly to the GPIO pins of the Raspberry PI. An informal sketch of the design follows:


The overall idea is based on a 4×6 cm prototype PCB board and a 2×13 Pin header soldered together in such a way that the board becomes a suitable add-on to the Raspberry PI.  The mini relay for switching the heater on/off is placed on the opposite end of the board relative to the pin header, along with its control circuitry. Between the two there is room for a “bus” for multiple DS18B20 temperature sensors. One is placed on the board, screw connectors are provided for the other sensors off the board. As the DS18B20 sensors are “1wire” devices, they can be identified in software via their unique serial numbers.

The board design thus allows both GPIO relay control + reading of 3 temperature sensors.


This looks like an improvement to me.  As designed, the board simply connects to the 28 GPIO pins of the Raspberry PI model B using the 2×13 Pin header. My friend is getting the Model B+ with more GPIO pins, but luckily the common pins of the two RPI models are the same, so the board should fit the B+ just fine.


A couple of quick tests showed that both the relay control and the temperature sensor worked just fine, so the board is fully operational and awaiting the Mark2 camera board heater element to be completed.

After completing the Mark2 heater board, I received some PCB Pin connector kits. They are possibly better alternatives than the screw connectors, since you do not risk getting the polarity wrong once the board has been properly made. Still, I am quite happy with the current Mark2 board!

Raspberry Pi Lens Heater

Happy New  Year!  Again it has taken some time since the last blog entry, due to Christmas activities taking priority. However, quite a few things have been happening with the Raspberry Pi weather camera in December.  Just over Christmas we had a cold snap, and I noticed that the camera images appeared degraded in the cold, they used to be much sharper before, didn’t they? I decided to check, here is a comparison for the same time of day, comparable weather, but different temperatures on 26. Dec (-15C) and 01. Jan (+3.8C).


You don’t have to be a rocket scientist to see that the image quality is degraded at lower ambient temperature. When comparing with older images from September 2014 when it was much warmer it is also clear that the relative sharpness of the 01.  Jan image is also degraded compared to the warmer September days.

I looked around to see if this was a known problem, and I did find a report of a very similar problem by someone in Germany (?), where problems with focus were correlated with cool temperatures.  More looking around landed me at a page with a lot of technical specifications for the Raspberry Pi. There is an interesting quote there that says “The threaded focus adjustment is set to infinity at the factory. Changing the focus from infinity to something closer requires that you turn the threaded lens cell counter-clockwise, moving the lens further away from the imaging sensor”  .

In other words, the Pi camera lens has fixed focus unless you start messing with it.  It is a so called Extended Depth Of Field (EDOF) lens, which essentially is using some clever optical and internal processing tricks to reach a pretty decent, sharp image without the user having to perform any focusing at all. Note that it is not an auto-focus system, the lens is fixed at all times. So it is a decent and user friendly compromise if you operate the camera within the design specifications.

Based on this, I suspected that there was an assumption of optimal temperature built into the PI camera EDOF system, for example an assumption room temperature (say, +20C).  My take would then be that low winter temperatures causes the lens assembly to contract/deform in such a way that the lens is effectively brought slightly closer to the imaging sensor, resulting in a “beyond infinity” focus setting, and thus rather blurred images in the cold.

This is bad news if you are using the PI camera for outdoor imaging at low temperatures, but is it possible to do something about it? Of course, one might consider changing the lens focus position by rotating the lens, but this is not practical in this case, considering the tiny lens and doing it in the cold.

However, heating the camera board to near room temperature is perhaps more feasible? From amateur astronomy we know dew heaters are made by coupling a number of resistors in parallel and sending a small amount of current through them, generating something like 2W in total to heat the optical surfaces and thus avoid dew.


We could perhaps make a similar system using just a few resistors and generate something like 0.5W to heat just the camera board?  The general idea is illustrated at left, using 3×150 Ohm resistors in parallel. If you apply 5V to this setup, it will generate 0.5 Watt. By placing the resistors close to the lens assembly, then much of the generated heat will be transferred to lens.  By also measuring the temperature close to the lens one can determine how long/much the lens should be heated and optionally turn it on/off automatically as required. To make this work,  one needs to insulate the resistors so they don’t lose the generated heat too fast. I decided to embed the resistors in melted plastic, as I had some hobby plastic that could be used. I made a simple form, put the resistor assembly in it, poured plastic over it and melted the plastic with a heat gun.  After cooling and adjustments I had a basic lens heater element,  shown below. The heat from the resistors will not dissipate as easily and will probably also cause a slightly more uniform heating around the lens.


I could have put a small DS18B20 temperature sensor into the melted plastic, but I was unsure about whether it would survive.  So instead I cut a trace for it after the plastic had cooled and glued in place between the red markings in the image below left. Before that I had soldered suitable wires to it. At the same time, holes were drilled to match the existing holes in the PI camera board. Here one needs to be accurate with the separation and placement of the holes.  In the end I used M2 machine screws and a piece of plastic on the back side of the camera board with similar holes to hold the assembly in place. The purpose of the plastic on the back is to insulate both electrically and also temperature-wise.


The DS18B20 temperature sensors are quite “friendly”, as you can connect many such sensors to the same wire/GPIO pin, they are so called “1-wire” sensors, although you also need wires for current. Once connected to the GPIO pins, the measurements turn up as small text files you can read.  The method I use for reading the temperature sensors is described here and  especially here . Since the weather camera images are scheduled using crontab, the driver for using 1-wire  sensors must be loaded at system start up, there is a page describing how to do that here.


In a previous post, I discussed how to control a relay, and now this could come into use.  Quite possibly, one does not want the heater to be on at all times. We have very variable temperatures during the winter, and when the sun is high in the summer it can get rather warm. So a system for control the applied heat is required. If a separate power supply is used and the socket is accessible, one may do it manually. But in this case, the socket is not conveniently located and I eventually want 100% automatic temperature control.

A simple solution to this is to use the relay board,  allowing the power to the lens heater to be controlled from the PI itself, even when the heater is powered from a separate power supply. Then it also becomes possible to automate the heater control, by evaluating the temperature sensor embedded in the heater. Typically, one may want to turn on the heater if the temperature drops below +10C and turn it off when it exceeds +20C, or something of that nature. Such a thing is possible to do from software,  using the relay.

Adapting a relay board inside the camera housing was not part of the original weather camera design. The PI was simply placed on a  85mmx123mm aluminium plate that slides into the tracks in the inside of the camera housing. To fit the relay, I found a piece of unused plastic that could serve as a relay board holder. Adapting the relay board required a couple of holes to be drilled, and checking that the final assembly still fit inside the housing.


There are probably far more elegant ways of connecting it all than what is shown below, it is a bit of a “bird’s nest” :-) But it shows where the temperature sensors are and also that the wires are connected to a 28 pin pin-header on the far side, so nothing is soldered directly to the GPIO Pins of the PI (Model B in this instance). If required, the whole thing can easily be disassembled.


In the image above, all wiring is done, except for the power to the heater and power to the PI itself.  Notice that he PI camera board + lens heater assembly is placed on the front side of the plate holding it. This is different from before, and places the camera closer to the front glass.

The PI is powered via a micro USB cable (black in the image below), and the lens heater is connected to the red/black power cable via the relay. The whole thing then slides inside the housing, using the tracks on the inside walls.


A likely improvement and simplification if I was to make it again, would be to integrate the plate the PI sits on with the actual holder of the camera/heater as one piece.  Another likely improvement would be to create a “breakout board” for both the relay and temperature sensors. That would eliminate the need for much of the messy wiring. So the current solution should be considered a prototype.

Below is the new front of the camera, now a combination of the old dew fix and the new lens heater. The lens heater in this configuration should also help to prevent dew, since the back side of the glass is now heated.


Initial test results

Once assembled, I was eager to test it. First step was to check that the camera still worked, and that it was possible to read both temperature sensors. The 1-wire sensors kept their promise and both showed data. Each sensor has a unique serial number, but you cannot say which is which by looking at the serial number, you have to observe the behaviour.  After some simple experimentation, I was able to determine the “body” sensor and the “cmos” sensor  and their respective serial numbers.

Then the real test began, by applying current to the lens heater. To switch the relay on/off, I used the C code found in the article Raspberry Pi – Driving a Relay using GPIO, i.e. the same method as in Raspberry Pi – Controlling a Relay.

After switching on the heater current, the “cmos” temperature sensor started to report higher values. Success! During the initial testing, the outside temperature was about +2C, and before heating began the cmos temperature sensor reported just over 5C. After switching on the 5V heater current, the temperature increased gradually over 45-60 minutes until it stabilised around +17C. This was pretty good!  If more power is needed, it is possible to run the heater at 6V or higher, one just needs to check that the power rating of each resistor is not exceeded, we don’t want anything to catch fire!

How about image quality? This is the best part, the sharpness is dramatically improved. At the time of writing, it is dark. But I will write a new post tomorrow,  comparing daylight images to previous images at the similar ambient temperature conditions.

To conclude, the heater works and it has the desired image quality effect!

fighting dew

I have not updated the blog for a while, because I have been working abroad (Singapore). During that time, the weather camera developed dew problems after a long period of massive rain.  The camera house is not 100% water proof, and the variation on outside air humidity causes dew to settle on the inside walls. Another problem was the big front glass that was exposed to the cold environment, it became the coldest “wall” as seen from inside, and therefore the most likely place for dew to settle, precisely where you don’t want it. The result is seen below, lots of dew causing fogging of the image!


The camera chip & lens cannot be seen in that image, but it is in the centre between the fake LED components (the camera house is from a fake surveillance camera). The fake LEDs site on a dummy PCB that is also part of the problem: it make internal ventilation problematic, increasing the dew problems.

As a first step in fixing the problem, the camera was opened and all the fake LEDs were removed. After all, their only “purpose” was to cause strange reflections of the Sun. Next, 4 big holes were drilled in the fake PCB, so that air could be freely ventilated between the space between the camera and front glass, and the rest of the camera house, where the Raspberry PI generates some heat. 


Measurements have shown that the temperature inside the camera house is generally about 6 degrees C higher than the outside air.  This looks like an improvement, but the front glass is still much to large and exposed to the environment. How about masking off the part of the glass that the camera isn’t looking through? I did some indoor tests with a piece of cardboard to determine the size of the area that needs to be clear of obstructions, and the result is shown below. Most of the glass can be covered without obstructing the view from the Raspberry Pi camera lens.


The thinking is to cover and insulate the the glass plate on the outside so the limited heat generated inside the camera house has a smaller surface to “work on”, i.e. just the inside of the unobstructed circular glass area exposed to the environment, right in front of the lens. 


The final result was as show above: A piece of Plexiglas with the same size and shape as the cardboard plate (slightly bigger hole) with a 1cm thick foam plate as insulation towards the glass. The assembly is then attached to the front using water proof tape.

The resulting camera performance can be observed on the weather station page .

Weather camera database

At the top of this page, you may have seen the weather station link, showing up-to-date temperature, pressure and more. The page updates automatically every 10 minutes, 24/7. The weather station was installed 31. Jan 2010 taking readings every 10 minutes. Beginning 04 Jan 2012, the frequency of readings was increased to every 5 minutes, and it has been doing that since then, almost without any pause.  31 January 2015 will mark the 5th anniversary of the weather station and the associated web page, pumping out graphs like this:


On 03 Sep 2014, my new Raspberry PI based weather camera became operational, it has been capturing images every minute 24/7 since then, adding visual context to the other data. It is easier to understand the causes of the temperature fluctuations when you see what the weather actually looked like at the time.  The weather camera construction and setup will be subject of later post(s) here.

The database for the weather station has collected only  24MB of data since 2010, but capturing images is something completely different, even though the weather camera is set up to save images at half resolution and as JPEG with high compression. Keeping all those images as individual files in the file system, eventually causes trouble. It is also cumbersome to review old images that way.  Therefore, I have started developing a database & viewer for the images and other data produced by the weather camera. Eventually, this will be merged with the weather station data, but first we need to handle the substantial volume of image data coming from the camera.

As a first test of some ideas, I created a prototype database and viewer application to see how responsive it would be. I took all images from October 2014 – more than 44 000 individual images! – and put them all in the same database, resulting in a file size of 2.95GB. Here is a small glimpse of the responsiveness, which I find quite adequate.

Testing the weather camera database

Even though this appears to be working fine, I would like to find ways of compressing the data more, without compromising on the final image quality, so there will be more tests before I settle down on the “final system”. I am thinking of presenting temperature or other graphs alongside the images, to give better overview. The image database is based on SQLite, but I have added my own C++ layer on top of it, which makes it more suitable for object orientation. This layer may become open source at some stage, if it turns out the way I want it.

The next video below, isn’t really about the database as such, but it illustrates with better image quality what the weather camera can do. Of course, producing such time lapse videos from the database is a possible goal.

Weather camera time lapse 04. September 2014

If you are interested in any of this, and want to know more detail, tell me about it!

Raspberry Pi – Controlling a Relay

I have no background in electronics, but the Raspberry Pi has given me an incentive to learn. Some time ago I made a Raspberry PI weather camera (it will be subject of a separate post here at some later stage) which has now operated continuously for over two months in very mixed weather. Sometimes, the camera develops dew on its front cover window, it may be inside or outside or both.

imageCould I do something to fix that, for example using a window heating circuit controlled from the Raspberry Pi  camera?  This post is exploring how such an external circuit could be controlled.

First, one might be tempted to think the GPIO pins could provide enough power to drive such a circuit, but that is a sure way to short circuit and terminate the PI, so don’t even think of trying that!

When looking for answers, I found an extremely instructive post on the subject, Raspberry Pi – Driving a Relay using GPIO . It provided a solution: The GPIO pins cannot drive a heater directly, but they can be used to control a relay – which works as the on/off switch of another circuit isolated from the PI, i.e. using its own power supply.  I recommend reading that original post carefully, this post should be regarded as mere ‘replication’ as done by a novice. A circuit diagram was also provided, but how does it actually work, would I be able to use it in practice?  I set out to try and understand.

Starting at the relay end, the switch in the relay opens and closes as the relay coil, an electromagnet, is powered. It turns out that the Raspberry Pi 5V GPIO pin can provide enough power to activate this coil, but we need a way to turn the power on/off so the relay can be opened or closed from software running on the PI. For this purpose, a transistor is ideal, as it may be used as yet another on/off switch, only at lower power. image By combining the relay coil and the transistor circuit one should be able to control the external circuit.

A transistor has 3 pins or “legs”, and there are 2 kinds of transistors, NPN and PNP types, we are here using the NPN type. You may want to look up the difference.

The current that goes through the relay coil goes to the collector  pin of the transistor and exits via the emitter pin, on the condition that the base pin is powered. The emitter pin is grounded.

Even less power, just a couple of milli-Ampere at 3.3V is required to “turn on” the transistor . Using U=R*I, U=3.3V, R=1.2KOhm we find that it corresponds to about 2.75 mA of power from the GPIO pin to the transistor base pin. Turning this GPIO pin on/off will control the transistor switch, and therefore also the relay.

We are almost done, but one component is missing: the diode labelled D1 above. The diode is there to protect from power spikes when switching off the relay, when the coil magnetic field collapses. The diode dissipates the power spike and makes sure the PI survives another on/off cycle!

Ok, that’s all talk, how about the real thing?  First, some components are needed, and for this Ebay is quite nice. I got most components from Asia with free shipping. For the relay, it is important that the coil circuit is 5V, I used a SRD-S-105D relay. The transistor must be NPN type, and the post above mentions the BC337 NPN transistor. Before receiving them, I found that I had a couple of BC547 transistors in a drawer, and it turns out they can both be used for this purpose.  The diode I used was 1N4004.

With all the parts collected, you just solder on, right?  Well, some do…. I had a strip board with holes connected in groups of 3, and I found it quite hard to imagine how to layout the circuit on the board without making a big mess.  imageTherefore, I got the idea of placing the strip board on my flatbed scanner, copper down, so that I could create an image to draw on.  I used Photoshop layers to experiment with layouts. I am sure much more suitable software exists for this purpose, but it worked for me.

I created the drawing at left this way. It is a little funny, because you are looking at the copper side and the components are really supposed to be on the opposite side, as in the photo further down. The black rectangle corresponds to the relay, and inside it you find the 5 relay legs as black dots.  The thing that almost looks like a grey resistor inside the relay rectangle is supposed to represent the relay coil, and the red line is the switch itself. The green show connections between strips.  The other symbols are perhaps more understandable. Observe that the diode and transistor legs must be soldered correctly, look up the data sheets! I am not suggesting you duplicate this way of working, it is highly non-standard, it simply shows how I was able to layout the components. Once again, remember that you are looking at the components from “under” the board (copper side), the components are really on the other side, as in the photo below-left.


I had to drill an extra hole for the 5th centre pin of the relay, as it hit right between 4 holes. I am no soldering expert, but the end result seemed quite ok to me.  But looks is one thing, more important is: Would it work?


In the image below, the +5V pin on the relay board is connected to the +5V GPIO pin (pin 2) using the black jumper cable.  The blue jumper is connected to GND (pin 6) and the green is connected to pin 11 (GPIO 17). The photo was taken before the green contact was added to the relay board.


As for testing the controlled circuit, I connected an external power supply to one of the green contact sockets on the relay board, and coupled a LED in series on a breadboard. The test was performed using the C program available from the article mentioned in the beginning of this post. Here’s an animated GIF showing that the relay did in fact respond as required. Success :-)