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

9 November 2018

Digital Rain Cloud

 
 

Description

This is a very simple project that turns a Rainbow Cube Kit from Seeedstudio, into a digital rain cloud. It features a relaxing rain animation which is ruined by a not-so-relaxing yet somewhat realistic lightning effect. The animation has a very random pattern, and is quite satisfying to watch. The strategically placed cotton wool on the top of the cube makes all the difference to the project, and is sure to impress all of your friends. Luckily, I have done all of the hard work for you. You will find the full source code for the animation sequence below. You just have to provide the Rainbow Cube Kit and the cotton wool. Have fun !!

 
 

10 April 2015

Arduino BeatBox

Create your very own Arduino BeatBox !

Home-made capacitive touch sensors are used to trigger the MP3 drum sounds stored on the Grove Serial MP3 player. I have used a number of tricks to get the most out of this module, and I was quite impressed on how well it did. Over 130 sounds were loaded onto the SDHC card. Most were drum sounds, but I added some farm animal noises to provide an extra element of surprise and entertainment. You can put any sounds you want on the module and play them back quickly. We'll put the Grove Serial MP3 module through it's paces and make it into a neat little BeatBox !!


Key learning objectives

  • How to make your own beatbox
  • How to make capacitive drum pad sensors without using resistors
  • How to speed up Arduino's Analog readings for better performance
  • How to generate random numbers on your Arduino


Parts Required:

Making the drum pads



 
 

Fritzing Sketch


 


 
 

Grove Connections


 


 
 

Grove Connections (without base shield)


 


 
 

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
 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
    
