I am sending data through serial port .. the sending part is ok, I am getting the the data in the other end but I can’t get the acknowledgement part done… this is what I am doing …
mySerialPort.Open();
mySerialPort.Write(databuffer, 0, 19);
System.Threading.Thread.Sleep(2000);
if (mySerialPort.BytesToRead > 0) // this condition not working
{
string rdata = mySerialPort.ReadExisting();
if (rdata.ToUpper().Trim() == "OK")
{
lblmsg.Text = "OK";
}
else
{
lblmsg.Text = "FL";
}
}
mySerialPort.Close();
and further my settings of serial port is like this ….
public void SettingRS232(string port)
{
try
{
SerialPort mySerialPort = new SerialPort(port);
mySerialPort.PortName = port;
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.ReadTimeout = 2000;
mySerialPort.WriteTimeout = 500;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
}
catch (Exception ex)
{
lblmsg.Text = ex.Message;
}
}
That’s very little to go by. First use another program to test the connection, something like HyperTerminal or Putty. That lets you very that you got the basics correct, a proper electrical connection and the correct baudrate, parity, stopbits and databits settings. And check that the device returns a response within the magic number you picked, 2 seconds.
By far the most common mistake is not taking care of the proper Handshake. If you leave it at None then you must turn on the handshake signals yourself. Set the RtsEnable and DtrEnable properties to true. The device won’t send anything when it sees those signals turned off, it assumes that you are not powered-up (DTR) and not ready to receive data (RTS).
Further improve your code by avoiding mixing binary data and strings, get rid the awful Sleep(). Call the Read() method to receive bytes, pay attention to the return value to know how many you got. Keep calling Read() until you got all of the ones you expected to receive.
Edit: your SettingRS232() method has a bug:
That creates a local variable with the name mySerialPort. You are initializing that local variable, not the mySerialPort variable that the rest of your code is using. Fix the bug by writing it like this: