importing Applesoft BASIC programs on the Apple IIe

Just what no-one has needed since about 1979 or so …

BASIC on the Apple II has no easy way to import text as a program. When you LOAD a file, it must be in Apple’s tokenized format. While Apple DOS has the EXEC facility to run script files as if they were typed from the keyboard, it’s very picky about the file format:

  1. There must be a carriage return character (CR, ASCII 13) before the first line
  2. All line numbers must have an extra space before and after them
  3. All tokens must be in upper case
  4. All tokens (keywords and functions) must have a space after them.

The right way to do this conversion would be to write a tokenizer that spits out the correct binary file. But you can (kinda) fudge it with this shell command, operating from BASIC source PROG.BAS:

sed 's/^[0-9][0-9]*/& /;s/^/ /;1s/^/\n/;s/$/ /;s/[:()]/ & /g;' PROG.BAS | tr '\n' '\r' | -p EG.dsk PROG T is the command line version of AppleCommander, and the file EG.dsk referred to above is an Apple DOS 3.3 image created with -dos140 EG.dsk

It still needs work, as there are functions that will mess this up, and Applesoft’s parser makes a mess of code like IF A THEN …, turning it into IF AT HEN ….

So if I wanted to import the following futile program:

30 FOR X=1 TO 20

Run through the script (but before EOL conversion) it would look like this:

 20  HOME 
 30  FOR X=1 TO 20 
 40  PRINT SPC ( X ) ;"FUTILE" 
 50  NEXT X

Make a disk and put the modified program text on it: -dos140 futile.dsk
sed 's/^[0-9][0-9]*/& /;s/^/ /;1s/^/\n/;s/$/ /;s/[:()]/ & /g;' futile.bas | tr '\n' '\r' | -p futile.dsk FUT T

Load the disk into your Apple II, clear out the init program, and import the code with EXEC FUT:

If all you get is ] cursors printed and no syntax errors, then something might be working. List it:

Run it:

Disk image:, containing:

$ -l futile.dsk

 T 002 FUT 
 A 002 FUTILE 
DOS 3.3 format; 134,144 bytes free; 9,216 bytes used.

The first of many … Logic Apple II library disks

The Apple II post from the other day wasn’t as random as it might seem. Through a friend, I got given not just the Apple IIe previously pictured, but also an Apple IIgs and the almost-complete disk library from a local Apple user group.

Logic (“Loyal Ontario Group Interested in Computers”) appears to be defunct now. The Internet Archive has 20+ years of their website archived, but the domain no longer resolves. It’s a shame if they are completely gone, because user groups contain social history. Once it’s gone, well … never send to know for whom the CtrlG tolls; it tolls for thee.

I’m going to archive as much of the Logic disk library as I can. I’ve been chatting with Jason Scott, and he’s keen to see that the disk images are preserved.

I’d never used an Apple II before. They’re quite, um, different from anything else I’d used. Sometimes hideously low-level (slot numbers!), sometimes rather clever (I/O streams from any of the cards can control the computer). Since nothing but an Apple II can read Apple II disks, I’ve got the IIgs running ADTPro sending images via serial to a Linux machine. It’s pretty quick: a 140 K disk image transfers in around 25 seconds, an 800 K image in just under two minutes. I’m marshalling the images with AppleCommander and trying to keep everything intact despite having little idea what I’m doing.

