我在使用串行數據接收事件處理程序時遇到問題。一半的時間數據顯示在文本框中,一半時間不顯示。它應該是跨線程操作的問題。顯示來自串行端口的接收數據
這是我的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;
}
}
}
}
當我使用接收到的事件處理程序的串行數據,它給了我這個問題,甚至調用後。
所以我試着通過點擊一個按鈕來運行一個相同的線程操作,它工作得很好。
任何人都可以告訴我我做錯了什麼?
好的!謝謝你的提示 :-) –