C#中SerialPort串口控件使用之字符的接收
来源:互联网 发布:unity3d安装包下载 编辑:程序博客网 时间:2024/05/16 05:39
好久没写东西了,工作时没什么事干,也就看看书;以前就对串口通信感点兴趣,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。如下图
到这来完成!
1 0
- C#中SerialPort串口控件使用之字符的接收
- C# serialPort 串口接收中this.Invoke的使用
- 使用.net的SerialPort串口监控控件接收串口数据
- C# 使用serialport 控件读写串口的大数据量解决方案 -- 以及与串口操作中常见的错误
- C#自带的serialPort串口控件
- C# 使用serialport串口发送和接收主要代码
- C#中串口类serialPort的用法!
- C#中串口类serialPort的用法!
- c# SerialPort控件串口通信
- C# SerialPort控件串口通信
- c# SerialPort控件串口通信
- c# SerialPort控件串口通信
- serialPort控件串口自动接收数据代码
- 在Delphi中使用串口控件MSComm的0字符接收例程祥解
- 在C#中使用SerialPort类实现串口通信
- C#中使用SerialPort类实现简单串口编程
- 在C#中使用SerialPort类实现串口通信
- 在C#中使用SerialPort类实现串口通信
- Java策略模式(Strategy模式)
- VC++6.0下通过opencv读入图像并反色
- 【学习ios之路:Objective-C】block块语法.NSDate和NSDateFormatter
- 写给我们这些浮躁的程序员
- CocoaPod关于Podfile文件编辑时,第三方库版本号的各种写法
- C#中SerialPort串口控件使用之字符的接收
- Android FM耳机长按事件
- 基于鲁棒性的数字水印的嵌入与提取
- What macro are predefined by gcc for different SPARC processors?
- 1205 Lock wait timeout exceeded try restarting transaction .
- wegewg
- ant build.xml模板
- ROS在ARM上的编译
- 使用spring+quartz配置多个定时任务