feat: 全量同步 254 个常用的 Arduino 扩展库文件

This commit is contained in:
yczpf2019
2026-01-24 16:05:38 +08:00
parent c665ba662b
commit 397b9a23a3
6878 changed files with 2732224 additions and 1 deletions

View File

@@ -0,0 +1,486 @@
/*!
* @file Adafruit_INA219.cpp
*
* @mainpage Adafruit INA219 current/power monitor IC
*
* @section intro_sec Introduction
*
* Driver for the INA219 current sensor
*
* This is a library for the Adafruit INA219 breakout
* ----> https://www.adafruit.com/product/904
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section author Author
*
* Written by Bryan Siepert and Kevin "KTOWN" Townsend for Adafruit Industries.
*
* @section license License
*
* BSD license, all text here must be included in any redistribution.
*
*/
#include "Arduino.h"
#include <Wire.h>
#include "Adafruit_INA219.h"
/*!
* @brief Instantiates a new INA219 class
* @param addr the I2C address the device can be found on. Default is 0x40
*/
Adafruit_INA219::Adafruit_INA219(uint8_t addr) {
ina219_i2caddr = addr;
ina219_currentDivider_mA = 0;
ina219_powerMultiplier_mW = 0.0f;
}
/*!
* @brief INA219 class destructor
*/
Adafruit_INA219::~Adafruit_INA219() { delete i2c_dev; }
/*!
* @brief Sets up the HW (defaults to 32V and 2A for calibration values)
* @param theWire the TwoWire object to use
* @return true: success false: Failed to start I2C
*/
bool Adafruit_INA219::begin(TwoWire *theWire) {
if (!i2c_dev) {
i2c_dev = new Adafruit_I2CDevice(ina219_i2caddr, theWire);
}
if (!i2c_dev->begin()) {
return false;
}
init();
return true;
}
/*!
* @brief begin I2C and set up the hardware
*/
void Adafruit_INA219::init() {
// Set chip to large range config values to start
setCalibration_32V_2A();
}
/*!
* @brief Gets the raw bus voltage (16-bit signed integer, so +-32767)
* @return the raw bus voltage reading
*/
int16_t Adafruit_INA219::getBusVoltage_raw() {
uint16_t value;
Adafruit_BusIO_Register bus_voltage_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_BUSVOLTAGE, 2, MSBFIRST);
_success = bus_voltage_reg.read(&value);
// Shift to the right 3 to drop CNVR and OVF and multiply by LSB
return (int16_t)((value >> 3) * 4);
}
/*!
* @brief Gets the raw shunt voltage (16-bit signed integer, so +-32767)
* @return the raw shunt voltage reading
*/
int16_t Adafruit_INA219::getShuntVoltage_raw() {
uint16_t value;
Adafruit_BusIO_Register shunt_voltage_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_SHUNTVOLTAGE, 2, MSBFIRST);
_success = shunt_voltage_reg.read(&value);
return value;
}
/*!
* @brief Gets the raw current value (16-bit signed integer, so +-32767)
* @return the raw current reading
*/
int16_t Adafruit_INA219::getCurrent_raw() {
uint16_t value;
// Sometimes a sharp load will reset the INA219, which will
// reset the cal register, meaning CURRENT and POWER will
// not be available ... avoid this by always setting a cal
// value even if it's an unfortunate extra step
Adafruit_BusIO_Register calibration_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CALIBRATION, 2, MSBFIRST);
calibration_reg.write(ina219_calValue, 2);
// Now we can safely read the CURRENT register!
Adafruit_BusIO_Register current_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CURRENT, 2, MSBFIRST);
_success = current_reg.read(&value);
return value;
}
/*!
* @brief Gets the raw power value (16-bit signed integer, so +-32767)
* @return raw power reading
*/
int16_t Adafruit_INA219::getPower_raw() {
uint16_t value;
// Sometimes a sharp load will reset the INA219, which will
// reset the cal register, meaning CURRENT and POWER will
// not be available ... avoid this by always setting a cal
// value even if it's an unfortunate extra step
Adafruit_BusIO_Register calibration_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CALIBRATION, 2, MSBFIRST);
calibration_reg.write(ina219_calValue, 2);
// Now we can safely read the POWER register!
Adafruit_BusIO_Register power_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_POWER, 2, MSBFIRST);
_success = power_reg.read(&value);
return value;
}
/*!
* @brief Gets the shunt voltage in mV (so +-327mV)
* @return the shunt voltage converted to millivolts
*/
float Adafruit_INA219::getShuntVoltage_mV() {
int16_t value;
value = getShuntVoltage_raw();
return value * 0.01;
}
/*!
* @brief Gets the shunt voltage in volts
* @return the bus voltage converted to volts
*/
float Adafruit_INA219::getBusVoltage_V() {
int16_t value = getBusVoltage_raw();
return value * 0.001;
}
/*!
* @brief Gets the current value in mA, taking into account the
* config settings and current LSB
* @return the current reading convereted to milliamps
*/
float Adafruit_INA219::getCurrent_mA() {
float valueDec = getCurrent_raw();
valueDec /= ina219_currentDivider_mA;
return valueDec;
}
/*!
* @brief Gets the power value in mW, taking into account the
* config settings and current LSB
* @return power reading converted to milliwatts
*/
float Adafruit_INA219::getPower_mW() {
float valueDec = getPower_raw();
valueDec *= ina219_powerMultiplier_mW;
return valueDec;
}
/*!
* @brief Configures to INA219 to be able to measure up to 32V and 2A
* of current. Each unit of current corresponds to 100uA, and
* each unit of power corresponds to 2mW. Counter overflow
* occurs at 3.2A.
* @note These calculations assume a 0.1 ohm resistor is present
*/
void Adafruit_INA219::setCalibration_32V_2A() {
// By default we use a pretty huge range for the input voltage,
// which probably isn't the most appropriate choice for system
// that don't use a lot of power. But all of the calculations
// are shown below if you want to change the settings. You will
// also need to change any relevant register settings, such as
// setting the VBUS_MAX to 16V instead of 32V, etc.
// VBUS_MAX = 32V (Assumes 32V, can also be set to 16V)
// VSHUNT_MAX = 0.32 (Assumes Gain 8, 320mV, can also be 0.16, 0.08,
// 0.04) RSHUNT = 0.1 (Resistor value in ohms)
// 1. Determine max possible current
// MaxPossible_I = VSHUNT_MAX / RSHUNT
// MaxPossible_I = 3.2A
// 2. Determine max expected current
// MaxExpected_I = 2.0A
// 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
// MinimumLSB = MaxExpected_I/32767
// MinimumLSB = 0.000061 (61uA per bit)
// MaximumLSB = MaxExpected_I/4096
// MaximumLSB = 0,000488 (488uA per bit)
// 4. Choose an LSB between the min and max values
// (Preferrably a roundish number close to MinLSB)
// CurrentLSB = 0.0001 (100uA per bit)
// 5. Compute the calibration register
// Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
// Cal = 4096 (0x1000)
ina219_calValue = 4096;
// 6. Calculate the power LSB
// PowerLSB = 20 * CurrentLSB
// PowerLSB = 0.002 (2mW per bit)
// 7. Compute the maximum current and shunt voltage values before overflow
//
// Max_Current = Current_LSB * 32767
// Max_Current = 3.2767A before overflow
//
// If Max_Current > Max_Possible_I then
// Max_Current_Before_Overflow = MaxPossible_I
// Else
// Max_Current_Before_Overflow = Max_Current
// End If
//
// Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
// Max_ShuntVoltage = 0.32V
//
// If Max_ShuntVoltage >= VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Else
// Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
// End If
// 8. Compute the Maximum Power
// MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
// MaximumPower = 3.2 * 32V
// MaximumPower = 102.4W
// Set multipliers to convert raw current/power values
ina219_currentDivider_mA = 10; // Current LSB = 100uA per bit (1000/100 = 10)
ina219_powerMultiplier_mW = 2; // Power LSB = 1mW per bit (2/1)
// Set Calibration register to 'Cal' calculated above
Adafruit_BusIO_Register calibration_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CALIBRATION, 2, MSBFIRST);
calibration_reg.write(ina219_calValue, 2);
// Set Config register to take into account the settings above
uint16_t config = INA219_CONFIG_BVOLTAGERANGE_32V |
INA219_CONFIG_GAIN_8_320MV | INA219_CONFIG_BADCRES_12BIT |
INA219_CONFIG_SADCRES_12BIT_1S_532US |
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
Adafruit_BusIO_Register config_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CONFIG, 2, MSBFIRST);
_success = config_reg.write(config, 2);
}
/*!
* @brief Set power save mode according to parameters
* @param on
* boolean value
*/
void Adafruit_INA219::powerSave(bool on) {
Adafruit_BusIO_Register config_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CONFIG, 2, MSBFIRST);
Adafruit_BusIO_RegisterBits mode_bits =
Adafruit_BusIO_RegisterBits(&config_reg, 3, 0);
if (on) {
_success = mode_bits.write(INA219_CONFIG_MODE_POWERDOWN);
} else {
_success = mode_bits.write(INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS);
}
}
/*!
* @brief Configures to INA219 to be able to measure up to 32V and 1A
* of current. Each unit of current corresponds to 40uA, and each
* unit of power corresponds to 800uW. Counter overflow occurs at
* 1.3A.
* @note These calculations assume a 0.1 ohm resistor is present
*/
void Adafruit_INA219::setCalibration_32V_1A() {
// By default we use a pretty huge range for the input voltage,
// which probably isn't the most appropriate choice for system
// that don't use a lot of power. But all of the calculations
// are shown below if you want to change the settings. You will
// also need to change any relevant register settings, such as
// setting the VBUS_MAX to 16V instead of 32V, etc.
// VBUS_MAX = 32V (Assumes 32V, can also be set to 16V)
// VSHUNT_MAX = 0.32 (Assumes Gain 8, 320mV, can also be 0.16, 0.08, 0.04)
// RSHUNT = 0.1 (Resistor value in ohms)
// 1. Determine max possible current
// MaxPossible_I = VSHUNT_MAX / RSHUNT
// MaxPossible_I = 3.2A
// 2. Determine max expected current
// MaxExpected_I = 1.0A
// 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
// MinimumLSB = MaxExpected_I/32767
// MinimumLSB = 0.0000305 (30.5uA per bit)
// MaximumLSB = MaxExpected_I/4096
// MaximumLSB = 0.000244 (244uA per bit)
// 4. Choose an LSB between the min and max values
// (Preferrably a roundish number close to MinLSB)
// CurrentLSB = 0.0000400 (40uA per bit)
// 5. Compute the calibration register
// Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
// Cal = 10240 (0x2800)
ina219_calValue = 10240;
// 6. Calculate the power LSB
// PowerLSB = 20 * CurrentLSB
// PowerLSB = 0.0008 (800uW per bit)
// 7. Compute the maximum current and shunt voltage values before overflow
//
// Max_Current = Current_LSB * 32767
// Max_Current = 1.31068A before overflow
//
// If Max_Current > Max_Possible_I then
// Max_Current_Before_Overflow = MaxPossible_I
// Else
// Max_Current_Before_Overflow = Max_Current
// End If
//
// ... In this case, we're good though since Max_Current is less than
// MaxPossible_I
//
// Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
// Max_ShuntVoltage = 0.131068V
//
// If Max_ShuntVoltage >= VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Else
// Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
// End If
// 8. Compute the Maximum Power
// MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
// MaximumPower = 1.31068 * 32V
// MaximumPower = 41.94176W
// Set multipliers to convert raw current/power values
ina219_currentDivider_mA = 25; // Current LSB = 40uA per bit (1000/40 = 25)
ina219_powerMultiplier_mW = 0.8f; // Power LSB = 800uW per bit
// Set Calibration register to 'Cal' calculated above
Adafruit_BusIO_Register calibration_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CALIBRATION, 2, MSBFIRST);
calibration_reg.write(ina219_calValue, 2);
// Set Config register to take into account the settings above
uint16_t config = INA219_CONFIG_BVOLTAGERANGE_32V |
INA219_CONFIG_GAIN_8_320MV | INA219_CONFIG_BADCRES_12BIT |
INA219_CONFIG_SADCRES_12BIT_1S_532US |
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
Adafruit_BusIO_Register config_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CONFIG, 2, MSBFIRST);
_success = config_reg.write(config, 2);
}
/*!
* @brief set device to alibration which uses the highest precision for
* current measurement (0.1mA), at the expense of
* only supporting 16V at 400mA max.
*/
void Adafruit_INA219::setCalibration_16V_400mA() {
// Calibration which uses the highest precision for
// current measurement (0.1mA), at the expense of
// only supporting 16V at 400mA max.
// VBUS_MAX = 16V
// VSHUNT_MAX = 0.04 (Assumes Gain 1, 40mV)
// RSHUNT = 0.1 (Resistor value in ohms)
// 1. Determine max possible current
// MaxPossible_I = VSHUNT_MAX / RSHUNT
// MaxPossible_I = 0.4A
// 2. Determine max expected current
// MaxExpected_I = 0.4A
// 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
// MinimumLSB = MaxExpected_I/32767
// MinimumLSB = 0.0000122 (12uA per bit)
// MaximumLSB = MaxExpected_I/4096
// MaximumLSB = 0.0000977 (98uA per bit)
// 4. Choose an LSB between the min and max values
// (Preferrably a roundish number close to MinLSB)
// CurrentLSB = 0.00005 (50uA per bit)
// 5. Compute the calibration register
// Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
// Cal = 8192 (0x2000)
ina219_calValue = 8192;
// 6. Calculate the power LSB
// PowerLSB = 20 * CurrentLSB
// PowerLSB = 0.001 (1mW per bit)
// 7. Compute the maximum current and shunt voltage values before overflow
//
// Max_Current = Current_LSB * 32767
// Max_Current = 1.63835A before overflow
//
// If Max_Current > Max_Possible_I then
// Max_Current_Before_Overflow = MaxPossible_I
// Else
// Max_Current_Before_Overflow = Max_Current
// End If
//
// Max_Current_Before_Overflow = MaxPossible_I
// Max_Current_Before_Overflow = 0.4
//
// Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
// Max_ShuntVoltage = 0.04V
//
// If Max_ShuntVoltage >= VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Else
// Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
// End If
//
// Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
// Max_ShuntVoltage_Before_Overflow = 0.04V
// 8. Compute the Maximum Power
// MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
// MaximumPower = 0.4 * 16V
// MaximumPower = 6.4W
// Set multipliers to convert raw current/power values
ina219_currentDivider_mA = 20; // Current LSB = 50uA per bit (1000/50 = 20)
ina219_powerMultiplier_mW = 1.0f; // Power LSB = 1mW per bit
// Set Calibration register to 'Cal' calculated above
Adafruit_BusIO_Register calibration_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CALIBRATION, 2, MSBFIRST);
calibration_reg.write(ina219_calValue, 2);
// Set Config register to take into account the settings above
uint16_t config = INA219_CONFIG_BVOLTAGERANGE_16V |
INA219_CONFIG_GAIN_1_40MV | INA219_CONFIG_BADCRES_12BIT |
INA219_CONFIG_SADCRES_12BIT_1S_532US |
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
Adafruit_BusIO_Register config_reg =
Adafruit_BusIO_Register(i2c_dev, INA219_REG_CONFIG, 2, MSBFIRST);
_success = config_reg.write(config, 2);
}
/*!
* @brief Provides the the underlying return value from the last operation
* called on the device.
* @return true: Last operation was successful false: Last operation failed
* @note For function calls that have intermediary device operations,
* e.g. calibration before read/write, only the final operation's
* result is stored.
*/
bool Adafruit_INA219::success() { return _success; }

