Advertisement
Guest User

Untitled

a guest
Mar 29th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.65 KB | None | 0 0
  1. package com.example.ibm.bluetooth_3;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.lang.reflect.Method;
  7. import java.util.UUID;
  8. import com.example.ibm.bluetooth_3.R;
  9.  
  10. import android.app.Activity;
  11. import android.bluetooth.BluetoothAdapter;
  12. import android.bluetooth.BluetoothDevice;
  13. import android.bluetooth.BluetoothSocket;
  14. import android.content.Intent;
  15. import android.os.Build;
  16. import android.os.Bundle;
  17. import android.os.Handler;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.view.View.OnClickListener;
  21. import android.widget.Button;
  22. import android.widget.EditText;
  23. import android.widget.TextView;
  24. import android.widget.Toast;
  25.  
  26. public class MainActivity extends Activity {
  27. private static final String TAG = "bluetooth2";
  28.  
  29. Button btnOn, btnOff;
  30. TextView txtArduino;
  31. Handler h;
  32.  
  33. final int RECIEVE_MESSAGE = 1; // Status for Handler
  34. private BluetoothAdapter btAdapter = null;
  35. private BluetoothSocket btSocket = null;
  36. private StringBuilder sb = new StringBuilder();
  37.  
  38. private ConnectedThread mConnectedThread;
  39.  
  40. // SPP UUID service
  41. private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  42.  
  43. // MAC-address of Bluetooth module (you must edit this line)
  44. private static String address = "00:06:66:68:30:D6";
  45.  
  46. /** Called when the activity is first created. */
  47. @Override
  48. public void onCreate(Bundle savedInstanceState) {
  49. super.onCreate(savedInstanceState);
  50. setContentView(R.layout.activity_main);
  51. btnOn = (Button) findViewById(R.id.btnOn); // button LED ON
  52. btnOff = (Button) findViewById(R.id.btnOff); // button LED OFF
  53. txtArduino = (EditText) findViewById(R.id.txtArduino); // for display the received data from the Arduino
  54. h = new Handler() {
  55. public void handleMessage(android.os.Message msg) {
  56. switch (msg.what) {
  57. case RECIEVE_MESSAGE: // if receive massage
  58. byte[] readBuf = (byte[]) msg.obj;
  59. String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
  60. sb.append(strIncom); // append string
  61. int endOfLineIndex = sb.indexOf("rn"); // determine the end-of-line
  62. if (endOfLineIndex > 0) { // if end-of-line,
  63. String sbprint = sb.substring(0, endOfLineIndex); // extract string
  64. sb.delete(0, sb.length()); // and clear
  65. txtArduino.setText(sbprint); // update TextView
  66. }
  67. //Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
  68. break;
  69. }
  70. };
  71. };
  72.  
  73. btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
  74. checkBTState();
  75.  
  76. btnOn.setOnClickListener(new OnClickListener() {
  77. public void onClick(View v) {
  78. btnOn.setEnabled(true);
  79. mConnectedThread.write("1"); // Send "1" via Bluetooth
  80. //Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
  81. }
  82. });
  83.  
  84. btnOff.setOnClickListener(new OnClickListener() {
  85. public void onClick(View v) {
  86. btnOff.setEnabled(true);
  87. mConnectedThread.write("0"); // Send "0" via Bluetooth
  88. //Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
  89. }
  90. });
  91. }
  92.  
  93. private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  94. if(Build.VERSION.SDK_INT >= 10){
  95. try {
  96. final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
  97. return (BluetoothSocket) m.invoke(device, MY_UUID);
  98. } catch (Exception e) {
  99. Log.e(TAG, "Could not create Insecure RFComm Connection",e);
  100. }
  101. }
  102. return device.createRfcommSocketToServiceRecord(MY_UUID);
  103. }
  104.  
  105. @Override
  106. public void onResume() {
  107. super.onResume();
  108.  
  109. Log.d(TAG, "...onResume - try connect...");
  110.  
  111. // Set up a pointer to the remote node using it's address.
  112. BluetoothDevice device = btAdapter.getRemoteDevice(address);
  113.  
  114. // Two things are needed to make a connection:
  115. // A MAC address, which we got above.
  116. // A Service ID or UUID. In this case we are using the
  117. // UUID for SPP.
  118.  
  119. try {
  120. btSocket = createBluetoothSocket(device);
  121. } catch (IOException e) {
  122. errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  123. }
  124.  
  125. /*try {
  126. btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  127. } catch (IOException e) {
  128. errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
  129. }*/
  130.  
  131. // Discovery is resource intensive. Make sure it isn't going on
  132. // when you attempt to connect and pass your message.
  133. btAdapter.cancelDiscovery();
  134.  
  135. // Establish the connection. This will block until it connects.
  136. Log.d(TAG, "...Connecting...");
  137. try {
  138. btSocket.connect();
  139. Log.d(TAG, "....Connection ok...");
  140. } catch (IOException e) {
  141. try {
  142. btSocket.close();
  143. } catch (IOException e2) {
  144. errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
  145. }
  146. }
  147.  
  148. // Create a data stream so we can talk to server.
  149. Log.d(TAG, "...Create Socket...");
  150.  
  151. mConnectedThread = new ConnectedThread(btSocket);
  152. mConnectedThread.start();
  153. }
  154.  
  155. @Override
  156. public void onPause() {
  157. super.onPause();
  158.  
  159. Log.d(TAG, "...In onPause()...");
  160.  
  161. try {
  162. btSocket.close();
  163. } catch (IOException e2) {
  164. errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
  165. }
  166. }
  167.  
  168. private void checkBTState() {
  169. // Check for Bluetooth support and then check to make sure it is turned on
  170. // Emulator doesn't support Bluetooth and will return null
  171. if(btAdapter==null) {
  172. errorExit("Fatal Error", "Bluetooth not support");
  173. } else {
  174. if (btAdapter.isEnabled()) {
  175. Log.d(TAG, "...Bluetooth ON...");
  176. } else {
  177. //Prompt user to turn on Bluetooth
  178. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  179. startActivityForResult(enableBtIntent, 1);
  180. }
  181. }
  182. }
  183.  
  184. private void errorExit(String title, String message){
  185. Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
  186. finish();
  187. }
  188.  
  189. private class ConnectedThread extends Thread {
  190. private final InputStream mmInStream;
  191. private final OutputStream mmOutStream;
  192.  
  193. public ConnectedThread(BluetoothSocket socket) {
  194. InputStream tmpIn = null;
  195. OutputStream tmpOut = null;
  196.  
  197. // Get the input and output streams, using temp objects because
  198. // member streams are final
  199. try {
  200. tmpIn = socket.getInputStream();
  201. tmpOut = socket.getOutputStream();
  202. } catch (IOException e) { }
  203.  
  204. mmInStream = tmpIn;
  205. mmOutStream = tmpOut;
  206. }
  207.  
  208. public void run() {
  209. byte[] buffer = new byte[1024]; // buffer store for the stream
  210. int bytes; // bytes returned from read()
  211. // Keep listening to the InputStream until an exception occurs
  212. while (true) {
  213. try {
  214. // Read from the InputStream
  215. bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
  216. h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
  217. } catch (IOException e) {
  218. break;
  219. }
  220. }
  221. }
  222.  
  223. /* Call this from the main activity to send data to the remote device */
  224. public void write(String message) {
  225. Log.d(TAG, "...Data to send: " + message + "...");
  226. byte[] msgBuffer = message.getBytes();
  227. try {
  228. mmOutStream.write(msgBuffer);
  229. } catch (IOException e) {
  230. Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
  231. }
  232. }
  233. }
  234. }
  235.  
  236. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  237. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  238. android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  239. android:paddingRight="@dimen/activity_horizontal_margin"
  240. android:paddingTop="@dimen/activity_vertical_margin"
  241. android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
  242. android:focusable="true">
  243.  
  244. <Button
  245. android:layout_width="wrap_content"
  246. android:layout_height="wrap_content"
  247. android:text="On"
  248. android:id="@+id/btnOn"
  249. android:layout_alignParentTop="true"
  250. android:layout_centerHorizontal="true"
  251. android:layout_marginTop="52dp"
  252. android:enabled="true"
  253. android:focusable="true"
  254. android:focusableInTouchMode="true" />
  255.  
  256. <Button
  257. android:layout_width="wrap_content"
  258. android:layout_height="wrap_content"
  259. android:text="Off"
  260. android:id="@+id/btnOff"
  261. android:layout_below="@+id/btnOn"
  262. android:layout_centerHorizontal="true"
  263. android:layout_marginTop="63dp"
  264. android:enabled="true"
  265. android:focusable="true"
  266. android:focusableInTouchMode="true" />
  267.  
  268. <EditText
  269. android:layout_width="wrap_content"
  270. android:layout_height="wrap_content"
  271. android:inputType="number"
  272. android:ems="10"
  273. android:id="@+id/txtArduino"
  274. android:layout_below="@+id/btnOff"
  275. android:layout_centerHorizontal="true"
  276. android:layout_marginTop="65dp" />
  277.  
  278. </RelativeLayout>
  279.  
  280. <?xml version="1.0" encoding="utf-8"?>
  281. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  282. package="com.example.ibm.bluetooth_3" >
  283. <uses-permission android:name="android.permission.BLUETOOTH" />
  284. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  285. <application
  286. android:allowBackup="true"
  287. android:icon="@drawable/ic_launcher"
  288. android:label="@string/app_name"
  289. android:theme="@style/AppTheme" >
  290. <activity
  291. android:name=".MainActivity"
  292. android:label="@string/app_name" >
  293. <intent-filter>
  294. <action android:name="android.intent.action.MAIN" />
  295.  
  296. <category android:name="android.intent.category.LAUNCHER" />
  297. </intent-filter>
  298. </activity>
  299. </application>
  300.  
  301. </manifest>
  302.  
  303. #include <SoftwareSerial.h>
  304. SoftwareSerial mySerial (3, 2);
  305. void setup()
  306. {
  307. Serial.begin (57600);
  308. mySerial.begin (115200);
  309. }
  310.  
  311. void loop()
  312. {
  313. for (int i=0; i < 1000000; i++)
  314. {
  315. mySerial.println (i);
  316. Serial.println (i);
  317. delay (100);
  318. }
  319. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement