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

i2cRtos_api.c

Committer:
humlet
Date:
2013-05-10
Revision:
13:530968937ccb
Parent:
12:6ddadcbbdca2
Child:
14:352609d395c1

File content as of revision 13:530968937ccb:

#include "i2cRtos_api.h"

#if DEVICE_I2C

#include "us_ticker_api.h"
#include "cmsis_os.h"
#include "error.h"

#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)
#define I2C_CONSET(x)       (x->i2c->I2CONSET)
#define I2C_CONCLR(x)       (x->i2c->I2CONCLR)
#define I2C_STAT(x)         (x->i2c->I2STAT)
#define I2C_DAT(x)          (x->i2c->I2DAT)
#elif defined(TARGET_LPC11U24)
#define I2C_CONSET(x)       (x->i2c->CONSET)
#define I2C_CONCLR(x)       (x->i2c->CONCLR)
#define I2C_STAT(x)         (x->i2c->STAT)
#define I2C_DAT(x)          (x->i2c->DAT)
#endif

#include "gpio_api.h"
static gpio_t gpio[2]; // evillive

enum I2cIsrCmd {
    readMst,
    writeMst,
    readSlv,
    writeSlv,
    waitSI
};
struct I2cIsrTransfer {
    i2c_t* obj;
    enum I2cIsrCmd cmd;
    int len;
    int cnt;
    int stat;
    char* rData;
    const char* wData;
};
static struct I2cIsrTransfer i2c_transfer[2];  // evillive: dare to get rid of volatile?


struct IsrIrqSem {
    IRQn_Type irq;
    osSemaphoreId sem;
};
static struct IsrIrqSem isrIrqSem[2];


// little helpers cloned from official i2c api
static inline void i2c_conclr(i2c_t *obj, int start, int stop, int interrupt, int acknowledge)
{
    I2C_CONCLR(obj) = (start << 5)
                      | (stop << 4)
                      | (interrupt << 3)
                      | (acknowledge << 2);
}
static inline void i2c_conset(i2c_t *obj, int start, int stop, int interrupt, int acknowledge)
{
    I2C_CONSET(obj) = (start << 5)
                      | (stop << 4)
                      | (interrupt << 3)
                      | (acknowledge << 2);
}
static inline void i2c_clear_SI(i2c_t *obj)
{
    i2c_conclr(obj, 0, 0, 1, 0);
}
static inline int i2c_status(i2c_t *obj)
{
    return I2C_STAT(obj);
}

// ISR stuff
static void i2cRtos_isr(uint32_t ch)
{
    struct I2cIsrTransfer* tr=&(i2c_transfer[ch]);
    if(tr->cmd==waitSI) {
        osSemaphoreRelease(isrIrqSem[ch].sem);
        NVIC_DisableIRQ(isrIrqSem[ch].irq);
        return;
    }
    int stat=i2c_status(tr->obj);
    int stay = 0;
    switch(tr->cmd) {
        case readMst:
            switch(stat) {
                case 0x50:
                    (tr->rData)[tr->cnt] = (char)(I2C_DAT(tr->obj) & 0xff);
                case 0x40:
                    ++(tr->cnt);
                    if(tr->cnt != tr->len-1)
                        i2c_conset(tr->obj, 0, 0, 0, 1);
                    else
                        i2c_conclr(tr->obj, 0, 0, 0, 1);
                    stay = 1;
                    break;
                case 0x58:
                    (tr->rData)[tr->cnt] = (char)(I2C_DAT(tr->obj) & 0xff);
                    stat=0;
                    break;
            }
            break;
        case writeMst:
            switch(stat) {
                case 0x18:
                case 0x28:
                    if(++(tr->cnt)!=tr->len) { // evillive
                        I2C_DAT(tr->obj) = (tr->wData)[tr->cnt];
                        stay=1;
                    } else {
                        stat=0;
                    }
            }
            break;
        case readSlv:
            ++(tr->cnt);
            if(stat==0x80 || stat==0x90)
                (tr->rData)[tr->cnt] = I2C_DAT(tr->obj) & 0xFF;
            stay = (stat==0x80 || stat==0x90 || stat==0x060 || stat==0x70) && (tr->cnt < tr->len-1);
            break;
        case writeSlv:
            ++(tr->cnt);
            stay = tr->cnt<tr->len && stat==0xb8;
            if(stay)
                I2C_DAT(tr->obj) = tr->wData[tr->cnt];
            break;
    }
    if(stay) {
        i2c_clear_SI(tr->obj);
    } else {
        tr->stat = stat;
        osSemaphoreRelease(isrIrqSem[ch].sem);
        NVIC_DisableIRQ(isrIrqSem[ch].irq);
    }
}
#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)
static void i2cRtos_isr_ch0()
{
    //gpio_write(&gpio[0], 1);
    i2cRtos_isr(0);
    //gpio_write(&gpio[0], 0);
}
#endif
static void i2cRtos_isr_ch1()
{
    //gpio_write(&gpio[1], 1);
    i2cRtos_isr(1);
    //gpio_write(&gpio[1], 0);
}


// determine channel
static inline uint32_t i2c_get_channel(const i2c_t *obj)
{
#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)
    switch((I2CName)(obj->i2c)) {
        case I2C_1:
            return 0;
        case I2C_2:
            return 1;
        default:
            error("Dial911 i2c_get_channel: Invaid I2CName \n");
    }
#endif
    return 1;
}


// wait for ISR finished
static inline void i2cRtos_wait_and_see(i2c_t *obj, int ch, uint32_t tmOut)  //evillive
{
    struct IsrIrqSem* iis = &(isrIrqSem[ch]);
    __disable_irq();
    i2c_clear_SI(obj);
    NVIC_ClearPendingIRQ(iis->irq);
    NVIC_EnableIRQ(iis->irq);
    __enable_irq();
    if(osSemaphoreWait(iis->sem, tmOut)!=1) NVIC_DisableIRQ(iis->irq);
}

static inline void i2cRtos_waitSI(i2c_t *obj, uint32_t tmOut)
{
    int ch = i2c_get_channel(obj);
    i2c_transfer[ch].cmd = waitSI;
    i2cRtos_wait_and_see(obj, ch, tmOut);
}


int i2cRtos_read(i2c_t *obj, int address, char *data, int length, int stop)
{
    //gpio_write(&gpio[1], 1);
    int stat = i2c_start(obj);
    if ((stat != 0x10) && (stat != 0x08)) {
        i2c_stop(obj);
        return stat;
    }
    //gpio_write(&gpio[1], 0);
    int ch = i2c_get_channel(obj);
    struct I2cIsrTransfer* tr = &(i2c_transfer[ch]); // evilive fill it locally and then copy it in one go to (volatile) mem?
    tr->obj=obj;
    tr->cmd=readMst;
    tr->len=length;
    tr->cnt=-1;
    tr->rData=data;
    I2C_DAT(obj) = address | 0x01;
    i2cRtos_wait_and_see(obj, ch,2+(length>>2));  // timeout (2+len/4)ms
    stat = tr->stat;
    //gpio_write(&gpio[1], 1);
    if(stat || stop) i2c_stop(obj);
    //gpio_write(&gpio[1], 0);
    return stat;
}

int i2cRtos_write(i2c_t *obj, int address, const char *data, int length, int stop)
{
    //gpio_write(&gpio[1], 1);
    int status = i2c_start(obj);
    if ((status != 0x10) && (status != 0x08)) {
        i2c_stop(obj);
        return status;
    }
    //gpio_write(&gpio[1], 0);

    int ch = i2c_get_channel(obj);
    struct I2cIsrTransfer* tr = &(i2c_transfer[ch]); // evilive fill it locally and then copy it in one go to (volatile) mem?
    tr->obj = obj;
    tr->cmd = writeMst;
    tr->len = length;
    tr->cnt = -1;
    tr->wData = data;
    I2C_DAT(obj) = address & 0xfe;
    i2cRtos_wait_and_see(obj, ch, 2+(length>>2));  // timeout (2+len/4)ms
    //i2c_clear_SI(obj); // ... why? Also in official lib ... I guess this is the "write instead of start" bug
    status = tr->stat;
    //gpio_write(&gpio[1], 1);
    if(status || stop) i2c_stop(obj);
    //gpio_write(&gpio[1], 0);
    return status;
}

int i2cRtos_byte_read(i2c_t *obj, int last)
{
    if(last) {
        i2c_conclr(obj, 0, 0, 0, 1); // send a NOT ACK
    } else {
        i2c_conset(obj, 0, 0, 0, 1); // send a ACK
    }
    i2cRtos_waitSI(obj, 2);
    return (I2C_DAT(obj) & 0xff);
}

int i2cRtos_byte_write(i2c_t *obj, int data)
{
    I2C_DAT(obj) = (data & 0xff);
    i2cRtos_waitSI(obj, 2);
    int stat=i2c_status(obj);
    return (stat==0x18 || stat==0x28 || stat==0x40 || stat==0xb8);
}


inline int i2cRtos_stop(i2c_t *obj) {
    i2c_conset(obj, 0, 1, 0, 0);
    i2c_clear_SI(obj);
    
    uint32_t t0=us_ticker_read();
    uint32_t dt=0;
    while((I2C_CONSET(obj) & (1 << 4)) && dt<23){
        dt = us_ticker_read() - t0;
    }
    return dt<23;
}


#if DEVICE_I2CSLAVE


int i2cRtos_slave_receive(i2c_t *obj, uint32_t tmOut)
{
    int retval = i2c_slave_receive(obj);
    //check for pending requests
    if(retval)return retval; // there is one => bail out
    // No request? Wait for it!
    i2cRtos_waitSI(obj, tmOut);
    // check again for pending requests
    return i2c_slave_receive(obj);
}

int i2cRtos_slave_read(i2c_t *obj, char *data, int length)
{
    int ch = i2c_get_channel(obj);
    struct I2cIsrTransfer* tr = &(i2c_transfer[ch]); // evilive fill it locally and then copy it in one go to (volatile) mem?
    tr->obj=obj;
    tr->cmd=readSlv;
    tr->len=length;
    tr->cnt=-1;
    tr->rData=data;
    i2cRtos_wait_and_see(obj, ch, 2+(length>>2));  // timeout (1+len/4)ms
    if(tr->stat != 0xa0) {
        i2c_stop(obj);
    }
    i2c_clear_SI(obj); // ... why? Also in official lib ... stops keeping scl low
    return tr->cnt;    // same weird return as in official lib
}

int i2cRtos_slave_write(i2c_t *obj, const char *data, int length)
{
    if(length <= 0) {
        return(0);
    }
    int ch = i2c_get_channel(obj);
    struct I2cIsrTransfer* tr = &(i2c_transfer[ch]); // evilive fill it locally and then copy it in one go to (volatile) mem?
    tr->obj=obj;
    tr->cmd=writeSlv;
    tr->len=length;
    tr->cnt=0;
    tr->wData=data;
    I2C_DAT(obj) = data[0];
    i2cRtos_wait_and_see(obj, ch, 2+(length>>2));  // timeout (1+len/4)ms
    int status = tr->stat;
    if(status!=0xC0 && status!=0xC8) {
        i2c_stop(obj);
    }
    i2c_clear_SI(obj); // ... why? Also in official lib ... stops keeping scl low
    return tr->cnt;
}


// setup semaphores and hook in ISRs
void i2cRtos_init(i2c_t *obj, PinName sda, PinName scl)
{
    
    static int called=0;
    if(!called) {
        gpio_init(&gpio[0], p15, PIN_OUTPUT);
        gpio_init(&gpio[1], p16, PIN_OUTPUT);
    }
    called = 1;
    gpio_write(&gpio[0], 0);
    gpio_write(&gpio[1], 0);
    
    i2c_init(obj,sda,scl);
    uint32_t ch = i2c_get_channel(obj);
#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)
    static osSemaphoreDef(i2cIsrDrvSem_ch0);
    static osSemaphoreDef(i2cIsrDrvSem_ch1);
    switch(ch) {
        case 0:
            isrIrqSem[ch].irq = I2C1_IRQn;
            NVIC_SetVector(I2C1_IRQn, (uint32_t)i2cRtos_isr_ch0);
            isrIrqSem[ch].sem = osSemaphoreCreate(osSemaphore(i2cIsrDrvSem_ch0), 1);
            break;
        case 1:
            isrIrqSem[ch].irq = I2C2_IRQn;
            NVIC_SetVector(I2C2_IRQn, (uint32_t)i2cRtos_isr_ch1);
            isrIrqSem[ch].sem = osSemaphoreCreate(osSemaphore(i2cIsrDrvSem_ch1), 1);
            break;
    }
    osSemaphoreWait(isrIrqSem[ch].sem, osWaitForever);
#elif defined(TARGET_LPC11U24)
    static osSemaphoreDef(i2cIsrDrvSem_ch1);
    isrIrqSem[ch].irq = I2C_IRQn;
    NVIC_SetVector(I2C_IRQn, (uint32_t)i2cRtos_isr_ch1);
    isrIrqSem[ch].sem = osSemaphoreCreate(osSemaphore(i2cIsrDrvSem_ch1), 1);
    osSemaphoreWait(isrIrqSem[ch].sem, osWaitForever);
#else
#error "Dial911 i2cRtos_init: Unsupported HW"
#endif
}
#endif
#endif