示例#1
0
  // initializes the usb connection to the arduino
  // returns the the status to be displayed on the GUI
  public static String start(Context context) {
    Log.i(TAG, "Starting ArduinoController");

    // set up usb manager
    if (usbManager == null) usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

    // get all available usb drivers
    Log.i(TAG, "Listing Drivers");
    SystemClock.sleep(1000);
    List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
    if (drivers.isEmpty()) {
      Log.i(TAG, "No drivers found!");
      return "No drivers found!";
    }

    // look for a supported usb driver
    Log.i(TAG, "Drivers found: " + drivers.toString());
    arduinoPort = drivers.get(0).getPorts().get(0); // assume first one is the arduino

    if (arduinoPort == null) {
      Log.i(TAG, "Did not find arduino device.");
      return "Arduino Not Found!";
    }

    // open the usb device
    UsbDevice device = arduinoPort.getDriver().getDevice();
    Log.i(TAG, "Connected to productID: " + device.getVendorId());
    UsbDeviceConnection connection = usbManager.openDevice(device);
    if (connection == null) {
      Log.i(TAG, "Could not open device");
      return "Opening device failed!";
    }

    // open usb connection and set parity and baud rate
    try {
      arduinoPort.open(connection);
      // set to send over 8 bits
      arduinoPort.setParameters(
          9600, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
    } catch (IOException e) {
      String result = "Error opening device: " + e.getMessage();
      Log.i(TAG, result);
      try {
        arduinoPort.close();
      } catch (IOException e2) {
        // Ignore
      }
      return result;
    }

    onDeviceStateChange(); // Restart the IO manager
    return "Connected to: " + arduinoPort.getClass().getSimpleName();
  }
示例#2
0
 public static void pause() {
   if (arduinoPort != null) {
     try {
       arduinoPort.close();
     } catch (IOException e) {
       // Ignore.
     }
     arduinoPort = null;
   }
 }