Problem with ph soil sensor with Arduino Mega

Hello everyone! I'm having problems using the soil pH sensor that uses the RS485 protocol, I searched the net and followed this tutorial:

I tried to make everything work, with an Arduino Uno it works perfectly, while if I use an Arduino Mega (which is used to implement my final project) the PH sensor is no longer able to read the value correctly, always printing the value of 25.5. Could you help me by establishing if the problem is in the initial frame that the sensor on the datasheet uses, or is it to be found elsewhere?

The problem is likely in your code for the Mega - post it so we can help you.

#include <SoftwareSerial.h>
//#include <Wire.h>
#define RE 8
#define DE 7
 
const byte ph[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
byte values[11];
SoftwareSerial modbus(2, 3);
 
void setup()
{
  Serial.begin(9600);
  modbus.begin(4800);
  //modbus.begin(9600);
  pinMode(RE, OUTPUT);
  pinMode(DE, OUTPUT);
  delay(3000);
}
 
void loop()
{
  byte val;
  digitalWrite(DE, HIGH);
  digitalWrite(RE, HIGH);
  delay(10);
  if (modbus.write(ph, sizeof(ph)) == 8)
  {
    digitalWrite(DE, LOW);
    digitalWrite(RE, LOW);
    for (byte i = 0; i < 11; i++)
    {
      values[i] = modbus.read();
      Serial.print(values[i], HEX);
    }
    Serial.println();
  }
  float soil_ph = float(values[4]) / 10;
  Serial.print("Soil Ph: ");
  Serial.println(soil_ph, 1); 
  delay(3000);
}

You don't need a software serial port on a mega. Use one of the hardware serial ports like Serial1.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.