test cp2120

Dependencies:   mbed

Revision:
0:7e56d5ba2990
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Apr 09 01:53:14 2015 +0000
@@ -0,0 +1,89 @@
+#include "mbed.h"
+
+Serial pc(USBTX, USBRX); // tx, rx
+
+
+SPI spi(p5, p6, p7); // mosi, miso, sclk
+DigitalOut rst_n(p8); // 
+DigitalOut cs_n(p9);
+
+// p5 : pin19 MOSI
+// p6 : pin20 MISO
+// p7 : pin01 SCLK
+// p8 : pin04 RESET_N
+
+
+
+
+
+int read_reg(int addr);
+void write_reg(int addr,int data);
+
+int read_reg(int addr) {
+        int retval;
+        cs_n=0;
+        wait_us(4000);
+        spi.write(0x21);
+        wait_us(1000);
+        spi.write(addr & 0xFF);
+        wait_us(1000);
+        retval = spi.write(0);
+        wait_us(1000);        
+        retval = spi.write(0);
+        wait_us(4000);
+        cs_n=1;
+        return retval;    
+}
+    
+void write_reg(int addr,int data){
+        cs_n=0;
+        wait_us(4000);
+        spi.write(0x20);
+        wait_us(1000);
+        spi.write(addr & 0xFF);
+        wait_us(1000);
+        spi.write(data);
+        wait_us(4000);
+        cs_n=1;
+}
+
+int main() {
+    int rw,addr,data;
+    // 8-bit, SPI mode 2
+    spi.format(8,2);
+    // 10kHz
+    spi.frequency(10000);
+
+    pc.printf("Init device\r\n");
+
+    cs_n  = 1;
+    rst_n = 0;    
+    wait_ms(10); 
+    rst_n = 1;    
+
+    while(1) {
+        rw = -1;
+        addr = 0;
+        data = 0;
+        pc.printf("Write and Read Address Data? rw(write=0,read=1) addr(hex) data(hex): \r\n");    
+        pc.scanf("%d %x %x",&rw,&addr,&data);
+        // Write
+        cs_n=0;
+        if ( rw == 0 ) {
+            write_reg(addr,data);
+            pc.printf("Wrote %02x @ %02x\r\n",data,addr);
+            pc.printf("Read  %02x @ %02x\r\n",read_reg(addr),addr);
+        }
+        else if (rw == 1 ) {
+            pc.printf("Read  %02x @ %02x\r\n",read_reg(addr),addr);
+        }
+        else if (rw == 2) {
+            for (int i=0; i<10;i++){
+                pc.printf("Read data %02x @ %02x\r\n",read_reg(i),i);
+            }
+        }
+        else {
+            pc.printf("Unknown command\r\n");
+        }
+    }
+}