i am using Arduino Due to do serial half duplex communication with Reaction Wheel(RW) using RS485.Below is my code.When i press enter the communication initiates.It takes the command from the RWCommand_6000[] array which is defined below.The output is saved in response[] array.Sending command to control my system seems to be easy but receiving the response from the system to arduino is giving the problem.I got around this by introducing a delay of around 1ms but cant figure it out why introducing delay is doing the trick.In the code below, i send the command bytes to RW and at the end of the final bytes the program enters the if() statement which Enables the Receiver to receive the response data to Arduino.Its in the if() statement block where i introduced the delayMicroseconds(1000) before enabling the Receiver.
Any idea why introducing delay is helping in this case?
I am using digitalWrite() to turn the pin HIGH or LOW and i dont like this idea because digitalWrite is slow,in Arduino Due i cant use DDR registor and PORTx to manipulate pins,maybe this is giving me the problem but i am not sure.
#define SerialTXControl 11 // RS485 Direction control
byte RW_response[64];
byte response[50];
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial2.begin(115200);
pinMode(SerialTXControl,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
char input = Serial.read();
if(input==13){ //press enter to initiate serial communication
for (int i=0; i<14; i++) { // the command to RW90 has at most 14 bytes
byte RWCommand_6000[] = {0x7e, 0x77, 0x40, 0x00, 0x06, 0x6d, 0x67, 0x00, 0xc3, 0x4f, 0xff, 0x4e, 0xf9, 0x0d};
digitalWrite(SerialTXControl,HIGH); //turns the Driver pin High to send data
Serial2.write(RWCommand_6000[i]);
Serial.print(RWCommand_6000[i],HEX); // print the command to monitor for degubbing
Serial.print(" ");
/******* this block check for the end byte and enables the receiver *******/
if(i==13){
Serial.println();
Serial.print("R: ");
delayMicroseconds(1000); /* using the delay function seems to establish the two way
communication */
digitalWrite(SerialTXControl,LOW); // enables the Receiver pin to get data from RW
if(Serial2.available()>0){
for(int j=0;j<12;j++){ /* the response is 12byte long */
Serial2.readBytes(response,Serial2.available());
Serial.print(response[j],HEX);
Serial.print(" ");
if(j==11){
Serial.println();
}
}
}
}
}
}
}
Thanks,
Bikash