MPU6050 library

Dependents:   CSSE4011_BLE_IMU_Project_rev2 Seeed_Tiny_BLE_Get_Started nrf51822_fix_i2c_spi_conflict balanceboard ... more

Revision:
1:6aedb937cb38
Parent:
0:1b6dab73c06b
--- 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;
+}