Ultrasonic distance sensor micro:bit theremin

I’ve tried to make really crude theremin-like noise-making machines before with an Arduino and an LED, and with micro:bits, and of course there’s my spooky bat theremin Scratch project.

sonar micro:bit theremin wired up

I had a HC-SR04 ultrasonic distance sensor lying around. You can buy these for under £4 and they’re common in robot vehicle projects to stop them bumping into things. I managed to hook one up to a micro:bit and not just get distance readings but use them to alter the pitch of sound too.

sonar theremin wiring diagram

You’ll need an external power supply for the sonar device – they need 5 volts and the 3 volts off a micro:bit board isn’t enough to make it work. I used 3 AAA batteries as a power source, but I imagine you could also use an old USB lead with the end chopped off instead. You also need a common ground, so make sure that the GND pin on the sensor is connected to the GND pin on your micro:bit as well as the negative terminal on its power supply. This ensures that the electrons that carry data between the sensor and the micro:bit have a complete circuit.

The code itself is very simple – just add the sonar block extensions and it’s as simple as this:

I added some buttons to turn it on and off as it can get a bit annoying after a while!

What else could you do with this? A commenter on my YouTube channel suggests attaching another one to control volume as well as pitch – micro:bit sound doesn’t have a volume function but it’s an intriguing idea, perhaps a second sensor could control something else like lights or octave shifts?

Posted in microbit | Tagged , , | 2 Comments

10 Backlisted episodes that changed my life

It’s that time when people post their top 10 books, films, albums of the year. I even just saw a ‘top 10 best staircases of 2019‘ list, which made me panic and realise I haven’t even got my top 10 best vestibules of 2019 list together yet.

This isn’t a top 10 list. This isn’t even a list of podcasts that changed my life, but as the wonderful Backlisted podcast goes into (I hope temporary) hibernation, here are some wonderful things I discovered, or rediscovered, through listening to the last 108 (count ‘em!) episodes.

Penelope Fitzgerald
I’ve already written about how special Human Voices is for me, with its BBC radio theme and the author’s connection to a school I taught at, but I’ve continued to read her fiction. I think I’ve read about half now, none disappoints. The Beginning of Spring is one of the most astonishing books I have ever read, but the most recent one to come my way, At Freddie’s, is now my favourite, devoured like the best chocolates from the selection box of my Christmas book haul. The four or five pages towards the end about how a relationship unfolds in a Lyons tea room is as perfect a piece of writing as you could ever wish for on love, failure, awkwardness, disappointment, Englishness (or Irishness), London or café etiquette. I know she’s having something of a renaissance, but I am still amazed this Booker Prize-winning author (even though she won for the wrong book) isn’t better-known.

Beyond Black by Hilary Mantel
Speaking of astonishing books, I thought I didn’t like Hilary Mantel. How stupid can one person be? If you, for some reason, think you don’t like her writing, you can’t have read Beyond Black. Breathtaking, I’m still not entirely sure what I make of it, just that I am in awe of it. I think I’ll have to read it again in 2020.

Jane Gardam
I’d read Bilgewater as a teenager and quite liked it, but here I really discovered that one of the best things about listening to Backlisted is not just the books they feature, but the books they mention in passing and the other books by the same authors that you stumble upon. I really liked the featured book A Long Way from Verona, but it felt a bit similar to Bilgewater. The real discoveries for me were Jane Gardam’s short stories and one other novel in particular: The Queen of the Tambourine. Wikipedia summarises it thus: ‘the novel takes the form of a series of increasingly bizarre letters written by Eliza Peabody, an interfering neighbour and hospice volunteer. The letters are written to Joan who has left her husband and fled the country…’ It’s fantastic, and unlike anything else I’ve read by her – indeed in some ways it reminded me of Beyond Black, a book it predates by some fourteen years. It won the Whitbread Prize in 1991 but it is, I think, largely forgotten and isn’t even the first book most Gardam fans would mention. Highly recommended.

Daphne du Maurier
I had read Jamaica Inn and even her 1973 Brexit novel Rule Britannia and I thought I knew what Daphne du Maurier was about, but the episode on her short stories caused me to buy her Don’t Look Now collection – I’m ashamed to say I’ve never even seen the film, let alone read the story it’s based on. The collection of five stories is superb and surprising, not least the last one, The Breakthrough from 1966, which is science fiction. Who know Daphne du Maurier was the best Doctor Who writer we never had? Set in a disused coastal radar research station, I tweeted that I could imagine it being filmed and set in Orfordness. Then someone pointed out it had been filmed, in 1975 – and (partially at least) set in Orford! (Cue Twilight Zone spooky music). It’s astonishingly faithful to the book, I recommend both. It has something of The Stone Tape and other 1970s TV science fiction about it.

 

Thanks to Backlisted, there are dozens more wonderful books and authors I’ve discovered  (Shirley Jackson, Jean Rhys) or rediscovered (Jacob’s Room – like Bilgewater, an utterly different book now to the one I read as a teenager, Red Shift by Alan Garner – which must be one of the most challenging children’s books ever published, although I think I did, kind of, understand it when I was 12 or 13.)

It’s also changed the way I read books and the kinds of books I look out for as I prowl secondhand shops. I’d like to mention two books I may not have read had it not been for Backlisted. They’ve not been featured, but ought to be.

Return to Yesterday by Ford Madox Ford
Currently, I think, out of print, this 1931 memoir is a joy. (Get on it, Carcanet – I did some work experience with you in around 1986 or 1987, surely that must count for something!) If you have any interest at all in the literary or publishing world of the early 1900s, you will love this. Discover which authors he tries to avoid and not avoid in an around Rye and Winchelsea. Learn some potato husbandry. Hilarious encounters with H G Wells and Henry James. Read how, in fact, it was Ford Madox Ford who wrote all the best bits in Joseph Conrad’s novels! How he tried to get Boots lending libraries closed down because LIBRARIES KILL BOOK SALES! He accuses Anita Loos of plagiarism! (And let’s face it, who hasn’t noticed the stylistic and thematic similarities between The Good Soldier and Gentlemen Prefer Blondes?) I’m not entirely sure if he intended this to be funny, but it made me laugh out loud.

Mistress Masham’s Repose by T H White
I somehow thought they’d done T H White on Backlisted, but I seem to have imagined that episode. The Sword in the Stone is rightly lauded, and clearly influenced Harry Potter and more but what about this lesser-known book from 1946?

Again I turn to Wikipedia for a summary: ‘describes the adventures of a girl who discovers a group of Lilliputians, a race of tiny people from Jonathan Swift’s satirical classic Gulliver’s Travels… Maria, a ten-year-old orphaned girl, lives on a derelict family estate, her only companions being a loving family Cook and a retired Professor of Ancient Latin. These two try to protect Maria from her tall, fat, strict Governess, Miss Brown. The Governess makes the child’s life miserable, taking her cue from Maria’s guardian, a Vicar named Mr. Hater. Miss Brown and Mr Hater are conspiring to keep Maria poor and abandoned.’

Ring any bells? Lemony Snicket, I’m looking your way. The book is utterly, utterly bonkers and a joy. Seek it out.

Will I finally read In Search of Lost Time or Ulysses in 2020? I will not. But I’ve even really enjoyed listening episodes on books and writers I know I’ll never read (or unlike those two, books that I don’t even want to have read) because I’ve learned so much. Next year I hope to finish reading Penelope Fitzgerald and more Muriel Spark and more writers mentioned in passing and featured on Backlisted. Hurry back!

 

Posted in fiction, literature, recently read | Tagged , | 2 Comments

Playing Arduboy games on a micro:bit

There are lots of little machines and platforms for making and playing your own games now; various colour LCD MakeCode Arcade machines, the Arduino-based Arduboy which uses a tiny but crisp black and white OLED display as well as the more advanced Pimoroni 32blit Kickstarter. There are probably more I’m not aware of.

A colleague recently showed me the Micro:Gamer. This really neat board turns a micro:bit into an Arduboy. It contains a battery pack, buzzer, power switch, 6 buttons and an OLED display of exactly the type I’ve been experimenting with on micro:bits.

Using the Arduino IDE with extra libraries installed, you flash modified Arduboy games onto a micro:bit which then acts a bit like a game cartridge – plug them into the top of the Micro:Gamer, and get playing.

It occurred to me that I had most of the bits to make my own Micro:Gamer lying around. It really would have been much easier to buy a real one but it was fun to reverse-engineer the board using a mixture of the source code and staring really hard at the PCB tracks in the photos to work out which pins all the buttons and speaker use. Here’s what I made…

I then managed to get a 3D first person shooter working – quite amazing, I think, that a micro:bit can produce these graphics. There’s a lot of power hidden in the humble :bit!

2020 update

I finally added the rest of the buttons and improved the layout to make it slightly more ergonomic!

Posted in Arduino, computers, microbit | Tagged , , , | Leave a comment

Simple Python game with micro:bit OLED display

I’ve managed to get a simple game working on my micro:bit OLED display, and I ditched the breadboard at the same time, meaning that it should be possible to build this into a small case. I may even add some external buttons and perhaps some sound?

Here’s what I used:

I added the extra Python modules using the new micro:bit Python editor’s feature to add extra files to your projects. It supports WebUSB, so using a recent version of Chrome you can flash Python projects straight onto your micro:bit without having to drag and drop HEX files.

