Test program that talkes to a I2C Microchip MCP9801 and logs results to USB serial and to mbeb local file system

Dependencies:   mbed

main.cpp

Committer:
monpjc
Date:
2010-10-13
Revision:
0:d40fd50424e3

File content as of revision 0:d40fd50424e3:


// Read from I2C slave at address 0x62

#include "mbed.h"

I2C i2c(p28, p27);
Serial pc(USBTX, USBRX);
DigitalOut myled(LED2);
LocalFileSystem local("local");             // Create the local filesystem under the name "local"


int main()
{
    unsigned int loop = 1;
    unsigned loopCount = 1;
    int address = 0x90;
    char RXdata[2];
    char TXdata[2];
    float temperature = 0;
    time_t seconds = 0;
    
    //Hello splash screen
    printf("\r\n\nmbeb Temperature logger V0.1\r\nBy Paul J clarke MIET\r\n13th Oct 2010\r\n\n");
    
    //clear serial buffer
    while( pc.readable() );
    
    //Configure sensor at 0.0625'C steps
    TXdata[0] = 0x01;
    TXdata[1] = 0x60;
    i2c.write(address, TXdata, 2);
    //Set dat for reading temperature
    TXdata[0] = 0x00;
    myled = 0;
    
    // Opens the root directory of the local file system
    printf("Files on mbed\r\n");
    DIR *d = opendir("/local");
    struct dirent *p;
    while((p = readdir(d)) != NULL)
    {                                         // Print the names of the files in the local file system
      printf("%s\n\r", p->d_name);            // to stdout (USB Serial).
    }
    closedir(d);
    printf("\n");
    
    // Removes the file "out.txt" from the local file system
    remove("/local/log.csv");
    // Open "log.csv" on the local file system for writing
    FILE *fp = fopen("/local/log.csv", "w");
   
    //reset time to zero
    set_time(0);
   
    //Send headers to csv file
    fprintf(fp, "Time_Seconds,Temperature_C\r");
   
    //main loop
    while(loop)
    {
        //toggle LED to show we are running
        myled = !myled;
        //set I2C device to point at temperature registor
        i2c.write(address, TXdata, 1);
        //read two bytes of raw data back
        i2c.read(address, RXdata, 2);
        //generate floating point number from raw data recived
        temperature = (((float)RXdata[1]) / 256) + RXdata[0];
        //stream temperature to USB serial port
        printf("Temperature = %.4f'C     Data Point = %d     \r", temperature, loopCount);
        //get time in seconds
        seconds = time(NULL);
        //and save to log file
        fprintf(fp, "%d,%.4f\n", seconds, temperature);
        //wait 250ms - time for ADC in temp sensor to re calculate new value
        wait(1);
     
        //inc loop counter
        loopCount++;
        
        if( pc.readable() || loopCount==1200 ) //1200 = 5 min's of loggin time
        {
            loop = 0;
        }
    }
    printf("\r\n\n Finished...\r\nTotal data points = %d\r\n", (loopCount-1));
    fclose(fp);

    while(1); //HALT
    
}