Arduino 使用入門 建國科技大學資管系饒瑞佶 2013/12 V1 2016/7 V2
何謂 Arduino? 義大利 Italy 設計者 Massimo Banzi David Cuartielles Tom Igoe Gianluca Martino David Mellis. 2005.10.1 第一批 快速開發 prototype: artists designers hobbyists OPEN SOURCE 軟體 + 硬體 + 社群
Arduino 架構 _ 軟體 _OPEN 魅力 開放 IDE 軟體原始碼, 可針對底層做修改 相同軟體平台, 透過 OPEN, 快速累積應用範例 玩家 廠商提供多元函式庫
Arduino https://www.arduino.cc/
Arduino 架構 _ 硬體 數位 I/O 腳 PWM 腳 類比輸入腳 供電系統 電源輸出 數位 I/O 腳位 :P0~P13 6 組 PWM 輸出 雙供電系統 10Bit 解析度 類比訊號輸入 三種電源輸出供應 Vin 5V 3.3V
Arduino 架構 _ 硬體 _OPEN 魅力 Arduino 不生產周邊硬體 不綁死 周邊裝置價格平實 周邊裝置搭配 arudino 腳位開發 硬體電路開放, 可自行製作與開發 硬體資源說明文件多 Arduino.cc/playground
DIY Arduino
Freeduino 系列 Ardupilot Boarduino Seeeduino Relayduino Openlog brasuino Fio
擴充 Shield MP3 播放板 SD 卡模組 WIFI 模組 GPRS 模組 AV 端子顯示模組 COLOR LCD 模組 CAN BUS 模組 RFID 模組 MIDI 訊號模組
iarduino
擴充板 shield
下載 IDE http://arduino.cc/en/main/software/ 此處使用 1.6.9 版 (Windows zip)
安裝驅動程式 解壓縮後內的 drivers 目錄
安裝驅動程式 初次使用 usb 連接 Arduino 裝置管理員並不認識 Arduino
更新驅動程式 安裝驅動程式
切換至 drivers 目錄 安裝驅動程式
安裝驅動程式
驅動程式安裝完成
Arduino IDE
啟動 Arduino IDE
載入範例程式 Blink
Blink 開啟畫面
功能選項區 程式編輯區 編譯訊息區錯誤訊息區
主要快速功能選項
開始使用 IDE 步驟 1 選擇對應的硬體設備型號
開始使用 IDE 步驟 2 選擇連結的通訊埠 (port) 位置
結果
驗證 Verify
執行 Blink Upload
Arduino 版上的黃燈持續閃爍 腳位 13
程式說明 程式碼解說
只會執行 1 次啟動或 reset 時 定義使用腳位 設定腳位腳色為 OUTPUT
重複執行 開 LED 關 LED
LED on board 目前 DO pin 13 對應到 Green LED DO pin 10 對應到 Red LED DO pin 9 對應到 Blue LED
光敏電阻範例
硬體設備 擴充板上內建有光敏電阻 其中一支腳接地, 另一支接在 BZ+ 光敏電阻
透過 Analog 讀取訊號 將 BZ+ 接至 A0~A5 其中一個點 ( 這裡是 A2) A2 A0 ~ A5
Digital Output D0 ~ D13 Analog Input A0 ~ A5
光敏電阻 將光訊號轉換成電阻訊號輸出 光越強, 則電阻越小 光越弱, 則電阻越大 透過電阻值判斷目前光量大小
程式
If error 大小寫是有差的!
結果 光越來越暗因為電阻值越來越大 如果看到亂碼, 記得調整 baudrate
DS18B20 溫度 SENSOR
硬體設備 DS18B20 Vdd 接 5V DQ 接到 Digital Input 7 溫度感測器
函示庫 需要 OneWire 與 DallasTemperature 兩個函示庫 函式庫需要放到 Arduino 內的 libraries 目錄內
下載函式庫 http://appsduino.com/360392830420998201 39.html
程式 // 載入函式庫 #include <OneWire.h> #include <DallasTemperature.h> // Data wire is plugged into pin 7 on the Arduino #define ONE_WIRE_BUS 7 // Setup a onewire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire onewire(one_wire_bus); // Pass our onewire reference to Dallas Temperature. DallasTemperature sensors(&onewire);
程式 void setup(void) { // start serial port Serial.begin(9600); Serial.println("Dallas Temperature IC Control Library Demo"); } // Start up the library sensors.begin();
程式 void loop(void) { // call sensors.requesttemperatures() to issue a global temperature // request to all devices on the bus Serial.print(" Requesting temperatures..."); sensors.requesttemperatures(); // Send the command to get temperatures Serial.println("DONE"); } Serial.print("Temperature for Device 1 is: "); Serial.print(sensors.getTempCByIndex(0)); // Why "byindex"? // You can have more than one IC on the same bus. // 0 refers to the first IC on the wire
結果
Arduino + BT + Android 非 BLE
BT Adapter
連接 BT Adapter 與 Arduino GND- GND 5V- 5V RX(Bluetooth) TX (Arduino) TX(Bluetooth) RX(Arduino) 閃爍
設定 Arduino 名稱 這個要先設定 為了之後配對選擇用
設定 Arduino 名稱 int LedGreen=13; void setup() { // put your setup code here, to run once: pinmode(ledgreen,output); digitalwrite(ledgreen,low); Serial.begin(57600); delay(1000); Serial.write("AT+NAMECTU"); // 設定名稱,CTU 改成你要的名稱 while(!serial.available()); Serial.read(); digitalwrite(ledgreen,high); // 如果連上, 則 LED 長亮 }
記得要先配對
測試 直接使用手機的藍芽掃描 或 使用 Blue Term
與 BT 通訊
動作 從 Arduino 每隔一秒回傳累加數字回到 Android 手機 Android 手機輸入資料後傳到 Arduino, Arduino 收到後會回覆收到資料
Arduino code #define BUFFERSIZE 127 uint8_t inbuffer[buffersize]; int inlength; // length of data in the buffer int numloop = 0; // number of times we looped int ledpin = 13; void setup() { Serial.begin(57600); pinmode(ledpin, OUTPUT); }
Arduino code void loop() { // read string if available if (Serial.available()) { inlength = 0; while (Serial.available()) { inbuffer[ inlength] = Serial.read(); inlength++; if (inlength >= BUFFERSIZE) break; } Serial.print("Arduino received: "); Serial.write(inBuffer,inLength); Serial.println(); } // blink the led and send a number digitalwrite(ledpin, HIGH); // set the LED on delay(100); // wait a bit Serial.println(numLoop); digitalwrite(ledpin, LOW); // set the LED off delay(1000); numloop++; }
測試 使用 Blue Term 如果有連上,Arduino 上的 BT 設備紅燈會停止閃爍
使用 Android 連接 直接使用 Android 內建的 BluetoothChat 範例就可以
唯一需要修改 BluetoothChatService.java 內的 UUID 改成 UUID for Serial port service https://kunyichen.wordpress.com/2007/06/08/bluetooth-service-uuid-list/
result
result 資料從 ARDUINO 傳到手機 停止閃爍
result Arduino 回傳收到 傳資料給 Arduino
jquery 連結 Arduino BT 整合 SQLite
Android 端
Android 端 main.java public class Main extends Activity { FromArduino mybt; // 取得藍芽服務 } @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); WebView mwebview=new WebView(this); mwebview.getsettings().setjavascriptenabled(true); mybt=new FromArduino(this); //mwebview.addjavascriptinterface(new FromArduino(this), "myjsinterface"); mwebview.addjavascriptinterface(mybt, "myjsinterface"); mwebview.loadurl("file:///android_asset/www/index.html"); setcontentview(mwebview); } @Override public void onbackpressed() { mybt.closebt(); // 關閉藍芽 finish(); // 關閉本程式 super.onbackpressed(); } @Override protected void onpause() { mybt.closebt(); // 關閉藍芽 finish(); // 關閉本程式 super.onpause(); }
Android 端 -FromArduino.java
Android 端 -FromArduino.java // 接收透過 BT 來自 Arduino 的訊號 public class FromArduino { Context mcontext; // Local Bluetooth adapter private BluetoothAdapter mbluetoothadapter = null; // Member object for the chat services private BluetoothChatService mchatservice = null; public static final int MESSAGE_STATE_CHANGE = 1; public static final int MESSAGE_DEVICE_NAME = 4; // Key names received from the BluetoothChatService Handler public static final String DEVICE_NAME = "device_name"; public static final int MESSAGE_TOAST = 5; public static final String TOAST = "toast"; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; // String buffer for outgoing messages private StringBuffer moutstringbuffer; // Name of the connected device private String mconnecteddevicename = null; private String readmessage; private String BTState=""; // Arduino BT MAC private String BTMAC=""; BluetoothDevice device;
Android 端 -FromArduino.java public FromArduino(Context c){ mcontext=c; // Get local Bluetooth adapter mbluetoothadapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported if (mbluetoothadapter == null) { return; } // If BT is not on, request that it be enabled. // setupchat() will then be called during onactivityresult if (!mbluetoothadapter.isenabled()) { //Intent enableintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //startactivityforresult(enableintent, REQUEST_ENABLE_BT); // Otherwise, setup the chat session } else { if (mchatservice == null) setupchat(); } }
Android 端 -FromArduino.java private void setupchat() { // Initialize the BluetoothChatService to perform bluetooth connections mchatservice = new BluetoothChatService(this, mhandler); // Initialize the buffer for outgoing messages moutstringbuffer = new StringBuffer(""); // Get the BLuetoothDevice object //BluetoothDevice device = mbluetoothadapter.getremotedevice("00:13:01:11:32:12"); if(btmac==""){ BTMAC="00:13:01:11:32:11";} device = mbluetoothadapter.getremotedevice(btmac); // Attempt to connect to the device mchatservice.connect(device); }
Android 端 -FromArduino.java // The Handler that gets information back from the BluetoothChatService private final Handler mhandler = new Handler() { @Override public void handlemessage(message msg) { switch (msg.what) { case MESSAGE_STATE_CHANGE: switch (msg.arg1) { case BluetoothChatService.STATE_CONNECTED: BTState=" 已連線 "; break; case BluetoothChatService.STATE_CONNECTING: BTState=" 連線中..."; break; case BluetoothChatService.STATE_LISTEN: case BluetoothChatService.STATE_NONE: break; } break; case MESSAGE_WRITE: byte[] writebuf = (byte[]) msg.obj; // construct a string from the buffer String writemessage = new String(writeBuf); break; case MESSAGE_READ: byte[] readbuf = (byte[]) msg.obj; // construct a string from the valid bytes in the buffer readmessage = new String(readBuf, 0, msg.arg1); break; case MESSAGE_DEVICE_NAME: // save the connected device's name mconnecteddevicename = msg.getdata().getstring(device_name); break; case MESSAGE_TOAST: break; } } };
Android 端 -FromArduino.java // return data public String setvalfromjava(){ return readmessage; // 數據 } public String setbtstate(){ return BTState; // 藍芽狀態 } //Javascript call JAV public void getsomestring(string macaddress){ //Toast.makeText(mcontext, "MAC 設定成功 ", Toast.LENGTH_LONG).show(); device = mbluetoothadapter.getremotedevice(macaddress); mchatservice.connect(device); } // 關閉 BT public void CloseBT(){ mchatservice.stop(); }
Android 端 -BluetoothChatService.java 原 BluetoothChat 範例內之 Service 需要修改 //private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Android 端 -index.html <html> <head> <title>phonegap</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"/> <script src="jquery-1.9.1.min.js"></script> <link rel="stylesheet" href="jquery.mobile-1.3.0.min.css"> <script src="jquery.mobile-1.3.0.min.js"></script> <script> $(document).ready(function(){ // 連線 $('#connecttoarduino').click(function(){ // 設定 Arduino MAC window.myjsinterface.getsomestring($('#arduinomac').val()); $('#showstate').html(' 連線中...'); var mycounter =setinterval(function() { if($('#showstate').text()!=" 已連線 "){ window.myjsinterface.getsomestring($('#arduinomac').val()); }else{ clearinterval(mycounter); // 暫停 timer } }, 5000); });
Android 端 -index.html // 斷線 $('#offarduino').click(function(){ // 設定 Arduino MAC="" window.myjsinterface.getsomestring("99:99:99:99:99:99"); }); // 每秒讀取一次連結狀態 setinterval(function() { $('#showstate').html(window.myjsinterface.setbtstate()); }, 1000); // 每秒讀取一次訊號 setinterval(function() { $('#showval').html(" 數據 =" + window.myjsinterface.setvalfromjava()); }, 1000); }); </script> </head>
Android 端 -index.html <body> <div data-role="page"> <div data-role="header"> <h1>android-arduino</h1> </div> <div data-role="content"> <input type=text id="arduinomac" value="00:13:01:11:32:12"><input type=button id="connecttoarduino" value=" 連線 "> <input type=button id="offarduino" value=" 斷線 "> <div id="showstate"> 未連線...</div> <div id="showval"></div> </div> <div data-role="footer"> <h1>2013/12/10</h1> </div> </div> </body> </html>
Android 端 -AndroidManifest.xml <uses-permission android:name="android.permission.bluetoo TH_ADMIN" /> <uses-permission android:name="android.permission.bluetoo TH" />