Monday, March 25, 2013

Bluetooth Android Processing 3

PART THREE


If you happened to land on this page and missed PART ONE, and PART TWO, I would advise you go back and read those sections first.

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


InputStream and OutputStream
We will now borrow some code from the Android developers site to help us to establish communication between the Android phone and the Bluetooth shield on the Arduino. By this stage we have already scanned and discovered the bluetooth device and made a successful connection. We now need to create an InputStream and OutputStream to handle the flow of communication between the devices. Let us start with the Android/Processing Side.
The Android Developers site suggests to create a new Thread to handle the incoming and outgoing bytes, because this task uses "blocking" calls. Blocking calls means that the application will appear to be frozen until the call completes. We will create a new Thread to receive bytes through the BluetoothSocket's InputStream, and will send bytes to the Arduino through the BluetoothSocket's OutputStream.
This Thread will continue to listen/send bytes for as long as needed, and will eventually close when we tell it to. We will also need a Handler() to act on any bytes received via the InputStream. The Handler is necessary to transfer information from the IO Thread to the main application thread. This is done by using a Message class. Here is a summary of relevant code that we will subsequently add to the ConnectBluetooth sketch (which was described in Part Two of this tutorial):

 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
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothSocket;
style="color: rgb(0, 0, 255);">import java.io.InputStream;
style="color: rgb(0, 0, 255);">import java.io.OutputStream;
style="color: rgb(0, 0, 255);">import android.os.Handler;
style="color: rgb(0, 0, 255);">import android.os.Message;
style="color: rgb(0, 0, 255);">import android.util.Log;

style="color: rgb(0, 128, 0);">// Message types used by the Handler
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(0, 0, 255);">final style="color: rgb(43, 145, 175);">int MESSAGE_WRITE = 1;
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(0, 0, 255);">final style="color: rgb(43, 145, 175);">int MESSAGE_READ = 2;

style="color: rgb(0, 128, 0);">// The Handler that gets information back from the Socket
style="color: rgb(0, 0, 255);">private style="color: rgb(0, 0, 255);">final Handler mHandler = style="color: rgb(0, 0, 255);">new Handler() {
@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void handleMessage(Message msg) {
style="color: rgb(0, 0, 255);">switch (msg.what) {
style="color: rgb(0, 0, 255);">case MESSAGE_WRITE:
style="color: rgb(0, 128, 0);">//Do something when writing
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case MESSAGE_READ:
style="color: rgb(0, 128, 0);">//Get the bytes from the msg.obj
style="color: rgb(43, 145, 175);">byte[] readBuf = (style="color: rgb(43, 145, 175);">byte[]) msg.obj;
style="color: rgb(0, 128, 0);">// construct a string from the valid bytes in the buffer
String readMessage = style="color: rgb(0, 0, 255);">new String(readBuf, 0, msg.arg1);
style="color: rgb(0, 0, 255);">break;
}
}
};



style="color: rgb(0, 0, 255);">private style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">SendReceiveBytes style="color: rgb(0, 0, 255);">implements Runnable {
style="color: rgb(0, 0, 255);">private BluetoothSocket btSocket;
style="color: rgb(0, 0, 255);">private InputStream btInputStream = style="color: rgb(0, 0, 255);">null;
style="color: rgb(0, 0, 255);">private OutputStream btOutputStream = style="color: rgb(0, 0, 255);">null;
String TAG = style="color: rgb(163, 21, 21);">"SendReceiveBytes";

style="color: rgb(0, 0, 255);">public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
style="color: rgb(0, 0, 255);">try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
style="color: rgb(0, 0, 255);">catch (IOException streamError) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when getting input or output Stream");
}
}

style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void run() {
style="color: rgb(43, 145, 175);">byte[] buffer = style="color: rgb(0, 0, 255);">new style="color: rgb(43, 145, 175);">byte[1024]; style="color: rgb(0, 128, 0);">// buffer store for the stream
style="color: rgb(43, 145, 175);">int bytes; style="color: rgb(0, 128, 0);">// bytes returned from read()

style="color: rgb(0, 128, 0);">// Keep listening to the InputStream until an exception occurs
style="color: rgb(0, 0, 255);">while (style="color: rgb(0, 0, 255);">true) {
style="color: rgb(0, 0, 255);">try {
style="color: rgb(0, 128, 0);">// Read from the InputStream
bytes = btInputStream.read(buffer);
style="color: rgb(0, 128, 0);">// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error reading from btInputStream");
style="color: rgb(0, 0, 255);">break;
}
}
}

style="color: rgb(0, 128, 0);">/* Call this from the main activity to send data to the remote device */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void write(style="color: rgb(43, 145, 175);">byte[] bytes) {
style="color: rgb(0, 0, 255);">try {
btOutputStream.write(bytes);
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when writing to btOutputStream");
}
}

style="color: rgb(0, 128, 0);">/* Call this from the main activity to shutdown the connection */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void cancel() {
style="color: rgb(0, 0, 255);">try {
btSocket.close();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when closing the btSocket");
}
}
}

Notice that we place an endless loop in the run() method to continuously read bytes from the InputStream. This continuous process of reading bytes needs to be a different thread from the main application otherwise it would cause the program to "hang". This thread passes any read bytes to the main application by using the Handler's .sendToTarget() method.
You will also notice the use of Log.e(TAG, ".....") commands. This is useful for debugging Android problems, especially when you comae across errors that generate a "caused the application to close unexpectedly" dialog box to appear on your phone.  I personally created a shortcut of the adb.exe on my desktop and changed the target to
  • "c:\[INSERT FOLDER]\Android\android-sdk\platform-tools\adb.exe" logcat *:E
The adb.exe program comes with the Android-SDK downloaded in Part One . Once you find the adb.exe on your hard-drive, you just create a shortcut on your desktop. Right-click the shortcut, choose "Properties" and as indicated above, you change the last bit of the Target to
  • logcat *:E
So if you get an unexpected error on your android device, just go back to your laptop, and double-click on your new desktop adb.exe shortcut to get a better idea of where your program has gone wrong.

We will now incorporate the sketch above into our ConnectBluetooth Android/Processing App, however we will call this updated version "SendReceiveBytes"
Once we have created a successful connection, and created our Input/OutputStreams, we will send a single letter "r" to the Arduino via bluetooth, and if all goes well, we should see the light on the RGB Chainable LED turn Red (see further down for Arduino sketch).
I borrowed Byron's code snippet from this site: to convert a string ("r") to a byte array, which is used in the write() method. The relevant code can be found on lines 199-208 below. I have bolded the lines numbers to make it a little easier to see the changes I made (compared to the previous sketch).

Android/Processing Sketch 6: SendReceiveBytes
 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
style="color: rgb(0, 128, 0);">/* SendReceiveBytes: Written by ScottC on 25 March 2013 using 
style="color: rgb(0, 128, 0);"> Processing version 2.0b8
style="color: rgb(0, 128, 0);"> Tested on a Samsung Galaxy SII, with Android version 2.3.4
style="color: rgb(0, 128, 0);"> Android ADK - API 10 SDK platform */

style="color: rgb(0, 0, 255);">import android.content.BroadcastReceiver;
style="color: rgb(0, 0, 255);">import android.content.Context;
style="color: rgb(0, 0, 255);">import android.content.Intent;
style="color: rgb(0, 0, 255);">import android.content.IntentFilter;
style="color: rgb(0, 0, 255);">import android.widget.Toast;
style="color: rgb(0, 0, 255);">import android.view.Gravity;
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothAdapter;
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothDevice;

