Sunday, 13 December 2015

Christmas Lights with Raspberry Pi and GPIOZERO

We were in Wilco yesterday and spotted some battery powered LED xmas lights for the bargain price of £2.50. They seemed ideal for a bit of festive hacking


There were a few types available and I picked up 3 different ones: warm white LEDs on a flexible but fairly rigid wire, some brighter white LEDs encapsulated in a snowflake housing and some traditional multi-colour LEDs.

The strings of LEDs come attached to  two AA cells in a neat enclosure with an on/off switch. I snipped the wires fitted jumper wire housings to the end of each so I could plug them straight onto the GPIO header. As the LEDs run on 3v and I was intending to drive them using an 'expendable' model B, I decided not to bother with a series resistor. 


I kept the batteries and the holders - these are bound to be useful for other projects (similar boxes can cost almost as much as the whole LED set).


Then I knocked up a quick Python program to run a mixed illuminate sequence for each of the lights. 

from gpiozero import PWMLED
from time import sleep
import random
import threading

white = PWMLED(23)
snowflakes = PWMLED(18)
colours = PWMLED(25)

LIGHTS = [white,snowflakes,colours]

def gentle(lights):
    for x in range(1,100):
        lights.value = x/100
        sleep(0.05)

def randomblink(lights): 
    lights.blink(random.randint(1,10)/10,random.randint(1,10)/10,10,False)

def sequence(lights):
    while True:
        print('gentle')
        gentle(lights)
        print('sleep')
        sleep(random.randint(1,10)/10)
        print('blink')
        randomblink(lights)
        print('sleep')
        sleep(random.randint(1,10)/10)
        print('on')
        lights.on()
        print('sleep')
        sleep(random.randint(1,10))

for i in LIGHTS:
    t = threading.Thread(target=sequence, args=(i,))
    t.start()


I then added a line to the /etc/rc.local file on the Pi so that the Python code runs automatically at startup.

Our Christmas tree was already quite covered with decorations so I decided to use these new lights on our spiky cactus!




Friday, 11 December 2015

BOM for sub-£15 Raspberry Pi robot

A few people on Twitter asked for a BOM for my CodeClub sub-£15 robot kit. So here it is:


Chassis, wheels, motors and battery pack - £6.57



L9110S DC motor driver board - £1.72


Power bank - £2.67

HC-SR04 ultrasonic distance sensor - £0.99


I already have enough Pis, cases, breadboards and leads but for completeness if you were starting from nothing:

mini breadboard - 5 for £2.09
M-F jumper leads - £0.89
F-F jumper leads - £1.05

For the Pi itself, any model will do. I'm planning on using our original model Bs but if you were buying just for this project I'd go for model A+s or o Pi Zero.

In many cases you can get the components even cheaper (per unit) if you're buying larger quantities.

The only other thing you'll need is AA cells to power the motors and (optionally) a wifi dongle if you want to remotely control the robot.

In oder to fit everything onto the chassis shown above I had to drill some extra holes, mainly to accommodate the Pi in its PiBow case and allow the power bank to be slung underneath.  Although this worked fine, I wanted to make things simpler so I've been developing a 3D-printed chassis that has slots for the main elements and also allows the Pi (the heaviest part) to sit more towards the centre.


My plan is that over the holidays I'll finish off some of the activity plans for building this in CodeClub next term and share them online.

Tuesday, 1 December 2015

Raspberry Pi Advent Calendar with SenseHAT

We missed out on a Lego Advent calendar this year so I decided to code up one for the Pi and the SenseHat.



The top 6 rows of the LED matrix are used to show the days on the month, each one being represented by 2 LEDs . Every day a new pair of LEDs illuminates and you can then select them using the joystick to navigate (your cursor is a pair of bright red LEDs). Pressing the joystick as a button will then display the day number followed by a Christmas image or animation created by my son Ozzy.





To make it funky, each day the grid redraws itself with different coloured LEDs in each position.

Everything you need is in this Github repo. Clone it and then run advent.py

Because the images are just 8x8 bit, they can take a little bit of imagination to work out (the Dec 1st is a snowball fight, before you ask!). You can, of course use your own content for each day. The static pictures should go in the pngs folder: name them decx.png, where x is the day. Animations should be added as a list of frames to animations.py  (follow the format of the existing ones).




You can use my 8x8grid drawing program to create your images and animations.

I wrote this in a bit of a rush so let me know if you spot any bugs surprise features!

Friday, 27 November 2015

Pi Zero soldering

Well, yesterday was certainly exciting! The launch of Pi Zero was an amazing, fun and rewarding day. I'd tried to warn as many people as I could that they should get down to the shops early or - even better - reserve a copy of The MagPi in advance.

