ANDROID REMOTE VIA BLUETOOTH
Ide nya sebetulnya pengen bikin alat kontrol dan monitoring jarak jauh menggunakan Android Gadget. Asik juga jika semua dapat di kontrol dan di monitoring lewat HP mulai dari alat-alat rumah, motor, mobil, robot dll. Untuk itu saya coba bikin aplikasi sederhana cara meng-komunikasikan Android Gadget dengan modul Bluetooth. Alat yang sudah saya bikin mempunyai sistem seperti berikut :
Jika temen2 ada yang teratrik untuk membuatnya juga, peralatannya antara lain adalah sbb:
1. Andorid Phone
Kali ini Saya menggunakan Android milik Lenovo S-560 dengan OS Android Ice Cream Sandwich 4.0
2. Modul Bluetooth
Modul Bluetooth yang Saya gunakan adalah Modul Bluetooth HC-06 dari Linvior, modul ini hanya dapat di konfigurasikan sebagai slave dan tidak dapat bertindak sebagai master. Modul ini memiliki interface serial TTL dengan pinout sbb:
Modul ini defaultnya memiliki konfigurasi seperti berikut :
Baudrate : 9600
Parity : None
Data : 8 Bit
Nama : Linvior
Selengkapnya untuk AT Command Bluetooth ini dapat di baca di http://diytech.net/.
Untuk aplikasi ini, semua nya saya biarkan dalam kondisi default kecuali nama device nya saya ubah menjadi “nutscientist”.
3. Modul Mikrokontroler
Modul Mikrokontroler yang Saya gunakan adalah DT-AVR Low Cost Micro System dan menggunakan mikrokontroler seri AVR ATMega 162. Kenapa harus menggunakan ATMega162? Karena yang Saya punya cuma mikrokontroler ini hehehehe…. . Dan untungnya, mikrokontroler ini memilikki 2 UART ( UART0 dan UART1 ) jadi bias saya koneksikan ke serial modul Bluetooth sekaligus di koneksikan ke Laptop menggunakan Serial-USB adapter
4. Laptop
Laptop digunakan untuk debugging apakah system yang di buat sudah di berjalan dengan baik, Untuk debuggingnya Saya menggunakan program “RealTerm”.
CARA KERJA
Cara kerja aplikasi ini sederhana saja, Dari sisi Androidnya, Saya hanya membuat aplikasi yang dapat mengirim dan menerima pesan dari modul Bluetooth. Secara umum fungsi di aplikasi android adalah sbb:
- Proses Pairing : Dilakukan memalui menu setting HP
- Proses Cari Client Bluetooth yang sudah di pairing (Paired Device)
- Proses Buka Koneksi Bluetooth
- Proses Komunikasi Data
- Proses Tutup Koneksi Bluetooh
Sedangkan pada sisi mikrokontroler nya, Saya hanya meng-cross kan data UART0 dengan UART1, yaitu dengan mengirimkan data yang di terima RX0 ke TX1 dan sebaliknya.
CODE PROGRAM MIKROKONTROLER
Software Development yang Saya gunakan adalah CodeVisionAVR dengan kode program sbb:
/*****************************************************
#include <mega162.h>
// Standard Input/Output functions
#include <stdio.h>
#include <delay.h>
#ifndef RXB8
#define RXB8 1
#endif
// Standard Input/Output functions
#include <stdio.h>
#include <delay.h>
#ifndef RXB8
#define RXB8 1
#endif
#ifndef TXB8
#define TXB8 0
#endif
#define TXB8 0
#endif
#ifndef UDRE
#define UDRE 5
#endif
#define UDRE 5
#endif
#ifndef RXC
#define RXC 7
#endif
#define RXC 7
#endif
#define DATA_REGISTER_EMPTY (1<<UDRE)
void putchar1(char c)
{
while ((UCSR1A & DATA_REGISTER_EMPTY)==0);
UDR1=c;
}
{
while ((UCSR1A & DATA_REGISTER_EMPTY)==0);
UDR1=c;
}
// USART0 Receiver interrupt service routine
interrupt [USART0_RXC] void usart0_rx_isr(void)
{
putchar1(UDR0);
}
interrupt [USART0_RXC] void usart0_rx_isr(void)
{
putchar1(UDR0);
}
interrupt [USART1_RXC] void usart1_rx_isr(void)
{
putchar(UDR1);
}
{
putchar(UDR1);
}
// Declare your global variables here
void main(void)
{
// Declare your local variables here
// Crystal Oscillator division factor: 1
{
// Declare your local variables here
// Crystal Oscillator division factor: 1
#pragma optsize-
CLKPR=0x80;
CLKPR=0x00;
#ifdef _OPTIMIZE_SIZE_
#pragma optsize+
#endif
CLKPR=0x80;
CLKPR=0x00;
#ifdef _OPTIMIZE_SIZE_
#pragma optsize+
#endif
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;
PORTB=0x00;
DDRB=0x02;
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;
PORTB=0x00;
DDRB=0x02;
// USART0 initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART0 Receiver: On
// USART0 Transmitter: On
// USART0 Mode: Asynchronous
// USART0 Baud Rate: 9600
UCSR0A=0x00;
UCSR0B=0x98;
UCSR0C=0x86;
UBRR0H=0x00;
UBRR0L=0x19;
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART0 Receiver: On
// USART0 Transmitter: On
// USART0 Mode: Asynchronous
// USART0 Baud Rate: 9600
UCSR0A=0x00;
UCSR0B=0x98;
UCSR0C=0x86;
UBRR0H=0x00;
UBRR0L=0x19;
// USART1 initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART1 Receiver: On
// USART1 Transmitter: On
// USART1 Mode: Asynchronous
// USART1 Baud Rate: 9600
UCSR1A=0x00;
UCSR1B=0x98;
UCSR1C=0x86;
UBRR1H=0x00;
UBRR1L=0x19;
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART1 Receiver: On
// USART1 Transmitter: On
// USART1 Mode: Asynchronous
// USART1 Baud Rate: 9600
UCSR1A=0x00;
UCSR1B=0x98;
UCSR1C=0x86;
UBRR1H=0x00;
UBRR1L=0x19;
// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
// Global enable interrupts
#asm(“sei”)
#asm(“sei”)
while (1)
{
// do nothing
}
}
{
// do nothing
}
}
CODE PROGRAM ANDROID
Program APK yang Saya buat Saya beri nama “BlueComm.Apk” dengan code sbb:
- activity_main.xml
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:tools=“http://schemas.android.com/tools”
android:id=“@+id/OpenButton”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:background=“@drawable/blue”
tools:context=“.MainActivity” >
<TextView
android:id=“@+id/label”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentRight=“true”
android:layout_alignParentTop=“true”
android:text=“@string/status”
android:textColor=“@color/status” />
<TextView
android:id=“@+id/textView1″
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentBottom=“true”
android:layout_alignParentLeft=“true”
android:text=“@string/hello_world”
android:textColor=“@color/web”
android:textColorLink=“@android:color/white” />
<Button
android:id=“@+id/ButtonOpen”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_above=“@+id/textView1″
android:layout_alignParentLeft=“true”
android:layout_marginBottom=“25dp”
android:layout_marginLeft=“25dp”
android:text=“@string/Open”
android:textColor=“@color/open” />
<Button
android:id=“@+id/ButtonSendData”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignBaseline=“@+id/ButtonOpen”
android:layout_alignBottom=“@+id/ButtonOpen”
android:layout_centerHorizontal=“true”
android:text=“@string/Send”
android:textColor=“@color/send” />
<Button
android:id=“@+id/ButtonClose”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignBaseline=“@+id/ButtonSendData”
android:layout_alignBottom=“@+id/ButtonSendData”
android:layout_alignParentRight=“true”
android:layout_marginRight=“24dp”
android:text=“@string/Close”
android:textColor=“@color/close” />
<EditText
android:id=“@+id/TxtInput”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/label”
android:layout_marginTop=“26dp”
android:background=“@color/backtext”
android:ems=“10”
android:inputType=“text” >
<requestFocus />
</EditText>
</RelativeLayout>
xmlns:tools=“http://schemas.android.com/tools”
android:id=“@+id/OpenButton”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:background=“@drawable/blue”
tools:context=“.MainActivity” >
<TextView
android:id=“@+id/label”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentRight=“true”
android:layout_alignParentTop=“true”
android:text=“@string/status”
android:textColor=“@color/status” />
<TextView
android:id=“@+id/textView1″
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentBottom=“true”
android:layout_alignParentLeft=“true”
android:text=“@string/hello_world”
android:textColor=“@color/web”
android:textColorLink=“@android:color/white” />
<Button
android:id=“@+id/ButtonOpen”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_above=“@+id/textView1″
android:layout_alignParentLeft=“true”
android:layout_marginBottom=“25dp”
android:layout_marginLeft=“25dp”
android:text=“@string/Open”
android:textColor=“@color/open” />
<Button
android:id=“@+id/ButtonSendData”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignBaseline=“@+id/ButtonOpen”
android:layout_alignBottom=“@+id/ButtonOpen”
android:layout_centerHorizontal=“true”
android:text=“@string/Send”
android:textColor=“@color/send” />
<Button
android:id=“@+id/ButtonClose”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignBaseline=“@+id/ButtonSendData”
android:layout_alignBottom=“@+id/ButtonSendData”
android:layout_alignParentRight=“true”
android:layout_marginRight=“24dp”
android:text=“@string/Close”
android:textColor=“@color/close” />
<EditText
android:id=“@+id/TxtInput”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/label”
android:layout_marginTop=“26dp”
android:background=“@color/backtext”
android:ems=“10”
android:inputType=“text” >
<requestFocus />
</EditText>
</RelativeLayout>
- string.xml
<?xml version=“1.0” encoding=“utf-8″?>
<resources>
<string name=“app_name”>Bluecomm</string>
<string name=“hello_world”>www.nutscientist.wordpress.com</string
<string name=“menu_about”>www.nutscientist.wordpress.com</string
<string name=“status”>Welcome To Bluecomm</string>
<string name=“Open”>Open</string>
<string name=“Close”>Close</string>
<string name=“Send”>Send</string>
</resources>
<resources>
<string name=“app_name”>Bluecomm</string>
<string name=“hello_world”>www.nutscientist.wordpress.com</string
<string name=“menu_about”>www.nutscientist.wordpress.com</string
<string name=“status”>Welcome To Bluecomm</string>
<string name=“Open”>Open</string>
<string name=“Close”>Close</string>
<string name=“Send”>Send</string>
</resources>
- color.xml
<?xml version=“1.0” encoding=“utf-8″?>
<resources>
<color name=“web”>#FFF00000</color>
<color name=“input”>#000000</color>
<color name=“open”>#000000</color>
<color name=“send”>#000000</color>
<color name=“close”>#000000</color>
<color name=“status”>#ffff00</color>
<color name=“backtext”>#f0f8ff</color>
<resources>
<color name=“web”>#FFF00000</color>
<color name=“input”>#000000</color>
<color name=“open”>#000000</color>
<color name=“send”>#000000</color>
<color name=“close”>#000000</color>
<color name=“status”>#ffff00</color>
<color name=“backtext”>#f0f8ff</color>
</resources>
- MainActivity.java
package com.example.bluecomm;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
// Debugging
private static final String TAG = “BlueComm”;
private static final boolean D = true;
// deklarasi
private BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
private InputStream mmInputStream;
private OutputStream mmOutputStream;
private Button ButtonOpen;
private Button ButtonClose;
private Button ButtonSend;
private TextView TextInput;
private TextView Label;
byte[] Buffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
public String dta;
private static final String TAG = “BlueComm”;
private static final boolean D = true;
// deklarasi
private BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
private InputStream mmInputStream;
private OutputStream mmOutputStream;
private Button ButtonOpen;
private Button ButtonClose;
private Button ButtonSend;
private TextView TextInput;
private TextView Label;
byte[] Buffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
public String dta;
// Untuk menerima message dari background thread
Handler h = new Handler()
{
@Override
public void handleMessage (Message m)
{
super.handleMessage(m);
if(D) Log.d(TAG, “Handle Message”);
Bundle bund =m.getData();
String key = bund.getString(“My Key”);
TextInput.setText(key);
}
};
{
@Override
public void handleMessage (Message m)
{
super.handleMessage(m);
if(D) Log.d(TAG, “Handle Message”);
Bundle bund =m.getData();
String key = bund.getString(“My Key”);
TextInput.setText(key);
}
};
// On Create Activity
@Override
public void onCreate(Bundle savedInstanceState)
{
if(D) Log.d(TAG, “On Create”);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonOpen = (Button)findViewById(R.id.ButtonOpen);
ButtonClose = (Button)findViewById(R.id.ButtonClose);
ButtonSend = (Button)findViewById(R.id.ButtonSendData);
TextInput = (TextView)findViewById(R.id.TxtInput);
//TextOutput = (TextView)findViewById(R.id.TextOutput);
Label = (TextView)findViewById(R.id.label);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
Label.setText(“No bluetooth adapter available”);
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
if(D) Log.d(TAG, “On Create”);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonOpen = (Button)findViewById(R.id.ButtonOpen);
ButtonClose = (Button)findViewById(R.id.ButtonClose);
ButtonSend = (Button)findViewById(R.id.ButtonSendData);
TextInput = (TextView)findViewById(R.id.TxtInput);
//TextOutput = (TextView)findViewById(R.id.TextOutput);
Label = (TextView)findViewById(R.id.label);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
Label.setText(“No bluetooth adapter available”);
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
}
// On Start Activity
@Override
public void onStart()
{
super.onStart();
if(D) Log.e(TAG, “ON START”);
@Override
public void onStart()
{
super.onStart();
if(D) Log.e(TAG, “ON START”);
//Open Button
ButtonOpen.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
CariBT();
BukaBT();
}
catch (IOException ex) { }
}
});
ButtonOpen.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
CariBT();
BukaBT();
}
catch (IOException ex) { }
}
});
//Send Button
ButtonSend.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
ButtonSend.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
//Close button
ButtonClose.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
ButtonClose.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
// Mencari Client Bluetooth yg sudah paired dengan nama “nutscientist“
void CariBT()
{
if(D) Log.d(TAG, “Cari BT”);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals(“nutscientist”))
{
mmDevice = device;
Label.setText(“Slave Client Found”);
//break;
}
else
{
Label.setText(“Slave Client Not Found”);
}
}
}
//Toast.makeText(this, “Remote Bluetooth Ditemukan“, Toast.LENGTH_LONG).show();
}
void CariBT()
{
if(D) Log.d(TAG, “Cari BT”);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals(“nutscientist”))
{
mmDevice = device;
Label.setText(“Slave Client Found”);
//break;
}
else
{
Label.setText(“Slave Client Not Found”);
}
}
}
//Toast.makeText(this, “Remote Bluetooth Ditemukan“, Toast.LENGTH_LONG).show();
}
@Override
protected void onStop() {
super.onStop();
if(D) Log.e(TAG, “ON STOP”);
}
protected void onStop() {
super.onStop();
if(D) Log.e(TAG, “ON STOP”);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(D) Log.e(TAG, “ON DESTROY”);
}
protected void onDestroy() {
super.onDestroy();
if(D) Log.e(TAG, “ON DESTROY”);
}
@Override
protected void onResume()
{
super.onResume();
if(D) Log.e(TAG, “+ ON RESUME +”);
}
protected void onResume()
{
super.onResume();
if(D) Log.e(TAG, “+ ON RESUME +”);
}
@Override
protected void onPause() {
super.onPause();
if(D) Log.e(TAG, “- ON PAUSE -“);
}
// Untuk memulai/ melakukan koneksi dengan client bluetooth
void BukaBT() throws IOException
{
if(D) Log.d(TAG, “Buka BT”);
UUID uuid = UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
ListenForData();
Label.setText(“Bluetooth Opened”);
// Toast.makeText(this, “Bluetooth Dibuka“, Toast.LENGTH_LONG).show();
}
protected void onPause() {
super.onPause();
if(D) Log.e(TAG, “- ON PAUSE -“);
}
// Untuk memulai/ melakukan koneksi dengan client bluetooth
void BukaBT() throws IOException
{
if(D) Log.d(TAG, “Buka BT”);
UUID uuid = UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
ListenForData();
Label.setText(“Bluetooth Opened”);
// Toast.makeText(this, “Bluetooth Dibuka“, Toast.LENGTH_LONG).show();
}
// Background thread untuk menerima data dari client bluetooth
void ListenForData()
{
if(D) Log.d(TAG, “Listen Data”);
final byte delimiter = 13; //atau Carriage Return (CR), di gunakan untuk mendeteksi akhir dari text
stopWorker = false;
readBufferPosition = 0;
Buffer = new byte[1024];
Thread workerThread = new Thread(new Runnable()
{
void ListenForData()
{
if(D) Log.d(TAG, “Listen Data”);
final byte delimiter = 13; //atau Carriage Return (CR), di gunakan untuk mendeteksi akhir dari text
stopWorker = false;
readBufferPosition = 0;
Buffer = new byte[1024];
Thread workerThread = new Thread(new Runnable()
{
@Override
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
//Do work
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(Buffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, “US-ASCII”);
readBufferPosition = 0;
Message m = new Message();
Bundle bund = new Bundle();
bund.putString(“My Key”, data);
m.setData(bund);
h.sendMessage(m);
}
else
{
Buffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
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(Buffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, “US-ASCII”);
readBufferPosition = 0;
Message m = new Message();
Bundle bund = new Bundle();
bund.putString(“My Key”, data);
m.setData(bund);
h.sendMessage(m);
}
else
{
Buffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
// Untuk mengirim data ke client bluetooth
void sendData() throws IOException
{
if(D) Log.d(TAG, “Kirim Data”);
String msg = TextInput.getText().toString();
msg += “\n\r”;
mmOutputStream.write(msg.getBytes());
Label.setText(“Data Sent”);
//Toast.makeText(this, “Data Terkirim“, Toast.LENGTH_LONG).show();
}
// Untuk menutup/mengakhiri koneksi dengan client bluetooth
void sendData() throws IOException
{
if(D) Log.d(TAG, “Kirim Data”);
String msg = TextInput.getText().toString();
msg += “\n\r”;
mmOutputStream.write(msg.getBytes());
Label.setText(“Data Sent”);
//Toast.makeText(this, “Data Terkirim“, Toast.LENGTH_LONG).show();
}
// Untuk menutup/mengakhiri koneksi dengan client bluetooth
void closeBT() throws IOException
{
if(D) Log.d(TAG, “Tutup BT”);
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
Label.setText(“Bluetooth Closed”);
//Toast.makeText(this, “Bluetooth Ditutup“, Toast.LENGTH_LONG).show();
}
{
if(D) Log.d(TAG, “Tutup BT”);
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
Label.setText(“Bluetooth Closed”);
//Toast.makeText(this, “Bluetooth Ditutup“, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
SCREENSHOTS
Cara kerja sistem lebih detail dapat di lihat di sini.
Demikian, dan selanjutnya aplikasi ini dapat di kembangkan menjadi alat control dan monitoring jarak jauh dengan menambahkan sedikit penyesuaian.. .
SELAMAT BERKREASI DAN SALING BERBAGI
KREATIF, INNOVATIF, DAN SEDIKIT JOROK
|
Ilmu Komputer 95
|