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

Présentation d'Hyper-V ( Hyperviseur de Microsoft )
Présentation d'Hyper-V ( Hyperviseur de Microsoft )Présentation d'Hyper-V ( Hyperviseur de Microsoft )
Présentation d'Hyper-V ( Hyperviseur de Microsoft )merlinparm
 
Exercices vhdl
Exercices vhdlExercices vhdl
Exercices vhdlyassinesmz
 
Microo exercices 16f877/877A
Microo exercices 16f877/877AMicroo exercices 16f877/877A
Microo exercices 16f877/877Aomar bllaouhamou
 
Présentation Arduino par Christian, F5HOD
Présentation Arduino par Christian, F5HODPrésentation Arduino par Christian, F5HOD
Présentation Arduino par Christian, F5HODwebmasterref68
 
Rapport regulation-de-temperature
Rapport regulation-de-temperatureRapport regulation-de-temperature
Rapport regulation-de-temperatureMarwa Bhouri
 
Medical openerp
Medical openerpMedical openerp
Medical openerpHORIYASOFT
 
Jeux d instruction du 6809
Jeux d instruction du 6809Jeux d instruction du 6809
Jeux d instruction du 6809Amel Morchdi
 
La spécification des besoins
La spécification des besoinsLa spécification des besoins
La spécification des besoinsIsmahen Traya
 
Traitement des images avec matlab
Traitement des images avec matlabTraitement des images avec matlab
Traitement des images avec matlabomar bllaouhamou
 
Noyau temps réel freertos cheriet mohammed el amine
Noyau temps réel freertos cheriet mohammed el amineNoyau temps réel freertos cheriet mohammed el amine
Noyau temps réel freertos cheriet mohammed el amineCHERIET Mohammed El Amine
 
Rapport De Stage de Fin d'etude : Modélisation et Dématérialisation des Proc...
Rapport De Stage de Fin  d'etude : Modélisation et Dématérialisation des Proc...Rapport De Stage de Fin  d'etude : Modélisation et Dématérialisation des Proc...
Rapport De Stage de Fin d'etude : Modélisation et Dématérialisation des Proc...Issa BEN MANSOUR
 
Presentation arduino
Presentation arduinoPresentation arduino
Presentation arduinoSinGuy
 
curriculum vitae
curriculum vitaecurriculum vitae
curriculum vitaeElyes MANAI
 

Tendances (20)

Présentation d'Hyper-V ( Hyperviseur de Microsoft )
Présentation d'Hyper-V ( Hyperviseur de Microsoft )Présentation d'Hyper-V ( Hyperviseur de Microsoft )
Présentation d'Hyper-V ( Hyperviseur de Microsoft )
 
Exercices vhdl
Exercices vhdlExercices vhdl
Exercices vhdl
 
Formation stm32
Formation stm32Formation stm32
Formation stm32
 
Microo exercices 16f877/877A
Microo exercices 16f877/877AMicroo exercices 16f877/877A
Microo exercices 16f877/877A
 
Présentation Arduino par Christian, F5HOD
Présentation Arduino par Christian, F5HODPrésentation Arduino par Christian, F5HOD
Présentation Arduino par Christian, F5HOD
 
Rapport regulation-de-temperature
Rapport regulation-de-temperatureRapport regulation-de-temperature
Rapport regulation-de-temperature
 
Medical openerp
Medical openerpMedical openerp
Medical openerp
 
S7 1500 opcua-pv
S7 1500 opcua-pvS7 1500 opcua-pv
S7 1500 opcua-pv
 
Jeux d instruction du 6809
Jeux d instruction du 6809Jeux d instruction du 6809
Jeux d instruction du 6809
 
Rapport Projet Fin d'Études PFE
Rapport Projet Fin d'Études PFERapport Projet Fin d'Études PFE
Rapport Projet Fin d'Études PFE
 
La spécification des besoins
La spécification des besoinsLa spécification des besoins
La spécification des besoins
 
Cours pics16 f877
Cours pics16 f877Cours pics16 f877
Cours pics16 f877
 
