【SerialPort】控件的使用实例

14 篇文章 1 订阅
2 篇文章 0 订阅

以下是【SerialPort】控件的使用实例,发送端和接收端代码除了端口号(例:“COM9”)不同,其他都一样:

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;

namespace Test_Serialport_串口控件_
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SerialPort port1;
        string strCom = "COM9";

        private delegate void ShowDelegate(string strshow);

        private void Form1_Load(object sender, EventArgs e)
        {
            //我现在用的COM1端口,按需要可改成COM2,COM3
            InitCOM(strCom);
            OpenPort();
            //this.txtReceive.InvokeRequired = true;
        }

        //初始化SerialPort对象方法.PortName为COM口名称,例如"COM1","COM2"等,注意是string类型
        public void InitCOM(string PortName)
        {
            port1 = new SerialPort(PortName);
            port1.BaudRate = 9600;//波特率
            port1.Parity = Parity.None;//无奇偶校验位
            port1.StopBits = StopBits.Two;//两个停止位
            port1.Handshake = Handshake.RequestToSend;//控制协议
            port1.ReceivedBytesThreshold = 1;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数
            port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);//DataReceived事件委托
        }

        //DataReceived事件委托方法
        private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                StringBuilder currentline = new StringBuilder();
                //循环接收数据
                while (port1.BytesToRead > 0)
                {
                    char ch = (char)port1.ReadByte();
                    currentline.Append(ch);
                }
                //在这里对接收到的数据进行处理
                ShowTxt(currentline.ToString());
                //this.txtReceive.Text = currentline.ToString();
                //
                currentline = new StringBuilder();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }

        public void ShowTxt(string strShow)
        {

            if (this.txtReceive.InvokeRequired)
            {
                //   this.txtreceive.BeginInvoke(new ShowDelegate(Show), strshow);//这个也可以
                this.txtReceive.Invoke(new ShowDelegate(ShowTxt), strShow);
            }
            else
            {
                this.txtReceive.Text = strShow;

            }
        }

        //打开串口的方法
        public void OpenPort()
        {
            try
            {
                port1.Open();
                if (port1.IsOpen)
                {
                    Console.WriteLine("the port is opened!");
                    this.labStat.Text = strCom + " 已连接!";
                }
                else
                {
                    Console.WriteLine("failure to open the port!");
                    this.labStat.Text = "连接失败!";
                }
            }
            catch { }
        }

        //关闭串口的方法
        public void ClosePort()
        {
            port1.Close();
            if (!port1.IsOpen)
            {
                Console.WriteLine("the port is already closed!");
            }
        }

        //向串口发送数据
        public void SendCommand(string CommandString)
        {
            byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
            port1.Write(WriteBuffer, 0, WriteBuffer.Length);
        }

        //调用实例
        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = this.txtSend.Text;
            SendCommand(str);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            labTime.Text = "当前时间是:" + DateTime.Now.ToLongTimeString();
        }
    }
}


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SerialPort控件是一种用于在计算机中控制串口通信的组件。它提供了一系列方法和属性,让开发者能够方便地与串口进行通信。 首先,使用SerialPort控件前,我们需要在项目中添加对该控件的引用。通过在代码中使用"using System.IO.Ports;"语句,我们可以引用SerialPort命名空间,以便在代码中使用SerialPort控件。 接下来,我们可以实例化一个SerialPort对象,通过设置该对象的属性来配置串口通信的相关参数。例如,我们可以通过设置PortName属性指定要使用的串口号,如"COM1"或"COM2"等;通过设置BaudRate属性指定波特率,如9600;通过设置Parity属性指定校验位,如None,Even,Odd等;通过设置DataBits属性指定数据位,如8;通过设置StopBits属性指定停止位,如One,Two等。 配置完SerialPort对象后,我们可以通过调用Open()方法打开串口。然后,我们可以使用Write()方法向串口发送数据,使用Read()方法接收从串口接收到的数据。我们也可以使用其他方法来读取和写入不同格式的数据,如ReadByte()和WriteByte()用于读写字节数据,ReadTo()和WriteLine()用于读写字符串数据等。 在串口通信过程中,可能会出现一些错误,SerialPort控件提供了一些事件,如DataReceived和ErrorReceived事件,我们可以通过监听这些事件来处理错误和接收到的数据。 最后,当我们不再需要使用串口时,需要调用Close()方法来关闭串口,避免资源的浪费。 总的来说,SerialPort控件提供了一种便捷的方式来进行串口通信。通过配置控件的属性和调用相应的方法,开发者可以实现与其他串口设备的通信。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值