View File

@@ -0,0 +1,183 @@
/*!
* @file Adafruit_INA219.h
*
* This is a library for the Adafruit INA219 breakout board
* ----> https://www.adafruit.com/product/904
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Written by Bryan Siepert and Kevin "KTOWN" Townsend for Adafruit Industries.
*
* BSD license, all text here must be included in any redistribution.
*
*/
#ifndef _LIB_ADAFRUIT_INA219_
#define _LIB_ADAFRUIT_INA219_
#include "Arduino.h"
#include <Adafruit_BusIO_Register.h>
#include <Adafruit_I2CDevice.h>
#include <Wire.h>
/** default I2C address **/
#define INA219_ADDRESS (0x40) // 1000000 (A0+A1=GND)
/** read **/
#define INA219_READ (0x01)
/*=========================================================================
CONFIG REGISTER (R/W)
**************************************************************************/
/** config register address **/
#define INA219_REG_CONFIG (0x00)
/** reset bit **/
#define INA219_CONFIG_RESET (0x8000) // Reset Bit
/** mask for bus voltage range **/
#define INA219_CONFIG_BVOLTAGERANGE_MASK (0x2000) // Bus Voltage Range Mask
/** bus voltage range values **/
enum {
INA219_CONFIG_BVOLTAGERANGE_16V = (0x0000), // 0-16V Range
INA219_CONFIG_BVOLTAGERANGE_32V = (0x2000), // 0-32V Range
};
/** mask for gain bits **/
#define INA219_CONFIG_GAIN_MASK (0x1800) // Gain Mask
/** values for gain bits **/
enum {
INA219_CONFIG_GAIN_1_40MV = (0x0000), // Gain 1, 40mV Range
INA219_CONFIG_GAIN_2_80MV = (0x0800), // Gain 2, 80mV Range
INA219_CONFIG_GAIN_4_160MV = (0x1000), // Gain 4, 160mV Range
INA219_CONFIG_GAIN_8_320MV = (0x1800), // Gain 8, 320mV Range
};
/** mask for bus ADC resolution bits **/
#define INA219_CONFIG_BADCRES_MASK (0x0780)
/** values for bus ADC resolution **/
enum {
INA219_CONFIG_BADCRES_9BIT = (0x0000), // 9-bit bus res = 0..511
INA219_CONFIG_BADCRES_10BIT = (0x0080), // 10-bit bus res = 0..1023
INA219_CONFIG_BADCRES_11BIT = (0x0100), // 11-bit bus res = 0..2047
INA219_CONFIG_BADCRES_12BIT = (0x0180), // 12-bit bus res = 0..4097
INA219_CONFIG_BADCRES_12BIT_2S_1060US =
(0x0480), // 2 x 12-bit bus samples averaged together
INA219_CONFIG_BADCRES_12BIT_4S_2130US =
(0x0500), // 4 x 12-bit bus samples averaged together
INA219_CONFIG_BADCRES_12BIT_8S_4260US =
(0x0580), // 8 x 12-bit bus samples averaged together
INA219_CONFIG_BADCRES_12BIT_16S_8510US =
(0x0600), // 16 x 12-bit bus samples averaged together
INA219_CONFIG_BADCRES_12BIT_32S_17MS =
(0x0680), // 32 x 12-bit bus samples averaged together
INA219_CONFIG_BADCRES_12BIT_64S_34MS =
(0x0700), // 64 x 12-bit bus samples averaged together
INA219_CONFIG_BADCRES_12BIT_128S_69MS =
(0x0780), // 128 x 12-bit bus samples averaged together
};
/** mask for shunt ADC resolution bits **/
#define INA219_CONFIG_SADCRES_MASK \
(0x0078) // Shunt ADC Resolution and Averaging Mask
/** values for shunt ADC resolution **/
enum {
INA219_CONFIG_SADCRES_9BIT_1S_84US = (0x0000), // 1 x 9-bit shunt sample
INA219_CONFIG_SADCRES_10BIT_1S_148US = (0x0008), // 1 x 10-bit shunt sample
INA219_CONFIG_SADCRES_11BIT_1S_276US = (0x0010), // 1 x 11-bit shunt sample
INA219_CONFIG_SADCRES_12BIT_1S_532US = (0x0018), // 1 x 12-bit shunt sample
INA219_CONFIG_SADCRES_12BIT_2S_1060US =
(0x0048), // 2 x 12-bit shunt samples averaged together
INA219_CONFIG_SADCRES_12BIT_4S_2130US =
(0x0050), // 4 x 12-bit shunt samples averaged together
INA219_CONFIG_SADCRES_12BIT_8S_4260US =
(0x0058), // 8 x 12-bit shunt samples averaged together
INA219_CONFIG_SADCRES_12BIT_16S_8510US =
(0x0060), // 16 x 12-bit shunt samples averaged together
INA219_CONFIG_SADCRES_12BIT_32S_17MS =
(0x0068), // 32 x 12-bit shunt samples averaged together
INA219_CONFIG_SADCRES_12BIT_64S_34MS =
(0x0070), // 64 x 12-bit shunt samples averaged together
INA219_CONFIG_SADCRES_12BIT_128S_69MS =
(0x0078), // 128 x 12-bit shunt samples averaged together
};
/** mask for operating mode bits **/
#define INA219_CONFIG_MODE_MASK (0x0007) // Operating Mode Mask
/** values for operating mode **/
enum {
INA219_CONFIG_MODE_POWERDOWN = 0x00, /**< power down */
INA219_CONFIG_MODE_SVOLT_TRIGGERED = 0x01, /**< shunt voltage triggered */
INA219_CONFIG_MODE_BVOLT_TRIGGERED = 0x02, /**< bus voltage triggered */
INA219_CONFIG_MODE_SANDBVOLT_TRIGGERED =
0x03, /**< shunt and bus voltage triggered */
INA219_CONFIG_MODE_ADCOFF = 0x04, /**< ADC off */
INA219_CONFIG_MODE_SVOLT_CONTINUOUS = 0x05, /**< shunt voltage continuous */
INA219_CONFIG_MODE_BVOLT_CONTINUOUS = 0x06, /**< bus voltage continuous */
INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS =
0x07, /**< shunt and bus voltage continuous */
};
/** shunt voltage register **/
#define INA219_REG_SHUNTVOLTAGE (0x01)
/** bus voltage register **/
#define INA219_REG_BUSVOLTAGE (0x02)
/** power register **/
#define INA219_REG_POWER (0x03)
/** current register **/
#define INA219_REG_CURRENT (0x04)
/** calibration register **/
#define INA219_REG_CALIBRATION (0x05)
/*!
* @brief Class that stores state and functions for interacting with INA219
* current/power monitor IC
*/
class Adafruit_INA219 {
public:
Adafruit_INA219(uint8_t addr = INA219_ADDRESS);
~Adafruit_INA219();
bool begin(TwoWire *theWire = &Wire);
void setCalibration_32V_2A();
void setCalibration_32V_1A();
void setCalibration_16V_400mA();
float getBusVoltage_V();
float getShuntVoltage_mV();
float getCurrent_mA();
float getPower_mW();
void powerSave(bool on);
bool success();
private:
Adafruit_I2CDevice *i2c_dev = NULL;
bool _success;
uint8_t ina219_i2caddr = -1;
uint32_t ina219_calValue;
// The following multipliers are used to convert raw current and power
// values to mA and mW, taking into account the current config settings
uint32_t ina219_currentDivider_mA;
float ina219_powerMultiplier_mW;
void init();
int16_t getBusVoltage_raw();
int16_t getShuntVoltage_raw();
int16_t getCurrent_raw();
int16_t getPower_raw();
};
#endif

View File

@@ -0,0 +1,16 @@
# Adafruit INA219 Library [![Build Status](https://github.com/adafruit/Adafruit_INA219/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_INA219/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit_INA219/html/index.html)
<a href="https://www.adafruit.com/products/904"><img src="assets/board.jpg" width="500px" /></a>
This is a library for the Adafruit INA219 high side DC current sensor boards:
* https://www.adafruit.com/products/904
* https://www.adafruit.com/product/3650
Check out the links above for our tutorials and wiring diagrams. This chip uses I2C to communicate.
To install, use the Arduino Library Manager and search for 'Adafruit INA219' and install the library.
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Ktown for Adafruit Industries.
MIT license, all text above must be included in any redistribution

View File

@@ -0,0 +1,127 @@
# Adafruit Community Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and leaders pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level or type of
experience, education, socio-economic status, nationality, personal appearance,
race, religion, or sexual identity and orientation.
## Our Standards
We are committed to providing a friendly, safe and welcoming environment for
all.
Examples of behavior that contributes to creating a positive environment
include:
* Be kind and courteous to others
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Collaborating with other community members
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and sexual attention or advances
* The use of inappropriate images, including in a community member's avatar
* The use of inappropriate language, including in a community member's nickname
* Any spamming, flaming, baiting or other attention-stealing behavior
* Excessive or unwelcome helping; answering outside the scope of the question
asked
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate
The goal of the standards and moderation guidelines outlined here is to build
and maintain a respectful community. We ask that you dont just aim to be
"technically unimpeachable", but rather try to be your best self.
We value many things beyond technical expertise, including collaboration and
supporting others within our community. Providing a positive experience for
other community members can have a much more significant impact than simply
providing the correct answer.
## Our Responsibilities
Project leaders are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project leaders have the right and responsibility to remove, edit, or
reject messages, comments, commits, code, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any community member for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## Moderation
Instances of behaviors that violate the Adafruit Community Code of Conduct
may be reported by any member of the community. Community members are
encouraged to report these situations, including situations they witness
involving other community members.
You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel
to all Community Helpers by tagging @community helpers. You may also send an
open message from any channel, or a direct message to @kattni#1507,
@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or
@Andon#8175.
Email and direct message reports will be kept confidential.
In situations on Discord where the issue is particularly egregious, possibly
illegal, requires immediate action, or violates the Discord terms of service,
you should also report the message directly to Discord.
These are the steps for upholding our communitys standards of conduct.
1. Any member of the community may report any situation that violates the
Adafruit Community Code of Conduct. All reports will be reviewed and
investigated.
2. If the behavior is an egregious violation, the community member who
committed the violation may be banned immediately, without warning.
3. Otherwise, moderators will first respond to such behavior with a warning.
4. Moderators follow a soft "three strikes" policy - the community member may
be given another chance, if they are receptive to the warning and change their
behavior.
5. If the community member is unreceptive or unreasonable when warned by a
moderator, or the warning goes unheeded, they may be banned for a first or
second offense. Repeated offenses will result in the community member being
banned.
## Scope
This Code of Conduct and the enforcement policies listed above apply to all
Adafruit Community venues. This includes but is not limited to any community
spaces (both public and private), the entire Adafruit Discord server, and
Adafruit GitHub repositories. Examples of Adafruit Community spaces include
but are not limited to meet-ups, audio chats on the Adafruit Discord, or
interaction at a conference.
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. As a community
member, you are representing our community, and are expected to behave
accordingly.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4, available at
<https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>,
and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html).
For other projects adopting the Adafruit Community Code of
Conduct, please contact the maintainers of those projects for enforcement.
If you wish to use this code of conduct for your own project, consider
explicitly mentioning your moderation policy or making a copy with your
own moderation policy so as to avoid confusion.

View File

@@ -0,0 +1,56 @@
#include <Wire.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;
void setup(void)
{
Serial.begin(115200);
while (!Serial) {
// will pause Zero, Leonardo, etc until serial console opens
delay(1);
}
uint32_t currentFrequency;
Serial.println("Hello!");
// Initialize the INA219.
// By default the initialization will use the largest range (32V, 2A). However
// you can call a setCalibration function to change this range (see comments).
if (! ina219.begin()) {
Serial.println("Failed to find INA219 chip");
while (1) { delay(10); }
}
// To use a slightly lower 32V, 1A range (higher precision on amps):
//ina219.setCalibration_32V_1A();
// Or to use a lower 16V, 400mA range (higher precision on volts and amps):
//ina219.setCalibration_16V_400mA();
Serial.println("Measuring voltage and current with INA219 ...");
}
void loop(void)
{
float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float loadvoltage = 0;
float power_mW = 0;
shuntvoltage = ina219.getShuntVoltage_mV();
busvoltage = ina219.getBusVoltage_V();
current_mA = ina219.getCurrent_mA();
power_mW = ina219.getPower_mW();
loadvoltage = busvoltage + (shuntvoltage / 1000);
Serial.print("Bus Voltage: "); Serial.print(busvoltage); Serial.println(" V");
Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
Serial.print("Load Voltage: "); Serial.print(loadvoltage); Serial.println(" V");
Serial.print("Current: "); Serial.print(current_mA); Serial.println(" mA");
Serial.print("Power: "); Serial.print(power_mW); Serial.println(" mW");
Serial.println("");
delay(2000);
}

View File

@@ -0,0 +1,259 @@
// Feather Power Meter
//
// Small Feather-based power monitor using an INA219 breakout and
// monochrome OLED display.
//
// Author: Tony DiCola (modded by ladyada)
//
// Released under a MIT license: http://opensource.org/licenses/MIT
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_NeoPixel.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
// Configure orientation of the display.
// 0 = none, 1 = 90 degrees clockwise, 2 = 180 degrees, 3 = 270 degrees CW
#define ROTATION 0
#define NEO_PIN 6
// Create NeoPixel, OLED and INA219 globals.
Adafruit_SSD1306 display;
Adafruit_INA219 ina219;
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(144, NEO_PIN, NEO_GRB + NEO_KHZ800);
// Keep track of total time and milliamp measurements for milliamp-hour computation.
uint32_t total_sec = 0;
float total_mA = 0.0;
uint8_t counter = 0;
void pixel_show_and_powerupdate() {
pixels.show();
if (counter == 0) {
update_power_display();
} else {
counter = (counter+1) % 10 ;
}
}
void setup() {
Serial.begin(115200);
while (!Serial) {
// will pause Zero, Leonardo, etc until serial console opens
delay(1);
}
pixels.begin();
pixels.show(); // Initialize all pixels to 'off'
// Try to initialize the INA219
if (! ina219.begin()) {
Serial.println("Failed to find INA219 chip");
while (1) { delay(10); }
}
// By default the INA219 will be calibrated with a range of 32V, 2A.
// However uncomment one of the below to change the range. A smaller
// range can't measure as large of values but will measure with slightly
// better precision.
//ina219.setCalibration_32V_1A();
//ina219.setCalibration_16V_400mA();
// Setup the OLED display.
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
Wire.setClock(400000);
// Clear the display.
display.clearDisplay();
display.display();
// Set rotation.
display.setRotation(ROTATION);
// Set text size and color.
display.setTextSize(2);
display.setTextColor(WHITE);
}
void loop() {
// Some example procedures showing how to display to the pixels:
colorWipe(pixels.Color(255, 0, 0), 50); // Red
colorWipe(pixels.Color(0, 255, 0), 50); // Green
colorWipe(pixels.Color(0, 0, 255), 50); // Blue
//colorWipe(pixels.Color(0, 0, 0, 255), 50); // White RGBW
// Send a theater pixel chase in...
theaterChase(pixels.Color(127, 127, 127), 50); // White
theaterChase(pixels.Color(127, 0, 0), 50); // Red
theaterChase(pixels.Color(0, 0, 127), 50); // Blue
rainbow(20);
rainbowCycle(20);
theaterChaseRainbow(50);
}
// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i<pixels.numPixels(); i++) {
pixels.setPixelColor(i, c);
pixel_show_and_powerupdate();
delay(wait);
}
}
void rainbow(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256; j++) {
for(i=0; i<pixels.numPixels(); i++) {
pixels.setPixelColor(i, Wheel((i+j) & 255));
}
pixel_show_and_powerupdate();
delay(wait);
}
}
// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
for(i=0; i< pixels.numPixels(); i++) {
pixels.setPixelColor(i, Wheel(((i * 256 / pixels.numPixels()) + j) & 255));
}
pixel_show_and_powerupdate();
delay(wait);
}
}
//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
for (int j=0; j<10; j++) { //do 10 cycles of chasing
for (int q=0; q < 3; q++) {
for (uint16_t i=0; i < pixels.numPixels(); i=i+3) {
pixels.setPixelColor(i+q, c); //turn every third pixel on
}
pixel_show_and_powerupdate();
delay(wait);
for (uint16_t i=0; i < pixels.numPixels(); i=i+3) {
pixels.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
for (int j=0; j < 256; j++) { // cycle all 256 colors in the wheel
for (int q=0; q < 3; q++) {
for (uint16_t i=0; i < pixels.numPixels(); i=i+3) {
pixels.setPixelColor(i+q, Wheel( (i+j) % 255)); //turn every third pixel on
}
pixel_show_and_powerupdate();
delay(wait);
for (uint16_t i=0; i < pixels.numPixels(); i=i+3) {
pixels.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3);
}
if(WheelPos < 170) {
WheelPos -= 85;
return pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
void update_power_display() {
// Read voltage and current from INA219.
float shuntvoltage = ina219.getShuntVoltage_mV();
float busvoltage = ina219.getBusVoltage_V();
float current_mA = ina219.getCurrent_mA();
// Compute load voltage, power, and milliamp-hours.
float loadvoltage = busvoltage + (shuntvoltage / 1000);
float power_mW = loadvoltage * current_mA;
total_mA += current_mA;
total_sec += 1;
float total_mAH = total_mA / 3600.0;
// Update display.
display.clearDisplay();
display.setCursor(0,0);
// Mode 0, display volts and amps.
printSIValue(loadvoltage, "V:", 2, 10);
display.setCursor(0, 16);
printSIValue(current_mA/1000.0, "A:", 5, 10);
display.display();
}
void printSIValue(float value, char* units, int precision, int maxWidth) {
// Print a value in SI units with the units left justified and value right justified.
// Will switch to milli prefix if value is below 1.
// Add milli prefix if low value.
if (fabs(value) < 1.0) {
display.print('m');
maxWidth -= 1;
value *= 1000.0;
precision = max(0, precision-3);
}
// Print units.
display.print(units);
maxWidth -= strlen(units);
// Leave room for negative sign if value is negative.
if (value < 0.0) {
maxWidth -= 1;
}
// Find how many digits are in value.
int digits = ceil(log10(fabs(value)));
if (fabs(value) < 1.0) {
digits = 1; // Leave room for 0 when value is below 0.
}
// Handle if not enough width to display value, just print dashes.
if (digits > maxWidth) {
// Fill width with dashes (and add extra dash for negative values);
for (int i=0; i < maxWidth; ++i) {
display.print('-');
}
if (value < 0.0) {
display.print('-');
}
return;
}
// Compute actual precision for printed value based on space left after
// printing digits and decimal point. Clamp within 0 to desired precision.
int actualPrecision = constrain(maxWidth-digits-1, 0, precision);
// Compute how much padding to add to right justify.
int padding = maxWidth-digits-1-actualPrecision;
for (int i=0; i < padding; ++i) {
display.print(' ');
}
// Finally, print the value!
display.print(value, actualPrecision);
}

View File

@@ -0,0 +1,10 @@
name=Adafruit INA219
version=1.1.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=INA219 Current Sensor
paragraph=INA219 Current Sensor
category=Sensors
url=https://github.com/adafruit/Adafruit_INA219
architectures=*
depends=Adafruit NeoPixel, Adafruit GFX Library, Adafruit SSD1306, Adafruit BusIO

View File

@@ -0,0 +1,26 @@
Software License Agreement (BSD License)
Copyright (c) 2012, Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.