您好我正在使用C#从com端口获取数据。使用Hercules检查数据,请参阅此图像以比较config:
在Hescules数据显示格式:FF ?? ZZ,但在C#中,日期只获得:FF
这是C#代码:
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
//ShowNetworkInterfaces();
getDataFromComPort();
}
private void getDataFromComPort()
{
try
{
_serialPort = new SerialPort("COM3");
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
//_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.NewLine = "\n";
//serialPort1.ReceivedBytesThreshold = 9;
//serialPort1.RtsEnable = true;
//serialPort1.DtrEnable = true;
//_serialPort.ReadTimeout = 500;
//_serialPort.WriteTimeout = 500;
if (_serialPort.IsOpen)
{
_serialPort.Close();
}
_serialPort.Open();
}
catch (Exception e)
{
Console.WriteLine("error : " + e.Message);
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (tbText.InvokeRequired)
{
tbText.Invoke(new SerialDataReceivedEventHandler(sp_DataReceived), sender, e);
}
else
{
try
{
string data = _serialPort.ReadLine();
Console.WriteLine("data: " + data);
tbText.Text = data;
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
}
}
似乎数据不是按行读取的。