溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

C#基于SerialPort類(lèi)怎么實(shí)現(xiàn)串口通訊

發(fā)布時(shí)間:2022-02-07 10:46:17 來(lái)源:億速云 閱讀:259 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容主要講解“C#基于SerialPort類(lèi)怎么實(shí)現(xiàn)串口通訊”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“C#基于SerialPort類(lèi)怎么實(shí)現(xiàn)串口通訊”吧!

最終效果

C#基于SerialPort類(lèi)怎么實(shí)現(xiàn)串口通訊

窗體設(shè)置:

C#基于SerialPort類(lèi)怎么實(shí)現(xiàn)串口通訊

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.IO.Ports;
using System.Threading;
using System.Windows.Forms;

namespace SerialCommunication
{
    public partial class Form1 : Form
    {
        System.Threading.SynchronizationContext m_SyncContext = null;
        SerialPort serialPort = null;
        ToHexadecimalString toHexadecimalString = new ToHexadecimalString();
        public Form1()
        {
            m_SyncContext = SynchronizationContext.Current;
            InitializeComponent();
        }

        //Data initialization
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            SerialPortNumber.Items.AddRange(ports);
            SerialPortNumber.SelectedIndex = SerialPortNumber.Items.Count > 0 ? 0 : -1;
            BaudRateCom.Text = "9600";  //Set parameters
            CheckBitCom.Text = "None";
            DataBitCom.Text = "8";
            StopBitCom.Text = "One";
        }

            //Send data
         private void Send_Click(object sender, EventArgs e)
        {
            try
            {
                //Send data and handle exceptions
                byte[] bytes = new byte[SendMessage.Text.Length];
                bytes = Encoding.Default.GetBytes(SendMessage.Text);
                serialPort.Write(bytes, 0, bytes.Length);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
                // Byte to hexadecimal string 

        //Clear data
        private void Clear_Click(object sender, EventArgs e)
        {
            ReceiveMessage.Text = "";
        }

        private void Open_Click(object sender, EventArgs e)
        {
            string portName = SerialPortNumber.Text;
            int buadRate = int.Parse(BaudRateCom.Text);
            Parity parity = 0;
            switch (CheckBitCom.Text)
            {
                case "None":
                    parity = Parity.None; break;
                case "Odd":
                    parity = Parity.Odd; break;
                case "Even":
                    parity = Parity.Even; break;
                case "Mark":
                    parity = Parity.Mark; break;
                case "Space":
                    parity = Parity.Space; break;
            }
            int dataBit = int.Parse(DataBitCom.Text);
            StopBits stopBits = 0;
            switch (StopBitCom.Text)
            {
                case "None":
                    stopBits = StopBits.None; break;
                case "One":
                    stopBits = StopBits.One; break;
                case "Tow":
                    stopBits = StopBits.Two; break;
                case "OnePointFive":
                    stopBits = StopBits.OnePointFive; break;
            }
            try
            {
                if (Open.Text == "Open")
                {
                    serialPort = new SerialPort(portName, buadRate, parity, dataBit, stopBits);
                    serialPort.Open();
                    Open.Text = "Close";
                }
                else if (Open.Text == "Close")
                {
                    serialPort.Close();
                    Open.Text = "Open";
                }
            }
            catch (Exception errror)
            {
                MessageBox.Show(errror.Message);
            }
            serialPort.DataReceived += onDataReceived;

        }
        private void onDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Byte[] bytes = new byte[serialPort.BytesToRead];
                serialPort.Read(bytes, 0, serialPort.BytesToRead);
                m_SyncContext.Post(new SendOrPostCallback((obj) =>
                {
                    ReceiveMessage.AppendText(Encoding.Default.GetString(bytes));
                }), bytes);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
    }
}

到此,相信大家對(duì)“C#基于SerialPort類(lèi)怎么實(shí)現(xiàn)串口通訊”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI