Posts with «processing» label

Send HEX values to Arduino

FIVE MINUTE TUTORIAL

Project Description: Sending Hex values to an Arduino UNO


This simple tutorial will show you how to send Hexadecimal values from a computer to an Arduino Uno. The "Processing" programming language will be used to send the HEX values from the computer when a mouse button is pressed. The Arduino will use these values to adjust the brightness of an LED.



 

Learning Objectives


  • To Send Hexadecimal (Hex) values from a computer to the Arduino
  • Trigger an action based on the press of a mouse button
  • Learn to create a simple Computer to Arduino interface
  • Use Arduino's PWM capabilities to adjust brightness of an LED
  • Learn to use Arduino's analogWrite() function
  • Create a simple LED circuit


 

Parts Required:


Fritzing Sketch


The diagram below will show you how to connect an LED to Digital Pin 10 on the Arduino.
Don't forget the 330 ohm resistor !
 


 
 

Arduino Sketch


The latest version of Arduino IDE can be downloaded here.
 
  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
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
     Arduino IDE: 1.6.4
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Arduino Sketch used to adjust the brightness of an LED based on the values received
                  on the serial port. The LED needs to be connected to a PWM pin. In this sketch
                  Pin 10 is used, however you could use Pin 3, 5, 6, 9, or 11 - if you are using an Arduino Uno.
===================================================================================================================================================== */

byte byteRead; //Variable used to store the byte received on the Serial Port
int ledPin = 10; //LED is connected to Arduino Pin 10. This pin must be PWM capable.

void setup() {
 Serial.begin(9600); //Initialise Serial communication with the computer
 pinMode(ledPin, OUTPUT); //Set Pin 10 as an Output pin
 byteRead = 0;                   //Initialise the byteRead variable to zero.
}

void loop() {
  if(Serial.available()) {
    byteRead = Serial.read(); //Update the byteRead variable with the Hex value received on the Serial COM port.
  }
  
  analogWrite(ledPin, byteRead); //Use PWM to adjust the brightness of the LED. Brightness is determined by the "byteRead" variable.
}


 


 
 

Processing Sketch


The latest version of the Processing IDE can be downloaded here.
 
  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
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
  Processing IDE: 2.2.1
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Processing Sketch used to send HEX values from computer to Arduino when the mouse is pressed.
                  The alternating values 0xFF and 0x00 are sent to the Arduino Uno to turn an LED on and off.
                  You can send any HEX value from 0x00 to 0xFF. This sketch also shows how to convert Hex strings
                  to Hex numbers.
===================================================================================================================================================== */

import processing.serial.*; //This import statement is required for Serial communication

Serial comPort;                       //comPort is used to write Hex values to the Arduino
boolean toggle = false; //toggle variable is used to control which hex variable to send
String zeroHex = "00"; //This "00" string will be converted to 0x00 and sent to Arduino to turn LED off.
String FFHex = "FF"; //This "FF" string will be converted to 0xFF and sent to Arduino to turn LED on.

void setup(){
    comPort = new Serial(this, Serial.list()[0], 9600); //initialise the COM port for serial communication at a baud rate of 9600.
    delay(2000);                      //this delay allows the com port to initialise properly before initiating any communication.
    background(0); //Start with a black background.
    
}


void draw(){ //the draw() function is necessary for the sketch to compile
    //do nothing here //even though it does nothing.
}


void mousePressed(){ //This function is called when the mouse is pressed within the Processing window.
  toggle = ! toggle;                   //The toggle variable will change back and forth between "true" and "false"
  if(toggle){ //If the toggle variable is TRUE, then send 0xFF to the Arduino
     comPort.write(unhex(FFHex)); //The unhex() function converts the "FF" string to 0xFF
     background(0,0,255); //Change the background colour to blue as a visual indication of a button press.
  } else {
    comPort.write(unhex(zeroHex)); //If the toggle variable is FALSE, then send 0x00 to the Arduino
    background(0); //Change the background colour to black as a visual indication of a button press.
  }
}


 

The Video


 

The tutorial above is a quick demonstration of how to convert Hex strings on your computer and send them to an Arduino. The Arduino can use the values to change the brightness of an LED as shown in this tutorial, however you could use it to modify the speed of a motor, or to pass on commands to another module. Hopefully this short tutorial will help you with your project. Please let me know how it helped you in the comments below.

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             


 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Send HEX values to Arduino

FIVE MINUTE TUTORIAL

Project Description: Sending Hex values to an Arduino UNO


This simple tutorial will show you how to send Hexadecimal values from a computer to an Arduino Uno. The "Processing" programming language will be used to send the HEX values from the computer when a mouse button is pressed. The Arduino will use these values to adjust the brightness of an LED.



 

Learning Objectives


  • To Send Hexadecimal (Hex) values from a computer to the Arduino
  • Trigger an action based on the press of a mouse button
  • Learn to create a simple Computer to Arduino interface
  • Use Arduino's PWM capabilities to adjust brightness of an LED
  • Learn to use Arduino's analogWrite() function
  • Create a simple LED circuit


 

Parts Required:


Fritzing Sketch


The diagram below will show you how to connect an LED to Digital Pin 10 on the Arduino.
Don't forget the 330 ohm resistor !
 


 
 

Arduino Sketch


The latest version of Arduino IDE can be downloaded here.
 
  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
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
     Arduino IDE: 1.6.4
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Arduino Sketch used to adjust the brightness of an LED based on the values received
                  on the serial port. The LED needs to be connected to a PWM pin. In this sketch
                  Pin 10 is used, however you could use Pin 3, 5, 6, 9, or 11 - if you are using an Arduino Uno.
===================================================================================================================================================== */

byte byteRead; //Variable used to store the byte received on the Serial Port
int ledPin = 10; //LED is connected to Arduino Pin 10. This pin must be PWM capable.

void setup() {
 Serial.begin(9600); //Initialise Serial communication with the computer
 pinMode(ledPin, OUTPUT); //Set Pin 10 as an Output pin
 byteRead = 0;                   //Initialise the byteRead variable to zero.
}

void loop() {
  if(Serial.available()) {
    byteRead = Serial.read(); //Update the byteRead variable with the Hex value received on the Serial COM port.
  }
  
  analogWrite(ledPin, byteRead); //Use PWM to adjust the brightness of the LED. Brightness is determined by the "byteRead" variable.
}


 


 
 

Processing Sketch


The latest version of the Processing IDE can be downloaded here.
 
  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
/* ==================================================================================================================================================
         Project: 5 min tutorial: Send Hex from computer to Arduino
          Author: Scott C
         Created: 21th June 2015
  Processing IDE: 2.2.1
         Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
     Description: Processing Sketch used to send HEX values from computer to Arduino when the mouse is pressed.
                  The alternating values 0xFF and 0x00 are sent to the Arduino Uno to turn an LED on and off.
                  You can send any HEX value from 0x00 to 0xFF. This sketch also shows how to convert Hex strings
                  to Hex numbers.
===================================================================================================================================================== */

import processing.serial.*; //This import statement is required for Serial communication

Serial comPort;                       //comPort is used to write Hex values to the Arduino
boolean toggle = false; //toggle variable is used to control which hex variable to send
String zeroHex = "00"; //This "00" string will be converted to 0x00 and sent to Arduino to turn LED off.
String FFHex = "FF"; //This "FF" string will be converted to 0xFF and sent to Arduino to turn LED on.

void setup(){
    comPort = new Serial(this, Serial.list()[0], 9600); //initialise the COM port for serial communication at a baud rate of 9600.
    delay(2000);                      //this delay allows the com port to initialise properly before initiating any communication.
    background(0); //Start with a black background.
    
}


void draw(){ //the draw() function is necessary for the sketch to compile
    //do nothing here //even though it does nothing.
}


void mousePressed(){ //This function is called when the mouse is pressed within the Processing window.
  toggle = ! toggle;                   //The toggle variable will change back and forth between "true" and "false"
  if(toggle){ //If the toggle variable is TRUE, then send 0xFF to the Arduino
     comPort.write(unhex(FFHex)); //The unhex() function converts the "FF" string to 0xFF
     background(0,0,255); //Change the background colour to blue as a visual indication of a button press.
  } else {
    comPort.write(unhex(zeroHex)); //If the toggle variable is FALSE, then send 0x00 to the Arduino
    background(0); //Change the background colour to black as a visual indication of a button press.
  }
}


 

The Video


 

The tutorial above is a quick demonstration of how to convert Hex strings on your computer and send them to an Arduino. The Arduino can use the values to change the brightness of an LED as shown in this tutorial, however you could use it to modify the speed of a motor, or to pass on commands to another module. Hopefully this short tutorial will help you with your project. Please let me know how it helped you in the comments below.

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 
             


 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Arduino Heart Rate Monitor


Project Description


Heart Rate Monitors are very popular at the moment.
There is something very appealing about watching the pattern of your own heart beat. And once you see it, there is an unstoppable urge to try and control it. This simple project will allow you to visualize your heart beat, and will calculate your heart rate. Keep reading to learn how to create your very own heart rate monitor.


 

Parts Required:


Fritzing Sketch


 

 
 
 

Grove Base Shield to Module Connections


 


 

Arduino Sketch


 

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
/* =================================================================================================
      Project: Arduino Heart rate monitor
       Author: Scott C
      Created: 21st April 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This is a simple sketch that uses a Grove Ear-clip Heart Rate sensor attached to an Arduino UNO,
               which sends heart rate data to the computer via Serial communication. You can see the raw data
               using the Serial monitor on the Arduino IDE, however, this sketch was specifically
               designed to interface with the matching Processing sketch for a much nicer graphical display.
               NO LIBRARIES REQUIRED.
=================================================================================================== */

#define Heart 2                            //Attach the Grove Ear-clip sensor to digital pin 2.
#define LED 4                              //Attach an LED to digital pin 4

boolean beat = false; /* This "beat" variable is used to control the timing of the Serial communication
                                           so that data is only sent when there is a "change" in digital readings. */

//==SETUP==========================================================================================
void setup() {
  Serial.begin(9600); //Initialise serial communication
  pinMode(Heart, INPUT); //Set digital pin 2 (heart rate sensor pin) as an INPUT
  pinMode(LED, OUTPUT); //Set digital pin 4 (LED) to an OUTPUT
}


//==LOOP============================================================================================
void loop() {
  if(digitalRead(Heart)>0){ //The heart rate sensor will trigger HIGH when there is a heart beat
    if<!beat){><span>//Only send data when it first discovers a heart beat - otherwise it will send a high value multiple times</span><br />      beat=<span>true</span>; <span>//By changing the beat variable to true, it stops further transmissions of the high signal</span><br />      <span>digitalWrite</span>(LED, <span>HIGH</span>); <span>//Turn the LED on </span><br />      <span><b>Serial</b></span>.<span>println</span>(1023); <span>//Send the high value to the computer via Serial communication.</span><br />    }<br />  } <span>else</span> { <span>//If the reading is LOW, </span><br />    <span>if</span>(beat){ <span>//and if this has just changed from HIGH to LOW (first low reading)</span><br />      beat=<span>false</span>; <span>//change the beat variable to false (to stop multiple transmissions)</span><br />      <span>digitalWrite</span>(LED, <span>LOW</span>); <span>//Turn the LED off.</span><br />      <span><b>Serial</b></span>.<span>println</span>(0); <span>//then send a low value to the computer via Serial communication.</span><br />    }<br />  }<br />}</pre> </td> </tr> </table></div></p> <br />  <br />   <br />  <br />  <p> <h4><a href="https://processing.org/download/?processing">Processing Sketch</a></h4> <br />  <div> <table> <tr> <td> <pre> 1<br /> 2<br /> 3<br /> 4<br /> 5<br /> 6<br /> 7<br /> 8<br /> 9<br /> 10<br /> 11<br /> 12<br /> 13<br /> 14<br /> 15<br /> 16<br /> 17<br /> 18<br /> 19<br /> 20<br /> 21<br /> 22<br /> 23<br /> 24<br /> 25<br /> 26<br /> 27<br /> 28<br /> 29<br /> 30<br /> 31<br /> 32<br /> 33<br /> 34<br /> 35<br /> 36<br /> 37<br /> 38<br /> 39<br /> 40<br /> 41<br /> 42<br /> 43<br /> 44<br /> 45<br /> 46<br /> 47<br /> 48<br /> 49<br /> 50<br /> 51<br /> 52<br /> 53<br /> 54<br /> 55<br /> 56<br /> 57<br /> 58<br /> 59<br /> 60<br /> 61<br /> 62<br /> 63<br /> 64<br /> 65<br /> 66<br /> 67<br /> 68<br /> 69<br /> 70<br /> 71<br /> 72<br /> 73<br /> 74<br /> 75<br /> 76<br /> 77<br /> 78<br /> 79<br /> 80<br /> 81<br /> 82<br /> 83<br /> 84<br /> 85<br /> 86<br /> 87<br /> 88<br /> 89<br /> 90<br /> 91<br /> 92<br /> 93<br /> 94<br /> 95<br /> 96<br /> 97<br /> 98<br /> 99<br />100<br />101<br />102<br />103<br />104<br />105<br />106<br />107<br />108<br />109<br />110<br />111<br />112<br />113<br />114<br />115<br />116<br />117<br />118<br />119<br />120<br />121<br />122<br />123<br />124<br />125<br />126<br />127<br />128<br />129<br />130<br />131<br />132<br />133<br />134<br />135<br />136<br />137<br />138<br />139<br />140<br />141<br />142<br />143<br />144<br />145<br />146<br />147<br />148<br />149<br />150<br />151<br />152<br />153<br />154<br />155<br />156<br />157<br />158<br />159<br />160<br />161<br />162<br />163<br />164<br />165<br />166<br />167<br />168<br />169<br />170<br />171<br />172<br />173<br />174<br />175<br />176<br />177<br />178<br />179<br />180<br />181<br />182<br />183<br />184<br />185<br />186<br />187<br />188<br />189<br />190<br />191<br />192<br />193<br />194<br />195<br />196<br />197<br />198<br />199<br />200<br />201<br />202<br />203<br />204<br />205<br />206<br />207<br />208<br />209<br />210<br />211<br />212<br />213<br />214<br /></pre> </td> <td> <pre><br /><span>/* =================================================================================================</span><br /><span>       Project: Arduino Heart rate monitor</span><br /><span>        Author: Scott C</span><br /><span>       Created: 21st April 2015</span><br /><span>Processing IDE: 2.2.1</span><br /><span>       Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html</span><br /><span>   Description: A Grove Ear-clip heart rate sensor allows an Arduino UNO to sense your pulse.</span><br /><span>                The data obtained by the Arduino can then be sent to the computer via Serial communication</span><br /><span>                which is then displayed graphically using this Processing sketch.</span><br /><span>                </span><br /><span>=================================================================================================== */</span><br /><br /><span>import</span> processing.serial.*; <span>// Import the serial library to allow Serial communication with the Arduino</span><br /><br /><span>int</span> numOfRecs = 45; <span>// numOfRecs: The number of rectangles to display across the screen</span><br />Rectangle[] myRecs = <span>new</span> Rectangle[numOfRecs]; <span>// myRecs[]: Is the array of Rectangles. Rectangle is a custom class (programmed within this sketch)</span><br /><br />Serial myPort;                                         <br /><span>String</span> comPortString=<span>"0"</span>; <span>//comPortString: Is used to hold the string received from the Arduino</span><br /><span>float</span> arduinoValue = 0; <span>//arduinoValue: Is the float variable converted from comPortString</span><br /><span>boolean</span> beat = <span>false</span>; <span>// beat: Used to control for multiple high/low signals coming from the Arduino</span><br /><br /><span>int</span> totalTime = 0; <span>// totalTime: Is the variable used to identify the total time between beats</span><br /><span>int</span> lastTime = 0; <span>// lastTime: Is the variable used to remember when the last beat took place</span><br /><span>int</span> beatCounter = 0; <span>// beatCounter: Is used to keep track of the number of beats (in order to calculate the average BPM)</span><br /><span>int</span> totalBeats = 10; <span>// totalBeats: Tells the computer that we want to calculate the average BPM using 10 beats.</span><br /><span>int</span>[] BPM = <span>new</span> <span>int</span>[totalBeats]; <span>// BPM[]: Is the Beat Per Minute (BPM) array - to hold 10 BPM calculations</span><br /><span>int</span> sumBPM = 0; <span>// sumBPM: Is used to sum the BPM[] array values, and is then used to calculate the average BPM.</span><br /><span>int</span> avgBPM = 0; <span>// avgBPM: Is the variable used to hold the average BPM calculated value.</span><br /><br /><span>PFont</span> f, f2; <span>// f & f2 : Are font related variables. Used to store font properties. </span><br /><br /><br /><span>//==SETUP==============================================================================================</span><br /><span>void</span> <span><b>setup</b></span>(){<br />  <span>size</span>(<span>displayWidth</span>,<span>displayHeight</span>); <span>// Set the size of the display to match the monitor width and height</span><br />  <span>smooth</span>(); <span>// Draw all shapes with smooth edges.</span><br />  f = <span>createFont</span>(<span>"Arial"</span>,24); <span>// Initialise the "f" font variable - used for the "calibrating" text displayed at the beginning</span><br />  f2 = <span>createFont</span>(<span>"Arial"</span>,96); <span>// Initialise the "f2" font variable - used for the avgBPM display on screen</span><br />  <br />  <span>for</span>(<span>int</span> i=0; i<numOfRecs; i++){ <span>// Initialise the array of rectangles</span><br />    myRecs[i] = <span>new</span> Rectangle(i, numOfRecs);<br />  }<br />  <br />  <span>for</span>(<span>int</span> i=0; i<totalBeats; i++){ <span>// Initialise the BPM array</span><br />    BPM[i] = 0;<br />  }<br />  <br />  myPort = <span>new</span> Serial(<span>this</span>, Serial.<span>list</span>()[0], 9600); <span>// Start Serial communication with the Arduino using a baud rate of 9600</span><br />  myPort.bufferUntil(<span>'\n'</span>); <span>// Trigger a SerialEvent on new line</span><br />}<br /><br /><br /><span>//==DRAW==============================================================================================</span><br /><span>void</span> <span><b>draw</b></span>(){<br />  <span>background</span>(0); <span>// Set the background to BLACK (this clears the screen each time)</span><br />  drawRecs();                                           <span>// Method call to draw the rectangles on the screen</span><br />  drawBPM();                                            <span>// Method call to draw the avgBPM value to the top right of the screen</span><br />}<br /><br /><br /><span>//==drawRecs==========================================================================================</span><br /><span>void</span> drawRecs(){ <span>// This custom method will draw the rectangles on the screen </span><br />  myRecs[0].setSize(arduinoValue);                      <span>// Set the first rectangle to match arduinoValue; any positive value will start the animation.</span><br />  <span>for</span>(<span>int</span> i=numOfRecs-1; i>0; i--){ <span>// The loop counts backwards for coding efficiency - and is used to draw all of the rectangles to screen</span><br />    myRecs[i].setMult(i);                               <span>// setMulti creates the specific curve pattern. </span><br />    myRecs[i].setRed(avgBPM);                           <span>// The rectangles become more "Red" with higher avgBPM values</span><br />    myRecs[i].setSize(myRecs[i-1].getH());              <span>// The current rectangle size is determined by the height of the rectangle immediately to it's left</span><br />    <span>fill</span>(myRecs[i].getR(),myRecs[i].getG(), myRecs[i].getB()); <span>// Set the colour of this rectangle</span><br />    <span>rect</span>(myRecs[i].getX(), myRecs[i].getY(), myRecs[i].getW(), myRecs[i].getH()); <span>// Draw this rectangle</span><br />  }<br />}<br /><br /><br /><span>//==drawBPM===========================================================================================</span><br /><span>void</span> drawBPM(){ <span>// This custom method is used to calculate the avgBPM and draw it to screen.</span><br />  sumBPM = 0;                                           <span>// Reset the sumBPM variable</span><br />  avgBPM = 0;                                           <span>// Reset the avgBPM variable</span><br />  <span>boolean</span> calibrating = <span>false</span>; <span>// calibrating: this boolean variable is used to control when the avgBPM is displayed to screen</span><br />  <br />  <span>for</span>(<span>int</span> i=1; i<totalBeats; i++){<br />    sumBPM = sumBPM + BPM[i-1];                         <span>// Sum all of the BPM values in the BPM array.</span><br />    <span>if</span>(BPM[i-1]<1){ <span>// If any BPM values are equal to 0, then set the calibrating variable to true. </span><br />      calibrating = <span>true</span>; <span>// This will be used later to display "calibrating" on the screen.</span><br />    }<br />  }<br />  avgBPM = sumBPM/(totalBeats-1);                       <span>// Calculate the average BPM from all BPM values</span><br />                                                        <br />  <span>fill</span>(255); <span>// The text will be displayed as WHITE text</span><br />  <span>if</span>(calibrating){<br />    <span>textFont</span>(f);<br />    <span>text</span>(<span>"Calibrating"</span>, (4*<span>width</span>)/5, (<span>height</span>/5)); <span>// If the calibrating variable is TRUE, then display the word "Calibrating" on screen</span><br />    <span>fill</span>(0); <span>// Change the fill and stroke to black (0) so that other text is "hidden" while calibrating variable is TRUE</span><br />    <span>stroke</span>(0);<br />  } <span>else</span> {<br />    <span>textFont</span>(f2);<br />    <span>text</span>(avgBPM, (4*<span>width</span>)/5, (<span>height</span>/5)); <span>// If the calibrating variable is FALSE, then display the avgBPM variable on screen</span><br />    <span>stroke</span>(255); <span>// Change the stroke to white (255) to show the white line underlying the word BPM.</span><br />  }<br />  <br />   <span>textFont</span>(f);<br />   <span>text</span>(<span>"BPM"</span>, (82*<span>width</span>)/100, (<span>height</span>/11)); <span>// This will display the underlined word "BPM" when calibrating variable is FALSE.</span><br />   <span>line</span>((80*<span>width</span>)/100, (<span>height</span>/10),(88*<span>width</span>)/100, (<span>height</span>/10));<br />   <span>stroke</span>(0);<br />}<br /><br /><br /><span>//==serialEvent===========================================================================================</span><br /><span>void</span> serialEvent(Serial cPort){ <span>// This will be triggered every time a "new line" of data is received from the Arduino</span><br /> comPortString = cPort.readStringUntil(<span>'\n'</span>); <span>// Read this data into the comPortString variable.</span><br /> <span>if</span>(comPortString != <span>null</span>) { <span>// If the comPortString variable is not NULL then</span><br />   comPortString=<span>trim</span>(comPortString); <span>// trim any white space around the text.</span><br />   <span>int</span> i = <span>int</span>(<span>map</span>(<span>Integer</span>.<span>parseInt</span>(comPortString),1,1023,1,<span>height</span>)); <span>// convert the string to an integer, and map the value so that the rectangle will fit within the screen.</span><br />   arduinoValue = <span>float</span>(i); <span>// Convert the integer into a float value.</span><br />   <span>if</span> (!beat){<br />     <span>if</span>(arduinoValue>0){ <span>// When a beat is detected, the "trigger" method is called.</span><br />       trigger(<span>millis</span>()); <span>// millis() creates a timeStamp of when the beat occured.</span><br />       beat=<span>true</span>; <span>// The beat variable is changed to TRUE to register that a beat has been detected.</span><br />     }<br />   }<br />   <span>if</span> (arduinoValue<1){ <span>// When the Arduino value returns back to zero, we will need to change the beat status to FALSE.</span><br />     beat = <span>false</span>;<br />   }<br /> }<br />} <br /><br /><br /><span>//==trigger===========================================================================================</span><br /><span>void</span> trigger(<span>int</span> time){ <span>// This method is used to calculate the Beats per Minute (BPM) and to store the last 10 BPMs into the BPM[] array.</span><br />  totalTime = time - lastTime;                         <span>// totalTime = the current beat time minus the last time there was a beat.</span><br />  lastTime = time;                                     <span>// Set the lastTime variable to the current "time" for the next round of calculations.</span><br />  BPM[beatCounter] = 60000/totalTime;                  <span>// Calculate BPM from the totalTime. 60000 = 1 minute.</span><br />  beatCounter++;                                       <span>// Increment the beatCounter </span><br />  <span>if</span> (beatCounter>totalBeats-1){ <span>// Reset the beatCounter when the total number of BPMs have been stored into the BPM[] array.</span><br />    beatCounter=0;                                     <span>// This allows us to keep the last 10 BPM calculations at all times.</span><br />  }<br />}<br /><br /><br /><span>//==sketchFullScreen==========================================================================================</span><br /><span>boolean</span> sketchFullScreen() { <span>// This puts Processing into Full Screen Mode</span><br /> <span>return</span> <span>true</span>;<br />}<br /><br /><br /><span>//==Rectangle CLASS==================================================================================*********</span><br /><span>class</span> Rectangle{<br />  <span>float</span> xPos, defaultY, yPos, myWidth, myHeight, myMultiplier; <span>// Variables used for drawing rectangles</span><br />  <span>int</span> blueVal, greenVal, redVal; <span>// Variables used for the rectangle colour</span><br />  <br />  Rectangle(<span>int</span> recNum, <span>int</span> nRecs){ <span>// The rectangles are constructed using two variables. The total number of rectangles to be displayed, and the identification of this rectangle (recNum)</span><br />    myWidth = <span>displayWidth</span>/nRecs; <span>// The width of the rectangle is determined by the screen width and the total number of rectangles.</span><br />    xPos = recNum * myWidth;                                      <span>// The x Position of this rectangle is determined by the width of the rectangles (all same) and the rectangle identifier.</span><br />    defaultY=<span>displayHeight</span>/2; <span>// The default Y position of the rectangle is half way down the screen.</span><br />    yPos = defaultY;                                              <span>// yPos is used to adjust the position of the rectangle as the size changes.</span><br />    myHeight = 1;                                                 <span>// The height of the rectangle starts at 1 pixel</span><br />    myMultiplier = 1;                                             <span>// The myMultiplier variable will be used to create the funnel shaped path for the rectangles.</span><br />    redVal = 0;                                                   <span>// The red Value starts off being 0 - but changes with avgBPM. Higher avgBPM means higher redVal</span><br />    <br />    <span>if</span> (recNum>0){ <span>// The blue Value progressively increases with every rectangle (moving to the right of the screen)</span><br />      blueVal = (recNum*255)/nRecs;<br />    } <span>else</span> {<br />      blueVal = 0;<br />    }<br />    greenVal = 255-blueVal;                                       <span>// Initially, the green value is at the opposite end of the spectrum to the blue value.</span><br />  }<br />  <br />  <span>void</span> setSize(<span>float</span> newSize){ <span>// This is used to set the new size of each rectangle </span><br />    myHeight=newSize*myMultiplier;<br />    yPos=defaultY-(newSize/2);<br />  }<br />  <br />  <span>void</span> setMult(<span>int</span> i){ <span>// The multiplier is a function of COS, which means that it varies from 1 to 0.</span><br />    myMultiplier = <span>cos</span>(<span>radians</span>(i)); <span>// You can try other functions to experience different effects.</span><br />  }<br />  <br />  <span>void</span> setRed(<span>int</span> r){<br />    redVal = <span>int</span>(<span>constrain</span>(<span>map</span>(<span>float</span>(r), 60, 100, 0, 255),0,255)); <span>// setRed is used to change the redValue based on the "normal" value for resting BPM (60-100). </span><br />    greenVal = 255 - redVal;                                       <span>// When the avgBPM > 100, redVal will equal 255, and the greenVal will equal 0.</span><br />  }                                                                <span>// When the avgBPM < 60, redVal will equal 0, and greenVal will equal 255.</span><br />  <br />  <span>float</span> getX(){ <span>// get the x Position of the rectangle</span><br />    <span>return</span> xPos;<br />  }<br /> <br />  <span>float</span> getY(){ <span>// get the y Position of the rectangle</span><br />    <span>return</span> yPos;<br />  }<br />  <br />  <span>float</span> getW(){ <span>// get the width of the rectangle</span><br />    <span>return</span> myWidth;<br />  }<br />  <br />  <span>float</span> getH(){ <span>// get the height of the rectangle</span><br />    <span>return</span> myHeight;<br />  }<br />  <br />  <span>float</span> getM(){ <span>// get the Multiplier of the rectangle</span><br />    <span>return</span> myMultiplier;<br />  }<br />  <br />  <span>int</span> getB(){ <span>// get the "blue" component of the rectangle colour</span><br />    <span>return</span> blueVal;<br />  }<br />  <br />  <span>int</span> getR(){ <span>// get the "red" component of the rectangle colour</span><br />    <span>return</span> redVal;<br />  }<br />  <br />  <span>int</span> getG(){ <span>// get the "green" component of the rectangle colour</span><br />    <span>return</span> greenVal;<br />  }<br />}<br /><br /></pre> </td> </tr> </table></div></p> <br />  <br /> <p> <h4>Processing Code Discussion:</h4><br /> </p><p> The Rectangle class was created to store relevant information about each rectangle. By using a custom class, we were able to design our rectangles any way we wanted. These rectangles have properties and methods which allow us to easily control their position, size and colour. By adding some smart functionality to each rectangle, we were able to get the rectangle to automatically position and colour itself based on key values. </p> <p> The Serial library is used to allow communication with the Arduino. In this Processing sketch, the values obtained from the Arduino were converted to floats to allow easy calulations of the beats per minute (BPM). I am aware that I have over-engineered the serialEvent method somewhat, because the Arduino is only really sending two values. I didn't really need to convert the String. But I am happy with the end result, and it does the job I needed it to... </p> <div> <p> <div> <a href="http://4.bp.blogspot.com/-EVTCQ3vkgGc/VTnOarlOWSI/AAAAAAAABdc/MslEU5oirAY/s1600/Complete%2BWorkstation2.jpg"><img src="http://4.bp.blogspot.com/-EVTCQ3vkgGc/VTnOarlOWSI/AAAAAAAABdc/MslEU5oirAY/s1600/Complete%2BWorkstation2.jpg" /> </a> </div> </p> </div> </div><!--separator --><img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /><p> <div> This project is quite simple. I designed it so that you could omit the Processing code if you wanted to. In that scenario, you would only be left with a blinking LED that blinks in time with your pulse. The Processing code takes this project to the next level. It provides a nice animation and calculates the beats per minute (BPM). <br />   <br /> I hope you liked this tutorial. Please feel free to share it, comment or give it a plus one. If you didn't like it, I would still appreciate your constructive feedback. </div> <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> </p><p> <div> If you like this page, please do me a favour and show your appreciation : <br /> <br />  <br /> Visit my <a href="https://plus.google.com/u/0/b/107402020974762902161/107402020974762902161/posts">ArduinoBasics Google + page</a>.<br /> Follow me on Twitter by looking for <a href="https://twitter.com/ArduinoBasics">ScottC @ArduinoBasics</a>.<br /> I can also be found on <a href="https://www.pinterest.com/ArduinoBasics/">Pinterest</a> and <a href="https://instagram.com/arduinobasics">Instagram</a>. <br /> Have a look at my videos on my <a href="https://www.youtube.com/user/ScottCMe/videos">YouTube channel</a>.<br /> </div> </p> <br />  <br />  <p> <div> <a href="http://3.bp.blogspot.com/-x_TA-qhOCzM/VTnULXoWhQI/AAAAAAAABds/quh02BWGsec/s1600/Slide1.JPG"><img src="http://3.bp.blogspot.com/-x_TA-qhOCzM/VTnULXoWhQI/AAAAAAAABds/quh02BWGsec/s1600/Slide1.JPG" /></a></div><br /> </p> <br />  <br />  <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> <p> However, if you do not have a google profile... <br />Feel free to share this page with your friends in any way you see fit. </p>

Arduino Heart Rate Monitor


Project Description


Heart Rate Monitors are very popular at the moment.
There is something very appealing about watching the pattern of your own heart beat. And once you see it, there is an unstoppable urge to try and control it. This simple project will allow you to visualize your heart beat, and will calculate your heart rate. Keep reading to learn how to create your very own heart rate monitor.


 

Parts Required:


Fritzing Sketch


 

 
 
 

Grove Base Shield to Module Connections


 


 

Arduino Sketch


 

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
/* =================================================================================================
      Project: Arduino Heart rate monitor
       Author: Scott C
      Created: 21st April 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This is a simple sketch that uses a Grove Ear-clip Heart Rate sensor attached to an Arduino UNO,
               which sends heart rate data to the computer via Serial communication. You can see the raw data
               using the Serial monitor on the Arduino IDE, however, this sketch was specifically
               designed to interface with the matching Processing sketch for a much nicer graphical display.
               NO LIBRARIES REQUIRED.
=================================================================================================== */

#define Heart 2                            //Attach the Grove Ear-clip sensor to digital pin 2.
#define LED 4                              //Attach an LED to digital pin 4

boolean beat = false; /* This "beat" variable is used to control the timing of the Serial communication
                                           so that data is only sent when there is a "change" in digital readings. */

//==SETUP==========================================================================================
void setup() {
  Serial.begin(9600); //Initialise serial communication
  pinMode(Heart, INPUT); //Set digital pin 2 (heart rate sensor pin) as an INPUT
  pinMode(LED, OUTPUT); //Set digital pin 4 (LED) to an OUTPUT
}


//==LOOP============================================================================================
void loop() {
  if(digitalRead(Heart)>0){ //The heart rate sensor will trigger HIGH when there is a heart beat
    if<!beat){><span>//Only send data when it first discovers a heart beat - otherwise it will send a high value multiple times</span><br />      beat=<span>true</span>; <span>//By changing the beat variable to true, it stops further transmissions of the high signal</span><br />      <span>digitalWrite</span>(LED, <span>HIGH</span>); <span>//Turn the LED on </span><br />      <span><b>Serial</b></span>.<span>println</span>(1023); <span>//Send the high value to the computer via Serial communication.</span><br />    }<br />  } <span>else</span> { <span>//If the reading is LOW, </span><br />    <span>if</span>(beat){ <span>//and if this has just changed from HIGH to LOW (first low reading)</span><br />      beat=<span>false</span>; <span>//change the beat variable to false (to stop multiple transmissions)</span><br />      <span>digitalWrite</span>(LED, <span>LOW</span>); <span>//Turn the LED off.</span><br />      <span><b>Serial</b></span>.<span>println</span>(0); <span>//then send a low value to the computer via Serial communication.</span><br />    }<br />  }<br />}</pre> </td> </tr> </table></div></p> <br />  <br />   <br />  <br />  <p> <h4><a href="https://processing.org/download/?processing">Processing Sketch</a></h4> <br />  <div> <table> <tr> <td> <pre> 1<br /> 2<br /> 3<br /> 4<br /> 5<br /> 6<br /> 7<br /> 8<br /> 9<br /> 10<br /> 11<br /> 12<br /> 13<br /> 14<br /> 15<br /> 16<br /> 17<br /> 18<br /> 19<br /> 20<br /> 21<br /> 22<br /> 23<br /> 24<br /> 25<br /> 26<br /> 27<br /> 28<br /> 29<br /> 30<br /> 31<br /> 32<br /> 33<br /> 34<br /> 35<br /> 36<br /> 37<br /> 38<br /> 39<br /> 40<br /> 41<br /> 42<br /> 43<br /> 44<br /> 45<br /> 46<br /> 47<br /> 48<br /> 49<br /> 50<br /> 51<br /> 52<br /> 53<br /> 54<br /> 55<br /> 56<br /> 57<br /> 58<br /> 59<br /> 60<br /> 61<br /> 62<br /> 63<br /> 64<br /> 65<br /> 66<br /> 67<br /> 68<br /> 69<br /> 70<br /> 71<br /> 72<br /> 73<br /> 74<br /> 75<br /> 76<br /> 77<br /> 78<br /> 79<br /> 80<br /> 81<br /> 82<br /> 83<br /> 84<br /> 85<br /> 86<br /> 87<br /> 88<br /> 89<br /> 90<br /> 91<br /> 92<br /> 93<br /> 94<br /> 95<br /> 96<br /> 97<br /> 98<br /> 99<br />100<br />101<br />102<br />103<br />104<br />105<br />106<br />107<br />108<br />109<br />110<br />111<br />112<br />113<br />114<br />115<br />116<br />117<br />118<br />119<br />120<br />121<br />122<br />123<br />124<br />125<br />126<br />127<br />128<br />129<br />130<br />131<br />132<br />133<br />134<br />135<br />136<br />137<br />138<br />139<br />140<br />141<br />142<br />143<br />144<br />145<br />146<br />147<br />148<br />149<br />150<br />151<br />152<br />153<br />154<br />155<br />156<br />157<br />158<br />159<br />160<br />161<br />162<br />163<br />164<br />165<br />166<br />167<br />168<br />169<br />170<br />171<br />172<br />173<br />174<br />175<br />176<br />177<br />178<br />179<br />180<br />181<br />182<br />183<br />184<br />185<br />186<br />187<br />188<br />189<br />190<br />191<br />192<br />193<br />194<br />195<br />196<br />197<br />198<br />199<br />200<br />201<br />202<br />203<br />204<br />205<br />206<br />207<br />208<br />209<br />210<br />211<br />212<br />213<br />214<br /></pre> </td> <td> <pre><br /><span>/* =================================================================================================</span><br /><span>       Project: Arduino Heart rate monitor</span><br /><span>        Author: Scott C</span><br /><span>       Created: 21st April 2015</span><br /><span>Processing IDE: 2.2.1</span><br /><span>       Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html</span><br /><span>   Description: A Grove Ear-clip heart rate sensor allows an Arduino UNO to sense your pulse.</span><br /><span>                The data obtained by the Arduino can then be sent to the computer via Serial communication</span><br /><span>                which is then displayed graphically using this Processing sketch.</span><br /><span>                </span><br /><span>=================================================================================================== */</span><br /><br /><span>import</span> processing.serial.*; <span>// Import the serial library to allow Serial communication with the Arduino</span><br /><br /><span>int</span> numOfRecs = 45; <span>// numOfRecs: The number of rectangles to display across the screen</span><br />Rectangle[] myRecs = <span>new</span> Rectangle[numOfRecs]; <span>// myRecs[]: Is the array of Rectangles. Rectangle is a custom class (programmed within this sketch)</span><br /><br />Serial myPort;                                         <br /><span>String</span> comPortString=<span>"0"</span>; <span>//comPortString: Is used to hold the string received from the Arduino</span><br /><span>float</span> arduinoValue = 0; <span>//arduinoValue: Is the float variable converted from comPortString</span><br /><span>boolean</span> beat = <span>false</span>; <span>// beat: Used to control for multiple high/low signals coming from the Arduino</span><br /><br /><span>int</span> totalTime = 0; <span>// totalTime: Is the variable used to identify the total time between beats</span><br /><span>int</span> lastTime = 0; <span>// lastTime: Is the variable used to remember when the last beat took place</span><br /><span>int</span> beatCounter = 0; <span>// beatCounter: Is used to keep track of the number of beats (in order to calculate the average BPM)</span><br /><span>int</span> totalBeats = 10; <span>// totalBeats: Tells the computer that we want to calculate the average BPM using 10 beats.</span><br /><span>int</span>[] BPM = <span>new</span> <span>int</span>[totalBeats]; <span>// BPM[]: Is the Beat Per Minute (BPM) array - to hold 10 BPM calculations</span><br /><span>int</span> sumBPM = 0; <span>// sumBPM: Is used to sum the BPM[] array values, and is then used to calculate the average BPM.</span><br /><span>int</span> avgBPM = 0; <span>// avgBPM: Is the variable used to hold the average BPM calculated value.</span><br /><br /><span>PFont</span> f, f2; <span>// f & f2 : Are font related variables. Used to store font properties. </span><br /><br /><br /><span>//==SETUP==============================================================================================</span><br /><span>void</span> <span><b>setup</b></span>(){<br />  <span>size</span>(<span>displayWidth</span>,<span>displayHeight</span>); <span>// Set the size of the display to match the monitor width and height</span><br />  <span>smooth</span>(); <span>// Draw all shapes with smooth edges.</span><br />  f = <span>createFont</span>(<span>"Arial"</span>,24); <span>// Initialise the "f" font variable - used for the "calibrating" text displayed at the beginning</span><br />  f2 = <span>createFont</span>(<span>"Arial"</span>,96); <span>// Initialise the "f2" font variable - used for the avgBPM display on screen</span><br />  <br />  <span>for</span>(<span>int</span> i=0; i<numOfRecs; i++){ <span>// Initialise the array of rectangles</span><br />    myRecs[i] = <span>new</span> Rectangle(i, numOfRecs);<br />  }<br />  <br />  <span>for</span>(<span>int</span> i=0; i<totalBeats; i++){ <span>// Initialise the BPM array</span><br />    BPM[i] = 0;<br />  }<br />  <br />  myPort = <span>new</span> Serial(<span>this</span>, Serial.<span>list</span>()[0], 9600); <span>// Start Serial communication with the Arduino using a baud rate of 9600</span><br />  myPort.bufferUntil(<span>'\n'</span>); <span>// Trigger a SerialEvent on new line</span><br />}<br /><br /><br /><span>//==DRAW==============================================================================================</span><br /><span>void</span> <span><b>draw</b></span>(){<br />  <span>background</span>(0); <span>// Set the background to BLACK (this clears the screen each time)</span><br />  drawRecs();                                           <span>// Method call to draw the rectangles on the screen</span><br />  drawBPM();                                            <span>// Method call to draw the avgBPM value to the top right of the screen</span><br />}<br /><br /><br /><span>//==drawRecs==========================================================================================</span><br /><span>void</span> drawRecs(){ <span>// This custom method will draw the rectangles on the screen </span><br />  myRecs[0].setSize(arduinoValue);                      <span>// Set the first rectangle to match arduinoValue; any positive value will start the animation.</span><br />  <span>for</span>(<span>int</span> i=numOfRecs-1; i>0; i--){ <span>// The loop counts backwards for coding efficiency - and is used to draw all of the rectangles to screen</span><br />    myRecs[i].setMult(i);                               <span>// setMulti creates the specific curve pattern. </span><br />    myRecs[i].setRed(avgBPM);                           <span>// The rectangles become more "Red" with higher avgBPM values</span><br />    myRecs[i].setSize(myRecs[i-1].getH());              <span>// The current rectangle size is determined by the height of the rectangle immediately to it's left</span><br />    <span>fill</span>(myRecs[i].getR(),myRecs[i].getG(), myRecs[i].getB()); <span>// Set the colour of this rectangle</span><br />    <span>rect</span>(myRecs[i].getX(), myRecs[i].getY(), myRecs[i].getW(), myRecs[i].getH()); <span>// Draw this rectangle</span><br />  }<br />}<br /><br /><br /><span>//==drawBPM===========================================================================================</span><br /><span>void</span> drawBPM(){ <span>// This custom method is used to calculate the avgBPM and draw it to screen.</span><br />  sumBPM = 0;                                           <span>// Reset the sumBPM variable</span><br />  avgBPM = 0;                                           <span>// Reset the avgBPM variable</span><br />  <span>boolean</span> calibrating = <span>false</span>; <span>// calibrating: this boolean variable is used to control when the avgBPM is displayed to screen</span><br />  <br />  <span>for</span>(<span>int</span> i=1; i<totalBeats; i++){<br />    sumBPM = sumBPM + BPM[i-1];                         <span>// Sum all of the BPM values in the BPM array.</span><br />    <span>if</span>(BPM[i-1]<1){ <span>// If any BPM values are equal to 0, then set the calibrating variable to true. </span><br />      calibrating = <span>true</span>; <span>// This will be used later to display "calibrating" on the screen.</span><br />    }<br />  }<br />  avgBPM = sumBPM/(totalBeats-1);                       <span>// Calculate the average BPM from all BPM values</span><br />                                                        <br />  <span>fill</span>(255); <span>// The text will be displayed as WHITE text</span><br />  <span>if</span>(calibrating){<br />    <span>textFont</span>(f);<br />    <span>text</span>(<span>"Calibrating"</span>, (4*<span>width</span>)/5, (<span>height</span>/5)); <span>// If the calibrating variable is TRUE, then display the word "Calibrating" on screen</span><br />    <span>fill</span>(0); <span>// Change the fill and stroke to black (0) so that other text is "hidden" while calibrating variable is TRUE</span><br />    <span>stroke</span>(0);<br />  } <span>else</span> {<br />    <span>textFont</span>(f2);<br />    <span>text</span>(avgBPM, (4*<span>width</span>)/5, (<span>height</span>/5)); <span>// If the calibrating variable is FALSE, then display the avgBPM variable on screen</span><br />    <span>stroke</span>(255); <span>// Change the stroke to white (255) to show the white line underlying the word BPM.</span><br />  }<br />  <br />   <span>textFont</span>(f);<br />   <span>text</span>(<span>"BPM"</span>, (82*<span>width</span>)/100, (<span>height</span>/11)); <span>// This will display the underlined word "BPM" when calibrating variable is FALSE.</span><br />   <span>line</span>((80*<span>width</span>)/100, (<span>height</span>/10),(88*<span>width</span>)/100, (<span>height</span>/10));<br />   <span>stroke</span>(0);<br />}<br /><br /><br /><span>//==serialEvent===========================================================================================</span><br /><span>void</span> serialEvent(Serial cPort){ <span>// This will be triggered every time a "new line" of data is received from the Arduino</span><br /> comPortString = cPort.readStringUntil(<span>'\n'</span>); <span>// Read this data into the comPortString variable.</span><br /> <span>if</span>(comPortString != <span>null</span>) { <span>// If the comPortString variable is not NULL then</span><br />   comPortString=<span>trim</span>(comPortString); <span>// trim any white space around the text.</span><br />   <span>int</span> i = <span>int</span>(<span>map</span>(<span>Integer</span>.<span>parseInt</span>(comPortString),1,1023,1,<span>height</span>)); <span>// convert the string to an integer, and map the value so that the rectangle will fit within the screen.</span><br />   arduinoValue = <span>float</span>(i); <span>// Convert the integer into a float value.</span><br />   <span>if</span> (!beat){<br />     <span>if</span>(arduinoValue>0){ <span>// When a beat is detected, the "trigger" method is called.</span><br />       trigger(<span>millis</span>()); <span>// millis() creates a timeStamp of when the beat occured.</span><br />       beat=<span>true</span>; <span>// The beat variable is changed to TRUE to register that a beat has been detected.</span><br />     }<br />   }<br />   <span>if</span> (arduinoValue<1){ <span>// When the Arduino value returns back to zero, we will need to change the beat status to FALSE.</span><br />     beat = <span>false</span>;<br />   }<br /> }<br />} <br /><br /><br /><span>//==trigger===========================================================================================</span><br /><span>void</span> trigger(<span>int</span> time){ <span>// This method is used to calculate the Beats per Minute (BPM) and to store the last 10 BPMs into the BPM[] array.</span><br />  totalTime = time - lastTime;                         <span>// totalTime = the current beat time minus the last time there was a beat.</span><br />  lastTime = time;                                     <span>// Set the lastTime variable to the current "time" for the next round of calculations.</span><br />  BPM[beatCounter] = 60000/totalTime;                  <span>// Calculate BPM from the totalTime. 60000 = 1 minute.</span><br />  beatCounter++;                                       <span>// Increment the beatCounter </span><br />  <span>if</span> (beatCounter>totalBeats-1){ <span>// Reset the beatCounter when the total number of BPMs have been stored into the BPM[] array.</span><br />    beatCounter=0;                                     <span>// This allows us to keep the last 10 BPM calculations at all times.</span><br />  }<br />}<br /><br /><br /><span>//==sketchFullScreen==========================================================================================</span><br /><span>boolean</span> sketchFullScreen() { <span>// This puts Processing into Full Screen Mode</span><br /> <span>return</span> <span>true</span>;<br />}<br /><br /><br /><span>//==Rectangle CLASS==================================================================================*********</span><br /><span>class</span> Rectangle{<br />  <span>float</span> xPos, defaultY, yPos, myWidth, myHeight, myMultiplier; <span>// Variables used for drawing rectangles</span><br />  <span>int</span> blueVal, greenVal, redVal; <span>// Variables used for the rectangle colour</span><br />  <br />  Rectangle(<span>int</span> recNum, <span>int</span> nRecs){ <span>// The rectangles are constructed using two variables. The total number of rectangles to be displayed, and the identification of this rectangle (recNum)</span><br />    myWidth = <span>displayWidth</span>/nRecs; <span>// The width of the rectangle is determined by the screen width and the total number of rectangles.</span><br />    xPos = recNum * myWidth;                                      <span>// The x Position of this rectangle is determined by the width of the rectangles (all same) and the rectangle identifier.</span><br />    defaultY=<span>displayHeight</span>/2; <span>// The default Y position of the rectangle is half way down the screen.</span><br />    yPos = defaultY;                                              <span>// yPos is used to adjust the position of the rectangle as the size changes.</span><br />    myHeight = 1;                                                 <span>// The height of the rectangle starts at 1 pixel</span><br />    myMultiplier = 1;                                             <span>// The myMultiplier variable will be used to create the funnel shaped path for the rectangles.</span><br />    redVal = 0;                                                   <span>// The red Value starts off being 0 - but changes with avgBPM. Higher avgBPM means higher redVal</span><br />    <br />    <span>if</span> (recNum>0){ <span>// The blue Value progressively increases with every rectangle (moving to the right of the screen)</span><br />      blueVal = (recNum*255)/nRecs;<br />    } <span>else</span> {<br />      blueVal = 0;<br />    }<br />    greenVal = 255-blueVal;                                       <span>// Initially, the green value is at the opposite end of the spectrum to the blue value.</span><br />  }<br />  <br />  <span>void</span> setSize(<span>float</span> newSize){ <span>// This is used to set the new size of each rectangle </span><br />    myHeight=newSize*myMultiplier;<br />    yPos=defaultY-(newSize/2);<br />  }<br />  <br />  <span>void</span> setMult(<span>int</span> i){ <span>// The multiplier is a function of COS, which means that it varies from 1 to 0.</span><br />    myMultiplier = <span>cos</span>(<span>radians</span>(i)); <span>// You can try other functions to experience different effects.</span><br />  }<br />  <br />  <span>void</span> setRed(<span>int</span> r){<br />    redVal = <span>int</span>(<span>constrain</span>(<span>map</span>(<span>float</span>(r), 60, 100, 0, 255),0,255)); <span>// setRed is used to change the redValue based on the "normal" value for resting BPM (60-100). </span><br />    greenVal = 255 - redVal;                                       <span>// When the avgBPM > 100, redVal will equal 255, and the greenVal will equal 0.</span><br />  }                                                                <span>// When the avgBPM < 60, redVal will equal 0, and greenVal will equal 255.</span><br />  <br />  <span>float</span> getX(){ <span>// get the x Position of the rectangle</span><br />    <span>return</span> xPos;<br />  }<br /> <br />  <span>float</span> getY(){ <span>// get the y Position of the rectangle</span><br />    <span>return</span> yPos;<br />  }<br />  <br />  <span>float</span> getW(){ <span>// get the width of the rectangle</span><br />    <span>return</span> myWidth;<br />  }<br />  <br />  <span>float</span> getH(){ <span>// get the height of the rectangle</span><br />    <span>return</span> myHeight;<br />  }<br />  <br />  <span>float</span> getM(){ <span>// get the Multiplier of the rectangle</span><br />    <span>return</span> myMultiplier;<br />  }<br />  <br />  <span>int</span> getB(){ <span>// get the "blue" component of the rectangle colour</span><br />    <span>return</span> blueVal;<br />  }<br />  <br />  <span>int</span> getR(){ <span>// get the "red" component of the rectangle colour</span><br />    <span>return</span> redVal;<br />  }<br />  <br />  <span>int</span> getG(){ <span>// get the "green" component of the rectangle colour</span><br />    <span>return</span> greenVal;<br />  }<br />}<br /><br /></pre> </td> </tr> </table></div></p> <br />  <br /> <p> <h4>Processing Code Discussion:</h4><br /> </p><p> The Rectangle class was created to store relevant information about each rectangle. By using a custom class, we were able to design our rectangles any way we wanted. These rectangles have properties and methods which allow us to easily control their position, size and colour. By adding some smart functionality to each rectangle, we were able to get the rectangle to automatically position and colour itself based on key values. </p> <p> The Serial library is used to allow communication with the Arduino. In this Processing sketch, the values obtained from the Arduino were converted to floats to allow easy calulations of the beats per minute (BPM). I am aware that I have over-engineered the serialEvent method somewhat, because the Arduino is only really sending two values. I didn't really need to convert the String. But I am happy with the end result, and it does the job I needed it to... </p> <div> <p> <div> <a href="http://4.bp.blogspot.com/-EVTCQ3vkgGc/VTnOarlOWSI/AAAAAAAABdc/MslEU5oirAY/s1600/Complete%2BWorkstation2.jpg"><img src="http://4.bp.blogspot.com/-EVTCQ3vkgGc/VTnOarlOWSI/AAAAAAAABdc/MslEU5oirAY/s1600/Complete%2BWorkstation2.jpg" /> </a> </div> </p> </div> </div><!--separator --><img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /><p> <div> This project is quite simple. I designed it so that you could omit the Processing code if you wanted to. In that scenario, you would only be left with a blinking LED that blinks in time with your pulse. The Processing code takes this project to the next level. It provides a nice animation and calculates the beats per minute (BPM). <br />   <br /> I hope you liked this tutorial. Please feel free to share it, comment or give it a plus one. If you didn't like it, I would still appreciate your constructive feedback. </div> <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> </p><p> <div> If you like this page, please do me a favour and show your appreciation : <br /> <br />  <br /> Visit my <a href="https://plus.google.com/u/0/b/107402020974762902161/107402020974762902161/posts">ArduinoBasics Google + page</a>.<br /> Follow me on Twitter by looking for <a href="https://twitter.com/ArduinoBasics">ScottC @ArduinoBasics</a>.<br /> I can also be found on <a href="https://www.pinterest.com/ArduinoBasics/">Pinterest</a> and <a href="https://instagram.com/arduinobasics">Instagram</a>. <br /> Have a look at my videos on my <a href="https://www.youtube.com/user/ScottCMe/videos">YouTube channel</a>.<br /> </div> </p> <br />  <br />  <p> <div> <a href="http://3.bp.blogspot.com/-x_TA-qhOCzM/VTnULXoWhQI/AAAAAAAABds/quh02BWGsec/s1600/Slide1.JPG"><img src="http://3.bp.blogspot.com/-x_TA-qhOCzM/VTnULXoWhQI/AAAAAAAABds/quh02BWGsec/s1600/Slide1.JPG" /></a></div><br /> </p> <br />  <br />  <br />  <div> <p> <!--separator --> <img src="https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http%3A%2F%2F1.bp.blogspot.com%2F-XQiwNpdqOxk%2FT_rKCzDh4nI%2FAAAAAAAAAQY%2FOfYBljhU6Lk%2Fs1600%2FSeparator.jpg&container=blogger&gadget=a&rewriteMime=image%2F*" /><br /> <br /> </p> </div> <p> However, if you do not have a google profile... <br />Feel free to share this page with your friends in any way you see fit. </p>

Play your emotional state with Social Vibes and twitter

Social Vibes’ is a Masters Degree (MSc.) project, in Interactive Media by Cian McLysaght, at the University of Limerick, Ireland. They shared with us their project, running on Arduino Uno, composed by a physical artifact designed and created specifically for an installation adopting the fundamental sound mechanisms used in a vibraphone, know also as a ‘Vibe’:

The instrument consists of twelve musical tones of different pitches. The music created on the instrument is derived from a continuous stream of input via multiple users on Twitter and the explicit interaction from Twitter users, tweeting the instrument directly to the project’s, “@vibe_experiment” Twitter account. Data associated with the emotional status of Twitter users, is mined from the Twitter network via Twitter’s open source, application programming interface (API).

For example if a user tweets “The sun is out, I’m happy”, the code I’ve written will strip out key words and strings associated with the user’s emotional state, within the tweets, ie “I’m happy”, and translate this to a musical notation. Mining Twitter’s API, allows a continuous stream of data. These emotional states are then mapped to specific notes on the physical musical instrument, located in a public space. The tempo of the musical expression will be entirely based upon the speed and volume of the incoming tweets on the Twitter API.

Twitter users who are both followers and non followers of the musical instrument’s Twitter account (@vibe_experiment) can tweet directly to the instrument and this direct interaction will be given precedence, allowing user’s who tweet directly to have their emotional state ‘played’. This allows users to hijack or take over the instrument and experiment with it in a playful manner, but also allows those with musical knowledge the potential to compose simple musical arrangements. When users are not tweeting the instrument directly, then the instrument will revert to mining the Twitter API.

To entice users to interact and observe the action of the instrument there is a live streaming broadcast of the instrument via Twitcam on the Vibe’s Twitter account. This is a live streaming broadcast of the instrument via Twitcam on the @vibe_experiment account. Twitcam, is Twitter’s built in live-streaming platform. This simply requires a webcam and a valid Twitter account.

The instrument constantly tweets back updates to it’s own Twitter account to not only inform people of the general status but also to engage users to interact directly with the ‘Vibe’.

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 partone:
  • 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
import android.bluetooth.BluetoothSocket;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;

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



private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";

public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}

public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()

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

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}

/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "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
/* SendReceiveBytes: Written by ScottC on 25 March 2013 using 
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public BluetoothSocket scSocket;


boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";

// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";

//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

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


/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();


/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();


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


void setup() {
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}


/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}


void draw() {
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if (foundDevice) {
if (BTisConnected) {
background(170, 50, 255); // purple screen
}
else {
background(10, 255, 10); // green screen
}
}

//Display anything received from Arduino
text(readMessage, 10, 10);
}


/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;

@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("ACTION:" + action);

//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("Discovered: " + discoveredDeviceName);

//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("getAddress() = " + discoveredDevice.getAddress());
ToastMaster("getName() = " + discoveredDevice.getName());

int bondyState=discoveredDevice.getBondState();
ToastMaster("getBondState() = " + bondyState);

String mybondState;
switch(bondyState) {
case 10:
mybondState="BOND_NONE";
break;
case 11:
mybondState="BOND_BONDING";
break;
case 12:
mybondState="BOND_BONDED";
break;
default:
mybondState="INVALID BOND STATE";
break;
}
ToastMaster("getBondState() = " + mybondState);

//Change foundDevice to true which will make the screen turn green
foundDevice=true;

//Connect to the discovered bluetooth device (SeeedBTSlave)
if (discoveredDeviceName.equals("SeeedBTSlave")) {
ToastMaster("Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}

//Notification if bluetooth device is connected
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster("CONNECTED _ YAY");

while (scSocket==null) {
//do nothing
}
ToastMaster("scSocket" + scSocket);
BTisConnected=true; //turn screen purple
if (scSocket!=null) {
SendReceiveBytes sendReceiveBT = new SendReceiveBytes(scSocket);
new Thread(sendReceiveBT).start();
String red = "r";
byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}
public static byte[] stringToBytesUTFCustom(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;
}

public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}

@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

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

/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}


private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";

public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}


public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()

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


/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}


/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}



/* My ToastMaster function to display a messageBox on the screen */
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.



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
/* 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

*/

#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
}
}

//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);
}



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
import apwidgets.*;

APWidgetContainer widgetContainer;
APButton redButton, greenButton, blueButton, offButton;
String buttonText="";
int buttonWidth=0;
int buttonHeight=0;
int n=4; //number of buttons
int gap=10; //gap between buttons


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



void draw() {
//Change the text based on the button being pressed.
text(buttonText, 10, buttonHeight+(buttonHeight/2));
}



//onClickWidget is called when a widget is clicked/touched
void onClickWidget(APWidget widget) {

if (widget == redButton) { //if the red button was clicked
buttonText="RED";
background(255, 0, 0);
}
else if (widget == greenButton) { //if the green button was clicked
buttonText="GREEN";
background(0, 255, 0);
}
else if (widget == blueButton) { //if the blue button was clicked
buttonText="BLUE";
background(0, 0, 255);
}
else if (widget == offButton) { //if the off button was clicked
buttonText="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
/* BluetoothApp1: Written by ScottC on 25 March 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 */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import apwidgets.*;
public BluetoothSocket scSocket;


//Used for the GUI**************************************
APWidgetContainer widgetContainer;
APButton redButton, greenButton, blueButton, offButton;
String buttonText="";
int buttonWidth=0;
int buttonHeight=0;
int n=4; //number of buttons
int gap=10; //gap between buttons

boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";

// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";

//Used to send bytes to the Arduino
SendReceiveBytes sendReceiveBT=null;

//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

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


/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();


/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();



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



void setup() {
orientation(LANDSCAPE);

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

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

/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}


void draw() {
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if (foundDevice) {
if (BTisConnected) {
background(170, 50, 255); // purple screen
}
else {
background(10, 255, 10); // green screen
}
}


//Change the text based on the button being pressed.
text(buttonText, 10, buttonHeight+(buttonHeight/2));

//Display anything received from Arduino
text(readMessage, 10, buttonHeight+(buttonHeight/2)+30);
}



/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;

@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("ACTION:" + action);

//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("Discovered: " + discoveredDeviceName);

//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("getAddress() = " + discoveredDevice.getAddress());
ToastMaster("getName() = " + discoveredDevice.getName());

int bondyState=discoveredDevice.getBondState();
ToastMaster("getBondState() = " + bondyState);

String mybondState;
switch(bondyState) {
case 10:
mybondState="BOND_NONE";
break;
case 11:
mybondState="BOND_BONDING";
break;
case 12:
mybondState="BOND_BONDED";
break;
default:
mybondState="INVALID BOND STATE";
break;
}
ToastMaster("getBondState() = " + mybondState);

//Change foundDevice to true which will make the screen turn green
foundDevice=true;

//Connect to the discovered bluetooth device (SeeedBTSlave)
if (discoveredDeviceName.equals("SeeedBTSlave")) {
ToastMaster("Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}

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

public static byte[] stringToBytesUTFCustom(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;
}

public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}

@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

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

// Will allow you to get the socket from this class
public BluetoothSocket getSocket() {
return mySocket;
}

/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}



private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";

public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}

public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()

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

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}

/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}



/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}




//onClickWidget is called when a widget is clicked/touched
void onClickWidget(APWidget widget) {
String sendLetter = "";

//Disable the previous Background colour changers
foundDevice=false;
BTisConnected=false;

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

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
/* 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);
}



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.





Bluetooth Android Processing 2

PART TWO


If you happened to land on this page and missed PART ONE, I would advise you go back and read that section first. You may get lost coming in half way through the story. 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.
In the last sketch we checked to see if Bluetooth was enabled, if not, we then asked for permission to turn it on. The screen would then display a different colour depending on the Bluetooth state. So let's keep on going,


ToastMaster - the master of all Toasts

I will now introduce you to Toast. What does "Toast" have to do with programming ? Toast is used by Android to quietly display little messages on the screen.
Have a look here for a a quick introduction to Toast, otherwise have a look at the Android Developers Toast information.

I will be creating my own method that relies on Toast to make the process of displaying messages easier. I have named this method: "ToastMaster".
A word of warning. Calling ToastMaster from within setup() will cause errorsin the DiscoverBluetooth sketch (further down this page).
This will not happen in every sketch, but the Discoverbluetooth sketch has subActivities which may cause some sort of conflict.. I did warn you.

Here is a quick look at my ToastMaster method (no need to compile this code):
1
2
3
4
5
6
7
8
/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_LONG);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}

Here is a breakdown of what this is doing:
  • Toast.makeText() - is used to construct the message to be displayed. 
  • getApplicationContext() - gets a handle on the Application
  • textToDisplay - is obvious, this is the text you want to display.
  • Toast.LENGTH_LONG - is how long you want the message to displayed for. (or LENGTH_SHORT)
  • setGravity() - sets the message position on the screen, in this case I have chosen to center the text.
  • show() - is used to actually show the message.

Broadcast Receivers : Looking out for Bluetooth devices
To listen/look out for any Bluetooth devices that are within range, we need to create and  register a Broadcast receiver.
When registering a BroadcastReceiver, you will need to tell the program what it is you are looking / listening out for. In our case we want to listen out for occasions whereby a Bluetooth device is FOUND.  This is represented by:
If a BluetoothDevice is found, then the designated BroadcastReceiver will be called. We make our own BroadcastReceiver in order to perform a task such as displaying the name of the discovered device on the phone. However, before you will find anything, you have to start Discovering. This is done by calling the startDiscovery() method of the default Bluetooth adapter.

Here are the relevant components:
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
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver myDiscoverer =
new myOwnBroadcastReceiver();
//Within Setup()
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
if (!bluetooth.isDiscovering()){
bluetooth.startDiscovery();
}
}

/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);

//Display the name of the discovered device
ToastMaster("
Discovered: " + discoveredDeviceName);
}
}




Discovering Bluetooth devices: putting it all together

You will notice that in the following sketch, we have to import a whole lot more. Which is why I have tried to break it down into bite size chunks, to help you digest it all. Now we will put it all together into a sketch which will
  • ask to turn Bluetooth ON if it happens to be disabled.
  • If you don't turn on Bluetooth, it will tell you that you need to turn it on.
  • If you turn on bluetooth (or if it was already on), it will try to discover any bluetooth devices in range. These devices need to be made "discoverable" before running this sketch.
  • If the phone finds a bluetooth device, it will display the name of the device and will change the background screen colour to GREEN.
Android/Processing Sketch 4: DiscoverBluetooth
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
/* DiscoverBluetooth: Written by ScottC on 18 March 2013 using 
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform */


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

boolean foundDevice=
false; //When this is true, the screen turns green.
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==0){
if(resultCode == RESULT_OK){
ToastMaster("
Bluetooth has been switched ON");
}
else {
ToastMaster("
You need to turn Bluetooth ON !!!");
}
}
}


/* Create a Broadcast Receiver that will later be used to
receive the names of Bluetooth devices in range. */

BroadcastReceiver myDiscoverer =
new myOwnBroadcastReceiver();


void setup(){
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth =
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}

/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */

if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()){
bluetooth.startDiscovery();
}
}
}


