Hello,
I have a problem I have been unable to solve for quite some
time now. I'm using the Serialport class and opening the port and
writing a byte to it. The byte is successfully received by the other
device. The other device then sends back a response.
But what I get back is the same character I sent! e.g. if i send 2, i
get back 2.
What is going on here? Why are things being echoed back. My code is
below. Please someone help me as I am going crazy with this? I even
tried using a thread with the same characteristic lack of success. It
works ok with a VC++ program I have so the mistake must be somewhere in
the c# code below. Can you spot it?
--------------------------
// connect statement. it also sets up the receiver event
handler
public void Connect()
{
port = new SerialPort("COM3", 57600, Parity.None, 8,
StopBits.One);
port.ReadTimeout = 500;
if (!port.IsOpen)
{
port.Open();
port.DataReceived += new
SerialDataReceivedEventHandler(Receiver);
}
}
// eventhandler that activates when a byte is received
public void Receiver(object sender, SerialDataReceivedEventArgs
e)
{
intBytes = port.BytesToRead;
byte[] bytes = new byte[intBytes];
port.Read(bytes, 0, intBytes);
str2 += bytes[0].ToString();
MessageBox.Show(str2);
}
// to send the number 2 to the other device (gets there
successfully)
public void Sender()
{
port.DiscardOutBuffer();
port.DiscardInBuffer();
port.Write("2");
}