串口通信学习,使用winform读取串口发送数据,(2)

C# Windows Forms SerialPort 串口通信使用方法 / 实例化 SerialPort1 对象。1.导入命名空间:using System.IO.Ports;// 打开串口 serialPort1.Open();// 关闭串口 serialPort1.Close();// 注册 ErrorReceived 事件处理程序。// ErrorReceived 事件处理程序。// 处理接收到的数据。 阅读详情

串口通信学习,使用 WinForm 读取串口发送数据(2)

使用winform去实现最简单的数据发送与接收,获取串口之后点击连接串口,进行串口连接,在后续会显示连接的状态。串口的配置使用代码中写死的配置:

        #region 串口配置常量
        /// <summary>
        /// 波特率(默认9600)
        /// </summary>
        private readonly int BaudRate = 9600;

        /// <summary>
        /// 校验位(默认无)
        /// </summary>
        private readonly Parity Parity = Parity.None;

        /// <summary>
        /// 数据位(默认8)
        /// </summary>
        private readonly int DataBits = 8;

        /// <summary>
        /// 停止位(默认1)
        /// </summary>
        private readonly StopBits StopBits = StopBits.One;

        #endregion

串口的名称使用: private SerialPort _serialPort; // 串口通信对象 ,用户可以发送可以使用“字符串”或“十六进制”格式发送数据,同时自动接收并显示来自串口的数据。用户使用发送数据的时候会以相同的发送方式去解析,比如发送十六进制数据的时候会以十六进制的方式去解析。
可以使用方向键去使用历史命令,类似命令行,使用方向键的上下去查询历史命令。

使用方式

打开程序选择串口

连接上串口了
在这里插入图片描述

发送与接收数据
在这里插入图片描述

在这里插入图片描述

可以使用方向键去控制命令的上下行,按下Enter去发送消息。
在这里插入图片描述

代码

私有字段与配置常量

首先定义串口通信所需的私有字段和默认配置参数:
命名空间

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

#region 私有字段
private SerialPort _serialPort;               // 串口通信对象
private bool _isConnected;                    // 串口连接状态标识
private string _selectedPortName;             // 当前选中的串口号

// 命令历史记录相关
private List<string> _commandHistory;         // 存储发送过的命令历史
private int _historyIndex;                    // 当前选中的历史命令索引
#endregion

#region 串口配置常量
/// <summary>
/// 波特率(默认9600)
/// </summary>
private readonly int BaudRate = 9600;

/// <summary>
/// 校验位(默认无)
/// </summary>
private readonly Parity Parity = Parity.None;

/// <summary>
/// 数据位(默认8)
/// </summary>
private readonly int DataBits = 8;

/// <summary>
/// 停止位(默认1)
/// </summary>
private readonly StopBits StopBits = StopBits.One;
#endregion

构造函数与初始化方法

窗体加载时完成组件初始化、端口列表刷新及串口对象创建:

#region 构造函数
/// <summary>
/// 初始化窗体及串口相关组件
/// </summary>
public Form1()
{
    InitializeComponent();
    RefreshPortList();
    InitializeSerialPort();
    InitSendFormatComboBox();
    UpdateControlStatus();

    // 初始化命令历史记录
    _commandHistory = new List<string>();
    _historyIndex = -1;
}
#endregion

#region 初始化方法
/// <summary>
/// 初始化发送格式下拉框
/// </summary>
private void InitSendFormatComboBox()
{
    comboBoxSendFormat.Items.Add(new ComboBoxItem("十六进制", SendDataFormat.Hex));
    comboBoxSendFormat.Items.Add(new ComboBoxItem("字符串", SendDataFormat.String));
    comboBoxSendFormat.DisplayMember = "DisplayName";
    comboBoxSendFormat.ValueMember = "Value";
    comboBoxSendFormat.SelectedIndex = 0;
}

/// <summary>
/// 刷新串口列表
/// </summary>
private void RefreshPortList()
{
    string currentSelectedPort = comboBoxPorts.SelectedItem?.ToString();
    string[] availablePorts = SerialPort.GetPortNames();
    var sortedPorts = availablePorts.OrderBy(port =>
    {
        if (int.TryParse(port.Replace("COM", ""), out int portNumber))
        {
            return portNumber;
        }
        return 0;
    }).ToArray();

    comboBoxPorts.Items.Clear();
    comboBoxPorts.Items.AddRange(sortedPorts);

    if (comboBoxPorts.Items.Count > 0)
    {
        comboBoxPorts.SelectedItem = !string.IsNullOrEmpty(currentSelectedPort)
            && comboBoxPorts.Items.Contains(currentSelectedPort)
            ? currentSelectedPort
            : comboBoxPorts.Items[0];
    }
}

/// <summary>
/// 初始化串口对象并注册数据接收事件
/// </summary>
private void InitializeSerialPort()
{
    _serialPort = new SerialPort
    {
        BaudRate = this.BaudRate,
        Parity = this.Parity,
        DataBits = this.DataBits,
        StopBits = this.StopBits,
        Encoding = Encoding.Default
    };
    _serialPort.DataReceived += SerialPort_DataReceived;
}
#endregion

串口通信核心逻辑

包括连接、断开、数据接收与发送等关键操作:

#region 串口通信
/// <summary>
/// 串口数据接收事件处理方法
/// </summary>
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        if (_serialPort.IsOpen && _serialPort.BytesToRead > 0)
        {
            int byteCount = _serialPort.BytesToRead;
            byte[] receiveBuffer = new byte[byteCount];
            _serialPort.Read(receiveBuffer, 0, byteCount);

            SendDataFormat currentFormat = SendDataFormat.Hex;
            this.Invoke(new Action(() =>
            {
                currentFormat = ((ComboBoxItem)comboBoxSendFormat.SelectedItem).Value;
            }));

            string displayContent = ParseReceiveData(receiveBuffer, currentFormat);
            string formatName = GetFormatFriendlyName(currentFormat);

            this.Invoke(new Action(() =>
            {
                AppendColoredLog($"[接收({formatName})] {displayContent}\r\n");
            }));
        }
    }
    catch (Exception ex)
    {
        this.Invoke(new Action(() =>
        {
            AppendColoredLog($"[错误] {ex.Message}\r\n");
        }));
    }
}

