Contoh program Modbus TCP Master

  1. Contoh program Modbus TCP Master

#include <SPI.h>
#include <Ethernet.h>
#include <ModbusIP.h>

IPAddress server(192, 168, 1, 177);

EthernetClient client;
ModbusIP mb;

void setup()
{
  Ethernet.begin(mac);
  Serial.begin(9600);
  mb.client();

  if (!client.connect(server, 502))
  {
    Serial.println("Connection failed.");
    return;
  }
}

void loop()
{
  uint16_t data[6];

  int result = mb.readInputRegisters(1, 0, 6, data);

  if (result == mb.ku8MBSuccess)
  {
    Serial.print("Humidity: ");
    Serial.print(data[0]);
    Serial.print(" %\t Temperature: ");
    Serial.print(data[1]);
    Serial.println(" °C");
  }
  else
  {
    Serial.print("Error: ");
    Serial.println(mb.lastError());
  }

  delay(1000);
}