Hello,
I got the Dissolved Oxygen sensor and I am working with ESP32 so I used a TTL RS845 converter and wrote two codes with two libraries but I still did not get an outcome.
First code:
#include <ModbusMaster.h>
ModbusMaster node;
uint8_t request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x04, 0x45, 0xBE};
uint8_t result;
uint16_t response[28];
void setup() {
Serial.begin(9600);
// Modbus device ID (Slave Address)
node.begin(1, Serial);
Serial.println(" test setup ");
}
void loop() {
Serial.println(" test loop1 ");
Serial.println("******************************************* ");
Serial.println(" ** Start Code ** ");
Serial.println("test loop2 ");
// Send the Modbus request with the CRC16 checksum
uint16_t crc16_update(uint16_t crc, uint8_t a);
// This function calculates the CRC16 checksum for a byte.
uint16_t crc = 0;
crc = crc16_update(crc, 0xAB);
// The following code prints the CRC16 checksum to the serial port:
Serial.println(crc);
for (int i = 0; i < sizeof(request); i++) {
for (int j = 0; j < 8; j++) {
node.sendBit((request[i] >> j) & 1);
}
}
// Receive the Modbus response
node.receive();
Serial.println("--- **Error part** ---");
// Check for errors
if (response[0] == 0x80) {
if (response[1] == 0x03) {
Serial.println("Data error");
} else {
Serial.println("Wrong function code");
}
}
Serial.println("--- after receiving ---");
// Print the response
for (int i = 0; i <28; i++) {
Serial.print("--> ");
Serial.println(response[i]);
}
// Interpret the data
uint16_t dissolvedOxygen = (response[7] << 8) | response[8];
uint16_t temperature = (response[11] << 8) | response[12];
int dissolvedOxygenDecimalPlaces = response[9] >> 4;
int temperatureDecimalPlaces = response[13] >> 4;
// Calculate the divisor based on the number of decimal places
float dissolvedOxygenValue = static_cast<float>(dissolvedOxygen) / pow(10, dissolvedOxygenDecimalPlaces);
float temperatureValue = static_cast<float>(temperature) / pow(10, temperatureDecimalPlaces);
// Print the results
Serial.print("Temperature: ");
Serial.print(temperatureValue);
Serial.println(" °C");
Serial.print("Dissolved oxygen: ");
Serial.print(dissolvedOxygenValue);
Serial.println(" mg/L");
/* } else {
Serial.print("probbb ");
Serial.print("Failed to read registers! Error code: ");
Serial.println(result);
}*/
delay(5000); // Adjust the delay according to your needs
}
--------------------------------------------------result
test loop2
48961
— Error part —
— after receiving —
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
→ 0
Temperature: 0.00 °C
Dissolved oxygen: 0.00 mg/L
and the second code with SoftwareSerial library, the result is unkown characters:
�������������//�
I didn't understand whether the problem is in the code, the wiring or the sensor. Can someone help me please ?