SlideShare a Scribd company logo
1 of 25
Download to read offline
Android-Arduino interaction via Bluetooth
ovvero, come fare anche il caffè da Android
Salvatore Carotenuto, Associazione “Open Makers Italy”
Parte 1
L'Associazione “Open Makers Italy”
L'Associazione “Open Makers Italy”
Siamo appassionati di making, elettronica, informatica...
e di tutto ciò che è possibile costruire e modificare con le nostre mani.
http://www.openmakersitaly.org
plus.google.com/u/0/101202526052803869784 www.facebook.com/OpenMakersItaly twitter.com/openmakersitaly
L'Associazione “Open Makers Italy”
learn, make, share!
because it's better when it's made with your hands!
http://www.openmakersitaly.org
Attività
● eventi di making
● promozione di eventi
● diffusione delle ultime tecnologie
● corsi di formazione
● workshop e seminari
● partecipazione ad eventi
● progetti e consulenza
● collaborazione con i FabLAB e gli HackLAB italiani
● promozione e divulgazione della tecnologia nel Sud Italia
2013
Giffoni HackLab 2013
@Giffoni FilmFestival 2013,
@StartUp Solutions Lab
2013
Giffoni HackLab 2013
@Giffoni FilmFestival 2013,
@StartUp Solutions Lab
2013
Electronics Lab [with Arduino]
@Flussi Media Arts Festival 2013,
@Teatro Gesualdo, Avellino
2013
Giffoni Open Makers Day
@Giffoni Valle Piana, Antica Ramiera
L'Associazione “Open Makers Italy”
learn, make, share!
because it's better when it's made with your hands!
http://www.openmakersitaly.org
Come partecipare
● essere parte attiva dei progetti esistenti
● proporre nuovi progetti
● proporre percorsi didattici
● rappresentanza
● workshop e seminari
● partecipazione ad eventi
● gestire tutorial e blog
● donazioni
Parte 2
Android-Arduino Interaction via Bluetooth
Arduino e Bluetooth ?!?
Il modulo HC-05 è un adattatore Bluetooth-UART.
Ci permette di convertire il flusso dati bluetooth in un flusso dati UART, ovvero una normalissima
porta seriale, e viceversa.
Arduino e Bluetooth ?!?
Connessione del modulo HC-05 ad Arduino
Il progetto
Arduino
Codice Arduino
Pagina 1 di 2
#define POWER_PIN 8
#define PUMP_PIN 9
int incomingByte = 0; // for incoming serial data
void setup()
{
pinMode(POWER_PIN, OUTPUT);
pinMode(PUMP_PIN, OUTPUT);
//
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
Serial.println("READY");
}
void loop()
{
String line = "";
char character;
while(Serial.available())
{
delay(10);
character = Serial.read();
line.concat(character);
}
if(line != "")
{
Serial.println("received: " + line);
parseCommand(line);
}
}
Arduino
Codice Arduino
Pagina 2 di 2
void parseCommand(String line)
{
// splits received line in command/argument by ':'
int separatorIndex = line.indexOf(':', 0); String command = line.substring(0, separatorIndex);
separatorIndex = line.indexOf(':', separatorIndex); String argument = line.substring(separatorIndex+1, line.length());
Serial.print("command: " + command); Serial.println(" - argument: " + argument);
if(command == "POWER")
{
if(argument == "ON")
{
digitalWrite(POWER_PIN, HIGH);
Serial.println("Power: ON");
}
else if(argument == "OFF")
{
digitalWrite(POWER_PIN, LOW);
Serial.println("Power: OFF");
}
}
else if(command == "PUMP")
{
if(argument == "ON")
{
digitalWrite(PUMP_PIN, HIGH);
Serial.println("Pump: ON");
}
else if(argument == "OFF")
{
digitalWrite(PUMP_PIN, LOW);
Serial.println("Pump: OFF");
}
}
}
L'applicazione Android
Java
L'applicazione Android, il codice
Pagina 1 di 5: creazione dell'activity
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class EspressoDroidActivity extends Activity implements OnClickListener, OnSeekBarChangeListener
{
// bluetooth stuff
private static String btDeviceAddress = "00:15:FF:F3:C7:B2";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter bluetoothAdapter = null;
private BluetoothSocket btSocket = null;
Private Handler handler = new Handler();
// serial stuff
private InputStream inStream = null;
private OutputStream outStream = null;
private byte[] readBuffer = new byte[1024];
private int readBufferPosition = 0;
private byte lineDelimiter = 10;
private boolean pauseSerialWorker = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
…
…
// Bluetooth initialization
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(btDeviceAddress);
}
Java
L'applicazione Android, il codice
Pagina 2 di 5: connessione e apertura socket bluetooth
public void bluetoothConnect()
{
Log.d(TAG, "Bluetooth device address: " + btDeviceAddress);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(btDeviceAddress);
Log.d(TAG, "Connecting to ... " + device);
bluetoothAdapter.cancelDiscovery();
try
{
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.d(TAG, "Connection made.");
Toast.makeText(getApplicationContext(), "Connected!", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(), "Unable to connect!", Toast.LENGTH_SHORT).show();
try
{
btSocket.close();
}
catch (IOException e2)
{
Log.d(TAG, "Unable to end the connection");
}
Log.d(TAG, "Socket creation failed");
}
// starts bluetooth-serial listening thread
beginListenForData();
}
Java
L'applicazione Android, il codice
Pagina 3 di 5: listener thread su socket bluetooth
public void beginListenForData()
{
try { inStream = btSocket.getInputStream(); } catch (IOException e) { }
Thread workerThread = new Thread(new Runnable()
{
public void run()
{
while (!Thread.currentThread().isInterrupted() && !pauseSerialWorker)
{
try
{
int bytesAvailable = inStream.available();
if (bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++)
{
byte b = packetBytes[i];
if (b == lineDelimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
txtSerialMonitor.append("n" + data);
}
});
}
else
readBuffer[readBufferPosition++] = b;
}
}
}
catch (IOException ex)
{
pauseSerialWorker = true;
}
}
}
});
workerThread.start();
}
Java
L'applicazione Android, il codice
Pagina 4 di 5: invio dei comandi e chiusura socket bluetooth
private void writeData(String data)
{
if (this.btSocket == null)
{
return;
}
try
{
outStream = btSocket.getOutputStream();
}
catch (IOException e)
{
Log.d(TAG, "Error BEFORE writing on bluetooth socket: ", e);
}
Log.d(TAG, "Sending string: " + data);
try
{
outStream.write(data.getBytes());
}
catch (IOException e)
{
Log.d(TAG, "Error writing on bluetooth socket!", e);
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
try
{
btSocket.close();
}
catch (IOException e) { }
}
Java
L'applicazione Android, il codice
Pagina 5 di 5: gestione degli eventi utente
@Override
public void onClick(View control)
{
switch (control.getId())
{
case R.id.btnConnect:
this.bluetoothConnect();
break;
case R.id.btnPower:
if (btnPower.isChecked())
{
writeData("POWER:ON");
}
else
{
writeData("POWER:OFF");
}
break;
case R.id.btnManualPump:
if (btnManualPump.isChecked())
{
writeData("PUMP:ON");
}
else
{
writeData("PUMP:OFF");
}
break;
}
}
public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser)
{
this.writeData("ANGLE:" + value); // value between 0 and 180 (defined in layout.xml)
}
Part 3
Live Demo!
< Thank You! />
openmakersitaly@gmail.com
plus.google.com/u/0/101202526052803869784 www.facebook.com/OpenMakersItaly twitter.com/openmakersitaly
Android-Arduino interaction via Bluetooth

More Related Content

What's hot

What's hot (8)

Android & Bluetooth: hacking e applicazioni
Android & Bluetooth: hacking e applicazioniAndroid & Bluetooth: hacking e applicazioni
Android & Bluetooth: hacking e applicazioni
 
Lezione 3 arduino - corso 20 ore
Lezione 3 arduino - corso 20 oreLezione 3 arduino - corso 20 ore
Lezione 3 arduino - corso 20 ore
 
Internet delle cose
Internet delle coseInternet delle cose
Internet delle cose
 
Come rendere Arduino professionale
Come rendere Arduino professionaleCome rendere Arduino professionale
Come rendere Arduino professionale
 
Arduino ICT2016 [IT]
Arduino ICT2016 [IT]Arduino ICT2016 [IT]
Arduino ICT2016 [IT]
 
Workshop Arduino by Fiore Basile
Workshop Arduino by Fiore BasileWorkshop Arduino by Fiore Basile
Workshop Arduino by Fiore Basile
 
Arduino: breve introduzione & progetti
Arduino: breve introduzione & progettiArduino: breve introduzione & progetti
Arduino: breve introduzione & progetti
 
Introduzione ad Arduino
Introduzione ad ArduinoIntroduzione ad Arduino
Introduzione ad Arduino
 

Viewers also liked

