Android+Arduino+藍芽程式

Android+Arduino+藍芽程式

Android+Arduino+藍芽程式

 

Arduino code

#include <SoftwareSerial.h>
#include <Wire.h>//引用二個函式庫SoftwareSerial及Wire
//http://blog.cavedu.com/programming-language/appinventor/appinventorandarduinowithbluetooth2/
SoftwareSerial I2CBT(10,11);//定義PIN10及PIN11分別為RX及TX腳位

byte cmmd[20];
int insize, a;

void setup()
{

Serial.begin(9600); //Arduino起始鮑率:9600
I2CBT.begin(9600); //藍牙鮑率:57600(注意!鮑率每個藍牙晶片不一定相同,請務必確認
pinMode(9, OUTPUT); //請注意您使用的Arduino 該腳位是否支援 PWM (會有~符號),否則會看不到效果
digitalWrite(9,HIGH); //點亮LED
}

void loop() {

byte cmmd[20];
int insize;
while(1)
{
if ((insize=(I2CBT.available()))>0)
{ //讀取藍牙訊息
Serial.print(“input size = “);
Serial.println(insize);
for (int i=0; i<insize; i++)
{
Serial.print(cmmd[i]=char(I2CBT.read()));
Serial.print(” “);
}//此段請參考上一篇解釋
}
switch (cmmd[0])
{ //讀取第一個字
case 97: //97為”a”的ASCII CODE
digitalWrite(13,HIGH); //點亮LED
digitalWrite(9,HIGH); //點亮LED
break;

case 98://98為”b”的ASCII CODE
Serial.println(“Get b”);
digitalWrite(13,LOW); //熄滅LED
digitalWrite(9,LOW); //熄滅LED
break;
} //Switch
} //while
}

 

Android code-setting xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.bluetooth9_3_01″
android:versionCode=”1″
android:versionName=”1.0″ >

<uses-sdk
android:minSdkVersion=”8″
android:targetSdkVersion=”18″ />
<uses-permission android:name=”android.permission.BLUETOOTH”/>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>
<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”com.example.bluetooth9_3_01.Bluetooth9_3_01″
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

 

Android code-layout01 xml

<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=”.Bluetooth9_3_01″ >

<Button
android:id=”@+id/button2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignBaseline=”@+id/textView1″
android:layout_marginTop=”28dp”
android:text=”結束” />

<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentRight=”true”
android:layout_alignParentTop=”true”
android:layout_marginRight=”84dp”
android:layout_marginTop=”42dp”
android:text=”TextView” />

<ListView
android:id=”@+id/bluetooth_list”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_below=”@+id/button2″ >

</ListView>

<EditText
android:id=”@+id/editText1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_alignRight=”@+id/bluetooth_list”
android:ems=”10″
android:inputType=”numberDecimal” >

<requestFocus />
</EditText>

<Button
android:id=”@+id/button1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@+id/editText1″
android:layout_toRightOf=”@+id/button2″
android:text=”Button” />

</RelativeLayout>

 

Android code-layout02 xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<TextView
android:id=”@+id/Bluetooth_Name”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Name”
android:textColor=”#ff0000″
android:textSize=”4mm” />

<TextView
android:id=”@+id/Bluetooth_Address”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Address”
android:textColor=”#00ff00″
android:textSize=”4mm” />

</LinearLayout>

 

Android code

package com.example.bluetooth9_3_01;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Bluetooth9_3_01 extends Activity implements OnItemClickListener{
private BluetoothAdapter bluetoothAdapter;
private int ENABLE_BULETOOTH=2;
private ArrayList<HashMap<String, String>> arrayList;
private SimpleAdapter adapter;
private ListView listmenu;
private BlueToothReceiver receiver;
private BufferedOutputStream out;
private BufferedInputStream in;
private BluetoothSocket socket;
private final UUID MY_UUID=UUID.fromString
(“00001101-0000-1000-8000-00805F9B34FB”);
private Button end;
private Button send;
private TextView tv1;
private byte[] array_51={‘b’,’a’};
private boolean m_blnchange=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth9_3_01);
findId();

bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter==null){
Toast.makeText(this, “不支援Bluetooth”, Toast.LENGTH_LONG).show();
finish();
}else if(!bluetoothAdapter.isEnabled()){
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, ENABLE_BULETOOTH);
}
arrayList=new ArrayList<HashMap<String,String>>();
if(bluetoothAdapter.isDiscovering()) bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.startDiscovery();
findBluetooth() ;
listmenu.setOnItemClickListener( this);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
if(!m_blnchange)
{
out.write(array_51[0]);
}
else
{
out.write(array_51[1]);
}
out.flush();
m_blnchange=!m_blnchange;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
end.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
out.close();
in.close();
socket.close();
finish();
} catch (IOException e) {
e.printStackTrace();
android.os.Process.killProcess(android.os.Process.myPid());
}

}
});

}

private void findBluetooth() {

receiver=new BlueToothReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
adapter=new SimpleAdapter(this, arrayList, R.layout.bluetoothitem,
new String[]{“arrayName”,”arrayAddress”},
new int[]{R.id.Bluetooth_Name, R.id.Bluetooth_Address});
listmenu.setAdapter(adapter);
}

public class BlueToothReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
HashMap<String, String> map=new HashMap<String, String>();
map.put(“arrayName”, device.getName());
map.put(“arrayAddress”, device.getAddress());
arrayList.add(map);
}else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
BluetoothDevice device1=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch(device1.getBondState()){
case BluetoothDevice.BOND_BONDING:
tv1.setText(“配對中”);
break;
case BluetoothDevice.BOND_BONDED:
tv1.setText(“配對完成”);
break;
case BluetoothDevice.BOND_NONE:
tv1.setText(“配對取消”);
break;
default:
break;

}
}
}
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
bluetoothAdapter.cancelDiscovery();
Set<BluetoothDevice> device1=bluetoothAdapter.getBondedDevices();
BluetoothDevice device =bluetoothAdapter.getRemoteDevice
(arrayList.get(arg2).get(“arrayAddress”));

try{
socket=device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
out=new BufferedOutputStream(socket.getOutputStream());
in=new BufferedInputStream(socket.getInputStream());
tv1.setText(“連線成功”);
}catch(IOException e){
}
}

private void findId() {
tv1=(TextView)findViewById(R.id.textView1);
end=(Button)findViewById(R.id.button2);
send=(Button)findViewById(R.id.button1);
listmenu=(ListView) findViewById(R.id.bluetooth_list);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(receiver!=null)
unregisterReceiver(receiver);
Toast.makeText(this, “結束”, 2000).show();
}

}

 

 

 


發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *