Home>
I want to connect Android to Arduino via Bluetooth

I am a beginner. Always I am indebted.

I want to connect Android and Arduino via Bluetooth.
First of all, let's try to send text from Android app to Arduino
Program based on this site , Tried wiring. (ArduinoStudio uses AndroidIDE)

But
There is no error on AndroidStudio or ArduinoIDE, but when you press the "connect button" in the Android app,
An error is displayed and text cannot be sent.
(The device is connected to RN-42 via Bluetooth)

I want to understand how it works because it is written on the site I am referring to.

If i have any questions about connecting Android apps to Arduino via Bluetooth,
I would appreciate your teaching.
Thanks for your consideration.

Error message

The error text below is the error text displayed on the actual machine.

java.lang NullPointerException: Attempt to invoke virtual method 'android bluetooth.BlutetoothSocket android.bluetooth.Bluetooth Device.createRfcommSocket ToServiceRecrod (java.util.UUID)' on a null object reference</code></pre >
<strong>Error displayed on actual device</strong>
<p>Initial screen<br />
</p>
<p>After pressing the CONNECT button<br />
<br />
It looks like this and it does n’t work ...<br />
(The device is connected to RN-42 via Bluetooth)</p>
<strong>Applicable source code</strong>
<p>I'll list it just in case.<br />
ArduinoStudio's activity_main/xml and AndroidManifest.xml are also described with reference to the site.</p>
<pre><code data-language = "ArduinoIDE"># include<SoftwareSerial.h>
SoftwareSerial android (2,3);
void setup () {
  // Set the serial port for Bluetooth
  android.begin (115200);
  // For arduino serial monitor
  Serial.begin (19200);
  Serial.write ("init");
}
void loop () {
  if (android.available ()) {
    Serial.println (android.read ());
  }
  if (Serial.available ()) {
    android.write (Serial.read ());
  }
}
package com.example.gcluemybluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

// public class MainActivity extends ActionBarActivity implements Runnable, View.OnClickListener {
public class MainActivity extends AppCompatActivity implements Runnable, View.OnClickListener {
    / * tag * /
    private static final String TAG = "BluetoothSample";
    / * Bluetooth Adapter * /
    private BluetoothAdapter mAdapter;/ * Bluetooth device * /
    private BluetoothDevice mDevice;
    / * Bluetooth UUID * /
    private final UUID MY_UUID = UUID.fromString ("00001101-0000-1000-8000-00805F9B34FB");
    / * Device name * /
    private final String DEVICE_NAME = "RNBT-205F";
    / * Soket * /
    private BluetoothSocket mSocket;
    / * Thread * /
    private Thread mThread;
    / * Represents Thread status * /
    private boolean isRunning;
    / ** Connect button * /
    private Button connectButton;
    / ** LED ON button * /
    private Button ledOnButton;
    / ** LED OFF button * /
    private Button ledOffButton;
    /** status. */
    private TextView mStatusTextView;
    / ** Value received from Bluetooth. * /
    private TextView mInputTextView;
    / ** Action (status display) * /
    private static final int VIEW_STATUS = 0;
    / ** Action (get string).
    private static final int VIEW_INPUT = 1;
    / ** Bluetooth OutputStream * /
    OutputStream mmOutputStream = null;
    / ** Connect status confirmation flag * /
    private boolean connectFlg = false;
    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        // Display the view set in Layout
        setContentView (R.layout.activity_main);
        // TextView settings (associate with settings set in Layout)
        mInputTextView = (TextView) findViewById (R.id.inputValue);
        mStatusTextView = (TextView) findViewById (R.id.statusValue);
        // Button settings (associate with settings set in Layout)
        connectButton = (Button) findViewById (R.id.connectButton);
        ledOnButton = (Button) findViewById (R.id.ledOnButton);
        ledOffButton = (Button) findViewById (R.id.ledOffButton);
        // Button event settings
        connectButton.setOnClickListener (this);
        ledOnButton.setOnClickListener (this);
        ledOffButton.setOnClickListener (this);
        // Get Bluetooth device name
        // Because the device name is RNBT-XXXX,
        // Define device name with DVICE_NAME
        mAdapter = BluetoothAdapter.getDefaultAdapter ();
        mStatusTextView.setText ("SearchDevice");
        Set<BluetoothDevice>devices = mAdapter.getBondedDevices ();
        for (BluetoothDevice device: devices) {
            if (device.getName (). equals (DEVICE_NAME)) {
                mStatusTextView.setText ("find:" + device.getName ());
                mDevice = device;
            }
        }
    }
    // Processing when another activity starts
    @Override
    protected void onPause () {
        super.onPause ();
        isRunning = false;
        connectFlg = false;
        try {
            mSocket.close ();}
        catch (Exception e) {}
    }
    // Thread processing (executed after pressing the connect button)
    @Override
    public void run () {
        InputStream mmInStream = null;
        Message valueMsg = new Message ();
        valueMsg.what = VIEW_STATUS;
        valueMsg.obj = "connecting ...";
        mHandler.sendMessage (valueMsg);
        try {
            // Socket connection with Bluetooth using the acquired device name
            mSocket = mDevice.createRfcommSocketToServiceRecord (MY_UUID);
            mSocket.connect ();
            mmInStream = mSocket.getInputStream ();
            mmOutputStream = mSocket.getOutputStream ();
            // Store the InputStream buffer
            byte [] buffer = new byte [1024];
            // Store the obtained buffer size
            int bytes;
            valueMsg = new Message ();
            valueMsg.what = VIEW_STATUS;
            valueMsg.obj = "connected.";
            mHandler.sendMessage (valueMsg);
            connectFlg = true;
            while (isRunning) {
                // Read InputStream
                bytes = mmInStream.read (buffer);
                Log.i (TAG, "bytes =" + bytes);
                // Convert to String type
                String readMsg = new String (buffer, 0, bytes);
                // display if not null
                if (readMsg.trim ()! = null&&! readMsg.trim (). equals ("")) {
                    Log.i (TAG, "value =" + readMsg.trim ());
                    valueMsg = new Message ();
                    valueMsg.what = VIEW_INPUT;
                    valueMsg.obj = readMsg;
                    mHandler.sendMessage (valueMsg);
                }
            }
        }
        // error handling
        catch (Exception e) {
            valueMsg = new Message ();
            valueMsg.what = VIEW_STATUS;
            valueMsg.obj = "Error1:" + e;
            mHandler.sendMessage (valueMsg);
            try {
                mSocket.close ();
            } catch (Exception ee) {}
            isRunning = false;
            connectFlg = false;
        }
    }
    // Processing when the button is pressed
    @Override
    public void onClick (View v) {
        // Connect button
        if (v.equals (connectButton)) {
            if (! connectFlg) {
                mStatusTextView.setText ("try connect");
                mThread = new Thread (this);
                // Start Thread and connect via Bluetooth
                isRunning = true;
                mThread.start ();
            }}
        // ledOn button
        else if (v.equals (ledOnButton)) {
            if (connectFlg) {
                try {
                    mmOutputStream.write ("1" .getBytes ());
                    mStatusTextView.setText ("LED ON:");
                } catch (IOException e) {
                    Message valueMsg = new Message ();
                    valueMsg.what = VIEW_STATUS;
                    valueMsg.obj = "Error3:" + e;
                    mHandler.sendMessage (valueMsg);
                }
            } else {
                mStatusTextView.setText ("Please push the connect button");
            }
        }
        // ledOff button
        else if (v.equals (ledOffButton)) {
            if (connectFlg) {
                try {
                    mmOutputStream.write ("0" .getBytes ());
                    mStatusTextView.setText ("LED OFF:");
                } catch (IOException e) {
                    Message valueMsg = new Message ();
                    valueMsg.what = VIEW_STATUS;
                    valueMsg.obj = "Error4:" + e;
                    mHandler.sendMessage (valueMsg);
                }
            } else {
                mStatusTextView.setText ("Please push the connect button");
            }
        }
    }
    / **
     * Rendering is done by Handler
     * /
    Handler mHandler = new Handler () {
        @Override
        public void handleMessage (Message msg) {
            int action = msg.what;
            String msgStr = (String) msg.obj;
            if (action == VIEW_INPUT) {
                mInputTextView.setText (msgStr);
            }
            else if (action == VIEW_STATUS) {
                mStatusTextView.setText (msgStr);
            }
        }
    };
}
Wiring



Supplemental information (FW/tool version etc.)

-Development environment--
MacOS.Catalina.10.15
ArduinoIDE1.8.10
AndroidStudio3.4.1

-Android device--
Elephone P8 Mini (Android OS v7.0)

-Arduino etc .--
ArduinoUno
Bluetooth module evaluation kit using RN-42

  • Answer # 1

    I think the circuit configuration of the RN-42 module is different

    RN-42 is running 3.3V Arduino UNO at 5V

    Reference RN-42 module circuit diagram

    Akizuki RN-42 connection example

    Akizuki RN-42 module
    5V supply from USB
    RTS-CTS connection
    RXD, TXD 3.3V-5V signal level conversion
    Is required

    The LED does not have a current limiting resistor. Is the LED a built-in resistor?