(Apple II annoyance: searching for the term is harder than it needs to be, as people will try to use the typography of the time and refer to it as “Apple ][”, or “Apple //”. Even though the Unicodely-correct representation should be “Apple Ⅱ”, nobody uses it. I’m going to stick with the two-capital-eyes version ‘cos it’s easier to type.)

Big old scanned manuals to small old scanned manuals

It is good that there are so many scanned manuals for old computer systems out there. Every old system did things its very own special way, and life’s too short to guess. I mean, there’s not much out there on the SYM-1 I’m trying to get working again:

— not much except for’s excellent Synertek SYM-1 Resources, that is.

Some manuals, though, while lovingly scanned, are just too large to download, browse or file. Take, for instance, AppleIIScans’ Apple II BASIC Programming With ProDOS. It’s a very faithful colour scan, but at 170 MB for 280 pages, it’s a bit unwieldy. I suspect it’s Adobe Acrobat Paper Capture’s fault: while it makes turning scans into readable files really easy, it doesn’t warn against using 600 dpi full colour for a book with only decorative use of colour.

Good old Ghostscript saves the day, though:

gs -sDEVICE=pdfwrite -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray -dPDFSETTINGS=/ebook -dNOPAUSE -dBATCH -dSAFER -q -sOutputFile=1983-A2L2013-m-a2-bpwp-grey.pdf -- 1983-A2L2013-m-a2-bpwp.pdf

By downsampling the scanned images and converting everything to greyscale, the result’s only 16 MB. All text and indexing from Acrobat is left intact.

gpiozero is rather good

gpiozero (‘A simple interface to GPIO devices with Raspberry Pi’) continues to impress me. One of its newer features is a pinout guide, accessed by the pinout command:

Raspberry Pi Zero pinout – click through for PDF

I’m trying to resist running it on every generation of Raspberry Pi that I have (B, A, 2B, 3B, Zero, Zero W) just for these pretty displays.

(ANSI console colours captured using script, then fed through ansi2html [from the Ubuntu colorized-logs package], printed to PDF from Firefox then mucked about a bit with in Inkscape)

inky phat draws a design

A bit dusty, and no sound, but worked out pretty well. (YouTube link if embed doesn’t work — inky phat draws a design)

Tiling based on plate 43, “a rotating motif …”, Wilson, Eva. Islamic designs for artists and craftspeople. New York: Dover Publications, 1988. ISBN: 978-0-486-25819-5

two-colour EPD displays are so pretty …

rotating tile pattern on Pimoroni Inky pHAT EPD display

This is a 600 dpi scan of a Pimoroni Inky pHAT EPD display. EPDs — electrophoretic displays, aka ‘e-ink’ or ‘e-paper’ — retain their image when turned off, so this Raspberry Pi had no power when I scanned it.

The image I made to fit the display is really small —

It’s a bit of a process making the images with just the right palette in GIMP, but I’m pleased how it turned out. I’d like to be able to write the vector images directly to the screen from SVG, but that might take some time.

Tiling based on plate 43, “a rotating motif …”, Wilson, Eva. Islamic designs for artists and craftspeople. New York: Dover Publications, 1988. ISBN: 978-0-486-25819-5

maximal annoyance with the BBC micro:bit and MicroPython

I just picked up a micro:bit, the little educational microprocessor board originally from the BBC. It’s a nice little unit, though like all educational resources, it’s sometimes hard to access resources as a non-edu type.

I landed upon MicroPython, a Python language subset that runs directly on the micro:bit’s ARM chip. I rather like the Mu editor:
To give the old microcontroller grumps something real to complain about, MicroPython includes a bunch of very high-level functions, such as a powerful music and sound module. Getting the sound out is easy: just croc-clip a speaker onto the output pads:

(MicroPython warns against using a piezo buzzer as a speaker, but mine worked fine — loudly and supremely annoyingly — with a large piezo element. Some piezos have a fixed-frequency oscillator attached, but this simple one was great.)

This trivial example plays the Nyan Cat theme forever, but every time it loops it gets faster. The beats variable starts at the default 120 bpm, but is increased by one every time:

# nyan but it gets faster
import music
beats = 120
while True:
    beats = beats + 1

This starts out as merely irritating, but quite quickly becomes deeply annoying, and in mere hours become vastly vexing. I’m sure you’d only use this power for good …

Easy Raspberry Pi framebuffer screenshots with raspi2png

I gave a talk about retro-gaming on the Raspberry Pi yesterday. I was describing RetroPie, and I really needed lots of screenshots to illustrate games. I’m used to grabbing screens under X, but RetroPie runs without it, so all my usual tools were of no use.

I’d just found out about raspi2png, and it works really well! Usage is simple: just call it like

raspi2png -p outfile.png

and it’ll save whatever’s on the screen. It doesn’t play well with X, but there are already tools to take screenshots with that. As I was playing games, I didn’t want to have to pause the computer to take a shot, so I ran the command every five seconds for 30*5 seconds like this:

for f in {1..30}; do raspi2png -p retro_$(date -Iseconds).png; sleep 5; done

Here are some quality shots via raspi2png from Deathchase, officially the best ZX Spectrum game ever:

VM-CLAP1 👏 sensor + gpiozero on Raspberry Pi

Well, that was easy!

Since the Verbal Machines VM-CLAP1 sensor is an open collector type — that is, it sinks current when triggered — it behaves like a simple button to gpiozero, the Raspberry Pi Python GPIO library. If you attach a callback function to the sensor’s when_pressed event, your Python script will call that function every time it registers a clap.

The wiring is as simple as it could be:

 VM-CLAP1: Raspberry Pi:
 ========= =============
      GND → GND
      PWR → 3V3
      OUT → GPIO 4

This example code just prints clap! when the board picks up a 👏:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Raspberry Pi gpiozero test for
# Verbal Machines VM-CLAP1 clap sensor
#   scruss - 2017-06
# Wiring:
#  VM-CLAP1:    Raspberry Pi:
#  =========    =============
#    GND     →   GND
#    PWR     →   3V3
#    OUT     →   GPIO 4

from gpiozero import Button
from signal import pause

def clapping():

clap = Button(4)
clap.when_pressed = clapping

This is a trivial example, but at least it shows that anything you can do with a button, you can also do with this hand-clap sensor.

Clap Sensor part for Fritzing

I have no idea if this wiring would work, but it’s pretty …

For work, I blogged about Verbal MachinesHand Clap Sensor VM-CLAP1 (“Clap on 👏👏, Clap off 👏👏 – Elmwood Electronics”). I’ve made a preliminary part for Fritzing for the board: VM-CLAP1 Clap Sensor for

It should work in Breadboard and Schematic mode, but absolutely doesn’t work in PCB mode. This shouldn’t be a problem, as it’s only available as a standalone board. Fritzing doesn’t have any way to create new parts from scratch any more, so I had to base it on a somewhat similar-looking board, the SparkFun Electret Microphone Breakout.

I’m looking forward to see what I can do with gpiozero and the clap sensor.

Headless Raspberry Pi + VNC: useful resolution

Breadboards of Canada …

I just set up a Raspberry Pi Zero to be a little breadboard computer. Running a headless machine only through SSH gets a bit dull at times, so the inclusion of VNC Connect in Raspbian is handy.

Only problem was that the default screen size — something like 720×480 — was too small for most dialogue windows. Here’s how to enable a more useful resolution of 1024 × 768.

All of these are enabled from the raspi-config tool, so open a terminal and start it with:

sudo raspi-config

Enable Boot to Desktop

Select 3 Boot OptionsB1 Desktop / CLIB4 Desktop Autologin:

Enable VNC on Startup

Select 5 Interfacing OptionsP3 VNC, and answer Yes to Would you like the VNC Server to be enabled?:

Set Screen Resolution

Select 7 Advanced OptionsA5 ResolutionDMT Mode 16 (1024×768) …:

Once you’ve enabled all of these, raspi-config will ask if you wish to reboot your Raspberry Pi. Once it has rebooted, you should have a usable remote desktop.

(All of the above screenshots were taken from a headless Raspberry Pi Zero via VNC.)

Before & After

These were taken later on a Raspberry Pi 2 I’m setting up for a maker festival booth:

decidedly smol: 720×480
fix it to 1024×768 …
so much better!

Simple — like, really simple — Arduino periodic timer with Brett’s MillisTimer library

I don’t know how many times I’ve written bad Arduino code to call a function every few milliseconds. Sometimes this bad code works well enough for my sketch to actually work. Often, it either doesn’t work at all or does something I really didn’t expect.

So on Arduino Day 2017, I’m glad I found out about bhagman/MillisTimer: A Wiring and Arduino library for working with millis(). It couldn’t be simpler to use: include the library, write the function you want to call every N milliseconds, set up the timer to run every N millis, and put in a loop that’s called frequently. The library handles the timing and resetting all by itself.

As an example, here’s the eternal “Hello, World!” of the embedded world, Blink, rewritten to use MillisTimer:

// MillisTimerBlink - blink LED every second
//  using Brett Hagman's MillisTimer library
//  (or use Sketch → Include Library → Manage Libraries … to install)
// scruss - 2017-04-01

#include <MillisTimer.h>
MillisTimer timer1;               // new empty timer object
const int led_pin = LED_BUILTIN;  // use the built-in LED

void flash() {                    // function called by timer
  static boolean output = HIGH;
  digitalWrite(led_pin, output);  // set LED on or off
  output = !output;               // toggle variable state High/Low

void setup() {
  pinMode(led_pin, OUTPUT);       // use built-in LED for output
  timer1.setInterval(1000);       // set timer to trigger every 1000 millis
  timer1.expiredHandler(flash);   // call flash() function when timer runs out
  timer1.setRepeats(0);           // repeat forever if set to 0
  timer1.start();                 // start the timer when the sketch starts

void loop() {;                   // trigger the timer only if it has run out
  // note that run() has to be called more frequently than the timer interval
  //  or timings will not be accurate

Note that MillisTimer only triggers when is called. Sticking a delay(2000) in the main loop will cause it to fire far less frequently than the interval you set. So it’s not technically a true periodic timer, but is good enough for most of my purposes. If you want a true interrupt-driven timer, use the MsTimer2 library. It relies on the timer interrupts built into the Arduino hardware, and isn’t quite as easy to use as MillisTimer.

Keypunch029 — for all your punched card font needs …

A fairly accurate rendition of the 5×7 dot matrix font printed at the
top of punched cards by the IBM Type 29 Card Punch (1965).

Local copy:
Fontlibrary link: Keypunch029

The 029 (as it is sometimes known) generated a bitmap font from an engraved metal plate pressing on a matrix of pins. A picture of this plate from a field engineering manual was used to re-create the pin matrices, and thus an outline font.

029 Code Plate
029 Code Key

Historical Accuracy

The 029 could have many different code plates, but the one used here contained the characters:


The character glyphs have been sized such that if printed at 12 points, the 029’s character pitch of 0.087″ is accurately reproduced. No attempt to research the pin matrix pitch or pin diameter has been made: the spacing was eyeballed from a couple of punched cards in my collection.

The earlier IBM Type 26 Card Punch (“026”) included a glyph for a square lozenge (Unicode U+2311, ⌑). The 029 code plate did not include this character, but I added it here for completeness.

The character set was extended to include:

  • all of ASCII, with lower case characters repeating the upper case glyphs;
  • sterling currency symbol; and
  • euro currency symbol.

While there may have been official IBM renditions of some of these additional glyphs (with the exception of euro) no attempt has been made to research the original shapes. This font set is intended to help with the visually accurate reproduction of 1960s-era punched cards, mostly coinciding with my interest in the FORTRAN programming language. No attempt has been made to use historical BCD/EBCDIC encodings in these fonts. We have Unicode now.

The 029 card punch could not produce any bold or italic font variants, but FontForge can, so I did.

Things I learned in making these fonts

  1. The 029 card punch printer could be damaged if you tried to print binary cards, as there was no way to disengage the code plate from the punch mechanism.
  2. FontForge really hates to have paths in a glyph just touching. Either keep them more than one unit apart, or overlap them and merge the overlapping paths.
  3. EBCDIC is weird.


In the unlikely event you need to represent Emoji in RTF using Perl …

Of all the niche blog entries I’ve written, this must be the nichest. I don’t even like the topic I’m writing about. But I’ve worked it out, and there seems to be a shortage of documented solutions.

For the both of you that generate Rich Text Format (RTF) documents by hand, you might be wondering how RTF converts ‘💩’ (that’s code point U+1F4A9) to the seemingly nonsensical \u-10179?\u-9047?. It seems that RTF imposes two encoding limitations on characters: firstly, everything must be in 7-bit ASCII for easy transmission, and secondly, it uses the somewhat old-fashioned UTF-16 representation for non-ASCII characters.

UTF-16 grew out of an early standard, UCS-2, that was all like “Hey, there will never be a Unicode cope point above 65536, so we can hard code the characters in two bytes … oh shiiii…”. So not merely does it have to escape emoji code points down to two bytes using a very dank scheme indeed, it then has to further escape everything to ASCII. That’s how your single enoji becomes 17 bytes in an RTF document.

So here’s a tiny subroutine to do the conversion. I wrote it in Perl, but it doesn’t do anything Perl-specific:

#!/usr/bin/env perl
# emoji2rtf - 2017 - scruss
# See UTF-16 decoder for the dank details
#  <>

use v5.20;
use strict;
use warnings;
use utf8;
sub emoji2rtf($);

my $c = substr( $ARGV[0], 0, 1 );
say join( "\t⇒ ", $c, sprintf( "U+%X", ord($c) ), emoji2rtf($c) );

sub emoji2rtf($) {
    my $n = ord( substr( shift, 0, 1 ) );
    die "emoji2rtf: code must be >= 65536\n" if ( $n < 0x10000 );
    return sprintf( "\\u%d?\\u%d?",
        0xd800 + ( ( $n - 0x10000 ) & 0xffc00 ) / 0x400 - 0x10000,
        0xdC00 + ( ( $n - 0x10000 ) & 0x3ff ) - 0x10000 );

This will take any emoji fed to it and spit out the RTF code:

📓	⇒ U+1F4D3	⇒ \u-10179?\u-9005?
💽	⇒ U+1F4BD	⇒ \u-10179?\u-9027?
🗽	⇒ U+1F5FD	⇒ \u-10179?\u-8707?
😱	⇒ U+1F631	⇒ \u-10179?\u-8655?
🙌	⇒ U+1F64C	⇒ \u-10179?\u-8628?
🙟	⇒ U+1F65F	⇒ \u-10179?\u-8609?
🙯	⇒ U+1F66F	⇒ \u-10179?\u-8593?
🚥	⇒ U+1F6A5	⇒ \u-10179?\u-8539?
🚵	⇒ U+1F6B5	⇒ \u-10179?\u-8523?
🛅	⇒ U+1F6C5	⇒ \u-10179?\u-8507?
💨	⇒ U+1F4A8	⇒ \u-10179?\u-9048?
💩	⇒ U+1F4A9	⇒ \u-10179?\u-9047?
💪	⇒ U+1F4AA	⇒ \u-10179?\u-9046?

Just to show that this encoding scheme really is correct, I made a tiny test RTF file unicode-emoji.rtf that looked like this in Google Docs on my desktop:

It looks a bit better on my phone, but there are still a couple of glyphs that won’t render:

“The Error Message as a bourgeois construct”

If you try to run the (unmodified) BASIC code for Oregon Trail (1975) on PDP-8 BASIC, you get this:

 DI 30
 XC 45
 XC 205
 IF 700
 NM 730
… (many, many more lines …)

I thought at first it was a stack trace, but nope — it’s error messages! You need to dig through your trusty language manual, and on page 132 it has a table to explain:


(and yes, they’re in all-caps. Mixed case? Mixed feelings!)

So whenever Python throws a tantrum (or as it calls it, an exception) and wails at length about its problems, remember PDP-8 BASIC: Two letters + a line number. That’s all.

PoorFish, v2

On FontLibrary: PoorFish

Local copy:

Full Language Support: Afrikaans, Baltic, Basic Latin, Catalan, Central European, Dutch, Esperanto, Euro, Turkish, Western European. Terrible kerning comes free.

(original version from 2010: PoorFish)

The Pocket DEC Pretender (PDP) Zero

PDP (Pocket DEC Pretender) Zero: lettering came out a bit more, um,  artisanal than I’d hoped …

Digital (aka DEC) used to make some very solid minicomputers back when a minicomputer was fridge-sized and people were still building nuclear power stations to be controlled by them. The Raspberry Pi Zero is a very mini computer indeed, and in USB gadget mode running SimH it makes a nice little emulation platform.

The case is from Thingiverse: One Piece Raspberry Pi Zero + Camera Case (with GPIO) by Superrei, but with the DEC PDP logo in relief on the top.

DEC minis were famous for their arrays of blinkenlights. The Pocket DEC Pretender, not so much: it has one tiny green light that flickers a bit now and again:

PDP (Pocket DEC Pretender) Zero: case open, very few blinkenlights

But it’s a genuinely useful (for my values of useful) emulation platform. Here it is pretending to be a PDP-8, running BASIC under OS-8:

PDP (Pocket DEC Pretender) Zero: PDP-8 BASIC!

(background in case pictures woven in Toronto by Deftly Weft)

TYPE BANG: First Person Shooter, 1975 style

— from the source code of an early (1975) time-shared system version of The Oregon Trail, as documented in On the Trail of the Oregon Trail.

Library Hand – Disjoint

LibHandDis — Based on scans of “Library Hand – Disjoint”, described in Dana’s A Library Primer, with some modifications.

Major changes from scan:

  • As the scan only covered A-Z, a-z, 0-9 and ‘&’, I had to make the rest up.
  • Many of the descenders had to be shortened to fit with modern typography conventions.
  • Kerning is much tighter than Dana’s guidelines suggest.

(idea for this came via MetaFilter, This question of library handwriting is an exceedingly practical one)

Local copy: