Arduino Basics: Processing
Showing posts with label Processing. Show all posts
Showing posts with label Processing. Show all posts

22 June 2015

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.

24 April 2015

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){                            //Only send data when it first discovers a heart beat - otherwise it will send a high value multiple times
      beat=true;                          //By changing the beat variable to true, it stops further transmissions of the high signal
      digitalWrite(LED, HIGH);            //Turn the LED on 
      Serial.println(1023);               //Send the high value to the computer via Serial communication.
    }
  } else {                                //If the reading is LOW, 
    if(beat){                             //and if this has just changed from HIGH to LOW (first low reading)
      beat=false;                         //change the beat variable to false (to stop multiple transmissions)
      digitalWrite(LED, LOW);             //Turn the LED off.
      Serial.println(0);                  //then send a low value to the computer via Serial communication.
    }
  }
}


 
 
 
 

Processing 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
 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
/* =================================================================================================
       Project: Arduino Heart rate monitor
        Author: Scott C
       Created: 21st April 2015
Processing IDE: 2.2.1
       Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
   Description: A Grove Ear-clip heart rate sensor allows an Arduino UNO to sense your pulse.
                The data obtained by the Arduino can then be sent to the computer via Serial communication
                which is then displayed graphically using this Processing sketch.
                
=================================================================================================== */

import processing.serial.*;                             // Import the serial library to allow Serial communication with the Arduino

int numOfRecs = 45;                                     //   numOfRecs: The number of rectangles to display across the screen
Rectangle[] myRecs = new Rectangle[numOfRecs];          //    myRecs[]: Is the array of Rectangles.  Rectangle is a custom class (programmed within this sketch)

Serial myPort;                                         
String comPortString="0";                              //comPortString: Is used to hold the string received from the Arduino
float arduinoValue = 0;                                 //arduinoValue: Is the float variable converted from comPortString
boolean beat = false;                                   //        beat: Used to control for multiple high/low signals coming from the Arduino

int totalTime = 0;                                      //   totalTime: Is the variable used to identify the total time between beats
int lastTime = 0;                                       //    lastTime: Is the variable used to remember when the last beat took place
int beatCounter = 0;                                    // beatCounter: Is used to keep track of the number of beats (in order to calculate the average BPM)
int totalBeats = 10;                                    //  totalBeats: Tells the computer that we want to calculate the average BPM using 10 beats.
int[] BPM = new int[totalBeats];                        //       BPM[]: Is the Beat Per Minute (BPM) array - to hold 10 BPM calculations
int sumBPM = 0;                                         //      sumBPM: Is used to sum the BPM[] array values, and is then used to calculate the average BPM.
int avgBPM = 0;                                         //      avgBPM: Is the variable used to hold the average BPM calculated value.

PFont f, f2;                                            //     f & f2 : Are font related variables. Used to store font properties. 


//==SETUP==============================================================================================
void setup(){
  size(displayWidth,displayHeight);                     // Set the size of the display to match the monitor width and height
  smooth();                                             // Draw all shapes with smooth edges.
  f = createFont("Arial",24);                           // Initialise the "f" font variable    - used for the "calibrating" text displayed at the beginning
  f2 = createFont("Arial",96);                          // Initialise the "f2" font variable   - used for the avgBPM display on screen
  
  for(int i=0; i<numOfRecs; i++){                       // Initialise the array of rectangles
    myRecs[i] = new Rectangle(i, numOfRecs);
  }
  
  for(int i=0; i<totalBeats; i++){                      // Initialise the BPM array
    BPM[i] = 0;
  }
  
  myPort = new Serial(this, Serial.list()[0], 9600);    // Start Serial communication with the Arduino using a baud rate of 9600
  myPort.bufferUntil('\n');                             // Trigger a SerialEvent on new line
}


//==DRAW==============================================================================================
void draw(){
  background(0);                                        // Set the background to BLACK (this clears the screen each time)
  drawRecs();                                           // Method call to draw the rectangles on the screen
  drawBPM();                                            // Method call to draw the avgBPM value to the top right of the screen
}


//==drawRecs==========================================================================================
void drawRecs(){                                        // This custom method will draw the rectangles on the screen                                
  myRecs[0].setSize(arduinoValue);                      // Set the first rectangle to match arduinoValue; any positive value will start the animation.
  for(int i=numOfRecs-1; i>0; i--){                     // The loop counts backwards for coding efficiency - and is used to draw all of the rectangles to screen
    myRecs[i].setMult(i);                               // setMulti creates the specific curve pattern. 
    myRecs[i].setRed(avgBPM);                           // The rectangles become more "Red" with higher avgBPM values
    myRecs[i].setSize(myRecs[i-1].getH());              // The current rectangle size is determined by the height of the rectangle immediately to it's left
    fill(myRecs[i].getR(),myRecs[i].getG(), myRecs[i].getB());                     // Set the colour of this rectangle
    rect(myRecs[i].getX(), myRecs[i].getY(), myRecs[i].getW(), myRecs[i].getH());  // Draw this rectangle
  }
}


//==drawBPM===========================================================================================
void drawBPM(){                                         // This custom method is used to calculate the avgBPM and draw it to screen.
  sumBPM = 0;                                           // Reset the sumBPM variable
  avgBPM = 0;                                           // Reset the avgBPM variable
  boolean calibrating = false;                          // calibrating: this boolean variable is used to control when the avgBPM is displayed to screen
  
  for(int i=1; i<totalBeats; i++){
    sumBPM = sumBPM + BPM[i-1];                         // Sum all of the BPM values in the BPM array.
    if(BPM[i-1]<1){                                     // If any BPM values are equal to 0, then set the calibrating variable to true. 
      calibrating = true;                               // This will be used later to display "calibrating" on the screen.
    }
  }
  avgBPM = sumBPM/(totalBeats-1);                       // Calculate the average BPM from all BPM values
                                                        
  fill(255);                                            // The text will be displayed as WHITE text
  if(calibrating){
    textFont(f);
    text("Calibrating", (4*width)/5, (height/5));      // If the calibrating variable is TRUE, then display the word "Calibrating" on screen
    fill(0);                                           // Change the fill and stroke to black (0) so that other text is "hidden" while calibrating variable is TRUE
    stroke(0);
  } else {
    textFont(f2);
    text(avgBPM, (4*width)/5, (height/5));             // If the calibrating variable is FALSE, then display the avgBPM variable on screen
    stroke(255);                                       // Change the stroke to white (255) to show the white line underlying the word BPM.
  }
  
   textFont(f);
   text("BPM", (82*width)/100, (height/11));           // This will display the underlined word "BPM" when calibrating variable is FALSE.
   line((80*width)/100, (height/10),(88*width)/100, (height/10));
   stroke(0);
}


//==serialEvent===========================================================================================
void serialEvent(Serial cPort){                        // This will be triggered every time a "new line" of data is received from the Arduino
 comPortString = cPort.readStringUntil('\n');          // Read this data into the comPortString variable.
 if(comPortString != null) {                           // If the comPortString variable is not NULL then
   comPortString=trim(comPortString);                  // trim any white space around the text.
   int i = int(map(Integer.parseInt(comPortString),1,1023,1,height));  // convert the string to an integer, and map the value so that the rectangle will fit within the screen.
   arduinoValue = float(i);                            // Convert the integer into a float value.
   if (!beat){
     if(arduinoValue>0){                               // When a beat is detected, the "trigger" method is called.
       trigger(millis());                              // millis() creates a timeStamp of when the beat occured.
       beat=true;                                      // The beat variable is changed to TRUE to register that a beat has been detected.
     }
   }
   if (arduinoValue<1){                                // When the Arduino value returns back to zero, we will need to change the beat status to FALSE.
     beat = false;
   }
 }
} 


//==trigger===========================================================================================
void trigger(int time){                                // This method is used to calculate the Beats per Minute (BPM) and to store the last 10 BPMs into the BPM[] array.
  totalTime = time - lastTime;                         // totalTime = the current beat time minus the last time there was a beat.
  lastTime = time;                                     // Set the lastTime variable to the current "time" for the next round of calculations.
  BPM[beatCounter] = 60000/totalTime;                  // Calculate BPM from the totalTime. 60000 = 1 minute.
  beatCounter++;                                       // Increment the beatCounter 
  if (beatCounter>totalBeats-1){                       // Reset the beatCounter when the total number of BPMs have been stored into the BPM[] array.
    beatCounter=0;                                     // This allows us to keep the last 10 BPM calculations at all times.
  }
}


//==sketchFullScreen==========================================================================================
boolean sketchFullScreen() {                           // This puts Processing into Full Screen Mode
 return true;
}


//==Rectangle CLASS==================================================================================*********
class Rectangle{
  float xPos, defaultY, yPos, myWidth, myHeight, myMultiplier;    // Variables used for drawing rectangles
  int blueVal, greenVal, redVal;                                  // Variables used for the rectangle colour
  
  Rectangle(int recNum, int nRecs){                               // The rectangles are constructed using two variables. The total number of rectangles to be displayed, and the identification of this rectangle (recNum)
    myWidth = displayWidth/nRecs;                                 // The width of the rectangle is determined by the screen width and the total number of rectangles.
    xPos = recNum * myWidth;                                      // The x Position of this rectangle is determined by the width of the rectangles (all same) and the rectangle identifier.
    defaultY=displayHeight/2;                                     // The default Y position of the rectangle is half way down the screen.
    yPos = defaultY;                                              // yPos is used to adjust the position of the rectangle as the size changes.
    myHeight = 1;                                                 // The height of the rectangle starts at 1 pixel
    myMultiplier = 1;                                             // The myMultiplier variable will be used to create the funnel shaped path for the rectangles.
    redVal = 0;                                                   // The red Value starts off being 0 - but changes with avgBPM. Higher avgBPM means higher redVal
    
    if (recNum>0){                                                // The blue Value progressively increases with every rectangle (moving to the right of the screen)
      blueVal = (recNum*255)/nRecs;
    } else {
      blueVal = 0;
    }
    greenVal = 255-blueVal;                                       // Initially, the green value is at the opposite end of the spectrum to the blue value.
  }
  
  void setSize(float newSize){                                    // This is used to set the new size of each rectangle 
    myHeight=newSize*myMultiplier;
    yPos=defaultY-(newSize/2);
  }
  
  void setMult(int i){                                            // The multiplier is a function of COS, which means that it varies from 1 to 0.
    myMultiplier = cos(radians(i));                               // You can try other functions to experience different effects.
  }
  
  void setRed(int r){
    redVal = int(constrain(map(float(r), 60, 100, 0, 255),0,255)); // setRed is used to change the redValue based on the "normal" value for resting BPM (60-100). 
    greenVal = 255 - redVal;                                       // When the avgBPM > 100, redVal will equal 255, and the greenVal will equal 0.
  }                                                                // When the avgBPM < 60, redVal will equal 0, and greenVal will equal 255.
  
  float  getX(){                                                   // get the x Position of the rectangle
    return xPos;
  }
 
  float getY(){                                                    // get the y Position of the rectangle
    return yPos;
  }
  
  float getW(){                                                    // get the width of the rectangle
    return myWidth;
  }
  
  float getH(){                                                    // get the height of the rectangle
    return myHeight;
  }
  
  float getM(){                                                    // get the Multiplier of the rectangle
    return myMultiplier;
  }
  
  int getB(){                                                      // get the "blue" component of the rectangle colour
    return blueVal;
  }
  
  int getR(){                                                      // get the "red" component of the rectangle colour
    return redVal;
  }
  
  int getG(){                                                      // get the "green" component of the rectangle colour
    return greenVal;
  }
}


 

Processing Code Discussion:


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.

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...


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).
 
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.

 



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.

8 April 2013

Serial Communication Tutorial (Part 3)





In the previous two parts of the this tutorial, we went through a number of simple sketches to get you acquainted with the way that the Arduino handles various data types when passed through the Serial COM port. Here are the main themes from part ONE:
  • Stage One:  Echoing data with the Arduino
  • Stage Two: Using Delimiters to split data.
  • Stage Three: Arduino Maths, simple addition
  • Stage Four: Sending a double to an Arduino, and then doubling it.
  • Stage Five: Sending Sensor data from the Arduino to the Serial Monitor
Here are the main themes from Part TWO:

  • Stage Six: ......A simple Processing Sketch
  • Stage Seven:  Arduino and Processing join forces for more fun
  • Stage Eight: A simple project that shows Serial communication from Arduino to Processing
