一键读写串口数据多次

Read and write data multiple times on a serial port with a single click

我需要通过单击一个按钮来读取和写入数据到串行端口。

传感器板连接到我的 PC,上面有一个微控制器。

我必须单击一下才能完成以下操作:

之后,我必须对接收到的数据进行一些计算。

如何通过单击按钮多次发送和读取数据?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(SerialPort.GetPortNames());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = comboBox1.Text;
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.Open();
            serialPort1.Write("$g helloboard!"); // A message sending to micro controller. After that micro controller send back a message. 
        }

        string str;

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytes = serialPort1.BytesToRead;
            byte[] buffer = new byte[bytes];
            serialPort1.Read(buffer, 0, bytes);

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            str = enc.GetString(buffer);
        }
    }
}

一个简单(而且肮脏)的解决方案是有这样的东西

    private bool data_received = true;
    private void button1_Click(object sender, EventArgs e)
    {
        while (true)
        {
            if (data_received)
            {
                data_received = false;
                serialPort1.Write("$get register 42");
            }
            System.Threading.Thread.Sleep(1);
        }
    }

并在您的回调中 serialPort1_DataReceived 添加:

data_received = true;

这仅用于测试目的。这远不是一个好的解决方案,下一个任务是在后台线程中工作,这样你的 GUI 就不会被阻塞,当然还要定义一个条件来打破 while 循环。