uint8_t twi_sync_mt(uint8_t address, uint8_t *req_data, uint8_t req_len) { // write start condition write_start(); WAIT_FOR_BUS(); // write SLA+W write_slave_address(address, TW_WRITE); WAIT_FOR_BUS(); if (TW_STATUS != TW_MT_SLA_ACK) { write_stop(); return TWI_ERROR; } // write request data while (req_len--) { write_data_byte(*req_data++); WAIT_FOR_BUS(); if (TW_STATUS != TW_MT_DATA_ACK) { write_stop(); return TWI_ERROR; } } // write stop condition write_stop(); while (!(TWCR & (1 << TWSTO))); return TWI_OK; }
/// write to a connect I2C slave device // /// This function writes n bytes of data to the device with address a /// that is connected to the I2C bus. void write( fast_byte a, const byte data[], fast_byte n ) override { write_start(); write_byte( a << 1 ); for( fast_byte i = 0; i < n; i++ ){ read_ack(); write_byte( data[ i ] ); } read_ack(); write_stop(); }
/// read from a connected I2C slave device // /// This function reads n bytes of data from the device with address a /// that is connected to the I2C bus. void read( fast_byte a, byte data[], fast_byte n ) override { write_start(); write_byte( ( a << 1 ) | 0x01 ); read_ack(); for( fast_byte i = 0; i < n; i++ ){ if( i > 0 ){ write_ack(); } data[ i ] = read_byte(); } write_stop(); }
uint8_t twi_sync_mtmr(uint8_t address, uint8_t *req_data, uint8_t req_len, uint8_t *res_data, uint8_t res_len) { // Master Transmitter // write start condition write_start(); WAIT_FOR_BUS(); // write SLA+W write_slave_address(address, TW_WRITE); WAIT_FOR_BUS(); if (TW_STATUS != TW_MT_SLA_ACK) { write_stop(); return TWI_ERROR; } // write request data while (req_len--) { write_data_byte(*req_data++); WAIT_FOR_BUS(); if (TW_STATUS != TW_MT_DATA_ACK) { write_stop(); return TWI_ERROR; } } // Master Receiver // write repeated start write_start(); WAIT_FOR_BUS(); if (TW_STATUS != TW_REP_START) { write_stop(); return TWI_ERROR; } // write SLA+R write_slave_address(address, TW_READ); WAIT_FOR_BUS(); if (TW_STATUS != TW_MR_SLA_ACK) { write_stop(); return TWI_ERROR; } // read data while (res_len > 1) { read_data_byte(res_data++, 1); WAIT_FOR_BUS(); if (TW_STATUS != TW_MR_DATA_ACK) { write_stop(); return TWI_ERROR; } res_len--; } read_data_byte(res_data++, 0); WAIT_FOR_BUS(); if (TW_STATUS != TW_MR_DATA_NACK) { write_stop(); return TWI_ERROR; } // write stop condition write_stop(); while (!(TWCR & (1 << TWSTO))); return TWI_OK; }