/* =================================================================================================
      Project: Arduino Beatbox
       Author: Scott C
      Created: 9th April 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This project uses home made capacitive sensors to trigger over 130 MP3 sounds
               on the Grove Serial MP3 player. 
               
               The ADCTouch library is used to eliminate the resistors from the Capacitive sensing circuit. 
               The code used for capacitive sensing was adapted from the ADCTouch library example sketches. 
               You can find the ADCTouch library and relevant example code here:
               http://playground.arduino.cc/Code/ADCTouch
               
               "Advanced Arduino ADC" is used to improve the analogRead() speed, and enhance the
               drum pad or capacitive sensor response time. The Advanced Arduino ADC code 
               was adapted from this site:
               http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/
               
               
=================================================================================================== */
  #include <ADCTouch.h>
  #include <SoftwareSerial.h>
  
  
  //Global variables
  //===================================================================================================
  int potPin = A4;                           //Grove Sliding potentiometer is connected to Analog Pin 4
  int potVal = 0;
  byte mp3Vol = 0;                           //Variable used to control the volume of the MP3 player
  byte oldVol = 0;
  
  int buttonPin = 5;                         //Grove Button is connected to Digital Pin 5
  int buttonStatus = 0;
  
  byte SongNum[4] = {0x01,0x02,0x03,0x04};  //The first 4 songs will be assigned to the drum pads upon initialisation
  byte numOfSongs = 130;                    //Total number of MP3 songs/sounds loaded onto the SDHC card
  
  long randNumber;                          //Variable used to hold the random number - used to randomise the sounds.
  
  int ledState[4];                          //Used to keep track of the status of all LEDs (on or off)
  int counter = 0;
  
  SoftwareSerial mp3(3, 4);                 // The Grove MP3 Player is connected to Arduino digital Pin 3 and 4 (Serial communication)
       
  int ref0, ref1, ref2, ref3;               //reference values to remove offset
  int threshold = 100;
      
  // Define the ADC prescalers
  const unsigned char PS_64 = (1 << ADPS2) | (1 << ADPS1);
  const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
  
  
  
  //Setup()
  //===================================================================================================
  void setup(){
    //Initialise the Grove MP3 Module
    delay(2500);                              //Allow the MP3 module to power up        
    mp3.begin(9600);                          //Begin Serial communication with the MP3 module
    setPlayMode(0x00);                        //0x00 = Single song - played once ie. not repeated.  (default)
    
    //Define the Grove Button as an INPUT
    pinMode(buttonPin, INPUT);
    
    //Define the 4 LED Pins as OUTPUTs
    pinMode(8, OUTPUT);                       //Green LED
    pinMode(9, OUTPUT);                       //Blue LED
    pinMode(10, OUTPUT);                      //Red LED
    pinMode(11, OUTPUT);                      //Yellow LED
    
    //Make sure each LED is OFF, and store the state of the LED into a variable.
    for(int i=8;i<12;i++){
      digitalWrite(i, LOW);
      ledState[i-8]=0;
    } 
    
    //Double our clock speed from 125 kHz to 250 kHz
    ADCSRA &= ~PS_128;   // set up the ADC
    ADCSRA |= PS_64;    // set our own prescaler to 64 
    
    //Create reference values to account for the capacitance of each pad.
    ref0 = ADCTouch.read(A0, 500);
    ref1 = ADCTouch.read(A1, 500);      //Take 500 readings
    ref2 = ADCTouch.read(A2, 500);
    ref3 = ADCTouch.read(A3, 500);
    
     //This helps to randomise the drum pads.
     randomSeed(analogRead(0));
  }
  
  
  
  // Loop()
  //===================================================================================================     
  void loop(){
     
    //Take a reading from the Grove Sliding Potentiometer, and set volume accordingly
    potVal = analogRead(potPin);
    mp3Vol = map(potVal, 0, 1023, 0,31);              // Convert the potentometer reading (0 - 1023) to fit within the MP3 player's Volume range (0 - 31)
    if((mp3Vol>(oldVol+1))|(mp3Vol<(oldVol-1))){      // Only make a change to the Volume on the Grove MP3 player when the potentiometer value changes
      oldVol = mp3Vol;
      setVolume(mp3Vol);
      delay(10);                                      // This delay is necessary with Serial communication to MP3 player
    }
    
    //Take a reading from the Pin attached to the Grove Button. If pressed, randomise the MP3 songs/sounds for each drum pad, and make the LEDs blink randomly.
    buttonStatus = digitalRead(buttonPin);
    if(buttonStatus==HIGH){
      SongNum[0]=randomSongChooser(1, 30);
      SongNum[1]=randomSongChooser(31, 60);
      SongNum[2]=randomSongChooser(61, 86);
      SongNum[3]=randomSongChooser(87, (int)numOfSongs);
      randomLEDBlink();
    }
    
    //Get the capacitive readings from each drum pad: 50 readings are taken from each pad. (default is 100) 
    int value0 = ADCTouch.read(A0,50);        //  Green drum pad
    int value1 = ADCTouch.read(A1,50);        //   Blue drum pad
    int value2 = ADCTouch.read(A2,50);        //    Red drum pad
    int value3 = ADCTouch.read(A3,50);        // Yellow drum pad
    
    //Remove the offset to account for the baseline capacitance of each pad.
    value0 -= ref0;       
    value1 -= ref1;
    value2 -= ref2;
    value3 -= ref3;
    
    
    //If any of the values exceed the designated threshold, then play the song/sound associated with that drum pad.
    //The associated LED will stay on for the whole time the drum pad is pressed, providing the value remains above the threshold. 
    //The LED will turn off when the pad is not being touched or pressed.
    if(value0>threshold){
      digitalWrite(8, HIGH);
      playSong(00,SongNum[0]);
    }else{
      digitalWrite(8,LOW);
    }
    
    if(value1>threshold){
      digitalWrite(9, HIGH);
      playSong(00,SongNum[1]);
    }else{
      digitalWrite(9,LOW);
    }
    
    if(value2>threshold){
      digitalWrite(10, HIGH);
      playSong(00,SongNum[2]);
    }else{
      digitalWrite(10,LOW);
    }
    
    if(value3>threshold){
      digitalWrite(11, HIGH);
      playSong(00,SongNum[3]);
    }else{
      digitalWrite(11,LOW);
    }
  }
      
   
  // writeToMP3: 
  // a generic function that simplifies each of the methods used to control the Grove MP3 Player
  //===================================================================================================
  void writeToMP3(byte MsgLEN, byte A, byte B, byte C, byte D, byte E, byte F){
    byte codeMsg[] = {MsgLEN, A,B,C,D,E,F};
    mp3.write(0x7E);                        //Start Code for every command = 0x7E
    for(byte i = 0; i<MsgLEN+1; i++){
      mp3.write(codeMsg[i]);                //Send the rest of the command to the GROVE MP3 player
    }
  }
  
  
  //setPlayMode: defines how each song is to be played
  //===================================================================================================
  void setPlayMode(byte playMode){
    /* playMode options:
          0x00 = Single song - played only once ie. not repeated.  (default)
          0x01 = Single song - cycled ie. repeats over and over.
          0x02 = All songs - cycled 
          0x03 = play songs randomly                                           */
    writeToMP3(0x03, 0xA9, playMode, 0x7E, 0x00, 0x00, 0x00);  
  }
  
  
  //playSong: tells the Grove MP3 player to play the song/sound, and also which song/sound to play
  //===================================================================================================
  void playSong(byte songHbyte, byte songLbyte){
    writeToMP3(0x04, 0xA0, songHbyte, songLbyte, 0x7E, 0x00, 0x00);            
    delay(100);
  }
  
  
  //setVolume: changes the Grove MP3 player's volume to the designated level (0 to 31)
  //===================================================================================================
  void setVolume(byte Volume){
    byte tempVol = constrain(Volume, 0, 31);             //Volume range = 00 (muted) to 31 (max volume)
    writeToMP3(0x03, 0xA7, tempVol, 0x7E, 0x00, 0x00, 0x00); 
  }
  
  
  //randomSongChooser: chooses a random song to play. The range of songs to choose from
  //is limited and defined by the startSong and endSong parameters.
  //===================================================================================================
  byte randomSongChooser(int startSong, int endSong){
    randNumber = random(startSong, endSong);
    return((byte) randNumber);
  }
  
  
  //randomLEDBlink: makes each LED blink randomly. The LEDs are attached to digital pins 8 to 12.
  //===================================================================================================
  void randomLEDBlink(){
   counter=8;
   for(int i=0; i<40; i++){
     int x = constrain((int)random(8,12),8,12);
     toggleLED(x);
     delay(random(50,100-i));
   }
     
    for(int i=8;i<12;i++){
      digitalWrite(i, HIGH);
    }
    delay(1000);
    for(int i=8;i<12;i++){
      digitalWrite(i, LOW);
      ledState[i-8]=0;
    }
  }
  
  
  //toggleLED: is used by the randomLEDBlink method to turn each LED on and off (randomly).
  //===================================================================================================
  void toggleLED(int pinNum){
    ledState[pinNum-8]= !ledState[pinNum-8];
    digitalWrite(pinNum, ledState[pinNum-8]);
  }
    


 

