int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { // Zero-length RX transfers are not supported. Such transfers cannot // be easily achieved with TWI peripheral (some dirty tricks would be // required for this), and they are actually useless (TX can be used // to check if the address is acknowledged by a slave). MBED_ASSERT(length > 0); twi_info_t *twi_info = TWI_INFO(obj); #if DEVICE_I2C_ASYNCH if (twi_info->active) { return I2C_ERROR_BUS_BUSY; } #endif twi_info->start_twi = false; NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; start_twi_read(twi, address); int result = length; while (length > 0) { int byte_read_result = i2c_byte_read(obj, (stop && length == 1)); if (byte_read_result < 0) { // When an error occurs, return the number of bytes that have been // received successfully. result -= length; // Force STOP condition. stop = 1; break; } *data++ = (uint8_t)byte_read_result; --length; } if (stop) { (void)i2c_stop(obj); } return result; }
int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { twi_info_t *twi_info = TWI_INFO(obj); bool timeout = false; uint32_t t0, t1; #if DEVICE_I2C_ASYNCH if (twi_info->active) { return I2C_ERROR_BUS_BUSY; } #endif twi_info->start_twi = false; NRF_TWI_Type *twi = m_twi_instances[TWI_IDX(obj)]; start_twi_write(twi, address); // Special case - transaction with no data. // It can be used to check if a slave acknowledges the address. if (length == 0) { nrf_twi_event_t event; if (stop) { event = NRF_TWI_EVENT_STOPPED; nrf_twi_task_trigger(twi, NRF_TWI_TASK_STOP); } else { event = NRF_TWI_EVENT_SUSPENDED; nrf_twi_event_clear(twi, event); nrf_twi_task_trigger(twi, NRF_TWI_TASK_SUSPEND); } t0 = ticker_read(get_us_ticker_data()); do { if (nrf_twi_event_check(twi, event)) { break; } t1 = ticker_read(get_us_ticker_data()); timeout = (t1 - t0) >= I2C_TIMEOUT_VALUE_US; } while (!timeout); uint32_t errorsrc = nrf_twi_errorsrc_get_and_clear(twi); if (errorsrc & NRF_TWI_ERROR_ADDRESS_NACK) { if (!stop) { i2c_stop(obj); } return I2C_ERROR_NO_SLAVE; } return (timeout ? I2C_ERROR_BUS_BUSY : 0); } int result = length; do { uint8_t byte_write_result = twi_byte_write(twi, (uint8_t)*data++); if (byte_write_result != 1) { if (byte_write_result == 0) { // Check what kind of error has been signaled by TWI. uint32_t errorsrc = nrf_twi_errorsrc_get_and_clear(twi); if (errorsrc & NRF_TWI_ERROR_ADDRESS_NACK) { result = I2C_ERROR_NO_SLAVE; } else { // Some other error - return the number of bytes that // have been sent successfully. result -= length; } } else { result = I2C_ERROR_BUS_BUSY; } // Force STOP condition. stop = 1; break; } --length; } while (length > 0); if (stop) { (void)i2c_stop(obj); } return result; }
uint8_t i2c_active(i2c_t *obj) { nrf_drv_twi_t const *twi = &m_twi_instances[TWI_IDX(obj)]; return nrf_drv_twi_is_busy(twi); }