【发布时间】:2016-01-29 08:42:47
【问题描述】:
我正在使用与蓝牙模块连接的 Arduino UNO。我在 Arduino 中有以下代码,它会监听特定的输入并点亮 LED。
int LED= 13;
char input;
void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
Serial.println(">> START<<");
Serial.flush();
}
void loop()
{
Serial.flush();
if(Serial.available()>0)
{
input= Serial.read();
if(input=='1')
{
Serial.write(1);
Serial.println('a');
digitalWrite(LED, HIGH);
}
else if(input=='0')
{
Serial.println("OFF");
digitalWrite(LED, LOW);
}
else
{
Serial.println("NO INPUT");
Serial.println(input);
}
}
}
从 Windows 8.1 (XAML/C#) 应用程序我通过蓝牙发送数据。它可以按预期完美运行。但我也在尝试从 Arduino 读取数据。为此,我在 C# 中有以下代码。
socket = new StreamSocket();
connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
await connectAction;//to make it cancellable
writer = new DataWriter(socket.OutputStream);
reader = new DataReader(socket.InputStream);
Task.Run(() =>
{
ListenForMessagesAsync();
});
ListenForMessagesAsync 方法应该继续监听 dataReader。但它只是等待无限的时间,永远不会回来。
private async Task ListenForMessagesAsync()
{
while (reader != null)
{
try
{
uint sizeFieldCount = await reader.LoadAsync(1);// taskLoadLength.GetResults();
if (sizeFieldCount != 1)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message.
uint messageLength = reader.ReadByte();
uint actualMessageLength = await reader.LoadAsync(messageLength);
if (messageLength != actualMessageLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message and process it.
string message = reader.ReadString(actualMessageLength);
}
catch (Exception ex)
{
}
}
}
我在这里做错了什么?
【问题讨论】:
-
一件事;为什么不在任务中创建阅读器?
-
这没有帮助。仍然表现相同。
-
抱歉,我看不出您的设置有什么问题。
标签: c# bluetooth windows-runtime arduino arduino-uno