You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.9 KiB
Arduino

// Sample communication Code for RS 485 Shield with Arduino Mega 2560
#define RS485_OE_1 22 //RS485 CH#1 Output Enable => pin 22 for CH#1
#define Snd_485 HIGH
#define Rcv_485 LOW
#define MC9_10_PV "10DRS,08,0001CB"
#define MC9_10_SV "10DRS,08,0011CC"
void RS485_setup(){
Serial1.setTimeout(300);
Serial1.begin(9600);
pinMode(RS485_OE_1, OUTPUT);
delay(10);
digitalWrite(RS485_OE_1, Rcv_485);
}
void send_485(){
if(!Wait_485){
String message = read_buff(Buff_485_Wr);
// Send request to return pv data
//Serial.println(Buff_485_Wr);
//Serial.print(message);
//Serial.print(" : ");
if(message != ""){
latest_sent_msg = message;
message += "\r\n";
digitalWrite(RS485_OE_1, Snd_485); delay(5);
Serial1.print(message);
returnTime = millis();
Serial1.flush();
digitalWrite(RS485_OE_1, Rcv_485); delay(5);
Wait_485 = true;
Wait_485_cnt = 0;
}
else{
//Serial.println("Free");
}
}
}
int read_485(){
// Timeout code
if(Wait_485){
Wait_485_cnt++;
if(Wait_485_cnt > 200){ // Timeout = periodic(100ms) x 200 = 2 sec
Serial.println("485 not responced... (Timeout)");
latest_sent_msg = "";
Wait_485 = false;
Wait_485_cnt = 0;
numOf485--;
return 0;
}
}
// Receive pv data
while(Wait_485 && (Serial1.available() > 0)) {
char c = Serial1.read();
write_buff_c(Buff_485_Rd, c);
}
String message = read_buff(Buff_485_Rd);
if(message != ""){
int addr;
String mode;
int data[8];
int crc;
numOf485--;
//message.replace("\r\n","");
//Serial.println(message);
if (parseMessage(message, addr, mode, data, crc)) {
if(latest_sent_msg == MC9_10_PV){
for(int i = 0 ; i < Size_PV ; i++){
Values_10_PV[i] = data[i];
}
}
if(latest_sent_msg == MC9_10_SV){
for(int i = 0 ; i < Size_SV ; i++){
Values_10_SV[i] = data[i];
}
}
} else {
// OK가 아닌 경우 또는 파싱 오류가 발생한 경우
Serial.println("error 485 read");
}
Wait_485 = false;
Wait_485_cnt = 0;
}
return 1;
}
int parseMessage(const String& message, int& addr, String& mode, int data[8], int& crc) {
char addrC[3], modeC[4], statusC[3];
int dataC[8], crcC;
if (message[0] == '\x02') {
message = message.substring(1);
}
int ret = sscanf(message.c_str(), "%2s%3s,%2s,%4x,%4x,%4x,%4x,%4x,%4x,%4x,%4x%2x",
addrC, modeC, statusC, &dataC[0], &dataC[1], &dataC[2], &dataC[3], &dataC[4], &dataC[5], &dataC[6], &dataC[7], &crcC);
if (strcmp(statusC, "OK") != 0 || ret != 12) {
// 오류 처리
return 0;
}
// 복사
addr = atoi(addrC);
mode = String(modeC);
for (int i = 0; i < 8; i++) {
data[i] = dataC[i];
}
crc = crcC;
return 1;
}