C#,需要从单片机接收数据

C#, need to receive data from microcontroller

尝试使用 DataReceived 和处理程序事件从 mk 接收数据,我所做的是 - 按下程序上的按钮(代码如下)然后 mk 上的 LED 将亮起,然后数据应发送回程序(期望 1,字节值,但也尝试过字符串值,不起作用)。发送方正在工作,但接收....不 好像我错过了什么。任何帮助 apreciate 它。感谢进一步

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 WindowsFormsApplication11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


        }
        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) // As i understood, here we configure where i data will be shown,
                                                                                       // trying to get it on TextBox1
        {

            SerialPort sp = (SerialPort)sender;
            richTextBox1.Text += sp.ReadExisting() + "\n";
        }

        private void button1_Click(object sender, EventArgs e)                                      // There are a main actions, first i receive data then send data by a click.    
        {
            serialPort1.Write("\u0001");
            serialPort1.Close();

            System.ComponentModel.IContainer components = new System.ComponentModel.Container();  //  
            serialPort1 = new System.IO.Ports.SerialPort(components);
            serialPort1.PortName = "COM4";
            serialPort1.BaudRate = 9600;
            serialPort1.DtrEnable = true;
            serialPort1.Open();
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);


        }
    }
}

串行端口与 UI 在不同的线程上。所以当你收到一个字符时,因为你没有调用 UI,你会得到一个异常并且 UI 没有更新。 在您的 DataReceivedHandler 中首先调用 UI。你可以这样做:

public static class ControlExt
{
    public static void InvokeChecked(this Control control, Action method)
    {
        try
        {
            if (control.InvokeRequired)
            {
                control.Invoke(method);
            }
            else
            {
                method();
            }
        }
        catch { }
    }
}


public partial class Form1 : Form
{
    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        this.InvokeChecked(delegate
        {
            richTextBox1.Text += serialPort1.ReadExisting() + "\n";

            richTextBox1.SelectionStart = Text.Length;
            richTextBox1.ScrollToCaret();
        });
    }
}