调试输出
我在通过USB接收来自Arduino的数据到通用Windows Platform应用程序(UWP)遇到问题。第一个代码块是在Arduino上运行的代码,
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.print("This is a sentence that varies...");
Serial.println(sensorValue);
}
,第二个用于UWP应用程序。
using System;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
namespace SerialTest
{
public sealed class FMKSerials
{
public DataReader dataReader;
public SerialDevice serialPort;
public async void InitializeConnection()
{
var aqs = SerialDevice.GetDeviceSelectorFromUsbVidPid(0x2A03, 0x0057);
var info = await DeviceInformation.FindAllAsync(aqs);
// Get connection data
serialPort = await SerialDevice.FromIdAsync(info[0].Id);
// Configure serial settings
serialPort.DataBits = 8;
serialPort.BaudRate = 115200;
serialPort.Parity = SerialParity.None;
serialPort.Handshake = SerialHandshake.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
dataReader = new DataReader(serialPort.InputStream);
while (true)
{
await ReadAsync();
}
}
private async Task ReadAsync()
{
try
{
Task<uint> loadAsyncTask;
dataReader.ByteOrder = ByteOrder.BigEndian;
dataReader.InputStreamOptions = InputStreamOptions.Partial;
dataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
uint readBufferLength = 20;
loadAsyncTask = dataReader.LoadAsync(readBufferLength).AsTask();
uint ReadAsyncBytes = await loadAsyncTask;
if (ReadAsyncBytes > 0)
{
string data = dataReader.ReadString(readBufferLength);
System.Diagnostics.Debug.Write(data);
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
}
这是一个问题列表:
- 接收缓冲区大小是固定的,但数据的大小各不相同。
- 我正在数据流中丢失数据包。(请参阅下图)
从UWP应用程序(图片)
也许波特率115200对您来说太快了,但对我有用。
但是,较高的速率230400使我获得了同样的问题。
正如@patrick Trentin指出的那样,我在Arduino方面插入了一个delay():
// print out the value you read:
Serial.print("This is a sentence that varies...");
Serial.println(sensorValue);
delay(100);
它解决了问题。