当前位置:   article > 正文

android蓝牙遥控车

android蓝牙遥控车

写了上一篇的,就一不做,二不休的把今天才完成的自制的蓝牙遥控车吧,


咱分两步走第一部分是Android 方面的,第二是硬件Zigbee方面的。

先说Android方面的,


上源代码吧:

一、Android部分


我的代码运行顺序是先是WelcomActivity,过两秒后然后进入MainActivity,在这里配对成功后进入CMDActivity

1.1、布局方面的代码,为了美观把平常写的UI美化了一下。

1.11、activity_welcome.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:paddingBottom="@dimen/activity_vertical_margin"
  8. android:paddingLeft="@dimen/activity_horizontal_margin"
  9. android:paddingRight="@dimen/activity_horizontal_margin"
  10. android:screenOrientation="landscape"
  11. android:paddingTop="@dimen/activity_vertical_margin"
  12. android:background="@drawable/hengping"
  13. tools:context="com.example.hejingzhou.bluetoothtoydemo.WelcomeActivity">
  14. </RelativeLayout><span style="color:#660000;">
  15. </span>

对应的java

  1. <span style="color:#660000;">package com.example.hejingzhou.bluetoothtoydemo;
  2. </span>import android.content.Intent;
  3. import android.os.Handler;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.view.Window;
  7. public class WelcomeActivity extends AppCompatActivity {
  8. private Handler handler;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_welcome);
  13. handler = new Handler();
  14. handler.postDelayed(newRun,3000);
  15. }
  16. private Runnable newRun = new Runnable() {
  17. @Override
  18. public void run() {
  19. startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
  20. finish();
  21. }
  22. };
  23. }<span style="color:#660000;">
  24. </span>

//***************//**************//**********//**************//*****************//*****************//****************//******************//****************//

1.12、activity_main


  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:paddingBottom="@dimen/activity_vertical_margin"
  8. android:paddingLeft="@dimen/activity_horizontal_margin"
  9. android:paddingRight="@dimen/activity_horizontal_margin"
  10. android:screenOrientation="landscape"
  11. android:paddingTop="@dimen/activity_vertical_margin"
  12. android:background="@drawable/q2"
  13. tools:context="com.example.hejingzhou.bluetoothtoydemo.MainActivity">
  14. <Button
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="允许对外可见"
  18. android:id="@+id/buttonvisual"
  19. android:textColor="#820041"
  20. android:background="@drawable/shape"
  21. android:layout_marginTop="35dp"
  22. android:layout_alignParentTop="true"
  23. android:layout_alignParentLeft="true"
  24. android:layout_alignParentStart="true"/>
  25. <Button
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:text="搜索其他设备"
  29. android:id="@+id/buttonsearch"
  30. android:background="@drawable/shape_2"
  31. android:textColor="#003e3e"
  32. android:layout_alignTop="@+id/buttonvisual"
  33. android:layout_toRightOf="@+id/buttonvisual"
  34. android:layout_toEndOf="@+id/buttonvisual"
  35. android:layout_marginLeft="49dp"
  36. android:layout_marginStart="49dp"/>
  37. <ImageView
  38. android:layout_width="60dp"
  39. android:layout_height="60dp"
  40. android:id="@+id/imageViewExit"
  41. android:layout_alignParentBottom="true"
  42. android:layout_alignParentRight="true"
  43. android:layout_alignParentEnd="true"
  44. android:layout_marginRight="38dp"
  45. android:layout_marginEnd="38dp"
  46. android:src="@drawable/exit"
  47. android:layout_marginBottom="42dp"/>
  48. <ListView
  49. android:layout_width="wrap_content"
  50. android:layout_height="wrap_content"
  51. android:id="@+id/listView"
  52. android:layout_alignParentLeft="true"
  53. android:layout_alignParentStart="true"
  54. android:layout_below="@+id/buttonvisual"
  55. android:layout_toLeftOf="@+id/imageViewExit"
  56. android:layout_toStartOf="@+id/imageViewExit"/>
  57. </RelativeLayout>
上边这个布局所用到的
@dimen
写到@drawable文件夹内是针对Button的圆角处理的
详情是这样的
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle" >
  4. <!-- 填充的颜色:这里设置背景透明 -->
  5. <solid android:color="@android:color/transparent" />
  6. <!-- 边框的颜色 :不能和窗口背景色一样-->
  7. <stroke
  8. android:width="3dp"
  9. android:color="#930093" />
  10. <!-- 设置按钮的四个角为弧形 -->
  11. <!-- android:radius 弧形的半径 -->
  12. <corners android:radius="5dip" />
  13. <!-- padding:Button里面的文字与Button边界的间隔 -->
  14. <padding
  15. android:bottom="10dp"
  16. android:left="10dp"
  17. android:right="10dp"
  18. android:top="10dp" />
  19. </shape>


对应的java                                                                                                                                                                                                                                                                                                                        
  1. <span style="color:#660000;">package com.example.hejingzhou.bluetoothtoydemo;
  2. </span>import android.bluetooth.BluetoothAdapter;
  3. import android.bluetooth.BluetoothDevice;
  4. import android.bluetooth.BluetoothServerSocket;
  5. import android.bluetooth.BluetoothSocket;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.IntentFilter;
  10. import android.os.*;
  11. import android.os.Process;
  12. import android.support.v7.app.AppCompatActivity;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.AdapterView;
  16. import android.widget.ArrayAdapter;
  17. import android.widget.Button;
  18. import android.widget.ImageView;
  19. import android.widget.ListView;
  20. import android.widget.Toast;
  21. import java.io.IOException;
  22. import java.lang.reflect.InvocationTargetException;
  23. import java.lang.reflect.Method;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.UUID;
  27. public class MainActivity extends AppCompatActivity {
  28. private Handler handler;
  29. private Button ButVisual,ButSearchDevice;
  30. private ImageView imageExit;
  31. private ListView listView;
  32. static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
  33. private UUID uuid;
  34. private ArrayAdapter<String> adapterDevices;
  35. private List<String> listDevices = new ArrayList<String>();
  36. private BluetoothAdapter bluetoothAdapter;
  37. public static BluetoothSocket socket = null;
  38. public static BluetoothSocket bluetoothSocket;
  39. public static AcceptThread acceptThread;
  40. @Override
  41. protected void onCreate(Bundle savedInstanceState) {
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.activity_main);
  44. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  45. uuid = UUID.fromString(SPP_UUID);
  46. findViewById();
  47. InitBlueTooth();
  48. click();
  49. }
  50. /**
  51. * 单击监听
  52. */
  53. private void click() {
  54. ButVisual.setOnClickListener(new View.OnClickListener() {
  55. @Override
  56. public void onClick(View v) {
  57. Intent discoverableIntent = new Intent(
  58. BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  59. discoverableIntent.putExtra(
  60. BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
  61. startActivity(discoverableIntent);
  62. }
  63. });
  64. ButSearchDevice.setOnClickListener(new View.OnClickListener() {
  65. @Override
  66. public void onClick(View v) {
  67. if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
  68. Toast.makeText(MainActivity.this, "请您打开蓝牙", Toast.LENGTH_SHORT).show();
  69. return;
  70. }
  71. //setTitle("本设备蓝牙地址" + bluetoothAdapter.getAddress());
  72. listDevices.clear();
  73. bluetoothAdapter.startDiscovery();
  74. }
  75. });
  76. imageExit.setOnClickListener(new View.OnClickListener() {
  77. @Override
  78. public void onClick(View v) {
  79. if (bluetoothSocket != null)
  80. try {
  81. bluetoothSocket.close();
  82. } catch (IOException e) {
  83. e.printStackTrace();
  84. }
  85. MainActivity.this.finish();
  86. }
  87. });
  88. }
  89. private void findViewById() {
  90. ButVisual = (Button)findViewById(R.id.buttonvisual);
  91. ButSearchDevice = (Button)findViewById(R.id.buttonsearch);
  92. imageExit = (ImageView)findViewById(R.id.imageViewExit);
  93. listView = (ListView)findViewById(R.id.listView);
  94. adapterDevices = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listDevices);
  95. listView.setAdapter(adapterDevices);
  96. listView.setOnItemClickListener(new ItemClickEvent());
  97. }
  98. /**
  99. * 初始化蓝牙
  100. */
  101. private void InitBlueTooth(){
  102. if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
  103. {
  104. //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
  105. handler = new Handler()
  106. {
  107. public void HanMessage(Message message)
  108. {
  109. switch (message.what)
  110. {
  111. case 0:
  112. acceptThread = new AcceptThread();
  113. acceptThread.start();//开启线程的时候出错
  114. }
  115. }
  116. };
  117. IntentFilter intentFilter = new IntentFilter();
  118. intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
  119. intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  120. intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
  121. intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  122. registerReceiver(searchDevices, intentFilter);
  123. } else if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)
  124. {
  125. bluetoothAdapter.enable();
  126. try {
  127. Thread.sleep(1000);
  128. }
  129. /* try {
  130. if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
  131. {
  132. Toast.makeText(MainActivity.this,"已打开蓝牙",Toast.LENGTH_SHORT).show();
  133. //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
  134. handler = new Handler()
  135. {
  136. public void HanMessage(Message message)
  137. {
  138. switch (message.what)
  139. {
  140. case 0:
  141. acceptThread = new AcceptThread();
  142. acceptThread.start();//开启线程的时候出错
  143. }
  144. }
  145. };
  146. IntentFilter intentFilter = new IntentFilter();
  147. intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
  148. intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  149. intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
  150. intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  151. registerReceiver(searchDevices, intentFilter);
  152. }else
  153. {
  154. Toast.makeText(MainActivity.this,"蓝牙打开失败,请手动打开",Toast.LENGTH_SHORT).show();
  155. return;
  156. }
  157. }*/ catch (Exception e) {
  158. Toast.makeText(MainActivity.this,"STATE_OFF注册错误",Toast.LENGTH_SHORT).show();
  159. }
  160. } /*catch (InterruptedException e) {
  161. e.printStackTrace();
  162. }*/
  163. }
  164. /**
  165. * 管理蓝牙连接套接口
  166. */
  167. private void manageConnectedSocket()
  168. {
  169. bluetoothSocket = socket;
  170. startActivity(new Intent(MainActivity.this,CMDActivity.class));
  171. }
  172. /**
  173. * BroadcastReceiver基类代码,将收到发送的意图sendBroadcast()。
  174. */
  175. private BroadcastReceiver searchDevices = new BroadcastReceiver() {
  176. @Override
  177. public void onReceive(Context context, Intent intent) {
  178. String action = intent.getAction();
  179. Bundle bundle = intent.getExtras();
  180. Object[] objectName = bundle.keySet().toArray();
  181. //显示详细的消息细节
  182. for(int i = 0;i<objectName.length;i++)
  183. {
  184. String keyName = objectName[i].toString();
  185. Log.e(keyName,String.valueOf(bundle.get(keyName)));
  186. }
  187. //搜索到设备时
  188. if(BluetoothDevice.ACTION_FOUND.equals(action))
  189. {
  190. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  191. String str = device.getName()+"|"+device.getAddress();
  192. if(listDevices.indexOf(str) == -1 )
  193. {
  194. listDevices.add(str);
  195. }
  196. adapterDevices.notifyDataSetChanged();//每次改变就刷新
  197. }
  198. }
  199. };
  200. @Override
  201. protected void onDestroy() {
  202. this.unregisterReceiver(searchDevices);//取消注册量
  203. super.onDestroy();
  204. android.os.Process.killProcess(Process.myPid());
  205. acceptThread.cancel();
  206. acceptThread.destroy();
  207. }
  208. class ItemClickEvent implements AdapterView.OnItemClickListener
  209. {
  210. @Override
  211. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  212. String str = listDevices.get(position);
  213. String[] values = str.split("\\|");
  214. String address = values[1];
  215. Log.e("address",values[1]);
  216. uuid = UUID.fromString(SPP_UUID);
  217. Log.e("uuid",uuid.toString());
  218. BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(address);
  219. Method method;
  220. try {
  221. method = bluetoothDevice.getClass().getMethod("createRfcommSocket",new Class[] {int.class});
  222. bluetoothSocket = (BluetoothSocket)method.invoke(bluetoothDevice,Integer.valueOf(1));
  223. } catch (NoSuchMethodException e) {
  224. e.printStackTrace();
  225. } catch (InvocationTargetException e) {
  226. e.printStackTrace();
  227. } catch (IllegalAccessException e) {
  228. e.printStackTrace();
  229. }
  230. bluetoothAdapter.cancelDiscovery();
  231. try {
  232. bluetoothSocket.connect();
  233. startActivity(new Intent(MainActivity.this,CMDActivity.class));
  234. } catch (IOException e) {
  235. e.printStackTrace();
  236. }
  237. }
  238. }
  239. class AcceptThread extends Thread
  240. {
  241. private final BluetoothServerSocket serverSocket;
  242. public AcceptThread()
  243. {
  244. BluetoothServerSocket tmp = null;
  245. try {
  246. Method listenMethod = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn",new Class[]{int.class});
  247. tmp = (BluetoothServerSocket)listenMethod.invoke(bluetoothAdapter,Integer.valueOf(1));
  248. } catch (NoSuchMethodException e) {
  249. e.printStackTrace();
  250. } catch (InvocationTargetException e) {
  251. e.printStackTrace();
  252. } catch (IllegalAccessException e) {
  253. e.printStackTrace();
  254. }
  255. serverSocket = tmp;
  256. }
  257. public void run()
  258. {
  259. while(true)
  260. {
  261. try {
  262. socket = serverSocket.accept();
  263. } catch (IOException e) {
  264. break;
  265. }
  266. if(socket != null)
  267. {
  268. manageConnectedSocket();
  269. try {
  270. serverSocket.close();
  271. } catch (IOException e) {
  272. e.printStackTrace();
  273. }
  274. break;
  275. }
  276. }
  277. Message message = new Message();
  278. message.what = 0;
  279. handler.sendMessage(message);
  280. }
  281. //将取消监听套接字,导致线程结束
  282. public void cancel()
  283. {
  284. try {
  285. serverSocket.close();
  286. } catch (IOException e) {
  287. e.printStackTrace();
  288. }
  289. }
  290. }
  291. }<span style="color:#660000;">
  292. </span>

//***************//**************//**********//**************//*****************//*****************//****************//******************//****************//

                                                                                                                             1.13、activity_cmd.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:paddingBottom="@dimen/activity_vertical_margin"
  8. android:paddingLeft="@dimen/activity_horizontal_margin"
  9. android:paddingRight="@dimen/activity_horizontal_margin"
  10. android:paddingTop="@dimen/activity_vertical_margin"
  11. android:background="@drawable/www"
  12. tools:context="com.example.hejingzhou.bluetoothtoydemo.CMDActivity">
  13. <ImageButton
  14. android:layout_width="60dp"
  15. android:layout_height="60dp"
  16. android:id="@+id/imageButtonShang"
  17. android:background="@drawable/shang"
  18. android:layout_marginLeft="19dp"
  19. android:layout_marginStart="19dp"
  20. android:layout_above="@+id/imageButtonYuan"
  21. android:layout_toRightOf="@+id/imageButtonZuo"
  22. android:layout_toEndOf="@+id/imageButtonZuo"
  23. android:layout_marginBottom="25dp"/>
  24. <ImageButton
  25. android:layout_width="60dp"
  26. android:layout_height="60dp"
  27. android:id="@+id/imageButtonXia"
  28. android:background="@drawable/xia"
  29. android:layout_marginTop="25dp"
  30. android:layout_below="@+id/imageButtonZuo"
  31. android:layout_alignLeft="@+id/imageButtonYuan"
  32. android:layout_alignStart="@+id/imageButtonYuan"/>
  33. <ImageButton
  34. android:layout_width="60dp"
  35. android:layout_height="60dp"
  36. android:id="@+id/imageButtonZuo"
  37. android:background="@drawable/zuo"
  38. android:layout_centerVertical="true"
  39. android:layout_alignParentLeft="true"
  40. android:layout_alignParentStart="true"/>
  41. <ImageButton
  42. android:layout_width="60dp"
  43. android:layout_height="60dp"
  44. android:id="@+id/imageButtonYou"
  45. android:background="@drawable/you"
  46. android:layout_marginLeft="23dp"
  47. android:layout_marginStart="23dp"
  48. android:layout_above="@+id/imageButtonXia"
  49. android:layout_toRightOf="@+id/imageButtonShang"
  50. android:layout_toEndOf="@+id/imageButtonShang"/>
  51. <ImageButton
  52. android:layout_width="60dp"
  53. android:layout_height="60dp"
  54. android:id="@+id/imageButtonYuan"
  55. android:background="@drawable/yuan"
  56. android:layout_above="@+id/imageButtonXia"
  57. android:layout_toLeftOf="@+id/imageButtonYou"
  58. android:layout_toStartOf="@+id/imageButtonYou"/>
  59. <ImageButton
  60. android:layout_width="wrap_content"
  61. android:layout_height="wrap_content"
  62. android:id="@+id/imageButtondisconnect"
  63. android:src="@drawable/duankai"
  64. android:background="#00000000"
  65. android:layout_marginRight="107dp"
  66. android:layout_marginEnd="107dp"
  67. android:layout_alignBottom="@+id/imageButtonXia"
  68. android:layout_alignParentRight="true"
  69. android:layout_alignParentEnd="true"/>
  70. <ImageButton
  71. android:layout_width="40dp"
  72. android:layout_height="40dp"
  73. android:id="@+id/imageButtonLight"
  74. android:src="@drawable/dengpao"
  75. android:background="#00000000"
  76. android:layout_marginRight="30dp"
  77. android:layout_marginEnd="30dp"
  78. android:layout_alignTop="@+id/imageButtondisconnect"
  79. android:layout_toLeftOf="@+id/imageButtondisconnect"
  80. android:layout_toStartOf="@+id/imageButtondisconnect"/>
  81. <ImageButton
  82. android:layout_width="wrap_content"
  83. android:layout_height="wrap_content"
  84. android:id="@+id/imageButtonBACK"
  85. android:background="@drawable/fanhui"
  86. android:layout_marginRight="32dp"
  87. android:layout_marginEnd="32dp"
  88. android:layout_alignBottom="@+id/imageButtonLight"
  89. android:layout_alignParentRight="true"
  90. android:layout_alignParentEnd="true"/>
  91. </RelativeLayout><span style="color:#660000;">
  92. </span>