void draw(){
//Display a green screen if a device has been found
if(foundDevice){
background(10,255,10);
}
}


/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);

//Display the name of the discovered device
ToastMaster("
Discovered: " + discoveredDeviceName);

//Change foundDevice to true which will make the screen turn green
foundDevice=
true;
}
}


/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_LONG);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}


Upgrading the Broadcast Receiver : More Device info

Ok, we have the device name. But what other information can we collect from the device? You can call
This will return the discovered BluetoothDevice, which can then be probed to find the following information.
  • .getName()   =  Which is a different way of getting the name of the BluetoothDevice.
  • .getAddress() = Returns the hardware address of the BluetoothDevice.  eg. "00:11:22:AA:BB:CC"
  • .getBondState() = Returns an integer which describes the BondState of the BluetoothDevice
These are the three possible BondStates 
Here is an updated version of the custom BroadcastReceiver class (myOwnBroadcastReceiver) from the DiscoverBluetooth sketch described above.
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
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("
Discovered: " + discoveredDeviceName);

//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("
getAddress() = " + discoveredDevice.getAddress());
ToastMaster("
getName() = " + discoveredDevice.getName());

int bondyState=discoveredDevice.getBondState();
ToastMaster("
getBondState() = " + bondyState);

String mybondState;
switch(bondyState){
case 10: mybondState="BOND_NONE";
break;
case 11: mybondState="BOND_BONDING";
break;
case 12: mybondState="BOND_BONDED";
break;
default: mybondState="INVALID BOND STATE";
break;
}
ToastMaster("
getBondState() = " + mybondState);

//Change foundDevice to true which will make the screen turn green
foundDevice=
true;
}
}

If you replace the old version of  myOwnBroadcastReceiver with this one, you will know a little bit more about the devices discovered.


Connecting to the Bluetooth Device:
While we now have more information about the Bluetooth device, we don't really need it, and we will get rid of it by the end of the tutorial, however we will keep it here for the time being. In the next updated sketch we will be making a connection to the discovered device, and turning the background purple when the connection is made. In order to do this we will need to
  • Create a boolean variable to hold the connection status
  • Create and register a new BroadcastReceiver to notify us when a connection broadcast action has been received.
  • Create a new thread to handle the connection
  • Change the background screen colour when a successful connection has been made
First we need the boolean to hold the connection status:
  • boolean BTisConnected=false;
When the boolean is true, the screen will change to purple. The draw() method will be updated to accommodate this requirement.
Next we will create and register a new BroadcastReceiver, it is created using this:
  • BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
This broadcastreceiver will be used to notify us when a connection has been made. Therefore we need to register the (BluetoothDevice.ACTION_ACL_CONNECTED)
action with the BroadcastReceiver in the following way
  • registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
We will need to update myOwnBroadcastReceiver() to be able to differentiate beween this action and the (BluetoothDevice.ACTION_FOUND) action used already. This is done by first getting the action from the intent variable described in the onReceive() method within myOwnBroadcastReceiver().
  • String action=intent.getAction();
We can differentiate the two actions using the following simplified code in myOwnBroadcastReceiver:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class myOwnBroadcastReceiver 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)){
foundDevice=
true; //Change the screen to green
}

//Notification if bluetooth device is connected
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
BTisConnected=
true; //turn screen purple
}
}
}

Now that we can be notified about the connection made to the Bluetooth Device, lets go through the code required to make the connection. We will only connect if we have actually discovered a device, so we will put this code within the FOUND section of myOwnBroadcastReceiver.

1
2
3
4
5
6
7
8
 //Connect to the discovered bluetooth device (SeeedBTSlave)
if(discoveredDeviceName.equals("SeeedBTSlave")){
unregisterReceiver(myDiscoverer);
ConnectToBluetooth connectBT =
new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}

We use the discoveredDeviceName variable to specifically target the Bluetooth device we wish to connect to. We then unregister the myDiscoverer BroadcastReceiver because we are going to stop discovering before we connect to the Bluetooth Device, plus if you don't, it will generate an error. We then pass our discovered device to a new Thread to connect to that device in the background.  The class used to handle the connection is the "ConnectToBluetooth" class as displayed below:

We will cancelDiscovery() on the bluetooth Adapter to prevent a slow connection.
Also we will need to use a specific UUID as per below:
  • private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I have tried changing the UUID, but changing it to a different number prevented it from establishing a connection.
Before you can connect to the Bluetooth shield you need to use the UUID to create a BluetoothSocket.
  • mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
