使用Arduino和手机蓝牙实现控制LED指示灯
一、所需材料
● Arduino UNO开发板
● HC-05蓝牙模块
● LED指示灯
● Arduino蓝牙控制器
● 面包板
● 连接导线
二、实物连接图
Android手机蓝牙软件截图
三、关键代码
1、根据串口接收的信号开关灯
if (state == '0') {
digitalWrite(ledPin, LOW); // Turn LED OFF
Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
state = 0;
}
else if (state == '1') {
digitalWrite(ledPin, HIGH);
Serial.println("LED: ON");;
state = 0;
}
四、效果展示图
五、完整源码
#define ledPin 7
int state = 0;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(38400); // Default communication rate of the Bluetooth module
}
void loop() {
if(Serial.available() > 0){ // Checks whether data is comming from the serial port
state = Serial.read(); // Reads the data from the serial port
}
if (state == '0') {
digitalWrite(ledPin, LOW); // Turn LED OFF
Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
state = 0;
}
else if (state == '1') {
digitalWrite(ledPin, HIGH);
Serial.println("LED: ON");;
state = 0;
}
}