// Libraries
#include <dht.h> // Sensor library from https://www.ardumotive.com/how-to-use-dht-22-sensor-en.html
#include <LiquidCrystal_I2C.h> // LCD library from https://www.ardumotive.com/i2clcden.html
#include <Wire.h> 
#include <ModbusMaster.h>

// Constants
#define MAX485_DE 3
#define MAX485_RE_NEG 4
#define DHT22_PIN 2 // Digital pin used for DHT22 sensor
#define LCD_ADDRESS 0x27 // I2C address of the LCD
#define LCD_COLUMNS 16 // Number of columns in the LCD
#define LCD_ROWS 2 // Number of rows in the LCD
#define SLAVE_ID 1 // Modbus Slave ID (1-127)

// Initialize objects
ModbusMaster node;
dht DHT;
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS); 

void setup() {
    // Initialize LCD
    lcd.init();
    lcd.backlight();
    lcd.setBacklight(HIGH);

    // Initialize RS-485 transceiver pins
    pinMode(MAX485_RE_NEG, OUTPUT);
    pinMode(MAX485_DE, OUTPUT);
    digitalWrite(MAX485_RE_NEG, LOW);
    digitalWrite(MAX485_DE, LOW);

    // Initialize serial communication for Modbus
    Serial.begin(9600);
    node.begin(SLAVE_ID, Serial);
}

void loop() {
    // Read data from DHT22 sensor
    int chk = DHT.read22(DHT22_PIN);

    // Read humidity and temperature
    float hum = DHT.humidity;
    float temp = DHT.temperature;

    // Check if readings are valid
    if (isnan(temp) || isnan(hum)) {
      Serial.println("Failed to read data from DHT sensor");
      return;
    }

    // Display temperature and humidity on LCD
    lcd.setCursor(0,0);
    lcd.print("Humidity: ");
    lcd.print(hum);
    lcd.print("%");
    lcd.setCursor(0,1);
    lcd.print("Temp: "); 
    lcd.print(temp);
    lcd.println(" C");

    // Print temperature to Serial monitor
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.println(" °C");

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

    // Example logic for controlling LEDs based on humidity
    if (hum > 50) {
        digitalWrite(8, HIGH);
        digitalWrite(7, LOW);
        delayMicroseconds(500);
    } else if (hum < 30) {
       digitalWrite(8, LOW);
       digitalWrite(7, HIGH);
    }

    delay(2000); // Delay between readings
}
Loading chip...chip-max485
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module