Viewers also liked (10)

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
 
Communication entre android et arduino via bluetooth
Communication entre android et arduino via bluetoothCommunication entre android et arduino via bluetooth
Communication entre android et arduino via bluetooth
 
Android bluetooth
Android bluetoothAndroid bluetooth
Android bluetooth
 
MIT App Inventor + Arduino + Bluetooth
MIT App Inventor + Arduino + BluetoothMIT App Inventor + Arduino + Bluetooth
MIT App Inventor + Arduino + Bluetooth
 
QML + Arduino & Leap Motion
QML + Arduino & Leap MotionQML + Arduino & Leap Motion
QML + Arduino & Leap Motion
 
Enable talk
Enable talkEnable talk
Enable talk
 
Coders need to learn hardware hacking NOW
Coders need to learn hardware hacking NOWCoders need to learn hardware hacking NOW
Coders need to learn hardware hacking NOW
 
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
 
Vehicle tracking system,be computer android report,android project report,gps...
Vehicle tracking system,be computer android report,android project report,gps...Vehicle tracking system,be computer android report,android project report,gps...
Vehicle tracking system,be computer android report,android project report,gps...
 
Introduction to Bluetooth Low Energy
Introduction to Bluetooth Low EnergyIntroduction to Bluetooth Low Energy
Introduction to Bluetooth Low Energy
 

Similar to Android-Arduino interaction via Bluetooth

Sviluppare per microsoft band
Sviluppare per microsoft bandSviluppare per microsoft band
Sviluppare per microsoft band
DotNetCampus
 
Electronics LAB [with Arduino] | DAY 3
Electronics LAB [with Arduino] | DAY 3Electronics LAB [with Arduino] | DAY 3
Electronics LAB [with Arduino] | DAY 3
Daniele Costarella
 
Lo sbarco di Google nel pianeta Mobile Internet: primo impatto ed esempi pra...
Lo sbarco di Google nel pianeta Mobile Internet:  primo impatto ed esempi pra...Lo sbarco di Google nel pianeta Mobile Internet:  primo impatto ed esempi pra...
Lo sbarco di Google nel pianeta Mobile Internet: primo impatto ed esempi pra...
Riccardo Solimena
 

Similar to Android-Arduino interaction via Bluetooth (20)

TechDay: Internet delle cose - Paolo Aliverti
TechDay: Internet delle cose - Paolo Aliverti TechDay: Internet delle cose - Paolo Aliverti
TechDay: Internet delle cose - Paolo Aliverti
 
Sviluppare per Microsoft Band
Sviluppare per Microsoft BandSviluppare per Microsoft Band
Sviluppare per Microsoft Band
 
Reverse Engineering per dispositivi IoT
Reverse Engineering per dispositivi IoTReverse Engineering per dispositivi IoT
Reverse Engineering per dispositivi IoT
 
Sviluppare per microsoft band
Sviluppare per microsoft bandSviluppare per microsoft band
Sviluppare per microsoft band
 
SVILUPPARE PER MICROSOFT BAND
SVILUPPARE PER MICROSOFT BANDSVILUPPARE PER MICROSOFT BAND
SVILUPPARE PER MICROSOFT BAND
 
Electronics LAB [with Arduino] | DAY 3
Electronics LAB [with Arduino] | DAY 3Electronics LAB [with Arduino] | DAY 3
Electronics LAB [with Arduino] | DAY 3
 
