Skip to content

Instantly share code, notes, and snippets.

@lotherk
Created February 26, 2018 14:31
Show Gist options
  • Save lotherk/2ee27766e56985b7bb438d3bf45d784d to your computer and use it in GitHub Desktop.
Save lotherk/2ee27766e56985b7bb438d3bf45d784d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MEM_SIZE_KBYTES 32
#define MEM_SIZE (1024 * MEM_SIZE_KBYTES)
struct vehicle {
char serial[32];
char name[32];
double km;
} vehicle;
struct config {
char serial[32];
char name[32];
} cfg;
struct gpslog {
struct {
double lat;
double lon;
} entry[64];
} gpslog;
char memory[MEM_SIZE];
void write8(int address, char byte) {
memory[address] = byte;
}
char read8(int address) {
return memory[address];
}
int openmem(char *file) {
FILE *fp;
fp = fopen(file, "r");
if (fp == NULL)
return 1;
size_t r;
r = fread(memory, sizeof(char), MEM_SIZE, fp);
fclose(fp);
printf("read %zu bytes from memory\n", r);
return 0;
}
int dumpmem(char *file) {
FILE *fp;
fp = fopen(file, "w");
if (fp == NULL)
return 1;
size_t r = fwrite(memory, sizeof(char), MEM_SIZE, fp);
fclose(fp);
printf("%zu bytes written to memry\n", r);
return 0;
}
void initmem() {
int i;
printf("zeroing memory...\n");
for (i = 0; i < MEM_SIZE; i++) {
fprintf(stdout, "0x%04X ", i);
fflush(stdout);
memory[i] = '\0';
}
printf("\n");
}
void writemem(int addr, void *mem, size_t size) {
printf("writing %zu bytes to memory at address %04X - %04X\n", size, addr, addr + (int) size);
int i = 0;
unsigned char *byte;
for (byte = (unsigned char *)mem; size--; ++byte) {
memory[addr + (i++)] = *byte;
}
}
void readmem(int addr, void *mem, size_t size) {
char buf[size];
int n;
for (n = 0; n < size; n++) {
buf[n] = memory[addr + n];
}
memcpy(mem, buf, size);
}
void setup() {
int r;
openmem:
r = openmem("memory.txt");
if (r) {
initmem();
strcpy(vehicle.serial, "E312312-D43M");
strcpy(vehicle.name, "xyz");
vehicle.km = 23.43;
writemem(0, &vehicle, sizeof(cfg));
gpslog.entry[0].lat = 55.3235;
gpslog.entry[0].lon = 11.2453;
gpslog.entry[1].lat = 22.2222;
gpslog.entry[1].lon = 33.3333;
writemem(8000, &gpslog, sizeof(gpslog));
int x = -1022;
writemem(500, &x, sizeof(x));
dumpmem("memory.txt");
goto openmem;
}
readmem(0, &vehicle, sizeof(cfg));
struct gpslog mylog;
readmem(8000, &mylog, sizeof(mylog));
int y;
readmem(500, &y, sizeof(y));
printf("entry0: lat: %f, lon: %f, y: %d\n", mylog.entry[0].lat, mylog.entry[0].lon, y);
dumpmem("memory.txt");
}
int main() {
setup();
printf("serial: %s\nname: %s\n", vehicle.serial, vehicle.name);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment