Joris Aerts / I2CSlaveX
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers I2CSlaveX.cpp Source File

I2CSlaveX.cpp

00001 #include "I2CSlaveX.h"
00002 
00003 #if DEVICE_I2CSLAVE
00004 
00005 namespace mbed {
00006 
00007 I2CSlaveX* instance;
00008 
00009 I2CSlaveX::I2CSlaveX(PinName sda, PinName scl) : I2CSlave(sda, scl) {
00010     
00011 }
00012 
00013 // Add optional index argument for slaves that accept multiple addresses
00014 void I2CSlaveX::address(int address, int idx) {
00015     int addr = (address & 0xFF) | 1;
00016     i2c_slave_address(&_i2c, idx, addr, 0);
00017 }
00018 
00019 // Add optional argument that will be set with the received data value (usually slave address)
00020 int I2CSlaveX::receive(char *data) {
00021     if(data) {
00022         *data = _i2c.i2c->DAT;
00023     }
00024     return i2c_slave_receive(&_i2c);
00025 }
00026 
00027 // Return read length rather than match/no match
00028 int I2CSlaveX::read(char *data, int length) {
00029     return i2c_slave_read(&_i2c, data, length);
00030 }
00031 
00032 // Return write length rather than match/no match
00033 int I2CSlaveX::write(const char *data, int length) {
00034     return i2c_slave_write(&_i2c, data, length);
00035 }
00036 
00037 void I2CSlaveX::attach(void (*fptr)(void)) {
00038     if (fptr) {
00039         _receive.attach(fptr);
00040         enable_irq();
00041     } else {
00042         disable_irq();
00043     }
00044 }
00045 
00046 void I2CSlaveX::_irq_handler(uint32_t id, uint8_t addr, uint8_t state) {
00047     instance->_receive.call();
00048 }
00049 
00050 void I2CSlaveX::enable_irq() {
00051     // Hacky way to call this instance
00052     instance = this;
00053     NVIC_SetVector(I2C_IRQn, (uint32_t)(&I2CSlaveX::_irq_handler));
00054     NVIC_EnableIRQ(I2C_IRQn);    
00055 }
00056 
00057 void I2CSlaveX::disable_irq() {
00058     NVIC_DisableIRQ(I2C_IRQn);    
00059 }
00060 
00061 }
00062 
00063 #endif