-
Notifications
You must be signed in to change notification settings - Fork 15
/
LoRaInterface.ino
116 lines (96 loc) · 2.42 KB
/
LoRaInterface.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* LoRaInterface.ino
*
* Implements all the LoRa communication functions.
*
* (c) 2019 Lee Dowthwaite. All Rights Reserved.
*/
#include "LoRaInterface.h"
// LoRa Settings
//#define ENA_TRANSMIT
#define USE_SPREAD_FACTOR
static int _spreadFactor = MIN_SPREAD_FACTOR;
#ifdef ENA_TRANSMIT
// transmission parameters
#define SEND_INTERVAL (1000)
static long _lastSendTime = 0;
static uint32_t _txCounter = 0;
#endif
// LoRa receive buffers
static bool _receivedFlag = false;
static String _payloadBuffer = "";
// LoRa Handling
void configureLoRa() {
Serial.println("configureLoRa()");
#ifdef ENA_TRANSMIT
LoRa.setTxPowerMax(MAX_TX_POWER);
#endif
#ifdef USE_SPREAD_FACTOR
LoRa.setSpreadingFactor(_spreadFactor);
#endif
LoRa.onReceive(onReceive);
LoRa.receive();
}
// LoRa receiver
// received signal strength
//
int rssi() {
return LoRa.packetRssi();
}
// receiver ISR
//
static void onReceive(int packetSize)
{
// Keep this short and sweet - it's an interrupt service routine
digitalWrite(LED_BUILTIN, HIGH);
// Copy LoRa payload into buffer
_payloadBuffer = "";
while (LoRa.available())
{
_payloadBuffer += (char) LoRa.read();
}
// set flag to say there's data ready
_receivedFlag = true;
digitalWrite(LED_BUILTIN, LOW);
}
void setDefaultSpread() {
LoRa.setSpreadingFactor(MIN_SPREAD_FACTOR);
}
// LoRa transmitter
#ifdef ENA_TRANSMIT
int sendTestPacket() {
Serial.println("Sending packet "+String(_txCounter));
LoRa.beginPacket();
LoRa.print("hello ");
LoRa.print(_txCounter++);
LoRa.endPacket();
}
void sendIfReady() {
if(millis() - _lastSendTime > SEND_INTERVAL)
{
digitalWrite(LED_BUILTIN, HIGH);
sendTestPacket();
_lastSendTime = millis();
clearDisplay();
displayString(0, 0, "sent packet ");
displayString(8, 0, (const char *)String(_txCounter-1).c_str());
displaySpreadFactor(_spreadFactor);
digitalWrite(LED_BUILTIN, LOW);
}
}
#endif
// Check for recent incoming LoRa payload and copy it from the rxbuffer and pass it onto the caller.
//
String *checkRxBuffer() {
static String payload;
if (_receivedFlag && _payloadBuffer.length() > 0) {
_receivedFlag = false;
// ensure length does not exceed maximum
int len = min((int)_payloadBuffer.length(), MAX_LORA_PAYLOAD-1);
// copy String from rx buffer to local static variable for return to caller
payload = _payloadBuffer;
return &payload;
} else {
return NULL;
}
}