Skip to content

Instantly share code, notes, and snippets.

@amirhaleem
Created August 24, 2020 20:35
Show Gist options
  • Save amirhaleem/d0eefdbfdbd76f5a96f3f85732f4939a to your computer and use it in GitHub Desktop.
Save amirhaleem/d0eefdbfdbd76f5a96f3f85732f4939a to your computer and use it in GitHub Desktop.
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#include <Adafruit_ZeroTimer.h>
#include <Adafruit_GPS.h>
// what's the name of the hardware serial port?
#define GPSSerial Serial1
#define CFG_sx1276_radio 1
// Connect to the GPS on the hardware port
Adafruit_GPS GPS(&GPSSerial);
// Timer for reading GPS data
const uint8_t timer_number = 3;
Adafruit_ZeroTimer timer = Adafruit_ZeroTimer(timer_number);
//define the interrupt handlers
void TC3_Handler() {
Adafruit_ZeroTimer::timerHandler(3);
}
void TC4_Handler() {
Adafruit_ZeroTimer::timerHandler(4);
}
void TC5_Handler() {
Adafruit_ZeroTimer::timerHandler(5);
}
#define GPSECHO true
//
// 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] = { 0x67, 0x59, 0x86, 0x87, 0xD0, 0xC1, 0xA3, 0xB3 };
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] = { 0x9A, 0xBB, 0x55, 0xBB, 0x30, 0xBE, 0x75, 0xF4 };
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] = { 0xF3, 0x35, 0xC1, 0x4B, 0x26, 0x0D, 0x54, 0x74, 0xAC, 0x01, 0xCF, 0x05, 0x67, 0xF6, 0xC9, 0x17 };
void os_getDevKey (u1_t* buf) {
memcpy_P(buf, APPKEY, 16);
}
// payload to send to TTN gateway
static osjob_t sendjob;
const uint8_t wait_fix_interval = 5;
// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 5;
// Pin mapping for Adafruit Feather M0 LoRa
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,
};
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("artKey: ");
for (int i = 0; i < sizeof(artKey); ++i) {
if (i != 0)
Serial.print("-");
Serial.print(artKey[i], HEX);
}
Serial.println("");
Serial.print("nwkKey: ");
for (int i = 0; i < sizeof(nwkKey); ++i) {
if (i != 0)
Serial.print("-");
Serial.print(nwkKey[i], HEX);
}
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);
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);
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;
default:
Serial.print(F("Unknown event: "));
Serial.println((unsigned) ev);
break;
}
}
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 {
// 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);
// 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;*/
static uint8_t payload[32];
uint8_t idx = 0;
uint32_t data;
float measuredvbat = analogRead(A7);
measuredvbat *= 2; // we divided by 2, so multiply back
measuredvbat *= 3.3; // Multiply by 3.3V, our reference voltage
measuredvbat /= 1024; // convert to voltage
if (GPS.newNMEAreceived()) {
GPS.parse(GPS.lastNMEA());
}
if (GPS.fix) {
Serial.println(F("Got a GPS fix"));
//data = GPS.latitude_fixed * (GPS.lat == 'N' ? 1 : -1) + 90 * 1E7;
data = (int)(GPS.latitudeDegrees * 1E7);
payload[idx++] = data >> 24;
payload[idx++] = data >> 16;
payload[idx++] = data >> 8;
payload[idx++] = data;
//data = GPS.longitude_fixed * (GPS.lon == 'E' ? 1 : -1) + 180 * 1E7;
data = (int)(GPS.longitudeDegrees * 1E7);
payload[idx++] = data >> 24;
payload[idx++] = data >> 16;
payload[idx++] = data >> 8;
payload[idx++] = data;
data = (int)(GPS.altitude + 0.5);
payload[idx++] = data >> 8;
payload[idx++] = data;
data = (int)(GPS.speed);
payload[idx++] = data >> 8;
payload[idx++] = data;
data = (int)(measuredvbat);
payload[idx++] = data >> 8;
payload[idx++] = data;
} else {
Serial.println(F("No GPS fix"));
for (idx = 0; idx < 255; idx++) {
payload[idx] = 0;
}
}
Serial.println(F("Packet queued"));
// 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, idx, 0);
}
// Next TX is scheduled after TX_COMPLETE event.
os_setTimedCallback(&sendjob, os_getTime() + sec2osticks(TX_INTERVAL), do_send);
}
// Timer interrupt handler
void timer_callback()
{
GPS.read();
}
void setup() {
delay(5000);
//while (! Serial);
Serial.begin(115200);
Serial.println(F("Starting"));
// 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_setAdrMode(0); // turn ADR on
LMIC_setLinkCheckMode(0); // enable link check mode on
LMIC_setDrTxpow(DR_SF10, 20);
LMIC_selectSubBand(1);
// 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
GPS.begin(9600);
// Only interrested in GGA, no antenna status
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
GPS.sendCommand(PGCMD_NOANTENNA);
// Update every second
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
// Request updates on antenna status, comment out to keep quiet
// GPS.sendCommand(PGCMD_ANTENNA);
// Configure timer
timer.configure(TC_CLOCK_PRESCALER_DIV16, // prescaler
TC_COUNTER_SIZE_16BIT, // bit width of timer
TC_WAVE_GENERATION_MATCH_PWM // frequency or PWM mode
);
// Set timer period.
// Transmission speed is 9600bps, wich is about 1byte/ms
// (The GPS module isn't sending that fast, we can reliably read data with
// 5 ms polling!)
// With DIV16 prescaler, 1 ms is F_CPU/16000
timer.setPeriodMatch(F_CPU / 16000, 1, 0);
timer.setCallback(true, TC_CALLBACK_CC_CHANNEL0, timer_callback);
timer.enable(true);
delay(2000);
// Start job (sending automatically starts OTAA too)
do_send(&sendjob);
}
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.
// read data from the GPS in the 'main loop'
os_runloop_once();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment