element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Sending serial data from Arduino to Android via Bluetooth - NOT ANSWERED Yet
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Verified Answer
  • Replies 23 replies
  • Answers 7 answers
  • Subscribers 396 subscribers
  • Views 5788 views
  • Users 0 members are here
  • bluetooth
  • arduino
Related

Sending serial data from Arduino to Android via Bluetooth - NOT ANSWERED Yet

Former Member
Former Member over 10 years ago

Hi all,

 

I've been working on my Arduino project for quite a while now, managed to process the incoming data in the Arduino and display it on LCD (data is coming from a simulation on the laptop). But I cannot manage to view this data on my Android App (used MIT App Inventor) via Bluetooth (HC-06). I have managed to do this but after a week I tested it again and found some errors (I think problem was with my hardware) therefore (silly me) I didnt save the sketch, therefore blocks in MIT App Inventor are 100% working.

 

Also, I am connecting RX pin of Bluetooth through a voltage divider with pin 7.  Any ideas pls?

 

Arduino sketch:

 

#include <SoftwareSerial.h>

#include <LiquidCrystal.h>

 

byte myByte; // Storing the incoming data from serial port

int txPin = 7;

int rxPin =6;

 

lcd(12,11,5,4,3,2) //pin of lcd   ****I know this is not the exact command

SoftwareSerial BlueToothConnect(txPin, rxPin);

 

pinMode(rxPin, INPUT);

pinMode(txPin, OUTPUT);

 

void setup(){

lcd.begin(16,2);

Serial.begin(9600);  //Serial communication

 

}

