Thanks to the folks at Newark/Farnell, I have been given the opportunity to review another microcontroller development board. This time, it’s the Atmel AT90USBKEY, a cool little USB development board. The AT90USBKEY is powered by the Atmel AT90USB1287 microcontroller. Here are some pictures of the unboxing:

It comes with several cool goodies:

  • The development board itself (which has a USB mini-AB receptacle)
  • A standard USB A-to-mini-B cable that you can use to connect the board to your computer
  • A special USB cable — on one end, it has a USB A receptacle, and on the other end it has a USB mini-A connector
    • I’ve never seen anything like this cable before. The mini-A end of it plugs into the development board, and then you can plug whatever device you want into the “A” receptacle, allowing the board to act as a USB host rather than a device.
  • A 9V battery clip for powering the microcontroller if you’re using it in host mode with the aforementioned cable

Since this board uses some weird (but standard) USB connectors, I’d like to explain them in detail right now before I finish reviewing the product.

USB connectors:

As you probably know, there are normally two major types of USB connectors: A and B. You usually plug a device with a B receptacle into a host with an A receptacle (or a hub with A receptacles). This is why most USB cables you find have an A connector on one side and a B connector on the other side. An A-to-A cable doesn’t make much sense (although I have seen them!), and neither does a B-to-B cable.

You also commonly see devices that have smaller USB receptacles, such as digital cameras and microcontroller development boards. They tend to use mini-B or micro-B receptacles. Because of this, another type of cable is very common: A-to-mini-B and A-to-micro-B. I have tons of these types of cables laying around.

One type of connector you don’t see very often is mini-A or micro-A. They do exist, but they aren’t very common because most computers and hubs have full-size A receptacles. There is a major reason you’d find them, though. Read on…

What about a USB port that is supposed to be either a device or a host, depending on what you connect it to? Should it have an A receptacle or a B receptacle? The answer is “neither.” This is why mini-AB and micro-AB receptacles exist, and it’s called USB On-The-Go. They can accept either an A connector or a B connector (of the required size — mini or micro). Depending on what type of cable you plug in, it will decide whether it should act as a host or a device. In practice, I haven’t seen this type of receptacle on consumer devices, but I see it a lot with development toolkits.

This is the type of receptacle that is on the AT90USBKEY. If you use an A-to-mini-B cable to plug it into your computer, it knows it should act as a device and does so. On the other hand, if you use the other supplied cable that is mini-A-to-A, it knows it should act in host mode, it will behave like one. The USB controller will give you, the programmer, the ability to detect whether it’s currently a host or a device. The A receptacle on the other end of the mini-A-to-A cable just makes it convenient to plug in a standard USB device because you don’t find many USB devices that have a mini-A connector.

I honestly can’t think of any reason for why you would need a mini-A or micro-A connector other than for a USB On-The-Go device, at least as of the time of this writing. Anyway, that is my quick introduction to the AT90USBKEY’s USB port. Enough about that — let’s get on with the review!

The review:

AVRs are very interesting microcontrollers for a number of reasons.

  • First of all, they are well-supported in the hobbyist community. The Arduino project is a good example of this. There are plenty of people making cool hobby projects with AVRs (myself included–more on this in a later post!). There is an excellent set of community-supported development tools for the AVR platform — binutils, gcc, avr-libc, and avrdude are a few of the essentials.
  • They are 8-bit microcontrollers (well, except for some of the newer AVRs). In the 32- and 64-bit world of PCs, it can be kind of strange going back to an 8-bit system. Although C compilers will automatically generate 8-bit code that manipulates larger variables (16- and 32-bit integers, for example), you have to be careful about performance and interrupt safety when working with bigger variables.
  • It gets better — not only are these microcontrollers 8-bit, but they are weird because they have different address spaces for RAM and program instructions (stored in flash), as opposed to something like an ARM microcontroller where everything shares different chunks of the same address space. This requires some weird coding if you’re trying to access constant variables stored in the flash memory, and also prevents you from executing instructions stored in RAM. (Side note: This distinction is sometimes called Harvard architecture versus von Neumann architecture, although modern processors seem to use aspects of both architectures in their designs.)
  • They tend to be very straightforward to program. The built-in peripherals are pretty easy to understand in my experience, and the datasheets that explain the peripherals are pretty easy to read. Recall when I covered the AVR’s SPI peripheral in a previous post–not too bad, right?

Like I said earlier, this board uses the AT90USB1287 microcontroller, which is an 8-bit AVR. You may notice the “USB” in the name. The reason for that is that because you can’t just pick any AVR to be a USB device. This is a chip with all of the necessary hardware built-in to be either a USB host or device, so the name lets you know that. More about this chip: it has 128 kilobytes of flash, 8 kilobytes of RAM, 4 kilobytes of EEPROM, and it can run at a maximum of 16 MHz, although this board only has an 8 MHz crystal on it.

When I said it has 128 kilobytes of flash and 4 kilobytes of EEPROM, you may have been wondering what I meant. What’s the difference? In 8-bit AVRs, flash is designed for code storage and must be erased in large chunks. If you want to erase a byte to write a new value in its place in flash, you must erase many of the neighboring bytes as well. For that reason, it’s not ideal for storing individual byte values that you will have to change in your program. On the other hand, EEPROM is meant for storing data and can be erased on a byte-by-byte basis. The idea is to put your code and large constants into flash because they will only change when you change the firmware. You can put program configuration values that must be saved across power cycles into the EEPROM and not worry about erasing other nearby bytes when you change them.

Aside from the microcontroller, the board also has a small joystick, a temperature sensor, two LEDs (which can each be green or red), two buttons (one is for resetting, the other one is a bootloader entry button which can also be used for your own purposes), and two external memory chips. It comes programmed with a demo application that acts as a mouse and USB disk when plugged into your computer. The demos seem to work great. It also comes from the factory with a USB bootloader, so you don’t even need any extra hardware to program it. The bootloader puts the device into a USB DFU (device firmware upgrade) mode if you’re holding down the bootloader button when it powers on. In order to flash your own program to the board through the bootloader, you will need to use a program compatible with the DFU bootloader — Atmel’s FLIP and the dfu-programmer open-source project are two ways to get it done. I’ll write more about them later in this review. If you want to use JTAG to program it instead, a 10-pin JTAG header came soldered on mine too. For that, you would need a JTAG-compatible programmer such as the AVR Dragon or the AVR ONE!.

Just like I said in my last microcontroller development board review, the demo apps are exciting and all, but the real value in these boards comes when you write your own programs. This can be quite complicated in this case because the most impressive built-in peripheral is the USB controller. USB is a monster of an interface to use for a simple program. Remember when I said earlier that AVRs are straightforward to program? Well, the USB controller is an exception. It’s not Atmel’s fault — it’s just that USB is complicated. Luckily, Dean Camera has come out with a really exciting project called LUFA. It handles talking to the USB controller for you, so all you have to do is work with a higher-level API instead of talking directly with the USB registers in the microcontroller. I’m not going to cover LUFA in this review, but you should definitely check it out.

For the rest of this review, I’m going to walk through getting a development environment set up for programming to this board, and then I will make a simple demo app (although it won’t involve the USB controller — sorry!). We will, however, use the USB capability of the chip to flash your new compiled program using the bootloader. Here goes nothing!

Setting up the development environment:

I really enjoy using Eclipse for my programming, so I’m going to create an Eclipse-based environment. Let’s start out by downloading Eclipse. As of the date of this review, the latest version of Eclipse is Indigo (3.7.1). Download the Eclipse C/C++ environment for your operating system from this page. Extract the contents of the zip archive to a location of your choice. (I’ve found that some versions of Windows don’t like the zip file very well — if you run into any problems, use 7-zip to extract the file instead of the built-in Windows extraction tools).

Open up Eclipse and install the AVR Eclipse plugin using the directions provided on this site. This will make it easy to create cross-compiled AVR projects in Eclipse. (Otherwise, you’d have to mess around with a bunch of C compiler settings to tell Eclipse to use AVR gcc instead of your system’s default gcc)

Now, install the AVR development tools. This will differ based on which operating system you’re using:

If you’re using Windows:

Install the Windows AVR development tools. This will include gcc, binutils, avr-libc, and avrdude. They are packaged together and called WinAVR (note: when accessing this site, I occasionally get redirected to another site because of the webring they are using — if that happens, just click the back button in your browser). Go ahead and download the latest version of WinAVR and install it. Make sure during the installation you check any boxes asking to add WinAVR binaries to your path.

While you’re at it, install Atmel’s FLIP. We will use this to program the new device.

You will probably have to quit and relaunch Eclipse at this point so that it gets the changes that WinAVR made to the system PATH variable. If you don’t relaunch it, it probably won’t be able to find the AVR compiler because it’s still using the old PATH variable.

If you’re using Linux:

Install your distribution’s AVR development tools. In Ubuntu, you can type the command:

sudo apt-get install binutils-avr gcc-avr avr-libc avrdude dfu-programmer

(You don’t really need avrdude right now, but it’s good to have in case you ever start using JTAG or ISP to program AVR devices)

There’s a little more to it, though. Linux can be picky about the permissions of USB devices, so you will probably need to add a udev rule. If you don’t add this udev rule, you will have to run dfu-programmer as root, which is less than ideal. Create the file /etc/udev/rules.d/99-dfu-programmer.rules containing:

SUBSYSTEM=="usb", ACTION=="add", SYSFS{idVendor}=="03eb", SYSFS{idProduct}=="2ffb", MODE="660", GROUP="plugdev", SYMLINK+="at90usb-%k"
BUS=="usb", ACTION=="add", SYSFS{idVendor}=="03eb", SYSFS{idProduct}=="2ffb", MODE="660", GROUP="plugdev"

Once you’ve created the file, type:

sudo udevadm control --reload-rules

The purpose of this last command is to get udev to reread its list of rules. After doing this, the permissions for the USB device should be correct the next time you plug it in. By the way, I got these udev instructions from the AVR Freaks wiki, but their wiki is so slow and messed up right now that I’m not going to bother linking to it.

If you’re using Mac OS X:

Sorry, I’m lazy, but it shouldn’t be too bad. You just need dfu-programmer for OS X and AVR development tools. Looks like this is a good AVR toolkit for OS X. I’m not sure where you can find dfu-programmer, but you could always compile it from source if you want.

Creating the project:

Now, we’re back to a point where it doesn’t matter what OS you’re using. Open up Eclipse. Go to File->New->C Project. A window will pop up. If it’s not already expanded, expand the arrow next to “AVR Cross Target Application” and choose “Empty Project.” The toolchain selected on the right should be “AVR-GCC Toolchain.” Give your project a name and click Next. You’ll notice that Eclipse will create a Debug and Release configuration. You can leave them both on if you want, but I tend to remove the Debug configuration because it breaks some of the optimizations that avr-libc depends on (the delay functions, for instance). Click Next, and then you will be asked to name the microcontroller and clock frequency. The microcontroller is an AT90USB1287. The AT90USBKEY has an 8 MHz crystal and its provided programmed fusebits divide the crystal frequency by 8 to give you a clock rate of 1 MHz by default. However, we’re going to be disabling that prescaler at the start of our code and making it run at the full 8 MHz, so you should type “8000000” into the MCU frequency text box. Finally, click Finish.

If you left the Debug build configuration enabled, make sure that your currently-selected build configuration is the “Release” configuration. Right-click your project in the left column of the Eclipse window and choose Build Configurations->Set Active->Release to select Release. If you don’t do this, the delays won’t work (and you will get build warnings from avr-libc telling you to turn on optimizations or else the delay functions won’t behave as intended).

Now, we’re ready to create a simple project. Let’s blink the LEDs. The code will be very similar to some of my earlier microcontroller programming examples. Before we write the code, let’s do the research and find out what GPIO pins we will need to play with.

According to the AT90USBKEY hardware user guide, the LEDs (D2 and D5) are bi-color LEDs connected to PORTD:

  • D2
    • Red is connected to PORTD, pin 4
    • Green is connected to PORTD, pin 5
  • D5
    • Red is connected to PORTD, pin 7
    • Green is connected to PORTD, pin 6

They behave just like they are separate LEDs. So in effect, you have four LEDs available, although each pair of green and red LEDs overlap with each other and look kind of strange when they are both on at the same time. Anyway, this is all we need to know to get a simple program running. Let’s do it!

Create a new C file by right-clicking on your project in the left column of your Eclipse window and choosing New->Source File. Name your file main.c and leave the template as the “Default C source template.” Type (or copy/paste, if you’re not masochistic) this code into main.c:

#include <avr/io.h>
#include <util/delay.h>
#include <avr/wdt.h>
#include <avr/power.h>

#define LED_PORT                                PORTD
#define LED_PORT_DDR                            DDRD
#define LED_PIN                                 PIND

#define LED1_RED                                (1 << 4)
#define LED1_GREEN                              (1 << 5)

#define LED2_RED                                (1 << 7)
#define LED2_GREEN                              (1 << 6)

int main(void)
{
    // In case the watchdog timer is enabled, disable it.
    wdt_disable();

    // Make sure the clock prescaler is disabled (divide by 1)
    clock_prescale_set(clock_div_1);

    // Set the LEDs as outputs and turn them all off
    LED_PORT_DDR |= LED1_RED | LED1_GREEN | LED2_RED | LED2_GREEN;
    LED_PORT &= ~(LED1_RED | LED1_GREEN | LED2_RED | LED2_GREEN);

    // Turn on LED1's red output and LED2's green output
    LED_PORT |= (LED1_RED | LED2_GREEN);

    while (1)
    {
        // Wait and then toggle all four LEDs
        _delay_ms(1000);
        LED_PIN = LED1_RED | LED1_GREEN | LED2_RED | LED2_GREEN;
    }
}

Now, compile the program by going to Project->Build All. This command actually builds all open projects, but since this is the only project we have open, it will work. You may see some weird errors about DDRD and PORTD being undefined — if so, it’s probably Eclipse whining about it rather than the compiler. Rebuild the index by right-clicking on your project and choosing Index->Rebuild — hopefully those errors will go away. Anyway, you should have a .hex file inside the “Release” folder ready for flashing.

I want to share a quick note about this code before we get to the rest of the flashing. Did you notice that I write to the PIND register to toggle the LEDs inside the while loop? Normally, this register is used for reading the state of port D’s input pins, and you would use PORTD to change the state of the output pins. AVRs have a cool feature — if you write a “1” to a bit in an AVR’s PINx register, it will actually toggle the value of the corresponding bit in the PORT register. Any bits that are 0 are unaffected. It’s just a handy little shortcut that probably doesn’t apply to other microcontrollers, but it does work on several different AVRs that I have used. The code generates results identical to (but is more efficient than):

LED_PORT ^= LED1_RED | LED1_GREEN | LED2_RED | LED2_GREEN;

Enough about that — back to flashing!

Flashing your code to the board:

If all went well, you are ready to test your newly-created firmware project. First of all, let’s get your AT90USBKEY board into its bootloader. Connect the board to your computer. Now, while holding down the HWB button on the board, press the RST button on the board. This forces the AT90USB1287 to boot into its supplied USB DFU bootloader. Alternatively, you could also just hold down the HWB button while plugging the board into your computer.

Now, we need to break off depending on which OS you’re using again:

If you’re using Windows:

Open up Flip (you installed it already, right?). Click the leftmost icon in the toolbar (looks like a DIP chip) and select AT90USB1287 as your target device. Now, click the second icon from the left (looks like a USB cable) and choose USB. A dialog box will come up–click Open. All of the buttons in the Flip window should be enabled now. You’ve made contact with the bootloader! Click the third icon from the right (looks like a book with an arrow pointing down) to load a hex file to download to the device. Navigate to your Eclipse workspace and find the YourProjectName.hex file. It should be in the Release folder inside your project’s folder. This will load the .hex file into Flip’s buffer, but won’t program it yet.

On the left side of the Flip window under Operations Flow, make sure Erase, Program, and Verify are checked. If they are, click Run. If all goes well, the status bar in the bottom of the Flip window should say “Verify PASS.”

If you’re using Linux:

This should be pretty easy, assuming you have already configured dfu-programmer correctly. Type:

dfu-programmer at90usb1287 erase
dfu-programmer at90usb1287 flash /path/to/my/projectfile.hex

(Of course, replacing /path/to/my/projectfile.hex with the path to your hex file.) That’s it!

If you’re using Mac OS X:

Once again, I’m lazy. You should be able to use the same directions as Linux if you can get dfu-programmer up and running.

Running your code:

You have now successfully programmed your firmware onto the board. Press the RST button on your board and watch as your program runs and toggles the LEDs every second. Easy, right? If you want the original firmware that came on the board, you should be able to get that back by flashing one of the provided .a90 files from Atmel’s AVR287 example. To be safe, it might be wise to back up the supplied contents of the mass storage device that the board’s default firmware creates before loading your custom firmware.

Conclusion:

I have now shown you how to get a simple program running on the board. Download LUFA, play around with it, and see what you can create! Atmel also provides some USB libraries, although I haven’t played with them.

As far as this board goes, it’s fantastic. It gives you plenty of fun devices play with. You can learn about GPIO pins with the LEDs (outputs) and the joystick (inputs), you can learn about analog-to-digital converters (ADCs) with the temperature sensor, you can learn about SPI with the two serial flash chips, and you can of course learn about USB.

Pros:

  • It’s really easy to get running without needing any external programmer hardware. It’s basically unbrickable.
  • They provided some handy (exotic?) cables to give you the opportunity to play with the board as either a USB host or device.
  • Atmel made creative use of the USB capability by providing all documentation and software on the device itself as a mass storage device that appears when you plug it in.
  • It has awesome community support because it’s an AVR.

Cons:

  • The DFU flashing software (particularly Flip) is kind of confusing and annoying to use. It’s a lot more convenient to develop with JTAG or ISP because you don’t have to physically mess with the board whenever you want to write a new program to it. It would also be nice to integrate this flashing with Eclipse. I’m sure it’s possible with a custom run configuration and a script.
  • They brought the other port pins out to very tiny headers. It appears that headers would be difficult to solder, and it would be a challenge to find the correct header part for soldering. It would be nice if they used standard 0.1″ pitch headers instead, although that would obviously come at the expense of a larger board size.

You can buy an AT90USBKEY at Newark. Thanks again to Newark/Farnell for the opportunity to review this cool little development kit!

After recently installing Ubuntu 11.10 onto my Mac mini, I’ve been mildly annoyed when I connect to it through PuTTY from my Windows machine. It’s working fine, except gcc displays a weird “â” character instead of quotes in its error messages. I figured it was some weird locale or terminal setting I hadn’t configured properly in Ubuntu because I did a minimal install with only a few server packages, but I was dead wrong. I tried SSHing to a standard Ubuntu 11.10 install with a regular desktop environment and everything, and it still had the weird character in PuTTY!

It turns out that it’s really simple — PuTTY defaults to an ISO-8859-1 character set and Ubuntu defaults to a UTF-8 character set. All I had to do was change my PuTTY settings to use UTF-8 instead:

(The highlight is kind of hard to see, but I clicked “Translation” underneath the “Window” category on the left side to get to that screen.)

After making that change in PuTTY, it works perfectly. Passing the gcc output to hexdump -C shows that the quote characters are represented as:

0xE2 0x80 0x98

and

0xE2 0x80 0x99

(which are UTF-8 sequences for ‘ and ’, respectively). Sure enough, 0xE2 in ISO-8859-1 is â, and 0x80, 0x98, and 0x99 are C1 control codes, which don’t actually display a character. So that’s the “why” behind this whole situation.

I know this probably seems like a simple thing to write a blog post about, but sometimes it’s kind of freaky when you do a minimal install of a Linux distribution and little glitches like this pop up because you forgot to install or configure a standard package that everyone tends to use. Even though that wasn’t the case here, I know others will run into the same problem and suspect the same thing I did originally, so I hope this helps someone else out (and maybe teaches a little bit of trivia in the process)!

This should also apply to other PowerPC Macs such as the G3, G4, iBook, and various iMac models (I think)…

I wanted to install Ubuntu 11.10 onto my Mac mini after replacing its hard drive. I found some excellent netboot install directions by Evan Martin, which I was able to follow (although I used the files from this directory for the netboot). However, I ran into a small problem when beginning the install–the netboot image for 11.10 does not include the parallel ATA driver for Macs (pata_macio.ko). It causes the installer to not detect any hard drives.

The Ubuntu FAQ I linked to above suggests installing 11.04 and then upgrading to 11.10. I didn’t feel like doing an upgrade install, so I decided to go another route. Here’s how I did it (starting at the point where I was told that no hard drives could be detected)…

  1. I manually downloaded the PowerPC kernel package.
  2. Next, I extracted lib/modules/3.0.0-12-powerpc/kernel/drivers/ata/pata_macio.ko by opening the .deb file with Archive Manager, and stuck it in my TFTP server directory.
  3. Almost there…I used tftp to grab it from my TFTP server and put it in /tmp on the Mac mini
    • Get to a console on the Mac mini by pressing Alt-F2. Remember, on an Apple keyboard, Alt is the option key and you may have to hold down the “fn” key to get F2 to be recognized as F2 instead of a brightness key.
  4. Finally, I inserted the module with insmod, switched back to the installer by pressing Alt-F1, and continued on with my install. I think I had to go back one step and try again, and then the hard drive was recognized.

By the way, it sounds like this will be fixed in 12.04. Yippee! Until then, this is another way of getting it done. I hope this helps someone else out there…

I have a homebuilt computer with an Antec Sonata III case and an Intel DX58SO motherboard. I really, really like both the case and the motherboard, but I’ve been struggling with a sound problem in the computer for two years now. It never bothered me enough to think about fixing it until last week, but I finally fixed it tonight and would like to share my story.

The problem goes as follows:

I use the front panel headphone jack a lot on my computer. The sound coming out of that jack was always fine until I plugged a high-speed USB device into one of the two front panel USB ports. As soon as I did that, I would always hear weird “beeps” or “screeches” in my headphones as USB data was being transferred. The problem was especially noticeable with things like external USB flash drives, my iPhone, and my AVR ISP programmer, but not with lower-speed devices like USB gamepads. It only affected the combination of the front headphones and the front USB ports — devices plugged into the rear USB ports would not affect the headphones, and devices plugged into the front USB ports did not affect the rear speaker jack.

In some ways, it was actually kind of cool to be able to hear USB data transfers, but it would get annoying when I was trying to listen to music. I did a lot of Googling about this problem, and it turns out that it’s a common problem with some of Antec’s cases (and cases by other manufacturers too). The connector you plug into your motherboard for the front USB ports has a ground pin on it. The connector you plug into your motherboard for the front audio ports also has a ground pin on it. So your motherboard provides a ground for each of these connectors. The problem is that the front port assembly on my case connected the ground pins for the USB ports and the audio ports together on its end. This created a ground loop. My understanding is that because the USB and audio connectors provide their own separate grounds through different wires, they should not be connected together at the front panel because if the two grounds differ slightly in voltage (which they can, because wires and PCB traces do have a [small] resistance), current will flow between them. This current flow manifests itself as weird sounds on my headphone jack. (I’m really not an electrical engineering expert, so if I’m incorrect or lacking in my explanation, someone please let me know in the comments below).

Here are some forum/blog postings by other people who encountered this same problem on other case models:

I was able to verify this by using my multimeter in “continuity test” mode. After disconnecting all the case’s wires to the motherboard, I tested the continuity between the high definition audio (HDA) connector’s ground pin and the USB connector’s ground pin. It showed continuity, so that proved that the USB and audio connectors’ grounds were hooked together somewhere inside the front panel module.

Before I did any of these diagnostics, I was writing back and forth with Antec’s customer support. I must say, Antec has excellent customer service. The people I’ve dealt with are friendly and knowledgeable. Antec customer support told me that they have this problem fixed in a newer version of the front port assembly. Meanwhile, I was waiting for it to arrive, so I decided to play with my existing front port module to see if I could fix it myself, knowing that even if I failed, a new one was on the way. With nothing to lose, why not go for it?

First, I took the air filter out (it slides out of the bottom of the front of the case). Next, I removed the front of the case. This was slightly tricky — I removed all 5.25″ devices (just my DVD burner in this case) and the external 3.5″ drive bay. With those out of the way I was able to pull off the front of the case by releasing the 6 tabs holding it on (3 on each side of the case — top, middle, and bottom). The front panel module also had a wire screwed to the chassis which I had to disconnect (interestingly, this wire is only attached to the front panel eSATA port — it has no connection whatsoever to the audio or USB ports — good thing because that would probably cause another ground loop!)

Here’s the front of the case, completely removed:

The front port assembly was attached to the front of the case by 3 screws — I removed these and then it was free to go:

Unfortunately, the front port assembly is sealed–it’s glued together or something along those lines. It’s not held together with screws or anything like that, so it’s kind of a pain to open up. It was no match for my X-Acto knife though! I was able to cut around where I could see the two plastic halves meet, and with the help of a small screwdriver, pried it apart. Amazingly, the two halves of the plastic casing stayed intact! The culprit immediately jumped out at me: there was a white wire coming out of the sealed audio assembly and soldered to the shield of one of the USB ports. I checked it with my continuity tester to be sure, but I already knew it had to be that wire, because it was the only wire that connected the USB ports to the audio ports. (This picture was taken after I had hacked it, but I tried to recreate what it looked like at first)

I grabbed my soldering iron and desoldered the white wire from the USB port:

Before doing anything else, I plugged the USB ports and audio jacks back into the motherboard, booted it up, and tested to see if the interference was still there. It was GONE! In fact, I was able to make the interference reappear by momentarily touching the white wire back to the USB port. My multimeter confirmed that disconnecting the white wire had indeed separated the audio and USB grounds from each other. I ended up cutting off most of the white wire and covering the remaining stub with electrical tape just to be safe. Somehow, even after my hack job with the X-Acto knife, the two halves of the plastic case for the front port assembly snapped back together (and stayed that way), so I didn’t have to reseal it. I put the case back together, and the audio output from my headphone jack is perfect now. I can’t hear any interference at all anymore, even if I turn my sound up all the way and plug in both my AVR programmer and my iPhone to the front USB ports.

I wish I had fixed that one a long time ago!

Epilogue:

The replacement front port assembly from Antec arrived, and it also fixes the sound problem. If you don’t want to hack apart your front assembly, get ahold of Antec customer support. They are great! I would definitely recommend getting a replacement assembly from Antec instead of hacking apart your existing one. For anyone interested, I checked out the new assembly with my multimeter, and it correctly has the USB and audio grounds separated now. The new revision also makes another change I thought I’d mention: the USB ports are also grounded to the chassis now (only the eSATA port was before — now both USB ports and the eSATA port are). So if you insist on doing it yourself, it might be wise to take that white wire you cut and use it to connect the USB and eSATA grounds together, so they will all be grounded to the chassis.

The easiest way would probably be to leave the white wire soldered to the USB port, cut it off on the audio port end, shorten the wire, and solder the other end to where the chassis ground wire connects to the little eSATA PCB. Here’s an illustration of what I mean:

Hi again everybody! Once again, I let a bunch of time elapse before writing another article in my microcontroller programming series. I left off last time by mentioning that most microcontrollers have a built-in SPI peripheral that handles the SPI communication protocol for you. Today, I’m going to talk about how such a peripheral would work. I’m going to do it differently from I have done in the past, though. This time, instead of making up a theoretical peripheral, I’m going to actually walk through an actual peripheral built-in to a real microcontroller! I’m going to be using the AVR ATmega328P, which is also the chip used in the Arduino Uno. Note: I don’t actually have an Arduino Uno (nor anything else with an ATmega328P for that matter), but I figured I would review the peripheral and talk about how to make it work.

We’re going to pretend to talk to some random SPI slave device, and I’ll show you how to write (and read) a byte to it. In this situation, the ATmega328P will be the master device.

As you may (or may not) remember, SPI uses four pins: MISO, MOSI, CLK, and CS. Before we do anything, we need to initialize these four pins as inputs or outputs. Let’s take a second to figure out how the pins need to be configured. MISO is master in, slave out. This means it will be an input on the master, since data is coming from the slave to the master. MOSI is the opposite, so it will be an output. CLK and CS are both controlled by the master, so they will also be outputs. So the first line of business is to set MISO as an input and the other three pins as outputs.

On the AVR we’re using, port B is where the SPI functions are located. On port B, pin 2 is chip select (they call it slave select, but it means the same thing), pin 3 is MOSI, pin 4 is MISO, and pin 5 is CLK. So using the AVR’s data direction register, let’s make sure that port B, pin 4 is configured as an input, while port B, pins 2, 3, and 5 are outputs.

DDRB |= ((1 << 2) | (1 << 3) | (1 << 5));
DDRB &= ~(1 << 4);

This will turn on bits 2, 3, and 5 of the port B’s DDR register, and turn off bit 4.

Now, before we do any more register reading/writing, let’s look at the SPI registers available in the ATmega328P’s datasheet. This is more or less going to be the same information available in the datasheet, but I’d like to walk through it to describe which registers are important and which ones are just small configuration things that aren’t really relevant to understanding how the peripheral works.

The first register is SPCR, the SPI control register.

  • Bit 7 is SPIE — the SPI interrupt enable. If this bit is turned on, you will get an interrupt from the SPI peripheral whenever a transmission completes. For now, we don’t want to worry about interrupts, so we will leave this off.
  • Bit 6 is SPE — SPI enable. This bit actually turns on the SPI peripheral, so we will definitely want to turn it on.
  • Bit 5 is DORD — data order. When it’s 1, data is transmitted serially least-significant bit first. 0 means most-significant bit first. What you set here depends on the slave you will be talking to. For our purposes, let’s assume the slave we will be communicating with expects to receive data least-significant bit first, so we will set it to 1.
  • Bit 4 is MSTR — master/slave select. We will be setting this to a 1 to ensure that the AVR will act as a master rather than a slave.
  • Bit 3 is CPOL — clock polarity. This is another one that’s dependent on the slave you’re talking to. Some slaves expect you to keep the clock line high when you’re not communicating to the slave, and others expect you to leave it low. The slave datasheet will tell you which one you’re supposed to use. For our purposes, let’s assume we are supposed to set CPOL to 1.
  • Bit 2 is CPHA — clock phase. This one goes hand-in-hand with CPOL, and is another one that you will have to determine by looking at the slave’s datasheet. It has to do with when data is sampled. We will assume CPHA is supposed to be 0.
    • Quick note: CPOL and CPHA are sometimes treated together as a 2-bit value called the SPI mode. In our case, with CPOL 1 and CPHA 0, we are using SPI mode 2 (binary 10). Some SPI slave datasheets will specify a mode number rather than CPOL or CPHA, or might only show a signal diagram in which you will have to figure out for yourself what CPOL and CPHA are. See the datasheet for more info on this, but it’s not really important for understanding how to use the SPI peripheral.
  • Bits 1 and 0 (SPR1 and SPR0) together determine the SPI clock rate divider. They will allow you to divide the CPU clock by 4, 16, 64, or 128 to determine an SPI clock rate (how fast the CLK pin will toggle from low to high and low again while you are sending data to the slave). The datasheet also mentions that if you set the SPI2X bit of the SPI status register, you can divide the clock by 2, 8, 32, or 64 instead. For our purposes, let’s assume the CPU clock rate is 8 MHz and our SPI peripheral’s maximum clock rate is 500 KHz. Thus, we can set the divider to 16 (so the divider bits will be 01 and SPI2X will be 0), which will give us an exact SPI clock rate of 500 KHz (0.5 MHz).

I’ll also go through the SPI status register (SPSR) really quickly since I have already mentioned it. Usually, status registers are read-only, and they exist to tell you the status of the peripheral. In this case, the SPI2X bit is a special exception.

  • Bit 7 (SPIF) is the SPI interrupt flag, which is just a flag that gets set to 1 whenever a transfer has completed. Even though we’re not using interrupts in this simple example, we will still look at this bit to determine when an SPI transfer is complete.
  • Bit 6 (WCOL) is the write collision flag, which lets you know if you wrote to the data register while a transfer was still in progress (you’re not supposed to do that). I consider this a fairly useless bit because you should ensure your code doesn’t try to write to the data register while a transfer is already in progress.
  • Bit 0 is the SPI2X bit that I mentioned earlier — it changes the clock rate as I mentioned.

There is one more register: the SPI data register (SPDR). This is the register you write to in order to begin an SPI transmission. If you want to send 0x52 over SPI, you would write 0x52 to this register, and then wait for the transmission to complete. Then, you can read from this same SPI data register to see the eight bits that the slave sent back to you while you were sending the 0x52 to it.

That’s it! That’s all there is to the SPI peripheral in the AVR. You’ll notice that it doesn’t provide any options for 16- or 32-bit transmissions, but you can do it yourself by sending 2 or 4 successive 8-bit transmissions. Also, there’s one other thing I should point out. The datasheet says that the SPI interface does not automatically control the SS (chip select) line. So you need to handle it yourself before starting a transmission and after a transmission is complete. Let’s assume that the chip select line should be high when idle, and low when you’re talking to the chip. OK, so let’s write some code!

We have already initialized the port direction registers, so now let’s turn on the SPI peripheral:

SPCR = (1 << SPE) | (1 << DORD) | (1 << MSTR) | (1 << CPOL) | (1 << SPR0);

I went ahead and left out the bits I set to zero, but you could insert them as (0 << BITNAME) if you want it to be completely clear.

We should probably also ensure that the SPI2X bit in the status register is off:

SPSR &= ~(1 << SPI2X);

OK, so now the SPI peripheral is pretty much ready for action! Let’s do one last part of preparation and ensure that the chip select pin is high, which it should be while idle:

PORTB |= (1 << 2);

We don’t have to worry about any of the other pins, because the AVR’s SPI peripheral has taken control of them at this point.

Now, let’s send the 0x52 byte to the slave:

// Pull chip select low to assert it (activating the slave)
PORTB &= ~(1 << 2);

// Send 0x52 to the slave
SPDR = 0x52;

At this point, we have started to send 0x52 to the slave. But the instruction will complete before the peripheral has finished sending the data to the slave. So now, before we do anything else (such as trying to send another byte or reading what the slave sent to us), we need to wait for the transmission to complete.

If we had enabled interrupts and created an interrupt routine, we could go on to doing other stuff and an interrupt would occur as soon as the transmission finished. But since this example is not interrupt-driven, we will now poll the status register until we know that the transmission has completed:

while ((SPSR & (1 << SPIF)) == 0);

This code waits until the SPIF bit of the status register becomes 1. This means that the transmission has completed, so we can now read the 8 bits that the chip sent to us:

uint8_t result = SPDR;

This act of waiting until the SPIF bit becomes set and then reading the SPDR register will clear the SPIF bit (the datasheet for the AVR says so). So next time we begin a transfer, we can do the same thing — wait until the SPIF bit goes high again, and then read the SPDR register.

The last thing we should do, now that we’re done, is pull chip select high to complete the transfer. Some slaves might prefer for chip select to stay low until several bytes have been sent and received, but we will assume that this chip only wants chip select to go low for a single byte and then return high.

PORTB |= (1 << 2);

There you go. You now know how to use the SPI peripheral in an AVR microcontroller. You’ll find that most of the 8-bit AVRs have an SPI controller very similar to this one. You’ll also find that this is basically how the SPI peripheral works in all microcontrollers. The toughest part is getting all of the setup values correct, particularly the CPHA and CPOL values. Once you have that in place, the rest of it is really, really simple.

I didn’t cover handling SPI with interrupts, but it’s not much more difficult than this — in the SPI interrupt handler, you can read back the data and either begin another transfer or pull chip select high to finish the transfer. If you have a big list of bytes that need to be sent as quickly as possible, interrupt-driven SPI would be ideal to take care of that.

That’s all I have for SPI. Tune in next time for a discussion of some other yet-to-be-determined microcontroller peripheral!

I recently had the opportunity to get a Freescale KwikStik Kinetis K40 Cortex-M4 development board (thanks, Newark/Farnell!). I’ve been using the Cortex-M3, so I had been very excited to test out the Cortex-M4. Plus, I have also been anxious to evaluate Freescale’s ARM offerings, so this was the perfect board for that. Sadly, the Cortex-M4 included in the K40X256VLQ100 chip used on the KwikStik does not have the optional floating-point unit, so I wasn’t able to do any performance tests as far as that is concerned.

Anyway, I thought I’d share my experience with the board, so here goes nothing!

It came packaged in a nifty box that opens up to reveal two sides — one with some documentation and a getting started DVD, the other with the Kinetis in its awesome cover and a USB A-to-micro-B cable:

  

Here is the KwikStik, powered up in all its orange glory:

And here it is outside of its case:

 

The DVD contains various PDF datasheets for the Kinetis microcontrollers, evaluation and code-limited versions of several compilers, and Freescale’s MQX RTOS.

Freescale put a ton of interesting things on the KwikStik to play around with:

  • LCD display
  • 3.5 mm audio output jack
  • Microphone
  • Buzzer
  • Onboard USB J-Link programmer for flashing the chip (and to use the board as a programmer for other boards)
  • USB OTG/host/device port for applications
  • Infrared transmitter/receiver
  • microSD card slot (doesn’t totally work in the revision I received — see below)
  • Six capacitive touch buttons
  • Rechargeable MgLi (manganese lithium) coin cell battery

So without further adieu, let’s get started with the fun stuff!

When you power the board up with the default firmware by plugging into either of the two USB ports, a menu comes up with three options, navigable with the capacitive touch buttons. The options are: sound recorder, remote control, and USB joystick.

The sound recorder will record two seconds of audio with the built-in microphone and play the recorded sound back through the 3.5 mm jack. The remote control feature is meant for controlling a Sony TV, and the USB joystick will let you use some of the capacitive touch buttons as a simple HID joystick on a computer.

Unfortunately, I couldn’t get the HID joystick demo to work — it was recognized on the computer as a gamepad, but the buttons wouldn’t register any presses in the Windows 7 game controller settings dialog. I also couldn’t test the Sony TV controller since I have a Vizio TV. The sound recorder works fine though!

The default firmware doesn’t really matter much, though — the fun part is making your own programs to do stuff! To start out, I downloaded CodeWarrior Development Studio for Microcontrollers (Special Edition with 128K code size limit). I had to download it since it didn’t come on the DVD. Installing it was a bit of a pain because I later found out that putting it in the default C:\Program Files (x86) directory will cause problems later on when trying to update it, so I had to uninstall it and put it in a standard unprotected location where administrator access isn’t needed to modify files. Despite that annoyance, I like it because it’s based on Eclipse and I’m used to Eclipse. I also tried IAR, but I didn’t like the user interface (and couldn’t get it to work with the demo firmware anyway). I also downloaded the Segger J-Link software — Segger’s site seemed to imply that my DVD should have come with it, but I couldn’t find it as an option to install in the Flash interface. Luckily, Segger still lets me download it as long as I agree not to use it with illegal cloned boards. So I got that all ironed out!

Despite not caring too much about the default firmware, the first thing I did was download the factory image off the device, just in case. After installing the Segger software, I used JLink.exe to read the flash contents after using JMem.exe to determine where the flashed image ended (where a bunch of endless 0xFFs began). It turns out the firmware binary is 0xD004 bytes long, so I used these commands in JLink.exe:

h
savebin C:\Path\To\DefaultFirmware.bin, 0x0, 0xD004

The “h” command halts the CPU, and the “savebin” command will save 0xD004 bytes of data starting at address 0 to DefaultFirmware.bin, so I can always restore the board back to the exact way I got it. Yeah, I’m paranoid like that. It’s always the first thing I do when I get a microcontroller evaluation board. The way I see it, I’m going to need to know how to use the flashing/debugging tools anyway, so it’s not a waste of time to do that first!

Next, I decided to try to compile Freescale’s example firmware to see if maybe they had worked out some of the kinks in the HID joystick demo. This required updating CodeWarrior to the latest version and installing the latest version of Freescale’s MQX RTOS, which the demo uses. Finally, after trying to compile the example firmware, I ran into some errors because there were a couple of hardcoded “C:\Program Files” paths which I had to change. After all that mumbo jumbo, I was finally able to compile their example firmware which is available for download on the KwikStik page on their website.

Programming the device from inside CodeWarrior worked fine, and once that was done, I ran the demo — they actually had replaced the HID demo with a USB mouse demo, which does work (it lets me left click and right click). They had also fixed a bug that caused the remote control app’s exit button to not work, and they added a Tetris clone game demo.

OK, so at this point I finally had an environment ready for doing some real development! I didn’t really feel like learning how to use Freescale’s RTOS yet, so I just made a simple bare metal demo app to turn on all the LCD’s segments in succession, then turn them off in succession, endlessly.

CodeWarrior comes with some pretty interesting features — the microcontroller appears as a picture in CodeWarrior, and the picture contains a bunch of blocks for all the peripherals built in, including the CPU itself. You can click on them to set up options (such as clocking for the CPU) and it will generate initialization code for you. It made it pretty easy to make a quick app. I borrowed some of the code from the KwikStik demo application for the LCD to understand the options Freescale used for setting it up, and it pretty much worked right out of the box. It turned out that the LCD was visibly flickering in my app, and it was because I had to change the IRCLK source to be the fast internal reference clock (2 MHz) instead of the default slow internal reference clock (32.768 KHz) — it looks like the SLCD’s initialization was using the IRCLK and the default setting was not fast enough, so I saw flickering. With that out of the way, my program worked like a charm!

After all the initialization is complete, here’s the simple main loop code:

int x;
int y;
volatile int c;

for (;;)
{
    for (x = 1; x < 40; x++)
    {
        for (y = 0; y < 8; y++)
        {
            // Turn on the segments one at a time...
            LCD_WF8B(x) |= (1 << y);

            // Wait a bit?
            c = 0x20000;
            while (c--);
        }
    }

    for (x = 1; x < 40; x++)
    {
        for (y = 0; y < 8; y++)
        {
            // Turn off the segments one at a time...
            LCD_WF8B(x) &= ~(1 << y);

            // Wait a bit?
            c = 0x20000;
            while (c--);
        }
    }
}

I like the SLCD peripheral! It makes it easy to turn segments on or off by changing a single bit, and then you’re done. The SLCD peripheral uses up to 8 pins as backplane pins, and the other 40 pins can be used to control 40 segments per backplane. It is very quickly switching between the eight backplanes and turning the segments on and off as necessary. This all happens so fast that you have no idea that the LCD segments are being turned on and off (well, unless you accidentally set the clock rate too low like I did!). With 8 backplane pins and 40 segment pins, you can control up to 320 LCD segments with this peripheral. It would be a big pain in the rear end to implement the LCD refreshing I just described manually, and the peripheral makes it so easy — just set the bit for the segment you want to turn on, and you’re done!

The next thing I should do is get rid of the ugly busy waiting that I have for delays right now, and switch over to using a timer, which would be pretty easy to do.

So yeah, once you get down to making your own stuff, it’s a cool little board with tons of possibilities for interesting applications!

Now, remember how I said the SD card slot doesn’t totally work? Well, it turns out that in board revisions earlier than revision 5 (I received revision 4), Freescale accidentally connected the SD card socket’s data pins to the wrong pins on the microcontroller! It essentially makes the microSD card slot useless because you can’t use the Kinetis’s built-in SDHC controller peripheral for accessing the SD card. You could bit-bang it yourself, but that will have a (very negative) performance impact. Maybe I can hack the board with some cut traces and wires to connect the SD card socket’s pins to the correct microcontroller pins — who knows? Maybe I’ll do THAT as a fun project soon! If I do, I’ll be sure to post about it here!

So, in conclusion, I’m happy with the board, although it seems like Freescale made a really boneheaded mistake (the SD card wiring problem is inexcusable, especially given that it was still present in revision 4 of the board!). Regardless of that, though, I’d still definitely recommend it as a platform for learning about microcontrollers, simply because of all the awesome stuff it has built-in aside from the microSD slot. And seriously, a 100 MHz processor in a microcontroller? I know the Cortex-M3s were up there in clock speed too, but still–what’s the world coming to? With all of that processing power combined with the wide range of peripherals, it provides plenty of awesome opportunities to learn about microcontroller programming. The included orange protective jacket is a nice touch, too!

You can purchase the Kinetis KwikStik from Newark.

Until next time, see ya later!

I haven’t written about my Mac ROM hacking lately, so this post will double as an update to my ROM hacking endeavors and a review of Seeed Studio‘s awesome Fusion PCB service.

After going through all the hoopla to desolder the DIP chips on my Mac IIci and socket them, I finally got frustrated. The main annoyance is that the DIP ROMs are all the way underneath the hard drive and floppy drive carrier. It was forcing me to basically rip everything out of the IIci in order to access the DIP sockets. I also had been in contact with the folks on the 68k Mac Liberation Army forums, and they had a lot of useful information, including the tidbit that many of the Mac II series machines (and the SE/30) have a SIMM socket that you can put a ROM SIMM into. My IIci also has this socket, and it’s easily accessible without removing anything from the case. So, I decided to make my own! Thanks to a lot of advice from fellow forum members, I was able to lay out a SIMM printed circuit board to have manufactured.

I ran into a problem: the SIMM needs to be about 0.047″ thick in order to physically fit in the socket. Most of the inexpensive circuit board prototyping manufacturers make boards that are 0.063″ thick. Luckily, bigmessowires from the 68k Mac Liberation Forums was able to recommend a PCB manufacturer that could make the boards in the thickness I needed: Seeed Studio Fusion PCB. He had used them in the past with good results, so I went for it.

Seeed Studio has amazing pricing. My board was about 3.85″ by 1.1″. That fits within a 10 cm by 5 cm rectangle. As of this writing, they can manufacture ten 2-layer boards of that size for a total of $24.90 plus shipping. That includes solder mask and silkscreen on both sides. It’s an incredible price! They also offer many thickness options, including 1.2 mm, which works out to 0.047″. I asked for red solder mask instead of the standard green, which added an additional $10 to the price. They have extremely good trace width/spacing requirements: 6 mil (0.006″) trace width and 6 mil spacing. I went ahead and made my minimum trace width and spacing 8 mils, just to be safe.

After you place your order online, you e-mail them a zip file containing the Gerber files for your PCB. If there are any problems, they will let you know — otherwise, you just have to wait for the boards to be manufactured and shipped.

Shipping was only $3.52 for registered air mail to the United States from Hong Kong. They had other options, too, but this was the least expensive one. They take PayPal as a payment option, and I can’t remember the other options they offered. I placed my order on the night of Monday, September 5, they shipped my board on Tuesday, September 13, and the package arrived on Friday, September 23.

I’m sure you’re wondering: how did the boards turn out? Well, they turned out just fine! As you can see, they were able to manufacture a board with an irregular shape:

You may see some numbers on the silkscreen. Seeed Studio’s directions tell you to add your order number to the silkscreen somewhere, so I did that on the bottom. They also added a few other numbers onto the top silkscreen. Not a big deal at all, especially for the price!

Electrically, the SIMM tested fine. All the traces were perfect. Seeed Studio will electrically test 5 of your boards for free, and you can pay to have the other 5 tested, too.

Oh, did I mention that they actually sent me 12 boards instead of 10? How cool is that?

I would highly recommend them if you are looking for budget PCB fabrication. They only do 1 or 2 layer boards, so you can’t do anything overly fancy with 4 or more layers, but 2 layers is plenty for all kinds of fun stuff you can make, such as this SIMM.

By the way, my SIMM ended up working perfectly, and it expanded my IIci’s ROM capacity to 2 MB (the original ROM is only 512 KB). I naturally tested the rest of the capacity by filling the remaining 1.5 MB with the Super Mario Bros music and turning it into the longest Mac startup chime ever:

If you’re curious what the assembled board looks like, I show it off briefly in the video.

So anyway, all in all, I had a very positive experience with Seeed Studio’s Fusion PCB service! I was shocked when I saw the pricing, and I am very happy with the boards I got back. Thanks, Seeed Studio!

 

Introduction

OpenOCD is an extremely useful (and free!) piece of software for microcontroller programming. In particular, I use it to program to and debug with various development boards I have laying around. I have a Luminary Micro/TI Stellaris LM3S2965 evaluation kit that has a built-in USB port which can be used for JTAG. The board also has a JTAG connector on it, so you can use it as a passthrough for JTAG on another board. The JTAG is powered by an FTDI FT2232D USB to serial chip. Just calling it a USB to serial chip is not giving it quite enough credit, though — it can be used for all kinds of crazy things, including JTAG. I would venture a guess that most USB to JTAG adapters you can buy are really just a simple board with this chip on it connected to a JTAG connector on one end, and USB on the other.

Anyway, OpenOCD is a bit interesting. It can interface to FT2232-based JTAG devices with two options for communication. The first option is libftdi, an open-source library that uses libusb to talk to the FTDI chip. The second option is ftd2xx, which is a proprietary library provided by FTDI itself (which also appears to be based on libusb?).

So naturally the question is: which one should you use?

Well, I think it depends on your specific needs. I first got OpenOCD working a couple of years ago in Ubuntu Linux. At the time, it didn’t really matter to me which library to use, so I tried them both. My experience was that FTDI’s own driver was much faster than libftdi. The situation may have changed since then, but I haven’t had a reason to change my setup.

When I got OpenOCD working on Windows 7 64-bit, it got even more interesting. At the time, libusb was not a signed driver, so it was a huge pain in the butt to get it to work with Windows 7. Apparently you could get it to work by starting up Windows with a special option in the same startup menu you’d use to boot into safe mode. But you’d have to do that EVERY time you booted, or the driver wouldn’t work. That’s my understanding of the situation, anyway. The other option was just to use FTDI’s driver and forget about it all. So I did.

Things have changed since then, though. libusb is now available as a signed driver that won’t make you jump through hoops on Windows. I haven’t tested libftdi lately to see how it compares performance-wise to ftd2xx. Anyway, I’ve stuck with ftd2xx just because it’s what I started with, so this post will be about the ftd2xx library. It’s very possible that my instructions will still work with libftdi though!

Anyway, here’s the other thing about the ftd2xx library. It’s a proprietary library incompatible with the license used by OpenOCD (GPL). So you won’t be able to find a (legally good) distribution of OpenOCD that has the ftd2xx library capability built-in. It’s perfectly OK to distribute OpenOCD that’s linked against libftdi since it’s compatible with the “viral” GPL. But since back in the day I needed OpenOCD with ftd2xx, I had to compile it myself.

I recently had to compile OpenOCD for 64-bit Windows again. That’s where this blog post comes in.

Compiling OpenOCD for Windows

There are a few options you can use to compile stuff designed for GNU tools in Windows. One example would be MSYS, and another would be Cygwin. These are both EXCELLENT environments, but I don’t like having to install a bunch of their stuff on my computer just for the sole purpose of having all the crazy tools necessary to be able to compile OpenOCD. I’d rather keep my Windows partition nice and clean to the point where I just have the OpenOCD executable and any supporting libraries, and that’s it. But how do you get past needing all the stuff necessary to run configure scripts, process Makefiles, and yadda yadda yadda?

You cross-compile it for Windows using Linux and MinGW! That’s how!

Here are the basic instructions I found on Dangerous Prototypes for cross-compiling OpenOCD for Windows from Linux. I tried to follow them step-by-step, but I ran into a few snags, so I decided to make my own post that will go step-by-step through compiling OpenOCD for 64-bit Windows (Vista and 7, and probably 64-bit XP too?). I see no reason why this shouldn’t work on a 32-bit platform as well–just substitute any 64-bit compilers/tools I specify with the corresponding 32-bit versions instead!

I had trouble getting 64-bit MinGW to work correctly in Ubuntu, so this post by Matpen on the Ubuntu forums also helped me immensely. I’m guessing if you’re doing a 32-bit compile, you don’t need to worry about the problems I had with the 64-bit MinGW included with Ubuntu. The version included with Ubuntu 10.04 had a really deep problem in that it doesn’t include libgcc_s.a, and the version included with Ubuntu 11.04 has problems such as not providing a getopt.h include file.

Finally, I had more trouble getting OpenOCD to link against the ftd2xx library after I solved the first problem, and this post by el_nihilo on the SparkFun forums also helped me out.

I’m hoping that by combining the instructions from these three sources, I can create a single source that anyone can go to in order to get OpenOCD to compile on the FIRST TRY. Here goes nothing!

Prerequisites (for Ubuntu 12.04)

Since I first wrote this article, Ubuntu 12.04 came out, and this process is MUCH simpler to get working with it. The supplied toolchains work fine now. All you need to do is:

sudo apt-get install mingw-w64

No need to install weird packages or regenerate FTDI’s .lib file. Great!

Prerequisites (for Ubuntu < 12.04)

You’re going to need an install of Ubuntu (32-bit or 64-bit — your choice). I have successfully tested this procedure on the 64-bit version of Ubuntu 10.04,  the 32-bit version of Ubuntu 10.10, and the 64-bit version of Ubuntu 11.04. Use whatever you’d like. You can do it on a separate partition, in a VMware Player virtual machine, or whatever else it takes to get Ubuntu.

To start, we’re going to install some packages that Ubuntu will need:

sudo apt-get install libcloog-ppl0 libgmpxx4ldbl libmpfr1ldbl libppl-c2 libppl7

Now, rather than use Ubuntu’s provided 64-bit MinGW package, which does not work (as of this writing), we will instead use a version which does. So get the two packages that apply to you and install them:

If you’re on a 32-bit version of Ubuntu:

wget http://ppa.launchpad.net/mingw-packages/ppa/ubuntu/pool/main/w/w64-toolchain/i686-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_i386.deb
wget http://ppa.launchpad.net/mingw-packages/ppa/ubuntu/pool/main/w/w64-toolchain/x86-64-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_i386.deb

dpkg -i i686-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_i386.deb
dpkg -i x86-64-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_i386.deb

If you’re on a 64-bit version of Ubuntu:

wget http://ppa.launchpad.net/mingw-packages/ppa/ubuntu/pool/main/w/w64-toolchain/i686-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_amd64.deb
wget http://ppa.launchpad.net/mingw-packages/ppa/ubuntu/pool/main/w/w64-toolchain/x86-64-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_amd64.deb

dpkg -i i686-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_amd64.deb
dpkg -i x86-64-w64-mingw32-toolchain_1.0b+201011211643-0w2273g93970b22426p16~karmic1_amd64.deb

These commands will install special versions of MinGW that aren’t broken for producing 64-bit code. I’m not 100% sure if you actually need to do the i686 toolchain as well, but I’ve included them because the original steps from the Ubuntu forums also included them. The packages may say Karmic in the filenames, but I was also able to install them successfully in 10.04, 10.10, and 11.04.

Downloading OpenOCD and FTDI’s library

So now let’s grab OpenOCD and the FTDI library:

wget http://download.berlios.de/openocd/openocd-0.5.0.tar.bz2
wget http://www.ftdichip.com/Drivers/CDM/CDM20814_WHQL_Certified.zip