In Part Three - we will reverse the direction of communication and get Processing to send data to the Arduino via a USB cable,

  • Stage Nine: A simple processing sketch that switches an LED on the Arduino
  • Stage Ten:  A processing sketch that reads from a text file
  • Stage Eleven: A processing sketch that reads data from a text file and sends to the Arduino
  • Stage Twelve: A processing sketch that trasmits data from a file to another Arduino via an XBee module.


Stage Nine - Using your computer to switch an LED

In this stage we create a simple Arduino sketch which will receive a simple command from the Processing Sketch to switch an LED. The Processing sketch will allow you to turn an LED on/off by clicking on the Processing Application window. It will detect the press of the mouse, and will send a command to the Arduino via the USB Serial COM port.

Parts Required:
  • Arduino UNO or compatible board
  • USB cable
  • Arduino and Processing IDE (on computer)
Arduino Logo The 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
/* ===================================================
Simple number reader: Written by ScottC - 07 Apr 2013
 Arduino Version: 1.04
======================================================*/

// The onboard LED is on pin # 13
int onboardLED = 13;


void setup() {
 // Begin Serial communication
 Serial.begin(9600);
 
 //Set the onboard LED to OUTPUT
 pinMode(onboardLED, OUTPUT);
}

void loop(){
 /* Read serial port, if the number is 0, then turn off LED
 if the number is 1 or greater, turn the LED on. */
 while (Serial.available() > 0) {
 int num=Serial.read()-'0';
 if(num<1){
 digitalWrite(onboardLED, LOW); //Turn Off LED
 } else{ 
 digitalWrite(onboardLED, HIGH); //Turn On LED
 } 
 }
}


Processing icon The Processing 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
/*===========================================================
 Toggle Switch: Send Number to Arduino
 Written by Scott C on 07 Apr 2013
 Processing Version: 2.0b8
=============================================================*/

import processing.serial.*;

Serial comPort;
boolean ledState=false; //LED is off

void setup(){
 //Open COM Port for Communication
 comPort = new Serial(this, Serial.list()[0], 9600);
 background(255,0,0); //Start with a Red background
}

void draw(){
}


void mousePressed() {
 //Toggle led ON and OFF
 ledState=!ledState;
 
 //If ledState is True - then send a value=1 (ON) to Arduino
 if(ledState){
 background(0,255,0); //Change the background to green
 
 /*When the background is green, transmit
 a value=1 to the Arduino to turn ON LED */
 comPort.write('1');
 }else{
 background(255,0,0); //Change background to red
 comPort.write('0'); //Send "0" to turn OFF LED.
 }
}




The Video


Stage Ten: Reading from a Text File

We are now going to give the Arduino a rest (for a moment) and concentrate on a Processing Sketch that will read from a text file. Once we learn this skill, we can then build this Processing functionality into our Arduino Projects. Reading from a text file in Processing is actually quite easy if you use the loadStrings() method. However, it is best if you make things easy for yourself by using delimiters. The most common delimitter is a "comma". The comma allows the computer to group information according to your needs.
  • 11,22,33,44,55,66
  • 1,1,2,2,3,3,4,4,5,5,6,6
  • 112,223,334,455,566
The examples above contain the same numbers but are delimitted in different ways.
We are going to import a few different numbers/letters and store them in an array. We will then iterate through the array to display the values within.
So let us now create the text file. Copy and paste the following text into notepad and save the file, but remember where you save it, because we will need to know location and the name of the file in order to read from in.

NotepadIconCopy and Paste into Notepad:
100,200,A,B,C,10.2,0.1,wx,yz,arduinobasics
 
 
 
 

Save the file
I am going to call my file data.txt, and will be saving it to my D drive, so the file will be located here:
  • D:/data.txt

We will now create the processing sketch to read the text file and display the data on the screen.
We will use the comma delimiters to separate the data so that it displays in the following way:




Processing icon The Processing 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
/* =============================================================
 ReadTextFile and Display on Screen:
 Written by ScottC on 15th April 2013 using 
 Processing version 2.0b8
 
 Website: http://arduinobasics.blogspot.com/
 Projects: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
 
 References:
 Displaying Text: http://processing.org/reference/text_.html
 Reading Text File: http://processing.org/reference/loadStrings_.html
=================================================================*/

