C#,需要从微控制器接收数据

时间:2017-01-30 04:49:59

标签: c# serial-port microcontroller uart

尝试使用DataReceived和handler事件从mk接收数据,我所做的是 - 按下程序上的按钮(代码在下面),然后mk上的LED将打开,然后数据应该被发送回程序(期望1,字节值,但也尝试字符串值,不起作用)。发送方正在工作,但收到....没有 好像我错过了什么。任何帮助都可以帮助它。 Thx in Further

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


        }
    }
}

1 个答案:

答案 0 :(得分:0)

串行端口与UI不在同一个线程上。因此,当您收到一个角色时,由于您没有调用该UI,您将获得一个异常,并且UI不会更新。 首先在DataReceivedHandler中调用用户界面。你可以这样做:

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