Forked MMA7660 , extend implementation by using i2c asynch API, to sleep while waiting for transfer -> blocking asynch :-D
Fork of MMA7660 by
Diff: MMA7660.cpp
- Revision:
- 5:556829f081f6
- Parent:
- 4:36a163511e34
--- a/MMA7660.cpp Tue May 13 18:14:34 2014 +0000
+++ b/MMA7660.cpp Tue May 05 07:23:40 2015 +0000
@@ -1,18 +1,38 @@
#include "MMA7660.h"
-MMA7660::MMA7660(PinName sda, PinName scl, bool active) : _i2c(sda, scl)
+MMA7660::MMA7660(PinName sda, PinName scl, bool active, bool asynch) : _i2c(sda, scl), callback_done(false), asynch(asynch)
{
+ event.attach(this, &MMA7660::callback);
setActive(active);
samplerate = 64;
}
+void MMA7660::callback(int event)
+{
+ if (event == I2C_EVENT_TRANSFER_COMPLETE) {
+ callback_done = true;
+ } else {
+ // handling errors
+ }
+}
+
//Since the MMA lacks a WHO_AM_I register, we can only check if there is a device that answers to the I2C address
bool MMA7660::testConnection( void )
{
- if (_i2c.write(MMA7660_ADDRESS, NULL, 0) == 0 )
- return true;
- else
- return false;
+ if (!asynch) {
+ if (_i2c.write(MMA7660_ADDRESS, NULL, 0) == 0 )
+ return true;
+ else
+ return false;
+ } else {
+ callback_done = false;
+ char received = 0;
+ _i2c.transfer(MMA7660_ADDRESS, NULL, 0, &received, 1, event, I2C_EVENT_ALL, false);
+ while (!callback_done) {
+ sleep();
+ }
+ return received == 0 ? true : false;
+ }
}
void MMA7660::setActive(bool state)
@@ -150,21 +170,49 @@
temp[0]=address;
temp[1]=data;
- _i2c.write(MMA7660_ADDRESS, temp, 2);
+ if (!asynch) {
+ _i2c.write(MMA7660_ADDRESS, temp, 2);
+ } else {
+ callback_done = false;
+ _i2c.transfer(MMA7660_ADDRESS, &temp[0], 2, NULL, 0, event, I2C_EVENT_ALL);
+ while (!callback_done) {
+ sleep();
+ }
+ }
}
char MMA7660::read(char address)
{
- char retval;
- _i2c.write(MMA7660_ADDRESS, &address, 1, true);
- _i2c.read(MMA7660_ADDRESS, &retval, 1);
- return retval;
+ if (!asynch) {
+ char retval;
+
+ _i2c.write(MMA7660_ADDRESS, &address, 1, true);
+ _i2c.read(MMA7660_ADDRESS, &retval, 1);
+ return retval;
+ } else {
+ callback_done = false;
+ char received = 0;
+ char addr = address;
+ _i2c.transfer(MMA7660_ADDRESS, &addr, 1, &received, 1, event, I2C_EVENT_ALL);
+ while (!callback_done) {
+ sleep();
+ }
+ return received;
+ }
}
void MMA7660::read(char address, char *data, int length)
{
- _i2c.write(MMA7660_ADDRESS, &address, 1, true);
- _i2c.read(MMA7660_ADDRESS, data, length);
+ if (!asynch) {
+ _i2c.write(MMA7660_ADDRESS, &address, 1, true);
+ _i2c.read(MMA7660_ADDRESS, data, length);
+ } else {
+ callback_done = false;
+ _i2c.transfer(MMA7660_ADDRESS, &address, 1, data, length, event, I2C_EVENT_ALL);
+ while (!callback_done) {
+ sleep();
+ }
+ }
}
float MMA7660::getSingle( int number )
@@ -191,4 +239,4 @@
setActive(false);
return temp / MMA7660_SENSITIVITY;
-}
\ No newline at end of file
+}
