打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#中SerialPort串口控件使用之字符的接收

好久没写东西了,工作时没什么事干,也就看看书;以前就对串口通信感点兴趣,serialport控件也看了几天,想做一个类似串口助手的东西,由于是刚看的C#,很多东西都不知道,网上的SerialPort控件要不讲得不清楚,要不代码错误;所以把自己看到的学到的供大家分享!

注:我这里写的是SerialPort串口控件使用之字符的接收,的工具为VS2010,串口调试助手,VSPD(虚拟串口)6.9,。很多东西我也不知道为什么要这样做,大家相互学习和探讨!

好了,下面开始吧!

第一步:新建C#窗体项目,拖一个textbox控件,一个SerialPort控件,两个按钮,命名如下:

     控件名                           Name

1  编辑框                     textBox1

2  SerialPort              mySerialPort

3   按钮                        button1 button2

如下图:



第二步:添加事件:

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;using System.IO.Ports;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string s = ''; int count = mySerialPort.BytesToRead; byte[] data = new byte[count]; mySerialPort.Read(data, 0, count); foreach (byte item in data) { s += Convert.ToChar(item); } if (this.InvokeRequired) { this.Invoke(new MethodInvoker(delegate { this.textBox1.Text = s; })); } else { this.textBox1.Text = s; } } private void button1_Click(object sender, EventArgs e) { if (!mySerialPort.IsOpen) { mySerialPort.Open();//打开端口,进行监控 } mySerialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived); } private void button2_Click(object sender, EventArgs e) { if (mySerialPort.IsOpen) mySerialPort.Close(); } }}
注意在namespace处添加 using System.IO.Ports;

第三步:编译运行。

第四部通信。

打开VSPD,串口助手,写好的程序。

设置VSPD如图:


串口助手设置如图:选择COM2;


打开写好的程序,点击打开串口,这时看到VSPD两个串口均为打开状态,在串口助手发送字符编辑框处输入 ss,如上图。

接着可在程序窗口中得到发送过来的 ss。如下图


到这来完成!


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
WinForm串口收发
c#serialport类实现串口通信的源代码
手机通过蓝牙串口与arduino通信
使用SerialPort类设计串口通讯程序
最简单的【上位机软件】详解
C#的SerialPort使用,动态创建串口连接,短信猫通信
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服