CMB27 / ModbusRTUSlave

This is an Arduino library that implements the slave/server logic of the Modbus RTU protocol.
MIT License
58 stars 14 forks source link

Slave to master write problem #37

Closed serefseven closed 2 months ago

serefseven commented 3 months ago

Hi Chris,

I have been working on simple modbus communication but, I haven't succeeded yet. I need your help.

I want to write boolean value from slave and read it from master. 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

Where is 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);
}

Best regards, Seref

CMB27 commented 3 months ago

You are using Serial for both debugging and Modbus communication. These need to be on separate ports. The Arduino Nano only has one HardwareSerial port, but the ModbusRTUMaster and ModbusRTUSlave libraries will work with SoftwareSerial.