最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實(shí)現(xiàn)簡(jiǎn)單串口通信的示例詳解

 更新時(shí)間:2023年10月26日 09:50:34   作者:SongYuLong的博客  
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)串口通信的相關(guān)知識(shí),文中示例代碼介紹的非常詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴們可以跟隨小編一起了解一下

串口通信

C# 串口通信主要操作:

命名空間:using System.IO.Ports;

獲取端口:string[] ports = System.IO.Ports.SerialPort.GetPortNames();

設(shè)置端口名:serialPort1.PortName = “COM1”; // 字符串

設(shè)置波特率:serialPort1.BaudRate = 115200;// int.Parse(“115200”);

設(shè)置數(shù)據(jù)位:serialPort1.DataBits = 1; // int.Parse(“1”);

設(shè)置停止位:serialPort1.StopBits = StopBits.One;

  • StopBits.One:停止位1
  • StopBits.OnePointFive:停止位1.5
  • StopBits.Two:停止位2

設(shè)置校驗(yàn)位:serialPort1.Parity = Parity.None;

  • Parity.None:無
  • Parity.Even:奇校驗(yàn)
  • Parity.Odd:偶校驗(yàn)

打開串口:serialPort1.Open();

關(guān)閉串口:serialPort1.Close();

可讀字節(jié):serialPort1.BytesToRead;

讀取數(shù)據(jù):serialPort1.Read(buffer, 0, len);

寫入數(shù)據(jù):serialPort1.Write(buffer);

接收事件: XXX_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e);

示例代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;

namespace serial_tools
{
    public partial class Form1 : Form
    {
        String serialPortName;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames(); // 獲取本機(jī)可用串口端口
            comboBoxPort.Items.AddRange(ports);
            comboBoxPort.SelectedIndex = comboBoxPort.Items.Count > 0 ? 0 : -1; // 有可用端口顯示第一個(gè)

            comboBoxBaudrate.Text = "115200"; // 默認(rèn)波特率
            comboBoxDataBits.Text = "8"; // 默認(rèn)數(shù)據(jù)位:8
            comboBoxStopbit.Text = "1"; // 默認(rèn)停止位:1
            comboBoxCheck.Text = "無"; // 默認(rèn)無校驗(yàn)
        }

        /// <summary>
        /// 重寫 系統(tǒng)消息函數(shù)
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
           
            base.WndProc(ref m);
        }

        /// <summary>
        /// 串口數(shù)據(jù)接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead; // 獲取可讀字節(jié)數(shù)
            byte[] buff = new byte[len]; // 創(chuàng)建緩存數(shù)據(jù)數(shù)組
            serialPort1.Read(buff, 0, len); // 把數(shù)據(jù)讀取到buff數(shù)組

            string str = Encoding.Default.GetString(buff); // Byte值轉(zhuǎn)ASCII字符串

            Invoke((new Action(() => {
                if (checkBoxHexShow.Checked)
                {
                    textBoxRecv.AppendText(byteToHexStr(buff));
                }
                else
                { 
                    textBoxRecv.AppendText(str);                 
                }
            
            }))); // 對(duì)話框追加顯示數(shù)據(jù)
        }


        public static string byteToHexStr(byte[] bytes)
        {
            string hexStr = "";
            try
            {
                if (bytes != null) {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        hexStr += bytes[i].ToString("X2");
                        hexStr += " "; // 兩個(gè)Hex數(shù)值以空格隔開
                    }
                }

                return hexStr;
            }
            catch (Exception)
            {
                return hexStr;
            }
        }

        /// <summary>
        /// 打開關(guān)閉串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonPortOnOff_Click(object sender, EventArgs e)
        {
            if (buttonPortOnOff.Text == "打開串口") {
                try
                {
                    serialPort1.PortName = comboBoxPort.Text; // 獲取選擇的串口端口
                    serialPortName = comboBoxPort.Text;
                    serialPort1.BaudRate = int.Parse(comboBoxBaudrate.Text); // 獲取選擇的波特率
                    serialPort1.DataBits = int.Parse(comboBoxDataBits.Text); // 獲取選擇的數(shù)據(jù)位

                    // 設(shè)置停止位
                    if (comboBoxStopbit.Text == "1") { serialPort1.StopBits = StopBits.One; }
                    else if (comboBoxStopbit.Text == "1.5") { serialPort1.StopBits = StopBits.OnePointFive; }
                    else if (comboBoxStopbit.Text == "2") { serialPort1.StopBits = StopBits.Two; }

                    // 設(shè)置奇偶校驗(yàn)
                    if (comboBoxCheck.Text == "無") { serialPort1.Parity = Parity.None; }
                    else if (comboBoxCheck.Text == "奇校驗(yàn)") { serialPort1.Parity = Parity.Even; }
                    else if (comboBoxCheck.Text == "偶校驗(yàn)") { serialPort1.Parity = Parity.Odd; }

                    // 打開串口
                    serialPort1.Open();
                    buttonPortOnOff.Text = "關(guān)閉串口";

                }
                catch (Exception ex)
                {
                    MessageBox.Show("串口打開失敗"+ ex.ToString(), "警告",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    serialPort1.Close();
                }
                catch (Exception ex)
                { 
                
                }

                buttonPortOnOff.Text = "打開串口"; 
            }
        }

        /// <summary>
        /// 清空接收數(shù)據(jù)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClearRecv_Click(object sender, EventArgs e)
        {
            textBoxRecv.Clear();
        }

        /// <summary>
        /// 發(fā)送數(shù)據(jù)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSendData_Click(object sender, EventArgs e)
        {
            String Str = textBoxSend.Text.ToString(); // 獲取發(fā)送文本框里的數(shù)據(jù)
            try
            {
                if (Str.Length > 0) {
                    serialPort1.Write(Str); // 串口發(fā)送數(shù)據(jù)
                }
            }
            catch (Exception)
            { 
            
            }
        }

        /// <summary>
        /// 清除發(fā)送數(shù)據(jù)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClearSend_Click(object sender, EventArgs e)
        {
            textBoxSend.Clear();
        }

        private void comboBoxPort_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBoxPort_MouseClick(object sender, MouseEventArgs e)
        {

        }
    }
}

