From 943f37b3cc72856cd2c11a7119c5e39783ffaca7 Mon Sep 17 00:00:00 2001 From: Peter Harper Date: Thu, 28 Aug 2025 17:27:42 +0100 Subject: [PATCH] Add ina260 example This can be used to monitor power usage of a Pico device. --- i2c/CMakeLists.txt | 1 + i2c/ina260_i2c/CMakeLists.txt | 8 ++++++ i2c/ina260_i2c/ina260_i2c.c | 52 +++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 i2c/ina260_i2c/CMakeLists.txt create mode 100644 i2c/ina260_i2c/ina260_i2c.c 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..38b2cf63f --- /dev/null +++ b/i2c/ina260_i2c/CMakeLists.txt @@ -0,0 +1,8 @@ +add_executable(ina260_i2c + ina260_i2c.c +) +target_link_libraries(ina260_i2c + pico_stdlib + hardware_i2c +) +pico_add_extra_outputs(ina260_i2c) diff --git a/i2c/ina260_i2c/ina260_i2c.c b/i2c/ina260_i2c/ina260_i2c.c new file mode 100644 index 000000000..84bc86173 --- /dev/null +++ b/i2c/ina260_i2c/ina260_i2c.c @@ -0,0 +1,52 @@ +#include +#include "pico/stdlib.h" +#include "hardware/i2c.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() { + setup_default_uart(); + 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); + + while(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); + sleep_ms(1000); + } + return 0; +}