#include <DHT.h>
#include <ModbusMaster.h>
#include <SoftwareSerial.h>

#define DHTPIN 2
#define DHTTYPE DHT22

#define MAX485_DE 8
#define MAX485_RE_NEG 8

DHT dht(DHTPIN, DHTTYPE);

ModbusMaster node;

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

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

#define BAUD_RATE 19200
#define PARITY 'E'

SoftwareSerial RS485Serial(3, 4); // RX, TX

void setup() {
  RS485Serial.begin(BAUD_RATE);
  Serial.begin(9600); // Initialize hardware serial for debugging
  dht.begin();

  pinMode(MAX485_RE_NEG, OUTPUT);
  pinMode(MAX485_DE, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(MAX485_RE_NEG, LOW);
  digitalWrite(MAX485_DE, LOW);
  node.begin(1, RS485Serial);
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop() {
  int result;
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  node.clearResponseBuffer();
  node.clearTransmitBuffer();
  result = node.writeSingleRegister(1, temperature * 10); // Convert float to int (temperature * 10)
  if (result != node.ku8MBSuccess) {
    Serial.print("Failed to write temperature to Modbus register! Error: ");
    Serial.println(result, HEX);
  }

  result = node.writeSingleRegister(2, humidity * 10); // Convert float to int (humidity * 10)
  if (result != node.ku8MBSuccess) {
    Serial.print("Failed to write humidity to Modbus register! Error: ");
    Serial.println(result, HEX);
  }

  // Debugging information
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print("°C, Humidity: ");
  Serial.print(humidity);
  Serial.println("%");

  delay(800);
}
Loading chip...chip-max485