SerialPort串口通信

  使用串口线,将两台计算机、或将计算机与设备连接后。便可通过串口,进行通信。

串口通信,实现串口数据的发送和接收即可。

因为只有一台计算机,我们使用虚拟串口模拟软件,将COM1和COM2两个串口连接(替代串口线的连接)。

 通过这两个串口进行通信。

SerialPort.exe下载 

 

 源码:

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.Windows.Forms;

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

        SerialPort port;

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 1; i < 256; i++)
            {
                comboBox1.Items.Add("COM" + i);
            }
            comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// 打开指定的串口
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                if (port == null)
                {
                    port = new SerialPort(comboBox1.Text, 115200, Parity.Even, 8, StopBits.One);
                    port.RtsEnable = true;  // 启用请求发送(RTS)信号
                    port.DtrEnable = true;  // 启用数据终端就绪(DTR)信息
                    port.ReadTimeout = 3000;

                    port.DataReceived += port_DataReceived; // 添加数据接收处理逻辑
                }

                if (!port.IsOpen)
                {
                    port.Open();

                    button1.Enabled = false;
                    button3.Enabled = true;
                }
            }
            catch (Exception)
            {
                port = null;
                MessageBox.Show("串口" + comboBox1.Text + "可能已占用,请选择其它端口!");
            }
        }

        /// <summary>
        /// 关闭对应的串口
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            if (port != null && port.IsOpen)
            {
                port.Close();

                button1.Enabled = true;
                button3.Enabled = false;

                port = null;
            }
        }

        public delegate void ShowTextD(string content);
        public event ShowTextD ShowTextI;

        /// <summary>
        /// 输出显示发送或接收的数据
        /// </summary>
        private void ShowText(string content)
        {
            textBox1.Text += "\r\n" + content;
            textBox1.ScrollToCaret();
        }

        /// <summary>
        /// 串口数据接收处理逻辑
        /// </summary>
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //string content = "[接收]" + port.ReadExisting();

            int len = port.BytesToRead;
            byte[] buf = new byte[len];
            port.Read(buf, 0, len);
            string content = "[接收] " + Encoding.Default.GetString(buf);

            if (ShowTextI == null) ShowTextI = ShowText;
            this.Invoke(ShowTextI, content);
            //throw new NotImplementedException();
        }

        /// <summary>
        /// 发送数据
        private void button2_Click(object sender, EventArgs e)
        {
            if (port != null && port.IsOpen)
            {
                String content = textBox2.Text;
                if (!String.IsNullOrEmpty(content))
                {
                    //port.Write(content);
                    byte[] data = Encoding.Default.GetBytes(content);
                    port.Write(data, 0, data.Length);

                    ShowText("[发送] " + content);

                    textBox2.Text = "";
                }
            }
        }

    }
}
namespace SerialPortDemo
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.button2 = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(183, 22);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "打开";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(56, 24);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(122, 20);
            this.comboBox1.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(9, 27);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(41, 12);
            this.label1.TabIndex = 2;
            this.label1.Text = "串口:";
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(15, 183);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox1.Size = new System.Drawing.Size(324, 186);
            this.textBox1.TabIndex = 3;
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(11, 80);
            this.textBox2.Multiline = true;
            this.textBox2.Name = "textBox2";
            this.textBox2.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox2.Size = new System.Drawing.Size(247, 64);
            this.textBox2.TabIndex = 4;
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(264, 90);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 43);
            this.button2.TabIndex = 5;
            this.button2.Text = "发送";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(9, 65);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(77, 12);
            this.label2.TabIndex = 6;
            this.label2.Text = "待发送数据:";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(13, 168);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(65, 12);
            this.label3.TabIndex = 7;
            this.label3.Text = "接收数据:";
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(264, 22);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 23);
            this.button3.TabIndex = 8;
            this.button3.Text = "关闭";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(353, 381);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.comboBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "SerialPort(串口通信)";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button button3;
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C++ 中可以通过 SerialPort 类来实现串口通信SerialPort 类封装了串口的基本操作,如打开/关闭串口、设置串口参数、读/写数据等。 以下是一个简单的 SerialPort 类的实现,支持 Windows 和 Linux 平台: ``` #include <iostream> #include <cstring> #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #include <fcntl.h> #include <termios.h> #endif class SerialPort { public: SerialPort(const char* portName, int baudRate) : fd(-1) { #ifdef _WIN32 // 打开串口 fd = CreateFileA(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { std::cerr << "Failed to open serial port " << portName << std::endl; return; } // 配置串口 DCB dcbSerialParams = { 0 }; dcbSerialParams.DCBlength = sizeof(dcbSerialParams); if (!GetCommState(fd, &dcbSerialParams)) { std::cerr << "Failed to get serial parameters" << std::endl; CloseHandle(fd); fd = -1; return; } dcbSerialParams.BaudRate = baudRate; dcbSerialParams.ByteSize = 8; dcbSerialParams.StopBits = ONESTOPBIT; dcbSerialParams.Parity = NOPARITY; if (!SetCommState(fd, &dcbSerialParams)) { std::cerr << "Failed to set serial parameters" << std::endl; CloseHandle(fd); fd = -1; return; } // 配置超时 COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = 50; timeouts.ReadTotalTimeoutConstant = 50; timeouts.ReadTotalTimeoutMultiplier = 10; timeouts.WriteTotalTimeoutConstant = 50; timeouts.WriteTotalTimeoutMultiplier = 10; if (!SetCommTimeouts(fd, &timeouts)) { std::cerr << "Failed to set serial timeouts" << std::endl; CloseHandle(fd); fd = -1; return; } #else // 打开串口 fd = open(portName, O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { std::cerr << "Failed to open serial port " << portName << std::endl; return; } // 配置串口 struct termios options = { 0 }; tcgetattr(fd, &options); cfsetispeed(&options, baudRate); cfsetospeed(&options, baudRate); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_cflag &= ~CRTSCTS; options.c_iflag &= ~(IXON | IXOFF | IXANY); options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_oflag &= ~OPOST; tcsetattr(fd, TCSANOW, &options); tcflush(fd, TCIOFLUSH); #endif } ~SerialPort() { if ( C++ 中有一个标准库,叫做 asio,它可以提供串口通信类。当使用C++编写串口通信时,可以使用SerialPort类来管理串口通信。该类提供了一组用于打开、关闭、读取和写入串口数据的方法。下面是一个使用SerialPort类的示例: ```cpp #include <iostream> #include <SerialPort.h> int main() { SerialPort port("COM1", 9600); // 打开COM1端口,波特率为9600 if (!port.isOpen()) { std::cout << "Failed to open port" << std::endl; return 1; } char data[10] = "Hello"; port.write(data, sizeof(data)); // 向串口写入数据 char buffer[256]; int bytesRead = port.read(buffer, sizeof(buffer)); // 从串口读取数据 if (bytesRead > 0) { buffer[bytesRead] = '\0'; // 将读取的数据添加字符串结束符 std::cout << "Received: " << buffer << std::endl; } port.close(); // 关闭串口 return 0; } ``` 在上述示例中,SerialPort类的构造函数用于打开指定的串口。打开串口后,可以使用write()方法向串口写入数据,并使用read()方法从串口读取数据。在完成通信后,需要使用close()方法关闭串口。 ### 回答2: c serialport是一种用于串口通信的C++类库。通过这个类库,可以以一种简单而方便的方式实现串口通信功能。c serialport在使用过程中需要用到串口类的对象,这个对象需要传入串口的名称和波特率,同时支持处理串口的各种事件。 c serialport支持的串口通信协议包括RS232、RS422、RS485等,同时支持各种操作系统平台,包括Windows、Linux、Unix等。这样一来,开发者可以快速地将c serialport集成到自己的开发项目中,而不必去考虑平台兼容性和通信协议的问题。 在使用c serialport进行串口通信时,需要注意以下几个方面: 1. 串口通信的波特率需要和接收端的波特率保持一致,否则无法正常通信。 2. 需要对串口通信进行错误处理,避免通信过程中出现异常情况,导致程序异常终止。 3. 需要使用事件处理机制,及时处理串口通信过程中产生的各种事件,以保证正常的通信流程。 总之,c serialport是一种非常实用的串口通信类库,可以非常方便地实现串口通信的功能。但是需要在使用过程中仔细处理各种异常情况,确保程序的正常运行。 ### 回答3: c serialport 是用于在 C 语言中进行串口通信的类。串口通信是一种在计算机和其他设备之间进行通信的方式,其中发送和接收的数据以串行方式进行传输。这种通信方式常用于与MCUs(单片机)和其他外部设备进行通信。 c serialport 可以与多个串口通信设备进行通信,并支持不同的数据位、校验位和停止位的设置,以确保通信的稳定性和可靠性。它可以与 Windows 和 Linux 操作系统上的串行端口通信。 c serialport 可以通过建立连接、发送和接收数据等方法来与串口通信设备进行通信。使用这个类需要先创建一个串口通信对象,然后打开和关闭串口,设置串口通信的参数,最后通过调用发送和接收数据方法进行数据交换。 c serialport 是一个在 C 语言中非常方便的串口通信库,它可以帮助开发者快速地进行串口通信的开发,并且支持多种平台以及多个串口设备。它为计算机和外部设备之间的通信提供了一种快捷实用和简单易用的解决方案。它在不同的应用场景中都有广泛的应用,如自动化系统、机器人等等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值