void loop(){

if(Serial.available(){

lcd.clear();

while(Serial.available()>0){       //Until data is being found in Serial, turn on serial on Bluetooth

BlueToothConnect.begin(9600);

myByte = Serial.read(); //reading the myByte data

lcd.write(myByte);  //showing data on LCD

Serial.write(myByte) ; //Showing data on serial monitor

 

txPin = digitalWrite(myByte);   //writing myByte content on pin 7 (txPin)

BlueToothConnect.write(txPin);   //  BlueToothConnect.print(txPin);  //displaying content of txPin to be view on Android display

 

}

 

Message was edited by: Lor B

  • Sign in to reply
  • Cancel

Top Replies

  • neilk
    neilk over 10 years ago in reply to Former Member +2 verified
    Hi lorrainebarbara I've never used SoftwareSerial successfully, although I've been trying to recently to reprogram an HC05 (Master/Slave Bluetooth). This requires the use of SoftWare serial ad so far I…
  • Former Member
    Former Member over 10 years ago in reply to neilk +2 suggested
    Hi neilk , Thank you so much I have managed to incorporate (and change) some of the program you ve published, worked Here is my whole sketch. Thanks alot for your help!! //Sending data serially to Android…
  • gadget.iom
    gadget.iom over 7 years ago in reply to happyforever +2 suggested
    Are you trying to send sensor values or text typed into the serial monitor? All of the other references to bluetooth.print are commented out. Try putting: bluetooth.print("Sending Init String"); // Test…
Parents
  • happyforever
    0 happyforever over 7 years ago

    I can receive data from android but cant send data to android, please help me to solve. The below is my code.

    #include <SoftwareSerial.h>

     

     

    int bluetoothTx = 13;  // TX-O pin of bluetooth mate, Arduino D2

    int bluetoothRx = 14;  // RX-I pin of bluetooth mate, Arduino D3

     

     

    char incomingByte; // incoming data

    int sensorPin = A0;   

    int ledPin = 11;      // select the pin for the LED

    int ledPin2 = 12;

    int sensorValue = 0;  // variable to store the value coming from the sensor

    int rTrigPin = 6;

    int rEchoPin = 7;

    int trigPin = 9;

    int echoPin = 10;

    int lTrigPin = 4;

    int lEchoPin = 5;

     

     

    // defines variables

    long rDuration;

    int rDistance;

    long duration;

    int distance;

    long lDuration;

    int lDistance;

     

     

     

     

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

     

     

    void setup() {

     

     

      Serial.begin(115200);

     

      bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps

      //bluetooth.print("$");  // Print three times individually

      //bluetooth.print("$");

      //bluetooth.print("$");  // Enter command mode

      //delay(100);  // Short delay, wait for the Mate to send back CMD

      //bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity

      // 115200 can be too fast at times for NewSoftSerial to relay the data reliably

      bluetooth.begin(9600);  // Start bluetooth serial at 9600

     

      pinMode(rTrigPin, OUTPUT); // Sets the rTrigPin as an Output

      pinMode(rEchoPin, INPUT); // Sets the rEchoPin as an Input

      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

      pinMode(echoPin, INPUT); // Sets the echoPin as an Input

      pinMode(lTrigPin, OUTPUT); // Sets the lTrigPin as an Output

      pinMode(lEchoPin, INPUT); // Sets the lEchoPin as an Input

     

     

      // declare the ledPin as an OUTPUT:

      pinMode(ledPin, OUTPUT);

      pinMode(ledPin2, OUTPUT);

     

     

    }

     

    /*void loop() {

      // read the value from the sensor:

      sensorValue = analogRead(sensorPin);

      // turn the ledPin on

      digitalWrite(ledPin, LOW);

      // stop the program for <sensorValue> milliseconds:

      delay(sensorValue);

      // turn the ledPin off:

      digitalWrite(ledPin, HIGH);

      // stop the program for for <sensorValue> milliseconds:

      delay(sensorValue);

      }*/

     

     

    void loop()

    {   

            digitalWrite(rTrigPin, LOW);

            delayMicroseconds(2);

            digitalWrite(rTrigPin, HIGH);

            delayMicroseconds(10);

            digitalWrite(rTrigPin, LOW);

            rDuration = pulseIn(rEchoPin, HIGH);

            rDistance = (rDuration / 2) / 29.1;

         

            digitalWrite(trigPin, LOW);

            delayMicroseconds(2);

            digitalWrite(trigPin, HIGH);

            delayMicroseconds(10);

            digitalWrite(trigPin, LOW);

            duration = pulseIn(echoPin, HIGH);

            distance = (duration / 2) / 29.1;

         

            digitalWrite(lTrigPin, LOW);

            delayMicroseconds(2);

            digitalWrite(lTrigPin, HIGH);

            delayMicroseconds(10);

            digitalWrite(lTrigPin, LOW);

            lDuration = pulseIn(lEchoPin, HIGH);

            lDistance = (lDuration / 2) / 29.1;

         

            sensorValue = analogRead(sensorPin); 

     

     

              if (rDistance <= 221 || distance <= 221 || lDistance <= 221)

            {

              if (sensorValue <= 140)

              {

                digitalWrite(ledPin, LOW);

                digitalWrite(ledPin2, LOW);

              }

              else

              {

                digitalWrite(ledPin, HIGH);

                digitalWrite(ledPin2, HIGH);

              }

               

            }

            else if (rDistance > 221 || distance > 221 || lDistance > 221)

            {

              if (sensorValue <= 140)

              {

                digitalWrite(ledPin, LOW);

                digitalWrite(ledPin2, LOW);

              }

              else

              {

                digitalWrite(ledPin, HIGH);

                digitalWrite(ledPin2, HIGH);

              }

            }

     

      if (bluetooth.available()) // If the bluetooth sent any characters

      {

        // Send any characters the bluetooth prints to the serial monitor

       

        Serial.println((char)bluetooth.read());

        incomingByte = bluetooth.read();

     

     

       

        if(incomingByte == '1') { 

     

     

             Serial.println("Music is pause and now you are in dangerous situation.");  // print message

             //bluetooth.print("1");

            

             //delay(1000);

        }

     

     

     

        if(incomingByte == '0') {

         

              digitalWrite(ledPin, HIGH);

              digitalWrite(ledPin2, HIGH);

              Serial.println("Alert signal OFF and music would not pause when in dangerous situation.");  // print message

              //bluetooth.print("0");

              //delay(1000);

              //break;

             

        }

      }

     

     

      if (Serial.available()>0) // If stuff was typed in the serial monitor

      {

        int bytes=Serial.available();

        //Serial.readBytes(buffer, startPosition, bytes);

     

        bluetooth.print((char)Serial.read());

       

      }

     

     

     

    }









    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • neilk
    0 neilk over 7 years ago in reply to happyforever

    Hi happyforever I have replied to you as well, but at the other location. I was already composing my reply there when mcb1 replied here.

     

    Neil

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Reply
  • neilk
    0 neilk over 7 years ago in reply to happyforever

    Hi happyforever I have replied to you as well, but at the other location. I was already composing my reply there when mcb1 replied here.

     

    Neil

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Children
  • happyforever
    0 happyforever over 7 years ago in reply to neilk

    Hi Neil, can you help me check my android code got any problem? I think maybe is android part cause this error.

     

    Below is my android code(MainActivity.java)

     

    package com.example.helloworld.ninjatechsmartheadphone;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.reflect.Method;
    import java.util.UUID;

    import android.support.v7.app.AppCompatActivity;
    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.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.media.MediaPlayer;
    import android.widget.Toast;


    public class MainActivity extends AppCompatActivity {

       private static final String TAG = "bluetooth";

       Button on;
       Button off;
       Button button;
       TextView txtArduino;
       Handler h;

      final int RECIEVE_MESSAGE = 1;  // Status for Handler
       private BluetoothAdapter btAdapter = null;
      private BluetoothSocket btSocket = null;
      private StringBuilder sb = new StringBuilder();

      private ConnectedThread mConnectedThread;

       // SPP UUID service
       private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


      private static String address = "98:D3:31:FD:21:00";

       @Override
       public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

      final MediaPlayer catSoundMediaPlayer = MediaPlayer.create(this, R.raw.afi);

       button = (Button) findViewById(R.id.play);
       on = (Button) findViewById(R.id.on);
       off = (Button) findViewById(R.id.off);
       txtArduino = (TextView) findViewById(R.id.txtArduino);  // for display the received data from the Arduino

       h = new Handler() {

       public void handleMessage(android.os.Message msg) {

      Log.d("msg", "msg.what is " + msg.what);
      switch (msg.what) {

       case RECIEVE_MESSAGE:  // if receive massage
       byte[] readBuf = (byte[]) msg.obj;
       Toast.makeText(getBaseContext(), "I want try try try", Toast.LENGTH_SHORT).show();
       String strIncom = new String(readBuf, 0, msg.arg1);  // create string from bytes array
       sb.append(strIncom);  // append string
       int endOfLineIndex = sb.indexOf("\r\n");  // determine the end-of-line
       if (endOfLineIndex > 0) {  // if end-of-line,
       String sbprint = sb.substring(0, endOfLineIndex);  // extract string
       sb.delete(0, sb.length());  // and clear
       txtArduino.setText("Data from Arduino: " + sbprint);  // update TextView
      //off.setEnabled(true);
      // on.setEnabled(true);
       }

      Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
      break;

      default:

      Toast.makeText(getBaseContext(), "I want try", Toast.LENGTH_LONG).show();
       Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
       }

      }

     

       ;
       };

       btAdapter = BluetoothAdapter.getDefaultAdapter();  // get Bluetooth adapter
       checkBTState();

       button.setOnClickListener(new OnClickListener() {

       public void onClick(View v) {

     

       catSoundMediaPlayer.start();

       //Intent intent = new Intent("android.intent.action.MUSIC_PLAYER");
      //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      //startActivity(intent);
       }

      });

       on.setOnClickListener(new OnClickListener() {

       public void onClick(View v) {

       //on.setEnabled(false);
       mConnectedThread.write("1");  // Send "1" via Bluetooth
       Toast.makeText(getBaseContext(), "Turn on Alert Signal", Toast.LENGTH_SHORT).show();
       }

      });

       off.setOnClickListener(new OnClickListener() {

       public void onClick(View v) {

       //off.setEnabled(false);
       mConnectedThread.write("0");  // Send "0" via Bluetooth
       Toast.makeText(getBaseContext(), "Turn off Alert Signal", Toast.LENGTH_SHORT).show();
       }

      });

       }

     

     

       private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

     

       try {

       final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
      return (BluetoothSocket) m.invoke(device, MY_UUID);
       } catch (Exception e) {

      Log.e(TAG, "Could not create Insecure RFComm Connection",e);
       }

     

       return  device.createRfcommSocketToServiceRecord(MY_UUID);
       }

     

     

       @Override
       public void onResume() {

       super.onResume();

       Log.d(TAG, "...onResume - try connect...");

       // Set up a pointer to the remote node using it's address.
       BluetoothDevice device = btAdapter.getRemoteDevice(address);

       // Two things are needed to make a connection:
      // A MAC address, which we got above.
      // A Service ID or UUID. In this case we are using the
      // UUID for SPP.

       try {

       btSocket = createBluetoothSocket(device);
       } catch (IOException e) {

      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
       }

     

       // Discovery is resource intensive. Make sure it isn't going on
      // when you attempt to connect and pass your message.
       btAdapter.cancelDiscovery();

       // Establish the connection. This will block until it connects.
       Log.d(TAG, "...Connecting...");
      try {

       btSocket.connect();
       Log.d(TAG, "....Connection ok...");
       Toast.makeText(getBaseContext(), "Connected", Toast.LENGTH_SHORT).show();
       } catch (IOException e) {

       try {

       //Log.d(TAG, "....111...");
      //Toast.makeText(getBaseContext(), "1", Toast.LENGTH_SHORT).show();
       btSocket.close();
       } catch (IOException e2) {

      errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
       //Toast.makeText(getBaseContext(), "2", Toast.LENGTH_SHORT).show();
       }

      }

     

       // Create a data stream so we can talk to server.
       Log.d(TAG, "...Create Socket...");

       mConnectedThread = new ConnectedThread(btSocket);
       mConnectedThread.start();
       }

     

       @Override
       public void onPause() {

       super.onPause();

       Log.d(TAG, "...In onPause()...");

      try  {

       btSocket.close();
       } catch (IOException e2) {

      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
       }

      }

     

       private void checkBTState() {

       // Check for Bluetooth support and then check to make sure it is turned on
      // Emulator doesn't support Bluetooth and will return null
       if(btAdapter==null) {

      errorExit("Fatal Error", "Bluetooth not support");
       } else {

       if (btAdapter.isEnabled()) {

      Log.d(TAG, "...Bluetooth ON...");
       } else {

       //Prompt user to turn on Bluetooth
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
       startActivityForResult(enableBtIntent, 1);
       }

      }

      }

     

       private void errorExit(String title, String message){

      Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
       finish();
       }

     

       private class ConnectedThread extends Thread {

       private final InputStream mmInStream;
      private final OutputStream mmOutStream;

      public ConnectedThread(BluetoothSocket socket) {

      InputStream tmpIn = null;
       OutputStream tmpOut = null;

       // Get the input and output streams, using temp objects because
      // member streams are final
       try {

      tmpIn = socket.getInputStream();
       tmpOut = socket.getOutputStream();
       } catch (IOException e) { }

     

       mmInStream = tmpIn;
       mmOutStream = tmpOut;
       }

     

       public void run() {

       byte[] buffer = new byte[256];  // buffer store for the stream
       int bytes; // bytes returned from read()
      //Toast.makeText(getBaseContext(), "qqqqqqq", Toast.LENGTH_SHORT).show();

      // Keep listening to the InputStream until an exception occurs
       while (true) {

       try {

       // Read from the InputStream
       bytes = mmInStream.read(buffer);  // Get number of bytes and message in "buffer"
       h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();  // Send to message queue Handler
       Toast.makeText(getBaseContext(), "q111q", Toast.LENGTH_SHORT).show();
       } catch (IOException e) {

       //Toast.makeText(getBaseContext(), "qq222qq", Toast.LENGTH_SHORT).show();
       break;
       }

      }

      }

     

       /* Call this from the main activity to send data to the remote device */
       public void write(String message) {

      Log.d(TAG, "...Data to send: " + message + "...");
      byte[] msgBuffer = message.getBytes();
      try {

       mmOutStream.write(msgBuffer);
       } catch (IOException e) {

      Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
       }

      }

      }

    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
  • happyforever
    0 happyforever over 7 years ago in reply to happyforever

    I had debug the android code, found that the I cant run into the switch case. Can anyone help me to correct it? Thanks

     

       h = new Handler() {

       public void handleMessage(android.os.Message msg) {

      Log.d("msg", "msg.what is " + msg.what);
      switch (msg.what) {

       case RECIEVE_MESSAGE:  // if receive massage
       byte[] readBuf = (byte[]) msg.obj;
       Toast.makeText(getBaseContext(), "I want try try try", Toast.LENGTH_SHORT).show();
       String strIncom = new String(readBuf, 0, msg.arg1);  // create string from bytes array
       sb.append(strIncom);  // append string
       int endOfLineIndex = sb.indexOf("\r\n");  // determine the end-of-line
       if (endOfLineIndex > 0) {  // if end-of-line,
       String sbprint = sb.substring(0, endOfLineIndex);  // extract string
       sb.delete(0, sb.length());  // and clear
       txtArduino.setText("Data from Arduino: " + sbprint);  // update TextView
      //off.setEnabled(true);
      // on.setEnabled(true);
       }

      Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
      break;

      default:

      Toast.makeText(getBaseContext(), "I want try", Toast.LENGTH_LONG).show();
       Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
       }

      }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • neilk
    0 neilk over 7 years ago in reply to happyforever

    Sorry - I develop my android Apps at a much higher level using MIT Appinventor

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube