After spending a lot of time, I found out how to connect one BT device and make Pi read data. I used the Bluetooth library and this is the code I wrote to connect two devices:
Code: Select all
import bluetooth, subprocess
nearby_devices = bluetooth.discover_devices(duration=4, lookup_names=True, flush_cache=True, lookup_class=False)
print nearby_devices
addr1 = "XX:XX:XX:XX"
port1 = 1
passkey = "1234"
addr2 = "XX:XX:XX:XX"
port2 = 2
passkey = "1234"
subprocess.call("kill -9 'pidof bluetooth-agent'", shell=True)
status = subprocess.call("bluetooth-agent" + passkey + "&", shell=True)
try:
s1 = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s1.connect((addr1,port1))
data = s1.recv(1024)
print data
subprocess.call("kill -9 'pidof bluetooth-agent'", shell=True)
s1.close()
except bluetooth.btcommon.BluetoothError as err:
print "Error"
try:
s2 = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s2.connect((addr2,port2))
data = s2.recv(1024)
print data
s2.close()
except bluetooth.btcommon.BluetoothError as err:
print "Error"
Code: Select all
rfcomm0 {
bind yes;
device XX:XX:XX:XX;
channel 1;
comment "Module 1";
}
rfcomm1 {
bind yes;
device XX:XX:XX:XX;
channel 2;
comment "Module 2";
}
This is the Arduino code:
Code: Select all
#include <SoftwareSerial.h>
SoftwareSerial btSerial(10, 11); // TX, RX
void setup() {
//Setup and flush the serials to begin
btSerial.begin(9600);
Serial.begin(9600);
btSerial.flush();
Serial.flush();
}
void loop() {
float data = 150.25; //Just a constant for now. To be replaced with sensor data
String sendData = "<" + String(data, 2) + ">";
//Convert to byte array
char charArray[sendData.length() + 1];
sendData.toCharArray(charArray, sendData.length()+1);
btSerial.write(charArray);
}