2 April 2013

Bluetooth Android Processing 4

PART FOUR

The Video





This is part 4 of my tutorial on designing an Android Phone Bluetooth App using the Android/Processing language. The App sends information to an Arduino via Bluetooth after pressing a button on the phone. The RGB LED attached to the Arduino Uno (or compatible board) will change colour depending on the button being pressed on the phone. The Arduino gains Bluetooth capabilities through the Seeedstudio Bluetooth shield (which can be found here).

Parts 1-3 of the tutorial were designed to take you step-by-step through designing the app. If you are wondering what you missed, here is a summary:

This is what you'll find in part one:
  • Downloading and setting up the Android SDK
  • Downloading the Processing IDE
  • Setting up and preparing the Android device
  • Running through a couple of Processing/Android sketches on an Andoid phone.

This is what you will find in part two:

  • Introducing Toasts (display messages)
  • Looking out for BluetoothDevices using BroadcastReceivers
  • Getting useful information from a discovered Bluetooth device
  • Connecting to a Bluetooth Device
  • An Arduino Bluetooth Sketch that can be used in this tutorial

This is what you will find in part three:

  • InputStreams and OutputStreams
  • Error Logs using logcat
  • Testing the InputStreams and OutputStreams
  • Using the APWidgets library to create buttons
  • Adding Buttons to the BlueTooth Project



In Part 4, we simplify and strip down the App so that it will only sends a specific String to the Arduino via Bluetooth. The String sent to the Arduino depends on the Button being pressed. The code has been cleaned up and has many comments to help you understand what is going on. You should be able to run this sketch without having to go back through parts one, two or three of the tutorial. This fourth part of the tutorial was designed for those people who want the final end product, and are happy to work it out for themselves. I hope this serves you well.
I will therefore assume that you have already setup your phone and have downloaded all the neccesary drivers, libraries, SDKs and IDEs. If not, then here are a few quick links:
If you are a bit lost and want want a bit more information then please go through parts one, two and three of this tutorial.
Make sure that you have selected the Bluetooth permissions as per the following:

  • Android > Sketch permissions  (as per the picture below)


Make sure that BLUETOOTH and BLUETOOTH_ADMIN are selected (as per the picture below). Then press the OK button.



Then copy and paste the following sketch into the processing/android IDE:

Android/Processing Sketch 9: Bluetooth App2
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/* BluetoothApp2: Written by ScottC on 1st April 2013 using 
 Processing version 2.0b8
 Tested on a Samsung Galaxy SII, with Android version 2.3.4
 Android ADK - API 10 SDK platform
 Apwidgets version: r44 : http://code.google.com/p/apwidgets/
 */


/*------------------------------------------------------------------------------
 IMPORT statements required for this sketch
-----------------------------------------------------------------------------*/
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 

import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 

import java.io.IOException; 
import java.io.OutputStream; 
import java.util.UUID; 
import android.util.Log; 

import apwidgets.APWidgetContainer;
import apwidgets.APButton; 
import apwidgets.APWidget;
import apwidgets.OnClickWidgetListener;


/*------------------------------------------------------------------------------
 GLOBAL Variables to be used between a number of classes.
-----------------------------------------------------------------------------*/
public int[] bg={0,80,0};
public BluetoothDevice btShield = null;
public BluetoothSocket btSocket = null;
public OutputStream btOutputStream = null;
public APWidgetContainer widgetContainer=null;
public Connect2BtDevice ConBTdevice=new Connect2BtDevice();



/*------------------------------------------------------------------------------
 The following variables are used to setup the Buttons used in the GUI
 of the phone. It includes the variables that determine the
 - text on the buttons
 - the number of buttons
 - the letters that will be sent to Arduino when the buttons are pressed
 - the colour that the background will change to when the buttons are pressed
 - the dimensions of the buttons (width and height)
 - The gap between each button
-----------------------------------------------------------------------------*/
String[] buttonText = { "RED", "GREEN", "BLUE", "OFF"}; //Button Labels
String[] sendLetter={"r","g","b","x"}; //Letters to send when button pressed
int n= buttonText.length; //Number of buttons
int[][] buttonColour = { {255,10,10}, 
 {10,255,10}, 
 {10,10,255}, 
 {0,0,0} 
 }; //The Background colour on phone when button pressed


APButton[] guiBtns = new APButton[n]; //Array of buttons
int gap=10; //gap between buttons
int buttonWidth=0; //initialising the variable to hold the WIDTH of each button
int buttonHeight=0; //initialising the variable to hold the HEIGHT of each button




/*------------------------------------------------------------------------------
 The setup() method is used to connect to the Bluetooth Device, and setup
 the GUI on the phone.
-----------------------------------------------------------------------------*/
void setup(){
 new Thread(ConBTdevice).start(); //Connect to SeeedBTSlave device
 orientation(LANDSCAPE); //Make GUI appear in landscape mode
 
 //Setup the WidgetContainer and work out the size of each button
 widgetContainer = new APWidgetContainer(this);
 buttonWidth=((width/n)-(n*(gap/2))); //button width depends on screen width
 buttonHeight=(height/2); //button height depends on screen height
 
 //Add ALL buttons to the widgetContainer.
 for(int i=0; i<n;i++){
 guiBtns[i]= new APButton(((buttonWidth*i)+(gap*(i+1))), gap, buttonWidth, buttonHeight, buttonText[i]);
 widgetContainer.addWidget(guiBtns[i]);
 }
}



/*------------------------------------------------------------------------------
 The draw() method is only used to change the colour of the phone's background
-----------------------------------------------------------------------------*/
void draw(){
 background(bg[0],bg[1],bg[2]);
}




/*------------------------------------------------------------------------------
 onClickWidget is called when a button is clicked/touched, which will
 change the colour of the background, and send a specific letter to the Arduino.
 The Arduino will use this letter to change the colour of the RGB LED 
 -----------------------------------------------------------------------------*/
void onClickWidget(APWidget widget){ 
 String letrToSend="";
 
 /*Identify the button that was pressed, Change the phone background 
 colout accordingly and choose the letter to send */
 for(int i=0; i<n;i++){
 if(widget==guiBtns[i]){
 ConBTdevice.changeBackground(buttonColour[i][0],
 buttonColour[i][1],
 buttonColour[i][2]);
 letrToSend=sendLetter[i];
 }
 }
 
 /* Send the chosen letter to the Arduino/Bluetooth Shield */
 if(ConBTdevice!=null){
 ConBTdevice.write(letrToSend);
 }
}



/*==============================================================================
 CLASS: Connect2BtDevice implements Runnable
 - used to connect to remote bluetooth device and send values to the Arduino
==================================================================================*/
public class Connect2BtDevice implements Runnable{

/*------------------------------------------------------------------------------
 Connect2BtDevice CLASS Variables 
-----------------------------------------------------------------------------*/ 
 BluetoothAdapter btAdapter=null;
 BroadcastReceiver broadcastBtDevices=null;
 private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
 
 
 
/*------------------------------------------------------------------------------
 DEFAULT CONSTRUCTOR: Connect2BtDevice() 
 - Create a BroadcastReceiver (registered in run() method).
 - Get the default Bluetooth Adapter
 - Enable the adapter (if it is not already enabled).
 - Discover available Bluetooth devices to connect to 
-----------------------------------------------------------------------------*/
 public Connect2BtDevice(){
 broadcastBtDevices = new btBroadcastReceiver();
 getBtAdapter();
 enableBtAdapter();
 discoverBtDevices();
 }



/*------------------------------------------------------------------------------
 run() method
 - used to register the broadcast receiver only
-----------------------------------------------------------------------------*/
 @Override
 public void run() {
 registerReceiver(broadcastBtDevices, new IntentFilter(BluetoothDevice.ACTION_FOUND));
 }
 
 
 
/*------------------------------------------------------------------------------
 getBtAdapter() method
 - get the default Bluetooth adapter
-----------------------------------------------------------------------------*/
 void getBtAdapter(){
 btAdapter = BluetoothAdapter.getDefaultAdapter();
 }
 
 
 
/*------------------------------------------------------------------------------
 enableBtAdapter() method
 - Enable the default Bluetooth Adapter if it isn't already enabled
-----------------------------------------------------------------------------*/ 
 void enableBtAdapter(){
 if (!btAdapter.isEnabled()) {
 btAdapter.enable();
 }
 }
 
 
 
/*------------------------------------------------------------------------------
 discoverBtDevices() method
 - Discover other Bluetooth devices within range (ie SeeedBTSlave device)
-----------------------------------------------------------------------------*/ 
 void discoverBtDevices(){
 while(!btAdapter.isEnabled()){
 //Wait until the Bluetooth Adapter is enabled before continuing
 }
 if (!btAdapter.isDiscovering()){
 btAdapter.startDiscovery();
 }
 }
 
 
 
/*------------------------------------------------------------------------------
 connect2Bt() method: called by the btBroadcastReceiver
 - Create a BluetoothSocket with the discovered Bluetooth device
 - Change background to yellow at this step
 - Connect to the discovered Bluetooth device through the BluetoothSocket
 - Wait until socket connects then
 - Attach an outputStream to the BluetoothSocket to communicate with Bluetooth
 device. (ie. Bluetooth Shield on the the Arduino)
 - Write a "g" string through the outputStream to change the colour of the LED
 to green and change the phone background colour to green also.
 A green screen and green LED suggests a successful connection, plus the
 Bluetooth shield's onboard LED starts flashing green slowly (1 per second),
 which also confirms the successful connection.
-----------------------------------------------------------------------------*/ 
 void connect2Bt(){
 try{
 btSocket = btShield.createRfcommSocketToServiceRecord(uuid);
 changeBackground(255,255,0); //YELLOW Background
 try{
 btSocket.connect();
 while(btSocket==null){
 //Do nothing
 }
 try {
 btOutputStream = btSocket.getOutputStream();
 changeBackground(0,255,0); //Green Background
 write("g"); //Green LED (Successful connection)
 }catch (IOException e) { 
 Log.e("ConnectToBluetooth", "Error when getting output Stream");
 }
 }catch(IOException e){
 Log.e("ConnectToBluetooth", "Error with Socket Connection");
 changeBackground(255,0,0); //Red background
 }
 }catch(IOException e){
 Log.e("ConnectToBluetooth", "Error with Socket Creation");
 changeBackground(255,0,0); //Red background
 try{
 btSocket.close(); //try to close the socket
 }catch(IOException closeException){
 Log.e("ConnectToBluetooth", "Error Closing socket");
 }return;
 }
 }
 
 
/*------------------------------------------------------------------------------
 write(String str) method
 - Allows you to write a String to the remote Bluetooth Device
-----------------------------------------------------------------------------*/ 
 public void write(String str) {
 try {
 btOutputStream.write(stringToBytes(str));
 } catch (IOException e) { 
 Log.e("Writing to Stream", "Error when writing to btOutputStream");
 }
 }
 
 
 
/*------------------------------------------------------------------------------
 byte[] stringToBytes(String str) method
 - Used by the write() method 
 - This method is used to convert a String to a byte[] array
 - This code snippet is from Byron: 
 http://www.javacodegeeks.com/2010/11/java-best-practices-char-to-byte-and.html
-----------------------------------------------------------------------------*/ 
 public byte[] stringToBytes(String str) {
 char[] buffer = str.toCharArray();
 byte[] b = new byte[buffer.length << 1];
 for(int i = 0; i < buffer.length; i++) {
 int bpos = i << 1;
 b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
 b[bpos + 1] = (byte) (buffer[i]&0x00FF);
 }
 return b;
 }
 
 
 
/*------------------------------------------------------------------------------
 cancel() method
 - Can be called to close the Bluetooth Socket
-----------------------------------------------------------------------------*/ 
 public void cancel() {
 try {
 btSocket.close();
 } catch (IOException e){
 }
 }
 
 
 
/*------------------------------------------------------------------------------
 changeBackground(int bg0, int bg1, int bg2) method
 - A method to change the background colour of the phone screen
-----------------------------------------------------------------------------*/ 
 void changeBackground(int bg0, int bg1, int bg2){
 bg[0] = bg0;
 bg[1] = bg1;
 bg[2] = bg2; 
 } 
}


/*==============================================================================
 CLASS: btBroadcastReceiver extends BroadcastReceiver
 - Broadcasts a notification when the "SeeedBTSlave" is discovered/found.
 - Use this notification as a trigger to connect to the remote Bluetooth device
==================================================================================*/
public class btBroadcastReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
 String action=intent.getAction();
 /* Notification that BluetoothDevice is FOUND */
 if(BluetoothDevice.ACTION_FOUND.equals(action)){
 /* Get the discovered device Name */
 String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
 
 /* If the discovered Bluetooth device Name =SeeedBTSlave then CONNECT */
 if(discoveredDeviceName.equals("SeeedBTSlave")){ 
 /* Get a handle on the discovered device */
 btShield = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 /* Connect to the discovered device. */
 ConBTdevice.connect2Bt();
 }
 }
 }
}


Here is a picture of the components used in this sketch:
Bluetooth Shield with Grove RGB LED



Please take notice of the Jumper pin placement on the Bluetooth Shield. This ensures communication between the Arduino and Bluetooth Shield, and is reflected in the Arduino code further down this page. The Arduino transmits information to the Bluetooth Shield on Digital pin 7, and therefore the Bluetooth Shield receives information from the Arduino on Digital pin 7. On the other hand, the Bluetooth shield transmits and the Arduino receives information on Digital pin 6 (see picture below).  This serial communication between the Arduino and the Bluetooth Shield occurs through the SoftwareSerial library. This is different from the Serial library used in some of my other tutorials (often to display information in the Serial Monitor). The Arduino UNO's Serial pins are 0 (RX) and 1 (TX). It is worth looking at the Arduino Serial page if you happen to have an Arduino Leonardo, because there are some differences that you should take into consideration when running this sketch.



