//Android畫面,控制按鈕的開與關畫面,並呼叫sendLedSwitchCommand()方法 OnCheckedChangeListenertoggleButtonCheckedListener = newOnCheckedChangeListener() { public void onCheckedChanged(CompoundButtonbuttonView, boolean isChecked) { if (buttonView.getId() == R.id.led_toggle_button){ new AsyncTask<Boolean, Void, Void>() { protected Void doInBackground(Boolean... params){ sendLedSwitchCommand(TARGET_PIN_2, params[0]); return null; } }.execute(isChecked); } } }; //開啟android與USB連接 private void openAccessory(UsbAccessoryaccessory) { mFileDescriptor = mUsbManager.openAccessory(accessory); if (mFileDescriptor != null) { mAccessory = accessory; FileDescriptor fd = mFileDescriptor.getFileDescriptor(); mInputStream = new FileInputStream(fd); mOutputStream = new FileOutputStream(fd); Log.d(TAG, "accessory opened"); } else { Log.d(TAG, "accessory open fail"); } } //關閉android與USB連接 private void closeAccessory() { ……………… } //控制LED燈的亮與暗,VALUE_ON為LED亮, VALUE_ON為LED暗 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程式介紹 /* 資料傳輸速度可分為: 300, 600, 1200, 2400, 4800, 9600, 14400,19200, 28800, 38400, 57600, or 115200. rcvmsg 是用來接收並發送訊息 rcvmsg[0] command byte 命令字元 rcvmsg[1] target byte 目標字元 rcvmsg[2] value byte constant 接收值 (VALUE_ON為LED亮, VALUE_ON為LED暗) */ …….. #define PIN 2 //正極連接PIN2 …….. byte rcvmsg[3]; void setup() { //初始設定區塊 Serial.begin(19200); // 設定資料傳輸速度 acc.powerOn(); //使單晶片開始工作 pinMode(PIN, OUTPUT); //設定PIN腳為輸出 }
void loop() { //重複執行區塊 if(acc.isConnected()) { //讀取所接收到的值 intlen = acc.read(rcvmsg, sizeof(rcvmsg), 1); if(len > 0) { if(rcvmsg[0] == COMMAND_LED) { //接收到一個byte的值的程序 if(rcvmsg[1] == TARGET_PIN_2){ //取得開關狀態 byte value = rcvmsg[2]; //根據開關狀態來設定PIN的輸出 if(value == VALUE_ON) { digitalWrite(PIN, HIGH); //5V } else if(value == VALUE_OFF) { digitalWrite(PIN, LOW); //0V ……. 連接方式 實際畫面 |
share >