Mobile phone and Bluetooth communication experiment

Mobile phone and Bluetooth communication experiment

Experimental phenomena

Use android phone to control the switch of relay

Theoretical study

The experiment uses the BT-HC05 Bluetooth module, which is a master and slave, and can be set as a master or a slave by software. (Delivery default machine, baud rate 9600, PIN password 1234), and use the slave mode to connect to the mobile phone without additional settings.
The module defaults to the serial port transparent transmission mode, as long as the cable is connected, it can be used as a wireless serial port.
The Bluetooth serial port assistant needs to be installed on the mobile phone, select the implementation mode

Schematic diagram

Insert picture description here

Code writing

arduino UNO R3 board code:

//串口中断实验
//arduino UNO R3板子代码
String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
void setup() {
    
    
  // put your setup code here, to run once:
  Serial.begin(9600);//初始化串口设置波特率
  pinMode(13, OUTPUT);
}
void loop() {
    
    
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
void serialEvent() {
    
    
  while (Serial.available()) {
    
    
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
    
    
      stringComplete = true;
    }
    if (stringComplete) {
    
    
      Serial.println(inputString);
      // clear the string:
      inputString = "";
      stringComplete = false;
    }
  }
}

arduino Leonardo board code:

//串口中断实验
//arduino Leonardo板子代码
String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
void setup() {
    
    
  // put your setup code here, to run once:
  Serial1.begin(9600);//初始化串口设置波特率
  pinMode(13, OUTPUT);
}
void loop() {
    
    
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
void serialEvent1() {
    
    
  while (Serial1.available()) {
    
    
    // get the new byte:
    char inChar = (char)Serial1.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
    
    
      stringComplete = true;
    }
    if (stringComplete) {
    
    
      Serial1.println(inputString);
      // clear the string:
      inputString = "";
      stringComplete = false;
    }
  }
}

Guess you like

Origin blog.csdn.net/qq_45671732/article/details/109526652
Recommended