Example of a Serial bootloader for the K64F platform

Dependencies:   mbed

Introduction

Once in a while on mbed questions arise regarding making your own bootloader. So I decided to make one. Due to the device specific parts in the code this only works on the K64F. Porting it to other Freescale devices should be fairly straightforward. Devices from other manufacturers will require completely different code, although it could still be used as a basic guide.

Disclaimer

Bricking your device!

This rewrites your flash memory, including the security byte which determines among others the access external programmers get, and which can completely block future access.

Additionally this is an example, it is not intended to be used in a mission critical system in a nuclear power plant.

Requirements

I set some requirements for this bootloader. To start with, it should work when build from the online compiler. So no special compiler options to place functions in the correct sections. Even more important, it should be able to load regular programs from the mbed online compiler.

There are different options to get the data to the mbed, but for simplicity the goal is to just use the USBTX/USBRX serial pins. Finally there are some different types of bootloaders, for example they can launch at start up. That is not going to be easy with the requirement to also be able to load regular programs, although it might be possible, but it is not a requirement for here. In principle it is sufficient if the new user program has to call the bootloader, but an alternative is presented which allows a button to be able to enter bootloader mode, regardless of user code (not completely regardless, but it does not need to explictitly add any code for the bootloader).

Bootloader options

When a bootloader recides in the first part of the flash memory, it will run at start up and allows you to always upload a new program, regardless of your old program (it is always possible to brick it). However this means your user program needs to be compiled with an offset, and the online compiler cannot do this.

The alternative is putting the bootloader at the end of the flash memory. From here it can reprogram the first parts of the flash memory, but it will not automatically start up. Still this options has been used here.

The bootloader

The first requirement is placing the functions at the end of the flash memory. The online compiler (and Keil, other compilers will have different options) uses the following syntax to place functions at an absolute location:

__attribute__((section(".ARM.__at_0x10000"))) void bootloader(void)

Here obviously the 0x10000 is the absolute address where the function is placed. You may realise this is in fact not the end of the flash memory on the K64F. You are correct, I randomly choose this and cannot be bothered to change it. It allows 64kB for your user program, which is sufficient for just trying it out.

You do not need to worry about placing it on top of other functions/values: The compiler checks this, and gives a clear error message on the location and sizes of the collision.

It is important to realise that you cannot depend on any functions in the 'regular' area of your flash! This can be reprogrammed to contain any value/data, so every single functions and variable used by your bootloader needs to be specifically placed in your bootloader section. This also means that we cannot use mbed library functions, unless you manage to move the entire mbed library. Which could be done for the C API functions, but for here we use an easier solution, we just code it ourselves :D.

Serial code

Using void setupserial(); the serial peripheral is set up. This assumes the clock is already running correctly, so it depends a bit on the user program, but for any normal mbed user program this will be the case. I started using the K20D50M serial_api.c file from the mbed library, which contains all registers which are being set (The K64F code uses the KSDK drivers, which besides harder to use also cannot be used, because they will not reside in the correct memory area). The code simply hardcodes some register values to be correct for 9600 baud rate at USBTX/USBRX.

void write(char *value); is used to write messages on the serial connection.

Flash programming

Now we can send serial data (and receiving it is also pretty straight forward), we need to be able to program or flash memory. We use this program for this: http://developer.mbed.org/users/Sissors/code/FreescaleIAP/. However also this needs to be placed in the correct flash location. Since I have not been able yet to do it in a nice way in the library, it was done here manually.

To program flash it first needs to be erased. This takes a relative large amount of time, and due to the setup of this bootloader we do not know beforehand how many sectors need to be erased. So it just erases 15 4kB sectors, allowing for a program size of 60kB.

Once erased, the program will wait until the first char arrived. From this moment on it will enter a loop where received chars are placed in a 16-byte buffer. In principle the K64F should be able to program per 8-byte, however this resulted in error statuses from the flash peripheral. Since it works fine with programming per 16-bytes we use this. Every time 16-new bytes have arrived they are programmed into the flash memory, and a counter is increased.

In the loop also a timeout counter runs. Once no new chars have arrived for a period of time it assumes the program has been completely sent. The remaining bytes in the buffer are programmed, and the MCU resets itself, loading automatically the new user program.

Non-Maskable Interrupt

All (mbed) Freescale MCUs have a NMI setup which is called when the correct pin is pulled to zero. This interrupt vector resides in bytes 8-9-10-11, and on the K64F is connected to SW3, which makes it easy to use. The code currently simply replaces those 4 bytes with the location of the bootloader function. This means that regardless of the user program, it will be modified to start the bootloader upon pressing SW3 on your board.

Usage

After loading this program on your K64F the regular way, it will directly start the bootloader. Later on you can enter the bootloader by pressing SW3, or call it from your user code (for this you need to make a function pointer towards the location of the bootloader).

I assume for this Teraterm is used, other terminal programs might have similar options. After confirming you want to start the bootloader by typing 'y', it will erase the current program. Next you need to send the binary intact to the K64F via Teraterm. You can NOT do this via drag and dropping files into it, Teraterm will mutilate them. Instead go to File > Send File, and locate your file. Next make sure the "Binary" option is checked. If everything goes correctly you see a stream '#'s appear in your serial window, followed by a "Done programming!". It resets itself and your bootloaded program should run directly.

The bootloader simply expects the binary data to be transmitted via the Serial connection, so any programs which does so will do.

Remarks and Comments

Since you cannot rely on any functions outside the bootloader, you have to write everything yourself, or move existing libraries one function at a time. This makes it easiest if you stick to simple peripherals, such as SPI or Serial. It might be doable to move USBDevice over, although it would be far from trivial. I wouldn't even consider starting with Ethernet.

