fritzing: Generic 4×4 Keypad part

This needs work, but I made this keypad part for Fritzing:

Part file (zipped): Generic_4x4_Keypad.zip

You’ll see these parts described as variations on “4×4 Matrix 16 Keypad Keyboard Module 16 Button” on ebay. They’re very simple: if you press a button (say S7), the row pins (R1-4; R2 for S7) and the column pins (C1-C4; C3 for S7) are connected. So pins R2 and C3 are connected when S7 is pressed. You can use the Arduino Keypad library to talk to these, but do remember they use up 8 I/O pins.

It’s not internally routed in Fritzing, and you likely won’t be able to use it for any kind of schematic work, but who uses Fritzing for anything other than pretty pictures?

Creating a systemd user service on your Raspberry Pi

Flushed with success from yesterday’s post where I made my first systemd service, I got carried away and wanted to show you how to create a service that runs as a regular user.

A fairly common question on the Raspberry Pi Forums is “How do I run a script every time I reboot?”. The traditional answer (and one I’ve given more than once) is to add a @reboot clause to your crontab. This will indeed run a command when the computer reboots, but it will run pretty early on in the boot sequence when there’s no guarantee of network or time services. So the usual remedy is a bit of a kludge:

@reboot sleep 60 && 

This waits a full minute after rebooting, then executes the command. Network and time services are really likely to be available, but it’s not very elegant. Cron also has some weird gotchas with PATH settings, so while it’s ubiquitous and has worked for decades, it’s not easy to get working. Systemd, however, has a much better way of doing it, and better yet, you can do it all without ever hitting sudo.

I’ll take as a basis for this post the forum query “python and crontab”. The asker wanted to log the time when their Raspberry Pi had rebooted, but they’ve hit the usual problem that the clock didn’t have the right time when their script was triggered, so the log was useless.

(I’m not going to do exactly what the forum poster did, but this is more a demo of a systemd user service than recreating their results.)

First off, here’s the script to log the time to a file (saved as ~/bin/boot_time.py):

#!/usr/bin/python3
from time import strftime
with open("/home/pi/logs/boot_time.txt", "a") as log:
 log.write(strftime("%d-%m-%Y,%H:%M:%S\n"))

I’d have done this as a shell script, but the OP used Python, so why fight it?

FUN FACT: Under most Linux flavours, if you create a bin folder in your home directory, it’s automatically added to your path. So I could just type boot_time.py and the shell would find it.
(You might have to log out and log back in again for the shell to review your path.)

In order to get that to run, I need to do a little housekeeping: make the script executable, and make sure the logs folder exits:

chmod +x ~/bin/boot_time.py
mkdir -p ~/logs

Now we need to do the bits that pertain to systemd. First off, you must make a folder for user services:

mkdir -p ~/.config/systemd/user

NOTE: mkdir -p … is useful here as it makes the directory and any parent directories that don’t exist. It also doesn’t complain if any of them already exist. It’s kind of a “make sure this directory exists” command. Make friends with it.

And here’s the service file, which I saved as ~/.config/systemd/user/boot_time_log.service:

[Unit]
Description=boot time log
DefaultDependencies=no
After=local-fs.target time-sync.target

[Service]
Type=oneshot
ExecStart=/home/pi/bin/boot_time.py

[Install]
WantedBy=default.target

The service file does the following (even if I’m slightly mystified by some of the headings …):

  • Unit
    • Description — a plain text name for the service. This appears in logs when it starts, stops or fails.
    • DefaultDependencies — as this service runs once at boot-up, it doesn’t need the normal systemd functions of restarting and shutting down on reboot. Most service files omit this line.
    • After — here we tell systemd what service targets must be running before this service is started. As we need to write to a file and have the right time, the local-fs.target and time-sync.target seem sensible.
  • Service
    • Type — this is run once, so it’s a oneshot rather than the usual simple service.
    • ExecStart — this is the command to run when the service is required.
  • Install
    • WantedBy — tbh no idea what this does, but if you omit it the service won’t install. Found the answer in this SE, and it works. So I guess what it does is make the service not fail

