I can get my Android app to connect via Bluetooth to my Arduino. However no data can be transmitted between them. Below is my setup and code:
HTC Android v2.2, Bluetooth mate gold modem, Arduino Mega (ATmega1280)
Android Java code:
package com.example.BluetoothExample;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothExampleActivity extends Activity {
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.label);
myTextbox = (EditText)findViewById(R.id.entry);
//Open Button
openButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Send Button
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
}
catch (IOException ex) {
showMessage("SEND FAILED");
}
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
closeBT();
}
catch (IOException ex) { }
}
});
}
void findBT() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for(BluetoothDevice device : pairedDevices) {
if(device.getName().equals("FireFly-108B")) {
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++) {
byte b = packetBytes[i];
if(b == delimiter) {
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() {
myLabel.setText(data);
}
});
}
else {
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData() throws IOException {
String msg = myTextbox.getText().toString();
msg += "\n";
//mmOutputStream.write(msg.getBytes());
mmOutputStream.write('A');
myLabel.setText("Data Sent");
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
private void showMessage(String theMsg) {
Toast msg = Toast.makeText(getBaseContext(),
theMsg, (Toast.LENGTH_LONG)/160);
msg.show();
}
}
Arduino Code:
#include <SoftwareSerial.h>
int bluetoothTx = 45;
int bluetoothRx = 47;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup() {
//pinMode(45, OUTPUT);
//pinMode(47, INPUT);
pinMode(53, OUTPUT);
//Setup usb serial connection to computer
Serial.begin(9600);
//Setup Bluetooth serial connection to android
bluetooth.begin(115200);
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);
}
void loop() {
//Read from bluetooth and write to usb serial
if(bluetooth.available()) {
char toSend = (char)bluetooth.read();
Serial.print(toSend);
flashLED();
}
//Read from usb serial to bluetooth
if(Serial.available()) {
char toSend = (char)Serial.read();
bluetooth.print(toSend);
flashLED();
}
}
void flashLED() {
digitalWrite(53, HIGH);
delay(500);
digitalWrite(53, LOW);
}
I've tried using 115200 and 9600 for the baud rates, and I've tried setting the bluetooth rx and tx pins as input/output and output/input. The Arduino is receiving serial data from the PC but can't send it to the Android (I can see this because of the flashLED() method).
The Android can't send any data at all to the Arduino. However they are both connected because the green light on the modem turns on and goes off and the red led flashes when I close the connection. The sendData() method doesn't throw an exception because otherwise showMessage("SEND FAILED"); would appear.
I also have this in my manifest .xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />
Any help would be greatly appreciated!
Code taken from:
http://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/
Just solved the problem for anyone else who came across this page.
Seems that my Arduino doesn't like me using digital pins for serial communication, I use TX and RX instead with this code taken from http://jondontdoit.blogspot.com.au/2011/11/bluetooth-mate-tutorial.html, also seems that 9600 is a good baud instead of 115200.
/***********************
Bluetooth test program
***********************/
//TODO
//TEST THIS PROGRAM WITH ANDROID,
//CHANGE PINS TO RX AND TX THO ON THE ARDUINO!
//int counter = 0;
int incomingByte;
void setup() {
pinMode(53, OUTPUT);
Serial.begin(9600);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital R, reset the counter
if (incomingByte == 'g') {
digitalWrite(53, HIGH);
delay(500);
digitalWrite(53, LOW);
delay(500);
//Serial.println("RESET");
//counter=0;
}
}
//Serial.println(counter);
//counter++;
//delay(250);
}
I was getting the same thing. I went into 'Settings'->'Wireless and Networks'->'Bluetooth Settings' and paired the device. When I went back and re-ran my code, it connected, no exception. I put controls in my UI for displaying the paired devices, I'm going to see if I can code to manage pairing devices from my UI.
I was able to get this to run only after replacing this section:
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().startsWith("FireFly-"))
{
mmDevice = device;
Log.d("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.d("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
with this:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
mmDevice = mBluetoothAdapter.getRemoteDevice("00:06:66:46:5A:91");
if (pairedDevices.contains(mmDevice))
{
statusText.setText("Bluetooth Device Found, address: " + mmDevice.getAddress() );
Log.d("ArduinoBT", "BT is paired");
}
where I entered the address of my Bluetooth device.
The original code finds the device and returns the correct address, but
mmSocket.connect();
generates an exception "java.io.IOException: Service discovery failed"
Suggestions?
For anyone who finds this page, but is stuck using a hardcoded mac address as above, set mac address to NULL, and insert this code into OnResume()
try{
File f = new File(Environment.getExternalStorageDirectory()+"/mac.txt");
FileInputStream fileIS = new FileInputStream(f);
buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
while((readString = buf.readLine())!= null){
address = readString;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
ALSO, don't forget to allow eclipse to include necessary libraries, and place your mac address into mac.txt on the root of the SD Card, then you can simply give users a text file with their mac address while still allowing the app to be downloaded from the market without customizing every instance.
#Backwards_Dave just for a curious, try to connect to 45 and 46 pins and use this simple code. I use it and have no problem. You will be able to send data from Arduino Serial Monitor and read it there.
/*
Pinout:
45 --> BT module Tx
46 --> BT module Rx
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(45, 46); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("I am ready to send some stuff!");
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
}
void loop() // run over and over
{
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
}
Also, what BlueTooth shield are you using for Arduino? HC-06?
EDIT
Just tested it with Mega2560(don't have 1280) and it works with no problem.
I believe problem was with pinout.
Waiting for your feedback
If you're still looking for an answer, try changing the software serial pins. This is a well known limitation of the library you are using.
Not all pins on the Mega support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69). Refs
Hope this helps.
I think it might be some fault in Bluetooth.. its better to re-install its drivers.. as the code given above looks correct.
Related
I've created an Android app to communicate with my Arduino using Bluetooth. But when I'm sending data from my Android device to my Arduino, the Arduino isn't responding to what I've send. I am able to get a connection from my Android device to my Arduino. So that's not the problem.
Here's my full script for Android.
package nl.handoko.LumaMini;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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 = "LumaMini";
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button fourty, thirty, twenty, twelve, automatic, manual;
TextView message;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Server's MAC address
private static String address = "98:D3:31:30:09:43";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
setContentView(R.layout.activity_mainnn);
fourty = (Button) findViewById(R.id.button1);
thirty = (Button) findViewById(R.id.button4);
twenty = (Button) findViewById(R.id.button2);
twelve = (Button) findViewById(R.id.button5);
automatic = (Button) findViewById(R.id.button3);
manual = (Button) findViewById(R.id.button6);
message = (TextView) findViewById(R.id.textView1);
fourty.setText("40 Leds");
thirty.setText("30 Leds");
twenty.setText("20 Leds");
twelve.setText("12 Leds");
automatic.setText("Automatic");
manual.setText("Manual");
message.setText("Using this app you can take full control of the Luma Mini!" +
"When it's running on automatic please switch back to manual first before switching to other versions.");
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
fourty.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("a");
Toast msg = Toast.makeText(getBaseContext(),
"40 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
thirty.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("b");
Toast msg = Toast.makeText(getBaseContext(),
"30 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
twenty.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("c");
Toast msg = Toast.makeText(getBaseContext(),
"20 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
twelve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("d");
Toast msg = Toast.makeText(getBaseContext(),
"12 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
automatic.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("e");
Toast msg = Toast.makeText(getBaseContext(),
"Run automatically", Toast.LENGTH_SHORT);
msg.show();
}
});
manual.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("f");
Toast msg = Toast.makeText(getBaseContext(),
"Manually switch Leds", Toast.LENGTH_SHORT);
msg.show();
}
});
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client 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 = 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 to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} 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, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
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 supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here's my Arduino script:
#include <SoftwareSerial.h>
#include <TimerOne.h>
#define Rx 2
#define Tx 3
#define seconds 4
char serialData; // Serial data memory
int counter1; // Overflow memory
int action; // Action trigger
int once = 0; // Run only once
SoftwareSerial Bluetooth(Rx, Tx);
void setup(){
pinMode(Tx, OUTPUT); // Configure Tx as OUTPUT (Transmitter)
pinMode(Rx, INPUT);
delay(1000);
Bluetooth.begin(9600);
Serial.begin(1200);
delay(1000);
Serial.print("Bluetooth ready");
Bluetooth.flush();
TimerOneSetup(); // Run the setup for Timer One
for(int i = 5; i <= 8; i++){ // Make pins 5, 6, 7 and 8 OUTPUT
pinMode(i, OUTPUT);
}
}
void interrupt1(){ // Timer One loop
counter1++; // Count the amount of seconds has passed
if (counter1 == seconds){ // Trigger the next action after a several amount of seconds (Default: 4 seconds)
action++;
counter1 = 0;
}
if (action > 3){ // Reset action trigger when after all actions were runned
action = 0;
}
}
void loop(){ // Endless loop
if (Serial.available()){ // Wait for data recieved from Local device
serialData = Serial.read(); // Put recieved data in memory
Serial.print("Data recieved from Local device: ");
Serial.println(serialData);
}
if (Bluetooth.available()){ // Wait for data recieved from Bluetooth device
serialData = Bluetooth.read(); // Put recieved data in memory
Serial.print("Data recieved from Bluetooth device: ");
Serial.print(serialData);
}
if (once == 0){ // This script will be run only once
serialData = 'e'; // Put switch on automatic on startup
once++; // Get into the next stage which may be run only once
}
switch(serialData){ // Perform action on state of the switch
case 'a':
fourtyLeds(); // Show the 40 Leds version of the Luma Mini
break;
case 'b':
thirtyLeds(); // Show the 30 Leds version of the Luma Mini
break;
case 'c':
twentyLeds(); // Show the 20 Leds version of the Luma Mini
break;
case 'd':
twelveLeds(); // Show the 12 Leds version of the Luma Mini
break;
case 'e':
while(serialData == 'e'){ // Keep changing different Led versions of the Luma Mini automatically
switch(action){
case 0: // Wait for the action trigger to hit the first action
fourtyLeds(); // Show the 40 Leds version of the Luma Mini
break;
case 1: // Wait for the action trigger to hit the second action
twelveLeds(); // Show the 12 Leds version of the Luma Mini
break;
case 2: // Wait for the action trigger to hit the third action
twentyLeds(); // Show the 20 Leds version of the Luma Mini
break;
case 4: // Wait for the action trigger to hit the fourth action
thirtyLeds(); // Show the 30 Leds version of the Luma Mini
break;}
if (Serial.read() == 'f'){ // Wait for data recieved from Local device
serialData = Serial.read(); // Put recieved data in memory
Serial.print("Data recieved from Local device: ");
Serial.println(serialData);
}
if (Bluetooth.read() == 'f'){ // Wait for data recieved from Bluetooth device
serialData = Bluetooth.read(); // Put recieved data in memory
Serial.print("Data recieved from Bluetooth device: ");
Serial.println(serialData);
}
break;
}
}
}
void BluetoothSetup(){
pinMode(Tx, OUTPUT); // Configure Tx as OUTPUT (Transmitter)
pinMode(Rx, INPUT); // Configure Rx as INPUT (Reciever)
Bluetooth.begin(9600); // Set Bluetooth baud rate to default baud rate 38400
Bluetooth.print("\r\n+STWMOD=0\r\n"); // Set the Bluetooth to work in slave mode
Bluetooth.print("\r\n+STNA=Luma Mini\r\n"); // Set Bluetooth name to Luma Mini
Bluetooth.print("\r\n+STOAUT=1\r\n"); // Permit paired device to connect
Bluetooth.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000);
Bluetooth.print("\r\n+INQ=1\r\n"); // Make this Bluetooth Slave inquirable
Serial.println("The slave Bluetooth is inquirable!");
delay(2000);
Bluetooth.flush();
}
void TimerOneSetup(){
Timer1.initialize(1000000); // Initialize Timer One for an overflow exactly every 1 second
Timer1.attachInterrupt(interrupt1); // Open the Timer One loop
}
void fourtyLeds(){ // Show the 40 Leds version of the Luma Mini
for(int i = 5; i <= 8; i++){
digitalWrite(i, LOW);
}
}
void thirtyLeds(){ // Show the 30 Leds version of the Luma Mini
digitalWrite(5, HIGH);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
}
void twentyLeds(){ // Show the 20 Leds version of the Luma Mini
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
digitalWrite(8, HIGH);
}
void twelveLeds(){ // Show the 12 Leds version of the Luma Mini
for (int i = 5; i <= 8; i++){
digitalWrite(i, HIGH);
}
}
My question: How can I send CHAR data from an Android Device to my Arduino? And what to edit on my script?
I have not gone through your code. But looking at the question, I suggests to keep Arduino FW coding away till Android app is tested and developed to a certain level. The way forward could be:
Disconnect HC-06 from other hardware.
Make a loopback connection at HC-06 (i.e Connect TX & RX outputs of HC-06 together.
Then Test your Android application. If app is receiving same as transmitted, then your android app is ok, and you can move on perfecting Arduino FW. Else, the android app needs to be perfected.
You can have a look at a similar question HC-05 bluetooth module on Arduino + Debugging .
Here's the code I use, and it works fine for me.
On the Android side, I'm only including my bluetooth file, which should be easy to fit into your app. It's main advantage is that after your app start it by calling btConnect(), everything else is automatic. It finds and connects to your "HC-06" without further "human intervention". And if you turn off the "HC-06", Android will continue watching for the "HC-06" to come back online, and will auto-connect to it again.
The Arduino Sketch sends a signal once each second. If 10 seconds are missed, the Android assumes the connection has been lost and re-enters connect mode.
ANDROID BLUETOOTH JAVA FILE:
package com.exercise.androidanimbuttons;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.IntentFilter;
import android.widget.Toast;
import android.bluetooth.BluetoothSocket;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.Set;
import android.os.Handler;
public class BlueTooth extends vars {
private Set<BluetoothDevice> pairedDevices;
String address = null;
private ProgressDialog progress = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
InputStream mmInStream = null;
private Handler myHandler = new Handler();
byte[] buffer = new byte[25];
int readBytes;
files filesI = new files();
Handler btH = new Handler();
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private SingBroadcastReceiver mReceiver;
Runnable btSearch;
void stopDiscovery() {
if (myBluetooth.isDiscovering()){
myBluetooth.cancelDiscovery();
}
}
void findCurrentBT() {
if (!myBluetooth.isEnabled()){
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, 0xDEADBEEF);
}
if (myBluetooth.isDiscovering()){
myBluetooth.cancelDiscovery();
}
closeProgress();
progress = ProgressDialog.show(BlueTooth.this, "Searching for headband...",
"MAKE SURE THE HEADBAND IS TURNED ON.");
progress.setCanceledOnTouchOutside(true);
myBluetooth.startDiscovery();
mReceiver = new SingBroadcastReceiver();
IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, ifilter);
checkSearch();
}
private class SingBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String derp = device.getName() + " - " + device.getAddress();
ta(derp);
Toast.makeText(context, derp, Toast.LENGTH_LONG);
if ((device.getName() != null) &&
(device.getName().indexOf("HC-06") == 0) &&
(device.getName().length() == 5))
{
myBluetooth.cancelDiscovery();
address = device.getAddress();
new ConnectBT().execute();
}
}
}
}
private Runnable readBT = new Runnable() {
public void run() {
int i;
int twoByte = 0;
short high = 0, low = 0;
try {
if (mmInStream.available() > 3) {
cnt = 0;
readBytes = mmInStream.read(buffer);
String S = "";
for (i = 0; i < 2; i++)
S += String.format("%03d", buffer[i] & 0xFF)+", ";
high = (short)(buffer[3] & 0xFF);
low = (short)(buffer[2] & 0xFF);
twoByte = ((high << 8) | low);
S += String.format("%03d", twoByte) + "\r\n";
filesI.writeALine("nights","data12.txt",S);
ta(S);
}
} catch (IOException e) {
ta("err:2 " + e.toString());
}
if (btSocket.isConnected())
myHandler.postDelayed(this, 100);
}
};
public void btConnect() {
Disconnect();
findCurrentBT();
}
public void btOn() {
turnOnLed();
}
public void btOff() { turnOffLed(); }
public void btDisconnect() { Disconnect(); }
private void Disconnect()
{
if (btSocket!=null)
{
try
{
btSocket.close();
}
catch (IOException e)
{ msg("Bluetooth Disconnect Error");}
}
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
int len;
byte[] buffer = new byte[400];
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TO".toString().getBytes());
len = btSocket.getInputStream().available();
btSocket.getInputStream().read(buffer,0,len);
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
void closeProgress() {
if (progress != null)
progress.dismiss();
}
private class ConnectBT extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
closeProgress();
progress = ProgressDialog.show(BlueTooth.this, "Connecting to headband...",
"");
progress.setCanceledOnTouchOutside(true);
}
#Override
protected Void doInBackground(Void... devices)
{
try
{
if (btSocket == null || (!btSocket.isConnected()))
{
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
}
catch (IOException e) { }
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (!btSocket.isConnected())
{
msg("Connection Failed. Is the headband turned on?");
}
else
{
msg("Connected.");
try {
mmInStream = btSocket.getInputStream();
myHandler.postDelayed(readBT, 1000);
} catch (IOException e) {
ta("err:1 " + e.toString());
}
}
closeProgress();
}
}
int cnt = 0;
void checkSearch() {
if (btSearch != null)
return;
btSearch = new Runnable(){#Override public void run(){
if ((btSocket != null) && (btSocket.isConnected())) {
cnt--;
if (cnt < -10) {
cnt = 0;
btConnect();
}
} else if (myBluetooth.isDiscovering()) {
cnt++;
}
btH.postDelayed(this, 1000);
fa(cnt);
}};
btH.postDelayed(btSearch,1000);
}
}
MATCHING ARDUINO SKETCH:
byte mini [4];
int battery;
unsigned long mill = millis();
byte moveCnt = 1;
int minuteCnt = 0;
int lastMove = 0;
int moveA, moveB, moveC, LMoveA, LMoveB, LMoveC, totMove, eyes, LEyes, totEyes;
int moveUpA = 0;
int moveDnA = 1000;
int moveUpB = 0;
int moveDnB = 1000;
int moveUpC = 0;
int moveDnC = 1000;
#include <SoftwareSerial.h>
SoftwareSerial mySerial(3, 5); // RX, TX
void setup()
{
Serial .begin(9600);
mySerial.begin(9600);
}
void loop()
{
if (millis() > mill)
{
mill += 100;
minuteCnt++;
// *** EYES ***
eyes = analogRead(A6);
totEyes += abs(eyes-LEyes);
LEyes = eyes;
// *** MOVEMENT *** --KEEP-- moveA = max(0,analogRead(A1) >> 2);
moveA = analogRead(A0);
moveB = analogRead(A1);
moveC = analogRead(A2);
totMove += abs(moveA-LMoveA) + abs(moveB-LMoveB) + abs(moveC-LMoveC);
LMoveA = moveA; LMoveB = moveB; LMoveC = moveC;
// *** SEND SECOND ***
if (minuteCnt >= 10)
{
minuteCnt = 0;
// *** BATTERY ***
battery = analogRead(A5); // battery
mini[2] = (battery & 0xff); // battery low byte
mini[3] = ((battery >> 8) & 0xff); // battery high byte
// *** EYES ***
mini[0] = min(max(0,totEyes-10),255);
totEyes = 0;
// *** MOVEMENT ***
mini[1] = min(max(0,totMove-30),255);
totMove = 0;
Serial.print(mini[0]);
Serial.print(" ");
Serial.print(mini[1]);
Serial.print(" ");
Serial.print(mini[2]);
Serial.print(" ");
Serial.println(mini[3]);
mySerial.write(mini,4);
}
}
}
Hey Guys i have problem ; i can send data from Phone to arduino but i cant send data from arduino to android via Bluetooth on procesing it doesnt work for me . i dont get any Error while compiling but I cant see anything on phone screen .. i used for blueToothSerial.print(XXX); for arduino side .. and used text(readMessage , width,heigth); for processing side in order to see as a text Please check it out . Where is my fault ? . What am I missing ? Thanks in Advance
ARDUINO CODE
#include <SoftwareSerial.h>
#include <Stepper.h>
#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
#define DEBUG_ENABLED 1
#define RELAY 4
SoftwareSerial blueToothSerial(RxD, TxD);
int led = 9 ;
int in1Pin = 10;
int in2Pin = 12;
int in3Pin = 11;
int in4Pin = 13;
data = 100;
Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);
/*----------------------SETUP----------------------------*/
void setup() {
Serial.begin(9600);//low Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13, OUTPUT); // Use onboard LED if required.
pinMode(9,OUTPUT);
motor.setSpeed(30);
pinMode(RELAY,OUTPUT);
setupBlueToothConnection(); //Used to initialise the Bluetooth shield
}
/*----------------------LOOP----------------------------*/
void loop() {
digitalWrite(13, LOW); //Turn off the onboard Arduino LED
char recvChar;
while (1) {
if (blueToothSerial.available()) {//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
//If the character received = 'r' , then change the RGB led to display a RED colour
if (recvChar=='r') {
motor.step(300);
digitalWrite(led,HIGH);
delay(500);
}
//If the character received = 'g' , then change the RGB led to display a GREEN colour
if (recvChar=='g') {
digitalWrite(led,LOW);
motor.step(-300);
}
//If the character received = 'b' , then change the RGB led to display a BLUE colour
if (recvChar=='b') {
digitalWrite(led,HIGH);
digitalWrite(RELAY,HIGH);
}
//If the character received = 'x' , then turn RGB led OFF
if (recvChar=='x') {
digitalWrite(led,LOW);
digitalWrite(RELAY,LOW);
}
}
//You can use the following code to deal with any information coming from the Computer (serial monitor)
if (Serial.available()) {
recvChar = Serial.read();
//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
blueToothSerial.print("burak:");
blueToothSerial.print(data); // data which is defined begin of sketch
}
}
}
//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
blueToothSerial.begin(9600);// BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=HC-05\r\n"); //set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
Serial.println("The slave bluetooth is inquirable!");
delay(2000); // This delay is required.
blueToothSerial.flush();
}
PROCESSING CODE
/* BluetoothApp1: Written by ScottC on 25 March 2013 using
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform
Apwidgets version: r44 */
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import apwidgets.*;
public BluetoothSocket scSocket;
//Used for the GUI**************************************
APWidgetContainer widgetContainer;
APButton redButton, greenButton, blueButton, offButton,yeniButton;
String buttonText="";
int buttonWidth=0;
int buttonHeight=0;
int n=4; //number of buttons
int gap=10; //gap between buttons
boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";
// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";
//Used to send bytes to the Arduino
SendReceiveBytes sendReceiveBT=null;
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==0) {
if (resultCode == RESULT_OK) {
ToastMaster("Bluetooth simdi acildi");
}
else {
ToastMaster("Programi kullanabilmek icin Bluetoot acmalisiniz!!!");
}
}
}
/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
// The Handler that gets information back from the Socket
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
//Do something when writing
break;
case MESSAGE_READ:
//Get the bytes from the msg.obj
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
readMessage = new String(readBuf, 0, msg.arg1);
break;
}
}
};
void setup() {
orientation(LANDSCAPE);
//Setup GUI********************************
buttonWidth=((width/n)-(n*gap));
buttonHeight=(height/2);
widgetContainer = new APWidgetContainer(this); //create new container for widgets
yeniButton = new APButton(700,600,(buttonWidth/2),(buttonHeight/2),"Yeni buton");
redButton =new APButton(0,0 ,400,400, "PERDE YUKARI"); //Create a RED button
// redButton =new APButton((buttonWidth*(n-4)+(gap*1)), gap, buttonWidth, buttonHeight, "RED"); //Create a RED button
greenButton = new APButton((buttonWidth*(n-3)+(gap*2)), gap, buttonWidth, buttonHeight, "GREEN"); //Create a GREEN button
blueButton = new APButton((buttonWidth*(n-2)+(gap*3)), gap, buttonWidth, buttonHeight, "BLUE"); //Create a BLUE button
offButton = new APButton((buttonWidth*(n-1)+(gap*4)), gap, buttonWidth, buttonHeight, "OFF"); //Create a OFF button
widgetContainer.addWidget(redButton); //place red button in container
widgetContainer.addWidget(greenButton); //place green button in container
widgetContainer.addWidget(blueButton);//place blue button in container
widgetContainer.addWidget(offButton);//place off button in container
widgetContainer.addWidget(yeniButton);
background(0); //Start with a black background
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}
/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}
void draw() {
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if (foundDevice) {
if (BTisConnected) {
background(170, 50, 255); // purple screen
}
else {
background(10, 255, 10); // green screen
}
}
//Change the text based on the button being pressed.
text(buttonText, 10, buttonHeight+(buttonHeight/2));
//Display anything received from Arduino
text(readMessage, 10, buttonHeight+(buttonHeight/2)+30);
}
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("Eylem:" + action);
//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("Bulunan Cihaz: " + discoveredDeviceName);
//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("getAddress() = " + discoveredDevice.getAddress());
ToastMaster("getName() = " + discoveredDevice.getName());
int bondyState=discoveredDevice.getBondState();
ToastMaster("getBondState() = " + bondyState);
String mybondState;
switch(bondyState) {
case 10:
mybondState="BOND_NONE";
break;
case 11:
mybondState="BOND_BONDING";
break;
case 12:
mybondState="BOND_BONDED";
break;
default:
mybondState="INVALID BOND STATE";
break;
}
ToastMaster("getBondState() = " + mybondState);
//Change foundDevice to true which will make the screen turn green
foundDevice=true;
//Connect to the discovered bluetooth device (SeeedBTSlave)
if (discoveredDeviceName.equals("HC-05")) {
ToastMaster("BAGLANIYOR!!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}
//Notification if bluetooth device is connected
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster("CIHAZINIZ BAGLANDI");
int counter=0;
while (scSocket==null) {
//do nothing
}
ToastMaster("scSocket" + scSocket);
BTisConnected=true; //turn screen purple
if (scSocket!=null) {
sendReceiveBT = new SendReceiveBytes(scSocket);
new Thread(sendReceiveBT).start();
String red = "r";
byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}
public static byte[] stringToBytesUTFCustom(String str) {
char[] buffer = str.toCharArray();
byte[] b = new byte[buffer.length << 1];
for (int i = 0; i < buffer.length; i++) {
int bpos = i << 1;
b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (byte) (buffer[i]&0x00FF);
}
return b;
}
public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}
#Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();
try {
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
catch (IOException connectException) {
Log.e("ConnectToBluetooth", "Error with Socket Connection");
try {
mySocket.close(); //try to close the socket
}
catch(IOException closeException) {
}
return;
}
}
// Will allow you to get the socket from this class
public BluetoothSocket getSocket() {
return mySocket;
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}
private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}
public void run() {
byte[] buffer = new byte[1024]; // 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 = btInputStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
catch (IOException e) {
Log.e(TAG, "Error reading from btInputStream");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}
/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}
//onClickWidget is called when a widget is clicked/touched
void onClickWidget(APWidget widget) {
String sendLetter = "";
//Disable the previous Background colour changers
foundDevice=false;
BTisConnected=false;
if (widget == redButton) { //if the red button was clicked
buttonText="RED";
background(255, 0, 0);
sendLetter = "r";
}
else if (widget == greenButton) { //if the green button was clicked
buttonText="GREEN";
background(0, 255, 0);
sendLetter = "g";
}
else if (widget == blueButton) { //if the blue button was clicked
buttonText="BLUE";
background(0, 0, 255);
sendLetter = "b";
}
else if (widget == offButton) { //if the off button was clicked
buttonText="OFF";
background(0);
sendLetter = "x";
}
else if (widget == yeniButton) { //if the off button was clicked
buttonText="yeni buton";
background(100,100,100);
sendLetter = "y";
}
byte[] myByte = stringToBytesUTFCustom(sendLetter);
sendReceiveBT.write(myByte);
}
Hello i can send data from android to arduino but i cant send data from arduino to android via Bluetooth on procesing i dont get any Error but I cant see anything on display of android app.. i used for blueToothSerial.print(XXX); for arduino side .. and used text(readMessage , width,heigth); for processing side.
Please check it out . Where is my fault ? . What am I missing ?
Thanks in Advance
** on arduino side**
#include <SoftwareSerial.h>
#include <Stepper.h>
#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
#define DEBUG_ENABLED 1
#define RELAY 4
SoftwareSerial blueToothSerial(RxD, TxD);
int led = 9 ;
int in1Pin = 10;
int in2Pin = 12;
int in3Pin = 11;
int in4Pin = 13;
data = 100;
Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);
/*----------------------SETUP----------------------------*/
void setup() {
Serial.begin(9600);//low Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13, OUTPUT); // Use onboard LED if required.
pinMode(9,OUTPUT);
motor.setSpeed(30);
pinMode(RELAY,OUTPUT);
setupBlueToothConnection(); //Used to initialise the Bluetooth shield
}
/*----------------------LOOP----------------------------*/
void loop() {
digitalWrite(13, LOW); //Turn off the onboard Arduino LED
char recvChar;
while (1) {
if (blueToothSerial.available()) {//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
//If the character received = 'r' , then change the RGB led to display a RED colour
if (recvChar=='r') {
motor.step(300);
digitalWrite(led,HIGH);23
delay(500);
}
//If the character received = 'g' , then change the RGB led to display a GREEN colour
if (recvChar=='g') {
digitalWrite(led,LOW);
motor.step(-300);
}
//If the character received = 'b' , then change the RGB led to display a BLUE colour
if (recvChar=='b') {
digitalWrite(led,HIGH);
digitalWrite(RELAY,HIGH);
}
//If the character received = 'x' , then turn RGB led OFF
if (recvChar=='x') {
digitalWrite(led,LOW);
digitalWrite(RELAY,LOW);
}
}
//You can use the following code to deal with any information coming from the Computer (serial monitor)
if (Serial.available()) {
recvChar = Serial.read();
//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
blueToothSerial.print("burak:");
blueToothSerial.print(data); // data which is defined begin of sketch
}
}
}
//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
blueToothSerial.begin(9600);// BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=HC-05\r\n"); //set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
Serial.println("The slave bluetooth is inquirable!");
delay(2000); // This delay is required.
blueToothSerial.flush();
}
And i have processing sketch .
*on processing side *
/* BluetoothApp1: Written by ScottC on 25 March 2013 using
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform
Apwidgets version: r44 */
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import apwidgets.*;
public BluetoothSocket scSocket;
//Used for the GUI**************************************
APWidgetContainer widgetContainer;
APButton redButton, greenButton, blueButton, offButton,yeniButton;
String buttonText="";
int buttonWidth=0;
int buttonHeight=0;
int n=4; //number of buttons
int gap=10; //gap between buttons
boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";
// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";
//Used to send bytes to the Arduino
SendReceiveBytes sendReceiveBT=null;
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==0) {
if (resultCode == RESULT_OK) {
ToastMaster("Bluetooth simdi acildi");
}
else {
ToastMaster("Programi kullanabilmek icin Bluetoot acmalisiniz!!!");
}
}
}
/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
// The Handler that gets information back from the Socket
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
//Do something when writing
break;
case MESSAGE_READ:
//Get the bytes from the msg.obj
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
readMessage = new String(readBuf, 0, msg.arg1);
break;
}
}
};
void setup() {
orientation(LANDSCAPE);
//Setup GUI********************************
buttonWidth=((width/n)-(n*gap));
buttonHeight=(height/2);
widgetContainer = new APWidgetContainer(this); //create new container for widgets
yeniButton = new APButton(700,600,(buttonWidth/2),(buttonHeight/2),"Yeni buton");
redButton =new APButton(0,0 ,400,400, "PERDE YUKARI"); //Create a RED button
// redButton =new APButton((buttonWidth*(n-4)+(gap*1)), gap, buttonWidth, buttonHeight, "RED"); //Create a RED button
greenButton = new APButton((buttonWidth*(n-3)+(gap*2)), gap, buttonWidth, buttonHeight, "GREEN"); //Create a GREEN button
blueButton = new APButton((buttonWidth*(n-2)+(gap*3)), gap, buttonWidth, buttonHeight, "BLUE"); //Create a BLUE button
offButton = new APButton((buttonWidth*(n-1)+(gap*4)), gap, buttonWidth, buttonHeight, "OFF"); //Create a OFF button
widgetContainer.addWidget(redButton); //place red button in container
widgetContainer.addWidget(greenButton); //place green button in container
widgetContainer.addWidget(blueButton);//place blue button in container
widgetContainer.addWidget(offButton);//place off button in container
widgetContainer.addWidget(yeniButton);
background(0); //Start with a black background
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}
/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}
void draw() {
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if (foundDevice) {
if (BTisConnected) {
background(170, 50, 255); // purple screen
}
else {
background(10, 255, 10); // green screen
}
}
//Change the text based on the button being pressed.
text(buttonText, 10, buttonHeight+(buttonHeight/2));
//Display anything received from Arduino
text(readMessage, 10, buttonHeight+(buttonHeight/2)+30);
}
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("Eylem:" + action);
//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("Bulunan Cihaz: " + discoveredDeviceName);
//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("getAddress() = " + discoveredDevice.getAddress());
ToastMaster("getName() = " + discoveredDevice.getName());
int bondyState=discoveredDevice.getBondState();
ToastMaster("getBondState() = " + bondyState);
String mybondState;
switch(bondyState) {
case 10:
mybondState="BOND_NONE";
break;
case 11:
mybondState="BOND_BONDING";
break;
case 12:
mybondState="BOND_BONDED";
break;
default:
mybondState="INVALID BOND STATE";
break;
}
ToastMaster("getBondState() = " + mybondState);
//Change foundDevice to true which will make the screen turn green
foundDevice=true;
//Connect to the discovered bluetooth device (SeeedBTSlave)
if (discoveredDeviceName.equals("HC-05")) {
ToastMaster("BAGLANIYOR!!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}
//Notification if bluetooth device is connected
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster("CIHAZINIZ BAGLANDI");
int counter=0;
while (scSocket==null) {
//do nothing
}
ToastMaster("scSocket" + scSocket);
BTisConnected=true; //turn screen purple
if (scSocket!=null) {
sendReceiveBT = new SendReceiveBytes(scSocket);
new Thread(sendReceiveBT).start();
String red = "r";
byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}
public static byte[] stringToBytesUTFCustom(String str) {
char[] buffer = str.toCharArray();
byte[] b = new byte[buffer.length << 1];
for (int i = 0; i < buffer.length; i++) {
int bpos = i << 1;
b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (byte) (buffer[i]&0x00FF);
}
return b;
}
public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}
#Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();
try {
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
catch (IOException connectException) {
Log.e("ConnectToBluetooth", "Error with Socket Connection");
try {
mySocket.close(); //try to close the socket
}
catch(IOException closeException) {
}
return;
}
}
// Will allow you to get the socket from this class
public BluetoothSocket getSocket() {
return mySocket;
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}
private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}
public void run() {
byte[] buffer = new byte[1024]; // 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 = btInputStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
catch (IOException e) {
Log.e(TAG, "Error reading from btInputStream");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}
/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}
//onClickWidget is called when a widget is clicked/touched
void onClickWidget(APWidget widget) {
String sendLetter = "";
//Disable the previous Background colour changers
foundDevice=false;
BTisConnected=false;
if (widget == redButton) { //if the red button was clicked
buttonText="RED";
background(255, 0, 0);
sendLetter = "r";
}
else if (widget == greenButton) { //if the green button was clicked
buttonText="GREEN";
background(0, 255, 0);
sendLetter = "g";
}
else if (widget == blueButton) { //if the blue button was clicked
buttonText="BLUE";
background(0, 0, 255);
sendLetter = "b";
}
else if (widget == offButton) { //if the off button was clicked
buttonText="OFF";
background(0);
sendLetter = "x";
}
else if (widget == yeniButton) { //if the off button was clicked
buttonText="yeni buton";
background(100,100,100);
sendLetter = "y";
}
byte[] myByte = stringToBytesUTFCustom(sendLetter);
sendReceiveBT.write(myByte);
}
you forgot to declare the mode (int ) in data on line 14
SoftwareSerial blueToothSerial(RxD, TxD);
int led = 9 ;
int in1Pin = 10;
int in2Pin = 12;
int in3Pin = 11;
int in4Pin = 13;
int data = 100;
I see a fault on the Arduino code - don't think that 23 should be there.
if (recvChar=='r') {
motor.step(300);
digitalWrite(led,HIGH);23
Also - this code requires that you send data from the serial monitor before any Arduino data is sent through bluetooth . Try to echo back the character received by the arduino on this line
Serial.print(recvChar);
Change it to
blueToothSerial.print(recvChar);
Burak have you solved the problem? I am working with Arduino-Android communication for my project. Try to use blueToothSerial.write("burak:");
Also to test your program run some test program. Make some changes with Rx,Tx and you can test it via Arduino Serial Monitor.
/*
Pinout:
8 --> BT module Tx
9 --> BT module Rx
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8, 9); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("I am ready to send some stuff!");
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
}
void loop() // run over and over
{
if (mySerial.available())
Serial.write(mySerial.read());
while (Serial.available())
mySerial.write(Serial.read());
}
Also you could try to use ready app from GooglePlay, like "Bluetooth Terminal". If it works with this then look in your code. Please check this for now and later we will be able to continue.
I download the code Sketch 6 : Send receive bytes From this site : http://arduinobasics.blogspot.com.tr/2013/03/arduinobasics-bluetooth-android_25.html I can see "device discovered : (device name) and FOUND on my screen. But I can't Connect to device ( i try to connect to HC05 Bluetooth module from Galaxy s4). (i have never seen purple screen. i had just green , i think problem is after " foundDevice=true;" Please check it . Its my final year project and i cant do anything without it :(
`/* SendReceiveBytes: Written by ScottC on 25 March 2013 using
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform */
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public BluetoothSocket scSocket;
boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";
// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==0) {
if (resultCode == RESULT_OK) {
ToastMaster("Bluetooth has been switched ON");
}
else {
ToastMaster("You need to turn Bluetooth ON !!!");
}
}
}
/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
// The Handler that gets information back from the Socket
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
//Do something when writing
break;
case MESSAGE_READ:
//Get the bytes from the msg.obj
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
readMessage = new String(readBuf, 0, msg.arg1);
break;
}
}
};
void setup() {
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}
/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}
void draw() {
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if (foundDevice) {
if (BTisConnected) {
background(170, 50, 255); // purple screen
}
else {
background(10, 255, 10); // green screen
}
}
//Display anything received from Arduino
text(readMessage, 10, 10);
}
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("ACTION:" + action);
//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("Discovered: " + discoveredDeviceName);
//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("getAddress() = " + discoveredDevice.getAddress());
ToastMaster("getName() = " + discoveredDevice.getName());
int bondyState=discoveredDevice.getBondState();
ToastMaster("getBondState() = " + bondyState);
String mybondState;
switch(bondyState) {
case 10:
mybondState="BOND_NONE";
break;
case 11:
mybondState="BOND_BONDING";
break;
case 12:
mybondState="BOND_BONDED";
break;
default:
mybondState="INVALID BOND STATE";
break;
}
ToastMaster("getBondState() = " + mybondState);
//Change foundDevice to true which will make the screen turn green
foundDevice=true;
//Connect to the discovered bluetooth device (SeeedBTSlave)
if (discoveredDeviceName.equals("SeeedBTSlave")) {
ToastMaster("Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}
//Notification if bluetooth device is connected
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster("CONNECTED _ YAY");
while (scSocket==null) {
//do nothing
}
ToastMaster("scSocket" + scSocket);
BTisConnected=true; //turn screen purple
if (scSocket!=null) {
SendReceiveBytes sendReceiveBT = new SendReceiveBytes(scSocket);
new Thread(sendReceiveBT).start();
String red = "r";
byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}
public static byte[] stringToBytesUTFCustom(String str) {
char[] buffer = str.toCharArray();
byte[] b = new byte[buffer.length << 1];
for (int i = 0; i < buffer.length; i++) {
int bpos = i << 1;
b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (byte) (buffer[i]&0x00FF);
}
return b;
}
public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}
#Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();
try {
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
catch (IOException connectException) {
Log.e("ConnectToBluetooth", "Error with Socket Connection");
try {
mySocket.close(); //try to close the socket
}
catch(IOException closeException) {
}
return;
}
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}
private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}
public void run() {
byte[] buffer = new byte[1024]; // 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 = btInputStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
catch (IOException e) {
Log.e(TAG, "Error reading from btInputStream");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}
/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}`
hello i changed the code for my final year project preparing .
i removed the some codes related to RGBs. i suggest you to check out the datasheet of the chainable RGB . look at code bottom of datasheet ,you will understand clearly that where came to another codes .
anyway . i used servo motor instead of RGB . and as i said before i changed the name of the bt device as HC-05.
include
#include <SoftwareSerial.h>
//#define uint8 unsigned char
//#define uint16 unsigned int
//#define uint32 unsigned long int
#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
#define DEBUG_ENABLED 1
Servo myservo ;
int led = 9 ;
SoftwareSerial blueToothSerial(RxD, TxD);
/*----------------------SETUP----------------------------*/
void setup() {
myservo.attach(10);
myservo.write(0);
Serial.begin(9600);//low Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13, OUTPUT); // Use onboard LED if required.
pinMode(9,OUTPUT);
setupBlueToothConnection(); //Used to initialise the Bluetooth shield
}
/*----------------------LOOP----------------------------*/
void loop() {
digitalWrite(13, LOW); //Turn off the onboard Arduino LED
char recvChar;
while (1) {
if (blueToothSerial.available()) {//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
//If the character received = 'r' , then change the RGB led to display a RED colour
if (recvChar=='r') {
myservo.write(100);
// Send32Zero(); // begin
// DataDealWithAndSend(255, 0, 0); // first node data
// Send32Zero(); // send to update data
digitalWrite(led,HIGH);
delay(500);
}
//If the character received = 'g' , then change the RGB led to display a GREEN colour
if (recvChar=='g') {
digitalWrite(led,LOW);
myservo.write(50);
}
//If the character received = 'b' , then change the RGB led to display a BLUE colour
if (recvChar=='b') {
// Send32Zero(); // begin
// DataDealWithAndSend(0, 0, 255); // first node data
// Send32Zero(); // send to update data
digitalWrite(led,HIGH);
myservo.write(180);
}
//If the character received = 'x' , then turn RGB led OFF
if (recvChar=='x') {
// Send32Zero(); // begin
// DataDealWithAndSend(0, 0, 0); // first node data
// Send32Zero(); // send to update data
digitalWrite(led,LOW);
myservo.write(0);
}
}
//You can use the following code to deal with any information coming from the Computer (serial monitor)
if (Serial.available()) {
recvChar = Serial.read();
//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
}
}
}
//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
blueToothSerial.begin(9600);// BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=HC-05\r\n"); //set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
Serial.println("The slave bluetooth is inquirable!");
delay(2000); // This delay is required.
blueToothSerial.flush();
}
So I'm trying to communicate with an Arduino Uno through an HC-06 chip, but the SoftwareSerial isn't available for reading, even after a connection has been established. The Processing code was mainly taken from this article:
http://arduinobasics.blogspot.com/2013/03/arduinobasics-bluetooth-android_25.html
Can anyone help me out with this and tell me where the problem lies?
Processing Code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public BluetoothSocket scSocket;
boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";
// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==0) {
if (resultCode == RESULT_OK) {
ToastMaster("Bluetooth has been switched ON");
}
else {
ToastMaster("You need to turn Bluetooth ON !!!");
}
}
}
/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
// The Handler that gets information back from the Socket
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WRITE:
//Do something when writing
break;
case MESSAGE_READ:
//Get the bytes from the msg.obj
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
readMessage = new String(readBuf, 0, msg.arg1);
break;
}
}
};
void setup() {
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}
/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
}
}
void draw() {
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if (foundDevice) {
if (BTisConnected) {
background(170, 50, 255); // purple screen
}
else {
background(10, 255, 10); // green screen
}
}
//Display anything received from Arduino
text(readMessage, 10, 10);
}
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("ACTION:" + action);
//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("Discovered: " + discoveredDeviceName);
//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(discoveredDevice.getName()=="HC-06"){
ToastMaster("getAddress() = " + discoveredDevice.getAddress());
ToastMaster("getName() = " + discoveredDevice.getName());
int bondyState=discoveredDevice.getBondState();
ToastMaster("getBondState() = " + bondyState);
String mybondState;
switch(bondyState) {
case 10:
mybondState="BOND_NONE";
break;
case 11:
mybondState="BOND_BONDING";
break;
case 12:
mybondState="BOND_BONDED";
break;
default:
mybondState="INVALID BOND STATE";
break;
}
ToastMaster("getBondState() = " + mybondState);
}
//Change foundDevice to true which will make the screen turn green
foundDevice=true;
//Connect to the discovered bluetooth device (SeeedBTSlave)
if (discoveredDeviceName.equals("HC-06")) {
ToastMaster("Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}
//Notification if bluetooth device is connected
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster("CONNECTED _ YAY");
while (scSocket==null) {
//do nothing
}
ToastMaster("scSocket " + scSocket);
BTisConnected=true; //turn screen purple
if (scSocket!=null) {
SendReceiveBytes sendReceiveBT = new SendReceiveBytes(scSocket);
new Thread(sendReceiveBT).start();
String red = "r";
byte[] myByte = stringToBytesUTFCustom(red);
sendReceiveBT.write(myByte);
}
}
}
}
public static byte[] stringToBytesUTFCustom(String str) {
char[] buffer = str.toCharArray();
byte[] b = new byte[buffer.length << 1];
for (int i = 0; i < buffer.length; i++) {
int bpos = i << 1;
b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (byte) (buffer[i]&0x00FF);
}
return b;
}
public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothChip) {
btShield = bluetoothChip;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}
#Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();
try {
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
catch (IOException connectException) {
Log.e("ConnectToBluetooth", "Error with Socket Connection");
try {
mySocket.close(); //try to close the socket
}
catch(IOException closeException) {
}
return;
}
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}
private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
private OutputStream btOutputStream = null;
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
println("Error when getting input or output Stream");
}
}
public void run() {
byte[] buffer = new byte[1024]; // 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 = btInputStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
}
catch (IOException e) {
println("Error reading from btInputStream");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
println("Error when writing to btOutputStream");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
println("Error when closing the btSocket");
}
}
}
/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay) {
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}
Arduino Code:
int data;
char character;
int start_flag = 0;
#include <SoftwareSerial.h>
int bluetoothTx = 3;
int bluetoothRx = 2;
SoftwareSerial blue = SoftwareSerial(bluetoothRx, bluetoothTx);
void setup(){
blue.begin(9600);
pinMode(13, OUTPUT);
pinmode(bluetoothRx, INPUT);
pinmode(bluetoothTx, OUTPUT);
digitalWrite(13, LOW);
}
void loop() {
if (blue.available() > 0) {
digitalWrite(13, HIGH);
character = (char) blue.read();
if (character != '#') {
start_flag = 1;
}
if(character == 't'){
start_flag = 0;
}
} else {
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
if (start_flag == 1) {
//digitalWrite(13, HIGH);
blue.print(data); //data that was acquired by internal ADC
}
}
I think you need to change the order of your lines within the Arduino setup() code:
And you also need some code to initialise your bluetooth module.
This is what I think you need to change it to:
void setup(){
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
pinmode(bluetoothRx, INPUT);
pinmode(bluetoothTx, OUTPUT);
//You may need to modify this to suit your bluetooth module
//This is used to initialise the bluetooth module
blue.begin(9600); //*************
blue.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blue.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
blue.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blue.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
blue.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
delay(2000); // This delay is required.
blue.flush();
}
Hello i used to same code from #ScottC :)
its old post but maybe someone will have same problem anytime .
the problem is blue.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
change it to
blue.print("\r\n+STNA=HC-06\r\n"); //set the bluetooth name as "SeeedBTSlave"
"OR CHANGE IT AS YOUR BLUETOOTH DEVICE NAME . ( i assumed is HC-06)
pinmode(bluetoothRx, INPUT);
pinmode(bluetoothTx, OUTPUT);
Capital "M" in pinMode