Processing Android Mode + Android Device + Bluetooth + Arduino

edited February 24 in Android Mode

I usually create my own graphical user interface (custom design) to control an arduino via an android device using an android phone, wherein the GUI and communication was coded in processing android mode. But after upgrades done during the development of processing, a problem arise. The code that I created does not run the GUI on the later versions anymore.

My previous codes using Bluetooth communication was able and still is able to run in processing 2.0b6 and 2.0b7 (old dowloads). The problem on the codes started when I tested it with processing 2.2.1 (old download) states "that the package "android" does note exist". Also problems from existing later version, from processing 2.2.1(new download) untl the last version, states that there is an "error from inside the android tools, check the console".

This was test until February 2017.

I am still currently working on projects using the android device communicating with arduino via bluetooth, and it is still working perfectly. It was fortunate that I did not delete my old versions for testing my codes.

May I know, why did the foundation remove android packages in developing android device communicating via bluetooth? Or does the later versions require a procedure to install android packages.

Are there other ways wherein I could code bluetooth communication using a custom graphic user interface to communicate with arduino using the latest version of processing. Or are there any alternatives wherein I could code making android communicate with arduino designing my own GUI?

«13

Answers

  • I am still currently working on projects using the android device communicating with arduino via bluetooth, and it is still working perfectly

    This is using an older version of Processing as you mention at the beginning of your post?

    May I know, why did the foundation remove android packages in developing android device communicating via bluetooth

    What packages are you referring to? I haven't done any Android programming in Processing 2, so I'm not sure about what changes you are referring to, and how much it has change to the current version available in Processing 3. In regards to the bluetooth features, what library were you using in Processing 2.0b6 and 2.0b7? I wonder if it is available in Processing 3. Just to clarify, I am not from the foundation.

    Are there other ways wherein I could code bluetooth communication using a custom graphic user interface to communicate with arduino using the latest version of processing. Or are there any alternatives wherein I could code making android communicate with arduino designing my own GUI?

    This is a recent post that is related to bluetooth in Android mode:https://forum.processing.org/two/discussion/20007/using-bluetooth-ble-for-downloading-orientation-data#latest I am not sure if you could find a GUI "out of the box" that will interact with other devices via bluetooth. The general concept is that you will build your GUI and you will build your own bluetooth API (or a wrapper from a current API) and connect them in your main program.

    Just to add to this post, can you tell us your OS, Android mode version, Target Android API? Have you consider migrating to Processing 3?

    Kf

  • That is what I meant, creating your own GUI using processing android mode and making it communicate via bluetooth through an android device to an arduino hardware. It worked and still currently working on a windows 7 OS computer, running the program and compiling it to an android device using processing android version 2.0b7. But it does not work anymore with later version of processing android like processing 3. If you have any samples or tutorials that I can use to review in order for me to know why my code does not work in later versions, it would be much appreciated, thank you.

  • I understand what you are looking for now. It was not totally clear in your first post. You could have a look at the ketai library's source code. I ran some examples using Processing 3.01. You can install it through Processing's library manager. Visit ketai.org to access its source code. There are also some bluetooth code in the forum using Android API, but I am not sure if you can find a complete application as most people only provide chunks of code demonstrating their problem. If you post your code here or a small running example, some forum goers will be able to test it or provide feedback.

    You could also refer to the Bluetooth library from Android Developers and follow their strategies to create and maintain this type of communication (this will be the latest version of instructions available) or check available open source code by googling "android Bluetooth connection".

    Also here are previous psts in case you haven't explore this option: https://forum.processing.org/two/search?Search=bluetooth

    Kf

  • I was able to make arduino communicate with android via bluetooth without using a ketai library, but only using android imports. I will create and a attach a sample inclusion of the old version of processing where I was able to run the program. What I don't understand is, why is it not working in the later versions where it should still be able to run it there. Some of the basic elements, I got it in this link: http://arduinobasics.blogspot.com/2013/03/arduino-basics-bluetooth-android.html Please give me time to finish the sample and test it before attaching it here in the forum.

  • edited February 22

    Indicated below are the processing codes that run on processing 2.0b7. By this codes, you could create your own custom GUI that communicates with arduino. Just in case you would be able to recreate the code with just using imports in processing android, using almost the same as the the indicated codes.

    Processing Android Mode Codes:

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.widget.Toast;
    import android.view.Gravity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import java.util.UUID;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.bluetooth.BluetoothServerSocket;
    import android.bluetooth.BluetoothSocket;
    
    public BluetoothSocket scSocket;
    
    // *** GUI Initialization *** //
    int i = 150;
    int j = 150;
    int Mode = 1;
    
    int numFrames = 12;
    int frame = 0;
    PImage[] images = new PImage[numFrames];
    
    int circleX1, circleY1; 
    int circleX2, circleY2; 
    int circleSize1 = 100;
    int circleSize2 = 100;
    boolean circleOver1 = false;
    boolean circleOver2 = false;
    
    PImage img1;
    PImage img2;
    
    boolean foundDevice=false;
    boolean BTisConnected=false;
    String serverName = "ArduinoBasicServer";
    
    // *** For GUI Communicaion *** //
    public static final int MESSAGE_WRITE = 1;
    public static final int MESSAGE_READ = 2;
    String readMessage="";
    //String sendLetter="";
    SendReceiveBytes sendReceiveBT=null;
    
    // *** For Bluetooth Features *** //
    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(requestCode==0) {
      if(resultCode == RESULT_OK) {
      background(0);
      ToastMaster ("Bluetooth has been switched ON");
      ToastMaster("Please Reload Application to Connect to Device");
      ToastMaster("Please Reload Application to Connect to Device");
      ToastMaster("Please Reload Application to Connect to Device");
      } else {
      background(0);
      ToastMaster("You need to turn Bluetooth ON !!!");
      ToastMaster("You need to turn Bluetooth ON !!!");
      ToastMaster("You need to turn Bluetooth ON !!!");
      }
      }
    }
    
    BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
    BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
    
    // *** For GUI Communication *** //
    private final Handler mHandler = new Handler() {
      @ Override
      public void handleMessage(Message msg) {
      switch (msg.what) {
      case MESSAGE_WRITE:
      break;
      case MESSAGE_READ:
      byte[] readBuf = (byte[]) msg.obj;
      readMessage = new String(readBuf, 0, msg.arg1);
      break;
      }
      }
    };
    
    // *** For GUI Setup *** //
    void setup() {
      background(0);
      orientation(PORTRAIT);
      size(displayWidth,displayHeight); //Resolution Size
      frameRate(12);
    
      circleX1 = width/2;
      circleY1 = (height/2)+55;
      circleX2 = width/2;
      circleY2 = (height/2)-55;
      ellipseMode(CENTER);
    
      images[0] = loadImage("Loader.1.png");
      images[1] = loadImage("Loader.2.png");
      images[2] = loadImage("Loader.3.png");
      images[3] = loadImage("Loader.4.png");
      images[4] = loadImage("Loader.5.png");
      images[5] = loadImage("Loader.6.png");
      images[6] = loadImage("Loader.7.png");
      images[7] = loadImage("Loader.8.png");
      images[8] = loadImage("Loader.9.png");
      images[9] = loadImage("Loader.10.png");
      images[10] = loadImage("Loader.11.png");
      images[11] = loadImage("Loader.12.png");
    
      img1 = loadImage("SwitchOff.png");
      img2 = loadImage("SwitchOn.png");
    
      background(0);
    
    // *** For Bluetooth Features *** // 
      if (!bluetooth.isEnabled()) {
      Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(requestBluetooth, 0);
      }
    
      if (bluetooth.isEnabled()) {
      registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
      registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    
      if (!bluetooth.isDiscovering()) {
      bluetooth.startDiscovery();
      }
      }
    }
    
    // *** GUI Proper Draw Setup *** //
    void draw() {
       if(foundDevice) {
      if(BTisConnected){
      update(mouseX, mouseY);
      background(0);
    
      if(circleOver1 && mousePressed == true){
        Mode = 1;
        byte[] myByte = stringToBytesUTFCustom("B");
        sendReceiveBT.write(myByte);
      } else if(circleOver2 && mousePressed == true){
        Mode = 2;
        byte[] myByte = stringToBytesUTFCustom("A");
        sendReceiveBT.write(myByte);
      }
    
      if (Mode == 1) {
        image(img1,(width/2)-60,(height/2)-120);
      } else if (Mode == 2) {
        image(img2,(width/2)-60,(height/2)-120);
      }
    
      } else {
    
      if (j == 0) {
      background(0);  
      text("Target Device not Found", (width/2)-80, height/4);
      } else {
      background(0);
      frame = (frame+1) % numFrames;
      image(images[frame],(width/2)-80,(height/2)-80);
      text("Searching for Target Device", (width/2)-70, height/4);
      j = j-1;
      }
    
      }
      } else {
    
      if (i == 0) {
      background(0);  
      text("No Bluetooth Device Found", (width/2-70), height/4);
      } else {
      background(0);
      frame = (frame+1) % numFrames;
      image(images[frame],(width/2)-80,(height/2)-80);
      text("Searching for Bluetooth Device", (width/2)-70, height/4);
      i = i-1;
      }
    
      }
    }
    
    // *** For Bluetooth Features *** //
    public class myOwnBroadcastReceiver extends BroadcastReceiver {
      ConnectToBluetooth connectBT;
      @Override
      public void onReceive(Context context, Intent intent) {
      String action=intent.getAction();
    
      if(BluetoothDevice.ACTION_FOUND.equals(action)){
      String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
      BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      foundDevice=true;
    
      if(discoveredDeviceName.equals("HMSoft")) {//name of device 
      ToastMaster("Connecting you Now !!!");
      unregisterReceiver(myDiscoverer);
      connectBT = new ConnectToBluetooth(discoveredDevice);
      new Thread(connectBT).start();
      } else { 
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      }
      }
    
      if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
      ToastMaster("Already CONNECTED with Target Device");
      int counter=0;
      while(scSocket==null){
      }
      BTisConnected=true;
      if(scSocket!=null){
      sendReceiveBT = new SendReceiveBytes(scSocket);
      new Thread(sendReceiveBT).start();
      String red = "r";
      byte[] myByte = stringToBytesUTFCustom(red);
      sendReceiveBT.write(myByte);
      }
      }
      }
    }
    
    // *** for Communication NEW *** //
    public static byte[] stringToBytesUTFCustom(String str) {
      char[] buffer = str.toCharArray();
      byte[] b = new byte [buffer.length << 1];
      for (int i = 0; i < buffer.length; i++) {
      int bpos = i << 1;
      b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
      b[bpos + 1] =(byte) (buffer[i]&0x00FF);
      }
      return b;
    }
    
    public class ConnectToBluetooth implements Runnable{
      private BluetoothDevice btShield;
      private BluetoothSocket mySocket = null;
      private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
      public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
      btShield = bluetoothShield;
    
      try{
      mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
      }
      catch(IOException createSocketException){
      Log.e("ConnectToBluetooth", "Error with Socket");
      }
      }
    
      public void run() {
      bluetooth.cancelDiscovery();
    
      try{
      mySocket.connect();
      scSocket=mySocket;
      } catch (IOException connectException){
      Log.e("ConnectToBluetooth", "Error with Socket Connection");
    
      try{
      mySocket.close();
      }
      catch(IOException closeException){
      }
      return;
     }
     }
    
      public BluetoothSocket getSocket() {
      return mySocket;
      }
    
      public void cancel() {
      try {
      mySocket.close();
      } catch (IOException e) {
      }
      }
    }
    
    // *** For GUI Communication *** //
    private class SendReceiveBytes implements Runnable {
      private BluetoothSocket btSocket;
      private InputStream btInputStream = null;
      //;
      private OutputStream btOutputStream = null;
      String TAG = "SendReceiveBytes";
      public SendReceiveBytes(BluetoothSocket socket) {
      btSocket = socket;
      try {
      btInputStream = btSocket.getInputStream();
      btOutputStream = btSocket.getOutputStream();
      }
      catch (IOException streamError) {
      Log.e (TAG, "Error when getting input or output Stream");
      }
      }
    
      public void run () {
      byte[] buffer = new byte [1024];
      int bytes;
      while (true) {
      try {
      bytes = btInputStream.read(buffer);
      mHandler.obtainMessage (MESSAGE_READ, bytes, -1, buffer)
      .sendToTarget();
      }
      catch (IOException e) {
      Log.e(TAG, "Error reading from btInputStream");
      break;
      }
      }
      }
      public void write(byte[] bytes) {  
      try {
      btOutputStream.write(bytes);
      }
      catch (IOException e) {
      Log.e(TAG, "Error when writing to btOutputStream");
      }
      }
      public void cancel() {
      try {
      btSocket.close();
      }
      catch (IOException e) {
      Log.e(TAG, "Error when closing the btSocket");
      }
      }
    }
    
    void ToastMaster(String textToDisplay) {
      Toast myMessage = Toast.makeText(getApplicationContext(),
      textToDisplay,
      Toast.LENGTH_LONG);
      myMessage.setGravity(Gravity.CENTER, 0, 0);
      myMessage.show();
    }
    
    // *** GUI Proper --- Ending Codes --- *** //
    void update(int x, int y) {
      if( overCircle(circleX1, circleY1, circleSize1)) {
        circleOver1 = true;
        circleOver2 = false;
      } else if( overCircle(circleX2, circleY2, circleSize2)) {
        circleOver1 = false;
        circleOver2 = true;
      } else {
        circleOver1 = false;
        circleOver2 = false;
      }
    }
    
    boolean overCircle(int x, int y, int diameter) {
      float disX = x - mouseX;
      float disY = y - mouseY;
      if(sqrt(sq(disX) + sq(disY)) < diameter/2) {
        return true;
      } else {
        return false;
      }
    }
    

    Arduino Codes:

    #include <SoftwareSerial.h>
    
    #define RxPin 4
    #define TxPin 2
    #define DEBUG_ENABLED 1
    
    SoftwareSerial BTSerial(RxPin, TxPin);
    
    int ledPin = 13;
    int Mode = 1;
    
    void setup()
     {
     Serial.begin(9600);
     pinMode(RxPin, INPUT);
     pinMode(TxPin, OUTPUT);
    
     pinMode(ledPin, OUTPUT);
    
     BTSerial.begin(9600);
     }
    
    void loop() {
      char val;
      if (BTSerial.available());{
        val = BTSerial.read();
        if (val == 'A') {
          Mode = 2;
         } else if (val == 'B') {
          Mode = 1;
         } 
      }
        if (Mode == 1){
          digitalWrite(ledPin, LOW);
        } else if (Mode == 2) {
          digitalWrite(ledPin, HIGH);     
      }
        delay(10);
    }
    

    The GUI is executed and tested on a samsung galaxy android phone and is used to turn on a diode connected to pin D13 of an arduino uno. Communication was done via bluetooth via a seeed studion bluetooh shield version 2. If there are any information that you need to know, as long as I know about it, I would be glad to share it.

    Files can be downloaded from my google drive containing the codes but unfortunately I am having a hardttime uploading processing version 2.0b7 where I could run the codes. Link: https://drive.google.com/drive/folders/0B23a7LuYxuDLR0F5UXMyVDZMeFE

  • Please format your code. Press the gear icon to edit your post, then select your code and press ctrl+o. Leave a line above and below your code.

    Kf

  • Thanks for the input, code already formatted. By the way, for worst case scenario, if codes could not work on processing 3, do you have any sample codes on how would I be able to make a code in latest processing version, to make an android GUI to communicate via bluetooth with arduino as shown from the codes above. I already tried everything I could to make the processing code work on processing versio 3, but still no success.

  • May I know why some of the bluetooth processing imports are not working as they used to be in the later versions of processing. Are there any latest samples on how would I be able to make processing android communicate with arduino via bluetooth that works with processing 3?

  • Ketai has some sample code for bluetooth. It should be able to communicate with arduino boards. You could do a search in the forum and explore previous posts of any available code.

    Kf

  • Actually, I am thinking of using android studio using processing core library, the other way around in creating GUI controls for android device to communicate with arduino via bluetooth. I have not used ketai yet but this, what I mentioned is in the tutorial given by the processing. I just don't get it why they did not include bluetooth communication in there tutorials

  • But I will try ketai, if it works, then I will be using it instead.

  • Do you have push button GUI samples and receiving samples using ketai communicating via bluetooth to arduino, ketai samples using bluetooth is very limited.

  • Togglebutton from the Android API is an option. Some discussion here: https://forum.processing.org/two/discussion/comment/69041/#Comment_69041

    Documentation:
    https://developer.android.com/guide/topics/ui/controls.html
    https://developer.android.com/guide/topics/ui/controls/togglebutton.html
    https://developer.android.com/reference/android/widget/ToggleButton.html

    This last one provides available functions to operate your togglebutton.

    How to put everything together? Check this post, specifically @akenaton's second code block. Instead of an editText object, use a toggleButton instance. Don't forget to include proper imports. One thing. Get the GUI elements working first before you attempt to mix your GUI code with B2 code. If you want to keep it simple, you could use the controlP5 library instead. You can see a sample code in the first link in this current post.

    There are also natural buttons in the Android API:
    https://developer.android.com/guide/topics/ui/controls/button.html
    https://developer.android.com/reference/android/widget/Button.html

    If you don't want to use ketai, check Android API info related to bluetooth: https://developer.android.com/guide/topics/connectivity/bluetooth.html

    Kf

  • edited February 24

    everything you posted regarding GUI buttons are just buttons but does not communicate to andruino that makes the LED turn on/off. The links that you sent are very useful, but what I prioritize to be after is with regards to Bluetooth communication.

    Also, the Android API info related to bluetooth was the one I used on the sample code I used above. It works with the old version but does not work with the latter version.

  • edited February 24

    @myrds===

    i know quite nothing about arduino && cannot help you for that neither test your code (though it seems ok); as for blue tooth you have only to adapt your code to P3, i mean knowing that you are not in an activity but in a fragment.Example::

    instead of::

    registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));

    put ::

    this.getActivity().registerReceiver(myDiscoverer, new IntentFilter(.......);

    --- Note also that you can use the blepdroid lib for bluetooth (le) connection

  • Your suggestion akenaton did not work, I am also currently trying to adapt the code to processing 3, but for now, I also do not have success.

    And also with regards to KFs input with the use of ketai, some codes do not work on processing 3, If you could post a working sample code, maybe I would be able to see where I am doing wrong.

  • @myrds=== error code???

  • @myrds=== i have modified (as i said) your code, then simplify (no images, no sendReceive) in order to test: everything is working and i get "no device connected" as expected!

  • edited February 24

    The code I used above is working perfectly with processing 2.0b7. I don't understand why at higher versions, it does not work anymore. Also, the only problem is with the bluetooth communication with an android device. If only the processing foundation can create a library/android package using processing android mode, to be able to make an android device to communicate via bluetooth with arduino, or if possible also, to connect an android device to communicate also with arduino via wi-fi.

    If there will still be no success, maybe I have no choice but to use android studio with a processing core library. Unfortunately, I have no experience coding using android studio.

  • @myrds===

    i have already explained the with P2 you were in AN ACTIVITY and that now you are in A FRAGMENT; and i posted also that i have tested your code (without arduino) modifying it and it compiles && works...

  • edited February 24

    Can you post the code? With comments if possible so that I could analyze? I would like to try and test it here in my end, and if it works, it would be worthwhile :D ... If I could see the difference, maybe I would understand better. I apologize if I could not currently get it. Do you mean adding " this.getActivity(). " to all register?

  • @myrds===

    the code as it is, try to see the differences (and remove comments for images or arduino i have added to test):

                import android.content.BroadcastReceiver;
                import android.content.Context;
                import android.content.Intent;
                import android.content.IntentFilter;
                import android.widget.Toast;
                import android.view.Gravity;
                import android.bluetooth.BluetoothAdapter;
                import android.bluetooth.BluetoothDevice;
                import java.util.UUID;
                import java.io.IOException;
                import java.io.InputStream;
                import java.io.OutputStream;
                import android.os.Handler;
                import android.os.Message;
                import android.util.Log;
                import android.bluetooth.BluetoothServerSocket;
                import android.bluetooth.BluetoothSocket;
                import android.app.Activity;
    
                public BluetoothSocket scSocket;
    
                // *** GUI Initialization *** //
                int i = 150;
                int j = 150;
                int Mode = 1;
    
                int numFrames = 12;
                int frame = 0;
                PImage[] images = new PImage[numFrames];
    
                int circleX1, circleY1; 
                int circleX2, circleY2; 
                int circleSize1 = 100;
                int circleSize2 = 100;
                boolean circleOver1 = false;
                boolean circleOver2 = false;
    
                PImage img1;
                PImage img2;
    
                boolean foundDevice=false;
                boolean BTisConnected=false;
                String serverName = "ArduinoBasicServer";
    
                // *** For GUI Communicaion *** //
                public static final int MESSAGE_WRITE = 1;
                public static final int MESSAGE_READ = 2;
                private static final int RESULT_OK = 1;
                String readMessage="";
                //String sendLetter="";
                SendReceiveBytes sendReceiveBT=null;
    
                // *** For Bluetooth Features *** //
                BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
                Activity act;
    
                @Override
                public void onActivityResult(int requestCode, int resultCode, Intent data) {
                  if(requestCode==0) {
                  if(resultCode == RESULT_OK) {
                  background(0);
                  ToastMaster ("Bluetooth has been switched ON");
                  ToastMaster("Please Reload Application to Connect to Device");
                  ToastMaster("Please Reload Application to Connect to Device");
                  ToastMaster("Please Reload Application to Connect to Device");
                  } else {
                  background(0);
                  ToastMaster("You need to turn Bluetooth ON !!!");
                  ToastMaster("You need to turn Bluetooth ON !!!");
                  ToastMaster("You need to turn Bluetooth ON !!!");
                  }
                  }
                }
    
                BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
                BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
    
                // *** For GUI Communication *** //
                private final Handler mHandler = new Handler() {
                  @ Override
                  public void handleMessage(Message msg) {
                  switch (msg.what) {
                  case MESSAGE_WRITE:
                  break;
                  case MESSAGE_READ:
                  byte[] readBuf = (byte[]) msg.obj;
                  readMessage = new String(readBuf, 0, msg.arg1);
                  break;
                  }
                  }
                };
    
                // *** For GUI Setup *** //
                void setup() {
                  background(0);
                  orientation(PORTRAIT);
                  size(displayWidth,displayHeight); //Resolution Size
                  frameRate(12);
    
                  circleX1 = width/2;
                  circleY1 = (height/2)+55;
                  circleX2 = width/2;
                  circleY2 = (height/2)-55;
                  ellipseMode(CENTER);
    
                  //images[0] = loadImage("Loader.1.png");
                  //images[1] = loadImage("Loader.2.png");
                  //images[2] = loadImage("Loader.3.png");
                  //images[3] = loadImage("Loader.4.png");
                  //images[4] = loadImage("Loader.5.png");
                  //images[5] = loadImage("Loader.6.png");
                  //images[6] = loadImage("Loader.7.png");
                  //images[7] = loadImage("Loader.8.png");
                  //images[8] = loadImage("Loader.9.png");
                  //images[9] = loadImage("Loader.10.png");
                  //images[10] = loadImage("Loader.11.png");
                  //images[11] = loadImage("Loader.12.png");
    
                  //img1 = loadImage("SwitchOff.png");
                  //img2 = loadImage("SwitchOn.png");
    
                  background(0);
    
                // *** For Bluetooth Features *** // 
                  if (!bluetooth.isEnabled()) {
                  Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  startActivityForResult(requestBluetooth, 0);
                  }
    
                  if (bluetooth.isEnabled()) {
                  this.getActivity().registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
                  this.getActivity().registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    
                  if (!bluetooth.isDiscovering()) {
                  bluetooth.startDiscovery();
                  }
                  }
                }
    
                // *** GUI Proper Draw Setup *** //
                void draw() {
                   if(foundDevice) {
                  if(BTisConnected){
                  update(mouseX, mouseY);
                  background(0);
    
                  if(circleOver1 && mousePressed == true){
                    Mode = 1;
                    byte[] myByte = stringToBytesUTFCustom("B");
                    //sendReceiveBT.write(myByte);
                  } else if(circleOver2 && mousePressed == true){
                    Mode = 2;
                    byte[] myByte = stringToBytesUTFCustom("A");
                    //sendReceiveBT.write(myByte);
                  }
    
                  if (Mode == 1) {
                    //image(img1,(width/2)-60,(height/2)-120);
                  } else if (Mode == 2) {
                    //image(img2,(width/2)-60,(height/2)-120);
                  }
    
                  } else {
    
                  if (j == 0) {
                  background(0);  
                  text("Target Device not Found", (width/2)-80, height/4);
                  } else {
                  background(0);
                  frame = (frame+1) % numFrames;
                  //image(images[frame],(width/2)-80,(height/2)-80);
                  text("Searching for Target Device", (width/2)-70, height/4);
                  j = j-1;
                  }
    
                  }
                  } else {
    
                  if (i == 0) {
                  background(0);  
                  text("No Bluetooth Device Found", (width/2-70), height/4);
                  } else {
                  background(0);
                  frame = (frame+1) % numFrames;
                //image(images[frame],(width/2)-80,(height/2)-80);
                  text("Searching for Bluetooth Device", (width/2)-70, height/4);
                  i = i-1;
                  }
    
                  }
                }
    
                // *** For Bluetooth Features *** //
                public class myOwnBroadcastReceiver extends BroadcastReceiver {
                  ConnectToBluetooth connectBT;
                  @Override
                  public void onReceive(Context context, Intent intent) {
                  String action=intent.getAction();
    
                  if(BluetoothDevice.ACTION_FOUND.equals(action)){
                  String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
                  BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                  foundDevice=true;
    
                  if(discoveredDeviceName.equals("HMSoft")) {//name of device 
                  ToastMaster("Connecting you Now !!!");
                  act.unregisterReceiver(myDiscoverer);
                  connectBT = new ConnectToBluetooth(discoveredDevice);
                  new Thread(connectBT).start();
                  } else { 
                  ToastMaster("Please Turn on Target Device");
                  ToastMaster("Please Turn on Target Device");
                  ToastMaster("Please Turn on Target Device");
                  ToastMaster("Please Turn on Target Device");
                  ToastMaster("Please Turn on Target Device");
                  }
                  }
    
                  if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
                  ToastMaster("Already CONNECTED with Target Device");
                  int counter=0;
                  while(scSocket==null){
                  }
                  BTisConnected=true;
                  if(scSocket!=null){
                  //sendReceiveBT = new SendReceiveBytes(scSocket);
                  new Thread(sendReceiveBT).start();
                  String red = "r";
                  byte[] myByte = stringToBytesUTFCustom(red);
                  //sendReceiveBT.write(myByte);
                  }
                  }
                  }
                }
    
                // *** for Communication NEW *** //
                public static byte[] stringToBytesUTFCustom(String str) {
                  char[] buffer = str.toCharArray();
                  byte[] b = new byte [buffer.length << 1];
                  for (int i = 0; i < buffer.length; i++) {
                  int bpos = i << 1;
                  b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
                  b[bpos + 1] =(byte) (buffer[i]&0x00FF);
                  }
                  return b;
                }
    
                public class ConnectToBluetooth implements Runnable{
                  private BluetoothDevice btShield;
                  private BluetoothSocket mySocket = null;
                  private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
                  public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
                  btShield = bluetoothShield;
    
                  try{
                  mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
                  }
                  catch(IOException createSocketException){
                  Log.e("ConnectToBluetooth", "Error with Socket");
                  }
                  }
    
                  public void run() {
                  bluetooth.cancelDiscovery();
    
                  try{
                  mySocket.connect();
                  scSocket=mySocket;
                  } catch (IOException connectException){
                  Log.e("ConnectToBluetooth", "Error with Socket Connection");
    
                  try{
                  mySocket.close();
                  }
                  catch(IOException closeException){
                  }
                  return;
                 }
                 }
    
                  public BluetoothSocket getSocket() {
                  return mySocket;
                  }
    
                  public void cancel() {
                  try {
                  mySocket.close();
                  } catch (IOException e) {
                  }
                  }
                }
    
                // *** For GUI Communication *** //
                private class SendReceiveBytes implements Runnable {
                  private BluetoothSocket btSocket;
                  private InputStream btInputStream = null;
                  //;
                  private OutputStream btOutputStream = null;
                  String TAG = "SendReceiveBytes";
                  public SendReceiveBytes(BluetoothSocket socket) {
                  btSocket = socket;
                  try {
                  btInputStream = btSocket.getInputStream();
                  btOutputStream = btSocket.getOutputStream();
                  }
                  catch (IOException streamError) {
                  Log.e (TAG, "Error when getting input or output Stream");
                  }
                  }
    
                  public void run () {
                  byte[] buffer = new byte [1024];
                  int bytes;
                  while (true) {
                  try {
                  bytes = btInputStream.read(buffer);
                  mHandler.obtainMessage (MESSAGE_READ, bytes, -1, buffer)
                  .sendToTarget();
                  }
                  catch (IOException e) {
                  Log.e(TAG, "Error reading from btInputStream");
                  break;
                  }
                  }
                  }
                  public void write(byte[] bytes) {  
                  try {
                  btOutputStream.write(bytes);
                  }
                  catch (IOException e) {
                  Log.e(TAG, "Error when writing to btOutputStream");
                  }
                  }
                  public void cancel() {
                  try {
                  btSocket.close();
                  }
                  catch (IOException e) {
                  Log.e(TAG, "Error when closing the btSocket");
                  }
                  }
                }
    
                void ToastMaster(String textToDisplay) {
                  Toast myMessage = Toast.makeText(this.getActivity().getApplicationContext(),
                  textToDisplay,
                  Toast.LENGTH_LONG);
                  myMessage.setGravity(Gravity.CENTER, 0, 0);
                  myMessage.show();
                }
    
                // *** GUI Proper --- Ending Codes --- *** //
                void update(int x, int y) {
                  if( overCircle(circleX1, circleY1, circleSize1)) {
                    circleOver1 = true;
                    circleOver2 = false;
                  } else if( overCircle(circleX2, circleY2, circleSize2)) {
                    circleOver1 = false;
                    circleOver2 = true;
                  } else {
                    circleOver1 = false;
                    circleOver2 = false;
                  }
                }
    
                boolean overCircle(int x, int y, int diameter) {
                  float disX = x - mouseX;
                  float disY = y - mouseY;
                  if(sqrt(sq(disX) + sq(disY)) < diameter/2) {
                    return true;
                  } else {
                    return false;
                  }
                }
    
  • Ok thank you, I will just do some reviews and test then I will give you updates. For the meantime, kindly wait for my feedback.

  • @myrds===

    ok, and if it works (for bluetooth!) do't forget to put answered for others

  • edited February 24

    This is the edited processing code based from your input:

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.widget.Toast;
    import android.view.Gravity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import java.util.UUID;
    //import java.io.IOException;
    //import java.io.InputStream;
    //import java.io.OutputStream;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.bluetooth.BluetoothServerSocket;
    import android.bluetooth.BluetoothSocket;
    import android.app.Activity;
    
    public BluetoothSocket scSocket;
    
    // *** GUI Initialization *** //
    int i = 150;
    int j = 150;
    int Mode = 1;
    
    int numFrames = 12;
    int frame = 0;
    PImage[] images = new PImage[numFrames];
    
    int circleX1, circleY1; 
    int circleX2, circleY2; 
    int circleSize1 = 100;
    int circleSize2 = 100;
    boolean circleOver1 = false;
    boolean circleOver2 = false;
    
    PImage img1;
    PImage img2;
    
    boolean foundDevice=false;
    boolean BTisConnected=false;
    String serverName = "ArduinoBasicServer";
    
    // *** For GUI Communicaion *** //
    public static final int MESSAGE_WRITE = 1;
    public static final int MESSAGE_READ = 2;
    private static final int RESULT_OK = 1;
    String readMessage="";
    //String sendLetter="";
    SendReceiveBytes sendReceiveBT=null;
    
    // *** For Bluetooth Features *** //
    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    Activity act;
    
    //<a href="/two/profile/Override">@Override</a>
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(requestCode==0) {
      if(resultCode == RESULT_OK) {
      background(0);
      ToastMaster ("Bluetooth has been switched ON");
      ToastMaster("Please Reload Application to Connect to Device");
      ToastMaster("Please Reload Application to Connect to Device");
      ToastMaster("Please Reload Application to Connect to Device");
      } else {
      background(0);
      ToastMaster("You need to turn Bluetooth ON !!!");
      ToastMaster("You need to turn Bluetooth ON !!!");
      ToastMaster("You need to turn Bluetooth ON !!!");
      }
      }
    }
    
    BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
    BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
    
    // *** For GUI Communication *** //
    private final Handler mHandler = new Handler() {
      @ Override
      public void handleMessage(Message msg) {
      switch (msg.what) {
      case MESSAGE_WRITE:
      break;
      case MESSAGE_READ:
      byte[] readBuf = (byte[]) msg.obj;
      readMessage = new String(readBuf, 0, msg.arg1);
      break;
      }
      }
    };
    
    // *** For GUI Setup *** //
    void setup() {
      background(0);
      orientation(PORTRAIT);
      size(displayWidth,displayHeight); //Resolution Size
      frameRate(12);
    
      circleX1 = width/2;
      circleY1 = (height/2)+55;
      circleX2 = width/2;
      circleY2 = (height/2)-55;
      ellipseMode(CENTER);
    
      images[0] = loadImage("Loader.1.png");
      images[1] = loadImage("Loader.2.png");
      images[2] = loadImage("Loader.3.png");
      images[3] = loadImage("Loader.4.png");
      images[4] = loadImage("Loader.5.png");
      images[5] = loadImage("Loader.6.png");
      images[6] = loadImage("Loader.7.png");
      images[7] = loadImage("Loader.8.png");
      images[8] = loadImage("Loader.9.png");
      images[9] = loadImage("Loader.10.png");
      images[10] = loadImage("Loader.11.png");
      images[11] = loadImage("Loader.12.png");
    
      img1 = loadImage("SwitchOff.png");
      img2 = loadImage("SwitchOn.png");
    
      background(0);
    
    // *** For Bluetooth Features *** // 
      if (!bluetooth.isEnabled()) {
      Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(requestBluetooth, 0);
      }
    
      if (bluetooth.isEnabled()) {
      this.getActivity().registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
      this.getActivity().registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    
      if (!bluetooth.isDiscovering()) {
      bluetooth.startDiscovery();
      }
      }
    }
    
    // *** GUI Proper Draw Setup *** //
    void draw() {
       if(foundDevice) {
      if(BTisConnected){
      update(mouseX, mouseY);
      background(0);
    
      if(circleOver1 && mousePressed == true){
        Mode = 1;
        byte[] myByte = stringToBytesUTFCustom("B");
        sendReceiveBT.write(myByte);
      } else if(circleOver2 && mousePressed == true){
        Mode = 2;
        byte[] myByte = stringToBytesUTFCustom("A");
        sendReceiveBT.write(myByte);
      }
    
      if (Mode == 1) {
        image(img1,(width/2)-60,(height/2)-120);
      } else if (Mode == 2) {
        image(img2,(width/2)-60,(height/2)-120);
      }
    
      } else {
    
      if (j == 0) {
      background(0);  
      text("Target Device not Found", (width/2)-80, height/4);
      } else {
      background(0);
      frame = (frame+1) % numFrames;
      //image(images[frame],(width/2)-80,(height/2)-80);
      text("Searching for Target Device", (width/2)-70, height/4);
      j = j-1;
      }
    
      }
      } else {
    
      if (i == 0) {
      background(0);  
      text("No Bluetooth Device Found", (width/2-70), height/4);
      } else {
      background(0);
      frame = (frame+1) % numFrames;
    //image(images[frame],(width/2)-80,(height/2)-80);
      text("Searching for Bluetooth Device", (width/2)-70, height/4);
      i = i-1;
      }
    
      }
    }
    
    // *** For Bluetooth Features *** //
    public class myOwnBroadcastReceiver extends BroadcastReceiver {
      ConnectToBluetooth connectBT;
      //<a href="/two/profile/Override">@Override</a>
      @Override
      public void onReceive(Context context, Intent intent) {
      String action=intent.getAction();
    
      if(BluetoothDevice.ACTION_FOUND.equals(action)){
      String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
      BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      foundDevice=true;
    
      if(discoveredDeviceName.equals("HMSoft")) {//name of device 
      ToastMaster("Connecting you Now !!!");
      act.unregisterReceiver(myDiscoverer);
      connectBT = new ConnectToBluetooth(discoveredDevice);
      new Thread(connectBT).start();
      } else { 
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      }
      }
    
      if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
      ToastMaster("Already CONNECTED with Target Device");
      int counter=0;
      while(scSocket==null){
      }
      BTisConnected=true;
      if(scSocket!=null){
      sendReceiveBT = new SendReceiveBytes(scSocket);
      new Thread(sendReceiveBT).start();
      String red = "r";
      byte[] myByte = stringToBytesUTFCustom(red);
      sendReceiveBT.write(myByte);
      }
      }
      }
    }
    
    // *** for Communication NEW *** //
    public static byte[] stringToBytesUTFCustom(String str) {
      char[] buffer = str.toCharArray();
      byte[] b = new byte [buffer.length << 1];
      for (int i = 0; i < buffer.length; i++) {
      int bpos = i << 1;
      b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
      b[bpos + 1] =(byte) (buffer[i]&0x00FF);
      }
      return b;
    }
    
    public class ConnectToBluetooth implements Runnable{
      private BluetoothDevice btShield;
      private BluetoothSocket mySocket = null;
      private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
      public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
      btShield = bluetoothShield;
    
      try{
      mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
      }
      catch(IOException createSocketException){
      Log.e("ConnectToBluetooth", "Error with Socket");
      }
      }
    
      public void run() {
      bluetooth.cancelDiscovery();
    
      try{
      mySocket.connect();
      scSocket=mySocket;
      } catch (IOException connectException){
      Log.e("ConnectToBluetooth", "Error with Socket Connection");
    
      try{
      mySocket.close();
      }
      catch(IOException closeException){
      }
      return;
     }
     }
    
      public BluetoothSocket getSocket() {
      return mySocket;
      }
    
      public void cancel() {
      try {
      mySocket.close();
      } catch (IOException e) {
      }
      }
    }
    
    // *** For GUI Communication *** //
    private class SendReceiveBytes implements Runnable {
      private BluetoothSocket btSocket;
      private InputStream btInputStream = null;
      //;
      private OutputStream btOutputStream = null;
      String TAG = "SendReceiveBytes";
      public SendReceiveBytes(BluetoothSocket socket) {
      btSocket = socket;
      try {
      btInputStream = btSocket.getInputStream();
      btOutputStream = btSocket.getOutputStream();
      }
      catch (IOException streamError) {
      Log.e (TAG, "Error when getting input or output Stream");
      }
      }
    
      public void run () {
      byte[] buffer = new byte [1024];
      int bytes;
      while (true) {
      try {
      bytes = btInputStream.read(buffer);
      mHandler.obtainMessage (MESSAGE_READ, bytes, -1, buffer)
      .sendToTarget();
      }
      catch (IOException e) {
      Log.e(TAG, "Error reading from btInputStream");
      break;
      }
      }
      }
      public void write(byte[] bytes) {  
      try {
      btOutputStream.write(bytes);
      }
      catch (IOException e) {
      Log.e(TAG, "Error when writing to btOutputStream");
      }
      }
      public void cancel() {
      try {
      btSocket.close();
      }
      catch (IOException e) {
      Log.e(TAG, "Error when closing the btSocket");
      }
      }
    }
    
    void ToastMaster(String textToDisplay) {
      Toast myMessage = Toast.makeText(this.getActivity().getApplicationContext(),
      textToDisplay,
      Toast.LENGTH_LONG);
      myMessage.setGravity(Gravity.CENTER, 0, 0);
      myMessage.show();
    }
    
    // *** GUI Proper --- Ending Codes --- *** //
    void update(int x, int y) {
      if( overCircle(circleX1, circleY1, circleSize1)) {
        circleOver1 = true;
        circleOver2 = false;
      } else if( overCircle(circleX2, circleY2, circleSize2)) {
        circleOver1 = false;
        circleOver2 = true;
      } else {
        circleOver1 = false;
        circleOver2 = false;
      }
    }
    
    boolean overCircle(int x, int y, int diameter) {
      float disX = x - mouseX;
      float disY = y - mouseY;
      if(sqrt(sq(disX) + sq(disY)) < diameter/2) {
        return true;
      } else {
        return false;
      }
    }
    

    A lot of errors were eliminated, but one last problem, the android device does not play the app, and does not finish communicating with the android device.

    debug: blendMode(), or this particular variation of it, is not available with this renderer. FATAL EXCEPTION: main Process: processing.test.processing_android_switch, PID: 15502 java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 bqHint=4 (has extras) } in processing.test.processing_android_switch.Processing_Android_Switch$myOwnBroadcastReceiver@36f08946 at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:988) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6934) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.unregisterReceiver(android.content.BroadcastReceiver)' on a null object reference at processing.test.processing_android_switch.Processing_Android_Switch$myOwnBroadcastReceiver.onReceive(Processing_Android_Switch.java:243) at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:978) ... 8 more

    Indicated on the debiug is what is shown after running the sketch. My apologies if I could not detect the errors, it has been a longtime for me using the old version, so not that I am using the new one, I still need to adjust.

  • The code tries to connect to the target device, but suddenly stops after.

  • @myrds===

    error is nullPointerException when you unregister; try to add "act = this.getActivity();" in your setup(); BTW this error means that your device was discovered.

  • Is this what you mean?

    // *** For GUI Setup *** //
    void setup() {
      act = this.getActivity(); //added suggest code
      background(0);
      orientation(PORTRAIT);
      size(displayWidth,displayHeight); //Resolution Size
      frameRate(12);
    

    It didn't work.

  • @myrds===

    add this when you want to unregister, in order to verify that your receiver was registered.

    if(myDiscoverer !=null){ act.unregisterReceiver(myDiscoverer); }else{ println("Receiver === null"); }

  • May I request for you to post the code where to insert it? Im quite confused. Unfortunately I need to sleep now, I'll keep in touch with you again tomorrow, thanks for the help with the codes. I will be posting the working codes as soon as the code for the latest version is already ok and tested, for everyone to make it as reference.

  • edited February 24

    @myrds===

    ok; you have also to check the context;

    add code here::

             if(discoveredDeviceName.equals("HMSoft")) {//name of device 
              ToastMaster("Connecting you Now !!!");
              if(myDiscoverer !=null){
              act.unregisterReceiver(myDiscoverer);
              }else{
               println("Receiver est null"); 
              }
    

    dont know if tomorrow i have time enough to have a look (another problem is that i cannot test really, only looking at the code...)

  • Don't worry, we can do just fine, I just would appreciate if you could reply on this discussion when you have time. If with regarding the testing, I will be the one to test it. So far the codes can already run on a device, unlike before.

    The only problem as of now is it detects the target device, but does not execute the GUI and stops immediately.

    By the way, the latest update that you gave, did not work either.

  • @myrds===

    did you get your toast "connecting you now?"??????

    if(discoveredDeviceName.equals("HMSoft")) {//name of device ToastMaster("Connecting you Now !!!"); if(myDiscoverer !=null){ act.unregisterReceiver(myDiscoverer); }else{ println("Receiver est null"); }

  • That was the same as the code you sent me earlier before your last post that I informed you that did not work, I also tried some in my end but not successful as of now. Still trying to resolve execution problem.

  • edited February 25

    Although the code you gave me did not work, I got and idea from your code to change

    if(found device) {

    to

    if(myDiscoverer != null) {

    and it actually worked. I also removed the last code you sent me on the setup and the latest code you suggested, and it still works.

    I'll confirm a few more tests, and if there will be no problems, I will post the corrected processing code.

  • edited February 25

    I think, I have one final problem, the GUI only connects to the target device ones. If you close the GUI and connect it again with the device, it does not detect the target device anymore. Unless I switch off, switch on the bluetooth again of the bluetooth shield again.

    I think there is a problem with it disconnecting with the target device when closing the running GUI.

  • How do I cancel discovery when closing app?

  • @myrds===

    as you have unregistered your receiver you dont have your gui anymore... question 2: use cancelDiscovery() with condition (isDiscovering()= true) then verify that your receiver is correctly unregistered (==null)

    use this in onPause() && onStop() and in onDestroy()

  • It is still not working, maybe I am using the code wrongly, can you post a partial code of it?

  • @myrds===

    please, post the code you are now using and be more precise about "what is not working" (error code)

  • edited February 26

    This is what I did, for sure I used it wrongly.

      if(discoveredDeviceName.equals("HMSoft")) {//name of device 
      ToastMaster("Connecting you Now !!!");
      if (isDiscovering()=true) {
        onStop();
      }
    

    It says error from inside andoid tools.

  • I think that this would be the last problem, if solved, it may be used as reference for those who want to create there own GUI using processing, communicating with arduino, without external libraries. Just purely processing android mode.

  • edited February 26

    This the part of the code that is incharge for the closure of the socket, but it does not close unless the bluetooth of the arduino turns off wherin the closure was done manually. I don't understand why it does not close after the revising of the codes for processing 3, I think it is looking for something before it executes.

    public void cancel() {
     try {
     mySocket.close();
     } 
     catch (IOException e) {
     }
     }
    }
    
  • edited February 26

    I found the problem but don't know how to fix it.

    At line 348, a problem was stated that:

    The method cancel() from the type Processing_Android_Switch.SendReceiveBytes is never used locally

  • @myrds=== i dont know what code you are exactly using now and cannot help only guessing

  • edited February 26

    This part of the code: Indicated below is the the error:

            // *** For GUI Communication *** //
            private class SendReceiveBytes implements Runnable {
              private BluetoothSocket btSocket;
              private InputStream btInputStream = null;
              private OutputStream btOutputStream = null;
              String TAG = "SendReceiveBytes";
              public SendReceiveBytes(BluetoothSocket socket) {
              btSocket = socket;
              try {
              btInputStream = btSocket.getInputStream();
              btOutputStream = btSocket.getOutputStream();
              }
              catch (IOException streamError) {
              Log.e (TAG, "Error when getting input or output Stream");
              }
              }
    
              public void run () {
              byte[] buffer = new byte [1024];
              int bytes;
              while (true) {
              try {
              bytes = btInputStream.read(buffer);
              mHandler.obtainMessage (MESSAGE_READ, bytes, -1, buffer)
              .sendToTarget();
              }
              catch (IOException e) {
              Log.e(TAG, "Error reading from btInputStream");
              break;
              }
              }
              }
    
              public void write(byte[] bytes) {  
              try {
              btOutputStream.write(bytes);
              }
              catch (IOException e) {
              Log.e(TAG, "Error when writing to btOutputStream");
              }
              }
         // ------ Indicated area of error ------     
              public void cancel() { // indicated line of error
              try {
              btSocket.close();
              }
              catch (IOException e) {
              Log.e(TAG, "Error when closing the btSocket");
              }
              }
            }
         // ------ Indicated area of error -----
    
            void ToastMaster(String textToDisplay) {
              Toast myMessage = Toast.makeText(this.getActivity().getApplicationContext(),
              textToDisplay,
              Toast.LENGTH_LONG);
              myMessage.setGravity(Gravity.CENTER, 0, 0);
              myMessage.show();
            }
    
  • edited February 26

    Indicated error is in between line 42 and 52

    error indicated is "The method cancel() from the type Processing_Android_Switch.SendReceiveBytes is never used locally"

  • @myrds===

    this is not an error, only warning that you are never calling this cancel() method; have you called it? When?

  • actually, I don't know how to fix that part, for that was how it is from the old coding from processing 2, it works as is from the old version, I don't know how to deal with it now. How do I call it without affecting other codes?

  • @myrds=== this warning has nothing to see with P2 or P3; in your "old P2" code can you tell me when you call it?

Sign In or Register to comment.