#include <ArduinoModbus.h>
#include <DHT.h>

#define DHTPIN 2        // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // Wait for serial port to connect
  }
  Serial.println("Serial port connected.");
  
  ModbusRTUServer.begin(1, 9600); // Initialize Modbus communication with device ID 1 and baudrate 9600
  Serial.println("Modbus communication initialized.");
  
  dht.begin();
  Serial.println("DHT sensor initialized.");
}

void loop() {
  float temperature = dht.readTemperature();  // Read temperature
  float humidity = dht.readHumidity();        // Read humidity
  
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" *C");

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  // Send data over Modbus
  if (ModbusRTUServer.holdingRegisterWrite(0, temperature * 10) != 0) {
    Serial.println("Failed to write temperature to holding register.");
  }
  if (ModbusRTUServer.holdingRegisterWrite(1, humidity * 10) != 0) {
    Serial.println("Failed to write humidity to holding register.");
  }

  delay(2000);  // Adjust as needed for your application
}
MAX485Breakout