pythonc#上位机_C#上位机之—WinForm实现串⼝通信⽰例上位机开发常⽤到串⼝通信来控制设备,串⼝通信的主要参数:COM⼝,波特率(9600),停⽌位(One),数据位(8),校验位(None),括号中的是常⽤值,具体意思我也不太懂,会⽤能实现功能就⾏哈哈;
开发⼯具:VS2012;  开发前需要添加以下服务引⽤:
.......using System.IO.Ports;
窗体搭建,因为没有串⼝设备供调试 ,所以我⽤虚拟串⼝即两个串⼝互相连接来实现通信,窗体分为上下两部分,对应两个串⼝区,上图为虚拟串⼝设置,下图为Winform样式:
⾸先创建⼀个baseCom类:
1.声明变量,构造函数:
public delegate void delegateOnShowMsg(comType type,stringmsg);public delegate void delegateOnOpenCom(comType type, boolonOff);public eventdelegateOnShowMsg OnShow;public eventdelegateOnOpenCom OnOpen;
comType type;string baudRate = string.Empty;string parity = string.Empty;string stopBits = string.Empty;string dataBits = string.Empty;string portName = string.Empty;public System.IO.Ports.SerialPort comPort =
newSystem.IO.Ports.SerialPort();public baseCom(string portName, string baudRate, string stopBits, string dataBits, stringparity,comType type)
{this.portName =portName;this.baudRate =baudRate;this.stopBits =stopBits;this.dataBits =dataBits;this.parity
=pe =type;
}
View Code
2.打开串⼝和关闭串⼝函数:
public voidOpenPort()
{try{if(comPort.IsOpen)
comPort.Close();
comPort.BaudRate= int.Parse(baudRate);
comPort.StopBits= (StopBits)Enum.Parse(typeof(StopBits), stopBits);
comPort.DataBits= int.Parse(dataBits);
comPort.Parity= (Parity)Enum.Parse(typeof(Parity), parity);
comPort.PortName=portName;
comPort.Handshake=Handshake.None;
comPort.Open();if(comPort.IsOpen)
{
showOnoff(true);
comPort.Handshake=Handshake.None;
comPort.DataReceived+=comPort_DataReceived;
}
showMsg(portName+ "Open Success");
}catch(Exception ex)
{
showMsg("Unable to Open" +portName);
python怎么读取串口数据
showMsg(ex.Message);
showOnoff(false);
}
}public voidClosePort()
{if(comPort.IsOpen)
{
comPort.Close();
comPort.Dispose();
showOnoff(false);
showMsg(portName+ "Close Success");
}
}
View Code
3.接受数据和发送数据函数:
public void comPort_DataReceived(objectsender,SerialDataReceivedEventArgs e)
{try{int n =comPort.BytesToRead;if (n == 0)return;byte[] buffer = new byte[n];
comPort.Read(buffer,0, n);string rcv = Encoding.Default.GetString(buffer, 0, buffer.Length); showMsg("RECV:" +rcv);
}catch(Exception ex)
{
ClosePort();
showMsg("Com Closed:" +ex.Message);
}
}public void comPort_SendData(stringmsg)
{if (msg == "")
{
showMsg("CAN Not EMPTY");return;
}if (comPort == null)
{
showMsg("First Open Port");return;
}if (!comPort.IsOpen)
{
showMsg("COM Not Open");return;
}byte[] data =Encoding.Default.GetBytes(msg);
comPort.Write(data,0, data.Length);
showMsg("SEND:" +msg);
}
View Code
4.显⽰信息,显⽰状态函数:
public void showMsg(stringmsg)
{if (OnShow != null)
OnShow(type, msg);
}public void showOnoff(boolflag)
{if (OnOpen != null)
OnOpen(type, flag);
}public enumcomType
{
_up,
_down
}
View Code
OK,baseCOM类已定义完成,现在编写窗体各控件的功能函数:
1.初始化控件,主要是下拉菜单的Item的添加,初始值,初始状态:
public string[] baudRates = { "2400", "4800", "9600", "19200", "39400", "43000", "56000"};public string[] paritys = { "None", "ODD", "Even"};public string[] dataBits = { "5", "6", "7", "8"};public string[] stopBits = { "None", "One", "Two", "OnePointFive"} ;public voidInitControls()
{
comboBox_com.Items.Clear();
comboBox_baudRate.Items.Clear();
comboBox_dataBits.Items.Clear();
comboBox_parity.Items.Clear();
comboBox_StopBit.Items.Clear();
comboBox_com2.Items.Clear();foreach (var v inbaudRates)
comboBox_baudRate.Items.Add(v);foreach (var v instopBits)
comboBox_StopBit.Items.Add(v);foreach (var v inparitys)
comboBox_parity.Items.Add(v);foreach (var v indataBits)
comboBox_dataBits.Items.Add(v);foreach (var v inSystem.IO.Ports.SerialPort.GetPortNames())
{
comboBox_com.Items.Add(v);
comboBox_com2.Items.Add(v);
}
comboBox_com.SelectedIndex= 0;
comboBox_baudRate.SelectedIndex= 2;
comboBox_dataBits.SelectedIndex= 3;
comboBox_parity.SelectedIndex= 0;
comboBox_StopBit.SelectedIndex= 1;
comboBox_com2.SelectedIndex= 0;
}
View Code
2.声明两个COM类,comUp和comDown:
public delegate void delegateOnOff(comType type,bool onoff);//定义两个委托
public delegate void delegateShow(comType type,string msg);//为了防⽌报错“从不是创建控件的线程控制它”
baseCom comUp; //定义上串⼝COM
baseCom comDown; //定义下串⼝COM
Image imgOn, imgOff; //指⽰灯
Thread th; //线程⽤来实现⾃动发送
3.编写打开(关闭)串⼝按钮点击事件(打开comUp和打开comDown代码⼀样,只贴出comUp):
private void button_OpenCom_Click(objectsender, EventArgs e)
{string cmd = ((Button)sender).Text.Split(' ')[0];if (comUp != null)
comUp.ClosePort();if (cmd == "Close")return;string s1 =comboBox_com.SelectedItem.ToString();string s2
=comboBox_baudRate.SelectedItem.ToString();string s3 =comboBox_StopBit.SelectedItem.ToString();string s4 =comboBox_dataBits.SelectedItem.ToString();string s5 =comboBox_parity.SelectedItem.ToString();
comUp= newbaseCom(s1, s2, s3, s4, s5,comType._up);
comUp.OnOpen+=SignalState;
comUp.OnShow+=ShowMsg;
comUp.OpenPort();
}
View Code
4.编写发送数据按钮点击事件:
private void button_Send_Click(objectsender, EventArgs e)
{if (comUp != null)
comUpPort_SendData(textBox_ComSend.Text);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。