USB-DFU example

Dependencies:   mbed mbed-STM32F103C8T6 USBDevice_STM32F103

main.cpp

Committer:
adv_lut
Date:
2019-09-06
Revision:
9:37b5f4bc101f
Parent:
6:2f7ee2af27f9

File content as of revision 9:37b5f4bc101f:

#include "stm32f103c8t6.h"
#include "mbed.h"
#include "USBDFU.h"

/*
 * This is an example program demonstrating a USB DFU runtime combined with
 * a USB DFU bootloader that does not require an offset.
 * 
 * It normally blinks an LED at 1Hz, but when it receives a DFU detach
 * request over USB (eg, by running "dfu-util -d 1234:0006 -e"), it
 * blinks 3 times rapidly and resets into the bootloader.
 *
 * New programs can be uploaded by running
 * dfu-util -d 1234:0006,1209:db42 -D your_firmware.bin
 *
 * The companion bootloader source can be found on GitHub:
 * https://github.com/devanlai/dapboot/tree/highboot
 *
 */

DigitalOut  myled(LED1);

bool detached = false;
void onDetachRequested() {
    detached = true;
}

void resetIntoBootloader() {
    // Turn on write access to the backup registers
    __PWR_CLK_ENABLE();
    HAL_PWR_EnableBkUpAccess();
    
    // Write the magic value to force the bootloader to run
    BKP->DR2 = 0x544F;
    BKP->DR1 = 0x4F42;
    
    HAL_PWR_DisableBkUpAccess();
    
    // Reset and let the bootloader run
    NVIC_SystemReset();
}

int main() {
    confSysClock();     //Configure system clock (72MHz HSE clock, 48MHz USB clock)
    
    USBDFU usbDFU(0x1234, 0x0006, 0x0001, false);
    usbDFU.attach(onDetachRequested);
    
    while(1) {
        // Check the DFU status
        if (!usbDFU.configured()) {
            usbDFU.connect(false);
        }
        if (detached) {
            for (int i=0; i < 5; i++) {
                myled = 1;
                wait_ms(100);
                myled = 0;
                wait_ms(100);
            }
            resetIntoBootloader();
        }
        
        // Do normal stuff
        myled = !myled;
        wait_ms(1000);
    }
}