[Tutorial] Kontrol Peralatan Jarak Jauh dengan Bluetooth menggunakan Android Studio dan Arduino

Pada tutorial kali ini saya akan memberi tahu mengenai project yang telah saya buat yaitu kontrol peralatan jarak jauh menggunakan bluetooth. Berikut langkah-langkahnya :
1. Pertama kita buka aplikasi android studio
2. Buatlah 4 activity: Splash,Login,DeviceList,dan MainActivity
3. Kemudian mulai memprogram:
    a. Pada bagian Splash Screen

- SplashScreen.xml:
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.example.dimas.tugastelemetrikontrolled.SplashScreen"
 android:background="@drawable/homeautomation">

<ProgressBar
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/progressBar"
 android:layout_marginBottom="63dp"
 android:layout_alignParentBottom="true"
 android:layout_centerHorizontal="true" />
</RelativeLayout>


- SplashScreen.java:
package com.example.dimas.tugastelemetrikontrolled;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashScreen extends AppCompatActivity {
    //Set waktu lama splashscreen    private static int splashInterval = 2000;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        new Handler().postDelayed(new Runnable() {
            @Override            public void run() {
                // TODO Auto-generated method stub                
                Intent i = new Intent(SplashScreen.this, Login.class);
                startActivity(i);
                //jeda selesai Splashscreen                
                this.finish();
            }
            private void finish() 
            {
            // TODO Auto-generated method stub            
            }
        }, splashInterval);

    };
    }




    b. Pada bagian Login

- Login.xml:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.example.dimas.tugastelemetrikontrolled.Login"
 android:background="@drawable/login">

<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:text="Login"
 android:id="@+id/textView"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true" />
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:text="Username"
 android:id="@+id/textView2"
 android:layout_below="@+id/textView"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="50dp" />
<EditText
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/txtUsername"
 android:layout_below="@+id/textView2"
 android:layout_marginTop="48dp"
 android:layout_alignParentLeft="true"
 android:layout_alignParentStart="true"
 android:layout_alignParentRight="true"
 android:layout_alignParentEnd="true"
 android:gravity="center"android:hint="username" />
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:text="Password" 
 android:id="@+id/textView3"
 android:layout_centerVertical="true"
 android:layout_centerHorizontal="true" />
<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Login"android:id="@+id/btnLogin"
 android:layout_alignParentBottom="true"
 android:layout_centerHorizontal="true"
 android:layout_marginBottom="38dp" />
<EditText
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:inputType="textPassword"
 android:ems="10"
 android:id="@+id/txtPassword"
 android:layout_below="@+id/textView3"
 android:layout_marginTop="35dp"
 android:layout_alignParentLeft="true"
 android:layout_alignParentStart="true"
 android:layout_alignParentRight="true"
 android:layout_alignParentEnd="true"
 android:hint="password"
 android:gravity="center" />
</RelativeLayout>


- Login.java:
package com.example.dimas.tugastelemetrikontrolled;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends AppCompatActivity {

    Button login,cancel;
    EditText username,password;
    TextView tx1,tx2;
    int counter = 3;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        login=(Button)findViewById(R.id.btnLogin);
        username=(EditText)findViewById(R.id.txtUsername);
        password=(EditText)findViewById(R.id.txtPassword);
        //tx1=(TextView)findViewById(R.id.tx1);        
       //tx2=(TextView)findViewById(R.id.tx2);        
        //cancel=(Button)findViewById(R.id.btnCancel);

        login.setOnClickListener(new View.OnClickListener() {
            @Override            
            public void onClick(View v) {
                if (username.getText().toString().equals("admin") && 
                     password.getText().toString().equals("admin")) 
                   {
          Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show();
                    Thread timerThread = new Thread() {
                        public void run() {
                            try {
                                sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                Intent intent = new Intent(getBaseContext(), DeviceList.class);
                                startActivity(intent);
                            }
                        }
                    };
                    timerThread.start();
                }
            }});
    }
    }


    c. Pada bagian DeviceList

- DeviceList.xml:
<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.example.dimas.tugastelemetrikontrolled.DeviceList"
 android:background="@drawable/smarthomenew">
<TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:text="DeviceList"
 android:id="@+id/textView4"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true" />
<Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Paired"
 android:id="@+id/btnPaired"
 android:layout_alignParentBottom="true"
 android:layout_alignLeft="@+id/textView4"
 android:layout_alignStart="@+id/textView4" />
<ListView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/listView"
 android:layout_below="@+id/textView4"
 android:layout_centerHorizontal="true"
 android:layout_above="@+id/btnPaired" />
</RelativeLayout>



