我目前有一个使用VB6代码编写的程序,该代码使用MSCOMM控件从串行端口提取数据。这设法成功地从我的串口接收数据,其中连接了Denso BHT-904B设备。
我现在正试图将此代码移至C#,因此它适合我正在开发的新软件。为此,我使用的是SerialPort类。但问题是,当我打开端口时,接收到的数据事件仅在设备无法通信时触发(我猜测是由于超时)。然后在事件中收到的数据是'↑↑↑↑↑'。
我的SerialPort控件设置如下:
我在表单控件后面使用的代码是:
namespace BHTTestingDotNet
{
public partial class Form1 : Form
{
private string rxString;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
serialPort.DtrEnable = true;
serialPort.Encoding = Encoding.Default;
serialPort.DataReceived += serialPort_DataReceived;
serialPort.ErrorReceived += serialPort_ErrorReceived;
serialPort.Open();
}
private void serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
MessageBox.Show(e.ToString());
}
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
var test = serialPort.BytesToRead;
SerialPort sr = (SerialPort)sender;
rxString = sr.ReadExisting();
this.BeginInvoke(new EventHandler(displayText));
}
private void displayText(object o, EventArgs e)
{
txtBHT.AppendText(rxString);
}
}
}
我已尝试将RtsEnable
和DtrEnable
都设置为true
,但这没有任何区别。
更新 - 我现在已更改为设备上的协议设置,但我现在只接收管道,然后返回一个返回符号,例如: |||||¬
答案 0 :(得分:-2)
我经常使用SerialPort类,为了我的目的,我已经创建了自己的类
公共类SerialPortDataSource:SerialPort
其中SerialPort.DataReceived处理程序调用此方法:
private void SerialPortDataSource_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (BytesToRead > 0)
{
var buffor = new byte[BytesToRead];
Read(buffor, 0, buffor.Length);
_receivedBytes = buffor;
//wConsole.WriteLine(ArrayExtension.ToString(buffor));
var dataLogger = DataLogger;
if (dataLogger != null)
{
dataLogger.WriteLine("- DR - {0}", true, BitConverterExtension.ToHexString(buffor));
}
if (OnDataReceived != null)
{
OnDataReceived(this, buffor);
}
}
}
catch (InvalidOperationException)
{
// sometimes DataReceived event is invoked after port is closed which causes InvalidOperationException
}
}
在许多具有各种串口设置的应用程序中,此方法适用于我。