/*
readCoils(slave_address, address, quantity);
readDiscreteInputs(slave_address, address, quantity);
readHoldingRegisters(slave_address, address, quantity);
readInputRegisters(slave_address, address, quantity);
writeSingleCoil(slave_address, address, value);
writeSingleRegister(slave_address, address, value);
writeMultipleCoils(slave_address, address, values, quantity);
writeMultipleRegisters(slave_address, address, values, quantity);
*/
#include <ModbusMaster.h> //Library for using ModbusMaster
#include <dht.h>
#define DHT22_PIN 2 // Adjust based on your DHT sensor model (4 or 5)
//int ran;
#define MAX485_DE 3
#define MAX485_RE_NEG 4
dht DHT;
float hum; // Stores humidity value
float temp; // Stores temperature value
ModbusMaster node; //object node for class ModbusMaster 8bits,none parity,1 stop bit
void preTransmission() //Function for setting stste of Pins DE & RE of RS-485
{
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);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
Serial.begin(9600); //Baud Rate as 9600
node.begin(1, Serial); //Slave ID as 1
node.preTransmission(preTransmission); //Callback for configuring RS-485 Transreceiver correctly
node.postTransmission(postTransmission);
}
void loop()
{
delay(2000); // Adjust delay as needed
int chk = DHT.read22(DHT22_PIN);
int result;
hum = DHT.humidity;
temp= DHT.temperature;
// ran=random(0,10);
uint16_t value = temp * 10;
node.clearResponseBuffer();
node.clearTransmitBuffer();
result = node.writeSingleRegister(40001,value);
if (result != node.ku8MBSuccess) {
Serial.print("Failed to write temperature to Modbus register! Error: ");
Serial.println(result, HEX);
}
/*
// Read temperature and humidity values from Modbus registers
node.clearResponseBuffer();
node.clearTransmitBuffer();
result = node.readInputRegisters(0x0001, 1);
if (result == node.ku8MBSuccess) {
temp = node.getResponseBuffer(0) / 10.0; // Divide by 10 to get the actual temperature
Serial.print("Read temperature from Modbus: ");
Serial.print(temp);
Serial.println(" °C");
} else {
Serial.print("Failed to read temperature from Modbus! Error: ");
Serial.println(result, HEX);
}
*/
delay(4000);
/*int led = node.readHoldingRegisters(0x40006,1);
if(led==1)
{
digitalWrite(LED_BUILTIN, LOW);
}
else if(led==0)
{
digitalWrite(LED_BUILTIN, HIGH);
}*/
}