Thursday, December 27, 2012

Bluetooth + Arduino Tutorial

Bluetooth and its wonders. Set it up with Arduino and Attiny85!

Introduction

This is my very first tutorial and it is on Bluetooth with Arduino.  I feel this is necessary for the community as there are not so many of them out there. The ones that are floating around the web are highly outdated or just not to my taste. Sorry! I know I'm not the best one to do a tutorial either but I will try my best. I learned how to use the Seeeduino Bluetooth, or any Bluetooth the hard way. This is created to make it easier for you! 

note: When I was learning about how to add Bluetooth to my project I was following closely the Wiki page of Seeeduino Bluetooth Shield. Find it here. Also, I will be covering how to set up your Bluetooth as a slave. If you would like to learn how to set it up as a Master reference the link above.

I hope you enjoy this tutorial / how to

What you need, Arduino Bluetooth



What you will need for the first part of this tutorial (Bluetooth with Arduino not Attiny!!) is an Arduino Uno, I'm using version 3, and the Seeeduino Bluetooth Shield. You can use a different one by modifying the
tutorial slightly. In the second part of the tutorial I will introduce a different Bluetooth module and how to work it with the Attiny85. 

The list:
  • Arduino Uno (I'm sure you can use others but I haven't had a chance to test)
  • Seeeduino Bluetooth Shield

OK! We are Ready to Set Up! 

First of, lets connect everything like it should be. When you are placing your shield onto the Arduino make sure the analog side is on the analog side of the Arduino and the Digital on Digital. Make sure the pins are matching and just place it down and push it in.
We are ready to upload! I'm going to assume you have the Arduino software installed and you know how to upload a sketch to your Arduino. The only problem is that we don't have the code!

The Seeeduino Bluetooth Shield Code

This is my favorite part, the coding! 
Start off by opening up a new Arduino sketch. Fill in the usual aka Bare Minimum:

 void setup(){ }  
   
 void loop(){ }  

Now, for us to set up a communication via a serial port we can use a library called SoftwareSerial. Go to tools -> library and choose the SoftwareSerial library. Once you have it imported we can start using it.

For the first part we are going to set up the software serial port on Arduino channel 6 and 7. 6 being the receiving pin and 7 being the transmitting pin.

 #include            // this will include the software serial port library
 int rx_pin = 6;     // setting digital pin 6 to be the receiving pin
 int tx_pin = 7;     // setting the digital pin 7 to be the transmitting pin

 SoftwareSerial Bt(rx_pin,tx_pin); // this creates a new SoftwareSerial object on 
                                   // the selected pins!
 void setup(){ }  
   
 void loop(){ }  

OK, so far so good! The code is not doing much yet but we are getting somewhere. Now its time to set up the pinModes like so.

 void setup(){
 Serial.begin(9600); // this is a connection between the arduino and 
                       // the pc via USB
 pinMode(rx_pin, INPUT);  // receiving pin as INPUT
 pinMode(tx_pin, OUTPUT); // transmitting pin as OUTPUT

 bluetoothInitiate(); // this function will initiate our bluetooth (next section)
 }  

And now the Bluetooth as a slave. What this means that your android phone or your PC will be able to pair with it and send information back and forth. For this I will create a separate function to keep everything neat in the setup function.

 void bluetoothInitiate(){
 // this part is copied from the Seeeduino example*
 Bt.begin(38400); // this sets the the module to run at the default bound rate
 Bt.print("\r\n+STWMOD = 0\r\n");        //set the bluetooth work in slave mode
 Bt.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
 Bt.print("\r\n+STOAUT=1\r\n");          // Permit Paired device to connect me
 Bt.print("\r\n+STAUTO=0\r\n");          // Auto-connection should be forbidden here
 delay(2000);                            // This delay is required.
 Bt.print("\r\n+INQ=1\r\n");             //make the slave bluetooth inquirable
 delay(2000);                            // This delay is required.
 Bt.flush(); 
 Bt.print("Bluetooth connection established correctly!"); // if connection is successful then print to the master device
 }

Congrats! You can now connect to your Bluetooth, but it wont do much at all.
So... now we need to do something to receive the packets thrown at us from a PC or any other device.
For this we setup the RX pin and the TX pin, so lets put it to works.

 char buffer; // this is where we are going to store the received character
 void loop(){
 if(Bt.avaliable()){     // this will check if there is anything being
                           // sent to the Bluetooth from another device
   buffer = Bt.read();   // this will save anything that is being sent to the Bluetooth
   Serial.print(buffer); // this will print to the local serial (tools->serial monitor)
   }
 // this is for recieving on the device with bluetooth, now we can make it send stuff too!
 if(Serial.available()){   // this will check if any data is sent
                             // from the local terminal
   buffer = Serial.read(); // get what the terminal sent
   Bt.print(buffer);       // and now send it to the master device
   }
 }


Putty and COM

In order for us to communicate between the PC and Arduino via Bluetooth we have to establish a connection via COM. A really good and free program that we can use to establish a serial connection between the Bluetooth module and our PC is Putty. You can download it and read more about it here. Now once you have installed Putty we can move on to the next step. 
Power on your Arduino with the shield and the code already uploaded. Remember to restart the Arduino after you have uploaded the code. 
You should notice two leds flashing on the shield, red and yellow. This is good, now you can search for the module using your PC's Bluetooth software. It should be named SeedBtSlave. The pairing code is "0000" Once you have it paired with your computer we can start working our magic, but first we need to check what COM port we are running the Bluetooth connection on. We can do this by clicking start then typing "device manager". Open device manager and navigate down to Ports(COM&LPT), expand it. Now you should notice that you have two new things there. It should say "Standard Serial over Bluetooth link (COM#)" If it does, then you know that you paired your device correctly and are ready to start using it. NOTE: I have more than one Bluetooth device connected therefore there are 4 ports!

Note the COM number. (usually the top one out of the two) and lets go over to Putty. 
Open up Putty and select the "serial" radio button. Now set the COM# and the speed as 38400. This is what we used in the code*

At this point I would recommend that you restart your Arduino before proceeding to open the connection. When the red/yellow lights are flashing on the Arduino you are ready to connect! If everything went right you should see this screen:



Congratulations!!! This message has been sent over Bluetooth from your Arduino to your PC!
Now open your local terminal monitor (the USB connection between your PC and Arduino) and send messages between the two. I have used this to turn on and off LEDS and move SERVOS. Its heaps of fun and the limits are your imagination.

Later on this week I will post a tutorial building upon this and how to use a different Bluetooth module with the Attiny85. Stay tuned! I hope you enjoyed this tutorial, if you have any questions please comment. Also, keep in mind that this is my first tutorial and one of the first blog posts ever. If you do not understand something or if you would like to comment on anything do not hesitate to post.

Thanks for reading!

