#define DE_RE_PIN 25      // DE and RE pins linked to GPIO 18
#define rx2_pin   16
#define tx2_pin   17
#define MODE_SEND HIGH   // HIGH for transmitting
#define MODE_RECV LOW    // LOW for receiving
byte ByteArray[40];int ByteData[40];
float temp = 0, humi = 0;

void readXY_MD02() {
  // Modbus command to read two holding registers (temp and humi) from device 0x01
  uint8_t buff[] = {
    0x02, // Device Address
    0x04, // Function code (Read Input Registers)
    0x00, // Start Address HIGH (0x0001 for temperature)
    0x01, // Start Address LOW
    0x00, // Quantity HIGH
    0x02, // Quantity LOW (read 2 registers)
    0x20, // CRC LOW
    0x38  // CRC HIGH
  };

  digitalWrite(DE_RE_PIN, MODE_SEND); // Enable transmission
  Serial2.write(buff, sizeof(buff));   // Send the command via Serial2
  Serial2.flush();  delayMicroseconds(50);  // Wait for send to complete
  digitalWrite(DE_RE_PIN, MODE_RECV);  // Enable reception

  int a = 0;

  while(Serial2.available()){
    ByteArray[a] = Serial2.read();
    a++;
  }
   // The sensor should respond with a packet like: 
   //[0]=2 [1]=4 [2]=4 [3]=1 [4]=4a [5]=2 [6]=b8 [7]=e9 [8]=bc  
 
  int b = 0;
  String Register;
  Serial.println("Receiving Data...");
  for(b=0;b<a;b++){
    Serial.print("[");
    Serial.print(b);
    Serial.print("]");
    Serial.print("=");

    Register = String(ByteArray[b],HEX);
    Serial.print(Register);
    Serial.print(" ");
  }

  Serial.println();
  Serial.println();
  temp = (int)(ByteArray[3] << 8 | ByteArray[4]) / 10.0f;
  humi = (int)(ByteArray[5] << 8 | ByteArray[6]) / 10.0f;


}

void setup() {
  pinMode(DE_RE_PIN, OUTPUT);
  digitalWrite(DE_RE_PIN, MODE_RECV); // Start in receive mode
  Serial.begin(115200);               // Serial monitor output
  Serial2.begin(9600, SERIAL_8N1,rx2_pin ,tx2_pin ); // Initialize Serial2 with standard Modbus settings
  Serial2.setTimeout(200);            // Set a timeout for response
}

void loop() {
  readXY_MD02();
  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println(" *C");
  Serial.print("Humidity: ");
  Serial.print(humi);
  Serial.println(" %");
  delay(2000);
}
