UPDATE This code below works. It turns out my problem lied further down the chain with the software I was using to interface with the device and download files off. I pulled the SD card out of the device and plugged it directly into my PC, and you wouldn't believe it, but the data was there in the file.
Just another classic case of how assumptions screw you over. Never assume anything :)
I'll keep the post here just incase someone else comes along and finds this usefeul.
===============================================================
I am trying to write a logger that creates a file on the SD card of a device, and stores data into it. Right now, all I am trying to do is write the text "hello123" into the log file, however when I download the file off the card and open with a text editor there is no ASCII data in there, and contains binary data (series of ^@
) characters.
The file is created without any problems, it's just when I try to write to it. I call this function after another log function that runs on the devices firmware, so we can assume that the SD card is mounted and the CS pin to the SD is high (well low, but inverted).
So the sequence of events is:
- Program starts
- Main logging function called and SD line selected
- My log function called
- My DEBUG.LOG file is created
- DEBUG.LOG written to and closed
- Program continues on
The f_
functions used are a part of the FatFS library.
My code is as follows:
#include <ff.h>
#include <stdio.h>
#include <string.h>
#include "main.h"
unsigned char filename[10] = "debug.log";
unsigned char line[360];
static FIL logFile;
unsigned char error = 0;
FRESULT fresult;
UINT written = 0;
FATFS fatfs[1];
void writeLog()
{
volatile unsigned char retVal;
memset(line, 0, sizeof(line));
// check if sd card is mounted
if(f_mount(&fatfs[0], "0:", 1) != FR_OK)
{
error = 1; // breakpoint purposes
}
else
{
if(f_open(&logFile, (const char*)filename, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK){
retVal = f_lseek(&logFile, f_size(&logFile));
line[0] = 'h';
line[1] = 'e';
line[2] = 'l';
line[3] = 'l';
line[4] = 'o';
line[5] = '1';
line[6] = '2';
line[7] = '3';
line[8] = 0x00;
f_puts((char const*)line, &logFile) ;
f_puts("\r\n", &logFile);
f_sync(&logFile);
retVal = f_close(&logFile);
}
}
}
I'm not sure why it's not writing anything into the file. I mean it is as if I write 8 bytes into it, the filesize is 8 bytes, and I can see ^@^@^@^@^@^@^@^@^@^@
in my ubuntu terminal when I view it with less
.
Hex dump:
$ xxd DEBUG.LOG
00000000: 0000 0000 0000 0000 0000 ..........