style="color: rgb(0, 0, 255);">import java.util.UUID;
style="color: rgb(0, 0, 255);">import java.io.IOException;
style="color: rgb(0, 0, 255);">import java.io.InputStream;
style="color: rgb(0, 0, 255);">import java.io.OutputStream;
style="color: rgb(0, 0, 255);">import android.os.Handler;
style="color: rgb(0, 0, 255);">import android.os.Message;
style="color: rgb(0, 0, 255);">import android.util.Log;

style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothServerSocket;
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothSocket;
style="color: rgb(0, 0, 255);">public BluetoothSocket scSocket;


style="color: rgb(43, 145, 175);">boolean foundDevice=style="color: rgb(0, 0, 255);">false; style="color: rgb(0, 128, 0);">//When true, the screen turns green.
style="color: rgb(43, 145, 175);">boolean BTisConnected=style="color: rgb(0, 0, 255);">false; style="color: rgb(0, 128, 0);">//When true, the screen turns purple.
String serverName = style="color: rgb(163, 21, 21);">"ArduinoBasicsServer";

style="color: rgb(0, 128, 0);">// Message types used by the Handler
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(0, 0, 255);">final style="color: rgb(43, 145, 175);">int MESSAGE_WRITE = 1;
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(0, 0, 255);">final style="color: rgb(43, 145, 175);">int MESSAGE_READ = 2;
String readMessage=style="color: rgb(163, 21, 21);">"";

style="color: rgb(0, 128, 0);">//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

style="color: rgb(0, 128, 0);">/*The startActivityForResult() within setup() launches an
style="color: rgb(0, 128, 0);"> Activity which is used to request the user to turn Bluetooth on.
style="color: rgb(0, 128, 0);"> The following onActivityResult() method is called when this
style="color: rgb(0, 128, 0);"> Activity exits. */
@Override
style="color: rgb(0, 0, 255);">protected style="color: rgb(43, 145, 175);">void onActivityResult(style="color: rgb(43, 145, 175);">int requestCode, style="color: rgb(43, 145, 175);">int resultCode, Intent data) {
style="color: rgb(0, 0, 255);">if (requestCode==0) {
style="color: rgb(0, 0, 255);">if (resultCode == RESULT_OK) {
ToastMaster(style="color: rgb(163, 21, 21);">"Bluetooth has been switched ON");
}
style="color: rgb(0, 0, 255);">else {
ToastMaster(style="color: rgb(163, 21, 21);">"You need to turn Bluetooth ON !!!");
}
}
}


style="color: rgb(0, 128, 0);">/* Create a BroadcastReceiver that will later be used to
style="color: rgb(0, 128, 0);"> receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = style="color: rgb(0, 0, 255);">new myOwnBroadcastReceiver();


style="color: rgb(0, 128, 0);">/* Create a BroadcastReceiver that will later be used to
style="color: rgb(0, 128, 0);"> identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = style="color: rgb(0, 0, 255);">new myOwnBroadcastReceiver();


style="color: rgb(0, 128, 0);">// The Handler that gets information back from the Socket
style="color: rgb(0, 0, 255);">private style="color: rgb(0, 0, 255);">final Handler mHandler = style="color: rgb(0, 0, 255);">new Handler() {
@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void handleMessage(Message msg) {
style="color: rgb(0, 0, 255);">switch (msg.what) {
style="color: rgb(0, 0, 255);">case MESSAGE_WRITE:
style="color: rgb(0, 128, 0);">//Do something when writing
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case MESSAGE_READ:
style="color: rgb(0, 128, 0);">//Get the bytes from the msg.obj
style="color: rgb(43, 145, 175);">byte[] readBuf = (style="color: rgb(43, 145, 175);">byte[]) msg.obj;
style="color: rgb(0, 128, 0);">// construct a string from the valid bytes in the buffer
readMessage = style="color: rgb(0, 0, 255);">new String(readBuf, 0, msg.arg1);
style="color: rgb(0, 0, 255);">break;
}
}
};


style="color: rgb(43, 145, 175);">void setup() {
orientation(LANDSCAPE);
style="color: rgb(0, 128, 0);">/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
style="color: rgb(0, 0, 255);">if (!bluetooth.isEnabled()) {
Intent requestBluetooth = style="color: rgb(0, 0, 255);">new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}


style="color: rgb(0, 128, 0);">/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
style="color: rgb(0, 128, 0);"> discovered Bluetooth devices, and then start discovering */
style="color: rgb(0, 0, 255);">if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, style="color: rgb(0, 0, 255);">new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, style="color: rgb(0, 0, 255);">new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

style="color: rgb(0, 128, 0);">//Start bluetooth discovery if it is not doing so already
style="color: rgb(0, 0, 255);">if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}


style="color: rgb(43, 145, 175);">void draw() {
style="color: rgb(0, 128, 0);">//Display a green screen if a device has been found,
style="color: rgb(0, 128, 0);">//Display a purple screen when a connection is made to the device
style="color: rgb(0, 0, 255);">if (foundDevice) {
style="color: rgb(0, 0, 255);">if (BTisConnected) {
background(170, 50, 255); style="color: rgb(0, 128, 0);">// purple screen
}
style="color: rgb(0, 0, 255);">else {
background(10, 255, 10); style="color: rgb(0, 128, 0);">// green screen
}
}

style="color: rgb(0, 128, 0);">//Display anything received from Arduino
text(readMessage, 10, 10);
}


style="color: rgb(0, 128, 0);">/* This BroadcastReceiver will display discovered Bluetooth devices */
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">myOwnBroadcastReceiver style="color: rgb(0, 0, 255);">extends BroadcastReceiver {
ConnectToBluetooth connectBT;

@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster(style="color: rgb(163, 21, 21);">"ACTION:" + action);

style="color: rgb(0, 128, 0);">//Notification that BluetoothDevice is FOUND
style="color: rgb(0, 0, 255);">if (BluetoothDevice.ACTION_FOUND.equals(action)) {
style="color: rgb(0, 128, 0);">//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster(style="color: rgb(163, 21, 21);">"Discovered: " + discoveredDeviceName);

style="color: rgb(0, 128, 0);">//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster(style="color: rgb(163, 21, 21);">"getAddress() = " + discoveredDevice.getAddress());
ToastMaster(style="color: rgb(163, 21, 21);">"getName() = " + discoveredDevice.getName());

style="color: rgb(43, 145, 175);">int bondyState=discoveredDevice.getBondState();
ToastMaster(style="color: rgb(163, 21, 21);">"getBondState() = " + bondyState);

String mybondState;
style="color: rgb(0, 0, 255);">switch(bondyState) {
style="color: rgb(0, 0, 255);">case 10:
mybondState=style="color: rgb(163, 21, 21);">"BOND_NONE";
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case 11:
mybondState=style="color: rgb(163, 21, 21);">"BOND_BONDING";
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case 12:
mybondState=style="color: rgb(163, 21, 21);">"BOND_BONDED";
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">default:
mybondState=style="color: rgb(163, 21, 21);">"INVALID BOND STATE";
style="color: rgb(0, 0, 255);">break;
}
ToastMaster(style="color: rgb(163, 21, 21);">"getBondState() = " + mybondState);

style="color: rgb(0, 128, 0);">//Change foundDevice to true which will make the screen turn green
foundDevice=style="color: rgb(0, 0, 255);">true;

style="color: rgb(0, 128, 0);">//Connect to the discovered bluetooth device (SeeedBTSlave)
style="color: rgb(0, 0, 255);">if (discoveredDeviceName.equals(style="color: rgb(163, 21, 21);">"SeeedBTSlave")) {
ToastMaster(style="color: rgb(163, 21, 21);">"Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = style="color: rgb(0, 0, 255);">new ConnectToBluetooth(discoveredDevice);
style="color: rgb(0, 128, 0);">//Connect to the the device in a new thread
style="color: rgb(0, 0, 255);">new Thread(connectBT).start();
}
}

style="color: rgb(0, 128, 0);">//Notification if bluetooth device is connected
style="color: rgb(0, 0, 255);">if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster(style="color: rgb(163, 21, 21);">"CONNECTED _ YAY");

style="color: rgb(0, 0, 255);">while (scSocket==style="color: rgb(0, 0, 255);">null) {
style="color: rgb(0, 128, 0);">//do nothing
}
ToastMaster(style="color: rgb(163, 21, 21);">"scSocket" + scSocket);
BTisConnected=style="color: rgb(0, 0, 255);">true; style="color: rgb(0, 128, 0);">//turn screen purple
style="color: rgb(0, 0, 255);">if (scSocket!=style="color: rgb(0, 0, 255);">null) {
SendReceiveBytes sendReceiveBT = style="color: rgb(0, 0, 255);">new SendReceiveBytes(scSocket);
style="color: rgb(0, 0, 255);">new Thread(sendReceiveBT).start();
String red = style="color: rgb(163, 21, 21);">"r";
style="color: rgb(43, 145, 175);">byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(43, 145, 175);">byte[] stringToBytesUTFCustom(String str) {
style="color: rgb(43, 145, 175);">char[] buffer = str.toCharArray();
style="color: rgb(43, 145, 175);">byte[] b = style="color: rgb(0, 0, 255);">new style="color: rgb(43, 145, 175);">byte[buffer.length << 1];
style="color: rgb(0, 0, 255);">for (style="color: rgb(43, 145, 175);">int i = 0; i < buffer.length; i++) {
style="color: rgb(43, 145, 175);">int bpos = i << 1;
b[bpos] = (style="color: rgb(43, 145, 175);">byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (style="color: rgb(43, 145, 175);">byte) (buffer[i]&0x00FF);
}
style="color: rgb(0, 0, 255);">return b;
}

style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">ConnectToBluetooth style="color: rgb(0, 0, 255);">implements Runnable {
style="color: rgb(0, 0, 255);">private BluetoothDevice btShield;
style="color: rgb(0, 0, 255);">private BluetoothSocket mySocket = style="color: rgb(0, 0, 255);">null;
style="color: rgb(0, 0, 255);">private UUID uuid = UUID.fromString(style="color: rgb(163, 21, 21);">"00001101-0000-1000-8000-00805F9B34FB");

style="color: rgb(0, 0, 255);">public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
style="color: rgb(0, 0, 255);">try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
style="color: rgb(0, 0, 255);">catch(IOException createSocketException) {
style="color: rgb(0, 128, 0);">//Problem with creating a socket
Log.e(style="color: rgb(163, 21, 21);">"ConnectToBluetooth", style="color: rgb(163, 21, 21);">"Error with Socket");
}
}

@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void run() {
style="color: rgb(0, 128, 0);">/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

style="color: rgb(0, 0, 255);">try {
style="color: rgb(0, 128, 0);">/*Connect to the bluetoothShield through the Socket. This will block
style="color: rgb(0, 128, 0);"> until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
style="color: rgb(0, 0, 255);">catch (IOException connectException) {
Log.e(style="color: rgb(163, 21, 21);">"ConnectToBluetooth", style="color: rgb(163, 21, 21);">"Error with Socket Connection");
style="color: rgb(0, 0, 255);">try {
mySocket.close(); style="color: rgb(0, 128, 0);">//try to close the socket
}
style="color: rgb(0, 0, 255);">catch(IOException closeException) {
}
style="color: rgb(0, 0, 255);">return;
}
}

style="color: rgb(0, 128, 0);">/* Will cancel an in-progress connection, and close the socket */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void cancel() {
style="color: rgb(0, 0, 255);">try {
mySocket.close();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
}
}
}


style="color: rgb(0, 0, 255);">private style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">SendReceiveBytes style="color: rgb(0, 0, 255);">implements Runnable {
style="color: rgb(0, 0, 255);">private BluetoothSocket btSocket;
style="color: rgb(0, 0, 255);">private InputStream btInputStream = style="color: rgb(0, 0, 255);">null;
style="color: rgb(0, 0, 255);">private OutputStream btOutputStream = style="color: rgb(0, 0, 255);">null;
String TAG = style="color: rgb(163, 21, 21);">"SendReceiveBytes";

style="color: rgb(0, 0, 255);">public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
style="color: rgb(0, 0, 255);">try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
style="color: rgb(0, 0, 255);">catch (IOException streamError) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when getting input or output Stream");
}
}


style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void run() {
style="color: rgb(43, 145, 175);">byte[] buffer = style="color: rgb(0, 0, 255);">new style="color: rgb(43, 145, 175);">byte[1024]; style="color: rgb(0, 128, 0);">// buffer store for the stream
style="color: rgb(43, 145, 175);">int bytes; style="color: rgb(0, 128, 0);">// bytes returned from read()

style="color: rgb(0, 128, 0);">// Keep listening to the InputStream until an exception occurs
style="color: rgb(0, 0, 255);">while (style="color: rgb(0, 0, 255);">true) {
style="color: rgb(0, 0, 255);">try {
style="color: rgb(0, 128, 0);">// Read from the InputStream
bytes = btInputStream.read(buffer);
style="color: rgb(0, 128, 0);">// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error reading from btInputStream");
style="color: rgb(0, 0, 255);">break;
}
}
}


style="color: rgb(0, 128, 0);">/* Call this from the main activity to send data to the remote device */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void write(style="color: rgb(43, 145, 175);">byte[] bytes) {
style="color: rgb(0, 0, 255);">try {
btOutputStream.write(bytes);
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when writing to btOutputStream");
}
}


style="color: rgb(0, 128, 0);">/* Call this from the main activity to shutdown the connection */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void cancel() {
style="color: rgb(0, 0, 255);">try {
btSocket.close();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when closing the btSocket");
}
}
}



style="color: rgb(0, 128, 0);">/* My ToastMaster function to display a messageBox on the screen */
style="color: rgb(43, 145, 175);">void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}


Arduino Sketch: Testing the Input/OutputStream
We will borrow the Arduino Sketch from my previous blog post (here). Which should change the RGB LED to red when it receives an "r" through the bluetooth serial port.
You should also be able to send text to the Android phone by opening up the Serial Monitor on the Arduino IDE (although found this to be somewhat unreliable/unpredictable. I may need to investigate a better way of doing this, but it should work to some capacity (I sometimes find that a couple of letters go missing on transmision).
In this sketch I am using a Bluetooth shield like this one,  and have connected a Grove Chainable RGB LED to it using a Grove Universal 4 Pin Cable.

Bluetooth Shield with Grove RGB LED

Arduino Sketch 2: Bluetooth RGB Colour Changer

 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
style="color: rgb(0, 128, 0);">/* This project combines the code from a few different sources.
style="color: rgb(0, 128, 0);">This project was put together by ScottC on the 15/01/2013
style="color: rgb(0, 128, 0);">http://arduinobasics.blogspot.com/

style="color: rgb(0, 128, 0);">Bluetooth slave code by Steve Chang - downloaded from :
style="color: rgb(0, 128, 0);">http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield

style="color: rgb(0, 128, 0);">Grove Chainable RGB code can be found here :
style="color: rgb(0, 128, 0);">http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED#Introduction

style="color: rgb(0, 128, 0);">*/

#include <SoftwareSerial.h> style="color: rgb(0, 128, 0);">//Software Serial Port

#define uint8 unsigned style="color: rgb(43, 145, 175);">char
#define uint16 unsigned style="color: rgb(43, 145, 175);">int
#define uint32 unsigned style="color: rgb(43, 145, 175);">long style="color: rgb(43, 145, 175);">int

#define RxD 6 style="color: rgb(0, 128, 0);">// This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 style="color: rgb(0, 128, 0);">// This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

#define DEBUG_ENABLED 1

style="color: rgb(43, 145, 175);">int Clkpin = 9; style="color: rgb(0, 128, 0);">//RGB LED Clock Pin (Digital 9)
style="color: rgb(43, 145, 175);">int Datapin = 8; style="color: rgb(0, 128, 0);">//RGB LED Data Pin (Digital 8)

SoftwareSerial blueToothSerial(RxD,TxD);
style="color: rgb(0, 128, 0);">/*----------------------SETUP----------------------------*/ style="color: rgb(43, 145, 175);">void setup() {
Serial.begin(9600); style="color: rgb(0, 128, 0);">// Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); style="color: rgb(0, 128, 0);">// Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); style="color: rgb(0, 128, 0);">// Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13,OUTPUT); style="color: rgb(0, 128, 0);">// Use onboard LED if required.
setupBlueToothConnection(); style="color: rgb(0, 128, 0);">//Used to initialise the Bluetooth shield

pinMode(Datapin, OUTPUT); style="color: rgb(0, 128, 0);">// Setup the RGB LED Data Pin
pinMode(Clkpin, OUTPUT); style="color: rgb(0, 128, 0);">// Setup the RGB LED Clock pin

}
style="color: rgb(0, 128, 0);">/*----------------------LOOP----------------------------*/ style="color: rgb(43, 145, 175);">void loop() {
digitalWrite(13,LOW); style="color: rgb(0, 128, 0);">//Turn off the onboard Arduino LED
style="color: rgb(43, 145, 175);">char recvChar;
style="color: rgb(0, 0, 255);">while(1){
style="color: rgb(0, 0, 255);">if(blueToothSerial.available()){style="color: rgb(0, 128, 0);">//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); style="color: rgb(0, 128, 0);">// Print the character received to the Serial Monitor (if required)

style="color: rgb(0, 128, 0);">//If the character received = 'r' , then change the RGB led to display a RED colour
style="color: rgb(0, 0, 255);">if(recvChar==style="color: rgb(163, 21, 21);">'r'){
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(255, 0, 0); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}

style="color: rgb(0, 128, 0);">//If the character received = 'g' , then change the RGB led to display a GREEN colour
style="color: rgb(0, 0, 255);">if(recvChar==style="color: rgb(163, 21, 21);">'g'){
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(0, 255, 0); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}

style="color: rgb(0, 128, 0);">//If the character received = 'b' , then change the RGB led to display a BLUE colour
style="color: rgb(0, 0, 255);">if(recvChar==style="color: rgb(163, 21, 21);">'b'){
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(0, 0, 255); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}
}

style="color: rgb(0, 128, 0);">//You can use the following code to deal with any information coming from the Computer (serial monitor)
style="color: rgb(0, 0, 255);">if(Serial.available()){
recvChar = Serial.read();

style="color: rgb(0, 128, 0);">//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
}
}
}

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

style="color: rgb(0, 128, 0);">//The following code snippets are used update the colour of the RGB LED-----copy and paste------------
style="color: rgb(43, 145, 175);">void ClkProduce(style="color: rgb(43, 145, 175);">void){
digitalWrite(Clkpin, LOW);
delayMicroseconds(20);
digitalWrite(Clkpin, HIGH);
delayMicroseconds(20);
}
style="color: rgb(43, 145, 175);">void Send32Zero(style="color: rgb(43, 145, 175);">void){
unsigned style="color: rgb(43, 145, 175);">char i;
style="color: rgb(0, 0, 255);">for (i=0; i<32; i++){
digitalWrite(Datapin, LOW);
ClkProduce();
}
}

uint8 TakeAntiCode(uint8 dat){
uint8 tmp = 0;
style="color: rgb(0, 0, 255);">if ((dat & 0x80) == 0){
tmp |= 0x02;
}

style="color: rgb(0, 0, 255);">if ((dat & 0x40) == 0){
tmp |= 0x01;
}

style="color: rgb(0, 0, 255);">return tmp;
}
style="color: rgb(0, 128, 0);">// gray data
style="color: rgb(43, 145, 175);">void DatSend(uint32 dx){
uint8 i;
style="color: rgb(0, 0, 255);">for (i=0; i<32; i++){
style="color: rgb(0, 0, 255);">if ((dx & 0x80000000) != 0){
digitalWrite(Datapin, HIGH);
} style="color: rgb(0, 0, 255);">else {
digitalWrite(Datapin, LOW);
}

dx <<= 1;
ClkProduce();
}
}
style="color: rgb(0, 128, 0);">// data processing
style="color: rgb(43, 145, 175);">void DataDealWithAndSend(uint8 r, uint8 g, uint8 b){
uint32 dx = 0;

dx |= (uint32)0x03 << 30; style="color: rgb(0, 128, 0);">// 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);
}



Some GUI Buttons

My aim is to somewhat recreate the experience from a similar project I blogged about (here). However I wanted to have much more control over the GUI. I will start by creating a few buttons, but will later look at making a much more fun/interactive design (hopefully). The following simple Android/Processing sketch will be totally independant of the sketch above, it will be a simple App that will have a few buttons which will change the colour of the background on the phone. Once we get the hang of this, we will incorporate it into our Bluetooth Sketch.
To start off with, we will need to download an Android/Processing library which will allow us to create the buttons that we will use in our App.
Unzip the apwidgets_r44.zip file and put the apwidgets folder into your default Processing sketch "libraries" folder. For more information about installing contributed libraries into you Processing IDE - have a look at this site.
You will need to reboot your Processing IDE before being able to see the "apwidgets" item appear in the Processing IDE's menu,
  • Sketch > Import Library :  Under the "Contributed" list item.
If you cannot see this menu item, then you will need to try again. Make sure you are putting it into the default sketch libraries folder, which may not be in the same folder as the processing IDE. To find out the default sketch location - look here:
  • File > Preferences > Sketchbook location
Ok, now that you have the APWidgets library installed in your Processing IDE, make sure you are still in Andorid Mode, and copy the following sketch into the IDE, and run the program on your device. This sketch borrows heavily from the APWidgets Button example, which can be found here.

Android/Processing Sketch 7: Button Presser
 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
style="color: rgb(0, 0, 255);">import apwidgets.*;

APWidgetContainer widgetContainer;
APButton redButton, greenButton, blueButton, offButton;
String buttonText=style="color: rgb(163, 21, 21);">"";
style="color: rgb(43, 145, 175);">int buttonWidth=0;
style="color: rgb(43, 145, 175);">int buttonHeight=0;
style="color: rgb(43, 145, 175);">int n=4; style="color: rgb(0, 128, 0);">//number of buttons
style="color: rgb(43, 145, 175);">int gap=10; style="color: rgb(0, 128, 0);">//gap between buttons


style="color: rgb(43, 145, 175);">void setup() {
buttonWidth=((width/n)-(n*gap));
buttonHeight=(height/2);
widgetContainer = style="color: rgb(0, 0, 255);">new APWidgetContainer(style="color: rgb(0, 0, 255);">this); style="color: rgb(0, 128, 0);">//create new container for widgets
redButton =style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-4)+(gap*1)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"RED"); style="color: rgb(0, 128, 0);">//Create a RED button
greenButton = style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-3)+(gap*2)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"GREEN"); style="color: rgb(0, 128, 0);">//Create a GREEN button
blueButton = style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-2)+(gap*3)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"BLUE"); style="color: rgb(0, 128, 0);">//Create a BLUE button
offButton = style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-1)+(gap*4)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"OFF"); style="color: rgb(0, 128, 0);">//Create a OFF button
widgetContainer.addWidget(redButton); style="color: rgb(0, 128, 0);">//place red button in container
widgetContainer.addWidget(greenButton); style="color: rgb(0, 128, 0);">//place green button in container
widgetContainer.addWidget(blueButton);style="color: rgb(0, 128, 0);">//place blue button in container
widgetContainer.addWidget(offButton);style="color: rgb(0, 128, 0);">//place off button in container
background(0); style="color: rgb(0, 128, 0);">//Start with a black background
}



