C#实现简单串口通讯实例

本文实例为大家分享了C#实现简单串口通讯的具体代码,供大家参考,具体内容如下

参数设置界面代码:

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 ComDemo
{
    public partial class ComSet : Form
    {
        public ComSet()
        {
            InitializeComponent();
        }

        private void ComSet_Load(object sender, EventArgs e)
        {
            //串口
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                cmbPort.Items.Add(port);
            }
            cmbPort.SelectedIndex = 0;

            //波特率
            cmbBaudRate.Items.Add("110");
            cmbBaudRate.Items.Add("300");
            cmbBaudRate.Items.Add("1200");
            cmbBaudRate.Items.Add("2400");
            cmbBaudRate.Items.Add("4800");
            cmbBaudRate.Items.Add("9600");
            cmbBaudRate.Items.Add("19200");
            cmbBaudRate.Items.Add("38400");
            cmbBaudRate.Items.Add("57600");
            cmbBaudRate.Items.Add("115200");
            cmbBaudRate.Items.Add("230400");
            cmbBaudRate.Items.Add("460800");
            cmbBaudRate.Items.Add("921600");
            cmbBaudRate.SelectedIndex = 5;

            //数据位
            cmbDataBits.Items.Add("5");
            cmbDataBits.Items.Add("6");
            cmbDataBits.Items.Add("7");
            cmbDataBits.Items.Add("8");
            cmbDataBits.SelectedIndex = 3;

            //停止位
            cmbStopBit.Items.Add("1");
            cmbStopBit.SelectedIndex = 0;

            //佼验位
            cmbParity.Items.Add("无");
            cmbParity.SelectedIndex = 0;
        }

        private void bntOK_Click(object sender, EventArgs e)
        {
            //以下4个参数都是从窗体MainForm传入的
            MainForm.strProtName = cmbPort.Text;
            MainForm.strBaudRate = cmbBaudRate.Text;
            MainForm.strDataBits = cmbDataBits.Text;
            MainForm.strStopBits = cmbStopBit.Text;
            DialogResult = DialogResult.OK;
        }

        private void bntCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}

主界面代码:

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