Electronics LAB [with Arduino] | DAY 3
Electronics LAB [with Arduino] | DAY 3Electronics LAB [with Arduino] | DAY 3
Electronics LAB [with Arduino] | DAY 3
 
Fashion goes interactive by WeMake
Fashion goes interactive by WeMakeFashion goes interactive by WeMake
Fashion goes interactive by WeMake
 
Hardwire Trigger il data logger per l'Internet of Things
Hardwire Trigger il data logger per l'Internet of ThingsHardwire Trigger il data logger per l'Internet of Things
Hardwire Trigger il data logger per l'Internet of Things
 
Guida al Computer - Lezione 198 - Apertura porte (Port forwarding)
Guida al Computer - Lezione 198 - Apertura porte (Port forwarding)Guida al Computer - Lezione 198 - Apertura porte (Port forwarding)
Guida al Computer - Lezione 198 - Apertura porte (Port forwarding)
 
Lo sbarco di Google nel pianeta Mobile Internet: primo impatto ed esempi pra...
Lo sbarco di Google nel pianeta Mobile Internet:  primo impatto ed esempi pra...Lo sbarco di Google nel pianeta Mobile Internet:  primo impatto ed esempi pra...
Lo sbarco di Google nel pianeta Mobile Internet: primo impatto ed esempi pra...
 
Android Bluetooth Hacking
Android Bluetooth HackingAndroid Bluetooth Hacking
Android Bluetooth Hacking
 
Semantic ArDroid
Semantic ArDroidSemantic ArDroid
Semantic ArDroid
 
Italian Agile Day 2011 - Corso di cucina fusion elettro-agile con Arduino
Italian Agile Day 2011 - Corso di cucina fusion elettro-agile con ArduinoItalian Agile Day 2011 - Corso di cucina fusion elettro-agile con Arduino
Italian Agile Day 2011 - Corso di cucina fusion elettro-agile con Arduino
 
Sviluppare per Microsoft Band
Sviluppare per Microsoft BandSviluppare per Microsoft Band
Sviluppare per Microsoft Band
 
Intro to Arduino
Intro to ArduinoIntro to Arduino
Intro to Arduino
 
Predictive Maintenance per le aziende del nord-est con Azure e IoT
Predictive Maintenance per le aziende del nord-est con Azure e IoTPredictive Maintenance per le aziende del nord-est con Azure e IoT
Predictive Maintenance per le aziende del nord-est con Azure e IoT
 
SIAM domotica open source Fiera Elettronica 2014
SIAM   domotica open source Fiera Elettronica 2014SIAM   domotica open source Fiera Elettronica 2014
SIAM domotica open source Fiera Elettronica 2014
 
Workshop su Arduino
Workshop su ArduinoWorkshop su Arduino
Workshop su Arduino
 
L'ecosistema Google a supporto dei progetti IoT: dalla prototipazione ai dati...
L'ecosistema Google a supporto dei progetti IoT: dalla prototipazione ai dati...L'ecosistema Google a supporto dei progetti IoT: dalla prototipazione ai dati...
L'ecosistema Google a supporto dei progetti IoT: dalla prototipazione ai dati...
 

More from Open Makers Italy

More from Open Makers Italy (18)

GoogleIO Extended Campania
GoogleIO Extended CampaniaGoogleIO Extended Campania
GoogleIO Extended Campania
 
Arduino e stampa 3d: le nuove frontiere della robotica homemade
Arduino e stampa 3d: le nuove frontiere della robotica homemadeArduino e stampa 3d: le nuove frontiere della robotica homemade
Arduino e stampa 3d: le nuove frontiere della robotica homemade
 
Arduino e stampa 3D - Le nuove frontiere della robotica homemade
Arduino e stampa 3D - Le nuove frontiere della robotica homemadeArduino e stampa 3D - Le nuove frontiere della robotica homemade
Arduino e stampa 3D - Le nuove frontiere della robotica homemade
 
Open Makers Italy - Company profile
Open Makers Italy - Company profileOpen Makers Italy - Company profile
Open Makers Italy - Company profile
 
Cyclomatic: un datalogger per bicicletta con Arduino
Cyclomatic: un datalogger per bicicletta con ArduinoCyclomatic: un datalogger per bicicletta con Arduino
Cyclomatic: un datalogger per bicicletta con Arduino
 
Frankenstein printer: dalla discarica al CNC
Frankenstein printer: dalla discarica al CNCFrankenstein printer: dalla discarica al CNC
Frankenstein printer: dalla discarica al CNC
 
Lua e MOAI SDK: sviluppiamo videogames!
Lua e MOAI SDK: sviluppiamo videogames!Lua e MOAI SDK: sviluppiamo videogames!
Lua e MOAI SDK: sviluppiamo videogames!
 
HySolarKit - Solar Hybridization of Conventional Vehicles
HySolarKit - Solar Hybridization of Conventional Vehicles HySolarKit - Solar Hybridization of Conventional Vehicles
HySolarKit - Solar Hybridization of Conventional Vehicles
 
Geecom: il nuovo CMS open source
Geecom: il nuovo CMS open sourceGeecom: il nuovo CMS open source
Geecom: il nuovo CMS open source
 
Django & Google App Engine: a value composition
Django & Google App Engine: a value compositionDjango & Google App Engine: a value composition
Django & Google App Engine: a value composition
 
Primi passi con la scheda BeagleBone Black
Primi passi con la scheda BeagleBone BlackPrimi passi con la scheda BeagleBone Black
Primi passi con la scheda BeagleBone Black
 
Hands on Embedded Linux with BeagleBone Black
Hands on Embedded Linux with BeagleBone BlackHands on Embedded Linux with BeagleBone Black
Hands on Embedded Linux with BeagleBone Black
 
Geecom, nascita di un progetto open source
Geecom, nascita di un progetto open sourceGeecom, nascita di un progetto open source
Geecom, nascita di un progetto open source
 
Introduzione al sistema operativo mobile Android
Introduzione al sistema operativo mobile AndroidIntroduzione al sistema operativo mobile Android
Introduzione al sistema operativo mobile Android
 
Making in action: facciamo il caffè con Android e Arduino
Making in action: facciamo il caffè con Android e ArduinoMaking in action: facciamo il caffè con Android e Arduino
Making in action: facciamo il caffè con Android e Arduino
 
Email 4 blackout
Email 4 blackoutEmail 4 blackout
Email 4 blackout
 
BACS platform
BACS platformBACS platform
BACS platform
 
OpenStreetMap: costruiamo una mappa libera
OpenStreetMap: costruiamo una mappa liberaOpenStreetMap: costruiamo una mappa libera
OpenStreetMap: costruiamo una mappa libera
 

Recently uploaded

Adducchio.Samuel-Steve_Jobs.ppppppppppptx
Adducchio.Samuel-Steve_Jobs.ppppppppppptxAdducchio.Samuel-Steve_Jobs.ppppppppppptx
Adducchio.Samuel-Steve_Jobs.ppppppppppptx
sasaselvatico
 
Scienza Potere Puntoaaaaaaaaaaaaaaa.pptx
Scienza Potere Puntoaaaaaaaaaaaaaaa.pptxScienza Potere Puntoaaaaaaaaaaaaaaa.pptx
Scienza Potere Puntoaaaaaaaaaaaaaaa.pptx
lorenzodemidio01
 
Presentazione tre geni della tecnologia informatica
Presentazione tre geni della tecnologia informaticaPresentazione tre geni della tecnologia informatica
Presentazione tre geni della tecnologia informatica
nico07fusco
 
Nicola pisano aaaaaaaaaaaaaaaaaa(1).pptx
Nicola pisano aaaaaaaaaaaaaaaaaa(1).pptxNicola pisano aaaaaaaaaaaaaaaaaa(1).pptx
Nicola pisano aaaaaaaaaaaaaaaaaa(1).pptx
lorenzodemidio01
 
case passive_GiorgiaDeAscaniis.pptx.....
case passive_GiorgiaDeAscaniis.pptx.....case passive_GiorgiaDeAscaniis.pptx.....
case passive_GiorgiaDeAscaniis.pptx.....
giorgiadeascaniis59
 

Recently uploaded (17)

Tosone Christian_Steve Jobsaaaaaaaa.pptx
Tosone Christian_Steve Jobsaaaaaaaa.pptxTosone Christian_Steve Jobsaaaaaaaa.pptx
Tosone Christian_Steve Jobsaaaaaaaa.pptx
 
