Need Help configuring Soil pH sensor with ESP32

78 views Asked by At

I have a soil pH sensor with rs485 output that is connected to MAX485 and ESP32. I'm having a bit of a problem as the serial monitor doesn't show the correct value (Just random characters that is not supposed to be showing)

This is the Datasheet for the soil pH sensor.

And this is my code:

#include <ModbusMaster.h>

#define RE 5   // GPIO 5
#define DE 6   // GPIO 6

const byte ph[] = {0x01, 0x03, 0x00, 0x0D, 0x00, 0x01, 0x15, 0xC9};
byte values[2];  // Assuming the response is 2 bytes
ModbusMaster node;

void setup() {
  Serial.begin(4800);  // Adjust the baud rate to 4800
  pinMode(RE, OUTPUT);
  pinMode(DE, OUTPUT);
  digitalWrite(RE, LOW);   // Set RE low for receiving data
  digitalWrite(DE, LOW);   // Set DE low for receiving data
  node.begin(1, Serial);    // Node ID 1, use hardware serial for communication

  // Wait for the serial connection to be established
  while (!Serial) {
    delay(10);
  }

  Serial.println("Serial communication established.");
}

void loop() {
  // Send inquiry frame to the soil pH sensor
  sendInquiryFrame();

  // Wait for a response from the soil pH sensor
  delay(500);  // Adjust the delay as needed

  // Read and process the response
  if (readResponse()) {
    // Calculate pH value from the received data
    uint16_t pHRaw = (values[0] << 8) | values[1];
    float pHValue = pHRaw / 100.0;  // Assuming the pH value is represented as a two-decimal fixed-point number

    Serial.print("Soil pH: ");
    Serial.println(pHValue, 2);  // Print pH value with 2 decimal places
  } else {
    Serial.println("Failed to read from the soil pH sensor.");
  }

  delay(3000);
}

void sendInquiryFrame() {
  // Enable DE to send data
  digitalWrite(DE, HIGH);

  // Send inquiry frame to the soil pH sensor
  if (Serial.write(ph, sizeof(ph)) != sizeof(ph)) {
    Serial.println("Failed to send inquiry frame.");
  }

  delay(2);  // Allow time for transmission to complete
  digitalWrite(DE, LOW);  // Disable DE to receive data
}

bool readResponse() {
  digitalWrite(DE, LOW);
  digitalWrite(RE, HIGH);
  delay(10);
  
  // Read the response from the soil pH sensor
  for (byte i = 0; i < 2; i++) {
    if (Serial.available()) {
      values[i] = Serial.read();
      Serial.print(values[i], HEX);
    } else {
      Serial.println("Timeout waiting for response byte.");
      return false;
    }
  }
  Serial.println();

  digitalWrite(RE, LOW);

  // Check if the expected number of bytes are received
  return (Serial.available() == 0);
}

The following are the pinouts for the max485 for more reference: DI - GPIO19 DE - GPIO6 RE - GPIO5 RO - GPIO21

i tried using the other inquiry frame from the datasheet and also connecting and disconnecting the pins but it still persists. Any form of criticisms is much appreciated

0

There are 0 answers