Compare commits

...
18 Commits
Author SHA1 Message Date
jlehmann 59ce7ee44d 20200602 2020-06-02 21:21:05 +02:00
jlehmann f8909fc353 print LMIC.opmode before sleep 2020-06-01 19:31:36 +02:00
jlehmann ab86c843b1 cancel transactions at timeout 2020-06-01 19:04:39 +02:00
jlehmann 6d3053d8ad try to make it more stable... 2020-06-01 12:57:54 +02:00
jlehmann 85b0f6db06 refactor 2020-05-30 20:11:19 +02:00
jlehmann 0c5c673e5e add delay, see https://github.com/mcci-catena/arduino-lmic/issues/547 2020-05-30 18:01:13 +02:00
jlehmann e30a8293ac do not try a second time to use SendBuffer at failure 2020-05-29 17:12:20 +02:00
jlehmann 174f8b360f refactor a bit 2020-05-29 16:16:12 +02:00
jlehmann d0389af061 try second time if first try fails (SendBuffer) 2020-05-28 20:08:21 +02:00
jlehmann 7c8a52cafe tune code 2020-05-28 13:27:19 +02:00
jlehmann b71e0c0f0c make it more stable 2020-05-27 15:10:40 +02:00
jlehmann d2e4b81416 remove unused variable 2020-05-27 10:20:45 +02:00
jlehmann de0fef6971 some more tuning 2020-05-25 18:07:56 +02:00
jlehmann 1ce266ab22 remove timestamps in debug messages, debug nau7802 i2c connection 2020-05-23 18:13:08 +02:00
jlehmann 775eafc74f revised version 20200522 2020-05-22 14:52:09 +02:00
jlehmann 760ae035fd new version 20200522 2020-05-22 11:14:51 +02:00
jlehmann bf8c9f8441 optimize power 2020-05-18 16:06:31 +02:00
jlehmann 14490795af power optimizations 2020-05-15 10:10:29 +02:00
4 changed files with 334 additions and 298 deletions
+203 -250
View File
@@ -9,7 +9,7 @@
*/ */
// HX711: 0 => compile for hx711, 1 => compile for NAU7802 // HX711: 0 => compile for hx711, 1 => compile for NAU7802
#define HX711 1 #define HX711 0
#include <Catena.h> #include <Catena.h>
@@ -143,8 +143,6 @@ bool fFlash;
bool fUsbPower; bool fUsbPower;
// have we printed the sleep info? // have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code // the job that's used to synchronize us with the LMIC code
static osjob_t iterationJob; static osjob_t iterationJob;
static osjob_t sendJob; static osjob_t sendJob;
@@ -170,7 +168,7 @@ void setup(void)
void setup_platform(void) void setup_platform(void)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_platform\n", millis()); gCatena.SafePrintf("Setup_platform\n");
} }
/* add our application-specific commands */ /* add our application-specific commands */
@@ -181,12 +179,12 @@ void setup_platform(void)
// read config_data from fram... // read config_data from fram...
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - Reading Calibration Config from FRAM...\n", millis()); gCatena.SafePrintf("Reading Calibration Config from FRAM...\n");
} }
gCatena.getFram()->getField(cFramStorage::kAppConf, (uint8_t *)&config_data, sizeof(config_data)); gCatena.getFram()->getField(cFramStorage::kAppConf, (uint8_t *)&config_data, sizeof(config_data));
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_platform, this is the configuration\n", millis()); gCatena.SafePrintf("Setup_platform, this is the configuration\n");
gCatena.SafePrintf("cal_w1_0: %d\n", config_data.cal_w1_0); gCatena.SafePrintf("cal_w1_0: %d\n", config_data.cal_w1_0);
gCatena.SafePrintf("cal_w2_0: %d\n", config_data.cal_w2_0); gCatena.SafePrintf("cal_w2_0: %d\n", config_data.cal_w2_0);
gCatena.SafePrintf("cal_w1_factor: %d.%03d\n", (int)config_data.cal_w1_factor, (int)abs(config_data.cal_w1_factor * 1000) % 1000); gCatena.SafePrintf("cal_w1_factor: %d.%03d\n", (int)config_data.cal_w1_factor, (int)abs(config_data.cal_w1_factor * 1000) % 1000);
@@ -253,6 +251,7 @@ void setup_platform(void)
} }
gLoRaWAN.SetReceiveBufferBufferCb(receiveMessage); gLoRaWAN.SetReceiveBufferBufferCb(receiveMessage);
setTxCycleTime(CATCFG_T_CYCLE_INITIAL, CATCFG_INTERVAL_COUNT_INITIAL);
gCatena.registerObject(&gLoRaWAN); gCatena.registerObject(&gLoRaWAN);
/* find the platform */ /* find the platform */
@@ -285,7 +284,7 @@ void setup_platform(void)
void setup_bme280(void) void setup_bme280(void)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_bme280\n", millis()); gCatena.SafePrintf("Setup_bme280\n");
} }
if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) { if (gBME280.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep)) {
@@ -300,7 +299,7 @@ void setup_bme280(void)
bool setup_scales(void) bool setup_scales(void)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_scales\n", millis()); gCatena.SafePrintf("Setup_scales\n");
} }
bool res; bool res;
@@ -310,7 +309,7 @@ bool setup_scales(void)
PowerupScale(); PowerupScale();
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_scale done\n", millis()); gCatena.SafePrintf("Setup_scale done\n");
} }
return res; return res;
@@ -319,14 +318,14 @@ bool setup_scales(void)
void setup_flash(void) void setup_flash(void)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_flash\n", millis()); gCatena.SafePrintf("setup_flash\n");
} }
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) { if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS)) {
fFlash = true; fFlash = true;
gFlash.powerDown(); gFlash.powerDown();
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - FLASH found, but power down\n", millis()); gCatena.SafePrintf("FLASH found, but power down\n");
} }
} }
else { else {
@@ -334,7 +333,7 @@ void setup_flash(void)
gFlash.end(); gFlash.end();
gSPI2.end(); gSPI2.end();
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - No FLASH found: check hardware\n", millis()); gCatena.SafePrintf("FLASH found: check hardware\n");
} }
} }
} }
@@ -342,7 +341,7 @@ void setup_flash(void)
void setup_uplink(void) void setup_uplink(void)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - setup_uplink\n", millis()); gCatena.SafePrintf("setup_uplink\n");
} }
LMIC_setClockError(1 * 65536 / 100); LMIC_setClockError(1 * 65536 / 100);
@@ -353,14 +352,14 @@ void setup_uplink(void)
// Do an unjoin, so every reboot will trigger a join // Do an unjoin, so every reboot will trigger a join
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - do an unjoin...\n", millis()); gCatena.SafePrintf("do an unjoin...\n");
} }
LMIC_unjoin(); LMIC_unjoin();
/* trigger a join by sending the first packet */ /* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) { if (!(gCatena.GetOperatingFlags() & static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))) {
if (!gLoRaWAN.IsProvisioned()) if (!gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("%010d - LoRaWAN not provisioned yet. Use the commands to set it up.\n"); gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else { else {
if (config_data.debug_level > 1) { if (config_data.debug_level > 1) {
gLed.Set(LedPattern::Joining); gLed.Set(LedPattern::Joining);
@@ -421,7 +420,7 @@ void ClearLoraData(void)
void ShowLORAData(bool firstTime) void ShowLORAData(bool firstTime)
{ {
gCatena.SafePrintf("%010d - ShowLORAData\n", millis()); gCatena.SafePrintf("ShowLORAData\n");
if (firstTime) { if (firstTime) {
@@ -502,7 +501,7 @@ uint8_t GetVBatValue(int millivolts)
void DoDeepSleep(uint32_t sleep_time) void DoDeepSleep(uint32_t sleep_time)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - now going to deep sleep\n", millis()); gCatena.SafePrintf("DoDeepSleep, now going to deep sleep\n");
} }
// Prepare Deep Sleep // Prepare Deep Sleep
@@ -510,23 +509,16 @@ void DoDeepSleep(uint32_t sleep_time)
gLed.Set(LedPattern::Off); gLed.Set(LedPattern::Off);
} }
Serial.end(); deepSleepPrepare();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
// Now sleeping... // Now sleeping...
gCatena.Sleep(sleep_time); gCatena.Sleep(sleep_time);
// Recover from wakeup... // Recover from wakeup...
Serial.begin(); deepSleepRecovery();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - done with deep sleep\n", millis()); gCatena.SafePrintf("done with deep sleep\n");
} }
} }
@@ -537,11 +529,10 @@ void ReadSensors(SENSOR_data &sensor_data) {
long w2_0_real; long w2_0_real;
// vBat // vBat
gCatena.poll();
int vbat_mv = (int)(gCatena.ReadVbat() * 1000.0f); int vbat_mv = (int)(gCatena.ReadVbat() * 1000.0f);
res.vbat = GetVBatValue(vbat_mv); res.vbat = GetVBatValue(vbat_mv);
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - vBat: %d mV\n", millis(), vbat_mv); gCatena.SafePrintf("vBat: %d mV\n", vbat_mv);
} }
// Read Scales // Read Scales
@@ -549,43 +540,40 @@ void ReadSensors(SENSOR_data &sensor_data) {
w2_0_real = config_data.cal_w2_0; w2_0_real = config_data.cal_w2_0;
if (setup_scales()) { if (setup_scales()) {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - LoadCell is ready.\n", millis()); gCatena.SafePrintf("LoadCell is ready.\n");
} }
gCatena.poll();
if (config_data.cal_w1_0 != NOT_ATTACHED) { if (config_data.cal_w1_0 != NOT_ATTACHED) {
res.weight1 = (int32_t)ReadScale('A'); res.weight1 = (int32_t)ReadScale('A');
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - Load_cell 1 weight1_current: %ld\n", millis(), res.weight1); gCatena.SafePrintf("Load_cell 1 weight1_current: %ld\n", res.weight1);
} }
} else { } else {
res.weight1 = 0; res.weight1 = 0;
w1_0_real = 0; w1_0_real = 0;
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - Load_cell 1 is disabled\n", millis()); gCatena.SafePrintf("Load_cell 1 is disabled\n");
} }
} }
gCatena.poll();
if (config_data.cal_w2_0 != NOT_ATTACHED) { if (config_data.cal_w2_0 != NOT_ATTACHED) {
res.weight2 = (int32_t)ReadScale('B'); res.weight2 = (int32_t)ReadScale('B');
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - Load_cell 2 weight2_current: %ld\n", millis(), res.weight2); gCatena.SafePrintf("Load_cell 2 weight2_current: %ld\n", res.weight2);
} }
} else { } else {
res.weight2 = 0; res.weight2 = 0;
w2_0_real = 0; w2_0_real = 0;
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - Load_cell 2 is disabled\n", millis()); gCatena.SafePrintf("Load_cell 2 is disabled\n");
} }
} }
} }
else { else {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - LoadCell not ready.\n", millis()); gCatena.SafePrintf("LoadCell not ready.\n");
} }
} }
// Disable Power // Disable Power
gCatena.poll();
PowerdownScale(); PowerdownScale();
// Gewicht berechnen // Gewicht berechnen
@@ -605,19 +593,16 @@ void ReadSensors(SENSOR_data &sensor_data) {
res.weight = (uint16_t)weight_current32; res.weight = (uint16_t)weight_current32;
if (fBme) { if (fBme) {
gCatena.poll();
/* warm up the BME280 by discarding a measurement */ /* warm up the BME280 by discarding a measurement */
(void)gBME280.readTemperature(); (void)gBME280.readTemperature();
gCatena.poll();
Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity(); Adafruit_BME280::Measurements m = gBME280.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C // temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10. // pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256. // humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf( gCatena.SafePrintf(
"%010d - BME280: T: %d P: %d RH: %d\n", "BME280: T: %d P: %d RH: %d\n",
millis(),
(int)m.Temperature, (int)m.Temperature,
(int)m.Pressure, (int)m.Pressure,
(int)m.Humidity); (int)m.Humidity);
@@ -626,7 +611,7 @@ void ReadSensors(SENSOR_data &sensor_data) {
res.humidity = (uint8_t)m.Humidity; res.humidity = (uint8_t)m.Humidity;
res.pressure = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET); res.pressure = (uint8_t)((m.Pressure / 100) - PRESSURE_OFFSET);
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - pressure_current: %d\n", millis(), res.pressure); gCatena.SafePrintf("pressure_current: %d\n", res.pressure);
} }
} }
@@ -647,7 +632,7 @@ void StartNewIteration() {
// vBus // vBus
float vBus = gCatena.ReadVbus(); float vBus = gCatena.ReadVbus();
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - vBus: %d mV\n", millis(), (int)(vBus * 1000.0f)); gCatena.SafePrintf("vBus: %d mV\n", (int)(vBus * 1000.0f));
} }
fUsbPower = (vBus > 4.3) ? true : false; fUsbPower = (vBus > 4.3) ? true : false;
@@ -690,32 +675,48 @@ void StartNewIteration() {
// we send data the first time the system is started, when the array is full // we send data the first time the system is started, when the array is full
// or when the weight has fallen more than threshold or the first measurement is // or when the weight has fallen more than threshold or the first measurement is
// more than one hour old (which should not happen :-) ) // more than one hour old (which should not happen :-) )
if ( (next_package_is_init_package) || (my_position >= MAX_VALUES_TO_SEND) || ((last_sensor_reading.weight - current_sensor_reading.weight) > SEND_DIFF_THRESHOLD_5GRAMS) || ((millis() - timer_pos0) > 3600000)) { if ( (next_package_is_init_package) || (my_position >= MAX_VALUES_TO_SEND) || (abs(last_sensor_reading.weight - current_sensor_reading.weight) > SEND_DIFF_THRESHOLD_5GRAMS) || ((millis() - timer_pos0) > 3600000)) {
lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60); lora_data.offset_last_reading = (uint8_t)((millis() - timer_pos0) / 1000 / 60);
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - startSendingUplink(), my_position: %d, iteration: %d, package_counter: %d\n", millis(), my_position, iteration, package_counter); gCatena.SafePrintf("startSendingUplink(), my_position: %d, iteration: %d, package_counter: %d\n", my_position, iteration, package_counter);
} }
// the first 12 packets are "Init-Packets" or each INIT_PACKAGE_INTERVAL ... // the first <INIT_PACKETS> packets are "Init-Packets" or each INIT_PACKAGE_INTERVAL ...
startSendingUplink(next_package_is_init_package); startSendingUplink(next_package_is_init_package);
next_package_is_init_package = ((iteration < 12) || ((package_counter % INIT_PACKAGE_INTERVAL) == 0)); next_package_is_init_package = ((iteration < INIT_PACKETS) || ((package_counter % INIT_PACKAGE_INTERVAL) == 0));
if (config_data.debug_level > 1) { if (config_data.debug_level > 1) {
gLed.Set(LedPattern::TwoShort); gLed.Set(LedPattern::TwoShort);
} }
// Loop while sending is in progress, timeout just in case after 300 seconds // Loop sending is in progress, timeout just in case after 300 seconds
long start_time = millis(); long start_time = millis();
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - waiting while send is in progress\n", millis()); gCatena.SafePrintf("waiting while send is in progress\n");
} }
while (send_in_progress && ((millis() - start_time) < 300000)) while (send_in_progress && ((millis() - start_time) < 300000))
{ {
gCatena.poll(); gCatena.poll();
yield(); yield();
} }
// handle timeout...
if (send_in_progress) {
if (config_data.debug_level > 0) {
gCatena.SafePrintf("looks like we timed out waiting for sending to finish...\n", wait_time);
}
LMIC_clrTxData();
// we sleep 10 seconds...
start_time = millis();
while (send_in_progress && ((millis() - start_time) < 10000))
{
gCatena.poll();
yield();
}
send_in_progress = false;
}
wait_time = (uint32_t)((millis() - start_time) / 1000); wait_time = (uint32_t)((millis() - start_time) / 1000);
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - end waiting, wait time was %d seconds\n", millis(), wait_time); gCatena.SafePrintf("end waiting, wait time was %d seconds\n", wait_time);
} }
} }
@@ -732,17 +733,17 @@ void StartNewIteration() {
sleep_time_sec = 5; sleep_time_sec = 5;
} }
// for the first 12 iterations, we set the sleep time to 10 seconds only... // for the first <INIT_PACKETS> iterations, we set the sleep time to 120 seconds only...
if (iteration <= 12) { if (iteration <= INIT_PACKETS) {
sleep_time_sec = 10; sleep_time_sec = 120;
} }
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - now going to sleep for %d seconds...\n", millis(), sleep_time_sec); gCatena.SafePrintf("now going to sleep for %d seconds...\n", sleep_time_sec);
if (fUsbPower) { if (fUsbPower) {
gCatena.SafePrintf("%010d - USB Power is on\n", millis()); gCatena.SafePrintf("USB Power is on\n");
} else { } else {
gCatena.SafePrintf("%010d - USB Power is off\n", millis()); gCatena.SafePrintf("USB Power is off\n");
} }
//Serial.flush(); //Serial.flush();
if (config_data.debug_level > 1) { if (config_data.debug_level > 1) {
@@ -750,22 +751,38 @@ void StartNewIteration() {
} }
} }
// if we need to periodically reboot, we can do it now...
if (uint32_t(millis()) > gRebootMs) {
// time to reboot
if (config_data.debug_level > 0) {
gCatena.SafePrintf("Reached threshold to reboot...\n");
Serial.flush();
}
NVIC_SystemReset();
}
if (config_data.debug_level > 0) {
gCatena.SafePrintf("LMIC.opmode just before Sleeping: %#x\n", LMIC.opmode);
}
if (!fUsbPower) { if (!fUsbPower) {
DoDeepSleep(sleep_time_sec); DoDeepSleep(sleep_time_sec);
os_setTimedCallback( if (! stop_iterations) {
&iterationJob, StartNewIteration();
os_getTime() + sec2osticks(2), }
startNewIterationCb);
} }
else { else {
if (! stop_iterations) {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - light sleep; os_setTimedCallback for startNewIterationCb in %d...seconds\n", millis(), sleep_time_sec); gCatena.SafePrintf("light sleep; os_setTimedCallback for startNewIterationCb in %d...seconds\n", sleep_time_sec);
} }
os_setTimedCallback( os_setTimedCallback(
&iterationJob, &iterationJob,
os_getTime() + sec2osticks(sleep_time_sec), os_getTime() + sec2osticks(sleep_time_sec),
startNewIterationCb); startNewIterationCb);
} }
}
} }
void startSendingUplink(bool firstTime) void startSendingUplink(bool firstTime)
@@ -794,16 +811,29 @@ void startSendingUplink(bool firstTime)
if (firstTime) { if (firstTime) {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - SendBuffer firstTime\n", millis()); gCatena.SafePrintf("SendBuffer firstTime\n");
} }
gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed, kUplinkPort); if (gLoRaWAN.SendBuffer((uint8_t*)&lora_data_first, sizeof(LORA_data_first), sendBufferDoneCb, NULL, fConfirmed, kUplinkPort)) {
package_counter++; package_counter++;
if (config_data.debug_level > 0) {
gCatena.SafePrintf("LMIC.opmode just after SendBuffer (successful): %#x\n", LMIC.opmode);
} else {
gCatena.SafePrintf("LMIC.opmode just before SendBuffer (failed): %#x\n", LMIC.opmode);
}
}
} else { } else {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - SendBuffer not firstTime\n", millis()); gCatena.SafePrintf("LMIC.opmode just before SendBuffer: %#x\n", LMIC.opmode);
gCatena.SafePrintf("SendBuffer not firstTime\n");
} }
gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed, kUplinkPort); if (gLoRaWAN.SendBuffer((uint8_t*)&lora_data, sizeof(LORA_data), sendBufferDoneCb, NULL, fConfirmed, kUplinkPort)) {
package_counter++; package_counter++;
if (config_data.debug_level > 0) {
gCatena.SafePrintf("LMIC.opmode just after SendBuffer (successful): %#x\n", LMIC.opmode);
} else {
gCatena.SafePrintf("LMIC.opmode just before SendBuffer (failed): %#x\n", LMIC.opmode);
}
}
} }
ClearLoraData(); ClearLoraData();
@@ -817,6 +847,7 @@ static void sendBufferDoneCb(
if (config_data.debug_level > 1) { if (config_data.debug_level > 1) {
gLed.Set(LedPattern::Settling); gLed.Set(LedPattern::Settling);
gCatena.SafePrintf("LMIC.opmode in sendBufferDoneCb: %#x\n", LMIC.opmode);
} }
pFn = settleDoneCb; pFn = settleDoneCb;
@@ -831,7 +862,7 @@ static void sendBufferDoneCb(
gLoRaWAN.Shutdown(); gLoRaWAN.Shutdown();
} }
else if (config_data.debug_level > 0) { else if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - send buffer failed\n", millis()); gCatena.SafePrintf("send buffer failed, LMIC.opmode: %#x\n", LMIC.opmode);
} }
} }
@@ -855,128 +886,36 @@ static void txNotProvisionedCb(
} }
} }
static void settleDoneCb(
osjob_t* pSendJob)
{
const bool fDeepSleep = checkDeepSleep();
if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - settleDoneCb\n", millis());
}
if (config_data.debug_level > 2) {
// Terry vv
gCatena.SafePrintf("LMIC.rxDelay: %i\n", LMIC.rxDelay);
gCatena.SafePrintf("LMIC.dn2Dr: %i\n", LMIC.dn2Dr);
gCatena.SafePrintf("LMIC.dn2Freq: %i\n", LMIC.dn2Freq);
gCatena.SafePrintf("LMIC.rx1DrOffset: %i\n", LMIC.rx1DrOffset);
gCatena.SafePrintf("LMIC.adrAckReq: %i\n", LMIC.adrAckReq);
gCatena.SafePrintf("LMIC.adrEnabled: %i\n", LMIC.adrEnabled);
// Terry ^^
}
if (uint32_t(millis()) > gRebootMs) {
// time to reboot
NVIC_SystemReset();
}
if (! g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
/* count what we're up to */
updateSleepCounters();
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void) bool checkDeepSleep(void)
{ {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & return !fUsbPower;
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDeepSleepTest);
bool fDeepSleep;
if (fDeepSleepTest)
{
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr())
{
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDisableDeepSleep))
{
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0)
{
fDeepSleep = true;
}
else
{
fDeepSleep = false;
}
return fDeepSleep;
} }
void doSleepAlert(const bool fDeepSleep) void doSleepAlert(const bool fDeepSleep)
{ {
g_fPrintedSleeping = true; if (config_data.debug_level > 0) {
gCatena.SafePrintf("We wait until is is safe to go to sleep...\n");
if (fDeepSleep)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDeepSleepTest);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
if (config_data.debug_level > 2) {
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay
);
}
// sleep and print
if (config_data.debug_level > 2) {
gLed.Set(LedPattern::TwoShort);
} }
for (auto n = deepSleepDelay; n > 0; --n) for (int i = 0; i <= 15; i++) {
{ long prevPrint = millis();
uint32_t tNow = millis(); while (os_queryTimeCriticalJobs(ms2osticks(2000)) != 0)
while (uint32_t(millis() - tNow) < 1000)
{ {
gCatena.poll(); gCatena.poll();
yield(); yield();
} if (millis() - prevPrint > 1000) {
if (config_data.debug_level > 2) { prevPrint = millis();
gCatena.SafePrintf("."); if (config_data.debug_level > 0) {
gCatena.SafePrintf("LMIC.opmode: %#x in loop %d\n", LMIC.opmode, i);
} }
} }
if (config_data.debug_level > 2) {
gCatena.SafePrintf("\nStarting deep sleep.\n");
}
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100)
{
gCatena.poll();
yield();
} }
} }
else if (config_data.debug_level > 2) {
gCatena.SafePrintf("using light sleep\n"); if (config_data.debug_level > 0) {
gCatena.SafePrintf("Now it is safe to go to sleep\n");
} }
} }
void updateSleepCounters(void) void updateSleepCounters(void)
@@ -990,10 +929,9 @@ void updateSleepCounters(void)
else if (gTxCycleCount == 1) else if (gTxCycleCount == 1)
{ {
// it's now one (otherwise we couldn't be here.) // it's now one (otherwise we couldn't be here.)
if (config_data.debug_level > 2) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("resetting tx cycle to default: %u\n", CATCFG_T_CYCLE); gCatena.SafePrintf("resetting tx cycle to default: %u\n", CATCFG_T_CYCLE);
} }
gTxCycleCount = 0; gTxCycleCount = 0;
gTxCycle = CATCFG_T_CYCLE; gTxCycle = CATCFG_T_CYCLE;
} }
@@ -1003,31 +941,34 @@ void updateSleepCounters(void)
} }
} }
void doDeepSleep(osjob_t *pJob)
static void settleDoneCb(
osjob_t* pSendJob)
{ {
bool const fDeepSleepTest = gCatena.GetOperatingFlags() & if (config_data.debug_level > 0) {
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDeepSleepTest); gCatena.SafePrintf("settleDoneCb - we are at the end of the callback chain!\n");
uint32_t const sleepInterval = CATCFG_GetInterval( }
fDeepSleepTest ? CATCFG_T_CYCLE_TEST : gTxCycle
);
/* ok... now it's time for a deep sleep */ const bool fDeepSleep = checkDeepSleep();
gLed.Set(LedPattern::Off);
deepSleepPrepare();
/* sleep */ if (uint32_t(millis()) > gRebootMs)
gCatena.Sleep(sleepInterval); {
// time to reboot
NVIC_SystemReset();
}
/* recover from sleep */ doSleepAlert(fDeepSleep);
deepSleepRecovery();
/* and now... we're awake again. trigger another measurement */ /* count what we're up to */
sleepDoneCb(pJob); updateSleepCounters();
send_in_progress = false;
} }
void deepSleepPrepare(void) void deepSleepPrepare(void)
{ {
Serial.end(); Serial.end();
Wire.endTransmission(true);
Wire.end(); Wire.end();
SPI.end(); SPI.end();
if (fFlash) if (fFlash)
@@ -1043,54 +984,11 @@ void deepSleepRecovery(void)
gSPI2.begin(); gSPI2.begin();
} }
void doLightSleep(osjob_t *pJob)
{
uint32_t interval = sec2osticks(CATCFG_GetInterval(gTxCycle));
gLed.Set(LedPattern::Sleeping);
if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fQuickLightSleep))
{
interval = 1;
}
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
&iterationJob,
os_getTime() + interval,
sleepDoneCb
);
}
static void sleepDoneCb(osjob_t* pJob)
{
if (config_data.debug_level > 1) {
gLed.Set(LedPattern::WarmingUp);
}
if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - sleepDoneCb\n", millis());
}
os_setTimedCallback(
pJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb);
}
static void warmupDoneCb(osjob_t* pJob)
{
if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - warmupDoneCb\n", millis());
}
send_in_progress = false;
}
static void startNewIterationCb(osjob_t* pJob) static void startNewIterationCb(osjob_t* pJob)
{ {
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - startNewIterationCb\n", millis()); gCatena.SafePrintf("startNewIterationCb\n");
} }
if (! stop_iterations) { if (! stop_iterations) {
@@ -1100,6 +998,9 @@ static void startNewIterationCb(osjob_t* pJob)
static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage, size_t nMessage) static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage, size_t nMessage)
{ {
unsigned txCycle;
unsigned txCount;
long cal_w1_0; long cal_w1_0;
long cal_w2_0; long cal_w2_0;
float cal_w1_factor; float cal_w1_factor;
@@ -1110,10 +1011,8 @@ static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage
float fval; float fval;
} u; } u;
SENSOR_data temp_sensor_data;
if (config_data.debug_level > 0) { if (config_data.debug_level > 0) {
gCatena.SafePrintf("%010d - receiveMessage was called!!!\n", millis()); gCatena.SafePrintf("receiveMessage was called!!!\n");
} }
if (config_data.debug_level > 2) { if (config_data.debug_level > 2) {
@@ -1215,12 +1114,64 @@ static void receiveMessage(void *pContext, uint8_t port, const uint8_t *pMessage
lora_data_first.cal_w2_factor = config_data.cal_w2_factor; lora_data_first.cal_w2_factor = config_data.cal_w2_factor;
} }
} }
if (port == 0)
{
return;
}
else if (! (port == 1 && 2 <= nMessage && nMessage <= 3))
{
if (config_data.debug_level > 0) {
gCatena.SafePrintf("invalid message port(%02x)/length(%x)\n",
port, nMessage
);
}
return;
}
txCycle = (pMessage[0] << 8) | pMessage[1];
if (txCycle < CATCFG_T_MIN || txCycle > CATCFG_T_MAX)
{
if (config_data.debug_level > 0) {
gCatena.SafePrintf("tx cycle time out of range: %u\n", txCycle);
}
return;
}
// byte [2], if present, is the repeat count.
// explicitly sending zero causes it to stick.
txCount = CATCFG_INTERVAL_COUNT;
if (nMessage >= 3)
{
txCount = pMessage[2];
}
setTxCycleTime(txCycle, txCount);
} }
void setTxCycleTime(unsigned txCycle, unsigned txCount)
{
if (txCount > 0) {
if (config_data.debug_level > 0) {
gCatena.SafePrintf("message cycle time %u seconds for %u messages\n", txCycle, txCount);
}
}
else if (config_data.debug_level > 0) {
gCatena.SafePrintf("message cycle time %u seconds indefinitely\n", txCycle);
}
gTxCycle = txCycle;
gTxCycleCount = txCount;
}
/* process "application hello" -- args are ignored */ /* process "application hello" -- args are ignored */
// argv[0] is "hello" // argv[0] is "hello"
// argv[1..argc-1] are the (ignored) arguments // argv[1..argc-1] are the (ignored) arguments
cCommandStream::CommandStatus cmdHello(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdHello(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
pThis->printf("Hello, world!\n"); pThis->printf("Hello, world!\n");
@@ -1228,7 +1179,7 @@ cCommandStream::CommandStatus cmdHello(cCommandStream *pThis, void *pContext, in
} }
cCommandStream::CommandStatus cmdGetCalibrationSettings(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdGetCalibrationSettings(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
pThis->printf("{\n"); pThis->printf("{\n");
pThis->printf(" \"cal_w1_0\": \"%d\",\n", config_data.cal_w1_0); pThis->printf(" \"cal_w1_0\": \"%d\",\n", config_data.cal_w1_0);
@@ -1240,7 +1191,7 @@ cCommandStream::CommandStatus cmdGetCalibrationSettings(cCommandStream *pThis, v
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdGetSensorReadings(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdGetSensorReadings(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
SENSOR_data temp_sensor_data; SENSOR_data temp_sensor_data;
@@ -1258,21 +1209,21 @@ cCommandStream::CommandStatus cmdGetSensorReadings(cCommandStream *pThis, void *
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdGetScale1(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdGetScale1(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
pThis->printf("getscale1\n"); pThis->printf("getscale1\n");
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdGetScale2(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdGetScale2(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
pThis->printf("getscale2\n"); pThis->printf("getscale2\n");
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdCalibrateZeroScaleA(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdCalibrateZeroScaleA(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
setup_scales(); setup_scales();
config_data.cal_w1_0 = (int32_t)ReadScale('A'); config_data.cal_w1_0 = (int32_t)ReadScale('A');
@@ -1282,7 +1233,7 @@ cCommandStream::CommandStatus cmdCalibrateZeroScaleA(cCommandStream *pThis, void
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdCalibrateZeroScaleB(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdCalibrateZeroScaleB(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
setup_scales(); setup_scales();
config_data.cal_w2_0 = (int32_t)ReadScale('B'); config_data.cal_w2_0 = (int32_t)ReadScale('B');
@@ -1292,7 +1243,7 @@ cCommandStream::CommandStatus cmdCalibrateZeroScaleB(cCommandStream *pThis, void
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdCalibrateScaleA(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdCalibrateScaleA(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
String w1_gramm(argv[1]); String w1_gramm(argv[1]);
long weight1; long weight1;
@@ -1314,7 +1265,7 @@ cCommandStream::CommandStatus cmdCalibrateScaleA(cCommandStream *pThis, void *pC
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdCalibrateScaleB(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdCalibrateScaleB(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
String w2_gramm(argv[1]); String w2_gramm(argv[1]);
long weight2; long weight2;
@@ -1336,18 +1287,20 @@ cCommandStream::CommandStatus cmdCalibrateScaleB(cCommandStream *pThis, void *pC
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdSetDebugLevel(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdSetDebugLevel(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
String s_debug_level(argv[1]); String s_debug_level(argv[1]);
config_data.debug_level = s_debug_level.toInt(); config_data.debug_level = s_debug_level.toInt();
gCatena.getFram()->saveField(cFramStorage::kAppConf, (const uint8_t *)&config_data, sizeof(config_data)); gCatena.getFram()->saveField(cFramStorage::kAppConf, (const uint8_t *)&config_data, sizeof(config_data));
SetScalesDebugLevel(config_data.debug_level);
pThis->printf("{ \"msg\": \"set_debug_level was successful\" }\n"); pThis->printf("{ \"msg\": \"set_debug_level was successful\" }\n");
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdGetDebugLevel(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdGetDebugLevel(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
gCatena.getFram()->saveField(cFramStorage::kAppConf, (const uint8_t *)&config_data, sizeof(config_data)); gCatena.getFram()->saveField(cFramStorage::kAppConf, (const uint8_t *)&config_data, sizeof(config_data));
@@ -1356,7 +1309,7 @@ cCommandStream::CommandStatus cmdGetDebugLevel(cCommandStream *pThis, void *pCon
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
} }
cCommandStream::CommandStatus cmdStopIterations(cCommandStream *pThis, void *pContext, int argc, char **argv) cCommandStream::CommandStatus cmdStopIterations(cCommandStream * pThis, void *pContext, int argc, char **argv)
{ {
stop_iterations = true; stop_iterations = true;
return cCommandStream::CommandStatus::kSuccess; return cCommandStream::CommandStatus::kSuccess;
+7 -6
View File
@@ -15,10 +15,10 @@ enum {
// add measurement and broadcast time, but we attempt // add measurement and broadcast time, but we attempt
// to compensate for the gross effects below. // to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
//CATCFG_T_CYCLE = 30, // for Testing //CATCFG_T_CYCLE = 30, // for Testing (Swisscom Compliance)
CATCFG_T_CYCLE_TEST = 30, // every 10 seconds CATCFG_T_CYCLE_TEST = 30, // every 30 seconds
CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially
CATCFG_INTERVAL_COUNT_INITIAL = 30, // repeat for 15 minutes CATCFG_INTERVAL_COUNT_INITIAL = 10, // repeat for 5 minutes
CATCFG_T_REBOOT = 30 * 24 * 60 * 60, // reboot every 30 days CATCFG_T_REBOOT = 30 * 24 * 60 * 60, // reboot every 30 days
}; };
@@ -26,7 +26,7 @@ enum {
enum { enum {
CATCFG_T_WARMUP = 1, CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5, CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE), CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE + 4),
CATCFG_T_MIN = CATCFG_T_OVERHEAD, CATCFG_T_MIN = CATCFG_T_OVERHEAD,
CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max. CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max.
CATCFG_INTERVAL_COUNT = 30, CATCFG_INTERVAL_COUNT = 30,
@@ -56,7 +56,7 @@ enum {
| |
\****************************************************************************/ \****************************************************************************/
static const int32_t fwVersion = 20200513; static const int32_t fwVersion = 20200602;
static const byte INIT_PACKAGE_INTERVAL = 100; // send an init package every 100 packages; static const byte INIT_PACKAGE_INTERVAL = 100; // send an init package every 100 packages;
static const byte MAX_VALUES_TO_SEND = 8; static const byte MAX_VALUES_TO_SEND = 8;
@@ -64,8 +64,9 @@ static const byte MAX_VALUES_TO_SEND = 8;
static const uint8_t LORA_DATA_VERSION = 1; static const uint8_t LORA_DATA_VERSION = 1;
static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128; static const uint8_t LORA_DATA_VERSION_FIRST_PACKAGE = 128;
static const uint32_t PRESSURE_OFFSET = 825; static const uint32_t PRESSURE_OFFSET = 825;
static const uint16_t SEND_DIFF_THRESHOLD_5GRAMS = 10; // when weight value drops by 50g, then send data static const uint16_t SEND_DIFF_THRESHOLD_5GRAMS = 20; // when weight changes by 100g, then send data
static const long NOT_ATTACHED = -2147483648; static const long NOT_ATTACHED = -2147483648;
static const byte INIT_PACKETS = 5;
// must be 64 bytes long (size of kAppConf) // must be 64 bytes long (size of kAppConf)
typedef struct { typedef struct {
+9 -4
View File
@@ -11,11 +11,16 @@ Q2HX711 hx711(A1, A0);
byte debug_level; byte debug_level;
void SetScalesDebugLevel(byte dbg_level)
{
debug_level = dbg_level;
}
bool SetupScales(byte dbg_level) bool SetupScales(byte dbg_level)
{ {
debug_level = dbg_level; debug_level = dbg_level;
if (debug_level > 0) { if (debug_level > 0) {
gCatena.SafePrintf("%010d - setup_scales\n", millis()); gCatena.SafePrintf("setup_scales\n");
} }
bool res; bool res;
@@ -25,7 +30,7 @@ bool SetupScales(byte dbg_level)
pinMode(D10, OUTPUT); pinMode(D10, OUTPUT);
if (debug_level > 0) { if (debug_level > 0) {
gCatena.SafePrintf("%010d - setup_scale done\n", millis()); gCatena.SafePrintf("setup_scale done\n");
} }
return res; return res;
@@ -47,7 +52,7 @@ long ReadScale(char channel)
long readings[num_scale_readings]; // create arry to hold readings long readings[num_scale_readings]; // create arry to hold readings
if (debug_level > 0) { if (debug_level > 0) {
gCatena.SafePrintf("%010d - my_read_average, measurements:\n", millis()); gCatena.SafePrintf("my_read_average, measurements:\n");
} }
for (int i = 0; i < num_scale_readings; i++) { for (int i = 0; i < num_scale_readings; i++) {
@@ -84,6 +89,6 @@ void PowerupScale()
delay(400); delay(400);
if (debug_level > 0) { if (debug_level > 0) {
gCatena.SafePrintf("%010d - setup_scale done\n", millis()); gCatena.SafePrintf("setup_scale done\n");
} }
} }
+102 -25
View File
@@ -1,3 +1,5 @@
#pragma once
#include <Wire.h> #include <Wire.h>
#ifndef _HELPER_H_ #ifndef _HELPER_H_
@@ -6,36 +8,70 @@
#include "SparkFun_Qwiic_Scale_NAU7802_Arduino_Library.h" #include "SparkFun_Qwiic_Scale_NAU7802_Arduino_Library.h"
#define SAMPLES 10 #define SAMPLES 5
NAU7802 myScale; //Create instance of the NAU7802 class NAU7802 myScale; //Create instance of the NAU7802 class
byte debug_level; byte debug_level;
byte interruptPin = A0; //byte interruptPin = A0;
void SetScalesDebugLevel(byte dbg_level)
{
debug_level = dbg_level;
}
bool InitializeScales()
{
bool result;
result = myScale.reset(); //Reset all registers
result &= myScale.powerUp(); //Power on analog and digital sections of the scale
result &= myScale.setIntPolarityHigh();
result &= myScale.setLDO(NAU7802_LDO_3V3); //Set LDO to 3.3V
result &= myScale.setGain(NAU7802_GAIN_128); //Set gain to 128
result &= myScale.setSampleRate(NAU7802_SPS_40); //Set samples per second to 40
result &= myScale.setRegister(NAU7802_ADC, 0x30); //Turn off CLK_CHP. From 9.1 power on sequencing.
result &= myScale.clearBit(NAU7802_PGA_PWR_PGA_CAP_EN, NAU7802_PGA_PWR);
//result &= myScale.setRegister(NAU7802_OTP_B1, 0x30);
//result &= myScale.setRegister(NAU7802_PGA, NAU7802_PGA_OUT_EN | NAU7802_PGA_CHP_DIS);
result &= myScale.calibrateAFE(); //Re-cal analog front end when we change gain, sample rate, or channel
return result;
}
bool SetupScales(byte dbg_level) bool SetupScales(byte dbg_level)
{ {
debug_level = dbg_level; debug_level = dbg_level;
if (debug_level > 0) {
gCatena.SafePrintf("SetupScales start\n");
}
// pinMode(interruptPin, INPUT);
pinMode(interruptPin, INPUT); if (!myScale.begin(Wire, false))
Wire.begin();
if (!myScale.begin())
{ {
Serial.println("Scale not detected. Please check wiring. Freezing..."); gCatena.SafePrintf("Scale not detected. Please check wiring. Freezing...\n");
return false; return false;
} }
Serial.println("Scale detected!"); gCatena.SafePrintf("Scale detected!\n");
myScale.setIntPolarityHigh(); bool result = InitializeScales();
delay(500); if (debug_level > 0) {
gCatena.SafePrintf("SetupScales done, result: %d\n", result);
}
return true; return result;
} }
long ReadScale(char channel) long ReadScale(char channel)
{ {
long res;
if (debug_level > 0) {
gCatena.SafePrintf("ReadScale Start, Channel %c\n", channel);
}
uint8_t channelNumber; uint8_t channelNumber;
if (channel == 'B') { if (channel == 'B') {
channelNumber = NAU7802_CHANNEL_1; channelNumber = NAU7802_CHANNEL_1;
@@ -44,31 +80,44 @@ long ReadScale(char channel)
} }
long startTime = millis(); long startTime = millis();
myScale.setChannel(channelNumber); myScale.setChannel(channelNumber);
myScale.clearBit(NAU7802_PGA_PWR_PGA_CAP_EN, NAU7802_PGA_PWR); bool calibrate_success = myScale.calibrateAFE();
myScale.setSampleRate(NAU7802_SPS_10); if (! calibrate_success) {
myScale.setLDO(NAU7802_LDO_2V7); if (debug_level > 0) {
myScale.calibrateAFE(); gCatena.SafePrintf("Error: Calibration not successful!\n");
//delay(500); }
}
long res; if (myScale.available()) {
long dummy = myScale.getReading();
}
int const num_scale_readings = SAMPLES; // number of instantaneous scale readings to calculate the median int const num_scale_readings = SAMPLES; // number of instantaneous scale readings to calculate the median
// we use the median, not the average, see https://community.particle.io/t/boron-gpio-provides-less-current-than-electrons-gpio/46647/13 // we use the median, not the average, see https://community.particle.io/t/boron-gpio-provides-less-current-than-electrons-gpio/46647/13
long readings[num_scale_readings]; // create arry to hold readings long readings[num_scale_readings]; // create arry to hold readings
for (int i = 0; i < num_scale_readings; i++) { for (int i = 0; i < num_scale_readings; i++) {
while (digitalRead(interruptPin) == LOW) { //while (digitalRead(interruptPin) == LOW) {
//while(! myScale.available()) { long mytimer = millis();
// we set a timeout of 60 seconds for the measurement... while (! myScale.available()) {
if ((millis() - startTime) > 60000) { // we set a timeout of 10 seconds for the measurement...
if ((millis() - mytimer) > 10000) {
// Timeout reading scale...
Wire.endTransmission(true);
if (debug_level > 0) { if (debug_level > 0) {
gCatena.SafePrintf("Timeout while reading scale...\n"); gCatena.SafePrintf("Timeout while reading scale...\n");
} }
return 0; break;
} }
delay(1); delay(1);
} }
readings[i] = myScale.getReading(); // fill the array with instantaneous readings from the scale long reading;
if (myScale.available()) {
reading = myScale.getReading();
readings[i] = reading;
}
if (debug_level > 0) {
gCatena.SafePrintf("Reading: %d\n", reading);
}
delay(10);
} }
long duration = millis() - startTime; long duration = millis() - startTime;
@@ -80,20 +129,48 @@ long ReadScale(char channel)
sdev = stddev(readings, num_scale_readings); sdev = stddev(readings, num_scale_readings);
float sdev_proc; float sdev_proc;
sdev_proc = 100 * (sdev / float(res)); sdev_proc = 100 * (sdev / float(res));
gCatena.SafePrintf("Measurements: [");
for (int i = 0; i < num_scale_readings; i++) {
gCatena.SafePrintf("%d", readings[i]);
if (i < (SAMPLES - 1)) {
gCatena.SafePrintf(",");
}
}
gCatena.SafePrintf("]\n");
gCatena.SafePrintf("Standard Deviation: %d.%03d\n", (int)sdev, (int)abs(sdev * 1000) % 1000); gCatena.SafePrintf("Standard Deviation: %d.%03d\n", (int)sdev, (int)abs(sdev * 1000) % 1000);
gCatena.SafePrintf("Standard Deviation / Median (Percent): %d.%03d\n", (int)sdev_proc, (int)abs(sdev_proc * 1000) % 1000); gCatena.SafePrintf("Standard Deviation / Median (Percent): %d.%03d\n", (int)sdev_proc, (int)abs(sdev_proc * 1000) % 1000);
gCatena.SafePrintf("Duration (ms): %d\n", duration); gCatena.SafePrintf("Duration (ms): %d\n", duration);
} }
if (debug_level > 0) {
gCatena.SafePrintf("ReadScale Done\n");
}
return res; return res;
} }
void PowerdownScale() void PowerdownScale()
{ {
if (debug_level > 0) {
gCatena.SafePrintf("PowerdownScale Start\n");
}
myScale.powerDown(); myScale.powerDown();
if (debug_level > 0) {
gCatena.SafePrintf("PowerdownScale Done\n");
}
} }
void PowerupScale() void PowerupScale()
{ {
myScale.powerUp(); //Power up scale. This scale takes ~600ms to boot and take reading. if (debug_level > 0) {
gCatena.SafePrintf("PowerupScale Start\n");
}
InitializeScales();
if (debug_level > 0) {
gCatena.SafePrintf("PowerupScale Done\n");
}
} }