การใช้งาน IOXESP32 Modbus RTU shield / Lite กับบอร์ดรีเลย์ Modbus RTU/RS485 4 ช่อง 12V

ตัวอย่างการใช้งาน IOXESP32 Modbus RTU shield ต่อกับบอร์ดรีเลย์ Modbus RTU

บอร์ดรีเลย์ Modbus RTU/RS485 4 ช่อง 12V ใช้ขับอุปกรณ์กำลังสูง เช่น หลอดไฟ 220V เครื่องใช้ไฟฟ้าต่าง ๆ ในตัวอย่างนี้จะแนะนำการใช้งานร่วมกับ IOXESP32 Modbus RTU shield โดยเขียนโปรแกรมสั่งเปิด-ปิดรีเลย์ เพื่อให้ต่อยอดได้ต่อไป

ห้ามจ่ายไฟผ่านช่อง 7-24V พร้อมเสียบสาย USB โดยเด็ดขาด

การต่อวงจร

ให้ต่อวงจรระหว่างชุด IOXESP32 Modbus RTU shield กับบอร์ดรีเลย์ดังนี้

  • โมดูล IOXESP32 Modbus RTU shield ใช้ไฟจาก USB จึงไม่ต้องต่อไฟเลี้ยงเข้าอีก

  • บอร์ดรีเลย์ใช้ไฟจากแหล่งจ่ายไฟแยก 12V

  • IOXESP32 Modbus RTU shield และบอร์ดรีเลย์เชื่อมต่อผ่าน RS485 ด้วยสาย A และ B โดย A ต่อ A และ B ต่อ B

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

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

/* Dev by IOXhop.com */

void setup() {
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, 27, 26); // Rx, Tx
  Serial2.setTimeout(100);
}

uint16_t CRC16(uint8_t *buf, int len) {  
  uint16_t crc = 0xFFFF;
  for (uint16_t pos = 0; pos < len; pos++) {
    crc ^= (uint16_t)buf[pos];        // XOR byte into least sig. byte of crc
    for (int i = 8; i != 0; i--) {    // Loop over each bit
      if ((crc & 0x0001) != 0) {      // If the LSB is set
        crc >>= 1;                    // Shift right and XOR 0xA001
        crc ^= 0xA001;
      } else {                        // Else LSB is not set
        crc >>= 1;                    // Just shift right
      }
    }
  }

  return crc;
}

void relayWrite(uint8_t n, bool setToON) {
  if (n < 1 || n > 4) {
    return;
  }
  
  uint8_t buff[] = {
    0x01,                  // Devices Address
    0x05,                  // Function code
    0x00,                  // Start Address HIGH
    n - 1,                 // Start Address LOW
    setToON ? 0xFF : 0x00, // Data 1 HIGH
    0x00,                  // Data 1 LOW
    0,                     // CRC LOW
    0                      // CRC HIGH
  };

  uint16_t crc = CRC16(&buff[0], 6);
  buff[6] = crc & 0xFF;
  buff[7] = (crc >> 8) & 0xFF;

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

  if (!Serial2.find("\x01\x05")) {
    Serial.println("Write to Relay error !");
    return;
  }
}

void loop() {
  relayWrite(1, HIGH); // Relay 1 -> ON
  delay(1000);
  relayWrite(1, LOW);  // Relay 1 -> OFF
  relayWrite(2, HIGH); // Relay 2 -> ON
  delay(1000);
  relayWrite(2, LOW);  // Relay 2 -> OFF
  relayWrite(3, HIGH); // Relay 3 -> ON
  delay(1000);
  relayWrite(3, LOW);  // Relay 3 -> OFF
  relayWrite(4, HIGH); // Relay 4 -> ON
  delay(1000);
  relayWrite(4, LOW);  // Relay 4 -> OFF
}

ผลที่ได้

รีเลย์ช่อง 1 ถึงช่อง 4 ติด และดับ ไปเรื่อย ๆ ตามคลิปวิดีโอดังนี้

Last updated