C#的SerialPort串口程序设计总结

简介:微软的VS提供了SerialPort控件,也就是串行端口资源。

当然也可以添加引用 using System.IO.Ports;

通过实例化SerialPort对象就可以使用其属性和方法了。

SerialPort serialPort1 = new SerialPort();

最重要的几个属性:

serialPort1.Open();打开串行端口连接

serialPort1.Close();关闭串行端口连接

serialPort1.PortName 获取或设置通信端口(COM)

serialPort1.BaudRate 获取或设置串行波特率

serialPort1.DataBits 获取或设置每个字节的标准数据位长度

serialPort1.StopBits 获取或设置每个字节的标准停止位数

serialPort1.Parity 获取或设置奇偶校验检查协议

serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); 数据接收事件的方法

简单的界面示例代码如下:

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;
using System.IO;
using System.Timers;

namespace WinFromApp
{
public partial class Form1 : Form
{
private StreamReader sRead;
public int iTextbox2 = 0;
SerialPort serialPort1 = new SerialPort();
public Form1()
{
InitializeComponent();
}
private DateTime _dt = DateTime.Now; //定义一个成员函数用于保存每次的时间点
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
DateTime tempDt = DateTime.Now; //保存按键按下时刻的时间点
TimeSpan ts = tempDt .Subtract(_dt); //获取时间间隔
if (ts.Milliseconds > 50) //判断时间间隔,如果时间间隔大于50毫秒,则将TextBox清空
textBox2.Text = "";
_dt = tempDt ;
}

private void timer1_Tick(object sender, EventArgs e)
{
string str1;
str1 = sRead.ReadLine();
if (str1 == null)
{
timer1.Stop();
sRead.Close();
MessageBox.Show("发送完毕","NICE");
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
textBox1.Enabled = true;
textBox3.Enabled = true;
textBox4.Enabled = true;
return;
}
byte[] data = Encoding.Default.GetBytes(str1);
serialPort1.Write(data, 0, data.Length);
}

private void Form1_Load(object sender, EventArgs e)
{
timer2.Start();
string[] str = SerialPort.GetPortNames();
if(str==null)
{
MessageBox.Show("本机没有串口!","Error");
return;
}
comboBox1.Items.AddRange(str);
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 1;
comboBox4.SelectedIndex = 2;
comboBox5.SelectedIndex = 2;
this.toolStripStatusLabel1.Text = "端口号:端口未打开";
this.toolStripStatusLabel2.Text = "波特率:端口未打开";
this.toolStripStatusLabel3.Text = "数据位:端口未打开";
this.toolStripStatusLabel4.Text = "停止位:端口未打开";
int count = comboBox1.Items.Count;
//去除下拉框可选数据的重复项
int i;
for (i = 0; i < count; i++)
{
string strs = comboBox1.Items[i].ToString();
for (int j = i + 1; j < count; j++)
{
string str1 = comboBox1.Items[j].ToString();
if (str1 == strs)
{
comboBox1.Items.RemoveAt(j); count--; j--;
}
}
}
}

//打开串口
private void button1_Click(object sender, EventArgs e)
{
String str1 = comboBox1.Text;
String str2 = comboBox2.Text;
String str3 = comboBox4.Text;
String str4 = comboBox5.Text;
Int32 int2 = Convert.ToInt32(str2);
Int32 int3 = Convert.ToInt32(str3);
try
{
if (str1 == null)
{
MessageBox.Show("请先选择串口!", "Error");
return;
}
serialPort1.PortName = str1;
serialPort1.BaudRate = int2;
serialPort1.DataBits = int3;
switch (comboBox5.Text)
{
case "1":
serialPort1.StopBits = StopBits.One;
break;
case "1.5":
serialPort1.StopBits = StopBits.OnePointFive;
break;
case "2":
serialPort1.StopBits = StopBits.Two;
break;
default:
MessageBox.Show("Error:参数不正确", "Error");
break;
}
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
}
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Open();
MessageBox.Show("串口打开成功!",str1);
this.toolStripStatusLabel1.Text = "端口号:" + serialPort1.PortName + "";
this.toolStripStatusLabel2.Text="波特率:"+serialPort1.BaudRate+"";
this.toolStripStatusLabel3.Text = "数据位:" + serialPort1.DataBits + "";
this.toolStripStatusLabel4.Text = "停止位:" + serialPort1.StopBits + "";
button1.Enabled = false;
comboBox1.Enabled = false;
comboBox2.Enabled = false;
comboBox4.Enabled = false;
comboBox5.Enabled = false;
}
catch(Exception er)
{
MessageBox.Show("Error:"+er.Message,"Error");
return;
}
}

//关闭串口
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;
serialPort1.Close();
this.toolStripStatusLabel1.Text = "端口号:" + serialPort1.PortName + "";
this.toolStripStatusLabel2.Text = "波特率:" + serialPort1.BaudRate + "";
this.toolStripStatusLabel3.Text = "数据位:" + serialPort1.DataBits + "";
this.toolStripStatusLabel4.Text = "停止位:" + serialPort1.StopBits + "";
}

private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
Application.Exit();
}

//发送
private void button4_Click(object sender, EventArgs e)
{
if (button1.Enabled == true)
{
MessageBox.Show("请先打开串口","Error");
return;
}
String str1;
str1 = textBox1.Text;
byte[] data = Encoding.Default.GetBytes(str1);
if (checkBox1.Checked == true)
{
for (int i = 0; i < data.Length; i++)
{
byte temp = data[i];
string tempHex = temp.ToString("X2") + "";
serialPort1.Write(tempHex);
}
}
else
{
serialPort1.Write(data,0,data.Length);
}
}
//使用Control.Invoke
public delegate void DeleUpdateTextbox(string dateRe);
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string dataRe;
byte[] byteRead = new byte[serialPort1.BytesToRead];
DeleUpdateTextbox deleupdatetextbox = new DeleUpdateTextbox(UpdateTextbox);
serialPort1.Read(byteRead, 0, byteRead.Length);
if (checkBox2.Checked == false)
{
dataRe = Encoding.Default.GetString(byteRead);
textBox2.Invoke(deleupdatetextbox, dataRe);
}
else
{
for (int i = 0; i < byteRead.Length; i++)
{
byte temp = byteRead[i];
dataRe = temp.ToString("X2") + "";
textBox2.Invoke(deleupdatetextbox, dataRe);
}
}
}
private void UpdateTextbox(string dataRe)
{
if (iTextbox2 == 0)
{
this.textBox2.Text = dataRe;
iTextbox2++;
}
else
{
textBox2.AppendText(dataRe);
}
}
//发送文件
private void button6_Click(object sender, EventArgs e)
{
string str3 = textBox3.Text;
if (button1.Enabled == true)
{
MessageBox.Show("请先打开串口", "Error");
return;
}
if (str3 == "")
{
MessageBox.Show("请选择要发送的文件!", "Error");
return;
}
string str1;
str1 = textBox4.Text;
timer1.Interval = Convert.ToInt32(str1);
timer1.Start();
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
textBox1.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
}
//选择文件
private void button8_Click(object sender, EventArgs e)
{
String filename;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
filename = openFileDialog1.FileName;
if(filename=="")
{
MessageBox.Show("请选择要发送的文件!","Error");
return;
}
textBox3.Text = filename;
if (filename != null)
{
sRead = new StreamReader(filename);
}
button5.Enabled = true;
}
//停止发送
private void button7_Click(object sender, EventArgs e)
{
timer1.Stop();
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
textBox1.Enabled = true;
textBox3.Enabled = true;
textBox4.Enabled = true;
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{

if (e.KeyValue == 13)
{
if (button1.Enabled == true)
{
MessageBox.Show("请先打开串口!", "Error");
return;
}
String str1;
str1 = textBox1.Text;
byte[] data = Encoding.Default.GetBytes(str1);
serialPort1.Write(data, 0, data.Length);
textBox1.Clear();
}
return;
}
//发送文件清屏
private void button5_Click(object sender, EventArgs e)
{
textBox2.Clear();
iTextbox2 = 0;
}
//发送字符清屏
private void button3_Click(object sender, EventArgs e)
{
textBox1.Clear();
iTextbox2 = 0;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text.Length > 0)
{
MessageBox.Show("条码长度:"+textBox2.Text.Length+"\n条码内容:"+textBox2.Text,"系统提示");
}
}

private void timer2_Tick(object sender, EventArgs e)
{
string Week = DateTime.Now.DayOfWeek.ToString();
switch (Week)
{
case "Sunday":
Week = "星期天";
break;
case "Monday":
Week = "星期一";
break;
case "Tuesday":
Week = "星期二";
break;
case "Wednesday":
Week = "星期三";
break;
case "Thursday":
Week = "星期四";
break;
case "Friday":
Week = "星期五";
break;
case "Saturday":
Week = "星期六";
break;
}
label6.Text=DateTime.Now.ToString()+" "+Week;
}
}
}

 

时间: 2024-10-17 23:41:33

C#的SerialPort串口程序设计总结的相关文章

(c#2.0)serialPort串口通讯

原文:(c#2.0)serialPort串口通讯 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Configuration; usi

SerialPort串口多个窗体访问

串口在每个窗体打开关闭容易出现访问被拒绝情况,这个时候只能重启电脑重置解决. 所以比较好的方式是使用母窗体打开串口,然后子窗体调用,不会出现上诉问题. 调用方法: 1.母窗体 //打开SerialPort即可 private void button2_Click(object sender, EventArgs e) { serialPort1.BaudRate = 9600; serialPort1.Parity = System.IO.Ports.Parity.None; serialPor

基于FPGA具有容错能理的异步串口程序设计

首先,问题源于一个项目.本来是一个很简单的多个串口收发FIFO存取数据的小程序,通过电脑验证也可用,而下位机板子之间通信就出现了丢数问题. 经过分析原因如下: 我的串口收模块是基于特权同学的开发板程序修改而来的,也就是信号线一旦拉低,就认为数据开始传输,便闷头数数,那么数满10个bit(1起始位+8位数据+1停止位),就算接完一个字节,回头接着检测信号线是否被拉低.当发数端发出了错码的情况下,这套程序是不能检测出来的.要想能识别错码,就必须起始位与停止位都检测,才能确定该字节是否完整. 经过一个

vc 使用了SerialPort类的串口通信软件分析

实现串口通信,使用的类文件是SerialPort.cpp.在项目中使用mscomm控件的时候,串口连续传递若干数据后,会出现卡死的情况,关闭串口再打开,继续读取的话可以正常通信. 为了解决这个问题,想到就用SerialPort串口类来实现会好吧.当然,完全用windows的api函数来实现也可以,太麻烦吧,我也没用过.用微软的一些控件编程虽然容易了,但是也不熟悉底层. 软件主界面为: 点了自动发送单选框后: 点开始发送按钮: 一个界面就知道很好实现. 借这个例子,重点来梳理一下串口类的使用. 1

C# Serial串口打印

项目中需要使用串口热敏打印机,所以研究一下串口打印. using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Collections; using System.Windows.Forms; using System.Drawing; namespace PrinterTest { public class P

出售 unity3d串口插件

出售unity3d串口插件 利用C++编写,解决了mono库 serialport的bug. serialport串口的bug地方在于: 1.有一些数据无法收到. 2.会丢失第一个字节. 3.延迟 我写的库,可以接受所有消息,实时接受,支持高波特率,测试稳定的有38400,单片机30ms发送过来一次数据. 我的QQ:1357098586,欢迎联系.

使用Java实现简单串口通信

最近一门课要求编写一个上位机串口通信工具,我基于Java编写了一个带有图形界面的简单串口通信工具,下面详述一下过程,供大家参考 ^_^ 一: 首先,你需要下载一个额外的支持Java串口通信操作的jar包,由于java.comm比较老了,而且不支持64位系统,这里推荐Rxtx这个jar包(32位/64位均支持). 官方下载地址:http://fizzed.com/oss/rxtx-for-java (注:可能需要FQ才能下载) 不能FQ的童鞋,可以在这里下载: http://files.cnblo

串口API及数据流的传输

参考网站:http://blog.csdn.net/update_java/article/details/46898937 直接上参考代码,比较直接,需要用到阻塞队列,否则会出现流读取不完整的情况,看简介的如上网站: @RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = AmsApplication.class)@WebAppConfiguration@Transactional@Com

Java实现RS485串口通信,发送和接收数据进行解析

最近项目有一个空气检测仪,需要得到空气检测仪的实时数据,保存到数据库当中.根据了解得到,硬件是通过rs485进行串口通讯的,需要发送16进制命令给仪器,然后通过轮询来得到数据. 需要先要下载RXTX的jar包,win64位下载地址:http://pan.baidu.com/s/1o6zLmTc):将解压后的rxtxParallel.dll和rxtxSerial.dll两个文件放在%JAVA_HOME%/jre/bin目录下,这样该包才能被正常的加载和调用. 代码如下: package com.g