23
Communication entre Android et Arduino via Bluetooth ElAchèche Bedis

Communication entre android et arduino via bluetooth

Embed Size (px)

DESCRIPTION

La création d'un robot téléguidé, est cool! Mais, pourquoi dépenser du temps et de l'argent sur une télécommande. Comment, peut-on observer le fonctionnement du robot? La solution est dans votre poche! Lors de l'atelier, on va entamer la partie de la communication sans fil Android/Ardiuno via Bluetooth. La création de votre télécommande, et le suivi de l'état de votre robot via votre appareil n'a jamais été aussi facile.

Citation preview

Page 1: Communication entre android et arduino via bluetooth

Communication entre Android et Arduinovia Bluetooth

ElAchèche Bedis

Page 2: Communication entre android et arduino via bluetooth

Introduction

La création d'un robot téléguidé, est cool! Mais, pourquoi dépenser encore du temps et de l'argent sur une télécommande ? La solution et ici ! Saisissez juste votre smartphone de votre poche et allons-y !

Page 3: Communication entre android et arduino via bluetooth

Android et Bluetooth...

La plate-forme Android inclut le support du réseau Bluetooth, qui permet à un dispositif sans fil d'échanger des données avec d'autres dispositifs Bluetooth.

Votre smartphone Android doit avoir le Bluetooth bien évidement et doit tourner sur Android 2.0 minimum: les fonctions pour l'utilisation Bluetooth ne sont présentes dans le SDK qu'à partir de l'API 5.

Page 4: Communication entre android et arduino via bluetooth

Android et Bluetooth...

Voici les étapes nécessaires pour pouvoir utiliser le Bluetooth dans Android

1 - Demander la permission d'utiliser le Bluetooth :

<uses-permission android:name="android.permission.BLUETOOTH" />

2 – Vérifier la présence du Bluetooth sur le terminal :

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (bluetoothAdapter == null) { // Le device ne possède pas la technologie Bluetooth} else { // Le device possède le Bluetooth}

Page 5: Communication entre android et arduino via bluetooth

Android et Bluetooth...

3 - Activer le Bluetooth : Il existe deux méthodes pour pouvoir le faire.3.1 - Être gentil et demander la permission :

if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_CODE_ENABLE_BLUETOOTH);}

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode != REQUEST_CODE_ENABLE_BLUETOOTH) return; if (resultCode == RESULT_OK) { // L'utilisateur a activé le bluetooth } else { // L'utilisateur n'a pas activé le bluetooth } }

Page 6: Communication entre android et arduino via bluetooth

Android et Bluetooth...

3.2 - Activer le Bluetooth tout seul comme un grand :

if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable();}

N.B : Il faut ajouter la permission suivante :<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

4 - Obtenir la liste des devices déjà connus

Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();for (BluetoothDevice blueDevice : devices) { Toast.makeText(Activity.this, "Device " + blueDevice.getName(), 1000).show();}

Page 7: Communication entre android et arduino via bluetooth

Projet :

Le scénario de notre projet est le suivant :Un visiteur arrive et sonne la porte à l'aide du bouton poussoir. Une notification de joignabilité est envoyée à l'application Android pour que l'utilisateur décide s'il veut ouvrir la porte ou non. La réponse de l'utilisateur activera une de deux diodes LED (rouge/verte).

La liaison Bluetooth se fait par le profil Bluetooth SPP (Serial Port Profile), qui permet d'émuler une connexion série.Cette méthode est donc compatible avec n'importe quel microcontrôleur ayant une interface série (Arduino pour notre cas).

Page 8: Communication entre android et arduino via bluetooth

Côté Arduino : Circuit

Composants :- Carte Arduino Uno- 2 LED- Bouton poussoir- 3 résistances 220Ω- Module Bluetooth

Page 9: Communication entre android et arduino via bluetooth

Côté Arduino: Code

const int redLed = 4;const int greenLed = 3;const int btnPin = 2;int buttonState;int reading;int lastButtonState = LOW;int incomingByte;long lastDebounceTime = 0;long debounceDelay = 50;

void setup() { Serial.begin(9600); pinMode(greenLed, OUTPUT); pinMode(redLed, OUTPUT); pinMode(btnPin, INPUT);}

Page 10: Communication entre android et arduino via bluetooth

Côté Arduino: Code

void loop() { reading = digitalRead(btnPin); if (reading != lastButtonState) { lastDebounceTime = millis(); // reset the debouncing timer } if ((millis() - lastDebounceTime) > debounceDelay) { if (reading != buttonState) { buttonState = reading; if (buttonState == HIGH) { Serial.write('K'); } } } lastButtonState = buttonState; if (Serial.available() > 0){ incomingByte = Serial.read(); if (incomingByte == 'Y'){ digitalWrite(greenLed, HIGH); } else if (incomingByte == 'N'){ digitalWrite(redLed, HIGH); } }}

Page 11: Communication entre android et arduino via bluetooth

Côté Android: UI

Absence du Bluetooth

Réception de données

Interface principale

Page 12: Communication entre android et arduino via bluetooth

Côté Android: Code

ReceiverThread

~ Handler handler

+ void run()

Main

- BluetoothAdapter btAdapter- BluetoothInterface myBTInterface- Button accept- Button decline- String adress- TextView status~ Handler handler

+ void onClick(View)+ void OnCreate(Bundle)+ void onDestroy()

BluetoothInterface

- BluetoothAdapter btAdapter- BluetoothDevice device- ReceiverThread receiverThread- InputStream inSteam- OutputStream outSteam- String adress- static final UUID MY_UUID

+ BluetoothInterface(BluetoothAdapter, String, Handler, Context) + void closeBT()+ void connectBT()+ void sendData(String)

Page 13: Communication entre android et arduino via bluetooth

Côté Android: Code

public class Main extends Activity implements OnClickListener { private BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); private BluetoothInterface myBTInterface = null; private Button accept, decline; private TextView status; private String address = "XX:XX:XX:XX:XX:XX"; // BT module MAC final Handler handler = new Handler() { public void handleMessage(Message msg) { ... } };

@Override public void onCreate(Bundle savedInstanceState) { ... }

@Override public void onClick(View v) { ... }

@Override public void onDestroy() { ... }

}

Page 14: Communication entre android et arduino via bluetooth

Côté Android: Code

@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (btAdapter == null) { setContentView(R.layout.no_bt); new Handler().postDelayed(new Runnable() { @Override public void run() { Main.this.finish(); } }, 3000); } else { setContentView(R.layout.main); myBTInterface = new BluetoothInterface(btAdapter, address, handler, Main.this); myBTInterface.connectBT(); accept = (Button) findViewById(R.id.accept); decline = (Button) findViewById(R.id.decline); status = (TextView) findViewById(R.id.satus); accept.setOnClickListener(this); decline.setOnClickListener(this); }}

Page 15: Communication entre android et arduino via bluetooth

Côté Android: Code

@Overridepublic void onClick(View v) { if (v == accept) { myBTInterface.sendData("Y"); } else if (v == decline) { myBTInterface.sendData("N"); } status.setText(R.string.foreveralone); accept.setEnabled(false); accept.setAlpha(0.5f); decline.setEnabled(false); decline.setAlpha(0.5f);}

@Overridepublic void onDestroy() { myBTInterface.closeBT(); super.onDestroy();}

Page 16: Communication entre android et arduino via bluetooth

Côté Android: Code

public void handleMessage(Message msg) { String data = msg.getData().getString("receivedData"); if (data.equals("K")) { status.setText(R.string.company); accept.setEnabled(true); accept.setAlpha(1f); decline.setEnabled(true); decline.setAlpha(1f); }}

Page 17: Communication entre android et arduino via bluetooth

Côté Android: Code

public class BluetoothInterface { private BluetoothAdapter btAdapter = null; private BluetoothDevice device = null; private BluetoothSocket socket = null; private OutputStream outStream = null; private InputStream inStream = null; private String address; private static final UUID MY_UUID = UUID .fromString("00001101-0000-1000-8000-00805F9B34FB"); private ReceiverThread receiverThread; public BluetoothInterface(BluetoothAdapter bt, String address, Handler h, final Context c) { ... } public void connectBT() { ... } public void sendData(String message) { ... } public void closeBT() { ... }

}

Page 18: Communication entre android et arduino via bluetooth

Côté Android: Code

public BluetoothInterface(BluetoothAdapter bt, String address, Handler h, final Context c) { this.btAdapter = bt; this.address = address; this.receiverThread = new ReceiverThread(h); AsyncTask<Void, Void, Void> async = new AsyncTask<Void, Void, Void>() { ProgressDialog dialog = new ProgressDialog(c); protected void onPreExecute() { super.onPreExecute(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setMessage("Enabeling Bluetooth, please wait..."); dialog.setCancelable(false); dialog.show(); } @Override protected Void doInBackground(Void... params) { if (!btAdapter.isEnabled()) btAdapter.enable(); while (!btAdapter.isEnabled()); return null; } @Override protected void onPostExecute(Void result) { dialog.dismiss(); dialog = null; } }; async.execute(); }

Page 19: Communication entre android et arduino via bluetooth

Côté Android: Code

public void connectBT() { Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { if (device.getAddress().equals(address)) { this.device = device; break; }}} try { socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); socket.connect(); outStream = socket.getOutputStream(); inStream = socket.getInputStream(); receiverThread.start(); Log.i("connectBT","Connected device"); } catch (NullPointerException e) { Log.e("connectBT: NullPointer",e.toString()); } catch (IOException e) { Log.e("connectBT: IO",e.toString()); }}

Page 20: Communication entre android et arduino via bluetooth

Côté Android: Code

public void sendData(String message) { try { outStream.write(message.getBytes()); outStream.flush(); } catch (NullPointerException e) { Log.e("sendData: NullPointer",e.toString()); } catch (IOException e) { Log.e("sendData: IO",e.toString()); } Log.i("SendData",message);}

public void closeBT() { if (btAdapter.isEnabled()) btAdapter.disable(); Log.i("closeBt","Bluetooth disabled");}

Page 21: Communication entre android et arduino via bluetooth

Côté Android: Code

private class ReceiverThread extends Thread { Handler handler;

public ReceiverThread(Handler h) { handler = h; }

@Override public void run() { ... }

}

Page 22: Communication entre android et arduino via bluetooth

Côté Android: Code

@Overridepublic void run() { while (true) { try { if (inStream.available() > 0) { byte[] buffer = new byte[10]; int k = inStream.read(buffer, 0, 10); if (k > 0) { byte rawdata[] = new byte[k]; for (int i = 0; i < k; i++) rawdata[i] = buffer[i]; String data = new String(rawdata); Message msg = handler.obtainMessage(); Bundle b = new Bundle(); b.putString("receivedData", data); msg.setData(b); handler.sendMessage(msg); }}} catch (IOException e) { Log.e("recieveData: IO",e.toString()); }}}}

Page 23: Communication entre android et arduino via bluetooth

Merci de votre attention

ElAchèche Bedis