- DeviceList.java:
package com.example.dimas.tugastelemetrikontrolled;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class DeviceList extends AppCompatActivity {
    //widgets    Button btnPaired;
    ListView devicelist;
    //Bluetooth    private BluetoothAdapter myBluetooth = null;
    private Set<BluetoothDevice> pairedDevices;
    public static String EXTRA_ADDRESS = "device_address";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);

        //Calling widgets        
        btnPaired = (Button)findViewById(R.id.btnPaired);
        devicelist = (ListView)findViewById(R.id.listView);

        //if the device has bluetooth        
        myBluetooth = BluetoothAdapter.getDefaultAdapter();

        if(myBluetooth == null)
        {
            //Show a mensag. that the device has no bluetooth adapter            
            Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();

            //finish apk            
            finish();
        }
        else if(!myBluetooth.isEnabled())
        {
            //Ask to the user turn the bluetooth on            
            Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnBTon,1);
        }

        btnPaired.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                pairedDevicesList();
            }
        });
    }

    private void pairedDevicesList()
    {
        pairedDevices = myBluetooth.getBondedDevices();
        ArrayList list = new ArrayList();

        if (pairedDevices.size()>0)
        {
            for(BluetoothDevice bt : pairedDevices)
            {
                list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address            
            }
        }
        else        
        {
            Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
        }

        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        devicelist.setAdapter(adapter);
        devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked    
    }

    private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
    {
        public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
        {
            // Get the device MAC address, the last 17 chars in the View            
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Make an intent to start next activity.            
             Intent i = new Intent(DeviceList.this, MainActivity.class);
            Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
            //Change the activity.            
            i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity            
            startActivity(i);
        }
    };
    }


    d. Pada bagian MainActivity
- MainActivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"    
  android:layout_height="match_parent"    
  android:paddingBottom="@dimen/activity_vertical_margin"    
  android:paddingLeft="@dimen/activity_horizontal_margin"    
  android:paddingRight="@dimen/activity_horizontal_margin"    
  android:paddingTop="@dimen/activity_vertical_margin"    
  tools:context="com.example.dimas.tugastelemetrikontrolled.MainActivity"    
  android:background="@drawable/banner">

<Button        
  android:layout_width="100dp"        
  android:layout_height="100dp"        
  android:id="@+id/btnOne"        
  android:layout_alignParentLeft="true"        
  android:layout_alignParentStart="true"        
  android:layout_marginLeft="40dp"        
  android:layout_marginStart="40dp"        
  android:layout_marginTop="86dp"        
  android:onClick="change_image1"        
  android:background="@drawable/redbutton" />

<Button
  android:layout_width="100dp"        
  android:layout_height="100dp"        
  android:id="@+id/btnTwo"        
  android:layout_alignTop="@+id/btnOne"        
  android:layout_alignParentRight="true"        
  android:layout_alignParentEnd="true"        
  android:layout_marginRight="40dp"        
  android:layout_marginEnd="40dp"        
  android:onClick="change_image2"        
  android:background="@drawable/redbutton" />

<Button        
  android:layout_width="100dp"        
  android:layout_height="100dp"        
  android:id="@+id/btnThree"        
  android:layout_above="@+id/btnDisconnect"        
  android:layout_alignLeft="@+id/btnOne"        
  android:layout_alignStart="@+id/btnOne"        
  android:layout_marginBottom="75dp"        
  android:onClick="change_image3"        
  android:background="@drawable/redbutton" />

<Button
  android:layout_width="100dp"
  android:layout_height="100dp"
  android:id="@+id/btnFour"        
  android:onClick="change_image4"        
  android:layout_marginRight="40dp"        
  android:layout_marginEnd="40dp"        
  android:layout_alignBottom="@+id/btnThree"        
  android:layout_alignLeft="@+id/btnTwo"        
  android:layout_alignStart="@+id/btnTwo"        
  android:background="@drawable/redbutton" />

<Button
  android:layout_width="wrap_content"        
  android:layout_height="wrap_content"        
  android:text="Disconnect"        
  android:id="@+id/btnDisconnect"        
  android:layout_alignParentBottom="true"        
  android:layout_centerHorizontal="true"        
  android:layout_marginBottom="30dp" />

<TextView        
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:text="Main"        
  android:id="@+id/textView5"        
  android:layout_alignParentTop="true"        
  android:layout_centerHorizontal="true" />
</RelativeLayout>

- MainActivity.java:
package com.example.dimas.tugastelemetrikontrolled;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    //int flag1=0,flag2=0,flag3=0,flag4=0;    Button btnA,btnB,btnC,btnD,btnDisconnect;
    Handler bluetoothIn;

    Boolean flag1=true;
    Boolean flag2=true;
    Boolean flag3=true;
    Boolean flag4=true;

    final int handlerState = 0;                        //used to identify handler message    
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder recDataString = new StringBuilder();
    private ConnectedThread mConnectedThread;
    // SPP UUID service - this should work for most devices    
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    // String for MAC address    
    private static String address;//Address Bluetooth untuk koneksi socket    

@Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        //btnA=(Button)findViewById(R.id.btnOne);        
        //btnB=(Button)findViewById(R.id.btnTwo);        
        //btnC=(Button)findViewById(R.id.btnThree);        
        //btnD=(Button)findViewById(R.id.btnFour);        
        btnDisconnect=(Button)findViewById(R.id.btnDisconnect);

        btnDisconnect.setOnClickListener(new View.OnClickListener() {
     @Override            
        public void onClick(View v) {
                Disconnect(); //close connection            }
        });
    }

    private void Disconnect()
    {
        if (btSocket!=null) //If the btSocket is busy        {
            try            {
                btSocket.close(); //close connection            }
            catch (IOException e)
            {
              Toast.makeText(getBaseContext(), "Open Data", Toast.LENGTH_SHORT).show();}
        }
        finish(); //return to the first layout
    }

    public void change_image1(View v)
    {
        Button btnA =(Button)findViewById(R.id.btnOne);
        //use flag to change image        
        if(flag1==false)
        {
           btnA.setBackgroundResource(R.drawable.redbutton);
            mConnectedThread.write("a");
            flag1=true;
        }
        else        {
            btnA.setBackgroundResource(R.drawable.greenbutton);
            flag1=false;
            mConnectedThread.write("b");
        }
    }

    public void change_image2(View v)
    {
        Button btnB =(Button)findViewById(R.id.btnTwo);
        //use flag to change image        
        if(flag2==false)
        {
            btnB.setBackgroundResource(R.drawable.redbutton);
            flag2=true;
            mConnectedThread.write("c");
        }
        else        {
            btnB.setBackgroundResource(R.drawable.greenbutton);
            flag2=false;
            mConnectedThread.write("d");
        }
    }

    public void change_image3(View v)
    {
        Button btnC =(Button)findViewById(R.id.btnThree);
        //use flag to change image        
        if(flag3==false)
        {
            btnC.setBackgroundResource(R.drawable.redbutton);
            flag3=true;
            mConnectedThread.write("e");
        }
        else        {
            btnC.setBackgroundResource(R.drawable.greenbutton);
            flag3=false;
            mConnectedThread.write("f");
        }
    }

    public void change_image4(View v)
    {
        Button btnD =(Button)findViewById(R.id.btnFour);
        //use flag to change image        
       if(flag4==false)
        {
            btnD.setBackgroundResource(R.drawable.redbutton);
            flag4=true;
            mConnectedThread.write("g");
        }
        else        {
            btnD.setBackgroundResource(R.drawable.greenbutton);
            flag4=false;
            mConnectedThread.write("h");
        }
    }

    //Program Koneksi Bluetooth    
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
    {
        return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
        //creates secure outgoing connecetion with BT device using UUID    }

    @Override    public void onResume() {
        super.onResume();
        //Get MAC address from DeviceListActivity via intent        
           Intent intent = getIntent();
        //Get the MAC address from the DeviceListActivty via EXTRA        
           address = intent.getStringExtra(DeviceList.EXTRA_ADDRESS);
        //create device and set the MAC address        
           BluetoothDevice device = btAdapter.getRemoteDevice(address);
        try        {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e)
        {
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
        }
        // Establish the Bluetooth socket connection.        try        {
            btSocket.connect();
        } catch (IOException e)
        {
            try            {
                btSocket.close();
            } catch (IOException e2)
            {
                //insert code to deal with this            }
        }
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();

    //I send a character when resuming.beginning transmission to check device is connected        
    //If it is not an exception will be thrown in the write method and finish() will be called        mConnectedThread.write("x");
    }

    @Override    public void onPause()
    {
        super.onPause();
        try        {
            //Don't leave Bluetooth sockets open when leaving activity            
           btSocket.close();
        } 
        catch (IOException e2) 
        {
            //insert code to deal with this        }
    }

    //Checks that the Android device Bluetooth is available and prompts to be turned on if off    
    private void checkBTState() {
        if(btAdapter==null) {
            Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
        } else {
            if (btAdapter.isEnabled()) {
            } else {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    //create new class for connect thread    
   private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        //creation of the connect thread        
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                //Create I/O streams for connection                
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];
            int bytes;

            // Keep looping to listen for received messages            while (true) {
                try {
                    bytes = mmInStream.read(buffer);            
                    //read bytes from input buffer                    
                    String readMessage = new String(buffer, 0, bytes);
                    bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                } catch (IOException e)
                {
                    break;
                }
            }
        }
        //write method        
     public void write(String input) {
            byte[] msgBuffer = input.getBytes();           //converts entered String into bytes            
             try {
                mmOutStream.write(msgBuffer);                
               //write bytes over BT connection via outstream            
               } catch (IOException e) {
                //if you cannot write, close the application                
                Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                finish();

            }
        }
    }

    public void getCurrentDate(View view) {
    }

}


Selanjutnya kita lakukan tambahkan bluetooth permission pada Android Manifest :

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


Sekian terima kasih.
Berikut hasil project yang bisa anda dowload : disini
Kemudian ini coding program Arduino :
Berikut referensi nya :

Post a Comment

Previous Post Next Post