Once you have the socket, you can then try to connect using:
  • mySocket.connect();
Make sure you have some way of closing the socket, this is done in the cancel() method.

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
public class ConnectToBluetooth implements Runnable{
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try{
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException){
//Problem with creating a socket
}
}

@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

try{
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */

mySocket.connect();
}
catch (IOException connectException){
try{
mySocket.close();
//try to close the socket
}
catch(IOException closeException){
}
return;
}
}

/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e){
}
}
}

The major structure of this code was made possible using the following site:
http://jayxie.com/mirrors/android-sdk/guide/topics/wireless/bluetooth.html

And the following sites were also useful in getting some of the information I needed:
http://stackoverflow.com/questions/13238600/use-registerreceiver-for-non-activity-and-non-service-class
http://developer.android.com/guide/topics/connectivity/bluetooth.html


While I have described all the major components required to connect to the Bluetooth Device, I will now put it all together in a new and updated version of the "DiscoverBluetooth" Android/Processing sketch and call it "ConnectBluetooth". There is some additional code in this sketch which I did not specifically go through, for example, the code used to turn the background to purple in the draw() method. Look out for that one. Anyway, read through the following code, and make sure that you understand what each section is doing.

Android/Processing Sketch 5: ConnectBluetooth
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
/* ConnectBluetooth: Written by ScottC on 18 March 2013 using 
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform */


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

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

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

boolean foundDevice=
false; //When true, the screen turns green.
boolean BTisConnected=
false; //When true, the screen turns purple.


//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==0){
if(resultCode == RESULT_OK){
ToastMaster("
Bluetooth has been switched ON");
}
else {
ToastMaster("
You need to turn Bluetooth ON !!!");
}
}
}


/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */

BroadcastReceiver myDiscoverer =
new myOwnBroadcastReceiver();
/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */

BroadcastReceiver checkIsConnected =
new myOwnBroadcastReceiver();

void setup(){
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth =
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}

/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */

if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()){
bluetooth.startDiscovery();
}
}
}


void draw(){
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if(foundDevice){
if(BTisConnected){
background(170,50,255);
// purple screen
}
else {
background(10,255,10);
// green screen
}
}
}


/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("
ACTION:" + action);

//Notification that BluetoothDevice is FOUND
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("
Discovered: " + discoveredDeviceName);

//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("
getAddress() = " + discoveredDevice.getAddress());
ToastMaster("
getName() = " + discoveredDevice.getName());

int bondyState=discoveredDevice.getBondState();
ToastMaster("
getBondState() = " + bondyState);

String mybondState;
switch(bondyState){
case 10: mybondState="BOND_NONE";
break;
case 11: mybondState="BOND_BONDING";
break;
case 12: mybondState="BOND_BONDED";
break;
default: mybondState="INVALID BOND STATE";
break;
}
ToastMaster("
getBondState() = " + mybondState);

//Change foundDevice to true which will make the screen turn green
foundDevice=
true;

//Connect to the discovered bluetooth device (SeeedBTSlave)
if(discoveredDeviceName.equals("SeeedBTSlave")){
ToastMaster("
Connecting you Now !!");
unregisterReceiver(myDiscoverer);
ConnectToBluetooth connectBT =
new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}

//Notification if bluetooth device is connected
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
ToastMaster("
CONNECTED _ YAY");
BTisConnected=
true; //turn screen purple
}
}
}
public class ConnectToBluetooth implements Runnable{
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try{
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException){
//Problem with creating a socket
}
}

@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

try{
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */

mySocket.connect();
}
catch (IOException connectException){
try{
mySocket.close();
//try to close the socket
}
catch(IOException closeException){
}
return;
}
}

/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e){
}
}
}

/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}


The Arduino Sketch

Most of the Android/Processing code used so far has depended on a Bluetooth Device being discoverable. Our ultimate aim it to connect to a Bluetooth Shield on an Arduino UNO or compatible board such as the Freetronics Eleven. The following sketch was essentially taken from one of my previous posts (here), however, I have stripped it down to the bear essentials so that it will only be discoverable, and will not send or receive data. I will provide this functionality later. I just wanted to show you the essential bits to establish the connection to the Shield.

