C# 如何操作串口

1.首先要引用  System.IO.Ports

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;

namespace FrmScanProt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //APICloud  //app

        string text = "";
        SerialPort sp = new SerialPort();

        delegate void UpdateTextEventHandler(string text);  //委托,此为重点.
        UpdateTextEventHandler updateText;  //事件


        private void Form1_Load(object sender, EventArgs e)
        {
            AddParameters();


            string[] itemName = SerialPort.GetPortNames();  //获取当前计算机串型端口名称数组.
            cboPortName.Items.Clear();
            foreach (var item in itemName)
            {
                cboPortName.Items.Add(item);
            }

            cboPortName.SelectedIndex = 0;
            cboBaudRate.SelectedIndex = 1;
            cboDataBit.SelectedIndex = 3;
            cboParityBit.SelectedIndex = 0;
            cboStopBit.SelectedIndex = 1;

            updateText += new UpdateTextEventHandler(UpdateTextBox);    //委托方法
            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //处理串口对象的数据接收事件的方法.

            sp.Close();
            lblScan.Text = "未开启采集程序.";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtCode.Text != "")
            {
                listBox1.Items.Add(txtCode.Text);
                txtCode.Text = "";
                txtCode.Focus();
            }
            else { MessageBox.Show(" 条码不能为空!"); txtCode.Focus(); }
        }

        private void btnStartScan_Click(object sender, EventArgs e)
        {
            if (!sp.IsOpen)
            {
                sp.Open();  //打开一个新的串口连接.
                lblScan.Text = "采集中...";
                txtCode.Focus();
            }
        }

        private void btnEndScan_Click(object sender, EventArgs e)
        {
            if (sp.IsOpen)
            {
                sp.Close(); //关闭一个串口连接.
                lblScan.Text = "采集结束.";
                txtCode.Focus();
            }
        }

        /// <summary>
        /// 串口名称
        /// </summary>
        private void cboPortName_SelectedIndexChanged(object sender, EventArgs e)
        {
            sp.PortName = cboPortName.Items[cboPortName.SelectedIndex].ToString();
        }

        /// <summary>
        /// 波特率(每秒传送字节数)
        /// </summary>
        private void cboBaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {
            //获取或设置串口波特率
            // cboBaudRate.Items.Add(sp.BaudRate);
            sp.BaudRate = Convert.ToInt32(cboBaudRate.Items[cboBaudRate.SelectedIndex].ToString());

        }
        /// <summary>
        /// 数据字节
        /// </summary>
        private void cboDataBit_SelectedIndexChanged(object sender, EventArgs e)
        {
            //设置每个字节的标准数据长度
            sp.DataBits = Convert.ToInt32(cboDataBit.Items[cboDataBit.SelectedIndex].ToString());
        }
        /// <summary>
        /// 停止位置
        /// </summary>
        private void cboStopBit_SelectedIndexChanged(object sender, EventArgs e)
        {
            //设置每个字节的标准停止位数
            sp.StopBits =(StopBits)cboStopBit.SelectedIndex;
        }
        /// <summary>
        /// 奇偶位置
        /// </summary>
        private void cboParityBit_SelectedIndexChanged(object sender, EventArgs e)
        {
            //设置奇偶校验检查协议
           // sp.Parity = Parity.Odd;
            sp.Parity = (Parity)System.Enum.Parse(typeof(Parity), cboParityBit.SelectedIndex.ToString());
        }
        /// <summary>
        /// 接收到的数据
        /// </summary>
        private void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if(!sp.IsOpen)
            {
                MessageBox.Show("请先启用扫描枪采集...");
                Thread.Sleep(2000);
                this.Close();
                return;
            }

            Thread.Sleep(100);
            byte[] buffer = Encoding.UTF8.GetBytes(sp.ReadExisting());
            string newString = Encoding.UTF8.GetString(buffer);

            //string readString = sp.ReadExisting();//读取串口对象的流和输入缓冲区所有立即可用的字节流.

            this.Invoke(updateText, new string[] { newString });   //控件基础句柄的线程上,执行委托.
        }

        /// <summary>
        /// 获取数据.
        /// </summary>
        private void UpdateTextBox(string text)
        {
            this.txtCode.Text = text;
            listBox1.Items.Add(txtCode.Text);
            txtCode.Text = "";
        }


        private void AddParameters()
        {
            this.cboBaudRate.Items.AddRange(new object[] { "4800", "9600", "14400", "19200", "38400", "56000", "57600", "115200", "128000" });

            this.cboDataBit.Items.AddRange(new object[] { "5", "6", "7", "8" });

            this.cboStopBit.Items.AddRange(new object[] { "0.5", "1", "1.5", "2" });

            this.cboParityBit.Items.AddRange(new object[]{"none","odd","even"});
        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }
    }
}

 

 

转载于:https://www.cnblogs.com/bmyblogs/p/6509981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值