對於手機的Android Apps今次是作為初學者的第一個項目。但不枉我在這次印度公幹期間,電腦之外,我都執了幾件零件和書。在印度試好了如何在Android上用藍牙連接Arduino,簡單的按鍵去傳送方向指令(數字),和預備日後作其他用途的顯示和輸入介面。詳細的檔案己經放到下面的dropbox link。
Arduino Sketch: https://dl.dropboxusercontent.com/u/71621110/Blogger/Sketch_CarBT.ino
Android Project: https://dl.dropboxusercontent.com/u/71621110/Blogger/myFirstBluetoothApp.zip
Arduino
首先,Arduino 的Sketch中,令小車移動的指令是連接L298D的4個腳位控制個馬達的正轉反轉和速度。先把向前向後轉左轉右等指令包裝成forward()、backward()、left()、right()、brake()等指令:
int Left_motor_go=8; //左馬達前進(IN1)
int Left_motor_back=9; //左馬達後退(IN2)
int Right_motor_go=10; // 右馬達前進(IN3)
int Right_motor_back=11; // 右馬達後退(IN4)
void forward() // 前進
{
digitalWrite(Right_motor_go,HIGH); // 右馬達前進
digitalWrite(Right_motor_back,LOW);
digitalWrite(Left_motor_go,LOW); // 左馬達前進
digitalWrite(Left_motor_back,HIGH);
analogWrite(Right_motor_go,200);
analogWrite(Right_motor_back,0);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,200);
}
連接藍牙到Arduino時要像以下般連接,藍牙模組會直播接連到板子上的TX,RX 腳位。當Arduino開始"setup()"時除了設定相關腳位的pinMode外,也需設定Serial的通訊。之後的程式上就可以像Serial 通訊般互傳指令。而Serial Rate 要跟自己藍牙模組的Baud Rate 相同,才可以在同一頻率下理解訊息。之前在電腦上搜尋這藍牙時,確定自己用的是HC-05的藍牙組件。HC-05出廠設定是rate=9600,配對密碼1234。
Bluetooth's TX <--> Arduino's RX
Bluetooth's RX <--> Arduino's TX
Bluetooth's GND <--> Arduino's GND
Bluetooth's VCC <--> Arduino's 5V