Arduino Code Discussion

You can see from the Arduino code above, that it uses the ADCTouch library. This library was chosen over the Capacitive Sensing Library to eliminate the need for a high value resistor which are commonly found in Capacitive Sensing projects).
 
To increase the speed of the Analog readings, I utilised one of the "Advanced Arduino ADC" techniques described by Guy van den Berg on this Microsmart website.
 
The readings are increased by modifying the Arduino's ADC clock speed from 125kHz to 250 kHz. I did notice an overall better response time with this modification. However, the Grove Serial MP3 player is limited by it's inability to play more than one song or sound at a time. This means that if you hit another drum pad while the current sound is playing, it will stop playing the current sound, and then play the selected sound. The speed at which it can perform this task was quite impressive. In fact it was much better than I thought it would be. But if you are looking for polyphonic playability, you will be dissapointed.
 
This Serial MP3 module makes use of a high quality MP3 audio chip known as the "WT5001". Therefore, you should be able to get some additional features and functionality from this document. Plus you may find some extra useful info from the Seeedstudio wiki. I have re-used some code from the Arduino Boombox tutorial... you will find extra Grove Serial MP3 functions on that page.
 
I will warn you... the Grove Serial MP3 player can play WAV files, however for some reason it would not play many of the sound files in this format. Once the sounds were converted to the MP3 format, I did not look back. So if you decide to take on this project, make sure your sound files are in MP3 format, you'll have a much better outcome.
 
I decided to introduce a random sound selection for each drum pad to extend the novelty of this instrument, which meant that I had to come up with a fancy way to illuminate the LEDs. I demonstrated some of my other LED sequences on my instagram account. I sometimes use instagram to show my work in progress.
 
Have a look at the video below to see this project in action, and putting the Grove Serial MP3 player through it's paces.
 

The Video


 


First there was the Arduino Boombox, and now we have the Arduino Beatbox..... who knows what will come next !
 
Whenever I create a new project, I like to improve my Arduino knowledge. Sometimes it takes me into some rather complicated topics. There is a lot I do not know about Arduino, but I am enjoying the journey. I hope you are too !! Please Google plus one this post if it helped you in any way. These tutorials are free, which means I survive on feedback and plus ones... all you have to do is just scroll a little bit more and click that button :)

 
 



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.

19 March 2015

Arduino Boombox

Add sound or music to your project using the "Grove Serial MP3 Player".

An Arduino UNO will be used to control the Grove Serial MP3 player by sending it specific serial commands. The Grove Base Shield allows for the easy connection of Grove sensor modules to an Arduino UNO without the need for a breadboard. A sliding potentiometer, switch and button will be connected to the Base shield along with the Serial MP3 player. A specific function will be assigned to each of the connected sensor modules to provide a useful interface:

  • Sliding Potentiometer – Volume control
  • Button – Next Song
  • Switch – On/Off (toggle)
Once the MP3 module is working the way we want, we can then build a simple enclosure for it.
Grab a shoe-box, print out your favourite design, and make your very own Arduino BOOMBOX!


 

Video

Watch the following video to see the project in action
 


 
 

Parts Required:

Optional components (for the BoomBox Enclosure):
  • Empty Shoe Box
  • Paper
  • Printer
  • Glue
If I had a 3D printer - I would have printed my own enclosure, but a shoebox seems to work just fine.


 

Putting it Together

Place the Grove Base shield onto the Arduino UNO,
and then connect each of the Grove Modules as per the table below.
 


 

If you do not have a Grove Base shield,
you can still connect the modules directly to the Arduino as per the table below:
 


 

When you are finished connecting the modules, it should look something like this:
  (ignore the battery pack):
 

As you can see from the picture above. You can cut holes out of the shoebox and stick the modules in place. Please ignore the battery pack, because you won't use it until after you have uploaded the Arduino code.


 
 

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
 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
    
    
/* ===============================================================================
      Project: Grove Serial MP3 Player overview
       Author: Scott C
      Created: 9th March 2015
  Arduino IDE: 1.6.0
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html

  Description: The following Arduino sketch will allow you to control a Grove Serial MP3 player
               with a Grove Sliding Potentiometer (volume), a Grove button (next song), 
               and a Grove Switch (on/off). It will also show you how to retrieve some useful information from the player. 
               Some functions are not used in this sketch,but have been included for your benefit. 
               
               Additional features and functionality can be found on the WT5001 voice chip datasheet 
               which I retrieved from here: http://goo.gl/ai6oQ9
               
               The Seeedstudio wiki was a very useful resource for getting started with the various Grove modules:
               http://goo.gl/xOiSCl
=============================================================================== */

#include <SoftwareSerial.h>
SoftwareSerial mp3(2, 3);      // The Grove MP3 Player is connected to Arduino digital Pin 2 and 3 (Serial communication)
int potPin = A0;               // The Sliding Potentiometer is connected to AnalogPin 0
int potVal = 0;                // This is used to hold the value of the Sliding Potentiometer
byte mp3Vol = 0;               // mp3Vol is used to calculate the Current volume of the Grove MP3 player
byte oldVol = 0;               // oldVol is used to remember the previous volume level
int ledPin = A1;               // The Grove sliding potentiometer has an onboard LED attached to Analog pin 1.

int switchPin = 12;             // The Grove Switch(P) is connected to digital Pin 12
int switchStatus = 0;           // This is used to hold the status of the switch 
int switchChangeStatus = 0;     // Used to identify when the switch status has changed

int buttonPin = 5;              // The Grove Button is connected to digital pin 5
int buttonStatus = 0;           // This is used to hold the status of the button  



void setup(){
  //Initialise the Grove MP3 Module
  delay(2500);
  mp3.begin(9600);
  
        
  // initialize the pushbutton and switch pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(switchPin, INPUT);
  
  // set ledPin on the sliding potentiometer to OUTPUT
  pinMode(ledPin, OUTPUT);
  
  //You can view the following demostration output in the Serial Monitor
  demonstrate_GET_FUNCTIONS();     
}


void loop(){
  switchStatus = digitalRead(switchPin);
  if(switchStatus==HIGH){
    if(switchChangeStatus==LOW){             // When Arduino detects a change in the switchStatus (from LOW to HIGH) - play song      
      setPlayMode(0x02);                     // Automatically cycle to the next song when the current song ends
      playSong(00,01);                       // Play the 1st song when you switch it on
      switchChangeStatus=HIGH;
    }
    
    potVal = analogRead(potPin);                      // Analog read values from the sliding potentiometer range from 0 to 1023
    analogWrite(ledPin, potVal/4);                    // Analog write values range from 0 to 255, and will turn LED ON once potentiometer reaches about half way (or more).
    mp3Vol = map(potVal, 0, 1023, 0,31);              // Convert the potentometer reading (0 - 1023) to fit within the MP3 player's Volume range (0 - 31)
    if((mp3Vol>(oldVol+1))|(mp3Vol<(oldVol-1))){      // Only make a change to the Volume on the Grove MP3 player when the potentiometer value changes
      oldVol = mp3Vol;
      setVolume(mp3Vol);
      delay(10);                               // This delay is necessary with Serial communication to MP3 player
    }

    buttonStatus = digitalRead(buttonPin);
    if(buttonStatus==HIGH){                    // When a button press is detected - play the next song
      playNextSong();
      delay(200);                              // This delay aims to prevent a "skipped" song due to slow button presses - can modify to suit.
    }
  } else {
    if(switchChangeStatus==HIGH){              // When switchStatus changes from HIGH to LOW - stop Song.
      stopSong();
      switchChangeStatus=LOW;
    }
  } 
}


// demonstrate_GET_FUNCTIONS  will show you how to retrieve some useful information from the Grove MP3 Player (using the Serial Monitor).
void demonstrate_GET_FUNCTIONS(){
        Serial.begin(9600);
        Serial.print("Volume: ");
        Serial.println(getVolume());
        Serial.print("Playing State: ");
        Serial.println(getPlayingState());
        Serial.print("# of Files in SD Card:");
        Serial.println(getNumberOfFiles());
        Serial.println("------------------------------");
}


// writeToMP3: is a generic function that aims to simplify all of the methods that control the Grove MP3 Player

void writeToMP3(byte MsgLEN, byte A, byte B, byte C, byte D, byte E, byte F){
  byte codeMsg[] = {MsgLEN, A,B,C,D,E,F};
  mp3.write(0x7E);                        //Start Code for every command = 0x7E
  for(byte i = 0; i<MsgLEN+1; i++){
    mp3.write(codeMsg[i]);                //Send the rest of the command to the GROVE MP3 player
  }
}


/* The Following functions control the Grove MP3 Player : see datasheet for additional functions--------------------------------------------*/

