C#學習與上位機開發之串口通信模塊介紹


 

串口通信模塊(SerialPort)

(1)模塊簡介

使用此模塊需要首先包含一些文件IO相關文件

using System.IO;
using System.IO.Ports;

 

圖標如下圖1所示,將其拖拽到面板。會顯示在最下方,其參數有如下:

BaudRate 波特率
DataBits 數據位
Parity 奇偶校驗位
PortName 端口號
StopBits 停止位
ByteToRead 獲取輸入緩沖區的
IsOpen 獲取是否開啟串口
   
   

 

以上是我們做串口通信上位機需要用到的(如圖2所示)。

image          image 

     圖1   串口模塊圖                             圖2    串口模塊參數圖

串口通信模塊的事件有三個,如圖3所示。

DataReceived     串口接收函數

ErrorReceived     串口數據接收錯誤

PinChanged       串口號發生改變

雙擊即可建立函數。

image

常見的方法還有

方 法 名 稱

說  明

Open 打開串口.
Close 關閉串口
Read 從SerialPort 輸入緩沖區讀
ReadByte 從SerialPort 輸入緩沖區讀一個字節
ReadChar 從SerialPort 輸入緩沖區讀一個字符
Write 寫入到輸出緩沖寄存器

(2)代碼編寫

image

1、串口初始化函數

初始化函數以按鍵點擊函數為起點。需要將各控件的參數幅值給串口各項參數,具體代碼如下:

private void button1_Click(object sender, EventArgs e)
        {
           // if(Button_on == 1)
            if (!serialPort1.IsOpen)//如果串口是開
            {
                serialPort1.PortName = comboBox1.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text, 10);
                float f = Convert.ToSingle(comboBox3.Text.Trim());
                if (f == 0)//設置停止位
                    serialPort1.StopBits = StopBits.None;
                else if (f == 1.5)
                    serialPort1.StopBits = StopBits.OnePointFive;
                else if (f == 1)
                    serialPort1.StopBits = StopBits.One;
                else if (f == 2)
                    serialPort1.StopBits = StopBits.Two;
                else
                    serialPort1.StopBits = StopBits.One;
                //設置數據位
                serialPort1.DataBits = Convert.ToInt32(comboBox4.Text.Trim());
                //設置奇偶校驗位
                string s = comboBox5.Text.Trim();
                if (s.CompareTo("無") == 0)
                    serialPort1.Parity = Parity.None;
                else if (s.CompareTo("奇校驗") == 0)
                    serialPort1.Parity = Parity.Odd;
                else if (s.CompareTo("偶校驗") == 0)
                    serialPort1.Parity = Parity.Even;
                else
                    serialPort1.Parity = Parity.None;
                try
                {
                    serialPort1.Open();     //打開串口
                    button1.Text = "關閉串口";
                    comboBox1.Enabled = false;//關閉使能
                    comboBox2.Enabled = false;
                    comboBox3.Enabled = false;
                    comboBox4.Enabled = false;
                    comboBox5.Enabled = false;
                }
                catch
                {
                    MessageBox.Show("串口打開失敗!");
                }
            }
            else//如果串口是打開的則將其關閉
            {
                serialPort1.Close();
                button1.Text = "打開串口";
                comboBox1.Enabled = true;//使能配置
                comboBox2.Enabled = true;
                comboBox3.Enabled = true;
                comboBox4.Enabled = true;
                comboBox5.Enabled = true;
            }          

        }

 

2、串口寫函數

寫函數主要用於發送數據,用到serialPort.write函數

本例以鼠標點擊按鍵觸發寫函數,代碼如下:

 

private void button_send_Click(object sender, EventArgs e)
        {//發送數據
            if(serialPort1.IsOpen)
            {//如果串口開啟
                if (textBox2.Text.Trim() != "")//如果框內不為空則
                {
                    serialPort1.Write(textBox2.Text.Trim());//寫數據
                }
                else
                {
                    MessageBox.Show("發送框沒有數據");
                }
            }
            else
            {
                MessageBox.Show("串口未打開");
            }
        }

3、串口讀函數

串口讀函數主要用於讀取串口緩沖區的數據。

此處用到post_DataReceived事件

這里增減了兩種顯示方式:

1十六進制顯示    2字符串顯示

private void post_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
            if (!radioButton1.Checked)
            {
                string str = serialPort1.ReadExisting();//字符串方式讀
                textBox_receive.AppendText(str);

            }
            else
            {
                byte data;
                data = (byte)serialPort1.ReadByte();
                string str = Convert.ToString(data, 16).ToUpper();//
                textBox_receive.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + "  ");

            }
        }

 

 

未完待續…下一節介紹(C#學習與上位機開發之串口協議接收數據)

 

源碼可以訪問我GITHUB下載

https://github.com/Harryjun/Csha_demo

 

參考博客如下:

1、C#中顯現串口通信SerialPort類

http://www.cnblogs.com/BookCode/p/5583853.html


免責聲明!

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



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