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;
}
}
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM