我試圖做一個應用程序,讀取從Arduino傳出的信號,但我不能讓它在C#Windows Forms,只在控制檯中工作。我的C#Windows窗體代碼錯了嗎?我在調試時沒有遇到任何錯誤,但這並不意味着我沒有忘記一些東西。C#讀Arduino
這裏是我的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace CommunicateWithArduino
{
public partial class Form1 : Form
{
public static System.IO.Ports.SerialPort port;
delegate void SetTextCallback(string text);
private BackgroundWorker hardWorker;
private Thread readThread = null;
public Form1()
{
InitializeComponent();
hardWorker = new BackgroundWorker();
sendBtn.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
System.ComponentModel.IContainer components =
new System.ComponentModel.Container();
port = new System.IO.Ports.SerialPort(components);
port.PortName = comPort.SelectedItem.ToString();
port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
port.DtrEnable = true;
port.ReadTimeout = 5000;
port.WriteTimeout = 500;
port.Open();
readThread = new Thread(new ThreadStart(this.Read));
readThread.Start();
this.hardWorker.RunWorkerAsync();
btnConnect.Text = "<Connected>";
btnConnect.Enabled = false;
comPort.Enabled = false;
sendBtn.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comPort.Items.Add(s);
}
if (comPort.Items.Count > 0)
comPort.SelectedIndex = comPort.Items.Count-1;
else
comPort.SelectedIndex = 0;
baudRate.Items.Add("2400");
baudRate.Items.Add("4800");
baudRate.Items.Add("9600");
baudRate.Items.Add("14400");
baudRate.Items.Add("19200");
baudRate.Items.Add("28800");
baudRate.Items.Add("38400");
baudRate.Items.Add("57600");
baudRate.Items.Add("115200");
baudRate.SelectedIndex = 2;
}
private void sendBtn_Click(object sender, EventArgs e)
{
if (port.IsOpen)
{
port.Write(sendText.Text);
}
}
private void SetText(string text)
{
if (this.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.receiveText.Text += "Text: ";
this.receiveText.Text += text;
this.receiveText.Text += Environment.NewLine;
}
}
public void Read()
{
while (port.IsOpen)
{
try
{
if (port.BytesToRead > 0)
{
string message = port.ReadLine();
this.SetText(message);
}
}
catch (TimeoutException) { }
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
if(!(readThread == null))
readThread.Abort();
}
catch (NullReferenceException)
{
}
try
{
port.Close();
}
catch (NullReferenceException)
{
}
}
}
}
什麼不工作?你是否收到有關串口的數據,或者你無法從線程獲取數據到gui? – erikH
如果你不知道,你可以:1,將串行數據記錄到一個文件中,2,創建一個線程,每5秒左右創建一個調用「SetText」的線程。 – erikH
我不能在C#winform應用程序的串行端口上獲取數據。但在Arduino程序串行監視器我得到的數據,我可以在我的C#控制檯應用程序的數據,所以沒有錯誤的Arduino。但我無法在我的winform中獲取數據,這讓我瘋狂的cus我不認爲我發佈的winform代碼有任何問題。我寫了應用程序,所以我可以發送數據並在文本框中收回數據。 – user1680862