Android Bluetooth

On request, another example code, displaying the analog read value of an Arduino equipped with a potentiometer and an HC-05 Bluetooth module.

Analog Read
  • Arduino code
#include <SoftwareSerial.h>
#include <Wire.h>

SoftwareSerial mySerial(11, 12); // RX, TX

int value = 0;
int previous_value = 0;

void setup() {
  mySerial.begin(115200); // Set the baudrate equal to HC06 setting
}

void loop() {
  for (int i = 0; i < 32; i++) value += analogRead(0);
  value /= 32;
  if( value != previous_value) mySerial.print(String(value) + '!');
  previous_value = value;
  delay(100);
}
  • Processing code
import android.Manifest; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.os.Build.VERSION_CODES; 
import processing.core.PConstants;
import android.app.Activity; 
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Activity activity;
Permission bt, afl;

Thread runThread;
byte[] readBuffer;
int buffer_index;
int counter;
boolean stop_thread, plotting = false, init = true;

String msg = " ";
String device_name = "HC-05";
String r_str = " ";
String str_1, str_2, str_3;
float px, py, x, y;
int ts_1, ts_2, ts_3;

void setup() {
  fullScreen();
  orientation(LANDSCAPE);
  bt = new Permission(this, "BLUETOOTH");
  afl = new Permission(this, "ACCESS_FINE_LOCATION");
  textAlign(CENTER, CENTER);
  textSize(12);
  str_1 = "Click to connect.";
  str_2 = "8888";
  str_3 = "Analog reading value";
  textSize(12); // Start value to create a "textwidth factor",
  // Making it  proportional for other screen resolutions
  float twf_1 = width/textWidth(str_1);
  float twf_2 = width/textWidth(str_2);
  float twf_3 = width/textWidth(str_3);
  int f_1 = 4; // Empericaly found 
  int f_2 = 11;
  int f_3 = 8;
  ts_1 = int(f_1*twf_1);
  ts_2 = int(f_2*twf_2);
  ts_3 = int(f_3*twf_3);
  fill(255);
  activity = this.getActivity();
}

void draw() {
  if (init) {
    background(150);
    textSize(ts_1); 
    text(str_1, width/2, height/2);
  }
}

void mousePressed () {
  if (init) {
    try {
      init = false;
      findBluetooth();
      connect();
      plotting = true;
      background(0);
      fill(255, 255, 0);
      textSize(ts_3); 
      text(str_3, width/2, height/8);
      textSize(ts_2);
    } 
    catch (IOException ex) {
      println(ex);
    }
  }
}

void plot(String r_str) {
  if (r_str.length() < 1 || r_str == null) r_str =  "0";
  if (plotting) {
    fill(0);
    rect(0, height/3, width, 2*height/3);
    fill(255, 255, 0);
    text(r_str, width/2, 2*height/3);
  }
}

void findBluetooth() {
  mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if (mBluetoothAdapter == null) {
    println("No bluetooth adapter available");
  }
  if (!mBluetoothAdapter.isEnabled()) {
    Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    activity.startActivityForResult(enableBluetooth, 0);
  }
  Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  if (pairedDevices.size() > 0) {
    print("Paired devices MAC Adress:");
    printArray(pairedDevices);
    for (BluetoothDevice device : pairedDevices) {
      print("Paired devices by name:");
      println(device.getName());
      if (device.getName().equals(device_name)) {
        mmDevice = device;
        println("Bluetooth device name found");
        break;
      }
    }
  }
}

void connect() throws IOException {
  UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);        
  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();
  println("Bluetooth connected");
  final byte delimiter = 33; //This is the ASCII code for a ! character
  stop_thread = false;
  buffer_index = 0;
  readBuffer = new byte[1024];
  runThread = new Thread(new Runnable() {
    public void run() {                
      while (!Thread.currentThread().isInterrupted() && !stop_thread) {
        try {
          int bytesAvailable = mmInputStream.available();                        
          if (bytesAvailable > 0) {
            byte[] packetBytes = new byte[bytesAvailable];
            mmInputStream.read(packetBytes);
            for (int i = 0; i < bytesAvailable; i++) {
              byte b = packetBytes[i];
              if (b == delimiter) {
                byte[] encodedBytes = new byte[buffer_index];
                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                final String data = new String(encodedBytes, "US-ASCII");
                plot(data);
                buffer_index = 0;
              } else {
                readBuffer[buffer_index++] = b;
              }
            }
          }
        } 
        catch (IOException ex) 
        {
          stop_thread = true;
        }
      }
    }
  }
  );
  runThread.start();
}

void closeBluetooth() throws IOException {
  stop_thread = true;
  mmOutputStream.close();
  mmInputStream.close();
  mmSocket.close();
  println("Bluetooth stopped");
}

class Permission {
  PApplet parent;
  boolean requestedPortraitImage = false;

  Permission(PApplet pParent, String permissionName) {
    parent = pParent;
    parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
  }

  void onPermissionResult(boolean granted) {
    if (granted)  println("User did grant permission.");
    else println("User did NOT grant permission.");
  }
}

void onPause() {
  try {
    closeBluetooth();
  } 
  catch (Exception ex) {
  }
  super.onPause();
}

void onStop () {
  try {
    closeBluetooth();
  } 
  catch (Exception ex) {
  }
  super.onStop();
}

void onRestart() {
  try {
    findBluetooth();
    connect();
  } 
  catch (IOException ex) {
    println(ex);
  }
}

2 Likes