Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.56 KB | None | 0 0
  1. //-----------------------------------------------------------------------------------------------------------//
  2. // //
  3. // Master_ELEC1601_Student_2019_v3 //
  4. // The Instructor version of this code is identical to this version EXCEPT it also sets PIN codes //
  5. // 20191008 Peter Jones //
  6. // //
  7. // Bi-directional passing of serial inputs via Bluetooth //
  8. // Note: the void loop() contents differ from "capitalise and return" code //
  9. // //
  10. // This version auto-searches for slave MAC using slave name and attempts connection repeatedly //
  11. // (as implemented in original BluetoothShield demo code "Master.pde" by Steve Chang / Seeed Tech. 2011) //
  12. // //
  13. // This version was initially based on the 2011 Steve Chang code but has been substantially revised //
  14. // and heavily documented throughout. //
  15. // //
  16. // 20190927 Ross Hutton //
  17. // Identified that opening the Arduino IDE Serial Monitor asserts a DTR signal which resets the Arduino, //
  18. // causing it to re-execute the full connection setup routine. If this reset happens on the Master system, //
  19. // it should subsequently re-connect to the Slave but appears to hang while searching for the slave //
  20. // address. As the Bluetooth shield itself is not reset by opening the Serial Monitor, code has been added //
  21. // to check if the Bluetooth connection remains established and, if so, the setup process is bypassed. //
  22. // //
  23. //-----------------------------------------------------------------------------------------------------------//
  24.  
  25. #include <SoftwareSerial.h> // Software Serial Port
  26.  
  27. #define RxD 7
  28. #define TxD 6
  29. #define ConnStatus A1 // Connection status on the SeeedStudio v1 shield is available on pin A1
  30. // See also ConnStatusSupported boolean below
  31. #define DEBUG_ENABLED 1
  32.  
  33. int buzzer_pin = 9;
  34. int r = 11;
  35. int g = 12;
  36. int b = 13;
  37.  
  38. // ##################################################################################
  39. // ### EDIT THE LINES BELOW TO MATCH YOUR SHIELD NUMBER AND CONNECTION PIN OPTION ###
  40. // ##################################################################################
  41.  
  42. int shieldPairNumber = 15;
  43.  
  44. // CAUTION: If ConnStatusSupported = true you MUST NOT use pin A1 otherwise "random" reboots will occur
  45. // CAUTION: If ConnStatusSupported = true you MUST set the PIO[1] switch to A1 (not NC)
  46.  
  47. boolean ConnStatusSupported = true; // Set to "true" when digital connection status is available on Arduino pin
  48.  
  49. // #######################################################
  50.  
  51. // The following four string variable are used to simplify adaptation of code to different shield pairs
  52.  
  53. String slaveName = "Slave"; // This is concatenated with shieldPairNumber later
  54. String masterNameCmd = "\r\n+STNA=Master"; // This is concatenated with shieldPairNumber later
  55. String connectCmd = "\r\n+CONN="; // This is concatenated with slaveAddr later
  56.  
  57. int nameIndex = 0;
  58. int addrIndex = 0;
  59.  
  60. String recvBuf;
  61. String slaveAddr;
  62. String retSymb = "+RTINQ="; // Start symble when there's any return
  63.  
  64. SoftwareSerial blueToothSerial(RxD,TxD);
  65.  
  66.  
  67. void setup()
  68. {
  69. pinMode(buzzer_pin, OUTPUT);
  70. pinMode(r, OUTPUT);
  71. pinMode(g, OUTPUT);
  72. pinMode(b, OUTPUT);
  73. Serial.begin(9600);
  74. blueToothSerial.begin(38400); // Set Bluetooth module to default baud rate 38400
  75.  
  76. pinMode(RxD, INPUT);
  77. pinMode(TxD, OUTPUT);
  78. pinMode(ConnStatus, INPUT);
  79.  
  80. // Check whether Master and Slave are already connected by polling the ConnStatus pin (A1 on SeeedStudio v1 shield)
  81. // This prevents running the full connection setup routine if not necessary.
  82.  
  83. if(ConnStatusSupported) Serial.println("Checking Master-Slave connection status.");
  84.  
  85. if(ConnStatusSupported && digitalRead(ConnStatus)==1)
  86. {
  87. Serial.println("Already connected to Slave - remove USB cable if reboot of Master Bluetooth required.");
  88. }
  89. else
  90. {
  91. Serial.println("Not connected to Slave.");
  92.  
  93. setupBlueToothConnection(); // Set up the local (master) Bluetooth module
  94. getSlaveAddress(); // Search for (MAC) address of slave
  95. makeBlueToothConnection(); // Execute the connection to the slave
  96.  
  97. delay(1000); // Wait one second and flush the serial buffers
  98. Serial.flush();
  99. blueToothSerial.flush();
  100. }
  101. }
  102.  
  103.  
  104. void loop()
  105. {
  106. char recvChar;
  107. char temp;
  108.  
  109. while(1)
  110. {
  111. if(blueToothSerial.available()) // Check if there's any data sent from the remote Bluetooth shield
  112. {
  113. recvChar = blueToothSerial.read();
  114. if (recvChar == 'h') {
  115. while (recvChar != 'f') {
  116. if(Serial.available()) // Check if there's any data sent from the local serial terminal. You can add the other applications here.
  117. {
  118. recvChar = Serial.read();
  119. //Serial.print(recvChar);
  120. blueToothSerial.print(recvChar);
  121. }
  122. //flash lights and sound buzzer
  123. digitalWrite(r, HIGH);
  124. analogWrite(buzzer_pin, 500);
  125. delay(500);
  126. digitalWrite(buzzer_pin, LOW);
  127. digitalWrite(r, LOW);
  128. delay(250);
  129. recvChar = blueToothSerial.read();
  130. }
  131. }
  132.  
  133. if (recvChar == 'd') {
  134. digitalWrite(g, HIGH);
  135. delay(1000);
  136. digitalWrite(g, LOW);
  137. }
  138. }
  139.  
  140. if(Serial.available()) // Check if there's any data sent from the local serial terminal. You can add the other applications here.
  141. {
  142. recvChar = Serial.read();
  143. //Serial.print(recvChar);
  144. blueToothSerial.print(recvChar);
  145. }
  146. }
  147. }
  148.  
  149.  
  150. void setupBlueToothConnection()
  151. {
  152. Serial.println("Setting up the local (master) Bluetooth module.");
  153.  
  154. masterNameCmd += shieldPairNumber;
  155. masterNameCmd += "\r\n";
  156.  
  157. blueToothSerial.print("\r\n+STWMOD=1\r\n"); // Set the Bluetooth to work in master mode
  158. blueToothSerial.print(masterNameCmd); // Set the bluetooth name using masterNameCmd
  159. blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection is forbidden here
  160.  
  161. // print() sets up a transmit/outgoing buffer for the string which is then transmitted via interrupts one character at a time.
  162. // This allows the program to keep running, with the transmitting happening in the background.
  163. // Serial.flush() does not empty this buffer, instead it pauses the program until all Serial.print()ing is done.
  164. // This is useful if there is critical timing mixed in with Serial.print()s.
  165. // To clear an "incoming" serial buffer, use while(Serial.available()){Serial.read();}
  166.  
  167. blueToothSerial.flush();
  168. delay(2000); // This delay is required
  169.  
  170. blueToothSerial.print("\r\n+INQ=1\r\n"); // Make the master Bluetooth inquire
  171.  
  172. blueToothSerial.flush();
  173. delay(2000); // This delay is required
  174.  
  175. Serial.println("Master is inquiring!");
  176. }
  177.  
  178.  
  179. void getSlaveAddress()
  180. {
  181. slaveName += shieldPairNumber;
  182.  
  183. Serial.print("Searching for address of slave: ");
  184. Serial.println(slaveName);
  185.  
  186. slaveName = ";" + slaveName; // The ';' must be included for the search that follows
  187.  
  188. char recvChar;
  189.  
  190. // Initially, if(blueToothSerial.available()) will loop and, character-by-character, fill recvBuf to be:
  191. // +STWMOD=1 followed by a blank line
  192. // +STNA=MasterTest (followed by a blank line)
  193. // +S
  194. // OK (followed by a blank line)
  195. // OK (followed by a blank line)
  196. // OK (followed by a blank line)
  197. // WORK:
  198. //
  199. // It will then, character-by-character, add the result of the first device that responds to the +INQ request:
  200. // +RTINQ=64,A2,F9,xx,xx,xx;OnePlus 6 (xx substituted for anonymity)
  201. //
  202. // If this does not contain slaveName, the loop will continue. If nothing else responds to the +INQ request, the
  203. // process will appear to have frozen BUT IT HAS NOT. Be patient. Ask yourself why your slave has not been detected.
  204. // Eventually your slave will respond and the loop will add:
  205. // +RTINQ=0,6A,8E,16,C4,1B;SlaveTest
  206. //
  207. // nameIndex will identify "SlaveTest", return a non -1 value and progress to the if() statement.
  208. // This will strip 0,6A,8E,16,C4,1B from the buffer, assign it to slaveAddr, and break from the loop.
  209.  
  210. while(1)
  211. {
  212. if(blueToothSerial.available())
  213. {
  214. recvChar = blueToothSerial.read();
  215. recvBuf += recvChar;
  216.  
  217. nameIndex = recvBuf.indexOf(slaveName); // Get the position of slave name
  218.  
  219. if ( nameIndex != -1 ) // ie. if slaveName was found
  220. {
  221. addrIndex = (recvBuf.indexOf(retSymb,(nameIndex - retSymb.length()- 18) ) + retSymb.length()); // Get the start position of slave address
  222. slaveAddr = recvBuf.substring(addrIndex, nameIndex); // Get the string of slave address
  223.  
  224. Serial.print("Slave address found: ");
  225. Serial.println(slaveAddr);
  226.  
  227. break; // Only breaks from while loop if slaveName is found
  228. }
  229. }
  230. }
  231. }
  232.  
  233.  
  234. void makeBlueToothConnection()
  235. {
  236. Serial.println("Initiating connection with slave.");
  237.  
  238. char recvChar;
  239.  
  240. // Having found the target slave address, now form the full connection command
  241.  
  242. connectCmd += slaveAddr;
  243. connectCmd += "\r\n";
  244.  
  245. int connectOK = 0; // Flag used to indicate succesful connection
  246. int connectAttempt = 0; // Counter to track number of connect attempts
  247.  
  248. // Keep trying to connect to the slave until it is connected (using a do-while loop)
  249.  
  250. do
  251. {
  252. Serial.print("Connect attempt: ");
  253. Serial.println(++connectAttempt);
  254.  
  255. blueToothSerial.print(connectCmd); // Send connection command
  256.  
  257. // Initially, if(blueToothSerial.available()) will loop and, character-by-character, fill recvBuf to be:
  258. // OK (followed by a blank line)
  259. // +BTSTATE:3 (followed by a blank line)(BTSTATE:3 = Connecting)
  260. //
  261. // It will then, character-by-character, add the result of the connection request.
  262. // If that result is "CONNECT:OK", the while() loop will break and the do() loop will exit.
  263. // If that result is "CONNECT:FAIL", the while() loop will break with an appropriate "FAIL" message
  264. // and a new connection command will be issued for the same slave address.
  265.  
  266. recvBuf = "";
  267.  
  268. while(1)
  269. {
  270. if(blueToothSerial.available())
  271. {
  272. recvChar = blueToothSerial.read();
  273. recvBuf += recvChar;
  274.  
  275. if(recvBuf.indexOf("CONNECT:OK") != -1)
  276. {
  277. connectOK = 1;
  278. Serial.println("Connected to slave!");
  279. blueToothSerial.print("Master-Slave connection established!");
  280. break;
  281. }
  282. else if(recvBuf.indexOf("CONNECT:FAIL") != -1)
  283. {
  284. Serial.println("Connection FAIL, try again!");
  285. break;
  286. }
  287. }
  288. }
  289. } while (0 == connectOK);
  290.  
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement