I want to establish Modbus RTU communication between the NodeMCU-ESP8266 (Amica) and ModScan software. On the NodeMCU side, I'm using a TTL MAX485, but I'm not getting any values. Whenever I try to establish communication on ModScan software, it shows 'Invalid response.'
Please help with my project.
#include <ModbusRTU.h>
#include <SoftwareSerial.h>
SoftwareSerial s(D3, D2); // RX, TX pins for SoftwareSerial communication
#define SLAVE_ID 1 // Modbus Slave ID
#define NUM_REGS 10 // Number of Modbus registers to handle
ModbusRTU mb; // ModbusRTU instance
// Array to store register values (optional if using multiple registers)
uint16_t holdingRegs[NUM_REGS];
void setup() {
Serial.begin(9600); // Initialize serial monitor for debugging
s.begin(9600, SWSERIAL_8E1); // Initialize SoftwareSerial
mb.begin(&s, D0); // Initialize Modbus RTU communication with SoftwareSerial and RX pin D0
mb.slave(SLAVE_ID); // Set the Modbus slave ID
for (int i = 0; i < NUM_REGS; i++) {
mb.addHreg(i); // Add holding registers from 0 to NUM_REGS-1
}
}
void loop() {
mb.task(); // Handle Modbus task, processing any incoming requests
mb.Hreg(0, 100); // Example: Write value 100 to the first register (index 0)
// Read the holding register value (e.g., register 0) and print it to Serial Monitor
uint16_t readHoldingRegister = mb.Hreg(0); // Read from register index 0
Serial.print("Holding Register 0: ");
Serial.println(readHoldingRegister);
delay(100); // Small delay between readings
}