MPU6050 library

Dependents:   CSSE4011_BLE_IMU_Project_rev2 Seeed_Tiny_BLE_Get_Started nrf51822_fix_i2c_spi_conflict balanceboard ... more

Files at this revision

API Documentation at this revision

Comitter:
yihui
Date:
Thu Nov 05 01:38:50 2015 +0000
Parent:
0:1b6dab73c06b
Commit message:
add mbed_i2c_clear() function; ; use mbed_i2c_clear to recover i2c bus when i2c is stuck

Changed in this revision

mbed_i2c.c Show annotated file Show diff for this revision Revisions of this file
mbed_i2c.h Show annotated file Show diff for this revision Revisions of this file
diff -r 1b6dab73c06b -r 6aedb937cb38 mbed_i2c.c
--- a/mbed_i2c.c	Sat Feb 07 08:09:26 2015 +0000
+++ b/mbed_i2c.c	Thu Nov 05 01:38:50 2015 +0000
@@ -1,7 +1,10 @@
 
+#include <stdio.h>
 #include "i2c_api.h"
+#include "gpio_api.h"
+#include "nrf_delay.h"
 
-static i2c_t mbed_i2c_object;
+static i2c_t mbed_i2c_object = {0,};
 
 void mbed_i2c_init(PinName sda, PinName scl)
 {
@@ -35,3 +38,41 @@
     i2c_write(&mbed_i2c_object, slave_addr, &reg_addr, 1, 0);
     return (i2c_read(&mbed_i2c_object, slave_addr, data, length, 1) == length) ? 0 : 1;
 }
+
+int mbed_i2c_clear(PinName sda, PinName scl)
+{
+    gpio_t sda_io, scl_io;
+    
+    if (mbed_i2c_object.i2c) {
+        mbed_i2c_object.i2c->PSELSCL = 31;
+        mbed_i2c_object.i2c->PSELSDA = 31;
+    }
+    
+    gpio_init_in(&sda_io, sda);
+    
+    if (!gpio_read(&sda_io)) {
+        printf("sda is always 0, i2c bus is not released\r\n");
+        printf("try to clear i2c bus\r\n");
+        gpio_init_out(&scl_io, scl);
+        
+        // Clock max 18 pulses worst case scenario(9 for master to send the rest of command and 9
+        // for slave to respond) to SCL line and wait for SDA come high.
+        for (int i = 0; i < 18; i++) {
+            gpio_write(&scl_io, 0);
+            nrf_delay_us(4);
+            gpio_write(&scl_io, 1);
+            nrf_delay_us(4);
+        }
+        
+        if (!gpio_read(&sda_io)) {
+            printf("warning! sda is still 0,, i2c bus is not released\r\n");
+        }
+    }
+    
+    
+    if (mbed_i2c_object.i2c) {
+        mbed_i2c_init(sda, scl);
+    }
+    
+    return 0;
+}
diff -r 1b6dab73c06b -r 6aedb937cb38 mbed_i2c.h
--- a/mbed_i2c.h	Sat Feb 07 08:09:26 2015 +0000
+++ b/mbed_i2c.h	Thu Nov 05 01:38:50 2015 +0000
@@ -67,6 +67,8 @@
                     unsigned char length,
                     unsigned char *data);
                     
+int mbed_i2c_clear(PinName sda, PinName scl);
+                    
 #ifdef __cplusplus
 }
 #endif