M5Unified
INA3221_Class.cpp
Go to the documentation of this file.
1 // Copyright (c) M5Stack. All rights reserved.
2 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3 
4 #include "INA3221_Class.hpp"
5 
6 #if __has_include(<esp_log.h>)
7 #include <esp_log.h>
8 #endif
9 
10 #include <algorithm>
11 
12 namespace m5
13 {
15  {
16  uint16_t id = readRegister16(0xFF);
17 #if defined (ESP_LOGV)
18  ESP_LOGV("INA3221", "regFFh:%04x", id);
19 #endif
20  _init = (id == 0x3220);
21  return _init;
22  }
23 
24  void INA3221_Class::setShuntRes(uint8_t channel, uint32_t res)
25  {
26  if (channel < INA3221_CH_NUM_MAX) {
27  _shunt_res[channel] = res;
28  }
29  }
30 
31  int_fast16_t INA3221_Class::getBusMilliVoltage(uint8_t channel)
32  {
33  int_fast16_t res = 0;
34  if (channel < INA3221_CH_NUM_MAX) {
35  res = (int16_t)readRegister16(INA3221_CH1_BUS_V + (channel * 2));
36  }
37  return res;
38  }
39 
40  int32_t INA3221_Class::getShuntMilliVoltage(uint8_t channel)
41  {
42  int32_t res = 0;
43  if (channel < INA3221_CH_NUM_MAX) {
44  res = (int16_t)readRegister16(INA3221_CH1_SHUNT_V + (channel * 2));
45  res *= 5;
46  }
47  return res;
48  }
49 
50  float INA3221_Class::getBusVoltage(uint8_t channel)
51  {
52  return getBusMilliVoltage(channel) / 1000.0f;
53  }
54 
55  float INA3221_Class::getShuntVoltage(uint8_t channel)
56  {
57  return getShuntMilliVoltage(channel) / 1000.0f;
58  }
59 
60  float INA3221_Class::getCurrent(uint8_t channel)
61  {
62  float res = 0.0f;
63  if (channel < INA3221_CH_NUM_MAX) {
64  res = getShuntVoltage(channel) / _shunt_res[channel];
65  }
66  return res;
67  }
68 
69  std::size_t INA3221_Class::readRegister16(std::uint8_t addr)
70  {
71  std::uint8_t buf[2] = {0};
72  readRegister(addr, buf, 2);
73  return buf[0] << 8 | buf[1];
74  }
75 }
bool readRegister(std::uint8_t reg, std::uint8_t *result, std::size_t length) const
Definition: I2C_Class.hpp:177
float getBusVoltage(uint8_t channel)
void setShuntRes(uint8_t channel, uint32_t res)
static constexpr std::uint8_t INA3221_CH_NUM_MAX
static constexpr uint8_t INA3221_CH1_BUS_V
static constexpr uint8_t INA3221_CH1_SHUNT_V
int_fast16_t getBusMilliVoltage(uint8_t channel)
float getShuntVoltage(uint8_t channel)
float getCurrent(uint8_t channel)
int32_t getShuntMilliVoltage(uint8_t channel)
Definition: M5Unified.cpp:48