SlideShare une entreprise Scribd logo
1  sur  23
Télécharger pour lire hors ligne
Communication entre Android et Arduino
via Bluetooth
ElAchèche Bedis
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 !
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.
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
}
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);
}
@Override
protected 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
}
}
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();
}
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).
Côté Arduino : Circuit
Composants :
- Carte Arduino Uno
- 2 LED
- Bouton poussoir
- 3 résistances 220Ω
- Module 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);
}
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);
}
}
}
Côté Android: UI
Absence du
Bluetooth
Réception
de données
Interface
principale
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)
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() { ... }
}
Côté Android: Code
@Override
public 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);
}
}
Côté Android: Code
@Override
public 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);
}
@Override
public void onDestroy() {
myBTInterface.closeBT();
super.onDestroy();
}
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);
}
}
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() { ... }
}
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(); }
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());
}
}
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");
}
Côté Android: Code
private class ReceiverThread extends Thread {
Handler handler;
public ReceiverThread(Handler h) {
handler = h;
}
@Override
public void run() { ... }
}
Côté Android: Code
@Override
public 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());
}
}}}
Merci de votre attention
ElAchèche Bedis

Contenu connexe

Tendances

Détecter et réparer les pannes d
Détecter et réparer les pannes dDétecter et réparer les pannes d
Détecter et réparer les pannes d
Paul Kamga
 

Tendances (20)

Internet des Objets
Internet des ObjetsInternet des Objets
Internet des Objets
 
Présentation des IoT
Présentation des IoTPrésentation des IoT
Présentation des IoT
 
Cours routage inter-vlan
Cours routage inter-vlanCours routage inter-vlan
Cours routage inter-vlan
 
Introduction aux réseaux informatiques
Introduction aux réseaux informatiquesIntroduction aux réseaux informatiques
Introduction aux réseaux informatiques
 
Présentation UMTS
Présentation UMTSPrésentation UMTS
Présentation UMTS
 
Chapitre 2 - Réseaux locaux
Chapitre 2 - Réseaux locauxChapitre 2 - Réseaux locaux
Chapitre 2 - Réseaux locaux
 
chap3 numerisation_des_signaux
chap3 numerisation_des_signauxchap3 numerisation_des_signaux
chap3 numerisation_des_signaux
 
Internet Of Things
Internet Of Things Internet Of Things
Internet Of Things
 
Trame mic
Trame micTrame mic
Trame mic
 
Travaux dirigés Réseau Ethernet
Travaux dirigés Réseau EthernetTravaux dirigés Réseau Ethernet
Travaux dirigés Réseau Ethernet
 
Internet des Objets
Internet des ObjetsInternet des Objets
Internet des Objets
 
C5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-natC5 Réseaux : vlsm-classe-nat
C5 Réseaux : vlsm-classe-nat
 
Détecter et réparer les pannes d
Détecter et réparer les pannes dDétecter et réparer les pannes d
Détecter et réparer les pannes d
 
Administration réseaux sous linux cours 1
Administration réseaux sous linux   cours 1Administration réseaux sous linux   cours 1
Administration réseaux sous linux cours 1
 
L’abandon en formation à distance : constats et leviers possibles pour le lim...
L’abandon en formation à distance : constats et leviers possibles pour le lim...L’abandon en formation à distance : constats et leviers possibles pour le lim...
L’abandon en formation à distance : constats et leviers possibles pour le lim...
 
Introduction aux réseaux locaux
 Introduction aux réseaux locaux Introduction aux réseaux locaux
Introduction aux réseaux locaux
 
Chapitre 6 - couche transport
Chapitre 6  - couche transportChapitre 6  - couche transport
Chapitre 6 - couche transport
 
Distribution et transport.ppt
Distribution et transport.pptDistribution et transport.ppt
Distribution et transport.ppt
 
Réseaux de transmission des données
Réseaux de transmission des donnéesRéseaux de transmission des données
Réseaux de transmission des données
 
Traitement du signal
Traitement du signalTraitement du signal
Traitement du signal
 

En vedette

Android + Bluetooth + Arduino
Android + Bluetooth + ArduinoAndroid + Bluetooth + Arduino
Android + Bluetooth + Arduino
Jonathan Alvarado
 
Andrui car
Andrui carAndrui car
Andrui car
dani
 

En vedette (20)

Android + Bluetooth + Arduino
Android + Bluetooth + ArduinoAndroid + Bluetooth + Arduino
Android + Bluetooth + Arduino
 
Arduino + Android
Arduino + AndroidArduino + Android
Arduino + Android
 
Connecting Arduino and Android
Connecting Arduino and AndroidConnecting Arduino and Android
Connecting Arduino and Android
 
Bluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduinoBluetooth android application For interfacing with arduino
Bluetooth android application For interfacing with arduino
 
Android-Arduino interaction via Bluetooth
Android-Arduino interaction via BluetoothAndroid-Arduino interaction via Bluetooth
Android-Arduino interaction via Bluetooth
 
Controlling an Arduino with Android
Controlling an Arduino with AndroidControlling an Arduino with Android
Controlling an Arduino with Android
 
QML + Arduino & Leap Motion
QML + Arduino & Leap MotionQML + Arduino & Leap Motion
QML + Arduino & Leap Motion
 
Andrui car
Andrui carAndrui car
Andrui car
 
Andrui car final
Andrui car finalAndrui car final
Andrui car final
 
Diseño de carro a control remoto
Diseño de carro a control remoto Diseño de carro a control remoto
Diseño de carro a control remoto
 
Android bluetooth
Android bluetoothAndroid bluetooth
Android bluetooth
 
Connect your Android to the real world with Bluetooth Low Energy
Connect your Android to the real world with Bluetooth Low EnergyConnect your Android to the real world with Bluetooth Low Energy
Connect your Android to the real world with Bluetooth Low Energy
 
Introduction to cross platform natitve mobile development with c# and xamarin
Introduction to cross platform natitve mobile development with c# and xamarinIntroduction to cross platform natitve mobile development with c# and xamarin
Introduction to cross platform natitve mobile development with c# and xamarin
 
Xamarin.Android + Arduino : Hacking Robots
Xamarin.Android + Arduino : Hacking RobotsXamarin.Android + Arduino : Hacking Robots
Xamarin.Android + Arduino : Hacking Robots
 
Android meets Arduino
Android meets ArduinoAndroid meets Arduino
Android meets Arduino
 
Arduino sin cables: usando Bluetooth
Arduino sin cables: usando BluetoothArduino sin cables: usando Bluetooth
Arduino sin cables: usando Bluetooth
 
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
Codesign-Oriented Platform for Agile Internet of Things Prototype DevelopmentCodesign-Oriented Platform for Agile Internet of Things Prototype Development
Codesign-Oriented Platform for Agile Internet of Things Prototype Development
 
02.El Soporte Visual
02.El Soporte Visual02.El Soporte Visual
02.El Soporte Visual
 
P01.Desarrollo de aplicaciones con mplab
P01.Desarrollo de aplicaciones con mplabP01.Desarrollo de aplicaciones con mplab
P01.Desarrollo de aplicaciones con mplab
 
Práctica09.Librerías
Práctica09.LibreríasPráctica09.Librerías
Práctica09.Librerías
 

Similaire à Communication entre android et arduino via bluetooth

Workshop IoT Hub : Pilotez une ampoule connectée
Workshop IoT Hub : Pilotez une ampoule connectéeWorkshop IoT Hub : Pilotez une ampoule connectée
Workshop IoT Hub : Pilotez une ampoule connectée
Scaleway
 
20140415200533!rapport projet deltombe_gerier
20140415200533!rapport projet deltombe_gerier20140415200533!rapport projet deltombe_gerier
20140415200533!rapport projet deltombe_gerier
bessem ellili
 
Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Liaison modbus wago_atv_31
Liaison modbus wago_atv_31
Moha Belkaid
 
Google day ISI - android IOIO
Google day ISI - android IOIOGoogle day ISI - android IOIO
Google day ISI - android IOIO
Mouafa Ahmed
 
Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Liaison modbus wago_atv_31
Liaison modbus wago_atv_31
Moha Belkaid
 

Similaire à Communication entre android et arduino via bluetooth (20)

chapitre 7 Android 2.pptx
chapitre 7 Android 2.pptxchapitre 7 Android 2.pptx
chapitre 7 Android 2.pptx
 
Rapport application chat
Rapport application chatRapport application chat
Rapport application chat
 
Workshop IoT Hub : Pilotez une ampoule connectée
Workshop IoT Hub : Pilotez une ampoule connectéeWorkshop IoT Hub : Pilotez une ampoule connectée
Workshop IoT Hub : Pilotez une ampoule connectée
 
Messaging temps réel avec Go
Messaging temps réel avec GoMessaging temps réel avec Go
Messaging temps réel avec Go
 
Développement informatique : Programmation réseau
Développement informatique : Programmation réseauDéveloppement informatique : Programmation réseau
Développement informatique : Programmation réseau
 
02 java-socket
02 java-socket02 java-socket
02 java-socket
 
Bluetooth Low Energy dans les applications Windows
Bluetooth Low Energy dans les applications WindowsBluetooth Low Energy dans les applications Windows
Bluetooth Low Energy dans les applications Windows
 
Comment développer un serveur métier en python/C++
Comment développer un serveur métier en python/C++Comment développer un serveur métier en python/C++
Comment développer un serveur métier en python/C++
 
8-socket.pdf
8-socket.pdf8-socket.pdf
8-socket.pdf
 
20140415200533!rapport projet deltombe_gerier
20140415200533!rapport projet deltombe_gerier20140415200533!rapport projet deltombe_gerier
20140415200533!rapport projet deltombe_gerier
 
Deploiement_Lora_exo.pdf
Deploiement_Lora_exo.pdfDeploiement_Lora_exo.pdf
Deploiement_Lora_exo.pdf
 
IoT (M2M) - Big Data - Analyses : Simulation et Démonstration
IoT (M2M) - Big Data - Analyses : Simulation et DémonstrationIoT (M2M) - Big Data - Analyses : Simulation et Démonstration
IoT (M2M) - Big Data - Analyses : Simulation et Démonstration
 
Sockets
SocketsSockets
Sockets
 
Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Liaison modbus wago_atv_31
Liaison modbus wago_atv_31
 
Google day ISI - android IOIO
Google day ISI - android IOIOGoogle day ISI - android IOIO
Google day ISI - android IOIO
 
IoT.pptx
IoT.pptxIoT.pptx
IoT.pptx
 
Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Liaison modbus wago_atv_31
Liaison modbus wago_atv_31
 
Programmation de systèmes embarqués : Internet of Things : système connecté e...
Programmation de systèmes embarqués : Internet of Things : système connecté e...Programmation de systèmes embarqués : Internet of Things : système connecté e...
Programmation de systèmes embarqués : Internet of Things : système connecté e...
 
HTML5 en projet
HTML5 en projetHTML5 en projet
HTML5 en projet
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à Android
 

Plus de Bedis ElAchèche

Plus de Bedis ElAchèche (6)

Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
The dark side of IA
The dark side of IAThe dark side of IA
The dark side of IA
 
Have we forgotten how to program? - Tunisian WebDev MeetUp
Have we forgotten how to program? - Tunisian WebDev MeetUpHave we forgotten how to program? - Tunisian WebDev MeetUp
Have we forgotten how to program? - Tunisian WebDev MeetUp
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
 
SVN essentials
SVN essentialsSVN essentials
SVN essentials
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 

Communication entre android et arduino via bluetooth

  • 1. Communication entre Android et Arduino via Bluetooth ElAchèche Bedis
  • 2. 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 !
  • 3. 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.
  • 4. 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 }
  • 5. 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); } @Override protected 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 } }
  • 6. 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(); }
  • 7. 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).
  • 8. Côté Arduino : Circuit Composants : - Carte Arduino Uno - 2 LED - Bouton poussoir - 3 résistances 220Ω - Module Bluetooth
  • 9. 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); }
  • 10. 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); } } }
  • 11. Côté Android: UI Absence du Bluetooth Réception de données Interface principale
  • 12. 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)
  • 13. 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() { ... } }
  • 14. Côté Android: Code @Override public 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); } }
  • 15. Côté Android: Code @Override public 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); } @Override public void onDestroy() { myBTInterface.closeBT(); super.onDestroy(); }
  • 16. 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); } }
  • 17. 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() { ... } }
  • 18. 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(); }
  • 19. 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()); } }
  • 20. 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"); }
  • 21. Côté Android: Code private class ReceiverThread extends Thread { Handler handler; public ReceiverThread(Handler h) { handler = h; } @Override public void run() { ... } }
  • 22. Côté Android: Code @Override public 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()); } }}}
  • 23. Merci de votre attention ElAchèche Bedis