forked from sandeepmistry/arduino-BLEPeripheral
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.ino
70 lines (57 loc) · 1.79 KB
/
serial.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Serial Port over BLE
* Create UART service compatible with Nordic's *nRF Toolbox* and Adafruit's *Bluefruit LE* iOS/Android apps.
*
* BLESerial class implements same protocols as Arduino's built-in Serial class and can be used as it's wireless
* replacement. Data transfers are routed through a BLE service with TX and RX characteristics. To make the
* service discoverable all UUIDs are NUS (Nordic UART Service) compatible.
*
* Please note that TX and RX characteristics use Notify and WriteWithoutResponse, so there's no guarantee
* that the data will make it to the other end. However, under normal circumstances and reasonable signal
* strengths everything works well.
*/
// Import libraries (BLEPeripheral depends on SPI)
#include <SPI.h>
#include <BLEPeripheral.h>
#include "BLESerial.h"
// define pins (varies per shield/board)
#define BLE_REQ 10
#define BLE_RDY 2
#define BLE_RST 9
// create ble serial instance, see pinouts above
BLESerial BLESerial(BLE_REQ, BLE_RDY, BLE_RST);
void setup() {
// custom services and characteristics can be added as well
BLESerial.setLocalName("UART");
Serial.begin(115200);
BLESerial.begin();
}
void loop() {
BLESerial.poll();
forward();
// loopback();
// spam();
}
// forward received from Serial to BLESerial and vice versa
void forward() {
if (BLESerial && Serial) {
int byte;
while ((byte = BLESerial.read()) > 0) Serial.write((char)byte);
while ((byte = Serial.read()) > 0) BLESerial.write((char)byte);
}
}
// echo all received data back
void loopback() {
if (BLESerial) {
int byte;
while ((byte = BLESerial.read()) > 0) BLESerial.write(byte);
}
}
// periodically sent time stamps
void spam() {
if (BLESerial) {
BLESerial.print(millis());
BLESerial.println(" tick-tacks!");
delay(1000);
}
}