void setup(){
 size(180,250);
 background(255);
 
 /* Read the text file */
 String[] lines = loadStrings("D:/data.txt");
 int numOfLines=lines.length;
 for(int i=0;i<numOfLines;i++){
 
 /* Split the data based on a "," delimiter. */
 String[] data = splitTokens(lines[i], ",");
 int dataCount = data.length;
 
 for(int j=0; j<dataCount; j++){
 /* Set the size and colour of the text */
 textSize(16);
 fill(100,100,255,50+(j*20));
 
 /* Display the text on the screen */
 text(data[j],10,16+(16*j));
 }
 }
}


void draw(){
}

The code above has the ability to display data from multiple lines within the text file, however for simplicity, I have chosen to use a single line. If I wanted to display more than one line, I would have to change the "for-loops".



Stage Eleven: Read Text File and send to Arduino

In stage 10 we used the Processing  programming language to import a line of data from a text file, break-up the line into pieces (based on comma delimiters) and then displayed the data on the Computer Screen. We will now use this knowledge and take it one step further. We will create a text file, import the data using processing, but this time we will send the data to the Arduino. Meanwhile the Arduino will be waiting patiently for this data, and once it receives the data, it will react according to our needs. We are going to keep this simple. The goal is to send two different letters from the Computer to the Arduino. One letter will turn an LED on, and the other letter will turn the LED off. We will also send an integer to tell the Arduino how long to keep the LED on or off.

GOAL:  Turn an LED on and off by reading a text file.
Our first step in this process is to create a text file that will store our important data. We will store two variables in this file. The first variable will be used to tell the Arduino whether we want to turn the LED on or whether we want to turn the LED off. We will use the letter "O" to turn the LED on, and use the letter "X" to turn the LED off.
The second variable will be a time based variable. It will be used to tell the Arduino "how long" to keep the LED on or off. We will store this variable as an integer and will represent time in "milliseconds".
  • 1000 milliseconds = 1 second
It makes sense to keep these two variables as a pair, however we will separate them using a comma delimitter. We will separate each command by putting the variables on a new line. Copy and paste the following data into notepad (or equivalent text editor), and save the file to your harddrive. I have saved this file as

  • D:/LEDdata.txt

NotepadIcon Text File Data: Here is the data to put into your text file (notepad):
X,50
O,45
X,40
O,35
X,30
O,25
X,20
O,15
X,10
O,5
X,10
O,15
X,20
O,25
X,30
O,35
X,40
O,45
X,50
O,55
X,60
O,65
X,70
O,75
X,80
O,85
X,90
O,95
X,100
O,200
X,200
O,200
X,500
O,500
X,500
O,500
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,200
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,200
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,200
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20



We will now set up the Arduino to accept data from the Computer and react to the Letters
  • "O" to turn the LED on
  • "X" to turn the LED off
  • "E" will be used to test for a successful Serial connection.
We will also get the Arduino to interpret the second variable which will be used to set the amount of time to keep the LED on or off.


Arduino LogoArduino Code:
 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
/* Read TextFile Data: Written by ScottC on 24 April 2013
 Arduino IDE version: 1.0.4
 http://arduinobasics.blogspot.com.au/2013/04/serial-communication-tutorial-part-3.html
*/

/* Global Variables */
byte byteRead; //Used to receive data from computer.
int timeDelay; //time that the LED is On or Off
int maxtimeDelay=10000; //Maximum time delay = 10 seconds
int ledPin=13; //LED connected to pin 13 on Arduino UNO.

void setup() { 
//Set pin 13 (ledPin) as an output 
 pinMode(ledPin, OUTPUT); 
// Turn the Serial Protocol ON
 Serial.begin(9600);
}

