Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ikkentim
Created March 27, 2018 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikkentim/2555a24c2a60ee19428aaee8370b4b70 to your computer and use it in GitHub Desktop.
Save ikkentim/2555a24c2a60ee19428aaee8370b4b70 to your computer and use it in GitHub Desktop.
#include "optiboot.h"
#include <avr/pgmspace.h>
#define MEMADDR 0x10000
void setup() {
int i;
uint8_t c;
uint16_t w;
uint8_t ram_buffer[SPM_PAGESIZE];
// Init serial
Serial.begin(9600);
Serial.print("addr size: ");
Serial.println(sizeof(optiboot_addr_t));
// Print current flash buffer content
Serial.println("Current flash contents:");
for (i=0;i<SPM_PAGESIZE;i++) {
c = pgm_read_byte(&((uint8_t *)MEMADDR)[i]);
if (c!=0 && c!=255) {
Serial.write(c);
} else {
Serial.print(".");
}
}
// Print prompt to enter some new characters to write to flash
Serial.println();
Serial.print("Type ");
Serial.print(SPM_PAGESIZE);
Serial.println(" characters to store in flash:");
// Get characters from serial and put into ram buffer
i=0;
while (i<SPM_PAGESIZE) {
if (Serial.available()>0) {
c = Serial.read(); // read character from serial
Serial.write(c); // echo character back
ram_buffer[i] = c;
i++;
}
}
Serial.println("\nAll chars received");
delay(100); // wait for sending all text via serial
// Erasing FLASH page
Serial.println("Erasing buffer");
delay(100); // wait for sending all text via serial
optiboot_page_erase((optiboot_addr_t)(void*) &((uint8_t *)MEMADDR)[0]);
// Copy ram buffer to temporary flash buffer
Serial.println("Writing to temporary flash buffer");
delay(100); // wait for sending all text via serial
for (i=0;i<SPM_PAGESIZE;i++) {
if (i % 2 == 0) { // we must write WORDs
w = ram_buffer[i];
} else {
w += (ram_buffer[i] << 8);
optiboot_page_fill((optiboot_addr_t)(void*) &((uint8_t *)MEMADDR)[i],w);
}
}
// Writing temporary buffer to FLASH
Serial.println("Writing buffer to flash");
delay(100); // wait for sending all text via serial
optiboot_page_write((optiboot_addr_t)(void*) &((uint8_t *)MEMADDR)[0]);
Serial.println("Write done, thank you!");
Serial.println("Now you can reset or power cycle board and check for new contents!");
}
void loop() {
// no code here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment