I am trying to read data from a serialport. When i use USB adapters i get junk instead of what is sendt.
What i expect (And get with a normal serialport)
0001 C0 23:33:41.9114 00
0001 C1 23:34:17.8207 00
0001 RT 00:00:35.90 00
n0002
0002 C0 23:34:32.8372 00
0002 C1 23:42:36.2617 00
0002 RT 00:08:03.42 00
n0003
0003 C0 23:42:44.3947 00
What i get when connected through a USB serial port (0x00 0x3F ...)
003F003F783F003F003F003F003F003F
003F003F003F003F003F3F3F3F003F00
3F3F78003F003F003F003F003F780000
3F003F783F003F003F003F003F003F00
3F003F003F003F003F3F3F3F003F003F
3F78003F003F00
Also when i use Putty to connect it displays correct texte even through USB serial port.
What can be wrong here? How does Putty "fix" the corrupt data.
Edit: Added code used for reading
SerialPort p = new SerialPort(Conf.Value("ExternalClockPort"), int.Parse(Conf.Value("ExternalClockBaud")), Parity.None, 8, StopBits.Two);
p.Handshake = Handshake.RequestToSend;
p.Open();
byte[] buffer = new byte[512];
String command = "";
while (!Done)
{
int cnt = p.Read(buffer, 0, buffer.Length);
File.AppendAllText(this.appDataDirectory + "ExternalClock.log", ASCIIEncoding.ASCII.GetString(buffer, 0, cnt));
command = ExternalClock.parseCommand(command + ASCIIEncoding.ASCII.GetString(buffer, 0, cnt));
}
OK, so you need to register an event DataRecieved
and read the port data from it. Also, make sure your port initialization values are correct.
_sp = new SerialPort(Conf.Value("ExternalClockPort"), int.Parse(Conf.Value("ExternalClockBaud")), Parity.None, 8, StopBits.Two);
_sp.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);
_sp.Open();
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int totalBytes = _sp.BytesToRead;
byte[] buffer = new byte[totalBytes];
_sp.Read(buffer, 0, totalBytes);
}
I have got the answer to your question. I had the same problem and the fix was as follows: My parity was set to Odd instead of Even, and I was having this exact issue up until I changed the parity to Even.
myParity = Parity.Even;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.