Jumpers on Shield


Make sure that your Arduino has the following code installed and running BEFORE you launch the Android/Processing Sketch on your Android Device. If you don't do it in this order, your Android phone will not discover the Bluetooth Device attached to the Arduino, and you will waste a lot of time. Make sure that the Bluetooth shield is flashing it's red/green LEDs. Once you see this alternating red/green LED display, launch the Android/Processing sketch on the Android device. When you see the chainable RGB LED turn from white to green, you know you have a successful connection. You may then press the GUI buttons on the Android phone to change the colour of the LED to either Red, Green, Blue or Off.

Arduino Sketch 3: Bluetooth RGB Colour Changer (with OFF option)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/* This project combines the code from a few different sources.
This project was put together by ScottC on the 15/01/2013
http://arduinobasics.blogspot.com/

Bluetooth slave code by Steve Chang - downloaded from :
http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield

Grove Chainable RGB code can be found here :
http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED#Introduction

Updated on 25 March 2013: Receive 'x' to turn off RGB LED.

*/
 
#include <SoftwareSerial.h> //Software Serial Port

#define uint8 unsigned char 
#define uint16 unsigned int
#define uint32 unsigned long int

#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
 
#define DEBUG_ENABLED 1

int Clkpin = 9; //RGB LED Clock Pin (Digital 9)
int Datapin = 8; //RGB LED Data Pin (Digital 8)
 
SoftwareSerial blueToothSerial(RxD,TxD);
/*----------------------SETUP----------------------------*/ void setup() { 
 Serial.begin(9600); // Allow Serial communication via USB cable to computer (if required)
 pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
 pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
 pinMode(13,OUTPUT); // Use onboard LED if required.
 setupBlueToothConnection(); //Used to initialise the Bluetooth shield
 
 pinMode(Datapin, OUTPUT); // Setup the RGB LED Data Pin
 pinMode(Clkpin, OUTPUT); // Setup the RGB LED Clock pin
 
} 
/*----------------------LOOP----------------------------*/ void loop() { 
 digitalWrite(13,LOW); //Turn off the onboard Arduino LED
 char recvChar;
 while(1){
 if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield
 recvChar = blueToothSerial.read();
 Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
 
 //If the character received = 'r' , then change the RGB led to display a RED colour
 if(recvChar=='r'){
 Send32Zero(); // begin
 DataDealWithAndSend(255, 0, 0); // first node data
 Send32Zero(); // send to update data 
 }
 
 //If the character received = 'g' , then change the RGB led to display a GREEN colour
 if(recvChar=='g'){
 Send32Zero(); // begin
 DataDealWithAndSend(0, 255, 0); // first node data
 Send32Zero(); // send to update data 
 }
 
 //If the character received = 'b' , then change the RGB led to display a BLUE colour
 if(recvChar=='b'){
 Send32Zero(); // begin
 DataDealWithAndSend(0, 0, 255); // first node data
 Send32Zero(); // send to update data 
 }
 
 //If the character received = 'x' , then turn RGB led OFF
 if(recvChar=='x'){
 Send32Zero(); // begin
 DataDealWithAndSend(0, 0, 0); // first node data
 Send32Zero(); // send to update data 
 }
 }
 
 //You can use the following code to deal with any information coming from the Computer (serial monitor)
 if(Serial.available()){
 recvChar = Serial.read();
 
 //This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
 blueToothSerial.print(recvChar);
 }
 }
} 

//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
 blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400
 blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
 blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
 blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
 blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
 delay(2000); // This delay is required.
 blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable 
 Serial.println("The slave bluetooth is inquirable!");
 delay(2000); // This delay is required.
 blueToothSerial.flush();
}

//The following code snippets are used update the colour of the RGB LED-----copy and paste------------
void ClkProduce(void){
 digitalWrite(Clkpin, LOW);
 delayMicroseconds(20); 
 digitalWrite(Clkpin, HIGH);
 delayMicroseconds(20); 
}
 void Send32Zero(void){
 unsigned char i;
 for (i=0; i<32; i++){
 digitalWrite(Datapin, LOW);
 ClkProduce();
 }
}
 
uint8 TakeAntiCode(uint8 dat){
 uint8 tmp = 0;
 if ((dat & 0x80) == 0){
 tmp |= 0x02; 
 }
 
 if ((dat & 0x40) == 0){
 tmp |= 0x01; 
 }
 
 return tmp;
}
 // gray data
void DatSend(uint32 dx){
 uint8 i;
 for (i=0; i<32; i++){
 if ((dx & 0x80000000) != 0){
 digitalWrite(Datapin, HIGH);
 } else {
 digitalWrite(Datapin, LOW);
 }
 
 dx <<= 1;
 ClkProduce();
 }
}
 // data processing
