You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.3 KiB

  1. /*
  2. Example sketch for the RFCOMM/SPP Bluetooth library - developed by Kristian Lauszus
  3. For more information visit my blog: http://blog.tkjelectronics.dk/ or
  4. send me an e-mail: kristianl@tkjelectronics.com
  5. */
  6. #include <SPP.h>
  7. #include <usbhub.h>
  8. // Satisfy IDE, which only needs to see the include statment in the ino.
  9. #ifdef dobogusinclude
  10. #include <spi4teensy3.h>
  11. #include <SPI.h>
  12. #endif
  13. USB Usb;
  14. //USBHub Hub1(&Usb); // Some dongles have a hub inside
  15. BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
  16. const uint8_t length = 2; // Set the number of instances here
  17. SPP *SerialBT[length]; // We will use this pointer to store the instances, you can easily make it larger if you like, but it will use a lot of RAM!
  18. bool firstMessage[length] = { true }; // Set all to true
  19. void setup() {
  20. for (uint8_t i = 0; i < length; i++)
  21. SerialBT[i] = new SPP(&Btd); // This will set the name to the default: "Arduino" and the pin to "0000" for all connections
  22. Serial.begin(115200);
  23. #if !defined(__MIPSEL__)
  24. while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
  25. #endif
  26. if (Usb.Init() == -1) {
  27. Serial.print(F("\r\nOSC did not start"));
  28. while (1); // Halt
  29. }
  30. Serial.print(F("\r\nSPP Bluetooth Library Started"));
  31. }
  32. void loop() {
  33. Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
  34. for (uint8_t i = 0; i < length; i++) {
  35. if (SerialBT[i]->connected) {
  36. if (firstMessage[i]) {
  37. firstMessage[i] = false;
  38. SerialBT[i]->println(F("Hello from Arduino")); // Send welcome message
  39. }
  40. if (SerialBT[i]->available())
  41. Serial.write(SerialBT[i]->read());
  42. }
  43. else
  44. firstMessage[i] = true;
  45. }
  46. // Set the connection you want to send to using the first character
  47. // For instance "0Hello World" would send "Hello World" to connection 0
  48. if (Serial.available()) {
  49. delay(10); // Wait for the rest of the data to arrive
  50. uint8_t id = Serial.read() - '0'; // Convert from ASCII
  51. if (id < length && SerialBT[id]->connected) { // Make sure that the id is valid and make sure that a device is actually connected
  52. while (Serial.available()) // Check if data is available
  53. SerialBT[id]->write(Serial.read()); // Send the data
  54. }
  55. }
  56. }