基于C# Winform的串口数据接收

很多初学者在接触到串口编程时,不知道如何入手,找了网上一些文章,也是鱼龙混杂,不好学习。

今天,我分享一篇文章,讲述 基于C# Winform的串口数据接收编程(适合大概明白WinForm编程的同学,没有接触过WinForm的同学下载源码学习)


首先添加串口(自行拖拽)

        SerialPort serialPort1 = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);      //初始化串口设置

创建一个数据接收方法

void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            Byte[] InputBuf = new Byte[128];

            try
            {
                serialPort1.Read(InputBuf, 0, serialPort1.BytesToRead);                                //读取缓冲区的数据直到“}”即0x7D为结束符
                //InputBuf = UnicodeEncoding.Default.GetBytes(strRD);             //将得到的数据转换成byte的格式
                System.Threading.Thread.Sleep(50);
                this.Invoke(disp_delegate, InputBuf);

            }
            catch (TimeoutException ex)         //超时处理
            {
                MessageBox.Show(ex.ToString());
            }
        }

建立一个委托事件:(关于C#委托事件,下文会有参考文章)

        public void DispUI(byte[] InputBuf)
        {
            //textBox1.Text = Convert.ToString(InputBuf);

            ASCIIEncoding encoding = new ASCIIEncoding();
            richTextBox1.Text = encoding.GetString(InputBuf);
        }

完整的程序代码:

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;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        SerialPort serialPort1 = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);      //初始化串口设置
        public delegate void Displaydelegate(byte[] InputBuf);
        Byte[] OutputBuf = new Byte[128];
        public Displaydelegate disp_delegate;

        public Form1()
        {
            disp_delegate = new Displaydelegate(DispUI);
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);

            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "打开")
                {
                    serialPort1.Open();
                    button1.Text = "关闭";
                }
                else
                {
                    serialPort1.Close();
                    button1.Text = "打开";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            Byte[] InputBuf = new Byte[128];

            try
            {
                serialPort1.Read(InputBuf, 0, serialPort1.BytesToRead);                                //读取缓冲区的数据直到“}”即0x7D为结束符
                //InputBuf = UnicodeEncoding.Default.GetBytes(strRD);             //将得到的数据转换成byte的格式
                System.Threading.Thread.Sleep(50);
                this.Invoke(disp_delegate, InputBuf);

            }
            catch (TimeoutException ex)         //超时处理
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void DispUI(byte[] InputBuf)
        {
            //textBox1.Text = Convert.ToString(InputBuf);

            ASCIIEncoding encoding = new ASCIIEncoding();
            richTextBox1.Text = encoding.GetString(InputBuf);
        }
    }
}

程序运行



最后分享一个虚拟串口工具:vspd(在没有底层硬件的时候,这个工具就派上用场了,结合串口小助手还有自己开发的程序使用)



程序源码:http://download.csdn.net/detail/kevin_iot/9724392

委托事件:http://www.cnblogs.com/hyddd/archive/2009/07/26/1531538.html

  • 30
    点赞
  • 90
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
public partial class Form1 : Form { public Form1() { InitializeComponent(); } SerialPort port1 = new SerialPort(); string InputData = String.Empty; delegate void SetTextCallback(string text); private void Port_Select() {//获取机器中的串口地址 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add(port); } } private void Form1_Load_1(object sender, EventArgs e) { Port_Select(); this.comboBox1.SelectedIndex = 0; this.comboBox2.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (button1.Text == "关闭串口") //当要关闭串口的时候 { port1.DiscardOutBuffer(); port1.DiscardInBuffer(); port1.Close(); button1.Text = "打开串口"; label3.Text = "串口当前状况:未打开"; comboBox1.Enabled = true; comboBox2.Enabled = true; } else if (button1.Text == "打开串口") //当要打开串口的时候 { try { port1.PortName = comboBox1.SelectedItem.ToString(); port1.BaudRate = Convert.ToInt32(comboBox2.SelectedItem); port1.DataBits = 8; port1.RtsEnable = true; port1.Open(); port1.DiscardOutBuffer(); port1.DiscardInBuffer(); button1.Text = "关闭串口"; comboBox1.Enabled = false; comboBox2.Enabled = false; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + " 波特率:" + comboBox2.SelectedItem.ToString() + " 数据位:8 "; } catch { button1.Text = "打开串口"; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + "打开失败"; MessageBox.Show("该串口无法打开"); } } } 资源中部分代码
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值