我正在关注这个教程。目标是通过串口从arduino接收周期性数据。我已经为此苦苦挣扎了一段时间了。 com 端口连接很好,因为当我的 c# 应用程序运行时(端口已连接),我无法将另一个终端程序连接到 arduino。此时 SerialListen 线程应该启动,但这并没有发生。
namespace TestReceiveArduino
{
public partial class Form1 : Form
{
//object serialport to listen usb
System.IO.Ports.SerialPort Port;
//variable to check if arduino is connect
bool IsClosed = false;
public Form1()
{
InitializeComponent();
//configuration of arduino, you check if com3 is the port correct,
//in arduino ide you can make it
Port = new System.IO.Ports.SerialPort();
Port.PortName = "COM11";
Port.BaudRate = 9600;
Port.ReadTimeout = 500;
try
{
Port.Open();
Console.WriteLine("open port ");
}
catch { }
}
private void Form1_Load(object sender, EventArgs e)
{
//A Thread to listen forever the serial port
Console.WriteLine("start thread ");
Thread Hilo = new Thread(ListenSerial);
Hilo.Start();
}
private void ListenSerial()
{
Console.WriteLine("start listener");
while (!IsClosed)
{
Console.WriteLine("in while");
try
{
//read to data from arduino
string AString = Port.ReadLine();
//write the data in something textbox
txtSomething.Invoke(new MethodInvoker(
delegate
{
txtSomething.Text = AString;
}
));
}
catch { }
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
//when the form will be closed this line close the serial port
IsClosed = true;
if (Port.IsOpen)
Port.Close();
}
}
}
我的arduino正在发送数据,我已经用终端软件检查了这一点。我也使用了正确的 COM 端口 我对 C# 有一些经验,但我对线程很陌生。这可能是什么原因?
看看这些更改是否有帮助:
namespace TestReceiveArduino
{
public partial class Form1 : Form
{
//object serialport to listen usb
System.IO.Ports.SerialPort Port;
//variable to check if arduino is connect
bool IsClosed = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
// Connect to Arduino
Port = new System.IO.Ports.SerialPort();
Port.PortName = "COM11";
Port.BaudRate = 9600;
Port.ReadTimeout = 500;
Port.Open();
Console.WriteLine("Port successfully opened: Name: {0}, Baud: {1}, ReadTimeout: {2}", Port.PortName, Port.BaudRate, Port.ReadTimeout);
//A Thread to listen forever the serial port
Console.WriteLine("start thread ");
Thread Hilo = new Thread(ListenSerial);
Hilo.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
...
我将“打开串行连接”和“启动侦听器线程”移动到同一位置(Form1_Load),并将两者包装在同一个 try/catch 块中。您甚至可能希望将“try/catch”移至更高级别(例如,以便您可以在 Windows GUI 中显示任何异常)。
我假设您使用 Microsoft Visual Studio(例如 MSVS Express 2019)作为 GUI,对吗?一定要熟悉 IDE 的调试器;一定要养成在开发时逐步执行代码的习惯。
您的后续步骤:
ListenSerial()
,并打印“start Listener”和“in while”至少一次。