sakura fan / SakuraIO_official

Fork of SakuraIO by SAKURA Internet

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SakuraIO_I2C.cpp Source File

SakuraIO_I2C.cpp

00001 #include "mbed.h"
00002 #include "SakuraIO.h"
00003 #include "debug.h"
00004  
00005 #define SAKURAIO_SLAVE_ADDR 0x4F
00006  
00007 #define MODE_IDLE  0x00
00008 #define MODE_WRITE 0x01
00009 #define MODE_READ  0x02
00010  
00011 void SakuraIO_I2C::begin(){
00012   mode = MODE_IDLE;
00013 }
00014  
00015 void SakuraIO_I2C::end(){
00016   switch(mode){
00017     case MODE_WRITE:
00018       i2c.stop();
00019       break;
00020     case MODE_READ:
00021       while (_length > 0) {
00022         _length --;
00023         i2c.read(_length > 0 ? 1 : 0);
00024       }
00025       i2c.stop();
00026       break;
00027   }
00028  
00029   mode = MODE_IDLE;
00030 }
00031  
00032 void SakuraIO_I2C::sendByte(uint8_t data){
00033   if(mode != MODE_WRITE){
00034     dbg("beginTr\r\n");
00035     i2c.start();
00036     i2c.write(SAKURAIO_SLAVE_ADDR<<1);
00037     mode = MODE_WRITE;
00038   }
00039   dbg("Write=%02x\r\n", data);
00040   i2c.write(data);
00041 }
00042  
00043  
00044 uint8_t SakuraIO_I2C::startReceive(uint8_t length){
00045   if(mode != MODE_IDLE){
00046     dbg("endTransmission\r\n");
00047     i2c.stop();
00048   }
00049   dbg("requestForm=%d\r\n", length);
00050   _length = length;
00051   i2c.start();
00052   i2c.write(SAKURAIO_SLAVE_ADDR<<1 | 1);
00053   mode = MODE_READ;
00054   return 0;
00055 }
00056  
00057 uint8_t SakuraIO_I2C::receiveByte(){
00058   return receiveByte(false);
00059 }
00060  
00061 uint8_t SakuraIO_I2C::receiveByte(bool stop){
00062   uint8_t ret = 0;
00063   if (_length > 0) {
00064     _length --;
00065     ret = i2c.read(_length > 0 ? 1 : 0);
00066   }
00067   if(stop){
00068     end();
00069   }
00070   dbg("Read=%d\r\n", ret);
00071   return ret;
00072 }
00073  
00074 SakuraIO_I2C::SakuraIO_I2C (I2C &_i2c) : i2c(_i2c) {
00075   mode = MODE_IDLE;
00076 }
00077  
00078 SakuraIO_I2C::SakuraIO_I2C (PinName sda, PinName scl) : i2c(sda, scl) {
00079   mode = MODE_IDLE;
00080 }