有没有简单的几行代码,功能就是读取端口
追答因为是串口,所以必须要设置串口通讯协议。这些代码基本上少不了。
以下这些就是绑定串口通讯的。任何与串口通讯的程序都需要配置以下参数。
CurrentPort.PortName = comName; //端口号基本上我以上代码是最少了,不设置通讯参数是无法与串口通讯的
追问通讯参数这些代码应该放在哪里?
追答 System.IO.Ports.SerialPort CurrentPort=null;
//创建并打开通讯端口 ,以下参数的赋值需要自己写。
public static int OpenPort()
{
CurrentPort = new SerialPort();
CurrentPort.ReadBufferSize = 128;
CurrentPort.PortName = "COM1"; //端口号
CurrentPort.BaudRate = 1600; //比特率
CurrentPort.Parity =parity;//奇偶校验
CurrentPort.StopBits = stop;//停止位
CurrentPort.DataBits = databit;//数据位
CurrentPort.DataReceived += Sp_DataReceived;
}
//接收数据事件处理
private static void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = sender as SerialPort;
//readBuffer 就是接收到的数据。
byte[] readBuffer = new byte[sp.ReadBufferSize];//扩大接收数据量
sp.Read(readBuffer, 0, readBuffer.Length);
}
再不明白我也没办法了
不是啊 我的意思是 这段代码复制过去 应该放在什么地方 放在 private void Form1_Load(object sender, EventArgs e)里面 还是外面
追答晕死了,我已经给你封装成了两个方法,
OpenPort 是用来启动串口通讯的
而Sp_DataReceived 是一个被动执行方法,当串口通讯启动后 有数据过来他会自动执行,因此你只需要调用OpenPort 方法即可,至于你想在什么地方执行,看你的代码逻辑,在formLoad中初始化的时候就执行也可以,在button中点击按钮后执行也可以。