15 January 2013

Bluetooth Tutorial 1


Introduction:
The bluetooth shield used in this project is a great way to detach the Arduino from your computer. What is even better, is that the shield allows you to control your arduino from your mobile phone or other bluetooth enabled device through simple Serial commands. In this tutorial we will connect a Grove Chainable RGB LED to the bluetooth shield directly, and send simple commands using the Bluetooth SPP app on a Samsung Galaxy S2 to change the colour of the LED (Red , Green and Blue)



Parts Required:
Freetronics Eleven or any compatible Arduino.
Bluetooth shield
Grove Chainable RGB LED
Grove Wire connectors




The Video:





The Arduino Sketch:








Arduino Code:
You can download the Arduino IDE from this site.


 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
/* This project combines the code from a few different sources.
This project was put together by ScottC on the 15/01/2013
http://arduinobasics.blogspot.com/

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

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

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

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

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


int Clkpin = 9; //RGB LED Clock Pin (Digital 9)
int Datapin = 8; //RGB LED Data Pin (Digital 8)
 
SoftwareSerial blueToothSerial(RxD,TxD);

/*----------------------SETUP----------------------------*/ 
void setup() { 
 Serial.begin(9600); // Allow Serial communication via USB cable to computer (if required)
 pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
 pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
 pinMode(13,OUTPUT); // Use onboard LED if required.
 setupBlueToothConnection(); //Used to initialise the Bluetooth shield
 
 pinMode(Datapin, OUTPUT); // Setup the RGB LED Data Pin
 pinMode(Clkpin, OUTPUT); // Setup the RGB LED Clock pin
 
} 

/*----------------------LOOP----------------------------*/ 
void loop() { 
 digitalWrite(13,LOW); //Turn off the onboard Arduino LED
 char recvChar;
 while(1){
 if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield
 recvChar = blueToothSerial.read();
 Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
 
 //If the character received = 'r' , then change the RGB led to display a RED colour
 if(recvChar=='r'){
 Send32Zero(); // begin
 DataDealWithAndSend(255, 0, 0); // first node data
 Send32Zero(); // send to update data 
 }
 
 //If the character received = 'g' , then change the RGB led to display a GREEN colour
 if(recvChar=='g'){
 Send32Zero(); // begin
 DataDealWithAndSend(0, 255, 0); // first node data
 Send32Zero(); // send to update data 
 }
 
 //If the character received = 'b' , then change the RGB led to display a BLUE colour
 if(recvChar=='b'){
 Send32Zero(); // begin
 DataDealWithAndSend(0, 0, 255); // first node data
 Send32Zero(); // send to update data 
 }
 }
 
 //You can use the following code to deal with any information coming from the Computer (serial monitor)
 if(Serial.available()){
 recvChar = Serial.read();
 
 //This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
 blueToothSerial.print(recvChar);
 }
 }
} 


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


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

The code above was formatted using hilite.me

Notes:
You don't need to download a library to get this project running. But if you plan to use bluetooth shields to get 2 Arduinos to communicate to each other, then I would advise that you download the library files (which are just examples) from the Seeedstudio site : here.

Visit this site to setup your phone or laptop for bluetooth communication to the shield - here

The app used on my Samsung Galaxy S2 phone was "Bluetooth SPP"

You will initially need to enter a pin of '0000' to establish a connection to the Bluetooth shield - which will appear as "SeeedBTSlave" or whatever text you place on line 90 of the Arduino code above.





Warning !

Not all phones are compatible with the bluetooth shield.
If you have used this shield before - please let me know what phone you used - so that we can build a list and inform others whether their phone is likely to work with this project or not. Obviously - those phones that do not have bluetooth within - will not work :).
And I have not tried any other apps either

I got it to work very easily with my Samsung Galaxy S2 using the free Bluetooth SPP app from the google play store.