Quite a few of my Y5-6 CodeClub listened and demanded politely asked that their parents get them a copy on their way to work. One boy was amusingly concerned at lunchtime when I told him that some shops had already sold out!

I was also pleased to see that the work we've been doing has got them thinking along the right lines: the first thing they asked when I showed them the Pi Zero was 'how do we connect things to those funny GPIO pins?" I showed them the Pi Zero I had in the Zero Bot and the female header I'd used on that.


When I explained that all you had to do was solder on a header, those who made the DIY Gamer kits last year seemed fairly relaxed. Some of the new clubbers, especially those who hadn't done any soldering before, looked less convinced. Even after showing them the excellent page of instructions in the MagPi, a couple said that it looked really complicated.

So I decided to put together a short video to cover the procedure.  I thought it came out quite well and so I thought I'd share it more widely.




Monday, 2 November 2015

Hallowe'en Pis

This year we ended up with three Raspberry Pis powering or controlling our Trick or Treater greeters (scarers).



Spooky Spider

A cheap spider decoration, hollowed out and enhanced with an A+ and a motion sensor that activated  evil red eyes.



The skinny power bank powered the Pi happily for over 4 hours.


The styrofoam body of the spider made it easy to hollow out a cavity for the A+



      



import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

# Setup the pins we'll use
GPIO_PIR = 26
GPIO.setup(13,GPIO.OUT)
GPIO.setup(GPIO_PIR,GPIO.IN)
GPIO.setup(15,GPIO.OUT)


print "PIR Alarm active (CTRL-C to exit)"

Current_State  = 0
Previous_State = 0

try:

    print "Waiting for PIR to settle ..."

  # Loop until PIR output is 0
    while GPIO.input(GPIO_PIR)==1:
        Current_State  = 0    

    print "  Ready"     
    
  # Loop until users quits with CTRL-C
    while True :
   
    # Read PIR state
        Current_State = GPIO.input(GPIO_PIR)
   
        if Current_State==1 and Previous_State==0:

            # PIR is triggered
            print "  ALARM!"
            GPIO.output(13,1)
            GPIO.output(15,1)
            time.sleep(5)
            GPIO.output(13,0)
            GPIO.output(15,0)
            # Record previous state
            Previous_State=1
      
        elif Current_State==0 and Previous_State==1:

        # PIR has returned to ready state
            print "  Ready"
            Previous_State=0
      
        # Wait for 10 milliseconds
        time.sleep(0.01)      
      
except KeyboardInterrupt:
    print "  Quit" 
    # Reset GPIO settings
    GPIO.cleanup()

A (cute rather than scary) bat that descended from the porch, also activated by a Pi with a motion sensor and lowered by a stepper motor.


The Pimoroni BlackHAT Hackr and the Pi touch display made is really easy to set everything up on the windowseal so that just the wires from the picoborg board could be passed out through the window to the motor. A shaft adapter and some Lego made a nice winding mechanism.



A sinister Lego skull with Pi-controlled blinking eyes.


Why bother building some supports for the breadboards when you can just wedge the LEDs through the eye sockets. I don't know, kids today, eh?




Ozzy wrote the code for this and I thought the use of a simple random function to control the frequency of blinking was particularly effective and gave the impression of a lurking creature rather than just a thing with regular flashing eyes.

import RPi.GPIO as GPIO
import time
import random

GPIO.setmode(GPIO.BOARD)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)


def eyes_blinking(pin1,pin2):
    GPIO.output(pin1, GPIO.HIGH)
    GPIO.output(pin2, GPIO.HIGH)
    time.sleep(random.randint(1,3))
    GPIO.output(pin1, GPIO.LOW)
    GPIO.output(pin2, GPIO.LOW)
    time.sleep(0.2)
counter = 0
while True:
    eyes_blinking(13,15)
    counter+=1
    print ('boo ' + str(counter))

Monday, 5 October 2015

Squeezing Raspbian Jessie on to a 4GB SD card

The promise of sudo-free access to GPIO was just too tempting so, despite the fact that I'd only created the whole club set of fresh SD cards before the start of term, I decided to re-create them with the fab new Jessie image.

The challenge: We have a bunch of original model Bs which are still perfectly good for a lot of the circuit based activities but they all have 4GB SD cards. I could just buy a bunch of 8GB ones, but that seemed like a waste.

But the new Jessie image clocks in at over 4.3GB. Here's how I made it fit. It might look a little daunting but its actually quite straight forward. the only tricky bit I found was keeping track of the cards at the various steps. There is probably an easier way of doing it, but this worked for me and only took an hour (with most of that time taken by waiting for the cards/partitions to copy).

