Click to See Complete Forum and Search --> : [RESOLVED] SerialPort problem


jasonli
February 12th, 2009, 10:21 AM
I am using SerialPort class to communicate with scale on COM1.

The communication is good tested by a serial port debug tool. I set COM1, 9600, N, 8, 1 and send "W"+NewLine, get received data like "0A 20 30 30 39 2E 37 35 4C 0D 0A 30 30 0D 03 0A 3F 0D 0A 3F 0D".

If I use SerialPort class to send and recieve, I only get "0A 3F 0D"., can't get the whole data.

Anybody have an idea about this?

As below is the part of source code: public SerialPort sPort;
private void Form1_Load(object sender, EventArgs e)
{
sPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
sPort.Handshake = Handshake.RequestToSend;
sPort.Encoding = Encoding.ASCII;
sPort.DataReceived += new SerialDataReceivedEventHandler(sPort_DataReceived);
sPort.Open();
}

private void button1_Click(object sender, EventArgs e)
{
if (!sPort.IsOpen)
sPort.Open();

sPort.WriteLine("W");
}
void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
byte[] buf = new byte[sPort.BytesToRead];
sPort.Read(buf, 0, sPort.BytesToRead);
string strs = "";
foreach (byte ch in buf)
{
strs += Convert.ToInt32(((int)ch)).ToString() + ",";
}
MessageBox.Show(strs);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

eclipsed4utoo
February 12th, 2009, 11:03 AM
if you breakpoint, what is the value of "BytesToRead"?

ricky_cpp
February 13th, 2009, 05:15 AM
Hello Jasonli,

I will suggest you to use asynchronous stream attached with base stream of your port. I was also useing port.Read but it was always gving me problems.

with stream assignment, you can use BeginRead and EndRead and it is really effective.

-Ricky

jasonli
February 13th, 2009, 08:16 AM
Thank you guys for your help. I figured it out myself. It was because I send and receive data with type of text, not hex. I changed to hex and get all I want. There is no such setting for serial port, just convert text to hex and then send out, will receive hex data and convert to text.

Thank you guys again.