Reputation: 43
I'm trying to communicate with a win ce device via a rs485 connection configured as 8n1 and no handshaking. The problem is the device has two modes of operation acting as a receiver or a transmitter. In order to change between the two modes of operation i need to toggle rts on/off. I have tried to do so but the device never changes mode unless i use breakpoints where rts is enabled or disabled. This leads me to believe that there is a timing problem and rts is toggled on and off before I manage to send anything (the default mode is receive). I've tried looking through previous questions on the topic and i have tried google but so far i haven't come across anything. Can anyone please help?
Here is my code:
public static ushort Send_rs485(byte[] ToSend)
{
try
{
rs485.Write(ToSend, 0, ToSend.Length);
}
catch (TimeoutException)
{
MessageBox.Show("COM port error");
}
return (0);
}
private void button2_Click(object sender, EventArgs e)
{
if (COM_opened)
{
bool CTS = false;
rs485.RtsEnable = true;
rs485_Execute_cmd(on_off);
on_off = !on_off;
rs485.RtsEnable = false;
}
else
{
MessageBox.Show("COM port not opened");
}
//rs485.RtsEnable = false;
}
Upvotes: 0
Views: 355
Reputation: 63772
The basic problem is that Write
doesn't wait for all the data to be transmitted IIRC. This isn't a big problem when you're communicating in a reasonable way, since it still waits for the data to be buffered (so you don't try to send 100 MiB/s), but if you're also doing other things other than simple reads and writes (in your case, changing pins), this creates a synchronization issue.
That means that you have to wait - and communication over the serial port is usually quite slow. To get the amount of time you have to wait, you need to know the amount of data you're sending and the baud rate. For example, to send 12 bytes over a 9600 baud port, you will need to wait for 10 ms.
I'm not sure if there's something you can use to make this feel less dirty.
Upvotes: 2