Hello, I got FFFFFFFFFFF 255 error in serial monitor. Is there anybody face this problem before? and can anyone know what's the problem? I've no idea what was the problem ? but first time got output while run the program but that wasn't accurate and stable output. can anyone help me to solve this problem?
This is my code
#include <SoftwareSerial.h>
#include <Wire.h>
// RE and DE Pins set the RS485 module
// to Receiver or Transmitter mode
#define RE 18
#define DE 19
// Modbus RTU requests for reading NPK values
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};
// Define software serial for RS485 communication
SoftwareSerial mod(16, 17); // RX = 16, TX = 17 (Change pins as needed)
void setup() {
Serial.begin(9600); // Start Serial Monitor
mod.begin(4800); // Start Modbus communication
// Define pin modes for RS485 control
pinMode(RE, OUTPUT);
pinMode(DE, OUTPUT);
delay(500);
}
byte read_npk(const byte* command) {
digitalWrite(DE, HIGH);
digitalWrite(RE, HIGH);
delay(10);
mod.write(command, 8); // Send request
delay(10);
digitalWrite(DE, LOW);
digitalWrite(RE, LOW);
// Wait for response (7 bytes expected)
long timeout = millis();
while (mod.available() < 7) {
if (millis() - timeout > 2000) { // 2 sec timeout
Serial.println("Timeout! No data received.");
return 255; // Error value
}
delay(10);
}
// Read response
byte response[7];
for (byte i = 0; i < 7; i++) {
response[i] = mod.read();
}
// Print received data
Serial.print("Response: ");
for (byte i = 0; i < 7; i++) {
Serial.print(response[i], HEX);
Serial.print(" ");
}
Serial.println();
// Extract NPK value (bytes 3 & 4)
int value = (response[3] << 8) | response[4]; // Combine High + Low byte
return value; // Return proper data
}
void loop() {
Serial.println("\nReading NPK values...");
byte nitrogen = read_npk(nitro);
byte phosphorous = read_npk(phos);
byte potassium = read_npk(pota);
Serial.print("Nitrogen: ");
Serial.print(nitrogen);
Serial.println(" mg/kg");
Serial.print("Phosphorous: ");
Serial.print(phosphorous);
Serial.println(" mg/kg");
Serial.print("Potassium: ");
Serial.print(potassium);
Serial.println(" mg/kg");
delay(2000);
}
circuit diagram:
