Sorry to be late. So here are the both code. The goal of my project is to open and close a door from a smartphone. There is MD22 board linked with the arduino board.
On the android code I use a three buttons interface : one to connect, one to send "1" and the last to send "2"
show(String) is to show messages into a textView.
Android (only an extract):
public void onClick (View v)
{
if (v==butConnect)
connect(); // connect is to initialize the bluetooth radio, search for the MAC adress of my BT board and to connect.
else if (v==but1)
sendData(1);
else if (v==but2)
sendData(2);
}
public void sendData(int data)
{
try
{
sendStream.write(data);
sendStream.flush();
} catch (IOException e)
{
show("Not send " + data.tostring()
e.printStackTrace();
}
}
//extract from the connect() function : to connect the smartphone
try {
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
socket.connect();
sendStream = socket.getOutputStream();
} catch (IOException e)
{
e.printStackTrace();
show("Connect FAIL");
return -4;
}
show("Connect OK");
return 1;
Arduino :
#include <SoftwareSerial.h>
// Values to send to control the motor (MD22 board)
const int ouv = 255; // Value when opening
const int fer = 0; // Value when closing
const int stp = 128; // Vlaue when we want to stop the motor
const int pinSCL = 11; // Where we send these values to control the motor
const int pinTX0 = 2; // Linked to RX of the bluetooth board
const int pinRX1 = 3; // Linked to TX of the the bluetooth board
const int pinPI06 = 16; // To reset the bluetooth board
SoftwareSerial bluetooth(pinTX0, pinRX1);
char reception = 0; // to receive what the bluetooth send to the arduino board
unsigned long tempo = 5000;
void ouvrir() // to open our door
{
analogWrite(pinSCL, ouv);
delay (tempo);
analogWrite(pinSCL, stp);
}
void fermer() // to close our door
{
analogWrite(pinSCL, fer);
delay(tempo);
analogWrite(pinSCL, stp);
}
void resetBT()
{
digitalWrite(pinPI06, HIGH);
digitalWrite(pinPI06, LOW);
bluetooth.begin(115200);
delay(320);
bluetooth.print("$$$");
delay(250);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);
}
void setup()
{
pinMode(pinSCL, OUTPUT);
pinMode(pinPI06, OUTPUT);
Serial.begin(9600);
analogWrite(pinSCL, stp);
resetBT();
}
void loop()
{
if (bluetooth.available())
{
reception = Serial.read();
if (reception == 1)
{
ouvrir();
}
else if (reception == 2)
{
fermer();
}
}