我有无线Proto Shield的Arduino Uno R3,我想与Windows Phone 8进行通信。
我正在使用示例Windows_Phone_8_communicating_with_Arduino_using_Bluetooth
中的基础这是一种异步接收方法:
private async void ReceiveMessages(object sender, DoWorkEventArgs e)
{
try
{
while (true)
{
// Read first byte (length of the subsequent message, 255 or less).
uint sizeFieldCount = await dataReader.LoadAsync(1);
if (sizeFieldCount != 1)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message.
uint messageLength = dataReader.ReadByte();
uint actualMessageLength = await dataReader.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 = dataReader.ReadString(actualMessageLength);
MessageReceived(message);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
我有一些方法可以从Arduino发送回信息,(SendCarId,SendRideId)
如果我尝试自己发送每个命令,它会将(从Arduino)发回给我正确的数据。
但是当我一个接一个地发送请求时,它只响应第一个而不是第二个。 (它永远不会第二次进入ReceiveMessages方法)
任何人都知道这是什么问题?
答案 0 :(得分:0)
我发现如果我在得到答案时终止连接, 然后,我可以初始化新连接(可能不是最有效的解决方案,但它正在工作)
public void Terminate()
{
connected = false;
dataReadWorker.DoWork -= new DoWorkEventHandler(ReceiveMessages);
if (socket != null)
{
socket.Dispose();
socket = null;
}
if (dataReadWorker != null)
{
dataReadWorker.CancelAsync();
}
}
public void Initialize()
{
socket = new StreamSocket();
dataReadWorker = new BackgroundWorker();
dataReadWorker.WorkerSupportsCancellation = true;
dataReadWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);
}