# Android Bluetooth

**URL:** <https://discourse.processing.org/t/android-bluetooth/27140>\
**Category:** Gallery\
**Created:** [January 17, 2021, 11:33am UTC](https://discourse.processing.org/t/android-bluetooth/27140 "2021-01-17T11:33:17Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![noel](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/noel/32/213_2.png) [@noel](https://discourse.processing.org/u/noel)\
**Post date:** [January 21, 2021, 3:41pm UTC](https://discourse.processing.org/t/android-bluetooth/27140/14 "2021-01-21T15:41:32Z")

</div>

[One more request;](https://discourse.processing.org/t/pwm-dimmer-led-android/25906/4) this time a display of the axis position of a motor. Here the object is drawn in the draw() loop instead of the plot() event, the latest is faster and excellent for wave-line plotting, but not as stable as draw();

> **Code**
>
> - Arduino code (just used for testing, because I don’t have the hardware.
> 
> ```auto
> #include <SoftwareSerial.h>
> 
> SoftwareSerial mySerial(11, 12); // RX, TX
> int value = 0;
> 
> void setup() {
> mySerial.begin(115200); // Set the baudrate equal to HC06 setting
> }
> 
> void loop() {
> mySerial.println(value);
> value++;
> delay(5);
> if(value > 1023) value = 0;
> }
> 
> ```
> 
> - Processing code
> 
> ```auto
> 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;
> Knob knob_1;
> 
> Thread runThread;
> byte[] readBuffer;
> int buffer_index;
> int counter;
> boolean stop_thread, plotting = false, init = true;
> String myString = null;
> String msg = " ";
> String device_name = "HC-05";
> String r_str = " ";
> String t_str;
> String incoming_position = "";
> float px, py, x, y;
> float s_angle = 0;
> float position_in_degree = 0;
> 
> void setup() {
> fullScreen();
> orientation(PORTRAIT);
> bt = new Permission(this, "BLUETOOTH");
> afl = new Permission(this, "ACCESS_FINE_LOCATION");
> knob_1 = new Knob(width/2, height/3, int(width/1.5));
> textAlign(CENTER);
> textSize(70);
> t_str = "Click to connect.";
> textSize(12); // To create a "text width factor",
> float twf = width/textWidth(t_str);
> int f = 6; // Empericaly found 
> textSize(f*twf); // Making it proportional for other screen resolutions
> activity = this.getActivity();
> }
> 
> void draw() {
> if (plotting == false && init) {
> background(150);
> text(t_str, width/2, height/2);
> } else {
> background(100);
> knob_1.render(s_angle);
> fill(255);
> text("Position in Degree: ", width/2, 2*height/3);
> text(int(degrees(s_angle)), width/2, 2*height/3+1.5*textAscent());
> text("RAW Position:", width/2, 3*height/4);
> text(incoming_position, width/2, 3*height/4+1.5*textAscent());
> }
> }
> 
> void mousePressed () {
> if (init) {
> try {
> init = false;
> findBluetooth();
> connect();
> plotting = true;
> fill(0, 0, 90);
> rect(0, 0, width, height); 
> } 
> catch (IOException ex) {
> println(ex);
> }
> }
> }
> 
> void plot(String r_str) {
> if(r_str.length() < 1 || r_str == null) r_str = "0";
> incoming_position = r_str;
> s_angle = map(float(r_str), 0, 1024, 0, TWO_PI);
> }
> 
> class Knob {
> float size, slice, angle;
> PVector center;
> 
> Knob(int x, int y, int diameter) {
> this.center = new PVector(x, y);
> this.size = diameter;
> this.slice = TWO_PI/24; 
> }
> 
> void render(float angle) {
> pushStyle();
> pushMatrix();
> translate(center.x, center.y);
> noFill();
> strokeWeight(size/100);
> stroke(255);
> ellipse(0, 0, size, size);
> float e;
> for (int i = 0; i < 24; i++) {
> if(i % 6 == 0) e = size/18;
> else e = 0;
> line(size*0.41, 0, size*0.47+e, 0);
> rotate(slice);
> }
> rotate(angle);
> line(0, 0, size*0.47, 0);
> popMatrix();
> popStyle();
> }
> }
> 
> 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 = 10; //This is the ASCII code for a lf
> 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);
> }
> }
> 
> ```

 ![receiveclock](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/4/4c05276c339abc897c62e94de9413de138d1be6c.png)

---

_[View the full topic](https://discourse.processing.org/t/android-bluetooth/27140)._
