Update Usermod Battery (#2975)
* auto-off feature and usermod rename * low-power-indicator, voltage fine tuning, clean-up * corrected small mistakes * Bugfixes, added usermod logo, update readme * minor changes, implemented change requests, optimizationz
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB |
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 46 KiB |
BIN
usermods/Battery/assets/battery_info_screen.png
Normal file
After Width: | Height: | Size: 122 KiB |
BIN
usermods/Battery/assets/battery_usermod_logo.png
Normal file
After Width: | Height: | Size: 23 KiB |
67
usermods/Battery/battery_defaults.h
Normal file
@ -0,0 +1,67 @@
|
||||
// pin defaults
|
||||
// for the esp32 it is best to use the ADC1: GPIO32 - GPIO39
|
||||
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html
|
||||
#ifndef USERMOD_BATTERY_MEASUREMENT_PIN
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#define USERMOD_BATTERY_MEASUREMENT_PIN 35
|
||||
#else //ESP8266 boards
|
||||
#define USERMOD_BATTERY_MEASUREMENT_PIN A0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// the frequency to check the battery, 30 sec
|
||||
#ifndef USERMOD_BATTERY_MEASUREMENT_INTERVAL
|
||||
#define USERMOD_BATTERY_MEASUREMENT_INTERVAL 30000
|
||||
#endif
|
||||
|
||||
// default for 18650 battery
|
||||
// https://batterybro.com/blogs/18650-wholesale-battery-reviews/18852515-when-to-recycle-18650-batteries-and-how-to-start-a-collection-center-in-your-vape-shop
|
||||
// Discharge voltage: 2.5 volt + .1 for personal safety
|
||||
#ifndef USERMOD_BATTERY_MIN_VOLTAGE
|
||||
#define USERMOD_BATTERY_MIN_VOLTAGE 2.6f
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_MAX_VOLTAGE
|
||||
#define USERMOD_BATTERY_MAX_VOLTAGE 4.2f
|
||||
#endif
|
||||
|
||||
// a common capacity for single 18650 battery cells is between 2500 and 3600 mAh
|
||||
#ifndef USERMOD_BATTERY_TOTAL_CAPACITY
|
||||
#define USERMOD_BATTERY_TOTAL_CAPACITY 3100
|
||||
#endif
|
||||
|
||||
// offset or calibration value to fine tune the calculated voltage
|
||||
#ifndef USERMOD_BATTERY_CALIBRATION
|
||||
#define USERMOD_BATTERY_CALIBRATION 0
|
||||
#endif
|
||||
|
||||
// calculate remaining time / the time that is left before the battery runs out of power
|
||||
// #ifndef USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED
|
||||
// #define USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED false
|
||||
// #endif
|
||||
|
||||
// auto-off feature
|
||||
#ifndef USERMOD_BATTERY_AUTO_OFF_ENABLED
|
||||
#define USERMOD_BATTERY_AUTO_OFF_ENABLED true
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_AUTO_OFF_THRESHOLD
|
||||
#define USERMOD_BATTERY_AUTO_OFF_THRESHOLD 10
|
||||
#endif
|
||||
|
||||
// low power indication feature
|
||||
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED
|
||||
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED true
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET
|
||||
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET 0
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD
|
||||
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD 20
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION
|
||||
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION 5
|
||||
#endif
|
104
usermods/Battery/readme.md
Normal file
@ -0,0 +1,104 @@
|
||||
<p align="center">
|
||||
<img width="700" src="assets/battery_usermod_logo.png">
|
||||
</p>
|
||||
|
||||
# Welcome to the battery usermod! 🔋
|
||||
|
||||
Enables battery level monitoring of your project.
|
||||
|
||||
For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)).
|
||||
|
||||
If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39)
|
||||
|
||||
<p align="center">
|
||||
<img width="500" src="assets/battery_info_screen.png">
|
||||
</p>
|
||||
|
||||
## ⚙️ Features
|
||||
|
||||
- 💯 Displays current battery voltage
|
||||
- 🚥 Displays battery level
|
||||
- 🚫 Auto-off with configurable Threshold
|
||||
- 🚨 Low power indicator with many configuration posibilities
|
||||
|
||||
## 🎈 Installation
|
||||
|
||||
define `USERMOD_BATTERY` in `wled00/my_config.h`
|
||||
|
||||
### Example wiring
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="assets/battery_connection_schematic_01.png">
|
||||
</p>
|
||||
|
||||
### Define Your Options
|
||||
|
||||
| Name | Unit | Description |
|
||||
| ----------------------------------------------- | ----------- |-------------------------------------------------------------------------------------- |
|
||||
| `USERMOD_BATTERY` | | define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_PIN` | | defaults to A0 on ESP8266 and GPIO32 on ESP32 |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_INTERVAL` | ms | battery check interval. defaults to 30 seconds |
|
||||
| `USERMOD_BATTERY_MIN_VOLTAGE` | v | minimum battery voltage. default is 2.6 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_MAX_VOLTAGE` | v | maximum battery voltage. default is 4.2 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_TOTAL_CAPACITY` | mAh | the capacity of all cells in parralel sumed up |
|
||||
| `USERMOD_BATTERY_CALIBRATION` | | offset / calibration number, fine tune the measured voltage by the microcontroller |
|
||||
| Auto-Off | --- | --- |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_ENABLED` | true/false | enables auto-off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_THRESHOLD` | % (0-100) | when this threshold is reached master power turns off |
|
||||
| Low-Power-Indicator | --- | --- |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED` | true/false | enables low power indication |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET` | preset id | when low power is detected then use this preset to indicate low power |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100) | when this threshold is reached low power gets indicated |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION` | seconds | for this long the configured preset is played |
|
||||
|
||||
All parameters can be configured at runtime via the Usermods settings page.
|
||||
|
||||
## ⚠️ Important
|
||||
|
||||
- Make sure you know your battery specifications! All batteries are **NOT** the same!
|
||||
- Example:
|
||||
|
||||
| Your battery specification table | | Options you can define |
|
||||
| :-------------------------------- |:--------------- | :---------------------------- |
|
||||
| Capacity | 3500mAh 12,5 Wh | |
|
||||
| Minimum capacity | 3350mAh 11,9 Wh | |
|
||||
| Rated voltage | 3.6V - 3.7V | |
|
||||
| **Charging end voltage** | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
|
||||
| **Discharge voltage** | **2,5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
|
||||
| Max. discharge current (constant) | 10A (10000mA) | |
|
||||
| max. charging current | 1.7A (1700mA) | |
|
||||
| ... | ... | ... |
|
||||
| .. | .. | .. |
|
||||
|
||||
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
|
||||
|
||||
## 🌐 Useful Links
|
||||
|
||||
- https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start
|
||||
- https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/
|
||||
|
||||
## 📝 Change Log
|
||||
|
||||
2022-12-25
|
||||
|
||||
- added "auto-off" feature
|
||||
- added "low-power-indication" feature
|
||||
- added "calibration/offset" field to configuration page
|
||||
- added getter and setter, so that user usermods could interact with this one
|
||||
- update readme (added new options, made it markdownlint compliant)
|
||||
|
||||
2021-09-02
|
||||
|
||||
- added "Battery voltage" to info
|
||||
- added circuit diagram to readme
|
||||
- added MQTT support, sending battery voltage
|
||||
- minor fixes
|
||||
|
||||
2021-08-15
|
||||
|
||||
- changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
|
||||
- Updated readme, added specification table
|
||||
|
||||
2021-08-10
|
||||
|
||||
- Created
|
730
usermods/Battery/usermod_v2_Battery.h
Normal file
@ -0,0 +1,730 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include "battery_defaults.h"
|
||||
|
||||
/*
|
||||
* Usermod by Maximilian Mewes
|
||||
* Mail: mewes.maximilian@gmx.de
|
||||
* GitHub: itCarl
|
||||
* Date: 25.12.2022
|
||||
* If you have any questions, please feel free to contact me.
|
||||
*/
|
||||
class UsermodBattery : public Usermod
|
||||
{
|
||||
private:
|
||||
// battery pin can be defined in my_config.h
|
||||
int8_t batteryPin = USERMOD_BATTERY_MEASUREMENT_PIN;
|
||||
// how often to read the battery voltage
|
||||
unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL;
|
||||
unsigned long nextReadTime = 0;
|
||||
unsigned long lastReadTime = 0;
|
||||
// battery min. voltage
|
||||
float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE;
|
||||
// battery max. voltage
|
||||
float maxBatteryVoltage = USERMOD_BATTERY_MAX_VOLTAGE;
|
||||
// all battery cells summed up
|
||||
unsigned int totalBatteryCapacity = USERMOD_BATTERY_TOTAL_CAPACITY;
|
||||
// raw analog reading
|
||||
float rawValue = 0.0f;
|
||||
// calculated voltage
|
||||
float voltage = maxBatteryVoltage;
|
||||
// mapped battery level based on voltage
|
||||
int8_t batteryLevel = 100;
|
||||
// offset or calibration value to fine tune the calculated voltage
|
||||
float calibration = USERMOD_BATTERY_CALIBRATION;
|
||||
|
||||
// time left estimation feature
|
||||
// bool calculateTimeLeftEnabled = USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED;
|
||||
// float estimatedTimeLeft = 0.0;
|
||||
|
||||
// auto shutdown/shutoff/master off feature
|
||||
bool autoOffEnabled = USERMOD_BATTERY_AUTO_OFF_ENABLED;
|
||||
int8_t autoOffThreshold = USERMOD_BATTERY_AUTO_OFF_THRESHOLD;
|
||||
|
||||
// low power indicator feature
|
||||
bool lowPowerIndicatorEnabled = USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED;
|
||||
int8_t lowPowerIndicatorPreset = USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET;
|
||||
int8_t lowPowerIndicatorThreshold = USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD;
|
||||
int8_t lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
|
||||
int8_t lowPowerIndicatorDuration = USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION;
|
||||
bool lowPowerIndicationDone = false;
|
||||
unsigned long lowPowerActivationTime = 0; // used temporary during active time
|
||||
int8_t lastPreset = 0;
|
||||
|
||||
bool initDone = false;
|
||||
bool initializing = true;
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
static const char _name[];
|
||||
static const char _readInterval[];
|
||||
static const char _enabled[];
|
||||
static const char _threshold[];
|
||||
static const char _preset[];
|
||||
static const char _duration[];
|
||||
static const char _init[];
|
||||
|
||||
|
||||
// custom map function
|
||||
// https://forum.arduino.cc/t/floating-point-using-map-function/348113/2
|
||||
double mapf(double x, double in_min, double in_max, double out_min, double out_max)
|
||||
{
|
||||
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
|
||||
}
|
||||
|
||||
float dot2round(float x)
|
||||
{
|
||||
float nx = (int)(x * 100 + .5);
|
||||
return (float)(nx / 100);
|
||||
}
|
||||
|
||||
/*
|
||||
* Turn off all leds
|
||||
*/
|
||||
void turnOff()
|
||||
{
|
||||
bri = 0;
|
||||
stateUpdated(CALL_MODE_DIRECT_CHANGE);
|
||||
}
|
||||
|
||||
/*
|
||||
* Indicate low power by activating a configured preset for a given time and then switching back to the preset that was selected previously
|
||||
*/
|
||||
void lowPowerIndicator()
|
||||
{
|
||||
if (!lowPowerIndicatorEnabled) return;
|
||||
if (lowPowerIndicationDone && lowPowerIndicatorReactivationThreshold <= batteryLevel) lowPowerIndicationDone = false;
|
||||
if (lowPowerIndicatorThreshold <= batteryLevel) return;
|
||||
if (lowPowerIndicationDone) return;
|
||||
if (lowPowerActivationTime <= 1) {
|
||||
lowPowerActivationTime = millis();
|
||||
lastPreset = currentPreset;
|
||||
applyPreset(lowPowerIndicatorPreset);
|
||||
}
|
||||
|
||||
if (lowPowerActivationTime+(lowPowerIndicatorDuration*1000) <= millis()) {
|
||||
lowPowerIndicationDone = true;
|
||||
lowPowerActivationTime = 0;
|
||||
applyPreset(lastPreset);
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
//Functions called by WLED
|
||||
|
||||
/*
|
||||
* setup() is called once at boot. WiFi is not yet connected at this point.
|
||||
* You can use it to initialize variables, sensors or similar.
|
||||
*/
|
||||
void setup()
|
||||
{
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
bool success = false;
|
||||
DEBUG_PRINTLN(F("Allocating battery pin..."));
|
||||
if (batteryPin >= 0 && digitalPinToAnalogChannel(batteryPin) >= 0)
|
||||
if (pinManager.allocatePin(batteryPin, false, PinOwner::UM_Battery)) {
|
||||
DEBUG_PRINTLN(F("Battery pin allocation succeeded."));
|
||||
success = true;
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
DEBUG_PRINTLN(F("Battery pin allocation failed."));
|
||||
batteryPin = -1; // allocation failed
|
||||
}
|
||||
#else //ESP8266 boards have only one analog input pin A0
|
||||
|
||||
pinMode(batteryPin, INPUT);
|
||||
#endif
|
||||
|
||||
nextReadTime = millis() + readingInterval;
|
||||
lastReadTime = millis();
|
||||
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* connected() is called every time the WiFi is (re)connected
|
||||
* Use it to initialize network interfaces
|
||||
*/
|
||||
void connected()
|
||||
{
|
||||
//Serial.println("Connected to WiFi!");
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* loop() is called continuously. Here you can check for events, read sensors, etc.
|
||||
*
|
||||
*/
|
||||
void loop()
|
||||
{
|
||||
if(strip.isUpdating()) return;
|
||||
|
||||
lowPowerIndicator();
|
||||
|
||||
// check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms)
|
||||
if (millis() < nextReadTime) return;
|
||||
|
||||
nextReadTime = millis() + readingInterval;
|
||||
lastReadTime = millis();
|
||||
initializing = false;
|
||||
|
||||
// read battery raw input
|
||||
rawValue = analogRead(batteryPin);
|
||||
|
||||
// calculate the voltage
|
||||
voltage = ((rawValue / getAdcPrecision()) * maxBatteryVoltage) + calibration;
|
||||
// check if voltage is within specified voltage range
|
||||
voltage = voltage<minBatteryVoltage||voltage>maxBatteryVoltage?-1.0f:voltage;
|
||||
|
||||
// translate battery voltage into percentage
|
||||
/*
|
||||
the standard "map" function doesn't work
|
||||
https://www.arduino.cc/reference/en/language/functions/math/map/ notes and warnings at the bottom
|
||||
*/
|
||||
batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100);
|
||||
|
||||
// if (calculateTimeLeftEnabled) {
|
||||
// float currentBatteryCapacity = totalBatteryCapacity;
|
||||
// estimatedTimeLeft = (currentBatteryCapacity/strip.currentMilliamps)*60;
|
||||
// }
|
||||
|
||||
// Auto off -- Master power off
|
||||
if (autoOffEnabled && (autoOffThreshold >= batteryLevel))
|
||||
turnOff();
|
||||
|
||||
// SmartHome stuff
|
||||
// still don't know much about MQTT and/or HA
|
||||
if (WLED_MQTT_CONNECTED) {
|
||||
char buf[64]; // buffer for snprintf()
|
||||
snprintf_P(buf, 63, PSTR("/voltage"), mqttDeviceTopic);
|
||||
mqtt->publish(buf, 0, false, String(voltage).c_str());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API.
|
||||
* Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI.
|
||||
* Below it is shown how this could be used for e.g. a light sensor
|
||||
*/
|
||||
void addToJsonInfo(JsonObject& root)
|
||||
{
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull()) user = root.createNestedObject("u");
|
||||
|
||||
// info modal display names
|
||||
JsonArray infoPercentage = user.createNestedArray(F("Battery level"));
|
||||
JsonArray infoVoltage = user.createNestedArray(F("Battery voltage"));
|
||||
// if (calculateTimeLeftEnabled)
|
||||
// {
|
||||
// JsonArray infoEstimatedTimeLeft = user.createNestedArray(F("Estimated time left"));
|
||||
// if (initializing) {
|
||||
// infoEstimatedTimeLeft.add(FPSTR(_init));
|
||||
// } else {
|
||||
// infoEstimatedTimeLeft.add(estimatedTimeLeft);
|
||||
// infoEstimatedTimeLeft.add(F(" min"));
|
||||
// }
|
||||
// }
|
||||
JsonArray infoNextUpdate = user.createNestedArray(F("Next update"));
|
||||
|
||||
infoNextUpdate.add((nextReadTime - millis()) / 1000);
|
||||
infoNextUpdate.add(F(" sec"));
|
||||
|
||||
if (initializing) {
|
||||
infoPercentage.add(FPSTR(_init));
|
||||
infoVoltage.add(FPSTR(_init));
|
||||
return;
|
||||
}
|
||||
|
||||
if (batteryLevel < 0) {
|
||||
infoPercentage.add(F("invalid"));
|
||||
} else {
|
||||
infoPercentage.add(batteryLevel);
|
||||
}
|
||||
infoPercentage.add(F(" %"));
|
||||
|
||||
if (voltage < 0) {
|
||||
infoVoltage.add(F("invalid"));
|
||||
} else {
|
||||
infoVoltage.add(dot2round(voltage));
|
||||
}
|
||||
infoVoltage.add(F(" V"));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
|
||||
* Values in the state object may be modified by connected clients
|
||||
*/
|
||||
/*
|
||||
void addToJsonState(JsonObject& root)
|
||||
{
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
|
||||
* Values in the state object may be modified by connected clients
|
||||
*/
|
||||
/*
|
||||
void readFromJsonState(JsonObject& root)
|
||||
{
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object.
|
||||
* It will be called by WLED when settings are actually saved (for example, LED settings are saved)
|
||||
* If you want to force saving the current state, use serializeConfig() in your loop().
|
||||
*
|
||||
* CAUTION: serializeConfig() will initiate a filesystem write operation.
|
||||
* It might cause the LEDs to stutter and will cause flash wear if called too often.
|
||||
* Use it sparingly and always in the loop, never in network callbacks!
|
||||
*
|
||||
* addToConfig() will make your settings editable through the Usermod Settings page automatically.
|
||||
*
|
||||
* Usermod Settings Overview:
|
||||
* - Numeric values are treated as floats in the browser.
|
||||
* - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float
|
||||
* before being returned to the Usermod. The float data type has only 6-7 decimal digits of precision, and
|
||||
* doubles are not supported, numbers will be rounded to the nearest float value when being parsed.
|
||||
* The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38.
|
||||
* - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a
|
||||
* C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod.
|
||||
* Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type
|
||||
* used in the Usermod when reading the value from ArduinoJson.
|
||||
* - Pin values can be treated differently from an integer value by using the key name "pin"
|
||||
* - "pin" can contain a single or array of integer values
|
||||
* - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins
|
||||
* - Red color indicates a conflict. Yellow color indicates a pin with a warning (e.g. an input-only pin)
|
||||
* - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used
|
||||
*
|
||||
* See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings
|
||||
*
|
||||
* If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work.
|
||||
* You will have to add the setting to the HTML, xml.cpp and set.cpp manually.
|
||||
* See the WLED Soundreactive fork (code and wiki) for reference. https://github.com/atuline/WLED
|
||||
*
|
||||
* I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings!
|
||||
*/
|
||||
void addToConfig(JsonObject& root)
|
||||
{
|
||||
JsonObject battery = root.createNestedObject(FPSTR(_name)); // usermodname
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
battery["pin"] = batteryPin;
|
||||
#endif
|
||||
|
||||
// battery[F("time-left")] = calculateTimeLeftEnabled;
|
||||
battery[F("min-voltage")] = minBatteryVoltage;
|
||||
battery[F("max-voltage")] = maxBatteryVoltage;
|
||||
battery[F("capacity")] = totalBatteryCapacity;
|
||||
battery[F("calibration")] = calibration;
|
||||
battery[FPSTR(_readInterval)] = readingInterval;
|
||||
|
||||
JsonObject ao = battery.createNestedObject(F("auto-off")); // auto off section
|
||||
ao[FPSTR(_enabled)] = autoOffEnabled;
|
||||
ao[FPSTR(_threshold)] = autoOffThreshold;
|
||||
|
||||
JsonObject lp = battery.createNestedObject(F("indicator")); // low power section
|
||||
lp[FPSTR(_enabled)] = lowPowerIndicatorEnabled;
|
||||
lp[FPSTR(_preset)] = lowPowerIndicatorPreset; // dropdown trickery (String)lowPowerIndicatorPreset;
|
||||
lp[FPSTR(_threshold)] = lowPowerIndicatorThreshold;
|
||||
lp[FPSTR(_duration)] = lowPowerIndicatorDuration;
|
||||
|
||||
DEBUG_PRINTLN(F("Battery config saved."));
|
||||
}
|
||||
|
||||
void appendConfigData()
|
||||
{
|
||||
oappend(SET_F("addInfo('Battery:min-voltage', 1, 'v');"));
|
||||
oappend(SET_F("addInfo('Battery:max-voltage', 1, 'v');"));
|
||||
oappend(SET_F("addInfo('Battery:capacity', 1, 'mAh');"));
|
||||
oappend(SET_F("addInfo('Battery:interval', 1, 'ms');"));
|
||||
oappend(SET_F("addInfo('Battery:auto-off:threshold', 1, '%');"));
|
||||
oappend(SET_F("addInfo('Battery:indicator:threshold', 1, '%');"));
|
||||
oappend(SET_F("addInfo('Battery:indicator:duration', 1, 's');"));
|
||||
|
||||
// cannot quite get this mf to work. its exeeding some buffer limit i think
|
||||
// what i wanted is a list of all presets to select one from
|
||||
// oappend(SET_F("bd=addDropdown('Battery:low-power-indicator', 'preset');"));
|
||||
// the loop generates: oappend(SET_F("addOption(bd, 'preset name', preset id);"));
|
||||
// for(int8_t i=1; i < 42; i++) {
|
||||
// oappend(SET_F("addOption(bd, 'Preset#"));
|
||||
// oappendi(i);
|
||||
// oappend(SET_F("',"));
|
||||
// oappendi(i);
|
||||
// oappend(SET_F(");"));
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* readFromConfig() can be used to read back the custom settings you added with addToConfig().
|
||||
* This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page)
|
||||
*
|
||||
* readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes),
|
||||
* but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup.
|
||||
* If you don't know what that is, don't fret. It most likely doesn't affect your use case :)
|
||||
*
|
||||
* Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings)
|
||||
*
|
||||
* getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present
|
||||
* The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them
|
||||
*
|
||||
* This function is guaranteed to be called on boot, but could also be called every time settings are updated
|
||||
*/
|
||||
bool readFromConfig(JsonObject& root)
|
||||
{
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
int8_t newBatteryPin = batteryPin;
|
||||
#endif
|
||||
|
||||
JsonObject battery = root[FPSTR(_name)];
|
||||
if (battery.isNull())
|
||||
{
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
newBatteryPin = battery[F("pin"] | newBatteryPin;
|
||||
#endif
|
||||
// calculateTimeLeftEnabled = battery[F("time-left")] | calculateTimeLeftEnabled;
|
||||
setMinBatteryVoltage(battery[F("min-Voltage")] | minBatteryVoltage);
|
||||
setMaxBatteryVoltage(battery[F("max-Voltage")] | maxBatteryVoltage);
|
||||
setTotalBatteryCapacity(battery[F("capacity")] | totalBatteryCapacity);
|
||||
setCalibration(battery[F("calibration")] | calibration);
|
||||
setReadingInterval(battery[FPSTR(_readInterval)] | readingInterval);
|
||||
|
||||
JsonObject ao = battery[F("auto-off")];
|
||||
setAutoOffEnabled(ao[FPSTR(_enabled)] | autoOffEnabled);
|
||||
setAutoOffThreshold(ao[FPSTR(_threshold)] | autoOffThreshold);
|
||||
|
||||
JsonObject lp = battery[F("indicator")];
|
||||
setLowPowerIndicatorEnabled(lp[FPSTR(_enabled)] | lowPowerIndicatorEnabled);
|
||||
setLowPowerIndicatorPreset(lp[FPSTR(_preset)] | lowPowerIndicatorPreset); // dropdown trickery (int)lp["preset"]
|
||||
setLowPowerIndicatorThreshold(lp[FPSTR(_threshold)] | lowPowerIndicatorThreshold);
|
||||
lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
|
||||
setLowPowerIndicatorDuration(lp[FPSTR(_duration)] | lowPowerIndicatorDuration);
|
||||
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if (!initDone)
|
||||
{
|
||||
// first run: reading from cfg.json
|
||||
newBatteryPin = batteryPin;
|
||||
DEBUG_PRINTLN(F(" config loaded."));
|
||||
}
|
||||
else
|
||||
{
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
|
||||
// changing paramters from settings page
|
||||
if (newBatteryPin != batteryPin)
|
||||
{
|
||||
// deallocate pin
|
||||
pinManager.deallocatePin(batteryPin);
|
||||
batteryPin = newBatteryPin;
|
||||
// initialise
|
||||
setup();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return !battery[FPSTR(_readInterval)].isNull();
|
||||
}
|
||||
|
||||
/*
|
||||
* Generate a preset sample for low power indication
|
||||
*/
|
||||
void generateExamplePreset()
|
||||
{
|
||||
// StaticJsonDocument<300> j;
|
||||
// JsonObject preset = j.createNestedObject();
|
||||
// preset["mainseg"] = 0;
|
||||
// JsonArray seg = preset.createNestedArray("seg");
|
||||
// JsonObject seg0 = seg.createNestedObject();
|
||||
// seg0["id"] = 0;
|
||||
// seg0["start"] = 0;
|
||||
// seg0["stop"] = 60;
|
||||
// seg0["grp"] = 0;
|
||||
// seg0["spc"] = 0;
|
||||
// seg0["on"] = true;
|
||||
// seg0["bri"] = 255;
|
||||
|
||||
// JsonArray col0 = seg0.createNestedArray("col");
|
||||
// JsonArray col00 = col0.createNestedArray();
|
||||
// col00.add(255);
|
||||
// col00.add(0);
|
||||
// col00.add(0);
|
||||
|
||||
// seg0["fx"] = 1;
|
||||
// seg0["sx"] = 128;
|
||||
// seg0["ix"] = 128;
|
||||
|
||||
// savePreset(199, "Low power Indicator", preset);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* Getter and Setter. Just in case some other usermod wants to interact with this in the future
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
|
||||
* This could be used in the future for the system to determine whether your usermod is installed.
|
||||
*/
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_BATTERY;
|
||||
}
|
||||
|
||||
|
||||
unsigned long getReadingInterval()
|
||||
{
|
||||
return readingInterval;
|
||||
}
|
||||
|
||||
/*
|
||||
* minimum repetition is 3000ms (3s)
|
||||
*/
|
||||
void setReadingInterval(unsigned long newReadingInterval)
|
||||
{
|
||||
readingInterval = max((unsigned long)3000, newReadingInterval);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get lowest configured battery voltage
|
||||
*/
|
||||
float getMinBatteryVoltage()
|
||||
{
|
||||
return minBatteryVoltage;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set lowest battery voltage
|
||||
* can't be below 0 volt
|
||||
*/
|
||||
void setMinBatteryVoltage(float voltage)
|
||||
{
|
||||
minBatteryVoltage = max(0.0f, voltage);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get highest configured battery voltage
|
||||
*/
|
||||
float getMaxBatteryVoltage()
|
||||
{
|
||||
return maxBatteryVoltage;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set highest battery voltage
|
||||
* can't be below minBatteryVoltage
|
||||
*/
|
||||
void setMaxBatteryVoltage(float voltage)
|
||||
{
|
||||
maxBatteryVoltage = max(getMinBatteryVoltage()+1.0f, voltage);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get the capacity of all cells in parralel sumed up
|
||||
* unit: mAh
|
||||
*/
|
||||
unsigned int getTotalBatteryCapacity()
|
||||
{
|
||||
return totalBatteryCapacity;
|
||||
}
|
||||
|
||||
void setTotalBatteryCapacity(unsigned int capacity)
|
||||
{
|
||||
totalBatteryCapacity = capacity;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the choosen adc precision
|
||||
* esp8266 = 10bit resolution = 1024.0f
|
||||
* esp32 = 12bit resolution = 4095.0f
|
||||
*/
|
||||
float getAdcPrecision()
|
||||
{
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// esp32
|
||||
return 4095.0f;
|
||||
#else
|
||||
// esp8266
|
||||
return 1024.0f;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the calculated voltage
|
||||
* formula: (adc pin value / adc precision * max voltage) + calibration
|
||||
*/
|
||||
float getVoltage()
|
||||
{
|
||||
return voltage;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the mapped battery level (0 - 100) based on voltage
|
||||
* important: voltage can drop when a load is applied, so its only an estimate
|
||||
*/
|
||||
int8_t getBatteryLevel()
|
||||
{
|
||||
return batteryLevel;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the configured calibration value
|
||||
* a offset value to fine-tune the calculated voltage.
|
||||
*/
|
||||
float getCalibration()
|
||||
{
|
||||
return calibration;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the voltage calibration offset value
|
||||
* a offset value to fine-tune the calculated voltage.
|
||||
*/
|
||||
void setCalibration(float offset)
|
||||
{
|
||||
calibration = offset;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get auto-off feature enabled status
|
||||
* is auto-off enabled, true/false
|
||||
*/
|
||||
bool getAutoOffEnabled()
|
||||
{
|
||||
return autoOffEnabled;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set auto-off feature status
|
||||
*/
|
||||
void setAutoOffEnabled(bool enabled)
|
||||
{
|
||||
autoOffEnabled = enabled;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get auto-off threshold in percent (0-100)
|
||||
*/
|
||||
int8_t getAutoOffThreshold()
|
||||
{
|
||||
return autoOffThreshold;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set auto-off threshold in percent (0-100)
|
||||
*/
|
||||
void setAutoOffThreshold(int8_t threshold)
|
||||
{
|
||||
autoOffThreshold = min((int8_t)100, max((int8_t)0, threshold));
|
||||
// when low power indicator is enabled the auto-off threshold cannot be above indicator threshold
|
||||
autoOffThreshold = lowPowerIndicatorEnabled /*&& autoOffEnabled*/ ? min(lowPowerIndicatorThreshold-1, (int)autoOffThreshold) : autoOffThreshold;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get low-power-indicator feature enabled status
|
||||
* is the low-power-indicator enabled, true/false
|
||||
*/
|
||||
bool getLowPowerIndicatorEnabled()
|
||||
{
|
||||
return lowPowerIndicatorEnabled;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set low-power-indicator feature status
|
||||
*/
|
||||
void setLowPowerIndicatorEnabled(bool enabled)
|
||||
{
|
||||
lowPowerIndicatorEnabled = enabled;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get low-power-indicator preset to activate when low power is detected
|
||||
*/
|
||||
int8_t getLowPowerIndicatorPreset()
|
||||
{
|
||||
return lowPowerIndicatorPreset;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set low-power-indicator preset to activate when low power is detected
|
||||
*/
|
||||
void setLowPowerIndicatorPreset(int8_t presetId)
|
||||
{
|
||||
// String tmp = ""; For what ever reason this doesn't work :(
|
||||
// lowPowerIndicatorPreset = getPresetName(presetId, tmp) ? presetId : lowPowerIndicatorPreset;
|
||||
lowPowerIndicatorPreset = presetId;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get low-power-indicator threshold in percent (0-100)
|
||||
*/
|
||||
int8_t getLowPowerIndicatorThreshold()
|
||||
{
|
||||
return lowPowerIndicatorThreshold;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set low-power-indicator threshold in percent (0-100)
|
||||
*/
|
||||
void setLowPowerIndicatorThreshold(int8_t threshold)
|
||||
{
|
||||
lowPowerIndicatorThreshold = threshold;
|
||||
// when auto-off is enabled the indicator threshold cannot be below auto-off threshold
|
||||
lowPowerIndicatorThreshold = autoOffEnabled /*&& lowPowerIndicatorEnabled*/ ? max(autoOffThreshold+1, (int)lowPowerIndicatorThreshold) : max(5, (int)lowPowerIndicatorThreshold);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get low-power-indicator duration in seconds
|
||||
*/
|
||||
int8_t getLowPowerIndicatorDuration()
|
||||
{
|
||||
return lowPowerIndicatorDuration;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set low-power-indicator duration in seconds
|
||||
*/
|
||||
void setLowPowerIndicatorDuration(int8_t duration)
|
||||
{
|
||||
lowPowerIndicatorDuration = duration;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get low-power-indicator status when the indication is done thsi returns true
|
||||
*/
|
||||
bool getLowPowerIndicatorDone()
|
||||
{
|
||||
return lowPowerIndicationDone;
|
||||
}
|
||||
};
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
const char UsermodBattery::_name[] PROGMEM = "Battery";
|
||||
const char UsermodBattery::_readInterval[] PROGMEM = "interval";
|
||||
const char UsermodBattery::_enabled[] PROGMEM = "enabled";
|
||||
const char UsermodBattery::_threshold[] PROGMEM = "threshold";
|
||||
const char UsermodBattery::_preset[] PROGMEM = "preset";
|
||||
const char UsermodBattery::_duration[] PROGMEM = "duration";
|
||||
const char UsermodBattery::_init[] PROGMEM = "init";
|
Before Width: | Height: | Size: 68 KiB |
@ -1,68 +0,0 @@
|
||||
# :battery: Battery status/level Usermod :battery:
|
||||
Enables battery level monitoring of your project.
|
||||
|
||||
You can see the battery level and voltage in the `info modal`.
|
||||
|
||||
For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)).
|
||||
|
||||
If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39)
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="assets/battery_info_screen.png">
|
||||
</p>
|
||||
|
||||
## Installation
|
||||
|
||||
define `USERMOD_BATTERY_STATUS_BASIC` in `my_config.h`
|
||||
|
||||
### Basic wiring diagram
|
||||
<p align="center">
|
||||
<img width="300" src="assets/battery_connection_schematic_01.png">
|
||||
</p>
|
||||
|
||||
### Define Your Options
|
||||
|
||||
* `USERMOD_BATTERY_STATUS_BASIC` - define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp
|
||||
* `USERMOD_BATTERY_MEASUREMENT_PIN` - defaults to A0 on ESP8266 and GPIO32 on ESP32
|
||||
* `USERMOD_BATTERY_MEASUREMENT_INTERVAL` - battery check interval. defaults to 30 seconds
|
||||
* `USERMOD_BATTERY_MIN_VOLTAGE` - minimum battery voltage. default is 2.6 (18650 battery standard)
|
||||
* `USERMOD_BATTERY_MAX_VOLTAGE` - maximum battery voltage. default is 4.2 (18650 battery standard)
|
||||
|
||||
All parameters can be configured at runtime via the Usermods settings page.
|
||||
|
||||
## Important :warning:
|
||||
* Make sure you know your battery specifications! All batteries are **NOT** the same!
|
||||
* Example:
|
||||
|
||||
| Your battery specification table | | Options you can define |
|
||||
| :-------------------------------- |:--------------- | :---------------------------- |
|
||||
| Capacity | 3500mAh 12,5 Wh | |
|
||||
| Minimum capacity | 3350mAh 11,9 Wh | |
|
||||
| Rated voltage | 3.6V - 3.7V | |
|
||||
| **Charging end voltage** | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
|
||||
| **Discharge voltage** | **2,5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
|
||||
| Max. discharge current (constant) | 10A (10000mA) | |
|
||||
| max. charging current | 1.7A (1700mA) | |
|
||||
| ... | ... | ... |
|
||||
| .. | .. | .. |
|
||||
|
||||
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
|
||||
|
||||
## Useful Links
|
||||
* https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start
|
||||
* https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/
|
||||
|
||||
## Change Log
|
||||
2021-09-02
|
||||
* added "Battery voltage" to info
|
||||
* added circuit diagram to readme
|
||||
* added MQTT support, sending battery voltage
|
||||
* minor fixes
|
||||
|
||||
2021-08-15
|
||||
* changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
|
||||
* Updated readme, added specification table
|
||||
|
||||
2021-08-10
|
||||
* Created
|
||||
|
@ -1,398 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
|
||||
|
||||
|
||||
|
||||
// pin defaults
|
||||
// for the esp32 it is best to use the ADC1: GPIO32 - GPIO39
|
||||
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html
|
||||
#ifndef USERMOD_BATTERY_MEASUREMENT_PIN
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#define USERMOD_BATTERY_MEASUREMENT_PIN 32
|
||||
#else //ESP8266 boards
|
||||
#define USERMOD_BATTERY_MEASUREMENT_PIN A0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// esp32 has a 12bit adc resolution
|
||||
// esp8266 only 10bit
|
||||
#ifndef USERMOD_BATTERY_ADC_PRECISION
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// 12 bits
|
||||
#define USERMOD_BATTERY_ADC_PRECISION 4095.0f
|
||||
#else
|
||||
// 10 bits
|
||||
#define USERMOD_BATTERY_ADC_PRECISION 1024.0f
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
// the frequency to check the battery, 30 sec
|
||||
#ifndef USERMOD_BATTERY_MEASUREMENT_INTERVAL
|
||||
#define USERMOD_BATTERY_MEASUREMENT_INTERVAL 30000
|
||||
#endif
|
||||
|
||||
|
||||
// default for 18650 battery
|
||||
// https://batterybro.com/blogs/18650-wholesale-battery-reviews/18852515-when-to-recycle-18650-batteries-and-how-to-start-a-collection-center-in-your-vape-shop
|
||||
// Discharge voltage: 2.5 volt + .1 for personal safety
|
||||
#ifndef USERMOD_BATTERY_MIN_VOLTAGE
|
||||
#define USERMOD_BATTERY_MIN_VOLTAGE 2.6f
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_MAX_VOLTAGE
|
||||
#define USERMOD_BATTERY_MAX_VOLTAGE 4.2f
|
||||
#endif
|
||||
|
||||
class UsermodBatteryBasic : public Usermod
|
||||
{
|
||||
private:
|
||||
// battery pin can be defined in my_config.h
|
||||
int8_t batteryPin = USERMOD_BATTERY_MEASUREMENT_PIN;
|
||||
// how often to read the battery voltage
|
||||
unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL;
|
||||
unsigned long nextReadTime = 0;
|
||||
unsigned long lastReadTime = 0;
|
||||
// battery min. voltage
|
||||
float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE;
|
||||
// battery max. voltage
|
||||
float maxBatteryVoltage = USERMOD_BATTERY_MAX_VOLTAGE;
|
||||
// 0 - 1024 for esp8266 (10-bit resolution)
|
||||
// 0 - 4095 for esp32 (Default is 12-bit resolution)
|
||||
float adcPrecision = USERMOD_BATTERY_ADC_PRECISION;
|
||||
// raw analog reading
|
||||
float rawValue = 0.0;
|
||||
// calculated voltage
|
||||
float voltage = 0.0;
|
||||
// mapped battery level based on voltage
|
||||
long batteryLevel = 0;
|
||||
bool initDone = false;
|
||||
bool initializing = true;
|
||||
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
static const char _name[];
|
||||
static const char _readInterval[];
|
||||
|
||||
|
||||
// custom map function
|
||||
// https://forum.arduino.cc/t/floating-point-using-map-function/348113/2
|
||||
double mapf(double x, double in_min, double in_max, double out_min, double out_max)
|
||||
{
|
||||
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
|
||||
}
|
||||
|
||||
float truncate(float val, byte dec)
|
||||
{
|
||||
float x = val * pow(10, dec);
|
||||
float y = round(x);
|
||||
float z = x - y;
|
||||
if ((int)z == 5)
|
||||
{
|
||||
y++;
|
||||
}
|
||||
x = y / pow(10, dec);
|
||||
return x;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public:
|
||||
//Functions called by WLED
|
||||
|
||||
/*
|
||||
* setup() is called once at boot. WiFi is not yet connected at this point.
|
||||
* You can use it to initialize variables, sensors or similar.
|
||||
*/
|
||||
void setup()
|
||||
{
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
DEBUG_PRINTLN(F("Allocating battery pin..."));
|
||||
if (batteryPin >= 0 && pinManager.allocatePin(batteryPin, false))
|
||||
{
|
||||
DEBUG_PRINTLN(F("Battery pin allocation succeeded."));
|
||||
} else {
|
||||
if (batteryPin >= 0) DEBUG_PRINTLN(F("Battery pin allocation failed."));
|
||||
batteryPin = -1; // allocation failed
|
||||
}
|
||||
#else //ESP8266 boards have only one analog input pin A0
|
||||
|
||||
pinMode(batteryPin, INPUT);
|
||||
#endif
|
||||
|
||||
nextReadTime = millis() + readingInterval;
|
||||
lastReadTime = millis();
|
||||
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* connected() is called every time the WiFi is (re)connected
|
||||
* Use it to initialize network interfaces
|
||||
*/
|
||||
void connected()
|
||||
{
|
||||
//Serial.println("Connected to WiFi!");
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* loop() is called continuously. Here you can check for events, read sensors, etc.
|
||||
*
|
||||
*/
|
||||
void loop()
|
||||
{
|
||||
if(strip.isUpdating()) return;
|
||||
|
||||
// check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms)
|
||||
if (millis() < nextReadTime) return;
|
||||
|
||||
|
||||
nextReadTime = millis() + readingInterval;
|
||||
lastReadTime = millis();
|
||||
initializing = false;
|
||||
|
||||
// read battery raw input
|
||||
rawValue = analogRead(batteryPin);
|
||||
|
||||
// calculate the voltage
|
||||
voltage = (rawValue / adcPrecision) * maxBatteryVoltage ;
|
||||
// check if voltage is within specified voltage range
|
||||
voltage = voltage<minBatteryVoltage||voltage>maxBatteryVoltage?-1.0f:voltage;
|
||||
|
||||
// translate battery voltage into percentage
|
||||
/*
|
||||
the standard "map" function doesn't work
|
||||
https://www.arduino.cc/reference/en/language/functions/math/map/ notes and warnings at the bottom
|
||||
*/
|
||||
batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100);
|
||||
|
||||
|
||||
// SmartHome stuff
|
||||
if (WLED_MQTT_CONNECTED) {
|
||||
char subuf[64];
|
||||
strcpy(subuf, mqttDeviceTopic);
|
||||
strcat_P(subuf, PSTR("/voltage"));
|
||||
mqtt->publish(subuf, 0, false, String(voltage).c_str());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API.
|
||||
* Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI.
|
||||
* Below it is shown how this could be used for e.g. a light sensor
|
||||
*/
|
||||
void addToJsonInfo(JsonObject& root)
|
||||
{
|
||||
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull()) user = root.createNestedObject("u");
|
||||
|
||||
// info modal display names
|
||||
JsonArray batteryPercentage = user.createNestedArray("Battery level");
|
||||
JsonArray batteryVoltage = user.createNestedArray("Battery voltage");
|
||||
|
||||
if (initializing) {
|
||||
batteryPercentage.add((nextReadTime - millis()) / 1000);
|
||||
batteryPercentage.add(" sec");
|
||||
batteryVoltage.add((nextReadTime - millis()) / 1000);
|
||||
batteryVoltage.add(" sec");
|
||||
return;
|
||||
}
|
||||
|
||||
if(batteryLevel < 0) {
|
||||
batteryPercentage.add(F("invalid"));
|
||||
} else {
|
||||
batteryPercentage.add(batteryLevel);
|
||||
}
|
||||
batteryPercentage.add(F(" %"));
|
||||
|
||||
if(voltage < 0) {
|
||||
batteryVoltage.add(F("invalid"));
|
||||
} else {
|
||||
batteryVoltage.add(truncate(voltage, 2));
|
||||
}
|
||||
batteryVoltage.add(F(" V"));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
|
||||
* Values in the state object may be modified by connected clients
|
||||
*/
|
||||
/*
|
||||
void addToJsonState(JsonObject& root)
|
||||
{
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
|
||||
* Values in the state object may be modified by connected clients
|
||||
*/
|
||||
/*
|
||||
void readFromJsonState(JsonObject& root)
|
||||
{
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object.
|
||||
* It will be called by WLED when settings are actually saved (for example, LED settings are saved)
|
||||
* If you want to force saving the current state, use serializeConfig() in your loop().
|
||||
*
|
||||
* CAUTION: serializeConfig() will initiate a filesystem write operation.
|
||||
* It might cause the LEDs to stutter and will cause flash wear if called too often.
|
||||
* Use it sparingly and always in the loop, never in network callbacks!
|
||||
*
|
||||
* addToConfig() will make your settings editable through the Usermod Settings page automatically.
|
||||
*
|
||||
* Usermod Settings Overview:
|
||||
* - Numeric values are treated as floats in the browser.
|
||||
* - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float
|
||||
* before being returned to the Usermod. The float data type has only 6-7 decimal digits of precision, and
|
||||
* doubles are not supported, numbers will be rounded to the nearest float value when being parsed.
|
||||
* The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38.
|
||||
* - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a
|
||||
* C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod.
|
||||
* Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type
|
||||
* used in the Usermod when reading the value from ArduinoJson.
|
||||
* - Pin values can be treated differently from an integer value by using the key name "pin"
|
||||
* - "pin" can contain a single or array of integer values
|
||||
* - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins
|
||||
* - Red color indicates a conflict. Yellow color indicates a pin with a warning (e.g. an input-only pin)
|
||||
* - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used
|
||||
*
|
||||
* See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings
|
||||
*
|
||||
* If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work.
|
||||
* You will have to add the setting to the HTML, xml.cpp and set.cpp manually.
|
||||
* See the WLED Soundreactive fork (code and wiki) for reference. https://github.com/atuline/WLED
|
||||
*
|
||||
* I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings!
|
||||
*/
|
||||
void addToConfig(JsonObject& root)
|
||||
{
|
||||
// created JSON object:
|
||||
/*
|
||||
{
|
||||
"Battery-Level": {
|
||||
"pin": "A0", <--- only when using esp32 boards
|
||||
"minBatteryVoltage": 2.6,
|
||||
"maxBatteryVoltage": 4.2,
|
||||
"read-interval-ms": 30000
|
||||
}
|
||||
}
|
||||
*/
|
||||
JsonObject battery = root.createNestedObject(FPSTR(_name)); // usermodname
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
battery["pin"] = batteryPin; // usermodparam
|
||||
#endif
|
||||
battery["minBatteryVoltage"] = minBatteryVoltage; // usermodparam
|
||||
battery["maxBatteryVoltage"] = maxBatteryVoltage; // usermodparam
|
||||
battery[FPSTR(_readInterval)] = readingInterval;
|
||||
|
||||
DEBUG_PRINTLN(F("Battery config saved."));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* readFromConfig() can be used to read back the custom settings you added with addToConfig().
|
||||
* This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page)
|
||||
*
|
||||
* readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes),
|
||||
* but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup.
|
||||
* If you don't know what that is, don't fret. It most likely doesn't affect your use case :)
|
||||
*
|
||||
* Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings)
|
||||
*
|
||||
* getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present
|
||||
* The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them
|
||||
*
|
||||
* This function is guaranteed to be called on boot, but could also be called every time settings are updated
|
||||
*/
|
||||
bool readFromConfig(JsonObject& root)
|
||||
{
|
||||
// looking for JSON object:
|
||||
/*
|
||||
{
|
||||
"BatteryLevel": {
|
||||
"pin": "A0", <--- only when using esp32 boards
|
||||
"minBatteryVoltage": 2.6,
|
||||
"maxBatteryVoltage": 4.2,
|
||||
"read-interval-ms": 30000
|
||||
}
|
||||
}
|
||||
*/
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
int8_t newBatteryPin = batteryPin;
|
||||
#endif
|
||||
|
||||
JsonObject battery = root[FPSTR(_name)];
|
||||
if (battery.isNull())
|
||||
{
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
newBatteryPin = battery["pin"] | newBatteryPin;
|
||||
#endif
|
||||
minBatteryVoltage = battery["minBatteryVoltage"] | minBatteryVoltage;
|
||||
//minBatteryVoltage = min(12.0f, (int)readingInterval);
|
||||
maxBatteryVoltage = battery["maxBatteryVoltage"] | maxBatteryVoltage;
|
||||
//maxBatteryVoltage = min(14.4f, max(3.3f,(int)readingInterval));
|
||||
readingInterval = battery["read-interval-ms"] | readingInterval;
|
||||
readingInterval = max(3000, (int)readingInterval); // minimum repetition is >5000ms (5s)
|
||||
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if (!initDone)
|
||||
{
|
||||
// first run: reading from cfg.json
|
||||
newBatteryPin = batteryPin;
|
||||
DEBUG_PRINTLN(F(" config loaded."));
|
||||
}
|
||||
else
|
||||
{
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
|
||||
// changing paramters from settings page
|
||||
if (newBatteryPin != batteryPin)
|
||||
{
|
||||
// deallocate pin
|
||||
pinManager.deallocatePin(batteryPin);
|
||||
batteryPin = newBatteryPin;
|
||||
// initialise
|
||||
setup();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return !battery[FPSTR(_readInterval)].isNull();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
|
||||
* This could be used in the future for the system to determine whether your usermod is installed.
|
||||
*/
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_BATTERY_STATUS_BASIC;
|
||||
}
|
||||
};
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
const char UsermodBatteryBasic::_name[] PROGMEM = "Battery-level";
|
||||
const char UsermodBatteryBasic::_readInterval[] PROGMEM = "read-interval-ms";
|
@ -79,7 +79,7 @@
|
||||
#define USERMOD_ID_RTC 15 //Usermod "usermod_rtc.h"
|
||||
#define USERMOD_ID_ELEKSTUBE_IPS 16 //Usermod "usermod_elekstube_ips.h"
|
||||
#define USERMOD_ID_SN_PHOTORESISTOR 17 //Usermod "usermod_sn_photoresistor.h"
|
||||
#define USERMOD_ID_BATTERY_STATUS_BASIC 18 //Usermod "usermod_v2_battery_status_basic.h"
|
||||
#define USERMOD_ID_BATTERY 18 //Usermod "usermod_v2_battery.h"
|
||||
#define USERMOD_ID_PWM_FAN 19 //Usermod "usermod_PWM_fan.h"
|
||||
#define USERMOD_ID_BH1750 20 //Usermod "usermod_bh1750.h"
|
||||
#define USERMOD_ID_SEVEN_SEGMENT_DISPLAY 21 //Usermod "usermod_v2_seven_segment_display.h"
|
||||
|
@ -50,6 +50,7 @@ enum struct PinOwner : uint8_t {
|
||||
// #define USERMOD_ID_VL53L0X // 0x0C // Usermod "usermod_vl53l0x_gestures.h" -- Uses "standard" HW_I2C pins
|
||||
UM_MultiRelay = USERMOD_ID_MULTI_RELAY, // 0x0D // Usermod "usermod_multi_relay.h"
|
||||
UM_AnimatedStaircase = USERMOD_ID_ANIMATED_STAIRCASE, // 0x0E // Usermod "Animated_Staircase.h"
|
||||
UM_Battery = USERMOD_ID_BATTERY, //
|
||||
// #define USERMOD_ID_RTC // 0x0F // Usermod "usermod_rtc.h" -- Uses "standard" HW_I2C pins
|
||||
// #define USERMOD_ID_ELEKSTUBE_IPS // 0x10 // Usermod "usermod_elekstube_ips.h" -- Uses quite a few pins ... see Hardware.h and User_Setup.h
|
||||
// #define USERMOD_ID_SN_PHOTORESISTOR // 0x11 // Usermod "usermod_sn_photoresistor.h" -- Uses hard-coded pin (PHOTORESISTOR_PIN == A0), but could be easily updated to use pinManager
|
||||
|
@ -11,8 +11,8 @@
|
||||
*/
|
||||
//#include "../usermods/EXAMPLE_v2/usermod_v2_example.h"
|
||||
|
||||
#ifdef USERMOD_BATTERY_STATUS_BASIC
|
||||
#include "../usermods/battery_status_basic/usermod_v2_battery_status_basic.h"
|
||||
#ifdef USERMOD_BATTERY
|
||||
#include "../usermods/battery/usermod_v2_battery.h"
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_DALLASTEMPERATURE
|
||||
@ -193,8 +193,8 @@ void registerUsermods()
|
||||
* \/ \/ \/
|
||||
*/
|
||||
//usermods.add(new MyExampleUsermod());
|
||||
#ifdef USERMOD_BATTERY_STATUS_BASIC
|
||||
usermods.add(new UsermodBatteryBasic());
|
||||
#ifdef USERMOD_BATTERY
|
||||
usermods.add(new UsermodBattery());
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_DALLASTEMPERATURE
|
||||
|