【发布时间】:2017-08-27 15:30:10
【问题描述】:
我的程序在启动时检查是否连接了 Arduino,如果是这样,它会通过串行端口发送一条测试消息以查看它是否正确响应。然后它等待结果,如果答案是“成功”,它会继续启动。
这是代码的重要部分:
...
using System.IO.Ports;
using System.Threading;
namespace ProFlagControlApp
{
public partial class MainWindow : Window
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
...
private SerialPort arduinoBoard = new SerialPort();
private string ardAnswer;
/// <summary>
/// Automatically detect the COM port on which an Arduino is connected.
/// </summary>
/// <returns>If an Aduino is connected, the port is returned as a string. If not, it returns null.</returns>
private string AutodetectArduinoPort() { ... }
/// <summary>
/// Initializing communications with the Arduino.
/// </summary>
/// <param name="port">The identifier of the port the Arduino is connected to. Example: 'COM4'</param>
private void OpenArduinoConnection(string port)
{
if (!arduinoBoard.IsOpen)
{
arduinoBoard.DataReceived += new SerialDataReceivedEventHandler(ArdSerPort_DataReceived);
arduinoBoard.BaudRate = 115200;
arduinoBoard.PortName = port;
arduinoBoard.Parity = Parity.None;
arduinoBoard.DataBits = 8;
arduinoBoard.StopBits = StopBits.One;
arduinoBoard.Handshake = Handshake.None;
arduinoBoard.Open();
}
else
{
throw new InvalidOperationException("port is already in use");
}
}
/// <summary>
/// The event handler for receiving data from the Arduino.
/// </summary>
private void ArdSerPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = arduinoBoard.ReadTo("\x03"); // Read Arduino data until exit code
ardAnswer = data.Split('\x02', '\x03')[1]; // Only save information between the start and exit code
autoEvent.Set();
}
public MainWindow()
{
InitializeComponent();
...
// Detect if Arduino is connected, shutdown the application otherwise.
if (AutodetectArduinoPort() == null) { ... }
OpenArduinoConnection(AutodetectArduinoPort());
// Test Arduino communication
arduinoBoard.Write("connection#");
autoEvent.WaitOne(500);
if (ardAnswer != "success")
{
MessageBox.Show("Error communicating with Arduino", "Control Unit Error", MessageBoxButton.OK, MessageBoxImage.Warning);
Application.Current.Shutdown();
return;
}
...
}
...
}
}
我通过 Arduino 串行监视器检查了命令是否被正确读取,并且适当的响应消息被写入串行端口,是这种情况。
但是,ArdSerPort_DataReceived 事件永远不会被触发。当我尝试在测试 ardAnswer 变量中的内容之前手动输入 ardAnswer = arduinoBoard.ReadTo("\x03"); 时,程序似乎冻结并且无法继续执行任何操作。
我真的很想知道为什么。我必须承认,我已经有一段时间没有接触过这个程序了,但是当我上次处理它时,它的表现完全正常,代码完全相同。
【问题讨论】:
-
您的 SerialPort 初始化代码不足。您还必须设置 Parity、DataBits、StopBits (none, 8, 1)。重要的是,Handshake 必须为 None,因为 Arduino 没有实现握手信号。不设置它会产生一个随机值,该值取决于端口的先前使用情况。 ARE 是有风险的,但只要 Arduino 只在您要求时发送一些东西,那么您就可以侥幸逃脱。完全不使用 DataReceived 更为明智。
-
在我的代码中更改了它,谢谢。不幸的是,没有解决主要问题。
标签: c# arduino serial-port