40 comments:

  1. can you please provide me with one code to connect.
    I mean not in pieces.
    my email is:-lokesh.crazy20@gmail.com
    its quite imp for me

    ReplyDelete
    Replies
    1. I can definately provide you with the complete code when I get home tonight, however I do recomend piecing it together yourself as it will give you more of an understanding on how it works. I will email you the whole code tonight though

      Delete
  2. Does this shield connect with a bluetooth device thats shares a 8 digit pairing code ( PIN "12345678" ), or it works only with 4 ( PIN "1234") digit pairing codes?
    Thank you!

    ReplyDelete
    Replies
    1. what device are you trying to connect to? I'm 99% sure that you can change the default pairing pin to an 8 digit number. Take a look at the documentation for the Bluetooth and try ;)
      http://www.seeedstudio.com/wiki/images/e/e8/BTSoftware_Instruction.pdf
      if you can, report back on your findings for others to see :)

      Delete
    2. I think this is over a year old, but I'm really looking for an answer and can't find anything.

      Does the Seeeduino BT Shield support PIN codes of over 4 digits?
      Many Thanks

      Delete
  3. When are you going to post the Bluetooth with attiny85?., I have been struggling with my attiny for days..I just can't figure it out, I know it can be done....I find your tutorial style very easy to follow.and can't wait for an update

    ReplyDelete
    Replies
    1. Today is my last final exam, I promise it by tomorrow night. What hardware are you using?

      Delete
  4. Cool..im using attiny85,..usbtiny isp programmer
    ,and the same Bluetooth as above. I just want to control a led ..simple on and off. I have a breadboard and jumpers also misc electronic parts...

    ReplyDelete
  5. Sorry the Bluetooth is a jy- mcu hc. The cheap modules you can find on ebay. The funny thing is i can connect to the module just fine but i can't see any output from there attiny thru putty. I'm struggling with the code. There are no tutorials that i can find that cover How to use bluetooth with the attiny..but there are youtube videos showing people using Bluetooth with them. .. very frustrating. ....lol

    ReplyDelete
  6. I ended up fuguring it out..I had to much voltage going to the chip...lol

    ReplyDelete
    Replies
    1. im glad you figured it out. I will be publishing a tutorial by tomorrow night either way. You are welcome to check back in if you need help.

      Delete
  7. can you please provide me with the code all together?
    I mean not in pieces.
    my email is: crock.bmc@gmail.com

    I been having trouble trying to connect the adruino to bluetooth.

    ReplyDelete
  8. #include // import the serial library

    SoftwareSerial Genotronex(10, 11); // RX, TX
    int ledpin=13; // led on D13 will show blink on / off
    int BluetoothData; // the data given from Computer

    void setup() {
    // put your setup code here, to run once:
    Genotronex.begin(9600);
    Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
    pinMode(ledpin,OUTPUT);
    }

    void loop() {
    // put your main code here, to run repeatedly:
    if (Genotronex.available()){
    BluetoothData=Genotronex.read();
    if(BluetoothData=='1'){ // if number 1 pressed ....
    digitalWrite(ledpin,1);
    Genotronex.println("LED On D13 ON ! ");
    }
    if (BluetoothData=='0'){// if number 0 pressed ....
    digitalWrite(ledpin,0);
    Genotronex.println("LED On D13 Off ! ");
    }
    }
    delay(100);// prepare for next data ...
    }

    This code above I am trying to convert this code to ATtiny85. What changes do I need to make?

    ReplyDelete
  9. U r the boss! I was wasting valuable hours trying to connect Bluetooth shield and you just solved my problem. Thanks a lot!

    ReplyDelete
  10. First I would like to thank you for providing this valuable information. I want to know how to close this connection once established so that i can connect this to other devices like android mobile.Is there any code to close connection just like bluetoothInitiate() to initialize the bluetooth.?

    ReplyDelete
    Replies
    1. As you notice, we can setup the bluetooth through AT commands. This allows us to change its settings "live", meaning if we have the right command we can do anything with the device. Now I'm not 100% sure and I cannot test this right now but the solution might be simple. When you want to disconnect the device you could try running this line of code -

      delay(2000); // This delay is required.
      Bt.print("\r\n+INQ=0\r\n"); //make the slave bluetooth NOT inquirable
      delay(2000); // This delay is required.

      notice that in the original code we made it inquirable? well, this line simply makes it not inquirable. This in theory should kill the connection. I have not tried this and I am unable to do so at the moment. Also, take a look at the link below, there are some useful AT commands that you might be interested in.

      http://www.seeedstudio.com/wiki/Serial_port_bluetooth_module_(Master/Slave)#Commands_to_change_default_settings

      Also, if the above doesnt work I would try this code.

      Bt.print("\r\n+STOAUT=0\r\n"); // DO NOT Permit Paired device to connect me

      Delete
    2. Funny.. I just did a little bit of reading form the link I provided above and it says how to disconnect the device.
      "Disconnect device Pulling PIO0 high will disconnect current working Bluetooth device."
      simple. connect PIO0 to a pin on your micro controller and pull it high when you want to disconnect the device.

      Delete
  11. If I had a camera connected to the Arduino and wanted to transfer the image as a HEX file to my PC via Bluetooth shield, could I do it using this code as a reference point?

    ReplyDelete
    Replies
    1. yea you can definitely do it! the code would have to be really sophisticated, but sure possible. if you are able to do the same through a regular USB serial, you can do it through the bluetooth connection. The only thing is the speed, but 115200 bitrate should be plenty i believe

      Delete
  12. do I need to upload all the codes shown above into arduino??

    ReplyDelete
  13. Thanks for making this post, it was very helpful. I have a question though, that you may or may not be able to answer.

    Does your code only work with a Seeeduino Bluetooth Shield? Because I am currently trying to apply this code to a ITead Studio Bluetooth Shield V2.2.

    I got the code on the Arduino Uno board, connected to my computer via Bluetooth, through the steps you provided. But when I open up putty to open up the connection I don't see the "Bluetooth connection established correctly" message. So I was wondering what I was doing wrong, or something that's commonly missed in cases like this.

    Thanks.

    ReplyDelete
    Replies
    1. This code is designed to work with the seeeduino shield, but can be easily altered to work with any other shield you might have. Since the board you have has the hc-05 bluetooth module then you dont need the whole code actually but it should work just fine without modifying the code. If you do not modify the code and run it, do not expect the bluetooth name to be what we named it in code. Instead expect something such as "hc-05". Another thing to watch out is what pins are RX and TX. take a look at this link:
      http://home.comcast.net/~tomhorsley/hardware/arduino/datasheet.html

      Delete
  14. Can I ask for the whole codes for bluetoothshield? I cannot connect the bluetooth to my laptop.

    thank you

    here is my email: kruistinemagno@yahoo.com

    ReplyDelete
  15. Can I ask for the whole codes for bluetoothshield? I cannot connect the bluetooth to my laptop.
    thank you
    here is my email:mohamed_shatara2012@yahoo.com

    ReplyDelete
  16. You can just use Apploader iOS app to upload over BLE:
    http://www.apploader.info

    Check out video:
    https://www.youtube.com/watch?v=3CpzrsvriKw

    ReplyDelete
  17. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. Best Treadmills Under 1000

    ReplyDelete
  18. I really loved it and visit here soon. IDM Crack

    ReplyDelete
  19. Hi!
    This is very well written and it's so intresting.
    This is so awesome.
    But you should also see this...
    This site provides free serial/activation codes and license keys.
    typing master pro crack
    driver easy pro key
    freemake video converter key

    ReplyDelete
  20. It’s not my first time to pay a quick visit this web
    site, i am visiting this site dailly and obtain fastidious data from here
    daily.


    buy age of empires cd key crack
    autodesk autocad civil 3d
    eventsentry 4 crack
    bitdefender total security key
    apex launcher apk

    ReplyDelete
  21. After looking over a number of the blog posts on your
    the site, I seriously like your way of writing a blog.
    I book-marked it to my bookmark website list and will be checking back soon. Take a look at my web site
    as well, and let me know what you think.
    football manager product key
    outbyte antivirus crack
    eset internet security crack
    driverpack solution crack

    ReplyDelete
  22. Excellent blog! Do you have any advice for aspiring writers?
    I hope to start with the website soon. You advise from
    Is it a free platform like WordPress or a paid option? There are so many options, I am completely confused about...
    Any suggestions? Thank you!
    freemake video converter
    hma pro vpn crack
    ytd video download pro crack

    ReplyDelete
  23. Wow, amazing weblog structure! How lengthy have
    you ever been blogging for? you made running a blog look easy.
    The entire glance of your web site is magnificent, let alone
    the content!
    file viewer plus crack

    ReplyDelete
  24. Fantastic blog! What advice do you have for aspiring writers?
    I hope to start my page soon, but I am a bit
    lost in total. Would you suggest starting with
    a free platform like WordPress, or do you opt for the paid option? There are so many options that I am completely overwhelmed.
    Some suggestions? Thank you!
    fabfilter pro q crack
    sure cuts a lot pro crack

    ReplyDelete
  25. I like this site, this is a new theory, I read it, it gives good knowledge.
    abbyy finereader
    easy gif animator crack

    ReplyDelete
  26. I searched for this for a long time and finally found it. Glad you did it here, thank you!
    transmac crack
    movavi video converter activation key crack

    ReplyDelete
  27. Its truly strong for you from a general point of view all window programming establishment. This site is stunning its article are major and overwhelming. I got a kick out of and bookmark this site on my chrome. This is the place where you can get all break programming in like manner present in clear way.
    https://zsactivatorskey.com/

    ReplyDelete
  28. Its really solid for you from an overall perspective all window programming foundation. This site is shocking its article are major and overpowering. I got a kick out of and bookmark this site on my chrome. This is where you can get all break programming in like way present in clear manner.
    https://shahzifpc.com/

    ReplyDelete
  29. Its truly strong for you from a general viewpoint all window programming establishment. This site is stunning its article are major and overwhelming. I got a kick out of and bookmark this site on my chrome. This is the place where you can get all break programming in like manner present in clear way.
    https://ziapc.org/

    ReplyDelete
  30. Its really solid for you from an overall perspective all window programming foundation. This site is staggering its article are major and overpowering. I got a kick out of and bookmark this site on my chrome. This is where you can get all break programming in like way present in clear manner.
    https://cracksmod.org/

    ReplyDelete