ARDUINO Sketch 1: Bluetooth Pair and Connect
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
/* This project combines the code from a few different sources.
This project was put together by ScottC on the 22/03/2013
http://arduinobasics.blogspot.com/

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

This sketch does nothing more than setup bluetooth
connection capabilities. It does not send or receive data.

*/


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

#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

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
}
/*----------------------LOOP----------------------------*/ void loop() {
digitalWrite(13,LOW);
//Turn off the onboard Arduino LED
}

//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();
}



Please make sure to setup the Bluetooth jumpers as per the picture below, otherwise you will not have much luck with the sketch above.






Well that brings us to the end of part TWO.

PART THREE
In part three we will attempt to actually send some data from the Android phone to the Arduino via Bluetooth, and vice versa. This will be when the real fun starts.


or GO BACK
Click on the link if you missed PART ONE

Bluetooth Android Processing 1


PART ONE


Introduction

This is a four part tutorial which will take you through step-by-step on how to create Android apps on your Mobile device that will allow you to communicate with your Arduino over Bluetooth. This tutorial is based upon the Windows environment and an Android device like the Samsung Galaxy S2 Phone.
I will take you through setting up your computer and phone, and will move through in stages so that you understand what each part of the bluetooth code is actually doing. Obviously you will need to ensure that you have a Bluetooth Shield on your Arduino to be able to walk through this tutorial with me.
If you are not interested in the step-by-step instructions, you can jump straight to the end (Part 4) which will have the complete Arduino and Android/Processing code that was used in the following video:

The Goal of this project (Video)


Setting up Processing for Android applications:
For the latest and most up to date version, please follow the instructions on this website: http://wiki.processing.org/w/Android

    Step One:
    Download the Android SDK from this website:
    http://developer.android.com/sdk/index.html

    Android SDK Download:
    Make sure to select the "Use and Existing IDE" link, as per the picture below.



    When you select the "Use an Existing IDE" link, it will then show you the appropriate download to use. This is what it should look like.

    Select the "Download the SDK Tools for Windows" link.
    Once you have downloaded the Android SDK, go ahead and install it as per the instructions below.
    These instruction can also be found here.






    Installing the necessary packages in the Android SDK Manager program
    Make the following 3 selections:
    • Tools: Android SDK Platform-tools
    • API 10: SDK Platform
    • Extras: Google USB Driver
    Then select the button on the bottom-right to install your selections.

    Here is a picture of the Android SDK Manager selections:


    While you may decide to download other packages,
    you MUST download API 10: SDK Platform .
    Do not leave this one out !!



    Step Two: Processing Download

    Download the latest Processing IDE(version 2.0 Beta 8) from this website:
    http://processing.org/download/

    I am using Windows 7, and have chosen to download the Windows 32 bit version as shown below.




    Load Processing, and switch to Android mode, as per the image below.




    You should now have an empty sketch window which looks something like this.





    Step Three: Setting up the Android Hardware device (Phone)
    For the latest steps you can have a look at this site:
    http://developer.android.com/tools/device.html

    However, these are the ones that I carried out:

    Turn on USB debugging on your Android Phone:
    To find out what Android Version you are on, have a look at
        Settings > About Phone : look for heading "Android Version".
    • My Android version is 2.3.4 on my Samsung Galaxy S2.
    To Enable USB Debugging:
       
    Settings > Applications > Development > Select (or Enable) USB debugging

      For those of you who have a different Android version, have a look below:





      Downloading the USB driver for your Android Phone(Windows Users)
      If you are developing on Windows and would like to connect an Android-powered device to test your applications, then you need to install the appropriate USB driver. Have a look at this site for more information on how to download the USB driver for your phone:
      http://developer.android.com/tools/extras/oem-usb.html

      I have a Samsung Galaxy S2 phone, so I had to go to the Samsung Site here:
      http://www.samsung.com/us/support/downloads

      But because I am not in the USA, I had to click on the link for "non-US products":
      http://www.samsung.com/us/support/downloads/global

      You will need the model number of your phone:
      On the Samsung Galaxy S2, you can go into
          Settings > About Phone => Model number. Otherwise, it is located behind the battery.
      • My Phone's Model Number is: GT-I9100
      See the image below for the link to press if you have a non-US phone.



      Then I continued with the install of the USB driver as per the document below:
      http://developer.android.com/tools/extras/oem-usb.html







      Step Four: Android-Processing Sketch
      We will now test our our current setup and make sure that we can run a simple Processing Sketch on the Phone. Bluetooth functionality will be tested later on, so all we need for this step, is our computer, our Android phone, and a USB cable. While it is possible to run this sketch without an Android phone (by using the emulator), I personally do not have the patience to wait an eternity while the emulator boots up... (yes, it takes an eternity)... In this tutorial, we are going to test it on the device (phone).
      This sketch has an orange background and a black circle which you can move around the screen with your finger (that's it) - I did say it was going to be a simple sketch.

      Copy and paste the following Android-Processing sketch into the IDE, and then press the (Run on Device) button, which is the triangle button or press Ctrl-R.


      Android/Processing Sketch 1: Circle Dragger

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      /*Circle Dragger: Simple Android-Processing Sketch written by ScottC on 13/03/2013.
      Visit: http://arduinobasics.blogspot.com/
      */

      int circleWidth = 150;
      void setup(){
      orientation(LANDSCAPE);
      }
      void draw(){
      background(255,100,0);
      fill(0);
      ellipse(mouseX,mouseY,circleWidth,circleWidth);
      }


      You should see an orange screen appear on your phone. Move your finger across the screen and watch as the black circle follows your finger.
      No, not rocket science, but hopefully everything worked as planned. If you want to change the colour of the background or circle, this is a good site:
      http://www.colorpicker.com/



      Step Five: Bluetooth testing:
      We are now going to walk through Bluetooth connectivity. While we could just use a library to do all the heavy lifting for us, I decided to explore Bluetooth functionality from scratch. This will hopefully provide greater returns in the long run. Ok, lets create a new Android/Processing Sketch which changes its behaviour depending on whether Bluetooth is enabled or disabled when the sketch is run. We will display a red screen when Bluetooth is switched off, and green when Bluetooth is switched on.

      To enable Bluetooth on my Samsung Galaxy SII phone:
      • Settings >Wireless and Network > Bluetooth Settings > Bluetooth (Turn on Bluetooth) - check the box

      To disable Bluetooth on my Samsung Galaxy SII phone:
      • Settings >Wireless and Network > Bluetooth Settings > Bluetooth - Uncheck the box

      In the processing/android IDE, you need to make sure that you update the AndroidManifest.xml file to grant specific permissions. You can either edit the file manually in the sketch folder, however, it is much easier and safer to do the following. In the processing/android IDE, select:
      •   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 2: BluetoothChecker1
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      /*BluetoothChecker1: Written by ScottC on 17 March 2013
      This will show a red screen if Bluetooth is off,
      and a green screen when Bluetooth is switched on */


      import android.bluetooth.BluetoothAdapter;

      BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
      void setup(){
      orientation(LANDSCAPE);
      }
      void draw(){
      if(bluetooth.isEnabled()){
      background(10,255,30);
      }
      else {
      background(255,10,30);
      }
      }


      When you run the BluetoothChecker1 sketch on the device, you will either see a red screen or a green screen depending on whether you had Bluetooth enabled or disabled at the time. Ok, pretty boring, but it is a start. What if we wanted to ask the USER if they would like to enable Bluetooth at the beginning? We could then change the appearance of the screen depending on their selected answer. Before we add this functionality, I would recommend that you read about the following concepts introduced in the next sketch.
      While it is actually possible to turn bluetooth on without asking for permission, I thought I would retain my manners for the following sketch:

      Android/Processing Sketch 3: BluetoothChecker2
      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
      /*BluetoothChecker2: Written by ScottC on 17 March 2013

      If Bluetooth is already ON when you run this sketch,
      the background will display BLUE.

      If Bluetooth is OFF when you run this sketch but you
      agree to turn it on, the background will display GREEN.

      If Bluetooth is OFF when you run this sketch and then
      choose to keep it off, the background will display RED.

      =======================================================*/


      import android.bluetooth.BluetoothAdapter;
      import android.content.Intent;
      int BACKGND=0; //Set the background to BLUE
      //Get the default Bluetooth adapter
      BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

      /*The startActivityForResult() launches an Activity which is
      used to request the user to turn Bluetooth on.
      The following onActivityResult() method is called when the
      Activity exits. */

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data){
      if(requestCode==0){
      if(resultCode == RESULT_OK){
      BACKGND=2;
      //Set the background to GREEN
      }
      else {
      BACKGND=1;
      //Set the background to RED
      }
      }
      }
      void setup(){
      orientation(LANDSCAPE);

      /*IF Bluetooth is NOT enabled,
      then ask user permission to enable it */

      if (!bluetooth.isEnabled()) {
      Intent requestBluetooth =
      new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(requestBluetooth, 0);
      }
      }
      void draw(){
      if(BACKGND==0){
      background(10,10,255);
      //Set background to BLUE
      }
      else if(BACKGND==1) {
      background(255,10,10);
      //Set background to RED
      }
      else {
      background(10,255,10);
      //Set background to GREEN
      }
      }

      I tried my best to explain the code via the comments within. I hope it made sense.


      Useful Links:

      Android Processing Wiki: http://wiki.processing.org/w/Android

      Here is a good tutorial which helped me put Processing and Android together:
      http://www.creativeapplications.net/android/mobile-app-development-processing-android-tutorial/

      And most importantly:
      The Android Developers site : Bluetooth



      Click here for PART TWO

      Click here for PART THREE

      Click here for PART FOUR

       
       



      If you like this page, please do me a favour and show your appreciation :

       
      Visit my ArduinoBasics Google + page.
      Follow me on Twitter by looking for ScottC @ArduinoBasics.
      Have a look at my videos on my YouTube channel.


       
       

       
       
       


      However, if you do not have a google profile...
      Feel free to share this page with your friends in any way you see fit.

      Cant get my processing sketch to wait for a response from the arduino

      sorry if im getting boring. i promise i will get onto a rock crawler rover thing once i have got some life out of the polargraph...

      read more

      First Robot - Arduino + Processing

      Primary image

      What does it do?

      Remote Controlled Robot, Navigate around via ultrasound

      After some weeks of browsing this website, I felt inspired to built something, so, here is the first robot that I'm currently working on.

      The idea of this project is to have a platform that can be controlled remotely or work autonomously. For the initial fase, I'm working on some basic remote programmed on Processing, which send commands to the robot via bluetooth (using controlP5 for the UI, and bluetoothDesktop to handle bt communication).

      Cost to build

      $100,00

      Embedded video

      Finished project

      Number

      Time to build

      10 hours

      Type

      wheels

      URL to more information

      Weight

      read more