Upgrading Embedded Design Firmware via USB - Embedded.com

Upgrading Embedded Design Firmware via USB

The ubiquitous USB communication medium that was intended to connect amice or keyboard to a computer has spawned to work wonders withspeakers, cameras, printers and many other devices.

Today, products ranging from guitars to automobiles come equippedwith USB. In such devices, new features can often be added orperformance glitches can be fixed through changes in software runningwithin the embedded controller and using the existing USB connection,designers can exploit an inherent benefit and provide product residentreprogrammability.

Changing the software running in a microcontroller can often addfeatures and/or fix bugs on a device that were not caught beforeshipping. In a glucose meter for instance, compatibility with newstrips can be made possible by a change in software. In the case of anoptical mouse that does not work on certain customer's desks, asoftware change could allow re-characterization of data received fromthe image sensor.

Such design changes that do not require a redesign of the hardwarelayout are quite commonplace and can be effectively handled byreprogramming the target silicon when the product has not left thefactory.

Once in the hands of the customer, however, direct programming isnot practical as such processes require unique hardware and access todedicated pins on the microcontroller.

If the device already required USB to serve as a communicationmechanism, then with the addition of a simple bootloader application inthe original firmware, new and subsequent firmware can be downloadedusing a standard computer, either by the manufacturer or an end user.

In embedded microcontrollers, a bootloader is a small program thatresides in program memory. When the part is reset or powered on, thebootloader application runs first and directs the processor to eitherexecute the user application or download a new one.

With this configuration, direct programming is required only toinsert the bootloader into the program memory. The bootloader can thenuse different communication techniques to fetch the new application.USB, I2C, SPI, UART, or even a proprietary protocol can be implementedto download the new program.

Different approaches can also be used to store the downloadedapplication. Based on memory requirements, the program can either bestored on the internal Flash of the microcontroller or externally in avariety of storage mediums.

As most bootloaders can be implemented using a small amount ofprogram space, they often reside alongside the user application in thesame Flash memory. While coexisting, it is the bootloader application'sresponsibility to avoid writing over itself when trying to downloadcode to the same memory. The bootloader portion of memory space can bewrite-protected to prevent any accidental corruption.

Figure1. USB bootloader data flow

The Bootloader
The general data flow prescribed for a USB bootloader application isshown in Figure 1, above . Uponpower-up or reset, the bootloader calculates the checksum of the userapplication and compares it to the one stored in memory set aside as afield programmable bootloader checksum block.

If the two values match, then the bootloader directs the processorto begin executing the user application. However, if the checksums aredifferent, the bootloader assumes that a host is waiting to dispatchnew user code. In preparation, it turns off any interrupts that coulddisturb the download process.

In certain systems it might be necessary for the microcontroller tomanage critical tasks before starting the download. For instance, a fanmight need to be turned on or some LEDs need to be blinking. As theapplication space is targeted for deletion, it is important forcritical tasks such as the fan or LED control routines to be a part ofthe bootloader application.

To begin communication, the bootloader sets up the USB interface andwaits till the computer connects with the device. The handshake processthrough which a computer learns about what is plugged in is calledenumeration.

This ensures that the device is communicating with the right hostsoftware, which in this case will be a PC application containing thecontent that needs to be downloaded. In order to prevent accidentaldownloads and to ensure security, the bootloader looks for a key fromthe host in the transactions.

Once the key has been verified, the bootloader responds to the hostand requests the Flash image. As Flash memory does not support singleaddress writes, a full page write is required. This is made possible bybuffering the arriving data in RAM before addressing the entire page.

As the processor at this point is dedicated to downloading newfirmware, almost all the RAM resources should be available. Writes toFlash need to be stronger at lower temperatures.

In order to increase the memory retention and the number of writecycles, it is important to know the temperature expected in the fieldand implement the programming algorithms accordingly. Power stabilityis also an important factor during flash programming.

Any power noise, glitches, brownouts, slow power ramps, and poorconnections can cause problems which are difficult to diagnose. If apower transient does occur, then the bootloader starts again andrestarts the download process as the checksum verification will fail.

Once all the Flash pages including the checksum are successfullywritten, the bootloader verifies the Flash and initiates a reset. Thistime, after system reset, the bootloader finds the right checksum andbegins execution of the user code.

Once the valid checksum is in place, any further bootloaderoperations need to be called from the running user code. With the rightapplication interface calls in place, the PC application should be ableto directly command the user code to disable all interrupts, reset theUSB hardware, and begin functioning as a bootloader.

Alternately, the device could be set up to enter the bootloaderenumeration process after being triggered by a change in status of somehardware such as a switch.

Figure2. Possible layout of a general purpose bootloader

Memory Management
Accidental erasures of the bootloader can cripple any further attemptsto download code via USB. A systematic allocation of memory reduces oreliminates the risk of such a mishap. Figure2 above shows a possible layout that may be employed to arrangethe bootloader application which can be used by a wide variety of Flasharchitectures.

The first set of blocks contains the reset and USB interruptvectors. This part of memory is non-relocatable and non-upgradable. Thesecond set, highlighted in green, comprises the memory that is setaside for the bootloader application.

This consists of the initial start command that looks for thebootloader checksum, the code used for downloading the new image, andfinally room for the checksum itself. This set of code is re-locatableand different sections can be placed in unique areas of memory.However, once the project is ready to be deployed, all areas of thissection except the checksum are non-upgradable.

The third section is set aside for the user application. Thisportion contains the user code, along with any associated interruptvectors and also the routines to call the bootloader application.

This area is reprogrammable and re-locatable but should not beaccessed when the bootloader is downloading code. Any interrupts thatpoint to this section of code should be disabled before calling anybootloader functions. Consider the problems that a program mightencounter if the code being executed was changed during execution.

The PC side of bootloading
On the PC side, a software application needs to communicate with thedevice and transmit the new user code. This software can be madeavailable by developers via the web or CD ROMs.

The software should be capable of requesting the device to enter thebootloading state and provide it with the right verification key. Whenthe device is ready, the host should send over the new contents whichwill be programmed onto the Flash memory.

The user code being downloaded should be stitched together with thebootloader's memory allocation in mind. This requires knowledge of thebeginning and end of the user code, the checksum etc.

As specified, in normal operation mode, the bootloader will alwayslink to the address where it expects to find the start of the usercode. Any bootloader calls from the user code will also have to pointto the correct static locations of the bootloader functions.

The PC can use a variety of mechanisms to deliver the content overUSB to the bootloader. Based on the requirements of the bootloaderresiding in the device, either control, interrupt, or bulk transferscan be used to shuttle the data.

The USB descriptors nested in the device can also decide the type ofdriver support that the application will require. The application caneither be designed to exploit an operating system's HID driver or use acustom vendor specific one.

Simplifying bootloading
Bootloading is actually a common practice. Personal computers use thesame principle for loading an operating system from a hard-drive. Manyreference designs and example projects on the web help with theimplementation of a bootloader in embedded designs.

 For example there is PSoC Designer, a utility that can be usedto create a USB or I2C bootloader that works with a wide series ofProgrammable System on Chips or PSoCs. The USB bootloader user modulegenerates all required bootloader code in a framework that coexistswith the user application.

Figure3: The USB bootloader looks for various selectable parameters such asthe location of the first and last user application blocks, the firstand last bootloader blocks, and the checksum addresses.

This utility allows design of either a full speed, Chapter 9compliant, HID, or generic USB device. A wizard that helps generateaccurate USB descriptors and supports bootloader transfers using eitherinterrupt or control transfer types.

The user module dynamically creates the bootloader code based on therequirements anticipated during the design process. As shown in Figure3 above it looks for various selectable parameters such as thelocationof the first and last user application blocks, the first and lastbootloader blocks, and the checksum addresses.

Bootloader size can be also be customized to allow insertion of anyspecial code that needs to run alongside the download process. The keythat is prepended to USB transactions is also customizable.

Knowledge of the anticipated temperature during future bootloaderoperations allows the utility to generate the appropriate programmingroutines. Finally, users can generate functions like voidBootLdrUSB_EnterBootloader(void) that provide user code with ability toinitiate bootloading operations from within the application.

The module generates and validates the checksum of the content thatis to be downloaded through the bootloader. Another tool derives thedownload file from the output of the compiler. This *.dld file containsthe hex code arranged in Flash blocks along with the new checksum. Itcan be parsed easily by PC applications written using Visual Basic orC#.

Engineering a method to download new user application into devicesvia USB can allow end users to upgrade their products for bug fixes orfeature enhancements. The ability to update without requiring anyspecial hardware eliminates the need for expensive recalls orreplacements.

Rakesh Reddy graduated fromMarquette University with a degree in Electrical Engineering. He isAssociate Product Manager in CypressSemiconductor's Lynnwood, WA offices supporting embeddedapplications development for lighting, USB, and power-linecommunication.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.