Information wants to be free...

M.I.A. in Wine

M.I.A.: Missing In Action is a relatively unknown game that came out for Windows back in 1998. I got the game back then in my childhood as part of some bundle with a new computer. I do remember the game being fun, but I had issues getting it to run later on because it will only install on Windows 98. Fast forward some 20 years, Wine has now become a better Windows than Windows on Linux in many aspects, especially running older games.
I have been using Wine version 4.0.2 for these experiments.

Using some tricks I finally got to run and play this on Linux! In order to get there I had do spend some time with both Winedbg and OllyDbg debuggers to figure out what the game tried to do and failed on.

The first problem was the detection of the CDs, which I figured out it does by calling GetVolumeInformationA() and looking at the volume label. This is fixed by creating a ".windows-label" file in the emulated CD drive with the correct label.

The second problem was getting the CD audio to work correctly. Apart from having to fake this somehow, the game uses the ancient Media Control Interface which still have some missing features (bugs?) in Wine at the time of writing. Maybe this will be fixed in an upcoming version, but I had no time to wait for that. The root of the problem is that Wine returns the code (as string) "1088" instead of the string "audio" when the game asks what type of track is on the CD. The quickest way to fix this is to simply patch the game binary to look for that other string.

To actually play the CD audio without the CDs I figured out it was easiest to hack the Wine "mcicda.dll" library and make it call MPlayer to play the tracks as .FLAC files. This is done in MPlayer's FIFO mode to avoid blocking anything.

A third problem is that the in-game video cutscenes, using Smacker Video Technology still does not play correctly in Wine. The symptom is that the video may play for some seconds, but then just hangs. Since it's possible to bypass this by hitting Escape, I have simply ignored this for now.

Anyway, the common steps to install and run are as follows:
1) Create a new directory to store a Wine prefix for M.I.A.:
mkdir -p ~/opt/mia
2) Run winecfg on the prefix, in 32-bit mode, and set it has "Windows 98":
WINEARCH=win32 WINEPREFIX=~/opt/mia winecfg
3) Create two directories for each M.I.A. CD in the prefix:
mkdir ~/opt/mia/cd1
mkdir ~/opt/mia/cd2
4) Copy the CD contents into the respective directories.
Either directly from the CDs or ISO images mounted as loopback devices.
5) Create fake volume labels for each CD, as needed by the game:
echo "MIA_VOL1" > ~/opt/mia/cd1/.windows-label
echo "MIA_VOL2" > ~/opt/mia/cd2/.windows-label
6) Create a symbolic link kalled "drive_d" pointing to "cd1"
ln -s "cd1" ~/opt/mia/drive_d
7) Run winecfg again to map D: to the newly created "drive_d" directory.
Also set the type as "CD-ROM".
WINEARCH=win32 WINEPREFIX=~/opt/mia winecfg
8) Allow low memory to be mapped, since it is needed by M.I.A. installer.
sudo sysctl vm.mmap_min_addr=0
9) Start the M.I.A. installation through Wine,
WINEARCH=win32 WINEPREFIX=~/opt/mia wine ~/opt/mia/drive_d/mia.exe
10) When prompted for installation of installation type...
Select "Leave ground textures on CD".
This is needed because the installer has issues finding CD #2.
11) Run the following script to easily start the game:

#!/bin/sh
export WINEPREFIX=~/opt/mia

sudo sysctl vm.mmap_min_addr=0 # Wine needs to be allowed to map low memory.

CD_NO=0
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD Number? (1 or 2) " CD_NO
done

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

(cd "${WINEPREFIX}/drive_c/MIA" && WINEARCH=win32 wine miarel.exe -avhpd)
          


