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.

103 lines
2.1 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
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);
if(message != ""){
//save sent message info. for received data processing
latest_sent_msg = message;
message += CRLF;
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 recieve_485(){
// Timeout code
if(Wait_485){
Wait_485_cnt++;
if(Wait_485_cnt > 25){ // Timeout = periodic(20ms) x 25 = 500 msec
Serial.println("485 not responced... (Timeout)");
if((latest_sent_msg == MC9_10_PV) ||(latest_sent_msg == MC9_10_SV)){
timeoutMC9();
}
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 != ""){
numOf485--;
if((latest_sent_msg == MC9_10_PV) ||(latest_sent_msg == MC9_10_SV)){
saveMC9(message);
}
else{
Serial.print("485 rcv : ");
Serial.println(message);
}
Wait_485 = false;
Wait_485_cnt = 0;
}
return 1;
}
/* For Test from PC */
void recieve_485_0(){
// Receive pv data
while(Serial.available() > 0) {
char c = Serial.read();
IdeSerial += c;
}
if(IdeSerial.endsWith("\n")){
IdeSerial.replace(CRLF,"");
IdeSerial += sumMC9(IdeSerial);
IdeSerial = "" + IdeSerial + CRLF;
write_buff_first(Buff_485_Wr, IdeSerial);
IdeSerial = "";
}
}