I want to connect an Android phone and an Arduino Mega 2560 with bluetooth (JY-MCU) to open or close LED. Here's my Arduino code:
#include <SoftwareSerial.h>
#define arduinoRx 2
#define arduinoTx 3
int gelen_veri;
int LedCikis = 8;
SoftwareSerial bluetooth(arduinoRx,arduinoTx);
void setup()
{
bluetooth.begin(9600);
}
void loop()
{
if(bluetooth.available()>0)
{
gelen_veri=bluetooth.read();
switch(gelen_veri)
{
case 'A' :
digitalWrite(LedCikis,HIGH);
break;
case 'K' :
digitalWrite(LedCikis,LOW);
break;
default:
break;
}
}
}
In addition I have Android code:
onlight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
// String msg = "A\n";
// mmOutputStream.write(msg.getBytes()); // transmitter nesnemize 'A' karakterini ilettik.
mmOutputStream.write('A');
} catch (IOException ex) {
Log.e("hata", ex.getMessage());
}
}
});
offlight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mmOutputStream.write('K'); // aynı şekilde transmitter nesnemize 'K' karakterini ilettik.
} catch (IOException ex) {}
}
});
}
When I debug my Android code everything is normal. But it doesn't work. Help me please.
Do you know blueArduıno? You can try and test your program & bluetooth devıce to understand where is the problem.
void findDevice() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //daha önceden eşleşmiş cihazların listesi alındı
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("HC-06")) // JY MCU ; bizim bluetooth modulumuzun default ismi.
{
mmDevice = device; // JY-MCU bizim mmDevice nesnesimiz oldu .
break;
}
}
myLabel.setText("Bluetooth Device Found");
}
}
And
void connectBT() throws IOException {
try {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("20:13:05:06:54:98");
// Benim bluetooth modulumun MAC adresi.
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
// Standard UUID. Çok büyük ihtimalle sizinde alacağınız modulün UUID numarası aynı olacaktır
mmSocket = device.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
}
they are my connection methods. As debug result of android is normal, i thought that arduino code has any problem or my bluetooth device. How can i understand where is the problem???
If you are using your phone did you use any bluetooth api ?
Anyway you can try the following
Download Bluetooth chat source which is widely available
https://www.google.com.sg/search?q=bluetooth+chat+&oq=bluetooth+chat+&aqs=chrome..69i57j0l3.2172j0&sourceid=chrome&ie=UTF-8#q=bluetooth+chat+source
OR use bluetooth SPP from android market
Install and test by sending characters from the send message to test for connectivity .
Subsequently you can read through the example and get a feel of using the bluetooth api .
You can do so by using bluetoth spp from android market or google bluetooth sample code (bluetoothchat) to test whether e issues is with android code or arduino.
Related
I am making an android app on Android Studio that writes serial data from the app, and transfers it to my Mac laptop via Bluetooth. I have seen code from this very helpful stack overflow answer but I'm unsure where this output goes. The following code is in my OnCreate in my MainActivity.java.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
String mac = "D0:88:0C:80:42:2B";
BluetoothDevice device = adapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
// Get a BluetoothSocket to connect with the given BluetoothDevice
BluetoothSocket socket = null;
OutputStream out = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
System.out.println(socket);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.connect();
//now you can use out to send output via out.write
for (int i = 0; i < 150; i++){
socket.getOutputStream().write("TESTING BLUETOOTH SERIAL".getBytes());
Thread.sleep(100);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The android phone and Mac are paired before the launch of the app, and the appropriate permissions are given in manifest.xml. I know that the for loop executes socket.getOutputStream().write(...) but I don't know where to look for the output TESTING BLUETOOTH SERIAL on my Mac laptop. I tried looking at the output of /dev/tty.Bluetooth-Incoming-Port but did not find anything. So how can I find this output?
i'm developing a code which lists all paired devices (working till here) and on click on a device whcih are listed in textviews, i want the programm to connect to device programmatically.
So here is myCode:
final View.OnClickListener onclicklistener = new View.OnClickListener() {
#Override
public void onClick(View view) {
index_connection=view.getId();
try {
btSocket=devices[index_connection].createInsecureRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
Toast.makeText(Connection.this, "Connected to "+devices[index_connection].getName(),Toast.LENGTH_LONG);
} catch (IOException e1) {
Toast.makeText(Connection.this, "Not connected!",Toast.LENGTH_LONG);
e1.printStackTrace();
}
}
}
};
So onclick i'm getting the ID of the Textview which is equal with the index of the device i saved into an array. But now on clicking it does not create any connection (and yes, the other device has Bluetooth activated).
The code throws an Exception if i'm getting the device UUID from the Telephony manager:
myUUID = UUID.fromString(tManager.getDeviceId());
The exception says: java.lang.SecurityException: getDeviceId: The user 10284 does not meet the requirements to access device identifiers.
If i try to create the UUID "fromString" i don't get an exception, but it doesn't connect either.
Best regars,
flar2000
Try this as your UUID, set it like:
private final string MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";
Then you can create your connection using ServiceRecord.
BluetoothDevice mDevice;
Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
for (BluetoothDevices device : devices) {
if (device.getAdress().equals("YOUR DEVICE ADRESS HERE")) {
mDevice = device;
break;
}
}
BluetoothSocket mSocket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
mSocket.connect();
Don't forget to declare on your manifest the bluetooth permission.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Current I am working on OBDII. While in bluetooth discovery to connect obd, How I determine which device is obd and which device is normal bluetooth device.Because I want auto connect my app with obd.
Is there any common characteristic of obd device which help me to determine this is OBD device?
My Code which I am trying for pairing obd device as per name.
//Register receiver for bluetooth discovery
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismiss progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found for pair
try {
// Here I want to know device is obd or not?
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Make pair of obd device as per name:
if (device != null && !device.getName().equals("")) {
LogUtils.LOGE("NEW DEVICE", device.getName());
if (device.getName().equals(OBD_DEVICE_NAME_ONE) ||
device.getName().equals(OBD_DEVICE_NAME_TWO) ||
device.getName().equals(OBD_DEVICE_NAME_THREE)) {
pairDevice(device);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
//Send pairing request to OBD Device
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
After Pairing OBD Device with name, It will autoconnect and work fine.
Only good way to find out, is to connect and to send:
ATI
Which will return a ID, which always contain ELM327.
We have a Bluegiga Bluetooth module that is set up to work as hands free device.
After initial pairing, I need my application to initiate connection to it via HFP programmatically. Can this be achieved in Android?
Using hidden api works for me!
// get default bluetooth adapter
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
// get bounded device on Android
Set<BluetoothDevice> devices = mAdapter.getBondedDevices();
if (devices.size() > 0) {
for (Iterator<BluetoothDevice> it = devices.iterator(); it.hasNext();) {
BluetoothDevice device = it.next();
// treat the device the default buletooth device you needed
mCurrentDevice = device;
// break;
}
} else {
return;
}
// another method to get headset(HFP) profile
mAdapter.getProfileProxy(mContext, new BluetoothProfile.ServiceListener() {
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.e("log", "headset proxy connected");
try {
BluetoothHeadset mCurrentHeadset = (BluetoothHeadset) proxy;
// check whether or not current device hfp is connected or not, if not,
// try to connect the channel between phone and device using hidden api
if (mCurrentHeadset.getConnectionState(mCurrentDevice) != BluetoothHeadset.STATE_CONNECTED) {
Method connectMethod = mCurrentHeadset.getClass().getMethod("connect", mCurrentDevice.getClass());
connectMethod.setAccessible(true);
Boolean returnValue = (Boolean) connectMethod.invoke(proxy, mCurrentDevice);
Log.e("log", "headset proxy connected " + returnValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(int profile) {
Log.e(LogTag.TAG, "headset profile disconnected");
}
}, BluetoothA2dp.HEADSET);
I am trying to connect to a BLE devices based on CC2540 from TI (I have the keyfob from TI, and another device from connectblue OLP425) with my Motorola RAZR, the only succes I had so far is an app named Propagation on the market that I don't have access to the sources.
I tried to connect to the device with this code but the biggest thing I don't understand is the UUID,
I downloaded an app on a iPad 3 and I found a device has the following UUID
00000000-0000-0000-ff31-1a064f8c5966
private static final UUID SPP_UUID = UUID.fromString("00000000-0000-0000-ff31-1a064f8c5966");
BluetoothDevice bd =BluetoothAdapter.getDefaultAdapter().getBondedDevices().iterator().next();
//I only have I device paired that is the Bluetooth Low Energy Device so using the first Device returned by the iterator is fine.
try {
BluetoothSocket bs = bd.createRfcommSocketToServiceRecord(UUID);
bs.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
All I get is a Service discovery failed in logcat
In almost all the example everyone is using
00000000-0000-1000-8000-00805f9b34fb
If I go further in the app it syas that the battery service is UUID 0x180f
I would just like to create an app the read the value of this service which is a simple decimal value
anyone has any succes pairing with a BLE device in the past?
thank you
Jonathan
I've been able to connect to my CC2540 with the Heart Rate Monitor.
I flashed the firmware using the CCDebugger and using 0000180d-0000-1000-8000-00805f9b34fbas the UUID i've been able to read a value.
Using the Motorola_BLE_profile sample app with some modifications.
primaryServices = mGattService.getGattPrimaryServices(device);
if (primaryServices == null) {
String message = "Connection failed !";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
return;
}
for (i = 0; i < primaryServices.length; i++) {
Log.v(TAG, "primary service " + primaryServices[i]);
if (primaryServices[i].equalsIgnoreCase(hrmUUID)) {
try {
status = mGattService.connectGatt(device, hrmUUID, callback1);
if (status == true){
mDevice = device;
mLeState = CONNECTING;
BluetoothLeReceiver.isDevicePickerPending = false;
} else {
String message = "Connection failed !";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(TAG,"Exception while calling gatt Connect");
}
return;
if (i == primaryServices.length) {
Log.v(TAG,"Primary Service not found");
String message = "Connection failed !";
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}