Connecting the OLED is easy, especially if you have the well-labelled pin:bit – connect micro:bit 3v to VCC on the display, GND to GND, micro:bit pin 19 SCL (serial clock) to the display’s SCL pin and micro:bit pin 20 (SDA / serial data) to the SDA pin on the display.

The program works by creating ‘stamps’ – like crude sprites – for 3 hazards (a duck, a ghost and a tortoise), all using graphics from the micro:bit’s own built-in 5×5 icons. This is a neat touch that avoids having to create your own bitmap graphics.

You move left and right using A and B buttons, and press A+B together to move forward – you can’t move backwards! When you reach the top you level up, complete 10 levels to win.

There was no function I could find in the Python modules to invert the screen, which is possible if you know what control codes to send, so I added the flash() function which will flash the screen any number of times by making the screen negative then positive quickly in succession. I use this effect when you level up, win or lose.

The levels don’t get harder – it’s running as fast as it can, so I can’t speed it up. To make it more challenging I might add more hazards or slow the player down in some way. Adding sound would also be a logical next step, along with building into a small case, perhaps with some external buttons.

My main Python game program is here, and you can download the whole project HEX file here.

from ssd1306 import initialize, clear_oled, command
from ssd1306_stamp import draw_stamp
from ssd1306_img import create_stamp
from ssd1306_text import add_text
from microbit import sleep, display as LED, Image, button_a as A, button_b as B

def flash(times):
    for i in range(times):
        command([0xa7])
        sleep(300)
        command([0xa6])
        sleep(300)

def move_stamp(x1, y1, x2, y2, stmp):
  draw_stamp(x1, y1, stmp, 0, 0)
  draw_stamp(x2, y2, stmp, 1, 1)

alive = True
level = 0
ghostx, ghosty = 3, 10
ghostDirection = 1
tortoiseX, tortoiseY = 40, 20
tortoiseDirection = -1
duckX, duckY = 20, 5
duckDirection = 1
playerX, playerY = 32, 27

LED.show(level)
initialize()
clear_oled()
ghost = create_stamp(Image.GHOST)
tortoise = create_stamp(Image.TORTOISE)
duck = create_stamp(Image.DUCK)
player = create_stamp(Image.TRIANGLE)
draw_stamp(ghostx, ghosty, ghost, 1)
draw_stamp(tortoiseX, tortoiseY, tortoise, 1)
draw_stamp(duckX, duckY, duck, 1)
draw_stamp(playerX, playerY, player, 1)

while alive:
    oldGhostX = ghostx
    ghostx += ghostDirection
    if ghostx > 58:
        ghostDirection = -1
    if ghostx < 3:
        ghostDirection = 1
    move_stamp(oldGhostX, ghosty, ghostx, ghosty, ghost)

    oldTortoiseX = tortoiseX
    tortoiseX += tortoiseDirection
    if tortoiseX > 58:
        tortoiseDirection = -1
    if tortoiseX < 3:
        tortoiseDirection = 1
    move_stamp(oldTortoiseX, tortoiseY, tortoiseX, tortoiseY, tortoise)

    oldDuckX = duckX
    duckX += duckDirection
    if duckX > 58:
        duckDirection = -1
    if duckX < 3:
        duckDirection = 1
    move_stamp(oldDuckX, duckY, duckX, duckY, duck)

    oldPlayerX = playerX
    playerX = playerX - 1 if (A.is_pressed() and playerX > 0) else playerX
    playerX = playerX + 1 if (B.is_pressed() and playerX < 58) else playerX
    oldPlayerY = playerY
    playerY = playerY - 1 if (A.is_pressed() and B.is_pressed() and playerY > 0) else playerY

    if oldPlayerX != playerX or oldPlayerY != playerY:
        move_stamp(oldPlayerX, oldPlayerY, playerX, playerY, player)

# have we reached the top?
    if playerY == 1:
        level = level + 1
        LED.show(level)
        flash(1)
        draw_stamp(playerX, playerY, player, 0)
        playerX, playerY = 32, 27
        draw_stamp(playerX, playerY, player, 1)

# have we won?
    if level == 10:
        alive = False

# have we hit anything?
    if ghostx-3 <= playerX <= ghostx+3 and ghosty-3 <= playerY <= ghosty+3 \
    or tortoiseX-3 <= playerX <= tortoiseX+3 and tortoiseY-3 <= playerY <= tortoiseY+3 \
    or duckX-3 <= playerX <= duckX+3 and duckY-3 <= playerY <= duckY+3:
        alive = False

if level == 10:
    LED.show(Image.HAPPY)
    clear_oled()
    add_text(3, 1, 'You win!')
    flash(5)
else:
    LED.show(Image.SKULL)
    clear_oled()
    add_text(2, 1, 'Game over!')
    flash(5)

Beta Python editor update

