我正在开发一个与Arduino设备通信的通用Windows 10应用程序。 我不想远程控制Arduino。我想简单地向设备发送数据和从设备接收数据。我尝试了几种这样做的方法无济于事。以下是我现在正在尝试的内容:
SerialDevice tempDevice = await SerialDevice.FromIdAsync(devices.ElementAt(i).Id);
tempDevice.WriteTimeout = TimeSpan.FromMilliseconds(1000);
tempDevice.ReadTimeout = TimeSpan.FromMilliseconds(1000);
tempDevice.BaudRate = 115200;
tempDevice.Parity = SerialParity.None;
tempDevice.StopBits = SerialStopBitCount.One;
tempDevice.DataBits = 8;
tempDevice.Handshake = SerialHandshake.None;
tempDevice.IsRequestToSendEnabled = true;
DataWriter dataWriter = new DataWriter(tempDevice.OutputStream);
dataWriter.WriteString("Test string");
await dataWriter.FlushAsync(); // <-- program hangs here
testDevice.Dispose();
我正在使用Windows.Devices.SerialCommunication.SerialDevice
和Windows.Storage.Streams.DataWriter
我在标记的行周围添加了各种断点,并确定程序挂在那里。我甚至尝试删除await
关键字,程序仍然挂在同一行。为什么我无法将数据发送到Arduino?
有一些我不明白的事情,另外还有为什么它完全不起作用:
await
关键字)我使用的是Arduino Mega 2560,该程序是用C#编码的Windows 10 Universal App。
答案 0 :(得分:1)
只需在打开端口之后和创建DataWriter之前添加暂停:
Task.Delay(1000).Wait();
这是我检查过的工作方法:
private async Task sendToPort(string sometext)
{
using (SerialDevice serialPort = await SerialDevice.FromIdAsync(deviceId))
{
Task.Delay(1000).Wait();
if ((serialPort != null) && (sometext.Length != 0))
{
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = 9600;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
Task.Delay(1000).Wait();
try
{
using (DataWriter dataWriteObject = new DataWriter(serialPort.OutputStream))
{
Task<UInt32> storeAsyncTask;
dataWriteObject.WriteString(sometext);
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
if (bytesWritten > 0)
{
txtStatus.Text = bytesWritten + " bytes written";
}
}
}
catch (Exception ex)
{
txtStatus.Text = ex.Message;
}
}
}
}