温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#基于SerialPort类怎么实现串口通讯

发布时间:2022-02-07 10:46:17 来源:亿速云 阅读:268 作者:iii 栏目:开发技术

本篇内容主要讲解“C#基于SerialPort类怎么实现串口通讯”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C#基于SerialPort类怎么实现串口通讯”吧!

最终效果

C#基于SerialPort类怎么实现串口通讯

窗体设置:

C#基于SerialPort类怎么实现串口通讯

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

到此,相信大家对“C#基于SerialPort类怎么实现串口通讯”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI