Merge branch 'master' of into patch2

This commit is contained in:
Magnus 2022-12-05 13:51:42 +01:00
commit 3be6847238
38 changed files with 452 additions and 275 deletions

View File

@ -10,10 +10,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Cache pip
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
@ -21,13 +21,13 @@ jobs:
${{ runner.os }}-pip-
- name: Cache PlatformIO
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: ~/.platformio
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
- name: Set up Python
uses: actions/setup-python@v2
uses: actions/setup-python@v3
- name: Install PlatformIO
run: |
@ -38,7 +38,7 @@ jobs:
- name: Run PlatformIO
run: pio run -e gravity-release
- uses: EndBug/add-and-commit@v7 # You can change this to use a specific version. https://github.com/marketplace/actions/add-commit
- uses: EndBug/add-and-commit@v9 # You can change this to use a specific version. https://github.com/marketplace/actions/add-commit
with:
add: 'bin'
author_name: GitHub Action

View File

@ -10,10 +10,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Cache pip
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
@ -21,7 +21,7 @@ jobs:
${{ runner.os }}-pip-
- name: Cache PlatformIO
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: ~/.platformio
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
@ -38,7 +38,7 @@ jobs:
- name: Run PlatformIO
run: pio run -e gravity-release -e gravity32-release -e gravity32c3-release -e gravity32s2-release
- uses: EndBug/add-and-commit@v7 # You can change this to use a specific version. https://github.com/marketplace/actions/add-commit
- uses: EndBug/add-and-commit@v9 # You can change this to use a specific version. https://github.com/marketplace/actions/add-commit
with:
add: 'bin'
author_name: GitHub Action

View File

@ -11,9 +11,9 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
- name: clang format support
run: |
sudo apt install clang-format cppcheck
- uses: pre-commit/action@v2.0.3
- uses: pre-commit/action@v3.0.0

5
.gitignore vendored
View File

@ -1,9 +1,4 @@
.pio/*
.vscode/*
*.map
test/*.md
test/env/*
test/configure_*.py
TODO.md
src_docs/_build/*
data/*.min.htm

View File

@ -12,7 +12,7 @@
GravityMon is a replacement firmware for the iSpindle firmware. It's 100% compatible with the iSpindle hardware design so it does not require any hardware changes.
Now also works with ESP32, either an ESP32 d1 mini or ESP32 c3 mini which both are pin compatible with ESP8266.
Now also works with ESP32 d1 mini, ESP32 c3 mini, ESP32 S2 mini which both are pin compatible with ESP8266.
Installation can be made using https://www.brewflasher.com or the web version at https://web.brewflasher.com
@ -23,3 +23,9 @@ Visit the gravitymon homepage here for more information about the project: https
If you want to support my work you can do that through these options
[<img src="https://gravitymon.com/images/buymecoffee.png" height=40>](https://www.buymeacoffee.com/mpse/) [<img src="https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86" height=40>](https://github.com/sponsors/mp-se)
# Supporters
Thanks to the following persons for supporting me and this project:
* David Conde

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bin/firmware32lite.bin Normal file

Binary file not shown.

Binary file not shown.

BIN
bin/partitions32lite.bin Normal file

Binary file not shown.

View File

@ -109,6 +109,10 @@
<div id="collapseDevice" class="accordion-collapse collapse show" aria-labelledby="headingDevice" data-bs-parent="#accordion">
<div class="accordion-body">
<input type="text" name="runtime-average" id="runtime-average" hidden>
<input type="text" name="platform" id="platform" hidden>
<input type="text" name="voltage-factor-calc" id="voltage-factor-calc" hidden>
<form action="/api/config/device" method="post">
<input type="text" name="id" id="id1" hidden>
@ -240,17 +244,11 @@
<div class="row mb-3">
<div class="col-sm-8 offset-sm-2">
<button type="submit" class="btn btn-primary" id="push-btn" data-bs-toggle="tooltip" title="Save changes in this section">Save</button>
<button type="button" class="btn btn-secondary" id="format-btn" data-bs-toggle="tooltip" title="Open up the format editor to change data format posted">Format editor</button>
<button type="button" class="btn btn-secondary" id="test-btn" data-bs-toggle="tooltip" title="Test posting data to defined push targets">Test Push</button>
</div>
</div>
</form>
<div class="row mb-3">
<div class="col-sm-8 offset-sm-2">
<button class="btn btn-secondary" id="format-btn" data-bs-toggle="tooltip" title="Open up the format editor to change data format posted">Format editor</button>
<button class="btn btn-secondary" id="test-btn" data-bs-toggle="tooltip" title="Test posting data to defined push targets">Test Push</button>
</div>
</div>
</div>
</div>
</div>
@ -329,17 +327,12 @@
<div class="row mb-3">
<div class="col-sm-8 offset-sm-2">
<button type="submit" class="btn btn-primary" id="push-btn2" data-bs-toggle="tooltip" title="Save changes in this section">Save</button>
<button type="button" class="btn btn-secondary" id="format-btn2" data-bs-toggle="tooltip" title="Open up the format editor to change data format posted">Format editor</button>
<button type="button" class="btn btn-secondary" id="test-btn2" data-bs-toggle="tooltip" title="Test posting data to defined push targets">Test Push</button>
</div>
</div>
</form>
<div class="row mb-3">
<div class="col-sm-8 offset-sm-2">
<button class="btn btn-secondary" id="format-btn2" data-bs-toggle="tooltip" title="Open up the format editor to change data format posted">Format editor</button>
<button class="btn btn-secondary" id="test-btn2" data-bs-toggle="tooltip" title="Test posting data to defined push targets">Test Push</button>
</div>
</div>
</div>
</div>
</div>
@ -415,8 +408,16 @@
<div class="col-sm-2">
<input type="number" step=".01" class="form-control" name="voltage-factor" id="voltage-factor" placeholder="1.59" data-bs-toggle="tooltip" title="Factor used to calculate the battery voltage. Can vary depending on the R2 value">
</div>
<div class="col-sm-2">
<label for="voltage-factor" class="col-sm-3 col-form-label" id="battery">Loading...</label>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-secondary" id="volt-factor-btn" data-bs-toggle="tooltip" title="Calcualte the voltage factor based on measured battery voltage">Calculate</button>
</div>
<div class="col-sm-2">
<input type="number" step=".01" class="form-control" name="measured-voltage" id="measured-voltage" placeholder="" data-bs-toggle="tooltip" title="Enter the measured battery voltage to calcualte the factor">
</div>
</div>
<div class="row mb-3">
<label for="voltage-config" class="col-sm-2 col-form-label">Config voltage</label>
@ -474,16 +475,55 @@
</div>
</div>
<div class="row mb-3">
<div class="col-sm-4 offset-sm-2">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="gravitymon-com" id="gravitymon-com" data-bs-toggle="tooltip" title="If enabled gravitymon.com will be checked for new versions.">
<label class="form-check-label" for="gravitymon-com">OTA from gravitymon.com</label>
</div>
</div>
</div>
<script>
$("#volt-factor-btn").click(function(e) {
var f = $("#voltage-factor-calc").val();
var mv = parseFloat( $("#measured-voltage").val() );
if( isNaN(mv) ) {
showError("You need to enter a measured voltage in order to calculate the factor");
return;
}
var vf = mv / f;
$("#voltage-factor").val( parseFloat(vf).toFixed(2) );
});
</script>
<script>
var gravitymonUrl = "https://www.gravitymon.com/firmware/";
$("#gravitymon-com").click(function(e){
var b = $("#gravitymon-com").is(":checked");
if ( b ) {
$("#ota-url").val(gravitymonUrl);
$("#ota-url").prop("disabled", true);
} else {
$("#ota-url").prop("disabled", false);
}
});
</script>
<div class="row mb-3">
<div class="col-sm-8 offset-sm-2">
<button type="submit" class="btn btn-primary" id="hardware-btn" data-bs-toggle="tooltip" title="Save changes in this section">Save</button>
<button type="button" class="btn btn-secondary" id="firmware-btn" checked data-bs-toggle="tooltip" title="Manually upload a new firmware version to the device">Upload firmware</button>
</div>
</div>
</form>
<div class="row mb-3">
<div class="col-sm-8 offset-sm-2">
<button class="btn btn-secondary" id="firmware-btn" checked data-bs-toggle="tooltip" title="Manually upload a new firmware version to the device">Upload firmware</button>
</div>
</div>
</div>
@ -740,10 +780,40 @@
// MPU-6050 consumes 4mA
// DS18B20 consumes 1mA
// For this estimation we use an average of 160mA
var pwrActive = 160; // mA per hour (120-170 mA)
var pwrSleep = 15; // mA per day (include all pheripials as well)
var batt = 2200; // mA
var ble = false;
var wifi = true;
var platform = $("#platform").val();
var pwrActive = 170; // mA per hour
var pwrSleep = 15; // mA per day
var batt = 2000; // mA
if($("#ble").val() != "")
ble = true;
if($("#http-push").val() == "" && $("#http-push2").val() == "" && $("#http-push3").val() == "" && $("#influxdb2-push").val() == "" && $("#mqtt-push").val() == "")
wifi = false;
console.log( "Connection options: BLE=" + (ble?"on":"off") + " WIFI=" + (wifi?"on":"off") );
if(platform == "esp32" && wifi) {
var pwrActive = 320; // mA per hour (260-379 mA)
} else if(platform == "esp32" && !wifi) {
var pwrActive = 160;
} else if(platform == "esp32c3" && wifi) {
var pwrActive = 320; // mA per hour (290-350 mA)
} else if(platform == "esp32c3" && !wifi) {
var pwrActive = 160;
} else if(platform == "esp32s2" && wifi) {
var pwrActive = 280; // mA per hour (260-300 mA)
} else if(platform == "esp32s2" && !wifi) {
var pwrActive = 160;
} else if(platform == "esp32lite" && wifi) {
var pwrActive = 330; // mA per hour (260-379 mA)
} else if(platform == "esp32lite" && !wifi) {
var pwrActive = 160;
}
console.log( "Estimated power per hour = " + pwrActive.toString() + "mA on platform = " + platform);
if(rt<1) rt = 2;
@ -757,8 +827,11 @@
var rt = parseInt($("#runtime-average").val());
var j = 0;
if( rt>0 )
console.log("Average runtime " + $("#runtime-average").val() )
if( rt>0 ) {
j = estimateBatteryLife(i, rt);
}
var t1 = Math.floor(i/60) + " m " + (i%60) + " s";
var t2 = Math.floor(j/7) + " weeks " + Math.floor(j%7) + " days";
@ -795,14 +868,14 @@
$("#test-btn2").prop("disabled", b);
$("#advanced-btn").prop("disabled", b);
checkAdvancedSection( b );
checkAdvancedSection();
}
$("#adv-config").click(function(e){
checkAdvancedSection();
});
function checkAdvancedSection( b ) {
function checkAdvancedSection() {
var b = $("#adv-config").is(":checked");
$("#advanced-btn").prop("disabled", b);
@ -869,11 +942,15 @@
$.getJSON(url, function (cfg) {
console.log( cfg );
if(cfg["platform"]=="esp32" || cfg["platform"]=="esp32c3") {
if(cfg["platform"]=="esp32" || cfg["platform"]=="esp32c3" || cfg["platform"]=="esp32lite") {
$('#ble').prop('disabled', false);
$("#ble").val(cfg["ble"]);
}
if(cfg["platform"]=="esp32lite") {
$('#gyro-temp').prop('disabled', true);
}
$("#id1").val(cfg["id"]);
$("#id2").val(cfg["id"]);
$("#id3").val(cfg["id"]);
@ -886,6 +963,12 @@
if( cfg["gravity-format"] == "G" ) $("#gravity-format-g").click();
else $("#gravity-format-p").click();
$("#ota-url").val(cfg["ota-url"]);
if( cfg["ota-url"] == gravitymonUrl) {
$("#gravitymon-com").prop( "checked", true );
$("#ota-url").prop("disabled", true);
}
$("#token").val(cfg["token"]);
$("#token2").val(cfg["token2"]);
$("#http-push").val(cfg["http-push"]);
@ -918,6 +1001,8 @@
$("#water-angle").text( "(Water angle: " + cfg["formula-calculation-data"]["a1"] + ") - default off");
$("#wifi-ssid").text(cfg["wifi-ssid"]);
$("#wifi-ssid2").text(cfg["wifi-ssid2"]);
$("#platform").val(cfg["platform"]);
$("#voltage-factor-calc").val( cfg["battery"] / cfg["voltage-factor"] );
//$("#gravity").text(cfg["gravity"] + " SG");
})
.fail(function () {

File diff suppressed because one or more lines are too long

View File

@ -90,7 +90,7 @@
<div class="row mb-3">
<div class="col-sm-8">
<button class="btn btn-primary" id="test-btn" data-bs-toggle="tooltip" title="Test all push targets">Test</button>
<button type="button" class="btn btn-primary" id="test-btn" data-bs-toggle="tooltip" title="Test all push targets">Test</button>
</div>
</div>

File diff suppressed because one or more lines are too long

View File

@ -40,7 +40,7 @@ build_flags =
-DUSER_SSID=\""\"" # =\""myssid\""
-DUSER_SSID_PWD=\""\"" # =\""mypwd\""
-DCFG_APPVER="\"1.2.0\""
-DCFG_GITREV=\""beta-1\""
-DCFG_GITREV=\""beta-2\""
#!python script/git_rev.py
lib_deps =
# Using local copy of these libraries
@ -96,6 +96,7 @@ build_unflags = ${common_env_data.build_unflags}
build_flags =
${common_env_data.build_flags}
-D LOG_LEVEL=4
#-DUSE_SERIAL_PINS # Use the TX/RX pins for the serial port
lib_deps =
https://github.com/mp-se/incbin # https://github.com/graphitemaster/incbin
${common_env_data.lib_deps}
@ -116,6 +117,9 @@ build_flags =
#-DCORE_DEBUG_LEVEL=0
${common_env_data.build_flags}
-D LOG_LEVEL=5
-DESP32D1
-DCORE_DEBUG_LEVEL=0
#-DUSE_SERIAL_PINS # Use the TX/RX pins for the serial port
lib_deps =
${common_env_data.lib_deps}
${common_env_data.lib_deps32}
@ -148,6 +152,7 @@ build_flags =
-DCORE_DEBUG_LEVEL=0
-DESP32C3
-DARDUINO_ESP32C3_DEV
-DREDUCE_WIFI_POWER # Enable this if v1.0 chip is used
#-DUSE_SERIAL_PINS # Use the TX/RX pins for the serial port
lib_deps =
${common_env_data.lib_deps}
@ -246,3 +251,36 @@ board_build.embed_txtfiles =
html/index.min.htm
html/test.min.htm
# This is a version for the floaty hardware. No DSB18 sensor and no battery measurement.
[env:gravity32lite-release]
framework = ${common_env_data.framework}
platform = ${common_env_data.platform32}
upload_speed = ${common_env_data.upload_speed}
monitor_speed = ${common_env_data.monitor_speed}
extra_scripts = ${common_env_data.extra_scripts}
build_unflags =
${common_env_data.build_unflags}
build_flags =
-Wl,-Map,output.map
${common_env_data.build_flags}
-DLOG_LEVEL=5
-DCORE_DEBUG_LEVEL=0
-DESP32LITE
-DFLOATY
#-DUSE_SERIAL_PINS # Use the TX/RX pins for the serial port
lib_deps =
${common_env_data.lib_deps}
${common_env_data.lib_deps32}
lib_ignore =
board = lolin32_lite
build_type = release
board_build.partitions = part32.csv
board_build.filesystem = littlefs
board_build.embed_txtfiles =
html/calibration.min.htm
html/config.min.htm
html/firmware.min.htm
html/format.min.htm
html/about.min.htm
html/index.min.htm
html/test.min.htm

View File

@ -56,6 +56,16 @@ def after_build(source, target, env):
print( "Copy file : " + source + " -> " + target )
shutil.copyfile( source, target )
if name == "gravity32lite-release" :
target = dir + "/bin/firmware32lite.bin"
source = dir + "/.pio/build/" + name + "/firmware.bin"
print( "Copy file : " + source + " -> " + target )
shutil.copyfile( source, target )
target = dir + "/bin/partitions32lite.bin"
source = dir + "/.pio/build/" + name + "/partitions.bin"
print( "Copy file : " + source + " -> " + target )
shutil.copyfile( source, target )
print( "Adding custom build step (copy firmware): ")
env.AddPostAction("buildprog", after_build)

View File

@ -41,7 +41,7 @@ BleSender::BleSender(const char* color) {
// boost power to maximum, these might be changed once battery life using BLE
// has been tested.
#if defined(ESP32C3)
#if defined(ESP32C3) && defined(REDUCE_WIFI_POWER)
esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_DEFAULT, ESP_PWR_LVL_P6);
esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_ADV, ESP_PWR_LVL_P6);
esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_SCAN, ESP_PWR_LVL_P6);

View File

@ -149,13 +149,19 @@ class Config {
float _voltageFactor = 1.3;
#elif defined(ESP32S2)
float _voltageFactor = 0.59;
#elif defined(ESP32LITE)
float _voltageFactor = 1.59;
#else // ESP32
float _voltageFactor = 1.3;
#endif
float _voltageConfig = 4.15;
float _tempSensorAdjC = 0;
int _sleepInterval = 900;
#if defined(FLOATY)
bool _gyroTemp = true;
#else
bool _gyroTemp = false;
#endif
bool _storageSleep = false;
// Wifi Config
@ -211,8 +217,12 @@ class Config {
const bool isGyroTemp() { return _gyroTemp; }
void setGyroTemp(bool b) {
#if defined(FLOATY)
// Floaty hardware dont have a temp sensor, uses gyro temperature
#else
_gyroTemp = b;
_saveNeeded = true;
#endif
}
const bool isStorageSleep() { return _storageSleep; }

View File

@ -30,22 +30,41 @@ MPU6050 accelgyro;
#define GYRO_USE_INTERRUPT // Use interrupt to detect when new sample is ready
#define GYRO_SHOW_MINMAX // Will calculate the min/max values when doing
// calibration
// #define GYRO_CALIBRATE_STARTUP // Will calibrate sensor at startup
//
// Initialize the sensor chip.
//
bool GyroSensor::setup() {
int clock = 400000;
#if defined(FLOATY)
pinMode(PIN_VCC, OUTPUT);
pinMode(PIN_GND, OUTPUT_OPEN_DRAIN);
digitalWrite(PIN_VCC, HIGH);
digitalWrite(PIN_GND, LOW);
delay(10); // Wait for the pins to settle or we will fail to connect
#else
#endif
/* For testing pin config of new boards with led.
pinMode(PIN_SDA, OUTPUT);
pinMode(PIN_SCL, OUTPUT);
for(int i = 0, j = LOW, k = LOW; i < 100; i++) {
digitalWrite(PIN_SDA, k);
digitalWrite(PIN_SCL, j);
k = !k;
delay(300);
digitalWrite(PIN_SDA, k);
k = !k;
j = !j;
delay(300);
}*/
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Setting up hardware." CR));
#endif
Wire.begin(PIN_SDA, PIN_SCL);
Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having
// compilation difficulties
Wire.setClock(clock); // 400kHz I2C clock.
uint8_t id = accelgyro.getDeviceID();
if (id != 0x34 && id != 0x38) { // Allow both MPU6050 and MPU6000
if (id != 0x34 && id != 0x38) { // Allow both MPU6050 and MPU6500
writeErrorLog("GYRO: Failed to connect to gyro, is it connected?");
_sensorConnected = false;
} else {
@ -68,11 +87,6 @@ bool GyroSensor::setup() {
accelgyro.setIntDataReadyEnabled(true);
#endif
#if defined(GYRO_CALIBRATE_STARTUP)
// Run the calibration at start, useful for testing.
calibrateSensor();
#endif
// Once we have calibration values stored we just apply them from the
// config.
_calibrationOffset = myConfig.getGyroCalibration();
@ -81,19 +95,17 @@ bool GyroSensor::setup() {
return _sensorConnected;
}
//
// Set sensor in sleep mode to conserve battery
//
void GyroSensor::enterSleep() {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Setting up hardware." CR));
#endif
#if defined(FLOATY)
digitalWrite(PIN_VCC, LOW);
#else
accelgyro.setSleepEnabled(true);
#endif
}
//
// Do a number of reads to get a more stable value.
//
void GyroSensor::readSensor(RawGyroData &raw, const int noIterations,
const int delayTime) {
RawGyroDataL average = {0, 0, 0, 0, 0, 0};
@ -105,7 +117,8 @@ void GyroSensor::readSensor(RawGyroData &raw, const int noIterations,
// Set some initial values
#if defined(GYRO_SHOW_MINMAX)
RawGyroData min, max;
RawGyroData min = {0, 0, 0};
RawGyroData max = {0, 0, 0};
accelgyro.getAcceleration(&min.ax, &min.ay, &min.az);
min.temp = accelgyro.getTemperature();
max = min;
@ -179,9 +192,6 @@ void GyroSensor::readSensor(RawGyroData &raw, const int noIterations,
#endif
}
//
// Calcuate the angles (tilt)
//
float GyroSensor::calculateAngle(RawGyroData &raw) {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Calculating the angle." CR));
@ -209,9 +219,6 @@ float GyroSensor::calculateAngle(RawGyroData &raw) {
return vY;
}
//
// Check if the values are high that indicate that the sensor is moving.
//
bool GyroSensor::isSensorMoving(RawGyroData &raw) {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Checking for sensor movement." CR));
@ -229,9 +236,6 @@ bool GyroSensor::isSensorMoving(RawGyroData &raw) {
return false;
}
//
// Read the tilt angle from the gyro.
//
bool GyroSensor::read() {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Getting new gyro position." CR));
@ -270,9 +274,6 @@ bool GyroSensor::read() {
return _validValue;
}
//
// Dump the stored calibration values.
//
void GyroSensor::dumpCalibration() {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Accel offset\t%d\t%d\t%d" CR), _calibrationOffset.ax,
@ -282,9 +283,6 @@ void GyroSensor::dumpCalibration() {
#endif
}
//
// Update the sensor with out calculated offsets.
//
void GyroSensor::applyCalibration() {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Applying calibration offsets to sensor." CR));
@ -306,9 +304,6 @@ void GyroSensor::applyCalibration() {
accelgyro.setZGyroOffset(_calibrationOffset.gz);
}
//
// Calculate the offsets for calibration.
//
void GyroSensor::calibrateSensor() {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Calibrating sensor" CR));
@ -330,14 +325,10 @@ void GyroSensor::calibrateSensor() {
_calibrationOffset.gy = accelgyro.getYGyroOffset();
_calibrationOffset.gz = accelgyro.getZGyroOffset();
// Save the calibrated values
myConfig.setGyroCalibration(_calibrationOffset);
myConfig.saveFile();
}
//
// Calibrate the device.
//
void GyroSensor::debug() {
#if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING)
Log.verbose(F("GYRO: Debug - Clock src %d." CR),

View File

@ -238,9 +238,8 @@ void printBuildOptions() {
SerialDebug::SerialDebug(const uint32_t serialSpeed) {
// Start serial with auto-detected rate (default to defined BAUD)
#if defined(USE_SERIAL_PINS) && defined(ESP8266)
// EspSerial.begin(serialSpeed, SERIAL_8N1, 3, 1);
EspSerial.begin(serialSpeed);
#warning "SerialPins is not implemented on ESP8266"
uint8_t txPin = 3;
EspSerial.begin(serialSpeed, SERIAL_8N1, SERIAL_TX_ONLY, txPin);
#elif defined(ESP8266)
EspSerial.begin(serialSpeed);
#elif defined(USE_SERIAL_PINS) && defined(ESP32C3)
@ -251,8 +250,10 @@ SerialDebug::SerialDebug(const uint32_t serialSpeed) {
EspSerial.begin(115200L, SERIAL_8N1, 37, 39);
#elif defined(ESP32S2)
EspSerial.begin(115200L);
#elif defined(USE_SERIAL_PINS) && defined(ESP32LITE)
EspSerial.begin(serialSpeed, SERIAL_8N1, 16, 17);
#elif defined(USE_SERIAL_PINS) && defined(ESP32)
EspSerial.begin(serialSpeed, SERIAL_8N1, 3, 1);
EspSerial.begin(serialSpeed, SERIAL_8N1, 1, 3);
#elif defined(ESP32)
EspSerial.begin(115200L);
#endif
@ -270,11 +271,26 @@ void printTimestamp(Print* _logOutput, int _logLevel) {
_logOutput->print(c);
}
bool checkPinConnected() {
#if defined(ESP8266)
pinMode(PIN_CFG1, INPUT);
#else
pinMode(PIN_CFG1, INPUT_PULLDOWN);
#endif
pinMode(PIN_CFG2, OUTPUT);
delay(5);
digitalWrite(PIN_CFG2, 1);
delay(5);
int i = digitalRead(PIN_CFG1);
digitalWrite(PIN_CFG2, 0);
return i == LOW ? false : true;
}
BatteryVoltage::BatteryVoltage() {
#if defined(ESP8266)
pinMode(PIN_A0, INPUT);
pinMode(PIN_VOLT, INPUT);
#else
pinMode(PIN_A0, INPUT_PULLDOWN);
pinMode(PIN_VOLT, INPUT_PULLDOWN);
#endif
}
@ -282,7 +298,7 @@ void BatteryVoltage::read() {
// The analog pin can only handle 3.3V maximum voltage so we need to reduce
// the voltage (from max 5V)
float factor = myConfig.getVoltageFactor(); // Default value is 1.63
int v = analogRead(PIN_A0);
int v = analogRead(PIN_VOLT);
// An ESP8266 has a ADC range of 0-1023 and a maximum voltage of 3.3V
// An ESP32 has an ADC range of 0-4095 and a maximum voltage of 3.3V

View File

@ -43,6 +43,9 @@ void checkResetReason();
// Sleep mode
void deepSleep(int t);
// Force config mode
bool checkPinConnected();
// Show build options
void printBuildOptions();

View File

@ -137,6 +137,7 @@ void setup() {
// Add a delay so that serial is started.
// delay(3000);
#endif
delay(2000);
// Main startup
#if defined(ESP8266)
@ -163,6 +164,11 @@ void setup() {
myAdvancedConfig.loadFile();
LOG_PERF_STOP("main-config-load");
sleepModeAlwaysSkip = checkPinConnected();
if (sleepModeAlwaysSkip) {
Log.notice(F("Main: Forcing config mode since D7/D8 are connected." CR));
}
// Setup watchdog
#if defined(ESP8266)
ESP.wdtDisable();
@ -256,11 +262,8 @@ void setup() {
millis(); // Dont include time for wifi connection
}
//
// Main loop that does gravity readings and push data to targets
//
// Return true if gravity reading was successful
//
bool loopReadGravity() {
float angle = 0;
@ -334,15 +337,14 @@ bool loopReadGravity() {
}
return true;
} else {
Log.error(F("MAIN: No gyro value found, the device might be moving." CR));
// Log.error(F("MAIN: No gyro value found, the device might be moving."
// CR));
}
return false;
}
//
// Wrapper for loopGravity that only calls every 200ms so that we dont overload
// this.
//
void loopGravityOnInterval() {
if (abs((int32_t)(millis() - loopMillis)) > interval) {
loopReadGravity();
@ -358,9 +360,6 @@ void loopGravityOnInterval() {
bool skipRunTimeLog = false;
//
// Main loop that determines if device should go to sleep
//
void goToSleep(int sleepInterval) {
float volt = myBatteryVoltage.getVoltage();
float runtime = (millis() - runtimeMillis);

View File

@ -38,14 +38,20 @@ enum RunMode {
extern RunMode runMode;
#if defined(ESP8266)
// Hardware config for ESP8266-d1, iSpindel hardware
// ------------------------------------------------------
#include <LittleFS.h>
#define ESP_RESET ESP.reset
#define PIN_SDA D3
#define PIN_SCL D4
#define PIN_CFG1 D8
#define PIN_CFG2 D7
#define PIN_DS D6
#define PIN_LED 2
// #define PIN_A0 A0
#define PIN_VOLT PIN_A0
#elif defined(ESP32C3)
// Hardware config for ESP32-c3-mini, iSpindel hardware
// ------------------------------------------------------
#include <FS.h>
#include <LittleFS.h>
@ -61,12 +67,16 @@ extern RunMode runMode;
#define PIN_SDA 7
#define PIN_SCL 6
#endif // JTAG_DEBUG
#define PIN_CFG1 A5
#define PIN_CFG2 A4
#define PIN_DS A3
#define PIN_A0 A0
#define PIN_VOLT A0
// This should be the LED_BUILTIN, but that is also connected SDA (Gyro) so we
// cannot use both. So we point LED to pin 8 which is not used.
#define PIN_LED 8
#elif defined(ESP32S2)
// Hardware config for ESP32-s2-mini, iSpindel hardware
// ------------------------------------------------------
#include <FS.h>
#include <LittleFS.h>
@ -76,10 +86,33 @@ extern RunMode runMode;
#define ESP8266WebServer WebServer
#define PIN_SDA A17
#define PIN_SCL A15
#define PIN_CFG1 A11
#define PIN_CFG2 A10
#define PIN_DS A8
#define PIN_A0 A2
#define PIN_VOLT A2
#define PIN_LED LED_BUILTIN
#elif defined(ESP32LITE)
// Hardware config for ESP32-lite, Floaty hardware
// ------------------------------------------------------
#include <FS.h>
#include <LittleFS.h>
#include "esp32/rom/rtc.h"
#define ESPhttpUpdate httpUpdate
#define ESP_RESET ESP.restart
#define ESP8266WebServer WebServer
#define PIN_SDA A17
#define PIN_SCL A19
#define PIN_DS A3
#define PIN_VOLT A7
#define PIN_CFG1 A14
#define PIN_CFG2 A13
#define PIN_VCC A5
#define PIN_GND A18
#define PIN_LED LED_BUILTIN
#else // defined (ESP32)
// Hardware config for ESP32-d1-min, iSpindel hardware
// ------------------------------------------------------
#include <FS.h>
#include <LittleFS.h>
@ -90,11 +123,13 @@ extern RunMode runMode;
#define PIN_SDA D3
#define PIN_SCL D4
#define PIN_DS D6
#define PIN_CFG1 D8
#define PIN_CFG2 D7
#define PIN_LED LED_BUILTIN
// #define PIN_A0 A4
#define PIN_VOLT PIN_A0
#endif
#if defined(USE_SERIAL_PINS) && defined(ESP32)
#if defined(USE_SERIAL_PINS) && (defined(ESP32C3) || defined(ESP32S2))
// #define EspSerial Serial0 // We cant use Serial on newer boards since this is
// using USBC port
#define EspSerial \

View File

@ -35,15 +35,7 @@ DallasTemperature mySensors(&myOneWire);
TempSensor myTempSensor;
//
// Setup DS18B20 temp sensor. Doing setup is not that time consuming.
//
void TempSensor::setup() {
#if defined(SIMULATE_TEMP)
hasSensors = true;
return;
#endif
#if LOG_LEVEL == 6 && !defined(TSEN_DISABLE_LOGGING)
Log.verbose(F("TSEN: Looking for temp sensors." CR));
#endif
@ -70,10 +62,6 @@ void TempSensor::setup() {
// Retrieving value from sensor, value is in Celcius
//
float TempSensor::getValue(bool useGyro) {
#if defined(SIMULATE_TEMP)
return 21;
#endif
if (useGyro) {
// When using the gyro temperature only the first read value will be
// accurate so we will use this for processing.

View File

@ -91,6 +91,8 @@ void WebServerHandler::webHandleConfig() {
doc[PARAM_PLATFORM] = "esp32c3";
#elif defined(ESP32S2)
doc[PARAM_PLATFORM] = "esp32s2";
#elif defined(ESP32LITE)
doc[PARAM_PLATFORM] = "esp32lite";
#else // esp32 mini
doc[PARAM_PLATFORM] = "esp32";
#endif
@ -274,6 +276,8 @@ void WebServerHandler::webHandleStatus() {
doc[PARAM_PLATFORM] = "esp32c3";
#elif defined(ESP32S2)
doc[PARAM_PLATFORM] = "esp32s2";
#elif defined(ESP32LITE)
doc[PARAM_PLATFORM] = "esp32lite";
#else // esp32 mini
doc[PARAM_PLATFORM] = "esp32";
#endif

View File

@ -118,7 +118,7 @@ void WifiConnection::startPortal() {
ESP_WMParameter deviceName(mdns.c_str());
myWifiManager->addParameter(&deviceName);
#if defined(ESP32C3)
#if defined(ESP32C3) && defined(REDUCE_WIFI_POWER)
Log.notice(F("WIFI: Reducing wifi power for c3 chip." CR));
WiFi.setTxPower(WIFI_POWER_8_5dBm); // Required for ESP32C3 Mini
#endif
@ -157,7 +157,7 @@ void WifiConnection::connectAsync(int wifiIndex) {
WiFi.persistent(true);
WiFi.mode(WIFI_STA);
#if defined(ESP32C3)
#if defined(ESP32C3) && defined(REDUCE_WIFI_POWER)
Log.notice(F("WIFI: Reducing wifi power for c3 chip." CR));
WiFi.setTxPower(WIFI_POWER_8_5dBm); // Required for ESP32C3 Mini
#endif
@ -303,6 +303,8 @@ bool WifiConnection::updateFirmware() {
serverPath += "firmware32c3.bin";
#elif defined(ESP32S2)
serverPath += "firmware32s2.bin";
#elif defined(ESP32LITE)
serverPath += "firmware32lite.bin";
#else // defined (ESP32)
serverPath += "firmware32.bin";
#endif

View File

@ -84,7 +84,7 @@ GET: /api/status
Retrieve the current device status via an HTTP GET command. Payload is in JSON format.
* ``temp-format`` can be either ``C`` or ``F``
* ``platform`` can be either ``esp8266``, ``esp32c3``, ``esp32s2`` or ``esp32``
* ``platform`` can be either ``esp8266``, ``esp32c3``, ``esp32s2``, ``esp32`` or ``esp32lite`` (floaty hardware)
* ``temp-c`` will be set to -273 C if there is no temp sensor
* ``angle`` will be set to 0 if no valid angle is found and -1 if there is no gyro

View File

@ -32,6 +32,7 @@ In the platformio config there are 3 targets defined
* gravity32-release: Version for ESP32 mini.
* gravity32-c3-release: Version for ESP32 C3 mini.
* gravity32-s2-release: Version for ESP32 S2 mini.
* gravity32-lite-release: Version for ESP32 lite (Floaty hardware).
.. warning::
The debug target can be unstable and crash the device under certain circumstanses. Excessive logging to the serial port can cause corruption and crashes.
@ -114,4 +115,7 @@ This is a list of C++ defines that is used to enable/disable functions in the co
- Defines the version of the compiled software
* - USE_SERIAL_PINS
- Will send the serial console to the TX/RX pins on an ESP32 target so that debugging can be done when on battery
* - REDUCE_WIFI_POWER
- Will reduce wifi power to support the ESP32C3 v1.0 which has a bad antenna
* - FLOATY
- Build for the ESP32lite FLOATY hardware option (no DS18B20 and no battery monitor)

View File

@ -10,7 +10,7 @@ One of the following conditions will place the device in ``configuration mode``:
- Gyro has not been calibrated
- Sleep mode has been disabled in the web interface
- Placed in horizontal mode 85-90 degrees
- Charger connected >4.15V (or the value that is configured)
- Charger connected >4.15V (or the value that is configured). This does not work on the Floaty variant due to lack of hardware support.
Status

View File

@ -136,6 +136,11 @@ The main features
fermentation vessel. This sequence takes 900 ms seconds to execute and besides wifi connection this is what consumes the most
battery. With more testing this might be changes to either speed up or provide more stable readings.
* **Crash detection and Error Logging**
There is a build in logging function so that errors that occurs can be detected and logged to a file. On the ESP8266 crashes will also
be logged so that these problems can be detected and fixed. Crash logging is not available on the ESP32 variants.
* **Performance measurements**
I've also create a small library to measure execution code in some areas of the code that i know is time consuming. This
@ -152,20 +157,45 @@ The main features
See the :ref:`compiling-the-software` for more information.
* **Power measurements**
I've also create a project to measure the power consumption of the device, but more on this later.
Battery life
------------
The long term battery test has now been completed. Using a 2200 mA battery and sending data every 5 minutes to a local server on my network. The battery lasted 47 days which is excellent battery life.
For the 1.2 version I have been running some long term battery tests on a few of the boards and also comparing wifi vs Bluetooth. I was using a standard 2200 mA battery
that was fully charged at the start of the tests. All devices started with factory settings with only a change in push destination and sleep interval.
In another test I had a device running with an sleep interval of only 30s with ok wifi connection. The device lasted 12 days which i think is excellent considering the short sleep interval.
For the wifi tests, I was pushing data every 30 seconds to a local influxdb2 server to reduce errors connected to slow response on the server side. The devices
was placed 2 meters from the wifi AP to ensure a good and stable wifi connection (so ideal conditions).
From what I have discovered it's the WIFI connection or latency to internet hosted that has the most impact on the battery life. The typical runtime in the tests above was around 2 seconds.
For the Bluetooth tests I was pusing data every 10 seconds to a linux server.
To make this comparable I measured how many times the device was able to wake up and push data before the battery was dead. I theory the power consumption when in
deep sleep is to low it can almost be ignored for the calculations. So the impact on battery is mainly caused by how long the device is awake. In the most optimal case
this can be as low as 1.5-2.0 seconds but in reality its probably around 3-4 seconds. Wifi consumes a lot of power so Bluetooth is a better option for long battery life.
.. list-table:: Battery power
:widths: 30 20 20 20
:header-rows: 1
* - Device
- Transmissions
- 30s
- 300s / 15min
* - ESP 8266 (wifi)
- 26,000
- 9 days
- 90 days
* - ESP32 c3 (wifi)
- 12,000
- 4 days
- 43 days
* - ESP32 d1 (ble)
- 56,000
- 20 days
- 196 days
As you can see from the table above there is quite some differences between the boards and connection methods.
Performance
-----------

View File

@ -25,6 +25,7 @@ Schema for esp8266 build
:width: 700
:alt: Schema esp8266
iSpindle based on esp32
=======================
@ -90,7 +91,7 @@ Schema for esp32 build
:alt: Schema esp32
Adding a reed (magnetic) reset switch
=====================================
+++++++++++++++++++++++++++++++++++++
A reed switch is a switch that reacts to magnetic fields. The ones I have tested are normally open and close in proximity to
a magnet.
@ -107,3 +108,37 @@ The reed switch is the glass tube visible under the esp8266.
.. image:: images/reed_build.jpg
:width: 400
:alt: Reed build
Floaty Hydrometer DIY based on esp32 lite
=========================================
Here we have another projects that has build a device similar to the iSpindel but based on an ESP32 instead.
The setup is much simpler and attaches the GYRO to an ESP32 with a build in charger chip. GravityMon works on
this hardware platform as well but there are a few limitations:
* Temperature is read from the GYRO and cannot be changed. This works fine when measuring gravity but when in configuration mode the temperature will increase since it shows the chip temperature.
* No possibility to measure battery level (can be added with additional hardware).
Hardware extensions
===================
GravityMon has implemented a few additions to the standard iSpindel hardware. It's possible to channel the serial console to the TX/RX pins on the chip (these position also applies to all the
ESP32 chips for iSpindel). You need a USB to TTL converter for this to work. This enables you to read the serial console even when on battery (newer chips dont have a diode to remove).
.. note::
You need to compile the software using the -DUSE_SERIAL_PINS option to enable this feature.
Its also possible to force the device into configuration mode by connecting D7/D8 on the board during the startup sequence. This will enable the feature "gravity mode enabled during float".
.. image:: images/8266_pins.jpg
:width: 500
:alt: iSpindel pins
For the floaty device pins 16/17 are used as TX/RX pins and the 13/15 pins are used to force the device into configuration mode. Pin 35 can also be connected to the battery voltage via an voltage divider to be able to read the battery voltage.
.. image:: images/32lite_pins.jpg
:width: 500
:alt: Floaty pins

Binary file not shown.

After

Width:  |  Height:  |  Size: 416 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 324 KiB

View File

@ -7,7 +7,7 @@ Welcome to GravityMon
#####################
.. note::
This documentation reflects **v1.2 - beta 1**. Last updated 2022-11-04
This documentation reflects **v1.2 - beta 2**. Last updated 2022-11-19
What is GravityMon?
--------------------
@ -25,7 +25,7 @@ implements a lot of the features that has been requested in the original iSpindl
various reasons.
The firmware also supports a iSpindle built using an ESP32 which is pin compatible with esp8266, currently there are 3 options that are
supported ESP32-D1 mini, ESP32-C3 mini and ESP32-S2 mini. See :ref:`hardware`. The more modern hardware will allow better support for SSL and
supported ESP32-D1 mini, ESP32-C3 mini, ESP32-S2 mini, ESP32 lite (floaty). See :ref:`hardware`. The more modern hardware will allow better support for SSL and
other memory intensive functions.
I started GravityMon because I like to create software and wanted to do some microcontroller programming. I had done a few

View File

@ -53,6 +53,9 @@ In the /bin directory you will find 4 different firmware builds;
This is the release build for an ESP32s2-mini variant. When flashing an ESP32 you also need the *partition32s2.bin* file that outlines the flash memory structure. Due to
the size of the firmware we are using a custom partition setup.
* **firmware32lite.bin**
This is the release build for an ESP32lite which is used by the floaty build (clone).
Esptool (esp8266)
=================

View File

@ -3,6 +3,20 @@
Releases
########
v1.2.0 - beta2
==============
Features
++++++++
* Added function to calcualate voltage factor based on measured value.
* Updated battery estimation for the various esp32 boards.
* Added support for the ESP32 lite board which is used in the Floaty Hydrometer variant.
Documentation
+++++++++++++
* Added section about the Floaty hardware.
v1.2.0 - beta1
==============

View File

@ -1,91 +0,0 @@
import requests
import json
host = "192.168.1.1" # IP adress (or name) of the device to send these settings to
id = "ee1bfc" # Device ID (shown in serial console during startup or in UI)
def set_config( url, json ):
headers = { "ContentType": "application/json" }
print( url )
#print( json )
resp = requests.post( url, headers=headers, data=json )
if resp.status_code != 200 :
print ( "Failed " )
else :
print ( "Success " )
#
# Configure the device settings.
#
url = "http://" + host + "/api/config/device"
json = { "id": id,
"mdns": "gravmon", # Name of the device
"temp-format": "C", # Temperature format C or F
"sleep-interval": 30 # Sleep interval in seconds
}
set_config( url, json )
#
# Configure the push settings. Blank means that its no used.
#
url = "http://" + host + "/api/config/push"
json = { "id": id,
"token": "",
"http-push": "http://192.168.1.1/ispindel", # HTTP endpoint
"http-push2": "", # HTTP endpoint2
"http-push-h1": "Content-Type: application/json",
"http-push-h2": "",
"http-push2-h1": "Content-Type: application/json",
"http-push2-h2": "",
"influxdb2-push": "", # InfluxDB2 settings
"influxdb2-org": "",
"influxdb2-bucket": "",
"influxdb2-auth": "" ,
"mqtt-push": "",
"mqtt-port": 1883,
"mqtt-user": "",
"mqtt-pass": ""
}
set_config( url, json )
#
# Configure the gravity settings.
#
url = "http://" + host + "/api/config/gravity"
json = { "id": id,
"gravity-formula": "", # If you want to set the gravity formula
"gravity-format": "G",
"gravity-temp-adjustment": "off" # on or off
}
set_config( url, json )
#
# Configure the hardware settings.
#
url = "http://" + host + "/api/config/hardware"
json = { "id": id,
"voltage-factor": 1.59, # Default value for voltage calculation
"temp-adjustment": 0, # If temp sensor needs to be corrected
"gyro-temp": "off", # Use the temp sensor in the gyro
"ota-url": "" # if the device should seach for a new update when active
}
set_config( url, json )
#
# Configure the gravity formula settings. If this is called the formula will be updated based on these measurements (zero angle values will be ignored)
#
url = "http://" + host + "/api/formula"
json = { "id": id,
"a1": 22.4,
"a2": 54.4,
"a3": 58,
"a4": 0,
"a5": 0,
"g1": 1.000,
"g2": 1.053,
"g3": 1.062,
"g4": 1,
"g5": 1
}
set_config( url, json )