style="color: rgb(43, 145, 175);">void draw() {
style="color: rgb(0, 128, 0);">//Change the text based on the button being pressed.
text(buttonText, 10, buttonHeight+(buttonHeight/2));
}



style="color: rgb(0, 128, 0);">//onClickWidget is called when a widget is clicked/touched
style="color: rgb(43, 145, 175);">void onClickWidget(APWidget widget) {

style="color: rgb(0, 0, 255);">if (widget == redButton) { style="color: rgb(0, 128, 0);">//if the red button was clicked
buttonText=style="color: rgb(163, 21, 21);">"RED";
background(255, 0, 0);
}
style="color: rgb(0, 0, 255);">else if (widget == greenButton) { style="color: rgb(0, 128, 0);">//if the green button was clicked
buttonText=style="color: rgb(163, 21, 21);">"GREEN";
background(0, 255, 0);
}
style="color: rgb(0, 0, 255);">else if (widget == blueButton) { style="color: rgb(0, 128, 0);">//if the blue button was clicked
buttonText=style="color: rgb(163, 21, 21);">"BLUE";
background(0, 0, 255);
}
style="color: rgb(0, 0, 255);">else if (widget == offButton) { style="color: rgb(0, 128, 0);">//if the off button was clicked
buttonText=style="color: rgb(163, 21, 21);">"OFF";
background(0);
}
}

The sketch creates 4 buttons, one for Red, Green, Blue and Off. In this example, we use the onClickWidget() method to deal with button_click events, which we use to change the colour of the background.  I forgot to include the following line in the setup() method:
  • orientation(LANDSCAPE);
This will force the application to go into landscape mode, which is what I intended.


Bluetooth Buttons : Adding Buttons to the Bluetooth project

We will now incorporate the Buttons sketch into our Bluetooth project so that when we press a button, it will send a letter to the Arduino via Bluetooth. The letter will be used by the Arduino to decide what colour to display on the Chainable RGB LED. We will still keep the previous functionality of changing the LED to RED when a successful Input/OutputStream is created, because this will be the signal to suggest that it is now ok to press the buttons (and we should see it work).

Here is the updated Android/Processing sketch

Android/Processing Sketch 8: Bluetooth App1

 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
style="color: rgb(0, 128, 0);">/* BluetoothApp1: Written by ScottC on 25 March 2013 using 
style="color: rgb(0, 128, 0);"> Processing version 2.0b8
style="color: rgb(0, 128, 0);"> Tested on a Samsung Galaxy SII, with Android version 2.3.4
style="color: rgb(0, 128, 0);"> Android ADK - API 10 SDK platform
style="color: rgb(0, 128, 0);"> Apwidgets version: r44 */

style="color: rgb(0, 0, 255);">import android.content.BroadcastReceiver;
style="color: rgb(0, 0, 255);">import android.content.Context;
style="color: rgb(0, 0, 255);">import android.content.Intent;
style="color: rgb(0, 0, 255);">import android.content.IntentFilter;
style="color: rgb(0, 0, 255);">import android.widget.Toast;
style="color: rgb(0, 0, 255);">import android.view.Gravity;
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothAdapter;
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothDevice;

style="color: rgb(0, 0, 255);">import java.util.UUID;
style="color: rgb(0, 0, 255);">import java.io.IOException;
style="color: rgb(0, 0, 255);">import java.io.InputStream;
style="color: rgb(0, 0, 255);">import java.io.OutputStream;
style="color: rgb(0, 0, 255);">import android.os.Handler;
style="color: rgb(0, 0, 255);">import android.os.Message;
style="color: rgb(0, 0, 255);">import android.util.Log;

style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothServerSocket;
style="color: rgb(0, 0, 255);">import android.bluetooth.BluetoothSocket;
style="color: rgb(0, 0, 255);">import apwidgets.*;
style="color: rgb(0, 0, 255);">public BluetoothSocket scSocket;


style="color: rgb(0, 128, 0);">//Used for the GUI**************************************
APWidgetContainer widgetContainer;
APButton redButton, greenButton, blueButton, offButton;
String buttonText=style="color: rgb(163, 21, 21);">"";
style="color: rgb(43, 145, 175);">int buttonWidth=0;
style="color: rgb(43, 145, 175);">int buttonHeight=0;
style="color: rgb(43, 145, 175);">int n=4; style="color: rgb(0, 128, 0);">//number of buttons
style="color: rgb(43, 145, 175);">int gap=10; style="color: rgb(0, 128, 0);">//gap between buttons

style="color: rgb(43, 145, 175);">boolean foundDevice=style="color: rgb(0, 0, 255);">false; style="color: rgb(0, 128, 0);">//When true, the screen turns green.
style="color: rgb(43, 145, 175);">boolean BTisConnected=style="color: rgb(0, 0, 255);">false; style="color: rgb(0, 128, 0);">//When true, the screen turns purple.
String serverName = style="color: rgb(163, 21, 21);">"ArduinoBasicsServer";

style="color: rgb(0, 128, 0);">// Message types used by the Handler
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(0, 0, 255);">final style="color: rgb(43, 145, 175);">int MESSAGE_WRITE = 1;
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(0, 0, 255);">final style="color: rgb(43, 145, 175);">int MESSAGE_READ = 2;
String readMessage=style="color: rgb(163, 21, 21);">"";

style="color: rgb(0, 128, 0);">//Used to send bytes to the Arduino
SendReceiveBytes sendReceiveBT=style="color: rgb(0, 0, 255);">null;

style="color: rgb(0, 128, 0);">//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

style="color: rgb(0, 128, 0);">/*The startActivityForResult() within setup() launches an
style="color: rgb(0, 128, 0);"> Activity which is used to request the user to turn Bluetooth on.
style="color: rgb(0, 128, 0);"> The following onActivityResult() method is called when this
style="color: rgb(0, 128, 0);"> Activity exits. */
@Override
style="color: rgb(0, 0, 255);">protected style="color: rgb(43, 145, 175);">void onActivityResult(style="color: rgb(43, 145, 175);">int requestCode, style="color: rgb(43, 145, 175);">int resultCode, Intent data) {
style="color: rgb(0, 0, 255);">if (requestCode==0) {
style="color: rgb(0, 0, 255);">if (resultCode == RESULT_OK) {
ToastMaster(style="color: rgb(163, 21, 21);">"Bluetooth has been switched ON");
}
style="color: rgb(0, 0, 255);">else {
ToastMaster(style="color: rgb(163, 21, 21);">"You need to turn Bluetooth ON !!!");
}
}
}


style="color: rgb(0, 128, 0);">/* Create a BroadcastReceiver that will later be used to
style="color: rgb(0, 128, 0);"> receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = style="color: rgb(0, 0, 255);">new myOwnBroadcastReceiver();


style="color: rgb(0, 128, 0);">/* Create a BroadcastReceiver that will later be used to
style="color: rgb(0, 128, 0);"> identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = style="color: rgb(0, 0, 255);">new myOwnBroadcastReceiver();



style="color: rgb(0, 128, 0);">// The Handler that gets information back from the Socket
style="color: rgb(0, 0, 255);">private style="color: rgb(0, 0, 255);">final Handler mHandler = style="color: rgb(0, 0, 255);">new Handler() {
@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void handleMessage(Message msg) {
style="color: rgb(0, 0, 255);">switch (msg.what) {
style="color: rgb(0, 0, 255);">case MESSAGE_WRITE:
style="color: rgb(0, 128, 0);">//Do something when writing
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case MESSAGE_READ:
style="color: rgb(0, 128, 0);">//Get the bytes from the msg.obj
style="color: rgb(43, 145, 175);">byte[] readBuf = (style="color: rgb(43, 145, 175);">byte[]) msg.obj;
style="color: rgb(0, 128, 0);">// construct a string from the valid bytes in the buffer
readMessage = style="color: rgb(0, 0, 255);">new String(readBuf, 0, msg.arg1);
style="color: rgb(0, 0, 255);">break;
}
}
};



style="color: rgb(43, 145, 175);">void setup() {
orientation(LANDSCAPE);

style="color: rgb(0, 128, 0);">//Setup GUI********************************
buttonWidth=((width/n)-(n*gap));
buttonHeight=(height/2);
widgetContainer = style="color: rgb(0, 0, 255);">new APWidgetContainer(style="color: rgb(0, 0, 255);">this); style="color: rgb(0, 128, 0);">//create new container for widgets
redButton =style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-4)+(gap*1)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"RED"); style="color: rgb(0, 128, 0);">//Create a RED button
greenButton = style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-3)+(gap*2)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"GREEN"); style="color: rgb(0, 128, 0);">//Create a GREEN button
blueButton = style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-2)+(gap*3)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"BLUE"); style="color: rgb(0, 128, 0);">//Create a BLUE button
offButton = style="color: rgb(0, 0, 255);">new APButton((buttonWidth*(n-1)+(gap*4)), gap, buttonWidth, buttonHeight, style="color: rgb(163, 21, 21);">"OFF"); style="color: rgb(0, 128, 0);">//Create a OFF button
widgetContainer.addWidget(redButton); style="color: rgb(0, 128, 0);">//place red button in container
widgetContainer.addWidget(greenButton); style="color: rgb(0, 128, 0);">//place green button in container
widgetContainer.addWidget(blueButton);style="color: rgb(0, 128, 0);">//place blue button in container
widgetContainer.addWidget(offButton);style="color: rgb(0, 128, 0);">//place off button in container
background(0); style="color: rgb(0, 128, 0);">//Start with a black background

style="color: rgb(0, 128, 0);">/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
style="color: rgb(0, 0, 255);">if (!bluetooth.isEnabled()) {
Intent requestBluetooth = style="color: rgb(0, 0, 255);">new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}

style="color: rgb(0, 128, 0);">/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
style="color: rgb(0, 128, 0);"> discovered Bluetooth devices, and then start discovering */
style="color: rgb(0, 0, 255);">if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, style="color: rgb(0, 0, 255);">new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, style="color: rgb(0, 0, 255);">new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

style="color: rgb(0, 128, 0);">//Start bluetooth discovery if it is not doing so already
style="color: rgb(0, 0, 255);">if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}


style="color: rgb(43, 145, 175);">void draw() {
style="color: rgb(0, 128, 0);">//Display a green screen if a device has been found,
style="color: rgb(0, 128, 0);">//Display a purple screen when a connection is made to the device
style="color: rgb(0, 0, 255);">if (foundDevice) {
style="color: rgb(0, 0, 255);">if (BTisConnected) {
background(170, 50, 255); style="color: rgb(0, 128, 0);">// purple screen
}
style="color: rgb(0, 0, 255);">else {
background(10, 255, 10); style="color: rgb(0, 128, 0);">// green screen
}
}


style="color: rgb(0, 128, 0);">//Change the text based on the button being pressed.
text(buttonText, 10, buttonHeight+(buttonHeight/2));

style="color: rgb(0, 128, 0);">//Display anything received from Arduino
text(readMessage, 10, buttonHeight+(buttonHeight/2)+30);
}



style="color: rgb(0, 128, 0);">/* This BroadcastReceiver will display discovered Bluetooth devices */
style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">myOwnBroadcastReceiver style="color: rgb(0, 0, 255);">extends BroadcastReceiver {
ConnectToBluetooth connectBT;

@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster(style="color: rgb(163, 21, 21);">"ACTION:" + action);

style="color: rgb(0, 128, 0);">//Notification that BluetoothDevice is FOUND
style="color: rgb(0, 0, 255);">if (BluetoothDevice.ACTION_FOUND.equals(action)) {
style="color: rgb(0, 128, 0);">//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster(style="color: rgb(163, 21, 21);">"Discovered: " + discoveredDeviceName);

style="color: rgb(0, 128, 0);">//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster(style="color: rgb(163, 21, 21);">"getAddress() = " + discoveredDevice.getAddress());
ToastMaster(style="color: rgb(163, 21, 21);">"getName() = " + discoveredDevice.getName());

style="color: rgb(43, 145, 175);">int bondyState=discoveredDevice.getBondState();
ToastMaster(style="color: rgb(163, 21, 21);">"getBondState() = " + bondyState);

String mybondState;
style="color: rgb(0, 0, 255);">switch(bondyState) {
style="color: rgb(0, 0, 255);">case 10:
mybondState=style="color: rgb(163, 21, 21);">"BOND_NONE";
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case 11:
mybondState=style="color: rgb(163, 21, 21);">"BOND_BONDING";
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">case 12:
mybondState=style="color: rgb(163, 21, 21);">"BOND_BONDED";
style="color: rgb(0, 0, 255);">break;
style="color: rgb(0, 0, 255);">default:
mybondState=style="color: rgb(163, 21, 21);">"INVALID BOND STATE";
style="color: rgb(0, 0, 255);">break;
}
ToastMaster(style="color: rgb(163, 21, 21);">"getBondState() = " + mybondState);

style="color: rgb(0, 128, 0);">//Change foundDevice to true which will make the screen turn green
foundDevice=style="color: rgb(0, 0, 255);">true;

style="color: rgb(0, 128, 0);">//Connect to the discovered bluetooth device (SeeedBTSlave)
style="color: rgb(0, 0, 255);">if (discoveredDeviceName.equals(style="color: rgb(163, 21, 21);">"SeeedBTSlave")) {
ToastMaster(style="color: rgb(163, 21, 21);">"Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = style="color: rgb(0, 0, 255);">new ConnectToBluetooth(discoveredDevice);
style="color: rgb(0, 128, 0);">//Connect to the the device in a new thread
style="color: rgb(0, 0, 255);">new Thread(connectBT).start();
}
}

style="color: rgb(0, 128, 0);">//Notification if bluetooth device is connected
style="color: rgb(0, 0, 255);">if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster(style="color: rgb(163, 21, 21);">"CONNECTED _ YAY");
style="color: rgb(43, 145, 175);">int counter=0;
style="color: rgb(0, 0, 255);">while (scSocket==style="color: rgb(0, 0, 255);">null) {
style="color: rgb(0, 128, 0);">//do nothing
}
ToastMaster(style="color: rgb(163, 21, 21);">"scSocket" + scSocket);
BTisConnected=style="color: rgb(0, 0, 255);">true; style="color: rgb(0, 128, 0);">//turn screen purple
style="color: rgb(0, 0, 255);">if (scSocket!=style="color: rgb(0, 0, 255);">null) {
sendReceiveBT = style="color: rgb(0, 0, 255);">new SendReceiveBytes(scSocket);
style="color: rgb(0, 0, 255);">new Thread(sendReceiveBT).start();
String red = style="color: rgb(163, 21, 21);">"r";
style="color: rgb(43, 145, 175);">byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}

style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">static style="color: rgb(43, 145, 175);">byte[] stringToBytesUTFCustom(String str) {
style="color: rgb(43, 145, 175);">char[] buffer = str.toCharArray();
style="color: rgb(43, 145, 175);">byte[] b = style="color: rgb(0, 0, 255);">new style="color: rgb(43, 145, 175);">byte[buffer.length << 1];
style="color: rgb(0, 0, 255);">for (style="color: rgb(43, 145, 175);">int i = 0; i < buffer.length; i++) {
style="color: rgb(43, 145, 175);">int bpos = i << 1;
b[bpos] = (style="color: rgb(43, 145, 175);">byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (style="color: rgb(43, 145, 175);">byte) (buffer[i]&0x00FF);
}
style="color: rgb(0, 0, 255);">return b;
}

style="color: rgb(0, 0, 255);">public style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">ConnectToBluetooth style="color: rgb(0, 0, 255);">implements Runnable {
style="color: rgb(0, 0, 255);">private BluetoothDevice btShield;
style="color: rgb(0, 0, 255);">private BluetoothSocket mySocket = style="color: rgb(0, 0, 255);">null;
style="color: rgb(0, 0, 255);">private UUID uuid = UUID.fromString(style="color: rgb(163, 21, 21);">"00001101-0000-1000-8000-00805F9B34FB");

style="color: rgb(0, 0, 255);">public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
style="color: rgb(0, 0, 255);">try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
style="color: rgb(0, 0, 255);">catch(IOException createSocketException) {
style="color: rgb(0, 128, 0);">//Problem with creating a socket
Log.e(style="color: rgb(163, 21, 21);">"ConnectToBluetooth", style="color: rgb(163, 21, 21);">"Error with Socket");
}
}

@Override
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void run() {
style="color: rgb(0, 128, 0);">/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

style="color: rgb(0, 0, 255);">try {
style="color: rgb(0, 128, 0);">/*Connect to the bluetoothShield through the Socket. This will block
style="color: rgb(0, 128, 0);"> until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
style="color: rgb(0, 0, 255);">catch (IOException connectException) {
Log.e(style="color: rgb(163, 21, 21);">"ConnectToBluetooth", style="color: rgb(163, 21, 21);">"Error with Socket Connection");
style="color: rgb(0, 0, 255);">try {
mySocket.close(); style="color: rgb(0, 128, 0);">//try to close the socket
}
style="color: rgb(0, 0, 255);">catch(IOException closeException) {
}
style="color: rgb(0, 0, 255);">return;
}
}

style="color: rgb(0, 128, 0);">// Will allow you to get the socket from this class
style="color: rgb(0, 0, 255);">public BluetoothSocket getSocket() {
style="color: rgb(0, 0, 255);">return mySocket;
}

style="color: rgb(0, 128, 0);">/* Will cancel an in-progress connection, and close the socket */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void cancel() {
style="color: rgb(0, 0, 255);">try {
mySocket.close();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
}
}
}



style="color: rgb(0, 0, 255);">private style="color: rgb(0, 0, 255);">class style="color: rgb(43, 145, 175);">SendReceiveBytes style="color: rgb(0, 0, 255);">implements Runnable {
style="color: rgb(0, 0, 255);">private BluetoothSocket btSocket;
style="color: rgb(0, 0, 255);">private InputStream btInputStream = style="color: rgb(0, 0, 255);">null;
;
style="color: rgb(0, 0, 255);">private OutputStream btOutputStream = style="color: rgb(0, 0, 255);">null;
String TAG = style="color: rgb(163, 21, 21);">"SendReceiveBytes";

style="color: rgb(0, 0, 255);">public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
style="color: rgb(0, 0, 255);">try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
style="color: rgb(0, 0, 255);">catch (IOException streamError) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when getting input or output Stream");
}
}

style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void run() {
style="color: rgb(43, 145, 175);">byte[] buffer = style="color: rgb(0, 0, 255);">new style="color: rgb(43, 145, 175);">byte[1024]; style="color: rgb(0, 128, 0);">// buffer store for the stream
style="color: rgb(43, 145, 175);">int bytes; style="color: rgb(0, 128, 0);">// bytes returned from read()

style="color: rgb(0, 128, 0);">// Keep listening to the InputStream until an exception occurs
style="color: rgb(0, 0, 255);">while (style="color: rgb(0, 0, 255);">true) {
style="color: rgb(0, 0, 255);">try {
style="color: rgb(0, 128, 0);">// Read from the InputStream
bytes = btInputStream.read(buffer);
style="color: rgb(0, 128, 0);">// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error reading from btInputStream");
style="color: rgb(0, 0, 255);">break;
}
}
}

style="color: rgb(0, 128, 0);">/* Call this from the main activity to send data to the remote device */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void write(style="color: rgb(43, 145, 175);">byte[] bytes) {
style="color: rgb(0, 0, 255);">try {
btOutputStream.write(bytes);
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when writing to btOutputStream");
}
}

style="color: rgb(0, 128, 0);">/* Call this from the main activity to shutdown the connection */
style="color: rgb(0, 0, 255);">public style="color: rgb(43, 145, 175);">void cancel() {
style="color: rgb(0, 0, 255);">try {
btSocket.close();
}
style="color: rgb(0, 0, 255);">catch (IOException e) {
Log.e(TAG, style="color: rgb(163, 21, 21);">"Error when closing the btSocket");
}
}
}



style="color: rgb(0, 128, 0);">/* My ToastMaster function to display a messageBox on the screen */
style="color: rgb(43, 145, 175);">void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}




style="color: rgb(0, 128, 0);">//onClickWidget is called when a widget is clicked/touched
style="color: rgb(43, 145, 175);">void onClickWidget(APWidget widget) {
String sendLetter = style="color: rgb(163, 21, 21);">"";

style="color: rgb(0, 128, 0);">//Disable the previous Background colour changers
foundDevice=style="color: rgb(0, 0, 255);">false;
BTisConnected=style="color: rgb(0, 0, 255);">false;

style="color: rgb(0, 0, 255);">if (widget == redButton) { style="color: rgb(0, 128, 0);">//if the red button was clicked
buttonText=style="color: rgb(163, 21, 21);">"RED";
background(255, 0, 0);
sendLetter = style="color: rgb(163, 21, 21);">"r";
}
style="color: rgb(0, 0, 255);">else if (widget == greenButton) { style="color: rgb(0, 128, 0);">//if the green button was clicked
buttonText=style="color: rgb(163, 21, 21);">"GREEN";
background(0, 255, 0);
sendLetter = style="color: rgb(163, 21, 21);">"g";
}
style="color: rgb(0, 0, 255);">else if (widget == blueButton) { style="color: rgb(0, 128, 0);">//if the blue button was clicked
buttonText=style="color: rgb(163, 21, 21);">"BLUE";
background(0, 0, 255);
sendLetter = style="color: rgb(163, 21, 21);">"b";
}
style="color: rgb(0, 0, 255);">else if (widget == offButton) { style="color: rgb(0, 128, 0);">//if the off button was clicked
buttonText=style="color: rgb(163, 21, 21);">"OFF";
background(0);
sendLetter = style="color: rgb(163, 21, 21);">"x";
}

style="color: rgb(43, 145, 175);">byte[] myByte = stringToBytesUTFCustom(sendLetter);
sendReceiveBT.write(myByte);
}

The sketch above has been thrown together without much planning or consideration for code efficiency. It was deliberately done this way so that you could see and follow the incremental approach used to create this Android/Processing Bluetooth App. I will do my best to rewrite and simplify some of the code, however, I don't anticipate the final sketch will be a short script.
You should have noticed that I included a fourth button called an "off" button. This will turn off the RGB led. However, the Arduino code in its current format does not know what to do with an 'x'. So we will update the sketch as follows:

Arduino Sketch 3: Bluetooth RGB Colour Changer (with OFF option)

 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
style="color: rgb(0, 128, 0);">/* This project combines the code from a few different sources.
style="color: rgb(0, 128, 0);"> This project was put together by ScottC on the 15/01/2013
style="color: rgb(0, 128, 0);"> http://arduinobasics.blogspot.com/
style="color: rgb(0, 128, 0);">
style="color: rgb(0, 128, 0);"> Bluetooth slave code by Steve Chang - downloaded from :
style="color: rgb(0, 128, 0);"> http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield
style="color: rgb(0, 128, 0);">
style="color: rgb(0, 128, 0);"> Grove Chainable RGB code can be found here :
style="color: rgb(0, 128, 0);"> http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED#Introduction
style="color: rgb(0, 128, 0);">
style="color: rgb(0, 128, 0);"> Updated on 25 March 2013: Receive 'x' to turn off RGB LED.
style="color: rgb(0, 128, 0);">
style="color: rgb(0, 128, 0);"> */

style="color: rgb(0, 0, 255);">#include <SoftwareSerial.h> style="color: rgb(0, 128, 0);">//Software Serial Port

style="color: rgb(0, 0, 255);">#define uint8 unsigned char
style="color: rgb(0, 0, 255);">#define uint16 unsigned int
style="color: rgb(0, 0, 255);">#define uint32 unsigned long int

style="color: rgb(0, 0, 255);">#define RxD 6 style="color: rgb(0, 128, 0);">// This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
style="color: rgb(0, 0, 255);">#define TxD 7 style="color: rgb(0, 128, 0);">// This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

style="color: rgb(0, 0, 255);">#define DEBUG_ENABLED 1

style="color: rgb(43, 145, 175);">int Clkpin = 9; style="color: rgb(0, 128, 0);">//RGB LED Clock Pin (Digital 9)
style="color: rgb(43, 145, 175);">int Datapin = 8; style="color: rgb(0, 128, 0);">//RGB LED Data Pin (Digital 8)

SoftwareSerial blueToothSerial(RxD, TxD);


style="color: rgb(0, 128, 0);">/*----------------------SETUP----------------------------*/
style="color: rgb(43, 145, 175);">void setup() {
Serial.begin(9600); style="color: rgb(0, 128, 0);">// Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); style="color: rgb(0, 128, 0);">// Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); style="color: rgb(0, 128, 0);">// Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13, OUTPUT); style="color: rgb(0, 128, 0);">// Use onboard LED if required.
setupBlueToothConnection(); style="color: rgb(0, 128, 0);">//Used to initialise the Bluetooth shield

pinMode(Datapin, OUTPUT); style="color: rgb(0, 128, 0);">// Setup the RGB LED Data Pin
pinMode(Clkpin, OUTPUT); style="color: rgb(0, 128, 0);">// Setup the RGB LED Clock pin
}


style="color: rgb(0, 128, 0);">/*----------------------LOOP----------------------------*/
style="color: rgb(43, 145, 175);">void loop() {
digitalWrite(13, LOW); style="color: rgb(0, 128, 0);">//Turn off the onboard Arduino LED
style="color: rgb(43, 145, 175);">char recvChar;
style="color: rgb(0, 0, 255);">while (1) {
style="color: rgb(0, 0, 255);">if (blueToothSerial.available()) {style="color: rgb(0, 128, 0);">//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); style="color: rgb(0, 128, 0);">// Print the character received to the Serial Monitor (if required)

style="color: rgb(0, 128, 0);">//If the character received = 'r' , then change the RGB led to display a RED colour
style="color: rgb(0, 0, 255);">if (recvChar==style="color: rgb(163, 21, 21);">'r') {
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(255, 0, 0); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}

style="color: rgb(0, 128, 0);">//If the character received = 'g' , then change the RGB led to display a GREEN colour
style="color: rgb(0, 0, 255);">if (recvChar==style="color: rgb(163, 21, 21);">'g') {
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(0, 255, 0); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}

style="color: rgb(0, 128, 0);">//If the character received = 'b' , then change the RGB led to display a BLUE colour
style="color: rgb(0, 0, 255);">if (recvChar==style="color: rgb(163, 21, 21);">'b') {
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(0, 0, 255); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}

style="color: rgb(0, 128, 0);">//If the character received = 'x' , then turn RGB led OFF
style="color: rgb(0, 0, 255);">if (recvChar==style="color: rgb(163, 21, 21);">'x') {
Send32Zero(); style="color: rgb(0, 128, 0);">// begin
DataDealWithAndSend(0, 0, 0); style="color: rgb(0, 128, 0);">// first node data
Send32Zero(); style="color: rgb(0, 128, 0);">// send to update data
}
}

style="color: rgb(0, 128, 0);">//You can use the following code to deal with any information coming from the Computer (serial monitor)
style="color: rgb(0, 0, 255);">if (Serial.available()) {
recvChar = Serial.read();

style="color: rgb(0, 128, 0);">//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
}
}
}



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


style="color: rgb(0, 128, 0);">//The following code snippets are used update the colour of the RGB LED-----copy and paste------------
style="color: rgb(43, 145, 175);">void ClkProduce(style="color: rgb(43, 145, 175);">void) {
digitalWrite(Clkpin, LOW);
delayMicroseconds(20);
digitalWrite(Clkpin, HIGH);
delayMicroseconds(20);
}
style="color: rgb(43, 145, 175);">void Send32Zero(style="color: rgb(43, 145, 175);">void) {
style="color: rgb(43, 145, 175);">unsigned style="color: rgb(43, 145, 175);">char i;
style="color: rgb(0, 0, 255);">for (i=0; i<32; i++) {
digitalWrite(Datapin, LOW);
ClkProduce();
}
}



uint8 TakeAntiCode(uint8 dat) {
uint8 tmp = 0;
style="color: rgb(0, 0, 255);">if ((dat & 0x80) == 0) {
tmp |= 0x02;
}

style="color: rgb(0, 0, 255);">if ((dat & 0x40) == 0) {
tmp |= 0x01;
}
style="color: rgb(0, 0, 255);">return tmp;
}


style="color: rgb(0, 128, 0);">// gray data
style="color: rgb(43, 145, 175);">void DatSend(uint32 dx) {
uint8 i;
style="color: rgb(0, 0, 255);">for (i=0; i<32; i++) {
style="color: rgb(0, 0, 255);">if ((dx & 0x80000000) != 0) {
digitalWrite(Datapin, HIGH);
}
style="color: rgb(0, 0, 255);">else {
digitalWrite(Datapin, LOW);
}
dx <<= 1;
ClkProduce();
}
}

style="color: rgb(0, 128, 0);">// data processing
style="color: rgb(43, 145, 175);">void DataDealWithAndSend(uint8 r, uint8 g, uint8 b) {
uint32 dx = 0;

dx |= (uint32)0x03 << 30; style="color: rgb(0, 128, 0);">// 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);
}



Well that concludes part 3.
Part 4 is a summary of the finished project with videos, screenshots, parts used etc.
I hope you found this tutorial useful. I would love to receive any advice on how I could improve these tutorials (please put your recommendations in comments below).

Reason for this Project:
While there are quite a few people creating Android/Arduino projects, I have not been able to find many that show how these are being accomplished using the Android/Processing IDE, and even less on how they are using Bluetooth in their Android/Processing projects. I hope my piecing of information will spark some creative Bluetooth projects of your own.



PART 4: Navigate here.








No comments:

Post a Comment