我有安卓应用程序通过HC-06连接和读取Arduino Uno中的字节。但是这种沟通非常缓慢,我需要它尽可能快(当我点击一个按钮时我想立即响应android)。而且有时我甚至不能从Arduino Uno获得字节。
这是我连接蓝牙设备(HC-06)的代码
public async Task Connect(string address)
{
ProgressDialog pd = new ProgressDialog(this);
pd.SetMessage("Please wait trying to connect...");
pd.SetCancelable(false);
pd.Show();
if (btSocket != null)
{
if (!btSocket.IsConnected)
{
btSocket.Close();
}
}
//INITILIZATION OF THE ARDUINO BLUETOOTH
device = mBluetoothAdapter.GetRemoteDevice(address);
mBluetoothAdapter.CancelDiscovery();
try
{
//Making a socket for communication
btSocket = device.CreateRfcommSocketToServiceRecord(MY_UUID);
//Cconnecting to a socket
await btSocket.ConnectAsync();
pd.Hide();
print("Connection succes", "short");
runthread = true;
beginListenForData();
}
catch (System.Exception e)
{
pd.Hide();
print("Can't connect", "long");
//en caso de generarnos error cerramos el socket
System.Console.WriteLine(e.Message);
try
{
btSocket.Close();
}
catch (System.Exception)
{
}
}
}
这是用于读取数据
public void beginListenForData()
{
print(" Function beginListedForData", "short");
try
{
inStream = btSocket.InputStream;
}
catch (System.IO.IOException ex)
{
System.Console.WriteLine(ex.Message);
}
Task.Factory.StartNew(() =>
{
byte[] buffer = new byte[1024];
int bytes;
while (true)
{
try
{
bytes = inStream.Read(buffer, 0, buffer.Length);
if (bytes > 0)
{
RunOnUiThread(() =>
{
string valor = System.Text.Encoding.ASCII.GetString(buffer);
public_bluetooth_data = valor;
result.Text += valor;
});
for (int x = 0; x < buffer.Length; ++x)
{
buffer[x] = 0;
}
}
else
{
RunOnUiThread(() =>
{
result.Text = "No bytes have been read";
});
}
}
catch (Java.IO.IOException)
{
RunOnUiThread(() =>
{
print("Connection has stopped", "long");
result.Text = string.Empty;
});
break;
}
}
});
}
这是Arduino代码
int button = 5;
void setup()
{
Serial.begin(9600);
pinMode(button, INPUT);
}
void loop()
{
if(digitalRead(button)=="LOW")
{
Serial.print("0");
}
else{
Serial.print("1");
}
delay(10);
}
我的代码在Xamarin Android中。任何帮助表示赞赏。