How to connect App Inventor apps to Arduino using Bluetooth wireless

How to Connect App Inventor apps to Arduino Using Bluetooth

Bluetooth is a low power, short range wireless technology built in to many phones, tablets and other devices.

MIT App Inventor 2 supports a set of Bluetooth communication functions that may be used to send data between smart phones and tablets (see previous tutorials: Part 1, Part 2)

This capability may be extended so that App Inventor apps can communicate with Arduino-based devices and other embedded systems.

This tutorial describes how to interface App Inventor apps running on Android to Arduino devices, via the Bluetooth wireless link.

What is Bluetooth?

Bluetooth is an industry standard for low power, short range wireless communications between devices such as personal computers, printers, smart phones, tablets, wireless headphones, wireless stereo speakers, sensor systems (like in security alarms) and other applications.

To learn more about Bluetooth technology (and why it has a funny name!), please read our first tutorial on Bluetooth.

What is Arduino?

Arduino is an open hardware, open software platform for building small electronic devices. The Arduino board is a “microcontroller” – that is, a complete – albeit small, inexpensive and with limited function – computer. Arduino is a popular choice for do-it-yourself projects and is well established in the “Maker” community of DIY project builders. (Side note: I will be at the San Francisco Maker Faire on Saturday, May 16th, 2015).

This is not a tutorial about Arduino boards, software or electronics and presumes the reader is familiar with Arduino development. To learn more about Arduino (and you should learn more about it!) start at the Arduino web site.

This tutorial assumes you have the Arduino software development environment installed on your computer and are familiar with Arduino development.

HARDWARE: Setting Up Arduino for Bluetooth Wireless Communications

There are several versions of the Arduino board; I used the Uno version but others should work just fine.

The Arduino board does not contain Bluetooth hardware – to implement Bluetooth requires using a third-party Bluetooth module. I use the JY-MCU Bluetooth module . IMPORTANT – not all Bluetooth modules will work with App Inventor!  While new versions of Android support all versions of Bluetooth, App Inventor (at the time of this writing) supports “classic” Bluetooth only. In particular, App Inventor does not support the newer Bluetooth LE (Low Energy) version, at least it does not support the Bluetooth LE module that I have.

I can confirm that the JY-MCU Bluetooth module works but the Bluetooth LE modules I have do not work with App Inventor.  My phone can see the Bluetooth LE device but the App Inventor source code cannot communicate with the LE devices.

Where to buy the JY-MCU Module online: Amazon (Prime), Amazon (non-Prime)

The module is also available from other vendors.

Photo shows my Arduino UNO board, at left, a prototyping breadboard with a status LED set up, and the JY-MCU Bluetooth module, just above the breadboard.

DSC_1266Click through to  see how the Arduino and Bluetooth module are setup, and get the Arduino source code and the App Inventor source code!

To learn how to set up this hardware, please refer to this external tutorial from roboTosh on setting up the JY-MCU Bluetooth module with your Arduino board. Be sure to use the sample Arduino source code on that web page to test your hardware set up and verify that everything is working.

The hardware configuration sets up power and interface to the JY-MCU module, and configures a single LED as a status indicator when the code is running.

In the test case (on that page), you’ll program the Arduino using the USB-serial link, and then run the Arduino Serial Monitor to type commands to the Arduino board. Type ‘H’ to turn on the status LED light, and then type ‘L’ (actually anything other than H) to turn the light off.

ARDUINO SOFTWARE: Arduino Source Code for Bluetooth Communications

Once the Arduino and JY-MCU hardware are set up,  install the software on the Arduino board.

You may download the following source code as both a text file (.txt) and as an Arduino .ino project file (see end of this post for download links).

A description of what this Arduino code does and how it works follows the code listing. If you are not familiar with Arduino source code, it is similar to the C++ programming language.

/*
BTArduino sketch By Edward Mitchell http://appinventor.pevest.com
Description:
Uses the JY-MCU Bluetooth module to enable an Arduino board to communicate over Bluetooth
wireless to an Android app written in MIT App Inventor 2, running on an Android device.

Buy the JY-MCU module here
(Amazon Prime) http://www.amazon.com/gp/product/B0093XAV4U/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=B0093XAV4U&linkCode=as2&tag=commonsensevi-20&linkId=4L5VQJW7JJKBGCMU
(Amazon non Prime option) http://www.amazon.com/gp/product/B009DZQ4MG/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=B009DZQ4MG&linkCode=as2&tag=commonsensevi-20&linkId=S6VEEZVTF4GBGYWC

Credit:
This Arduino code based very loosely on the original Arduino code for the JY-MCU Bluetooth module tutorial at
http://robotosh.blogspot.com/2012/07/arduino-jy-mcu-bluetooth.html

A tutorial for using this code with App Inventor 2, is available at the appinventor.pevest.com
web site. Please refer to the tutorial for information and source code for the Android side of this sketch.

Note - this sample code is intended only to show how the basic Bluetooth communications link may
be set up, and illustrates just one possible way of sending commands from the Android device
to the Arduino phone. The purpose of this code is as an introduction/tutorial and is not meant
to be used for any particular purpose. No warranties.
*/

// Constant Definitions
#define LEDPIN 8 // Pin on Arduino board to which status LED is connected
#define READ_RATE 100 // How often the serial link is read, in milliseconds
#define FLASH_RATE 100 // The on/off period in milliseconds, for the LED Flash status feedback

// Declarations
byte cmd; // Stores the next byte of incoming data, which is a "command" to do something
byte param; // Stores the 2nd byte, which is the command parameter

// Initialization
void setup() {

pinMode(LEDPIN, OUTPUT); // pin 48 (on-board LED) as OUTPUT
digitalWrite(LEDPIN, LOW);
Serial.begin(9600); // start serial communication at 9600bps
}

// Arduino Execution Loop
void loop() {

if ( Serial.available() ) // if data is available to read
{
cmd = Serial.read(); // read it and store it in 'cmd'
// Data format is byte 1 = command, byte 2 = parameter
};

switch ( cmd ) {
case 1:
// First byte contains a generic "command" byte. We arbitrarily defined '1' as the command to then check the 2nd parameter byte
// User can additional commands by adding case 2, 3, 4, etc
{
// read the parameter byte
param = Serial.read();
switch (param)
{
case 1:
// Android device requests the Arduino to send some data back to Android
flashLED(1);
if (Serial)
{
// Send back 2 bytes with a value of 1, 2
Serial.write(1);
Serial.write(2);
};
break;
case 2:
// Turn on status LED
flashLED(2);
digitalWrite(LEDPIN, HIGH );
break;
case 3:
// Turn off status LED
flashLED(3);
digitalWrite(LEDPIN, LOW);
break;
case 4:
// Demonstrate flashing the LED 4 times
flashLED(4);
break;
case 5:
// Demonstrate flashing the LED 5 times
// Could add code here to control a servo via PWM outputs
flashLED(5);
break;
default: break; // do nothing
} // switch (param)
} // switch (cmd) case 1
default: break; // do nothing
} // switch (cmd)

delay(READ_RATE); // wait 100ms for next reading
}

// Support routine
void flashLED (int n) {
// Flash the LED n times, to provide an on board status indicator
for (int i=1; i<=n; i++) {
digitalWrite (LEDPIN, HIGH);
delay (FLASH_RATE);
digitalWrite (LEDPIN, LOW);
delay(FLASH_RATE);
};
return;
}

Description of the Arduino Code

This description assumes you are familiar with Arduino projects.

The basic operation configures a Serial port to communicate with the JY-MCU module. Data is  received or transmitted between the JY-MCU module using the Serial interface.

This project defines a very simple protocol for communicating between the Arduino and the App Inventor app running on an Android device.

The protocol is merely a 2-byte sequence. The first byte contains a value that we interpret as a “command”, and the second byte contains a parameter value for the command. When the code reads incoming data from the JY-MCU module, the first byte is stored in a variable named cmd and the second byte is stored in a variable named param.

The initialization code, in setup() sets the Serial data rate to 9600 bps as this is the default data rate on the JY-MCU module. The module may be configured to use different (and faster) data rates but for this tutorial, the data rate is left at the default value of 9600 bps.

The loop() section of the Arduino code reads an incoming cmd byte value, and then uses a switch statement to select from among a set of possible values. This tutorial implements only a command value of 1; you can add additional values to define additional commands. For a command of 1, the 2nd byte is then read as the parameter value. (One could define a command value of say, 2, and then define that the next several bytes contains a text string, for example.)

