尝试从 mk 接收数据,使用 DataReceived 和处理程序事件,我所做的是 -按下程序上的按钮(代码如下),然后 mk 上的 LED 将打开,然后数据应发送回程序(期望 1,在字节值上,但也尝试了字符串值,不起作用)。发送方正在工作,但正在接收....不似乎我错过了什么。任何帮助都赞赏它。谢谢在进一步
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();
});
}
}