namespace ComDemo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private Thread getRecevice;
        protected Boolean stop = false;
        protected Boolean conState = false;
        private StreamReader sRead;
        string strRecieve;
        bool bAccpet = false;

        SerialPort sp = new SerialPort();//实例化串口通讯类
        //以下定义4个公有变量,用于参数传递
        public static string strProtName = "";
        public static string strBaudRate = "";
        public static string strDataBits = "";
        public static string strStopBits = "";

        private void MainForm_Load(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            groupBox2.Enabled = false;
            this.toolStripStatusLabel1.Text = "端口号:端口未打开 | ";
            this.toolStripStatusLabel2.Text = "波特率:端口未打开 | ";
            this.toolStripStatusLabel3.Text = "数据位:端口未打开 | ";
            this.toolStripStatusLabel4.Text = "停止位:端口未打开 | ";
            this.toolStripStatusLabel5.Text = "";
        }
        //串口设计
        private void btnSetSP_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            sp.Close();
            ComSet dlg = new ComSet();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                sp.PortName = strProtName;//串口号
                sp.BaudRate = int.Parse(strBaudRate);//波特率
                sp.DataBits = int.Parse(strDataBits);//数据位
                sp.StopBits = (StopBits)int.Parse(strStopBits);//停止位
                sp.ReadTimeout = 500;//读取数据的超时时间,引发ReadExisting异常
            }
        }
        //打开/关闭串口
        private void bntSwitchSP_Click(object sender, EventArgs e)
        {
            if (bntSwitchSP.Text == "打开串口")
            {
                if (strProtName != "" && strBaudRate != "" && strDataBits != "" && strStopBits != "")
                {
                    try
                    {
                        if (sp.IsOpen)
                        {
                            sp.Close();
                            sp.Open();//打开串口
                        }
                        else
                        {
                            sp.Open();//打开串口
                        }
                        bntSwitchSP.Text = "关闭串口";
                        groupBox1.Enabled = true;
                        groupBox2.Enabled = true;
                        this.toolStripStatusLabel1.Text = "端口号:" + sp.PortName + " | ";
                        this.toolStripStatusLabel2.Text = "波特率:" + sp.BaudRate + " | ";
                        this.toolStripStatusLabel3.Text = "数据位:" + sp.DataBits + " | ";
                        this.toolStripStatusLabel4.Text = "停止位:" + sp.StopBits + " | ";
                        this.toolStripStatusLabel5.Text = "";

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("错误:" + ex.Message, "C#串口通信");
                    }
                }
                else
                {
                    MessageBox.Show("请先设置串口!", "RS232串口通信");
                }
            }
            else
            {
                timer1.Enabled = false;
                timer2.Enabled = false;
                bntSwitchSP.Text = "打开串口";
                if (sp.IsOpen)
                    sp.Close();
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;
                this.toolStripStatusLabel1.Text = "端口号:端口未打开 | ";
                this.toolStripStatusLabel2.Text = "波特率:端口未打开 | ";
                this.toolStripStatusLabel3.Text = "数据位:端口未打开 | ";
                this.toolStripStatusLabel4.Text = "停止位:端口未打开 | ";
                this.toolStripStatusLabel5.Text = "";
            }
        }
        //发送数据
        private void bntSendData_Click(object sender, EventArgs e)
        {
            if (sp.IsOpen)
            {
                try
                {
                    sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                    sp.Write(txtSend.Text);//发送数据
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("请先打开串口!");
            }
        }
        //选择文件
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.InitialDirectory = "c\\";
            open.RestoreDirectory = true;
            open.FilterIndex = 1;
            open.Filter = "txt文件(*.txt)|*.txt";
            if (open.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (open.OpenFile() != null)
                    {
                        txtFileName.Text = open.FileName;
                    }
                }
                catch (Exception err1)
                {
                    MessageBox.Show("文件打开错误!  " + err1.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        //发送文件内容
        private void bntSendFile_Click(object sender, EventArgs e)
        {
            string fileName = txtFileName.Text.Trim();
            if (fileName == "")
            {
                MessageBox.Show("请选择要发送的文件!", "Error");
                return;
            }
            else
            {
                //sRead = new StreamReader(fileName);
                sRead = new StreamReader(fileName,Encoding.Default);//解决中文乱码问题
            }
            timer1.Start();
        }
        //发送文件时钟
        private void timer1_Tick(object sender, EventArgs e)
        {
            string str1;
            str1 = sRead.ReadLine();
            if (str1 == null)
            {
                timer1.Stop();
                sRead.Close();
                MessageBox.Show("文件发送成功!", "C#串口通讯");
                this.toolStripStatusLabel5.Text = "";
                return;
            }
            byte[] data = Encoding.Default.GetBytes(str1);
            sp.Write(data, 0, data.Length);
            this.toolStripStatusLabel5.Text = "   文件发送中...";
        }
        //接收数据
        private void btnReceiveData_Click(object sender, EventArgs e)
        {
            if (btnReceiveData.Text == "接收数据")
            {
                sp.Encoding = Encoding.GetEncoding("GB2312");
                if (sp.IsOpen)
                {
                    //timer2.Enabled = true; //使用主线程进行

                    //使用委托以及多线程进行
                    bAccpet = true;
                    getRecevice = new Thread(new ThreadStart(testDelegate));
                    //getRecevice.IsBackground = true;
                    getRecevice.Start();
                    btnReceiveData.Text = "停止接收";
                }
                else
                {
                    MessageBox.Show("请先打开串口");
                }
            }
            else
            {
                //timer2.Enabled = false;
                bAccpet = false;
                try
                {   //停止主监听线程
                    if (null != getRecevice)
                    {
                        if (getRecevice.IsAlive)
                        {
                            if (!getRecevice.Join(100))
                            {
                                //关闭线程
                                getRecevice.Abort();
                            }
                        }
                        getRecevice = null;
                    }
                }
                catch { }
                btnReceiveData.Text = "接收数据";
            }
        }
        private void testDelegate()
        {
            reaction r = new reaction(fun);
            r();
        }
        //用于接收数据的定时时钟
        private void timer2_Tick(object sender, EventArgs e)
        {
            string str = sp.ReadExisting();
            string str2 = str.Replace("\r", "\r\n");
            txtReceiveData.AppendText(str2);
            txtReceiveData.ScrollToCaret();
        }
        //下面用到了接收信息的代理功能,此为设计的要点之一
        delegate void DelegateAcceptData();
        void fun()
        {
            while (bAccpet)
            {
                AcceptData();
            }
        }

        delegate void reaction();
        void AcceptData()
        {
            if (txtReceiveData.InvokeRequired)
            {
                try
                {
                    DelegateAcceptData ddd = new DelegateAcceptData(AcceptData);
                    this.Invoke(ddd, new object[] { });
                }
                catch { }
            }
            else
            {
                try
                {
                    strRecieve = sp.ReadExisting();
                    txtReceiveData.AppendText(strRecieve);
                }
                catch (Exception ex) { }
            }
        }

        private void bntClear_Click(object sender, EventArgs e)
        {
            txtReceiveData.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Directory.GetCurrentDirectory() + @"\output.txt";
                string content = this.txtReceiveData.Text;
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter write = new StreamWriter(fs);
                write.Write(content);
                write.Flush();
                write.Close();
                fs.Close();
                MessageBox.Show("接收信息导出在:" + path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

效果图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • c# 实现简单的串口通讯

    本文提供一个用C#实现串口通讯实例,亲自编写,亲测可用! 开发环境: VS2008+.net FrameWork3.5(实际上2.0应该也可以) 第一步 创建一个WinForm窗体,拉入一些界面元素 重点就是,图中用红框标出的,工具箱--组件--SerialPort,做.net串口通讯,这是必备控件 第二步 设置SerialPort控件属性 用C#向串口发送数据没什么特别的,就是调用SerialPort的Write方法往串口写数据就行 但是从串口那里接收数据的方式就比较特别了 首先,需要在代码里

  • C#串口通讯概念及简单的实现方法

    前言 最近在研究串口通讯,其中有几个比较重要的概念,RS-232这种适配于上位机和PC端进行连接,RS-232只限于PC串口和设备间点对点的通信.它很简单的就可以进行连接,由于串口通讯是异步的,也就是说你可以同时向两端或者更多进行数据发送,它们之间的传输数据类型是byte,串口通信最重要的参数是波特率.数据位.停止位和奇偶校验.对于两个进行通信的端口,这些参数必须匹配. 听大佬说的几个关于串口通讯的术语,啥?啥,这是啥? 就让我这个"小白"给你说说:第一个波特率,这个东西在不同领域都有

  • 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; usi

  • C#实现简单串口通讯实例

    本文实例为大家分享了C#实现简单串口通讯的具体代码,供大家参考,具体内容如下 参数设置界面代码: 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.P

  • 对Python 简单串口收发GUI界面的实例详解

    忙活了三个多小时,连学带做,总算是搞出来了一个具有基本功能的串口通信PC机的GUI界面,Tkinter在python中确实很好用,而且代码量确实也很少,不足的是Tkinter不自带combox,但是幸运的是我下载的2.7版本自带了包含有combox的ttk模块,于是乎问题就顺利解决了. 下面是源代码,一些错误提示功能还没有做,目前只是简单地实现了下位机与PC的通信界面,下位机还是用的STM32F103 #encoding=utf-8 __author__ = 'freedom' from Tki

  • 浅谈Android串口通讯SerialPort原理

    目录 前言 一.名词解释 二.SerialPort的函数分析 三.SerialPort打开串口的流程 四.疑惑 五.总结 前言 通过前面这篇文章Android串口通讯SerialPort的使用详情已经基本掌握了串口的使用,那么不经想问自己,到底什么才是串口通讯呢?串口通讯(Serial Communication),设备与设备之间,通过输入线(RXD),输出线(TXD),地线(GND),按位进行传输数据的一种通讯方式.CPU 和串行设备间的编码转换器(转换器(converter)是指将一种信号转

  • 浅谈linux下的串口通讯开发

    串行口是计算机一种常用的接口,具有连接线少,通讯简单,得到广泛的使用.常用的串口是RS-232-C接口(又称EIA RS-232-C)它是在1970年由美国电子工业协会(EIA)联合贝尔系统.调制解调器厂家及计算机终端生产厂家共同制定的用于串行通讯的标准.串口通讯指的是计算机依次以位(bit)为单位来传送数据,串行通讯使用的范围很广,在嵌入式系统开发过程中串口通讯也经常用到通讯方式之一. Linux对所有设备的访问是通过设备文件来进行的,串口也是这样,为了访问串口,只需打开其设备文件即可操作串口

  • Java使用开源Rxtx实现串口通讯

    本文实例为大家分享了Java使用开源Rxtx实现串口通讯的具体代码,供大家参考,具体内容如下 使用方法: windows平台: 1.把rxtxParallel.dll.rxtxSerial.dll拷贝到:C:\WINDOWS\system32下. 2.如果是在开发的时候(JDK),需要把RXTXcomm.jar.rxtxParallel.dll.rxtxSerial.dll拷贝到..\jre...\lib\ext下:如:D:\Program Files\Java\jre1.6.0_02\lib\

  • Python 实现Serial 与STM32J进行串口通讯

    Python果然是一款非常简明的语言,做东西非常流畅,今天又尝试了一下用Serial做了一个控制台的串口通讯,我用的下位机是STM32F103,搞了一个多小时就成功了,可见Python的能力之强. 说明几点注意,一是Python在windows下的串口号可以用COM来标注,此时序号从1开始,如果自己单独指定序号,则是从0开始. 另外,如果下位机串口通讯设定的非常简单的话,在Python中只需要设定好串口号和波特率即可,其余的均设为默认值.一般来说在单片机或者是嵌入式系统中的串口通讯基本都不需要设

  • 使用Java实现简单串口通信

    本博文参考自https://www.jb51.net/article/100269.htm www.jb51.net/article/100269.htm 没想到挺多人需要这个的,很高兴这篇文章能对大家有帮助,主要的工具类博文里已经有了,当然,要小工具源码的留言邮箱即可. 2019.09.05 最近接触到了串口及其读写,在此记录java进行串口读写的过程. 1.导入支持java串口通信的jar包: 在maven项目的pom.xml中添加RXTXcomm的依赖 或者 下载RXTXcomm.jar并

  • .NET Core使用flyfire.CustomSerialPort实现Windows/Linux跨平台串口通讯

    1,前言 开发环境:在 Visual Studio 2017,.NET Core 2.x 串口通讯用于设备之间,传递数据,物联网设备中广泛使用串口方式连接通讯,物联网通讯协议 :Modbus 协议 ASCII.RTU.TCP模式是应用层的协议,与通讯方式无关. 笔者现在实现的是 串口通信,实现后,可以在上层加上 Modbus 协议,笔者的另一篇文章即是在串口上实现 Modbus 协议,计算中心向物联网设备发送消息,要求设备响应,传送设备信息.检测状态等. 本文是 串口通讯 的实现. 2,安装虚拟

随机推荐