CRC test, dont work

The question is more about the quality of the data you acquire on the sender side.

here I can't see how the acquisition works. It would be interesting to check if the crazy values like 40,000 kg comes from reading the HX711, in which case there is no need to worry about the Lora transmission and the work would be about ensuring the acquisition does not fail.

Regarding the code, your bubble sort does work and I see how you are trying to get the median value taking into account how many samples were actually acquired - this feels in theory fine (you create a median value that was not really an acquired sample by taking the average when you have 2 and 4 samples but that's a design decision that sounds rational).

What does not work is that because the window array and the sortedArray are actually one and the same in memory, you have messed up the window array when you did the sorting.

The consequence is that when you store the new sample with window[indeks] = input; you are very likely overwriting a previous value and not keeping a rolling window for the last 5 samples.

➜ you need a real copy of the array and not just a pointer. I would change this code

  // sort the values in the window:
  float* sortedArray = window;
  mySort(sortedArray, 5);

into

  // sort the values in a copy of the window:
  float sortedArray[5]; // it would be good to make 5 a global constant and use the constant everywhere instead of the magic value 5
  for (byte i = 0; i < 5; i++) sortedArray[i] = window[i];
  mySort(sortedArray, 5);

Your existing code could lead to wrong median values but as the array is a global variable, it's initialized with 0 values and then you fill it up with real samples (even when you overwrite an existing one) the median would not go to crazy high values. So it doesn't explain the 40,000 kg reading ➜ you should really explore what the HX711 reads return.

I can't comment much on the hardware design, I'm not a pro there and if you took the layout from spark fun and did a correct soldering job, then I assume it's fine. Quality of the power supply does matter - may be something to check too.

Hi @J-M-L

Thanks for going into my code and analyse, I really appreciate it! :grinning: :grinning:

I am now updating my sender with the new code you made for me.

Also rigged my system to make reading and read the serial with Putty so I can store the result, and analyse later.

Data logged in putty is actual data sent to receiver by LoRa and my influxDB, so this will be a real test.

And now its running:

I added a if statement to better visualize wrong values:

100% exact copy, PCB is open source
image

My board (Bee shape:-)

Hi

Result of scale test, the scale and the system delivers according to plan.
Weight is very stable but there is a falling trend, may be due to temp change.

Run for 8,2 h, from 23:00 to 07:00, falling temp.
Sample each 10 sec.
Will let it run for a few days to se if temp rising and falling.

My Conclusion:
Nothing wrong on sender side of my system.
Sender side sems to send correct data.
Receiver may receive data from the ether.... CRC will help
Something happens from receiver side to my influxDB

Other...?

Nice touch for the bee shape PCB :slight_smile:

The weight drift over time is well documented in many posts over the internet - so Google that to get ideas on how to deal with it.

Were you also sending the info with Lora at the same time? And if so Did you get wrong data when the acquisition was working?

Of course its possible, given the long range nature of LoRa you can receive packets that someone else has sent.

Or you receive your own packets that have receive errors and are corrupt data, but thats easy to resolve.

In addition a LoRa device can receive random packets that appear to come from nowhere, its the 'Phantom Packet' problem.

And if you want to receive 'reliable' data then you need to address the above issues.

Hi

I have struggled a lot with drift, but my need is to se development of weight. If its 42 kg or 43 is not so important, the most important is r\to register if the bees has swarmed, then the weight can change -1 to -1,5 kg and send an alarm to my wife's phone.

My drift is not so bad at all, next step is to use a load cell from Bosch, but 100€ is a bit much.

I did send on LoRa but my receiver system (HomeAssistant) is not reliable yes, so difficult to control, but I saw on my receivers OLED that it received around 25.3 kg, but I did not look at it all nigth :slight_smile:

Thanks for info.
I have had this in mind "ether noise", now I know the name Phantom Packet and can start to read/learn.

My system is built on spare time, so step 1 was to make all sensors and system work, witch I'm almost done with (13 months now). Sender->LoRa->Receiver->WiFi->HomeAssistant->InfluxDB->Grafana
All is set up, but the HA system is only in a test state.

Now the real job starts, stability, presentation etc.
I plan to use CRC to filter bad packages. After that I must see what's happening, and probably ask the forum experts :slight_smile:

There is a LoRa library that has transmit and receive functions that automatically adds a 16 bit network ID and 16 bit payload CRC to each packet. If the received packet does not have a matching ID and payload CRC the packet is rejected.

This means the chances of receiving a rogue packet as valid data is very remote.

Hi

I'm logging my scale, after 36h it has decresed 64 g on fixed load = 25,3 kg
I cant see that temp changes har impact, temp changes are not that big, around 20 deg C at night and 28 at day.
For my purpose I can live with it, but is there an explanation why weight "steady" goes down?

Hi

I have now made a log for what's in the loraPacket without any filter.

No question, there is noise bugging my data, so I will need some sorting

I did not fint this library, have you a link?


To the serial logg:
Serial: Vekt_f, is weigth float: (Norwegian).
HA is home assistant

A 100% correct package is
weigth; packet no 12445; nan nan; weight; humidity; rssi seen in this format:

Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;12445/nan&nan£25.23#0.00%1.00 ;rssi;-105


Serial output:

10:17:19.219 -> Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;!⸮=08/nan&nan£25.23#0.00%1.00 ;rssi;-101

10:17:28.273 -> Vekt_f sendt til HA;7.00; LoRaMessage unfiltered;Q⸮009nQ⸮6n3nʣ7
.RyC⸮"0(%1⸮U⸮ ;rssi;-101

10:17:37.340 -> Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;12410/nan&nan£25.23#0.00%1.00 ;rssi;-101

10:17:49.379 -> Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;12411/nan&nan£25.23#0.00%1.00 ;rssi;-101

10:18:07.507 -> Vekt_f sendt til HA;0.00; LoRaMessage unfiltered;;⸮⸮:'n
10:18:07.507 -> lQn,s#26(2: 7.

10:17:19.219 -> Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;!⸮=08/nan&nan£25.23#0.00%1.00 ;rssi;-101

10:17:28.273 -> Vekt_f sendt til HA;7.00; LoRaMessage unfiltered;Q⸮009nQ⸮6n3nʣ7
.RyC⸮"0(%1⸮U⸮ ;rssi;-101

10:17:37.340 -> Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;12410/nan&nan£25.23#0.00%1.00 ;rssi;-101

10:17:49.379 -> Vekt_f sendt til HA;25.23; LoRaMessage unfiltered;12411/nan&nan£25.23#0.00%1.00 ;rssi;-101

10:18:07.507 -> Vekt_f sendt til HA;0.00; LoRaMessage unfiltered;;⸮⸮:'n
10:18:07.507 -> lQn,s#26(2: 7.

https://github.com/StuartsProjects/SX12XX-LoRa

That link was copied from the article linked to in post #28, worth a read ..........

I did read it, a bit quick... thanks for sharing link!

I have found the reason for the "strange" graph. Occasionally, the LoRa receiver picks up the transmission with "noise," and the packet number is interpreted as "kg" (kilograms). As a result, I see the packet count increasing (n=n+1), which causes a steady rise in the graph values. The solution may be to send packets with CRC (Cyclic Redundancy Check) and a payload that discards faulty packets. This is, after learning from you guys, probably not a "Phantom package".

Here you can see the mistake, Vekt_f is weigth_float, and the number after unfiltered is the package nr:

Vekt_f sendt til HA;12576.00; LoRaMessage unfiltered;12576/nan&nan⸮+⸮S⸮M⸮5⸮F`⸮N00 ;rssi;-100

image

Each time I boot the sender it restarts

can you share the actual code of the sender and the receiver ?

Hi Jackson, thanks again for reaching out. Your previous feedback was spot on!

I go on vacation tomorrow, so I may take some time, but yes I can share it. (I must remove some code I have promised to keep offline, but that is has with calibration and storing to mem to do, nothing with packages).

M

Hi
@J-M-L

I woke up early today, here is my code, sender and receiver
forum.zip (10.8 KB)

I had a quick check through the code and did not spot anything clearly bogus besides a double read and the heavy reliance on the String class

The String class can sometimes induce weird bugs because the concatenation would fail silently if memory is short, but on an ESP32 that should not happen as you have plenty of SRAM.

You should clean up your prints and string concatenation as much as possible.

Note that what you print might actually be different than what you send as you perform two consecutive reads of the scale (blocking calls) and there are faster way to get the absolute value of a reading than using pow and sort...

    Serial.print(";Raw-scale.get_units();" + String(scale.get_units(), 3) );
    double data = sqrt(pow(scale.get_units(), 2));  // data er avlest vekt, make abs value

I would recommend doing

  float reading = scale.get_units();
  Serial.print(";Raw-scale.get_units();"); + Serial.print(reading, 3); // two prints better than using String concatenation. Will be faster and lighter on memory
  if (reading < 0) reading = -reading; // but not sure why you would do that...

Instead of taking the median you could also use the library's builtin capability to make multiple readings and give you an average by passing the number of readings you want to perform to scale.get_units() (that is if you do scale.get_units(5); what you get is the averaged weight on 5 consecutive reads).


On the receiver side, your readPacket() function is not blocking which means that if there is no incoming packet, the loop prints and publishes to MQTT even though there was no new reading. I've not looked at the code in details but it means that if the variables you use for printing have changed then you'll push nonsense out.

your readPacket() function should return a bool, sending true if there was a new message and parsing was fine and you should use that to decide to print to MQTT

Regarding the parsing, you expect something formatted like this:

    String(packetID)       + "/" +
    String(temperature)    + "&" +
    String(humidity)       + "£" +
    String(weight_median)  + "#" +
    String(alarmValue)     + "%" +
    String(hiveNr)         + "@";

and so you look for separators

      int pos1 =    LoRaMessage.indexOf('/'); //PacketID
      int pos2 =    LoRaMessage.indexOf('&'); //temp
      int pos3 =    LoRaMessage.indexOf('£'); //hum
      int pos4 =    LoRaMessage.indexOf('#'); //vekt_median
      int pos5 =    LoRaMessage.indexOf('%'); // alarm
      int pos6 =    LoRaMessage.indexOf('@'); // hiveNr

and then go right ahead and extract the values

      packetID =    LoRaMessage.substring(0, pos1);
      temperature = LoRaMessage.substring(pos1 + 1, pos2);
      humidity =    LoRaMessage.substring(pos2 + 1, pos3);
      weight =      LoRaMessage.substring(pos3 + 1, pos4);
      alarmValue =  LoRaMessage.substring(pos4 + 1, pos5);
      hiveName =    LoRaMessage.substring(pos5 + 1, LoRaMessage.length());

Assuming you do get possibly bogus messages, indexOf() will return -1 if you can't find the separator. You should check for this before doing maths on the positions and blindly extracting substrings.

finally the conversations relying on the String class are weak too, not only because of the previous point (you are not sure the String was extracted correctly) but also because toInt() and toFloat() do not report a parsing error

      packetID_i        = packetID.toInt();
      temperature_f     = temperature.toFloat();
      humidity_f        = humidity.toFloat();
      weight_f          = weight.toFloat();
      //tareValue_i     = tareValue.toInt();
      alarmValue_i      = alarmValue.toInt();
      hiveName_i        = hiveName.toInt();
      hiveName_f        = hiveName.toInt();    // for å skrive på oled 1 i stedet for 1.00

You would be better served by strtol() or strtoul() for integral values (signed or unsigned) and strtof ()or strtod() for floating point values. Those functions take an endPtr parameter that can be used to check if the parsing worked and read all the symbols in the c-string.

Last but not least, if you have an Lora32 Oled ESP32 on both side (same architecture), rather than sending a String and decoding the String on the other side, I would put everything inside a packed struct on the sender side and just receive in the same struct on the receiving side ➜ no parsing to do and you could add also a CRC or magic keyword in the struct to ensure this is really a packet meant for you.

Again @J-M-L , thanks for giving me this insight in LoRa, string and strt*(), and general about some "issues" in my code. Thanks!!!

I have searched quite a bit on net to learn about LoRa, and all I have found is code that uses strings and concatenate into packages. And my code has "worked" until I started to send to database for making graphs etc.

I'm not a skilled coder (Basic, Fortran, Pascal in the 1980-90'), my son helps me a bit, he has a degree in coding.

My son is not here so I did run your tip into chatGPT, to get some learning for myself.

If some of you her on forum can take a look at the AI code and tell me AI is on track, then I will try to update my own code along this lines.

This code is not tested, but it compiles for ESP32 which in my "new" HW is in both ends, sender ESP32 WROOM, receiver is the TTGO ESP32 OLED

Here is AI code sender:

#include <LoRa.h>

#define LORA_SS_PIN     18
#define LORA_RST_PIN    14
#define LORA_DIO0_PIN   26
#define LORA_BAND       915E6    // Frequency band for your LoRa module

// Define your own network key and address
const uint8_t networkKey[16] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
const uint8_t address = 0x01;

void setup() {
  Serial.begin(115200);
  while (!Serial);

  LoRa.setPins(LORA_SS_PIN, LORA_RST_PIN, LORA_DIO0_PIN);
  if (!LoRa.begin(LORA_BAND)) {
    Serial.println("LoRa initialization failed. Check your connections.");
    while (1);
  }
}

void loop() {
  // Simulated sensor readings
  float weight = 55.23;
  float temperature = 25.57;
  float humidity = 65.12;

  // Create a payload string
  char payload[50];
  sprintf(payload, "%.2f %.2f %.2f", weight, temperature, humidity);

  // Convert payload string to byte array
  uint8_t payloadArray[sizeof(payload)];
  memcpy(payloadArray, payload, sizeof(payload));

  // Send the payload
  LoRa.beginPacket();
  LoRa.write(payloadArray, sizeof(payload));
  LoRa.endPacket();

  Serial.println("Payload sent: " + String(payload));

  delay(5000);  // Wait for 5 seconds before sending the next packet
}

Receiver:

#include <LoRa.h>

#define LORA_SS_PIN     18
#define LORA_RST_PIN    14
#define LORA_DIO0_PIN   26
#define LORA_BAND       915E6    // Frequency band for your LoRa module

void setup() {
  Serial.begin(115200);
  while (!Serial);

  LoRa.setPins(LORA_SS_PIN, LORA_RST_PIN, LORA_DIO0_PIN);
  if (!LoRa.begin(LORA_BAND)) {
    Serial.println("LoRa initialization failed. Check your connections.");
    while (1);
  }
}

void loop() {
  // Check for incoming packets
  if (LoRa.parsePacket()) {
    uint8_t receivedPayload[50];
    int len = LoRa.readBytes(receivedPayload, sizeof(receivedPayload));

    // Null-terminate the received payload
    receivedPayload[len] = '\0';

    Serial.println("Received payload: " + String((char*)receivedPayload));

    // Parsing the received payload
    char* endPtr;
    float receivedWeight = strtod((char*)receivedPayload, &endPtr);
    if (endPtr == (char*)receivedPayload) {
      Serial.println("Rejected: Invalid weight");
      return;
    }

    float receivedTemperature = strtod(endPtr, &endPtr);
    if (endPtr == (char*)receivedPayload) {
      Serial.println("Rejected: Invalid temperature");
      return;
    }

    float receivedHumidity = strtod(endPtr, &endPtr);
    if (endPtr == (char*)receivedPayload) {
      Serial.println("Rejected: Invalid humidity");
      return;
    }

    // Display the received values
    Serial.println("Received weight: " + String(receivedWeight, 2) + " kg");
    Serial.println("Received temperature: " + String(receivedTemperature, 2) + " °C");
    Serial.println("Received humidity: " + String(receivedHumidity, 2) + " %RH");
  }
}

LoRa devices just send packet of data.

How you fill the LoRa data buffer, for the packet, is up to you.

You can fill the data buffer with a string if you want or fill an array or structure with data and pass the pointers across to the LoRa library to transmit.

There is also a library that allows you to fill the LoRa buffer directly;


LoRa.startWriteSXBuffer(0);   //start write at SX127X internal buffer location 0
LoRa.writeFloat(latitude);
LoRa.writeFloat(longitude);
LoRa.writeUint16(altitude);
LoRa.writeUint8(satellites);
LoRa.writeUint16(voltage);
LoRa.writeInt8(temperature);
LoRa.endWriteSXBuffer();

And you read the data back in the same order on the receiver.

So lots of choices on how the write to and read from the LoRa internal packet buffer.

what I meant with structures (code typed here based on yours, I have not tested)

sender

#include <LoRa.h>

#define LORA_SS_PIN     18
#define LORA_RST_PIN    14
#define LORA_DIO0_PIN   26
#define LORA_BAND       915E6    // Frequency band for your LoRa module

// Define your own network key and address
const uint8_t networkKey[16] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
const uint8_t address = 0x01;

struct __attribute__((packed)) Payload {
  float weight;
  float temperature;
  float humidity;
};



void setup() {
  Serial.begin(115200);
  while (!Serial);

  LoRa.setPins(LORA_SS_PIN, LORA_RST_PIN, LORA_DIO0_PIN);
  if (!LoRa.begin(LORA_BAND)) {
    Serial.println("LoRa initialization failed. Check your connections.");
    while (true);
  }
}

void loop() {
  Payload myPayload; // the container for what we want to send

  // Simulated sensor readings
  myPayload.weight = random(-300, 400) / 10.0;
  myPayload.temperature = 42.42;
  myPayload.humidity = 65.12;

  LoRa.beginPacket();
  LoRa.write((uint8_t*) &myPayload, sizeof(Payload));
  LoRa.endPacket();
  Serial.println("Payload sent");

  delay(5000);  // Wait for 5 seconds before sending the next packet
}

and receiver

#include <LoRa.h>

#define LORA_SS_PIN     18
#define LORA_RST_PIN    14
#define LORA_DIO0_PIN   26
#define LORA_BAND       915E6    // Frequency band for your LoRa module

struct __attribute__((packed)) Payload {
  float weight;
  float temperature;
  float humidity;
};


void setup() {
  Serial.begin(115200);
  while (!Serial);

  LoRa.setPins(LORA_SS_PIN, LORA_RST_PIN, LORA_DIO0_PIN);
  if (!LoRa.begin(LORA_BAND)) {
    Serial.println("LoRa initialization failed. Check your connections.");
    while (true);
  }
}

void loop() {
  if (LoRa.parsePacket()) {
    Payload myPayload; // the container for what we want to receive
    size_t len = LoRa.readBytes((uint8_t*) &myPayload, sizeof(Payload));
    if (len == sizeof(Payload)) {
      Serial.println("Received payload: ");
      Serial.print("  Received weight: ");       Serial.println(myPayload.weight);
      Serial.print("  Received temperature: ");  Serial.println(myPayload.temperature);
      Serial.print("  Received humidity: ");     Serial.println(myPayload.humidity);
    } else {
      Serial.println("wrong payload size.");
    }
  }
}

as you can see, we don't need to go through an ASCII communication and all the string building and then the parsing of what we receive. You get the structure of data (the Payload) and can use the data fields right away.