想了想,还是把这个项目记录一下,刚接触Android不久,这个算是第二个Android项目吧!不废话了,还是开始叙述一下项目吧!整个项目涉及Android的Wifi、Bluetooth通信,这里只介绍蓝牙部分:
一边是Android手机,另一端是串口蓝牙模块,具体是在淘宝买的(参考网址:http://item.taobao.com/item.htm?id=12792736263),串口蓝牙与AVR(ATMEGA 1280)相连。Android手机通过蓝牙向ATMEGA 1280发送指令信息来控制机器人做出相应动作。
主界面截图如下:两个EditText输入两个马达的速度,后面两个按钮设置马达转动的方向,点击发送指令开始发送,同时在下面的TextView中显示所发送的指令。
界面布局比较简单,就不再贴代码了。解释一下指令格式:前四位为固定值“CMD:”;接下来四位为ACK发送成功一次,ACK累加1;接下来四位设置第一个马达,第一位设置方向,后三位为速度;最后四位就是第二个马达的设置。
Android要使用蓝牙,首先要在AndroidManifest.xml文件中进行如下配置:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
在AndroidManifest.xml里面注册Service
<service android:name=".BluetoothServe.BluetoothService" android:enabled="true"></service>
1、首先是主Activity,主界面如上图,点击菜单,可以扫描远端蓝牙设备,可以设置本机蓝牙可见性,代码如下:
package com.example.android.BluetoothChat;
import java.io.IOException;
import com.example.android.BluetoothServe.BluetoothService;
import com.example.android.BluetoothServe.BluetoothData;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothChat extends Activity {
/** Called when the activity is first created. */
private static final String TAG = "BlutoothTest";
private static final boolean D = true ;
private Button btF1,btF2,btW1,btW2,sendCMD;
private TextView mTextView;
private TextView commandview,ackview;
private EditText edit1,edit2;
private BluetoothAdapter myBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private static final int REQUEST_CONNECT_DEVICE = 1;
private String BackACK = "ACK:";
private String speed1,speed2;
private int left = 1,right=1;
private static int count = 1;
private BluetoothData bluetoothData;
//此处用于启动蓝牙服务程序
private ServiceConnection connection=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName arg0, IBinder service) {
bluetoothData = (BluetoothData)service;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
bluetoothData = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//本地蓝牙启动