在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# RS232串口通信

C# RS232串口通信

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.20M
  • 下载次数:245
  • 浏览次数:1601
  • 发布时间:2020-08-17
  • 实例类别:C#语言基础
  • 发 布 人:baohu
  • 文件格式:.rar
  • 所需积分:2
 相关标签: 串口通信 通信 串口 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;
using System.Threading;
using System.IO;
using System.Collections;

namespace RS232Comm
{
    public partial class MainForm : Form
    {
        protected Boolean stop = false;    
        protected Boolean conState = false;
        private StreamReader sRead;
        public MainForm()
        {
            InitializeComponent();
        }
        string strRecieve;
        bool bAccept = false;
        SerialPort sp = new SerialPort();
 
        public static string strPortName = "";
        public static string strBaudRate = "";
        public static string strDataBits = "";
        public static string strStopBits = "";

        private void btnSetSP_Click(object sender, EventArgs e)//串口设置
        {
            timer1.Enabled = false;
            sp.Close();
            ComSet dlg = new ComSet();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                sp.PortName = strPortName;
                sp.BaudRate = int.Parse(strBaudRate);
                sp.DataBits = int.Parse(strDataBits);
                sp.StopBits = (StopBits)int.Parse(strStopBits);
                sp.ReadTimeout = 500;
            }
        }

        private void btnSwitchSP_Click(object sender, EventArgs e)//打开串口
        {
            if (btnSwitchSP.Text == "打开串口")
            {
                if (strPortName != "" && strBaudRate != "" && strDataBits != "" && strStopBits != "")
                {
                    try
                    {
                        if (sp.IsOpen)
                        {
                            sp.Close();
                            sp.Open(); //打开串口    
                        }
                        else
                        {
                            sp.Open();//打开串口    
                        }
                        btnSwitchSP.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;
                btnSwitchSP.Text = "打开串口";
                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 btnSendData_Click(object sender, EventArgs e)//数据发送
        {
            if (sp.IsOpen)
            {
                try
                {
                    sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");//GB2312即信息交换用汉字编码字符集
                    sp.Write(txtSend.Text);
                }
                catch (Exception ex)//若应用程序出现调试问题
                {
                    MessageBox.Show("错误:"   ex.Message);
                }
            }
            else
            {
                MessageBox.Show("请先打开串口!");
            }
        }


        delegate void DelegateAcceptData();
        void fun()
        {
            while (bAccept )
            { AcceptData(); }
        }

        delegate void reaction();
        void AcceptData()
        {
            if (textBox2.InvokeRequired)
            {
                try
                {
                    DelegateAcceptData ddd = new DelegateAcceptData(AcceptData);
                    this.Invoke(ddd, new object[] { });
                }
                catch { }
            }
            else
            {
                try
                {
                    strRecieve = sp.ReadExisting();
                    textBox2.Text  = strRecieve;
                }
                catch (Exception e) { }
            }
        }
        
        private void btnReceiveData_Click(object sender, EventArgs e)//接受信息
        {
            sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");//GB2312即信息交换用汉字编码字符集
            if (sp.IsOpen)
            {
                timer2.Enabled = true;
            }
            else
            {
                MessageBox.Show("请先打开串口!");
            }
        }

        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 btnOutputInfo_Click(object sender, EventArgs e)//导出信息
        {
            try
            {
                string path = @"c:\output.txt";
                string content = this.textBox2.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 exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void btnClearInfo_Click(object sender, EventArgs e)//清空接受区
        {
            this.textBox2.Text = "";
        }

        private void btnQueryFile_Click(object sender, EventArgs e)//设置文件路径
        {
            String filename;
            OpenFileDialog Open1 = new OpenFileDialog(); 
            Open1.FileName = "";
            Open1.ShowDialog();
            filename = Open1.FileName;

            if (filename == "")
            {
                MessageBox.Show("请选择要发送的文件!", "Error");
                return;
            }
            textBox1.Text = filename;

            if (filename != null)
            {
                StreamReader sRead = new StreamReader(filename);
            }
            btnReceiveData.Enabled = true;

        }

        private void btnSendFile_Click(object sender, EventArgs e)//文件发送
        {
            string fileName = textBox1.Text;

            if (fileName == "")
            {
                MessageBox.Show("请选择要发送的文件!", "Error");
                return;
            }
            else
            {
                sRead = new StreamReader(fileName);
            }
            timer1.Start();
        }
 
        private void timer2_Tick(object sender, EventArgs e)
        {
            string str = sp.ReadExisting();
            string str4 = str.Replace("\r", "\r\n");
            textBox2.AppendText(str4);
            textBox2.ScrollToCaret();
        }


        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 = "";
        }
    }
}


网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警