此方法主要是用于仪器数据接收
运行界面如下
硬件条件
串口3与串口4之间使用导线连接(正确交叉连接)
运行结果如下
可以看到通过调用数据发送与数据接收正常
代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class ClassPortTest
{
System.IO.Ports.SerialPort sp = new System.IO.Ports.SerialPort();
//构造函数
public ClassPortTest(System.IO.Ports.SerialPort s)
{
sp = s;
sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(sp_DataReceived);
sp.ReceivedBytesThreshold = 5; //事件触发设置为5字节
}
~ClassPortTest() // finalizer //析构函数
{
// cleanup statements...
}
//发送数据演示
public bool sendTest()
{
try
{
//if (!sp.IsOpen)
//{
// return false;
//}
if (!sp.IsOpen)
{
//return false;
sp.Open();
}
Byte[] tmp = new Byte[10];
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = (Byte)(i * 2);
}
sp.Write(tmp, 0, 5);
return true;
}
catch
{
return false;
}
}
Int32 index = 0;
//接收数据演示
private void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
index += 1;
string stmp;
stmp = String.Empty;
//Console.WriteLine(DateTime.Now.ToString() + " -> " + index.ToString() + " -> " + sp.ReadByte().ToString("x2"));
do
{
if (sp.BytesToRead > 0)
//Console.Write(" " + sp.ReadByte().ToString("x2"));
stmp += " " + sp.ReadByte().ToString("x2");
else
break;
} while (true);
Console.WriteLine(DateTime.Now.ToString() + " -> " + index.ToString() + " -> " + stmp);
}
}
}
主界面程序如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.Ports.SerialPort sp ;
sp = new System.IO.Ports.SerialPort();
sp.PortName = "COM3";
//sp.Open();
ClassPortTest ctest = new ClassPortTest(sp);
bool tmp;
tmp = ctest.sendTest();
richTextBox1.AppendText(DateTime.Now.ToString() + " -> " + tmp.ToString() + "\r\n");
if (sp.IsOpen)
{
richTextBox1.AppendText("串口打开\r\n");
}
sp.Close();
}
System.IO.Ports.SerialPort sp ;
private void button2_Click(object sender, EventArgs e)
{
sp = new System.IO.Ports.SerialPort();
sp.PortName = "COM4";
sp.BaudRate = 9600;
sp.Open();
ClassPortTest ctest = new ClassPortTest(sp);
}
}
}
特此记录
anlog
2022年8月15日