c#读串口数据问题(rs232)
C#通過com口讀測量仪器数据,测量时用超级终端能读到数据(C#com口参数设置与超级终端都是一样的)
1、用超級終端可以正常讀取數據,附圖
2、用C#調試時只有開關設備才能讀到數據,测量仪测试时收不到数据,是怎么回事?
问题:C#com口参数设置与超级终端都是一样的,C#为什么只有在开关设备时读到数据,测试仪测试时读不到数据是怎么回事?
详见代码
private void Form1_Load(object sender, EventArgs e)
{
this.cmbBPS.Text = "9600";
this.cmbCheck.Text = this.cmbCheck.Items[0].ToString();
this.cmbDataLen.Text = "8";
this.cmbStopBit.Text = "1";
this.cmbSerialPortNo.Text ="COM1";
try
{
if (this.serialPort1.IsOpen == false)
{
this.serialPort1.Open();
this.btnOpenSerialPort.ImageIndex = 0;
this.btnOpenSerialPort.Text = "关闭串口";
}
}
catch
{
MessageBox.Show(this, "打开串口失败!串口不存在或其它设置占用", "打开串口失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 使用异步回调机制来显示数据到主界面
/// </summary>
/// <param name="text"></param>
private void SetText(string text)
{
string str = "";
if (this.txtReceive.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
int i = text.IndexOf("@");
str = text.Substring(0, i);
this.lbRcvBytes.Text = "R:" + str;
//接收到的数据
this.txtReceive.Text += text.Substring(i + 1, text.Length - i - 1); ;
this.txtReceive.SelectionStart = this.txtReceive.Text.Length;
this.txtReceive.ScrollToCaret();
//接收的数据长度
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] receviedBuf;
SerialPort sp = (SerialPort)sender;
string str = "";
int rcvByteLen=0;
try
{
receviedBuf = new byte[sp.BytesToRead];
int itemp = sp.BytesToRead;
for (int i = 0; i < itemp; i++)
{
receviedBuf[i] = Convert.ToByte(sp.ReadByte());
rcvByteLen++;
}
foreach (byte rcvByte in receviedBuf)
{
if (this.chRcvHex.Checked == false)
{
if (rcvByte < 128)
{
str += Microsoft.VisualBasic.Strings.Chr(rcvByte).ToString();
this.lastRcvByte = 0;
}
else