|
| 1 | +#include <SD.h> |
| 2 | +#include <FlashStorage.h> |
| 3 | + |
| 4 | +#define OTA_START 0x2000 |
| 5 | +#define OTA_SIZE 0x4000 |
| 6 | + |
| 7 | +#define SKETCH_START (uint32_t*)(OTA_START + OTA_SIZE) |
| 8 | + |
| 9 | +#ifndef SDCARD_SS_PIN |
| 10 | +#define SDCARD_SS_PIN 4 |
| 11 | +#endif |
| 12 | + |
| 13 | +#define UPDATE_FILE "UPDATE.BIN" |
| 14 | + |
| 15 | +FlashClass flash; |
| 16 | + |
| 17 | +// Initialize C library |
| 18 | +extern "C" void __libc_init_array(void); |
| 19 | + |
| 20 | +int main() { |
| 21 | + init(); |
| 22 | + |
| 23 | + __libc_init_array(); |
| 24 | + |
| 25 | + delay(1); |
| 26 | + |
| 27 | + if (SD.begin(SDCARD_SS_PIN) && SD.exists(UPDATE_FILE)) { |
| 28 | + File updateFile = SD.open(UPDATE_FILE); |
| 29 | + uint32_t updateSize = updateFile.size(); |
| 30 | + bool updateFlashed = false; |
| 31 | + |
| 32 | + if (updateSize > OTA_SIZE) { |
| 33 | + // skip the OTA section |
| 34 | + updateFile.seek(OTA_SIZE); |
| 35 | + updateSize -= OTA_SIZE; |
| 36 | + |
| 37 | + uint32_t flashAddress = (uint32_t)SKETCH_START; |
| 38 | + |
| 39 | + // erase the pages |
| 40 | + flash.erase((void*)flashAddress, updateSize); |
| 41 | + |
| 42 | + uint8_t buffer[512]; |
| 43 | + |
| 44 | + // write the pages |
| 45 | + for (uint32_t i = 0; i < updateSize; i += sizeof(buffer)) { |
| 46 | + updateFile.read(buffer, sizeof(buffer)); |
| 47 | + |
| 48 | + flash.write((void*)flashAddress, buffer, sizeof(buffer)); |
| 49 | + |
| 50 | + flashAddress += sizeof(buffer); |
| 51 | + } |
| 52 | + |
| 53 | + updateFlashed = true; |
| 54 | + } |
| 55 | + |
| 56 | + updateFile.close(); |
| 57 | + |
| 58 | + if (updateFlashed) { |
| 59 | + SD.remove(UPDATE_FILE); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // jump to the sketch |
| 64 | + __set_MSP(*SKETCH_START); |
| 65 | + |
| 66 | + //Reset vector table address |
| 67 | + SCB->VTOR = ((uint32_t)(SKETCH_START) & SCB_VTOR_TBLOFF_Msk); |
| 68 | + |
| 69 | + // address of Reset_Handler is written by the linker at the beginning of the .text section (see linker script) |
| 70 | + uint32_t resetHandlerAddress = (uint32_t) * (SKETCH_START + 1); |
| 71 | + // jump to reset handler |
| 72 | + asm("bx %0"::"r"(resetHandlerAddress)); |
| 73 | +} |
| 74 | + |
0 commit comments