珂珂的个人博客 - 一个程序猿的个人网站

串口通信Demo

  至于什么是串口,百度有很多了,我如果copy下来,生疏的文字性的也不好理解。我的理解就是2个硬件通过电缆连接进行通信,串口是COM1-COM256之间。

它有几个重要的概念,波特率,数据位,停止位,奇偶校验。具体的相关知识可以进行百度。

在net 1.1时候,需要通过系统API 来进行,到 net 2的时候微软已经为我们封装了相关的类了。

在自己电脑上开发的时候,需要用软件来模拟2个串口,有一个软件叫Virtual Serial Port Driver 还有个叫VSPM

先上图。。

代码很简单  首先就是初始化2个串口的各项参数,这里给定一些默认参数。

然后就是调用发送和接收方法了,有一点需要注意的是,接收事件是异步的,最好不要直接访问UI控件

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

namespace SerialDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Dictionary GetInitData()
        {
            Dictionary dic = new Dictionary();
            List ports = new List();
            for (int i = 1; i 
                //{
                //    FunListen();
                //});
            }
            catch (Exception ex)
            {
                this.listLog.Items.Add(DateTime.Now + "    " + this.cbxCOMPort2.Text + "串口初始化失败," + ex.Message);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Dictionary dic = GetInitData();
            this.cbxCOMPort1.DataSource = dic["ports"] as List;
            this.cbxCOMPort1.SelectedItem = "COM3";
            this.cbxParity1.DataSource = dic["parity"] as List;
            this.cbxBaudRate1.DataSource = dic["baudRate"] as List;
            this.cbxBaudRate1.SelectedItem = "9600";
            this.cbxDataBits1.DataSource = dic["dataBits"] as List;
            this.cbxStopBits1.DataSource = dic["stopBits"] as List;


            Dictionary dic2 = GetInitData();
            this.cbxCOMPort2.DataSource = dic2["ports"] as List;
            this.cbxCOMPort2.SelectedItem = "COM4";
            this.cbxParity2.DataSource = dic2["parity"] as List;
            this.cbxBaudRate2.DataSource = dic2["baudRate"] as List;
            this.cbxBaudRate2.SelectedItem = "9600";
            this.cbxDataBits2.DataSource = dic2["dataBits"] as List;
            this.cbxStopBits2.DataSource = dic2["stopBits"] as List;

            Init1();
            Init2();
        }

        public delegate void Action();
        private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //读取串口数据 
            this.listReceive.Invoke(new Action(
                delegate
                {
                    this.listReceive.Items.Add(serialPort2.ReadExisting());
                }), null);
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            Init1();
            Init2();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtSend.Text))
            {
                MessageBox.Show("请输入要发送的数据");
                return;
            }
            try
            {
                serialPort1.WriteLine(this.txtSend.Text);
                //MessageBox.Show("数据发送成功!", "系统提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show("发送数据时发生错误!" + ex.Message);
            }
        }

        private void btnReceive_Click(object sender, EventArgs e)
        {
            try
            {
                //byte[] buffer = new byte[serialPort2.BytesToRead];
                //serialPort2.Read(buffer,0,buffer.Length);
                //string str = Encoding.Unicode.GetString(buffer, 0, buffer.Length);
                //读取串口数据 
                this.listReceive.Items.Add(serialPort2.ReadExisting());
                //this.listReceive.Items.Add(str);
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取串口时发生错误!" + ex.Message);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.serialPort1.Close();
            this.listLog.Items.Add(DateTime.Now + "    " + this.serialPort1.PortName + "串口已关闭");
            this.serialPort2.Close();
            this.listLog.Items.Add(DateTime.Now + "    " + this.serialPort2.PortName + "串口已关闭");
        }
    }
}

最后上源码包

SerialDemo2005.rar

还有一个wpf版本的

SerialDemo.rar



上一篇:wordpress3.6 修改的地方

下一篇:个人代码全部开源


0 评论

查看所有评论

给个评论吧