对应的JAVA

  1. <span style="color:#660000;">package com.example.hejingzhou.bluetoothtoydemo;
  2. </span>import android.os.Handler;
  3. import android.os.Message;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.os.Bundle;
  6. import android.view.MotionEvent;
  7. import android.view.View;
  8. import android.widget.CompoundButton;
  9. import android.widget.ImageButton;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12. import java.io.IOException;
  13. import java.io.InputStream;
  14. import java.io.OutputStream;
  15. import java.io.UnsupportedEncodingException;
  16. public class CMDActivity extends AppCompatActivity {
  17. public static boolean isRecording = false;
  18. private ImageButton IBUp;
  19. private ImageButton IBDown;
  20. private ImageButton IBLeft;
  21. private ImageButton IBRight;
  22. private ImageButton IBYuan;
  23. private ImageButton IBLight;
  24. private ImageButton IBDisconnect;
  25. private ImageButton IBBack;
  26. private TextView test;
  27. private OutputStream outputStream = null;
  28. private Handler handler;
  29. private ConnectedThread connectedThread;
  30. private String encodeType = "UTF-8";
  31. @Override
  32. protected void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_cmd);
  35. findViewById();
  36. click();
  37. connectedThread = new ConnectedThread();
  38. handler = new MyHandler();
  39. connectedThread.Start();
  40. }
  41. private void click() {
  42. IBBack.setOnClickListener(new View.OnClickListener() {
  43. @Override
  44. public void onClick(View v) {
  45. CMDActivity.this.finish();
  46. }
  47. });
  48. IBDisconnect.setOnClickListener(new View.OnClickListener() {
  49. @Override
  50. public void onClick(View v) {
  51. try {
  52. MainActivity.bluetoothSocket.close();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. connectedThread.Stop();
  57. }
  58. });
  59. IBUp.setOnTouchListener(new View.OnTouchListener() {
  60. @Override
  61. public boolean onTouch(View v, MotionEvent event) {
  62. if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
  63. sendMessage("U0#");
  64. } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
  65. sendMessage("U1#");
  66. }
  67. return false;
  68. }
  69. });
  70. IBDown.setOnTouchListener(new View.OnTouchListener() {
  71. @Override
  72. public boolean onTouch(View v, MotionEvent event) {
  73. if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
  74. sendMessage("U0#");
  75. } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
  76. sendMessage("U1");
  77. }
  78. return false;
  79. }
  80. });
  81. IBLeft.setOnTouchListener(new View.OnTouchListener() {
  82. @Override
  83. public boolean onTouch(View v, MotionEvent event) {
  84. if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
  85. sendMessage("30");
  86. } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
  87. sendMessage("31");
  88. }
  89. return false;
  90. }
  91. });
  92. IBRight.setOnTouchListener(new View.OnTouchListener() {
  93. @Override
  94. public boolean onTouch(View v, MotionEvent event) {
  95. if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
  96. sendMessage("40");
  97. } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
  98. sendMessage("41");
  99. }
  100. return false;
  101. }
  102. });
  103. /*IBLight.setOnTouchListener(new View.OnTouchListener() {
  104. boolean isClick = false;
  105. @Override
  106. public boolean onTouch(View v, MotionEvent event) {
  107. if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
  108. sendMessage("L0#");
  109. isClick = true;
  110. } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
  111. sendMessage("L1#");
  112. }
  113. return false;
  114. }
  115. });*/
  116. IBLight.setOnClickListener(new View.OnClickListener() {
  117. int a = 1 ;
  118. @Override
  119. public void onClick(View v) {
  120. if((a%2==0)==false)
  121. {
  122. sendMessage("L0#");
  123. }else if((a%2==0)==true)
  124. {
  125. sendMessage("L1#");
  126. }
  127. a++;
  128. }
  129. });
  130. }
  131. public void sendMessage(String strCmd) {
  132. try {
  133. outputStream = MainActivity.bluetoothSocket.getOutputStream();
  134. } catch (IOException e) {
  135. e.printStackTrace();
  136. }
  137. byte[] msgbuffer = null;
  138. try {
  139. msgbuffer = strCmd.getBytes(encodeType);
  140. } catch (UnsupportedEncodingException e) {
  141. e.printStackTrace();
  142. }
  143. try {
  144. outputStream.write(msgbuffer);
  145. } catch (IOException e) {
  146. e.printStackTrace();
  147. }
  148. }
  149. @Override
  150. protected void onDestroy() {
  151. try {
  152. MainActivity.bluetoothSocket.close();
  153. } catch (IOException e) {
  154. e.printStackTrace();
  155. }
  156. super.onDestroy();
  157. }
  158. private void findViewById() {
  159. IBUp = (ImageButton) findViewById(R.id.imageButtonShang);
  160. IBDown = (ImageButton) findViewById(R.id.imageButtonXia);
  161. IBLeft = (ImageButton) findViewById(R.id.imageButtonZuo);
  162. IBRight = (ImageButton) findViewById(R.id.imageButtonYou);
  163. IBYuan = (ImageButton) findViewById(R.id.imageButtonYuan);
  164. IBLight = (ImageButton) findViewById(R.id.imageButtonLight);
  165. IBBack = (ImageButton)findViewById(R.id.imageButtonBACK);
  166. IBDisconnect = (ImageButton) findViewById(R.id.imageButtondisconnect);
  167. }
  168. /***
  169. * 连接线程
  170. */
  171. class ConnectedThread extends Thread {
  172. private InputStream inputStream = null;
  173. private long wait;
  174. private Thread thread;
  175. public ConnectedThread() {
  176. isRecording = false;
  177. this.wait = 50;
  178. thread = new Thread(new ReadRunnable());
  179. }
  180. public void Stop() {
  181. isRecording = false;
  182. }
  183. public void Start() {
  184. isRecording = true;
  185. State state = thread.getState();
  186. if (state == State.NEW) {
  187. thread.start();
  188. } else thread.resume();
  189. }
  190. private class ReadRunnable implements Runnable {
  191. @Override
  192. public void run() {
  193. try {
  194. inputStream = MainActivity.bluetoothSocket.getInputStream();
  195. } catch (IOException e) {
  196. e.printStackTrace();
  197. }
  198. int length = 20;
  199. byte[] temp = new byte[length];
  200. if (inputStream != null) {
  201. try {
  202. int len = inputStream.read(temp, 0, length - 1);
  203. if (len > 0) {
  204. byte[] bluetoothBuff = new byte[len];
  205. System.arraycopy(temp, 0, bluetoothBuff, 0, bluetoothBuff.length);
  206. String readstr = new String(bluetoothBuff, encodeType);
  207. }
  208. Thread.sleep(wait);
  209. } catch (IOException e) {
  210. handler.sendEmptyMessage(00);
  211. } catch (InterruptedException e) {
  212. e.printStackTrace();
  213. }
  214. }
  215. }
  216. }
  217. /**
  218. * sendMessage
  219. */
  220. /*public void sendMessage(String strCmd) {
  221. try {
  222. outputStream = MainActivity.bluetoothSocket.getOutputStream();
  223. } catch (IOException e) {
  224. e.printStackTrace();
  225. }
  226. byte[] msgbuffer = null;
  227. try {
  228. msgbuffer = strCmd.getBytes(encodeType);
  229. } catch (UnsupportedEncodingException e) {
  230. e.printStackTrace();
  231. }
  232. try {
  233. outputStream.write(msgbuffer);
  234. } catch (IOException e) {
  235. e.printStackTrace();
  236. }
  237. }*/
  238. }
  239. private class MyHandler extends Handler {
  240. @Override
  241. public void dispatchMessage(Message msg) {
  242. switch (msg.what) {
  243. case 00:
  244. isRecording = false;
  245. break;
  246. case 01:
  247. String info = (String) msg.obj;
  248. break;
  249. default:
  250. break;
  251. }
  252. super.dispatchMessage(msg);
  253. }
  254. }
  255. }<span style="color:#660000;">
  256. </span>


