บทความ

ESP32 เชื่อมต่อกับเซนเซอร์ 3 in 1 วัดอุณหภูมิ ความชื้นและแสง (Light Temperature and Humidity)

#include <ModbusMaster.h>

 

#define MAX485_DE      32

#define MAX485_RE_NEG  33

 

#define RXD2 16

#define TXD2 17

 

ModbusMaster node;

 

void preTransmission()

{

  digitalWrite(MAX485_RE_NEG, 1);

  digitalWrite(MAX485_DE, 1);

}

 

void postTransmission()

{

  digitalWrite(MAX485_RE_NEG, 0);

  digitalWrite(MAX485_DE, 0);

}

 

void setup() {

  Serial.begin(4800);

  pinMode(MAX485_RE_NEG, OUTPUT);

  pinMode(MAX485_DE, OUTPUT);

  digitalWrite(MAX485_RE_NEG, 0);

  digitalWrite(MAX485_DE, 0);

 

  Serial2.begin(4800, SERIAL_8N1, RXD2, TXD2);

  node.begin(1, Serial2);  // Modbus slave ID 1 for 3 in 1

  node.preTransmission(preTransmission);

  node.postTransmission(postTransmission);

}

 

void loop() {

  uint8_t result = node.readInputRegisters(0x0001, 2); // Read one register

 

  Serial.println(“Get 3 in 1 Data”);

  result = node.readInputRegisters(0x0000, 3);

  if (result == node.ku8MBSuccess) {

    float humi = (node.getResponseBuffer(0)/10.0f); 

    float temp = (node.getResponseBuffer(1)/10.0f);

    float light = (node.getResponseBuffer(2)/10.0f);

 

    Serial.print(“Humi: “);

    Serial.print(humi);

    Serial.println(” %”);  

    Serial.print(“Temp: “);

    Serial.print(temp);

    Serial.println(” C”);

    Serial.print(“Light: “);

    Serial.print(light);

    Serial.println(” Lux”);

  }

  delay(2000); // Delay between readings

}