#include <DHT.h>
#include   <dht.h>
#include <Wire.h>
#include <ModbusRTUSlave.h> 
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SoftwareSerial.h>

#define   DHT22_PIN 2 // Adjust based on your DHT sensor model (4 or 5)
// #define DHTTYPE DHT22
#define SLAVE_ID 1 

dht DHT;

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const byte dePin = 3;
const byte rePin = 3;
const byte rxPin = 10;
const byte txPin = 11;
SoftwareSerial mySerial(rxPin, txPin);
ModbusRTUSlave modbus(mySerial, dePin); // Use default baud rate

uint16_t holdingRegisters[2];

float hum;  // Stores humidity value
float temp; // Stores temperature value

void setup() {
  Serial.begin(9600);
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("SSD1306 Display initialization failed!");
    while (1);
  }
 // dht.begin();
  modbus.configureHoldingRegisters(holdingRegisters, 2);  // Configure registers
  // Uncomment if using LCD
  // lcd.init();
}

void loop() {
  delay(2000); // Adjust delay as needed
 int chk = DHT.read22(DHT22_PIN);

   hum = DHT.humidity;
    temp= DHT.temperature;

  if (isnan(hum) || isnan(temp)) {
    Serial.println("Sensor reading failed!");
    return;
  }

  // Clear the display
  display.clearDisplay();

  // Display data on OLED
  display.setTextColor(WHITE);
  display.setTextSize(1.9);
  display.setCursor(2, 5);
  display.print("Humidity: ");
  display.print(hum);
  display.print(" %");
  display.setCursor(2, 20);
  display.print("Temp: ");
  display.print(temp);
  display.print(" ");
  display.print((char)247);  // Degree symbol
  display.print("C");
  display.display();


  // Store values in Modbus registers (correct way)
  holdingRegisters[0] = temp * 10;  // Multiply by 10 for 1 decimal place
  holdingRegisters[1] = hum;
 // uint8_t cbWrite(Modbus::ResultCode event, uint16_t transactionID, void* data) {
  //return 0;

  modbus.poll(); // Check for Modbus requests
}
Loading chip...chip-max485