A C++ implementation of TWI communication of the ATmega640/1280/2560.
Master and slave communication is possible.
Modify the CMakeLists.txt file:
Setting this to YES flashes the generated .hex file into the micro-controller
SET(FLASH YES)
SET(BAUD 115200)
The default Arduino programmer was used in the CMakeLists.txt.
SET(PROGRAMMER wiring)
set(PORT /dev/ttyACM0)
Run the following within the extracted folder.
mkdir Build
cd Build
cmake ..
make
Generated files would be found in the bin folder within the parent folder.
If SET(FLASH ???) was set as YES, as explained earlier, the file is flashed onto the ATMega2560
Typical usage
- Calling the constructor:
TWI twi; - To set I2C mode as slave:
Here, 0x01 is the slave address.
twi.TWISetMode(TWIMode::Slave, 0x01); - To set I2C mode as master:
twi.TWISetMode(TWIMode::Master); - To read or recieve use Read() function- depends on Master or slave:
twi.Read(); - To transmit use Write() function- depends on Master or slave:
twi.Write();
void TWI::TWISetMode(TWIMode requestedMode,
uint8_t setSlaveAddress,
PrescalerValue value,
uint32_t twiFrequency)
requestedModeSets the transmission mode. Default mode is set to Master. For master -TWIMode::Master, for slave -TWIMode::SlavesetSlaveAddressSets the address when slave mode is selected. Default value is set to 0x01.valueSets the prescaler value. Default prescaler of 1 (prescaling to 0). Use
PRESCALE_VALUE_1
PRESCALE_VALUE_4
PRESCALE_VALUE_16
PRESCALE_VALUE_64twiFrequencySets the TWI communication frequency. Default value of 100000 (100 kHz)
void TWI::Write(uint8_t slaveAddress,
const uint8_t *data,
uint8_t dataLen,
bool repeatedStart,
bool TWIReadRequest)
slaveAddressAddress of the TWI slave device (7 bit wide)dataData to be transmitted. Sent in as an arraydataLenLength of the data to be transmittedrepeatedStartBoolean value, set as default to false. To be set to true if a repeated start is neededTWIReadRequestBoolean value, set as default to false. This value is used by the Read function only!
Function is used to send char array to the Write function. This is necessary since the length of the character array is determined here.
void TWI::Write(const uint8_t slaveAddress,
const char *const data,
const bool repeatedStart)
slaveAddressAddress of the TWI slave device (7 bit wide)datachar array to be transmittedrepeatedStartBoolean value, set as default to false. To be set to true if a repeated start is needed
void TWI::Write(const char *const data)
dataData to be transferred
void TWI::Read(const uint8_t slaveAddress,
uint8_t *data,
uint8_t readBytesLen,
const bool repeatedStart)
slaveAddressAddress of the TWI slave devicedatapointer to the array where the data shall be saved toreadBytesLenNumber of bytes the received data shall berepeatedStartBoolean value, set as default to false. To be set to true if a repeated start is needed
void TWI::Read()