Heya, I've been having trouble making with using my NPK and pH sensor on the arduino mega.
At first i believed it was an issue with the pins, but switching the DI and RO pins didn't seem to fix it.
Right know, everything the sensor says that everything is at 255, while the uno works just fine...
#include <SoftwareSerial.h>
#include <Wire.h>
// Pines para RS485
#define RE 30
#define DE 31
// Comandos Modbus RTU
const byte nitro[] = {0x01, 0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c};
const byte phos[] = {0x01, 0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc};
const byte pota[] = {0x01, 0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0};
const byte ec[] = {0x01, 0x03, 0x00, 0x15, 0x00, 0x01, 0x95, 0xCE};
const byte salinity[] = {0x01, 0x03, 0x00, 0x14, 0x00, 0x01, 0xC4, 0x0E};
const byte ph[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
// Variables para almacenar lecturas
byte values[11];
SoftwareSerial mod(2, 3); // Pines para RS485
void setup() {
Serial.begin(9600);
mod.begin(9600); // Comunicación RS485
pinMode(RE, OUTPUT);
pinMode(DE, OUTPUT);
}
void loop() {
// Leer valores de sensores
Serial.print("Nitrogeno (mg/kg): ");
Serial.println(readSensor(nitro));
delay(250);
Serial.print("Fosforo (mg/kg): ");
Serial.println(readSensor(phos));
delay(250);
Serial.print("Potasio (mg/kg): ");
Serial.println(readSensor(pota));
delay(250);
Serial.print("Conductividad eléctrica (EC): ");
Serial.println(readSensorInt(ec));
delay(250);
Serial.print("Salinidad: ");
Serial.println(readSensor(salinity));
delay(250);
float soil_ph = readSensorPH();
Serial.print("pH del suelo: ");
Serial.println(soil_ph, 1);
delay(3000);
}
// Función para leer valores en formato byte
byte readSensor(const byte *command) {
digitalWrite(DE, HIGH);
digitalWrite(RE, HIGH);
delay(10);
if (mod.write(command, 8) == 8) {
digitalWrite(DE, LOW);
digitalWrite(RE, LOW);
for (byte i = 0; i < 7; i++) {
values[i] = mod.read();
}
}
return values[4];
}
// Función para leer valores en formato entero (16 bits)
int readSensorInt(const byte *command) {
digitalWrite(DE, HIGH);
digitalWrite(RE, HIGH);
delay(10);
if (mod.write(command, 8) == 8) {
digitalWrite(DE, LOW);
digitalWrite(RE, LOW);
for (byte i = 0; i < 7; i++) {
values[i] = mod.read();
}
}
return int(values[3] << 8 | values[4]);
}
// Función para leer el pH y convertirlo en flotante
float readSensorPH() {
digitalWrite(DE, HIGH);
digitalWrite(RE, HIGH);
delay(10);
if (mod.write(ph, 8) == 8) {
digitalWrite(DE, LOW);
digitalWrite(RE, LOW);
for (byte i = 0; i < 11; i++) {
values[i] = mod.read();
}
}
return float(values[4]) / 10.0; // Conversión a pH real
}
10 posts - 6 participants