1、蓝牙模块:HC-05(ZS-040)
2、Arduino 代码:
#define BTSerial Serial3 #define DEBUGSerial Serial #define LED_R 2 #define LED_G 3 #define LED_B 4 #define LED_ON LOW #define LED_OFF HIGH const unsigned int BTRxBufferLength = 100; char BTRxBuffer[BTRxBufferLength]; unsigned int BTBufferCount = 0; void setup() //初始化内容 { pinMode(LED_R, OUTPUT); pinMode(LED_G, OUTPUT); pinMode(LED_B, OUTPUT); digitalWrite(LED_R, LED_OFF); digitalWrite(LED_G, LED_OFF); digitalWrite(LED_B, LED_OFF); BTSerial.begin(9600); // 定义波特率9600 DEBUGSerial.begin(9600); DEBUGSerial.println("http://chanpinxue.cn"); DEBUGSerial.println("Wating..."); } void loop() //主循环 { while (BTSerial.available()) { char buffer = BTSerial.read(); BTRxBuffer[BTBufferCount++] = buffer; if (BTBufferCount == BTRxBufferLength)clrRxBuffer(); DEBUGSerial.write(buffer); // 收到数据则通过Serial输出 } if (strstr(BTRxBuffer, "RON") != NULL) { digitalWrite(LED_R, LED_ON); clrRxBuffer(); } else if (strstr(BTRxBuffer, "ROFF") != NULL) { digitalWrite(LED_R, LED_OFF); clrRxBuffer(); } if (strstr(BTRxBuffer, "GON") != NULL) { digitalWrite(LED_G, LED_ON); clrRxBuffer(); } else if (strstr(BTRxBuffer, "GOFF") != NULL) { digitalWrite(LED_G, LED_OFF); clrRxBuffer(); } if (strstr(BTRxBuffer, "BON") != NULL) { digitalWrite(LED_B, LED_ON); clrRxBuffer(); } else if (strstr(BTRxBuffer, "BOFF") != NULL) { digitalWrite(LED_B, LED_OFF); clrRxBuffer(); } } void clrRxBuffer(void) { memset(BTRxBuffer, 0, BTRxBufferLength); // 清空 BTBufferCount = 0; }
3、Android端:
用蓝牙调试助手,连接蓝牙模块BT04-A(默认工作在 从模式,接收指令)。蓝牙配对密码为1234。
连接成功后,发送RON、GON、BON指令,观看小灯亮灯效果。