acc_dev

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
p07gbar
Date:
Tue Apr 13 19:14:00 2010 +0000
Commit message:

Changed in this revision

SDstuff/FATFileSystem.lib Show annotated file Show diff for this revision Revisions of this file
SDstuff/SDFileSystem.cpp Show annotated file Show diff for this revision Revisions of this file
SDstuff/SDFileSystem.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 3033fd7e75a4 SDstuff/FATFileSystem.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SDstuff/FATFileSystem.lib	Tue Apr 13 19:14:00 2010 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_unsupported/code/fatfilesystem/
\ No newline at end of file
diff -r 000000000000 -r 3033fd7e75a4 SDstuff/SDFileSystem.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SDstuff/SDFileSystem.cpp	Tue Apr 13 19:14:00 2010 +0000
@@ -0,0 +1,442 @@
+/* mbed Microcontroller Library - SDFileSystem
+ * Copyright (c) 2008-2009, sford
+ */
+ 
+// VERY DRAFT CODE! Needs serious rework/refactoring 
+ 
+/* Introduction
+ * ------------
+ * SD and MMC cards support a number of interfaces, but common to them all
+ * is one based on SPI. This is the one I'm implmenting because it means
+ * it is much more portable even though not so performant, and we already 
+ * have the mbed SPI Interface!
+ *
+ * The main reference I'm using is Chapter 7, "SPI Mode" of: 
+ *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
+ *
+ * SPI Startup
+ * -----------
+ * The SD card powers up in SD mode. The SPI interface mode is selected by
+ * asserting CS low and sending the reset command (CMD0). The card will 
+ * respond with a (R1) response.
+ *
+ * CMD8 is optionally sent to determine the voltage range supported, and 
+ * indirectly determine whether it is a version 1.x SD/non-SD card or 
+ * version 2.x. I'll just ignore this for now.
+ *
+ * ACMD41 is repeatedly issued to initialise the card, until "in idle"
+ * (bit 0) of the R1 response goes to '0', indicating it is initialised.
+ *
+ * You should also indicate whether the host supports High Capicity cards,
+ * and check whether the card is high capacity - i'll also ignore this
+ *
+ * SPI Protocol
+ * ------------
+ * The SD SPI protocol is based on transactions made up of 8-bit words, with
+ * the host starting every bus transaction by asserting the CS signal low. The
+ * card always responds to commands, data blocks and errors.
+ * 
+ * The protocol supports a CRC, but by default it is off (except for the 
+ * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
+ * I'll leave the CRC off I think! 
+ * 
+ * Standard capacity cards have variable data block sizes, whereas High 
+ * Capacity cards fix the size of data block to 512 bytes. I'll therefore
+ * just always use the Standard Capacity cards with a block size of 512 bytes.
+ * This is set with CMD16.
+ *
+ * You can read and write single blocks (CMD17, CMD25) or multiple blocks 
+ * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
+ * the card gets a read command, it responds with a response token, and then 
+ * a data token or an error.
+ * 
+ * SPI Command Format
+ * ------------------
+ * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
+ *
+ * +---------------+------------+------------+-----------+----------+--------------+
+ * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
+ * +---------------+------------+------------+-----------+----------+--------------+
+ *
+ * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
+ *
+ * All Application Specific commands shall be preceded with APP_CMD (CMD55).
+ *
+ * SPI Response Format
+ * -------------------
+ * The main response format (R1) is a status byte (normally zero). Key flags:
+ *  idle - 1 if the card is in an idle state/initialising 
+ *  cmd  - 1 if an illegal command code was detected
+ *
+ *    +-------------------------------------------------+
+ * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
+ *    +-------------------------------------------------+
+ *
+ * R1b is the same, except it is followed by a busy signal (zeros) until
+ * the first non-zero byte when it is ready again.
+ *
+ * Data Response Token
+ * -------------------
+ * Every data block written to the card is acknowledged by a byte 
+ * response token
+ *
+ * +----------------------+
+ * | xxx | 0 | status | 1 |
+ * +----------------------+
+ *              010 - OK!
+ *              101 - CRC Error
+ *              110 - Write Error
+ *
+ * Single Block Read and Write
+ * ---------------------------
+ *
+ * Block transfers have a byte header, followed by the data, followed
+ * by a 16-bit CRC. In our case, the data will always be 512 bytes.
+ *  
+ * +------+---------+---------+- -  - -+---------+-----------+----------+
+ * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] | 
+ * +------+---------+---------+- -  - -+---------+-----------+----------+
+ */
+ 
+#include "SDFileSystem.h"
+
+#define SD_COMMAND_TIMEOUT 5000
+
+SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) :
+  FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs) {
+      _cs = 1; 
+}
+
+#define R1_IDLE_STATE           (1 << 0)
+#define R1_ERASE_RESET          (1 << 1)
+#define R1_ILLEGAL_COMMAND      (1 << 2)
+#define R1_COM_CRC_ERROR        (1 << 3)
+#define R1_ERASE_SEQUENCE_ERROR (1 << 4)
+#define R1_ADDRESS_ERROR        (1 << 5)
+#define R1_PARAMETER_ERROR      (1 << 6)
+
+// Types
+//  - v1.x Standard Capacity
+//  - v2.x Standard Capacity
+//  - v2.x High Capacity
+//  - Not recognised as an SD Card
+
+#define SDCARD_FAIL 0
+#define SDCARD_V1   1
+#define SDCARD_V2   2
+#define SDCARD_V2HC 3
+
+int SDFileSystem::initialise_card() {
+    // Set to 100kHz for initialisation, and clock card with cs = 1
+    _spi.frequency(400000); 
+    _cs = 1;
+    for(int i=0; i<16; i++) {   
+        _spi.write(0xFF);
+    }
+
+    // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
+    _cmd(0, 0);
+    if(_cmd(0, 0) != R1_IDLE_STATE) { 
+        fprintf(stderr, "No disk, or could not put SD card in to SPI idle state\n");
+        return SDCARD_FAIL;
+    }
+
+    // send CMD8 to determine whther it is ver 2.x
+    int r = _cmd8();
+    if(r == R1_IDLE_STATE) {
+        return initialise_card_v2();
+    } else if(r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
+        return initialise_card_v1();
+    } else {
+        fprintf(stderr, "Not in idle state after sending CMD8 (not an SD card?)\n");
+        return SDCARD_FAIL;
+    }
+}
+
+int SDFileSystem::initialise_card_v1() {
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        _cmd(55, 0); 
+        if(_cmd(41, 0) == 0) { 
+            return SDCARD_V1;
+        }
+    }
+
+    fprintf(stderr, "Timeout waiting for v1.x card\n");
+    return SDCARD_FAIL;
+}
+
+int SDFileSystem::initialise_card_v2() {
+    
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        _cmd(55, 0); 
+        if(_cmd(41, 0) == 0) { 
+            _cmd58();
+            return SDCARD_V2;
+        }
+    }
+
+    fprintf(stderr, "Timeout waiting for v2.x card\n");
+    return SDCARD_FAIL;
+}
+
+int SDFileSystem::disk_initialize() {
+
+    int i = initialise_card();
+//    printf("init card = %d\n", i);
+//    printf("OK\n");
+
+    _sectors = _sd_sectors();
+
+    // Set block length to 512 (CMD16)
+    if(_cmd(16, 512) != 0) {
+        fprintf(stderr, "Set 512-byte block timed out\n");
+        return 1;
+    }
+        
+    _spi.frequency(1000000); // Set to 1MHz for data transfer
+    return 0;
+}
+
+int SDFileSystem::disk_write(const char *buffer, int block_number) {
+    // set write address for single block (CMD24)
+    if(_cmd(24, block_number * 512) != 0) {
+        return 1;
+    }
+
+    // send the data block
+    _write(buffer, 512);    
+    return 0;    
+}
+
+int SDFileSystem::disk_read(char *buffer, int block_number) {        
+    // set read address for single block (CMD17)
+    if(_cmd(17, block_number * 512) != 0) {
+        return 1;
+    }
+    
+    // receive the data
+    _read(buffer, 512);
+    return 0;
+}
+
+int SDFileSystem::disk_status() { return 0; }
+int SDFileSystem::disk_sync() { return 0; }
+int SDFileSystem::disk_sectors() { return _sectors; }
+
+// PRIVATE FUNCTIONS
+
+int SDFileSystem::_cmd(int cmd, int arg) {
+    _cs = 0; 
+
+    // send a command
+    _spi.write(0x40 | cmd);
+    _spi.write(arg >> 24);
+    _spi.write(arg >> 16);
+    _spi.write(arg >> 8);
+    _spi.write(arg >> 0);
+    _spi.write(0x95);
+
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        int response = _spi.write(0xFF);
+        if(!(response & 0x80)) {
+            _cs = 1;
+            _spi.write(0xFF);
+            return response;
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+int SDFileSystem::_cmdx(int cmd, int arg) {
+    _cs = 0; 
+
+    // send a command
+    _spi.write(0x40 | cmd);
+    _spi.write(arg >> 24);
+    _spi.write(arg >> 16);
+    _spi.write(arg >> 8);
+    _spi.write(arg >> 0);
+    _spi.write(0x95);
+
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        int response = _spi.write(0xFF);
+        if(!(response & 0x80)) {
+            return response;
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+
+
+int SDFileSystem::_cmd58() {
+    _cs = 0; 
+    int arg = 0;
+    
+    // send a command
+    _spi.write(0x40 | 58);
+    _spi.write(arg >> 24);
+    _spi.write(arg >> 16);
+    _spi.write(arg >> 8);
+    _spi.write(arg >> 0);
+    _spi.write(0x95);
+
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        int response = _spi.write(0xFF);
+        if(!(response & 0x80)) {
+            int ocr = _spi.write(0xFF) << 24;
+            ocr |= _spi.write(0xFF) << 16;
+            ocr |= _spi.write(0xFF) << 8;
+            ocr |= _spi.write(0xFF) << 0;
+//            printf("OCR = 0x%08X\n", ocr);
+            _cs = 1;
+            _spi.write(0xFF);
+            return response;
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+
+int SDFileSystem::_cmd8() {
+    _cs = 0; 
+    
+    // send a command
+    _spi.write(0x40 | 8); // CMD8
+    _spi.write(0x00);     // reserved
+    _spi.write(0x00);     // reserved
+    _spi.write(0x01);     // 3.3v
+    _spi.write(0xAA);     // check pattern
+    _spi.write(0x87);     // crc
+
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT * 1000; i++) {
+        char response[5];
+        response[0] = _spi.write(0xFF);
+        if(!(response[0] & 0x80)) {
+                for(int j=1; j<5; j++) {
+                    response[i] = _spi.write(0xFF);
+                }
+                _cs = 1;
+                _spi.write(0xFF);
+                return response[0];
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+
+int SDFileSystem::_read(char *buffer, int length) {
+    _cs = 0;
+
+    // read until start byte (0xFF)
+    while(_spi.write(0xFF) != 0xFE);
+
+    // read data
+    for(int i=0; i<length; i++) {
+        buffer[i] = _spi.write(0xFF);
+    }
+    _spi.write(0xFF); // checksum
+    _spi.write(0xFF);
+
+    _cs = 1;    
+    _spi.write(0xFF);
+    return 0;
+}
+
+int SDFileSystem::_write(const char *buffer, int length) {
+    _cs = 0;
+    
+    // indicate start of block
+    _spi.write(0xFE);
+    
+    // write the data
+    for(int i=0; i<length; i++) {
+        _spi.write(buffer[i]);
+    }
+    
+    // write the checksum
+    _spi.write(0xFF); 
+    _spi.write(0xFF);
+
+    // check the repsonse token
+    if((_spi.write(0xFF) & 0x1F) != 0x05) {
+        _cs = 1;
+        _spi.write(0xFF);        
+        return 1;
+    }
+
+    // wait for write to finish
+    while(_spi.write(0xFF) == 0);
+
+    _cs = 1; 
+    _spi.write(0xFF);
+    return 0;
+}
+
+static int ext_bits(char *data, int msb, int lsb) {
+    int bits = 0;
+    int size = 1 + msb - lsb; 
+    for(int i=0; i<size; i++) {
+        int position = lsb + i;
+        int byte = 15 - (position >> 3);
+        int bit = position & 0x7;
+        int value = (data[byte] >> bit) & 1;
+        bits |= value << i;
+    }
+    return bits;
+}
+
+int SDFileSystem::_sd_sectors() {
+
+    // CMD9, Response R2 (R1 byte + 16-byte block read)
+    if(_cmdx(9, 0) != 0) {
+        fprintf(stderr, "Didn't get a response from the disk\n");
+        return 0;
+    }
+    
+    char csd[16];    
+    if(_read(csd, 16) != 0) {
+        fprintf(stderr, "Couldn't read csd response from disk\n");
+        return 0;
+    }
+
+    // csd_structure : csd[127:126]
+    // c_size        : csd[73:62]
+    // c_size_mult   : csd[49:47]
+    // read_bl_len   : csd[83:80] - the *maximum* read block length
+
+    int csd_structure = ext_bits(csd, 127, 126);
+    int c_size = ext_bits(csd, 73, 62);
+    int c_size_mult = ext_bits(csd, 49, 47);
+    int read_bl_len = ext_bits(csd, 83, 80);
+
+//    printf("CSD_STRUCT = %d\n", csd_structure);
+    
+    if(csd_structure != 0) {
+        fprintf(stderr, "This disk tastes funny! I only know about type 0 CSD structures\n");
+        return 0;
+    }
+             
+    // memory capacity = BLOCKNR * BLOCK_LEN
+    // where
+    //  BLOCKNR = (C_SIZE+1) * MULT
+    //  MULT = 2^(C_SIZE_MULT+2) (C_SIZE_MULT < 8)
+    //  BLOCK_LEN = 2^READ_BL_LEN, (READ_BL_LEN < 12)         
+                            
+    int block_len = 1 << read_bl_len;
+    int mult = 1 << (c_size_mult + 2);
+    int blocknr = (c_size + 1) * mult;
+    int capacity = blocknr * block_len;
+        
+    int blocks = capacity / 512;
+        
+    return blocks;
+}
diff -r 000000000000 -r 3033fd7e75a4 SDstuff/SDFileSystem.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SDstuff/SDFileSystem.h	Tue Apr 13 19:14:00 2010 +0000
@@ -0,0 +1,66 @@
+/* mbed Microcontroller Library - SDFileSystem
+ * Copyright (c) 2008-2009, sford
+ */
+ 
+// VERY DRAFT CODE!!! 
+
+#ifndef SDFILESYSTEM_H
+#define SDFILESYSTEM_H
+
+#include "mbed.h"
+#include "FATFileSystem.h"
+
+/* Class: SDFileSystem
+ *  Access the filesystem on an SD Card using SPI
+ *
+ * Example:
+ * > SDFileSystem sd(p5, p6, p7, p12, "sd");
+ * > 
+ * > int main() {
+ * >     FILE *fp = fopen("/sd/myfile.txt", "w");
+ * >     fprintf(fp, "Hello World!\n");
+ * >     fclose(fp);
+ * > }
+ */
+class SDFileSystem : public FATFileSystem {
+public:
+
+    /* Constructor: SDFileSystem
+     *  Create the File System for accessing an SD Card using SPI
+     *
+     * Variables:
+     *  mosi - SPI mosi pin connected to SD Card
+     *  miso - SPI miso pin conencted to SD Card
+     *  sclk - SPI sclk pin connected to SD Card
+     *  cs   - DigitalOut pin used as SD Card chip select
+   *  name - The name used to access the filesystem
+     */
+    SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name);
+    virtual int disk_initialize();
+    virtual int disk_write(const char *buffer, int block_number);
+    virtual int disk_read(char *buffer, int block_number);    
+    virtual int disk_status();
+    virtual int disk_sync();
+    virtual int disk_sectors();
+
+protected:
+
+    int _cmd(int cmd, int arg);
+    int _cmdx(int cmd, int arg);
+    int _cmd8();
+    int _cmd58();
+    int initialise_card();
+    int initialise_card_v1();
+    int initialise_card_v2();
+    
+    
+    int _read(char *buffer, int length);
+    int _write(const char *buffer, int length);
+    int _sd_sectors();
+    int _sectors;
+    
+    SPI _spi;
+    DigitalOut _cs;     
+};
+
+#endif
diff -r 000000000000 -r 3033fd7e75a4 main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Apr 13 19:14:00 2010 +0000
@@ -0,0 +1,390 @@
+#include "mbed.h"
+#include "SDFileSystem.h"
+
+SDFileSystem sd(p5, p6, p7, p8, "sd");
+
+//WWWWROTE is an interrupt driven AD345 logger - 16/3/2010 Tim Owen
+//This works OK for up to 1Mbyte files to flash -
+// misses at 1600, ? at 800s/s probably OK at 400s/s  ?????
+//This version writes on a read by read basis, no buffering internally
+//It stores in MBED flash, records by interrupt- it logs write times
+// usually its just OK at 1600 ss but the occasional write is too long.
+// needs a more reliable data store!!!!!!!!
+//class definitions etc
+//defines
+#define MAXFILESIZE 60               // secs
+#define BUFSIZE     16                   // size of 2 ram flipflop buffers
+#define CHANS       3                   // number of stored data values
+#define READSIZE   16                   // reads 16 x 3 int data values
+#define SS3200     0x0F                 // AD345 at 3200 s/s &c
+#define SS1600     0x0E
+#define SS800      0x0D
+#define SS400      0x0C
+#define SS200      0x0B
+#define SPFIFO     0x51                 // 17 samples - interrupt is dodgy if its 16 ???? curious
+#define SPRATE     SS400                 // see above  
+#define SPINTE     0x02                 //watermark
+#define SPINTM     0x00                 // true low
+#define SPDATA     0x2B                 // 16g
+#define SPPWRR     0x08                 // pwr ready   - run
+#define SPPWRS     0x00                 // pwr Standby - stop
+
+Serial pc(USBTX, USBRX);                // tx, rx
+DigitalOut led(LED1);                 // useful indicator of progress
+SPI spi(p11, p12, p13);                 // mosi, miso, sclk
+DigitalOut cs(p22);                     //SPI chip select true lo
+InterruptIn watermark(p21);             // goes lo when fifo has >21 values
+FILE *fp;
+Timer t;                               // output write file - bin
+
+
+//function prototypes
+int secondise(int in);
+int AD345_init(int rate);               // sets up accelerometer, rate = 100 x2 ...3200 s/s
+int AD345_check(void);                  // checks values in essential registers
+int AD345_standby(void);                // sets to standby mode to save power
+void AD345_watermark_service(void);     //services Watermark interrupt
+int show_bin_file(char* filename);      //reads binary file to screen
+int write_file(void*, int );
+int secs =0, mins = 0;
+// global variables
+int buf[BUFSIZE*CHANS];
+int buf_write_count;                       // number of ints in buffer to write.
+int buf_index=0;     // buf index points to next free space.
+int buf_file=0, elapse =0;           // is a file open?
+int rate,data_size=0,service_count=0;               //
+int file_size =0,write_count=0;                     // running total of writes
+int times[400],tindex=0,dumps[400];
+int bytes_written=0;
+int SampsCollected = 0;
+int samptime = 0;int samptimeS = 0;
+//buffer - there are 2 buffers of BUFSIZE ints each, buf_insw sets which buffer to use for input
+// and buf_outsw sets buffer to read.  buf_in_indx and ..._out_indx are buf pointers
+
+int secondise(int in)
+{
+   float S = in/1000;
+   int real = 0;
+   while(real < S - 1)
+   {
+    real = real + 1;
+   }
+    return real;
+}
+
+int AD345_init(int rate) {
+    //rate not used yet
+    // Setup the spi for
+    // 8 bit data, high steady state clock,
+    // second edge capture, with a 1000KHz clock rate
+    //watermark trigger via INT1 pin going lo on 21 datavalues
+    spi.format(8,3);
+    spi.frequency(1000000);
+    cs = 0;
+    pc.printf(".");  // this doesn't work - only when its copied below
+    spi.write(0x38); // write FIFO
+    spi.write(SPFIFO); // (mode FIFO-watermark )
+    cs = 1;
+    pc.printf(".");
+    cs = 0;
+    spi.write(0x2C); // write RATE
+    spi.write(SPRATE); // (? Hz)
+    cs = 1;
+    pc.printf(".");
+    cs = 0;
+    spi.write(0x2E); // write INT_ENABLE
+    spi.write(SPINTE); // (watermark)
+    cs = 1;
+    pc.printf(".");
+    cs = 0;
+    spi.write(0x2F); // write INT_MAP
+    spi.write(SPINTM); // (to INT1
+    cs = 1;
+    pc.printf(".");
+    cs =  0;
+    spi.write(0x31); // write DATA
+    spi.write(SPDATA); // (16g)
+    cs = 1;
+    cs = 0;
+    pc.printf(".");
+    spi.write(0x38); // write FIFO
+    spi.write(SPFIFO); // (mode FIFO-watermark)
+    cs = 1;
+    pc.printf(".");
+    cs = 0;
+    spi.write(0x2D); // write PWRCTL
+    spi.write(SPPWRR); // (ON)
+    cs = 1;
+    return(1);
+}
+
+int AD345_standby(void) {// sets AD345 into standby mode at the end of the run;
+    int pwrc;
+
+    pc.printf(".");
+    cs = 0;
+    spi.write(0x2D); // write PWRCTL
+    spi.write(0x00); // (Standby)
+    cs = 1;
+    pc.printf(".");
+    cs = 0;
+    spi.write(0x2D); // write PWRCTL
+    spi.write(0x00); // (Standby)
+    cs = 1;
+    cs = 0;
+    spi.write(0xAD); // read PWRCTL
+    pwrc = spi.write(0x00); // (?)
+    cs = 1;
+    return(pwrc&0x08);  // 0 if its in standby
+}
+
+int AD345_check(void) {//check them &prints out register values if wrong
+    char dump,pwrc,fifo,intc,intm,data,rate, loops,error=0;
+    loops = 3;
+    while (loops--) {
+        cs = 0;
+        dump = spi.write(0xAD); // read PWRCTL
+        pwrc = spi.write(0x00); // (ON)
+        cs = 1;
+        pc.printf(".");
+        cs = 0;
+        dump = spi.write(0xB8); // read FIFOCTL
+        fifo = spi.write(0x00); // (FIFO)
+        cs = 1;
+        pc.printf(".");
+        cs = 0;
+        dump = spi.write(0xAE); // read INT_EN
+        intc = spi.write(0x00); //
+        cs = 1;
+        pc.printf(".");
+        cs = 0;
+        dump = spi.write(0xAF); // read INT_MAP
+        intm = spi.write(0x00); // (INTM)
+        cs = 1;
+        pc.printf(".");
+        cs = 0;
+        dump = spi.write(0xB1); // read data
+        data = spi.write(0x00); // (DATA)
+        cs = 1;
+        pc.printf(".");
+        cs = 0;
+        dump = spi.write(0xAC); // read RATE
+        rate = spi.write(0x00); // (400 Hz)
+        cs = 1;
+
+        if ( fifo != SPFIFO) {
+            pc.printf("\n\rError FIFO %c = 0x%02X\n\r",SPFIFO,fifo);
+            error++;
+        }
+        if ( intc != SPINTE) {
+            pc.printf("Error INTC %c = 0x%02X\n\r",SPINTE,intc);
+            error++;
+        }
+        if ( intm != SPINTM) {
+            pc.printf("Error INTM %c = 0x%02X\n\r",SPINTM,intm);
+            error++;
+        }
+        if ( rate != SPRATE) {
+            pc.printf("Error RATE %c = 0x%02X\n\r",SPRATE,rate);
+            error++;
+        }
+        if ( data != SPDATA) {
+            pc.printf("Error DATA %c = 0x%02X\n\r",SPDATA,data);
+            error++;
+        }
+        if ( pwrc != SPPWRR) {
+            pc.printf("Error POWC %c = 0x%02X\n\r",SPPWRR,pwrc);
+            error++;
+        }
+        if (error == 0) {
+            pc.printf("AD345 Setup complete\n\r");
+            return(1);
+        }
+    }
+    return(0);
+}
+
+void AD345_watermark_service(void) {
+    
+    service_count++;
+    samptime = t.read_ms();
+    samptimeS = t.read();
+    pc.printf("\nTrig T : %i Tms : %i", samptimeS, samptime);
+    int datxlo,datxhi,datylo,datyhi,datzlo,datzhi;     //temp variables
+    int datx,daty,datz,ind;                                //temp variables
+    // check there is enough room in the current buffer before writing to it
+    data_size = 0;
+    buf_index =0;
+    for (ind=0; ind < 16; ind ++) {
+        cs = 0;
+        spi.write(0xF2);
+        datxlo = spi.write(0x80);
+        datxhi = spi.write(0x80);
+        datylo = spi.write(0x80);
+        datyhi = spi.write(0x80);
+        datzlo = spi.write(0x80);
+        datzhi = spi.write(0x80);
+        cs = 1;
+
+
+        datx = datxlo + datxhi*256;
+        if (datx > 32000) datx = -65536+datx;
+        buf[buf_index++] = datx;
+        daty = datylo + datyhi*256;
+        if (daty > 32000) daty = -65536+daty;
+        buf[buf_index++] = daty;
+        datz = datzlo + datzhi*256;
+        if (datz > 32000) datz = -65536+datz;
+        buf[buf_index++]=datz;
+        data_size += 3;
+
+    } // get 16 values
+    // putchar(':');
+    if (service_count > 30000000) { // emergency get out of jail card
+        pc.printf("\n\r gone on too long");
+        fclose(fp);
+        for (tindex=0;tindex < 200;tindex++)
+            //printf("wt=%d - %d //",times[tindex],dumps[tindex]);
+            watermark.fall(NULL);
+        exit(0);
+    }
+    SampsCollected = SampsCollected + 5;
+    //pc.printf("\n\r SAMPS = %i" , SampsCollected);
+    write_file(buf,data_size);   //assumes 32 bit ints
+    return;
+}
+
+int AD345_data_ready(void) {// this isn't used - its just the non-interrupt version for tests.
+    int  pending = 1;
+    int elapse,intc,over_run;
+    led =1;
+    while (pending) {
+        elapse = t.read_us();
+        pending++;
+        cs =0;
+        spi.write(0xB0); // read INT_SOURCE
+        intc = spi.write(0x00); // (INT_SOURCE)
+        cs =1;
+        if (intc&0x01) over_run++;
+        if (intc&0x02) pending = 0;// watermark
+        while (t.read_us() < elapse + 5);
+    }
+    led=0;
+    return(1);
+}
+
+int open_file(int junk) {
+    led = 1;
+    fp = fopen("/sd/sdtest.csv", "w");
+
+    if (!fp) {
+        fprintf(stderr, "/sd/sdtest.txt could not be opened!\n");
+        exit(0);
+    } else {
+        buf_file = 1;
+        pc.printf("\n\r/sd/sdtest.txt");
+    }
+    //fprintf(fp, "Hello fun SD Card World!");
+    return(buf_file);
+}
+
+int write_file(void *ptr, int size) { // writes file, keeps check of write times and size etc.
+
+    pc.printf("\n\rWrite Called");
+    if (buf_file == 0) open_file(1);
+    led=1;
+    int secondChangeFlag = 100;
+    
+    if(samptime - (samptimeS * 1000) <  40)
+    {
+    
+    pc.printf("TFlag %i" , samptime - (samptimeS * 1000));
+        int i = 50;
+        while(samptime - (samptimeS * 1000) <  i*2.5 && i>0)
+        {
+            secondChangeFlag = i;
+            i = i-1;
+            
+        }
+        pc.printf(": %i    ", secondChangeFlag);
+    }
+   
+    elapse = t.read_ms();
+    int timeS = t.read();
+    int timeStamp = SampsCollected;
+    
+    for (int i = 0; i < BUFSIZE/3; i += 1) {
+    
+    
+        pc.printf("%i,",i);
+        
+        if(i == secondChangeFlag)
+        {
+            timeStamp = timeS;
+            SampsCollected = 5-i;
+        }
+        else
+        {
+            timeStamp = SampsCollected + i - 5;
+        }
+        file_size += fprintf(fp, "%i,%i,%i,%i\n", timeStamp, buf[i*3],buf[(i*3)+1],buf[(i*3)+2]);
+    }
+    if (tindex < 399) {
+        times[tindex] = t.read_ms()- elapse;
+        dumps[tindex++] = size;
+    }
+    write_count++;
+    // if(write_count%25 == 0) pc.printf("-%d",write_count);
+    //pc.printf(".");
+    bytes_written += (size*4);
+    pc.printf("done at %i, %i", t.read_ms(), samptime - (samptimeS * 1000));
+    return(1);
+}
+
+
+int  main() {
+    int num,max=0,tot=0,val=0,vcnt=0,av=0;
+    pc.baud(115200);
+    pc.printf("\n\rWROTE AD345 software - 17/3/2010 Tim Owen");
+    AD345_init(rate);
+    AD345_check();
+    t.start();                              // clock starts here 
+    AD345_watermark_service();            // empty  buffer
+    AD345_watermark_service();             //empty buffer
+    data_size = 0;
+    // place interrupt for watermark flow control
+    watermark.fall(&AD345_watermark_service);
+    
+    while (t.read() < MAXFILESIZE) { // sit here in limbo
+        led = 1;        // need something to do to fight boredom
+        wait(0.5);
+        led = 0;
+        wait(0.5);
+    }
+    pc.printf("\n\r Ending normally now");
+    watermark.fall(NULL);
+    for (num=0; num < 400;num++) {
+        //// printf("wt=%d - %d //",times[num],dumps[num]);
+        if (times[num] != 0) {
+            tot += times[num];
+            vcnt++;
+        }
+        av = tot/vcnt;
+        if (times[num] > max) max = times[num];
+        if (times[num] > 30) { // appropriate value for 800 s/s ?
+            val++;
+            printf("<%d -%d>",num,times[num]);
+        }
+    }
+
+    fclose(fp);
+    pc.printf("\n\rAD345 calls %d, write av ms = %d, max ms = %d, >15ms = %d", service_count,av,max,val);
+    pc.printf("\n\rBytes in file %d, elapse time %f, s/s %f", bytes_written, t.read(), (float)bytes_written/(4.0*CHANS*t.read()) );
+    led =0;
+    t.stop();
+    AD345_standby();
+    pc.printf("\n\rAD345 in standby mode..");
+    watermark.fall(NULL);
+    pc.printf("\n\rAll done and dusted........");
+    return(0);
+}
diff -r 000000000000 -r 3033fd7e75a4 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Apr 13 19:14:00 2010 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/32af5db564d4