Android ADK USB 控制 Arduino LED 开关

好吧,废话不多,开始吧!

这次用的是Arduino MEGA ADK

Android完整代码:AALed

个人认为较重要的地方:

public void sendLedSwitchCommand(byte target,Boolean isSwitchedOn){

     byte[] buffer = new byte[3];

     buffer[0] = COMMAND_LED;

     buffer[1] = target;

     if (isSwitchedOn) {

         buffer[2] = VALUE_ON;

     }else {

     buffer[2] = VALUE_OFF;

 }

     if(mOutputStream != null){

     try{

         mOutputStream.write(buffer);

     }catch(IOException e){

         Log.e(TAG“write failed", e);

}

}

}

这个是把开灯和关灯的指令传给Arduino

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver(){

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

String action = intent.getAction();

if(ACTION_USB_PERMISSION.equals(action)){

synchronized (this) {

UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTEDfalse)){

openAccessory(accessory);

}else{

Log.d(TAG“permission denied for accessory" + accessory);

}

mPermissionRequestPending = false;

}

}else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {

UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

if(accessory != null && accessory.equals(mAccessory)){

closeAccessory();

}

}

}

};

这个就是接收/连接USB

有个地方非常重要:

一.在res档里创建一个xml档(accessory_filter.xml)

二.在AndroidManifest里的</activity>上面 加入

  <intent-filter>

<actionandroid:name=“android.hardware.usb.action.USB_ACCESSORY_ATTACHED"/>

</intent-filter>

<meta-dataandroid:name=“android.hardware.usb.action.USB_ACCESSORY_ATTACHED"

android:resource=“@xml/accessory_filter"/>

在</activity>后加入:

        <uses-libraryandroid:name=“com.android.future.usb.accessory"/>

之后就是Arduino的

#include <Max3421e.h>

#include <Usb.h>

#include <AndroidAccessory.h>

#define COMMAND_LED 0×2

#define TARGET_PIN_2 0×2

#define VALUE_ON 0×1

#define VALUE_OFF 0×0

#define PIN 2

AndroidAccessory acc(“Manufacturer",

“Model",

“Description",

“Version",

“URL",

“Serial");

byte rcvmsg[3];

void setup(){

Serial.begin(9600);

acc.powerOn();

pinMode(PIN, OUTPUT);

}

void loop(){

if(acc.isConnected()){

int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);

if(len > 0){

if(rcvmsg[0] == COMMAND_LED){

if(rcvmsg[1] == TARGET_PIN_2){

byte value = rcvmsg[2];

if(value == VALUE_ON){

digitalWrite(PIN, HIGH);

}else if(value == VALUE_OFF){

digitalWrite(PIN, LOW);

}

}

}

}

}

}

编译前请把board 转成 ArduinoMega2560/Mega ADK

ArduinoADK环境搭配看这:http://cartonsbase.twgg.org/arduino-adk-building/zh-cn/

你可能感兴趣的:(Android ADK USB 控制 Arduino LED 开关)