Depending on the parameter value (2, 3, 4, etc) a different function may be performed. As defined here, a value of 2 turns on the status LED; a value of 3 turns off the status LED.

A parameter value of 1 tells the Arduino to send 2 bytes of data back to the App Inventor app, via the Bluetooth connection. This could be modified to send back other types of data (2 byte or 4 byte numbers or text strings).

Additionally, the LED flashes the value of the parameter byte. For example, if a parameter value of 4 is received, the LED flashes 4 times, to provide visible feedback.

You can modify this code to implement new functions on the Arduino that are controlled remotely from the App Inventor app. For example, you could define that a parameter value of 4 means to set pin 9 of the Arduino HIGH and a parameter value of 5 means to set pin 9 to LOW. You could also use this to pass control information to operate a PWM interfaced servo or motor.

Finally, flashLED() is a simple function to flash the LED the number of times indicated by its argument.

APP INVENTOR 2 SOFTWARE for Bluetooth

The “Bluetooth Client for Arduino” is based on the similar client code introduced in the part 1 and 2 tutorials on Bluetooth. The app provides a simple interface to connect to the Bluetooth device, to disconnect from the device, to send a numeric value (such as 1, 2, 3, etc) and to display link status and data received from the Arduino.

The blocks code for this app may be downloaded at the link provided at the end of this tutorial.

 The Designer View

The user interface has 3 buttons: Connect to device, Disconnect device and Send Numeric.

Labels are used to display status and received data.

The User Interface, as seen in the MIT App Inventor Designer:

BTClient_ArduinoDesignerThe App Inventor App In Operation

FIRST! “Pair” Your Bluetooth Devices!

Prior to running the App, you must go into the Android Settings | Bluetooth options and “pair” the JY-MCU Bluetooth module with your Android phone. With the Arduino and JY-MCU powered up, you should see a device named “HC-06”. Please see the section titled Setting Up A Bluetooth Connection in Part 1: Basic Bluetooth communications using App Inventor. You may need to enter a pairing code of “1234” to set up the HC-6 device. (See  the roboTosh link for details on that.)

Once the app is running, you should see that the link is Disconnected.

Screenshot_2015-05-07-15-34-30Select Connect to device.

The app displays a list of potential Bluetooth devices. Select the HC-06 device from the list. There will be a pause for a second or two as the connection is established.

Screenshot_2015-05-05-17-48-39

If you see the following error message when you attempt to connect, it means your Arduino/Bluetooth module is probably not powered up or is too far away:

Screenshot_2015-05-07-15-39-26

Once the link is set up, the Link status will display “Client connected”:

Screenshot_2015-05-07-15-34-47

Enter a numeric value of 2 and press Send Numeric – the status LED should turn on. To turn it off, enter a value of 3 and press Send Numeric – the status LED should turn off. Note that the LED will also flash a number of times equal to the numeric value sent.

Screenshot_2015-05-07-15-35-02

To demonstrate sending data from the Arduino device to the App Inventor app, enter a numeric value of 1 and press Send Numeric. A moment later you should see that the Data received status displays “1,2”:

Screenshot_2015-05-07-15-35-24

 The Blocks Code

The original Bluetooth client code (see the original Parts 1 and 2) has been simplified to do only what is needed for the Arduino link.

The Send Numeric click event handler sends the numeric value across the Bluetooth link. For simplicity, only positive numbers are permitted (the absolute value function converts negative values to positive values), and since a byte may only represent values between 0 and 255, anything larger is set to 255.

The command byte value of 1 is sent, followed by the numeric value:

BTArduino_SendNumericData is received inside the Click Timer event. The two incoming bytes are read and displayed on the screen:

BTArduino_TimerEventKey Features Shown

  • Setting up the Arduino hardware to demonstrate Bluetooth communications using the JY-MCU module
  • Writing and installing Arduino code to use the JY-MCU module for Bluetooth communications
  • Writing the blocks code in MIT App Inventor for an app that links to the Arduino device over Bluetooth wireless.
  • Operation of sample programs showing how to send and receive data via Bluetooth.

Future Development

The command/parameter protocol may be extended to support many types of data transfer and a greater set of remote control functions.

