Skip to content

Commit 943f37b

Browse files
committed
Add ina260 example
This can be used to monitor power usage of a Pico device.
1 parent 4c3a3dc commit 943f37b

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

i2c/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ if (TARGET hardware_i2c)
1212
add_subdirectory_exclude_platforms(pcf8523_i2c)
1313
add_subdirectory_exclude_platforms(ht16k33_i2c)
1414
add_subdirectory_exclude_platforms(slave_mem_i2c)
15+
add_subdirectory_exclude_platforms(ina260_i2c)
1516
else()
1617
message("Skipping I2C examples as hardware_i2c is unavailable on this platform")
1718
endif()

i2c/ina260_i2c/CMakeLists.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
add_executable(ina260_i2c
2+
ina260_i2c.c
3+
)
4+
target_link_libraries(ina260_i2c
5+
pico_stdlib
6+
hardware_i2c
7+
)
8+
pico_add_extra_outputs(ina260_i2c)

i2c/ina260_i2c/ina260_i2c.c

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <stdio.h>
2+
#include "pico/stdlib.h"
3+
#include "hardware/i2c.h"
4+
5+
#define CURRENT_REGISTER 0x01
6+
#define VOLTAGE_REGISTER 0x02
7+
#define POWER_REGISTER 0x03
8+
#define I2C_ADDRESS 0x40
9+
10+
#define ByteSwap(u) (uint16_t)((u << 8)|(u >> 8))
11+
12+
// Read register value
13+
static uint16_t read_reg(uint8_t reg) {
14+
// Set the register address
15+
int ret = i2c_write_blocking(i2c_default, I2C_ADDRESS, &reg, 1, true); // no stop is set
16+
assert(ret == 1);
17+
if (ret != 1) return 0;
18+
// Read the value
19+
uint16_t data;
20+
ret = i2c_read_blocking(i2c_default, I2C_ADDRESS, (uint8_t*)&data, 2, false);
21+
assert(ret == 2);
22+
if (ret != 2) return 0;
23+
return ByteSwap(data);
24+
}
25+
26+
int main() {
27+
setup_default_uart();
28+
printf("ina260 test\n");
29+
30+
// Initialise i2c
31+
i2c_init(i2c_default, 100 * 1000);
32+
gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C);
33+
gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C);
34+
gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN);
35+
gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN);
36+
37+
while(true) {
38+
39+
// Read current and convert to mA
40+
float ma = read_reg(CURRENT_REGISTER) * 1.250f;
41+
if (ma > 15000) ma = 0;
42+
// Read the voltage
43+
float v = read_reg(VOLTAGE_REGISTER) * 0.00125f;
44+
// Read power and convert to mW
45+
uint16_t mw = read_reg(POWER_REGISTER) * 10;
46+
47+
// Display results
48+
printf("current: %.2f mA voltage: %.2f v power: %u mW\n", ma, v, mw);
49+
sleep_ms(1000);
50+
}
51+
return 0;
52+
}

0 commit comments

Comments
 (0)