Help with finalising Freezer Temp on our farm

I need to help on finalising temp code, i used chat gpt to help me out until now.
Wondering if i get some help on the code.

Equipment used;

AIM:

  • Using ESP32 to read temperature from a DS18B20 sensor and battery voltage via the UMS3 library
  • Sending the readings to a influxd cloud server
  • Send the readings when the usb power is on ( if usb_presence=1)
  • Wanna have led module code to be function when the usb power is on (usb_presence=1)
  • Store data on ESP32 until if there’s NO a WiFi connection
  • Store data on ESP32 until if there’s NO a influxdb connection
  • Disable WiFi when the ESP32 is running on battery mode when the usb presence is =0
  • Shut down the ESP32 if the battery reaches 3.60V or after 4 hours (whichever is first) if the usb presence is =0

I already have the base code for reading & sending data to influxdb
Also have the led module code.

Code for the Data Logging to influxdb

#include <Arduino.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFiMulti.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
#include <UMS3.h>
#include <esp_bt.h>

UMS3 ums3;

WiFiMulti wifiMulti;

#define DEVICE "eps32-s3"

#define WIFI_SSID "SSID_OF_NETWORK"
#define WIFI_PASSWORD "PASSWORD_OF_NETWORK"

#define WIFI_SSID1 "SSID_OF_NETWORK1"
#define WIFI_PASSWORD1 "PASSWORD_OF_NETWORK1"
#define WIFI_SSID2 "SSID_OF_NETWORK2"
#define WIFI_PASSWORD2 "PASSWORD_OF_NETWORK2"
#define WIFI_SSID3 "SSID_OF_NETWORK3"
#define WIFI_PASSWORD3 "PASSWORD_OF_NETWORK3"

#define INFLUXDB_URL "http://10.20.2.50:5006"
#define INFLUXDB_TOKEN "3n56566UfmFARbfTey0xLliyjQaNmFNIe0gv0qX6Ls7U7EqVocMEWTbihsA=="
#define INFLUXDB_ORG "928c8dd365c43aa5"
#define INFLUXDB_BUCKET "farm"
#define TZ_INFO "AEST-10AEDT,M10.1.0,M4.1.0/3"

InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);

Point sensorReadings("measurements");

#define ONE_WIRE_BUS 1

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void initDS18B20() {
  sensors.begin();
}

void setup() {
  Serial.begin(115200);
  ums3.begin();
  sensors.begin();
  WiFi.mode(WIFI_STA);

  wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  wifiMulti.addAP(WIFI_SSID1, WIFI_PASSWORD1);
  wifiMulti.addAP(WIFI_SSID2, WIFI_PASSWORD2);
  wifiMulti.addAP(WIFI_SSID3, WIFI_PASSWORD3);
  btStop();
  while (wifiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();

  initDS18B20();
  
  sensorReadings.addTag("device", DEVICE);
  sensorReadings.addTag("location", "farm");

  timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");

  if (client.validateConnection()) {
    Serial.print("Connected to InfluxDB: ");
    Serial.println(client.getServerUrl());
  } else {
    Serial.print("InfluxDB connection failed: ");
    Serial.println(client.getLastErrorMessage());
  }
}

void loop() {
  sensors.requestTemperatures();
  
  float temperature = sensors.getTempCByIndex(0);
  float batteryVoltage = ums3.getBatteryVoltage();
  delay(1000);
  int usbpresence = ums3.getVbusPresent();

  sensorReadings.addField("temperature", temperature);
  sensorReadings.addField("battery_voltage", batteryVoltage);
  sensorReadings.addField("usb_presence", usbpresence);

  Serial.print("Writing: ");
  Serial.println(client.pointToLineProtocol(sensorReadings));
  
  client.writePoint(sensorReadings);

  sensorReadings.clearFields();

  if (wifiMulti.run() != WL_CONNECTED) {
    Serial.println("Wifi connection lost");
  }

  Serial.println("Wait 30s");
  delay(30000);
}

Code for the LED MODULE

#include <Adafruit_NeoPixel.h>

#define PIN       2 // Input your RGB LED module GPIO pin
#define NUM_LEDS  1 // Number of LEDs in your module

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

int DELAYVAL = 500; // Time (in milliseconds) to pause between pixels

void setup() {
  strip.begin(); // Initialize the NeoPixel library
  strip.show();  // Initialize all pixels to 'off'
}

void loop() {
  rainbow(60*1000/256); // 60 seconds divided by 256-color spectrum
  strip.clear();
  strip.show();
  delay(60 * 60 * 1000); // Wait for 60 minutes
}


void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*2; j++) { // repeat twice for a smoother transition
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Input a value 0 to 255 to get a color value.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
1 Like

Hi @Huseyin262816
I’m sure we can lend a hand.
Are these two dot points the steps you need inspiration for?

2 Likes

Hi @Pixmusix
thanks so much :slight_smile:

Basically yes for storing data on the esp32 when there is no connection.
I tried using the NVS or SPIFFS, but couldnt get it working.

Also when my battery, only the wifi disable to save battery & shutdown if the battery reaches 3.60V or after 4 hours (whichever is first) if the usb presence is =0

2 Likes

Hi Huseyin,

Quite the project you have happening!

Unfortunately helping with a full projects code is a bit outside of what Core can go deep on over the forum but we can certainly help with gathering resources!

In either of the states where you arent connecting you’ll need to handle the ‘error’, in each of the libraries there ought to be a connected flag we can access to check if we still maintain the connection, more here: try/catch block in Arduino - Stack Overflow

This is kind of how more robust code can be written in Micropython using try catch (super general exception handling).

What issues were you having with NVS or SPIFFS - are there any error messages we might be able to help with?

Liam

1 Like

Hi @Liam

Thanks for the reply.

So do you prefer mircopython then?

I haven’t had any error messages on SPIFFS. Below is what i had, but it wasn;t working.

  //initialize SPIFFS
  if(!SPIFFS.begin(true)){
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
}

void loop() {
  sensors.requestTemperatures();

  float temperature = sensors.getTempCByIndex(0);
  float batteryVoltage = ums3.getBatteryVoltage();
  delay(1000);
  int usbpresence = ums3.getVbusPresent();

  if (wifiMulti.run() != WL_CONNECTED || !client.validateConnection()) {
    Serial.println("Connection lost. Saving sensor data to SPIFFS.");

    // Open file for reading sensor data
    File file = SPIFFS.open("/sensorData.txt", FILE_APPEND);
    if(!file) {
      Serial.println("Failed to open file for appending");
    }

    // Save temperature, batteryVoltage and usbPresence to file
    file.printf("temperature=%f, battery_voltage=%f, usb_presence=%d\n", temperature, batteryVoltage, usbpresence);

    file.close();
  }
  else {
    Serial.println("Connection available. Sending sensor data to InfluxDB.");

    // First send any stored data
    if(SPIFFS.exists("/sensorData.txt")){
      File file = SPIFFS.open("/sensorData.txt");
      String line;
      while(file.available()){
          line = file.readStringUntil('\n');
          sensorReadings.addField("temperature", line.substring(line.indexOf("=")+1, line.indexOf(",")).toFloat());
          line = line.substring(line.indexOf(",")+1);
          sensorReadings.addField("battery_voltage", line.substring(line.indexOf("=")+1, line.indexOf(",")).toFloat());
          line = line.substring(line.indexOf(",")+1);
          sensorReadings.addField("usb_presence", line.substring(line.indexOf("=")+1).toInt());
          client.writePoint(sensorReadings);
          sensorReadings.clearFields();
      }

      file.close();
      // Delete the data file now that it has been sent
      SPIFFS.remove("/sensorData.txt");
    }

    // Now send new sensor data
    sensorReadings.addField("temperature", temperature);
    sensorReadings.addField("battery_voltage", batteryVoltage);
    sensorReadings.addField("usb_presence", usbpresence);
    client.writePoint(sensorReadings);
    sensorReadings.clearFields();
    }

1 Like

Hi Huseyin.
I’m sorry I missed your reply.

I do have some quick thoughts that might help you on your way.

Firstly, how to store your data.

I’d recommend using Serialization. Serialization is when you distill a c++ object down to a unique binary hash. In this case, you want to serialize your sensorReadings object. Below is a famous example.
https://www.boost.org/doc/libs/1_36_0/libs/serialization/example/demo.cpp

Second, notice this section of your wifi code.

In this code block, consider adding the function that stores your data.
I’m imagining something like:

/* WARNING 
   UNTESTED CODE!!! */

const * char filename = "path/to/sdcard/";

  if (wifiMulti.run() != WL_CONNECTED) {
    // make an archive
    std::ofstream ofs(filename);
    boost::archive::text_oarchive oa(ofs);
    oa << sensorReadings;
    Serial.println("Wifi connection lost; archvie saved");
  }

Lastly, you’ll want an SD card to store your data.

Plenty of good libraries out there for SD card storage.

Some tough coding is ahead of you. Totally doable though. Good luck!!

Pix :heavy_heart_exclamation:

1 Like

Hi Huseyin,

No worries at all!

Yeah for work and personal projects its the preference :slight_smile:
It just makes working on projects so quick!

Liam