手机和蓝牙通讯实验

浅浅的花香味﹌ 2022-12-19 08:43 259阅读 0赞

手机和蓝牙通讯实验

实验现象

使用android手机控制继电器的开关

理论学习

实验采用BT-HC05蓝牙模块,该模块主从一体,可以软件设置是主机还是从机。(发货默认机,波特率9600,PIN密码1234),和手机连接使用从机模式不需要额外的设置
该模块默认就是串口的透传模式,只要连接好线就当无线串口用就可以了
手机上需要安装蓝牙串口助手,选择实施模式

原理图

在这里插入图片描述

代码编写

arduino UNO R3板子代码:

  1. //串口中断实验
  2. //arduino UNO R3板子代码
  3. String inputString = ""; // a String to hold incoming data
  4. bool stringComplete = false; // whether the string is complete
  5. void setup() {
  6. // put your setup code here, to run once:
  7. Serial.begin(9600);//初始化串口设置波特率
  8. pinMode(13, OUTPUT);
  9. }
  10. void loop() {
  11. digitalWrite(13, HIGH);
  12. delay(1000);
  13. digitalWrite(13, LOW);
  14. delay(1000);
  15. }
  16. void serialEvent() {
  17. while (Serial.available()) {
  18. // get the new byte:
  19. char inChar = (char)Serial.read();
  20. // add it to the inputString:
  21. inputString += inChar;
  22. // if the incoming character is a newline, set a flag so the main loop can
  23. // do something about it:
  24. if (inChar == '\n') {
  25. stringComplete = true;
  26. }
  27. if (stringComplete) {
  28. Serial.println(inputString);
  29. // clear the string:
  30. inputString = "";
  31. stringComplete = false;
  32. }
  33. }
  34. }

arduino Leonardo板子代码:

  1. //串口中断实验
  2. //arduino Leonardo板子代码
  3. String inputString = ""; // a String to hold incoming data
  4. bool stringComplete = false; // whether the string is complete
  5. void setup() {
  6. // put your setup code here, to run once:
  7. Serial1.begin(9600);//初始化串口设置波特率
  8. pinMode(13, OUTPUT);
  9. }
  10. void loop() {
  11. digitalWrite(13, HIGH);
  12. delay(1000);
  13. digitalWrite(13, LOW);
  14. delay(1000);
  15. }
  16. void serialEvent1() {
  17. while (Serial1.available()) {
  18. // get the new byte:
  19. char inChar = (char)Serial1.read();
  20. // add it to the inputString:
  21. inputString += inChar;
  22. // if the incoming character is a newline, set a flag so the main loop can
  23. // do something about it:
  24. if (inChar == '\n') {
  25. stringComplete = true;
  26. }
  27. if (stringComplete) {
  28. Serial1.println(inputString);
  29. // clear the string:
  30. inputString = "";
  31. stringComplete = false;
  32. }
  33. }
  34. }

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读

    相关 设计

    1.问:什么是蓝牙通信? 答:蓝牙通讯最初设计初衷是方便移动电话(手机)与配件之间进行低成本、低功耗无线通信连接,现在已经成为IEEE802.15标准,得到全球上万家厂商支持