窗體界面設(shè)計(jì)

運(yùn)行效果

到此這篇關(guān)于C#實(shí)現(xiàn)簡(jiǎn)單串口通信的示例詳解的文章就介紹到這了,更多相關(guān)C#串口通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#實(shí)現(xiàn)給定字符串生成MD5哈希的方法

    C#實(shí)現(xiàn)給定字符串生成MD5哈希的方法

    這篇文章主要介紹了C#實(shí)現(xiàn)給定字符串生成MD5哈希的方法,涉及C#操作字符串的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • C#實(shí)現(xiàn)Bitmap類型與Byte[]類型相互轉(zhuǎn)化的示例詳解

    C#實(shí)現(xiàn)Bitmap類型與Byte[]類型相互轉(zhuǎn)化的示例詳解

    在C#編程中,Bitmap類型和Byte[]類型之間的相互轉(zhuǎn)化是圖像處理和數(shù)據(jù)傳輸中常見的需求,Bitmap類型表示一個(gè)位圖圖像,而Byte[]類型則是一個(gè)字節(jié)數(shù)組,本文將詳細(xì)介紹如何在這兩種類型之間進(jìn)行相互轉(zhuǎn)化,需要的朋友可以參考下
    2024-07-07
  • C#中如何獲取當(dāng)前目錄和上級(jí)目錄

    C#中如何獲取當(dāng)前目錄和上級(jí)目錄

    這篇文章主要介紹了C#中如何獲取當(dāng)前目錄和上級(jí)目錄問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • C#正則表達(dá)式大全

    C#正則表達(dá)式大全

    本文詳細(xì)講解了C#正則表達(dá)式的用法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-04-04
  • C#存儲(chǔ)相同鍵多個(gè)值的Dictionary實(shí)例詳解

    C#存儲(chǔ)相同鍵多個(gè)值的Dictionary實(shí)例詳解

    在本篇文章里小編給大家整理的是關(guān)于C#存儲(chǔ)相同鍵多個(gè)值的Dictionary實(shí)例內(nèi)容,需要的朋友們可以學(xué)習(xí)下。
    2020-03-03
  • C#組合模式實(shí)例詳解

    C#組合模式實(shí)例詳解

    這篇文章主要介紹了C#組合模式,實(shí)例分析了C#實(shí)現(xiàn)組合模式的原理與相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07
  • C#幾種獲取網(wǎng)頁(yè)源文件代碼的實(shí)例

    C#幾種獲取網(wǎng)頁(yè)源文件代碼的實(shí)例

    C#幾種獲取網(wǎng)頁(yè)源文件代碼的實(shí)例,需要的朋友可以參考一下
    2013-04-04
  • 使用C#實(shí)現(xiàn)將CSV文件內(nèi)容裝配成對(duì)象列表

    使用C#實(shí)現(xiàn)將CSV文件內(nèi)容裝配成對(duì)象列表

    這篇文章主要為大家詳細(xì)介紹了如何使用C#實(shí)現(xiàn)將CSV文件內(nèi)容裝配成對(duì)象列表,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • C#多線程ThreadPool線程池詳解

    C#多線程ThreadPool線程池詳解

    這篇文章主要為大家詳細(xì)介紹了C#多線程ThreadPool線程池的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • C# 泛型字典 Dictionary的使用詳解

    C# 泛型字典 Dictionary的使用詳解

    本文主要介紹了C# 泛型字典 Dictionary的使用詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05

最新評(píng)論

城固县| 秭归县| 梧州市| 原阳县| 朝阳县| 安多县| 介休市| 阿拉善左旗| 隆化县| 长泰县| 沂源县| 永丰县| 万山特区| 罗城| 宿迁市| 清丰县| 云南省| 仁怀市| 霍邱县| 扎鲁特旗| 桦南县| 贵定县| 丘北县| 缙云县| 天气| 会理县| 方山县| 武穴市| 大港区| 连城县| 博乐市| 繁昌县| 长沙市| 泾阳县| 南涧| 邮箱| 潞城市| 靖江市| 泰宁县| 安达市| 宁城县|