Hello, I have an interface library that uses the SDK functions i2c_write_blocking and i2c_read_blocking within some of my library functions.
It occured to me that there should be a way for a user of the library to set the I2C instance without having to edit the library (and I2C sensor library).
I have header files and one source file for the sensor functions. I figured the pins are easily set by macros in the end users program, but I2C not so much?
Here is what I have decided,
showing the relevant parts of the header file, let's call it "sensor.h"then sensor.c with the library functions:Next the end user of the library would use the setter function if they want i2c1 in their program:
It occured to me that there should be a way for a user of the library to set the I2C instance without having to edit the library (and I2C sensor library).
I have header files and one source file for the sensor functions. I figured the pins are easily set by macros in the end users program, but I2C not so much?
Here is what I have decided,
showing the relevant parts of the header file, let's call it "sensor.h"
Code:
// declaration of external variable for setting I2C instanceextern i2c_inst_t *i2c_instance;
Code:
// variable to set the I2C instance to be used by sensor_set_instance()i2c_inst_t *i2c_instance = i2c0; // Default to i2c0// Function to set the I2C instance (i2c0 or i2c1)void sensor_set_instance(i2c_inst_t *instance) { i2c_instance = instance;}// below would be functions that use SDK i2c functions that require setting an i2c instance// EXAMPLE write data to a register using defined device address to i2c_instance set by sensor_set_instance()void write_register(uint8_t reg, uint16_t data) { uint8_t buffer[3] = {reg, ((data >> 8) & 0xFF), (data & 0xFF)}; i2c_write_blocking(i2c_instance, sensor_address, buffer, 3, false); last_pointer = reg; // Update the last used pointer}
Code:
#include "sensor.h"#include "hardware/i2c.h"int main(void) { // Selects I2C instance (I2C0 is set as default in the sensor.c) //sensor_set_instance(i2c1); // change to i2c1 as needed // initialize I2C (I2C0 is default) i2c_init(i2c_instance, 400 * 1000); // sensor is 400 kHz max.// ETC}
Statistics: Posted by breaker — Sat Nov 16, 2024 4:51 pm