目的: 測試ESP32與PLC RS485通訊
系統架構
接線
開發板設定
程式
//NodeMCU_32S UART2 -- DVP COM2 RS485 RTU F03
#include <HardwareSerial.h>
#define RXD2 16
#define TXD2 17
byte inByte[50] ; // 用來儲存收進來的 data byte
//read D0,D1 command : "010310000002C0CB"
byte cmd[]={0x01,0x03,0x10,0x00,0x00,0x02,0xC0,0xCB};
int i=0;
boolean once = false;
void setup() {
Serial.begin(115200);
// Serial2.begin(baud-rate, protocol, RX pin, TX pin);
Serial2.begin(9600, SERIAL_8E1, RXD2, TXD2); //Modbus RTU 9600,8,E,1
}
void loop(){
if(!once){
Serial.println("ESP32 --> DVP PLC");
for(i=0;i<sizeof(cmd);i++){ //for PC Monitor
Serial.print(cmd[i],HEX);
Serial.print(" ");
}
Serial2.write(cmd,sizeof(cmd)); //ESP32 2 PLC
delay(100);
Serial.println(" ");
Serial.println(" ");
// PLC Response
i=0;
while (Serial2.available()) { //PLC 2 ESP32
inByte[i++] = Serial2.read();
}
int len = i;
Serial.println("DVP PLC --> ESP32");
for(i=0;i<len;i++){ //for PC Monitor
Serial.print(inByte[i],HEX);
Serial.print(" ");
}
Serial.println(" ");
i=0;
once = true;
}//end once
}
沒有留言:
張貼留言