What you'll need:
  • A 4GB SD card (call it card F) with a working (but un-needed) Wheezy installation (card M) , a blank 8GB SD card and one at least 16GB card with a working Raspbian installation (card S) or another Linux/Mac machine with enough free space to store GBs of images.
  • An SD card reader



1. Download the Jessie image. In some circumstances, because the unzipped file is >4GB, you may encounter difficulties extracting the compressed image. On a Mac, you'll need to use a tool like the Unarchiver. Store this .img on your Pi booted with the 16GB card (S) or your Mac/Linux box.

2. Insert card M into the reader and write the jessie image to it. Then remove card M from the reader.

3. Now take your 4GB card (F) and put that in your card reader (still attached to the Pi booted with card S or using your Linux/Mac) and display the current partition information of the 4GB card (F) and note it down. 

sudo fdisk -l /dev/sda

Disk /dev/sda: 8068 MB, 8068792320 bytes
249 heads, 62 sectors/track, 1020 cylinders, total 15759360 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xba2edfb9

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1            8192      122879       57344    c  W95 FAT32 (LBA)
/dev/sda2          122880     7710719     3793920   83  Linux

4. Now shutdown and boot with card M. Personalise as needed (e.g whether to boot to desktop, swap default background etc).

5. Now for the slimming down. Remove Wolfram/mathematica

sudo apt-get purge wolfram-engine

6. Remove LibreOffice

sudo apt-get purge libreoffice*
sudo apt-get purge libreoffice-base
sudo apt-get purge libreoffice-impress
sudo apt-get purge libreoffice-writer
sudo apt-get purge libreoffice-calc
sudo apt-get purge libreoffice-draw
sudo apt-get purge libreoffice-math
sudo apt-get clean
sudo apt-get autoremove

7.  Remove any empty icons from the top menu bar and the main drop-down menu. Reboot

8.  You should now find that your build uses less than 4GB. 

df -h

Filesystem      Size  Used Avail Use% Mounted on
/dev/root       3.4G  2.4G  763M  77% /
devtmpfs        182M     0  182M   0% /dev
tmpfs           186M     0  186M   0% /dev/shm
tmpfs           186M  4.5M  182M   3% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           186M     0  186M   0% /sys/fs/cgroup
/dev/mmcblk0p1   56M   20M   37M  36% /boot
tmpfs            38M     0   38M   0% /run/user/109
tmpfs            38M     0   38M   0% /run/user/1000

Also, have a look at the partition table with 

sudo fdisk -l /dev/mmcblk0

Disk /dev/mmcblk0: 7.4 GiB, 7892631552 bytes, 15415296 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xba2edfb9

Device         Boot  Start     End Sectors Size Id Type
/dev/mmcblk0p1        8192  122879  114688  56M  c W95 FAT32 (LBA)
/dev/mmcblk0p2      122880 8447999 8325120   4G 83 Linux

You can see that the second partition is still too big to fit on the 4GB card, even though not all the space is being used. 

9. Now Boot SD card S in your Pi and insert card M into the SD card reader (or use another Linux/Mac for this step).  These instructions assume that card M is now available as /dev/sda
Now we can shrink the 2nd disk partition:

sudo e2fsck -f /dev/sda2
sudo resize2fs /dev/sda2 3500M

10. Now we need to modify the partition table of card M to match.   Make sure you run fdisk against the correct disk! We need to edit the second partition, so run fdisk in interactive mode.

sudo fdisk /dev/sda

We can't simply resize it, we have to delete it and recreate it with a smaller size:

Press d to delete a partition, then 2 to select sda2.
Now add a new partition by pressing n, followed by p, then 2 (this creates a new, primary position, number 2)
It will ask you what sector you want this new partition to start at. Use the same starting value as we saw in step 2 (in this case, 122880), and give the end sector to match a normal 4GB layout - 7710719

Now press p to display the new layout and check that it matches the desired situation. When you're happy, press w to write the changes to the card.

11. Reboot with card M and check everything still works.

12. Now boot back into your big SD card (or other Linux/Mac box). Take a copy of the two individual partitions on SD card M using dd or dcfldd

dcfldd if=/dev/sda1 of=image4GB-p1.img
dcfldd if=/dev/sda2 of=image4GB-p2.img

13. Now swap the card in the reader (M) for card F (the 4GB one). Write these copied partitions  to your 4GB card.

dcfldd  if=image4GB-p1.img of=/dev/sda1
dcfldd  if=image4GB-p2.img of=/dev/sda2

