c# - How can I implement RS485 2 wires bidirectional communication in .NET? -
i'm trying bidirectional communication using rs485 2 wires , i've tried far failed.
i can send data , have peripheral react expected (so wiring correct), never receive reply.
i'm using .net serialport
, i've tried using datareceived
event , loop in thread
polling port. i've tried blocking on read until enough data received.
i have tried several hardware options:
- pci rs232 card sena rs232-rs485 converter
- pci rs232 card moxa rs232-rs485 converter
- pci rs485 card
i have played driver settings: - fifo interrupt trigger levels - receiver fifo flow control thresholds - rs485 buffer enable (normal, active high, active low)
following various leads (like can't receive serial data in .net 2.0, using rs232 rs485 converter), i've tried setting dtrenable
true, or false, or switching it.
i've tried switching rtsenable
when sending , receiving (following http://en.wikipedia.org/wiki/rs-232#rts.2fcts_handshaking).
i don't see else try right without resorting different wiring. wrong?
as requested, code (it's snapshot after many attempts):
open:
_serialport = new serialport(comboboxserialport.text, 9600, parity.none, 8, stopbits.one) { writetimeout = 500, readtimeout = 500, handshake = handshake.none }; _serialport.open(); _serialport.dtrenable = true; _serialport.rtsenable = true;
send:
_serialport.rtsenable = false; _serialport.write(data, 0, data.length); _serialport.rtsenable = true; thread.sleep(1); _datasent.set();
reader thread:
var port = form1._serialport; byte[] buffer = new byte[128]; int read = 0; { array.clear(buffer, 0, buffer.length); read = 0; try { form1._datasent.waitone(); //if (port.bytestoread > 0) read = port.read(buffer, 0, buffer.length); } catch (timeoutexception) { } catch (exception ex) { form1.invoke(form1.adderrormethod, ex.tostring()); continue; } if (read > 0) { form1.invoke(form1.addoutputmethod, bytelisttostring(buffer)); } thread.sleep(20); } while (_continue);
note: data packets 10 bytes long, in both directions.
i've fixed issue on 1 hardware configuration (the rs485 card) by:
- fixing wiring: although it's called '2 wires', 4 pins/wires card need used, joined, 2 tranport wire.
- using dtrenable indicate sending/receiving
- waiting before enabling receive mode after send.
my send code looks this:
// enable send mode serialport.dtrenable = false; serialport.write(data, 0, data.length); // wait little, enable response mode. thread.sleep(15); serialport.dtrenable = true;
Comments
Post a Comment