C#:通过串口读取扫描枪里的值

Posted WeAreZero

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;

namespace COM_TEST

    public partial class Form1 : Form
    
        CommBar commBar;

        bool buttonBool = false;//指示按钮是开还是关

        public Form1()
        
            InitializeComponent();
            commBar = new CommBar();
            CheckForIllegalCrossThreadCalls = false;
        

        private void Form1_Load(object sender, EventArgs e)
        
            this.comboBox_Com.Items.Clear();
            this.comboBox_Com.Items.Add("请选择COM口");
            string[] comNames = commBar.GetComName();
            for (int i = 0; i < comNames.Length; i++)
            
                this.comboBox_Com.Items.Add(comNames[i]);
            
            this.comboBox_Com.SelectedIndex = 0;
        

        private void button_Test_Click(object sender, EventArgs e)
        
            //关闭
            if (buttonBool)
            
                buttonBool = false;

                commBar.Close();
                this.button_Test.Text = "点击测试";
            
                //开始
            else if (!buttonBool)
            
                buttonBool = true;
                this.button_Test.Text = "正在测试……";

                //注册一该串口
                commBar.SerialPortValue(this.comboBox_Com.Text, Convert.ToInt32(this.comboBox_comPl.Text));
                //打开串口
                if (commBar.Open())
                    //关联事件处理程序
                    commBar.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
            
        

        //用来为文本框赋值
        private void CodeText(CommBar commBar)
        
            this.textBox_TestTxt.Text = "";
            this.textBox_TestTxt.Text = commBar.Code;
        

        //委托,指向CodeText方法
        private delegate void ModifyButton_dg(CommBar commBar);

        //串口接收接收事件处理程序
        //每当串口讲到数据后激发
        void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        
            System.Threading.Thread.Sleep(100);
            byte[] m_recvBytes = new byte[commBar.serialPort.BytesToRead];//定义缓冲区大小
            int result = commBar.serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);//从串口读取数据
            if (result <= 0)
                return;
            commBar.Code = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length);//对数据进行转换
            this.Invoke(new ModifyButton_dg(CodeText), commBar);//调用委托,将值传给文本框
            commBar.serialPort.DiscardInBuffer();
        

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        
            commBar.Close();
            commBar.serialPort.Dispose();
        
    

扫描枪工作类代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace COM_TEST

    /// <summary>
    /// 扫描枪工作类
    /// </summary>
    class CommBar
    
        //串口引用
        public SerialPort serialPort;

        //存储转换的数据值
        public string Code  get; set; 

        public CommBar()
        
            serialPort = new SerialPort();
        

        //串口状态
        public bool IsOpen
        
            get
            
                return serialPort.IsOpen;
            
        

        //打开串口
        public bool Open()
        
            if (serialPort.IsOpen)
            
                Close();
            
            serialPort.Open();
            if (serialPort.IsOpen)
            
                return true;
            
            else
            
                MessageBox.Show("串口打开失败!");
                return false;
            
        

        //关闭串口
        public void Close()
        
            serialPort.Close();
        

        //定入数据,这里没有用到
        public void WritePort(byte[] send, int offSet, int count)
        
            if (IsOpen)
            
                serialPort.Write(send, offSet, count);
            
        

        //获取可用串口
        public string[] GetComName()
        
            string[] names = null;
            try
            
                names = SerialPort.GetPortNames(); // 获取所有可用串口的名字
            
            catch (Exception)
            
                System.Windows.Forms.MessageBox.Show("找不到串口");
            
            return names;
        

        //注册一个串口
        public void SerialPortValue(string portName, int baudRate)
        
            //串口名
            serialPort.PortName = portName;
            //波特率
            serialPort.BaudRate = baudRate;
            //数据位
            serialPort.DataBits = 8;
            //两个停止位
            serialPort.StopBits = System.IO.Ports.StopBits.One;
            //无奇偶校验位
            serialPort.Parity = System.IO.Ports.Parity.None;
            serialPort.ReadTimeout = 100;
            //commBar.serialPort.WriteTimeout = -1;
        
    

以上是关于C#:通过串口读取扫描枪里的值的主要内容,如果未能解决你的问题,请参考以下文章

windows下怎么用C语言读取串口里的数据?

C# 串口导致电脑蓝屏一个可能的原因

C#定期从串口读取新行

C# 学习笔记(13)自己的串口助手

C# Winform 串口问题

c#从串口读取数据怎样读一个就清空缓存