# Android Bluetooth native code

**URL:** <https://discourse.processing.org/t/android-bluetooth-native-code/27586>\
**Category:** Processing for Android\
**Created:** [February 4, 2021, 3:40pm UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586 "2021-02-04T15:40:34Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 4, 2021, 3:40pm UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/1 "2021-02-04T15:40:34Z")

</div>

hi this code for member was helping what i need how to send 6 controlp5 sliders values to raduino

any one can help???

```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 bp, afl;

Thread runThread;
byte[] readBuffer;
int buffer_index;
boolean stop_thread, init = true;
String device_name = "HC-05";
boolean permissions_granted;
String Str = " "; 
String t_str;
float a, increment = 0.04;
int y;

void setup() {
  fullScreen();
  orientation(LANDSCAPE);
  bp = new Permission(this, "BLUETOOTH");
  afl = new Permission(this, "ACCESS_FINE_LOCATION");
  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 = 4; // Empericaly found 
  textSize(f*twf); // Making it proportional for other screen resolutions
}

void draw() {
  if (init) {
    background(150);
    text(t_str, width/2, height/2);
    strokeWeight(10);
    noFill();
    stroke(50);
    rect(0, 0, width, height);
  } else {
    y = int(80 * sin(a));
    a += increment;
    if (a > TWO_PI) a = 0;
    try {
      sendData();
    }  
    catch (IOException ex) {
    }
  }
}

void mousePressed () {
  if (init) {
    try {
      init = false;
      findBluetooth();
      connect();
      background(80);
      text("Connecting to send.", width/2, height/2);
    } 
    catch (IOException ex) {
      println(ex);
    }
  }
}

void sendData() throws IOException {
  mmOutputStream.write(y);
}

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);
  }
}

```

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 2:36am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/2 "2021-02-05T02:36:20Z")

</div>

this is a start to solve it