TeccarelliLorenzo-i4stilidellapitturaromana.docx
TeccarelliLorenzo-i4stilidellapitturaromana.docxTeccarelliLorenzo-i4stilidellapitturaromana.docx
TeccarelliLorenzo-i4stilidellapitturaromana.docx
 
Adducchio.Samuel-Steve_Jobs.ppppppppppptx
Adducchio.Samuel-Steve_Jobs.ppppppppppptxAdducchio.Samuel-Steve_Jobs.ppppppppppptx
Adducchio.Samuel-Steve_Jobs.ppppppppppptx
 
Oppressi_oppressori.pptx................
Oppressi_oppressori.pptx................Oppressi_oppressori.pptx................
Oppressi_oppressori.pptx................
 
Esame di Stato 2024 - Materiale conferenza online 09 aprile 2024
Esame di Stato 2024 - Materiale conferenza online 09 aprile 2024Esame di Stato 2024 - Materiale conferenza online 09 aprile 2024
Esame di Stato 2024 - Materiale conferenza online 09 aprile 2024
 
LE ALGHE.pptx ..........................
LE ALGHE.pptx ..........................LE ALGHE.pptx ..........................
LE ALGHE.pptx ..........................
 
Storia-CarloMagno-TeccarelliLorenzo.pptx
Storia-CarloMagno-TeccarelliLorenzo.pptxStoria-CarloMagno-TeccarelliLorenzo.pptx
Storia-CarloMagno-TeccarelliLorenzo.pptx
 
TeccarelliLorenzo-Mitodella.cavernaa.pdf
TeccarelliLorenzo-Mitodella.cavernaa.pdfTeccarelliLorenzo-Mitodella.cavernaa.pdf
TeccarelliLorenzo-Mitodella.cavernaa.pdf
 
Una breve introduzione ad Elsa Morante, vita e opere
Una breve introduzione ad Elsa Morante, vita e opereUna breve introduzione ad Elsa Morante, vita e opere
Una breve introduzione ad Elsa Morante, vita e opere
 
Scienza Potere Puntoaaaaaaaaaaaaaaa.pptx
Scienza Potere Puntoaaaaaaaaaaaaaaa.pptxScienza Potere Puntoaaaaaaaaaaaaaaa.pptx
Scienza Potere Puntoaaaaaaaaaaaaaaa.pptx
 
Presentazione tre geni della tecnologia informatica
Presentazione tre geni della tecnologia informaticaPresentazione tre geni della tecnologia informatica
Presentazione tre geni della tecnologia informatica
 
ProgettoDiEducazioneCivicaDefinitivo_Christian Tosone.pptx
ProgettoDiEducazioneCivicaDefinitivo_Christian Tosone.pptxProgettoDiEducazioneCivicaDefinitivo_Christian Tosone.pptx
ProgettoDiEducazioneCivicaDefinitivo_Christian Tosone.pptx
 
