写了上一篇的,就一不做,二不休的把今天才完成的自制的蓝牙遥控车吧,
咱分两步走第一部分是Android 方面的,第二是硬件Zigbee方面的。
先说Android方面的,
上源代码吧:
package com.example.hejingzhou.bluetoothtoydemo;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
public class WelcomeActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
handler = new Handler();
handler.postDelayed(newRun,3000);
}
private Runnable newRun = new Runnable() {
@Override
public void run() {
startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
finish();
}
};
}
@dimen
package com.example.hejingzhou.bluetoothtoydemo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.*;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private Handler handler;
private Button ButVisual,ButSearchDevice;
private ImageView imageExit;
private ListView listView;
static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
private UUID uuid;
private ArrayAdapter adapterDevices;
private List listDevices = new ArrayList();
private BluetoothAdapter bluetoothAdapter;
public static BluetoothSocket socket = null;
public static BluetoothSocket bluetoothSocket;
public static AcceptThread acceptThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
uuid = UUID.fromString(SPP_UUID);
findViewById();
InitBlueTooth();
click();
}
/**
* 单击监听
*/
private void click() {
ButVisual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discoverableIntent);
}
});
ButSearchDevice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
Toast.makeText(MainActivity.this, "请您打开蓝牙", Toast.LENGTH_SHORT).show();
return;
}
//setTitle("本设备蓝牙地址" + bluetoothAdapter.getAddress());
listDevices.clear();
bluetoothAdapter.startDiscovery();
}
});
imageExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bluetoothSocket != null)
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
MainActivity.this.finish();
}
});
}
private void findViewById() {
ButVisual = (Button)findViewById(R.id.buttonvisual);
ButSearchDevice = (Button)findViewById(R.id.buttonsearch);
imageExit = (ImageView)findViewById(R.id.imageViewExit);
listView = (ListView)findViewById(R.id.listView);
adapterDevices = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,listDevices);
listView.setAdapter(adapterDevices);
listView.setOnItemClickListener(new ItemClickEvent());
}
/**
* 初始化蓝牙
*/
private void InitBlueTooth(){
if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
{
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
handler = new Handler()
{
public void HanMessage(Message message)
{
switch (message.what)
{
case 0:
acceptThread = new AcceptThread();
acceptThread.start();//开启线程的时候出错
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intentFilter);
} else if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)
{
bluetoothAdapter.enable();
try {
Thread.sleep(1000);
}
/* try {
if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
{
Toast.makeText(MainActivity.this,"已打开蓝牙",Toast.LENGTH_SHORT).show();
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
handler = new Handler()
{
public void HanMessage(Message message)
{
switch (message.what)
{
case 0:
acceptThread = new AcceptThread();
acceptThread.start();//开启线程的时候出错
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intentFilter);
}else
{
Toast.makeText(MainActivity.this,"蓝牙打开失败,请手动打开",Toast.LENGTH_SHORT).show();
return;
}
}*/ catch (Exception e) {
Toast.makeText(MainActivity.this,"STATE_OFF注册错误",Toast.LENGTH_SHORT).show();
}
} /*catch (InterruptedException e) {
e.printStackTrace();
}*/
}
/**
* 管理蓝牙连接套接口
*/
private void manageConnectedSocket()
{
bluetoothSocket = socket;
startActivity(new Intent(MainActivity.this,CMDActivity.class));
}
/**
* BroadcastReceiver基类代码,将收到发送的意图sendBroadcast()。
*/
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle bundle = intent.getExtras();
Object[] objectName = bundle.keySet().toArray();
//显示详细的消息细节
for(int i = 0;i parent, View view, int position, long id) {
String str = listDevices.get(position);
String[] values = str.split("\\|");
String address = values[1];
Log.e("address",values[1]);
uuid = UUID.fromString(SPP_UUID);
Log.e("uuid",uuid.toString());
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(address);
Method method;
try {
method = bluetoothDevice.getClass().getMethod("createRfcommSocket",new Class[] {int.class});
bluetoothSocket = (BluetoothSocket)method.invoke(bluetoothDevice,Integer.valueOf(1));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
bluetoothAdapter.cancelDiscovery();
try {
bluetoothSocket.connect();
startActivity(new Intent(MainActivity.this,CMDActivity.class));
} catch (IOException e) {
e.printStackTrace();
}
}
}
class AcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public AcceptThread()
{
BluetoothServerSocket tmp = null;
try {
Method listenMethod = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn",new Class[]{int.class});
tmp = (BluetoothServerSocket)listenMethod.invoke(bluetoothAdapter,Integer.valueOf(1));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
serverSocket = tmp;
}
public void run()
{
while(true)
{
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
if(socket != null)
{
manageConnectedSocket();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
Message message = new Message();
message.what = 0;
handler.sendMessage(message);
}
//将取消监听套接字,导致线程结束
public void cancel()
{
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.example.hejingzhou.bluetoothtoydemo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
public class CMDActivity extends AppCompatActivity {
public static boolean isRecording = false;
private ImageButton IBUp;
private ImageButton IBDown;
private ImageButton IBLeft;
private ImageButton IBRight;
private ImageButton IBYuan;
private ImageButton IBLight;
private ImageButton IBDisconnect;
private ImageButton IBBack;
private TextView test;
private OutputStream outputStream = null;
private Handler handler;
private ConnectedThread connectedThread;
private String encodeType = "UTF-8";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cmd);
findViewById();
click();
connectedThread = new ConnectedThread();
handler = new MyHandler();
connectedThread.Start();
}
private void click() {
IBBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CMDActivity.this.finish();
}
});
IBDisconnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
MainActivity.bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
connectedThread.Stop();
}
});
IBUp.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
sendMessage("U0#");
} else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
sendMessage("U1#");
}
return false;
}
});
IBDown.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
sendMessage("U0#");
} else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
sendMessage("U1");
}
return false;
}
});
IBLeft.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
sendMessage("30");
} else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
sendMessage("31");
}
return false;
}
});
IBRight.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
sendMessage("40");
} else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
sendMessage("41");
}
return false;
}
});
/*IBLight.setOnTouchListener(new View.OnTouchListener() {
boolean isClick = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
sendMessage("L0#");
isClick = true;
} else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
sendMessage("L1#");
}
return false;
}
});*/
IBLight.setOnClickListener(new View.OnClickListener() {
int a = 1 ;
@Override
public void onClick(View v) {
if((a%2==0)==false)
{
sendMessage("L0#");
}else if((a%2==0)==true)
{
sendMessage("L1#");
}
a++;
}
});
}
public void sendMessage(String strCmd) {
try {
outputStream = MainActivity.bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte[] msgbuffer = null;
try {
msgbuffer = strCmd.getBytes(encodeType);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
outputStream.write(msgbuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
try {
MainActivity.bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
super.onDestroy();
}
private void findViewById() {
IBUp = (ImageButton) findViewById(R.id.imageButtonShang);
IBDown = (ImageButton) findViewById(R.id.imageButtonXia);
IBLeft = (ImageButton) findViewById(R.id.imageButtonZuo);
IBRight = (ImageButton) findViewById(R.id.imageButtonYou);
IBYuan = (ImageButton) findViewById(R.id.imageButtonYuan);
IBLight = (ImageButton) findViewById(R.id.imageButtonLight);
IBBack = (ImageButton)findViewById(R.id.imageButtonBACK);
IBDisconnect = (ImageButton) findViewById(R.id.imageButtondisconnect);
}
/***
* 连接线程
*/
class ConnectedThread extends Thread {
private InputStream inputStream = null;
private long wait;
private Thread thread;
public ConnectedThread() {
isRecording = false;
this.wait = 50;
thread = new Thread(new ReadRunnable());
}
public void Stop() {
isRecording = false;
}
public void Start() {
isRecording = true;
State state = thread.getState();
if (state == State.NEW) {
thread.start();
} else thread.resume();
}
private class ReadRunnable implements Runnable {
@Override
public void run() {
try {
inputStream = MainActivity.bluetoothSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
int length = 20;
byte[] temp = new byte[length];
if (inputStream != null) {
try {
int len = inputStream.read(temp, 0, length - 1);
if (len > 0) {
byte[] bluetoothBuff = new byte[len];
System.arraycopy(temp, 0, bluetoothBuff, 0, bluetoothBuff.length);
String readstr = new String(bluetoothBuff, encodeType);
}
Thread.sleep(wait);
} catch (IOException e) {
handler.sendEmptyMessage(00);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* sendMessage
*/
/*public void sendMessage(String strCmd) {
try {
outputStream = MainActivity.bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte[] msgbuffer = null;
try {
msgbuffer = strCmd.getBytes(encodeType);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
outputStream.write(msgbuffer);
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
private class MyHandler extends Handler {
@Override
public void dispatchMessage(Message msg) {
switch (msg.what) {
case 00:
isRecording = false;
break;
case 01:
String info = (String) msg.obj;
break;
default:
break;
}
super.dispatchMessage(msg);
}
}
}
#include
#include
#define uint unsigned int
#define uchar unsigned char
//定义控制LED灯的端口
#define LED1 P0_6
#define R1 P2_0
#define In P1_0
//函数声明
void Delayms(uint xms); //延时函数
void InitLed(void); //初始化
void InitUart(); //初始化串口
void Uart_Send_String(char *Data,int len);
void Infrared(void);
char Rxdata[3];
uchar RXTXflag = 1;
char temp;
uchar datanumber = 0;
/****************************
//延时函数
*****************************/
void Delayms(uint xms) //i=xms 即延时i毫秒 (16M晶振时候大约数,32M需要修改,系统不修改默认使用内部16M)
{
uint i,j;
for(i=xms;i>0;i--)
for(j=587;j>0;j--);
}
/****************************
//初始化程序
*****************************/
void InitLed(void)
{
P0DIR |= 0x50; //定义为输出 0100 0000
P2DIR |= 0x01;
//P0DIR |= 0x20;
LED1 = 0; //LED1、2灯熄灭
R1 = 1;
}
//红外控制初始化**********************
void Infrared(void)
{
P1DIR &= ~0x01;
P1SEL |= 0x01;
In = 0;
}
/****************************************************************
串口初始化函数
***********************************************************/
void InitUart()
{
CLKCONCMD &= ~0x40; // 设置系统时钟源为 32MHZ晶振
while(CLKCONSTA & 0x40); // 等待晶振稳定
CLKCONCMD &= ~0x47; // 设置系统主时钟频率为 32MHZ
PERCFG = 0x00; //位置1 P0口
P0SEL = 0x3c; //P0_2,P0_3,P0_4,P0_5用作串口,第二功能
P2DIR &= ~0XC0; //P0 优先作为UART0 ,优先级
U0CSR |= 0x80; //UART 方式
U0GCR |= 11; //U0GCR与U0BAUD配合
U0BAUD |= 216; // 波特率设为115200
UTX0IF = 1; //UART0 TX 中断标志初始置位1 (收发时候)
U0CSR |= 0X40; //允许接收
IEN0 |= 0x84; // 开总中断,接收中断
}
/****************************************************************
串口发送字符串函数
****************************************************************/
void Uart_Send_String(char *Data,int len)
{
{
int j;
for(j=0;j