Forum Xamarin.Android

An Error about Bluetooth connection between Android and Raspberry Pi

jamesmojamesmo Member ✭✭

Hi everyone! I am a beginner in writing Xamarin Android app. I am now doing a project which is using Android phone to control Raspberry Pi via Bluetooth. Therefore I try to use rfcomm approach to do it. However, after I finished the app and tested, an error "read failed, socket might closed or timeout, read ret:-1" always occurs. I am sure that it is not the Raspberry Pi problem since I can use BlueTerm to control my Pi.

My code:

`async void BtnConnect_Click(object sender, EventArgs e)
{
try
{
adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
throw new Exception("No Bluetooth adapter found.");

            if (!adapter.IsEnabled)
                throw new Exception("Bluetooth adapter is not enabled.");

            if (adapter.IsEnabled)
            {
                device = (from bd in adapter.BondedDevices
                          where bd.Name == "raspberrypi"
                          select bd).FirstOrDefault();
                var serialUUID = UUID.FromString("00001101-0000-1000-8000-00805f9b34fb");
                socket = device.CreateRfcommSocketToServiceRecord(serialUUID);
                await socket.ConnectAsync();
                txtStatus.Text = "RPi 1 Connected";
                EnableOrDisableAllMainFunctions(true);
                btnConnect.Enabled = false;
            }

        }
        catch (Exception ex)
        {
            txtStatus.Text = ex.Message;
            Toast.MakeText(this, ex.Message, ToastLength.Short);
        }
    }`

What's wrong with it? Anyone can help me?

Tagged:

Answers

Sign In or Register to comment.