2. Arduino code
// BT data commmuncation LCD dosplay and Arduino LED control + Servo control
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // 使用整合I2C的LCD2004顯示
#include <VarSpeedServo.h> //New servo lib. for speed control replace arduino default Servo.h
// the maximum received command length from an Android system (over the bluetooth)
#define MAX_BTCMDLEN 128
SoftwareSerial BTSerial(9,10); // Arduino RX/TX
LiquidCrystal_I2C lcd(0x27,20,4); // 使用整合I2C的LCD2004顯示
byte cmd[MAX_BTCMDLEN]; // received 128 bytes from an Android system
int len = 0; // received command length
int ledPin = 11; // for external LED light on
VarSpeedServo myservoa; // create servo object a
VarSpeedServo myservob; // create servo object b
void setup() {
Serial.begin(9600); // Arduino起始鮑率:9600
BTSerial.begin(9600); // HC-06 出廠的鮑率:每個藍牙晶片的鮑率都不太一樣,請務必確認
pinMode(ledPin, OUTPUT);
lcd.init(); // 初始化LCD2004
lcd.backlight();
}
void loop() {
char str[MAX_BTCMDLEN];
int insize, ii;
int tick=0;
int i;
lcd.setCursor(4,0);
lcd.print("Hello Jason");
lcd.setCursor(5,1);
lcd.print("Good day!");
lcd.scrollDisplayLeft(); //往左捲動
delay(400); //延遲0.4秒 rotation speed control
while ( tick<MAX_BTCMDLEN ) { // 因為包率同為9600, Android送過來的字元可能被切成數份
if ( (insize=(BTSerial.available()))>0 ){ // 讀取藍牙訊息,insize=輸入字串數
for ( ii=0; ii<insize; ii++ )
cmd[(len++)%MAX_BTCMDLEN]=char(BTSerial.read());
}
else
tick++;
}
if ( len ) { // 用LCD2004顯示從Android手機傳過來的訊息
cmd[(len++)%MAX_BTCMDLEN]=0; // clear buffer
sprintf(str,"%s",cmd);
lcd.clear();
Serial.println(str); // 將對串列埠的輸出改為對LCD2004輸出
if (len==2) //if BT input just 1 char, IO pin status command or check
switch (str[0])
{
case '9':
lcd.print("Servo-b rotate 0");
myservob.attach(6); // 連接數位腳位10,伺服馬達的PWM訊號線
myservob.write(0,50,true); // 使用write,傳入角度,轉到90度
led_off();
break;
case '8':
lcd.print("Servo-b rotate 90");
myservob.attach(6); // 連接數位腳位10,伺服馬達的PWM訊號線
myservob.write(90,50,true); // 使用write,傳入角度,轉到90度
led_off();
break;
case '1':
lcd.print("Servo-a rotate 180");
myservoa.attach(5); // 連接數位腳位10,伺服馬達的PWM訊號線
myservoa.write(180,50,true); // 使用write,傳入角度,轉到180度
led_on();
break;
case '0':
lcd.print("Servo-a rotate 0");
myservoa.attach(5); // 連接數位腳位10,伺服馬達的PWM訊號線
myservoa.write(0,50,true); // 使用write,傳入角度,轉到0度
led_on();
break;
case '2':
lcd.print("Servo-a rotate 90");
myservoa.attach(5); // 連接數位腳位10,伺服馬達的PWM訊號線
myservoa.write(90,50,true); // 使用write,傳入角度,轉到90度
led_on();
break;
}
else
{
lcd.clear();
lcd.print(str);
cmd[0] = '\0';
}
delay(1000);
lcd.clear();
}
len = 0;
}
void led_on()
{
for (int a=0;a<=255;a++)
analogWrite(ledPin,a);
delay(5); // sets the LED on
}
void led_off()
{
for (int a=255;a>=0;a--)
analogWrite(ledPin,a);
delay(5); // sets the LED on
}
4. APP MMI
5. Note
Android powered by PC USB power is not good enough and will cause
Servo malfunction sometimes. It 's better to powered by adpotor for
abundant power source.
沒有留言:
張貼留言