The communication protocol, in a production system, might be improved to include data error detection. If data bytes are missed or damaged, they should be detected and handled or discarded.

Source Code Downloads

DISCLAIMER

These code files and instructions are provided solely for educational purposes but you are free to use these in your projects. No warranty of any type is implied. I will  respond to reports of defects in the code but I am unable to debug your hardware or software projects or to develop custom code for you!

E-Books and Printed Books

If you find these tutorials helpful (I hope you do!) please take a look at my books on App Inventor. To learn more about the books and where to get them (they are inexpensive) please see my App Inventor Books page.

  • App Inventor 2 Introduction (Volume 1 e-book)
    Step-by-step guide to easy Android programming
  • App Inventor 2 Advanced Concepts (Volume 2 e-book)
    Step-by-step guide to Advanced features including TinyDB
  • App Inventor 2 Databases and Files (Volume 3 e-book)
    Step-by-step TinyDB, TinyWebDB, Fusion Tables and Files
  • App Inventor 2 Graphics, Animation and Charts (Volume 4 e-book and printed book)
    Step-by-step guide to graphics, animation and charts

Thank you for visiting! — Ed

Please Share on Social Media

Please click on the buttons below this post to share with your friends on Facebook or other social media.

If you are not already following this blog, click on the following links to like on Facebook, add to your Google+ circles or follow on Twitter or in your RSS news reader. Thank you for visiting!

Advertisements

16 thoughts on “How to connect App Inventor apps to Arduino using Bluetooth wireless

  1. Pingback: New Arduino Zero controller board | App Inventor 2 Tutorial – Learn to Code!

  2. Pingback: Coming soon: Bluetooth to connect Android App Inventor code to Arduino | App Inventor 2 – Learn to Code!

  3. Pingback: Part 2: Sending numeric data using App Inventor Bluetooth communications | App Inventor 2 – Learn to Code!

  4. Pingback: Part 1: Basic Bluetooth communications using App Inventor | App Inventor 2 – Learn to Code!

  5. I tried downloading the .aia client file and the link gives me a zip file with folders and files, but no .aia file. I suspect this may be for AppInventor I?

    Is there a .aia file available?

    Like

    • I just downloaded the files all okay use right -click, save as, in Firefox, on Windows 10.

      The .aia file format is, in fact, just a .zip file that can be opened in ZIP file decompressor. However, you should download as .aia and upload that entire .aia file to App Inventor. If you are seeing .zip as the file extension, then something odd is happening. Rename it to .aia (unmodified content) and upload that to MIT App Inventor.

      (You can read more about the internals of the .aia file format here – http://appinventor.pevest.com/?p=655)

      Ed

      Like

      • Ok. I tried Firefox and it works fine. I have Win 7 and latest IE. Right click – Save As would download it as a zip file, then my WinZip wanted to unzip it.

        Like

      • Cedric – that is good to know that Firefox works! I will test with IE to see what IE might be doing – I suspect it recognizes the internal .aia. zip file format and thinks it is doing a favor by opening it as a zip file 🙂

        Ed

        Like

    • To write code for Arduino, you need to install the Arduino software development editor and system, from http://arduino.cc.

      Code that you write for Arduino, in the Arduino Integrated Development Environment (or IDE) is downloaded to the Arduino board over USB. The “user interface” for Arduino programs are lights, motors and such, or attached LCD panels. If you want to display text for debugging purposes, the Arduino can send data over a serial link from the Arduino board, over the USB cable, back to the computer, where the text can be received and displayed on screen. Basically, this is a “terminal” program that lets you send text you type and display messages to and from the Arduino board.

      Ed

      Like

  6. hello friend nice website and content
    i’m a biginner to all this and i want to make an app that could be able to play or stop some tones wirelessly trough bluetooth or wifi to another android device

    Like

    • We can connect an Android App Inventor app over a Bluetooth link using the Bluetooth serial communications link.

      Can we connect to a Bluetooth audio device? I do not know. I expect that we can connect to the device but we do not know what data needs to be sent to the audio device nor do we know the form of the required audio data.

      While Android supports WiFi, there is no specific features in App Inventor to connect over WiFi to a specific device.

      Ed

      Like

  7. Pingback: Part 3: Bluetooth communications with 2 Arduino devices, using App Inventor – App Inventor 2 – Learn to Code!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s