我在使用串行数据接收事件处理程序时遇到问题。一半的时间数据显示在文本框中,一半时间不显示。它应该是跨线程操作的问题。显示来自串行端口的接收数据
这是我的Arduino代码:
int Loop = 1;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(Loop);
Loop++;
delay(1000);
}
这里是我的C#代码:
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 arduino_test
{
public partial class Form1 : Form
{
SerialPort sPort;
public Form1()
{
InitializeComponent();
initialiseArduino();
}
public void initialiseArduino()
{
sPort = new SerialPort();
sPort.BaudRate = 9600;
sPort.PortName = "COM16";
sPort.Open();
//sPort.DataReceived += new SerialDataReceivedEventHandler(sPort_DataReceived);
}
void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
displayMessage(data);
}
public void displayMessage(string data)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(displayMessage), new object[] { data });
return;
}
textBox1.Text = data;
}
private void button1_Click(object sender, EventArgs e)
{
while (true)
{
string data = sPort.ReadLine();
textBox1.Text = data;
}
}
}
}
当我使用接收到的事件处理程序的串行数据,它给了我这个问题,甚至调用后。
所以我试着通过点击一个按钮来运行一个相同的线程操作,它工作得很好。
任何人都可以告诉我我做错了什么?
好的!谢谢你的提示 :-) –