只需单击即可在串行端口上多次读写数据

时间:2015-06-10 08:38:24

标签: c# serial-port

只需单击一下按钮,我就需要读取和写入数据到串口。

传感器板连接到我的电脑上,上面装有微控制器。

我只需点击一下即可完成以下操作:

  • 将一些数据发送到微控制器,如传感器的寄存器地址
  • 读取控制器发回的数据
  • 发送另一个传感器的地址
  • 阅读数据

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

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

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

一个简单(和肮脏)的解决方案就是拥有类似的东西

    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循环的条件。