Third party cookies may be stored when visiting this site. Please see the cookie information.

Home Family Days Out Raspberry Pi & Electronics Blog

Stewart's Blog

Stewart Watkiss website to the world ...

(Children, computing, first aid and other ramblings ...)

Raspberry Pi Christmas Project – Christmas House and Neopixel Snowman

December 17th, 2018

This year I’ve been creating a 3D model of a building for an outdoor model railway. Technically it’s a building for a weigh bridge rather than a house, but I’ve given it a Santa’s Grotto make-over for Christmas and so Christmas House sounds better.

The building is designed in TinkerCAD based on a real building on the Gloucestershire and Warwickshire Railway.

Christmas House

I’ve added a 3D printed snowman also designed in TinkerCAD.

Initially I added a smoke generator for the chimney, a white LED for a lamp and a red LED for the glow from the fireplace. To give it it’s Christmas theme I’ve also added a NeoPixel light inside the snowman and string of LEDs as Christmas lights. I have disabled the smoke as that was more appropriate when it’s outdoor with the railway rather than the indoor Christmas display.

Circuit to control LEDs, Neopixels and Smoke Generator

The circuit diagram is shown below (click on the image for a large version).

Circuit diagram (schematic) of Christmas House with LEDs, NeoPixel and smoke generator

The circuit is designed for a Pi Zero with a custom HAT, which would fit better inside the building, but for the initial version this has been connected to a Raspberry Pi 2 with a half-size breadboard, which just fits inside the 3D printed building.

Breadboard wiring diagram for Christmas House with LEDs, NeoPixel and smoke generator

Although built on a bread-board wires need to be soldered to the LEDs.

Setting up the Raspberry Pi

To control the NeoPixel (RGB colour changing LED) then a library will need to be installed first. This is explained in the following worksheet:

Worksheet for configuring NeoPixels on a Raspberry Pi

Code to control the LEDs and NeoPixel

The following code should be added to a file called /home/pi/christmas-house/display.py


#!/usr/bin/python3
from gpiozero import LED 
from neopixel import *
import time

# config details for neopixel
LEDCOUNT = 1
GPIOPIN = 18
FREQ = 800000
DMA = 5
INVERT = True
BRIGHTNESS = 255

FIRE_PIN = 24
LAMP_PIN = 25
GREEN_PIN = 17
RED_PIN = 27

fire_led = LED(FIRE_PIN)
lamp_led = LED(LAMP_PIN)
green_led = LED(GREEN_PIN)
red_led = LED(RED_PIN)

timer = 0

# red / green chaser mode - toggle between red and green
# if 1 = red led on, if 0 then green led on
red_green = 1

rgb_colours = [Color(248,12,18), Color (255,51,17), Color(255,102,68), \
               Color(254,174,45), Color(208,195,16), Color(105,208,37), \
               Color(18,189,185), Color(68,68,221), Color(59,12,189)]
seq_number = 0

# Create neopixel object
strip = Adafruit_NeoPixel(LEDCOUNT, GPIOPIN, FREQ, DMA, INVERT, BRIGHTNESS)
strip.begin()
strip.setPixelColor(0, rgb_colours[0])
strip.show()

def led_change():
    global timer, red_green, seq_number
    timer += 1
    # if number is divisble by 6 then flicker red led
    if (timer % 6 == 0):
        fire_led.off()
    else:
        fire_led.on()
    
    # toggle red green leds
    if (timer % 10 == 0):
        red_green = 1 - red_green
        if (red_green == 1):
            red_led.on()
            green_led.off()
        else:
            red_led.off()
            green_led.on()

    # Color change snowman
    if (timer % 12 == 0):
        seq_number += 1
        if (seq_number >= len(rgb_colours)):
            seq_number = 0
        strip.setPixelColor(0, rgb_colours[seq_number])
        strip.show()

lamp_led.on()

while True:
    led_change()
    time.sleep(0.25)

It can then be run using:
sudo python3 /home/pi/christmas-house/display.py

The code works by having a single loop which runs and then pauses for 1/4 of a second. During the led_change function the timer is incremented and if the value of the timer reaches the appropriate factor then it changes which LEDs are on etc.

The % provides the modulo value, which is the remainder after dividing the number of the left by the number on the right.

For example
timer % 12
Will be exactly zero whenever the value of the timer is a multiple of 12. As the timer value incrementes every quarter of a second this means it updates every 3 seconds.

Startup automatically

To have the code run automatically when the computer boots then create the following file (you will need to sudo to root to have appropriate permissions) as /etc/systemd/system/house.service


[Unit]
Description=House

[Service]
ExecStart=/usr/bin/python3 /home/pi/christmas-house/display.py
User=root

[Install]
WantedBy=multi-user.target

Give it permission to run:

sudo chmod +x /etc/systemd/system/house.service

Then set it to start automatically using:

sudo systemctl enable house.service

YouTube video introuction

I’ve also created a YouTube video introducing the project. Please subscribe to penguintutor on YouTube.

Making the 3D Models

Details of how I made the 3D models in TinkerCAD are available below:

TinkerCAD 3D Snowman for 3D printing G-Scale model railway

December 3rd, 2018

This is a model that I’ve made using TinkerCAD. A snowman designed for 3D printing on a home 3D printer. It’s been created to approximate G-Scale (1:22.5) for outdoor model railways. It’s also hollow so that you can insert an LED inside and have it light-up (assuming it’s printed with a light coloured PLA) so it can be used as a light-up Christmas decoration.

G-Scale Snowman made in TinkerCAD for 3D printing

The photo below show the 3D snowman printed on a Wanahao i3 Duplicator Plus using white PLA.

To make it easier to hollow out there is a central cylinder which can be removed. The snowman arms are very delicate at this scale. If the size isn’t important then you may prefer to scale the model up a little which can be done within your Slicer software (eg. Ultimaker Cura).

GScale Snowman made 3D printed for garden model railway

Download 3D model files (STL)

Video – Beginners Guide to TinkerCAD

Below is a video on how to recreate the snowman in TinkerCAD

More models

See the PenguinTutor 3D projects page for more 3D models, including more model railway models.

The rules for building a model railway

November 25th, 2018

There are many different misconceptions about creating model railways and the people that are involved. I’d therefore like to start by dispelling some of these myths and explaining what I think that model railways is about.

The 3 Golden Rules of Model Railways

Many people have come up with different rules for model railways, here’s my take.
If you are wanting to design your own personal model railway then there are only three rules that you need to follow.

  1. Safety is always the top priority
  2. It’s your railway so you can do what you want
  3. See rule number 2

Okay, so that’s only really 2 rules, but both are just as important. You also need a reason to be spending all that money, so I included fun as a third rule in the description below.
This is for your own railway on private land, but if you are on a public display then new rules apply – see Public Display Railways rules.

Rule 1 – Safety

I think it’s fairly obvious why rule number 1 exists, but remember this applies to both the modeling and the display of the model railway.

Who is going to view the railway and in what environment?
Have you checked there are no exposed live electrical components that could be a danger. For example check the plug is wired correctly and that there is no damage to the mains electrical cable. If it’s an outdoor model railway then are all mains electrical parts suitably waterproof or located indoors?
If young children are going to be present then make sure they are no at risk of choking on small objects. In many cases this is best achieved through close supervision whilst they are viewing / interacting with the railway, but you may also want to consider adding a transparent plastic (perspex) screen to prevent them reaching the railway or designing a layout that is child friendly.

Health and safety for model railways - PPE goggles and ear protectors

When modeling – do you know how to use the tools, are you following the manufacturer instructions and are you wearing appropriate PPE?
When dealing with small models then it’s easy to make the mistake of thinking that the risks are also much smaller, but that is not the case. When using something like a rotary multi-tool / drill then the tools can be be spinning at thousands of revolutions per minute. If a small piece of metal or plastic is thrown out at that speed and hits your eye then it can result in permanent loss of sight. In fact due to the thickness of the cutting blades there is an increased risk of a blade breaking off and hitting you. I know that from experience (fortunately I was wearing eye protection at the time, but it could have been different).

Rule 2 – It’s your railway

If it’s your railway then you can do what you want, which is to say that you make up your own rules of how you want the model railway to look. This is based on you wanting to create a railway for yourself. If you are wanting to participate in a club model or create a model for public exhibition then there may be other rules you need to apply, but when modeling for your own pleasure then you make up your own rules.

Rule 3 – It should be fun

Why are you creating a model railway. For most of us it’s because it’s something you enjoy (or you want to try it and see if you enjoy it). Which comes back to rule number 2, you decide what the rules are that will make it enjoyable for you. If you can’t afford to buy expensive scale models and want to include some cheap toys in your layout (Playmobil works very well with Garden Gauge Railways), or if you really want to incorporate something but it’s not quite the same scale or a different era then do it. Feel free to do what you want and as long is it makes you happy then it’s the right thing for you.

What kind of person likes model railways?

You may be under the impression that model railways are just for boys and men that still think they are kids, but that is not the case at all.

Model railways are good for all ages, from young children to great-grandparents,and ability. It’s also just as much fun for girls, whether the girl is into science and engineering and likes those aspects of building a model railway, whether they are a historian and want to make it historically accurate or they prefer to make some kind of fantasy / science fiction world. There is not reason that model railway should be any less appealing to girls as it is to boys. There is something for everyone.

Sci-Fi layout from British Model Railway Challenge
Sci-fi layout winner of the British Model Railway Challenge TV program.

The skills involved in creating a model railway depend upon the type of layout. They could vary from digging the garden and building a brick wall to support an outdoor railway, to painting N Scale model people that are only 1cm tall. There is lots of scope for STEM subjects such as electronics and mechanical engineering; all manner of art from creating scenery items or painting realistic backdrops; and a role for the historian to check on historical accuracy (if that’s the type of layout you want).

Most model railway layouts attempt to create an element of realism, but if that’s not your thing you could create a fantasy land with unicorns, sci-fi space planet or a scene from a horror movie, whatever direction your imagination takes you.

How much space do you need?

You may be thinking that you don’t have the space for a model railway, but having seen some space constrained layouts I’m pretty sure that’s not the case. Many OO scale layouts can fit comfortably under a single bed, N gauge is smaller still and I’ve seen an impressive 9mm narrow gauge layout which packed away inside a box smaller than a briefcase. T-scale is smaller still, although the tiny size of those models is a little too small for me (although amazing to see some of the models that some people have made). Just take a look at the photo below of one that I saw at the Warley Model Railway show 2018.

Small model railway - From Warley Model Railway Show 2018

If you haven’t got space in the house, then how about the garden (if you have one)? It’s a great way to involve the whole family by choosing plants to grow next to the railway.

Guidelines / Information / Hints and Tips

As I said the only really rules for your own railway are the ones you impose on yourself. I have put together a few guidelines that you may want to consider. Feel free to go against these guidelines if you have a reason for doing so.

Scale, ratio and gauge

These are three terms that are often used interchangeably, although there are some subtle differences. Scale refers to something having a direct correlation with real size (usually smaller). The difference in size of a scale model is normally expressed as a ratio, often following one of the common named ratios. The gauge is the distance between the track, but often scale and gauge are used interchangeably as the distance between the gauge is normally based on the same ratio as the scale for the models (though not always quite the same).

The standard gauge for British (and most other country) full size track is 4ft 8½in. Model railways are often based on a scaled down version of standard gauge. Some railways are closer together than standard gauge which is often known as narrow gauge or light-railways. These narrow gauge railways are popular for some railway modellers as they make good model layouts with only a few carriages. The ones marked in the table with an * are narrow gauge railways.

The table below shows some of the most common scales used for British and European model railways.

Name Ratio Gauge Comments
T scale 1:480 3mm This scale is unbelievably tiny. It does look good, but I expect is very difficult to model in.
N scale 1:148 9mm This is a common model railway for those looking for a smaller scale for 9mm. It can be particularly useful where you want to model a large layout, but don’t have the space to create it in one of the larger scales.
OO scale (Double Oh) 1:76.2 16.5mm The most common scale of model railway used within the UK. Ideal for use in a loft, garage or under the bed. The track size is the same as HO, but the scale used for models is slightly bigger making it a little out of the proper ration.
HO (Half-O) 1:87 16.5mm The most common size of model railway used in continental Europe. Similar to the OO standard and on the same width, but with a more realistic ratio.
O Scale 1:45 32mm A scale often used for larger scale models and for some outdoor railways.
16mm Scale 1:19.05 Usualy 32mm * Use for some narrow gauge outdoor model railways in the UK (less popular in Europe).
G Scale 1:22.5 45mm * Also known as garden gauge this is a popular scale for modeling narrow gauge railways that can be used outdoors. There is a wide variety of pre-built items available, although often these are based on European or Americal railways.
Gauge 1 1:32 45mm Less common than G Scale these are standard gauge trains running on the same 45mm gauge as G scale.
Gauge 3 1:22.5 64mm The same scale as G scale, but with wider gauge track for standard gauge trains. Needs a lot of space compared with the other scales listed.

* These are the gauges used for narrow gauge tracks.

Some model railway enthusiasts are very strict in ensuring that where possible their model is true to their desired scale. It is however fairly common for some to use a similar scale when off-the-shelf models are not quite to the same scale. The use of HO and OO on some models where some scenic items intended for European countries are mixed with UK OO scale and a similar thing can happen with 16mm and G-Scale (although the track gauge is different the model scale is quite close).

Belos is an example of a narrow gauge – G-Scale railway.

Example of narrow gauge - G-Scale railway

Era or Theme and Historical Accuracy

Deciding upon a theme or year for the model railway to be based should be an early consideration. You should also decide on how important historical accuracy is to you.

This is perhaps one of the most controversial areas: the model railway purists may insist that you shouldn’t include anything that doesn’t comply with the historical accuracy at the time however having made an investment in a particular item then you may be keen to include that regardless of it’s historical accuracy.

There are sometimes stories that you can use to incorporate the items from a different era. For example if you have a modern railway layout, but would like to include a steam locomotive then you could design in a preservation railway within the layout, or just give a story that it is a historical railway running on the mainline.

At the end of the day remember the three rules above. If you want to include it, but it doesn’t fit with the accuracy then it’s your railway and if you are enjoying creating it then it doesn’t matter if it isn’t historically accurate.

Weathering or New

When buying a model then the chances are that it looks like a pristine brand new version. Weathering is the process of making a model look more realistic by making it look older and dirty. Not everything needs to be weathered as it’s always possible that, if age appropriate, it really is a new locomotive just delivered from the factory. It’s unlikely that all engines and buildings would look brand new.

On the other-hand some people may not want to spray dirty black / brown paint over their brand new model. If that’s you then don’t worry, just leave it as it is and accept how it looks.

Public Displays

When it comes to public displays then there are additional rules that you should follow. These apply whether the display is part of an exhibition, an outdoor public layout such as one at a preservation railway station or an open display on your own land. The main thing is an additional responsibility for health and safety and public liability insurance.

In addition the health and safety considerations already mentioned you may need to look at hazards around the site and periodic testing and certification of live steam engines. For electrical layouts you may need to consider PAT testing of electrical equipment that is in reach of visitors (or better still keep mains electricity away from the visitors).

Liability insurance is a requirement for public displays. If you are part of a model railway society check with them as they sometimes provide public liability if you have an “open day” at your own railway at your home. If not then make sure you take out insurance for a public event.

Thought should also be made about how accessible it is to disabled visitors as there may be a need to make reasonable adjustments for disabled access under the E qualities Act, particularly for a static display.

One final thing that I feel strongly about is swearing. If you are on a public display there should be no need to use bad language particularly when young children may be listening. This happened to me recently as we visited an outdoor model railway at a preservation railway station. One of the members there was talking with other members and used a completely inappropriate 4-letter word which was clearly audible to my son. Once may be a slip-up but then he repeated the same word again straight afterwards. It’s a word that I certainly wouldn’t ever use whilst with my children and was completely inappropriate.

Summary

There are very few rules beyond the need to keep yourself and others safe.

In my opinion having fun is much more important than realism or historical accuracy, but that is something you may want to think about when creating a layout for public display.

Model Railway – designing a G-Scale building for an outdoor model railway in the garden – part 1

November 24th, 2018

This is my first attempt at creating a proper scale model for 3D printing. In this case I am creating a weigh building in G-Scale. This has been a huge learning curve. I’ve since learned from some of the issues in the first model and so part 2 will improve on the techniques shown.

The model is based on a real building located at Winchcombe Station on the Gloucestershire and Warwickshire Steam Railway. The building is opposite the entrance to the station. See the photo below:

Weigh bridge building at Winchcombe Station on the Gloucestershire and Warwickshire Steam Railway

The 3D printed version is approximately in G-Scale (1:22.5 scale). This is also known as garden gauge railway, designed for narrow gauge trains running on 45mm track. It may also work well with 16mm model railways as the size is perhaps a little smaller than G-scale. The main difference between the real building and the scale model is that the model does not use the different coloured brick that is in a curved shape above the window and where the side walls meet the roof. The main reason for this is the time it would take for a feature that I expect few would actually notice if I hadn’t pointed it out.

3D printed model railway Weigh bridge building in G-Scale

Designing the model

The model was designed in TinkerCAD. In this version I have created the model in several parts.

  • The main part of the building from the floor to the top of the door
  • Upper part of the building (including the side walls up to the pitched roof)
  • Internal fireplace and chimney breast
  • Roof
  • Windows (not shown in the photo above)

In general this works, but in a later version I will combine the first three into a single model. The reason for this is that there was some warping of the upper part of the building (perhaps due to the bed temperature). Although this is something that I will need to revisit again in future when creating larger buildings.

The internal fireplace is something that I added as an afterthought on this model, but will be included directly in the next version.

I have created a short video on getting started with TinkerCAD which explains about how to create a simple brick wall.

3D Printer

The printer that I have is a Wanhao i3 Plus Duplicator. This is the perfect size for creating this 3D model, which fits fairly comfortably on the build plate. It would not be possible to create a larger building in a single print using this printer. If a larger building is required (as I hope to do in future) then the model will need to be separated in parts and then fastened together.

Brick effect PLA filament for 3D printer

One of the challenges was in finding an appropriate colour PLA to give a good brick effect. The problem with most suppliers is that the closest the provide is either red which tends to be a bright post box red colour, or brown which is too dark. I had tried experimenting with different colours with acrylic paint when creating a brick wall previously, but then I came across a brick effect PLA filament from Filo Alfa. I couldn’t find a UK supplier for the FiloAlfa PLA so I ordered it direct from the manufacturer in Italy. Unfortunately whilst the cost of the PLA is quite reasonable, the additional cost of shipping meant it was in fact very expensive. I am however very happy with the quality of the PLA which works very well in my Wanhao 3D printer.

Brick Effect PLA 3D printer element from FiloAlpha

The rest of the building (roof and window frames) is made using my normal 3D printer filament for which I normally use either Prima Value PLA (1kg reels) or Prima Select PLA (750g reels) depending upon the colour availability.

Update

The latest version is now available. Information on how this was created is available at:

Details of the changes to the latest version are available version 2 of GScale model railway building.

JLL Piano – Raspberry Pi Music Clip player

October 15th, 2018

This project is called the JLL piano. This is a school project that my daughter created for her music homework. She needed to create a project that related to Jerry Lee Lewis and she created a mini piano that plays a short clip for a different song depending upon the key that is pressed.

Raspberry Pi Piano Hat

It uses a Raspberry Pi with a Pimoroni Piano Hat.

You first need to setup the Piano Hat using the Pimoroni Piano Hat install instructions. Then create the following in a text editor.
The program will work in Python 2 or Python 3.

You can of course change the music clips to be any music you prefer.

import pianohat
import time
from pygame import mixer

# Change key numbering (black keys = -1)
keys = [0,-1,1,-1,2,3,-1,4,-1,5,-1,6,7]

sound_files = [
"/home/pi/MusicClips/jll-wholelotofshaking.wav",
"/home/pi/MusicClips/jll-greatballsoffire.wav",
"/home/pi/MusicClips/jll-milkshake.wav",
"/home/pi/MusicClips/jll-mynameisjll.wav",
"/home/pi/MusicClips/jll-itllbeme.wav",
"/home/pi/MusicClips/jll-highschoolrocking.wav",
"/home/pi/MusicClips/jll-waitinforatrain.wav",
"/home/pi/MusicClips/jll-whenimshaking.wav"
]

def inc_volume(ch,evt):
if evt:
change_volume(1)

def dec_volume(ch,evt):
if evt:
change_volume(-1)

# Change volume by amount specified 0 to 10 (+1, -1 etc.)
def change_volume (change):
#print ("Change volume "+str(change))
if change == 0 : return
# volume is 0 to 1 so divide by 10
delta = change / 10
new_volume = sounds[0].get_volume() + delta
if new_volume > 1:
new_volume = 1
if new_volume < 0: new_volume = 0 for this_sound in sounds: this_sound.set_volume(new_volume) def handle_note(channel, pressed): if pressed: channel = keys[channel] if (channel < 0): return mixer.stop() sounds[channel].play(loops=0) mixer.init(22050, -16, 2, 512) mixer.set_num_channels(13) sounds = [mixer.Sound(sound_file) for sound_file in sound_files] pianohat.on_note(handle_note) pianohat.on_octave_up(inc_volume) pianohat.on_octave_down(dec_volume) while True: time.sleep(0.001)

Programming games with Pygame Zero

October 15th, 2018

Recently I’ve been programming some games using Pygame Zero. Pygame Zero is combination of libraries and other code that interfaces with Pygame to make it easier to program graphical games (or other applications). I’ve created two games so far one of which is designed for the Picade, Raspberry Pi based mini Arcade Machine and the other second is mouse based.

Compass Game

This is the compass game. Use the joystick (or cursor keys) to move the character around the field.

Compass game for Raspberry Pi Picade

More details see:

Memory Card Game

This is the a memory card game. It’s mouse driven.
The supplied cards are based on photos from the Lake District in the UK.

Memory Card Game for Raspberry Pi

More details see:

Raspberry Pi or Arduino NeoPixels (Smart RGB LEDs with ws281x) – including Raspberry Pi 2

August 28th, 2018

I’ve recently been having fun with some NeoPixels on the Raspberry Pi. NeoPixel is the name that Adafruit uses to refer to “Smart RGB LEDs with WS2811 / WS2812 integrated controllers”. I’m sure you’ll agree that NeoPixel has a better ring to it and as that’s the name of the Python library that I’m using.

What is a NeoPixel / RGB LED

NeoPixels are essential three LEDs combined into a single package. One LED is Red, one Green and the other Blue. When the LEDs are turned on together then the LED appears to take the combined colour. For example turn on Red and Blue and you will see purple, or turn on all 3 LEDs and it will appear to be white.

The special thing about the NeoPixels is the WS281x (eg. WS2811 / WS2812) integrated circuit that is included in the same compact package. The integrated circuit allows the LEDs to be individually controlled using a simple serial signal. The LEDs can then be daisy chained together with each LED individually controllable. Note that some manufacturers and suppliers use the IC names interchangably, but it appears that WS2811 refers to the IC without an LED, WS2812 refers to an IC mounted underneath the integrated LEDs. There is also WS2812B which is a newer version of the WS2812.

There are also some older ICs such as the WS2801 which uses a two connection data bus. These have the advantage that timing is less critical (it includes a separate clock signal), but with an extra wire needed. These appear to be less popular with manufacturers so this will mainly concentrate on the WS2812 and WS2812B which are the most common. I will refer to WS2812 and NeoPixels throughout this guide.

More details are available from RGB LED (NeoPixel) page in the Electronics guides.

Data Sheets

The information used for this guide is based on the data sheets for the WS2812 and WS2812B. Note that different manufacturers / suppliers may differ and some of my actual measurements different betwen suppliers.

Power supply

The LEDs require between 3.5V and 5V for the power supply. The higher voltage being required to achieve full brightness of the LEDs so it is assumed most will be looking to run from a 5V power supply. See later for more about suitable power supplies and current requirements for NeoPixels.

Data Signal

The data signal is sent as a serial signal into the Data In of the Smart LED, and after stripping off it’s information that is passed out of the Data Out pin where it normally goes to the Data In of the next RGB LED. Each controller uses 24 bits of data which consists of the values for each of the three LEDs (Red, Green and Blue). So if there are two LEDs being controlled the data will be 48 bits long of which the first LED controller will strip off it’s 24 bit signal passing another 24 bit signal to the next LED. This allows 8 bits for each colour component which is a value of 0 to 255, where 0 is off and 255 is full on.

The timing of the signal is critical and any interuption in the signal will prevent the message from being understood. With a full operating system such as Linux on the Raspberry Pi then the operating system may use processing time for it’s own housekeeping which can disrupt the timing of the signal. This can be overcome using a micro-controller (eg. Arduino) or using the PWM pin of the Raspberry Pi as explained later.

The LED controllers requires an input signal 0.7 x supply voltage for a high signal. In the standard case running the LEDs at 5V then the minimum input for a high is 3.5V. As the Raspberry Pi runs at 3.3V then that is not sufficient to drive the LEDs directly. Some Arduinos that are designed to run at 5V can be used to drive the LEDs without requiring any additional interface.

As the Smart LEDs include an IC controller which is capable of switching the LEDs the signal that needs to be provided along the data signal is minimal (micro Amps).

How to control them with the Raspberry Pi

I had previously heard that the Raspberry Pi had a problem with communicating with the LEDs due to a timing issue and the lack of real time support for writing to the GPIO pins. When I heard about the Kickstarter for MyPiFi.net NeoPixel controller then I quickly backed the project. I was expecting some kind of special integrated circuit on the board that was able to communicate with the NeoPixels (something similar to the AdaFruit FadeCandy), but when it arrived it turned out to be a buffer IC used as a level shifter between the 3.3V of the Raspberry Pi GPIO ports and the 5V signal required for the NeoPixels.

It’s when I looked at the software library I realised that a “workaround” has been found to allow the Raspberry Pi to provide the accurate timing signal. The software uses the PWM controller of the Raspberry Pi to generate the signal required rather than trying to use one of the other GPIO ports. That isn’t to disparage the add-on board. The board does exactly what it says it will and it provides it in a easy to assemble format that fits nicely on the Raspberry pi. You could quite easily do something similar on a breadboard using a simple transistor circuit or an IC, but that isn’t as convenient as the small PCB that is provided.

The initial version of the software library was written by Jeremy Garff WS281x library for Raspberry Pi 1, but it has since been updated to support the Raspberry Pi 2 as well as the existing versions by Richard Hirst Updated WS281x library – includes support for Raspberry Pi 2.

I have created my own software to control the Raspberry Pi using a GUI on the Raspberry Pi, which uses this WS281x library in Python 3.

Installing the software library on the Raspberry Pi

The following instructions will install the drivers and python software libraries onto the Raspberry Pi. The software I use requires the Python 3 version, although you may want to install both python 2 and python 3 to also support other software.

First install the pre-requisite software required to configure and install the libraries (depending upon how much other software you have installed some of these may already been installed although there is no harm in issuing the command anyway).

sudo apt-get install build-essential python-dev python3-dev git scons swig

Download the software (using git this will download the latest version into a folder called rpi_ws281x)

git clone https://github.com/richardghirst/rpi_ws281x.git

Build the software using

cd rpi_ws281x
scons

Change to the python directory
cd python

Install one or both of the following depending upon the version of Python you require.
python 2
sudo python setup.py install
python 3
sudo python3 setup.py install

You can now find an example program to test that it is working as
examples/strandtest.py

Note that if you are using python 3 then you will need to make a change to the strandtest.py file. On line 85
add brackets () around the string in the print statement.
print ('Press Ctrl-C to quit.')

How to control NeoPixels using an Arduino

The Arduino NeoPixel Library is available to download from GitHub:

GitHub AdaFruit – Neopixel library for Arduino

The library needs to be installed into a folder called “Adafruit_NeoPixel” in the Arduino Library folder. Restart the Arduino IDE and look for the example code in the Library Sketchbook.

NeoPixel power requirements

The RGB LEDs can be supplied with

The most convenient and safest way to power the LEDs is using a 5v DC “power brick”. These are similar to the power supplies used for laptop computers, but you must ensure that you have a 5v output as laptops normally use much higher voltages. The power brick must also be able to supply at least the amount of current (measured in Amps) that the LEDs require to prevent damage.

5V 4A Powerbrick from CPC Farnell

According to the data sheet for the ws281x LEDs each device can consume up to 60mA of power when in the white full on mode. Whilst this doesn’t sound much if you connect to a 5 meter 150 LED strip this would be a total power requirement of 9A, which needs a powerful power supply. Whilst you can buy 10A power supplies the powerbricks are very expensive. An alternative is a metal framed power suppy, but these are normally designed to be integrated into another case and do not offer the same electrical safety protection afforded by a powerbrick.

Using the safe 60mA rating means that you can power a maximum of 66 LEDs from the 4A supply listed above. This would allow for 1 meter high density strip, or 2 x 1m strips with wider spacing.

To see if the power requirements were really as high as stated then I took some of my own readings.

I used three different NeoPixel / RGB LED strips and these are example current draws that I measured (per pixel).

AdaFruit 16 Neopixel Circle
Standby current 2mA
Full on current 51mA

60-way 1m RGB LED strip
Standby current 1mA
Full on current 30mA

150-way 5m RGB LED strip
Standby current 1mA
Full on current 30mA

I also found that when powering all the LEDs on the 5m strip that the current was even lower at around 22mA.
The reason for this is likely to be related to the resistance in the strip which results in a lower voltage supply at the LEDs furthest away from the power source. This was also evident as connecting power to only one end of the strip resulted in those at the furthest end appearing to be more of a light yellow colour compared to the bright white at the end nearest the power supply. To avoid this yellowing then I suggest connecting the 5V supply (but not the data signal) to both ends of the strip, or running the strip at a lower brightness.

These values are the maximum power that I saw on these particular strips. The power can be reduced by reducing the brightness of the LEDs or by not turning all the LEDs on at the same time. I recommend sticking to the 60mA draw unless you are able to measure the actual current requirements for your particular LEDs (including a more powerful power to supply to make sure it’s not just the power supply reducing the load due to being overloaded).

To avoid the yellowing I mentioned earlier then for longer strips I suggest that you connect the 5v supply (but not the data) to both ends of the strip.

It is also possible to subdivide the strips and power them from different power supplies. To achieve this the supplies will need to share a common gnd (so that the data signal still has a ground supply), but have isolation between the +5V supply. To achive this you will need to leave the ground (0v) connections connected between both sections of the strips, but break the connection between the +5v supplies.

JST power connectors

If you buy a long RGB LED strip then it may come with 3-pin JST connectors at the end. Others (including the AdaFruit NeoPixel range) may just have connection pads where you can solder your own wires on the end. JST connectors are normally used for connecting power supplies or motors within model cars / aircraft (although often different number of pins) and as such are not really designed for frequent plugging / unplugging. Despite this I decided to stick with JST connectors for my setup. The ones I bought had completely different colours to the ones soldered onto the strips. Instead of using the colours it was important to follow which pin connected to which supply and to connect appropriately. Note that there are male and female connectors to allow these to be daisy chained (as long as you remain within the maximum current of the power supply).

Updated Linux and Raspberry Pi Tutorials

March 27th, 2018

One of the things about creating a web site is having to keep it up-to-date as changes happen. In the case of my PenguinTutor web site that is the changes in Linux and the Raspberry Pi over the last few years. In particular a new release of Raspbian was created last year (based on Debian Stretch) and the latest Raspberry Pi (Raspberry Pi 3B+) was released recently. I’ve now updated the Linux Tutorials and Raspberry Pi guides to reflect those changes. I’ve also taken the opportunity to add some new material including an overview of computer networking and a basic introduction to running Samba on the Raspberry Pi.

I’ve also added a photo of the latest version of the Raspberry Pi.
Raspberry Pi Model 3B+

I still need to review the LPI practice exams (I do try and review them fairly frequently, but it is due another revision) and as a historical record the blog pages won’t necessarily get updated (although I do sometimes add updates where necessary). But for now most of the pages should be up-to-date.

Raspberry Pi 6th Birthday – Birmingham Raspberry Jam 2018

March 3rd, 2018

Today is the weekend of the Raspberry Pi 6th Birthday. In the past the birthday has been celebrated with a large Raspberry Jam in Cambridge (organized by Mike Horne and Tim Richardson). I have been to the earlier birthday celebrations, supporting workshops run by others, giving presentations and running workshops.

For 2018 the birthday celebrations have been expanded to enable more people to take part with over 100 Raspberry Jams around the world. The nearest to me is the West Midlands Raspberry Jam at Birmingham which is organized by Tim Wilson and Spencer Organ. I volunteered to give a short talk and run two workshops at the event.