This was fun, but I want to make my own app !
Have a look at my latest 4-part tutorial which takes you step-by-step through the process of building your own app using the Processing/Android IDE.
You can build your own GUI interface on your Android Phone and get it to communicate via Bluetooth to your Arduino/Bluetooth Shield. Click on the links below for more information:




 
 



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

 

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


 
 

 
 
 



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

40 comments:

  1. please help. i have the same bluetooth shield and i cannot get it into pairing mode (red/green lights). i've tried to use your code, but i cannot send proper commands to the bluetooth module.

    ReplyDelete
    Replies
    1. Hi Eric,
      Please confirm that you have the bluetooth module jumpers in the correct position. I think I modified them on my bluetooth module for this tutorial. And make sure that the bluetooth shield is sitting in the Arduino Pins. Also please confirm that you are using an Arduino UNO or equivalent, and not a MEGA.
      When you plug your Arduino into your computer, (before sending the sketch), you should notice that the light is blinking green. After sending the sketch to the Arduino, it should go into pairing mode. This is all done via a USB cable. Can you get to this step - or do you have a problem before this step?

      Regards
      Scott

      Delete
    2. My pins are correct, the shield is flush with the Arduino board, and I'm using an UNO. I get the blinking green light, but after sending the sketch nothing changes. This is all through the USB cable. I've tried with the shield attached and without the shield attached. I do not get red/green lights. When i send commands i receive garbage text in return. I've tried every baud rate, but the text still comes back as garbage.

      Delete
    3. Without flashing red/green lights, this will not work. However, am not sure how you are receiving any text if you are not getting any communication on your Bluetooth module. Also please make sure you are using the latest Arduino IDE software version. Also make sure that your jumper pins are not back to front (Rx and Tx reversed). Other than this, it may be worth asking for help in the Arduino Forums. There are people there who have much more experience than me.

      Delete
  2. Hey,

    Related topic, do you know how to establish bluetooth communication between a laptop (running linux) and an Arduino uno w/ BT shield?

    I've paired my laptop and Arduino, and am trying to connect using a python bluetooth module,
    however transferring data does not seem to work.

    Thanks,
    Ming

    ReplyDelete
    Replies
    1. Hi Mxiao,
      I noticed that you have posted on StackOverFlow:
      http://stackoverflow.com/questions/15486570/bluetooth-communication-between-arduino-and-pybluez

      There are a lot of different bluetooth modules around, and I only have the one displayed in this post, so I can only give you tips based on my experience with this one. Also note that I have absolutely no experience with Linux or Python, so can't help you on that front.

      However, you did say that you have successfully paired your laptop to your Arduino. Pairing and connected are two different things. So first step, before you even send data to or from the Arduino/Bluetooth module, is that you establish a successful connection.
      On my bluetooth module, it flashes red-green when it is in Discovery mode, looking for other devices to connect to. When a connection has been made, the light changes to a flashing green light (about 1 per second), and faster when it loses connection (about 1 per half second). In the video, it also shows how you can connect an LED to the shield to verify that a connection has been made.

      The next thing to be aware of is that the Bluetooth module that I have is communicating with the Arduino on Pins 6 and 7, so that it does not interfere with the communication that is happening on pins 0 and 1. You may want to investigate that further.

      You may also want to double check your Baud Rate - you have it set to a smaller value, you may need to double check this also.

      You may also want to look at these sites:
      http://www.seeedstudio.com/wiki/Bluetooth_Shield

      http://www.seeedstudio.com/wiki/Grove_-_Serial_Bluetooth

      They may provide the direction you need. Good luck.

      Delete
  3. Hello, I have not a Grove - Chainable RGB LED , I like turn on and turn off a LED in the pin13 with my android, I have some code but not working

    if (recvChar =='a'){
    digitalWrite(13, LOW);

    }

    ReplyDelete
    Replies
    1. Hi Anonymous,
      There isn't enough information in your question to see where you are going wrong. Because I don't know how much of my code you are using. In my code, I have turned off the onboard LED which is on pin13 (on line 45 - just after loop(){
      You will need to Delete this line.

      In your code, you are also turning it off, so I am assuming that somewhere in your code you have a character where you turn it on ?
      Eg. if(recvChar=='b'){ digitalWrite(13, HIGH);}

      Not sure if that helps or not.

      Delete
  4. Saludos, tengo un arduino leonardo y una placa de bluetooth de seeed studio deseo prender desde un android un led ubicado en el pin 13, la placa de bluetooth se conecta correctamente al android pero al enviar un valor para prender el led en pin 13 no pasa nada.
    Tengo que hacer una coneccion especial pra prender un led por bluetooth ?
    se debe conectar en los pines digital o analogico?
    Gracias

    ReplyDelete
    Replies
    1. Hi Anonymous,
      Sorry, had to use Google translate to convert your question into English, so I hope I am answering the right question. From what I understand, you have established a successful connection, therefore, if you keep your arduino connected to your computer via USB cable, you should be able to see the information being sent from the Android phone by opening the Serial Monitor in the Arduino IDE.
      If you are not seeing anything, then perhaps check your Baud Rate settings, check the pins being used to communicate between the bluetooth module and the Arduino. So your first step is making sure that you can actually see information being transmitted.

      Delete
  5. Hi, I can't see the information being transmitted from my android , I only see the information being transmitted from my laptop in my android.
    I have the jumpers like the picture

    ReplyDelete
    Replies
    1. When you open the Serial Monitor, do you see the following message at the top:
      The slave bluetooth is inquirable!

      Delete
    2. Also if you have a Arduino Leonardo, as per documentation from the Arduino website: http://arduino.cc/en/Main/arduinoBoardLeonardo, you may need to change all Serial references in the code above to Serial1. I don't have a Leonardo to test this out, but worth giving it a try.

      eg. Serial1.println("....");

      There may be other information on that page which may be relevant, so I suggest you read there, and then perhaps ask in the Arduino Forums on how to adapt my code to that Arduino Platform.

      Delete
    3. No, I only see this message in the code
      when I have connection with the bluetooth from my android. I open the serial monitor and this is clean

      Delete
    4. see my message above about using Serial1

      Delete
  6. Hi Scott, nice tutorial.
    I have a Arduino UNO R3 and I BT shield I bought on Deal Extreme (ElecFreaks BT Shield V 1.2) very similar to the one shown above (jumpers and connections). I have downloaded your sketch but all I have is a red led flashing once a sec. I downloaded the SPP app on my Sony Ericsson Xperia 8, turned on BT, clicked on Scan, but nothing happens. Can you please try to point out any mistakes I could have made during the process. Thanks, Caue.

    ReplyDelete
  7. BTW, I have the message "The slave bluetooth is inquirable!" on Serial Monitor.
    Thanks again, Caue.

    ReplyDelete
  8. Scott, never mind. I got it working. Just put another jumper in I/O position and changed the sketch to use BT speed of 9600. At least now we know Xperia 8 running Android 2.2 works fine with Arduino BT Shield.
    Thank you very much for sharing the info in your site,
    Caue

    ReplyDelete
    Replies
    1. Hi Caue,

      Glad to see that you got it to work.

      Regards
      Scott

      Delete
  9. Hi scott, Iam doing final project about to communicate between 2 bluetooth shield v2.2 and both of them are pluged in arduino uno. And how to connect that bluetooths automatically? thank you.. Please help

    ReplyDelete
    Replies
    1. Hi Meliza, I have never done what you are trying to do (because I only have one Bluetooth shield). You will however need to designate one board as the Master and one as the slave. See this site. And perhaps try the Arduino forums.

      Delete
  10. there is a problem with placing "blueToothSerial.begin (38400) to 38400" and "Serial.begin (9600) in 9600"? or not?

    ReplyDelete
    Replies
    1. Good question. But no, I did not have a problem with it. Some people have to modify the Bluetooth baud rate depending on their Bluetooth module. And you may need to modify Serial.begin depending on the baud rate that you use on your Serial monitor on your computer. But they are independent of each other.
      Because we are only sending a single character, there are no bottlenecks. But if we were sending continuous data over a longer period then maybe I would consider making these two baud rates the same.
      I hope that answered your question.

      Delete
  11. Hi Scott
    I'm trying to connect a RN-42 to my tab.I made some changes in u'r code.I didn't change the code for the blue-tooth part.The connections are fine.I'm using Bluetooth SPP app.I pressed 'r' in my tab,but the serial monitor is showing something else.Please help me out.Thank you...

    ReplyDelete
    Replies
    1. Hi Chaitanya,

      I have no experience with an RN-42, so my help is going to be very limited.
      You will need to change the contents within the
      void setupBlueToothConnection(){....} method.
      You will need to find out the specific commands and Baud rate for the RN-42 module. Have you seen this document from sparkfun?

      You may also want to have a read of the following Arduino forum post.
      http://forum.arduino.cc/index.php?topic=74548.0

      You will need to send the right commands to your specific bluetooth module to get it to work. Most likely to be a Baud Rate related issue.

      Scott


      Delete
    2. Hey Scott,

      I have a Multiwii WMC CRIUS BT Module and I wanted to connect it in order to send data from sensors connected to Arduino via bluetooth to another computer. However, I'm having problems on estabilishing the BT communication on my Arduino code. The code you posted is compatible with the CRIUS Bluetooth module or the instructions on this code just work with the BT shield for Arduino?

      Thanks in Advance

      Delete
    3. I have no experience with the MultiWii, and my guess is that you will need to source the code specific for that bluetooth module from the manufacturers??. The Arduino code I have in my tutorial for my bluetooth shield was sourced from Seeedstudio's website as per the comments at the beginning of the Arduino Sketch.

      Delete
  12. I'm trying to get this to work with the Arduino Due. Just the LED to start, but no luck. The LED comes on blue, but "manual" settings of it to other colors, based on the code in this article, as no effect. I can email anyone the test code I'm trying. Any help would be most appreciated!

    Randy Langer rlanger@technicrafts.com

    ReplyDelete
    Replies
    1. hey, i'm working on the similar case. Maybe we can discuss with each other and find a way out~

      My email: sctracy03@gmail.com

      Delete
  13. Uh, Scott C, help!

    First off, when I try to compile, it can't find . Does this not come with the Arduino package? (Clarification: I'm using the Arduino Due, if that makes a difference.)

    Second, the page linked to from "Visit this site to setup your phone or laptop for bluetooth communication to the shield" has recently changed, and no longer covers how to set up with a Win 7 machine. Does anyone know how to get back the previous article that did explain this????

    ReplyDelete
  14. The file it can't find is SoftwareSerial.h .

    ReplyDelete
  15. Try Arduino Visual application..

    ReplyDelete
    Replies
    1. I'm not sure what that is -- do you mean the add-on from Visual Micro? If so, I'm already using that, as it happens.And it is getting me no closer to resolution.....

      Delete
  16. I wonder if it's possible to use this code only to work with 3 leds, like if I send "r" the red led will turn on, do you get it? with individual leds. Can you help me with that

    ReplyDelete
    Replies
    1. Of course it is possible. In fact it would be a whole lot easier.
      Just connect your leds (with resistors) to any of the digital pins, and when you receive the letter 'r' set that pin to high. You may need another code to switch it off - or use the 'r' as a toggle.

      The code above is very complicated due to the use of that Grove RGB led.
      It adds a whole extra layer of complexity which could be avoided with a normal RGB LED.
      But I wanted to see if I could use the Grove RGB led - and wrote about it - so that others who have that LED could see how to use it.

      Delete
  17. Tried your code and it didn't work. Noticed Clk was very narrow- 20uS. Increased to 2000 and it worked

    ReplyDelete
    Replies
    1. Many people have successfully used the code without modification. But good to know for those who are in the same boat as you.

      Delete
  18. I just wanted the code for Arduino to be controlled using Android

    ReplyDelete

Feel free to leave a comment :