diff --git a/i2c/CMakeLists.txt b/i2c/CMakeLists.txt index 6b9c1ebef..05ebb2773 100644 --- a/i2c/CMakeLists.txt +++ b/i2c/CMakeLists.txt @@ -12,6 +12,7 @@ if (TARGET hardware_i2c) add_subdirectory_exclude_platforms(pcf8523_i2c) add_subdirectory_exclude_platforms(ht16k33_i2c) add_subdirectory_exclude_platforms(slave_mem_i2c) + add_subdirectory_exclude_platforms(ina260_i2c) else() message("Skipping I2C examples as hardware_i2c is unavailable on this platform") endif() diff --git a/i2c/ina260_i2c/CMakeLists.txt b/i2c/ina260_i2c/CMakeLists.txt new file mode 100644 index 000000000..b4f532150 --- /dev/null +++ b/i2c/ina260_i2c/CMakeLists.txt @@ -0,0 +1,11 @@ +add_executable(ina260_i2c + ina260_i2c.c +) +target_link_libraries(ina260_i2c + pico_stdlib + pico_status_led + hardware_i2c +) +pico_add_extra_outputs(ina260_i2c) +pico_enable_stdio_usb(ina260_i2c 1) +pico_enable_stdio_uart(ina260_i2c 1) diff --git a/i2c/ina260_i2c/ima260_example_bb.png b/i2c/ina260_i2c/ima260_example_bb.png new file mode 100755 index 000000000..e5f7b0e8a Binary files /dev/null and b/i2c/ina260_i2c/ima260_example_bb.png differ diff --git a/i2c/ina260_i2c/ina260_i2c.c b/i2c/ina260_i2c/ina260_i2c.c new file mode 100644 index 000000000..7eb208b18 --- /dev/null +++ b/i2c/ina260_i2c/ina260_i2c.c @@ -0,0 +1,57 @@ +#include +#include "pico/stdlib.h" +#include "hardware/i2c.h" +#include "pico/status_led.h" + +#define CURRENT_REGISTER 0x01 +#define VOLTAGE_REGISTER 0x02 +#define POWER_REGISTER 0x03 +#define I2C_ADDRESS 0x40 + +#define ByteSwap(u) (uint16_t)((u << 8)|(u >> 8)) + +// Read register value +static uint16_t read_reg(uint8_t reg) { + // Set the register address + int ret = i2c_write_blocking(i2c_default, I2C_ADDRESS, ®, 1, true); // no stop is set + assert(ret == 1); + if (ret != 1) return 0; + // Read the value + uint16_t data; + ret = i2c_read_blocking(i2c_default, I2C_ADDRESS, (uint8_t*)&data, 2, false); + assert(ret == 2); + if (ret != 2) return 0; + return ByteSwap(data); +} + +int main() { + stdio_init_all(); + printf("ina260 test\n"); + + // Initialise i2c + i2c_init(i2c_default, 100 * 1000); + gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C); + gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C); + gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN); + gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN); + + hard_assert(status_led_init()); + while(true) { + status_led_set_state(true); + + // Read current and convert to mA + float ma = read_reg(CURRENT_REGISTER) * 1.250f; + if (ma > 15000) ma = 0; + // Read the voltage + float v = read_reg(VOLTAGE_REGISTER) * 0.00125f; + // Read power and convert to mW + uint16_t mw = read_reg(POWER_REGISTER) * 10; + + // Display results + printf("current: %.2f mA voltage: %.2f V power: %u mW\n", ma, v, mw); + + status_led_set_state(false); + sleep_ms(1000); + } + return 0; +}