Unfortunately due to a large amount of snow and safety concerns the event has had to be postponed. The event will hopefully be rescheduled in a few weeks time.

In the meantime I thought I would still make my presentation and worksheets available as planned during the weekend. I still plan to give run these when the Birmingham Raspberry Jam can be rescheduled, but they may be useful in the meantime.

Creating Games on the Raspberry Pi – Space Asteroids

The talk and workshops are all on creating a game for the Raspberry Pi, from creating your own sprites to coding in Scratch or Python Pygame Zero and adding a controller using simple electronics.

The game is a cross between Space Invaders and Asteroids. All the sprites are created from scratch and programmed to interact with electronic button switches and an LED.

Talk on creating sprites using Blender

This is a short talk about what Blender is and how it can be used as a tool when looking to create computer games.

Raspberry Pi Birthday 2018 - Blender talk
Raspberry Pi Birthday 2018 – Presentation notes for talk on using Blender to create Sprites for computer games.

Workshop – Create Space Asteroids, physical computing computer game for Raspberry Pi – Scratch Version

This worksheet is created for a version of the Space Asteroids game that is created in Scratch 2 on the Raspberry Pi.

It’s designed for those young and old who have preferably done a bit of Scratch programming before, but want to take first steps in physical computing or designing an interactive game. It’s also suitable for complete beginners to Scratch, who may need some help to get started with using Scratch.


Space Asteroids physical computing game for the Raspberry Pi - Scratch version  2
Worksheet – Space Asteroids physical computing game for the Raspberry Pi – Scratch version 2

Workshop – Create Space Asteroids, physical computing computer game for Raspberry Pi – Python Pygame Zero version

This worksheet is created for a version of the Space Asteroids game that is created in Pygame Zero (Python 3) on the Raspberry Pi.

This is designed for older students and adults that have already done some programming in Python, but want to learn about designing games in pygame zero or how to connect to simple electronics using gpio zero.


Space Asteroids physical computing game for the Raspberry Pi - Pygame Zero and GPIO Zero (Python 3)
Worksheet – Space Asteroids physical computing game for the Raspberry Pi – Pygame Zero and GPIO Zero (Python 3)

World Book Day – Raspberry Pi and Pimoroni InkyPHat Badge

March 1st, 2018

Today is World Book Day. For the last few years I’ve been supporting my local school by helping run their book sale. Last year I dressed up as The Wizard of Oz complete with Wearable Electronic flashing bow tie. This year I am a little more subtle as I won’t be wearing a full costume, but still keeping with the wearable electronics I’ve gone for a Raspberry Pi powered electronic badge.

InkyPHat wearable Raspberry Pi badge for World Book Day

The badge is based around a Raspberry Pi Zero W, mounted in a Pimoroni PiBow case and a InkyPHat display. The display is based around ePaper / eInk technology (similar to how the original Kindle works). This means it uses very little power and will continue to display the output even after the power is switched off. It does have a bit of a flicker when it refreshes the screen (which takes a few cycles to update), but that only draws attention to the badge. Unlike most other ePaper displays this one can display more than one colour. It can display images in Red, Black and White (although one of these is likely to be the background colour).

You can see the badge in action on the short video below:

I’ve also included the source code of the program, for this you will also need a png file which needs to be created using a 3 colour palette (more details of how to create an Inky Phat compatible image are provided here).

Source code for Raspberry Pi InkyPHat World Book Day badge

#!/usr/bin/env python

import inkyphat
import time
from PIL import ImageFont, Image

font = ImageFont.truetype(inkyphat.fonts.FredokaOne, 32)

message = ""
w, h = font.getsize(message)
x = (inkyphat.WIDTH / 2) - (w / 2)
y = (inkyphat.HEIGHT / 2) - (h / 2)

font2 = ImageFont.truetype(inkyphat.fonts.FredokaOne, 28)
message2 = "Books are\nFun!"

w2,h2 = font.getsize(message)
x2 = (inkyphat.WIDTH / 2) - (w2 / 2)
y2 = (inkyphat.HEIGHT / 2) - (h2)

while 1:
inkyphat.clear()
inkyphat.text((x, y), message, inkyphat.RED, font)
inkyphat.show()
time.sleep(10)

inkyphat.clear()
inkyphat.set_image(Image.open("/home/pi/wbookday01.png"))
inkyphat.show()
time.sleep(10)

inkyphat.clear()
inkyphat.text((x2, y2), message2, inkyphat.BLACK, font)
inkyphat.show()
time.sleep(10)

The image file is below:

World book day InkyPHat image

Twitter Status - follow stewartwatkiss


UK days out, children and holiday information is also available on the Days Out Diary web site
Linux, LPI and the Quiz / Test Program posts are also available on the Penguin Tutor website
First Aid Information, first aid games and first aid practice test / quiz entries are also available on the First Aid Quiz Web site