uldara1 / Modbus

This library using for generate and communication with Modbus RTU protocol
Other
2 stars 1 forks source link

How to use the library #1

Closed JohannieK closed 1 year ago

JohannieK commented 1 year ago

Hi

I am trying to use the modbus library with an Arduino Mega2560 with the following code, but it seems to not work:

include

Modbus mb(Serial2);

void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial2.begin(9600); mb.init(16); if (mb.requestFrom(1, 3, 256, 16)) { for (int i = 0;i<16;i++) { Serial.print(mb.byteRead(i)); Serial.print(", "); }

} else { Serial.println("Request Failed"); } }

void loop() { // put your main code here, to run repeatedly:

}

I have used a modbus app on my pc to communicate with the device (SRNE charge controller) and I have communication with the device via the Windows app, so I know the device is wired up correctly.

uldara1 commented 1 year ago

Hi @JohannieK Sorry for library that haven't example yet. Please check code below for sample and this code work for me with energy meter device Make sure your register address is correct could you share SRNE model or modbus document ?

#include <Modbus.h>
#define MODE 5
#define RS485 Serial2
Modbus mbus(RS485);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  //RS485.begin(9600, SERIAL_8N1, 19, 18); // 19/18
    RS485.begin(9600);
  mbus.init(MODE);

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1000);

  //Serial.println(mbus.coilRead(17));
  // //Read Coil Register    (0x01) bit
  //  if( mbus.requestFrom(1,1,17,3))
  //  {
  //    byte val = mbus.byteRead(0); // read byte index 0     
  //  }

  // //Read Discret Register (0x02) bit
  // mbus.requestFrom(1,2,17,3);

  // //Read Input Register   (0x04)  byte 
  // mbus.requestFrom(1, 4, 21 , 4);

  //Read Holding Register (0x03)  byte
  if(mbus.requestFrom(1,3,1,3))                // Slave Id=1, func 3, register address, block count
  {

      Serial.println(mbus.blockRead(0) );   // Read 2 byte or Int16
      Serial.println(mbus.blockRead(1) );
      Serial.println(mbus.blockRead(2) );
      Serial.println();
  }
}
uldara1 commented 1 year ago

@JohannieK Any update ?