IoT
IoTIoT
IoT
 
Chap2fonctionscpp
Chap2fonctionscppChap2fonctionscpp
Chap2fonctionscpp
 
Traitement des images avec matlab
Traitement des images avec matlabTraitement des images avec matlab
Traitement des images avec matlab
 
Les systèmes embarqués arduino
Les systèmes embarqués arduinoLes systèmes embarqués arduino
Les systèmes embarqués arduino
 
Noyau temps réel freertos cheriet mohammed el amine
Noyau temps réel freertos cheriet mohammed el amineNoyau temps réel freertos cheriet mohammed el amine
Noyau temps réel freertos cheriet mohammed el amine
 
Rapport De Stage de Fin d'etude : Modélisation et Dématérialisation des Proc...
Rapport De Stage de Fin  d'etude : Modélisation et Dématérialisation des Proc...Rapport De Stage de Fin  d'etude : Modélisation et Dématérialisation des Proc...
Rapport De Stage de Fin d'etude : Modélisation et Dématérialisation des Proc...
 
Presentation arduino
Presentation arduinoPresentation arduino
Presentation arduino
 
curriculum vitae
curriculum vitaecurriculum vitae
curriculum vitae
 

En vedette

Android + Bluetooth + Arduino
Android + Bluetooth + ArduinoAndroid + Bluetooth + Arduino
Android + Bluetooth + ArduinoJonathan Alvarado
 
Connecting Arduino and Android
Connecting Arduino and AndroidConnecting Arduino and Android
Connecting Arduino and AndroidMichał Tuszyński
 
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 arduinosumit chakraborty
 
Android-Arduino interaction via Bluetooth
Android-Arduino interaction via BluetoothAndroid-Arduino interaction via Bluetooth
Android-Arduino interaction via BluetoothOpen Makers Italy
 
Controlling an Arduino with Android
Controlling an Arduino with AndroidControlling an Arduino with Android
Controlling an Arduino with AndroidA. Hernandez
 
QML + Arduino & Leap Motion
QML + Arduino & Leap MotionQML + Arduino & Leap Motion
QML + Arduino & Leap Motiondiro fan
 
Andrui car
Andrui carAndrui car
Andrui cardani
 
Andrui car final
Andrui car finalAndrui car final
Andrui car finaldani
 
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 EnergyGabor Paller
 
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 xamarinJames Montemagno
 
Xamarin.Android + Arduino : Hacking Robots
Xamarin.Android + Arduino : Hacking RobotsXamarin.Android + Arduino : Hacking Robots
Xamarin.Android + Arduino : Hacking RobotsAlejandro Ruiz Varela
 
Arduino sin cables: usando Bluetooth
Arduino sin cables: usando BluetoothArduino sin cables: usando Bluetooth
Arduino sin cables: usando BluetoothJorge Zaccaro
 
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 DevelopmentJonathan Ruiz de Garibay
 

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

Rapport application chat
Rapport application chatRapport application chat
Rapport application chatTbatou sanae
 
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éeScaleway
 
Messaging temps réel avec Go
Messaging temps réel avec GoMessaging temps réel avec Go
Messaging temps réel avec GoMickaël Rémond
 
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 WindowsMicrosoft
 
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++cppfrug
 
20140415200533!rapport projet deltombe_gerier
20140415200533!rapport projet deltombe_gerier20140415200533!rapport projet deltombe_gerier
20140415200533!rapport projet deltombe_gerierbessem ellili
 
Deploiement_Lora_exo.pdf
Deploiement_Lora_exo.pdfDeploiement_Lora_exo.pdf
Deploiement_Lora_exo.pdfmerazgaammar2
 
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émonstrationCHAKER ALLAOUI
 
Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Moha Belkaid
 
Google day ISI - android IOIO
Google day ISI - android IOIOGoogle day ISI - android IOIO
Google day ISI - android IOIOMouafa Ahmed
 
Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Liaison modbus wago_atv_31
Liaison modbus wago_atv_31Moha Belkaid
 
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...ECAM Brussels Engineering School
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à AndroidYoann Gotthilf
 

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