|
-
February 12th, 2009, 11:21 AM
#1
[RESOLVED] SerialPort problem
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:
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);
}
}
The difficulty is that you have no idea how difficult it is.
.Net 3.5/VS 2008
-
February 12th, 2009, 12:03 PM
#2
Re: SerialPort problem
if you breakpoint, what is the value of "BytesToRead"?
-
February 13th, 2009, 06:15 AM
#3
Re: SerialPort problem
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
-
February 13th, 2009, 09:16 AM
#4
Re: SerialPort problem
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.
The difficulty is that you have no idea how difficult it is.
.Net 3.5/VS 2008
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|