Commit 41533333 authored by BuildTools's avatar BuildTools

Initial Commit

Push all files from Home PC to Master
parent 6dacd3bc
/*
AirQuality library v1.0
2010 Copyright (c) Seeed Technology Inc. All right reserved.
Original Author: Bruce.Qin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include"Arduino.h"
#include"AirQuality.h"
//Get the avg voltage in 5 minutes.
void AirQuality::avgVoltage()
{
if(i==150)//sum 5 minutes
{
vol_standard=temp/150;
temp=0;
Serial.print("Vol_standard in 5 minutes:");
Serial.println(vol_standard);
i=0;
}
else
{
temp+=first_vol;
i++;
}
}
void AirQuality::init(int pin)
{
_pin=pin;
pinMode(_pin,INPUT);
unsigned char i=0;
Serial.println("sys_starting...");
delay(20000);//200000
init_voltage=analogRead(_pin);
Serial.println("The init voltage is ...");
Serial.println(init_voltage);
while(init_voltage)
{
if(init_voltage<798 && init_voltage>10)// the init voltage is ok
{
first_vol=analogRead(_pin);//initialize first value
last_vol=first_vol;
vol_standard=last_vol;
Serial.println("Sensor ready.");
error=false;;
break;
}
else if(init_voltage>798||init_voltage<=10)
{
i++;
delay(60000);//60000
Serial.println("waitting sensor init..");
init_voltage=analogRead(_pin);
if(i==5)
{
i=0;
error=true;
Serial.println("Sensor Error!");
}
}
else
break;
}
//init the timer
TCCR2A=0;//normal model
TCCR2B=0x07;//set clock as 1024*(1/16M)
TIMSK2=0x01;//enable overflow interrupt
Serial.println("Test begin...");
sei();
}
int AirQuality::slope(void)
{
while(timer_index)
{
if(first_vol-last_vol>400||first_vol>700)
{
Serial.println("High pollution! Force signal active.");
timer_index=0;
avgVoltage();
return 0;
}
else if((first_vol-last_vol>400&&first_vol<700)||first_vol-vol_standard>150)
{
Serial.print("sensor_value:");
Serial.print(first_vol);
Serial.println("\t High pollution!");
timer_index=0;
avgVoltage();
return 1;
}
else if((first_vol-last_vol>200&&first_vol<700)||first_vol-vol_standard>50)
{
//Serial.println(first_vol-last_vol);
Serial.print("sensor_value:");
Serial.print(first_vol);
Serial.println("\t Low pollution!");
timer_index=0;
avgVoltage();
return 2;
}
else
{
avgVoltage();
Serial.print("sensor_value:");
Serial.print(first_vol);
Serial.println("\t Air fresh");
timer_index=0;
return 3;
}
}
return -1;
}
/*
AirQuality library v1.0
2010 Copyright (c) Seeed Technology Inc. All right reserved.
Original Author: Bruce.Qin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __AIRQUALITY_H__
#define __AIRQUALITY_H__
#include"Arduino.h"
class AirQuality
{
public:
int i ;
long vol_standard;
int init_voltage;
int first_vol;
int last_vol;
long temp;
int counter;
boolean timer_index;
boolean error;
void init(int pin);
int slope(void);
private:
int _pin;
void avgVoltage(void);
};
#endif
## Grove Air Quality Sensor
-------------------------------------------------------------
![](https://statics3.seeedstudio.com/images/101020021%201.jpg)
[Grove Air Quality Sensor](https://www.seeedstudio.com/Grove-Air-quality-sensor-p-1065.html)
This sensor is designed for comprehensive monitoring of indoor air conditions.
It's responsive to a wide scope of harmful gases such as carbon monoxide, alcohol, acetone, thinner, formaldehyde and so on.
Due to the measuring mechanism, this sensor can not output specific data to describe target gases' concentrations quantitatively.
But it's still competent enough to be used in applications that require only qualitative results, like auto refresher sprayers and auto air cycling systems.
For more information, please refer to the [wiki page][1]
----
This software is written by Bruce Qin for Seeed Studio<br>
and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check license.txt for more information.<br>
Contributing to this software is warmly welcomed. You can do this basically by<br>
[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then submitting a [pull request](https://help.github.com/articles/using-pull-requests) (follow the links above<br>
for operating guide). Adding change log and your contact into file header is encouraged.<br>
Thanks for your contribution.
Seeed Studio is an open hardware facilitation company based in Shenzhen, China. <br>
Benefiting from local manufacturing power and a convenient global logistic system, <br>
we integrate resources to serve a new era of innovation. Seeed also works with <br>
global distributors and partners to push the open hardware movement.<br>
[1]:http://wiki.seeedstudio.com/Grove-Air_Quality_Sensor_v1.3
[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Grove_Air_quality_Sensor)](https://github.com/igrigorik/ga-beacon)
/*
AirQuality Demo V1.0.
connect to A1 to start testing. it will needs about 20s to start
* By: http://www.seeedstudio.com
*/
#include"AirQuality.h"
#include"Arduino.h"
AirQuality airqualitysensor;
int current_quality =-1;
void setup()
{
Serial.begin(9600);
airqualitysensor.init(A0);
}
void loop()
{
current_quality=airqualitysensor.slope();
if (current_quality >= 0)// if a valid data returned.
{
if (current_quality==0)
Serial.println("High pollution! Force signal active");
else if (current_quality==1)
Serial.println("High pollution!");
else if (current_quality==2)
Serial.println("Low pollution!");
else if (current_quality ==3)
Serial.println("Fresh air");
}
}
ISR(TIMER2_OVF_vect)
{
if(airqualitysensor.counter==122)//set 2 seconds as a detected duty
{
airqualitysensor.last_vol=airqualitysensor.first_vol;
airqualitysensor.first_vol=analogRead(A0);
airqualitysensor.counter=0;
airqualitysensor.timer_index=1;
PORTB=PORTB^0x20;
}
else
{
airqualitysensor.counter++;
}
}
#######################################
# Syntax Coloring Map For
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
i KEYWORD1
vol_standard KEYWORD1
init_voltage KEYWORD1
first_vol KEYWORD1
last_vol KEYWORD1
temp KEYWORD1
counter KEYWORD1
timer_index KEYWORD1
error KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
init KEYWORD2
slope KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
\ No newline at end of file
name=Grove - Air quality sensor
version=1.0.1
author=Seeed Studio
maintainer=Seeed Studio <techsupport@seeed.cc>
sentence=Arduino library to control Grove Air Quality Sensor.
paragraph=Arduino library to control Grove Air Quality Sensor.
category=Sensors
url=https://github.com/Seeed-Studio/Grove_Air_quality_Sensor
architectures=avr
includes=AirQuality.h
The MIT License (MIT)
Copyright (c) 2014 Seeed Technology Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
This diff is collapsed.
DISCLAIMER:
Please note that the software is provided AS IS and we cannot
provide support for optimizations, adaptations, integration,
ports to other platforms or device drivers!
==============================================================================
LMIC VERSION 1.4 (17-Mar-2015)
-------------------------------
- changed API: inverted port indicator flag in LMIC.txrxFlags
(now TXRX_PORT, previously TXRX_NOPORT)
- fixed offset OFF_CFLIST constant
- changed CRC-16 algorithm for beacons to CCITT(XMODEM) polynomial
- fixed radio driver (low data rate optimization for SF11+SF12 only for BW125)
- fixed timer rollover handling in job queue
==============================================================================
LMIC VERSION 1.5 (8-May-2015)
------------------------------
- fixed condition in convFreq()
- fixed freq*100 bug and freq==0 bug for CFList
- fixed TX scheduling bug
- better support for GNU compiler toolchain
==============================================================================
/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
*
* 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.
*
* This example transmits data on hardcoded channel and receives data
* when not transmitting. Running this sketch on two nodes should allow
* them to communicate.
*******************************************************************************/
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#if !defined(DISABLE_INVERT_IQ_ON_RX)
#error This example requires DISABLE_INVERT_IQ_ON_RX to be set. Update \
config.h in the lmic library to set it.
#endif
// How often to send a packet. Note that this sketch bypasses the normal
// LMIC duty cycle limiting, so when you change anything in this sketch
// (payload length, frequency, spreading factor), be sure to check if
// this interval should not also be increased.
// See this spreadsheet for an easy airtime and duty cycle calculator:
// https://docs.google.com/spreadsheets/d/1voGAtQAjC1qBmaVuP1ApNKs1ekgUjavHuVQIXyYSvNc
#define TX_INTERVAL 2000
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 6,
.rxtx = LMIC_UNUSED_PIN,
.rst = 5,
.dio = {2, 3, 4},
};
// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in config.h, otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
void onEvent (ev_t ev) {
}
osjob_t txjob;
osjob_t timeoutjob;
static void tx_func (osjob_t* job);
// Transmit the given string and call the given function afterwards
void tx(const char *str, osjobcb_t func) {
os_radio(RADIO_RST); // Stop RX first
delay(1); // Wait a bit, without this os_radio below asserts, apparently because the state hasn't changed yet
LMIC.dataLen = 0;
while (*str)
LMIC.frame[LMIC.dataLen++] = *str++;
LMIC.osjob.func = func;
os_radio(RADIO_TX);
Serial.println("TX");
}
// Enable rx mode and call func when a packet is received
void rx(osjobcb_t func) {
LMIC.osjob.func = func;
LMIC.rxtime = os_getTime(); // RX _now_
// Enable "continuous" RX (e.g. without a timeout, still stops after
// receiving a packet)
os_radio(RADIO_RXON);
Serial.println("RX");
}
static void rxtimeout_func(osjob_t *job) {
digitalWrite(LED_BUILTIN, LOW); // off
}
static void rx_func (osjob_t* job) {
// Blink once to confirm reception and then keep the led on
digitalWrite(LED_BUILTIN, LOW); // off
delay(10);
digitalWrite(LED_BUILTIN, HIGH); // on
// Timeout RX (i.e. update led status) after 3 periods without RX
os_setTimedCallback(&timeoutjob, os_getTime() + ms2osticks(3*TX_INTERVAL), rxtimeout_func);
// Reschedule TX so that it should not collide with the other side's
// next TX
os_setTimedCallback(&txjob, os_getTime() + ms2osticks(TX_INTERVAL/2), tx_func);
Serial.print("Got ");
Serial.print(LMIC.dataLen);
Serial.println(" bytes");
Serial.write(LMIC.frame, LMIC.dataLen);
Serial.println();
// Restart RX
rx(rx_func);
}
static void txdone_func (osjob_t* job) {
rx(rx_func);
}
// log text to USART and toggle LED
static void tx_func (osjob_t* job) {
// say hello
tx("Hello, world!", txdone_func);
// reschedule job every TX_INTERVAL (plus a bit of random to prevent
// systematic collisions), unless packets are received, then rx_func
// will reschedule at half this time.
os_setTimedCallback(job, os_getTime() + ms2osticks(TX_INTERVAL + random(500)), tx_func);
}
// application entry point
void setup() {
Serial.begin(115200);
Serial.println("Starting");
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif
pinMode(LED_BUILTIN, OUTPUT);
// initialize runtime env
os_init();
// Set up these settings once, and use them for both TX and RX
#if defined(CFG_eu868)
// Use a frequency in the g3 which allows 10% duty cycling.
LMIC.freq = 869525000;
#elif defined(CFG_us915)
LMIC.freq = 902300000;
#endif
// Maximum TX power
LMIC.txpow = 27;
// Use a medium spread factor. This can be increased up to SF12 for
// better range, but then the interval should be (significantly)
// lowered to comply with duty cycle limits as well.
LMIC.datarate = DR_SF9;
// This sets CR 4/5, BW125 (except for DR_SF7B, which uses BW250)
LMIC.rps = updr2rps(LMIC.datarate);
Serial.println("Started");
Serial.flush();
// setup initial job
os_setCallback(&txjob, tx_func);
}
void loop() {
// execute scheduled jobs and events
os_runloop_once();
}
/*******************************************************************************
* Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
*
* 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.
*
* This example sends a valid LoRaWAN packet with payload "Hello,
* world!", using frequency and encryption settings matching those of
* the The Things Network.
*
* This uses ABP (Activation-by-personalisation), where a DevAddr and
* Session keys are preconfigured (unlike OTAA, where a DevEUI and
* application key is configured, while the DevAddr and session keys are
* assigned/generated in the over-the-air-activation procedure).
*
* Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in
* g1, 0.1% in g2), but not the TTN fair usage policy (which is probably
* violated by this sketch when left running for longer)!
*
* To use this sketch, first register your application and device with
* the things network, to set or generate a DevAddr, NwkSKey and
* AppSKey. Each device should have their own unique values for these
* fields.
*
* Do not forget to define the radio type correctly in config.h.
*
*******************************************************************************/
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
// LoRaWAN NwkSKey, network session key
// This is the default Semtech key, which is used by the early prototype TTN
// network.
static const PROGMEM u1_t NWKSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
// LoRaWAN AppSKey, application session key
// This is the default Semtech key, which is used by the early prototype TTN
// network.
static const u1_t PROGMEM APPSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
// LoRaWAN end-device address (DevAddr)
static const u4_t DEVADDR = 0x03FF0001 ; // <-- Change this address for every node!
// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in config.h, otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
static uint8_t mydata[] = "Hello, world!";
static osjob_t sendjob;
// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 60;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 6,
.rxtx = LMIC_UNUSED_PIN,
.rst = 5,
.dio = {2, 3, 4},
};
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"));
break;
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;
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;
default:
Serial.println(F("Unknown event"));
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 {
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
Serial.println(F("Packet queued"));
}
// Next TX is scheduled after TX_COMPLETE event.
}
void setup() {
Serial.begin(115200);
Serial.println(F("Starting"));
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif
// LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Set static session parameters. Instead of dynamically establishing a session
// by joining the network, precomputed session parameters are be provided.
#ifdef PROGMEM
// On AVR, these values are stored in flash and only copied to RAM
// once. Copy them to a temporary buffer here, LMIC_setSession will
// copy them into a buffer of its own again.
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif
#if defined(CFG_eu868)
// Set up the channels used by the Things Network, which corresponds
// to the defaults of most gateways. Without this, only three base
// channels from the LoRaWAN specification are used, which certainly
// works, so it is good for debugging, but can overload those
// frequencies, so be sure to configure the full frequency range of
// your network here (unless your network autoconfigures them).
// Setting up channels should happen after LMIC_setSession, as that
// configures the minimal channel set.
// NA-US channels 0-71 are configured automatically
LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI); // g-band
LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK), BAND_MILLI); // g2-band
// TTN defines an additional channel at 869.525Mhz using SF9 for class B
// devices' ping slots. LMIC does not have an easy way to define set this
// frequency and support for class B is spotty and untested, so this
// frequency is not configured here.
#elif defined(CFG_us915)
// NA-US channels 0-71 are configured automatically
// but only one group of 8 should (a subband) should be active
// TTN recommends the second sub band, 1 in a zero based count.
// https://github.com/TheThingsNetwork/gateway-conf/blob/master/US-global_conf.json
LMIC_selectSubBand(1);
#endif
// Disable link check validation
LMIC_setLinkCheckMode(0);
// TTN uses SF9 for its RX2 window.
LMIC.dn2Dr = DR_SF9;
// Set data rate and transmit power for uplink (note: txpow seems to be ignored by the library)
LMIC_setDrTxpow(DR_SF7,14);
// Start job
do_send(&sendjob);
}
void loop() {
os_runloop_once();
}
/*******************************************************************************
* Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
*
* 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.
*
* This example sends a valid LoRaWAN packet with payload "Hello,
* world!", using frequency and encryption settings matching those of
* the The Things Network.
*
* This uses OTAA (Over-the-air activation), where where a DevEUI and
* application key is configured, which are used in an over-the-air
* activation procedure where a DevAddr and session keys are
* assigned/generated for use with all further communication.
*
* Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in
* g1, 0.1% in g2), but not the TTN fair usage policy (which is probably
* violated by this sketch when left running for longer)!
* To use this sketch, first register your application and device with
* the things network, to set or generate an AppEUI, DevEUI and AppKey.
* Multiple devices can use the same AppEUI, but each device has its own
* DevEUI and AppKey.
*
* Do not forget to define the radio type correctly in config.h.
*
*******************************************************************************/
#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
// 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]={ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
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 ttnctl can be copied as-is.
// The key shown here is the semtech default key.
static const u1_t PROGMEM APPKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY, 16);}
static uint8_t mydata[] = "Hello, world!";
static osjob_t sendjob;
// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 60;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 6,
.rxtx = LMIC_UNUSED_PIN,
.rst = 5,
.dio = {2, 3, 4},
};
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"));
// Disable link check validation (automatically enabled
// during join, but not supported by TTN at this time).
LMIC_setLinkCheckMode(0);
break;
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;
default:
Serial.println(F("Unknown event"));
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 {
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
Serial.println(F("Packet queued"));
}
// Next TX is scheduled after TX_COMPLETE event.
}
void setup() {
Serial.begin(115200);
Serial.println(F("Starting"));
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif
// LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Start job (sending automatically starts OTAA too)
do_send(&sendjob);
}
void loop() {
os_runloop_once();
}
name=IBM LMIC framework
version=1.5.1
author=IBM
maintainer=Matthijs Kooijman <matthijs@stdin.nl>
sentence=Deprecated arduino port of the LMIC (LoraWAN-in-C, formerly LoraMAC-in-C) framework provided by IBM.
paragraph=This library is deprecated. Try the "MCCI LoRaWAN LMIC Library" as a drop-in replacement, or see the github page for more info.
category=Communication
url=https://github.com/matthijskooijman/arduino-lmic
architectures=*
This diff is collapsed.
This diff is collapsed.
/*******************************************************************************
* Copyright (c) 2016 Matthijs Kooijman
*
* LICENSE
*
* 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.
*******************************************************************************/
/*
* The original LMIC AES implementation integrates raw AES encryption
* with CMAC and AES-CTR in a single piece of code. Most other AES
* implementations (only) offer raw single block AES encryption, so this
* file contains an implementation of CMAC and AES-CTR, and offers the
* same API through the os_aes() function as the original AES
* implementation. This file assumes that there is an encryption
* function available with this signature:
*
* extern "C" void lmic_aes_encrypt(u1_t *data, u1_t *key);
*
* That takes a single 16-byte buffer and encrypts it wit the given
* 16-byte key.
*/
#include "../lmic/oslmic.h"
#if !defined(USE_ORIGINAL_AES)
// This should be defined elsewhere
void lmic_aes_encrypt(u1_t *data, u1_t *key);
// global area for passing parameters (aux, key)
u4_t AESAUX[16/sizeof(u4_t)];
u4_t AESKEY[16/sizeof(u4_t)];
// Shift the given buffer left one bit
static void shift_left(xref2u1_t buf, u1_t len) {
while (len--) {
u1_t next = len ? buf[1] : 0;
u1_t val = (*buf << 1);
if (next & 0x80)
val |= 1;
*buf++ = val;
}
}
// Apply RFC4493 CMAC, using AESKEY as the key. If prepend_aux is true,
// AESAUX is prepended to the message. AESAUX is used as working memory
// in any case. The CMAC result is returned in AESAUX as well.
static void os_aes_cmac(xref2u1_t buf, u2_t len, u1_t prepend_aux) {
if (prepend_aux)
lmic_aes_encrypt(AESaux, AESkey);
else
memset (AESaux, 0, 16);
while (len > 0) {
u1_t need_padding = 0;
for (u1_t i = 0; i < 16; ++i, ++buf, --len) {
if (len == 0) {
// The message is padded with 0x80 and then zeroes.
// Since zeroes are no-op for xor, we can just skip them
// and leave AESAUX unchanged for them.
AESaux[i] ^= 0x80;
need_padding = 1;
break;
}
AESaux[i] ^= *buf;
}
if (len == 0) {
// Final block, xor with K1 or K2. K1 and K2 are calculated
// by encrypting the all-zeroes block and then applying some
// shifts and xor on that.
u1_t final_key[16];
memset(final_key, 0, sizeof(final_key));
lmic_aes_encrypt(final_key, AESkey);
// Calculate K1
u1_t msb = final_key[0] & 0x80;
shift_left(final_key, sizeof(final_key));
if (msb)
final_key[sizeof(final_key)-1] ^= 0x87;
// If the final block was not complete, calculate K2 from K1
if (need_padding) {
msb = final_key[0] & 0x80;
shift_left(final_key, sizeof(final_key));
if (msb)
final_key[sizeof(final_key)-1] ^= 0x87;
}
// Xor with K1 or K2
for (u1_t i = 0; i < sizeof(final_key); ++i)
AESaux[i] ^= final_key[i];
}
lmic_aes_encrypt(AESaux, AESkey);
}
}
// Run AES-CTR using the key in AESKEY and using AESAUX as the
// counter block. The last byte of the counter block will be incremented
// for every block. The given buffer will be encrypted in place.
static void os_aes_ctr (xref2u1_t buf, u2_t len) {
u1_t ctr[16];
while (len) {
// Encrypt the counter block with the selected key
memcpy(ctr, AESaux, sizeof(ctr));
lmic_aes_encrypt(ctr, AESkey);
// Xor the payload with the resulting ciphertext
for (u1_t i = 0; i < 16 && len > 0; i++, len--, buf++)
*buf ^= ctr[i];
// Increment the block index byte
AESaux[15]++;
}
}
u4_t os_aes (u1_t mode, xref2u1_t buf, u2_t len) {
switch (mode & ~AES_MICNOAUX) {
case AES_MIC:
os_aes_cmac(buf, len, /* prepend_aux */ !(mode & AES_MICNOAUX));
return os_rmsbf4(AESaux);
case AES_ENC:
// TODO: Check / handle when len is not a multiple of 16
for (u1_t i = 0; i < len; i += 16)
lmic_aes_encrypt(buf+i, AESkey);
break;
case AES_CTR:
os_aes_ctr(buf, len);
break;
}
return 0;
}
#endif // !defined(USE_ORIGINAL_AES)
/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This the HAL to run LMIC on top of the Arduino environment.
*******************************************************************************/
#include <Arduino.h>
#include <SPI.h>
#include "../lmic.h"
#include "hal.h"
#define _GNU_SOURCE 1 // For fopencookie
#include <stdio.h>
#undef _GNU_SOURCE
// -----------------------------------------------------------------------------
// I/O
static void hal_io_init () {
// NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK
ASSERT(lmic_pins.nss != LMIC_UNUSED_PIN);
ASSERT(lmic_pins.dio[0] != LMIC_UNUSED_PIN);
ASSERT(lmic_pins.dio[1] != LMIC_UNUSED_PIN || lmic_pins.dio[2] != LMIC_UNUSED_PIN);
pinMode(lmic_pins.nss, OUTPUT);
if (lmic_pins.rxtx != LMIC_UNUSED_PIN)
pinMode(lmic_pins.rxtx, OUTPUT);
if (lmic_pins.rst != LMIC_UNUSED_PIN)
pinMode(lmic_pins.rst, OUTPUT);
pinMode(lmic_pins.dio[0], INPUT);
if (lmic_pins.dio[1] != LMIC_UNUSED_PIN)
pinMode(lmic_pins.dio[1], INPUT);
if (lmic_pins.dio[2] != LMIC_UNUSED_PIN)
pinMode(lmic_pins.dio[2], INPUT);
}
// val == 1 => tx 1
void hal_pin_rxtx (u1_t val) {
if (lmic_pins.rxtx != LMIC_UNUSED_PIN)
digitalWrite(lmic_pins.rxtx, val);
}
// set radio RST pin to given value (or keep floating!)
void hal_pin_rst (u1_t val) {
if (lmic_pins.rst == LMIC_UNUSED_PIN)
return;
if(val == 0 || val == 1) { // drive pin
pinMode(lmic_pins.rst, OUTPUT);
digitalWrite(lmic_pins.rst, val);
} else { // keep pin floating
pinMode(lmic_pins.rst, INPUT);
}
}
static bool dio_states[NUM_DIO] = {0};
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (lmic_pins.dio[i] == LMIC_UNUSED_PIN)
continue;
if (dio_states[i] != digitalRead(lmic_pins.dio[i])) {
dio_states[i] = !dio_states[i];
if (dio_states[i])
radio_irq_handler(i);
}
}
}
// -----------------------------------------------------------------------------
// SPI
static const SPISettings settings(10E6, MSBFIRST, SPI_MODE0);
static void hal_spi_init () {
SPI.begin();
}
void hal_pin_nss (u1_t val) {
if (!val)
SPI.beginTransaction(settings);
else
SPI.endTransaction();
//Serial.println(val?">>":"<<");
digitalWrite(lmic_pins.nss, val);
}
// perform SPI transaction with radio
u1_t hal_spi (u1_t out) {
u1_t res = SPI.transfer(out);
/*
Serial.print(">");
Serial.print(out, HEX);
Serial.print("<");
Serial.println(res, HEX);
*/
return res;
}
// -----------------------------------------------------------------------------
// TIME
static void hal_time_init () {
// Nothing to do
}
u4_t hal_ticks () {
// Because micros() is scaled down in this function, micros() will
// overflow before the tick timer should, causing the tick timer to
// miss a significant part of its values if not corrected. To fix
// this, the "overflow" serves as an overflow area for the micros()
// counter. It consists of three parts:
// - The US_PER_OSTICK upper bits are effectively an extension for
// the micros() counter and are added to the result of this
// function.
// - The next bit overlaps with the most significant bit of
// micros(). This is used to detect micros() overflows.
// - The remaining bits are always zero.
//
// By comparing the overlapping bit with the corresponding bit in
// the micros() return value, overflows can be detected and the
// upper bits are incremented. This is done using some clever
// bitwise operations, to remove the need for comparisons and a
// jumps, which should result in efficient code. By avoiding shifts
// other than by multiples of 8 as much as possible, this is also
// efficient on AVR (which only has 1-bit shifts).
static uint8_t overflow = 0;
// Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,
// the others will be the lower bits of our return value.
uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;
// Most significant byte of scaled
uint8_t msb = scaled >> 24;
// Mask pointing to the overlapping bit in msb and overflow.
const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));
// Update overflow. If the overlapping bit is different
// between overflow and msb, it is added to the stored value,
// so the overlapping bit becomes equal again and, if it changed
// from 1 to 0, the upper bits are incremented.
overflow += (msb ^ overflow) & mask;
// Return the scaled value with the upper bits of stored added. The
// overlapping bit will be equal and the lower bits will be 0, so
// bitwise or is a no-op for them.
return scaled | ((uint32_t)overflow << 24);
// 0 leads to correct, but overly complex code (it could just return
// micros() unmodified), 8 leaves no room for the overlapping bit.
static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value");
}
// Returns the number of ticks until time. Negative values indicate that
// time has already passed.
static s4_t delta_time(u4_t time) {
return (s4_t)(time - hal_ticks());
}
void hal_waitUntil (u4_t time) {
s4_t delta = delta_time(time);
// From delayMicroseconds docs: Currently, the largest value that
// will produce an accurate delay is 16383.
while (delta > (16000 / US_PER_OSTICK)) {
delay(16);
delta -= (16000 / US_PER_OSTICK);
}
if (delta > 0)
delayMicroseconds(delta * US_PER_OSTICK);
}
// check and rewind for target time
u1_t hal_checkTimer (u4_t time) {
// No need to schedule wakeup, since we're not sleeping
return delta_time(time) <= 0;
}
static uint8_t irqlevel = 0;
void hal_disableIRQs () {
noInterrupts();
irqlevel++;
}
void hal_enableIRQs () {
if(--irqlevel == 0) {
interrupts();
// Instead of using proper interrupts (which are a bit tricky
// and/or not available on all pins on AVR), just poll the pin
// values. Since os_runloop disables and re-enables interrupts,
// putting this here makes sure we check at least once every
// loop.
//
// As an additional bonus, this prevents the can of worms that
// we would otherwise get for running SPI transfers inside ISRs
hal_io_check();
}
}
void hal_sleep () {
// Not implemented
}
// -----------------------------------------------------------------------------
#if defined(LMIC_PRINTF_TO)
#if defined(__AVR__)
// On AVR, use the AVR-specific fdev_setup_stream to redirect stdout
static int uart_putchar (char c, FILE *)
{
LMIC_PRINTF_TO.write(c) ;
return 0 ;
}
void hal_printf_init() {
// create a FILE structure to reference our UART output function
static FILE uartout;
memset(&uartout, 0, sizeof(uartout));
// fill in the UART file descriptor with pointer to writer.
fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
// The uart is the standard output device STDOUT.
stdout = &uartout ;
}
#else
// On non-AVR platforms, use the somewhat more complex "cookie"-based
// approach to custom streams. This is a GNU-specific extension to libc.
static ssize_t uart_putchar (void *, const char *buf, size_t len) {
auto res = LMIC_PRINTF_TO.write(buf, len);
// Since the C interface has no meaningful way to flush (fflush() is a
// no-op on AVR since stdio does not introduce any buffering), just flush
// every byte.
LMIC_PRINTF_TO.flush();
return res;
}
static cookie_io_functions_t functions = {
.read = NULL,
.write = uart_putchar,
.seek = NULL,
.close = NULL
};
void hal_printf_init() {
stdout = fopencookie(NULL, "w", functions);
// Disable buffering, so the callbacks get called right away
setbuf(stdout, nullptr);
}
#endif // !defined(__AVR__)
#endif // defined(LMIC_PRINTF_TO)
void hal_init () {
// configure radio I/O and interrupt handler
hal_io_init();
// configure radio SPI
hal_spi_init();
// configure timer and interrupt handler
hal_time_init();
#if defined(LMIC_PRINTF_TO)
// printf support
hal_printf_init();
#endif
}
void hal_failed (const char *file, u2_t line) {
#if defined(LMIC_FAILURE_TO)
LMIC_FAILURE_TO.println("FAILURE ");
LMIC_FAILURE_TO.print(file);
LMIC_FAILURE_TO.print(':');
LMIC_FAILURE_TO.println(line);
LMIC_FAILURE_TO.flush();
#endif
hal_disableIRQs();
while(1);
}
/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This the HAL to run LMIC on top of the Arduino environment.
*******************************************************************************/
#ifndef _hal_hal_h_
#define _hal_hal_h_
static const int NUM_DIO = 3;
struct lmic_pinmap {
u1_t nss;
u1_t rxtx;
u1_t rst;
u1_t dio[NUM_DIO];
};
// Use this for any unused pins.
const u1_t LMIC_UNUSED_PIN = 0xff;
// Declared here, to be defined an initialized by the application
extern const lmic_pinmap lmic_pins;
#endif // _hal_hal_h_
#ifdef __cplusplus
extern "C"{
#endif
#include "lmic/lmic.h"
#ifdef __cplusplus
}
#endif
#ifndef _lmic_config_h_
#define _lmic_config_h_
// In the original LMIC code, these config values were defined on the
// gcc commandline. Since Arduino does not allow easily modifying the
// compiler commandline, use this file instead.
#define CFG_eu868 1
//#define CFG_us915 1
// This is the SX1272/SX1273 radio, which is also used on the HopeRF
// RFM92 boards.
//#define CFG_sx1272_radio 1
// This is the SX1276/SX1277/SX1278/SX1279 radio, which is also used on
// the HopeRF RFM95 boards.
#define CFG_sx1276_radio 1
// 16 μs per tick
// LMIC requires ticks to be 15.5μs - 100 μs long
#define US_PER_OSTICK_EXPONENT 4
#define US_PER_OSTICK (1 << US_PER_OSTICK_EXPONENT)
#define OSTICKS_PER_SEC (1000000 / US_PER_OSTICK)
// Set this to 1 to enable some basic debug output (using printf) about
// RF settings used during transmission and reception. Set to 2 to
// enable more verbose output. Make sure that printf is actually
// configured (e.g. on AVR it is not by default), otherwise using it can
// cause crashing.
#define LMIC_DEBUG_LEVEL 0
// Enable this to allow using printf() to print to the given serial port
// (or any other Print object). This can be easy for debugging. The
// current implementation only works on AVR, though.
//#define LMIC_PRINTF_TO Serial
// Any runtime assertion failures are printed to this serial port (or
// any other Print object). If this is unset, any failures just silently
// halt execution.
#define LMIC_FAILURE_TO Serial
// Uncomment this to disable all code related to joining
//#define DISABLE_JOIN
// Uncomment this to disable all code related to ping
//#define DISABLE_PING
// Uncomment this to disable all code related to beacon tracking.
// Requires ping to be disabled too
//#define DISABLE_BEACONS
// Uncomment these to disable the corresponding MAC commands.
// Class A
//#define DISABLE_MCMD_DCAP_REQ // duty cycle cap
//#define DISABLE_MCMD_DN2P_SET // 2nd DN window param
//#define DISABLE_MCMD_SNCH_REQ // set new channel
// Class B
//#define DISABLE_MCMD_PING_SET // set ping freq, automatically disabled by DISABLE_PING
//#define DISABLE_MCMD_BCNI_ANS // next beacon start, automatical disabled by DISABLE_BEACON
// In LoRaWAN, a gateway applies I/Q inversion on TX, and nodes do the
// same on RX. This ensures that gateways can talk to nodes and vice
// versa, but gateways will not hear other gateways and nodes will not
// hear other nodes. By uncommenting this macro, this inversion is
// disabled and this node can hear other nodes. If two nodes both have
// this macro set, they can talk to each other (but they can no longer
// hear gateways). This should probably only be used when debugging
// and/or when talking to the radio directly (e.g. like in the "raw"
// example).
//#define DISABLE_INVERT_IQ_ON_RX
// This allows choosing between multiple included AES implementations.
// Make sure exactly one of these is uncommented.
//
// This selects the original AES implementation included LMIC. This
// implementation is optimized for speed on 32-bit processors using
// fairly big lookup tables, but it takes up big amounts of flash on the
// AVR architecture.
// #define USE_ORIGINAL_AES
//
// This selects the AES implementation written by Ideetroon for their
// own LoRaWAN library. It also uses lookup tables, but smaller
// byte-oriented ones, making it use a lot less flash space (but it is
// also about twice as slow as the original).
#define USE_IDEETRON_AES
#endif // _lmic_config_h_
/*******************************************************************************
* Copyright (c) 2014-2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Zurich Research Lab - initial API, implementation and documentation
*******************************************************************************/
#ifndef _hal_hpp_
#define _hal_hpp_
#ifdef __cplusplus
extern "C"{
#endif
/*
* initialize hardware (IO, SPI, TIMER, IRQ).
*/
void hal_init (void);
/*
* drive radio NSS pin (0=low, 1=high).
*/
void hal_pin_nss (u1_t val);
/*
* drive radio RX/TX pins (0=rx, 1=tx).
*/
void hal_pin_rxtx (u1_t val);
/*
* control radio RST pin (0=low, 1=high, 2=floating)
*/
void hal_pin_rst (u1_t val);
/*
* perform 8-bit SPI transaction with radio.
* - write given byte 'outval'
* - read byte and return value
*/
u1_t hal_spi (u1_t outval);
/*
* disable all CPU interrupts.
* - might be invoked nested
* - will be followed by matching call to hal_enableIRQs()
*/
void hal_disableIRQs (void);
/*
* enable CPU interrupts.
*/
void hal_enableIRQs (void);
/*
* put system and CPU in low-power mode, sleep until interrupt.
*/
void hal_sleep (void);
/*
* return 32-bit system time in ticks.
*/
u4_t hal_ticks (void);
/*
* busy-wait until specified timestamp (in ticks) is reached.
*/
void hal_waitUntil (u4_t time);
/*
* check and rewind timer for target time.
* - return 1 if target time is close
* - otherwise rewind timer for target time or full period and return 0
*/
u1_t hal_checkTimer (u4_t targettime);
/*
* perform fatal failure action.
* - called by assertions
* - action could be HALT or reboot
*/
void hal_failed (const char *file, u2_t line);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // _hal_hpp_
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*******************************************************************************
* Copyright (c) 2014-2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Zurich Research Lab - initial API, implementation and documentation
*******************************************************************************/
#include "lmic.h"
#include <stdbool.h>
// Output definitions of inline functions
extern inline u1_t table_get_u1(const u1_t *table, size_t index);
extern inline s1_t table_get_s1(const s1_t *table, size_t index);
extern inline u2_t table_get_u2(const u2_t *table, size_t index);
extern inline s2_t table_get_s2(const s2_t *table, size_t index);
extern inline u4_t table_get_u4(const u4_t *table, size_t index);
extern inline s4_t table_get_s4(const s4_t *table, size_t index);
extern inline ostime_t table_get_ostime(const ostime_t *table, size_t index);
// RUNTIME STATE
static struct {
osjob_t* scheduledjobs;
osjob_t* runnablejobs;
} OS;
void os_init () {
memset(&OS, 0x00, sizeof(OS));
hal_init();
radio_init();
LMIC_init();
}
ostime_t os_getTime () {
return hal_ticks();
}
static u1_t unlinkjob (osjob_t** pnext, osjob_t* job) {
for( ; *pnext; pnext = &((*pnext)->next)) {
if(*pnext == job) { // unlink
*pnext = job->next;
return 1;
}
}
return 0;
}
// clear scheduled job
void os_clearCallback (osjob_t* job) {
hal_disableIRQs();
u1_t res = unlinkjob(&OS.scheduledjobs, job) || unlinkjob(&OS.runnablejobs, job);
hal_enableIRQs();
#if LMIC_DEBUG_LEVEL > 1
if (res)
lmic_printf("%lu: Cleared job %p\n", os_getTime(), job);
#endif
}
// schedule immediately runnable job
void os_setCallback (osjob_t* job, osjobcb_t cb) {
osjob_t** pnext;
hal_disableIRQs();
// remove if job was already queued
os_clearCallback(job);
// fill-in job
job->func = cb;
job->next = NULL;
// add to end of run queue
for(pnext=&OS.runnablejobs; *pnext; pnext=&((*pnext)->next));
*pnext = job;
hal_enableIRQs();
#if LMIC_DEBUG_LEVEL > 1
lmic_printf("%lu: Scheduled job %p, cb %p ASAP\n", os_getTime(), job, cb);
#endif
}
// schedule timed job
void os_setTimedCallback (osjob_t* job, ostime_t time, osjobcb_t cb) {
osjob_t** pnext;
hal_disableIRQs();
// remove if job was already queued
os_clearCallback(job);
// fill-in job
job->deadline = time;
job->func = cb;
job->next = NULL;
// insert into schedule
for(pnext=&OS.scheduledjobs; *pnext; pnext=&((*pnext)->next)) {
if((*pnext)->deadline - time > 0) { // (cmp diff, not abs!)
// enqueue before next element and stop
job->next = *pnext;
break;
}
}
*pnext = job;
hal_enableIRQs();
#if LMIC_DEBUG_LEVEL > 1
lmic_printf("%lu: Scheduled job %p, cb %p at %lu\n", os_getTime(), job, cb, time);
#endif
}
// execute jobs from timer and from run queue
void os_runloop () {
while(1) {
os_runloop_once();
}
}
void os_runloop_once() {
#if LMIC_DEBUG_LEVEL > 1
bool has_deadline = false;
#endif
osjob_t* j = NULL;
hal_disableIRQs();
// check for runnable jobs
if(OS.runnablejobs) {
j = OS.runnablejobs;
OS.runnablejobs = j->next;
} else if(OS.scheduledjobs && hal_checkTimer(OS.scheduledjobs->deadline)) { // check for expired timed jobs
j = OS.scheduledjobs;
OS.scheduledjobs = j->next;
#if LMIC_DEBUG_LEVEL > 1
has_deadline = true;
#endif
} else { // nothing pending
hal_sleep(); // wake by irq (timer already restarted)
}
hal_enableIRQs();
if(j) { // run job callback
#if LMIC_DEBUG_LEVEL > 1
lmic_printf("%lu: Running job %p, cb %p, deadline %lu\n", os_getTime(), j, j->func, has_deadline ? j->deadline : 0);
#endif
j->func(j);
}
}
/*******************************************************************************
* Copyright (c) 2014-2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Zurich Research Lab - initial API, implementation and documentation
*******************************************************************************/
//! \file
#ifndef _oslmic_h_
#define _oslmic_h_
// Dependencies required for the LoRa MAC in C to run.
// These settings can be adapted to the underlying system.
// You should not, however, change the lmic.[hc]
#include "config.h"
#include <stdint.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C"{
#endif
//================================================================================
//================================================================================
// Target platform as C library
typedef uint8_t bit_t;
typedef uint8_t u1_t;
typedef int8_t s1_t;
typedef uint16_t u2_t;
typedef int16_t s2_t;
typedef uint32_t u4_t;
typedef int32_t s4_t;
typedef unsigned int uint;
typedef const char* str_t;
#include <string.h>
#include "hal.h"
#define EV(a,b,c) /**/
#define DO_DEVDB(field1,field2) /**/
#if !defined(CFG_noassert)
#define ASSERT(cond) if(!(cond)) hal_failed(__FILE__, __LINE__)
#else
#define ASSERT(cond) /**/
#endif
#define os_clearMem(a,b) memset(a,0,b)
#define os_copyMem(a,b,c) memcpy(a,b,c)
typedef struct osjob_t osjob_t;
typedef struct band_t band_t;
typedef struct chnldef_t chnldef_t;
typedef struct rxsched_t rxsched_t;
typedef struct bcninfo_t bcninfo_t;
typedef const u1_t* xref2cu1_t;
typedef u1_t* xref2u1_t;
#define TYPEDEF_xref2rps_t typedef rps_t* xref2rps_t
#define TYPEDEF_xref2rxsched_t typedef rxsched_t* xref2rxsched_t
#define TYPEDEF_xref2chnldef_t typedef chnldef_t* xref2chnldef_t
#define TYPEDEF_xref2band_t typedef band_t* xref2band_t
#define TYPEDEF_xref2osjob_t typedef osjob_t* xref2osjob_t
#define SIZEOFEXPR(x) sizeof(x)
#define ON_LMIC_EVENT(ev) onEvent(ev)
#define DECL_ON_LMIC_EVENT void onEvent(ev_t e)
extern u4_t AESAUX[];
extern u4_t AESKEY[];
#define AESkey ((u1_t*)AESKEY)
#define AESaux ((u1_t*)AESAUX)
#define FUNC_ADDR(func) (&(func))
u1_t radio_rand1 (void);
#define os_getRndU1() radio_rand1()
#define DEFINE_LMIC struct lmic_t LMIC
#define DECLARE_LMIC extern struct lmic_t LMIC
void radio_init (void);
void radio_irq_handler (u1_t dio);
void os_init (void);
void os_runloop (void);
void os_runloop_once (void);
//================================================================================
#ifndef RX_RAMPUP
#define RX_RAMPUP (us2osticks(2000))
#endif
#ifndef TX_RAMPUP
#define TX_RAMPUP (us2osticks(2000))
#endif
#ifndef OSTICKS_PER_SEC
#define OSTICKS_PER_SEC 32768
#elif OSTICKS_PER_SEC < 10000 || OSTICKS_PER_SEC > 64516
#error Illegal OSTICKS_PER_SEC - must be in range [10000:64516]. One tick must be 15.5us .. 100us long.
#endif
typedef s4_t ostime_t;
#if !HAS_ostick_conv
#define us2osticks(us) ((ostime_t)( ((int64_t)(us) * OSTICKS_PER_SEC) / 1000000))
#define ms2osticks(ms) ((ostime_t)( ((int64_t)(ms) * OSTICKS_PER_SEC) / 1000))
#define sec2osticks(sec) ((ostime_t)( (int64_t)(sec) * OSTICKS_PER_SEC))
#define osticks2ms(os) ((s4_t)(((os)*(int64_t)1000 ) / OSTICKS_PER_SEC))
#define osticks2us(os) ((s4_t)(((os)*(int64_t)1000000 ) / OSTICKS_PER_SEC))
// Special versions
#define us2osticksCeil(us) ((ostime_t)( ((int64_t)(us) * OSTICKS_PER_SEC + 999999) / 1000000))
#define us2osticksRound(us) ((ostime_t)( ((int64_t)(us) * OSTICKS_PER_SEC + 500000) / 1000000))
#define ms2osticksCeil(ms) ((ostime_t)( ((int64_t)(ms) * OSTICKS_PER_SEC + 999) / 1000))
#define ms2osticksRound(ms) ((ostime_t)( ((int64_t)(ms) * OSTICKS_PER_SEC + 500) / 1000))
#endif
struct osjob_t; // fwd decl.
typedef void (*osjobcb_t) (struct osjob_t*);
struct osjob_t {
struct osjob_t* next;
ostime_t deadline;
osjobcb_t func;
};
TYPEDEF_xref2osjob_t;
#ifndef HAS_os_calls
#ifndef os_getDevKey
void os_getDevKey (xref2u1_t buf);
#endif
#ifndef os_getArtEui
void os_getArtEui (xref2u1_t buf);
#endif
#ifndef os_getDevEui
void os_getDevEui (xref2u1_t buf);
#endif
#ifndef os_setCallback
void os_setCallback (xref2osjob_t job, osjobcb_t cb);
#endif
#ifndef os_setTimedCallback
void os_setTimedCallback (xref2osjob_t job, ostime_t time, osjobcb_t cb);
#endif
#ifndef os_clearCallback
void os_clearCallback (xref2osjob_t job);
#endif
#ifndef os_getTime
ostime_t os_getTime (void);
#endif
#ifndef os_getTimeSecs
uint os_getTimeSecs (void);
#endif
#ifndef os_radio
void os_radio (u1_t mode);
#endif
#ifndef os_getBattLevel
u1_t os_getBattLevel (void);
#endif
#ifndef os_rlsbf4
//! Read 32-bit quantity from given pointer in little endian byte order.
u4_t os_rlsbf4 (xref2cu1_t buf);
#endif
#ifndef os_wlsbf4
//! Write 32-bit quntity into buffer in little endian byte order.
void os_wlsbf4 (xref2u1_t buf, u4_t value);
#endif
#ifndef os_rmsbf4
//! Read 32-bit quantity from given pointer in big endian byte order.
u4_t os_rmsbf4 (xref2cu1_t buf);
#endif
#ifndef os_wmsbf4
//! Write 32-bit quntity into buffer in big endian byte order.
void os_wmsbf4 (xref2u1_t buf, u4_t value);
#endif
#ifndef os_rlsbf2
//! Read 16-bit quantity from given pointer in little endian byte order.
u2_t os_rlsbf2 (xref2cu1_t buf);
#endif
#ifndef os_wlsbf2
//! Write 16-bit quntity into buffer in little endian byte order.
void os_wlsbf2 (xref2u1_t buf, u2_t value);
#endif
//! Get random number (default impl for u2_t).
#ifndef os_getRndU2
#define os_getRndU2() ((u2_t)((os_getRndU1()<<8)|os_getRndU1()))
#endif
#ifndef os_crc16
u2_t os_crc16 (xref2u1_t d, uint len);
#endif
#endif // !HAS_os_calls
// ======================================================================
// Table support
// These macros for defining a table of constants and retrieving values
// from it makes it easier for other platforms (like AVR) to optimize
// table accesses.
// Use CONST_TABLE() whenever declaring or defining a table, and
// TABLE_GET_xx whenever accessing its values. The actual name of the
// declared variable will be modified to prevent accidental direct
// access. The accessor macros forward to an inline function to allow
// proper type checking of the array element type.
// Helper to add a prefix to the table name
#define RESOLVE_TABLE(table) constant_table_ ## table
// Accessors for table elements
#define TABLE_GET_U1(table, index) table_get_u1(RESOLVE_TABLE(table), index)
#define TABLE_GET_S1(table, index) table_get_s1(RESOLVE_TABLE(table), index)
#define TABLE_GET_U2(table, index) table_get_u2(RESOLVE_TABLE(table), index)
#define TABLE_GET_S2(table, index) table_get_s2(RESOLVE_TABLE(table), index)
#define TABLE_GET_U4(table, index) table_get_u4(RESOLVE_TABLE(table), index)
#define TABLE_GET_S4(table, index) table_get_s4(RESOLVE_TABLE(table), index)
#define TABLE_GET_OSTIME(table, index) table_get_ostime(RESOLVE_TABLE(table), index)
#define TABLE_GET_U1_TWODIM(table, index1, index2) table_get_u1(RESOLVE_TABLE(table)[index1], index2)
#if defined(__AVR__)
#include <avr/pgmspace.h>
// Macro to define the getter functions. This loads data from
// progmem using pgm_read_xx, or accesses memory directly when the
// index is a constant so gcc can optimize it away;
#define TABLE_GETTER(postfix, type, pgm_type) \
inline type table_get ## postfix(const type *table, size_t index) { \
if (__builtin_constant_p(table[index])) \
return table[index]; \
return pgm_read_ ## pgm_type(&table[index]); \
}
TABLE_GETTER(_u1, u1_t, byte);
TABLE_GETTER(_s1, s1_t, byte);
TABLE_GETTER(_u2, u2_t, word);
TABLE_GETTER(_s2, s2_t, word);
TABLE_GETTER(_u4, u4_t, dword);
TABLE_GETTER(_s4, s4_t, dword);
// This assumes ostime_t is 4 bytes, so error out if it is not
typedef int check_sizeof_ostime_t[(sizeof(ostime_t) == 4) ? 0 : -1];
TABLE_GETTER(_ostime, ostime_t, dword);
// For AVR, store constants in PROGMEM, saving on RAM usage
#define CONST_TABLE(type, name) const type PROGMEM RESOLVE_TABLE(name)
#define lmic_printf(fmt, ...) printf_P(PSTR(fmt), ## __VA_ARGS__)
#else
inline u1_t table_get_u1(const u1_t *table, size_t index) { return table[index]; }
inline s1_t table_get_s1(const s1_t *table, size_t index) { return table[index]; }
inline u2_t table_get_u2(const u2_t *table, size_t index) { return table[index]; }
inline s2_t table_get_s2(const s2_t *table, size_t index) { return table[index]; }
inline u4_t table_get_u4(const u4_t *table, size_t index) { return table[index]; }
inline s4_t table_get_s4(const s4_t *table, size_t index) { return table[index]; }
inline ostime_t table_get_ostime(const ostime_t *table, size_t index) { return table[index]; }
// Declare a table
#define CONST_TABLE(type, name) const type RESOLVE_TABLE(name)
#define lmic_printf printf
#endif
// ======================================================================
// AES support
// !!Keep in sync with lorabase.hpp!!
#ifndef AES_ENC // if AES_ENC is defined as macro all other values must be too
#define AES_ENC 0x00
#define AES_DEC 0x01
#define AES_MIC 0x02
#define AES_CTR 0x04
#define AES_MICNOAUX 0x08
#endif
#ifndef AESkey // if AESkey is defined as macro all other values must be too
extern xref2u1_t AESkey;
extern xref2u1_t AESaux;
#endif
#ifndef os_aes
u4_t os_aes (u1_t mode, xref2u1_t buf, u2_t len);
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#endif // _oslmic_h_
This diff is collapsed.
This diff is collapsed.
/*
ReadField
Description: Demonstates reading from a public channel which doesn't not require an API key and reading from a private channel which does requires a read API key.
The value read from the public channel is the current outside temperature at MathWorks headquaters in Natick, MA. The value from the
private channel is an example counter that increments every 10 seconds.
Hardware: Arduino Ethernet
!!! IMPORTANT - Modify the secrets.h file for this project with your network connection and ThingSpeak channel details. !!!
Note:
- Requires the Ethernet library
ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize, and
analyze live data streams in the cloud. Visit https://www.thingspeak.com to sign up for a free account and create a channel.
Documentation for the ThingSpeak Communication Library for Arduino is in the README.md folder where the library was installed.
See https://www.mathworks.com/help/thingspeak/index.html for the full ThingSpeak documentation.
For licensing information, see the accompanying license file.
Copyright 2020, The MathWorks, Inc.
*/
#include <Ethernet.h>
#include "secrets.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros
byte mac[] = SECRET_MAC;
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
EthernetClient client;
// Weather station channel details
unsigned long weatherStationChannelNumber = SECRET_CH_ID_WEATHER_STATION;
unsigned int temperatureFieldNumber = 4;
// Counting channel details
unsigned long counterChannelNumber = SECRET_CH_ID_COUNTER;
const char * myCounterReadAPIKey = SECRET_READ_APIKEY_COUNTER;
unsigned int counterFieldNumber = 1;
void setup() {
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(115200); //Initialize serial
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo native USB port only
}
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
int statusCode = 0;
// Read in field 4 of the public channel recording the temperature
float temperatureInF = ThingSpeak.readFloatField(weatherStationChannelNumber, temperatureFieldNumber);
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.getLastReadStatus();
if(statusCode == 200){
Serial.println("Temperature at MathWorks HQ: " + String(temperatureInF) + " deg F");
}
else{
Serial.println("Problem reading channel. HTTP error code " + String(statusCode));
}
delay(15000); // No need to read the temperature too often.
// Read in field 1 of the private channel which is a counter
long count = ThingSpeak.readLongField(counterChannelNumber, counterFieldNumber, myCounterReadAPIKey);
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.getLastReadStatus();
if(statusCode == 200){
Serial.println("Counter: " + String(count));
}
else{
Serial.println("Problem reading channel. HTTP error code " + String(statusCode));
}
delay(15000); // No need to read the counter too often.
}
// Use this file to store all of the private credentials
// and connection details
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
#define SECRET_MAC {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F}
#define SECRET_CH_ID_WEATHER_STATION 12397 //MathWorks weather station
#define SECRET_CH_ID_COUNTER 298725 //Test channel for counting
#define SECRET_READ_APIKEY_COUNTER "SODG0O2UZVGKWAWG" //API Key for Test channel
/*
WriteMultipleFields
Description: Writes values to fields 1,2,3 and 4 in a single ThingSpeak update every 20 seconds.
Hardware: Arduino Ethernet
!!! IMPORTANT - Modify the secrets.h file for this project with your network connection and ThingSpeak channel details. !!!
Note:
- Requires the Ethernet library
ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize, and
analyze live data streams in the cloud. Visit https://www.thingspeak.com to sign up for a free account and create a channel.
Documentation for the ThingSpeak Communication Library for Arduino is in the README.md folder where the library was installed.
See https://www.mathworks.com/help/thingspeak/index.html for the full ThingSpeak documentation.
For licensing information, see the accompanying license file.
Copyright 2020, The MathWorks, Inc.
*/
#include <Ethernet.h>
#include "secrets.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros
byte mac[] = SECRET_MAC;
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
EthernetClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
// Initialize our values
int number1 = 0;
int number2 = random(0,100);
int number3 = random(0,100);
int number4 = random(0,100);
void setup() {
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(115200); //Initialize serial
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo native USB port only
}
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
// set the fields with the values
ThingSpeak.setField(1, number1);
ThingSpeak.setField(2, number2);
ThingSpeak.setField(3, number3);
ThingSpeak.setField(4, number4);
// write to the ThingSpeak channel
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
// change the values
number1++;
if(number1 > 99){
number1 = 0;
}
number2 = random(0,100);
number3 = random(0,100);
number4 = random(0,100);
delay(20000); // Wait 20 seconds to update the channel again
}
// Use this file to store all of the private credentials
// and connection details
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
#define SECRET_MAC {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F}
#define SECRET_CH_ID 000000 // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "XYZ" // replace XYZ with your channel write API Key
/*
WriteSingleField
Description: Writes a value to a channel on ThingSpeak every 20 seconds.
Hardware: Arduino Ethernet
!!! IMPORTANT - Modify the secrets.h file for this project with your network connection and ThingSpeak channel details. !!!
Note:
- Requires the Ethernet library
ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize, and
analyze live data streams in the cloud. Visit https://www.thingspeak.com to sign up for a free account and create a channel.
Documentation for the ThingSpeak Communication Library for Arduino is in the README.md folder where the library was installed.
See https://www.mathworks.com/help/thingspeak/index.html for the full ThingSpeak documentation.
For licensing information, see the accompanying license file.
Copyright 2020, The MathWorks, Inc.
*/
#include <Ethernet.h>
#include "secrets.h"
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros
byte mac[] = SECRET_MAC;
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
EthernetClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
int number = 0;
void setup() {
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(115200); //Initialize serial
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo native USB port only
}
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
} else {
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeField(myChannelNumber, 1, number, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
// change the value
number++;
if(number > 99){
number = 0;
}
delay(20000); // Wait 20 seconds to update the channel again
}
// Use this file to store all of the private credentials
// and connection details
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
#define SECRET_MAC {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F}
#define SECRET_CH_ID 000000 // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "XYZ" // replace XYZ with your channel write API Key
This diff is collapsed.
// Use this file to store all of the private credentials
// and connection details
#define SECRET_CH_ID 000000 // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "XYZ" // replace XYZ with your channel write API Key
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment