Activity Forums Questions & Troubleshooting Modbus write single register code. Not working, can someone tell me why ?

  • Modbus write single register code. Not working, can someone tell me why ?

     Lukas updated 6 months ago 2 Members · 2 Posts
  • Nestor973

    Member
    November 19, 2021 at 3:39 pm

    #include <Controllino.h>

    #include “ModbusRtu.h”

    #define MasterModbusAdd 0

    #define SlaveModbusAdd 1

    #define RS485Serial 3

    int i;

    unsigned long u32wait;

    uint16_t au16data[16];

    uint8_t u8state;

    char caracter;

    String ch;

    int value;

    Modbus master(MasterModbusAdd, RS485Serial, 0);

    modbus_t data[1];

    uint16_t ModbusSlaveRegisters[4];

    void setup() {

    Serial.begin(115200);

    while (!Serial){

    }

    Serial.println(“Connecting to Serial3 “);

    master.begin(19200,SERIAL_8E1);

    Serial.println(“Connected”);

    Serial.println(“Enter desiderd address :”);

    master.setTimeOut(5000); // if there is no answer in 5000 ms, roll over

    u32wait = millis() + 2000;

    u8state = 0;

    i=0;

    ch=””;

    data[0].u8id = SlaveModbusAdd; // slave address

    data[0].u8fct = 6; // function code (this one is registers read)

    data[0].u16RegAdd = 19; // start address in slave

    data[0].u16CoilsNo = 1; // number of elements (coils or registers) to read

    data[0].au16reg = 123 ; //ModbusSlaveRegisters+4; // pointer to a memory array in the Arduino

    //ModbusSlaveRegisters[4] = 123;

    }

    void loop() {

    while (Serial.available()){

    caracter = Serial.read();

    ch.concat(caracter);

    }

    if (ch.toInt()>=1 and ch.toInt()<=247)

    {

    Serial.print(“Number received: “);

    Serial.println(ch);

    value = ch.toInt();

    ch=””;

    }

    else

    {

    //Serial.print(“bad number”);

    //Serial.println(ch);

    }

    delay(50);

    switch( u8state ) {

    case 0:

    if (millis() > u32wait) u8state++; // wait state

    break;

    case 1:

    if (value>=1 and value<=247)

    master.query(data[0]); // send query (only once)

    u8state++;

    break;

    case 2:

    master.poll(); // check incoming messages

    if (master.getState() == COM_IDLE) {

    //u8state = 0;

    u32wait = millis() + 500;

    Serial.println (“Value written : “);

    u8state++;

    }

    break;

    }

    } //

  • Lukas

    Member
    January 4, 2022 at 4:20 pm

    Hi,

    Do you have problem with register read (like in your sketch) or with register write (like in the title of the issue)?

    Do you have any progress so far?

    Thanks,

    Lukas

Viewing 1 - 2 of 2 replies

Log in to reply.

Original Post
0 of 0 posts June 2018
Now