2. Arduino Code
// BT data commmuncation LCD dosplay and pin-11 LED control
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h> // 使用整合I2C的LCD2004顯示
// 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
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秒
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");
led_off();
break;
case '8':
lcd.print("Servo-b rotate 90");
led_off();
break;
case '1':
lcd.print("Servo-a rotate 180");
led_on();
break;
case '0':
lcd.print("Servo-a rotate 0");
led_on();
break;
case '2':
lcd.print("Servo-a rotate 90");
led_on();
break;
}
else
{
lcd.clear();
lcd.print(str); //Display Android input text
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
}
3.Android APP code
4. APP MMI
沒有留言:
張貼留言