zoukankan      html  css  js  c++  java
  • C#串口编程学习简单实例

    在网上看到的帖子,按部就班的做了一遍,很简单的例子,.NET把串口编程封装的非常好!

    步骤一:下载安装串口模拟软件

    软件名称:VSPM虚拟串口软件   下载地址:http://download.csdn.net/source/1232967

    使用方法:1.安装以后工作模式选择为:VSPM运行在Server模式,支持Client模式设备

                  2.使用设备探测器建立虚拟串口。(如果选择 建立默认的串口,软件就会自动帮你建立四个虚拟串口的)之后就是新增虚拟串口

                  3.串口选COM2,选择监听的IP地址:192.168.1.101 ,Client模式的设备尝试连接此端口:8099

                  4.选择此串口,再选择菜单栏:检查此设备连接,输入刚才新增时候选择的IP地址:192.168.1.101,刚才选择的端口:8099

                  5.点击重新连接,这个窗口没有什么反映:但是主窗口的串口最右边一栏:最后一次操作:显示串口:COM2没有打开。

    步骤二:串口编程

                  1.建立winform项目,添加引用:Microsoft.VisualBasic

                  2.窗体界面

     

                  3.编码

    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;
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
                  
            System.IO.Ports.SerialPort com;

            private void Form1_Load(object sender, EventArgs e)
            {

                Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
                foreach (string s in pc.Ports.SerialPortNames)//遍历本机所有串口
                {
                    this.comboBox1.Items.Add(s);
                }

                com = new System.IO.Ports.SerialPort();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                com.PortName = this.comboBox1.Items[this.comboBox1.SelectedIndex].ToString();
                com.Open();//打开串口
            }

            private void button2_Click(object sender, EventArgs e)
            {

                com.WriteLine(this.textBox1.Text); //向串口写数据
            }

            private void button3_Click(object sender, EventArgs e)
            {

                this.textBox1.Text = string.Empty;
                this.textBox1.Text=com.ReadLine();//读串口数据

            }

            private void button4_Click(object sender, EventArgs e)
            {
                com.Close(); //关闭串口
            }

        }
    }
    步骤三:运行编译的串口操作程序

    1.open串口

     

    2.write串口

    示例:在textbox输入1222

     

     

    3.read串口

    示例:在虚拟软件的管理输入,然后回车。(注意:在虚拟界面不会显示你输入的,但winform这边会接收到)
     

  • 相关阅读:
    Linux 下安装JDK1.8
    INSERT IGNORE 与INSERT INTO的区别
    linux安装redis 完整步骤
    从0开始 图论学习 广度优先搜索 链式前向星表示法
    从0开始 图论学习 深度优先遍历 链式前向星表示法
    从0开始 图论学习 链式前向星 最好的建图方法
    从0开始 图论学习 邻接表 STL vector
    从0开始 图论学习 前向星表示法
    数据结构实习
    数据结构实习
  • 原文地址:https://www.cnblogs.com/youchun/p/1612724.html
Copyright © 2011-2022 走看看