суббота, 17 августа 2013 г.

Android-Bluetooth-Arduino sample

I’ve received some questions from beginners about how to transfer data between Android device and Arduino controller. So I decided to write this post as an easy step by step tutorial that describes how to make a Bluetooth connection between your Android app and Arduino sketch. In other words let’s take an Android device (phone or tablet) and try to use it to control LED on Arduino controller.

For this tutorial you should know how to build a typical “Hello World!” application for your Android device and you should also know how to upload an easy LED blink sketch to your Arduino controller.



Let’s start with Arduino. I’ve found an Arduino Uno on my home shelf. So I’ll use it and you can take any other Arduino-compatible controller. There’s a build-in LED on Arduino’s 13th pin that’s why I don’t plan to use any breadboards, LEDs or resistors. All I need is a Bluetooth adapter. And I have one. It is “JY-MCU BT_BOARD V1.05”.



Connect your Arduino controller to PC and upload the sketch below.


const byte LED_PIN = 13;

void setup()
{
  Serial.begin(9600);

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);
}

void loop()
{
  while (Serial.available() > 0)
  {
    char ch = Serial.read();
    executeReceivedCommand(ch);
  }
}

void executeReceivedCommand(char command)
{
  switch (command)
  {
    case '0':
      digitalWrite(LED_PIN, LOW);
      break;
    case '1':
      digitalWrite(LED_PIN, HIGH);
      break;
  }
}


The sketch just waits for the char incoming to the serial port. If this char is ‘0’ it turns the LED on, if ‘1’ then it turns the LED off. You can use Arduino IDE tools to check the sketch. Run Port Monitor and send ‘1’ to the controller. I hope you will see the LED turned on. Send ‘0’ and the LED should turn off.


Next step - let’s connect the controller to the Bluetooth adapter. Take a look at the photo.



PC is disconnected and four Bluetooth adapter’s pins are connected to “3.3V”, “GND”, “0 (RX)” and “1 (TX)” pins of the controller. Note that Bluetooth’s RX pin should be connected to controller’s TX pin. And Bluetooth’s TX -  to controller’s RX. After that plug in some power source from 6 to 12 V.


Now let’s check the Bluetooth adapter. After you've connected the power source you should see that the green power LED indicator on the controller is turned on and that the red LED on the Bluetooth adapter is blinking. Of course these colors and behavior are typical for my hardware only. But I’m sure that most of Bluetooth adapters has some signals that describe whether the adapter is powered or linked to remote host. On this step we should see that the adapter is just been powered.
Now we should check the connection to remote host. I can suggest one good Android app for this test. The app is named Amarino. Unfortunately I couldn’t find it in Play Google Market. But you can download apk installation file from Amarino’s home page. After you’ve installed this app click “Add BT Device” button and pair the Bluetooth adapter to your Android device. Now you can press “Connect” button. If everything is OK the blinking red LED on the Bluetooth adapter should stop blinking and should permanently turn on.


And there’s one more thing you should do in Amarino app. Look at the apps screen and find your Bluetooth adapter’s MAC address. Save this MAC to some note. You'll use it later.


Now let’s make a small Android application that demonstrates connection to remote Bluetooth adapter and data transmission. Create an Android project with one activity. Update four files: layout, string resources, main activity sources and application manifest. Take a look at them.


Layout (activity_main.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_bluetooth"
        android:id="@+id/textView"/>
    <Button
            android:id="@+id/button_disconnect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_text_disconnect"
            android:layout_below="@+id/textView"
            android:layout_alignParentRight="true"/>
    <Button
            android:id="@+id/button_connect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_text_connect"
            android:layout_alignTop="@+id/button_disconnect"
            android:layout_toLeftOf="@+id/button_disconnect"/>
    <EditText
            android:id="@+id/edit_text_mac"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="@string/hint_mac_address"
            android:layout_below="@+id/textView"
            android:layout_toLeftOf="@+id/button_connect"
            android:layout_alignBottom="@+id/button_connect"
            android:layout_alignLeft="@+id/textView"/>
    <CheckBox
            android:id="@+id/checkbox_led"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/switch_text_led"
            android:layout_below="@+id/edit_text_mac"
            android:layout_alignLeft="@+id/edit_text_mac"
            android:layout_alignParentRight="true"/>
</RelativeLayout>

You see, there’s only four controls on the app’s main activity: a text edit to input the MAC of the remote Bluetooth adapter, buttons to connect and disconnect and a checkbox to turn on and off the Arduino LED on the 13th pin.


String resources (strings.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">EasyBluetooth</string>
    <string name="action_settings">Settings</string>
    <string name="hello_bluetooth">Hello Bluetooth!</string>
    <string name="hint_mac_address">BT\'s MAC</string>
    <string name="button_text_connect">Link</string>
    <string name="button_text_disconnect">Unlink</string>
    <string name="switch_text_led">LED state</string>
</resources>
Main activity (MainActivity.java) is too big, so here is the link. See the comments in MainActivity.java file. I’ve tried to make the code plain, short and clear. I hope it is.
Don't forget to add two permissions to AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Now turn on Bluetooth on your Android device, run the app, input the saved MAC in the text edit field and press “Connect”. The app will output a toast (small Android message): “Connected”. You’ll also see that the red LED on the remote Bluetooth adapter is turned on (not blinking). That’s the best proof that the link is established.


Check the box “LED state” and the LED on Arduino 13th pin should turn on. Uncheck it and the LED should turn off.

You can download Arduino and Android sources from my GitHub repository. Good luck!