Android Bluetooth to Arduino

I copied and pasted this; ArduinoBluetoothAndroid - Pastebin.com into sketch and then clicked upload. It said there is an error: stray '@' in program.

All I want to do is enable my Arduino Duemilanove to except bluetooth to control a servo motor using the Android App on Google Play.

I have no knowledge of all this Arduino stuff so I am hoping that someone here can guide a dummy step by step.

I promise I will go away then.

Trust I am trying but what am I doing wrong?

error:'class HardwareSerial' has no member named 'parseint'

Also in box below (in sketh)...

in function 'void loop () ':
error: 'class HardwareSerial' has no member named 'parseint'

#include <Servo.h>

Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created

int pos = 0; // variable to store the servo position
int motor = 0;

void setup()
{
Serial.begin(9600); // initialize serial:
myservo.attach(9); // attaches the servo on pin 9 to the servo object

Serial.print("Arduino control Servo Motor Connected OK");
Serial.print('\n');
}

void loop()
{
// if there's any serial available, read it:
while (Serial.available() > 0) {

// look for the next valid integer in the incoming serial stream:
motor = Serial.parseInt();

// do it again:
pos = Serial.parseInt();

// look for the newline. That's the end of your sentence:
if (Serial.read() == '\n') {

myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position

// print the three numbers in one string as hexadecimal:
Serial.print("Data Response : ");
Serial.print(motor, HEX);
Serial.print(pos, HEX);

}
}
}

//for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
//{ // in steps of 1 degree
// myservo.write(pos); // tell servo to go to position in variable 'pos'
// delay(15); // waits 15ms for the servo to reach the position
//}
//for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
//{
// myservo.write(pos); // tell servo to go to position in variable 'pos'
// delay(15); // waits 15ms for the servo to reach the position
//}

//val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
//val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
//myservo.write(val); // sets the servo position according to the scaled value
//delay(15);

The Sketch then highlights this...

motor = Serial.parseInt();

Hi !

I am sending a letter from an Android phone to my Arduino, using Bluetooth.
When I send the letter A I get the number 255 on the Serial Monitor. And when I send the letter B I get the same number, 255. Any letter I send I get 255...

I can't make my led go on and off...

That is my code on the Arduino:

int Led = 0; // variavel que recebe a informação do bluetooth

void setup() {

Serial.begin(9600);// Inicializa a serial
pinMode(13, OUTPUT);
//Serial.flush();

}

void loop() {
/*
Serial.flush();
delay(500); //Espero meio segundo
Led = Serial.read(); // Recebe o valor via bluetooth
delay(500); //Espero meio segundo
*/
//if (Serial.available() > 0) {
Led = Serial.read(); // Recebe o valor via bluetooth
delay(500); //Espero meio segundo

// say what you got:
Serial.print("I received: ");
Serial.println(Led, DEC);
//}
if (Led == 255){
digitalWrite(13, HIGH);
}
else if (Led == 254) {
digitalWrite(13, LOW);
}
}

I am using three diferent types of apps on the Android: Blueserial, S2Terminal for Bluetooth and ITEAD BT.

Can anyone help me ?

Thanks !

popfansin:
Hello,

I tried your codes but I can't seem to turn ON/OFF the led using your writeData(). I think arduino does not receive the value from android. Please can you help me figure it out. By the way. Here's my sketch:

int led = 13;
char inbyte = '0';
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}

void loop() {

if (Serial.available() > 0)
{
inbyte = Serial.read();
if (inbyte == '0')
{
//LED off
digitalWrite(led, LOW);
}
if (inbyte == '1')
{
//LED on
digitalWrite(led, HIGH);
}
}
}

I'm having the same problem here =/

It might be a bit late, but the code goes in your Main Activity at least that's where I put it.
If you want to learn more about Android Development, here's a pretty nice video tutorial :

The website covers lots of programming languages.
(I don't own this website, nor i'm related to it, I just find it very good and pretty complete at least to start)

Can someone share an Arduino code that worked with this Android code?

Thanks for the post.
I will also try this hope i will learn new things.It's a interesting concept.

Hi please find another nice article on this
http://knowledge-cess.com/arduino-android-interfacing-example-code-and-troubleshooting/

Hi please find another nice article on this
http://knowledge-cess.com/arduino-android-interfacing-example-code-and-troubleshooting/

Hey,you can try this article to connect arduino with android using bluetooth

You might be interested in an Android app called Bluetooth Control Keypad. It allows you to configure up to 25 buttons to send both printable and non-printable ASCII characters to a Bluetooth-enabled device. I use it to control an Arduino-based XY table and a little Arduino music maker. You can find information at http://bluetoothkeypad.eclecticstudio.com.

I want to try to introduce android app to programming Arduino Uno via bluetooth, https://play.google.com/store/apps/details?id=com.bluino.bluinoloader

Jon17:
Hello everybody !

I'm quite new to the world of Arduino, but since the beginning I wanted to use my phone (an Android) to control my Arduino through Bluetooth. (I'm also a beginner to Android by the way).

I did tones of research online in order to find something relevant and simple in order to do that. But I miserably failed.
But since patience is a virtue, I managed to gather information from almost everywhere and found this.

Without any pretension, here is a short how-to tutorial.
Maybe this post will help, maybe not, but at least I tried ^_^.

You need a Bluetooth Adapter plugged to your Arduino obviously.
For the Arduino code, I simply used the blink code and mixed it with Serial.read() function.
http://arduino.cc/en/Serial/read

I'm not gonna explain how android works but here's the link to download the IDE.
Download Android Studio & App Tools - Android Developers

Before anything, I want to add something, I'm not a pro in programming, like not at all, and I'm not a native English speaker, so I apologize for the mistakes I will make and for the non-scholarly terms I will use. (Remember that while reading, please).

Since I just want to use my App with my arduino, I hardcoded its Mac Address in the code.

First thing first you're gonna need to test if the bluetooth in your phone is enabled or not and if you can use it.

	private void CheckBt() {
	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

	if (!mBluetoothAdapter.isEnabled()) {
		Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
				Toast.LENGTH_SHORT).show();

/* It tests if the bluetooth is enabled or not, if not the app will show a message. */
}

	if (mBluetoothAdapter == null) {
		Toast.makeText(getApplicationContext(),
				"Bluetooth null !", Toast.LENGTH_SHORT)
				.show();
	}
}



You can invoke that method in the onCreate method or whenever you want to (before trying to make a connection obviously).

The connect part is quite simple, in that case the method was triggered by clicking on a button :




public void Connect() {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d("", "Connecting to ... " + device);
mBluetoothAdapter.cancelDiscovery();
try {
                       btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
/* Here is the part the connection is made, by asking the device to create a RfcommSocket (Unsecure socket I guess), It map a port for us or something like that */
btSocket.connect();
Log.d("", "Connection made.");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d("", "Unable to end the connection");
}
Log.d("", "Socket creation failed");
}

	beginListenForData();

/* this is a method used to read what the Arduino says for example when you write Serial.print("Hello world.") in your Arduino code */
}




Then the method to actually Send stuff to the arduino.



private void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}

	String message = data;

/* In my example, I put a button that invoke this method and send a string to it */
byte[] msgBuffer = message.getBytes();

	try {
		outStream.write(msgBuffer);
	} catch (IOException e) {
		Log.d(TAG, "Bug while sending stuff", e);
	}
}



Finally the part where the Android application actually read data just like I said earlier.



public void beginListenForData()   {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
}

        Thread workerThread = new Thread(new Runnable()
        {
            public void run()
            {                
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try 
                    {
                        int bytesAvailable = inStream.available();                        
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            inStream.read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == 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()
                                        {
                                        	
                                        	if(Result.getText().toString().equals("..")) {
                                        		Result.setText(data);
                                        	} else {
                                        		Result.append("\n"+data);
                                        	}
                                        	
                                        	/* You also can use Result.setText(data); it won't display multilines
                                        	*/
                                        	
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    } 
                    catch (IOException ex) 
                    {
                        stopWorker = true;
                    }
               }
            }
        });

        workerThread.start();
    }



I took it online so I can't really tell you much about that other that it works.
From what I can understand this method creates a Thread that checks whether there's something or not in the buffer and display it in the Result TextView.

Don't forget to add those two lines in your manifest.

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>

Otherwise the app will crash.

Here's the full code :
http://pastebin.com/a7wPqA3d

There you go.

Hope it wasn't too useless and boring and maybe somewhat interesting, it helped me to understand Bluetooth SPP.

Maybe it will be simpler to upload the project so, here it is.

It's almost 6am 12/01/2015 and I just created this account to say: THANK YOU!
I wish you're doing fine @Jon17.

Best!

In this tutorial connect Arduino and Android by Bluetooth and App inventor.

http://kio4.com/appinventor/9bluetootharduino.htm

I got my Bluetooth shield to connect to my phone but I can't seem to get my arduino to do any functions. Like if I hook up an LED and put in the code for if the arduino receives the character "1" then turn the LED on but it doesn't. It just prints the number 1 to the serial monitor.

Any suggestions?

i have hc 06 blutooth module , i am using with android , it is connected but does not work . i want to just turn on led simple app, please help me,i have hc 06 blutooth module it is connected but not working i am using arduino uno
it is not working with any app in android , i am mechlogy,

Thanks for sharing, this is very cool

Hi,

I am new user to this site. and iam getting problem when connected to bluetooth device to arduino uno i got the result in in serial moniter, but did not get result when connect blutooth to android phone
give me any advices