c#读串口数据问题(rs232)

神色自若 2012-10-20 02:33:25
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
{
if (this.lastRcvByte == 0)
{
this.lastRcvByte = rcvByte;
}
else
{
str += Microsoft.VisualBasic.Strings.Chr(lastRcvByte * 256 + rcvByte).ToString();
this.lastRcvByte = 0;
}
}
}
else
{
if (rcvByte < 16)
{
str += " 0" + Microsoft.VisualBasic.Conversion.Hex(rcvByte).ToString();
}
else
{
str += " " + Microsoft.VisualBasic.Conversion.Hex(rcvByte).ToString();
}
}
}

UInt64 rcvBytes;
if (this.lbRcvBytes.Text != "R:")
rcvBytes = Convert.ToUInt64(rcvByteLen) + Convert.ToUInt64(this.lbRcvBytes.Text.Substring(2, this.lbRcvBytes.Text.Length - 2));
else
rcvBytes = Convert.ToUInt64(rcvByteLen);

str = rcvBytes.ToString() + "@" + str;

SetText(str);
}
catch (Exception ex)
{
int itemp = sp.BytesToRead;
byte byteTemp = 0;
for (int i = 0; i < itemp; i++)
byteTemp = Convert.ToByte(sp.ReadByte());
}



}
...全文
339 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
缭绕飘渺 2012-10-20
  • 打赏
  • 举报
回复
我只能说一句
楼主的代码写的真的很乱
串口事件中你很多语句都是非必要的
仔细看看SerialPort类的读取方式吧
同时要测试DTR和RTS属性是否有必要设置为True

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