Sunday, December 22, 2013

The bootloader

This week we reached a milestone by finishing the bootloader for the Stenosaurus. Well, maybe not finished but it's working. I hear you say, "That's great! But what's a bootloader? Why do we need one? Why should I care?"

Well, since you asked, I'll tell you. But I have to back up a bit.

Inside the Stenosaurus is a microcontroller, essentially a computer. This has a flash memory that stores the program that makes the Stenosaurus do what it does. As soon as you power on the Stenosaurus the microcontroller starts reading its flash memory from address zero and starts running the program. It goes something like this: read the next instruction, run it, read the next instruction, run it, repeat.

In order to get a program onto the microcontroller in the first place I use a device called a programmer. My computer connects to the programmer and the programmer connects to the microcontroller. Using this I can write the program onto the chip. But that's a hassle, in part, because you, the user, won't have a programmer. Also, we can make this easier.

It turns out that the microcontroller can also write to its own flash. This means that we can write a program that will run on the microcontroller and program itself. But remember what I mentioned above: the microcontroller fetches instructions and runs them one by one. If we overwrite the program while it is running then things will break badly.

One thing we could do is copy the program into RAM and run it from there while we write to the flash. But if there were some problem, like accidentally unplugging the Stenosaurus while uploading, then the flash wouldn't have a valid program and we'd be left with a Stenosaurus-shaped paper weight.

To fix that we make a bootloader. This is a program that sits at the beginning of the flash. When the microcontroller starts up it makes sure there is a valid program and then runs it. Normally, it will immediately run the regular program and the Stenosaurus will be ready to use. But when told to do so the bootloader can be a programmer instead. This lets you connect to the microcontroller and upload a new program. The program is written to a different area in flash so even if something goes wrong the bootloader is still there and we can just try again.

That is, pretty much, the story of the bootloader. I've glossed over some details. Maybe I'll talk about them more in a later post.

Stenosaurus now has a bootloader and a program that puts the Stenosaurus into programmer mode and uploads new programs. This program will be part of the Stenosaurus' companion app and, among other things, the app will let you update the firmware easily, and safely.