Skip to content

Instantly share code, notes, and snippets.

@MarcianoPreciado
Last active October 20, 2021 18:52
Show Gist options
  • Save MarcianoPreciado/a49b16f12b14d89435717973a909df06 to your computer and use it in GitHub Desktop.
Save MarcianoPreciado/a49b16f12b14d89435717973a909df06 to your computer and use it in GitHub Desktop.
Flash Write without Erase Checker Func
#pragma once
/**
* Check if a section of flash memory can be written to a new value without a
* sector erase.
*
* @param old_mem current contents of flash memory region
* @param new_mem desired contents of flash memory region
* @param len number of bytes desired to write
*
* @return 1 if can be written, 0 if not
*/
int writable_without_erase(unsigned char *old_mem, unsigned char *new_mem,
int len) {
for (int i = 0; i < len; i++) {
int cant_write = (old_mem[i] ^ new_mem[i]) & new_mem[i];
if (cant_write) {
return 0;
}
}
return 1;
}
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include "flash_util.h"
void test0(void) {
unsigned char old_mem[] = {0b11111111};
unsigned char new_mem[] = {0b11111110};
assert(writable_without_erase(old_mem, new_mem, 1));
printf("Test 0 passed\n");
}
void test1(void) {
unsigned char old_mem[] = {0b11111110};
unsigned char new_mem[] = {0b11111111};
assert(!writable_without_erase(old_mem, new_mem, 1));
printf("Test 1 passed\n");
}
void test2(void) {
unsigned char old_mem[] = {0b11111111};
unsigned char new_mem[] = {0b11111111};
assert(writable_without_erase(old_mem, new_mem, 1));
printf("Test 2 passed\n");
}
void test3(void) {
clock_t start, end;
double cpu_time_used;
start = clock();
unsigned char old_mem[1024] = {0};
unsigned char new_mem[1024] = {0};
new_mem[1023] = 1;
assert(!writable_without_erase(old_mem, new_mem, 1024));
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Test 3 passed in %.03e sec\n", cpu_time_used);
}
int main(void) {
printf("Test Start\n");
test0();
test1();
test2();
test3();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment