C#的SerialPort串口程序设计总结
简介:微软的VS提供了SerialPort控件,也就是串行端口资源。
serialPort1.BaudRate 获取或设置串行波特率
- 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 = ;
- 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毫秒,则将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, , 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 = ;
- comboBox2.SelectedIndex = ;
- comboBox4.SelectedIndex = ;
- comboBox5.SelectedIndex = ;
- this.toolStripStatusLabel1.Text = "端口号:端口未打开";
- this.toolStripStatusLabel2.Text = "波特率:端口未打开";
- this.toolStripStatusLabel3.Text = "数据位:端口未打开";
- this.toolStripStatusLabel4.Text = "停止位:端口未打开";
- int count = comboBox1.Items.Count;
- //去除下拉框可选数据的重复项
- int i;
- for (i = ; i < count; i++)
- {
- string strs = comboBox1.Items[i].ToString();
- for (int j = i + ; 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 "":
- serialPort1.StopBits = StopBits.One;
- break;
- case "1.5":
- serialPort1.StopBits = StopBits.OnePointFive;
- break;
- case "":
- 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 = ; i < data.Length; i++)
- {
- byte temp = data[i];
- string tempHex = temp.ToString("X2") + "";
- serialPort1.Write(tempHex);
- }
- }
- else
- {
- serialPort1.Write(data,,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, , byteRead.Length);
- if (checkBox2.Checked == false)
- {
- dataRe = Encoding.Default.GetString(byteRead);
- textBox2.Invoke(deleupdatetextbox, dataRe);
- }
- else
- {
- for (int i = ; i < byteRead.Length; i++)
- {
- byte temp = byteRead[i];
- dataRe = temp.ToString("X2") + "";
- textBox2.Invoke(deleupdatetextbox, dataRe);
- }
- }
- }
- private void UpdateTextbox(string dataRe)
- {
- if (iTextbox2 == )
- {
- 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 == )
- {
- if (button1.Enabled == true)
- {
- MessageBox.Show("请先打开串口!", "Error");
- return;
- }
- String str1;
- str1 = textBox1.Text;
- byte[] data = Encoding.Default.GetBytes(str1);
- serialPort1.Write(data, , data.Length);
- textBox1.Clear();
- }
- return;
- }
- //发送文件清屏
- private void button5_Click(object sender, EventArgs e)
- {
- textBox2.Clear();
- iTextbox2 = ;
- }
- //发送字符清屏
- private void button3_Click(object sender, EventArgs e)
- {
- textBox1.Clear();
- iTextbox2 = ;
- }
- private void textBox2_TextChanged(object sender, EventArgs e)
- {
- if (textBox2.Text.Length > )
- {
- 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;
- }
- }
- }
C#的SerialPort串口程序设计总结的更多相关文章
- (c#2.0)serialPort串口通讯
原文:(c#2.0)serialPort串口通讯 using System; using System.Collections.Generic; using System.ComponentModel ...
- SerialPort 串口开发
private SerialPort sPort = new SerialPort(); //串行端口资源 /// <summary> /// 函数功能:打开串口/关闭串口 /// < ...
- winform SerialPort串口通信问题
一.串口通信简介串行接口(串口)是一种可以将接受来自CPU的并行数据字符转换为连续的串行数据流发送出去,同时可将接受的串行数据流转换为并行的数据字符供给CPU的器件.一般完成这种功能的电路,我们称为串 ...
- System.IO.Ports.SerialPort串口通信接收完整数据
C#中使用System.IO.Ports.SerialPort进行串口通信网上资料也很多,但都没有提及一些细节: 比如 串口有时候并不会一次性把你想要的数据全部传输给你,可能会分为1次,2次,3次分别 ...
- serialport串口通讯
在.NET Framework 2.0中提供了SerialPort类,该类主要实现串口数据通信 = System.IO.Ports.SerialPort.GetPortNames();获取电脑有哪几个 ...
- java SerialPort串口通讯的使用
api文档 http://fazecast.github.io/jSerialComm/javadoc/com/fazecast/jSerialComm/package-summary.html ma ...
- 【winform】serialPort 串口
一. 1.串口通信简单实现 该来的总会来的,学做硬件的,串口这个东西必须得门清. 俗话说的好,不会做串口助手的电子工程师不是好程序员.
- [转]C# serialPort 串口接收中this.Invoke的使用
本文转自:https://blog.csdn.net/hjk216/article/details/72677596 转载地址:http://www.ciast.net/post/20160752.h ...
- 基于FPGA具有容错能理的异步串口程序设计
首先,问题源于一个项目.本来是一个很简单的多个串口收发FIFO存取数据的小程序,通过电脑验证也可用,而下位机板子之间通信就出现了丢数问题. 经过分析原因如下: 我的串口收模块是基于特权同学的开发板程序 ...
随机推荐
- UVA- 1504 - Genghis Khan the Conqueror(最小生成树-好题)
题意: n个点,m个边,然后给出m条边的顶点和权值,其次是q次替换,每次替换一条边,给出每次替换的边的顶点和权值,然后求出这次替换的最小生成树的值; 最后要你输出:q次替换的平均值.其中n<30 ...
- 1B. Spreadsheets
题目大意: 行和列的两种方式. A是1, B是2,....Z是26, AA是27, AB是28........... 如: BC23代表55列23行 还有一种表示方法:R23C55, 代表23行,55 ...
- 【数论】【扩展欧几里得】Codeforces 710D Two Arithmetic Progressions
题目链接: http://codeforces.com/problemset/problem/710/D 题目大意: 两个等差数列a1x+b1和a2x+b2,求L到R区间内重叠的点有几个. 0 < ...
- server 2008 ftp 环境重点说明
最近 在弄ftp 环境,但是 到server 2008 r2 这个系统之后,按照之前的方法 不行了 具体情况如下 利用本机 资源管理器 访问不了,根本不出现 登录框 提示 然后 到ftp 站点 ...
- UVALIVE 5893 计算几何+搜索
题意:很复杂的题意,我描述不清楚. 题目链接:http://acm.bnu.edu.cn/bnuoj/contest_show.php?cid=3033#problem/33526 大致是,给定一个起 ...
- 使用Java Mail发送邮件
本笔记参考自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983 JavaMail是SUN提供给开发人员在应用程序中实现 ...
- PHP学习之[第08讲]数据库MySQL基础之增删改查
一.工具: 1.phpMyAdmin (http://www.phpmyadmin.net/) 2.Navicat (http://www.navicat.com/) 3.MySQL GUI Tool ...
- backgroundworker组件的使用
本文转载:http://www.cnblogs.com/inforasc/archive/2009/10/12/1582110.html BackgroundWorker 组件用来执行诸如数据库事务. ...
- HDU 4287 Intelligent IME
Intelligent IME Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- HDU 3018 Ant Trip
九野的博客,转载请注明出处: http://blog.csdn.net/acmmmm/article/details/10858065 题意:n个点m条边的无向图,求用几笔可以把所有边画完(画过的边 ...