If you also want the in-game music, some additional steps are required:
12) Assuming all tracks are ripped from the CD's in FLAC format.
4 audio tracks from CD #1 named from "track02.flac" to "track05.flac".
5 audio tracks from CD #2 mamed from "track02.flac" to "track06.flac".
Copy .flac files into the root of each respective directory "cd1" and "cd2".
13) Patch the "mcicda.dll" file in ~/opt/mia/drive_c/windows/system32/
14) Patch the "miarel.exe" file in ~/opt/mia/drive_c/MIA/
15) Run the following modified script to start the game:

#!/bin/sh
export WINEPREFIX=~/opt/mia

MPLAYER_FIFO=/tmp/mplayer.fifo # Do not change, hardcoded in patched mcicda.dll

sudo sysctl vm.mmap_min_addr=0 # Wine needs to be allowed to map low memory.

CD_NO=0
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD Number? (1 or 2) " CD_NO
done

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

if [ ! -p "$MPLAYER_FIFO" ]; then
  mkfifo "$MPLAYER_FIFO"
fi

cd "${WINEPREFIX}/drive_d"
mplayer -idle -slave -input file=$MPLAYER_FIFO 1&>/dev/null &
MPLAYER_PID=$!
cd -

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

(cd "${WINEPREFIX}/drive_c/MIA" && WINEARCH=win32 wine miarel.exe -avhpd)

kill $MPLAYER_PID
rm -f "$MPLAYER_FIFO"
          


To patch "miarel.exe", open it in a hex-editor and go to offset 0x1427c4. At this location the string "audio" should be present. Replace this with 0x31 0x30 0x38 0x38 0x00 which represents the string "1088" with an additional NULL terminator.

Patching "mcicda.dll" is more complicated as it requires a rebuild of Wine. Get the Wine source code and apply the following source code patch to "./dlls/mcicda/mcicda.c":

--- mcicda.c.orig	2020-05-13 17:55:02.433346437 +0200
+++ mcicda.c	2020-05-13 17:54:53.230346338 +0200
@@ -25,6 +25,12 @@
 #include <stdio.h>
 #include <string.h>
 
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <limits.h>
+
 #define WIN32_NO_STATUS
 #include "windef.h"
 #include "winbase.h"
@@ -79,10 +85,72 @@
 typedef HRESULT(WINAPI*LPDIRECTSOUNDCREATE)(LPCGUID,LPDIRECTSOUND*,LPUNKNOWN);
 static LPDIRECTSOUNDCREATE pDirectSoundCreate;
 
+static void mplayer_command(const char *command)
+{
+    int fd, written;
+
+    fd = open("/tmp/mplayer.fifo", O_NONBLOCK | O_WRONLY);
+    if (fd == -1) {
+        TRACE("No pipe\n");
+        return;
+    }
+
+    written = write(fd, command, strlen(command));
+    if (written <= 0) {
+        TRACE("Write failed\n");
+    }
+
+    close(fd);
+}
+
 static BOOL device_io(HANDLE dev, DWORD code, void *inbuffer, DWORD insize, void *outbuffer, DWORD outsize, DWORD *retsize, OVERLAPPED *overlapped)
 {
     const char *str;
-    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+//    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+
+    int i;
+    BOOL ret = TRUE;
+    CDROM_TOC *toc;
+
+    *retsize = 0;
+
+    switch (code) {
+    case IOCTL_CDROM_READ_TOC:
+        toc = (CDROM_TOC *)outbuffer;
+
+        toc->FirstTrack = 1;
+        toc->LastTrack = 6;
+
+        // Set up first track as data track.
+        toc->TrackData[0].TrackNumber = 1;
+        toc->TrackData[0].Control = 0x4;
+        toc->TrackData[0].Address[1] = 0;
+        toc->TrackData[0].Address[2] = 0;
+        toc->TrackData[0].Address[3] = 0;
+
+        // Set up remaining tracks as dummy audio tracks.
+        for (i = 1; i < toc->LastTrack; i++) {
+            toc->TrackData[i].TrackNumber = i + 1;
+            toc->TrackData[i].Control = 0;
+            toc->TrackData[i].Address[1] = i;
+            toc->TrackData[i].Address[2] = 0;
+            toc->TrackData[i].Address[3] = 0;
+        }
+
+        *retsize = CDROM_TOC_SIZE;
+        break;
+
+    case IOCTL_CDROM_STOP_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    case IOCTL_CDROM_PAUSE_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    default:
+        break;
+    }
 
 #define XX(x) case (x): str = #x; break
     switch (code)
@@ -906,6 +974,9 @@
     SUB_Q_CHANNEL_DATA          data;
     CDROM_TOC			toc;
 
+    int track_no;
+    char command[PATH_MAX];
+
     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
 
     if (lpParms == NULL)
@@ -914,6 +985,20 @@
     if (wmcda == NULL)
 	return MCIERR_INVALID_DEVICE_ID;
 
+    // HIJACK START
+
+    mplayer_command("stop\n");
+
+    track_no = MCI_TMSF_TRACK(lpParms->dwFrom);
+    TRACE("Track no: %d\n", track_no);
+
+    snprintf(command, PATH_MAX, "loadfile track%02d.flac\n", track_no);
+    mplayer_command(command);
+
+    return 0;
+
+    // HIJACK END
+
     if (!MCICDA_ReadTOC(wmcda, &toc, &br))
         return MCICDA_GetError(wmcda);
          

To build the DLL file, it should be enough to run ./configure and make on the Wine source code. The resulting file will be named "mcicda.dll.so" but can be renamed to "mcicda.dll".

Topic: Configuration, by Kjetil @ 24/05-2020, Article Link

Amiga 500 Capacitor Replacement

I recently replaced all the electrolytic capacitors on my Commodore Amiga 500. This was originally for troubleshooting and diagnostics purposes, but sometimes it is a good idea anyway because electrolytic capacitors are prone to drying up and become worse over time. I understand that this varies a lot between manufacturers and production batches, so it's not always the case. As for the Amiga 500, there seems to be some dispute.

Anyway, in this process I had to come up with a easy way to track the work while soldering. So I made this "map" with all the capacitors and their values. It might be helpful to others later:

Amiga 500 Capacitor Locations


Note that this is a Amiga 500 revision 5 board, so others might be different.

Topic: Repair, by Kjetil @ 01/05-2020, Article Link

Dell 2005FPW Display Resolution Fix

I have an old Dell 2005FPW LCD display from around 2005. I had some problems getting this to display the native 1680x1050 resolution in Linux. Instead it would always want to display 1280x1024, and everything would look ugly. The cause of this seems to be bad EDID data being sent by the monitor, because I managed to fix it by manually creating a EDID firmware file with a resolution of 1680x1050 and the refresh rate forced to 59Hz, instead of the more common 60Hz.

There is a nice piece of software here on GitHub to create EDID firmware files from X modeline configuration. I used this together with this handy Online modeline generator.

Here is the modeline generated from the online tool:

# 1680x1050 @ 59.00 Hz (GTF) hsync: 64.07 kHz; pclk: 144.55 MHz
Modeline "1680x1050_59.00" 144.55 1680 1784 1968 2256 1050 1051 1054 1086 -HSync +Vsync
          


I had to trim away the excess ".00" from the string, or else the EDID firwmare file would be too big, 131 bytes instead of 128 bytes, so this should be the actual input to the 'modeline2edid' tool in the EDID generator package:

Modeline "1680x1050_59" 144.55 1680 1784 1968 2256 1050 1051 1054 1086 -HSync +Vsync
          


For reference, here is a hexdump of the newly created EDID firmware:

00000000  00 ff ff ff ff ff ff 00  31 d8 00 00 00 00 00 00  |..1......|
00000010  05 16 01 03 6d 2b 1b 78  ea 5e c0 a4 59 4a 98 25  |....m+.x^YJ.%|
00000020  20 50 54 00 00 00 b3 00  01 01 01 01 01 01 01 01  | PT............|
00000030  01 01 01 01 01 01 77 38  90 40 62 1a 24 40 68 b8  |......w8.@b.$@h|
00000040  13 00 b5 11 11 00 00 1e  00 00 00 ff 00 4c 69 6e  |...........Lin|
00000050  75 78 20 23 30 0a 20 20  20 20 00 00 00 fd 00 3b  |ux #0.    ....;|
00000060  3d 3f 41 0f 00 0a 20 20  20 20 20 20 00 00 00 fc  |=?A...      ...|
00000070  00 31 36 38 30 78 31 30  35 30 5f 35 39 0a 00 e1  |.1680x1050_59..|
          


The file needs to be loaded by putting it in /lib/firmware/edid/ and adding this to the Linux boot kernel parameters:

drm.edid_firmware=edid/1680x1050.bin
          


After this, the resolution became correct in both the framebuffer console and X on the computer where I use this LCD display. The computer has a NVIDIA GeForce FX 5200 graphics gard with the "nouveau" driver in use.

Topic: Configuration, by Kjetil @ 02/04-2020, Article Link

NCR System 3330 Dallas RTC Mod

The Dallas DS12887 RTC inside my NCR System 3330 PC had died a long time ago. Unfortunately, this made the machine unbootable from the hard drive, since it would forget the hard drive settings on each restart. Instead of finding a replacement, like for the Commodore PC 30-III, I opted for the external battery modification instead. I got this working with just two regular AA 1.5V alkaline batteries, a huge success!

The initial error on every startup was as follows:

NCR Battery Power Lost


Fortunately, the Dallas RTC is a in a socket on this machine, easily extracted:

NCR Dallas RTC Extracted


To perform the mod, two sections of the case needs to be opened, which I did with a Dremel tool:

NCR Dallas RTC Dremeled


Afterwards, it's possible to solder on leads for a new battery:

NCR Dallas RTC with new battery leads


I installed a new 2xAA battery holder inside the case, connected to the RTC:

NCR Dallas RTC external battery


The machine is now working again, settings can be saved to CMOS and booting from hard drive is possible:

NCR Powered On


Topic: Repair, by Kjetil @ 14/03-2020, Article Link

Reverse SSH Tunnel Listener

The Reverse SSH Tunnel Launcher script I posted a while ago has some limitations. The worst part is that the tunnel is only open for 5 minutes, leaving too little time to get any work done. This is kind of by design, to prevent having these connections open and "live" when not in use.

The solution to this limitation is another small script, this time just hacked together as a Bourne shell script. Take a look:

#!/bin/sh

while /bin/true; do
  if /bin/netstat -tln | fgrep 127.0.0.1:1337 > /dev/null; then
    ssh localhost -p 1337 screen -d -m ssh -v -R 1338:localhost:22 -N -p 22 192.168.0.1
    echo "New tunnel established!"
    exit
  fi
  sleep 10
done
          


This script will loop forever and wait for a socket to appear on the port (1337) opened by the original launcher. Once this happens, a new tunnel is created (on port 1338) in parallel which will persist forever through a screen session.

Topic: Scripts and Code, by Kjetil @ 02/02-2020, Article Link

Strawman

This is a game project I have had lying around for many years, which I finally made into something usable. The initial idea was to make a side-scroller using the SDL library, and the project codename was "Strawman", so that just became the title as well.

The end result is a highly configurable yet simple game. The map data is stored in a text file and can be easily changed. The "game engine" itself is configured through a bunch of #define macros.

Here's a screenshot:

Strawman screenshot


And the corresponding part of the map data, rotated by 90 degrees on purpose, so adding more lines makes the map longer horizontally:

#
# P
#
###
###  #  CCC
###  #E CCC
###  #  CCC
###
#
#E
#
#
#
##

        # CC
#       # CC
##      # CC
###
####
          


The source code is released under the MIT license and can be downloaded here.

Topic: Open Source, by Kjetil @ 01/01-2020, Article Link

Commodore PC 30-III Repair

The Commodore PC 30-III is a AT-class 286 clone PC running at 12MHz with 1MB of RAM. My first and initial problem was the battery failure upon booting:

Commodore PC 30-III Battery Failure


For some reason, It was not possible to get past this error and continue booting anyway, so a replacement was needed. I got hold of a Glitch Works GW-12887-1 which can replace the original Dallas 1287 RTC in this machine:

Commodore PC 30-III Dallas DS1287 RTC


This is unfortunately soldered directly to the motherboard. But I cut a socket and soldered that one on instead:

Commodore PC 30-III U201 Socket Replacement


In which the replacement fits nicely:

Commodore PC 30-III GW-12887-1


This got the machine booting properly. But after a while of playing around with Compact Flash disk replacements, magic smoke suddenly appeared. Which became my second problem. I located the source; a burned ceramic capacitor:

Commodore PC 30-III Burned Ceramic Capacitor


From what I could find out online, these capacitors can fail if cracks appear in them, and moisture gets in over time. So that's most likely what happened to this 30 year old component. I got a replacement and removed the bad one, which disintegrated almost by itself:

Commodore PC 30-III Capacitor Replacement


The brand new ceramic capacitor in place:

Commodore PC 30-III New Capacitor


The machine is now up and running again:

Commodore PC 30-III Front


Topic: Repair, by Kjetil @ 08/12-2019, Article Link

Linux Distribution for 386SX

I have a Commodore PC 50-II system with a Intel 386SX CPU running at 16MHz and only 5MB of RAM, in addition, the harddrive controller and harddrive is also missing. To get around this, I have installed a 3Com 3C509B-TPO ISA Network card and have managed to boot Linux on this ancient PC over the network instead.

At first I tried to use Buildroot, but I had to give up on this in the end, as it seems that pure 386 is not supported anywhere anymore. So instead, I have gone the route of building everything from scratch, so I could pick and choose specific source versions of GCC and the Linux kernel that supports 386 with math emulation. The end result is a cross-compiling toolchain for i386, a stripped down kernel and Busybox-based rootfs mounted over NFS from another host computer.

I ended up using these specific software versions:
* linux-2.4.37.9
* gcc-3.4.6
* busybox-1.01
* uClibc-0.9.33.2
* binutils-2.32

I also had to statically link everything. I tried with dynamic linking in the beginning but the system would hang during boot, and I didn't want to troubleshoot this any further.

I have made some scripts to greatly simplify the whole process of building the cross-compiling toolchain and all the binaries. Bundled in a file here.

Unpack this into a directory and then simply run the following:

./build.sh
./rootfs.sh
          

I have used these on a Slackware 14.2 box with GCC 5.3.0
The result will be a directory with the "rootfs" and a "bzImage" located inside the kernel build tree.

The rootfs is exported over NFS in /etc/exports like this:

/home/nfs/rootfs *(rw,sync,no_root_squash,no_all_squash,no_subtree_check)
          

Also note that the legacy NFSv2 protocol needs to be actived!

To prepare the kernel is the tricky part. To load it over TFTP with Etherboot you have to use the mkelf-linux script from the mknbi package. This package is not compilable on modern Linux distributions, so I ended up compiling and using it from an old Slackware 11.0 installation running in a QEMU virtual machine.

I used the command as follows:

mkelf-linux --output=pc50linux.nb --ip="192.168.0.3:192.168.0.2:192.168.0.1:255.255.255.0:pc50" --append="root=/dev/nfs nfsroot=/home/nfs/rootfs" bzImage
          

Where .3 is the booted client PC, .2 is the NFS server and .1 is the gateway and TFTP server.

The final step is to activate the TFTP/DHCP server. I used dnsmasq for this, with the following relevant configuration:

dhcp-host=00:ff:ff:ff:ff:ff,192.168.0.3,infinite,set:pxelinux
enable-tftp
tftp-root=/var/ftpd
dhcp-boot=net:pxelinux,/var/ftpd/pc50linux.nb,boothost,192.168.0.1
          


Some additional information: I have no Boot ROM on the Ethernet card, so I used a floppy disk to actually kick-start the network booting. More specifically, the "3c509.dsk" image made from compiling parts of the "Etherboot" package. Since this also isn't compilable on modern distributions, I had to use the Slackware 11.0 QEMU virtual machine again.

Commodore PC 50-II


Topic: Configuration, by Kjetil @ 01/12-2019, Article Link

ADCQ1706 USB Oscilloscope

On a trip to Japan I bought one of these strange USB oscilloscopes. It seems it was designed for use with a Raspberry Pi, but I wanted to use it on a regular Linux desktop PC. Fortunately, the available "client" software for the RPi is written in Python, but it has several limitations. It's all in Japanese and it looks to be based around a web-server capturing still images. However, due to source code availability, I could easily create a new client.

What I present here is a Python PyGame-based solution instead, which has a graphical screen that updates in real time:

Oscilloscope


I have uploaded the code to GitLab and GitHub, but it's also presented here:

#!/usr/bin/python
import serial
import pygame
import time

class Oscilloscope(object):
    def __init__(self, tty_dev='/dev/ttyUSB0', trig_level=2048):
        self._con = serial.Serial(tty_dev, 115200, timeout=2.0)
        self._settings = {
            1 : {'hsync' : 3, 'trig' : trig_level, 'rise' : 1},
            2 : {'hsync' : 3, 'trig' : trig_level, 'rise' : 1}}

    def get_samples(self, channel):
        hsync = str(self._settings[channel]['hsync'])
        trig  = str(self._settings[channel]['trig'])
        rise  = str(self._settings[channel]['rise'])

        self._con.write('ST' + hsync + str(channel) + trig + rise + 'E')
        data = self._con.read(4003)
        if len(data) != 4003:
            return None
        if not (data[0] == 'S') and (data[1] == 'M') and (data[4002] == 'E'):
            return None

        samples = list()
        for i in range(0, 2000):
            samples.append(int((ord(data[i*2+2]) & 0x7F) + (ord(data[i*2+3]) & 0x1F) * 128))
        return samples

    def increase_hsync(self, channel):
        if self._settings[channel]['hsync'] < 6:
            self._settings[channel]['hsync'] += 1

    def decrease_hsync(self, channel):
        if self._settings[channel]['hsync'] > 0:
            self._settings[channel]['hsync'] -= 1

    def get_hsync(self, channel):
        return self._settings[channel]['hsync']

    def toggle_trig_rise(self, channel):
        if self._settings[channel]['rise'] == 1:
            self._settings[channel]['rise'] = 0
        else:
            self._settings[channel]['rise'] = 1

    def increase_trig_level(self, channel):
        if self._settings[channel]['trig'] < 3968:
            self._settings[channel]['trig'] += 256

    def decrease_trig_level(self, channel):
        if self._settings[channel]['trig'] > 128:
            self._settings[channel]['trig'] -= 256

    def get_trig_level(self, channel):
        return self._settings[channel]['trig']

class GUI(object):
    def __init__(self, oscilloscope, scale=1):
        if scale not in [1,2,4]:
            raise Exception("Invalid scale")
        self._scale = scale
        self._osc = oscilloscope
        self._ch_active = {1 : True, 2 : True}
        pygame.init()
        pygame.display.set_caption("Oscilloscope")
        self._screen = pygame.display.set_mode((500 * scale, 512 * scale))
        self._font = pygame.font.Font(pygame.font.get_default_font(), 12 * scale)

    def _toggle_channel(self, channel):
        if self._ch_active[channel] == True:
            self._ch_active[channel] = False
        else:
            self._ch_active[channel] = True 

    def _draw_samples(self, samples, color):
        prev_y = None
        for sample_no, sample in enumerate(samples):
            y = (4096 - sample) / (8 / self._scale)
            x = sample_no / (4 / self._scale)
            if prev_y == None:
                prev_y = y
            pygame.draw.line(self._screen, color, (x, prev_y), (x, y))
            prev_y = y
    
    def _draw_volt_grid(self):
        for pos, volt in [(48,1.5), (715,1), (1381,0.5), (2048,0), (2715,-0.5), (3381,-1), (4048,-1.5)]:
            y = pos / (8 / self._scale)
            pygame.draw.line(self._screen, (128, 128, 128), (0, y), ((500 * self._scale), y))
            text = self._font.render(str(volt) + "V", True, (128, 128, 128))
            if text.get_height() > y:
                self._screen.blit(text, (0, y + (1 * self._scale)))
            else:
                self._screen.blit(text, (0, y - text.get_height() + (1 * self._scale)))

    def _draw_time_grid(self, channel, color):
        hsync = self._osc.get_hsync(channel)
        if hsync == 0:
            time = [0,5,10,15,20,25,30,35,40,45]
            unit = "us"
        elif hsync == 1:
            time = [0,10,20,30,40,50,60,70,80,90]
            unit = "us"
        elif hsync == 2:
            time = [0,50,100,150,200,250,300,350,400,450]
            unit = "us"
        elif hsync == 3:
            time = [0,100,200,300,400,500,600,700,800,900]
            unit = "us"
        elif hsync == 4:
            time = [0,1,2,3,4,5,6,7,8,9]
            unit = "ms"
        elif hsync == 5:
            time = [0,2,4,6,8,10,12,14,16,18]
            unit = "ms"
        elif hsync == 6:
            time = [0,10,20,30,40,50,60,70,80,90]
            unit = "ms"

        for index in range(0, 10):
            x = index * (50 * self._scale)
            if x > 0:
                pygame.draw.line(self._screen, (128, 128, 128), (x, 0), (x, (512 * self._scale)))
            text = self._font.render(str(time[index]) + unit, True, color)
            if channel == 1:
                self._screen.blit(text, (x + (1 * self._scale), 0))
            if channel == 2:
                self._screen.blit(text, (x + (1 * self._scale), (512 * self._scale) - text.get_height()))

    def _draw_trig_line(self, channel, color):
        y = (4096 - self._osc.get_trig_level(channel)) / (8 / self._scale)
        pygame.draw.line(self._screen, color, (0, y), ((500 * self._scale), y))

    def loop(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                        return
                    elif event.key == pygame.K_s:
                        pygame.image.save(self._screen, "oscilloscope.png")
                        print "Screenshot saved to 'oscilloscope.png'."
                    elif event.key == pygame.K_1:
                        self._toggle_channel(1)
                    elif event.key == pygame.K_2:
                        self._toggle_channel(2)
                    elif event.key == pygame.K_3:
                        self._osc.increase_hsync(1)
                    elif event.key == pygame.K_4:
                        self._osc.decrease_hsync(1)
                    elif event.key == pygame.K_5:
                        self._osc.increase_hsync(2)
                    elif event.key == pygame.K_6:
                        self._osc.decrease_hsync(2)
                    elif event.key == pygame.K_7:
                        self._osc.toggle_trig_rise(1)
                    elif event.key == pygame.K_8:
                        self._osc.toggle_trig_rise(2)
                    elif event.key == pygame.K_e:
                        self._osc.increase_trig_level(1)
                    elif event.key == pygame.K_r:
                        self._osc.decrease_trig_level(1)
                    elif event.key == pygame.K_t:
                        self._osc.increase_trig_level(2)
                    elif event.key == pygame.K_y:
                        self._osc.decrease_trig_level(2)

            self._screen.fill((255,255,255))
            self._draw_volt_grid()

            if self._ch_active[1]:
                self._draw_time_grid(1, (255,128,128))
                self._draw_trig_line(1, (255,128,128))
                samples = self._osc.get_samples(1)
                self._draw_samples(samples, (255,0,0))

            if self._ch_active[2]:
                self._draw_time_grid(2, (128,128,255))
                self._draw_trig_line(2, (128,128,255))
                samples = self._osc.get_samples(2)
                self._draw_samples(samples, (0,0,255))

            if (not self._ch_active[1]) and (not self._ch_active[2]):
                time.sleep(0.1) # To avoid 100% CPU usage.

            pygame.display.flip()

if __name__ == "__main__":
    import sys
    import getopt

    def print_usage_and_exit():
        print "Usage: %s [options]" % (sys.argv[0])
        print "Options:"
        print "  -h         Display this help and exit."
        print "  -d DEV     Serial TTY DEV to use instead of /dev/ttyUSB0."
        print "  -s SCALE   Scale of GUI, value 1, 2 or 4."
        print " "
        sys.exit(1)

    def print_keys():
        print "Keys:"
        print "  1 = Toggle channel #1"
        print "  2 = Toggle channel #2"
        print "  3 = Increase time/div for channel #1"
        print "  4 = Decrease time/div for channel #1"
        print "  5 = Increase time/div for channel #2"
        print "  6 = Decrease time/div for channel #2"
        print "  7 = Toggle rise/fall trigging for channel #1"
        print "  8 = Toggle rise/fall trigging for channel #2"
        print "  E = Increase trig level for channel #1"
        print "  R = Decrease trig level for channel #1"
        print "  T = Increase trig level for channel #2"
        print "  Y = Decrease trig level for channel #2"
        print "  S = Screenshot"
        print "  Q = Quit"

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hd:s:")
    except getopt.GetoptError as err:
        print "Error:", str(err)
        print_usage_and_exit()

    tty_dev = None
    scale = None
    for o, a in opts:
        if o == '-h':
            print_usage_and_exit()
        elif o == '-d':
            tty_dev = a
        elif o == '-s':
            scale = int(a)

    if tty_dev:
        osc = Oscilloscope(tty_dev)
    else:
        osc = Oscilloscope()

    if scale:
        gui = GUI(osc, scale)
    else:
        gui = GUI(osc)

    print_keys()
    gui.loop()
          


Topic: Scripts and Code, by Kjetil @ 01/11-2019, Article Link

Commodore 1541-II Floppy Drive Repair

I was able to repair my Commodore 1541-II floppy drive, which is typically used together with the Commodore 64.

The first problem was that I do not have the original (external) power supply, but fortunately it uses fairly standard +5V and +12V voltages, which are also used by most PC hardware. So I made an adapter from a 4-pin molex to a 4-pin DIN connector:

Commodore 1541-II Power Adapter

The pinout of the DIN connector can be found here among other places.

When powering up the drive for the first time, it would keep the drive motor running constantly, which is apparently a known problem. Some other people online said this could be caused by a faulty PSU or bad ROM chip...

When I attempted to continue troubleshooting the next day, the situation had worsened. Now the power LED on the drive would flash a little on power on and slowly fade away. Symptoms of a short circuit or something perhaps...

With no idea on what to do about this, I decided to try to replace the electrolytic capacitors, which people often do on restoration/repair projects.

There are only three of them on the main board, all 10uF and 25V, located here:

Commodore 1541-II Capacitor Locations


Old and new replacements:

Commodore 1541-II Capacitor Replacement


To my surprise, this actually worked, and the drive is now working:

Commodore 1541-II Working


I have a theory: Two of those capacitors I changed are between the incoming 12V/5V and ground, acting as "decouping/bypass" to filter out noise. If there happened to be a short circuit or weakened resistance in the capacitors, that would explain parts of the symptoms at least.

Topic: Repair, by Kjetil @ 26/10-2019, Article Link

Older articles