This is the quickstart guide for the Common service TWI, with step-by-step instructions on how to configure and use the driver in a selection of use cases.
The use cases contain several code fragments. The code fragments in the steps for setup can be copied into a custom initialization function, while the steps for usage can be copied into, e.g., the main application function.
Basic use case
In the most basic use case, the TWI module is configured for
- Master operation
- addressing one slave device of the bus at address 0x50
- TWI clock of 50kHz
- polled read/write handling
Setup steps
Example code
Add to your application C-file:
void twi_init(void)
{
.speed = 50000,
.chip = 0x50
};
}
Workflow
- Ensure that board_init() has configured selected I/Os for TWI function.
- Ensure that conf_twim.h is present for the driver.
- Note
- This file is only for the driver and should not be included by the user.
- Define and initialize config structs for TWI module in your TWI initialization function:
.speed = 50000,
.chip = 0x50
};
- field speed sets the baudrate of the TWI bus
- field chip sets the address of the slave device you want to communicate with
- Call twi_master_setup and optionally check its return code
- Note
- The config structs can be reused for other TWI modules after this step. Simply reconfigure and write to others modules.
Usage steps
Example code : Writing to a slave device
Use in application C-file:
.addr_length = sizeof (uint16_t),
};
Workflow
- Prepare the data you want to send to the slave device:
const uint8_t test_pattern[] = {0x55,0xA5,0x5A,0x77,0x99};
- Prepare a twi_package_t structure Fill all the fields of the structure :
- addr is the address in the slave device
- addr_length is the size of the address in the slave (support for large TWI memory devices)
- chip sets the 7 bit address of the slave device you want to communicate with
- buffer is a pointer on the data to write to slave
- length is the number of data to write
- Finally, call twi_master_write and optionally check its return value for TWI_SUCCESS.
Example code : Reading from a slave device
Use in application C-file:
uint8_t data_received[10];
.addr_length = sizeof (uint16_t),
.buffer = data_received,
.length = 10
};
if(data_received[0]==0x55)
do_something();
}
Workflow
- Prepare a data buffer that will receive the data from the slave device:
uint8_t data_received[10];
- Prepare a twi_package_t structure Fill all the fields of the structure :
- addr is the address in the slave device
- addr_length is the size of the address in the slave (support for large TWI memory devices)
- chip sets the 7 bit address of the slave device you want to communicate with
- buffer is a pointer on the data buffer that will receive the data from the slave device
- length is the number of data to read
- Finally, call twi_master_read and optionally check its return value for TWI_SUCCESS. the data read from the device are now in data_received.