• C#SerialPort串口的简单使用


    注:只要扫码枪设备都连接成功这段代码才可以使用

    如果不使用SerialPort控件可以这样写            最后获取扫码的结果放在textbox控件上有扫码枪的可以试一下

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO.Ports;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace 串口Dome
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            //声明一个串口
            public static SerialPort _serialPort;
    
           
            public void setPort(string portName, int baudRate)
            {
                //实例化一下串口
                _serialPort = new SerialPort();
                
                this.RegisterSerialPort(portName, baudRate);
                if (_serialPort.IsOpen == false)
                {
    
                    _serialPort.Open();
                }
            //不用太关注这个我也不是很懂,只要知道他是个回调函数就可以 _serialPort.DataReceived
    += new SerialDataReceivedEventHandler(_serialPort_DataReceived); } /// <summary> /// 注册串口 /// </summary> /// <param name="portName"></param> /// <param name="baudRate"></param> public void RegisterSerialPort(string portName, int baudRate) { // 串口名 _serialPort.PortName = portName; // 波特率 _serialPort.BaudRate = baudRate; // 数据位 _serialPort.DataBits = 8; // 停止位 _serialPort.StopBits = StopBits.One; // 无奇偶校验位 _serialPort.Parity = Parity.None; } private void _serialPort_DataReceived(object senderd, SerialDataReceivedEventArgs e) { //等待100ms 防止读取不全的情况 Thread.Sleep(100); byte[] m_recvBytes = new byte[_serialPort.BytesToRead]; //获取接受缓冲区的字节数 定义缓冲区的大小 int result = _serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);//从串口读取数据 返回读取的字节数 if (result <= 0) { return; } //将字节转换成字符串 //string strResult = Encoding.ASCII.GetString(m_recvBytes); string strResult = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length); //string strResult = Encoding.UTF8..GetString(); _serialPort.DiscardInBuffer(); this.Invoke((EventHandler)(delegate { txtCK.Text = strResult; })); } private void Form1_Load(object sender, EventArgs e) {
            //参数1:串口(端口)号名称 参数2:波特率 setPort(
    "COM14", 9600); } } }

    下面这个是使用SerialPort控件写的  省略了注册串口的那个方法

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO.Ports;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace 串口Dome
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
            public static SerialPort serialPort = new SerialPort();
            public void setPort()
            {
                if (serialPort.IsOpen==false)
                {
                    serialPort.Open();
                }
                serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
            }
    
            private  void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                //防止读取不全的情况 等待100ms
                Thread.Sleep(100);
                byte[] m_recvBytes = new byte[serialPort.BytesToRead];//获取缓冲区的的字节数
                int reslut = serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);
                if (reslut <= 0)
                {
                    return;
                }
                string strResult = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length);//转换成字符串格式的
    
                serialPort.DiscardInBuffer();
    
                this.Invoke((EventHandler)(delegate
                {
                    TxtCode.Text = strResult;
                }));
    
    
            }
            private void Form2_Load(object sender, EventArgs e)
            {
                var str = BarCode.PortName;
                int num = BarCode.BaudRate;
           setPort() MessageBox.Show(
    "Name:" + str + " " + "波特率" + num); } } }

    后期有更好的理解和写法在补充上去

    增加一个使用正则表达来转换条码  代码量少

    同第二个方法一样  使用SerialPort控件  在控件属性中修改对应的COM名称和波特率

     接下来就是代码部分

     public void OpenSbar()
            {
                if (serialPort1.IsOpen == false)
                {
                    serialPort1.Open();
                }
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(SBar_DataReceived);
            }
    
            private void SBar_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                this.labelCode.Text = "等待中...";
                Thread.Sleep(150);
                string str_Buff = serialPort1.ReadExisting();
                str_Buff = System.Text.RegularExpressions.Regex.Replace(str_Buff, @"[^0-9a-zA-Z]+", "");
           //Code获取到的条码
                string Code = str_Buff.Trim();
            }    
  • 相关阅读:
    洛谷—— P1196 银河英雄传说
    MySQL练习题参考答案
    January 16 2017 Week 3 Monday
    January 15 2017 Week 3 Sunday
    January 14 2017 Week 2nd Saturday
    January 13 2017 Week 2 Friday
    January 12 2017 Week 2 Thursday
    January 11 2017 Week 2nd Wednesday
    January 10 2017 Week 2nd Tuesday
    January 09 2017 Week 2nd Monday
  • 原文地址:https://www.cnblogs.com/xunmengrenli/p/13504478.html
Copyright © 2020-2023  润新知