BBC micro:bit guinea pig timed feeder instructions

This blog post is the instructions on how to use a timed servo motor circuit that I lashed up as part of a guinea pig feeder for a friend.

The hardware details can be found here: here

Software is on my GitHub site here

The need

A friend wanted something to open a box of food to feed his guinea pigs. The box needs to open after an adjustable time.

I can think of no more noble cause to focus on than feeding our furry friends.

After a period of procrastination and confusion I supplied the hardware and software detailed in this post. The mechanical components that the device will operate are up to my friend to make. He is a highly experienced mechanical engineer. I am but a lowly electronics tech.

Between the two of us, the guinea pigs will be fed!

Description

The microbit counts down for a preset amount of time. The remaining time is indicated on the LEDs on the microbit. At the end of the pre-set time, the servo motor lever moves 90 degrees. The two positions of the servo motor are shown in the pictures below.

The timer is adjusted using the A and B buttons as detailed in the Instructions section below.

Servo motor position while the timer is in operation
Servo motor position once the timer completes the countdown

Instructions for use

The A button adds 12 minutes to the timer. An extra LED will light up for each press of the button. The B button decrements 12 buttons from the timer. An LED will turn off for each press of the button. The photograph below shows two lit LEDs on the microbit, indicating 24 minutes or less are left on the timer.

The two lit LEDs indicate that 24 minutes are left until the servo motor is activated

The last timer setting is recorded to the memory on the microbit. When the board is reset, it will start counting down from this time. So, if you set the timer to 2 hours (10 LEDs lit), on resetting, you will see 10 LEDs lit up and the board will take 2 hours to trigger the servo motor.

The reset button on the back of the board restarts the board. Please see the photograph below which shows the position of this button.

Underside of the microbit with the rest button indicated, next to the battery connector

Hardware description

The components of the system are shown in the picture below. On the left is a AAA battery pack containing 2 x AAA batteries. I use battery packs with a switch, which I get from eBay. The microbit is in the centre, slotted into a kitronik microbit edge connector. This edge connector allows the signal pins of the microbit to be connected to the servo motor using female to male jumper cables . The cables are designed for the 0.1″ pins and sockets found on the edge connector and the cable connected to the servo motor.

AAA. battery pack, microbit, servo motor

The full assembly including cabling is shown in the photo below.

AAA battery pack (right), microbit and edge connector board (centre), servo motor (top), connectors (right)

A close up photo showing how the cables from the edge connector and the servo motor connector are connected is shown below. The black/brown wires are ground, the red wires are the battery voltage and the yellow wire is the PIN0 signal line.

Pins from cables connected to the Kitroniks edge connector on the left, sockets connected to the servo motor on the right

The photo below shows how the cables connect to the pins on the Kitronik edge connector.

Cables connected to the Kitronik edge connector. Yellow goes to 0, black to 0V, red to 3V.

Automating loading micropython code to the BBC micro:bit in Linux

Introduction

When I edit micropython for a microbit project, I want the code to automagically load onto the microbit each time that I save the code. Then I want to see any messages from the microbit displayed. I worked out a toolchain that does this under Linux.

I summarise the toolchain in the next section, then go through each step in more detail.

For the examples in this post, I am editing a file called ‘feeder.py’.

Toolchain

Use your favourite editor for creating your code with. The toolchain to load the code to the microbit kicks off when you save the file.

There are four tools needed to automate the process.

  • A script to locate and mount the microbit. I wrote a blog post about this script here.
  • The uflash utility to write the micropython file to the microbit.
  • screen terminal to display messages from the microbit
  • inotifywait command to monitor the micropython file being edited

uflash

Use pip to install this. Details are in the link given earlier in this post. To load a_file.py to an attached microbit, simply type:

uflash a_file.py

Using virtual environments makes my life easier, so I use one for my microbit programming. There are plenty of blog posts detailing how to set up and use these.

script to attach a microbit

I wrote a blog post on how to create a script that automatically locates and mounts a microbit here. This script is aliased to mm and md in my .bashrc file to mount a microbit and dismount a microbit.

screen

screen is built in to most Linux distros, so I use it here. This connects to the port that is in use by the microbit and displays any output from the microbit.

You need to know what port your microbit is attached to though. On my laptop this is often /dev/ttyACM3, which I use in the example below.

I present a script in the next section to automatically find the port that the microbit is connected to and fire up a screen connection using this.

To fire up the connection manually, if you know the port (in this example /dev/ttyACM3) use:

screen /dev/ttyACM3 115200

Remember to kill screen without leaving it running in the background by using:

control-a k

One potential problem with screen, is that it is easy to ‘detach’ from screen instead of ending the process, which leaves an instance of screen running invisibly which is attached to the same port as the microbit. When you come to try and run screen or connect to the microbit again, you will see an error like the one below:

can't open device "/dev/ttyACM3" 

To find and kill the errant screen instance:

lsof | grep /dev/ttyACM3

If you get something like:

screen  8610  elm    5u   CHR  166,3      0t0 5599015 /dev/ttyACM3

You still have a screen instance attached to the port. The PID is the second value in the list, in this case 8610. Kill it using e.g.

kill 8610

One way to prevent this potential problem is to replace screen with another terminal display tool such as gtkterm.

script to automate finding and connecting to the microbit

The python3 script below automates finding a connected microbit. The script starts a screen session on the port that the microbit is connected to.

'''
Find pyboard or microbit and open a terminal.
Created on 4 Nov 2015.
From http://wdi.supelec.fr/boulanger/MicroPython/
Usage: find_device [device]
Calls screen on "device". If device is not given, looks for /dev/ttyACM* devices
then /dev/tty.usbmodem* devices (for MacOS).
'''
#!/usr/bin/python
import sys
import os
import fnmatch

BAUD = 115200

def main():
    if len(sys.argv) > 1:
        ttymodems = [sys.argv[1]]
    else:
        ttymodems = fnmatch.filter(os.listdir('/dev'), 'ttyACM*')
        if len(ttymodems) == 0:
            ttymodems = fnmatch.filter(os.listdir('/dev'), 'tty.usbmodem*')
        if len(ttymodems) == 0:
            print('Error: no pyboard found.')
            sys.exit(1)
        ttymodems[0] = '/dev/' + ttymodems[0]
        print('connection at: {}'.format(ttymodems[0]))
    os.system('screen '+ttymodems[0] + ' {}'.format(BAUD))

if __name__ == "__main__":
    main()

inotifywait

inotifywait is a command line tool that can be configured to watch a file for a change, then trigger an action. Here we use it to watch for a change in the micropython file being edited. When this file is saved, inotifywait mounts the microbit and flashes the file to it.

If infotifywait is not already installed, then you need to install inotify-tools.

The command to watch a file called feeder.py for a change, then run the alias mm (to mount the microbit) and to flash the file to the microbit is:

while inotifywait -e modify feeder.py ; do mm && uflash feeder.py ; done

I would have formatted the above line as the other code in this post but found that the syntax highlighter plug-in refuses to show the ampersand symbol correctly.

notes

Some editors have the ‘feature’ of ‘kind of’ saving the file you are editing while you are editing it. This creates a new timestamp for the file and activates inotifywait without your saving the file. mu is one of these editors. In this case, I do not use inotify and run the following command from the command line each time I want to flash the updated file. In this example the updated file is called feeder.py:

mm && uflash feeder.py

but why not use a Makefile

Makefiles are typically used to build programming projects, detailing the dependencies of each component. The file is run when ‘make’ is typed on the command line.

The one-liner command using inotifywait is fine for this simple example where we are editing a single file. Which is most of what I do with the microbit and micropython. Makefile comes into its own for more complex builds involving multiple files. It allows for extra run-time options to be added, e.g. to clean files created by earlier builds.

