Étape 4: Traitement et Android
Dans la plupart des cas, vous devez suivre le wiki pour tout mettre en place, mais j’ai aussi inclus mes propres instructions ci-dessous. J’ai ont simplifié les pièces que je pense que le wiki fait un bon travail d’expliquer et ont étendu sur d’autres parties. J’ai également ajouté des conseils supplémentaires que j’ai utilisé pour obtenir le mien de travailler. Pas tout a fonctionné parfaitement chaque étape de la voie, alors soyez patient. J’ai essayé d’inclure tout ce que j’ai fait pour faire avancer les choses de travail chaque fois que j’ai frappé un barrage routier. Remarque : Si vous utilisez un Mac, pas toutes mes instructions s’appliqueront à vous et je vous suggère de plus suivent de près la page wiki.
Voici le lien pour la page wiki consacrée au traitement avec l’Android :
http://wiki.Processing.org/w/Android
Débogage USB
Une fois que vous avez installé le traitement, le SDK Android et toutes les plateformes nécessaires et les paquets, vous devrez activer le débogage USB sur votre appareil.
Sur mon Samsung Galaxy S III, je suis allé à paramètres , puis options de développeur puis coché Débogage USB. Sur une tablette Nexus, allez dans paramètres puis sur tablet PC puis cliquez sur générer nombre sept fois pour activer le débogage USB.
Pilotes USB
Si vous ne l’avez pas déjà fait, branchez votre téléphone à votre ordinateur et installer les pilotes USB pour votre appareil. J’ai pu télécharger tout pour mon téléphone à partir de ce site :
http://developer.Samsung.com/Android/Tools-SDKs/Samsung-Andorid-USB-Driver-for-Windows
Cela est uniquement nécessaire si vous utilisez un PC.
En cours d’exécution un croquis (première tentative)
Ouvrez le traitement et passer du mode Standard au mode Android en cliquant sur le menu déroulant sur le coin supérieur droit de la fenêtre et en sélectionnant Android. Pour passer en mode Android, vous devrez peut-être redémarrer le traitement après avoir fait cela.
Copiez et collez le code suivant dans votre schéma de traitement. Il s’agit d’une esquisse qui fera tourner l’écran vert, si l’appareil Android est en mesure de trouver le Seeed Bluetooth et puis tourne au violet une fois qu’il a relié au bouclier Seeed. L’androïde enverra la lettre « a » à l’Arduino de série.
Ouvrir les serial monitor de l’Arduino lorsque vous exécutez l’application Android pour vous être s’assurer que les deux sont en communication (communication série, c’est comment nous obtiendrons l’éclairage à changer plus tard). Lorsque vous exécutez le programme, assurez-vous que vous cliquez sur « Exécuter sur le périphérique ». J’ai contourné en cours d’exécution sur un périphérique virtuel parce que j’ai toujours eu accès à mon téléphone et j’ai décidé qu’il était plus d’ennui qu’il valait pour obtenir le travail de périphérique virtuel. La première fois vous exécutez le programme, il ne fonctionnera probablement pas correctement. Ne vous inquiétez pas. C’est l’étape suivante.
/* Bluetooth Connect and Send Bytes by Nicole Grimwood Based upon: SendReceiveBytes Created March 25 2013 by ScottC This code is in the public domain */ 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; boolean foundDevice=false; //When true, the screen turns green. boolean BTisConnected=false; //When true, the screen turns purple. // Message types used by the Handler public static final int MESSAGE_WRITE = 1; public static final int MESSAGE_READ = 2; String readMessage=""; //Get the default Bluetooth adapter BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); /*The startActivityForResult() within setup() launches an Activity which is used to request the user to turn Bluetooth on. The following onActivityResult() method is called when this Activity exits. */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode==0) { if (resultCode == RESULT_OK) { ToastMaster("Bluetooth has been switched ON"); } else { ToastMaster("You need to turn Bluetooth ON !!!"); } } } /* Create a BroadcastReceiver that will later be used to receive the names of Bluetooth devices in range. */ BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver(); /* Create a BroadcastReceiver that will later be used to identify if the Bluetooth device is connected */ BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver(); // The Handler that gets information back from the Socket private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_WRITE: //Do something when writing break; case MESSAGE_READ: //Get the bytes from the msg.obj byte[] readBuf = (byte[]) msg.obj; // construct a string from the valid bytes in the buffer readMessage = new String(readBuf, 0, msg.arg1); break; } } }; void setup() { orientation(LANDSCAPE); /*IF Bluetooth is NOT enabled, then ask user permission to enable it */ if (!bluetooth.isEnabled()) { Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(requestBluetooth, 0); } /*If Bluetooth is now enabled, then register a broadcastReceiver to report any discovered Bluetooth devices, and then start discovering */ if (bluetooth.isEnabled()) { registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND)); registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED)); //Start bluetooth discovery if it is not doing so already if (!bluetooth.isDiscovering()) { bluetooth.startDiscovery(); } } } void draw() { //Display a green screen if a device has been found, //Display a purple screen when a connection is made to the device if (foundDevice) { if (BTisConnected) { background(170, 50, 255); // purple screen } else { background(10, 255, 10); // green screen } } //Display anything received from Arduino text(readMessage, 10, 10); } /* This BroadcastReceiver will display discovered Bluetooth devices */ public class myOwnBroadcastReceiver extends BroadcastReceiver { ConnectToBluetooth connectBT; public void onReceive(Context context, Intent intent) { String action=intent.getAction(); ToastMaster("ACTION:" + action); //Notification that BluetoothDevice is FOUND if (BluetoothDevice.ACTION_FOUND.equals(action)) { //Display the name of the discovered device String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); ToastMaster("Discovered: " + discoveredDeviceName); //Display more information about the discovered device BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); ToastMaster("getAddress() = " + discoveredDevice.getAddress()); ToastMaster("getName() = " + discoveredDevice.getName()); int bondyState=discoveredDevice.getBondState(); ToastMaster("getBondState() = " + bondyState); String mybondState; switch(bondyState) { case 10: mybondState="BOND_NONE"; break; case 11: mybondState="BOND_BONDING"; break; case 12: mybondState="BOND_BONDED"; break; default: mybondState="INVALID BOND STATE"; break; } ToastMaster("getBondState() = " + mybondState); //Change foundDevice to true which will make the screen turn green foundDevice=true; //Connect to the discovered bluetooth device (SeeedBTSlave) if (discoveredDeviceName.equals("SeeedBTSlave")) { ToastMaster("Connecting you Now !!"); unregisterReceiver(myDiscoverer); connectBT = new ConnectToBluetooth(discoveredDevice); //Connect to the the device in a new thread new Thread(connectBT).start(); } } //Notification if bluetooth device is connected if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { ToastMaster("CONNECTED _ YAY"); while (scSocket==null) { //do nothing } ToastMaster("scSocket" + scSocket); BTisConnected=true; //turn screen purple if (scSocket!=null) { SendReceiveBytes sendReceiveBT = new SendReceiveBytes(scSocket); new Thread(sendReceiveBT).start(); String testLetter = "a"; byte[] myByte = stringToBytesUTFCustom(testLetter); sendReceiveBT.write(myByte); } } } } 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) { //Problem with creating a socket Log.e("ConnectToBluetooth", "Error with Socket"); } } public void run() { /* Cancel discovery on Bluetooth Adapter to prevent slow connection */ bluetooth.cancelDiscovery(); try { /*Connect to the bluetoothShield through the Socket. This will block until it succeeds or throws an IOException */ mySocket.connect(); scSocket=mySocket; } catch (IOException connectException) { Log.e("ConnectToBluetooth", "Error with Socket Connection"); try { mySocket.close(); //try to close the socket } catch(IOException closeException) { } return; } } /* Will cancel an in-progress connection, and close the socket */ public void cancel() { try { mySocket.close(); } catch (IOException e) { } } } 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]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) { try { // Read from the InputStream bytes = btInputStream.read(buffer); // Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Error reading from btInputStream"); break; } } } /* Call this from the main activity to send data to the remote device */ public void write(byte[] bytes) { try { btOutputStream.write(bytes); } catch (IOException e) { Log.e(TAG, "Error when writing to btOutputStream"); } } /* Call this from the main activity to shutdown the connection */ public void cancel() { try { btSocket.close(); } catch (IOException e) { Log.e(TAG, "Error when closing the btSocket"); } } } /* My ToastMaster function to display a messageBox on the screen */ void ToastMaster(String textToDisplay) { Toast myMessage = Toast.makeText(getApplicationContext(), textToDisplay, Toast.LENGTH_SHORT); myMessage.setGravity(Gravity.CENTER, 0, 0); myMessage.show(); }
Modifier Android Manifest.xml
Le manifeste d’Android ne s’affiche après que vous avez tenté d’exécuter le programme une fois. Il peut être trouvé dans le dossier contenant le fichier .pde pour votre code. Modifiez Manifest.xml Android en ajoutant les deux lignes suivantes entre les deuxième et troisième lignes dans le manifeste original :
< android:name="android.permission.BLUETOOTH"/ usages-autorisation >
< android:name="android.permission.BLUETOOTH_ADMIN"/ usages-autorisation >
Faire référence à la capture d’écran ci-dessus pour s’assurer que vous avez droit.
Se connecter
Exécutez de nouveau l’esquisse. Tout devrait fonctionner maintenant. Ouvrir le moniteur de série de l’Arduino pour s’assurer qu’il reçoit la lettre « a » quand le bluetooth est connecté. Si il n’est pas le cas, voici quelques choses que vous pouvez essayer de faire fonctionner correctement :
1. s’assurer que le bouclier de Bluetooth est configuré correctement et que les lumières rouges et vertes clignotent lorsque vous exécutez le programme Android.
2. Exécutez à nouveau l’application sur votre appareil
3. Redémarrez votre appareil Android
4. Redémarrez votre ordinateur
J’ai obtenu le mien pour travailler à l’aide d’une combinaison de ces mesures supplémentaires.
Conseil important: chaque fois que vous vous reconnectez le bluetooth, vous devez réinitialiser ou cycle de l’Arduino et fermez votre App et rouvrez-le.