//***************//**************//**********//**************//*****************//*****************//****************//******************//****************//

二、Zigbee程序

  1. <span style="color:#009900;">
  2. </span>#include <ioCC2530.h>
  3. #include <string.h>
  4. #define uint unsigned int
  5. #define uchar unsigned char
  6. //定义控制LED灯的端口
  7. #define LED1 P0_6
  8. #define R1 P2_0
  9. #define In P1_0
  10. //函数声明
  11. void Delayms(uint xms); //延时函数
  12. void InitLed(void); //初始化
  13. void InitUart(); //初始化串口
  14. void Uart_Send_String(char *Data,int len);
  15. void Infrared(void);
  16. char Rxdata[3];
  17. uchar RXTXflag = 1;
  18. char temp;
  19. uchar datanumber = 0;
  20. /****************************
  21. //延时函数
  22. *****************************/
  23. void Delayms(uint xms) //i=xms 即延时i毫秒 (16M晶振时候大约数,32M需要修改,系统不修改默认使用内部16M)
  24. {
  25. uint i,j;
  26. for(i=xms;i>0;i--)
  27. for(j=587;j>0;j--);
  28. }
  29. /****************************
  30. //初始化程序
  31. *****************************/
  32. void InitLed(void)
  33. {
  34. P0DIR |= 0x50; //定义为输出 0100 0000
  35. P2DIR |= 0x01;
  36. //P0DIR |= 0x20;
  37. LED1 = 0; //LED1、2灯熄灭
  38. R1 = 1;
  39. }
  40. //红外控制初始化**********************
  41. void Infrared(void)
  42. {
  43. P1DIR &= ~0x01;
  44. P1SEL |= 0x01;
  45. In = 0;
  46. }
  47. /****************************************************************
  48. 串口初始化函数
  49. ***********************************************************/
  50. void InitUart()
  51. {
  52. CLKCONCMD &= ~0x40; // 设置系统时钟源为 32MHZ晶振
  53. while(CLKCONSTA & 0x40); // 等待晶振稳定
  54. CLKCONCMD &= ~0x47; // 设置系统主时钟频率为 32MHZ
  55. PERCFG = 0x00; //位置1 P0口
  56. P0SEL = 0x3c; //P0_2,P0_3,P0_4,P0_5用作串口,第二功能
  57. P2DIR &= ~0XC0; //P0 优先作为UART0 ,优先级
  58. U0CSR |= 0x80; //UART 方式
  59. U0GCR |= 11; //U0GCR与U0BAUD配合
  60. U0BAUD |= 216; // 波特率设为115200
  61. UTX0IF = 1; //UART0 TX 中断标志初始置位1 (收发时候)
  62. U0CSR |= 0X40; //允许接收
  63. IEN0 |= 0x84; // 开总中断,接收中断
  64. }
  65. /****************************************************************
  66. 串口发送字符串函数
  67. ****************************************************************/
  68. void Uart_Send_String(char *Data,int len)
  69. {
  70. {
  71. int j;
  72. for(j=0;j<len;j++)
  73. {
  74. U0DBUF = *Data++;
  75. while(UTX0IF == 0);
  76. UTX0IF = 0;
  77. }
  78. }
  79. }
  80. /***************************
  81. //主函数
  82. ***************************/
  83. void main(void)
  84. {
  85. InitLed(); //调用初始化函数
  86. InitUart();
  87. Infrared();//初始化红外
  88. while(1)
  89. {
  90. if(RXTXflag == 1) //接收状态
  91. {
  92. if( temp != 0)
  93. {
  94. if((temp!='#')&&(datanumber<3)) //'#'被定义为结束字符,最多能接收50个字符
  95. Rxdata[datanumber++] = temp;
  96. else
  97. {
  98. RXTXflag = 3; //进入发送状态
  99. }
  100. temp = 0;
  101. }
  102. }
  103. if(RXTXflag == 3) //检测接收到的数据
  104. {
  105. if(Rxdata[0]=='L')
  106. {
  107. switch(Rxdata[1]-48)//很重要,ASICC码转成数字,判断L后面第一个数
  108. {
  109. case 0:
  110. {
  111. LED1=1; //点亮
  112. break;
  113. }
  114. case 1:
  115. {
  116. LED1=0;
  117. break;
  118. }
  119. }
  120. }
  121. else if(Rxdata[0]=='U')
  122. {
  123. switch(Rxdata[1]-48)
  124. {
  125. case 0:
  126. R1 = 0;
  127. break;
  128. case 1:
  129. R1 = 1;
  130. break;
  131. }
  132. }
  133. RXTXflag = 1;
  134. datanumber = 0; //指针归 0
  135. }
  136. ///***************************
  137. if(R1!=0)
  138. {
  139. if((In == 1)&&(LED1!=1 ))
  140. {
  141. LED1 = 1;
  142. }else if((In == 1) && (LED1==1))
  143. {
  144. LED1 = 0;
  145. }
  146. }
  147. ///***************************
  148. }
  149. }
  150. /****************************************************************
  151. 串口接收一个字符: 一旦有数据从串口传至CC2530, 则进入中断,将接收到的数据赋值给变量temp.
  152. ****************************************************************/
  153. #pragma vector = URX0_VECTOR
  154. __interrupt void UART0_ISR(void)
  155. {
  156. URX0IF = 0; // 清中断标志
  157. temp = U0DBUF;
 
 


因为硬件不够只做了车的前进,和控制LED小灯。。。。。
看效果:


三秒后。。。。

配对成功后。。。。


我自造的小车。。。。。








写的有点乱。给你们源代码  

android端:http://download.csdn.net/detail/csdnhejingzhou/9413347
Zigbee端:http://download.csdn.net/detail/csdnhejingzhou/9413322
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/225325
推荐阅读
相关标签
  

闽ICP备14008679号