Arduino Bootloader

Introduction

This article is going to explain what happens behind the scene when the upload button is pressed in Arduino IDE.

Arduino Bootloader

For programming Arduino require only PC, serial connector, no other special programmer is required. This is possible because of a small program called a bootloader. It will help to program microcontrollers without any external programmer.

Bootloader requires some space in program memory due to which available memory for the program gets reduced.

Bootloader makes Arduino programming easy as no external programmer is required to program.

Arduino uses an optimized version of the optiboot to reduce bootloader size.

Optiboot only implements the following instruction of STK500 protocol to save space.

  • STK_LOAD_ADDRESS -> load address
  • STK_PROG_PAGE -> Write one page
  • STK_READ_PAGE -> Read one page
  • STK_READ_SIGN -> Reads compiled-in signature.
  • STK_LEAVE_PROGMODE -> Exit program mode
  • STK_GET_PARAMETER -> Read version
  • STK_UNIVERSAL -> Not implemented returns success
  • STK_SET_DEVICE -> Not implemented returns success
  • STK_SET_DEVICE_EXT -> Not implemented returns success

How do bootloader works?

When Arduino powered on the program first goes to reset vector at 0x0000 address then jumps to bootloader.

We can see the detailed flow in official avr-core optiboot.c

This is possible because AVR supports the self-programming mechanism (SPM).

Bootloaderflow chart

How Arduino is programmed?

Programming Arduino can be divided into two parts to compile the sketch and upload binary.

Arduino sketch compiles to a binary file using avr-gcc.

Binary is uploaded by using AVRdude. AVRdude uses the STK500 protocol to communicate to the AVR microcontroller

AVRdude follows the following steps:

  1. Convert binary file to hex using avrdude

  2. Reset Arduino by lowering DTR pin to unload capacitor

  3. Arduino will enter the bootloader

  4. Write a program to program memory using STK500 protocol page by page

    • Write program to RAM in one page size (for Atmega328 one page size -> 64 word)
    • Erase one-page flash memory
    • Fill flash memory page with hex bytes from RAM
    • Repeat steps to write all program
  5. Program memory is verified by reading the flash page by page

  6. Exit program mode using STK500 protocol

Reference

https://github.com/Optiboot/optiboot/wiki/HowOptibootWorks https://www.electronicwings.com/arduino/basics-to-developing-bootloader-for-arduino