For completeness, I present a simple Makefile below for this project. Makefile is a useful tool that is worth learning to use for when we have larger projects to build.

Makefile

I created a Makefile containing commands to mount the microbit to the Linux filesystem, then flash a micropython file to the attached microbit.

An example Makefile is below. Note: Use tabs to create the indents after the line ‘run:’. Or the World Ends. The supporting file microbit_mount.sh is in the same directory as feeder.py to keep it simple.

MICROPYTHON_FILE=feeder.py

run:
	./microbit_mount.sh mount
	uflash $(MICROPYTHON_FILE)

In this example, microbit_mount.sh is the script to attach a microbit, detailed above.

uflash is the tool used to write the .py file to the microbit. This is detailed above.

To automate the Makefile being run each time that we save new code, we can use the inotifywait command below:

while inotifywait -e close_write feeder.py ; do make; done

how to configure the accelerometer range on the microbit using micropython

This article details how to set the range of sensitivity on the accelerometer on the microbit board using micropython and the i2c interface. I am using v1.7.9 of micropython for the microbit, the mu editor and linux mint v17.
 

After listening to Joe Finney talk about his role in developing the microbit board I realised I could use it for some of my hand gesture assistive technology work. The accelerometer on the microbit board is an MMA8653FC, data sheet here. There are programming notes for this chip here. The default range for this chip is +/-2g. This can be reconfigured to be +/-4g or +/-8g. For some of the students I work with on gesture recognition I need the higher ranges. So I entered the world of microbit i2c programming. I chose the micropython platform as python is always the ‘second best choice’ for any programming application. Actually, I’m a fan of using C for embedded hardware, but in this case using micropython looked to be fastest way of getting a solution. I used the simple mu editor. Long story short, it’s all about syntax. Thanks go to fizban for his example microbit code to interface a microbit with an lcd display using i2c. After reading this code I fixed the mistake(s) I’d been making. The documentation for the i2c microbit micropython is here.

Here’s my working code:

''' microbit i2c communications with onboard accelerometer '''
from microbit import *

ACCELEROMETER = 0x1d
ACC_2G = [0x0e, 0x00]
ACC_4G = [0x0e, 0x01]
ACC_8G = [0x0e, 0x02]
CTRL_REG1_STANDBY = [0x2a, 0x00]
CTRL_REG_1_ACTIVE = [0x2a, 0x01]
PL_THS_REG = [0x14] # returns b'\x84'
PL_BF_ZCOMP = [0x13] # returns b'\44' = 'D'
WHO_AM_I = [0x0d] # returns 0x5a=b'Z'
XYZ_DATA_CFG = [0x0e]

def command(c):
''' send command to accelerometer '''
i2c.write(ACCELEROMETER, bytearray(c))

def i2c_read_acc(register):
''' read accelerometer register '''
i2c.write(ACCELEROMETER, bytearray(register), repeat=True)
read_byte = i2c.read(ACCELEROMETER, 1)
print('read: {}'.format(read_byte))

def main_text():
''' send accelerometer data as a string '''
print('starting main')
counter = 0
while True:
x = accelerometer.get_x()
y = accelerometer.get_y()
z = accelerometer.get_z()
counter = counter + 1
print('{} {} {} {}'.format(counter, x, y, z))
sleep(250)

print("sending i2c commands...")
print('reading PL_BF_ZCOMP :')
print(i2c_read_acc(PL_BF_ZCOMP))
print('reading WHO_AM_I')
print(i2c_read_acc(WHO_AM_I))
# check the initial accelerometer range
print('reading XYZ_DATA_CFG:')
print(i2c_read_acc(XYZ_DATA_CFG))
# change the accelerometer range
command(CTRL_REG1_STANDBY)
command(ACC_4G)
command(CTRL_REG_1_ACTIVE)
print('commands sent')
# check the accelerometer range
print('reading XYZ_DATA_CFG:')
print(i2c_read_acc(XYZ_DATA_CFG))
display.show(Image.MEH)
# main_text()

output:

reading PL_BF_ZCOMP :
read: b'D'
None
reading WHO_AM_I
read: b'Z'
None
reading XYZ_DATA_CFG:
read: b'\x00'
None
commands sent
reading XYZ_DATA_CFG:
read: b'\x01'
None

The onboard accelerometer has an i2c address of 0x1d. There is a good article on how to scan for and verify this address here. I set the variable ACCELEROMETER to be this value in line 4 so that I could refer to it throughout the code without having to remember the hex value. Too many hex values flying around – I’d be bound to make a mistake if I didn’t give them names.

To send a command over i2c, as shown in line 18 of the example code, you need to address the target then send the commands as a bytearray. In this case the target is the accelerometer. Typically we send two bytes to the accelerometer. The first specifies the register we want to change, the second the value we want to write to this register. For example, to set the accelerometer’s range of sensitivity, we need to set the value of the register called XYZ_DATA_CFG to the value that corresponds with the range we are after. The address of this register is 0x0e. To set the +/4G range, we want to set this register to be 0x01. Now the variable I set in line 6 should make sense. Look in the data sheet linked above for more details. Before we can change this register we have to set CTRL_REG1 to be inactive by writing 0x00 to it. After changing the XYZ_DATA_CFG register we have to set CTRL_REG1 to be active again by writing 0x01 to it. This is detailed in the accelerometer application notes which I linked at the start of this article.

If you uncomment the last line, then the raw accelerometer values will stream out. The last column are the values for the z-axis of the accelerometer. Lay the board flat on the table. With the default +/-2g range you will see the z-axis values being around +1024 or -1024 depending on if the board is face up or down. This corresponds to +/-1g on the +/-2g range. Now that the board is set to +/-4g, the values for +/-1 g will be +/-512. The maximum and minimum value for the accelerometer stays as +/-2048, but it is now spread over +/-4g. Similarly, if you go crazy and set the range to be +/-8g, then you will see +/-256 for the z-axis value from the accelerometer for the board laying flat. As you would expect, you have to wave the board harder to get it to max out when you set the sensitivity to the higher ranges compared with the default +/-2g range.

So what about the PL_BF_ZCOMP and WHO_AM_I registers that I read from in lines 43 and 45? These are two read only directories. Reading the values stored in these is a sanity check that the chip is turned on and I have working code. I read the XYZ_DATA_CFG before and after setting it to verify that the sensitivity range has been set. Read up on these registers in the data sheet.

Look at line 23. The repeat=True flag has to be set. This clears the ‘message end’ flag in the write command. The default for this flag is False, which means that the i2c write command has a ‘message end’ flag at the end of it, which terminates the operation. As we want to read from the chip in line 24, we need to not set the ‘message end’ flag. Otherwise you will just read 0xff. Can you guess why? The data line is held high for i2c, so if there is nothing coming out of the chip you are trying to read from, you just read a bunch of ‘1s’. Line 24 means ‘read 1 byte from the device with address ACCELEROMETER’.

Where I initially came unstuck was by sending data as individual bytes, using e.g. b’\x0e’ followed by b’\x02′ to try and change the XYZ_DATA_CFG register. This looks to be valid for the Adafruit implementation of micropython, but I couldn’t get it work.

parsing and unpacking python3 serial data containing double backslashes

edit 11th October 2017: The ‘eval’ statements in the code shown below can be replaced with the safer ‘literal_eval’ from the ast class in the standard library. From the python docs: ‘Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.’

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

I lost a day of my life figuring out how to parse serial data sent as bytes from the BBC Microbit using micropython. The problem is that the data byte string appears with double backslash characters instead of single backslashes when read in over a serial interface.
Actual data:

b'ST\\x00\\x00\\x00\\xe0\\xeaE\\x00\\x00HB\\x00\\x00`\\xc3\\x00\\x00\\x10C\\x00\\x00t\\xc4EN'

What I wanted as data:

b'ST\x00\x00\x00\xe0\xeaE\x00\x00HB\x00\x00`\xc3\x00\x00\x10C\x00\x00t\xc4EN'

So how to convert from one misformed byte string to the clean one that python 3 would use?
I really went around in circles on this one. In the end I used a kludge. But it works. My life can now move on.
I convert the double slash byte to a string. Then I use the replace method to replace ‘\\’ with ‘\’. Then I use the literal_eval function to recast it as a byte. I am open to suggestions for a cleaner way of doing this!
Here’s some example code I used in a jupyter notebook session. test2 is the misformed byte string received over the serial interface and test3 is the cleaned byte that I can now unpack and extract the data from.

from struct import *
from ast import literal_eval
PACKER = ('2s5f2s')
test2=b'ST\\x00\\x00\\x00\\xe0\\xeaE\\x00\\x00HB\\x00\\x00`\\xc3\\x00\\x00\\x10C\\x00\\x00t\\xc4EN'
test3 = str(test2)
test3 = test3.replace('\\\\', '\\')
print('{}'.format(test3))
test3 = literal_eval(test3)
print(test3)
print(unpack(PACKER,test3))

output:

b'ST\x00\x00\x00\xe0\xeaE\x00\x00HB\x00\x00`\xc3\x00\x00\x10C\x00\x00t\xc4EN'
b'ST\x00\x00\x00\xe0\xeaE\x00\x00HB\x00\x00`\xc3\x00\x00\x10C\x00\x00t\xc4EN'
(b'ST', 7516.0, 50.0, -224.0, 144.0, -976.0, b'EN')

The data was produced from reading the accelerometer on a BBC Microbit board then using struct.pack(PACKER,scan). I am programming the boards using micropython.
The data is packed using the packer format:

PACKER = ('2s5f2s')

The transmitted scan is constructed using:

values = (START, counter, DELTA, x, y, z, END)
scan = struct.pack(packer, *values)

Where values contains a START and END string (‘ST’ and ‘EN’ respectively), a constant called DELTA which represents the time in between samples and the x, y and z readings from the accelerometer. So PACKER means ‘2 characters followed by 5 floats followed by 2 characters’.
I was being obstinate in sending bytes over the serial interface instead of a string. Why use bytes and not just send a text string? Using the pack and unpack enforces a structure to the data packets and reduces the amount of data needed to be transmitted compared with a string. Consider a number ‘2048’ sent using the packer function. This is coded as an ‘f’ meaning a float. This is 2 bytes long. Sending ‘2048’ as a string would require 4 bytes, one for each of ‘2’, ‘0’, ‘4’ and ‘8’.
If I encode the string:

'ST 7516.0 50.0 -224.0 144.0 -976.0 EN'

using packer ‘2s5f2s’, the message is 26 bytes. If I send it as a string, it will be 37 bytes. Please see the example code and its output below.

from struct import *
PACKER = ('2s5f2s')
test = 'ST 7516.0 50.0 -224.0 144.0 -976.0 EN'
test2 = (b'ST',7516.0,50.0,-224.0,144.0,-976.0,b'EN')
print('string length: {}'.format(len(test)))
packed_data = pack(PACKER,*test2)
print('packed length: {}'.format(len(packed_data)))
print('unpacked data: {}'.format(unpack(PACKER,packed_data)))

output:

string length: 37
packed length: 26
unpacked data: (b'ST', 7516.0, 50.0, -224.0, 144.0, -976.0, b'EN')

The second reason for using pack and unpack for data packed transmission over sending a stream is that this enforces error checking. If the data is corrupted while reading from the sensor, then an error will be raised during the pack process at the transmitter end. If the data packet is corrupted during transmission, an error will be raised during the unpack process at the receiving end. This can be caught using a try-except clause.