CHIẾN THẮNG KÌ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN - PHAN THẾ HOÀI (36...
CHIẾN THẮNG KÌ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN - PHAN THẾ HOÀI (36...CHIẾN THẮNG KÌ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN - PHAN THẾ HOÀI (36...
CHIẾN THẮNG KÌ THI TUYỂN SINH VÀO LỚP 10 THPT MÔN NGỮ VĂN - PHAN THẾ HOÀI (36...
 
Nicola pisano aaaaaaaaaaaaaaaaaa(1).pptx
Nicola pisano aaaaaaaaaaaaaaaaaa(1).pptxNicola pisano aaaaaaaaaaaaaaaaaa(1).pptx
Nicola pisano aaaaaaaaaaaaaaaaaa(1).pptx
 
TeccarelliLorenzo-PrimadiSteveJobselasuaconcorrenza.pptx
TeccarelliLorenzo-PrimadiSteveJobselasuaconcorrenza.pptxTeccarelliLorenzo-PrimadiSteveJobselasuaconcorrenza.pptx
TeccarelliLorenzo-PrimadiSteveJobselasuaconcorrenza.pptx
 
case passive_GiorgiaDeAscaniis.pptx.....
case passive_GiorgiaDeAscaniis.pptx.....case passive_GiorgiaDeAscaniis.pptx.....
case passive_GiorgiaDeAscaniis.pptx.....
 
Vuoi girare il mondo? educazione civica.
Vuoi girare il mondo? educazione civica.Vuoi girare il mondo? educazione civica.
Vuoi girare il mondo? educazione civica.
 

Android-Arduino interaction via Bluetooth

  • 1.
  • 2. Android-Arduino interaction via Bluetooth ovvero, come fare anche il caffè da Android Salvatore Carotenuto, Associazione “Open Makers Italy”
  • 4. L'Associazione “Open Makers Italy” Siamo appassionati di making, elettronica, informatica... e di tutto ciò che è possibile costruire e modificare con le nostre mani. http://www.openmakersitaly.org plus.google.com/u/0/101202526052803869784 www.facebook.com/OpenMakersItaly twitter.com/openmakersitaly
  • 5. L'Associazione “Open Makers Italy” learn, make, share! because it's better when it's made with your hands! http://www.openmakersitaly.org Attività ● eventi di making ● promozione di eventi ● diffusione delle ultime tecnologie ● corsi di formazione ● workshop e seminari ● partecipazione ad eventi ● progetti e consulenza ● collaborazione con i FabLAB e gli HackLAB italiani ● promozione e divulgazione della tecnologia nel Sud Italia
  • 6. 2013 Giffoni HackLab 2013 @Giffoni FilmFestival 2013, @StartUp Solutions Lab
  • 7. 2013 Giffoni HackLab 2013 @Giffoni FilmFestival 2013, @StartUp Solutions Lab
  • 8. 2013 Electronics Lab [with Arduino] @Flussi Media Arts Festival 2013, @Teatro Gesualdo, Avellino
  • 9. 2013 Giffoni Open Makers Day @Giffoni Valle Piana, Antica Ramiera
  • 10. L'Associazione “Open Makers Italy” learn, make, share! because it's better when it's made with your hands! http://www.openmakersitaly.org Come partecipare ● essere parte attiva dei progetti esistenti ● proporre nuovi progetti ● proporre percorsi didattici ● rappresentanza ● workshop e seminari ● partecipazione ad eventi ● gestire tutorial e blog ● donazioni
  • 12. Arduino e Bluetooth ?!? Il modulo HC-05 è un adattatore Bluetooth-UART. Ci permette di convertire il flusso dati bluetooth in un flusso dati UART, ovvero una normalissima porta seriale, e viceversa.
  • 13. Arduino e Bluetooth ?!? Connessione del modulo HC-05 ad Arduino
  • 15. Arduino Codice Arduino Pagina 1 di 2 #define POWER_PIN 8 #define PUMP_PIN 9 int incomingByte = 0; // for incoming serial data void setup() { pinMode(POWER_PIN, OUTPUT); pinMode(PUMP_PIN, OUTPUT); // Serial.begin(9600); // opens serial port, sets data rate to 9600 bps Serial.println("READY"); } void loop() { String line = ""; char character; while(Serial.available()) { delay(10); character = Serial.read(); line.concat(character); } if(line != "") { Serial.println("received: " + line); parseCommand(line); } }
  • 16. Arduino Codice Arduino Pagina 2 di 2 void parseCommand(String line) { // splits received line in command/argument by ':' int separatorIndex = line.indexOf(':', 0); String command = line.substring(0, separatorIndex); separatorIndex = line.indexOf(':', separatorIndex); String argument = line.substring(separatorIndex+1, line.length()); Serial.print("command: " + command); Serial.println(" - argument: " + argument); if(command == "POWER") { if(argument == "ON") { digitalWrite(POWER_PIN, HIGH); Serial.println("Power: ON"); } else if(argument == "OFF") { digitalWrite(POWER_PIN, LOW); Serial.println("Power: OFF"); } } else if(command == "PUMP") { if(argument == "ON") { digitalWrite(PUMP_PIN, HIGH); Serial.println("Pump: ON"); } else if(argument == "OFF") { digitalWrite(PUMP_PIN, LOW); Serial.println("Pump: OFF"); } } }
  • 18. Java L'applicazione Android, il codice Pagina 1 di 5: creazione dell'activity import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class EspressoDroidActivity extends Activity implements OnClickListener, OnSeekBarChangeListener { // bluetooth stuff private static String btDeviceAddress = "00:15:FF:F3:C7:B2"; private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private BluetoothAdapter bluetoothAdapter = null; private BluetoothSocket btSocket = null; Private Handler handler = new Handler(); // serial stuff private InputStream inStream = null; private OutputStream outStream = null; private byte[] readBuffer = new byte[1024]; private int readBufferPosition = 0; private byte lineDelimiter = 10; private boolean pauseSerialWorker = false; @Override protected void onCreate(Bundle savedInstanceState) { … … // Bluetooth initialization BluetoothDevice device = bluetoothAdapter.getRemoteDevice(btDeviceAddress); }
  • 19. Java L'applicazione Android, il codice Pagina 2 di 5: connessione e apertura socket bluetooth public void bluetoothConnect() { Log.d(TAG, "Bluetooth device address: " + btDeviceAddress); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(btDeviceAddress); Log.d(TAG, "Connecting to ... " + device); bluetoothAdapter.cancelDiscovery(); try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); btSocket.connect(); Log.d(TAG, "Connection made."); Toast.makeText(getApplicationContext(), "Connected!", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(getApplicationContext(), "Unable to connect!", Toast.LENGTH_SHORT).show(); try { btSocket.close(); } catch (IOException e2) { Log.d(TAG, "Unable to end the connection"); } Log.d(TAG, "Socket creation failed"); } // starts bluetooth-serial listening thread beginListenForData(); }
  • 20. Java L'applicazione Android, il codice Pagina 3 di 5: listener thread su socket bluetooth public void beginListenForData() { try { inStream = btSocket.getInputStream(); } catch (IOException e) { } Thread workerThread = new Thread(new Runnable() { public void run() { while (!Thread.currentThread().isInterrupted() && !pauseSerialWorker) { try { int bytesAvailable = inStream.available(); if (bytesAvailable > 0) { byte[] packetBytes = new byte[bytesAvailable]; inStream.read(packetBytes); for (int i = 0; i < bytesAvailable; i++) { byte b = packetBytes[i]; if (b == lineDelimiter) { byte[] encodedBytes = new byte[readBufferPosition]; System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); final String data = new String(encodedBytes, "US-ASCII"); readBufferPosition = 0; handler.post(new Runnable() { public void run() { txtSerialMonitor.append("n" + data); } }); } else readBuffer[readBufferPosition++] = b; } } } catch (IOException ex) { pauseSerialWorker = true; } } } }); workerThread.start(); }
  • 21. Java L'applicazione Android, il codice Pagina 4 di 5: invio dei comandi e chiusura socket bluetooth private void writeData(String data) { if (this.btSocket == null) { return; } try { outStream = btSocket.getOutputStream(); } catch (IOException e) { Log.d(TAG, "Error BEFORE writing on bluetooth socket: ", e); } Log.d(TAG, "Sending string: " + data); try { outStream.write(data.getBytes()); } catch (IOException e) { Log.d(TAG, "Error writing on bluetooth socket!", e); } } @Override protected void onDestroy() { super.onDestroy(); try { btSocket.close(); } catch (IOException e) { } }
  • 22. Java L'applicazione Android, il codice Pagina 5 di 5: gestione degli eventi utente @Override public void onClick(View control) { switch (control.getId()) { case R.id.btnConnect: this.bluetoothConnect(); break; case R.id.btnPower: if (btnPower.isChecked()) { writeData("POWER:ON"); } else { writeData("POWER:OFF"); } break; case R.id.btnManualPump: if (btnManualPump.isChecked()) { writeData("PUMP:ON"); } else { writeData("PUMP:OFF"); } break; } } public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser) { this.writeData("ANGLE:" + value); // value between 0 and 180 (defined in layout.xml) }
  • 24. < Thank You! /> openmakersitaly@gmail.com plus.google.com/u/0/101202526052803869784 www.facebook.com/OpenMakersItaly twitter.com/openmakersitaly