harger Le but du montage : Sur un smartphone Android, l’appui sur un bouton allume la led d’une carte Arduino Uno un autre bouton éteins la led.
Matériel : 1 carte Arduino UNO, 1 module Bluetooth HC-06, des câbles pour relier la carte et le module en option un module externe d’alimentation de la carte Arduino.
Scénario : sur le smartphone un programme se connecte au module BlueTooth en mode SPP (Émulation de port série), le programme via un handler scan le module bluetooth pour afficher les informations en provenance du module, le programme via deux boutons permet également d’envoyer un message à la carte Arduino pour allumer ou éteindre une Led.
Préparation : A l’aide d’un programme tel BlueTooth SPP PRO trouvez l’adresse MAC de la carte HC-06. La carte HC-06 doit être associée au smartphone via le menu système (le code est 1234).
Le programme Arduino à télécharger ici :
package com.andrologiciels.androblue2ways;
/**
* Modify from
* http://english.cxem.net/arduino/arduino5.php
* @author Koltykov A.V.
* Need an Arduino and HC-06 module see
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "androblue2ways";
Button btnOn, btnOff;
TextView txtArduino;
Handler h;
final int RECIEVE_MESSAGE = 1; //-- Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread; //-- Managing Thread
//-- SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//-- MAC-address of Bluetooth module (you must edit this line)
private static String address = "20:13:06:13:37:46";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.buttonon); //-- button LED ON
btnOff = (Button) findViewById(R.id.buttonoff); //-- button LED OFF
txtArduino = (TextView) findViewById(R.id.textView1); //-- for display the received data from the Arduino
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: //-- if receive message
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText(sbprint); //-- update TextView
btnOff.setEnabled(true);
btnOn.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOn.setEnabled(false);
mConnectedThread.write("1"); // Send "1" via Bluetooth
//Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOff.setEnabled(false);
mConnectedThread.write("0"); // Send "0" via Bluetooth
//Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
/*try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
}
Le fichier main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/textView1"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="@string/LibResArduino" />
<Button
android:id="@+id/buttonon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="52dp"
android:text="@string/ButtonOn" />
<Button
android:id="@+id/buttonoff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/buttonon"
android:layout_alignBottom="@+id/buttonon"
android:layout_alignLeft="@+id/textView1"
android:text="@string/ButtonOff" />
</RelativeLayout>
Fichier res/values/strings.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AndroBlue2Ways</string>
<string name="action_settings">Settings</string>
<string name="LibResArduino">From Arduino</string>
<string name="ButtonOn">ON</string>
<string name="ButtonOff">OFF</string>
</resources>
Et dimens.xml :
<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> </resources>
Ne pas oublier de modifier le fichier manifest en ajoutant les autorisations pour la communication BlueTooth :
<uses-permission android:name= »android.permission.BLUETOOTH_ADMIN » />
<uses-permission android:name= »android.permission.BLUETOOTH » />
Code pour Arduino :
#include <SoftwareSerial.h>
int bluetoothTx = 2; //-- To Tx bluetooth HC-6
int bluetoothRx = 3; //-- To Rx bluetooth HC-6
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
char incomingByte; //-- incoming data
int LED = 13; //-- LED pin
void setup() {
Serial.begin(9600); //--for computer display ctrl+maj+m
pinMode(LED, OUTPUT);
//Setup Bluetooth serial connection to android
bluetooth.begin(9600);
Serial.println("Press on smartphone LED ON or LED OFF...");
}
void loop() {
if (bluetooth.available() > 0) { //-- if the data came
incomingByte = bluetooth.read(); //-- read byte
if(incomingByte == '0') {
digitalWrite(LED, LOW); //-- if 1, switch LED Off
Serial.println("LED OFF"); //-- print message
bluetooth.println("Arduino tell you the LED is OFF"); //-- Send Message to bluetooth
}
if(incomingByte == '1') {
digitalWrite(LED, HIGH); //-- if 0, switch LED on
Serial.println("LED ON");
bluetooth.println("Arduino tell you the LED is ON"); //-- Send Message to bluetooth
}
}
}
Le source pour Android et pour Arduino.
Votre commentaire