通过应用程序通过Android手机中的micro usb向arduino发送指令

时间:2013-12-26 08:14:33

标签: android bluetooth usb arduino

我想通过微型USB端口通过Android应用程序向Arduino发送指令。 例如,点击应用程序中的按钮时,应该发光连接到Arduino的连接器,连接应该通过Android手机上的微型USB端口完成。我使用蓝牙连接做了同样的事情。我该怎么办呢?或者代码中的变化应该是什么?

通过蓝牙:

package com.example.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

  int red_count=0;
  int yellow_count=0;
  int green_count=0;
  int white_count=0;
  private static final String TAG = "bluetooth2";

  Button red_button,yellow_button,green_button,white_button,reset_button;
  Handler h;

  final int RECIEVE_MESSAGE = 1;        // Status  for Handler
  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket = null;
  private StringBuilder sb = new StringBuilder();
  private ConnectedThread mConnectedThread;

  // SPP UUID service
  private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // MAC-address of Bluetooth module (you must edit this line)
  private static String address = "20:13:01:18:05:08";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    red_button = (Button) findViewById(R.id.red_button);    
    yellow_button = (Button) findViewById(R.id.yellow_button);
    green_button = (Button) findViewById(R.id.green_button);
    white_button = (Button) findViewById(R.id.white_button);
    reset_button = (Button) findViewById(R.id.reset_button);

    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case RECIEVE_MESSAGE:                                                   // if receive massage
                byte[] readBuf = (byte[]) msg.obj;
                String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                sb.append(strIncom);                                                // append string
                int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                if (endOfLineIndex > 0) {                                           // if end-of-line,
                    sb.delete(0, sb.length());                                      // and clear
                    red_button.setEnabled(true);
                    yellow_button.setEnabled(true);
                    green_button.setEnabled(true);
                    white_button.setEnabled(true);
                }
                //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                break;
            }
        };
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();

    red_button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
          red_count++;
          yellow_count=0;
          green_count=0;
          white_count=0;
          red_button.setText(""+red_count);
          yellow_button.setText("");
          green_button.setText("");
          white_button.setText(""); 
          mConnectedThread.write("1");  // Send "1" via Bluetooth
      }
    });

    yellow_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          yellow_count++;
          red_count=0;
          green_count=0;
          white_count=0;
          yellow_button.setText(""+yellow_count);
          red_button.setText("");
          green_button.setText("");
          white_button.setText("");
          mConnectedThread.write("2");  // Send "2" via Bluetooth
        }
      });

    green_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          green_count++;
          red_count=0;
          yellow_count=0;
          white_count=0;
          green_button.setText(""+green_count);
          red_button.setText("");
          yellow_button.setText("");
          white_button.setText("");
          mConnectedThread.write("3");  // Send "3" via Bluetooth
        }
      });

    white_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          white_count++;
          red_count=0;
          green_count=0;
          yellow_count=0;
          white_button.setText(""+white_count);
          red_button.setText("");
          green_button.setText("");
          yellow_button.setText("");
          mConnectedThread.write("4");  // Send "4" via Bluetooth
        }
      });

    reset_button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          white_count=0;
          red_count=0;
          green_count=0;
          yellow_count=0;
          white_button.setText("");
          red_button.setText("");
          green_button.setText("");
          yellow_button.setText("");
          mConnectedThread.write("0");  // Send "0" via Bluetooth
        }
      });
  }

  private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
      if(Build.VERSION.SDK_INT >= 10){
          try {
              final Method  m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
              return (BluetoothSocket) m.invoke(device, MY_UUID);
          } catch (SecurityException e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        } catch (NoSuchMethodException e) {
        Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        } catch (IllegalArgumentException e) {
        Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        } catch (IllegalAccessException e) {
        Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        } catch (InvocationTargetException e) {
        Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
      }
      return  device.createRfcommSocketToServiceRecord(MY_UUID);
  }

  @Override
  public void onResume() {
    super.onResume();

    Log.d(TAG, "...onResume - try connect...");

    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    /*try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }*/

    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();

    // Establish the connection.  This will block until it connects.
    Log.d(TAG, "...Connecting...");
    try {
      btSocket.connect();
      Log.d(TAG, "....Connection ok...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }

    // Create a data stream so we can talk to server.
    Log.d(TAG, "...Create Socket...");

    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();
  }

  @Override
  public void onPause() {
    super.onPause();

    Log.d(TAG, "...In onPause()...");

    try     {
      btSocket.close();
    } catch (IOException e2) {
      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
  }

  private void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on
    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) { 
      errorExit("Fatal Error", "Bluetooth not support");
    } else {
      if (btAdapter.isEnabled()) {
        Log.d(TAG, "...Bluetooth ON...");
      } else {
        //Prompt user to turn on Bluetooth
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
      }
    }
  }

  private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
  }

  private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(String message) {
            Log.d(TAG, "...Data to send: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.d(TAG, "...Error data send: " + e.getMessage() + "...");     
              }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,首先我对adruino编码一无所知,但为了与usb设备进行通信,android使用USB Host Api,转到link。这里有一个教程可能帮助Android与Adruino接口,  how to communicate between the Arduino Uno and your computer using plain USB bulk and control transfers 希望这有帮助