python c#上位机_C#上位机之—WinForm实现串口通信示例

上位机开发常用到串口通信来控制设备,串口通信的主要参数:COM口,波特率(9600),停止位(One),数据位(8),校验位(None),括号中的是常用值,具体意思我也不太懂,会用能实现功能就行哈哈;

开发工具:VS2012;   开发前需要添加以下服务引用:

.......using System.IO.Ports;

窗体搭建,因为没有串口设备供调试 ,所以我用虚拟串口即两个串口互相连接来实现通信,窗体分为上下两部分,对应两个串口区,上图为虚拟串口设置,下图为Winform样式:

2130570c2d86e938f674d9887066b01f.png                  

294071b240f356ce555cdfd16421f327.png

首先创建一个baseCom类:

1.声明变量,构造函数:

eda2b81235fd8f7cae79d52d3e160a23635.jpg

dde1a60abb6e48d30dbc3bee2829a475678.jpg

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 =parity;this.type =type;

}

View Code

2.打开串口和关闭串口函数:

19035964ec2d06ed05a1c005a08f404600f.jpg

ef9666cc3301cb8ef3bed1cdef44618d0b9.jpg

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);

showMsg(ex.Message);

showOnoff(false);

}

}public voidClosePort()

{if(comPort.IsOpen)

{

comPort.Close();

comPort.Dispose();

showOnoff(false);

showMsg(portName+ "Close Success");

}

}

View Code

3.接受数据和发送数据函数:

e6b7d9ba776aec21611c653b87ff5379fdf.jpg

a50ef0a598b7de684c15973f3328c95ade2.jpg

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.显示信息,显示状态函数:

8d1b8eabe69a388a3d207d8b7ebcf1db780.jpg

834a692a3ff4c5e3a687a624d5fb67143fb.jpg

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的添加,初始值,初始状态:

f18b04cc278a2c5948be00499d5328cc0b9.jpg

e1909841af52aef63cd940260940d026aa6.jpg

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):

be31fe153507616170324f18bbf1817f7de.jpg

7293c9d64d9836baad1ba5918d8de1ec56b.jpg

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)

comUp.comPort_SendData(textBox_ComSend.Text);

}

5.编写数据接受发送显示到文本框及状态指示灯变化函数:

cf8847718e07ce28dfc0893df302dc0b656.jpg

02f1d140c4b658130c1b5a1da34cda145ed.jpg

public void SignalState(comType type,boolonoff)

{if (this.InvokeRequired)

{

delegateOnOff d= newdelegateOnOff(SignalState);this.Invoke(d,new object[]{type,onoff});

}else{if (type ==comType._up)

{

pictureBox_ComSignal.Image= onoff ?imgOn : imgOff;

button_OpenCom.Text= onoff ? "Close COM" : "Open COM";

}else{

pictureBox_Com2.Image= onoff ?imgOn : imgOff;

button_OpenCom2.Text= onoff ? "Close COM" : "Open COM";

}

}

}public void ShowMsg(comType type, stringmsg)

{if (this.InvokeRequired)

{

delegateShow d= newdelegateShow(ShowMsg);this.Invoke(d, new object[] { type, msg });

}else{string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "\r\n";if (type ==comType._up)

{

textBox_serialPort.Text+= (date + msg + "\r\n");

}else{

textBox_serialPort2.Text+= (date + msg + "\r\n");

}

}

}

View Code

6.Monitor函数,即线程函数,用来实现数据自动发送(没有进行准确定时,大概设了个间隔):

eb016ccf25bffdec0e3073b49fc3ddc8bf2.jpg

f27e4a9bb46197f45c1e9d2ab0bbecf5b68.jpg

public voidMonitor()

{double i =0;while (i++<10000000000)

{if (i == 1000000000)

{

i= 0;if(checkBox_AutoSend.Checked)

{if (comUp != null)

comUp.comPort_SendData(textBox_ComSend.Text);

}if(checkBox_AutoSend2.Checked)

{if (comDown != null)

comDown.comPort_SendData(textBox_comSend2.Text);

}

}

}

}

View Code

至此,串口通信功能已基本实现,可在此框架上进行实际应用开发,编码新手,欢迎大家批评指正!看下效果图(COM1和COM11虚拟连接):

6df906c2fdc4d7e8954d873b3dfb205f.png

相关资源:C#上位机源代码
已标记关键词 清除标记
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
<p> <b><span style="background-color:#FFE500;">【超实用课程内容】</span></b> </p> <p> <br /> </p> <p> <br /> </p> <p> 本课程内容包含讲解<span>解读Nginx的基础知识,</span><span>解读Nginx的核心知识、带领学员进行</span>高并发环境下的Nginx性能优化实战,让学生能够快速将所学融合到企业应用中。 </p> <p> <br /> </p> <p style="font-family:Helvetica;color:#3A4151;font-size:14px;background-color:#FFFFFF;"> <b><br /> </b> </p> <p style="font-family:Helvetica;color:#3A4151;font-size:14px;background-color:#FFFFFF;"> <b><span style="background-color:#FFE500;">【课程如何观看?】</span></b> </p> <p style="font-family:Helvetica;color:#3A4151;font-size:14px;background-color:#FFFFFF;"> PC端:<a href="https://edu.csdn.net/course/detail/26277"><span id="__kindeditor_bookmark_start_21__"></span></a><a href="https://edu.csdn.net/course/detail/27216">https://edu.csdn.net/course/detail/27216</a> </p> <p style="font-family:Helvetica;color:#3A4151;font-size:14px;background-color:#FFFFFF;"> 移动端:CSDN 学院APP(注意不是CSDN APP哦) </p> <p style="font-family:Helvetica;color:#3A4151;font-size:14px;background-color:#FFFFFF;"> 本课程为录播课,课程永久有效观看时长,大家可以抓紧时间学习后一起讨论哦~ </p> <p style="font-family:"color:#3A4151;font-size:14px;background-color:#FFFFFF;"> <br /> </p> <p class="ql-long-24357476" style="font-family:"color:#3A4151;font-size:14px;background-color:#FFFFFF;"> <strong><span style="background-color:#FFE500;">【学员专享增值服务】</span></strong> </p> <p class="ql-long-24357476" style="font-family:"color:#3A4151;font-size:14px;background-color:#FFFFFF;"> <b>源码开放</b> </p> <p class="ql-long-24357476" style="font-family:"color:#3A4151;font-size:14px;background-color:#FFFFFF;"> 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 </p> <p class="ql-long-24357476" style="font-family:"color:#3A4151;font-size:14px;background-color:#FFFFFF;"> 下载方式:电脑登录<a href="https://edu.csdn.net/course/detail/26277"></a><a href="https://edu.csdn.net/course/detail/27216">https://edu.csdn.net/course/detail/27216</a>,播放页面右侧点击课件进行资料打包下载 </p> <p> <br /> </p> <p> <br /> </p> <p> <br /> </p>
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页