Contoh program Modbus RTU Master

  1. Contoh program Modbus RTU Master
#include <ModbusMaster.h>

#define MAX485_DE      3
#define MAX485_RE_NEG  2

ModbusMaster node;

void preTransmission()
{
  digitalWrite(MAX485_RE_NEG, 1);
  digitalWrite(MAX485_DE, 1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);
}

void setup()
{
  pinMode(MAX485_RE_NEG, OUTPUT);
  pinMode(MAX485_DE, OUTPUT);

  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);

  Serial.begin(9600);

  node.begin(1, Serial);
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop()
{
  uint8_t result;
  uint16_t data[6];

  result = node.readInputRegisters(0, 6);

  if (result == node.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(node.strError(result));
  }

  delay(1000);
}