But what if you really want to use Ethernet? Let your user program handle it. Downside is of course your user program needs to handle this, and you cannot use any random program. But one example would be loading the new binary via whatever means you want, and storing it on an external memory chip. Then your bootloader program only needs to read it from your memory chip back.

If your code needs to be able to call the bootloader, for example after you loaded it via Ethernet, you need to add a pointer to the bootloader in your code, even though your newly loaded code does not contain the bootloader itself. This can be done using:

void *(*bootloader)(void) = (void *(*)(void))0x10001;

This creates a bootloader point of type void bootloader(void), pointing at a bootloader at 0x10000. If your bootloader function is at another memory location: you need the memory location plus 1. After this your code can call the bootloader simply as a normal function: bootloader();.

If you want it to start always upon reset, you can overwrite the Reset Handler. This is located right before the NMI, at bytes 4-5-6-7. It should work the same way as doing it the NMI way, with two differences. First of all currently the code relies on the clock being set up correctly. That won't be the case. In addition I do not know if it will correctly be able to make new variables on the stack, without code having run to initialize that. (My guess: It won't and you need to do that manually in your code).

The second difference is that you of course still need to be able to run the user code, so it needs to store the old reset vector in another location.

Committer:
Sissors
Date:
Fri Aug 22 15:14:52 2014 +0000
Revision:
0:9396d3376435
Child:
1:782a3ddc329e
versie 1

Who changed what in which revision?

UserRevisionLine numberNew contents of line
Sissors 0:9396d3376435 1 #include "mbed.h"
Sissors 0:9396d3376435 2 #include "FastPWM.h"
Sissors 0:9396d3376435 3 #include "FastIO.h"
Sissors 0:9396d3376435 4
Sissors 0:9396d3376435 5 #define TIME_REG LPC_TIM2->TC
Sissors 0:9396d3376435 6 FastPWM output(p21);
Sissors 0:9396d3376435 7 FastIn<p22> input;
Sissors 0:9396d3376435 8 void initTimer2();
Sissors 0:9396d3376435 9
Sissors 0:9396d3376435 10
Sissors 0:9396d3376435 11 int main()
Sissors 0:9396d3376435 12 {
Sissors 0:9396d3376435 13 //Ticks to be measured
Sissors 0:9396d3376435 14 unsigned int tick_width = 100;
Sissors 0:9396d3376435 15
Sissors 0:9396d3376435 16 unsigned int measured_timed[3];
Sissors 0:9396d3376435 17
Sissors 0:9396d3376435 18 initTimer2();
Sissors 0:9396d3376435 19
Sissors 0:9396d3376435 20 while (true) {
Sissors 0:9396d3376435 21 //Setup PWM
Sissors 0:9396d3376435 22 output.period_ticks(tick_width);
Sissors 0:9396d3376435 23 output.pulsewidth_ticks(tick_width/2);
Sissors 0:9396d3376435 24 wait_us(10);
Sissors 0:9396d3376435 25
Sissors 0:9396d3376435 26 //Start measuring at first rising edge
Sissors 0:9396d3376435 27 while(!input);
Sissors 0:9396d3376435 28 while(input);
Sissors 0:9396d3376435 29 measured_timed[0] = TIME_REG;
Sissors 0:9396d3376435 30 while(!input);
Sissors 0:9396d3376435 31 measured_timed[1] = TIME_REG;
Sissors 0:9396d3376435 32 while(input);
Sissors 0:9396d3376435 33 measured_timed[2] = TIME_REG;
Sissors 0:9396d3376435 34
Sissors 0:9396d3376435 35 printf("\r\nPulsewidth = %d ticks, which is %2.1fMHz\r\n", tick_width, (float)SystemCoreClock / (float)tick_width / 1000000.0f);
Sissors 0:9396d3376435 36 printf("Measured period = %d ticks, pulsewidth = %d ticks\r\n", measured_timed[2]-measured_timed[0], measured_timed[1]-measured_timed[0]);
Sissors 0:9396d3376435 37
Sissors 0:9396d3376435 38 //If more than 20% too large, consider it a fail
Sissors 0:9396d3376435 39 if ((measured_timed[2] - measured_timed[0]) > 1.2 * tick_width) {
Sissors 0:9396d3376435 40 printf("Period setting failed\r\n");
Sissors 0:9396d3376435 41 while(1);
Sissors 0:9396d3376435 42 }
Sissors 0:9396d3376435 43
Sissors 0:9396d3376435 44 //Setup next tick
Sissors 0:9396d3376435 45 tick_width--;
Sissors 0:9396d3376435 46
Sissors 0:9396d3376435 47 }
Sissors 0:9396d3376435 48 }
Sissors 0:9396d3376435 49
Sissors 0:9396d3376435 50 //Semi copy-pasted from: https://mbed.org/users/garyr/code/Counter/file/e619b6823668/Timer2.cpp
Sissors 0:9396d3376435 51 //We init timer at full clock speed, don't do anything else
Sissors 0:9396d3376435 52 void initTimer2() {
Sissors 0:9396d3376435 53 LPC_SC->PCONP |= (1<<22); // Power on the Timer2
Sissors 0:9396d3376435 54 LPC_SC->PCLKSEL1 &= ~(3<<12);
Sissors 0:9396d3376435 55 LPC_SC->PCLKSEL1 |= (1<<12); // Select CCLK for Timer2
Sissors 0:9396d3376435 56 LPC_TIM2->TCR = 2;
Sissors 0:9396d3376435 57 LPC_TIM2->TCR = 1; // Enable Timer2
Sissors 0:9396d3376435 58 }