1 year, 7 months ago.

Write in a text file

Hello I'm trying to write in a text file, but it never works. The Led always blink because the file is NULL, how to fix it ?

Write in a text file

#include "mbed.h"

DigitalIn button(USER_BUTTON);
DigitalOut myled(LED1);
int i;
int main()
{
    while (1)
    {
        if (button==0) {
            FILE*fp = fopen("/T:/Infrastructure/THEO-R/Code/go.txt","w");
            if(fp!=NULL) {

        fputc('A', fp);
        fprintf(fp, "hello");
                fclose(fp);
            } else {
                for(i=0; i<10; i++) {
                    myled = !myled;
                    wait (0.5);
                }
            }
        }
    }
}
Comment on this question

1 Answer

1 year, 7 months ago.

How is that code supposed to know where T drive is and how to connect to it? Where do you include the code to read / write to the file system?

On some boards you can use the on board flash as a file system, on others you need to use an SD card.

For more specific help you will need to tell us whether this is mbed 2 or mbed 5 code, where you are trying to put the files and which board you are using.

"How is that code supposed to know where T drive is and how to connect to it?" I don't know, but I can write to the OSDisk (C:) if it's simpler, but i think this is not the answer you expected.

I use the STM32L476RG board and I'm currently on the online compiler of Mbed (don't know if it's 2ou 5). I just want to write in a file on my computer and I'm a little lost, as you should guess I'm a beginner so I'm not sure to be able to answer to your questions ....

posted by Théo Rostaing 07 May 2018

The mbed is a completely separate computer to your PC, it knows nothing about the c: drive. To your PC it is a serial port and a USB memory stick, nothing more. Neither of those can write files to the hard drive. If they could that would be a massive security hole in the computer.

You can write to SD cards if you connect a socket to the board correctly. There are lots of examples on this site of how to do that or most arduino shields with an SD socket should work.

The software will vary a little depending on the mbed version used. If in the online compiler you have the library mbed as part of the project then it is an mbed 2 project, if you have mbed-os then it is an mbed 5 project. Your board supports both and there are lots of examples of the code for both around.

If you really want to write files onto the PC then you need two programs, one on the mbed that sends all of the required data over the serial port and one on the PC that reads the serial port and reads/writes the file as instructed.

posted by Andy A 07 May 2018

You need to log in to post a question