|
| 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, ®, 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