Austins SD card logger

Dependencies:   mbed SDFileSystem

main.cpp

Committer:
austinbrown124
Date:
2019-04-17
Revision:
3:8d4c12a3b5d4
Parent:
2:7bb016846566
Child:
4:4bd2b85412c3

File content as of revision 3:8d4c12a3b5d4:

#include "mbed.h"
#include "SDFileSystem.h"
#include "string.h"
 
/*SD card*/
//#define DI D11
//#define DO D12
//#define SCK D13
//#define CS D10
#define DI PB_5
#define DO PB_4
#define SCK PB_3
#define CS PB_6
 

char fname[255];
char current_time[64];

 
/*Serial buffer*/
//#define PAGE_SIZE 4096
#define PAGE_SIZE 2048
#define HEADER_SIZE 10
#define CHUNK_SIZE (PAGE_SIZE-HEADER_SIZE)
#define BUF_SIZE (16*PAGE_SIZE)
 
//RTC
#define SET_TIME false
 
int start = 0, end = 0;
unsigned char buf[BUF_SIZE];
unsigned char hdr[HEADER_SIZE] = {0xff, 0xff,'M','A','N','B','L','O','R','T'};
 
/*UART*/
#define BAUD_RATE 256000
//#define BAUD_RATE 9600
//Serial serial4(PA_11, D9);
Serial serial4(PA_2, PA_3);
Serial pc(PA_9, PA_10);
 
/*Test pins*/
DigitalOut test(PC_0);
DigitalOut test2(PC_2);
int flag=0, flag2=0;
 


 
void rx_callback() {
    while(serial4.readable()) {
        buf[end] = serial4.getc();
        //pc.printf("%c",buf[end]);
        end++;
        if (end == BUF_SIZE) end = 0;
    }
}
 
int main() {
    pc.baud(256000);
    test = 1;
    
    //buf[0] = 1;
    
    /*init SD card, wait for card insertion*/
    pc.printf("\n\rconfiging SD card \n\r");     
    SDFileSystem sd(DI, DO, SCK, CS, "sd");
    pc.printf("\n\r trying status \n\r"); 
    while (sd.disk_status()) {
        sd.disk_initialize();
        wait(0.5);
        pc.printf("nope \r");
    }
    pc.printf("disk initialized \r");
    
    if (SET_TIME) {set_time(1526496200);}

    time_t seconds = 0;//time(NULL);
    pc.printf("Time as seconds since January 1, 1970 = %d\n\r", seconds);


    
    strcpy(fname, "/sd/log_");
 
    sprintf(current_time, "%u", seconds );    
    strcat(fname, current_time);
    strcat(fname, ".dat");
    pc.printf("Logging to %s\n", fname);
    
    FILE *fp = fopen(fname, "wb");
    
    
    /*init serial*/    
    serial4.baud(BAUD_RATE);
    serial4.attach(rx_callback);
     
    //while (1==1) {pc.prinf("%i",end);}
    
    for (;;) {
        int length = end - start;
        if (length < 0) length += BUF_SIZE;
        if (length >= CHUNK_SIZE) {
            //fwrite(hdr, 1, HEADER_SIZE, fp);
            if (start+CHUNK_SIZE-1 < BUF_SIZE) {
                fwrite(buf+start, 1, CHUNK_SIZE, fp);
            } else {
                fwrite(buf+start, 1, BUF_SIZE-start+1, fp);
                fwrite(buf, 1, CHUNK_SIZE-(BUF_SIZE-start+1), fp);
            }
            fflush(fp);
            start += CHUNK_SIZE;
            if (start >= BUF_SIZE) start -= BUF_SIZE;
        }
    }
}