# การใช้งาน IOXESP32 Modbus RTU shield / Lite กับโมดูล XY-MD02 วัดอุณหภูมิและความชื้น

XY-MD02 เป็นโมดูลวัดอุณหภูมิและความชื้นที่สื่อสารผ่าน Modbus RTU นิยมใช้ในการศึกษาการทำงานของ Modbus RTU / RS485 ในบทความนี้จะนำโมดูลดังกล่าวมาต่อเข้ากับ IOXESP32 Modbus RTU shield เพื่อทดสอบการทำงานและเรียนรู้การใช้งาน

{% hint style="danger" %}
**ห้ามจ่ายไฟผ่านช่อง 7-24V พร้อมเสียบสาย USB โดยเด็ดขาด**
{% endhint %}

## การต่อวงจร

ให้ต่อวงจรระหว่างชุด IOXESP32 Modbus RTU shield กับ XY-MD02 ดังนี้

![](/files/-MTGyFsdyuZSHHwqyCRO)

* โมดูล IOXESP32 Modbus RTU shield ใช้ไฟจาก USB จึงไม่ต้องต่อไฟเลี้ยงเข้าอีก
* XY-MD02 ใช้ไฟจากแหล่งจ่ายไฟแยก 5V ถึง 30V
* IOXESP32 Modbus RTU shield และ XY-MD02 เชื่อมต่อผ่าน RS485 ด้วยสาย A และ B โดย A ต่อ A และ B ต่อ B

## การเขียนโปรแกรม

ใช้โปรแกรม ArduinoIDE ในการพัฒนา ... อัพโหลดโค้ดโปรแกรมต่อไปนี้ลงบอร์ด IOXESP32

```cpp
/* Dev by IOXhop.com */

float temp = 0, humi = 0;

void readXY_MD02() {
  uint8_t buff[] = {
    0x01, // Devices Address
    0x04, // Function code
    0x00, // Start Address HIGH
    0x01, // Start Address LOW
    0x00, // Quantity HIGH
    0x02, // Quantity LOW
    0x20, // CRC LOW
    0x0B  // CRC HIGH
  };

  Serial2.write(buff, sizeof(buff));
  Serial2.flush(); // wait MODE_SEND completed

  if (Serial2.find("\x01\x04")) {
    uint8_t n = Serial2.read();
    if (n != 4) {
      Serial.println("Error data size");
      return;
    }

    temp = ((uint16_t)(Serial2.read() << 8) | Serial2.read()) / 10.0;
    humi = ((uint16_t)(Serial2.read() << 8) | Serial2.read()) / 10.0;
  } else {
    Serial.println("ERROR Timeout");
    return;
  }
}

void setup() {
  Serial.begin(115200);

  Serial2.begin(9600, SERIAL_8N1, 27, 26); // Rx, Tx
  Serial2.setTimeout(200);
}

void loop() {
  readXY_MD02();
  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println(" *C");
  Serial.print("Humidity: ");
  Serial.print(humi);
  Serial.println(" *C");
  delay(500);
}
```

## การทดสอบ

เปิด Serial Monitor ขึ้นมา ตั้งค่าความเร็วเป็น 115200 baud หาก IOXESP32 Modbus RTU shield กับ XY-MD02 สามารถสื่อสารกันได้ ค่าอุณหภูมิและความชื้นที่วัดได้จะแสดงดังรูป

![](/files/-MTH9Y_LMx259byIw93W)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://artronshop.gitbook.io/ioxesp32/ioxesp32-modbus-rtu-shield/use-with-xt-md02.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