void DataDealWithAndSend(uint8 r, uint8 g, uint8 b){
 uint32 dx = 0;
 
 dx |= (uint32)0x03 << 30; // highest two bits 1,flag bits
 dx |= (uint32)TakeAntiCode(b) << 28;
 dx |= (uint32)TakeAntiCode(g) << 26; 
 dx |= (uint32)TakeAntiCode(r) << 24;
 
 dx |= (uint32)b << 16;
 dx |= (uint32)g << 8;
 dx |= r;
 
 DatSend(dx);
}


Please note that this Arduino code/project will work with SeeedStudio's Bluetooth Shield.  You may need to modify the Arduino Code (lines 95-107) to coincide with your own bluetooth shield. I got the code snippet within the my setupBlueToothConnection() method from some example code from Steve Chang which was found on SeeedStudio's Bluetooth Shield Wiki page. Here is some other useful information in relation to setting up this Bluetooth Shield that could be of help in your project (here).

Much of the code used within the Android/Processing sketch was made possible through constant reference to these sites:
And I would also like to thank Pauline303 who made the suggestion within the Processing Forums to use APWidgets Library for my Buttons in the App.
The Arduino and Processing Forums are always a great place to get help in a short amount of time.




58 comments:

  1. I am the former head of ecommerce for Billy Bob Teeth. They have landed a TV show on Discovery and filming starts on June 17th. The owner has asked me to bring one of my ideas for a product to life and demonstrate the product for the first episode. The arduino uno that I am using will have two switches and an OLED to read out how many button presses have occured. I am hoping to incorporate a TTL bluetooth module with the arduino that will post the amount of times each buttons has been pressed on an android app. While I was able to follow along with your tutorial quite easily, coding something that is totally different from your tutorial may take up more time than I may have to dedicate to this project. Could I offer you compensation for helping me complete this project?

    ReplyDelete
    Replies
    1. Hi Dustin,
      Thankyou for visiting this blog and for your consideration. I would love to help you, but I am studying at the moment and do not have any spare time to dedicate towards your project, especially considering the timeframe. Really sorry.
      Scott.

      Delete
  2. first when i try to connect using my phone its work great and then when i try to connect using other phone, bluetooth shield not discoverable. how can i make my bluetooth shield discoverable to other phone after first connection? or reset connection on bluetooth shield?
    sory for bad english.

    ReplyDelete
    Replies
    1. Hi Yantz,

      Perhaps you could attach a button to the Arduino (or bluetooth shield), so that when it is pressed it sends the Bluetooth shield some commands.

      The Arduino code/method responsible for setting up the bluetooth shield in the code above is void setupBlueToothConnection({...}

      Have a look at these documents/web pages, as they seem to have some useful commands for bluetooth devices (even though it is not the same bluetooth device used in this example, the code seems the same):
      Here and here


      This bluetooth tutorial is using the bluetooth module in Slave mode:
      And the following code may be what you are looking for:

      blueToothSerial.print("\r\n+INQ=0\r\n"); Disable been inquired
      blueToothSerial.print("\r\n+INQ=1\r\n"); Enable been inquired

      You may need to flush the bluetooth serial connection first by using:
      blueToothSerial.flush();

      Please note that I have not tried this myself, because I have limited time at the moment. So I hope it works for you. Good luck.

      Delete
    2. actualy i just need to disconnect the first pair and then call connection function. thanks for advice.

      Delete
  3. Hello, this has been a great help. However, my setup differs from yours. I have a simple bluetooth module http://dx.com/p/jy-mcu-arduino-bluetooth-wireless-serial-port-module-104299. How should I change the Arduino sketch to be more compatible with my current configuration? The Android app doesn't connect with the bluetooth module (the LED on it stays blinking which means it's NOT connected). However, it can see the bluetooth module and states it through the toasts. Thanks in advance.

    ReplyDelete
    Replies
    1. Hi RB,
      I don't have your bluetooth module, so am not sure what is the correct Arduino Setup, however, you may find the following article of use:

      Look here

      You may need to change the baud rate and a few other settings to get it to work. I accessed that document from the "discussions page" on the site you mentioned in your comment.

      But I am almost certain that you will need to modify the Arduino sketch in this tutorial to suit your specific bluetooth module.

      Good luck.

      Delete
    2. RB - also looks like this person has managed to get your bluetooth module to work on an Arduino, and made a YouTube video about it, they may be able to help you ??

      You tube video

      Delete
    3. RogueBanana that's an HC-05/06 Bluetooth module mounted on a JY-040 breakout board. It's very simple to use. You hook up the VCC and GND. The TX and Rx behave like TTL serial. That is, you use the Arduino's built in serial functions with a baud rate of 9600.

      On the BT side, it uses the same UUID for SPP so you just need to change the android code relating to the devices name/mac address which you can get from other apps like BlueTerm.

      If you need more information on the chip search for "CSR Bluecore EXT 4".

      Delete
    4. Sorry i meant JY-MCU, my board has ZS-040 written on it.

      Delete
  4. my PC doesn't run Processing...Can I use Android Studio?(Oficial IDE).. Thanks

    ReplyDelete
    Replies
    1. Hi FB.
      I had not heard of Android Studio until you mentioned it. Many of the concepts within my bluetooth tutorial originate from the Android developers website, however, I had to make some minor modifications to get it to work within the processing IDE. Considering that Android Studio comes from the Android developers website, I would say that yes, it would be possible to create an APP using that IDE to communicate to an Arduino via Bluetooth in a similar way to the one I described in my tutorial. However it would be very unlikely that you would be able to cut and paste my code. You would have to adapt it. Or you could start from scratch and utilise the bluetooth information from the Android developers website.

      You state that Android Studio is the official IDE, however you will probably find that there are hardly any bluetooth examples using it. In fact there were very few bluetooth examples using the Processing-Android IDE when I created my tutorial. There are many more examples using eclipse. Also bear in mind that Android Studio is only available as an "Early access preview" and according to the Android Developer's website, "Several features are either incomplete or not yet implemented and you may encounter bugs". But that should not stop you from trying.

      All the information is there, it is just a matter of sitting down and working it out :) Good luck.

      Scott

      Delete
  5. Hello Scott,

    Excellent article and well presented. I am a newbie to Arduino and bluetooth, and your article has helped me to understand the basics of Android OS communication with BT/Arduino. I was basically looking for text communication between the BT/Arduino and Android, with a little bit of tweaking it is working well with my setup. My setup consists of Arduino 2560 + BT + Samsung Note1 and the code is running like a charm. Thanks for your time and effort in making this article.

    ReplyDelete
    Replies
    1. Hi Metallica,
      Thanks for the feedback. And I am glad it worked for you.
      I would be interested in seeing a YouTube video of your project in action. Feel free to leave a link to it below (if you want to).

      Delete
  6. hi my name is miguel i am from mexico, i have a question, i used your Project only part one two and three, for discovery bluetooth and i running on my móvil, i saw when is discovering device show adressed and bond and name of the bluetooth devices of other android bluetooth, my question is if i want to connected to other android device what i need to do, is just connected byself or i need some kind of extra sketch, i want to do this for test the Project the conection between bluetooths the reason because i dont have a bluetooth device for complete the Project and i think if i can get conection between two androids device i guess the conection working thank you, every time i run the App show everithing but dont say nothing about to get connection.

    ReplyDelete
    Replies
    1. Hi Miguel,

      Sorry, you lost me a bit with your comment.
      What android device are you using, what bluetooth module are you using and what arduino are you using, and what are you trying to do? What is your final goal ?

      This may help me understand your question a bit better.

      Delete
    2. I know this is an older post, but I think he's asking if he could use your code to connect two android devices over bluetooth instead of connecting to an arduino BT module. He wants to test the bluetooth connection part of the project with another android instead of the arduino.

      Delete
  7. Hello Scott. Thanks for sharing these applications.

    I am using Part 4 to control my DIY Segway, but I find that connect() takes 30 seconds or more. Why is cancelDiscovery not called before connect? According to the Android Bluetooth tutorial, not calling cancelDiscovery will slow down the comms. So I tried calling cancelDiscovery before connect but the app crashes during connect. Is that why you don't call cancelDiscovery in part 4? Do you have suggested solution.

    ReplyDelete
    Replies
    1. Hi Carmelo,
      I think I did experience the same thing you did. Not sure why it crashes.
      So I left it out, and it worked.

      Delete
    2. I changed my program and based it on Part 3. It works very well -- I don't have to stop Bluetooth before running the program and it connects quickly. I would not recommend Part 4 - I think a single thread to do Bluetooth does not work properly,

      Delete
  8. Hi Scott, Thumbs up for sharing your very informative tutorial. I've noticed you do implement a cancel() method to close the Bluetooth socket, but it does not seem to be used in your code. I ask this because I am using a variation of your part 3 to read continuously from an ArduinoBT board with my Android 4.2 phone. First time it works perfectly, but if I get off the app with the Back or Home buttons and/or switch the ArduinoBT off, next time I want to reconnect it does so up to and including opening the streams (i.e: btSocket.getInputStream) but the inputstream.read(buffer) hangs, as if no bytes were received. I have to reboot the phone to properly reconnect again. So I'm thinking this could be a problem due to not properly closing streams and socket upon closing the app. Do you experience anything similar?

    Thanks again for your time and effort in sharing your work.

    ReplyDelete
    Replies
    1. Hi Claudio,

      It has been a while since I wrote this tutorial, but you are right, it is better if you can include a method to close the sockets cleanly.
      I did experience something similar to you, and yes, rebooting seemed to fix the issue. However, I vaguely remember that if your disconnected in a certain order, that you would not get this problem... But I cannot remember what order that was - it's been too long.
      Closing your sockets cleanly should fix the issue you are seeing.

      However, I also had the same issue if the bluetooth module went out of range... I got stuck in figuring out a way to manage that... if you have any ideas, I would love to hear them.


      Delete
  9. Scott, thanks for your quick reply! I'll keep on digging and post any relevant finding here, if any..

    ReplyDelete
  10. Hello Scott,

    I want to use your tutorial with arduino Mega ADK, and Bluetooth module ( FB155BC) like this :
    http://www.firmtech.co.kr/01pro/main_eng.php?index=100&proinfo=13
    before starting i want to know if these parts are compatible with all your sketch?

    thanks in advance for your help.
    regards

    ReplyDelete
    Replies
    1. Hi Laurent,

      Thank you for visiting my page. My experience with bluetooth has only been with the modules described in the tutorial. While I am sure, there may be parts of the sketches which could remain untouched, I am almost certain that the code would have to be adapted to suit the modules you queried about. And whether it will work with a Mega is anyone's guess, because I have never used one. Sorry, I am not an expert, but you may be able to find out through the various forums.
      Regards
      Scott

      Delete
  11. Hey, I was wondering if you would allow me to use your code for a project at school, I'm creating a simple bluetooth controller for one of my teachers, I was wondering if you would allow me to alter the code to fit the project and put put it on the google play store for my teacher's personal use?

    ReplyDelete
    Replies
    1. Hi +zachatttack,
      You are more than welcome to use my code, and alter it to suit your needs.
      I would appreciate however that you reference the ArduinoBasics blogspot site somewhere within your project description or code.
      And finally, feel free to create a link to your project in the comments below - I would love to see it.
      Regards
      Scott

      Delete
  12. It was an excellent piece of project to be shared which conveys about arduino programming, android programming and bluetooth of course. Thanks scott.

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    Can you let me know whether the above statements are predefined functions of the android? Thanks again..

    ReplyDelete
    Replies
    1. Hi Deepak,

      These are all android classes.
      Have a look at the android developers website.

      Also look at the other websites that I have recommended within the blog post. Very useful.

      Delete
    2. Thanks Scott,
      Yeah Scott. I will surely get through the tutorials. But I got some time limitations. Just one more last question. Pl don't mind. If I run your android programe on the IDE will I still be able to use my android phone for other usual purposes. In other words, will your application will run till I use process IDE on my desktop. If not how will I restore my actual state of my phone after executing the project?

      Delete
    3. Hi Deepak,
      The processing IDE uploads the program to the android phone in a similar way that the Arduino IDE uploads to the Arduino. However, you can exit out of this program on your phone in the same way you would exit any other program. Also once you have uploaded the program, you can detach the android phone from your computer. Plus you will see a shortcut to the program on your phone's desktop. So you can run it again without having to upload it again from your computer.

      Delete
    4. Hi scott. Just googled and got it. Thanks again... No more doubts. On my way to complete the project.

      Delete
    5. Good luck. I hope it goes well.

      Delete
  13. First off, excellent tutorial!! Everything works great.
    This question may have been answered at some point or another (which I apologize if it was and you've answered it a million times) but you mentioned being able to have data sent from the Arduino to the Android and displayed on the Android. I'm unable to have that done. Can you perhaps provide some guidance for this?? Ultimately, Id like to have the analogread pin data be sent to the tablet and stored on memory. Thanks!!

    ReplyDelete
    Replies
    1. Have a look at tutorial part 3 here. I think you will find most of what you are looking for in there.

      Delete
    2. I was able to implement the communication. Thanks!!

      Delete
    3. Can you please kindly elaborate a little how you transferred the arduino's analogread pins data to android ?

      Delete
  14. Hi Scott C , thank you for the tutorial , I am new to arduino android, I have my final year project can you please send me the files for the complete project at mosesmberwa@gmail.com

    ReplyDelete
    Replies
    1. All files can be downloaded and installed as per the links provided in the tutorials. I don't have a copy of them.

      Delete
  15. I read your whole step 3 twice but coudnt get the required info! can you kindly tell me which part will guide me for establishing arduino analog read pins data to be transferred to the app?

    ReplyDelete
    Replies
    1. Hi Farhad,
      I don't have any Analog readings going to the app in this tutorial, but if I wanted to do this, I would write the following in the Arduino code:
      blueToothSerial.print(analogRead(A0));

      This will send one analog reading to the Android device.
      You will need to get the android device to listen for this value and display it accordingly,
      I cannot remember if I accommodated for this in this Android sketch or not.

      Delete
  16. Thank you for your reply I will surely start working on it now and i am kind of a beginner in this stuff so please dont mind if I ask some silly questions :)

    ReplyDelete
  17. Hello Scott,

    Thanks for this wonderful tutorial. This helped me a lot starting from setting up the Processing for Android to create some simple app via processing.

    The question I have is I didn't find an option to communicate from Arduino to Android. As I am a basic user of JAVA may be I got mislead with the class and functions. I can able transmit the messages via Bluetooth from my Arduino but unable to receive them via Bluetooth in my android device.

    Regards,
    DREEM.

    ReplyDelete
  18. Hi scott!this is a wonderful tutorial.I now understand codes use in Bluetooth Processing. My problem now is: how can I make an APK file using the sketches?

    ReplyDelete
    Replies
    1. Good question - you will need to ask that one in the Processing Forums.
      However, when you run the processing sketches on your phone, it leaves behind a shortcut to the program. So you don't have to keep uploading it to the phone to get it to run.
      You can load it from the phone. Not sure if this is in an APK format - but you can ask in the forums... sorry I don't know.

      Delete
  19. hi scott!

    i understand the bluetooth process thanks to your guide. When I connect to the arduino bluetooth module, it ask the password of the module (i.e 1234). Does it have a code where the app is the one to input the password and confirm it? i search and found about "setpin()" something function. Do you know how to use this?

    ReplyDelete
    Replies
    1. No, have never tried to do this.
      The setpin() method looks like it would put you on the right track.
      I found this
      http://stackoverflow.com/questions/19774615/defining-passkey-for-android-bluetooth-connection

      Not sure if it helps or not - have not tried it.

      Delete
  20. There is someone who wrote this on the feedback form.: "Would you mind to gide me how can i write a part of bluetooth code witch will be added to the arduino (bipede) code so that i send command to the robot?

    I will really apprecchiate your help."


    I would advise for you to send me your query in the forum section of this blog (look for "Forum" at the top of this page).

    ReplyDelete
  21. Hi, thanks for tutorial.
    This tutorial was made with processing 2.0 but now we work with processing 3.0 and the code has a lot of error, What we can do?, How we can change the code?

    ReplyDelete
    Replies
    1. Not sure. Just work through the errors and try and fix each one by one. Maybe ask for help on each specific error in the processing forums... but don't expect them to fix the whole lot... Sorry - I have left this tutorial here for historical reasons.. but don't have the time at present to go back and fix it. I may get to it one day.

      Delete
  22. Hi , your tutorial was most informative tutorial i have ever seen , thanks. Actually your tutorial helped me a lot but I'm still confused and in the middle, i have project which it send the sensor data from Arduino to Processing and then displays it on application, the first stage without Bluetooth. when i tried to send the data from Arduino to processing the real time data can be displayed when i use the JAVA MODE instead of Android mode ,then when i try to change the same program to Android mode, it simply can't read because "import serial" is not defined in Android mode and shows me error so i can't transfer currently from arduino to Android while the phone is connected via USB and no need to Bluetooth at current stage.

    my second main question, later on if i want to transfer the real-time data via Bluetooth from Arduino to android applicationis that possible and how? your time is highly appreciated. Thanks in advance

    ReplyDelete
    Replies
    1. Hi Hala,

      Am not sure about the error in the first question.
      As for the second question - yes you can transfer data between Arduino and Android - but you would need to create an input stream.

      Delete
    2. Thanks for your response, I have already wrote the code and i found no compiling error for but when i tried to upload on phone i got error message: "unfortunately, "file_name" has stopped" i have tried with two phones. one of them it asked me to turn on the Bluetooth and the other i got the error message without asking for switching the Bluetooth, even though after switch it i got the error message, what can i do ? is this related to security of the phone that can't upload the file or what do u

      Delete
    3. This comment has been removed by a blog administrator.

      Delete
    4. Hala - Unless you have the same Processing IDE version, the same ADK etc etc and an older phone like Samsung Galaxy S2 - this tutorial is unlikely to work (without modification). I have provided all of the links that I used to create this tutorial... and I am sorry that this is now out of date... but treat it as a head start.. you will need to do your own research to get your device to work. I wish I could help you... but I can only tell you what I did to make it work... Current versions of Processing will probably handle the Output stream differently... so that is where I would start.

      Delete

Feel free to leave a comment about this tutorial below.
Any questions about your particular project should be asked in the ArduinoBasics forum.

Comments are moderated due to large amount of spam.