简介:微软的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); 数据接收事件的方法
 
简单的界面示例代码如下:
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.IO.Ports;
  10. using System.IO;
  11. using System.Timers;
  12.  
  13. namespace WinFromApp
  14. {
  15. public partial class Form1 : Form
  16. {
  17. private StreamReader sRead;
  18. public int iTextbox2 = ;
  19. SerialPort serialPort1 = new SerialPort();
  20. public Form1()
  21. {
  22. InitializeComponent();
  23. }
  24. private DateTime _dt = DateTime.Now; //定义一个成员函数用于保存每次的时间点
  25. private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
  26. {
  27. DateTime tempDt = DateTime.Now; //保存按键按下时刻的时间点
  28. TimeSpan ts = tempDt .Subtract(_dt); //获取时间间隔
  29. if (ts.Milliseconds > ) //判断时间间隔,如果时间间隔大于50毫秒,则将TextBox清空
  30. textBox2.Text = "";
  31. _dt = tempDt ;
  32. }
  33.  
  34. private void timer1_Tick(object sender, EventArgs e)
  35. {
  36. string str1;
  37. str1 = sRead.ReadLine();
  38. if (str1 == null)
  39. {
  40. timer1.Stop();
  41. sRead.Close();
  42. MessageBox.Show("发送完毕","NICE");
  43. button2.Enabled = true;
  44. button3.Enabled = true;
  45. button4.Enabled = true;
  46. textBox1.Enabled = true;
  47. textBox3.Enabled = true;
  48. textBox4.Enabled = true;
  49. return;
  50. }
  51. byte[] data = Encoding.Default.GetBytes(str1);
  52. serialPort1.Write(data, , data.Length);
  53. }
  54.  
  55. private void Form1_Load(object sender, EventArgs e)
  56. {
  57. timer2.Start();
  58. string[] str = SerialPort.GetPortNames();
  59. if(str==null)
  60. {
  61. MessageBox.Show("本机没有串口!","Error");
  62. return;
  63. }
  64. comboBox1.Items.AddRange(str);
  65. comboBox1.SelectedIndex = ;
  66. comboBox2.SelectedIndex = ;
  67. comboBox4.SelectedIndex = ;
  68. comboBox5.SelectedIndex = ;
  69. this.toolStripStatusLabel1.Text = "端口号:端口未打开";
  70. this.toolStripStatusLabel2.Text = "波特率:端口未打开";
  71. this.toolStripStatusLabel3.Text = "数据位:端口未打开";
  72. this.toolStripStatusLabel4.Text = "停止位:端口未打开";
  73. int count = comboBox1.Items.Count;
  74. //去除下拉框可选数据的重复项
  75. int i;
  76. for (i = ; i < count; i++)
  77. {
  78. string strs = comboBox1.Items[i].ToString();
  79. for (int j = i + ; j < count; j++)
  80. {
  81. string str1 = comboBox1.Items[j].ToString();
  82. if (str1 == strs)
  83. {
  84. comboBox1.Items.RemoveAt(j); count--; j--;
  85. }
  86. }
  87. }
  88. }
  89.  
  90. //打开串口
  91. private void button1_Click(object sender, EventArgs e)
  92. {
  93. String str1 = comboBox1.Text;
  94. String str2 = comboBox2.Text;
  95. String str3 = comboBox4.Text;
  96. String str4 = comboBox5.Text;
  97. Int32 int2 = Convert.ToInt32(str2);
  98. Int32 int3 = Convert.ToInt32(str3);
  99. try
  100. {
  101. if (str1 == null)
  102. {
  103. MessageBox.Show("请先选择串口!", "Error");
  104. return;
  105. }
  106. serialPort1.PortName = str1;
  107. serialPort1.BaudRate = int2;
  108. serialPort1.DataBits = int3;
  109. switch (comboBox5.Text)
  110. {
  111. case "":
  112. serialPort1.StopBits = StopBits.One;
  113. break;
  114. case "1.5":
  115. serialPort1.StopBits = StopBits.OnePointFive;
  116. break;
  117. case "":
  118. serialPort1.StopBits = StopBits.Two;
  119. break;
  120. default:
  121. MessageBox.Show("Error:参数不正确", "Error");
  122. break;
  123. }
  124. if (serialPort1.IsOpen == true)
  125. {
  126. serialPort1.Close();
  127. }
  128. serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
  129. serialPort1.Open();
  130. MessageBox.Show("串口打开成功!",str1);
  131. this.toolStripStatusLabel1.Text = "端口号:" + serialPort1.PortName + "";
  132. this.toolStripStatusLabel2.Text="波特率:"+serialPort1.BaudRate+"";
  133. this.toolStripStatusLabel3.Text = "数据位:" + serialPort1.DataBits + "";
  134. this.toolStripStatusLabel4.Text = "停止位:" + serialPort1.StopBits + "";
  135. button1.Enabled = false;
  136. comboBox1.Enabled = false;
  137. comboBox2.Enabled = false;
  138. comboBox4.Enabled = false;
  139. comboBox5.Enabled = false;
  140. }
  141. catch(Exception er)
  142. {
  143. MessageBox.Show("Error:"+er.Message,"Error");
  144. return;
  145. }
  146. }
  147.  
  148. //关闭串口
  149. private void button2_Click(object sender, EventArgs e)
  150. {
  151. button1.Enabled = true;
  152. comboBox1.Enabled = true;
  153. comboBox2.Enabled = true;
  154. comboBox4.Enabled = true;
  155. comboBox5.Enabled = true;
  156. serialPort1.Close();
  157. this.toolStripStatusLabel1.Text = "端口号:" + serialPort1.PortName + "";
  158. this.toolStripStatusLabel2.Text = "波特率:" + serialPort1.BaudRate + "";
  159. this.toolStripStatusLabel3.Text = "数据位:" + serialPort1.DataBits + "";
  160. this.toolStripStatusLabel4.Text = "停止位:" + serialPort1.StopBits + "";
  161. }
  162.  
  163. private void toolStripMenuItem3_Click(object sender, EventArgs e)
  164. {
  165. Application.Exit();
  166. }
  167.  
  168. //发送
  169. private void button4_Click(object sender, EventArgs e)
  170. {
  171. if (button1.Enabled == true)
  172. {
  173. MessageBox.Show("请先打开串口","Error");
  174. return;
  175. }
  176. String str1;
  177. str1 = textBox1.Text;
  178. byte[] data = Encoding.Default.GetBytes(str1);
  179. if (checkBox1.Checked == true)
  180. {
  181. for (int i = ; i < data.Length; i++)
  182. {
  183. byte temp = data[i];
  184. string tempHex = temp.ToString("X2") + "";
  185. serialPort1.Write(tempHex);
  186. }
  187. }
  188. else
  189. {
  190. serialPort1.Write(data,,data.Length);
  191. }
  192. }
  193. //使用Control.Invoke
  194. public delegate void DeleUpdateTextbox(string dateRe);
  195. private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  196. {
  197. string dataRe;
  198. byte[] byteRead = new byte[serialPort1.BytesToRead];
  199. DeleUpdateTextbox deleupdatetextbox = new DeleUpdateTextbox(UpdateTextbox);
  200. serialPort1.Read(byteRead, , byteRead.Length);
  201. if (checkBox2.Checked == false)
  202. {
  203. dataRe = Encoding.Default.GetString(byteRead);
  204. textBox2.Invoke(deleupdatetextbox, dataRe);
  205. }
  206. else
  207. {
  208. for (int i = ; i < byteRead.Length; i++)
  209. {
  210. byte temp = byteRead[i];
  211. dataRe = temp.ToString("X2") + "";
  212. textBox2.Invoke(deleupdatetextbox, dataRe);
  213. }
  214. }
  215. }
  216. private void UpdateTextbox(string dataRe)
  217. {
  218. if (iTextbox2 == )
  219. {
  220. this.textBox2.Text = dataRe;
  221. iTextbox2++;
  222. }
  223. else
  224. {
  225. textBox2.AppendText(dataRe);
  226. }
  227. }
  228. //发送文件
  229. private void button6_Click(object sender, EventArgs e)
  230. {
  231. string str3 = textBox3.Text;
  232. if (button1.Enabled == true)
  233. {
  234. MessageBox.Show("请先打开串口", "Error");
  235. return;
  236. }
  237. if (str3 == "")
  238. {
  239. MessageBox.Show("请选择要发送的文件!", "Error");
  240. return;
  241. }
  242. string str1;
  243. str1 = textBox4.Text;
  244. timer1.Interval = Convert.ToInt32(str1);
  245. timer1.Start();
  246. button2.Enabled = false;
  247. button3.Enabled = false;
  248. button4.Enabled = false;
  249. button5.Enabled = false;
  250. textBox1.Enabled = false;
  251. textBox3.Enabled = false;
  252. textBox4.Enabled = false;
  253. }
  254. //选择文件
  255. private void button8_Click(object sender, EventArgs e)
  256. {
  257. String filename;
  258. openFileDialog1.FileName = "";
  259. openFileDialog1.ShowDialog();
  260. filename = openFileDialog1.FileName;
  261. if(filename=="")
  262. {
  263. MessageBox.Show("请选择要发送的文件!","Error");
  264. return;
  265. }
  266. textBox3.Text = filename;
  267. if (filename != null)
  268. {
  269. sRead = new StreamReader(filename);
  270. }
  271. button5.Enabled = true;
  272. }
  273. //停止发送
  274. private void button7_Click(object sender, EventArgs e)
  275. {
  276. timer1.Stop();
  277. button2.Enabled = true;
  278. button3.Enabled = true;
  279. button4.Enabled = true;
  280. textBox1.Enabled = true;
  281. textBox3.Enabled = true;
  282. textBox4.Enabled = true;
  283. }
  284.  
  285. private void textBox1_KeyDown(object sender, KeyEventArgs e)
  286. {
  287.  
  288. if (e.KeyValue == )
  289. {
  290. if (button1.Enabled == true)
  291. {
  292. MessageBox.Show("请先打开串口!", "Error");
  293. return;
  294. }
  295. String str1;
  296. str1 = textBox1.Text;
  297. byte[] data = Encoding.Default.GetBytes(str1);
  298. serialPort1.Write(data, , data.Length);
  299. textBox1.Clear();
  300. }
  301. return;
  302. }
  303. //发送文件清屏
  304. private void button5_Click(object sender, EventArgs e)
  305. {
  306. textBox2.Clear();
  307. iTextbox2 = ;
  308. }
  309. //发送字符清屏
  310. private void button3_Click(object sender, EventArgs e)
  311. {
  312. textBox1.Clear();
  313. iTextbox2 = ;
  314. }
  315. private void textBox2_TextChanged(object sender, EventArgs e)
  316. {
  317. if (textBox2.Text.Length > )
  318. {
  319. MessageBox.Show("条码长度:"+textBox2.Text.Length+"\n条码内容:"+textBox2.Text,"系统提示");
  320. }
  321. }
  322.  
  323. private void timer2_Tick(object sender, EventArgs e)
  324. {
  325. string Week = DateTime.Now.DayOfWeek.ToString();
  326. switch (Week)
  327. {
  328. case "Sunday":
  329. Week = "星期天";
  330. break;
  331. case "Monday":
  332. Week = "星期一";
  333. break;
  334. case "Tuesday":
  335. Week = "星期二";
  336. break;
  337. case "Wednesday":
  338. Week = "星期三";
  339. break;
  340. case "Thursday":
  341. Week = "星期四";
  342. break;
  343. case "Friday":
  344. Week = "星期五";
  345. break;
  346. case "Saturday":
  347. Week = "星期六";
  348. break;
  349. }
  350. label6.Text=DateTime.Now.ToString()+" "+Week;
  351. }
  352. }
  353. }

 

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

  1. (c#2.0)serialPort串口通讯

    原文:(c#2.0)serialPort串口通讯 using System; using System.Collections.Generic; using System.ComponentModel ...

  2. SerialPort 串口开发

    private SerialPort sPort = new SerialPort(); //串行端口资源 /// <summary> /// 函数功能:打开串口/关闭串口 /// < ...

  3. winform SerialPort串口通信问题

    一.串口通信简介串行接口(串口)是一种可以将接受来自CPU的并行数据字符转换为连续的串行数据流发送出去,同时可将接受的串行数据流转换为并行的数据字符供给CPU的器件.一般完成这种功能的电路,我们称为串 ...

  4. System.IO.Ports.SerialPort串口通信接收完整数据

    C#中使用System.IO.Ports.SerialPort进行串口通信网上资料也很多,但都没有提及一些细节: 比如 串口有时候并不会一次性把你想要的数据全部传输给你,可能会分为1次,2次,3次分别 ...

  5. serialport串口通讯

    在.NET Framework 2.0中提供了SerialPort类,该类主要实现串口数据通信 = System.IO.Ports.SerialPort.GetPortNames();获取电脑有哪几个 ...

  6. java SerialPort串口通讯的使用

    api文档 http://fazecast.github.io/jSerialComm/javadoc/com/fazecast/jSerialComm/package-summary.html ma ...

  7. 【winform】serialPort 串口

    一. 1.串口通信简单实现 该来的总会来的,学做硬件的,串口这个东西必须得门清. 俗话说的好,不会做串口助手的电子工程师不是好程序员.

  8. [转]C# serialPort 串口接收中this.Invoke的使用

    本文转自:https://blog.csdn.net/hjk216/article/details/72677596 转载地址:http://www.ciast.net/post/20160752.h ...

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

    首先,问题源于一个项目.本来是一个很简单的多个串口收发FIFO存取数据的小程序,通过电脑验证也可用,而下位机板子之间通信就出现了丢数问题. 经过分析原因如下: 我的串口收模块是基于特权同学的开发板程序 ...

随机推荐

  1. UVA- 1504 - Genghis Khan the Conqueror(最小生成树-好题)

    题意: n个点,m个边,然后给出m条边的顶点和权值,其次是q次替换,每次替换一条边,给出每次替换的边的顶点和权值,然后求出这次替换的最小生成树的值; 最后要你输出:q次替换的平均值.其中n<30 ...

  2. 1B. Spreadsheets

    题目大意: 行和列的两种方式. A是1, B是2,....Z是26, AA是27, AB是28........... 如: BC23代表55列23行 还有一种表示方法:R23C55, 代表23行,55 ...

  3. 【数论】【扩展欧几里得】Codeforces 710D Two Arithmetic Progressions

    题目链接: http://codeforces.com/problemset/problem/710/D 题目大意: 两个等差数列a1x+b1和a2x+b2,求L到R区间内重叠的点有几个. 0 < ...

  4. server 2008 ftp 环境重点说明

    最近 在弄ftp  环境,但是 到server 2008 r2  这个系统之后,按照之前的方法 不行了 具体情况如下 利用本机 资源管理器 访问不了,根本不出现 登录框 提示 然后 到ftp  站点 ...

  5. UVALIVE 5893 计算几何+搜索

    题意:很复杂的题意,我描述不清楚. 题目链接:http://acm.bnu.edu.cn/bnuoj/contest_show.php?cid=3033#problem/33526 大致是,给定一个起 ...

  6. 使用Java Mail发送邮件

    本笔记参考自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983 JavaMail是SUN提供给开发人员在应用程序中实现 ...

  7. PHP学习之[第08讲]数据库MySQL基础之增删改查

    一.工具: 1.phpMyAdmin (http://www.phpmyadmin.net/) 2.Navicat (http://www.navicat.com/) 3.MySQL GUI Tool ...

  8. backgroundworker组件的使用

    本文转载:http://www.cnblogs.com/inforasc/archive/2009/10/12/1582110.html BackgroundWorker 组件用来执行诸如数据库事务. ...

  9. HDU 4287 Intelligent IME

    Intelligent IME Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  10. HDU 3018 Ant Trip

    九野的博客,转载请注明出处:  http://blog.csdn.net/acmmmm/article/details/10858065 题意:n个点m条边的无向图,求用几笔可以把所有边画完(画过的边 ...