Troubleshooting

SEN0491 getting "stuck"

userHead Matthew.Gale 2023-09-08 03:32:00 410 Views0 Replies

Hello,
When trying to use the example code, the sensor will “freeze” and keep giving the same repeating value regardless of the sensor position.
I was able to get the sensor to be more repeatable after communicating over modbus instead of UART. But after about 7 hours it would only return “0” as a measurement.

Any ideas what I can do?

Here is the code I am using to communicate over modbus:

#include <ModbusMaster.h>

unsigned long lastMeasTime = 0;  // Last time get_distance() was invoked
unsigned long measInterval = 2000;  // Interval at which to invoke get_distance() (in milliseconds)

ModbusMaster node;  // instantiate ModbusMaster object

void setup() {
 Serial1.begin(115200);  // Begin Serial1 at 115200 baud rate
 // Initialize Modbus communication on Serial1 with slave ID 0x50
 node.begin(0x50, Serial1);
 delay(1000);
}

void loop() {
 unsigned long currentTime = millis();  // Get the current time
 if (currentTime - lastMeasTime >= measInterval) { 
   uint16_t measurement = get_measurement();  // Get the measurement
}

uint16_t get_measurement()
{
 uint8_t result;  // variable to store result
 uint16_t data = 0;   // variable to store the data, initialized to 0
 
 result = node.readHoldingRegisters(0x34, 1);  //<--measurement
 if (result == node.ku8MBSuccess) {
   data = node.getResponseBuffer(0);  // get the data from buffer
   DEBUG_SERIAL.print("Measurement data: ");
   DEBUG_SERIAL.println(data);  // print the measurement data in decimal format
   if (data > 0) {
     return data;  // return the measurement data if it's within the range
   }
 } else {
   DEBUG_SERIAL.print("Read failed, Modbus error code: ");
   DEBUG_SERIAL.println(result);  // print error code
 }

 return 0;  // return 0 if the measurement is out of range or an error occurred
}