Setting variables from file

19 Aug 2011

I am trying to find a way to set a couple of global constants from a file on the mbed drive, so that the mbed reads the variables in from the file when it starts up, but if the values in the file get edited during the course of the program I want those new values to be read in the next time the mbed is reset. Is this even possible?

I just need these global constants in order to set a couple of array sizes, but I'm trying to implement some way of changing the values without having to recompile every time. If what I tried to describe above won't work, are there any other approaches I could take to achieve this?

20 Aug 2011

I Have used something that looks like this ( very easy without control ), I hope thats what you mean. Or is the the problem the size of the array?

#include "mbed.h"

DigitalOut myled(LED1);

int     offset=0;  // gemeten waarde bij 4mA ( 0..1 <> 0..3.3v )
float   gain=1.0;    // helling om gemeten waarde om te rekenen naar druk
char A[10], B[10];

LocalFileSystem local("local");               // Create the local filesystem under the name "local"


/*
on the usb memory there must be a file "setup.txt"
with 2 lines:
offset 1
gain 1.100000
*/

void ReadFile (void) {
    FILE *set = fopen("/local/setup.txt", "r");  // Open "setup.txt" on the local file system for read
    fscanf(set,"%s %d",A,&offset); // read offset
    fscanf(set,"%s %f",B,&gain);   // read gain
    fclose(set);
}


void WriteFile(void) { // write to USB memory
    FILE *fp = fopen("/local/setup.txt", "w");  // Open "setup.txt" on the local file system for write
    fprintf(fp,"offset %d\r\n",offset); // read offset
    fprintf(fp,"gain %f\r\n",gain);   // read gain
    fclose(fp);
}


int main() {
    ReadFile();// when you run first time without this line, the setup file is on created
    wait(1);
    offset++;
    gain=gain*1.1;
    WriteFile();
        while (1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}

every time you reset the mbed the values offset and gain are changed.

20 Aug 2011

Have a look at the ConfigFile library project.

The library takes care of reading and parsing your config file.

22 Aug 2011

Thanks, this is pretty much what I needed!

11 Oct 2016

Thanks Hugo for sharing this solution. I was looking for exactly the same and found this very useful!