Arduino Nano RS-485 Modbus slave to master write problem

I have been working on simple modbus communication but, I haven't succeeded.

I want to write the value read from the hc-sr04 sensor on the slave device to the master device as boolean according to a thresold value.
I have two Arduino nano and two TTL rs485 converter.

Both Arduino pin connection;

R0 to RX(D0)

DI to TX(D1)

DE and RE to D2

A to A

B to B

Master always print 0, where is the problem? could you help me?

Slave Code

#include "NewPing.h"
    #include <ModbusRTUSlave.h>
    
    #define TRIGGER_PIN 9
    #define ECHO_PIN 10
    #define MAX_DISTANCE 400
    #define TRESHOLD_DISTINCE 30 //100
    
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
    float duration, distance;
    
    #define SERIAL_BAUD 38400
    #define SERIAL_CONFIG SERIAL_8N1
    #define SLAVE_ID 1 
    #define TXEN	2
    
    
    ModbusRTUSlave slave(Serial, TXEN);
    bool discreteInputs[1];
    bool oldStatus = false;
    bool newStatus = false;
    
    void setup() {
      discreteInputs[0] = false;
      Serial.begin( SERIAL_BAUD, SERIAL_8E1 ); // 19200 baud, 8-bits, even, 1-bit stop
      slave.configureCoils(discreteInputs, 1);
      slave.begin(SLAVE_ID, SERIAL_BAUD, SERIAL_8E1);
    }
    
    void loop() {
      
      distance = sonar.ping_cm();
      
      Serial.print("DIST ");
      // Send results to Serial Monitor
      distance = distance == 0? 400 : distance;
      if (distance >= 400 || distance <= 2) {
        Serial.print("- |");
      } else {
        Serial.print(distance);
        Serial.print(" | ");
      }
    
      if (distance < TRESHOLD_DISTINCE) {
        Serial.print(" PARK F | ");
        newStatus = true;
      } else {
        Serial.print(" PARK E | ");
        newStatus = false;
      }
    
      if (oldStatus != newStatus) {
        oldStatus = newStatus;
        discreteInputs[0] = newStatus;
      }
      
      slave.poll();
    
      Serial.println();
      delay(1000);
    }

Master Code

#include <ModbusRTUMaster.h>
    
    #define SERIAL_BAUD 38400
    #define SERIAL_CONFIG SERIAL_8N1
    #define TXEN	2
    
    ModbusRTUMaster modbus(Serial, TXEN);
    bool discreteInputs[1];
    
    void setup() {
      Serial.begin(SERIAL_BAUD);
      modbus.begin(SERIAL_BAUD);
    }
    
    
    void loop() { 
      modbus.readCoils(1, 0, discreteInputs, 1);
      uint8_t reesponse = modbus.getExceptionResponse();
      Serial.print( reesponse );
      Serial.print(" |");
      Serial.print(discreteInputs[0]);
      Serial.print(" |");
      Serial.println();
      delay(1000);
    }

Library links

Using the same UART for two different functions (modbus and PC) will not work (or at least not reliably).

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