void loop() {
 /* check if data has been sent from the computer: */
 if (Serial.available()) {
 /* read the most recent byte */
 byteRead = Serial.read();
 
 switch (byteRead) {
 case 69: //This is an enquiry, send an acknowledgement
 Serial.println("A");
 break;
 case 79: //This is an "O" to turn the LED on
 digitalWrite(ledPin, HIGH);
 break;
 case 88: //This is an "X" to turn the LED off
 digitalWrite(ledPin, LOW);
 break;
 case 46: //End of line
 //Make sure time delay does not exceed maximum.
 if(timeDelay > maxtimeDelay){ 
 timeDelay=maxtimeDelay;
 }
 //Set the time for LED to be ON or OFF
 delay(timeDelay);
 Serial.println("S");
 timeDelay=0; //Reset timeDelay;
 break;
 default: 
 //listen for numbers between 0-9
 if(byteRead>47 && byteRead<58){
 //number found, use this to construct the time delay.
 timeDelay=(timeDelay*10)+(byteRead-48);
 }
 } 
 }
}

Our next step is to import the data in the text file into Processing and then send the data to the Arduino. You may want to review Stage 10 of this tutorial for another example of importing text file data into Processing. You may also want to review stage 7 which shows how to receive data from an Arduino.
We will import all of the data from the file when we push a button on the Processing Window, and send this data to the Arduino via the USB cable that is connected to the computer. We are going to use the same COM port that the Computer uses to upload Arduino Sketches, therefore it is important that you close the Arduino Serial Monitor before you run the processing sketch, otherwise you will get an error which states that the COM port is not available.


Processing icon Processing Code:
 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
/* TextFile Data sender (Stage 11) 
 Written by ScottC on 24th April 2013
 using Processing Version 2.0b8 
 
 The full tutorial can be found here:
 http://arduinobasics.blogspot.com/2013/04/serial-communication-tutorial-part-3.html
*/

import processing.serial.*;

Serial comPort; //The com port used between the computer and Arduino
int counter=0; // Helps to keep track of values sent.
int numItems=0; //Keep track of the number of values in text file
String comPortString; //String received From Arduino
String textFileLines[]; //Array of text file lines
String lineItems[]; //Array of line items

void setup(){
 comPort = new Serial(this, Serial.list()[0], 9600); //Setup the COM port 
 comPort.bufferUntil('\n'); //Generate a SerialEvent when a newline is received
 background(255,0,0); //Start with a Red background
}

/* Draw method is not used in this sketch */
void draw(){
}

//When the mouse is pressed, write an "E" to COM port. 
//The Arduino should send back an "A" in return. This will 
//generate a serialEvent - see below.
void mousePressed() {
 comPort.write("E"); 
}

void serialEvent(Serial cPort){
 comPortString = cPort.readStringUntil('\n');
 if(comPortString != null) {
 comPortString=trim(comPortString);
 
 /*If the String received = A, then import the text file
 change the background to Green, and start by sending the
 first line of the text file to the Arduino */
 if(comPortString.equals("A")){
 textFileLines=loadStrings("D:/LEDdata.txt");
 background(0,255,0);
 sendLineNum(counter);
 }
 
 /*If the the String received = S, then increment the counter
 which will allow us to send the next line in the text file.
 If we have reached the end of the file, then reset the counter
 and change the background colour back to red. */
 if(comPortString.equals("S")){
 counter++;
 if(counter > (textFileLines.length-1)){
 background(255,0,0);
 counter=0;
 } else { 
 sendLineNum(counter);
 }
 }
 }
}


/*The sendLineNum method is used to send a specific line
 from the imported text file to the Arduino. The first
 line item tells the Arduino to either switch the LED on or off.
 The second line item, tells the Arduino how long to keep the
 LED on or off. The full-stop is sent to the Arduino to indicate
 the end of the line. */
 
void sendLineNum(int lineNumber){
 lineItems=splitTokens(textFileLines[lineNumber],",");
 comPort.write(lineItems[0]);
 comPort.write(lineItems[1]);
 comPort.write(".");
}


Stage Twelve: To be continued..


I need to finish my XBee tutorial before doing this stage. But am just about to start studying again. So this stage probably won't get completed for another couple of months. But I hope there is enough content to keep you satisfied for the time being.

2 April 2013

Bluetooth Android Processing 4

PART FOUR

The Video





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

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

This is what you'll find in 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

This is what you will find in part three:

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



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

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


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



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

Android/Processing Sketch 9: Bluetooth App2

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


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

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

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

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


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



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


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




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



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




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



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

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



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


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


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



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



Jumpers on Shield


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

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

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

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

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

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

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

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

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

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

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


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

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