void setPlayMode(byte playMode){
  /* playMode options:
        0x00 = Single song - played only once ie. not repeated.  (default)
        0x01 = Single song - cycled ie. repeats over and over.
        0x02 = All songs - cycled 
        0x03 = play songs randomly                                           */
        
  writeToMP3(0x03, 0xA9, playMode, 0x7E, 0x00, 0x00, 0x00);  
}


void playSong(byte songHbyte, byte songLbyte){                              // Plays the selected song
  writeToMP3(0x04, 0xA0, songHbyte, songLbyte, 0x7E, 0x00, 0x00);            
}


void pauseSong(){                                                           // Pauses the current song
  writeToMP3(0x02, 0xA3, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void stopSong(){                                                            // Stops the current song
  writeToMP3(0x02, 0xA4, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void playNextSong(){                                                        // Play the next song
  writeToMP3(0x02, 0xA5, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void playPreviousSong(){                                                    // Play the previous song
  writeToMP3(0x02, 0xA6, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void addSongToPlayList(byte songHbyte, byte songLbyte){
  //Repeat this function for every song you wish to stack onto the playlist (max = 10 songs)
  writeToMP3(0x04, 0xA8, songHbyte, songLbyte, 0x7E, 0x00, 0x00);
}


void setVolume(byte Volume){                                                // Set the volume
  byte tempVol = constrain(Volume, 0, 31);
  //Volume range = 00 (muted) to 31 (max volume)
  writeToMP3(0x03, 0xA7, tempVol, 0x7E, 0x00, 0x00, 0x00); 
}



/* The following functions retrieve information from the Grove MP3 player : see data sheet for additional functions--------------*/

// getData: is a generic function to simplifly the other functions for retieving information from the Grove Serial MP3 player
byte getData(byte queryVal, int dataPosition){
  byte returnVal = 0x00;
  writeToMP3(0x02, queryVal, 0x7E, 0x00, 0x00, 0x00, 0x00);
  delay(50);
  for(int x = 0; x<dataPosition; x++){
    if(mp3.available()){
      returnVal = mp3.read();
      delay(50);
    }
  }
  return(returnVal);
}

byte getVolume(){                                              //Get the volume of the Grove Serial MP3 player
  //returns value from 0 - 31
  return(getData(0xC1, 4));
}

byte getPlayingState(){                                        //Get the playing state : Play / Stopped / Paused
  //returns 1: Play,   2: Stop,   3:Paused
  return(getData(0xC2, 2));
}


byte getNumberOfFiles(){                                      //Find out how many songs are on the SD card
  //returns the number of MP3 files on SD card
  return(getData(0xC4, 3));
}
    
    

You will notice from the code, that I did not utilise every function. I decided to include them for your benifit. This Serial MP3 module makes use of a high quality MP3 audio chip known as the "WT5001". Therefore, you should be able to get some additional features and functionality from this document. Plus you may find some extra useful info from the Seeedstudio wiki.
 
IMPORTANT: You need to load your MP3 sounds or songs onto the SDHC card before you install it onto the Serial MP3 player.
 
Once the SDHC card is installed, and your code is uploaded to the Arduino, all you have to do now is connect the MP3 player to some headphones or a powered speaker. You can then power the Arduino and modules with a battery pack or some other portable power supply.
 
You can design and decorate the shoebox in any way you like. Just print out your picture, glue them on, and before you know it, you will have your very own Arduino Boombox.
 


Comments

I was very surprised by the quality of the sound that came from the MP3 module. It is actually quite good.

This tutorial was an introduction to the Grove Serial MP3 module in it's most basic form. You could just as easily use some other sensor to trigger the MP3 module. For example, you could get it to play an alert if a water leak was detected, or if a door was opened, or if the temperature got too high or too low. You could get it to play a reminder when you walk into your room. The possibilities are endless.

I really liked this module, and I am sure it will appear in a future tutorial.


 



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.

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.