RFCOMM/SPP Library for Arduino
This is yet again a new library for Arduino.
But this time it is a speciel one and a library I have though about making for a long time since I wrote the PS3 Bluetooth Library. It is the RFCOMM/SPP library, in short it is a virtual serial port via Bluetooth, which means you can now communicate with your Arduino via Bluetooth using a normal terminal application on your computer, smartphone etc. It has been confirmed working with Windows 7, Mac OS X, Linux (Ubuntu 12.04) and several Android devices.
For it to work you will need a USB Host Shield and a Bluetooth dongle, much like the PS3 Bluetooth Library.
After that you simply upload the example sketch to your Arduino.
The example sketch can be found below as well:
USB Usb;
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "1234"
//SPP SerialBT(&Btd, "Lauszus's Arduino","0000"); // You can also set the name and pin like so
boolean firstMessage = true;
void setup() {
Serial.begin(115200);
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while(1); //halt
}
Serial.print(F("\r\nSPP Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if(SerialBT.connected) {
if(firstMessage) {
firstMessage = false;
SerialBT.println(F("Hello from Arduino")); // Send welcome message
}
if(Serial.available())
SerialBT.print(Serial.read());
if(SerialBT.available())
Serial.write(SerialBT.read());
}
else
firstMessage = true;
}
The example sketch is pretty easy to understand:
First you include the library and create the USB instance. You will then need to create the BTD (Bluetooth Dongle) instance, which will take care of all the HCI communication. Finally you have to create the SPP instance – you will notice that you can create it in several ways. You can either just create it and then it will use the default name “Arduino” and the default pin “1234″ – it is handled by this line in the source code. But you can also easily modify these values by including them as a string. By doing so you can set the name and pin of your device to whatever you want – the pin can be a maximum of 16 characters while the name can be as large as 248 characters as specified by the Bluetooth specification.
I then simple create the bool “firstMessage” which is used to detect when the connection is established. I then start the build in serial communication at 115200 baud and I then initialize the USB Host Shield. After that I just print a simple debug string to let the user know that the Arduino has started.
I then simple runs Usb.Task() which will initialize the Bluetooth dongle and run the SPP library automatically. It then waits until a SPP connection is established and if so sends a welcome message to the device.
After that it will simply sent any message it receives via it’s hardware serial port to the connected device via the SPP protocol. If a messages is received it is written to the connected computer via the USB serial communication.
You will of course need a terminal application on your device. I recommend the following terminals for the different platforms:
The full source code can as always be found at github: https://github.com/felis/USB_Host_Shield_2.0/blob/master/SPP.cpp.


I modify your sample to sending IO port values, it work for a while next I receive some errors and the sketch stop to send.
Here the complete logging sequence:
SPP Bluetooth Library Started
Bluetooth Dongle Initialized
No response to HCI Reset
HCI Reset complete
Local Bluetooth Address: 00:10:60:AA:75:19
The name is set to: Arduino
Wait For Incoming Connection Request
Incoming Connection Request
Remote Name: ANDROID BT
Connected to Device: 5C:E2:F4:CC:D1:F0
Received Key Request
Wait For Incoming Connection Request
Bluetooth pin is set too: 1234
SDP Incoming Connection Request
RFCOMM Incoming Connection Request
SDP Configuration Request
SDP Successfully Configured
RFCOMM Configuration Request
RFCOMM Successfully Configured
Received SABM Command
Received UIH Parameter Negotiation Command
Received SABM Command
Send UIH Modem Status Response
Send UIH Modem Status Command
Send UIH Command with credit
Received UIH Command with credit
RFCOMM Connection is now established -- Automatic
…here the script send correctly almost 20 string values, then….
Error sending L2CAP message: 0x0D -- Channel ID: 0 66
Error sending L2CAP message: 0x0D -- Channel ID: 0 66
Error sending L2CAP message: 0x0D -- Channel ID: 0 66
Error sending L2CAP message: 0x0D -- Channel ID: 0 66
……….
have some idea how to resolve?
Regards
Paolo
@Paolo
Can you post your code somewhere, then I will have a look at it
@Lauszus
Many thanks for your reply.
I tried it with some Android Terminal app (Bluetooth Viewer, SENA Bterm,BlueTerm ecc.) and with a my application developed with B4A also.
I tried your demo with Wiimote and all work very fine!, so I think the hardware it’s working.
The code is very simple:
*
Example sketch for the RFCOMM/SPP Bluetooth library -- developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include
USB Usb;
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
SPP SerialBT(&Btd); // This will set the name to the defaults: “Arduino” and the pin to “1234″
//SPP SerialBT(&Btd, “Lauszus’s Arduino”,”0000″); // You can also set the name and pin like so
boolean firstMessage = true;
void setup() {
Serial.begin(115200);
if (Usb.Init() == -1) {
Serial.print(F(“\r\nOSC did not start”));
while(1); //halt
}
Serial.print(F(“\r\nSPP Bluetooth Library Started”));
}
void loop() {
Usb.Task();
if(SerialBT.connected) {
if(firstMessage) {
firstMessage = false;
SerialBT.println(F(“Connected!”));
SerialBT.flush();
delay(500);
}
else
{
//*************************************************************
//try to send only 1 byte
//SerialBT.println(String(port0++));
//delay (300); THAT LOSE CONNECTION AFTER 17 LINES
//delay(30); THAT LOSE CONNECTION AFTER 17 LINES
//delay(0); THAT REPORT “Error sending L2CAP message: 0x0D -- Channel ID: 0 66″ AFTER 60 LINES
//*************************************************************
//try to send port values
//THAT STOP WITH ERROR MESSAGE “Error sending L2CAP message: 0x0D -- Channel ID: 0 66″ AFTER ALMOST 18 LINES
SerialBT.println(“A”+String(analogRead(0))+”|”
+”B”+String(analogRead(1))+”|”
+”C”+String(analogRead(2))+”|”
+”D”+String(analogRead(3))+”|”
+”E”+String(analogRead(4))+”|”
+”F”+String(analogRead(5))+”|”);
delay(1000);
//delay(200); //same behavior
//SerialBT.flush(); //same behavior
//************************************************************
}
}
else
firstMessage = true;
}
//Many thanks in advance
//
//Paolo
@Paolo
Try to split the string up like so:
+”B”+String(analogRead(1))+”|”
+”C”+String(analogRead(2))+”|”
+”D”+String(analogRead(3))+”|”
+”E”+String(analogRead(4))+”|”
+”F”+String(analogRead(5))+”|”;
SerialBT.println(string);
A longer delay will actually just make things worse, as you have to read the endpoint once in a while, this is how I would recommend doing it instead: https://github.com/TKJElectronics/BalancingRobotArduino/blob/master/BalancingRobotArduino.ino#L107-L110.
@Lauszus
.
Thanks for reply but unfortunatly not resolve
Using your sample above I can send any char from the device to Arduino but not viceversa (I think it should), the last startup message received is:
Disconnected SDP Channel
this can help to understand?
can I send you PM?
@Paolo
I believe some software app interfered with my bluetooh communications, ’cause I was able to send perfectly for a while, until I reset the device, so I think the problems are inside my apparatus configurations.
I call you if discover something.
Regards
@Lemorlenny
Okay. No you can’t send me a PM here. Either use the comments or send me an email at kristianl@tkjelectronics.dk
Do you think this code can work on Arduino DUE directly….
should I use SPP, BTD, Message and compile them with USB host for Arduino DUE ?
I am new to arduino and need your advise.
@Mohammad Hefny
No it can’t be used with the Due directly as the usb host functionality is much different, but it shouldn’t be that difficult to port the different bluetooth libraries I created.
using vztec vz-bt2279
i get the following error :
SPP Bluetooth Library Started
Bluetooth Dongle Initialized
HCI Reset complete
Local Bluetooth Address: 00:15:83:0C:BF:EB
The name is set to: Arduino
Wait For Incoming Connection Request
getConf
BTD Init Failed, error code: 13
it would be better if you can compatible models instead of pictures,
based on your pictures i bought another dongle
output : BTD Init Failed, error code: 13(immediately)
@acs
What do you mean?
It’s impossible to tell if a dongle is supported or not based on a picture. Two dongles might look exactly the same, but one of them might not work. It all depends on the chip inside the dongle.
But since they only cost 1$ you can just buy a couple of them.
A list of dongles that are confirmed to work can be found here: https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information#wiki-Hardware
Hi! how arduino communicate with computer (or mobile phone) via bluetooth? Any example?
@Kapil Saraswat
There is a written description for a Android phone here: http://www.circuitsathome.com/mcu/using-usb-bluetooth-dongle-on-arduino-to-connect-to-android-phone
To tell you how to connect to it with your computer I need to know what OS you are running? Like Windows, Linux, Mac etc.
How can I connect a pendrive through this shield?
@Kapil Saraswat
It’s currently not supported, but it is in development!
sorry to not mentioning os! I use windows os and I dint have android to test the code, thats why I requesting for the PC or Mobile connection. In nokia C1-02 it detect and then it disconnected. Thanks for your reply.
@Kapil Saraswat
Okay. Simply pair with the Arduino. It will then create a new COM-port.
Now download PuTTY: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html, now you are able to select the COM-port and press connect.
I can’t say if your phone is supported or not, but I don’t think so.
@Lauszus
One side I have one arduino board and another side I have computer with bluetooth. Now I want to see the response of arduino in PC linked via bluetooth. Is putty is for bluetooth communication? I think it’s for serial communication. I have lack of hardware so kindly tell me the possible way for testing (also in my place it is hard to find some electronic parts and the online shopping (for arduino) means I wait for least 10 days). Again thanks for your instant reply.
@Kapil Saraswat
SPP is serial communication!! So yes you can use putty with Bluetooth devices too.
If you want to see the debugging messages from you Arduino then you can use any serial terminal you like. You can use Putty as well or the build in serial monitor in the Arduino IDE.
Its working! thanx. But how to develop a thing that uses bi-directional communication? like, send the command to arduino and it send the value of analog signal (e.g. temperature)
thanx
@kapil saraswat
You could simply send a speciel character to the Arduino and it then responds with the analog reading.
If you want to write your own Android app, you can have a look at this app: https://github.com/TKJElectronics/BalanduinoAndroidApp I use to control my balancing robot.
Q: I have a cheap JY-MCU model that works is connected to the Arduino via the TX and RX ports. Will the code work for such a connection as well ?
Q2: I just want two things from my remote: let’s say that when I send the value “1″ via terminal, the wheels go forward, and for “2″ the wheels go backwards. What is the part of the code that does that (or something similar) in this library ?
Sorry for stupid questions but I’m a noob
@Tuomas
This code actually does what’s inside a Bluetooth module like that. The reason why I wrote it was because you don’t have to use a hardware UART and I were already using the Bluetooth dongle for communication with a Wii and a PS3 controller.
I think you have misunderstood what this library is all about. It’s simply let you send data to and from the Arduino via Bluetooth.
If you want your robot to do react on a certain character, then have a look at these lines for my balancing robot: https://github.com/TKJElectronics/BalancingRobotArduino/blob/master/BalancingRobotArduino.ino#L217-L281.
but you can do something similar
Hi! Is there any chance that this library could be changed to inherit from the Stream Library? That would make a lot of my coding easier, and it seems as though it would be a thing that would be required in the long run, if this library is to continue to be the de-facto standard Arduino USB library.
@Frederik Juul
I havn’t looked in to it, but that would certainly be a good idea.
Do you got any experience with it?
@Frederik Juul
Actually the main reason I havn’t used it is that you need to send the characters in one large string as ofter as possible or you would have to poll the endpoint in order to prevent the Bluetooth communication to work.
Hi Lauszus,
This is what I want to achieve. I have a separate circuit where I blink an Led with a particular sequence. This sequence represents encoded data. I want to be able to sense this pattern with a photo detector and decode the data from the led blink, and then I want to send this decoded data via bluetooth to my android device. I am a newbie to programming on a board, however I have programmed on Android. Do you think it is possible to achieve what I want with an Arduino. I have ordered the board, but they have still not delivered it. So I am still in the learning phase of my project, contemplating the problems I might run into. Do you think it is a better idea to collate and decode the entire data on the board itself and send it to the android in one go is a better idea? or should I send the information on the fly from the sensor to the android device and decode it in my Android code..please help! Sorry I have posted the same thing on the other forum as well
@xenonforlife
I think it would work better if you used a IR LED modulated at a specific frequency and then use an IR receiver to receive the data, by doing that you will filter out any noise. See this blog post: http://blog.tkjelectronics.dk/2012/03/attinyremote/ and this library: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html.
I would decode the data on the Arduino and then send the decoded command to the Android phone.
hi all,my Bluetooth dongle worked fine two weeks ago but now i have the error btd initialization failed error 15,please help
@mohmad
Please post the full error messages, but I think it’s a hardware problem if it just suddenly stops working. Try a different dongle.
HI i already replaced the dongle ,this is the error:- getDevDescr
BTD Init Failed, error code: 15
@mohmad
Okay. I don’t think you can do anything about it and dongles are so cheap anyway.
can you tell me whats wrong?
@mohmad
No, it could be a lot of different things.
@Lauszus Thank you so much for your reply. The thing is I want to be able to use visible light communication for my project and study the behavior of the same. I just received my board today and started playing with it right away. I am being able to send and receive signals between my Android phone and the Arduino board with the phone connected to the board with a usb cable. What I want to know would I need to change my Android side code if I want to use a bluetooth dongle instead? Will my FileInputStream object still be able to receive the data in the similar way? Since now(according to the SPP sample sketch) I will no longer be using adk.RcvData or adk.SndData, will my Android code remain the same as well or do I need to get a bluetooth socket and get an Input/Output Stream from that socket? I am in doubt because the bluetooth dongle is being inserted in the usb port of the board.
@Lauszus I just checked the code for Blueterm and it does use bluetooth sockets for communication. What I understand is I cannot seamlessly plug in/out my bluetooth dongle without affecting communication with the Arduino board. Please correct me if I am wrong.
@xenonforlife
You should check out my Android app for my balancing robot (see Kickstarter: http://www.kickstarter.com/projects/tkjelectronics/balanduino-balancing-robot-kit).
And here is the relevant java code: https://github.com/TKJElectronics/BalanduinoAndroidApp/blob/master/src/com/tkjelectronics/balanduino/BluetoothChatService.java.
@xenonforlife
Of course it stops working if you plug out the Bluetooth dongle from the USB Host Shield.
@Lauszus Ya ofcourse, but what I meant was something like in the IOIO, where I can plug out the BT dongle and plug in the usb cable and vice versa without any disruption, thats what I actually meant, sorry for the confusion.
@xenonforlife
Yes that is possible. You just need to write code both for the Bluetooth connection and the ADK connection. It shouldn’t be that difficult.
Hey @Lauszus!
I want to build a bluetooth connection between my android phone and my Arduino, using the USB shield with a Bluetooth dongle for great connection range. In the end i want to controle the arduino with my phone (like you RGB light project only with a greater range).
-- where do I look to find all the ansewers involving in that project ?? programming an app for my phone, the arduino code and so on?
@Nichlas
You should check out the app I use to control our Balancing robot: http://www.kickstarter.com/projects/tkjelectronics/balanduino-balancing-robot-kit. And here is the relevant java code from the app: https://github.com/TKJElectronics/BalanduinoAndroidApp/blob/master/src/com/tkjelectronics/balanduino/BluetoothChatService.java.
The best advice I can give you is just start reading other peoples code and use google a lot! Whenever I need to implement something I simply google it, since I’m no expect at Android programming.
Can Bluetooth be used with one host and several clients that can communicate to the host at the same time? I’d like to build a star network of Arduino devices that communicate wirelessly, using Bluetooth or some other system.
@the_ether
At the current time an Arduino can’t talk to another Arduino, but you can connect multiple devices to the Arduino -- see: https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/Bluetooth/SPPMulti/SPPMulti.ino.
If you want to Arduinos to talk to eachother, then take a look at the following code: https://github.com/felis/Arduino-Bluetooth.
@Lauszus
Thanks for the reply. I don’t understand how you can say that Arduinos can’t talk together but yet suggest I look at some code that allows them to talk together.
But at any rate, since posting this I’ve discovered Xbee. Zigbee would seem better suited for a mesh network than Bluetooth. Thanks anyway.