First, if you’re using the MinGW toolchain from before Ubuntu 12.04, you need to regenerate the FTDI library’s .lib file, because it and that MinGW version just don’t get along. If you have Ubuntu 12.04 and its built-in MinGW toolchain, skip down to “The actual compilation of OpenOCD.” If you have an Ubuntu version before 12.04 and don’t do this step, the final link of openocd.exe will fail with several errors similar to: undefined reference to `__imp__FT_Write’. Extract CDM20814_WHQL_Certified.zip and do the following commands:

cd CDM20814_WHQL_Certified/amd64
echo "LIBRARY ftd2xx64.dll" > ftd2xx64.def
echo "EXPORTS" >> ftd2xx64.def
strings ftd2xx64.dll | grep FT_ >> ftd2xx64.def
mv ftd2xx.lib ftd2xx.lib.old
x86_64-w64-mingw32-dlltool -d ftd2xx64.def -l ftd2xx.lib

If you go to the post by el_nihilo on the SparkFun forums which I mentioned earlier, you’ll see what’s going on. It has to do with the difference between how DLL function names are expected to be prefixed in Visual C++ and MinGW. It’s pretty goofy that there have to be all these stupid incompatibilities, but this clever little trick fixes it by regenerating the .lib file so it’s compatible with MinGW. This step was borrowed directly from that post.

Once all this preparation is done, it’s now safe to try to install OpenOCD!

The actual compilation of OpenOCD

Now, compiling OpenOCD is relatively straightforward!

Go into the OpenOCD directory, and do this command:

./configure --host=x86_64-w64-mingw32 --disable-werror --with-ftd2xx-win32-zipdir=/path/to/CDM20814_WHQL_Certified --with-ftd2xx-lib=static --enable-ft2232_ftd2xx --prefix=$PWD/_install

Let’s step through the options we gave to the configure script so we make sure we understand what it’s doing.

  • --host=x86_64-w64-mingw32

    specifies that we are compiling for a different host that we’re running on now. This is how we tell it to use the MinGW cross compiler.

  • --disable-werror

    makes it so a compiler warning is not treated as an error. We will get some compiler warnings which would cause the build to fail if we didn’t provide this option. The warnings seem to be harmless; it works just fine!

  • --with-ftd2xx-win32-zipdir=/path/to/CDM20814_WHQL_Certified

    is just the path to the folder containing the contents of the extracted zip file with the ftd2xx driver and libraries. It’s telling the configure script where to find the header file and library to compile/link against.

  • --with-ftd2xx-lib=static

    supposedly tells it to link OpenOCD against the static library instead of the dynamic library. Despite that fact, I still have to include ftd2xx64.dll with the final generated binary. Not sure why, but it works!

  • --enable-ft2232_ftd2xx

    tells the configure script that we’re going to want FT2232 support provided by the ftd2xx proprietary library.

  • --prefix=$PWD/_install

    just tells it to install in a directory called _install in the current directory instead of the default location of /usr/local. Since we’re just going to be transporting it over to the Windows computer when done, it makes no sense to install it in /usr/local.

So, do it!

Then, when it’s done and succeeds (hopefully), compile it:

make

and install it:

make install

Now, your OpenOCD directory should have a directory called _install inside of it, containing several directories including (almost) everything you need to get OpenOCD running on Windows! The only thing it’s missing is ftd2xx64.dll. Grab it from the CDM20814_WHQL_Certified/amd64 directory and stick it in the bin directory alongside openocd.exe. At this point, you should be able to transfer this directory over to your Windows partition/machine/whatever and run OpenOCD just like any other random Windows console app.

Hope this helps someone else who, like me, was struggling to get it to work!

In my last post, I wrote about how I had figured out how the Macintosh IIci’s synthesized startup sound works. I talked about how I replaced the ROM chips on the motherboard with sockets and disassembled the ROM code. I shared a video showing how I customized it to play the first few notes from the Super Mario Bros song. At the very end of it, I talked about how it would be awesome to figure out how to play a sampled sound at boot time, which would allow me to play any sound I wanted, limited by space available in the ROM. I didn’t feel very optimistic about getting that done, but after a ton of reading, experimentation, and frustration, I have figured it out, and my IIci now plays a sampled startup sound when it boots up. I’d like to share how I did it, as well as provide instructions on how to patch your own IIci’s startup sound with the sound of your choosing.

Before I start, I’d like to thank the people in the 68k Mac Liberation Army forums for the help and encouragement, and also the people who coded the MESS emulator for leaving a very handy register reference for the Apple Sound Chip in their source code. Without any of the aforementioned people, I would never have been able to get this far in my hacking!

Here’s are some videos, followed by how I did it and how you can do it. I decided to inject one of the sampled startup sounds from the LC/Performa series into my IIci:

And here is the sampled startup sound from the 5200/5300/6200/6300 series Macs:

How I did it

To begin, I disassembled an LC III ROM dump. The LC III is one of the oldest Macs that has a sampled startup chime. Its sound chip is not quite the same as the IIci’s, but the way it plays its sampled sounds at boot time gave me a few clues. To write sampled sounds to the Apple Sound Chip, you basically just keep writing samples, one at a time, as long as there is room in the chip. You determine whether there’s room in the chip or not by reading a status register.

So based on how the LC III did it, I wrote a program to test playing a sound by talking directly to the sound chip on my IIci. It failed miserably for two reasons:

  1. The bits of the FIFO status register in the sound chip act slightly differently on the LC III compared to the IIci
  2. When I’m booted into the Mac operating system, there are interrupts looking at the status of the sound chip. An interrupt can grab the FIFO status before I get a chance to see it, and then I’m stuck waiting in an infinite loop for a bit to change, even though it already changed long ago.

No biggie though! First of all, I decided to forget about the FIFO status register completely, and instead I made my program write samples blindly to the chip, adding a pause occasionally to give the chip some time to play the samples and clear space in its FIFO. I messed around with my delays, and I eventually was able to get it to mostly work. By mostly, I mean sometimes it would make some crackly sounds while playing the sound I wanted it to play. I figured this was because interrupts sometimes made my delays longer than they should have been, causing the FIFO to empty out for a short time. My main goal was accomplished though: I knew how to tell the chip to play sounds.

The delay code was lame, though. It makes more sense to listen to what the chip is telling me, rather than guess the status of the chip based on time delays. To solve problem #2, I disabled interrupts during my program. This helped immensely because it prevented the operating system from talking to the sound chip behind my back. Next, I started playing with the status bits to see when they come on and turn off. It was here that I discovered problem #1: The IIci’s sound chip doesn’t behave the same way the LC III’s code implies its sound chip behaves.

The LC III’s code always waits for one of the FIFO status bits to be “1” before it writes a sample to the chip–even the very first sample. The MESS source code says this bit is a “FIFO half empty” status bit. On the LC III, it looks like this bit is 1 any time the FIFO is anywhere between completely empty and half empty. If it’s more than half full, the bit is zero. On the IIci, though, this bit stays at zero, and only becomes 1 once you have filled the FIFO more than half full and it has dropped back down to being only half full by playing enough samples. Plus, once you read the bit, it goes back to 0 until the FIFO has filled more than half full again (and dropped back down to half full after that, which sets the bit at 1 again). This explained why my first attempt failed — an interrupt probably read the status bit’s 1 value (bringing it back to 0 in the process) and I was stuck waiting to see it and never did.

Once it’s finished writing all the samples to the chip, the LC III’s code waits for another status bit to be 1 before continuing on. I’m guessing that this other bit acts as a “FIFO is completely empty” bit, so it’s allowing the code to wait until the FIFO has totally drained out. I don’t know for sure, but that would make the most sense based on what the code is doing. On the IIci, though, according to my tests, this bit is zero until the FIFO is completely full. Then it becomes 1 until you read it, and it resets back to zero immediately.

Based on this information, I decided on an algorithm to use with the IIci to play sampled sounds driven totally by the two status bits:

  • Check the “FIFO is full” bit.
  • If the FIFO is not full (the bit was 0), write the next sample to the chip and start over again at the top.
  • If the “FIFO full” bit was 1, then wait until the “FIFO is half empty” bit comes on, then write the next sample to the chip and start over again at the top.

So the algorithm starts with the FIFO completely empty, fills it completely up, then waits for it to become half empty again, fills it completely up, waits until it’s half empty, fills it up, and so on, until it’s done.

I couldn’t find a way to determine that the FIFO was completely empty, though–so I may be cutting off the end of the sound. I’m not sure about that yet. I don’t notice it, but it’s possible that the sound I’m playing has some silence at the end of it anyway.

So after getting it working in a simple Mac program, I injected the code into the free space in the IIci’s ROM and patched the ROM to jump to my routine instead of the normal startup chime. After a monumental screwup where I accidentally commented out a single line that caused the whole thing to fail and had me puzzled for hours, I got it to work on my second try!

A couple of days later I tried another sound. The 5200/5300/6200/6300 startup chime is actually sampled at 11.127 KHz, which is half the Apple Sound Chip’s standard sample rate. So to play it, I changed my code slightly to write each sample into the sound chip twice, doubling the effective sample rate to 22.254 KHz. This also lets me use a sound twice as long!

So that’s my background info on how I did it. Now…I’m sure you’re chomping at the bit to do it yourself, right?

How you can do it

You need:

  • A working Mac IIci
  • Some soldering and desoldering skills
  • Four 32-pin 0.1″ pitch DIP sockets
  • Four pin-compatible EEPROMs (I used the Greenliant GLS29EE010)
  • An image of your Mac IIci’s ROM — read it from the chips after removing them or read it from the Mac before you tear it apart. (Do NOT ask me for ROM images – I’m not interested in infringing on Apple’s copyright)
  • An EEPROM burner compatible with the EEPROMs you choose and a computer that it can talk with — most likely it will be a Windows-based computer with a parallel port.
  • The ROM patches I will provide below
  • A hex editing utility to stick the patches where they belong (I used HxD)
  • A tool to recalculate the ROM’s checksum after your modification. Ben Boldt’s Mac ROM Checksum verifier will help you figure out what the checksum should be (nice work Ben!) — note: if you run this program on Windows, change the code so that it opens the files in binary mode. Otherwise it won’t work because it will do weird stuff with bytes that happen to be carriage returns and line feeds.
  • A tool to split the ROM file into four interleaved segments for burning. I made one for .NET that also does the checksumming but I don’t have time to upload it yet…if you don’t want to wait, make a suitable tool yourself! 🙂 See my previous post for info on how the ROM chips are interleaved.

All right! As far as hardware goes, desolder the old ROMs and remember where each one goes. Solder sockets in their place and put the original ROMs into the sockets to make sure that it still boots OK. Each EEPROM will have at least one extra pin that was not connected on the IIci’s original ROM. It will need to be connected to something and not left floating. See the datasheet of your chip to determine what it should be connected to for “read mode”. In the case of the GLS29EE010, it is a pin right next to VCC that is used for programming (the pin is called WE#), and in read mode it is supposed to be pulled high. How convenient! On the bottom of the motherboard, you can blob solder between these two pins to connect them and it should work well–at least for the GLS29EE010!

Now, read the ROM files onto your computer (or use the image you read from the Mac before tearing it apart and split it into 4 interleaved files). Burn the four ROM segments onto your EEPROMs, stick them in place of the original ROMs, and make sure the IIci still works. This will verify that your EEPROM burner and the hardware modifications are working correctly.

From this point on, it’s all software. First of all, here is the source code I used to generate this binary blob of sound-playing goodness (if you want to compile my code to make changes, you will need a 68k version of GNU binutils):

Sampled startup chime source code for Mac IIci

Here is the final assembled 140-byte binary generated from the source code:

Sampled startup chime binary ready for injection into Mac IIci ROM

You will need to append your own sound to the end of this binary blob. It should be in raw 8-bit unsigned format with a 22254 Hz sample rate. Audacity should be able to produce a file in that format for you [File–>Export–>Other uncompressed files–>Options–>RAW (header-less)–>Unsigned 8-bit PCM], and it should also be able to take a sound sampled at a different rate and convert it to 22254 Hz [Tracks–>Resample]. After the end of my binary blob, append the length of the sound (in number of samples) as a four-byte big-endian integer. Then append the raw 8-bit unsigned file you generated containing your sound. I decided to skip Apple’s sound resource format or AIFF or WAV or anything like that because it would do nothing except complicate the sound playing code.

Stick your combined blob into your ROM image (overwriting the old bytes so the file does not grow in size) starting at an offset of 0x51D70 (you should see an Apple copyright notice repeated over and over again along with other stuff). It can’t be longer than about 35 kilobytes, though, or it will start overwriting other stuff in the ROM. Make sure that some of Apple’s copyright notice is still visible and you’ll be fine! 🙂 If you don’t yet have a single ROM image because you read the ROM from the original chips, you need to combine them into a single file first — remember, they are interleaved!

Next, we need to patch the ROM image to jump to our newly-injected code instead of the standard startup chime code. It’s a simple matter of changing the four bytes starting at the offset 0x435D2. In your ROM image they should be:

FF FC 3A 82

You need to change them to:

00 00 E7 A0

Also, if you plan on using this patched IIci ROM in an SE/30 (and I’m guessing also a IIx/IIcx, but I can’t confirm that), you also need to change the four bytes starting at the offset 0x4122C. They should already be:

FF FC 5E 28

Change them to:

00 01 0B 46

Finally, recalculate the checksum using Ben’s tool I linked to above, split the ROM image into four segments, burn the segments to EEPROM, stick them in your IIci, and power it on! If all goes well, you will hear your awesome new startup sound. Otherwise, you probably have some troubleshooting to do 🙂

You know what’s really cool about this hack? I ended up using a Mac, Windows, and Linux together to do the job. Just the way I like it!

Update: I got sampled startup chimes working since I first posted this hack. See my latest post.

There’s been a cool project I’ve been working on for the last month or so, and I finally got to a good point where I could share what I’ve done! In summary, I have given my old Macintosh IIci a custom startup chime. Get ready for a long-winded post if you dare to read it all…or skip to the bottom if you just want to see and hear my custom IIci start up.

I’ve seen the question asked online. How do you change that sound a Mac makes immediately after you press the power button? The answer is inevitably “you can’t.” The sound is stored in the Mac’s ROM, making it impossible to change in software. It’s hiding somewhere in read-only memory chips (usually) soldered onto your Mac’s motherboard, nestled alongside other code that sets up all the Mac’s hardware when you first turn it on.

A year ago, I was talking with a coworker and we thought it would be awesome to try to hack the hardware to change the sound. I decided at that time that the IIci would be a perfect candidate because first of all, I have two of them. Second, its ROM chips are DIP (dual-inline package) chips, which I feel safe soldering. I just don’t have enough surface-mount soldering experience to risk damaging a motherboard. The big problem was that I found out the IIci’s startup sound is not a sampled sound. That means it isn’t just a sound file embedded into the ROM that you can easily replace. Instead, the Mac creates the sound from scratch, given a few instructions about what notes to play and how fast they should play. I’ll talk more about that further down in this post.

Well, about a month ago, I started thinking about this idea again and decided to go for it. I started out by booting up my old IIcis and deciding which one to hack. One of them had a very faint startup chime, it wouldn’t boot up unless left unplugged for a while, and the hard drive wouldn’t spin up. I decided to hack this one because it was in the worst shape of the two. After checking out the 68k Mac Liberation Army forums, it became clear that the faint startup chime was probably because the electrolytic capacitors on the motherboard had spewed electrolyte all over. I inspected the motherboard and sure enough, many of the capacitors had gunk nearby. Here’s an example of what I’m talking about:

Gross, right? This one happens to be right next to the power button. Perhaps it was causing the power button to work intermittently. Several of the other capacitors looked very similar, and in some cases it appeared that some of the electrolyte had actually gotten onto nearby components. This stuff is nasty and can corrode the motherboard over time, so I knew I had to get it off.

You may notice that these capacitors are surface-mount, and I just got done explaining how I’m not very comfortable with surface-mount soldering. Well, this isn’t terribly complicated soldering. I get nervous when I’m doing components with tens of pins very close together. This stuff wasn’t so bad–there’s a connection on each side, so you really just have to be careful about lifting pads. I did kind of lift one, but it is still electrically connected and everything’s fine. Anyway, I removed all the capacitors (including the through-hole ones as well). I could definitely tell the capacitors were bad when they began smelling like fish as I removed them. After taking them all out, I cleaned the board with 99% isopropyl alcohol (great for cleaning circuit boards! It evaporates almost instantly). I especially went over the areas that looked like the one pictured above. I then put in brand new capacitors.

While I had the board out, I removed the four ROM chips:

Removing them was pretty interesting. I did a lot of research on the web to see what other people thought about removing DIP chips in old forum posts, tutorials, videos, etc. The attitude I found online was mostly: “you can save the board or the chip, but not both.” Most suggestions were to cut the old chips out and then easily remove the remnants of the pins with a soldering iron. I also found a few videos of people who had vacuum desoldering guns — in particular, the Hakko 808. The thing had great reviews, so I got one. It’ll be nice to have in my set of tools anyway. It requires a lot of maintenance to keep it working and prevent the pump from getting messed up, but it’s definitely worth it just for the convenience. I really wanted to get the original ROM chips out intact, too, so I’m happy with that. I ran into a bit of trouble with either the ground or VCC pin (can’t remember which) because it takes longer to heat, but other than that, it was pretty easy to use it to remove the chips. I added a bit of extra solder to help the old solder heat up, and the gun sucked most of it out painlessly after that. Sometimes the chips did not lift out easily, even though I couldn’t find any visible solder with my eye loupe. I could tell that the solder was essentially gone, though, so I yanked the chip out with a bit of force to break the miniscule connection the solder still had, and it didn’t damage anything. That may have been stupid on my part, but it worked out for me!

So I replaced the ROMs with sockets:

Then, I stuck the original ROMs back in the sockets, and booted the IIci up. Success! Not only did it boot, but the sound was no longer faint and the power button worked every time, so the capacitor replacement fixed that. However, I knew I’d be using some kind of EEPROM in place of the original ROMs. Notice that one of the original ROMs says it is a TC531001CP. I somehow managed to find a (really old) datasheet for it online and discovered it uses a standard pinout that most 32-pin DIP devices also use.

I found a couple of reprogrammable SST chips of the same capacity which seem to fit the pinout and electrical specs: the SST27SF010 and the SST29EE010. It looks like Greenliant broke off from some of SST’s flash stuff, so they are actually now the GLS27SF010 and the GLS29EE010. I started out with the GLS27SF010. It has a couple of extra pins for programming the chip that are not connected on the IIci’s original ROM, so I had to tie them to VCC on the bottom of the motherboard. The GLS27SF010 was really annoying to program with my Willem programmer, though, because I had to change a jumper on the programmer board any time I wanted to erase it, and remove it to program it. So I switched to the GLS29EE010, which is a lot easier to use, is rated for many more erase cycles, and only has one pin that has to be connected to VCC. I read the contents of the original ROMs, burned the contents to my EEPROMs, stuck them in the motherboard, and it booted!

This completed the hardware portion of my hack. At this point I knew I could reprogram my EEPROMs, stick them in the IIci, and get it to do cool stuff.

I figured out that the four ROM chips are each 8-bit ROMs and the computer itself addresses 32 bits at once. How this works is one of the ROMs is connected to data lines 0 through 7, one is connected to 8 through 15, another is connected to 16 through 23, and the final one is connected to data lines 24 through 31. This means that as far as what the computer sees, to turn the four ROM images into a single ROM image I could disassemble, I had to take one byte at a time from each chip:

Chip 1, Byte 0
Chip 2, Byte 0
Chip 3, Byte 0
Chip 4, Byte 0
Chip 1, Byte 1
Chip 2, Byte 1
Chip 3, Byte 1
Chip 4, Byte 1

I wrote a quick program to do this and was on my way.

In order to get any further, I had to turn to posts by Dennis Nedry on the 68k Mac Liberation Army forums. After following his posts around I was able to discover he had done a lot of the dirty work for ROM hacking. It turns out that Macs have a checksum in the first four bytes of their ROMs, and if it doesn’t match, the Mac won’t start. He had already figured all this out and written code to calculate and check the checksum of a ROM image. Without his work, there’s no way I would have gotten any further — I probably would have given up and just said “whatever — Apple’s protecting their ROM from being modified, I guess I’ll go mess around with something else.” Anyway, he had a ton of useful information here and here.

I started out with the basics and changed an icon. After some crazy searching in the ROM image, I was able to locate the floppy disk icon that appears if you boot a Mac without a startup disk present. There are actually three icons: a floppy disk, a floppy disk with a question mark on it, and a floppy disk with an X on it. When there’s no startup disk present, it alternates between the plain floppy disk and the floppy disk with a question mark. I changed the plain floppy disk icon to a black Apple logo, and the question mark floppy icon to a white Apple logo. Then I recalculated the checksum, split the ROM image into four files, burned them, stuck them into the IIci, and got this:

OK, that’s great! I had proven that I could do it. But then I wanted to move on to bigger and better things–my original goal. The custom startup chime.

At this point, I have to once again thank the people on the 68k Mac Liberation Army forums who gave me some great pointers on what to look for in my post. Trash80toHP_Mini was kind enough to scan a bunch of pages of an old out-of-print Apple hardware book for me as well. Let me tell you, there are some really cool people on those forums!

I started disassembling the ROM code and searching for places that referenced the Apple Sound Chip located at 0x50F14000 (and other repeated addresses as well). It took a while to get comfortable with 68k assembly, but it’s really not that bad. It’s actually kind of nice compared to x86 assembly in my opinion. This site was an invaluable reference. In the middle of this, I installed MPW (Apple’s old software development setup) and happened to discover that it included several Mac ROM maps! The IIci was one of those. I found some interesting labels in the ROM maps called BOOTBEEP, BOOTBEEP6, ERRORBEEP1, ERRORBEEP2, ERRORBEEP3, and ERRORBEEP4. Using that info, I later discovered that the ROM location I was in the middle of disassembling did indeed happen to be the startup chime.

Once I got a clue as to what the code was doing, I figured out a way to play the various chimes provided by writing a Mac app that played them. It turns out BOOTBEEP is just a handler that plays BOOTBEEP6, which is the actual startup chime. ERRORBEEP1 is the minor chord that plays in the chimes of death before the arpeggio. ERRORBEEP2 is a weird tone I had never heard before. ERRORBEEP3 is that same tone, with another note added at the end. ERRORBEEP4 is the familiar arpeggio error chime.

Each one of these sounds is a structure in the ROM that is passed to a ROM sound synthesis function that plays it using the Apple Sound Chip. When you hear the chimes of death, it’s actually playing two sounds consecutively: first ERRORBEEP1 for the chord, then ERRORBEEP4. After doing some serious disassembly of the sound synthesis function, I more or less understand what it does. The MAME source code was extremely useful to help me understand some of what the function was telling the Apple Sound Chip to do.

The synthesis function uses the wavetable synthesis capability of the sound chip. It is given one to four frequencies to play. It also is given several time values. One tells it how long before the wavetable should be updated. I believe it essentially specifies how quickly the waveform evolves and eventually fades out to nothing. Another time value sets how many steps should occur between playing each of the frequencies it’s given. Once a frequency is playing, it leaves it running and starts the next frequency in another voice. So at the end of the chord, all four voices are playing. If you make this a small number, it will play them all close together and it will be a chord like the startup chime. If you make it a large number, it will play them spaced apart, more like the death chime arpeggio. There is also a time value that specifies how long the sound should play in total. This would allow you to keep the sound going for a while after all the notes are playing. The frequencies are specified in terms of a 24-bit fixed-point increment value, basically telling the wavetable synthesizer how many entries in the wavetable to skip each time it reads a value. This effectively changes the frequency of the sound that plays based on what you set the increment value to.

It may sound complicated (it is!) but what it comes down to is this: the startup chime on a Mac IIci takes up 32 bytes of ROM space (not counting the synthesis function, which is reused for all the other startup sounds like the error chime). That’s pretty impressive, and you can see why they went that route to save ROM space.

So, here’s some info on the structure of a synthesized sound in the ROM:

  • A 16-bit number that seems to specify some kind of a volume setting.
  • A 32-bit number that sets how fast the waveform changes (a “step length” perhaps?)
  • A 32-bit number that sets how many steps elapse before starting to play the next frequency in the list of frequencies
  • A 32-bit number that sets how many steps before the sound is done.
  • A 16-bit number that specifies the number of frequencies (maximum of 4, since the sound chip has 4 voices)
  • For each frequency, a 32-bit number that contains the 24-bit fixed-point increment value I described earlier. The top 8 bits are not used.

Once I figured all this out, I just had to find some space in the ROM to put my Mario tune. I found what appears to be 35 KB of empty space, filled with many repetitions of an Apple copyright notice and a date. I made several of these sound structures for all the different chords I needed to play, and stuck them in there, along with code to play them in the correct sequence. I then modified the startup chime code to jump to my code instead. Here are the results:

Yes, that’s right. a Super Mario Bros IIci. It reboots after the first Happy Mac because I don’t have a PRAM battery installed on the motherboard. After that it continues booting fine.

I’d like to figure out how to make it play a sampled startup sound, but it may be difficult to figure out how to set up the sound chip for that mode. (Forget that, I now have sampled startup sounds working!) Anyway, let me know if you have any questions and I’ll try to answer them…and thanks again to everyone who helped me out with this project either directly or indirectly!

P.S.: Remember how I said the hard drive wouldn’t spin up? Well, I found a really, really old newsgroup posting online where someone with the exact same drive model had the exact same problem. The advice given? Give it a smack (not too gentle, but not too rough either) while it’s powered up. I hit it with a screwdriver and sure enough, it started spinning up. It’s been fine ever since through many power cycles! All the data was still intact. I certainly wouldn’t try that trick with the hard drives we have today, but I guess with stuff from the lower-density storage era, it’s not a terrible idea!