Hi.
I am going to send/receive data to/from an RS485 device. Not to lose data, I have to be informed when send is completed and then start to receive data and vise versa.
In this way I changed the serial mode to RS485 Mode and used RTS as DE pin.
Hardware connections: (I am confused if I must use Serial1 or Serial2)
[Arduino] --- [ISL83485 IC]
Pin 23, RTS --- DE and /RE
Pin 17, RX2 --- RO
Pin 16, TX2 --- DI
I used the information of this website (Hardware RS485 - Arduino Due - Arduino Forum).
In the software, I initialized Serial2 to establish this connection.
The code:
#include "RS485_non_blocking.h"
#define DebugSerial Serial
#define MeterSerial Serial2
const byte msg [] = "Hello world";
char str[] = "Hello world";
unsigned int test;
size_t fWrite (const byte what) // The write function of the RS485 class
{
return MeterSerial.write (what);
}
int fAvailable ()
{
return MeterSerial.available ();
}
int fRead ()
{
return MeterSerial.read ();
}
//RS485 myChannel (fRead, fAvailable, fWrite, 20);
RS485 myChannel (NULL, NULL, fWrite, 0);
void setup() {
DebugSerial.begin(BaudRate_115200);
MeterSerial.begin(300, SERIAL_7E1);
myChannel.begin ();
pinMode(RTS, OUTPUT); //RTS for USART1=Serial2 set as output.
USART1->US_WPMR = 0x55534100; //Unlock the USART Mode register, just in case. (mine wasn't locked).
USART1->US_MR |= (1u << 0); //Set USART1 mode to RS485.
// USART1->US_MR |= (1u << 7); //7_BIT
}
void loop() {
myChannel.sendMsg(msg, sizeof(msg));
DebugSerial.println(MeterSerial.readString());
DebugSerial.println("send data to the meter");
// if (myChannel.update ())
// {
// MeterSerial.write (myChannel.getData (), myChannel.getLength ());
// MeterSerial.println ();
// }
delay(1000);
MeterSerial.println(str);
delay(5000);
}
But it sends some unexpected characters on the serial2 port. It seems that the serial port is not initialized correctly.
What is wrong with my code or hardware?!