-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttn-otaa-feather-us915-dht22.ino
725 lines (640 loc) · 24.8 KB
/
ttn-otaa-feather-us915-dht22.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/*******************************************************************************
* The Things Network - Sensor Data Example
*
* Example of sending a valid LoRaWAN packet with DHT22 temperature and
* humidity data to The Things Networ using a Feather M0 LoRa.
*
* Learn Guide: https://learn.adafruit.com/the-things-network-for-feather
*
* Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
* Copyright (c) 2018 Terry Moore, MCCI
* Copyright (c) 2018 Brent Rubell, Adafruit Industries
*
* Permission is hereby granted, free of charge, to anyone
* obtaining a copy of this document and accompanying files,
* to do whatever they want with them without any restriction,
* including, but not limited to, copying, modification and redistribution.
* NO WARRANTY OF ANY KIND IS PROVIDED.
*******************************************************************************/
#include <arduino_lmic.h>
#include <hal/hal.h>
#include <RTCZero.h> // Arduino Zero Real Time Clock Library
#include <SPI.h>
#include <CayenneLPP.h>
#include <DHT.h> // include the DHT22 Sensor Library
#include <SDI12.h> // Include SDI-12 master
#define ENABLE_LED 1 // Enable Led to show when awake
#define POWER_PIN_DHT 12
#define POWER_PIN_9V 9
#define BATTERY_ADC_PIN A1
#define DATA_PIN 11 /*!< The pin of the SDI-12 data bus */
#define SENSOR_ADDRESS 0
#define serial Serial1
// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 1800; // 30 mins (30*60=1800)
// DHT digital pin and sensor type
#define DHTPIN 10
#define DHTTYPE DHT22
// LMIC Device State
#define STATE_IDLE 0
#define STATE_STANDBY_READY 1
#define STATE_DO_JOB 2
static uint8_t state = STATE_IDLE;
// //
// // For normal use, we require that you edit the sketch to replace FILLMEIN
// // with values assigned by the TTN console. However, for regression tests,
// // we want to be able to compile these scripts. The regression tests define
// // COMPILE_REGRESSION_TEST, and in that case we define FILLMEIN to a non-
// // working but innocuous value.
// //
// #ifdef COMPILE_REGRESSION_TEST
// #define FILLMEIN 0
// #else
// #warning "You must replace the values marked FILLMEIN with real values from the TTN control panel!"
// #define FILLMEIN (#dont edit this, edit the lines that use FILLMEIN)
// #endif
// This EUI must be in little-endian format, so least-significant-byte
// first. When copying an EUI from ttnctl output, this means to reverse
// the bytes. For TTN issued EUIs the last bytes should be 0xD5, 0xB3,
// 0x70.
static const u1_t PROGMEM APPEUI[8]={ 0x00, 0x00,0x00, 0x00,0x00,0x00,0x00,0x00 };
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI, 8);}
// This should also be in little endian format, see above.
static const u1_t PROGMEM DEVEUI[8]={ 0xf3, 0xc2, 0xe8, 0x23, 0x2c, 0x3a, 0x23, 0x74 };
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI, 8);}
// This key should be in big endian format (or, since it is not really a
// number but a block of memory, endianness does not really apply). In
// practice, a key taken from the TTN console can be copied as-is.
static const u1_t PROGMEM APPKEY[16] = { 0x75, 0x91, 0x12, 0xf7, 0xce, 0xd1, 0x23, 0x82, 0x1a, 0x06, 0xdb, 0x51, 0x2a, 0x90, 0x92, 0xd2 };
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY, 16);}
// payload to send to TTN gateway
static uint8_t payload[5];
static osjob_t sendjob;
// Pin mapping for Adafruit Feather M0 LoRa
// /!\ By default Adafruit Feather M0's pin 6 and DIO1 are not connected.
// Please ensure they are connected.
const lmic_pinmap lmic_pins = {
.nss = 8,
.rxtx = LMIC_UNUSED_PIN,
.rst = 4,
.dio = {3, 6, LMIC_UNUSED_PIN},
.rxtx_rx_active = 0,
.rssi_cal = 8, // LBT cal for the Adafruit Feather M0 LoRa, in dB
.spi_freq = 8000000,
};
// init. DHT
DHT dht(DHTPIN, DHTTYPE);
// CayenneLPP testing stuff
#define MAX_CAYENNE_PAYLOAD_SIZE 51
CayenneLPP lpp(MAX_CAYENNE_PAYLOAD_SIZE);
// Declare real time clock
RTCZero rtc;
uint32_t userUTCTime; // Seconds since the UTC epoch
/** Define the SDI-12 bus */
SDI12 mySDI12(DATA_PIN);
// Utility function for digital clock display: prints preceding colon and
// leading 0
void printDigits(int digits) {
serial.print(':');
if (digits < 10) serial.print('0');
serial.print(digits);
}
void printHex2(unsigned v) {
v &= 0xff;
if (v < 16)
serial.print('0');
serial.print(v, HEX);
}
// A buffer for printing log messages.
static constexpr int MAX_MSG = 256;
static char msg[MAX_MSG];
// A printf-like function to print log messages prefixed by the current
// LMIC tick value. Don't call it before os_init();
//
// The RTC timestamps will start at 00:00:00, but will update to UTC
// if the DeviceTimeReq is answered.
void log_msg(const char *fmt, ...) {
#ifdef USE_SERIAL
snprintf(msg, MAX_MSG, "%02d:%02d:%02d / ", rtc.getHours(), rtc.getMinutes(), rtc.getSeconds());
serial.write(msg, strlen(msg));
snprintf(msg, MAX_MSG, "% 012ld: ", os_getTime());
serial.write(msg, strlen(msg));
va_list args;
va_start(args, fmt);
vsnprintf(msg, MAX_MSG, fmt, args);
va_end(args);
serial.write(msg, strlen(msg));
serial.println();
#endif
}
/*
* This function is used to set the alarm to a relative time in the future, such as when
* sleeping between LMIC tasks.
*/
void set_delta_alarm(uint32_t delta_seconds) {
int32_t ss = (int32_t)rtc.getSeconds();
int32_t mm = (int32_t)rtc.getMinutes();
int32_t hh = (int32_t)rtc.getHours();
// Sanity check.
if (delta_seconds < 1) {
delta_seconds = 1;
}
int32_t delta = delta_seconds;
int32_t hh_delta = delta / 3600; delta -= (hh_delta * 3600);
// Will always be less than 1 hour.
int32_t mm_delta = delta / 60; delta -= (mm_delta * 60);
// Will always be less than 1 minute.
int32_t ss_delta = delta;
ss += ss_delta;
if (ss > 59) {
ss = ss % 60;
mm_delta++;
}
mm += mm_delta;
if (mm > 59) {
mm = mm % 60;
hh_delta++;
}
hh = (hh + hh_delta) % 24;
serial.print("Delta(s) = ");
serial.print(delta_seconds);
serial.print(F(", wake at "));
serial.print(hh);
printDigits(mm);
printDigits(ss);
serial.println();
rtc.setAlarmTime((uint8_t)(hh & 0xff), (uint8_t)(mm & 0xff), (uint8_t)(ss & 0xff));
rtc.enableAlarm(RTCZero::MATCH_HHMMSS);
}
void user_request_network_time_callback(void *pVoidUserUTCTime, int flagSuccess) {
// Explicit conversion from void* to uint32_t* to avoid compiler errors
uint32_t *pUserUTCTime = (uint32_t *) pVoidUserUTCTime;
// A struct that will be populated by LMIC_getNetworkTimeReference.
// It contains the following fields:
// - tLocal: the value returned by os_GetTime() when the time
// request was sent to the gateway, and
// - tNetwork: the seconds between the GPS epoch and the time
// the gateway received the time request
lmic_time_reference_t lmicTimeReference;
if (flagSuccess != 1) {
serial.println(F("USER CALLBACK: Not a success"));
return;
}
// Populate "lmic_time_reference"
flagSuccess = LMIC_getNetworkTimeReference(&lmicTimeReference);
if (flagSuccess != 1) {
serial.println(F("USER CALLBACK: LMIC_getNetworkTimeReference didn't succeed"));
return;
}
// Update userUTCTime, considering the difference between the GPS and UTC
// epoch, and the leap seconds
*pUserUTCTime = lmicTimeReference.tNetwork + 315964800 - 18;
// Add the delay between the instant the time was transmitted and
// the current time
// Current time, in ticks
ostime_t ticksNow = os_getTime();
// Time when the request was sent, in ticks
ostime_t ticksRequestSent = lmicTimeReference.tLocal;
uint32_t requestDelaySec = osticks2ms(ticksNow - ticksRequestSent) / 1000;
*pUserUTCTime += requestDelaySec;
// Add time zone offset
*pUserUTCTime += (10*60*60);
// Update the system time with the time read from the network
rtc.setEpoch(*pUserUTCTime);
serial.print(F("The current UTC+10 time is: "));
serial.print(rtc.getHours());
printDigits(rtc.getMinutes());
printDigits(rtc.getSeconds());
serial.print(' ');
serial.print(rtc.getDay());
serial.print('/');
serial.print(rtc.getMonth());
serial.print('/');
serial.print(rtc.getYear());
serial.println();
}
void onEvent (ev_t ev) {
serial.print(os_getTime());
serial.print(": ");
switch(ev) {
case EV_SCAN_TIMEOUT:
serial.println(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
serial.println(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
serial.println(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
serial.println(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
serial.println(F("EV_JOINED"));
{
u4_t netid = 0;
devaddr_t devaddr = 0;
u1_t nwkKey[16];
u1_t artKey[16];
LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
serial.print("netid: ");
serial.println(netid, DEC);
serial.print("devaddr: ");
serial.println(devaddr, HEX);
serial.print("AppSKey: ");
for (size_t i=0; i<sizeof(artKey); ++i) {
if (i != 0)
serial.print("-");
printHex2(artKey[i]);
}
serial.println("");
serial.print("NwkSKey: ");
for (size_t i=0; i<sizeof(nwkKey); ++i) {
if (i != 0)
serial.print("-");
printHex2(nwkKey[i]);
}
serial.println();
}
// Disable link check validation (automatically enabled
// during join, but because slow data rates change max TX
// size, we don't use it in this example.
LMIC_setLinkCheckMode(0);
state = STATE_DO_JOB;
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_RFU1:
|| serial.println(F("EV_RFU1"));
|| break;
*/
case EV_JOIN_FAILED:
serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
serial.println(F("EV_REJOIN_FAILED"));
break;
break;
case EV_TXCOMPLETE:
serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
if (LMIC.txrxFlags & TXRX_ACK)
serial.println(F("Received ack"));
if (LMIC.dataLen) {
serial.println(F("Received "));
serial.println(LMIC.dataLen);
serial.println(F(" bytes of payload"));
}
// Schedule next transmission
// os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
state = STATE_IDLE;
break;
case EV_LOST_TSYNC:
serial.println(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
serial.println(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
serial.println(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
serial.println(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
serial.println(F("EV_LINK_ALIVE"));
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_SCAN_FOUND:
|| serial.println(F("EV_SCAN_FOUND"));
|| break;
*/
case EV_TXSTART:
serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
serial.println(F("EV_TXCANCELED"));
break;
case EV_RXSTART:
/* do not print anything -- it wrecks timing */
break;
case EV_JOIN_TXCOMPLETE:
serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept"));
break;
default:
serial.print(F("Unknown event: "));
serial.println((unsigned) ev);
break;
}
}
bool getResults(char i, int resultsExpected) {
uint8_t resultsReceived = 0;
uint8_t cmd_number = 0;
while (resultsReceived < resultsExpected && cmd_number <= 9) {
String command = "";
// in this example we will only take the 'DO' measurement
command = "";
command += i;
command += "D";
command += cmd_number;
command += "!"; // SDI-12 command to get data [address][D][dataOption][!]
mySDI12.sendCommand(command);
uint32_t start = millis();
while (mySDI12.available() < 3 && (millis() - start) < 1500) {}
mySDI12.read(); // ignore the repeated SDI12 address
char c = mySDI12.peek(); // check if there's a '+' and toss if so
if (c == '+') { mySDI12.read(); }
while (mySDI12.available()) {
char c = mySDI12.peek();
if (c == '-' || (c >= '0' && c <= '9') || c == '.') {
float result = mySDI12.parseFloat(SKIP_NONE);
serial.print(String(result, 10));
if (result != -9999) { resultsReceived++; }
} else if (c == '+') {
mySDI12.read();
serial.print(", ");
} else {
mySDI12.read();
}
delay(10); // 1 character ~ 7.5ms
}
if (resultsReceived < resultsExpected) { serial.print(", "); }
cmd_number++;
}
mySDI12.clearBuffer();
return resultsReceived == resultsExpected;
}
bool takeMeasurement(char i, String meas_type = "") {
mySDI12.clearBuffer();
String command = "";
command += i;
command += "M";
command += meas_type;
command += "!"; // SDI-12 measurement command format [address]['M'][!]
mySDI12.sendCommand(command);
delay(100);
// wait for acknowlegement with format [address][ttt (3 char, seconds)][number of
// measurments available, 0-9]
String sdiResponse = mySDI12.readStringUntil('\n');
sdiResponse.trim();
String addr = sdiResponse.substring(0, 1);
serial.print(addr);
serial.print(", ");
// find out how long we have to wait (in seconds).
uint8_t wait = sdiResponse.substring(1, 4).toInt();
serial.print(wait);
serial.print(", ");
// Set up the number of results to expect
int numResults = sdiResponse.substring(4).toInt();
serial.print(numResults);
serial.print(", ");
unsigned long timerStart = millis();
while ((millis() - timerStart) < (1000 * (wait + 1))) {
if (mySDI12.available()) // sensor can interrupt us to let us know it is done early
{
serial.print(millis() - timerStart);
serial.print(", ");
mySDI12.clearBuffer();
break;
}
}
// Wait for anything else and clear it out
delay(30);
mySDI12.clearBuffer();
if (numResults > 0) { return getResults(i, numResults); }
return true;
}
void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
serial.println(F("OP_TXRXPEND, not sending"));
} else {
if (POWER_PIN_9V > 1) {
digitalWrite(POWER_PIN_9V, HIGH);
}
if (POWER_PIN_DHT > 1) {
digitalWrite(POWER_PIN_DHT, HIGH);
delay(1000);
}
// read the temperature from the DHT22
float temperature = dht.readTemperature();
serial.print("Temperature: "); serial.print(temperature);
serial.println(" *C");
// adjust for the f2sflt16 range (-1 to 1)
// temperature = temperature / 100;
// read the humidity from the DHT22
float rHumidity = dht.readHumidity();
serial.print("%RH ");
serial.println(rHumidity);
if (POWER_PIN_DHT > 1) {
digitalWrite(POWER_PIN_DHT, LOW);
}
// adjust for the f2sflt16 range (-1 to 1)
// rHumidity = rHumidity / 100;
// float -> int
// note: this uses the sflt16 datum (https://github.com/mcci-catena/arduino-lmic#sflt16)
// uint16_t payloadTemp = LMIC_f2sflt16(temperature);
// // int -> bytes
// byte tempLow = lowByte(payloadTemp);
// byte tempHigh = highByte(payloadTemp);
// // place the bytes into the payload
// payload[0] = tempLow;
// payload[1] = tempHigh;
// // float -> int
// uint16_t payloadHumid = LMIC_f2sflt16(rHumidity);
// // int -> bytes
// byte humidLow = lowByte(payloadHumid);
// byte humidHigh = highByte(payloadHumid);
// payload[2] = humidLow;
// payload[3] = humidHigh;
uint8_t batt_val;
if (POWER_PIN_9V > 1) {
batt_val = map(analogRead(BATTERY_ADC_PIN), 0, 1023, 1, 255);
delay(2000);
}
// Read SDI-12 Sensor
float sdi_data[2];
String myCommand = "";
// first command to take a measurement
myCommand = String(SENSOR_ADDRESS) + "M!";
serial.println(myCommand); // echo command to terminal
mySDI12.clearBuffer();
mySDI12.sendCommand(myCommand);
delay(100);
// wait for acknowlegement with format [address][ttt (3 char, seconds)][number of
// measurments available, 0-9]
String sdiResponse = mySDI12.readStringUntil('\n');
sdiResponse.trim();
serial.println(sdiResponse);
// find out how long we have to wait (in seconds).
uint8_t wait = sdiResponse.substring(1, 4).toInt();
// Set up the number of results to expect
int numResults = sdiResponse.substring(4).toInt();
unsigned long timerStart = millis();
while ((millis() - timerStart) < (1000UL * (wait + 1))) {
// sensor can interrupt us to let us know it is done early
if (mySDI12.available()) {
serial.print(millis() - timerStart);
serial.print(", ");
mySDI12.clearBuffer();
break;
}
}
// Wait for anything else and clear it out
delay(30);
mySDI12.clearBuffer();
// Send Get Results
uint8_t resultsReceived = 0;
uint8_t cmd_number = 0;
myCommand = String(SENSOR_ADDRESS) + "D0!";
while (resultsReceived < numResults && cmd_number <= 9) {
myCommand = "0"; // Address
// in this example we will only take the 'DO' measurement
myCommand += "D";
myCommand += cmd_number;
myCommand += "!"; // SDI-12 command to get data [address][D][dataOption][!]
serial.println(myCommand);
mySDI12.sendCommand(myCommand);
uint32_t start = millis();
while (mySDI12.available() < 3 && (millis() - start) < 1500) {}
mySDI12.read(); // ignore the repeated SDI12 address
char c = mySDI12.peek(); // check if there's a '+' and toss if so
if (c == '+') { mySDI12.read(); }
while (mySDI12.available()) {
char c = mySDI12.peek();
if (c == '-' || (c >= '0' && c <= '9') || c == '.') {
float result = mySDI12.parseFloat(SKIP_NONE);
sdi_data[resultsReceived] = result;
serial.print(String(result, 10));
if (result != -9999) { resultsReceived++; }
} else if (c == '+') {
mySDI12.read();
serial.print(", ");
} else {
mySDI12.read();
}
delay(10); // 1 character ~ 7.5ms
}
if (resultsReceived < numResults) { serial.print(", "); }
cmd_number++;
}
if (POWER_PIN_9V > 1) {
digitalWrite(POWER_PIN_9V, LOW);
}
mySDI12.clearBuffer();
LMIC_setBatteryLevel(batt_val);
serial.println("");
// prepare upstream data transmission at the next possible time.
// transmit on port 1 (the first parameter); you can use any value from 1 to 223 (others are reserved).
// don't request an ack (the last parameter, if not zero, requests an ack from the network).
// Remember, acks consume a lot of network resources; don't ask for an ack unless you really need it.
// LMIC_setTxData2(1, payload, sizeof(payload)-1, 0);
// Testing CayenneLPP payload structure
lpp.reset();
lpp.addTemperature(1, temperature);
lpp.addRelativeHumidity(1, rHumidity);
lpp.addBarometricPressure(2, sdi_data[0]*10000);
lpp.addTemperature(2, sdi_data[1]);
serial.print(F("Cayenne Packet Size: "));
serial.println(lpp.getSize());
lmic_tx_error_t txDataError;
txDataError = LMIC_setTxData2(1, lpp.getBuffer(), lpp.getSize(), 0);
serial.println(F("Packet queued"));
if (txDataError == LMIC_ERROR_SUCCESS) {
serial.println(F("Packet will be sent"));
} else if (txDataError == LMIC_ERROR_TX_BUSY) {
serial.println(F("Packet not sent, LMIC busy sending other message"));
} else if (txDataError == LMIC_ERROR_TX_TOO_LARGE) {
serial.println(F("Packet too large for current datarate"));
} else if (txDataError == LMIC_ERROR_TX_NOT_FEASIBLE) {
serial.println(F("Packet unsuitable for current datarate"));
} else {
serial.println(F("Queued message failed to send for other reason than data len"));
}
}
// Next TX is scheduled after TX_COMPLETE event.
}
void setup() {
delay(5000);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(POWER_PIN_DHT, OUTPUT);
pinMode(POWER_PIN_9V, OUTPUT);
serial.begin(115200);
// while (!serial);
serial.println(F("Starting"));
dht.begin();
rtc.begin(false);
mySDI12.begin();
delay(500);
// LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Disable link-check mode and ADR, because ADR tends to complicate testing.
LMIC_setLinkCheckMode(0);
// Set the data rate to Spreading Factor 7. This is the fastest supported rate for 125 kHz channels, and it
// minimizes air time and battery power. Set the transmission power to 14 dBi (25 mW).
LMIC_setDrTxpow(DR_SF7,14);
// in the US, with TTN, it saves join time if we start on subband 1 (channels 8-15). This will
// get overridden after the join by parameters from the network. If working with other
// networks or in other regions, this will need to be changed.
LMIC_selectSubBand(1);
// Define device as being powered by external power source
LMIC_setBatteryLevel(MCMD_DEVS_EXT_POWER);
serial.println(F("Joining"));
LMIC_startJoining();
// Start job (sending automatically starts OTAA too)
// serial.println(F("Do First Job"));
// do_send(&sendjob);
LMIC_requestNetworkTime(user_request_network_time_callback, &userUTCTime);
}
bit_t have_deadline = 0;
void loop() {
// we call the LMIC's runloop processor. This will cause things to happen based on events and time. One
// of the things that will happen is callbacks for transmission complete or received messages. We also
// use this loop to queue periodic data transmissions. You can put other things here in the `loop()` routine,
// but beware that LoRaWAN timing is pretty tight, so if you do more than a few milliseconds of work, you
// will want to call `os_runloop_once()` every so often, to keep the radio running.
os_runloop_once();
// Let radio do its thing before consider doing anything else.
if (!(LMIC.opmode & OP_TXRXPEND)) {
switch (state) {
case STATE_DO_JOB:
digitalWrite(LED_BUILTIN, HIGH);
serial.println(F("State: Do_JOB"));
os_setCallback(&sendjob, do_send);
// State update in radio_onevent
state = STATE_IDLE;
break;
case STATE_STANDBY_READY:
digitalWrite(LED_BUILTIN, LOW);
serial.println(F("State: STANDBY_READY"));
set_delta_alarm(TX_INTERVAL);
// delay(TX_INTERVAL*1000);
serial.flush();
rtc.standbyMode();
// Disable the alarm in case it was set to some short interval and LMIC
// tasks will run for longer than that. It probably wouldn't cause
// trouble but may as well be sure.
rtc.disableAlarm();
state = STATE_DO_JOB;
break;
case STATE_IDLE:
have_deadline = os_queryTimeCriticalJobs(sec2osticks(TX_INTERVAL));
// os_getNextDeadline(&have_deadline);
if (!have_deadline) {
state = STATE_STANDBY_READY;
}
break;
}
}
}