Demoapplication for the FRAM FM24CL16B

Dependencies:   mbed

Revision:
0:f4b9a1ec4c5f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Nov 05 06:56:32 2014 +0000
@@ -0,0 +1,99 @@
+#include "mbed.h"
+ 
+I2C i2c(I2C_SDA, I2C_SCL);
+ 
+#define FRAM_BASEADDR (0xA) // A7 .. A4
+
+uint8_t fram_calcAddr(uint8_t pageAdr, bool receiveBit){
+    return FRAM_BASEADDR << 4 | ((pageAdr<<1) & 0xf) | receiveBit;
+}
+
+bool fram_sendAddr(uint8_t pageAdr, uint8_t wordAdr, bool receiveBit){
+    uint8_t addr = fram_calcAddr(pageAdr, receiveBit);
+//    printf("addr: %X\n", addr);
+    return !i2c.write(fram_calcAddr(pageAdr, receiveBit), (const char*)&wordAdr, 1, 1);
+}
+
+bool fram_write(uint8_t pageAdr, uint8_t wordAdr, uint8_t* buf, uint16_t dataLength){
+    int ret;
+    
+    ret = fram_sendAddr(pageAdr, wordAdr, false);
+    if(ret != 1){
+        printf("write: addressing failed\n");
+        i2c.stop();
+        return false;
+    }
+    
+    for(int i=0; i<dataLength;++i){
+        ret = i2c.write(buf[i]);
+        if(ret != 1){
+            printf("write: writing data %i failed\n", i);
+            i2c.stop();
+            return false;
+        }
+    }
+    i2c.stop();
+    return true;
+}
+
+bool fram_read(uint8_t pageAdr, uint8_t wordAdr, uint8_t* buf, uint16_t dataLength){
+    int ret;
+    
+    ret = fram_sendAddr(pageAdr, wordAdr, false);
+    if(ret != 1){
+        printf("read: addressing failed\n");
+        i2c.stop();
+        return false;
+    }
+    
+    ret = i2c.read(fram_calcAddr(pageAdr, true), (char*)buf, dataLength, 0);
+    if(ret != 0){
+        printf("Read data failed!");
+        return false;
+    }
+    
+    return true;
+}
+
+ 
+Serial pc(SERIAL_TX, SERIAL_RX);
+ 
+bool fram_test(){
+    int i, ret;
+    const int length = 600;
+    uint8_t buf[length];
+    
+    printf("FRAM Test\n");
+    for(i=0; i<length; ++i)
+        buf[i] = i;
+    
+    ret = fram_write(0, 0, buf, length);
+    printf("write: %i\n", ret);
+    if(!ret) return false;
+    
+  
+    ret = fram_read(0, 0, buf, length);
+    printf("read: %i\n", ret);
+    if(!ret) return false;
+    
+    
+    for(i=0; i<length; ++i)
+        if(buf[i] != (uint8_t)i){
+            printf("data mismatch: i: %i buf[i]: %i (uint8_t)i: %i\n", i, buf[i], (uint8_t)i);
+             return false;
+             }
+        
+    return true;
+}
+ 
+int main()
+{
+ 
+    printf("Hello FRAM\n");
+    while (1) {
+        pc.printf("fram_test: %i\n", fram_test());
+        wait(1.0);
+    }
+ 
+}
+