/// <summary>
/// 连接串口
/// </summary>
private void ConnectSerialPort()
{
    try
    {
        if (comboBoxPorts.SelectedItem == null)
        {
            AppendColoredLog("未选择可用串口\r\n");
            return;
        }

        if (!_serialPort.IsOpen)
        {
            _selectedPortName = comboBoxPorts.SelectedItem.ToString();
            _serialPort.PortName = _selectedPortName;
            _serialPort.Open();
            _isConnected = true;
            UpdateControlStatus();
            AppendColoredLog($"串口 {_selectedPortName} 连接成功!\r\n");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"串口连接失败: {ex.Message}", "错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

/// <summary>
/// 断开串口连接
/// </summary>
private void DisconnectSerialPort()
{
    try
    {
        if (_serialPort.IsOpen)
        {
            _serialPort.Close();
            _isConnected = false;
            UpdateControlStatus();
            AppendColoredLog("串口已断开连接\r\n");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"串口断开失败: {ex.Message}", "错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

/// <summary>
/// 发送数据到串口
/// </summary>
private void SendSerialData()
{
    if (!_isConnected || !_serialPort.IsOpen)
    {
        MessageBox.Show("请先连接串口!", "提示",
            MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    string inputContent = txtMessage.Text.Trim();
    if (string.IsNullOrEmpty(inputContent))
    {
        MessageBox.Show("请输入要发送的数据!", "提示",
            MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    try
    {
        SendDataFormat sendFormat = ((ComboBoxItem)comboBoxSendFormat.SelectedItem).Value;
        byte[] sendData = ProcessSendData(inputContent, sendFormat);

        _serialPort.Write(sendData, 0, sendData.Length);

        string formatName = GetFormatFriendlyName(sendFormat);
        string displayContent = sendFormat == SendDataFormat.Hex
            ? BytesToHexString(sendData)
            : inputContent;
        AppendColoredLog($"[发送({formatName})] {displayContent}\r\n");

        if (!_commandHistory.Contains(inputContent))
        {
            _commandHistory.Add(inputContent);
        }
        _historyIndex = _commandHistory.Count;

        txtMessage.Clear();
        txtMessage.Focus();
    }
    catch (FormatException ex)
    {
        MessageBox.Show($"数据格式错误:{ex.Message}\n示例:十六进制(01 0A FF 或 0x110x22) | 字符串(测试数据)",
            "格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    catch (ArgumentException ex)
    {
        MessageBox.Show($"参数错误:{ex.Message}", "输入错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    catch (Exception ex)
    {
        MessageBox.Show($"数据发送失败:{ex.Message}", "错误",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
#endregion

数据处理辅助方法

用于格式转换、解析与校验:

#region 数据处理辅助方法
/// <summary>
/// 解析接收到的字节数据
/// </summary>
private string ParseReceiveData(byte[] dataBytes, SendDataFormat format)
{
    if (dataBytes == null || dataBytes.Length == 0) return string.Empty;

    if (format == SendDataFormat.Hex)
    {
        return BytesToHexString(dataBytes);
    }
    else if (format == SendDataFormat.String)
    {
        return Encoding.UTF8.GetString(dataBytes);
    }
    else
    {
        return BytesToHexString(dataBytes);
    }
}

/// <summary>
/// 处理待发送的数据
/// </summary>
private byte[] ProcessSendData(string input, SendDataFormat format)
{
    if (format == SendDataFormat.Hex)
    {
        return HexStringToBytes(input);
    }
    else if (format == SendDataFormat.String)
    {
        return Encoding.UTF8.GetBytes(input);
    }
    else
    {
        throw new ArgumentException("不支持的发送格式");
    }
}

/// <summary>
/// 字节数组转十六进制字符串
/// </summary>
private string BytesToHexString(byte[] bytes)
{
    if (bytes == null || bytes.Length == 0) return string.Empty;

    StringBuilder hexBuilder = new StringBuilder(bytes.Length * 3);
    foreach (byte b in bytes)
    {
        hexBuilder.AppendFormat("{0:X2} ", b);
    }
    return hexBuilder.ToString().Trim();
}

/// <summary>
/// 十六进制字符串转字节数组
/// </summary>
private byte[] HexStringToBytes(string hexString)
{
    string cleanHex = hexString.ToLower()
                                  .Replace("0x", "")
                                  .Replace(" ", "")
                                  .Replace("\r", "")
                                  .Replace("\n", "")
                                  .Replace("\t", "");

    if (cleanHex.Length % 2 != 0)
    {
        throw new ArgumentException("十六进制字符串长度必须为偶数");
    }

    if (!Regex.IsMatch(cleanHex, "^[0-9a-f]+$"))
    {
        throw new FormatException("包含非法字符,仅允许0-9、A-F、a-f、0x/0X、空格");
    }

    byte[] result = new byte[cleanHex.Length / 2];
    for (int i = 0; i < result.Length; i++)
    {
        string hexByte = cleanHex.Substring(i * 2, 2);
        result[i] = Convert.ToByte(hexByte, 16);
    }
    return result;
}

/// <summary>
/// 获取枚举对应的友好显示名称
/// </summary>
private string GetFormatFriendlyName(SendDataFormat format)
{
    if (format == SendDataFormat.Hex)
    {
        return "十六进制";
    }
    else if (format == SendDataFormat.String)
    {
        return "字符串";
    }
    else
    {
        return "十六进制";
    }
}
#endregion

UI 操作与事件处理

确保线程安全地更新界面,并响应用户交互:

#region UI操作辅助方法
/// <summary>
/// 安全追加带颜色的日志
/// </summary>
private void AppendColoredLog(string text)
{
    if (txtReceived.InvokeRequired)
    {
        txtReceived.Invoke(new Action<string>(AppendColoredLog), text);
    }
    else
    {
        txtReceived.SelectionStart = txtReceived.TextLength;
        txtReceived.SelectionLength = 0;
        txtReceived.AppendText(text);
        txtReceived.ScrollToCaret();
    }
}

/// <summary>
/// 更新控件状态
/// </summary>
private void UpdateControlStatus()
{
    if (InvokeRequired)
    {
        Invoke(new Action(UpdateControlStatus));
        return;
    }

    btnConnect.Text = _isConnected ? "断开串口" : "连接串口";
    btnSend.Enabled = _isConnected;
    txtMessage.Enabled = _isConnected;

    _selectedPortName = comboBoxPorts.SelectedItem?.ToString() ?? string.Empty;
    lblStatus.Text = _isConnected
        ? $"已连接: {_selectedPortName} ({BaudRate} bps)"
        : "未连接";
    lblStatus.ForeColor = _isConnected ? System.Drawing.Color.Green : System.Drawing.Color.Red;
}

/// <summary>
/// 处理上下方向键调取历史命令
/// </summary>
private void HandleHistoryKey(Keys keyCode)
{
    if (_commandHistory.Count == 0) return;

    if (keyCode == Keys.Up)
    {
        _historyIndex--;
        if (_historyIndex < 0) _historyIndex = 0;
    }
    else if (keyCode == Keys.Down)
    {
        _historyIndex++;
        if (_historyIndex >= _commandHistory.Count)
        {
            _historyIndex = _commandHistory.Count;
            txtMessage.Clear();
            return;
        }
    }

    if (_historyIndex >= 0 && _historyIndex < _commandHistory.Count)
    {
        txtMessage.Text = _commandHistory[_historyIndex];
        txtMessage.SelectionStart = txtMessage.TextLength;
    }
}
#endregion

#region 控件事件处理
private void btnConnect_Click(object sender, EventArgs e)
{
    if (!_isConnected)
    {
        ConnectSerialPort();
    }
    else
    {
        DisconnectSerialPort();
    }
}

private void btnSend_Click(object sender, EventArgs e)
{
    SendSerialData();
}

private void txtMessage_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
    {
        HandleHistoryKey(e.KeyCode);
        e.Handled = true;
        e.SuppressKeyPress = true;
        return;
    }

    if (e.KeyCode == Keys.Enter && _isConnected)
    {
        SendSerialData();
        e.Handled = true;
        e.SuppressKeyPress = true;
    }
}

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    _serialPort?.Close();
    _serialPort?.Dispose();
}
#endregion

自定义类型定义

最后是用于下拉框绑定和数据格式枚举的辅助类:

#region 发送和解析的数据类型
/// <summary>
/// 发送和解析的数据类型
/// </summary>
public class ComboBoxItem
{
    public string DisplayName { get; set; }
    public SendDataFormat Value { get; set; }

    public ComboBoxItem(string displayName, SendDataFormat value)
    {
        DisplayName = displayName;
        Value = value;
    }
}

/// <summary>
/// 串口发送/接收数据格式枚举
/// </summary>
public enum SendDataFormat
{
    /// <summary>
    /// 十六进制格式
    /// </summary>
    Hex,
    /// <summary>
    /// 字符串格式(UTF8编码)
    /// </summary>
    String
}
#endregion

设计器代码

在这里插入图片描述

using System.Windows.Forms;

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

        private TextBox txtMessage;
        private Button btnSend;
        private Button btnConnect;
        private TextBox txtReceived;
        private Label lblStatus;

        /// <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.txtMessage = new System.Windows.Forms.TextBox();
            this.btnSend = new System.Windows.Forms.Button();
            this.btnConnect = new System.Windows.Forms.Button();
            this.txtReceived = new System.Windows.Forms.TextBox();
            this.lblStatus = new System.Windows.Forms.Label();
            this.comboBoxPorts = new System.Windows.Forms.ComboBox();
            this.comboBoxSendFormat = new System.Windows.Forms.ComboBox();
            this.SuspendLayout();
            // 
            // txtMessage
            // 
            this.txtMessage.Location = new System.Drawing.Point(138, 351);
            this.txtMessage.Name = "txtMessage";
            this.txtMessage.Size = new System.Drawing.Size(307, 21);
            this.txtMessage.TabIndex = 0;
            this.txtMessage.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtMessage_KeyDown);
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(455, 351);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(100, 21);
            this.btnSend.TabIndex = 1;
            this.btnSend.Text = "发送";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // btnConnect
            // 
            this.btnConnect.Location = new System.Drawing.Point(138, 14);
            this.btnConnect.Name = "btnConnect";
            this.btnConnect.Size = new System.Drawing.Size(100, 30);
            this.btnConnect.TabIndex = 2;
            this.btnConnect.Text = "连接串口";
            this.btnConnect.UseVisualStyleBackColor = true;
            this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
            // 
            // txtReceived
            // 
            this.txtReceived.Location = new System.Drawing.Point(12, 50);
            this.txtReceived.Multiline = true;
            this.txtReceived.Name = "txtReceived";
            this.txtReceived.ReadOnly = true;
            this.txtReceived.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtReceived.Size = new System.Drawing.Size(543, 290);
            this.txtReceived.TabIndex = 3;
            // 
            // lblStatus
            // 
            this.lblStatus.Location = new System.Drawing.Point(244, 14);
            this.lblStatus.Name = "lblStatus";
            this.lblStatus.Size = new System.Drawing.Size(311, 30);
            this.lblStatus.TabIndex = 4;
            this.lblStatus.Text = "未连接";
            this.lblStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // comboBoxPorts
            // 
            this.comboBoxPorts.FormattingEnabled = true;
            this.comboBoxPorts.Location = new System.Drawing.Point(12, 18);
            this.comboBoxPorts.Name = "comboBoxPorts";
            this.comboBoxPorts.Size = new System.Drawing.Size(120, 20);
            this.comboBoxPorts.TabIndex = 5;
            // 
            // comboBoxSendFormat
            // 
            this.comboBoxSendFormat.FormattingEnabled = true;
            this.comboBoxSendFormat.Location = new System.Drawing.Point(12, 351);
            this.comboBoxSendFormat.Name = "comboBoxSendFormat";
            this.comboBoxSendFormat.Size = new System.Drawing.Size(120, 20);
            this.comboBoxSendFormat.TabIndex = 6;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(567, 382);
            this.Controls.Add(this.comboBoxSendFormat);
            this.Controls.Add(this.comboBoxPorts);
            this.Controls.Add(this.lblStatus);
            this.Controls.Add(this.txtReceived);
            this.Controls.Add(this.btnConnect);
            this.Controls.Add(this.btnSend);
            this.Controls.Add(this.txtMessage);
            this.Name = "Form1";
            this.Text = "串口通信工具";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private ComboBox comboBoxPorts;
        private ComboBox comboBoxSendFormat;
    }
}


c#(winform)通过串口读取并解析数据 1、工具选择 在开发过程中,有时会遇到通过串口读取地磅等数据,但是在真实的环境测试也不方便,这时使用虚拟串口工具就显得非常方便了,虚拟出两个串口,一个模拟发送数据,一个模拟接收数据。 虚拟串口工具:Configure Virtual Serial Port Driver 串口调试工具:Serial Port Utility 2、程序编写 2.1winform中使用串口就需要在左侧工... 阅读详情

相关推荐

基于C#实现串口通信Demo

基于C#实现串口通信Demo 1.基本概念 2.前端winForm布局如下(仅仅为了实现功能,布局略丑) 3.代码实现如下 namespace SerialPortTest { public partial class Form1 : Form { SerialPort sp1 = new SerialPort...

刘欢的博客 5459

用Winform实现串口通讯

检测串口按钮功能,点击检测按钮,会检测出串口号并加到串口号下拉框中,主要是通过SerialPort的GetNames方法获取串口号,放入集合中。实现数据接收,也是选择哪种编码方式来接收,并且要用异步委托一个线程,不然接收数据的时候会出现数据线程的错误。实现数据发送,在下拉框中选择以哪种编码方式去发送,以ASCII或者Hex方式发送数据。通过下拉框选择串口参数,打开串口,发送数据,接收数据。设置串口,在打开串口前,要设置完这些串口参数。在加载方法事件中调用上面这些初始化方法。

Beg_inner__的博客 2262

c#/winform 串口编程

winform串口编程方法

轻描漫写的专栏 1387

C# Winform编程 串口通信简单示例

【代码】C# 串口通信简单示例。

若有博文对您有帮助,欢迎点赞关注,收藏评论。 3772

2.3-使用C#Winform开发串口小助手开发步骤

一、界面设计 在做软件之前使用“软件界面设计工具”先设计并绘制出软件界面,方便在写代码之前确认“功能需求”以及“交互流程”。 这里使用的软件是:“Axure RP” 二、新建工程与绘制界面 新建工程: 使用任意一个Visual studio即可,这里使用Visual studio2017作为开发环境(安装的时候选择.net桌面开发)。新建工程选择“c# winform类型的工程,然后填写工程名...

Robert Zhang 2228

C#上位机从零搭建:WinForm串口通信→数据解析→曲线展示(保姆级教程)

打开 Form1.cs 代码视图(右键 Form1 设计视图 → 查看代码),在Form1// 串口对象(核心)// 存储解析后的数据(温度、湿度、压力)// 曲线数据点计数器(控制只显示最近100个点)// 初始化串口对象// 绑定串口数据接收事件(数据到达时触发)// 初始化曲线控件// 后续代码在此处添加...本教程从零搭建了一个功能完整的 WinForm 上位机,涵盖串口通信、数据解析、曲线展示三大核心模块,新手可通过拖拽控件、复制代码快速上手。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1356

winform使用串口通信读取压力传感装置(CFM)的数据

目的:获取CFM的 “hi” 报文,解析出如下数据并绘制波形图。实现:使用c#打开CFM串口,发送 02 00 02 4C 49 0D 请求到串口,CFM就会不断返回不同类型的报文,我解析的是 “hi” 报文(至于什么是 “hi” 报文,请看协议),这一步称为登录。接下来就是接收CFM发送过来的报文,然后处理。实现的核心就这两步,是不是很简单。效果如下。

NJJML的博客 1215

进阶09:Winform编写串口通信范例

本文介绍了基于C#的串口通信程序开发过程。首先配置虚拟串口环境,使用VSPD软件绑定COM1和COM2端口。然后通过VS2013新建Winform项目,设计包含串口参数设置、数据收发等功能的界面。程序实现了串口扫描、参数配置、数据收发(支持HEX/ASCII格式)等核心功能,采用SerialPort类处理串口通信,并通过事件委托实现异步数据接收。调试时,将程序与串口调试助手分别连接COM2和COM1,成功实现双向通信验证。该程序既可作为独立串口调试工具,也可集成到其他项目中应用。

weixin_38637405的博客 625

1小时搞定C# winForm串口通信

1小时搞定C# winForm串口通信 界面设计 事件处理 界面设计 本文参考https://blog.csdn.net/yc5300891/article/details/100522854 1、完成如下界面一共需要Lable、ComboBox、TextBox、Button四个普通组件,两个特殊组件,一个是SerialPort特殊控件,它是处理串口通信用的一个组件。另一个是Timer组件,这是个定时器组件。 新建C#项目,选择Windows窗体应用 默认创建一个空白窗体 你可以

大道至简 1万+

C# Winform串口通信应用详解

数据帧的定义依赖于通信双方的约定,以下是一个简单的数据帧定义示例:起始位(1 Byte)地址位(1 Byte)数据长度(1 Byte)数据内容(n Bytes)校验位(1 Byte)停止位(1 Byte)数据封装时,按照定义的格式将数据打包。这里展示了一个简单的方法,封装一个数据帧:// 假定地址位为0x01// 加上起始位、停止位和校验位// 构建数据帧// 起始位// 校验位// 停止位// 实现校验算法,例如简单的异或校验。

weixin_34581040的博客 1283

构建Winform和WPF下的串口通信与仪表显示应用

在WPF中,自定义控件是一种扩展和增强UI功能的强大方式。自定义控件是通过继承现有的控件类或从System.Windows.Controls.Control类派生,并重写其模板、行为和功能来创建的。自定义控件可以扩展控件的功能,提供更加专业化和定制化的用户体验。例如,实现一个仪表控件时,可以创建一个新的控件类,这个类可能继承自Control或者更专业的如MeterBase这样的基类。创建自定义控件通常包括以下几个步骤:定义控件的外观:使用XAML定义控件的视觉表现形式。

weixin_35903223的博客 933

C#实现简单的串口通信

前言 本着学习研究的态度,用c#语言实现简单的串口通信工具。 一、串口通信原理 串口通信 串口通信(Serial Communications)的概念非常简单,串口按位(bit)发送和接收字节。尽管比按字节(byte)的并行通信慢,但是串口可以在使用一根线发送数据的同时用另一根线接收数据。它很简单并且能够实现远距离通信。由于串口通信是异步的,端口能够在一根线上发送数据同时在另一根线...

Pei_hua100的专栏 3977

C# WinForm虚拟串口通信

C# 利用虚拟串口工具生成虚拟串口,使用WinForm行串口之间的相互通信,发送与接收数据支持字符形式与16进制的发送与接收。

【亲测免费】 C WinForm 实现串口通信读取电子天平数据

本项目提供了一个基于C# WinForm的应用程序,用于通过串口通信读取赛多利斯电子天平的称重读数。用户可以通过该程序实时获取电子天平的称重数据,并进行进一步的处理和分析。 ## 功能特点 - **串口通信**:通过串口与电子天平进行通信,实时读取称重数据。 - **数据读取**:程序能够读取电子天平的称重读数,并将其显示在界面上。 - **自定义代码**:程序中的读数部分代码需要用户自行提取

gitblog_09817的博客 614

C#winform实现的串口通信入门实例

实现要点 1、串口的参数设置 2、串口名称的刷新,通过重写消息函数,监听的USB的变化,更新电脑的端口变化。 3、打开和关闭串口尽量判定串口是否打开后在进行操作。 4、串口发送前判定是否已经打开。 5、串口的读取Read和发送Write函数的应用。 6、字符串和16进制的转换以及16进制显示的处理。 7、窗体的关闭与串口处理线程的处理,通过增加标志位进行互斥处理,保证每次关闭都能处理完毕后在关闭,防止卡死。 8、串口接收事件是独立于UI线程的单独线程,因此如果在串口接收线程下刷新UI控件需要用到异步执行,本文使用 Invoke进行处理。

Amesim基础篇-热仿真常用模型库-Thermal Hydraulic /Resistance

流体库、管路库在热管理中是必备模块,如动力电池液冷循环系统均需要Thermal Hydraulic /Resistance库的元件建模。

2201_75375391的博客 5705

Winform读取串口电子秤重量:实现高效数据采集

Winform读取串口电子秤重量:实现高效数据采集 【下载地址】Winform读取串口电子秤重量 本项目提供了耀华3190-A12+E型号电子秤通过串口连接,在Winform应用程序中读取重量的实现方法。资源文件包含两种读取模式:连续发送模式和指令模式,适用于不同场景需求。用户可根据电子秤的工作模式选择合适的方案,确保串...

gitblog_06780的博客 1629

线性回归LinearRegression

对视频中线性回归算法的相关内容进行总结与记录 文章目录一、理论基础二、实例2.1 一元线性回归2.1.1 推导过程2.1.2 代码实现(基于numpy)2.1.3 代码实现(基于sklearn)2.2 多元线性回归2.2.1 代码实现(基于numpy)2.2.2 代码实现(基于sklearn) 一、理论基础 回归 通常是指利用某个函数,尽可能把数据样本点“串”在一起,用于描述输入变量和输出变量间的变化关系 线性回归 特点:用来把数据“串”起来的那个函数是线性的 (一元线性回归(一个自变量) &a.

邱邱邱的博客 1075
上一篇: c#Socket学习,使用Socket创建一个在线聊天,日志笔记(5)
下一篇: TypeScript 学习项目创建_1
先生沉默先
博客等级 码龄6年 920粉丝 149原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址