Why not try the new micro:bit Python editor (in Beta as at 22 June 2022) with this code and see how you like it? Download the HEX file from further up this page and drag and drop it onto the editor to load all the files:
screenshot of Beta micro:bit Python editor with this game loaded

Posted in computers, microbit | Tagged , , | 4 Comments

micro:bit OLED display

I love add-on displays for micro:bits, and after putting a cheap colour LCD through its paces, I’ve been experimenting with a tiny 128×64 pixel OLED screen.

OLED displays are great because they are very sharp and have insanely high contrast – which is why OLED TVs are so good. Instead of blocking out a backlight with filters, like LCDs, OLEDs have a tiny LED as each pixel which either emits light or doesn’t – so black really is black.

This display cost just over £5. It’s an SSD1306, widely-used in Arduino and other hobby projects, which means drivers are available for it. Unlike the colour LCD I used last week, this has a MakeCode extension that works with the current version of MakeCode.

MakeCode

Once you add the approved MakeCode extension, you connect your display using just 4 wires: GND on he display to micro:bit GND, VCC to 3v, SCL (serial clock) to 19 and SDA (serial data) to micro:bit pin 20. These last two are the I2C pins on the micro:bit, so you’ll need a special edge-connector / breakout board to get at them. Adafruit are about to release one in the UK via PiHut, the Kitronik one requires you to solder pins to get at I2C, so I used a Pimoroni pin:bit, 4 jumper wires and a breadboard.

The MakeCode extensions are very easy to use, though in normal mode they double up the pixels, giving an effective resolution of just 64 x 32. I guess this is to make the tiny text more readable – it uses the micro:bit’s 5×5 font with no spacing, so it’s not the easiest text to read but you can still get way more information on the display than you can with a micro:bit alone. The ‘non-zoom’ mode seems to show text at 10×5 true pixels, which looks horrible, so I didn’t use it. This is a pity as being able to access every tiny pixel would be pretty neat.

I made a max-min thermometer that plots temperature readings in real time, shows the current temperature and gives high and low readings at the press of a button.

The display seems to update faster than the colour LCD did, and when you write numbers to the display, it over-writes the whole 5×5 grid, meaning you don’t have to blank spaces by drawing rectangles as I had to do with the LCD.

There’s a block for inverting the screen as well, which you can use to make some seizure-inducing effects, and there are blocks to draw lines and rectangles (but not circles).

It was when I tried creating a game I found a major omission from this MakeCode OLED extension: there’s no way of querying the state of a given pixel. You need this to know, for example, if you’ve hit something.

There’s another MakeCode OLED extension from Elecfreaks for their Tinkercademy board and kit, which I discovered works fine without their board and just an SSD1306 OLED connected straight to the micro:bit’s i2c pins. It’s also very limited, just allowing the display of text, numbers, lines, rectangles and a progress bar that I can’t get to work, but it does use a better font, tall and narrow (around 5×7 or 5×8 pixels with spacing) but much more readable than porting the micro:bit’s own 5×5 pixel font. It seems to double each row, even when drawing graphics, so I think the effective resolution with this extension is 128×16 pixels:

Conclusion: this MakeCode OLED driver is great for displaying information as text, numbers and simple graphics, but it’s probably not much good for graphical games.

Enter the Python

That MakeCode driver is actually based on a Python one (which is, I think, itself based on a C++ one for the Arduino). The Python library for the SSD1306 OLED display is obviously a bit trickier to use, but really much more powerful. It actually allows you to query the state of a given pixel, meaning that graphical games become feasible. Indeed, a few games are provided in the Github repo. I tried the Asteroid one and, once I’d fixed a bug, it worked!

These Python programs require you to upload multiple Python files (and bitmaps) you your micro:bit, but the good news is that this is simple using the new version of the online Python editor. Click on Load/save, then under Project Files click on ‘Show Files’ and add as many files as you need for your project, then flash to your micro:bit (direct using WebUSB if you have a recent Chrome-based browser).

I had a go at uploading my own images too – after a lot of failure, I found this the best tool for the job, but I had to invert the images so they appeared negative and use vertical draw mode. You paste the HEX numbers into the bitmap_converter.py program to generate a binary file you can upload to reference in your Python programs.

Whatever I do next with this OLED display I will probably do in Python. Improving the MakeCode extension for gaming is a bit tricky because I suspect the Python driver holds the entire image display contents in an array so it can query that. I think MakeCode would need to query the device itself and I’m not sure if that’s possible. I also had a lot of fun working out how the MakeCode driver stored the micro:bit font, and eventually worked out it was using a very weird format indeed – but I did crack it – so adding better fonts may be an option down the line.

And here’s a bit of fun – what if Susan Kare had designed a micro:bit GUI in 1984 for the Macintosh?

Since writing this I’ve discovered this article which covers very similar territory, and has some nice wiring diagrams.

Posted in computers, microbit | Tagged , , , | 2 Comments