[![](https://img.youtube.com/vi/PjxbuSnj8Pk/hqdefault.jpg "13.2: Strings: Split and Join - Processing Tutorial") ](https://www.youtube.com/watch?v=PjxbuSnj8Pk)

[![](https://img.youtube.com/vi/TaPVzWBWqd4/maxresdefault.jpg "13.3: loadStrings() - Processing Tutorial") ](https://www.youtube.com/watch?v=TaPVzWBWqd4)

---

<div class="post-metadata">

**Author:** ![svan](https://avatars.discourse-cdn.com/v4/letter/s/82dd89/32.png) [@svan](https://discourse.processing.org/u/svan)\
**Post date:** [February 5, 2021, 3:16am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/3 "2021-02-05T03:16:58Z")

</div>

For openers, where are the five sliders in the Processing window and where is the Arduino code?

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 4:29am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/4 "2021-02-05T04:29:49Z")

</div>

Hi sir

this is Processing sketch

```auto
import controlP5.*;
import processing.serial.*;
 
ControlP5 cP5a;
ControlP5 cP5b;
ControlP5 cP5c;
ControlP5 cP5d;
ControlP5 cP5e;
ControlP5 cP5f; 
Serial arduino;
 
void setup() {
  size(350,660);
 printArray(Serial.list());
 
  arduino = new Serial(this, Serial.list()[0], 9600);
 
  cP5a = new ControlP5(this);
  cP5a.addSlider("CYCLE_TIME", 999, 1999,999, 10, 10, 255, 35);
  cP5b = new ControlP5(this);
  cP5b.addSlider("PULSE", 55, 455, 55, 10, 55, 255, 35);
cP5c = new ControlP5(this);
  cP5c.addSlider("dely1", 999, 1999,999, 10, 101, 255, 35);
  cP5d = new ControlP5(this);
  cP5d.addSlider("dely2", 55, 455, 55, 10, 155, 255, 35);

cP5e = new ControlP5(this);
  cP5e.addSlider("de1", 999, 1999,999, 10, 199, 255, 35);
  cP5f = new ControlP5(this);
  cP5f.addSlider("de2", 55, 455, 55, 10, 244, 255, 35);

}
 
void draw() {
  background(0);
 
  }
 
void controlEvent(ControlEvent theEvent) {
  if(theEvent.isController()) {
 
 print("control event from : "+theEvent.getController().getName());
 println(" value : "+theEvent.getController().getValue());
 
 if(theEvent.getController().getName()=="CYCLE_TIME") {
   int val1 = int(theEvent.getController().getValue());
   arduino.write("a" + val1+"\n");
 
 }
 
 if(theEvent.getController().getName()=="PULSE") {
   int val2 = int(theEvent.getController().getValue());
   arduino.write("b" + val2+"\n" );
   }
  }

 
 

// print("control event from : "+theEvent.getController().getName());
// println(", value : "+theEvent.getController().getValue());
 
 if(theEvent.getController().getName()=="dely1") {
   int val1 = int(theEvent.getController().getValue());
   arduino.write("c" + val1+"\n");

  }

  

 
 if(theEvent.getController().getName()=="dely2") {
 int val2 = int(theEvent.getController().getValue());
 arduino.write("d" + val2+"\n" );
  
 

} 

 if(theEvent.getController().getName()=="de1") {
   int val2 = int(theEvent.getController().getValue());
   arduino.write("e" + val2+"\n" );

 }
if(theEvent.getController().getName()=="de2") {
   int val2 = int(theEvent.getController().getValue());
   arduino.write("f" + val2+"\n" );

}

}

```

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 4:31am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/5 "2021-02-05T04:31:53Z")

</div>

[svan](https://discourse.processing.org/u/svan)

Hi Sir

Arduino code

```auto
void bob() {  
  
 
  
     if (Serial.available() >= 1)
 delay (1);
  {
    int value2;
    char command = Serial.read();
    switch (command)
    {
    case 'a': value2 = Serial.parseInt();
      CYCLE_TIME = value2;
     Serial.print ( CYCLE_TIME); 
    
     
      
      break;

    case 'b': value2 = Serial.parseInt();
     TX_PULSE = value2;
     Serial.print ( TX_PULSE); 
      {
       
      break;
case 'c': value2 = Serial.parseInt();
    del = value2;
     Serial.print ( del); 
     
      break;

   
     }
   case 'd': value2 = Serial.parseInt();
    del1 = value2;
     Serial.print ( del1); 
     
      break;
 }
   case 'e': value2 = Serial.parseInt();
    del2 = value2;
     Serial.print ( del2); 
     
      break;
    }
   case 'f': value2 = Serial.parseInt();
    del3 = value2;
     Serial.print ( del3); 
     
      break; 
    
    }
  }

```

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 4:39am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/6 "2021-02-05T04:39:06Z")

</div>

[svan](https://discourse.processing.org/u/svan)

Thanks for your response this is screenshot testing 2 sliders over processing serial

![jafal](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/b/bb7ae1ed7515cef0058803c00ad323c7f21410be.jpeg)

---

<div class="post-metadata">

**Author:** ![svan](https://avatars.discourse-cdn.com/v4/letter/s/82dd89/32.png) [@svan](https://discourse.processing.org/u/svan)\
**Post date:** [February 5, 2021, 4:52am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/7 "2021-02-05T04:52:10Z")

</div>

1. Can you combine the slider code and the bluetooth code so that we see five sliders in the bluetooth window?
2. Arduino code usually has a setup() and loop() ; not bob()?

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 5:00am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/8 "2021-02-05T05:00:15Z")

</div>

Can you combine the slider code and the bluetooth code so that we see five sliders in the bluetooth window? That what i am asking for help and i don’t know how to do it

. Arduino code usually has a setup() and loop() ; not bob()?

bob()? is a function name

---

<div class="post-metadata">

**Author:** ![svan](https://avatars.discourse-cdn.com/v4/letter/s/82dd89/32.png) [@svan](https://discourse.processing.org/u/svan)\
**Post date:** [February 5, 2021, 6:08am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/9 "2021-02-05T06:08:26Z")

</div>

It appears that you are not ready to delve into bluetooth communication. First you should probably learn how to create a window on an Android app.

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [February 5, 2021, 7:55am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/11 "2021-02-05T07:55:12Z")

</div>

You should really try the search function on the forum, this is probably the third android Bluetooth post this month, and yes sliders have already been discussed and solutions have already been found.

---

<div class="post-metadata">

**Author:** ![paulgoux](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@paulgoux](https://discourse.processing.org/u/paulgoux)\
**Post date:** [February 5, 2021, 9:37am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/14 "2021-02-05T09:37:38Z")

</div>

Just wanted to make sure sure your questions hadn’t been answered in previous posts. I am not familiar with the android Bluetooth. Anyways hopefully you’ll get your solution.

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 5, 2021, 9:44am UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/15 "2021-02-05T09:44:22Z")

</div>

> [@paulgoux](#):
>
> hopefully you’ll get your solution.

Thank you…

---

<div class="post-metadata">

**Author:** ![jafal](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jafal/32/19112_2.png) [@jafal](https://discourse.processing.org/u/jafal)\
**Post date:** [February 6, 2021, 7:42pm UTC](https://discourse.processing.org/t/android-bluetooth-native-code/27586/16 "2021-02-06T19:42:30Z")

</div>

solved here

> [@Unexpected behavior of char\[\] in print / println](https://discourse.processing.org/t/unexpected-behavior-of-char-in-print-println/27609):
>
> Hey. While working with an array of characters I checked the value of the array members by using the print / println function. The code boils down to : void setup() { char[] ch = new char[2]; ch[0] = ‘0’; ch[1] = ‘0’; print("two statements: "); println(ch[0] + ch[1]); println("one statement: " + ch[0] + ch[1]); exit(); } which on the console delivers: two statements: 96 one statement: 00 I am able to indicate the origine of the 96 as being twice de ASCII code of ‘0’ (zero) but the diffe…
