I2C Master driver¶
This library allows you to communicate with I2C devices as the master device.
To use this library
Header: #include "drv_i2c_master.h"
memake: MikroSDK.Driver
I2C is a two wire synchronous serial protocol that allows you to exchange data with an I2C Slave. You can use it to communicate with I2C devices such as serial memories, sensors and other modules or integrated circuits. For that purpose, I2C protocol defines two lines:
- SDA (Serial Data) – the line for master and slave to send and receive data.
- SCL (Serial Clock) – The line that carries clock signal.
The driver is responsible for re-configuring hardware module before any message transaction, to ensure that each driver instance use its own configuration (clock speed, pin-outs).
Initialization¶
Before calling other functions from the I2C driver, user must define I2C Master driver context variable and call the Open function. The Open function initializes driver instance, GPIO pins and I2C module to work as I2C master device with configured speed, and on desired pins.
i2c_master_t i2c_master;
i2c_master_config_t i2c_master_cfg;
i2c_master_configure_default(&i2c_master_cfg);
i2c_master_cfg.scl = PB8;
i2c_master_cfg.sda = PB9;
i2c_master_open(&i2c_master, &i2c_master_cfg);
i2c_master_set_speed(&i2c_master, I2C_MASTER_SPEED_STANDARD);
The driver tries to find a corresponding I2C module for configured pins.
If the target MCU does not have I2C hardware module connected on the selected
GPIO pins, or specified speed is not supported, i2c_master_open
returns an
error.
After the open function succeeds, i2c_master
is initialized and represents a
handle to driver instance and underlying hardware module.
Sending messages on I2C bus¶
The driver provides basic functionality for writing and reading messages on I2C
bus. Before initiating a write or a read, user must call i2c_master_set_slave_address()
function, otherwise the slave address will remain 0
.
Example write, which sends a byte of data to a device whose slave address is
0x50
on the I2C bus:
uint8_t write_data[ 2 ];
write_data[0] = 0x00; // Registry address
write_data[1] = 0xAA; // Data to write
i2c_master_set_slave_address(&i2c_master, 0x50);
i2c_master_write(&i2c_master, &write_data, 2);
Info
Slave address is in 7-bit format. R/W bit is altered automatically by the driver when initiating read or write message.
i2c_master_write() ends with a STOP signal.
Example multiple read starting from a specified register:
uint8_t write_buffer[3];
uint8_t read_buffer[3];
write_buffer[0] = 0x00; // Registry address
i2c_master_write_then_read(&i2c_master, &write_buffer, 1, &read_buffer, 3);