Finally, you enable the service with:

systemctl --user enable boot_time_log.service

Next time you reboot, the time will be appended to the log file ~/logs/boot_time.txt.

Unlike most (that is, Type=simple) services, it’s perfectly fine if this one spends most of its time inactive:

$ systemctl status --user boot_time_log.service
● boot_time_log.service - boot time log
 Loaded: loaded (/home/pi/.config/systemd/user/boot_time_log.service; enabled;
 Active: inactive (dead) since Sun 2017-10-22 22:17:56 EDT; 1h 5min ago
 Process: 722 ExecStart=/home/pi/bin/boot_time.py (code=exited, status=0/SUCCES
 Main PID: 722 (code=exited, status=0/SUCCESS)

It has executed successfully, so the process doesn’t have to stick around.

Combined Restart / Shutdown Button for Raspberry Pi

A very simple systemd service for Raspberry Pi that provides a software-controlled restart / shutdown button. Code: scruss/shutdown_button

Use

Default behaviour is:

  • your Raspberry Pi will reset if the button is held for more than two seconds but fewer than five seconds;
  • your Raspberry Pi will shut down if the button is held for more than five seconds.

By default, the software assumes the switch is connected to pin BCM 27. Both the pin and the timing can be changed in the Python source file.

Requirements

Hardware

  • A Raspberry Pi (tested on a model 2B, 3B and Zero, and on a model B after minor software modification)
  • A normally open, momentary contact button. I use surplus ATX power buttons (as used on desktop PCs), as they’re cheap and come with a handy set of wires and header connectors. Virtually any button will do the job, though. Just make sure it’s normally open (push to close).

Software

  • A Debian-based operating system that uses systemd (tested on Jessie and Stretch)
  • the python3-gpiozero package to provide GPIO Zero (tested on version 1.4.0)

Installation

Hardware

40-pin GPIO connector (B+, 2B, 3B, Zero)

Connect the button between GPIO 27 and GND. If you use an ATX power button and a Raspberry Pi with a 40-pin GPIO header, connect it across the seventh column from the left:

            -
· · · · · ·|·|· · · · · · · · · · · · · 
· · · · · ·|·|· · · · · · · · · · · · · 
            -

This shorts GPIO 27 (physical pin 13) to ground (physical pin 14) when the button is pressed.

26-pin GPIO connector (models B and A only)

GPIO 27 is not exposed on the original Raspberry Pi header, so GPIO 17 is a reasonable option. If you use an ATX power button and a Raspberry Pi with a 26-pin GPIO header, connect it across the fifth and sixth columns of the second row:

 . . . . ._. . . . . . . .
 . . . .|. .|. . . . . . .
          -

You will also need to change [line 7 of shutdown_button.py](https://github.com/scruss/shutdown_button/blob/master/shutdown_button.py#L7) to read:

use_button=17

Software

The software is installed with the following commands:

sudo apt install python3-gpiozero
sudo mkdir -p /usr/local/bin
chmod +x shutdown_button.py
sudo cp shutdown_button.py /usr/local/bin
sudo cp shutdown_button.service /etc/systemd/system
sudo systemctl enable shutdown_button.service
sudo systemctl start shutdown_button.service

Troubleshooting

Enabling the service should produce output very similar to:

Created symlink /etc/systemd/system/multi-user.target.wants/shutdown_button.service → /etc/systemd/system/shutdown_button.service.

You can check the status of the program at any time with the command:

systemctl status shutdown_button.service

This should produce output similar to:

● shutdown_button.service - GPIO shutdown button
   Loaded: loaded (/etc/systemd/system/shutdown_button.service; enabled; vendor 
   Active: active (running) since Sat 2017-10-21 11:20:56 EDT; 27s ago
 Main PID: 3157 (python3)
   CGroup: /system.slice/shutdown_button.service
           └─3157 /usr/bin/python3 /usr/local/bin/shutdown_button.py

Oct 21 11:20:56 naan systemd[1]: Started GPIO shutdown button.

If you’re seeing anything other than Active: active (running), it’s not working. Does the Python script have the right permissions? Is it in the right place? If you modified the script, did you check it for syntax errors?

The output from dmesg will show you any error messages generated by the service.

Modifications

If you use a HAT/pHAT/Bonnet/etc. with your Raspberry Pi, check pinout.xyz to see if it uses BCM 27. If you do need to change the pin, best to pick one that doesn’t have a useful system service like serial I/O or SPI. If you’re using an ATX button with a two pin connector, make sure you choose a pin physically adjacent to a ground pin.

If you modify the timing, please ensure that you keep the shutdown button press duration longer than the reboot one. Otherwise you’ll only be able to shut down.

Notes

You should not need to reboot to enable the service. One machine of mine — a Raspberry Pi Zero running Raspbian Stretch — did need a reboot before the button worked.

The reboot code is based on the Shutdown button example from the GPIO Zero documentation.

This is not the only combined shutdown/reset button project to use GPIO Zero. gilyes/pi-shutdown also does so, but pre-dates the implementation of the various hold time functions in GPIO Zero.

GPIO 27 was used, as it’s broken out onto a physical button on the Adafruit PiTFT+ display I own.

This is my first systemd service, and I’m still at the “amazed it works at all” stage. The service file may not contain the ideal configuration.

Connector Pinouts

From GPIO Zero’s pinout command

40 pin

   3V3  (1) (2)  5V    
 GPIO2  (3) (4)  5V    
 GPIO3  (5) (6)  GND   
 GPIO4  (7) (8)  GPIO14
   GND  (9) (10) GPIO15
GPIO17 (11) (12) GPIO18
GPIO27 (13) (14) GND   
GPIO22 (15) (16) GPIO23
   3V3 (17) (18) GPIO24
GPIO10 (19) (20) GND   
 GPIO9 (21) (22) GPIO25
GPIO11 (23) (24) GPIO8 
   GND (25) (26) GPIO7 
 GPIO0 (27) (28) GPIO1 
 GPIO5 (29) (30) GND   
 GPIO6 (31) (32) GPIO12
GPIO13 (33) (34) GND   
GPIO19 (35) (36) GPIO16
GPIO26 (37) (38) GPIO20
   GND (39) (40) GPIO21

26 pin

   3V3  (1) (2)  5V    
 GPIO0  (3) (4)  5V    
 GPIO1  (5) (6)  GND   
 GPIO4  (7) (8)  GPIO14
   GND  (9) (10) GPIO15
GPIO17 (11) (12) GPIO18
GPIO21 (13) (14) GND   
GPIO22 (15) (16) GPIO23
   3V3 (17) (18) GPIO24
GPIO10 (19) (20) GND   
 GPIO9 (21) (22) GPIO25
GPIO11 (23) (24) GPIO8 
   GND (25) (26) GPIO7 

Raspberry Pi combined reboot/shutdown button demo

NB: this version doesn’t actually do the rebooting or shutting down: it’s a demo. This one does, though …

Here’s how you might have just one button being a reset button (hold down for two seconds) or a shutdown button (hold down for five):

taking the whole proto-plate thing a bit far …

Yes, it’s a very tiny microcontroller board and breadboard doohickey. The board’s a Trinket M0 running CircuitPython 2.0. The base is laser-cut birch ply. Definitely #smol  at less than 75 × 55 mm …

Here’s the SVG for laser cutting:
To build it, you’ll need:

  • 3 mm birch ply (at least 75 mm × 55 mm)
  • Adafruit Trinket M0
  • Tiny breadboard: either a tiny or a Mini one. The board markings match either.
  • M2.5 screws and standoffs
  • 4× stick-on feet
  • 2× 1×5 female header — I cut down a 1×12 female header.

If I were to redesign this, I’d:

  1. make the breadboard outline a score line rather than an etched area. Scoring is much quicker than etching.
  2. Mark pin definitions on the plate. They’re a bit hard to read on the Trinket M0.

Obligatory blinky code for running a 16 LED NeoPixel Ring and the LED in the middle of the Trinket:

MS Word will break your links!

I was pleased to see that my nerrrdy Bourgoin mini-zine got cited in an art workbook for schools: Islamic mosaics activity (Patterning) from MathWeave. Yay!

But the link in the workbook doesn’t work! I mean, it looks right:

While the real link is:

Only when you copy the bad URL do you see the problem:

http://scruss.com/blog/2016/07/21/nerrrdy%E2%80%90bourgoin%E2%80%90mini%E2%80%90zine/

Word has changed the pasted ‘-’s to ‘‐’s: that’s from U+002D HYPHEN-MINUS to U+2010 HYPHEN. You’d have thought that software that was smart enough to recognize an URL would also be smart enough not to do any messing with the characters in it …

Most of the Logic Apple II Library now on archive.org


Well, that’s all the disks I can find easily up on archive.org. There are some Apple IIgs disks still to do, and there might be some random disks lurking in another box, but that’s more than 485 disk images uploaded.

You can find them by going to Internet Archive Search: creator:”LOGIC (“Loyal Ontario Group Interested In Computers”)”.

Installing the Pimoroni OnOff Shim the hard way

Hey! This process permanently modifies your Raspberry Pi and may prevent it from working with many HATs and add-ons … It also has some really fiddly soldering. If in doubt, don’t.

Pimoroni’s OnOff SHIM adds what the Raspberry Pi should have had all along: a power button. While there are lots of soft power switches out there, the OnOff Shim adds circuitry to cut power to the Raspberry Pi after shutdown.

While the shim comes with a 12-socket header, that prevents you from using any other device that uses the leftmost GPIO pins. I wanted access to all the pins, and not have the shim create an unsightly bump on the pins. So this is what I did …

Regular GPIO header in place on a Raspberry Pi Zero W
Test-fit the socket header to mark where you’re going to cut the pin support block
Very carefully, cut the pin support block between (physical) pins 11-13 and 12-14. I used a mix of a sharp craft knife and nibbling with fine diagonal cutters. Try not to bend the GPIO pins either as you cut the block or lever the block out of the way
Apply non-conductive tape to the back of the OnOff Shim. I used Kapton, but electrical/insulating tape will do. Just make sure you don’t block any of the GPIO holes
Test-fit the shim. You may have to pare away at the support block a bit to get it to fit level with the rest of the pins
Now solder the shim in place. You want the solder joints as small as possible. I used extra liquid flux and very fine silver solder to just fill the pin holes. Too much solder left on the pins will stop HATs and socket headers fitting, so you may have to desolder as I had to do on the rightmost pin
Example HAT fitted with OnOff shim underneath. Note that his particular HAT — the Pimoroni Inky pHAT — will not work with this shim.

The OnOff SHIM uses GPIO pin BCM 17 (physical pin 11) as the power button sensor and BCM 4 as the power off signal. Any device that also uses BCM 17 (and possibly BCM 4) will likely cause the reset process to be triggered. This means that I can’t use the shim with my Inky pHAT EPD. You would have thought that Pimoroni might’ve considered that, since they made both. Consulting pinout.xyz suggests that 41 boards that likely may not work with the OnOff shim: Cirrus Logic Audio Card, Display-o-Tron 3000, DOTs, Enviro pHAT, ESP IoT pHAT, Explorer HAT, Explorer HAT Pro, Flex, GertVGA 666, High-Precision AD/DA Board, Hyperpixel, Inky pHAT, IoT pHAT, LEDBorg, MotoZero, Navio2 Autopilot, PaPiRus HAT, PaPiRus Zero, Piano HAT, Pibrella, Picade HAT, Pi Cap, PiGRRL Gamepad, Pi-LITE-r, Pi-mote, Pi PoE Switch HAT, PiStep2 Dual, PiStep2 Quad, Pi Stop, Propeller HAT, RoboHat, RTK Motor Controller, Servo PWM Pi Zero, Skywriter HAT, Ultimate GPS HAT, Voice HAT, Witty Pi, Witty Pi 2, Zero2Go, Zero LiPo and ZeroSeg.

While I like the OnOff SHIM, check carefully that it will work with your application.

Installing the Versatile Commodore Emulator (VICE) on Raspberry Pi

As requested on our local Commodore user group mailing list, how to install VICE on a Raspberry Pi 3 running Raspbian Stretch:

# get dependencies - this may take a long time and ~ 1.5 GB
sudo apt install autoconf automake build-essential byacc dos2unix flex libavcodec-dev libavformat-dev libgtk2.0-cil-dev libgtkglext1-dev libmp3lame-dev libmpg123-dev libpcap-dev libpulse-dev libreadline-dev libswscale-dev libvte-dev libxaw7-dev subversion texi2html texinfo yasm libgtk3.0-cil-dev xa65

mkdir -p src

cd src

svn checkout https://svn.code.sf.net/p/vice-emu/code/trunk trunk

cd trunk/vice

./autogen.sh

./configure

make -j4

sudo make install

This was freely adapted from the build docs, Linux-Native-Howto.txt, which has more info if you get stuck.

6502 badge is go!

Yes readers, I built one:

All of 2 KB RAM, but the form factor can’t be beat. I’m sure I’ll be the hippest cat on the block when I pair it with my happening 2012 Hamvention lanyard …

Thanks to Josh Bensadon for bringing a 6502 40th Anniversary Badge back from VCF Midwest. Josh also got my Apple //e going again by replacing RAM chips: I can’t thank him enough for that, too!

VCF-MW 2017 6502 badge, with almost everything socketed

I did make some minor mods to the build:

  • I socketed the main chips. The 6502 is in 2× cut up 20-pin narrow sockets. Under the EPROM is the 2K×8 SRAM, socketed too. This means that the EPROM is in two stacked sockets and sticks out far too far. But at least it’ll allow me to upgrade the RAM
  • I used real pin-header jumpers and links for RAM and EPROM size selection instead of solder links. This meant a horrible kludge for the RAM selector under the SRAM chip involving angled and bent headers, a filed-down chip socket and a hand-knotted wire jumper (artisanal af!)
  • Even though there’s no mention of it in the manual, I stuck the battery pack on the back
  • One bad mod: the HL-340 RTS mod suggested in the manual is much harder than it looks. I trashed the supplied USB adapter, but I have others …

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' | ac.sh -p EG.dsk PROG T

ac.sh is the command line version of AppleCommander, and the file EG.dsk referred to above is an Apple DOS 3.3 image created with

ac.sh -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:

10 REM A FUTILE PROGRAM BY SCRUSS
20 HOME
30 FOR X=1 TO 20
40 PRINT SPC(X);"FUTILE"
50 NEXT X

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

 10  REM A FUTILE PROGRAM BY SCRUSS 
 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:

ac.sh -dos140 futile.dsk
sed 's/^[0-9][0-9]*/& /;s/^/ /;1s/^/\n/;s/$/ /;s/[:()]/ & /g;' futile.bas | tr '\n' '\r' | ac.sh -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: futile-AppleII-dsk.zip, containing:

$ ac.sh -l futile.dsk

DISK VOLUME #254
 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

TL;DR Update — The disk images are here: creator:”LOGIC (“Loyal Ontario Group Interested In Computers”)”

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 logicbbs.org 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 6502.org’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.

InkyPhat-rotating2-212x104-web.svg
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