【问题标题】:Cannot read data from Arduino bluetooth serial data in WinRT无法从 WinRT 中的 Arduino 蓝牙串行数据读取数据
【发布时间】: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


【解决方案1】:

在成功的ReadString 之后,你需要一个return,当然你需要对message 做一些事情。

【讨论】:

  • 问题是,它从未到达那条线。 :(
  • 捕获(异常)曾经发生过吗?如果是这样,它也将留在循环中
猜你喜欢
  • 1970-01-01
  • 2017-12-14
  • 2019-02-13
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多