RTOS enabled i2c-driver based on the official i2c-C-api.

Dependencies:   mbed-rtos

Fork of mbed-RtosI2cDriver by Helmut Schmücker

I2cRtosDriver

Overview

  • Based on RTOS
    • Less busy wait waste of CPU cycles
    • ... but some waste of CPU cycles by context switches
    • Frees up to 80% of CPU resources
  • Fixes the bug described in https://mbed.org/forum/bugs-suggestions/topic/4128/
  • Spends minimal time in interrupt context
  • Supports I2C Master and Slave mode
  • Interface compatible to official I2C lib
  • Supports LPC1768 and LPC11U24.
  • Reuses parts of the official I2C implementation
  • The test and example programs work quite well and the results look promising. But this is by no means a thoroughly regression tested library. There might be some surprises left.
  • If you want to avoid the RTOS overhead MODI2C might be a better choice.

Usage

  • In existing projects simply replace in the I2C interface class declaration the official type by one of the adapters I2CMasterRtos or I2CSlaveRtos described below. The behavior should be the same.
  • You can also use the I2CDriver interface directly.
  • You can create several instances of I2CMasterRtos, I2CSlaveRtos and I2CDriver. The interface classes are lightweight and work in parallel.
  • See also the tests/examples in I2CDriverTest01.h - I2CDriverTest05.h
  • The I2CDriver class is the central interface
    • I2CDriver provides a "fat" API for I2C master and slave access
    • It supports on the fly changes between master and slave mode.
    • All requests are blocking. Other threads might do their work while the calling thread waits for the i2c requests to be completed.
    • It ensures mutual exclusive access to the I2C HW.
      • This is realized by a static RTOS mutex for each I2C channel. The mutex is taken by the calling thread on any call of an I2CDriver-function.
      • Thus accesses are prioritized automatically by the priority of the calling user threads.
      • Once having access to the interface the requests are performed with high priority and cannot be interrupted by other threads.
      • Optionally the interface can be locked manually. Useful if one wants to perform a sequence of commands without interruption.
  • I2CMasterRtos and I2CSlaveRtos provide an interface compatible to the official mbed I2C interface. Additionally
    • the constructors provide parameters for defining the frequency and the slave address
    • I2CMasterRtos provides a function to read data from a given slave register
    • In contrast to the original interface the I2CSlaveRtos::receive() function is blocking, i.e it returns, when the master sends a request to the listening slave. There is no need to poll the receive status in a loop. Optionally a timeout value can be passed to the function.
    • The stop function provides a timeout mechanism and returns the status. Thus if someone on the bus inhibits the creation of a stop condition by keeping the scl or the sda line low the mbed master won't get freezed.
    • The interface adapters are implemented as object adapters, i.e they hold an I2CDriver-instance, to which they forward the user requests by simple inline functions. The overhead is negligible.

Design

The i2c read and write sequences have been realized in an interrupt service routine. The communicaton between the calling thread and the ISR is realized by a simple static transfer struct and a semaphore ... see i2cRtos_api.c
The start and stop functions still use the busy wait approach. They are not entered that frequently and usually they take less than 12µs at 100kHz bus speed. At 400kHz even less time is consumed. Thus there wouldn't be much benefit if one triggers the whole interrupt/task wait/switch sequence for that short period of time.

Performance

The following performance data have been measured with the small test applications in I2CDriverTest01.h and I2CDriverTest04.h . In these applications a high priority thread, triggered at a rate of 1kHz, reads on each trigger a data packet of given size with given I2C bus speed from a SRF08 ultra sonic ranger or a MPU6050 accelerometer/gyro. At the same time the main thread - running at a lower priority - counts in an endless loop adjacent increments of the mbed's µs-ticker API and calculates a duty cycle from this. These duty cycle measurements are shown in the table below together with the time measured for one read sequence (write address+register; write address and read x byte of data). The measurements have been performed with the ISR/RTOS approach used by this driver and with the busy wait approach used by the official mbed I2C implementation. The i2c implementation can be selected via #define PREFIX in I2CDriver.cpp.

  • The time for one read cycle is almost the same for both approaches
  • At full load the duty cycle of the low priority thread drops almost to zero for the busy wait approach, whereas with the RTOS/ISR enabled driver it stays at 80%-90% on the LPC1768 and above 65% on the LPC11U24.
  • => Especially at low bus speeds and/or high data transfer loads the driver is able to free a significant amount of CPU time.
LPC17681byte/ms4byte/ms6byte/ms1byte/ms6byte/ms12byte/ms25byte/ms
SRF08@ 100kHz@ 100kHz@ 100kHz@ 400kHz@ 400kHz@ 400kHz@ 400kHz
rtos/ISRDC[%]91.791.090.593.391.990.386.8
t[µs]421714910141314518961
busy waitDC[%]57.127.78.185.868.748.23.8
t[µs]415710907128299503949
LPC17681byte/ms4byte/ms7byte/ms1byte/ms6byte/ms12byte/ms36byte/ms
MPU6050@ 100kHz@ 100kHz@ 100kHz@ 400kHz@ 400kHz@ 400kHz@ 400kHz
rtos/ISRDC[%]91.590.789.393.091.690.084.2
t[µs]415687959133254398977
busy waitDC[%]57.730.53.386.574.359.71.2
t[µs]408681953121243392974
LPC11U241byte/ms6byte/ms1byte/ms6byte/ms23byte/ms
SRF08@ 100kHz@ 100kHz@ 400kHz@ 400kHz@ 400kHz
rtos/ISRDC[%]79.277.581.178.771.4
t[µs]474975199374978
busy waitDC[%]51.82.480.5633.3
t[µs]442937156332928
LPC11U241byte/ms6byte/ms1byte/ms6byte/ms32byte/ms
MPU6050@ 100kHz@ 100kHz@ 400kHz@ 400kHz@ 400kHz
rtos/ISRDC[%]79.176.881.078.667.1
t[µs]466922188316985
busy waitDC[%]52.87.281.769.87.4
t[µs]433893143268895

I2CDriver.cpp

Committer:
humlet
Date:
2013-05-19
Revision:
14:352609d395c1
Parent:
13:530968937ccb

File content as of revision 14:352609d395c1:

#include "I2CDriver.h"
#include "i2cRtos_api.h"
//#include "rt_System.h"
#include "error.h"

using namespace mbed;
using namespace rtos;

//DigitalOut I2CDriver::osci2(p7);

#define PREFIX i2cRtos
//#define PREFIX i2c // fallback to offical busy wait i2c c-api for performance testing 
#define PASTER(x,y) x ## _ ## y
#define EVALUATOR(x,y)  PASTER(x,y)
#define FUNCTION(fun) EVALUATOR(PREFIX, fun)

const PinName I2CDriver::c_sdas[] = {p9,p28};
const PinName I2CDriver::c_scls[] = {p10,p27};

I2CDriver::Channel* I2CDriver::s_channels[2] = {0,0};

I2CDriver::I2CDriver(PinName sda, PinName scl, int hz, int slaveAdr):m_freq(hz),m_slaveAdr(slaveAdr)
{
    // ensure exclusive access for initialization 
    static Mutex mtx;
    bool locked = false;
    if(osKernelRunning()) {  // but don't try to lock if rtos kernel is not running yet. (global/static definition) 
        mtx.lock();
        locked = true;
    }

    // check pins and determine i2c channel
    int channel=0;
#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)
    if(sda==c_sdas[0] && scl==c_scls[0]) channel=0; // I2C_1
    else
#endif
        if (sda==c_sdas[1] && scl==c_scls[1]) channel=1; //I2C_2 or I2C
        else error("I2CDriver: Invalid I2C pins selected\n");
    
    // initialize the selected i2c channel 
    if(s_channels[channel]==0) {
        s_channels[channel] = new I2CDriver::Channel;
        m_channel = s_channels[channel];
        m_channel->freq = 0;
        m_channel->slaveAdr = 0;
        m_channel->modeSlave = 0;
        m_channel->initialized=false; // defer i2c initialization util we are sure the rtos kernel is running (config() function)
    }
    m_channel = s_channels[channel];
    if(locked) mtx.unlock();
}

void I2CDriver::lock()
{
    //osci2.write(1);
    // One and the same thread can lock twice, but then it needs also to unlock twice.
    // exactly what we need here
    m_channel->mutex.lock(osWaitForever);
    m_channel->callerID = osThreadGetId();
    m_channel->callerPrio = osThreadGetPriority(m_channel->callerID);
    // maximize thread prio
    osThreadSetPriority(m_channel->callerID, c_drvPrio); // hopefully not interrupted since the lock in the line above
    // mutex code looks like that waiting threads are priority ordered
    // also priority inheritance seems to be provided
    //osci2.write(0);
}

void I2CDriver::unlock()
{
    //osci2.write(1);
    // free the mutex and restore original prio
    //rt_tsk_lock();  // just prevent beeing preempted after restoring prio before freeing the mutex 
    osThreadSetPriority(m_channel->callerID, m_channel->callerPrio);
    m_channel->mutex.unlock();   
    //rt_tsk_unlock();
    //osci2.write(0);
}

void I2CDriver::config()
{
    //osci2.write(1);
    // check and initialize driver
    if(!m_channel->initialized) {
        int channel = m_channel==s_channels[0] ? 0 : 1; // ...ugly
        FUNCTION(init)(&m_channel->i2c, c_sdas[channel], c_scls[channel]);
        m_channel->initialized=true;
    }
    // check and update frequency
    if(m_freq != m_channel->freq) {
        m_channel->freq = m_freq;
        i2c_frequency(&m_channel->i2c, m_freq);
    }
    // check and update slave/master mode
    if(m_modeSlave != m_channel->modeSlave) {
        m_channel->modeSlave = m_modeSlave;
        i2c_slave_mode(&m_channel->i2c, m_modeSlave);
    }
    // check and update slave address
    if(m_modeSlave && m_slaveAdr != m_channel->slaveAdr) {
        m_channel->slaveAdr = m_slaveAdr;
        i2c_slave_address(&m_channel->i2c, 0, m_slaveAdr, 0);
    }
    //osci2.write(0);
}

int I2CDriver::readMaster(int address, char *data, int length, bool repeated)
{
    m_modeSlave = false;
    lockNconfig();
    int ret = FUNCTION(read)(&m_channel->i2c, address, data, length, (repeated?0:1));
    unlock();
    return ret;
}
int I2CDriver::readMaster(int address, uint8_t _register, char *data, int length, bool repeated)
{
    m_modeSlave = false;
    lockNconfig();
    int ret = FUNCTION(write)(&m_channel->i2c, address,(const char*)&_register, 1, 0);
    if(!ret) ret = FUNCTION(read)(&m_channel->i2c, address, data, length, (repeated?0:1));
    unlock();
    return ret;
}
int I2CDriver::readMaster(int ack)
{
    m_modeSlave = false;
    lockNconfig();
    int ret = i2cRtos_byte_read(&m_channel->i2c, (ack?0:1));
    unlock();
    return ret;
}
int I2CDriver::writeMaster(int address, const char *data, int length, bool repeated)
{
    m_modeSlave = false;
    lockNconfig();
    int ret = FUNCTION(write)(&m_channel->i2c, address, data, length, (repeated?0:1));
    unlock();
    return ret;
}
int I2CDriver::writeMaster(int data)
{
    m_modeSlave = false;
    lockNconfig();
    int ret = i2cRtos_byte_write(&m_channel->i2c, data);
    unlock();
    return ret;
}
void I2CDriver::startMaster(void)
{
    m_modeSlave = false;
    lockNconfig();
    i2c_start(&m_channel->i2c);
    unlock();
}
bool I2CDriver::stopMaster(void)
{
    m_modeSlave = false;
    lockNconfig();
    bool ret=i2cRtos_stop(&m_channel->i2c);
    unlock();
    return ret;
}
void I2CDriver::stopSlave(void)
{
    m_modeSlave = true;
    lockNconfig();
    i2c_stop(&m_channel->i2c);
    unlock();
}
int I2CDriver::receiveSlave(uint32_t timeout_ms)
{
    m_modeSlave = true;
    lockNconfig();
    int ret = i2cRtos_slave_receive(&m_channel->i2c, timeout_ms);
    unlock();
    return ret;
}
int I2CDriver::readSlave(char* data, int length)
{
    m_modeSlave = true;
    lockNconfig();
    int ret = i2cRtos_slave_read(&m_channel->i2c, data, length);
    unlock();
    return ret;
}
int I2CDriver::readSlave(void)
{
    m_modeSlave = true;
    lockNconfig();
    int ret = i2cRtos_byte_read(&m_channel->i2c, 0);
    unlock();
    return ret;
}
int I2CDriver::writeSlave(const char *data, int length)
{
    m_modeSlave = true;
    lockNconfig();
    int ret = i2cRtos_slave_write(&m_channel->i2c, data, length);
    unlock();
    return ret;
}
int I2CDriver::writeSlave(int data)
{
    m_modeSlave = true;
    lockNconfig();
    int ret = i2cRtos_byte_write(&m_channel->i2c, data);
    unlock();
    return ret;
}