14. Now boot from this card (M). It should be identical to the 8GB image.  If you want to make more 4GB installations of Jessie, just copy this entire card (no need to bother with individual partitions now we've got everything squeezed in).

Thursday, 24 September 2015

Skycademy HAB payload testing with a kite


One of the big takeaways for me from Skycademy was the importance of testing each element of the flight. Its' easy to get things working at home or in the classroom, but you really need to head outdoors to put some of the kit (GPS, mobile Internet, payload assembly) through their paces.

A modified version of my kite-mapping project seemed like it might be a good way of ironing out the bugs and also provide a fun way for children to get involved even if they won't be able to come to the actual launch. When I tried it, it all worked really well. Here's my step-by-step.

What you'll need

A pack of small zinc plated screw hooks and eyes
A styrofoam box
Some strips of balsa wood
Duct tape
Adhesive backed velcro strips
Kite line (100 pound flying line)
3 x Medium size washers
2 x Carabiners (the diameter of the tubing should be able to fit through the hole in the washers)
A delta kite - anything with a 7 foot wingspan or above will have enough lift.
A long kite tail and two streamers for the wings.
Gardening gloves
Raspberry Pi (A+ is ideal)
Pi-in-the-sky board
LORA board (optional)

For aerial photography, I like to use a picavet rigging to keep the payload as steady as possible. There are plenty of ways to make one of these - this is a good set of general instructions.
1. Construct your payload container. I can't see any reason why the container for a kite flight should be any different for that of a HAB launch.  A simple styrofoam box makes a good starting point.


2. Attach the picavet mount. I used 7mm think balsa wood to create a cross that extends just over the lid of the box.  I attached the wood to the styrofoam using a hot glue gun: apply a layer of glue to the wood and then press it onto the box lid (if you apply the glue directly to the styrofoam, it will melt).


3. Attach four of the eye screws, one at each end of the cross of balsa. They should just screw in by hand without any drilling.


4. Thread the picavet line. Use a washer at the centre and two at the top. Tie the kite line to one washer and then thread as shown below. Tie off the end of the line back at the first washer.


I then like to use a cable tie around the kite line under each washer.


Thread a narrow carabiner through the washers. You'll use these to attach the whole thing to the kite line.

4. Test radio comms. Check that your Pi-in-the-sky board can communicate with your radio receiver. Ditto for the LORA board.

5. Test HabHub uploading. Make sure you have Internet connectivity for whatever device is receiving your transmissions. Check that data is appearing on the map.



6. Choose a flight location.  You don't need a huge amount of space, but ideally you'll want a clear area  twice as wide and long as the height you intend the kit to reach. I normally have 200m of line so an ideal site will be free of obstructions (trees and roads etc) for circular area of 400m diameter.


7. Assess the wind. You need some wind for the kite to fly. A big delta kite doesn't need much to get aloft, but if you want it to stay up you need at least 8mph of constant breeze. Anything much above 15mph is probably too much and you'll have a real tough time reeling the kite in again when you've finished. I have two kites: a 7' and a 9' are both are easily capable of lifting a Pi payload. Obviously the bigger kite can lift heavier payloads, but the wider wingspan and overall larger canvas area (it's 4.5' tall)  can get pulled about too much in strong winds and be less stable than the smaller one.

8. Prepare your kite. Assemble the kite and attach the main tail and wing streamers.  These are vital to keeping the kite level and stable in the air. Most delta kites are a similar design: a fiberglass cross spreader is inserted and this keeps the wings rigid around the central spar.  Make sure that the outside spars  are pushed down to the bottom of the sail and that they're not bunched up with fabric or bent.

9.Test flight. Without the payload, get the kite up in the air. take it up to at least 20 or 30m and assess the conditions. Is the kite jerking around? If it's not too stable, try increasing the altitude. If you still find that it is dive-bombing or suddenly changing position with gusts, you might want to abort the test flight until the wind is more settled. Make sure you put your gloves on before winding the kite in. Kite line can give you really nasty deep cuts or friction burns.



10. Attach the picavet. Assuming you're happy with the conditions, bring the kite down to just a few metres and attach the picavet carabiners. This is where having someone to help is useful. One person holds the kite reel while the other attaches the payload. Clip one carabiner  over the line and then twist it so that you wrap the line around the tubing several times.  Then do the same with the second carabiner, making sure that their spacing on the line isn't too wide (ideally it should be just slightly wide than the separation of the mounting points of the line on the longest edge of the picavet.


If it's just too windy or your by yourself, then land the kite and sit on it while you attach the payload. This sounds like an easier approach but there is more chance of the line getting tangled in the tails/streamers or the payload being dragged along the ground when you eventually take the kite airborne again.


12. Fly. Let the line out steadily and keep on eye on the flight pattern as you get higher. Listen to the kite string. If it is really thrumming then beware of sudden jerks, especially if you're letting children hold the reel.  Make sure everyone who holds the reel or line wears gloves.


13. Wind the kite in.  This can take a long time! A kite being flown at 150m may take up to 30 minutes to wind in!