From 5e5f979122418a8a8995ba85b4740760e50b5740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Wed, 15 Apr 2015 21:34:02 +0200 Subject: [PATCH 01/79] Updated with input from Bruce Lacey --- .../examples/MysensorMicro/MysensorMicro.ino | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino index c25fac2..f78d819 100644 --- a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino +++ b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino @@ -1,9 +1,9 @@ -// Default sensor sketch for MySensor Micro module +// Default sensor sketch for Sensebender Micro module // Act as a temperature / humidity sensor by default. // // If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals // -// Battery voltage is repported as child sensorId 199, as well as battery percentage +// Battery voltage is repported as child sensorId 199, as well as battery percentage (Internal message) #include @@ -52,6 +52,7 @@ MyMessage msgBattery(CHILD_ID_BATT, V_VOLTAGE); // Global settings int measureCount = 0; +boolean isMetric = true; // Storage of old measurements float lastTemperature = -100; @@ -70,7 +71,7 @@ void setup() { pinMode(TEST_PIN,INPUT); digitalWrite(TEST_PIN, HIGH); // Enable pullup if (!digitalRead(TEST_PIN)) testMode(); - + digitalWrite(TEST_PIN,LOW); digitalWrite(LED_PIN, HIGH); @@ -84,13 +85,14 @@ void setup() { humiditySensor.begin(); - gw.sendSketchInfo("MysensorMicro", "1.0"); + gw.sendSketchInfo("Sensebender Micro", "1.0"); gw.present(CHILD_ID_TEMP,S_TEMP); gw.present(CHILD_ID_HUM,S_HUM); - gw.present(CHILD_ID_BATT, S_POWER); - switchClock(1< FORCE_TRANSMIT_INTERVAL ) { // force a transmission forceTransmit = true; measureCount = 0; } - + gw.process(); sendBattLevel(forceTransmit); sendTempHumidityMeasurements(forceTransmit); @@ -127,16 +133,17 @@ void sendTempHumidityMeasurements(bool force) si7021_env data = humiditySensor.getHumidityAndTemperature(); - float temperature = data.celsiusHundredths/100; + float temperature = (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths) / 100.0; int humidity = data.humidityPercent; - if (lastTemperature != temperature) { + if ((lastTemperature != temperature) | (lastHumidity != humidity)) { + Serial.print("T: ");Serial.println(temperature); + Serial.print("H: ");Serial.println(humidity); + gw.send(msgTemp.set(temperature,1)); - lastTemperature = temperature; - } - if (lastHumidity != humidity) { gw.send(msgHum.set(humidity)); + lastTemperature = temperature; lastHumidity = humidity; } } @@ -154,10 +161,10 @@ void sendBattLevel(bool force) if (vcc != lastBattery) { lastBattery = vcc; // Calculate percentage - gw.send(msgBattery.set(vcc)); + vcc = vcc - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at - long percent = vcc / 14; + long percent = vcc / 14.0; gw.sendBatteryLevel(percent); } } @@ -278,7 +285,7 @@ void testMode() while (1) // Blink OK pattern! { digitalWrite(LED_PIN, HIGH); - delay(800); + delay(200); digitalWrite(LED_PIN, LOW); delay(200); } @@ -288,10 +295,7 @@ void testMode() Serial.println(F("----> Selftest failed!")); while (1) // Blink FAILED pattern! Rappidly blinking.. { - digitalWrite(LED_PIN, HIGH); - delay(100); - digitalWrite(LED_PIN, LOW); - delay(100); } } } + From 723b023ad0c48fa61988b931df93a56e9a01ab98 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 21 Apr 2015 22:28:01 +0200 Subject: [PATCH 02/79] Added DimmableLightWithRotaryEncoder example. --- libraries/Encoder/Encoder.cpp | 10 + libraries/Encoder/Encoder.h | 942 ++++++++++++++++++ libraries/Encoder/examples/Basic/Basic.pde | 29 + .../examples/NoInterrupts/NoInterrupts.pde | 46 + .../Encoder/examples/SpeedTest/SpeedTest.pde | 113 +++ .../Encoder/examples/TwoKnobs/TwoKnobs.pde | 46 + libraries/Encoder/keywords.txt | 4 + libraries/Encoder/utility/direct_pin_read.h | 27 + libraries/Encoder/utility/interrupt_config.h | 87 ++ libraries/Encoder/utility/interrupt_pins.h | 156 +++ .../DimmableLightWithRotaryEncoderButton.ino | 243 +++++ 11 files changed, 1703 insertions(+) create mode 100644 libraries/Encoder/Encoder.cpp create mode 100644 libraries/Encoder/Encoder.h create mode 100644 libraries/Encoder/examples/Basic/Basic.pde create mode 100644 libraries/Encoder/examples/NoInterrupts/NoInterrupts.pde create mode 100644 libraries/Encoder/examples/SpeedTest/SpeedTest.pde create mode 100644 libraries/Encoder/examples/TwoKnobs/TwoKnobs.pde create mode 100644 libraries/Encoder/keywords.txt create mode 100644 libraries/Encoder/utility/direct_pin_read.h create mode 100644 libraries/Encoder/utility/interrupt_config.h create mode 100644 libraries/Encoder/utility/interrupt_pins.h create mode 100644 libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino diff --git a/libraries/Encoder/Encoder.cpp b/libraries/Encoder/Encoder.cpp new file mode 100644 index 0000000..6911b4f --- /dev/null +++ b/libraries/Encoder/Encoder.cpp @@ -0,0 +1,10 @@ + +#include "Encoder.h" + +// Yes, all the code is in the header file, to provide the user +// configure options with #define (before they include it), and +// to facilitate some crafty optimizations! + +Encoder_internal_state_t * Encoder::interruptArgs[]; + + diff --git a/libraries/Encoder/Encoder.h b/libraries/Encoder/Encoder.h new file mode 100644 index 0000000..6745eab --- /dev/null +++ b/libraries/Encoder/Encoder.h @@ -0,0 +1,942 @@ +/* Encoder Library, for measuring quadrature encoded signals + * http://www.pjrc.com/teensy/td_libs_Encoder.html + * Copyright (c) 2011,2013 PJRC.COM, LLC - Paul Stoffregen + * + * Version 1.2 - fix -2 bug in C-only code + * Version 1.1 - expand to support boards with up to 60 interrupts + * Version 1.0 - initial release + * + * 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. + */ + + +#ifndef Encoder_h_ +#define Encoder_h_ + +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" +#elif defined(WIRING) +#include "Wiring.h" +#else +#include "WProgram.h" +#include "pins_arduino.h" +#endif + +#include "utility/direct_pin_read.h" + +#if defined(ENCODER_USE_INTERRUPTS) || !defined(ENCODER_DO_NOT_USE_INTERRUPTS) +#define ENCODER_USE_INTERRUPTS +#define ENCODER_ARGLIST_SIZE CORE_NUM_INTERRUPT +#include "utility/interrupt_pins.h" +#ifdef ENCODER_OPTIMIZE_INTERRUPTS +#include "utility/interrupt_config.h" +#endif +#else +#define ENCODER_ARGLIST_SIZE 0 +#endif + + + +// All the data needed by interrupts is consolidated into this ugly struct +// to facilitate assembly language optimizing of the speed critical update. +// The assembly code uses auto-incrementing addressing modes, so the struct +// must remain in exactly this order. +typedef struct { + volatile IO_REG_TYPE * pin1_register; + volatile IO_REG_TYPE * pin2_register; + IO_REG_TYPE pin1_bitmask; + IO_REG_TYPE pin2_bitmask; + uint8_t state; + int32_t position; +} Encoder_internal_state_t; + +class Encoder +{ +public: + Encoder(uint8_t pin1, uint8_t pin2) { + #ifdef INPUT_PULLUP + pinMode(pin1, INPUT_PULLUP); + pinMode(pin2, INPUT_PULLUP); + #else + pinMode(pin1, INPUT); + digitalWrite(pin1, HIGH); + pinMode(pin2, INPUT); + digitalWrite(pin2, HIGH); + #endif + encoder.pin1_register = PIN_TO_BASEREG(pin1); + encoder.pin1_bitmask = PIN_TO_BITMASK(pin1); + encoder.pin2_register = PIN_TO_BASEREG(pin2); + encoder.pin2_bitmask = PIN_TO_BITMASK(pin2); + encoder.position = 0; + // allow time for a passive R-C filter to charge + // through the pullup resistors, before reading + // the initial state + delayMicroseconds(2000); + uint8_t s = 0; + if (DIRECT_PIN_READ(encoder.pin1_register, encoder.pin1_bitmask)) s |= 1; + if (DIRECT_PIN_READ(encoder.pin2_register, encoder.pin2_bitmask)) s |= 2; + encoder.state = s; +#ifdef ENCODER_USE_INTERRUPTS + interrupts_in_use = attach_interrupt(pin1, &encoder); + interrupts_in_use += attach_interrupt(pin2, &encoder); +#endif + //update_finishup(); // to force linker to include the code (does not work) + } + + +#ifdef ENCODER_USE_INTERRUPTS + inline int32_t read() { + if (interrupts_in_use < 2) { + noInterrupts(); + update(&encoder); + } else { + noInterrupts(); + } + int32_t ret = encoder.position; + interrupts(); + return ret; + } + inline void write(int32_t p) { + noInterrupts(); + encoder.position = p; + interrupts(); + } +#else + inline int32_t read() { + update(&encoder); + return encoder.position; + } + inline void write(int32_t p) { + encoder.position = p; + } +#endif +private: + Encoder_internal_state_t encoder; +#ifdef ENCODER_USE_INTERRUPTS + uint8_t interrupts_in_use; +#endif +public: + static Encoder_internal_state_t * interruptArgs[ENCODER_ARGLIST_SIZE]; + +// _______ _______ +// Pin1 ______| |_______| |______ Pin1 +// negative <--- _______ _______ __ --> positive +// Pin2 __| |_______| |_______| Pin2 + + // new new old old + // pin2 pin1 pin2 pin1 Result + // ---- ---- ---- ---- ------ + // 0 0 0 0 no movement + // 0 0 0 1 +1 + // 0 0 1 0 -1 + // 0 0 1 1 +2 (assume pin1 edges only) + // 0 1 0 0 -1 + // 0 1 0 1 no movement + // 0 1 1 0 -2 (assume pin1 edges only) + // 0 1 1 1 +1 + // 1 0 0 0 +1 + // 1 0 0 1 -2 (assume pin1 edges only) + // 1 0 1 0 no movement + // 1 0 1 1 -1 + // 1 1 0 0 +2 (assume pin1 edges only) + // 1 1 0 1 -1 + // 1 1 1 0 +1 + // 1 1 1 1 no movement +/* + // Simple, easy-to-read "documentation" version :-) + // + void update(void) { + uint8_t s = state & 3; + if (digitalRead(pin1)) s |= 4; + if (digitalRead(pin2)) s |= 8; + switch (s) { + case 0: case 5: case 10: case 15: + break; + case 1: case 7: case 8: case 14: + position++; break; + case 2: case 4: case 11: case 13: + position--; break; + case 3: case 12: + position += 2; break; + default: + position -= 2; break; + } + state = (s >> 2); + } +*/ + +private: + static void update(Encoder_internal_state_t *arg) { +#if defined(__AVR__) + // The compiler believes this is just 1 line of code, so + // it will inline this function into each interrupt + // handler. That's a tiny bit faster, but grows the code. + // Especially when used with ENCODER_OPTIMIZE_INTERRUPTS, + // the inline nature allows the ISR prologue and epilogue + // to only save/restore necessary registers, for very nice + // speed increase. + asm volatile ( + "ld r30, X+" "\n\t" + "ld r31, X+" "\n\t" + "ld r24, Z" "\n\t" // r24 = pin1 input + "ld r30, X+" "\n\t" + "ld r31, X+" "\n\t" + "ld r25, Z" "\n\t" // r25 = pin2 input + "ld r30, X+" "\n\t" // r30 = pin1 mask + "ld r31, X+" "\n\t" // r31 = pin2 mask + "ld r22, X" "\n\t" // r22 = state + "andi r22, 3" "\n\t" + "and r24, r30" "\n\t" + "breq L%=1" "\n\t" // if (pin1) + "ori r22, 4" "\n\t" // state |= 4 + "L%=1:" "and r25, r31" "\n\t" + "breq L%=2" "\n\t" // if (pin2) + "ori r22, 8" "\n\t" // state |= 8 + "L%=2:" "ldi r30, lo8(pm(L%=table))" "\n\t" + "ldi r31, hi8(pm(L%=table))" "\n\t" + "add r30, r22" "\n\t" + "adc r31, __zero_reg__" "\n\t" + "asr r22" "\n\t" + "asr r22" "\n\t" + "st X+, r22" "\n\t" // store new state + "ld r22, X+" "\n\t" + "ld r23, X+" "\n\t" + "ld r24, X+" "\n\t" + "ld r25, X+" "\n\t" + "ijmp" "\n\t" // jumps to update_finishup() + // TODO move this table to another static function, + // so it doesn't get needlessly duplicated. Easier + // said than done, due to linker issues and inlining + "L%=table:" "\n\t" + "rjmp L%=end" "\n\t" // 0 + "rjmp L%=plus1" "\n\t" // 1 + "rjmp L%=minus1" "\n\t" // 2 + "rjmp L%=plus2" "\n\t" // 3 + "rjmp L%=minus1" "\n\t" // 4 + "rjmp L%=end" "\n\t" // 5 + "rjmp L%=minus2" "\n\t" // 6 + "rjmp L%=plus1" "\n\t" // 7 + "rjmp L%=plus1" "\n\t" // 8 + "rjmp L%=minus2" "\n\t" // 9 + "rjmp L%=end" "\n\t" // 10 + "rjmp L%=minus1" "\n\t" // 11 + "rjmp L%=plus2" "\n\t" // 12 + "rjmp L%=minus1" "\n\t" // 13 + "rjmp L%=plus1" "\n\t" // 14 + "rjmp L%=end" "\n\t" // 15 + "L%=minus2:" "\n\t" + "subi r22, 2" "\n\t" + "sbci r23, 0" "\n\t" + "sbci r24, 0" "\n\t" + "sbci r25, 0" "\n\t" + "rjmp L%=store" "\n\t" + "L%=minus1:" "\n\t" + "subi r22, 1" "\n\t" + "sbci r23, 0" "\n\t" + "sbci r24, 0" "\n\t" + "sbci r25, 0" "\n\t" + "rjmp L%=store" "\n\t" + "L%=plus2:" "\n\t" + "subi r22, 254" "\n\t" + "rjmp L%=z" "\n\t" + "L%=plus1:" "\n\t" + "subi r22, 255" "\n\t" + "L%=z:" "sbci r23, 255" "\n\t" + "sbci r24, 255" "\n\t" + "sbci r25, 255" "\n\t" + "L%=store:" "\n\t" + "st -X, r25" "\n\t" + "st -X, r24" "\n\t" + "st -X, r23" "\n\t" + "st -X, r22" "\n\t" + "L%=end:" "\n" + : : "x" (arg) : "r22", "r23", "r24", "r25", "r30", "r31"); +#else + uint8_t p1val = DIRECT_PIN_READ(arg->pin1_register, arg->pin1_bitmask); + uint8_t p2val = DIRECT_PIN_READ(arg->pin2_register, arg->pin2_bitmask); + uint8_t state = arg->state & 3; + if (p1val) state |= 4; + if (p2val) state |= 8; + arg->state = (state >> 2); + switch (state) { + case 1: case 7: case 8: case 14: + arg->position++; + return; + case 2: case 4: case 11: case 13: + arg->position--; + return; + case 3: case 12: + arg->position += 2; + return; + case 6: case 9: + arg->position -= 2; + return; + } +#endif + } +/* +#if defined(__AVR__) + // TODO: this must be a no inline function + // even noinline does not seem to solve difficult + // problems with this. Oh well, it was only meant + // to shrink code size - there's no performance + // improvement in this, only code size reduction. + __attribute__((noinline)) void update_finishup(void) { + asm volatile ( + "ldi r30, lo8(pm(Ltable))" "\n\t" + "ldi r31, hi8(pm(Ltable))" "\n\t" + "Ltable:" "\n\t" + "rjmp L%=end" "\n\t" // 0 + "rjmp L%=plus1" "\n\t" // 1 + "rjmp L%=minus1" "\n\t" // 2 + "rjmp L%=plus2" "\n\t" // 3 + "rjmp L%=minus1" "\n\t" // 4 + "rjmp L%=end" "\n\t" // 5 + "rjmp L%=minus2" "\n\t" // 6 + "rjmp L%=plus1" "\n\t" // 7 + "rjmp L%=plus1" "\n\t" // 8 + "rjmp L%=minus2" "\n\t" // 9 + "rjmp L%=end" "\n\t" // 10 + "rjmp L%=minus1" "\n\t" // 11 + "rjmp L%=plus2" "\n\t" // 12 + "rjmp L%=minus1" "\n\t" // 13 + "rjmp L%=plus1" "\n\t" // 14 + "rjmp L%=end" "\n\t" // 15 + "L%=minus2:" "\n\t" + "subi r22, 2" "\n\t" + "sbci r23, 0" "\n\t" + "sbci r24, 0" "\n\t" + "sbci r25, 0" "\n\t" + "rjmp L%=store" "\n\t" + "L%=minus1:" "\n\t" + "subi r22, 1" "\n\t" + "sbci r23, 0" "\n\t" + "sbci r24, 0" "\n\t" + "sbci r25, 0" "\n\t" + "rjmp L%=store" "\n\t" + "L%=plus2:" "\n\t" + "subi r22, 254" "\n\t" + "rjmp L%=z" "\n\t" + "L%=plus1:" "\n\t" + "subi r22, 255" "\n\t" + "L%=z:" "sbci r23, 255" "\n\t" + "sbci r24, 255" "\n\t" + "sbci r25, 255" "\n\t" + "L%=store:" "\n\t" + "st -X, r25" "\n\t" + "st -X, r24" "\n\t" + "st -X, r23" "\n\t" + "st -X, r22" "\n\t" + "L%=end:" "\n" + : : : "r22", "r23", "r24", "r25", "r30", "r31"); + } +#endif +*/ + + +#ifdef ENCODER_USE_INTERRUPTS + // this giant function is an unfortunate consequence of Arduino's + // attachInterrupt function not supporting any way to pass a pointer + // or other context to the attached function. + static uint8_t attach_interrupt(uint8_t pin, Encoder_internal_state_t *state) { + switch (pin) { + #ifdef CORE_INT0_PIN + case CORE_INT0_PIN: + interruptArgs[0] = state; + attachInterrupt(0, isr0, CHANGE); + break; + #endif + #ifdef CORE_INT1_PIN + case CORE_INT1_PIN: + interruptArgs[1] = state; + attachInterrupt(1, isr1, CHANGE); + break; + #endif + #ifdef CORE_INT2_PIN + case CORE_INT2_PIN: + interruptArgs[2] = state; + attachInterrupt(2, isr2, CHANGE); + break; + #endif + #ifdef CORE_INT3_PIN + case CORE_INT3_PIN: + interruptArgs[3] = state; + attachInterrupt(3, isr3, CHANGE); + break; + #endif + #ifdef CORE_INT4_PIN + case CORE_INT4_PIN: + interruptArgs[4] = state; + attachInterrupt(4, isr4, CHANGE); + break; + #endif + #ifdef CORE_INT5_PIN + case CORE_INT5_PIN: + interruptArgs[5] = state; + attachInterrupt(5, isr5, CHANGE); + break; + #endif + #ifdef CORE_INT6_PIN + case CORE_INT6_PIN: + interruptArgs[6] = state; + attachInterrupt(6, isr6, CHANGE); + break; + #endif + #ifdef CORE_INT7_PIN + case CORE_INT7_PIN: + interruptArgs[7] = state; + attachInterrupt(7, isr7, CHANGE); + break; + #endif + #ifdef CORE_INT8_PIN + case CORE_INT8_PIN: + interruptArgs[8] = state; + attachInterrupt(8, isr8, CHANGE); + break; + #endif + #ifdef CORE_INT9_PIN + case CORE_INT9_PIN: + interruptArgs[9] = state; + attachInterrupt(9, isr9, CHANGE); + break; + #endif + #ifdef CORE_INT10_PIN + case CORE_INT10_PIN: + interruptArgs[10] = state; + attachInterrupt(10, isr10, CHANGE); + break; + #endif + #ifdef CORE_INT11_PIN + case CORE_INT11_PIN: + interruptArgs[11] = state; + attachInterrupt(11, isr11, CHANGE); + break; + #endif + #ifdef CORE_INT12_PIN + case CORE_INT12_PIN: + interruptArgs[12] = state; + attachInterrupt(12, isr12, CHANGE); + break; + #endif + #ifdef CORE_INT13_PIN + case CORE_INT13_PIN: + interruptArgs[13] = state; + attachInterrupt(13, isr13, CHANGE); + break; + #endif + #ifdef CORE_INT14_PIN + case CORE_INT14_PIN: + interruptArgs[14] = state; + attachInterrupt(14, isr14, CHANGE); + break; + #endif + #ifdef CORE_INT15_PIN + case CORE_INT15_PIN: + interruptArgs[15] = state; + attachInterrupt(15, isr15, CHANGE); + break; + #endif + #ifdef CORE_INT16_PIN + case CORE_INT16_PIN: + interruptArgs[16] = state; + attachInterrupt(16, isr16, CHANGE); + break; + #endif + #ifdef CORE_INT17_PIN + case CORE_INT17_PIN: + interruptArgs[17] = state; + attachInterrupt(17, isr17, CHANGE); + break; + #endif + #ifdef CORE_INT18_PIN + case CORE_INT18_PIN: + interruptArgs[18] = state; + attachInterrupt(18, isr18, CHANGE); + break; + #endif + #ifdef CORE_INT19_PIN + case CORE_INT19_PIN: + interruptArgs[19] = state; + attachInterrupt(19, isr19, CHANGE); + break; + #endif + #ifdef CORE_INT20_PIN + case CORE_INT20_PIN: + interruptArgs[20] = state; + attachInterrupt(20, isr20, CHANGE); + break; + #endif + #ifdef CORE_INT21_PIN + case CORE_INT21_PIN: + interruptArgs[21] = state; + attachInterrupt(21, isr21, CHANGE); + break; + #endif + #ifdef CORE_INT22_PIN + case CORE_INT22_PIN: + interruptArgs[22] = state; + attachInterrupt(22, isr22, CHANGE); + break; + #endif + #ifdef CORE_INT23_PIN + case CORE_INT23_PIN: + interruptArgs[23] = state; + attachInterrupt(23, isr23, CHANGE); + break; + #endif + #ifdef CORE_INT24_PIN + case CORE_INT24_PIN: + interruptArgs[24] = state; + attachInterrupt(24, isr24, CHANGE); + break; + #endif + #ifdef CORE_INT25_PIN + case CORE_INT25_PIN: + interruptArgs[25] = state; + attachInterrupt(25, isr25, CHANGE); + break; + #endif + #ifdef CORE_INT26_PIN + case CORE_INT26_PIN: + interruptArgs[26] = state; + attachInterrupt(26, isr26, CHANGE); + break; + #endif + #ifdef CORE_INT27_PIN + case CORE_INT27_PIN: + interruptArgs[27] = state; + attachInterrupt(27, isr27, CHANGE); + break; + #endif + #ifdef CORE_INT28_PIN + case CORE_INT28_PIN: + interruptArgs[28] = state; + attachInterrupt(28, isr28, CHANGE); + break; + #endif + #ifdef CORE_INT29_PIN + case CORE_INT29_PIN: + interruptArgs[29] = state; + attachInterrupt(29, isr29, CHANGE); + break; + #endif + + #ifdef CORE_INT30_PIN + case CORE_INT30_PIN: + interruptArgs[30] = state; + attachInterrupt(30, isr30, CHANGE); + break; + #endif + #ifdef CORE_INT31_PIN + case CORE_INT31_PIN: + interruptArgs[31] = state; + attachInterrupt(31, isr31, CHANGE); + break; + #endif + #ifdef CORE_INT32_PIN + case CORE_INT32_PIN: + interruptArgs[32] = state; + attachInterrupt(32, isr32, CHANGE); + break; + #endif + #ifdef CORE_INT33_PIN + case CORE_INT33_PIN: + interruptArgs[33] = state; + attachInterrupt(33, isr33, CHANGE); + break; + #endif + #ifdef CORE_INT34_PIN + case CORE_INT34_PIN: + interruptArgs[34] = state; + attachInterrupt(34, isr34, CHANGE); + break; + #endif + #ifdef CORE_INT35_PIN + case CORE_INT35_PIN: + interruptArgs[35] = state; + attachInterrupt(35, isr35, CHANGE); + break; + #endif + #ifdef CORE_INT36_PIN + case CORE_INT36_PIN: + interruptArgs[36] = state; + attachInterrupt(36, isr36, CHANGE); + break; + #endif + #ifdef CORE_INT37_PIN + case CORE_INT37_PIN: + interruptArgs[37] = state; + attachInterrupt(37, isr37, CHANGE); + break; + #endif + #ifdef CORE_INT38_PIN + case CORE_INT38_PIN: + interruptArgs[38] = state; + attachInterrupt(38, isr38, CHANGE); + break; + #endif + #ifdef CORE_INT39_PIN + case CORE_INT39_PIN: + interruptArgs[39] = state; + attachInterrupt(39, isr39, CHANGE); + break; + #endif + #ifdef CORE_INT40_PIN + case CORE_INT40_PIN: + interruptArgs[40] = state; + attachInterrupt(40, isr40, CHANGE); + break; + #endif + #ifdef CORE_INT41_PIN + case CORE_INT41_PIN: + interruptArgs[41] = state; + attachInterrupt(41, isr41, CHANGE); + break; + #endif + #ifdef CORE_INT42_PIN + case CORE_INT42_PIN: + interruptArgs[42] = state; + attachInterrupt(42, isr42, CHANGE); + break; + #endif + #ifdef CORE_INT43_PIN + case CORE_INT43_PIN: + interruptArgs[43] = state; + attachInterrupt(43, isr43, CHANGE); + break; + #endif + #ifdef CORE_INT44_PIN + case CORE_INT44_PIN: + interruptArgs[44] = state; + attachInterrupt(44, isr44, CHANGE); + break; + #endif + #ifdef CORE_INT45_PIN + case CORE_INT45_PIN: + interruptArgs[45] = state; + attachInterrupt(45, isr45, CHANGE); + break; + #endif + #ifdef CORE_INT46_PIN + case CORE_INT46_PIN: + interruptArgs[46] = state; + attachInterrupt(46, isr46, CHANGE); + break; + #endif + #ifdef CORE_INT47_PIN + case CORE_INT47_PIN: + interruptArgs[47] = state; + attachInterrupt(47, isr47, CHANGE); + break; + #endif + #ifdef CORE_INT48_PIN + case CORE_INT48_PIN: + interruptArgs[48] = state; + attachInterrupt(48, isr48, CHANGE); + break; + #endif + #ifdef CORE_INT49_PIN + case CORE_INT49_PIN: + interruptArgs[49] = state; + attachInterrupt(49, isr49, CHANGE); + break; + #endif + #ifdef CORE_INT50_PIN + case CORE_INT50_PIN: + interruptArgs[50] = state; + attachInterrupt(50, isr50, CHANGE); + break; + #endif + #ifdef CORE_INT51_PIN + case CORE_INT51_PIN: + interruptArgs[51] = state; + attachInterrupt(51, isr51, CHANGE); + break; + #endif + #ifdef CORE_INT52_PIN + case CORE_INT52_PIN: + interruptArgs[52] = state; + attachInterrupt(52, isr52, CHANGE); + break; + #endif + #ifdef CORE_INT53_PIN + case CORE_INT53_PIN: + interruptArgs[53] = state; + attachInterrupt(53, isr53, CHANGE); + break; + #endif + #ifdef CORE_INT54_PIN + case CORE_INT54_PIN: + interruptArgs[54] = state; + attachInterrupt(54, isr54, CHANGE); + break; + #endif + #ifdef CORE_INT55_PIN + case CORE_INT55_PIN: + interruptArgs[55] = state; + attachInterrupt(55, isr55, CHANGE); + break; + #endif + #ifdef CORE_INT56_PIN + case CORE_INT56_PIN: + interruptArgs[56] = state; + attachInterrupt(56, isr56, CHANGE); + break; + #endif + #ifdef CORE_INT57_PIN + case CORE_INT57_PIN: + interruptArgs[57] = state; + attachInterrupt(57, isr57, CHANGE); + break; + #endif + #ifdef CORE_INT58_PIN + case CORE_INT58_PIN: + interruptArgs[58] = state; + attachInterrupt(58, isr58, CHANGE); + break; + #endif + #ifdef CORE_INT59_PIN + case CORE_INT59_PIN: + interruptArgs[59] = state; + attachInterrupt(59, isr59, CHANGE); + break; + #endif + default: + return 0; + } + return 1; + } +#endif // ENCODER_USE_INTERRUPTS + + +#if defined(ENCODER_USE_INTERRUPTS) && !defined(ENCODER_OPTIMIZE_INTERRUPTS) + #ifdef CORE_INT0_PIN + static void isr0(void) { update(interruptArgs[0]); } + #endif + #ifdef CORE_INT1_PIN + static void isr1(void) { update(interruptArgs[1]); } + #endif + #ifdef CORE_INT2_PIN + static void isr2(void) { update(interruptArgs[2]); } + #endif + #ifdef CORE_INT3_PIN + static void isr3(void) { update(interruptArgs[3]); } + #endif + #ifdef CORE_INT4_PIN + static void isr4(void) { update(interruptArgs[4]); } + #endif + #ifdef CORE_INT5_PIN + static void isr5(void) { update(interruptArgs[5]); } + #endif + #ifdef CORE_INT6_PIN + static void isr6(void) { update(interruptArgs[6]); } + #endif + #ifdef CORE_INT7_PIN + static void isr7(void) { update(interruptArgs[7]); } + #endif + #ifdef CORE_INT8_PIN + static void isr8(void) { update(interruptArgs[8]); } + #endif + #ifdef CORE_INT9_PIN + static void isr9(void) { update(interruptArgs[9]); } + #endif + #ifdef CORE_INT10_PIN + static void isr10(void) { update(interruptArgs[10]); } + #endif + #ifdef CORE_INT11_PIN + static void isr11(void) { update(interruptArgs[11]); } + #endif + #ifdef CORE_INT12_PIN + static void isr12(void) { update(interruptArgs[12]); } + #endif + #ifdef CORE_INT13_PIN + static void isr13(void) { update(interruptArgs[13]); } + #endif + #ifdef CORE_INT14_PIN + static void isr14(void) { update(interruptArgs[14]); } + #endif + #ifdef CORE_INT15_PIN + static void isr15(void) { update(interruptArgs[15]); } + #endif + #ifdef CORE_INT16_PIN + static void isr16(void) { update(interruptArgs[16]); } + #endif + #ifdef CORE_INT17_PIN + static void isr17(void) { update(interruptArgs[17]); } + #endif + #ifdef CORE_INT18_PIN + static void isr18(void) { update(interruptArgs[18]); } + #endif + #ifdef CORE_INT19_PIN + static void isr19(void) { update(interruptArgs[19]); } + #endif + #ifdef CORE_INT20_PIN + static void isr20(void) { update(interruptArgs[20]); } + #endif + #ifdef CORE_INT21_PIN + static void isr21(void) { update(interruptArgs[21]); } + #endif + #ifdef CORE_INT22_PIN + static void isr22(void) { update(interruptArgs[22]); } + #endif + #ifdef CORE_INT23_PIN + static void isr23(void) { update(interruptArgs[23]); } + #endif + #ifdef CORE_INT24_PIN + static void isr24(void) { update(interruptArgs[24]); } + #endif + #ifdef CORE_INT25_PIN + static void isr25(void) { update(interruptArgs[25]); } + #endif + #ifdef CORE_INT26_PIN + static void isr26(void) { update(interruptArgs[26]); } + #endif + #ifdef CORE_INT27_PIN + static void isr27(void) { update(interruptArgs[27]); } + #endif + #ifdef CORE_INT28_PIN + static void isr28(void) { update(interruptArgs[28]); } + #endif + #ifdef CORE_INT29_PIN + static void isr29(void) { update(interruptArgs[29]); } + #endif + #ifdef CORE_INT30_PIN + static void isr30(void) { update(interruptArgs[30]); } + #endif + #ifdef CORE_INT31_PIN + static void isr31(void) { update(interruptArgs[31]); } + #endif + #ifdef CORE_INT32_PIN + static void isr32(void) { update(interruptArgs[32]); } + #endif + #ifdef CORE_INT33_PIN + static void isr33(void) { update(interruptArgs[33]); } + #endif + #ifdef CORE_INT34_PIN + static void isr34(void) { update(interruptArgs[34]); } + #endif + #ifdef CORE_INT35_PIN + static void isr35(void) { update(interruptArgs[35]); } + #endif + #ifdef CORE_INT36_PIN + static void isr36(void) { update(interruptArgs[36]); } + #endif + #ifdef CORE_INT37_PIN + static void isr37(void) { update(interruptArgs[37]); } + #endif + #ifdef CORE_INT38_PIN + static void isr38(void) { update(interruptArgs[38]); } + #endif + #ifdef CORE_INT39_PIN + static void isr39(void) { update(interruptArgs[39]); } + #endif + #ifdef CORE_INT40_PIN + static void isr40(void) { update(interruptArgs[40]); } + #endif + #ifdef CORE_INT41_PIN + static void isr41(void) { update(interruptArgs[41]); } + #endif + #ifdef CORE_INT42_PIN + static void isr42(void) { update(interruptArgs[42]); } + #endif + #ifdef CORE_INT43_PIN + static void isr43(void) { update(interruptArgs[43]); } + #endif + #ifdef CORE_INT44_PIN + static void isr44(void) { update(interruptArgs[44]); } + #endif + #ifdef CORE_INT45_PIN + static void isr45(void) { update(interruptArgs[45]); } + #endif + #ifdef CORE_INT46_PIN + static void isr46(void) { update(interruptArgs[46]); } + #endif + #ifdef CORE_INT47_PIN + static void isr47(void) { update(interruptArgs[47]); } + #endif + #ifdef CORE_INT48_PIN + static void isr48(void) { update(interruptArgs[48]); } + #endif + #ifdef CORE_INT49_PIN + static void isr49(void) { update(interruptArgs[49]); } + #endif + #ifdef CORE_INT50_PIN + static void isr50(void) { update(interruptArgs[50]); } + #endif + #ifdef CORE_INT51_PIN + static void isr51(void) { update(interruptArgs[51]); } + #endif + #ifdef CORE_INT52_PIN + static void isr52(void) { update(interruptArgs[52]); } + #endif + #ifdef CORE_INT53_PIN + static void isr53(void) { update(interruptArgs[53]); } + #endif + #ifdef CORE_INT54_PIN + static void isr54(void) { update(interruptArgs[54]); } + #endif + #ifdef CORE_INT55_PIN + static void isr55(void) { update(interruptArgs[55]); } + #endif + #ifdef CORE_INT56_PIN + static void isr56(void) { update(interruptArgs[56]); } + #endif + #ifdef CORE_INT57_PIN + static void isr57(void) { update(interruptArgs[57]); } + #endif + #ifdef CORE_INT58_PIN + static void isr58(void) { update(interruptArgs[58]); } + #endif + #ifdef CORE_INT59_PIN + static void isr59(void) { update(interruptArgs[59]); } + #endif +#endif +}; + +#if defined(ENCODER_USE_INTERRUPTS) && defined(ENCODER_OPTIMIZE_INTERRUPTS) +#if defined(__AVR__) +#if defined(INT0_vect) && CORE_NUM_INTERRUPT > 0 +ISR(INT0_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(0)]); } +#endif +#if defined(INT1_vect) && CORE_NUM_INTERRUPT > 1 +ISR(INT1_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(1)]); } +#endif +#if defined(INT2_vect) && CORE_NUM_INTERRUPT > 2 +ISR(INT2_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(2)]); } +#endif +#if defined(INT3_vect) && CORE_NUM_INTERRUPT > 3 +ISR(INT3_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(3)]); } +#endif +#if defined(INT4_vect) && CORE_NUM_INTERRUPT > 4 +ISR(INT4_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(4)]); } +#endif +#if defined(INT5_vect) && CORE_NUM_INTERRUPT > 5 +ISR(INT5_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(5)]); } +#endif +#if defined(INT6_vect) && CORE_NUM_INTERRUPT > 6 +ISR(INT6_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(6)]); } +#endif +#if defined(INT7_vect) && CORE_NUM_INTERRUPT > 7 +ISR(INT7_vect) { Encoder::update(Encoder::interruptArgs[SCRAMBLE_INT_ORDER(7)]); } +#endif +#endif // AVR +#endif // ENCODER_OPTIMIZE_INTERRUPTS + + +#endif diff --git a/libraries/Encoder/examples/Basic/Basic.pde b/libraries/Encoder/examples/Basic/Basic.pde new file mode 100644 index 0000000..3394b58 --- /dev/null +++ b/libraries/Encoder/examples/Basic/Basic.pde @@ -0,0 +1,29 @@ +/* Encoder Library - Basic Example + * http://www.pjrc.com/teensy/td_libs_Encoder.html + * + * This example code is in the public domain. + */ + +#include + +// Change these two numbers to the pins connected to your encoder. +// Best Performance: both pins have interrupt capability +// Good Performance: only the first pin has interrupt capability +// Low Performance: neither pin has interrupt capability +Encoder myEnc(5, 6); +// avoid using pins with LEDs attached + +void setup() { + Serial.begin(9600); + Serial.println("Basic Encoder Test:"); +} + +long oldPosition = -999; + +void loop() { + long newPosition = myEnc.read(); + if (newPosition != oldPosition) { + oldPosition = newPosition; + Serial.println(newPosition); + } +} diff --git a/libraries/Encoder/examples/NoInterrupts/NoInterrupts.pde b/libraries/Encoder/examples/NoInterrupts/NoInterrupts.pde new file mode 100644 index 0000000..b890652 --- /dev/null +++ b/libraries/Encoder/examples/NoInterrupts/NoInterrupts.pde @@ -0,0 +1,46 @@ +/* Encoder Library - NoInterrupts Example + * http://www.pjrc.com/teensy/td_libs_Encoder.html + * + * This example code is in the public domain. + */ + +// If you define ENCODER_DO_NOT_USE_INTERRUPTS *before* including +// Encoder, the library will never use interrupts. This is mainly +// useful to reduce the size of the library when you are using it +// with pins that do not support interrupts. Without interrupts, +// your program must call the read() function rapidly, or risk +// missing changes in position. +#define ENCODER_DO_NOT_USE_INTERRUPTS +#include + +// Beware of Serial.print() speed. Without interrupts, if you +// transmit too much data with Serial.print() it can slow your +// reading from Encoder. Arduino 1.0 has improved transmit code. +// Using the fastest baud rate also helps. Teensy has USB packet +// buffering. But all boards can experience problems if you print +// too much and fill up buffers. + +// Change these two numbers to the pins connected to your encoder. +// With ENCODER_DO_NOT_USE_INTERRUPTS, no interrupts are ever +// used, even if the pin has interrupt capability +Encoder myEnc(5, 6); +// avoid using pins with LEDs attached + +void setup() { + Serial.begin(9600); + Serial.println("Basic NoInterrupts Test:"); +} + +long position = -999; + +void loop() { + long newPos = myEnc.read(); + if (newPos != position) { + position = newPos; + Serial.println(position); + } + // With any substantial delay added, Encoder can only track + // very slow motion. You may uncomment this line to see + // how badly a delay affects your encoder. + //delay(50); +} diff --git a/libraries/Encoder/examples/SpeedTest/SpeedTest.pde b/libraries/Encoder/examples/SpeedTest/SpeedTest.pde new file mode 100644 index 0000000..76cf350 --- /dev/null +++ b/libraries/Encoder/examples/SpeedTest/SpeedTest.pde @@ -0,0 +1,113 @@ +/* Encoder Library - SpeedTest - for measuring maximum Encoder speed + * http://www.pjrc.com/teensy/td_libs_Encoder.html + * + * This example code is in the public domain. + */ + + +// This SpeedTest example provides a simple way to verify how much +// CPU time Encoder is consuming. Connect a DC voltmeter to the +// output pin and measure the voltage while the encoder is stopped +// or running at a very slow speed. Even though the pin is rapidly +// pulsing, a DC voltmeter will show the average voltage. Due to +// software timing, it will read a number much less than a steady +// logic high, but this number will give you a baseline reading +// for output with minimal interrupt overhead. Then increase the +// encoder speed. The voltage will decrease as the processor spends +// more time in Encoder's interrupt routines counting the pulses +// and less time pulsing the output pin. When the voltage is +// close to zero and will not decrease any farther, you have reached +// the absolute speed limit. Or, if using a mechanical system where +// you reach a speed limit imposed by your motors or other hardware, +// the amount this voltage has decreased, compared to the baseline, +// should give you a good approximation of the portion of available +// CPU time Encoder is consuming at your maximum speed. + +// Encoder requires low latency interrupt response. Available CPU +// time does NOT necessarily prove or guarantee correct performance. +// If another library, like NewSoftSerial, is disabling interrupts +// for lengthy periods of time, Encoder can be prevented from +// properly counting the intput signals while interrupt are disabled. + + +// This optional setting causes Encoder to use more optimized code, +// but the downside is a conflict if any other part of your sketch +// or any other library you're using requires attachInterrupt(). +// It must be defined before Encoder.h is included. +//#define ENCODER_OPTIMIZE_INTERRUPTS + +#include +#include "pins_arduino.h" + +// Change these two numbers to the pins connected to your encoder +// or shift register circuit which emulates a quadrature encoder +// case 1: both pins are interrupts +// case 2: only first pin used as interrupt +Encoder myEnc(5, 6); + +// Connect a DC voltmeter to this pin. +const int outputPin = 12; + +/* This simple circuit, using a Dual Flip-Flop chip, can emulate + quadrature encoder signals. The clock can come from a fancy + function generator or a cheap 555 timer chip. The clock + frequency can be measured with another board running FreqCount + http://www.pjrc.com/teensy/td_libs_FreqCount.html + + +5V + | Quadrature Encoder Signal Emulator + Clock | + Input o----*-------------------------- ---------------------------o Output1 + | |14 | | + | _______|_______ | | _______________ + | | CD4013 | | | | CD4013 | + | 5 | | 1 | | 9 | | 13 + ---------| D Q |-----|----*----| D Q |------o Output2 + | | | | | | | + | | 3 | | | 11 | | + | ----|> Clk | ---------|> Clk | + | | | | | + | 6 | | 8 | | + | ----| S | ----| S | + | | | | | | | + | | 4 | _ | 2 | 10 | _ | 12 + | *----| R Q |--- *----| R Q |---- + | | | | | | | | + | | |_______________| | |_______________| | + | | | | | + | | | 7 | | + | | | | | + -------------------------------------------------------------- + | | | + | | | + ----- ----- ----- + --- --- --- + - - - +*/ + + +void setup() { + pinMode(outputPin, OUTPUT); +} + +#if defined(__AVR__) +#define REGTYPE unsigned char +#elif defined(__PIC32MX__) +#define REGTYPE unsigned long +#endif + +void loop() { + volatile int count = 0; + volatile REGTYPE *reg = portOutputRegister(digitalPinToPort(outputPin)); + REGTYPE mask = digitalPinToBitMask(outputPin); + + while (1) { + myEnc.read(); // Read the encoder while interrupts are enabled. + noInterrupts(); + *reg |= mask; // Pulse the pin high, while interrupts are disabled. + count = count + 1; + *reg &= ~mask; + interrupts(); + } +} + diff --git a/libraries/Encoder/examples/TwoKnobs/TwoKnobs.pde b/libraries/Encoder/examples/TwoKnobs/TwoKnobs.pde new file mode 100644 index 0000000..306b33e --- /dev/null +++ b/libraries/Encoder/examples/TwoKnobs/TwoKnobs.pde @@ -0,0 +1,46 @@ +/* Encoder Library - TwoKnobs Example + * http://www.pjrc.com/teensy/td_libs_Encoder.html + * + * This example code is in the public domain. + */ + +#include + +// Change these pin numbers to the pins connected to your encoder. +// Best Performance: both pins have interrupt capability +// Good Performance: only the first pin has interrupt capability +// Low Performance: neither pin has interrupt capability +Encoder knobLeft(5, 6); +Encoder knobRight(7, 8); +// avoid using pins with LEDs attached + +void setup() { + Serial.begin(9600); + Serial.println("TwoKnobs Encoder Test:"); +} + +long positionLeft = -999; +long positionRight = -999; + +void loop() { + long newLeft, newRight; + newLeft = knobLeft.read(); + newRight = knobRight.read(); + if (newLeft != positionLeft || newRight != positionRight) { + Serial.print("Left = "); + Serial.print(newLeft); + Serial.print(", Right = "); + Serial.print(newRight); + Serial.println(); + positionLeft = newLeft; + positionRight = newRight; + } + // if a character is sent from the serial monitor, + // reset both back to zero. + if (Serial.available()) { + Serial.read(); + Serial.println("Reset both knobs to zero"); + knobLeft.write(0); + knobRight.write(0); + } +} diff --git a/libraries/Encoder/keywords.txt b/libraries/Encoder/keywords.txt new file mode 100644 index 0000000..a4baa01 --- /dev/null +++ b/libraries/Encoder/keywords.txt @@ -0,0 +1,4 @@ +ENCODER_USE_INTERRUPTS LITERAL1 +ENCODER_OPTIMIZE_INTERRUPTS LITERAL1 +ENCODER_DO_NOT_USE_INTERRUPTS LITERAL1 +Encoder KEYWORD1 diff --git a/libraries/Encoder/utility/direct_pin_read.h b/libraries/Encoder/utility/direct_pin_read.h new file mode 100644 index 0000000..97b8862 --- /dev/null +++ b/libraries/Encoder/utility/direct_pin_read.h @@ -0,0 +1,27 @@ +#ifndef direct_pin_read_h_ +#define direct_pin_read_h_ + +#if defined(__AVR__) || defined(__MK20DX128__) || defined(__MK20DX256__) + +#define IO_REG_TYPE uint8_t +#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define DIRECT_PIN_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) + +#elif defined(__SAM3X8E__) + +#define IO_REG_TYPE uint32_t +#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define DIRECT_PIN_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) + +#elif defined(__PIC32MX__) + +#define IO_REG_TYPE uint32_t +#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define DIRECT_PIN_READ(base, mask) (((*(base+4)) & (mask)) ? 1 : 0) + +#endif + +#endif diff --git a/libraries/Encoder/utility/interrupt_config.h b/libraries/Encoder/utility/interrupt_config.h new file mode 100644 index 0000000..cde6adf --- /dev/null +++ b/libraries/Encoder/utility/interrupt_config.h @@ -0,0 +1,87 @@ +#if defined(__AVR__) + +#include +#include + +#define attachInterrupt(num, func, mode) enableInterrupt(num) +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define SCRAMBLE_INT_ORDER(num) ((num < 4) ? num + 2 : ((num < 6) ? num - 4 : num)) +#define DESCRAMBLE_INT_ORDER(num) ((num < 2) ? num + 4 : ((num < 6) ? num - 2 : num)) +#else +#define SCRAMBLE_INT_ORDER(num) (num) +#define DESCRAMBLE_INT_ORDER(num) (num) +#endif + +static void enableInterrupt(uint8_t num) +{ + switch (DESCRAMBLE_INT_ORDER(num)) { + #if defined(EICRA) && defined(EIMSK) + case 0: + EICRA = (EICRA & 0xFC) | 0x01; + EIMSK |= 0x01; + return; + case 1: + EICRA = (EICRA & 0xF3) | 0x04; + EIMSK |= 0x02; + return; + case 2: + EICRA = (EICRA & 0xCF) | 0x10; + EIMSK |= 0x04; + return; + case 3: + EICRA = (EICRA & 0x3F) | 0x40; + EIMSK |= 0x08; + return; + #elif defined(MCUCR) && defined(GICR) + case 0: + MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00); + GICR |= (1 << INT0); + return; + case 1: + MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10); + GICR |= (1 << INT1); + return; + #elif defined(MCUCR) && defined(GIMSK) + case 0: + MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00); + GIMSK |= (1 << INT0); + return; + case 1: + MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10); + GIMSK |= (1 << INT1); + return; + #endif + #if defined(EICRB) && defined(EIMSK) + case 4: + EICRB = (EICRB & 0xFC) | 0x01; + EIMSK |= 0x10; + return; + case 5: + EICRB = (EICRB & 0xF3) | 0x04; + EIMSK |= 0x20; + return; + case 6: + EICRB = (EICRB & 0xCF) | 0x10; + EIMSK |= 0x40; + return; + case 7: + EICRB = (EICRB & 0x3F) | 0x40; + EIMSK |= 0x80; + return; + #endif + } +} + +#elif defined(__PIC32MX__) + +#ifdef ENCODER_OPTIMIZE_INTERRUPTS +#undef ENCODER_OPTIMIZE_INTERRUPTS +#endif + +#else + +#ifdef ENCODER_OPTIMIZE_INTERRUPTS +#undef ENCODER_OPTIMIZE_INTERRUPTS +#endif + +#endif diff --git a/libraries/Encoder/utility/interrupt_pins.h b/libraries/Encoder/utility/interrupt_pins.h new file mode 100644 index 0000000..e677c4f --- /dev/null +++ b/libraries/Encoder/utility/interrupt_pins.h @@ -0,0 +1,156 @@ +// interrupt pins for known boards + +// Teensy (and maybe others) define these automatically +#if !defined(CORE_NUM_INTERRUPT) + +// Wiring boards +#if defined(WIRING) + #define CORE_NUM_INTERRUPT NUM_EXTERNAL_INTERRUPTS + #if NUM_EXTERNAL_INTERRUPTS > 0 + #define CORE_INT0_PIN EI0 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 1 + #define CORE_INT1_PIN EI1 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 2 + #define CORE_INT2_PIN EI2 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 3 + #define CORE_INT3_PIN EI3 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 4 + #define CORE_INT4_PIN EI4 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 5 + #define CORE_INT5_PIN EI5 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 6 + #define CORE_INT6_PIN EI6 + #endif + #if NUM_EXTERNAL_INTERRUPTS > 7 + #define CORE_INT7_PIN EI7 + #endif + +// Arduino Uno, Duemilanove, Diecimila, LilyPad, Mini, Fio, etc... +#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) + #define CORE_NUM_INTERRUPT 2 + #define CORE_INT0_PIN 2 + #define CORE_INT1_PIN 3 + +// Arduino Mega +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + #define CORE_NUM_INTERRUPT 6 + #define CORE_INT0_PIN 2 + #define CORE_INT1_PIN 3 + #define CORE_INT2_PIN 21 + #define CORE_INT3_PIN 20 + #define CORE_INT4_PIN 19 + #define CORE_INT5_PIN 18 + +// Arduino Leonardo (untested) +#elif defined(__AVR_ATmega32U4__) && !defined(CORE_TEENSY) + #define CORE_NUM_INTERRUPT 4 + #define CORE_INT0_PIN 3 + #define CORE_INT1_PIN 2 + #define CORE_INT2_PIN 0 + #define CORE_INT3_PIN 1 + +// Sanguino (untested) +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) + #define CORE_NUM_INTERRUPT 3 + #define CORE_INT0_PIN 10 + #define CORE_INT1_PIN 11 + #define CORE_INT2_PIN 2 + +// Chipkit Uno32 - attachInterrupt may not support CHANGE option +#elif defined(__PIC32MX__) && defined(_BOARD_UNO_) + #define CORE_NUM_INTERRUPT 5 + #define CORE_INT0_PIN 38 + #define CORE_INT1_PIN 2 + #define CORE_INT2_PIN 7 + #define CORE_INT3_PIN 8 + #define CORE_INT4_PIN 35 + +// Chipkit Uno32 - attachInterrupt may not support CHANGE option +#elif defined(__PIC32MX__) && defined(_BOARD_MEGA_) + #define CORE_NUM_INTERRUPT 5 + #define CORE_INT0_PIN 3 + #define CORE_INT1_PIN 2 + #define CORE_INT2_PIN 7 + #define CORE_INT3_PIN 21 + #define CORE_INT4_PIN 20 + +// http://hlt.media.mit.edu/?p=1229 +#elif defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) + #define CORE_NUM_INTERRUPT 1 + #define CORE_INT0_PIN 2 + +// Arduino Due (untested) +#elif defined(__SAM3X8E__) + #define CORE_NUM_INTERRUPT 54 + #define CORE_INT0_PIN 0 + #define CORE_INT1_PIN 1 + #define CORE_INT2_PIN 2 + #define CORE_INT3_PIN 3 + #define CORE_INT4_PIN 4 + #define CORE_INT5_PIN 5 + #define CORE_INT6_PIN 6 + #define CORE_INT7_PIN 7 + #define CORE_INT8_PIN 8 + #define CORE_INT9_PIN 9 + #define CORE_INT10_PIN 10 + #define CORE_INT11_PIN 11 + #define CORE_INT12_PIN 12 + #define CORE_INT13_PIN 13 + #define CORE_INT14_PIN 14 + #define CORE_INT15_PIN 15 + #define CORE_INT16_PIN 16 + #define CORE_INT17_PIN 17 + #define CORE_INT18_PIN 18 + #define CORE_INT19_PIN 19 + #define CORE_INT20_PIN 20 + #define CORE_INT21_PIN 21 + #define CORE_INT22_PIN 22 + #define CORE_INT23_PIN 23 + #define CORE_INT24_PIN 24 + #define CORE_INT25_PIN 25 + #define CORE_INT26_PIN 26 + #define CORE_INT27_PIN 27 + #define CORE_INT28_PIN 28 + #define CORE_INT29_PIN 29 + #define CORE_INT30_PIN 30 + #define CORE_INT31_PIN 31 + #define CORE_INT32_PIN 32 + #define CORE_INT33_PIN 33 + #define CORE_INT34_PIN 34 + #define CORE_INT35_PIN 35 + #define CORE_INT36_PIN 36 + #define CORE_INT37_PIN 37 + #define CORE_INT38_PIN 38 + #define CORE_INT39_PIN 39 + #define CORE_INT40_PIN 40 + #define CORE_INT41_PIN 41 + #define CORE_INT42_PIN 42 + #define CORE_INT43_PIN 43 + #define CORE_INT44_PIN 44 + #define CORE_INT45_PIN 45 + #define CORE_INT46_PIN 46 + #define CORE_INT47_PIN 47 + #define CORE_INT48_PIN 48 + #define CORE_INT49_PIN 49 + #define CORE_INT50_PIN 50 + #define CORE_INT51_PIN 51 + #define CORE_INT52_PIN 52 + #define CORE_INT53_PIN 53 + +#endif +#endif + +#if !defined(CORE_NUM_INTERRUPT) +#error "Interrupts are unknown for this board, please add to this code" +#endif +#if CORE_NUM_INTERRUPT <= 0 +#error "Encoder requires interrupt pins, but this board does not have any :(" +#error "You could try defining ENCODER_DO_NOT_USE_INTERRUPTS as a kludge." +#endif + diff --git a/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino b/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino new file mode 100644 index 0000000..600e521 --- /dev/null +++ b/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino @@ -0,0 +1,243 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Developed by Bruce Lacey and GizMoCuz (Domoticz) + * Version 1.1 - Modified by hek to incorporate a rotary encode to adjust + * light level locally at node + * + * DESCRIPTION + * This sketch provides an example how to implement a dimmable led light node with a rotary + * encoder connected for adjusting light level. + * The encoder has a click button which turns on/off the light (and remembers last dim-level) + * The sketch fades the light (non-blocking) to the desired level. + * + * Default MOSFET pin is 3 + * + * Arduino Encoder module + * --------------------------- + * 5V 5V (+) + * GND GND (-) + * 4 CLK (or putput 1) + * 5 DT (or output 1) + * 6 SW (Switch/Click) + */ + + +#include +#include +#include +#include + +#define LED_PIN 3 // Arduino pin attached to MOSFET Gate pin +#define KNOB_ENC_PIN_1 A0 // Rotary encoder input pin 1 +#define KNOB_ENC_PIN_2 A1 // Rotary encoder input pin 2 +#define KNOB_BUTTON_PIN 6 // Rotary encoder button pin +#define FADE_DELAY 10 // Delay in ms for each percentage fade up/down (10ms = 1s full-range dim) +#define SN "DimmableLED /w button" +#define SV "1.2" + +#define CHILD_ID_LIGHT 1 + +#define EEPROM_DIM_LEVEL_LAST 1 +#define EEPROM_DIM_LEVEL_SAVE 2 + +#define LIGHT_OFF 0 +#define LIGHT_ON 1 + +#define SEND_THROTTLE_DELAY 400 // Number of milliseconds before sending after user stops turning knob + +#define SN "Dimmable /w Button" +#define SV "1.0" + +int dimValue; +int fadeTo; +int fadeDelta; +byte oldButtonVal; +bool changedByKnob=false; +bool sendDimValue=false; +unsigned long lastFadeStep; +unsigned long sendDimTimeout; +char convBuffer[10]; + +MySensor gw; +MyMessage dimmerMsg(CHILD_ID_LIGHT, V_DIMMER); +Encoder knob(KNOB_ENC_PIN_1, KNOB_ENC_PIN_2); +Bounce debouncer = Bounce(); + +void setup() +{ + // Set knob button pin as input (with debounce) + pinMode(KNOB_BUTTON_PIN, INPUT); + digitalWrite(KNOB_BUTTON_PIN, HIGH); + debouncer.attach(KNOB_BUTTON_PIN); + debouncer.interval(5); + oldButtonVal = debouncer.read(); + + // Set analog led pin to off + analogWrite( LED_PIN, 0); + + // Init mysensors library + gw.begin(incomingMessage, AUTO, false); + + // Send the Sketch Version Information to the Gateway + gw.sendSketchInfo(SN, SV); + gw.present(CHILD_ID_LIGHT, S_DIMMER); + gw.sendSketchInfo(SN, SV); + + // Retreive our last dim levels from the eprom + fadeTo = dimValue = 0; + byte oldLevel = loadLevelState(EEPROM_DIM_LEVEL_LAST); + Serial.print("Sending in last known light level to controller: "); + Serial.println(oldLevel); + gw.send(dimmerMsg.set(oldLevel), true); + + Serial.println("Ready to receive messages..."); +} + +void loop() +{ + // Process incoming messages (like config and light state from controller) + gw.process(); + + // Check if someone turned the rotary encode + checkRotaryEncoder(); + + // Check if someone has pressed the knob button + checkButtonClick(); + + // Fade light to new dim value + fadeStep(); +} + +void incomingMessage(const MyMessage &message) +{ + if (message.type == V_LIGHT) { + // Incoming on/off command sent from controller ("1" or "0") + int lightState = message.getString()[0] == '1'; + int newLevel = 0; + if (lightState==LIGHT_ON) { + // Pick up last saved dimmer level from the eeprom + newLevel = loadLevelState(EEPROM_DIM_LEVEL_SAVE); + } + // Send dimmer level back to controller with ack enabled + gw.send(dimmerMsg.set(0), true); + // We do not change any levels here until ack comes back from gateway + return; + } else if (message.type == V_DIMMER) { + // Incoming dim-level command sent from controller (or ack message) + fadeTo = atoi(message.getString(convBuffer)); + // Save received dim value to eeprom (unless turned off). Will be + // retreived when a on command comes in + if (fadeTo != 0) + saveLevelState(EEPROM_DIM_LEVEL_SAVE, fadeTo); + } + saveLevelState(EEPROM_DIM_LEVEL_LAST, fadeTo); + + Serial.print("New light level received: "); + Serial.println(fadeTo); + + if (!changedByKnob) + knob.write(fadeTo); + + // Cancel send if user turns knob while message comes in + changedByKnob = false; + sendDimValue = false; + + // Stard fading to new light level + startFade(); +} + + + +void checkRotaryEncoder() { + long encoderValue = knob.read(); + + if (encoderValue > 100) { + encoderValue = 100; + knob.write(100); + } else if (encoderValue < 0) { + encoderValue = 0; + knob.write(0); + } + + if (encoderValue != fadeTo) { + fadeTo = encoderValue; + changedByKnob = true; + startFade(); + } +} + +void checkButtonClick() { + debouncer.update(); + byte buttonVal = debouncer.read(); + byte newLevel = 0; + if (buttonVal != oldButtonVal && buttonVal == LOW) { + if (dimValue==0) { + // Turn on light. Set the level to last saved dim value + int saved = loadLevelState(EEPROM_DIM_LEVEL_SAVE); + newLevel = saved > 0 ? saved : 100; + } + gw.send(dimmerMsg.set(newLevel),true); + } + oldButtonVal = buttonVal; +} + +void startFade() { + fadeDelta = ( fadeTo - dimValue ) < 0 ? -1 : 1; + lastFadeStep = millis(); +} + +// This method provides a graceful none-blocking fade up/down effect +void fadeStep() { + unsigned long currentTime = millis(); + if ( dimValue != fadeTo && currentTime > lastFadeStep + FADE_DELAY) { + dimValue += fadeDelta; + analogWrite( LED_PIN, (int)(dimValue / 100. * 255) ); + lastFadeStep = currentTime; + + Serial.print("Fading level: "); + Serial.println(dimValue); + + if (fadeTo == dimValue && changedByKnob) { + sendDimValue = true; + sendDimTimeout = currentTime; + } + } + // Wait a few millisecs before sending in new value (if user still turns the knob) + if (sendDimValue && currentTime > sendDimTimeout + SEND_THROTTLE_DELAY) { + // We're done fading.. send in new dim-value to controller. + // Send in new dim value with ack (will be picked up in incomingMessage) + gw.send(dimmerMsg.set(dimValue), true); // Send new dimmer value and request ack back + sendDimValue = false; + } +} + +// Make sure only to store/fetch values in the range 0-100 from eeprom +int loadLevelState(byte pos) { + return min(max(gw.loadState(pos),0),100); +} +void saveLevelState(byte pos, byte data) { + gw.saveState(pos,min(max(data,0),100)); +} + + + + From b46fae4254ae9cac0886e2ae0125b89469df8bb9 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 21 Apr 2015 23:14:22 +0200 Subject: [PATCH 03/79] Fix pin assignement in example --- .../DimmableLightWithRotaryEncoderButton.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino b/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino index 600e521..dd30b81 100644 --- a/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino +++ b/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino @@ -47,8 +47,8 @@ #include #define LED_PIN 3 // Arduino pin attached to MOSFET Gate pin -#define KNOB_ENC_PIN_1 A0 // Rotary encoder input pin 1 -#define KNOB_ENC_PIN_2 A1 // Rotary encoder input pin 2 +#define KNOB_ENC_PIN_1 4 // Rotary encoder input pin 1 +#define KNOB_ENC_PIN_2 5 // Rotary encoder input pin 2 #define KNOB_BUTTON_PIN 6 // Rotary encoder button pin #define FADE_DELAY 10 // Delay in ms for each percentage fade up/down (10ms = 1s full-range dim) #define SN "DimmableLED /w button" From c137b84b3b02d488fd864956cd54942b87d8e2ce Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 22 Apr 2015 07:20:42 +0200 Subject: [PATCH 04/79] Removed duplicate lines --- .../DimmableLightWithRotaryEncoderButton.ino | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino b/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino index dd30b81..81fe076 100644 --- a/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino +++ b/libraries/MySensors/examples/DimmableLightWithRotaryEncoderButton/DimmableLightWithRotaryEncoderButton.ino @@ -51,6 +51,7 @@ #define KNOB_ENC_PIN_2 5 // Rotary encoder input pin 2 #define KNOB_BUTTON_PIN 6 // Rotary encoder button pin #define FADE_DELAY 10 // Delay in ms for each percentage fade up/down (10ms = 1s full-range dim) +#define SEND_THROTTLE_DELAY 400 // Number of milliseconds before sending after user stops turning knob #define SN "DimmableLED /w button" #define SV "1.2" @@ -62,11 +63,6 @@ #define LIGHT_OFF 0 #define LIGHT_ON 1 -#define SEND_THROTTLE_DELAY 400 // Number of milliseconds before sending after user stops turning knob - -#define SN "Dimmable /w Button" -#define SV "1.0" - int dimValue; int fadeTo; int fadeDelta; @@ -98,7 +94,6 @@ void setup() gw.begin(incomingMessage, AUTO, false); // Send the Sketch Version Information to the Gateway - gw.sendSketchInfo(SN, SV); gw.present(CHILD_ID_LIGHT, S_DIMMER); gw.sendSketchInfo(SN, SV); From a26af52b6d2d3aff5348122db327d80f6083fa75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Sat, 25 Apr 2015 22:11:38 +0200 Subject: [PATCH 05/79] Added versioning info to serial output (for production verification) --- .../examples/MysensorMicro/MysensorMicro.ino | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino index f78d819..5c8ca71 100644 --- a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino +++ b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino @@ -18,6 +18,8 @@ // Define a static node address, remove if you want auto address assignment //#define NODE_ADDRESS 3 +#define RELEASE "1.1" + // Child sensor ID's #define CHILD_ID_TEMP 1 #define CHILD_ID_HUM 2 @@ -66,6 +68,10 @@ void setup() { digitalWrite(LED_PIN, LOW); Serial.begin(115200); + Serial.print(F("Sensebender Micro FW ")); + Serial.print(RELEASE); + Serial.flush(); + // First check if we should boot into test mode pinMode(TEST_PIN,INPUT); @@ -74,7 +80,7 @@ void setup() { digitalWrite(TEST_PIN,LOW); digitalWrite(LED_PIN, HIGH); - + #ifdef NODE_ADDRESS gw.begin(NULL, NODE_ADDRESS, false); #else @@ -84,8 +90,9 @@ void setup() { digitalWrite(LED_PIN, LOW); humiditySensor.begin(); - - gw.sendSketchInfo("Sensebender Micro", "1.0"); + Serial.flush(); + Serial.println(F(" - Online!")); + gw.sendSketchInfo("Sensebender Micro", RELEASE); gw.present(CHILD_ID_TEMP,S_TEMP); gw.present(CHILD_ID_HUM,S_HUM); @@ -105,8 +112,7 @@ void loop() { // This allows us to print debug messages on startup (as serial port is dependend on oscilator settings). if (measureCount == 5) switchClock(1< FORCE_TRANSMIT_INTERVAL - ) { // force a transmission + if (measureCount > FORCE_TRANSMIT_INTERVAL) { // force a transmission forceTransmit = true; measureCount = 0; } @@ -213,7 +219,7 @@ void testMode() byte tests = 0; digitalWrite(LED_PIN, HIGH); // Turn on LED. - + Serial.println(F(" - TestMode")); Serial.println(F("Testing peripherals!")); Serial.flush(); Serial.print(F("-> SI7021 : ")); From bcce65a292ccaf23d2d212fbe8e01b8310d1c52e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Sun, 26 Apr 2015 21:45:43 +0200 Subject: [PATCH 06/79] Small update, that ensures that we only switch to 1Mhz once --- libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino index 5c8ca71..7c5a074 100644 --- a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino +++ b/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino @@ -61,6 +61,7 @@ float lastTemperature = -100; int lastHumidity = -100; long lastBattery = -100; +bool highfreq = true; void setup() { @@ -110,7 +111,7 @@ void loop() { // When we wake up the 5th time after power on, switch to 1Mhz clock // This allows us to print debug messages on startup (as serial port is dependend on oscilator settings). - if (measureCount == 5) switchClock(1< FORCE_TRANSMIT_INTERVAL) { // force a transmission forceTransmit = true; @@ -208,6 +209,7 @@ void switchClock(unsigned char clk) CLKPR = 1< Date: Mon, 4 May 2015 16:18:32 -0300 Subject: [PATCH 07/79] fix check for NULL buffer in getString() --- libraries/MySensors/MyMessage.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/MyMessage.cpp b/libraries/MySensors/MyMessage.cpp index 7143e9c..782ac70 100755 --- a/libraries/MySensors/MyMessage.cpp +++ b/libraries/MySensors/MyMessage.cpp @@ -61,12 +61,11 @@ char* MyMessage::getStream(char *buffer) const { char* MyMessage::getString(char *buffer) const { uint8_t payloadType = miGetPayloadType(); - if (payloadType == P_STRING) { - strncpy(buffer, data, miGetLength()); - buffer[miGetLength()] = 0; - return buffer; - } else if (buffer != NULL) { - if (payloadType == P_BYTE) { + if (buffer != NULL) { + if (payloadType == P_STRING) { + strncpy(buffer, data, miGetLength()); + buffer[miGetLength()] = 0; + } else if (payloadType == P_BYTE) { itoa(bValue, buffer, 10); } else if (payloadType == P_INT16) { itoa(iValue, buffer, 10); From fe04c2789ec1dd0cc7fd38673bba74b58f385912 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 4 May 2015 22:56:52 +0200 Subject: [PATCH 08/79] Rename example sketch --- .../MysensorMicro.ino => SensebenderMicro/SensebenderMicro.ino} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename libraries/MySensors/examples/{MysensorMicro/MysensorMicro.ino => SensebenderMicro/SensebenderMicro.ino} (100%) diff --git a/libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino similarity index 100% rename from libraries/MySensors/examples/MysensorMicro/MysensorMicro.ino rename to libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino From 709d6421baec79ef610deb0a00ef5497f2bcac18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 5 May 2015 19:46:07 +0200 Subject: [PATCH 09/79] Added dualoptiboot to mysensors hardware definitions --- hardware/MySensors/avr/boards.txt | 2 +- .../avr/bootloaders/DualOptiboot/License.txt | 674 +++++++++++ .../avr/bootloaders/DualOptiboot/Makefile | 649 ++++++++++ .../avr/bootloaders/DualOptiboot/README.md | 40 + .../avr/bootloaders/DualOptiboot/boot.h | 848 +++++++++++++ .../avr/bootloaders/DualOptiboot/optiboot.c | 1068 +++++++++++++++++ .../optiboot_atmega328_pro_8MHz.hex | 67 ++ .../optiboot_atmega328_pro_8MHz.lst | 787 ++++++++++++ .../avr/bootloaders/DualOptiboot/pin_defs.h | 742 ++++++++++++ .../avr/bootloaders/DualOptiboot/stk500.h | 39 + 10 files changed, 4915 insertions(+), 1 deletion(-) create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/License.txt create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/Makefile create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/README.md create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/boot.h create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot.c create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.hex create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.lst create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/pin_defs.h create mode 100644 hardware/MySensors/avr/bootloaders/DualOptiboot/stk500.h diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index a603989..7220cad 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -13,7 +13,7 @@ MysensorsMicro.bootloader.lock_bits=0x0F MysensorsMicro.bootloader.low_fuses=0xE2 MysensorsMicro.bootloader.high_fuses=0xD2 MysensorsMicro.bootloader.extended_fuses=0xFE -MysensorsMicro.bootloader.file=DualOptiboot/optiboot_atmega328p-pro8.hex +MysensorsMicro.bootloader.file=DualOptiboot/optiboot_atmega328_pro_8MHz.hex MysensorsMicro.build.board=AVR_MICRO8 MysensorsMicro.build.core=arduino:arduino diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/License.txt b/hardware/MySensors/avr/bootloaders/DualOptiboot/License.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/License.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/Makefile b/hardware/MySensors/avr/bootloaders/DualOptiboot/Makefile new file mode 100644 index 0000000..95c806b --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/Makefile @@ -0,0 +1,649 @@ +# Makefile for ATmegaBOOT +# E.Lins, 18.7.2005 +# $Id$ +# +# Instructions +# +# To make bootloader .hex file: +# make diecimila +# make lilypad +# make ng +# etc... +# +# To burn bootloader .hex file: +# make diecimila_isp +# make lilypad_isp +# make ng_isp +# etc... +# +# Edit History +# 201303xx: WestfW: Major Makefile restructuring. +# Allows options on Make command line "make xx LED=B3" +# (see also pin_defs.h) +# Divide into "chip" targets and "board" targets. +# Most boards are (recursive) board targets with options. +# Move isp target to separate makefile (fixes m8 EFUSE) +# Some (many) targets will now be rebuilt when not +# strictly necessary, so that options will be included. +# (any "make" with options will always compile.) +# Set many variables with ?= so they can be overridden +# Use arduinoISP settings as default for ISP targets +# + +#---------------------------------------------------------------------- +# +# program name should not be changed... +PROGRAM = optiboot + +# The default behavior is to build using tools that are in the users +# current path variables, but we can also build using an installed +# Arduino user IDE setup, or the Arduino source tree. +# Uncomment this next lines to build within the arduino environment, +# using the arduino-included avrgcc toolset (mac and pc) +# ENV ?= arduino +# ENV ?= arduinodev +# OS ?= macosx +# OS ?= windows + +# export symbols to recursive makes (for ISP) +export + +# defaults +MCU_TARGET = atmega168 +LDSECTIONS = -Wl,--section-start=.text=0x3e00 -Wl,--section-start=.version=0x3ffe + +# Build environments +# Start of some ugly makefile-isms to allow optiboot to be built +# in several different environments. See the README.TXT file for +# details. + +# default +fixpath = $(1) + +ifeq ($(ENV), arduino) +# For Arduino, we assume that we're connected to the optiboot directory +# included with the arduino distribution, which means that the full set +# of avr-tools are "right up there" in standard places. +TOOLROOT = ../../../tools +GCCROOT = $(TOOLROOT)/avr/bin/ + +ifeq ($(OS), windows) +# On windows, SOME of the tool paths will need to have backslashes instead +# of forward slashes (because they use windows cmd.exe for execution instead +# of a unix/mingw shell?) We also have to ensure that a consistent shell +# is used even if a unix shell is installed (ie as part of WINAVR) +fixpath = $(subst /,\,$1) +SHELL = cmd.exe +endif + +else ifeq ($(ENV), arduinodev) +# Arduino IDE source code environment. Use the unpacked compilers created +# by the build (you'll need to do "ant build" first.) +ifeq ($(OS), macosx) +TOOLROOT = ../../../../build/macosx/work/Arduino.app/Contents/Resources/Java/hardware/tools +endif +ifeq ($(OS), windows) +TOOLROOT = ../../../../build/windows/work/hardware/tools +endif + +GCCROOT = $(TOOLROOT)/avr/bin/ +AVRDUDE_CONF = -C$(TOOLROOT)/avr/etc/avrdude.conf + +else +GCCROOT = +AVRDUDE_CONF = +endif + +STK500 = "C:\Program Files\Atmel\AVR Tools\STK500\Stk500.exe" +STK500-1 = $(STK500) -e -d$(MCU_TARGET) -pf -vf -if$(PROGRAM)_$(TARGET).hex \ + -lFF -LFF -f$(HFUSE)$(LFUSE) -EF8 -ms -q -cUSB -I200kHz -s -wt +STK500-2 = $(STK500) -d$(MCU_TARGET) -ms -q -lCF -LCF -cUSB -I200kHz -s -wt +# +# End of build environment code. + + +OBJ = $(PROGRAM).o +OPTIMIZE = -Os -fno-inline-small-functions -fno-split-wide-types -mrelax + +DEFS = +LIBS = + +CC = $(GCCROOT)avr-gcc + +# Override is only needed by avr-lib build system. + +override CFLAGS = -g -Wall $(OPTIMIZE) -mmcu=$(MCU_TARGET) -DF_CPU=$(AVR_FREQ) $(DEFS) +override LDFLAGS = $(LDSECTIONS) -Wl,--relax -nostartfiles -nostdlib +#-Wl,--gc-sections + +OBJCOPY = $(GCCROOT)avr-objcopy +OBJDUMP = $(call fixpath,$(GCCROOT)avr-objdump) + +SIZE = $(GCCROOT)avr-size + +# +# Make command-line Options. +# Permit commands like "make atmega328 LED_START_FLASHES=10" to pass the +# appropriate parameters ("-DLED_START_FLASHES=10") to gcc +# + +ifdef BAUD_RATE +BAUD_RATE_CMD = -DBAUD_RATE=$(BAUD_RATE) +dummy = FORCE +else +BAUD_RATE_CMD = -DBAUD_RATE=115200 +endif + +ifdef LED_START_FLASHES +LED_START_FLASHES_CMD = -DLED_START_FLASHES=$(LED_START_FLASHES) +dummy = FORCE +else +LED_START_FLASHES_CMD = -DLED_START_FLASHES=3 +endif + +# BIG_BOOT: Include extra features, up to 1K. +ifdef BIGBOOT +BIGBOOT_CMD = -DBIGBOOT=1 +dummy = FORCE +endif + +ifdef SOFT_UART +SOFT_UART_CMD = -DSOFT_UART=1 +dummy = FORCE +endif + +ifdef LED_DATA_FLASH +LED_DATA_FLASH_CMD = -DLED_DATA_FLASH=1 +dummy = FORCE +endif + +ifdef LED +LED_CMD = -DLED=$(LED) +dummy = FORCE +endif + +ifdef SINGLESPEED +SSCMD = -DSINGLESPEED=1 +endif + +COMMON_OPTIONS = $(BAUD_RATE_CMD) $(LED_START_FLASHES_CMD) $(BIGBOOT_CMD) +COMMON_OPTIONS += $(SOFT_UART_CMD) $(LED_DATA_FLASH_CMD) $(LED_CMD) $(SSCMD) + +#UART is handled separately and only passed for devices with more than one. +ifdef UART +UARTCMD = -DUART=$(UART) +endif + +# Not supported yet +# ifdef SUPPORT_EEPROM +# SUPPORT_EEPROM_CMD = -DSUPPORT_EEPROM +# dummy = FORCE +# endif + +# Not supported yet +# ifdef TIMEOUT_MS +# TIMEOUT_MS_CMD = -DTIMEOUT_MS=$(TIMEOUT_MS) +# dummy = FORCE +# endif +# + +#--------------------------------------------------------------------------- +# "Chip-level Platform" targets. +# A "Chip-level Platform" compiles for a particular chip, but probably does +# not have "standard" values for things like clock speed, LED pin, etc. +# Makes for chip-level platforms should usually explicitly define their +# options like: "make atmega1285 AVR_FREQ=16000000L LED=D0" +#--------------------------------------------------------------------------- +# +# Note about fuses: +# the efuse should really be 0xf8; since, however, only the lower +# three bits of that byte are used on the atmega168, avrdude gets +# confused if you specify 1's for the higher bits, see: +# http://tinker.it/now/2007/02/24/the-tale-of-avrdude-atmega168-and-extended-bits-fuses/ +# +# similarly, the lock bits should be 0xff instead of 0x3f (to +# unlock the bootloader section) and 0xcf instead of 0x2f (to +# lock it), but since the high two bits of the lock byte are +# unused, avrdude would get confused. +#--------------------------------------------------------------------------- +# + +# Test platforms +# Virtual boot block test +virboot328: TARGET = atmega328 +virboot328: MCU_TARGET = atmega328p +virboot328: CFLAGS += $(COMMON_OPTIONS) '-DVIRTUAL_BOOT' +virboot328: AVR_FREQ ?= 16000000L +virboot328: LDSECTIONS = -Wl,--section-start=.text=0x7e00 -Wl,--section-start=.version=0x7ffe +virboot328: $(PROGRAM)_atmega328.hex +virboot328: $(PROGRAM)_atmega328.lst + +# Diecimila, Duemilanove with m168, and NG use identical bootloaders +# Call it "atmega168" for generality and clarity, keep "diecimila" for +# backward compatibility of makefile +# +atmega168: TARGET = atmega168 +atmega168: MCU_TARGET = atmega168 +atmega168: CFLAGS += $(COMMON_OPTIONS) +atmega168: AVR_FREQ ?= 16000000L +atmega168: $(PROGRAM)_atmega168.hex +atmega168: $(PROGRAM)_atmega168.lst + +atmega168_isp: atmega168 +atmega168_isp: TARGET = atmega168 +# 2.7V brownout +atmega168_isp: HFUSE ?= DD +# Low power xtal (16MHz) 16KCK/14CK+65ms +atmega168_isp: LFUSE ?= FF +# 512 byte boot +atmega168_isp: EFUSE ?= 04 +atmega168_isp: isp + +atmega328: TARGET = atmega328 +atmega328: MCU_TARGET = atmega328p +atmega328: CFLAGS += $(COMMON_OPTIONS) +atmega328: AVR_FREQ ?= 16000000L +atmega328: LDSECTIONS = -Wl,--section-start=.text=0x7c00 -Wl,--section-start=.version=0x7ffe +atmega328: $(PROGRAM)_atmega328.hex +atmega328: $(PROGRAM)_atmega328.lst + +atmega328_isp: atmega328 +atmega328_isp: TARGET = atmega328 +atmega328_isp: MCU_TARGET = atmega328p +# 512 byte boot, SPIEN +atmega328_isp: HFUSE ?= DE +# Low power xtal (16MHz) 16KCK/14CK+65ms +atmega328_isp: LFUSE ?= FF +# 2.7V brownout +atmega328_isp: EFUSE ?= FD +atmega328_isp: isp + +atmega644p: TARGET = atmega644p +atmega644p: MCU_TARGET = atmega644p +atmega644p: CFLAGS += $(COMMON_OPTIONS) -DBIGBOOT $(LED_CMD) +atmega644p: AVR_FREQ ?= 16000000L +atmega644p: LDSECTIONS = -Wl,--section-start=.text=0xfc00 -Wl,--section-start=.version=0xfffe +atmega644p: CFLAGS += $(UARTCMD) +atmega644p: $(PROGRAM)_atmega644p.hex +atmega644p: $(PROGRAM)_atmega644p.lst + +atmega1284: TARGET = atmega1284p +atmega1284: MCU_TARGET = atmega1284p +atmega1284: CFLAGS += $(COMMON_OPTIONS) -DBIGBOOT $(LED_CMD) +atmega1284: AVR_FREQ ?= 16000000L +atmega1284: LDSECTIONS = -Wl,--section-start=.text=0x1fc00 -Wl,--section-start=.version=0x1fffe +atmega1284: CFLAGS += $(UARTCMD) +atmega1284: $(PROGRAM)_atmega1284p.hex +atmega1284: $(PROGRAM)_atmega1284p.lst + +atmega1284p: atmega1284 + +atmega1284_isp: atmega1284 +atmega1284_isp: TARGET = atmega1284p +atmega1284_isp: MCU_TARGET = atmega1284p +# 1024 byte boot +atmega1284_isp: HFUSE ?= DE +# Full Swing xtal (16MHz) 16KCK/14CK+65ms +atmega1284_isp: LFUSE ?= F7 +# 2.7V brownout +atmega1284_isp: EFUSE ?= FD +atmega1284_isp: isp + +#Atmega1280 +atmega1280: MCU_TARGET = atmega1280 +atmega1280: CFLAGS += $(COMMON_OPTIONS) -DBIGBOOT $(UART_CMD) +atmega1280: AVR_FREQ ?= 16000000L +atmega1280: LDSECTIONS = -Wl,--section-start=.text=0x1fc00 -Wl,--section-start=.version=0x1fffe +atmega1280: $(PROGRAM)_atmega1280.hex +atmega1280: $(PROGRAM)_atmega1280.lst + + +# ATmega8 +# +atmega8: TARGET = atmega8 +atmega8: MCU_TARGET = atmega8 +atmega8: CFLAGS += $(COMMON_OPTIONS) +atmega8: AVR_FREQ ?= 16000000L +atmega8: LDSECTIONS = -Wl,--section-start=.text=0x1e00 -Wl,--section-start=.version=0x1ffe +atmega8: $(PROGRAM)_atmega8.hex +atmega8: $(PROGRAM)_atmega8.lst + +atmega8_isp: atmega8 +atmega8_isp: TARGET = atmega8 +atmega8_isp: MCU_TARGET = atmega8 +# SPIEN, CKOPT (for full swing xtal), Bootsize=512B +atmega8_isp: HFUSE ?= CC +# 2.7V brownout, 16MHz Xtal, 16KCK/14CK+65ms +atmega8_isp: LFUSE ?= BF +atmega8_isp: isp + +# ATmega88 +# +atmega88: TARGET = atmega88 +atmega88: MCU_TARGET = atmega88 +atmega88: CFLAGS += $(COMMON_OPTIONS) +atmega88: AVR_FREQ ?= 16000000L +atmega88: LDSECTIONS = -Wl,--section-start=.text=0x1e00 -Wl,--section-start=.version=0x1ffe +atmega88: $(PROGRAM)_atmega88.hex +atmega88: $(PROGRAM)_atmega88.lst + +atmega88_isp: atmega88 +atmega88_isp: TARGET = atmega88 +atmega88_isp: MCU_TARGET = atmega88 +# 2.7V brownout +atmega88_isp: HFUSE ?= DD +# Low power xtal (16MHz) 16KCK/14CK+65ms +atemga88_isp: LFUSE ?= FF +# 512 byte boot +atmega88_isp: EFUSE ?= 04 +atmega88_isp: isp + +atmega32: TARGET = atmega32 +atmega32: MCU_TARGET = atmega32 +atmega32: CFLAGS += $(COMMON_OPTIONS) +atmega32: AVR_FREQ ?= 11059200L +atmega32: LDSECTIONS = -Wl,--section-start=.text=0x7e00 -Wl,--section-start=.version=0x7ffe +atmega32: $(PROGRAM)_atmega32.hex +atmega32: $(PROGRAM)_atmega32.lst + +atmega32_isp: atmega32 +atmega32_isp: TARGET = atmega32 +atmega32_isp: MCU_TARGET = atmega32 +# No OCD or JTAG, SPIEN, CKOPT (for full swing xtal), Bootsize=512B +atmega32_isp: HFUSE ?= CE +# 2.7V brownout, 16MHz Xtal, 16KCK/14CK+65ms +atemga32_isp: LFUSE ?= BF +atmega32_isp: isp + + + +#--------------------------------------------------------------------------- +# "Board-level Platform" targets. +# A "Board-level Platform" implies a manufactured platform with a particular +# AVR_FREQ, LED, and so on. Parameters are not particularly changable from +# the "make" command line. +# Most of the board-level platform builds should envoke make recursively +# appropriate specific options +#--------------------------------------------------------------------------- +# 20MHz clocked platforms +# +# These are capable of 230400 baud, or 115200 baud on PC (Arduino Avrdude issue) +# + +pro20: TARGET = pro_20mhz +pro20: CHIP = atmega168 +pro20: + $(MAKE) atmega168 AVR_FREQ=20000000L LED_START_FLASHES=3 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +pro20_isp: pro20 +pro20_isp: TARGET = pro_20mhz +# 2.7V brownout +pro20_isp: HFUSE ?= DD +# Full swing xtal (20MHz) 258CK/14CK+4.1ms +pro20_isp: LFUSE ?= C6 +# 512 byte boot +pro20_isp: EFUSE ?= 04 +pro20_isp: isp + +# 16MHz clocked platforms +# +# These are capable of 230400 baud, or 115200 baud on PC (Arduino Avrdude issue) +# + +pro16: TARGET = pro_16MHz +pro16: CHIP = atmega168 +pro16: + $(MAKE) $(CHIP) AVR_FREQ=16000000L LED_START_FLASHES=3 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +pro16_isp: pro16 +pro16_isp: TARGET = pro_16MHz +# 2.7V brownout +pro16_isp: HFUSE ?= DD +# Full swing xtal (20MHz) 258CK/14CK+4.1ms +pro16_isp: LFUSE ?= C6 +# 512 byte boot +pro16_isp: EFUSE ?= 04 +pro16_isp: isp + +diecimila: TARGET = diecimila +diecimila: CHIP = atmega168 +diecimila: + $(MAKE) $(CHIP) AVR_FREQ=16000000L LED_START_FLASHES=3 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +diecimila_isp: diecimila +diecimila_isp: TARGET = diecimila +# 2.7V brownout +diecimila_isp: HFUSE ?= DD +# Low power xtal (16MHz) 16KCK/14CK+65ms +diecimila_isp: LFUSE ?= FF +# 512 byte boot +diecimila_isp: EFUSE ?= 04 +diecimila_isp: isp + +# Sanguino has a minimum boot size of 1024 bytes, so enable extra functions +# +sanguino: TARGET = $@ +sanguino: CHIP = atmega644p +sanguino: + $(MAKE) $(CHIP) AVR_FREQ=16000000L LED=B0 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +sanguino_isp: sanguino +sanguino_isp: TARGET = sanguino +sanguino_isp: MCU_TARGET = atmega644p +# 1024 byte boot +sanguino_isp: HFUSE ?= DE +# Full swing xtal (16MHz) 16KCK/14CK+65ms +sanguino_isp: LFUSE ?= F7 +# 2.7V brownout +sanguino_isp: EFUSE ?= FD +sanguino_isp: isp + +mighty1284: TARGET = $@ +mighty1284: CHIP = atmega1284p +mighty1284: + $(MAKE) $(CHIP) AVR_FREQ=16000000L LED=D7 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +mighty1284_isp: mighty1284 +mighty1284_isp: TARGET = mighty1284 +mighty1284_isp: MCU_TARGET = atmega1284p +# 1024 byte boot +mighty1284_isp: HFUSE ?= DE +# Full swing xtal (16MHz) 16KCK/14CK+65ms +mighty1284_isp: LFUSE ?= F7 +# 2.7V brownout +mighty1284_isp: EFUSE ?= FD +mighty1284_isp: isp + +bobuino: TARGET = $@ +bobuino: CHIP = atmega1284p +bobuino: + $(MAKE) $(CHIP) AVR_FREQ=16000000L LED=B5 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +bobuino_isp: bobuino +bobuino_isp: TARGET = bobuino +bobuino_isp: MCU_TARGET = atmega1284p +# 1024 byte boot +bobuino_isp: HFUSE ?= DE +# Full swing xtal (16MHz) 16KCK/14CK+65ms +bobuino_isp: LFUSE ?= F7 +# 2.7V brownout +bobuino_isp: EFUSE ?= FD +bobuino_isp: isp + +# MEGA1280 Board (this is different from the atmega1280 chip platform) +# Mega has a minimum boot size of 1024 bytes, so enable extra functions +# Note that optiboot does not (can not) work on the MEGA2560 +#mega: TARGET = atmega1280 +mega1280: atmega1280 + + +mega1280_isp: mega1280 +mega1280_isp: TARGET = atmega1280 +mega1280_isp: MCU_TARGET = atmega1280 +# 1024 byte boot +mega1280_isp: HFUSE ?= DE +# Low power xtal (16MHz) 16KCK/14CK+65ms +mega1280_isp: LFUSE ?= FF +# 2.7V brownout; wants F5 for some reason... +mega1280_isp: EFUSE ?= F5 +mega1280_isp: isp + +# 8MHz clocked platforms +# +# These are capable of 115200 baud +# Note that "new" Arduinos with an AVR as USB/Serial converter will NOT work +# with an 8MHz target Arduino. The bitrate errors are in opposite directions, +# and total too large a number. +# + +lilypad: TARGET = $@ +lilypad: CHIP = atmega168 +lilypad: + $(MAKE) $(CHIP) AVR_FREQ=8000000L LED_START_FLASHES=3 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +lilypad_isp: lilypad +lilypad_isp: TARGET = lilypad +# 2.7V brownout +lilypad_isp: HFUSE ?= DD +# Internal 8MHz osc (8MHz) Slow rising power +lilypad_isp: LFUSE ?= E2 +# 512 byte boot +lilypad_isp: EFUSE ?= 04 +lilypad_isp: isp + +# lilypad_resonator is the same as a 8MHz lilypad, except for fuses. +lilypad_resonator: lilypad + +lilypad_resonator_isp: lilypad +lilypad_resonator_isp: TARGET = lilypad +# 2.7V brownout +lilypad_resonator_isp: HFUSE ?= DD +# Full swing xtal (20MHz) 258CK/14CK+4.1ms +lilypad_resonator_isp: LFUSE ?= C6 +# 512 byte boot +lilypad_resonator_isp: EFUSE ?= 04 +lilypad_resonator_isp: isp + +pro8: TARGET = pro_8MHz +pro8: CHIP = atmega328 +pro8: + $(MAKE) $(CHIP) AVR_FREQ=8000000L LED_START_FLASHES=3 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +pro8_isp: pro8 +pro8_isp: TARGET = pro_8MHz +# 2.7V brownout +pro8_isp: HFUSE ?= DD +# Full swing xtal (20MHz) 258CK/14CK+4.1ms +pro8_isp: LFUSE ?= C6 +# 512 byte boot +pro8_isp: EFUSE ?= 04 +pro8_isp: isp + +atmega328_pro8: TARGET = atmega328_pro_8MHz +atmega328_pro8: CHIP = atmega328 +atmega328_pro8: + $(MAKE) $(CHIP) AVR_FREQ=8000000L LED_START_FLASHES=3 + mv $(PROGRAM)_$(CHIP).hex $(PROGRAM)_$(TARGET).hex + mv $(PROGRAM)_$(CHIP).lst $(PROGRAM)_$(TARGET).lst + +atmega328_pro8_isp: atmega328_pro8 +atmega328_pro8_isp: TARGET = atmega328_pro_8MHz +atmega328_pro8_isp: MCU_TARGET = atmega328p +# 512 byte boot, SPIEN +atmega328_pro8_isp: HFUSE ?= DE +# Low power xtal (16MHz) 16KCK/14CK+65ms +atmega328_pro8_isp: LFUSE ?= FF +# 2.7V brownout +atmega328_pro8_isp: EFUSE ?= DE +atmega328_pro8_isp: isp + +mysensor_micro: atmega328_pro8 +mysensor_micro: target = atmega_pro_8MHz +mysensor_micro: MCU_TARGET = atmega328p +# 512 byte boot, SPIEN +mysensor_micro: HFUSE ?= DE +# Low power xtal (16MHz) 16KCK/14CK+65ms +mysensor_micro: LFUSE ?= FF +# 2.7V brownout +mysensor_micro: EFUSE ?= DE +mysensor_micro: LED=C3 +mysensor_micro: BAUD_RATE=57600 + +# 1MHz clocked platforms +# +# These are capable of 9600 baud +# + +luminet: TARGET = luminet +luminet: MCU_TARGET = attiny84 +luminet: CFLAGS += $(COMMON_OPTIONS) '-DSOFT_UART' '-DBAUD_RATE=9600' +luminet: CFLAGS += '-DVIRTUAL_BOOT_PARTITION' +luminet: AVR_FREQ ?= 1000000L +luminet: LDSECTIONS = -Wl,--section-start=.text=0x1d00 -Wl,--section-start=.version=0x1efe +luminet: $(PROGRAM)_luminet.hex +luminet: $(PROGRAM)_luminet.lst + +luminet_isp: luminet +luminet_isp: TARGET = luminet +luminet_isp: MCU_TARGET = attiny84 +# Brownout disabled +luminet_isp: HFUSE ?= DF +# 1MHz internal oscillator, slowly rising power +luminet_isp: LFUSE ?= 62 +# Self-programming enable +luminet_isp: EFUSE ?= FE +luminet_isp: isp + + +#--------------------------------------------------------------------------- +# +# Generic build instructions +# + +FORCE: + +baudcheck: FORCE + - @$(CC) $(CFLAGS) -E baudcheck.c -o baudcheck.tmp.sh + - @sh baudcheck.tmp.sh + +isp: $(TARGET) + $(MAKE) -f Makefile.isp isp TARGET=$(TARGET) + +isp-stk500: $(PROGRAM)_$(TARGET).hex + $(STK500-1) + $(STK500-2) + +%.elf: $(OBJ) $(dummy) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< $(LIBS) + $(SIZE) $@ + +clean: + rm -rf *.o *.elf *.lst *.map *.sym *.lss *.eep *.srec *.bin *.hex *.tmp.sh + +%.lst: %.elf + $(OBJDUMP) -h -S $< > $@ + +%.hex: %.elf + $(OBJCOPY) -j .text -j .data -j .version --set-section-flags .version=alloc,load -O ihex $< $@ + +%.srec: %.elf + $(OBJCOPY) -j .text -j .data -j .version --set-section-flags .version=alloc,load -O srec $< $@ + +%.bin: %.elf + $(OBJCOPY) -j .text -j .data -j .version --set-section-flags .version=alloc,load -O binary $< $@ diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/README.md b/hardware/MySensors/avr/bootloaders/DualOptiboot/README.md new file mode 100644 index 0000000..06bb760 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/README.md @@ -0,0 +1,40 @@ +DualOptiboot +============ + +Custom Optiboot to add wireless programming capability to Moteino +Copyright Felix Rusu (2013-2014), felix@lowpowerlab.com +More at: http://lowpowerlab.com/Moteino + +This Optiboot version is modified to add the capability of reflashing +from an external SPI flash memory chip. As configured this will work +with Moteino (www.lowpowerlab.com/Moteino) provided a SPI flash chip +is present on the dedicated onboard footprint. +Summary of how this Optiboot version works: +- it looks for an external flash chip +- if one is found (SPI returns valid data) it will further look + for a new sketch flash image signature and size + starting at address 0: FLXIMG:9999:XXXXXXXXXXX + where: - 'FLXIMG' is fixed signature indicating FLASH chip + contains a valid new flash image to be burned + - '9999' are 4 size bytes indicating how long the + new flash image is (how many bytes to read) + - 'XXXXXX' are the de-hexified bytes of the flash + pages to be burned + - ':' colons have fixed positions (delimiters) +- if no valid signature/size are found, it will skip and + function as it normally would (listen to STK500 protocol on serial port) + +The added code will result in a compiled size of just under 1kb +(Originally Optiboot takes just under 0.5kb) + +------------------------------------------------------------------------------------------------------------- + +To compile copy the Optiboot.c and Makefile files where Optiboot is originally located, mine is at: +arduino-install-dir\hardware\arduino\bootloaders\optiboot\ +Backup the original files andbefore overwrite both files. +Then compile by running: +make atmega328 +make atmega1284p + +##License +GPL 3.0. See License.txt file. \ No newline at end of file diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/boot.h b/hardware/MySensors/avr/bootloaders/DualOptiboot/boot.h new file mode 100644 index 0000000..2639cd8 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/boot.h @@ -0,0 +1,848 @@ +/* Modified to use out for SPM access +** Peter Knight, Optiboot project http://optiboot.googlecode.com +** +** Todo: Tidy up +** +** "_short" routines execute 1 cycle faster and use 1 less word of flash +** by using "out" instruction instead of "sts". +** +** Additional elpm variants that trust the value of RAMPZ +*/ + +/* Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Eric B. Weddington + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + * Neither the name of the copyright holders nor the names of + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. */ + +/* $Id: boot.h,v 1.27.2.3 2008/09/30 13:58:48 arcanum Exp $ */ + +#ifndef _AVR_BOOT_H_ +#define _AVR_BOOT_H_ 1 + +/** \file */ +/** \defgroup avr_boot : Bootloader Support Utilities + \code + #include + #include + \endcode + + The macros in this module provide a C language interface to the + bootloader support functionality of certain AVR processors. These + macros are designed to work with all sizes of flash memory. + + Global interrupts are not automatically disabled for these macros. It + is left up to the programmer to do this. See the code example below. + Also see the processor datasheet for caveats on having global interrupts + enabled during writing of the Flash. + + \note Not all AVR processors provide bootloader support. See your + processor datasheet to see if it provides bootloader support. + + \todo From email with Marek: On smaller devices (all except ATmega64/128), + __SPM_REG is in the I/O space, accessible with the shorter "in" and "out" + instructions - since the boot loader has a limited size, this could be an + important optimization. + + \par API Usage Example + The following code shows typical usage of the boot API. + + \code + #include + #include + #include + + void boot_program_page (uint32_t page, uint8_t *buf) + { + uint16_t i; + uint8_t sreg; + + // Disable interrupts. + + sreg = SREG; + cli(); + + eeprom_busy_wait (); + + boot_page_erase (page); + boot_spm_busy_wait (); // Wait until the memory is erased. + + for (i=0; i +#include +#include +#include + +/* Check for SPM Control Register in processor. */ +#if defined (SPMCSR) +# define __SPM_REG SPMCSR +#elif defined (SPMCR) +# define __SPM_REG SPMCR +#else +# error AVR processor does not provide bootloader support! +#endif + + +/* Check for SPM Enable bit. */ +#if defined(SPMEN) +# define __SPM_ENABLE SPMEN +#elif defined(SELFPRGEN) +# define __SPM_ENABLE SELFPRGEN +#else +# error Cannot find SPM Enable bit definition! +#endif + +/** \ingroup avr_boot + \def BOOTLOADER_SECTION + + Used to declare a function or variable to be placed into a + new section called .bootloader. This section and its contents + can then be relocated to any address (such as the bootloader + NRWW area) at link-time. */ + +#define BOOTLOADER_SECTION __attribute__ ((section (".bootloader"))) + +/* Create common bit definitions. */ +#ifdef ASB +#define __COMMON_ASB ASB +#else +#define __COMMON_ASB RWWSB +#endif + +#ifdef ASRE +#define __COMMON_ASRE ASRE +#else +#define __COMMON_ASRE RWWSRE +#endif + +/* Define the bit positions of the Boot Lock Bits. */ + +#define BLB12 5 +#define BLB11 4 +#define BLB02 3 +#define BLB01 2 + +/** \ingroup avr_boot + \def boot_spm_interrupt_enable() + Enable the SPM interrupt. */ + +#define boot_spm_interrupt_enable() (__SPM_REG |= (uint8_t)_BV(SPMIE)) + +/** \ingroup avr_boot + \def boot_spm_interrupt_disable() + Disable the SPM interrupt. */ + +#define boot_spm_interrupt_disable() (__SPM_REG &= (uint8_t)~_BV(SPMIE)) + +/** \ingroup avr_boot + \def boot_is_spm_interrupt() + Check if the SPM interrupt is enabled. */ + +#define boot_is_spm_interrupt() (__SPM_REG & (uint8_t)_BV(SPMIE)) + +/** \ingroup avr_boot + \def boot_rww_busy() + Check if the RWW section is busy. */ + +#define boot_rww_busy() (__SPM_REG & (uint8_t)_BV(__COMMON_ASB)) + +/** \ingroup avr_boot + \def boot_spm_busy() + Check if the SPM instruction is busy. */ + +#define boot_spm_busy() (__SPM_REG & (uint8_t)_BV(__SPM_ENABLE)) + +/** \ingroup avr_boot + \def boot_spm_busy_wait() + Wait while the SPM instruction is busy. */ + +#define boot_spm_busy_wait() do{}while(boot_spm_busy()) + +#define __BOOT_PAGE_ERASE (_BV(__SPM_ENABLE) | _BV(PGERS)) +#define __BOOT_PAGE_WRITE (_BV(__SPM_ENABLE) | _BV(PGWRT)) +#define __BOOT_PAGE_FILL _BV(__SPM_ENABLE) +#define __BOOT_RWW_ENABLE (_BV(__SPM_ENABLE) | _BV(__COMMON_ASRE)) +#define __BOOT_LOCK_BITS_SET (_BV(__SPM_ENABLE) | _BV(BLBSET)) + +#define __boot_page_fill_short(address, data) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r0, %3\n\t" \ + "out %0, %1\n\t" \ + "spm\n\t" \ + "clr r1\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_FILL), \ + "z" ((uint16_t)address), \ + "r" ((uint16_t)data) \ + : "r0" \ + ); \ +})) + +#define __boot_page_fill_normal(address, data) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r0, %3\n\t" \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + "clr r1\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_FILL), \ + "z" ((uint16_t)address), \ + "r" ((uint16_t)data) \ + : "r0" \ + ); \ +})) + +#define __boot_page_fill_alternate(address, data)\ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r0, %3\n\t" \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + ".word 0xffff\n\t" \ + "nop\n\t" \ + "clr r1\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_FILL), \ + "z" ((uint16_t)address), \ + "r" ((uint16_t)data) \ + : "r0" \ + ); \ +})) + +#define __boot_page_fill_extended(address, data) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r0, %4\n\t" \ + "movw r30, %A3\n\t" \ + "sts %1, %C3\n\t" \ + "sts %0, %2\n\t" \ + "spm\n\t" \ + "clr r1\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "i" (_SFR_MEM_ADDR(RAMPZ)), \ + "r" ((uint8_t)__BOOT_PAGE_FILL), \ + "r" ((uint32_t)address), \ + "r" ((uint16_t)data) \ + : "r0", "r30", "r31" \ + ); \ +})) + +#define __boot_page_fill_extended_short(address, data) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r0, %4\n\t" \ + "movw r30, %A3\n\t" \ + "out %1, %C3\n\t" \ + "out %0, %2\n\t" \ + "spm\n\t" \ + "clr r1\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "i" (_SFR_IO_ADDR(RAMPZ)), \ + "r" ((uint8_t)__BOOT_PAGE_FILL), \ + "r" ((uint32_t)address), \ + "r" ((uint16_t)data) \ + : "r0", "r30", "r31" \ + ); \ +})) + +#define __boot_page_erase_short(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "out %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_ERASE), \ + "z" ((uint16_t)address) \ + ); \ +})) + + +#define __boot_page_erase_normal(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_ERASE), \ + "z" ((uint16_t)address) \ + ); \ +})) + +#define __boot_page_erase_alternate(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + ".word 0xffff\n\t" \ + "nop\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_ERASE), \ + "z" ((uint16_t)address) \ + ); \ +})) + +#define __boot_page_erase_extended(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r30, %A3\n\t" \ + "sts %1, %C3\n\t" \ + "sts %0, %2\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "i" (_SFR_MEM_ADDR(RAMPZ)), \ + "r" ((uint8_t)__BOOT_PAGE_ERASE), \ + "r" ((uint32_t)address) \ + : "r30", "r31" \ + ); \ +})) +#define __boot_page_erase_extended_short(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r30, %A3\n\t" \ + "out %1, %C3\n\t" \ + "out %0, %2\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "i" (_SFR_IO_ADDR(RAMPZ)), \ + "r" ((uint8_t)__BOOT_PAGE_ERASE), \ + "r" ((uint32_t)address) \ + : "r30", "r31" \ + ); \ +})) + +#define __boot_page_write_short(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "out %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_WRITE), \ + "z" ((uint16_t)address) \ + ); \ +})) + +#define __boot_page_write_normal(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_WRITE), \ + "z" ((uint16_t)address) \ + ); \ +})) + +#define __boot_page_write_alternate(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + ".word 0xffff\n\t" \ + "nop\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_PAGE_WRITE), \ + "z" ((uint16_t)address) \ + ); \ +})) + +#define __boot_page_write_extended(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r30, %A3\n\t" \ + "sts %1, %C3\n\t" \ + "sts %0, %2\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "i" (_SFR_MEM_ADDR(RAMPZ)), \ + "r" ((uint8_t)__BOOT_PAGE_WRITE), \ + "r" ((uint32_t)address) \ + : "r30", "r31" \ + ); \ +})) +#define __boot_page_write_extended_short(address) \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "movw r30, %A3\n\t" \ + "out %1, %C3\n\t" \ + "out %0, %2\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "i" (_SFR_IO_ADDR(RAMPZ)), \ + "r" ((uint8_t)__BOOT_PAGE_WRITE), \ + "r" ((uint32_t)address) \ + : "r30", "r31" \ + ); \ +})) + +#define __boot_rww_enable_short() \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "out %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_RWW_ENABLE) \ + ); \ +})) + +#define __boot_rww_enable() \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_RWW_ENABLE) \ + ); \ +})) + +#define __boot_rww_enable_alternate() \ +(__extension__({ \ + __asm__ __volatile__ \ + ( \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + ".word 0xffff\n\t" \ + "nop\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_RWW_ENABLE) \ + ); \ +})) + +/* From the mega16/mega128 data sheets (maybe others): + + Bits by SPM To set the Boot Loader Lock bits, write the desired data to + R0, write "X0001001" to SPMCR and execute SPM within four clock cycles + after writing SPMCR. The only accessible Lock bits are the Boot Lock bits + that may prevent the Application and Boot Loader section from any + software update by the MCU. + + If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock bit + will be programmed if an SPM instruction is executed within four cycles + after BLBSET and SPMEN (or SELFPRGEN) are set in SPMCR. The Z-pointer is + don't care during this operation, but for future compatibility it is + recommended to load the Z-pointer with $0001 (same as used for reading the + Lock bits). For future compatibility It is also recommended to set bits 7, + 6, 1, and 0 in R0 to 1 when writing the Lock bits. When programming the + Lock bits the entire Flash can be read during the operation. */ + +#define __boot_lock_bits_set_short(lock_bits) \ +(__extension__({ \ + uint8_t value = (uint8_t)(~(lock_bits)); \ + __asm__ __volatile__ \ + ( \ + "ldi r30, 1\n\t" \ + "ldi r31, 0\n\t" \ + "mov r0, %2\n\t" \ + "out %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_LOCK_BITS_SET), \ + "r" (value) \ + : "r0", "r30", "r31" \ + ); \ +})) + +#define __boot_lock_bits_set(lock_bits) \ +(__extension__({ \ + uint8_t value = (uint8_t)(~(lock_bits)); \ + __asm__ __volatile__ \ + ( \ + "ldi r30, 1\n\t" \ + "ldi r31, 0\n\t" \ + "mov r0, %2\n\t" \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_LOCK_BITS_SET), \ + "r" (value) \ + : "r0", "r30", "r31" \ + ); \ +})) + +#define __boot_lock_bits_set_alternate(lock_bits) \ +(__extension__({ \ + uint8_t value = (uint8_t)(~(lock_bits)); \ + __asm__ __volatile__ \ + ( \ + "ldi r30, 1\n\t" \ + "ldi r31, 0\n\t" \ + "mov r0, %2\n\t" \ + "sts %0, %1\n\t" \ + "spm\n\t" \ + ".word 0xffff\n\t" \ + "nop\n\t" \ + : \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_LOCK_BITS_SET), \ + "r" (value) \ + : "r0", "r30", "r31" \ + ); \ +})) + +/* + Reading lock and fuse bits: + + Similarly to writing the lock bits above, set BLBSET and SPMEN (or + SELFPRGEN) bits in __SPMREG, and then (within four clock cycles) issue an + LPM instruction. + + Z address: contents: + 0x0000 low fuse bits + 0x0001 lock bits + 0x0002 extended fuse bits + 0x0003 high fuse bits + + Sounds confusing, doesn't it? + + Unlike the macros in pgmspace.h, no need to care for non-enhanced + cores here as these old cores do not provide SPM support anyway. + */ + +/** \ingroup avr_boot + \def GET_LOW_FUSE_BITS + address to read the low fuse bits, using boot_lock_fuse_bits_get + */ +#define GET_LOW_FUSE_BITS (0x0000) +/** \ingroup avr_boot + \def GET_LOCK_BITS + address to read the lock bits, using boot_lock_fuse_bits_get + */ +#define GET_LOCK_BITS (0x0001) +/** \ingroup avr_boot + \def GET_EXTENDED_FUSE_BITS + address to read the extended fuse bits, using boot_lock_fuse_bits_get + */ +#define GET_EXTENDED_FUSE_BITS (0x0002) +/** \ingroup avr_boot + \def GET_HIGH_FUSE_BITS + address to read the high fuse bits, using boot_lock_fuse_bits_get + */ +#define GET_HIGH_FUSE_BITS (0x0003) + +/** \ingroup avr_boot + \def boot_lock_fuse_bits_get(address) + + Read the lock or fuse bits at \c address. + + Parameter \c address can be any of GET_LOW_FUSE_BITS, + GET_LOCK_BITS, GET_EXTENDED_FUSE_BITS, or GET_HIGH_FUSE_BITS. + + \note The lock and fuse bits returned are the physical values, + i.e. a bit returned as 0 means the corresponding fuse or lock bit + is programmed. + */ +#define boot_lock_fuse_bits_get_short(address) \ +(__extension__({ \ + uint8_t __result; \ + __asm__ __volatile__ \ + ( \ + "ldi r30, %3\n\t" \ + "ldi r31, 0\n\t" \ + "out %1, %2\n\t" \ + "lpm %0, Z\n\t" \ + : "=r" (__result) \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_LOCK_BITS_SET), \ + "M" (address) \ + : "r0", "r30", "r31" \ + ); \ + __result; \ +})) + +#define boot_lock_fuse_bits_get(address) \ +(__extension__({ \ + uint8_t __result; \ + __asm__ __volatile__ \ + ( \ + "ldi r30, %3\n\t" \ + "ldi r31, 0\n\t" \ + "sts %1, %2\n\t" \ + "lpm %0, Z\n\t" \ + : "=r" (__result) \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t)__BOOT_LOCK_BITS_SET), \ + "M" (address) \ + : "r0", "r30", "r31" \ + ); \ + __result; \ +})) + +/** \ingroup avr_boot + \def boot_signature_byte_get(address) + + Read the Signature Row byte at \c address. For some MCU types, + this function can also retrieve the factory-stored oscillator + calibration bytes. + + Parameter \c address can be 0-0x1f as documented by the datasheet. + \note The values are MCU type dependent. +*/ + +#define __BOOT_SIGROW_READ (_BV(__SPM_ENABLE) | _BV(SIGRD)) + +#define boot_signature_byte_get_short(addr) \ +(__extension__({ \ + uint16_t __addr16 = (uint16_t)(addr); \ + uint8_t __result; \ + __asm__ __volatile__ \ + ( \ + "out %1, %2\n\t" \ + "lpm %0, Z" "\n\t" \ + : "=r" (__result) \ + : "i" (_SFR_IO_ADDR(__SPM_REG)), \ + "r" ((uint8_t) __BOOT_SIGROW_READ), \ + "z" (__addr16) \ + ); \ + __result; \ +})) + +#define boot_signature_byte_get(addr) \ +(__extension__({ \ + uint16_t __addr16 = (uint16_t)(addr); \ + uint8_t __result; \ + __asm__ __volatile__ \ + ( \ + "sts %1, %2\n\t" \ + "lpm %0, Z" "\n\t" \ + : "=r" (__result) \ + : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ + "r" ((uint8_t) __BOOT_SIGROW_READ), \ + "z" (__addr16) \ + ); \ + __result; \ +})) + +/** \ingroup avr_boot + \def boot_page_fill(address, data) + + Fill the bootloader temporary page buffer for flash + address with data word. + + \note The address is a byte address. The data is a word. The AVR + writes data to the buffer a word at a time, but addresses the buffer + per byte! So, increment your address by 2 between calls, and send 2 + data bytes in a word format! The LSB of the data is written to the lower + address; the MSB of the data is written to the higher address.*/ + +/** \ingroup avr_boot + \def boot_page_erase(address) + + Erase the flash page that contains address. + + \note address is a byte address in flash, not a word address. */ + +/** \ingroup avr_boot + \def boot_page_write(address) + + Write the bootloader temporary page buffer + to flash page that contains address. + + \note address is a byte address in flash, not a word address. */ + +/** \ingroup avr_boot + \def boot_rww_enable() + + Enable the Read-While-Write memory section. */ + +/** \ingroup avr_boot + \def boot_lock_bits_set(lock_bits) + + Set the bootloader lock bits. + + \param lock_bits A mask of which Boot Loader Lock Bits to set. + + \note In this context, a 'set bit' will be written to a zero value. + Note also that only BLBxx bits can be programmed by this command. + + For example, to disallow the SPM instruction from writing to the Boot + Loader memory section of flash, you would use this macro as such: + + \code + boot_lock_bits_set (_BV (BLB11)); + \endcode + + \note Like any lock bits, the Boot Loader Lock Bits, once set, + cannot be cleared again except by a chip erase which will in turn + also erase the boot loader itself. */ + +/* Normal versions of the macros use 16-bit addresses. + Extended versions of the macros use 32-bit addresses. + Alternate versions of the macros use 16-bit addresses and require special + instruction sequences after LPM. + + FLASHEND is defined in the ioXXXX.h file. + USHRT_MAX is defined in . */ + +#if defined(__AVR_ATmega161__) || defined(__AVR_ATmega163__) \ + || defined(__AVR_ATmega323__) + +/* Alternate: ATmega161/163/323 and 16 bit address */ +#define boot_page_fill(address, data) __boot_page_fill_alternate(address, data) +#define boot_page_erase(address) __boot_page_erase_alternate(address) +#define boot_page_write(address) __boot_page_write_alternate(address) +#define boot_rww_enable() __boot_rww_enable_alternate() +#define boot_lock_bits_set(lock_bits) __boot_lock_bits_set_alternate(lock_bits) + +#elif (FLASHEND > USHRT_MAX) + +/* Extended: >16 bit address */ +#define boot_page_fill(address, data) __boot_page_fill_extended_short(address, data) +#define boot_page_erase(address) __boot_page_erase_extended_short(address) +#define boot_page_write(address) __boot_page_write_extended_short(address) +#define boot_rww_enable() __boot_rww_enable_short() +#define boot_lock_bits_set(lock_bits) __boot_lock_bits_set_short(lock_bits) + +#else + +/* Normal: 16 bit address */ +#define boot_page_fill(address, data) __boot_page_fill_short(address, data) +#define boot_page_erase(address) __boot_page_erase_short(address) +#define boot_page_write(address) __boot_page_write_short(address) +#define boot_rww_enable() __boot_rww_enable_short() +#define boot_lock_bits_set(lock_bits) __boot_lock_bits_set_short(lock_bits) + +#endif + +/** \ingroup avr_boot + + Same as boot_page_fill() except it waits for eeprom and spm operations to + complete before filling the page. */ + +#define boot_page_fill_safe(address, data) \ +do { \ + boot_spm_busy_wait(); \ + eeprom_busy_wait(); \ + boot_page_fill(address, data); \ +} while (0) + +/** \ingroup avr_boot + + Same as boot_page_erase() except it waits for eeprom and spm operations to + complete before erasing the page. */ + +#define boot_page_erase_safe(address) \ +do { \ + boot_spm_busy_wait(); \ + eeprom_busy_wait(); \ + boot_page_erase (address); \ +} while (0) + +/** \ingroup avr_boot + + Same as boot_page_write() except it waits for eeprom and spm operations to + complete before writing the page. */ + +#define boot_page_write_safe(address) \ +do { \ + boot_spm_busy_wait(); \ + eeprom_busy_wait(); \ + boot_page_write (address); \ +} while (0) + +/** \ingroup avr_boot + + Same as boot_rww_enable() except waits for eeprom and spm operations to + complete before enabling the RWW mameory. */ + +#define boot_rww_enable_safe() \ +do { \ + boot_spm_busy_wait(); \ + eeprom_busy_wait(); \ + boot_rww_enable(); \ +} while (0) + +/** \ingroup avr_boot + + Same as boot_lock_bits_set() except waits for eeprom and spm operations to + complete before setting the lock bits. */ + +#define boot_lock_bits_set_safe(lock_bits) \ +do { \ + boot_spm_busy_wait(); \ + eeprom_busy_wait(); \ + boot_lock_bits_set (lock_bits); \ +} while (0) + +#endif /* _AVR_BOOT_H_ */ diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot.c b/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot.c new file mode 100644 index 0000000..a527c28 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot.c @@ -0,0 +1,1068 @@ +////////////////////////////////////////////////////////////////////////// +// +// DualOptiboot +// Optiboot based custom bootloader for Moteino +// Enables wireless programming of Moteino wireless arduino clone +// Copyright Felix Rusu (2013), felix@lowpowerlab.com +// http://lowpowerlab.com/Moteino +// +////////////////////////////////////////////////////////////////////////// +// +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program 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 General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program; if not, write +// to the Free Software Foundation, Inc., +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Licence can be viewed at +// http://www.fsf.org/licenses/gpl.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code +// +////////////////////////////////////////////////////////////////////////// +// +// This Optiboot version is modified to add the capability of reflashing +// from an external SPI flash memory chip. As configured this will work +// with Moteino (www.lowpowerlab.com/Moteino) provided a SPI flash chip +// is present on the dedicated onboard footprint. +// Summary of how this Optiboot version works: +// - it looks for an external flash chip +// - if one is found (SPI returns valid data) it will further look +// for a new sketch flash image signature and size +// starting at address 0: FLXIMG:NN:XXXXXXXXXXX +// where: - 'FLXIMG' is fixed signature indicating FLASH chip +// contains a valid new flash image to be burned +// - 'NN' are 2 size bytes (uint_16) indicating how long the +// new flash image is (how many bytes to read), max 65536Bytes +// - 'XXXXXX' are the de-hexified bytes of the flash +// pages to be burned +// - ':' colons have fixed positions (delimiters) +// - if no valid signature/size are found, it will skip and +// function as it normally would (listen to STK500 protocol on serial port) +// +// The added code will result in a compiled size of just under 1kb +// (Originally Optiboot takes just under 0.5kb) +// - Examples at: http://lowpowerlab.com/blog/category/moteino/wireless-programming/ +// - Tested on atmega328P and atmega644/1284P +// - Limited to 31K sketches for atmega328p and 64K sketches for atmega1284P. +////////////////////////////////////////////////////////////////////////// +/**********************************************************/ +/* Optiboot bootloader for Arduino */ +/* */ +/* http://optiboot.googlecode.com */ +/* */ +/* Arduino-maintained version : See README.TXT */ +/* http://code.google.com/p/arduino/ */ +/* It is the intent that changes not relevant to the */ +/* Arduino production envionment get moved from the */ +/* optiboot project to the arduino project in "lumps." */ +/* */ +/* Heavily optimised bootloader that is faster and */ +/* smaller than the Arduino standard bootloader */ +/* */ +/* Enhancements: */ +/* Fits in 512 bytes, saving 1.5K of code space */ +/* Background page erasing speeds up programming */ +/* Higher baud rate speeds up programming */ +/* Written almost entirely in C */ +/* Customisable timeout with accurate timeconstant */ +/* Optional virtual UART. No hardware UART required. */ +/* Optional virtual boot partition for devices without. */ +/* */ +/* What you lose: */ +/* Implements a skeleton STK500 protocol which is */ +/* missing several features including EEPROM */ +/* programming and non-page-aligned writes */ +/* High baud rate breaks compatibility with standard */ +/* Arduino flash settings */ +/* */ +/* Fully supported: */ +/* ATmega168 based devices (Diecimila etc) */ +/* ATmega328P based devices (Duemilanove etc) */ +/* */ +/* Beta test (believed working.) */ +/* ATmega8 based devices (Arduino legacy) */ +/* ATmega328 non-picopower devices */ +/* ATmega644P based devices (Sanguino) */ +/* ATmega1284P based devices */ +/* ATmega1280 based devices (Arduino Mega) */ +/* */ +/* Alpha test */ +/* ATmega32 */ +/* */ +/* Work in progress: */ +/* ATtiny84 based devices (Luminet) */ +/* */ +/* Does not support: */ +/* USB based devices (eg. Teensy, Leonardo) */ +/* */ +/* Assumptions: */ +/* The code makes several assumptions that reduce the */ +/* code size. They are all true after a hardware reset, */ +/* but may not be true if the bootloader is called by */ +/* other means or on other hardware. */ +/* No interrupts can occur */ +/* UART and Timer 1 are set to their reset state */ +/* SP points to RAMEND */ +/* */ +/* Code builds on code, libraries and optimisations from: */ +/* stk500boot.c by Jason P. Kyle */ +/* Arduino bootloader http://arduino.cc */ +/* Spiff's 1K bootloader http://spiffie.org/know/arduino_1k_bootloader/bootloader.shtml */ +/* avr-libc project http://nongnu.org/avr-libc */ +/* Adaboot http://www.ladyada.net/library/arduino/bootloader.html */ +/* AVR305 Atmel Application Note */ +/* */ +/* This program is free software; you can redistribute it */ +/* and/or modify it under the terms of the GNU General */ +/* Public License as published by the Free Software */ +/* Foundation; either version 2 of the License, or */ +/* (at your option) any later version. */ +/* */ +/* This program 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 General Public */ +/* License for more details. */ +/* */ +/* You should have received a copy of the GNU General */ +/* Public License along with this program; if not, write */ +/* to the Free Software Foundation, Inc., */ +/* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +/* */ +/* Licence can be viewed at */ +/* http://www.fsf.org/licenses/gpl.txt */ +/* */ +/**********************************************************/ + + +/**********************************************************/ +/* */ +/* Optional defines: */ +/* */ +/**********************************************************/ +/* */ +/* BIG_BOOT: */ +/* Build a 1k bootloader, not 512 bytes. This turns on */ +/* extra functionality. */ +/* */ +/* BAUD_RATE: */ +/* Set bootloader baud rate. */ +/* */ +/* LUDICROUS_SPEED: */ +/* 230400 baud :-) */ +/* */ +/* SOFT_UART: */ +/* Use AVR305 soft-UART instead of hardware UART. */ +/* */ +/* LED_START_FLASHES: */ +/* Number of LED flashes on bootup. */ +/* */ +/* LED_DATA_FLASH: */ +/* Flash LED when transferring data. For boards without */ +/* TX or RX LEDs, or for people who like blinky lights. */ +/* */ +/* SUPPORT_EEPROM: */ +/* Support reading and writing from EEPROM. This is not */ +/* used by Arduino, so off by default. */ +/* */ +/* TIMEOUT_MS: */ +/* Bootloader timeout period, in milliseconds. */ +/* 500,1000,2000,4000,8000 supported. */ +/* */ +/* UART: */ +/* UART number (0..n) for devices with more than */ +/* one hardware uart (644P, 1284P, etc) */ +/* */ +/**********************************************************/ + +/**********************************************************/ +/* Version Numbers! */ +/* */ +/* Arduino Optiboot now includes this Version number in */ +/* the source and object code. */ +/* */ +/* Version 3 was released as zip from the optiboot */ +/* repository and was distributed with Arduino 0022. */ +/* Version 4 starts with the arduino repository commit */ +/* that brought the arduino repository up-to-date with */ +/* the optiboot source tree changes since v3. */ +/* Version 5 was created at the time of the new Makefile */ +/* structure (Mar, 2013), even though no binaries changed*/ +/* It would be good if versions implemented outside the */ +/* official repository used an out-of-seqeunce version */ +/* number (like 104.6 if based on based on 4.5) to */ +/* prevent collisions. */ +/* */ +/**********************************************************/ + +/**********************************************************/ +/* Edit History: */ +/* */ +/* Mar 2013 */ +/* 5.0 WestfW: Major Makefile restructuring. */ +/* See Makefile and pin_defs.h */ +/* (no binary changes) */ +/* */ +/* 4.6 WestfW/Pito: Add ATmega32 support */ +/* 4.6 WestfW/radoni: Don't set LED_PIN as an output if */ +/* not used. (LED_START_FLASHES = 0) */ +/* Jan 2013 */ +/* 4.6 WestfW/dkinzer: use autoincrement lpm for read */ +/* 4.6 WestfW/dkinzer: pass reset cause to app in R2 */ +/* Mar 2012 */ +/* 4.5 WestfW: add infrastructure for non-zero UARTS. */ +/* 4.5 WestfW: fix SIGNATURE_2 for m644 (bad in avr-libc) */ +/* Jan 2012: */ +/* 4.5 WestfW: fix NRWW value for m1284. */ +/* 4.4 WestfW: use attribute OS_main instead of naked for */ +/* main(). This allows optimizations that we */ +/* count on, which are prohibited in naked */ +/* functions due to PR42240. (keeps us less */ +/* than 512 bytes when compiler is gcc4.5 */ +/* (code from 4.3.2 remains the same.) */ +/* 4.4 WestfW and Maniacbug: Add m1284 support. This */ +/* does not change the 328 binary, so the */ +/* version number didn't change either. (?) */ +/* June 2011: */ +/* 4.4 WestfW: remove automatic soft_uart detect (didn't */ +/* know what it was doing or why.) Added a */ +/* check of the calculated BRG value instead. */ +/* Version stays 4.4; existing binaries are */ +/* not changed. */ +/* 4.4 WestfW: add initialization of address to keep */ +/* the compiler happy. Change SC'ed targets. */ +/* Return the SW version via READ PARAM */ +/* 4.3 WestfW: catch framing errors in getch(), so that */ +/* AVRISP works without HW kludges. */ +/* http://code.google.com/p/arduino/issues/detail?id=368n*/ +/* 4.2 WestfW: reduce code size, fix timeouts, change */ +/* verifySpace to use WDT instead of appstart */ +/* 4.1 WestfW: put version number in binary. */ +/**********************************************************/ + +#define LED_DATA_FLASH 1 +#define OPTIBOOT_MAJVER 5 +#define OPTIBOOT_MINVER 0 + +#define MAKESTR(a) #a +#define MAKEVER(a, b) MAKESTR(a*256+b) + +asm(" .section .version\n" + "optiboot_version: .word " MAKEVER(OPTIBOOT_MAJVER, OPTIBOOT_MINVER) "\n" + " .section .text\n"); + +#include +#include +#include + +// uses sts instructions, but this version uses out instructions +// This saves cycles and program memory. +#include "boot.h" + + +// We don't use as those routines have interrupt overhead we don't need. + +#include "pin_defs.h" +#include "stk500.h" + +#ifndef LED_START_FLASHES +#define LED_START_FLASHES 1 +#endif + +#ifdef LUDICROUS_SPEED +#define BAUD_RATE 230400L +#endif + +/* set the UART baud rate defaults */ +#ifndef BAUD_RATE +#if F_CPU >= 8000000L +#define BAUD_RATE 115200L // Highest rate Avrdude win32 will support +#elsif F_CPU >= 1000000L +#define BAUD_RATE 9600L // 19200 also supported, but with significant error +#elsif F_CPU >= 128000L +#define BAUD_RATE 4800L // Good for 128kHz internal RC +#else +#define BAUD_RATE 1200L // Good even at 32768Hz +#endif +#endif + +#ifndef UART +#define UART 0 +#endif + +#define BAUD_SETTING (( (F_CPU + BAUD_RATE * 4L) / ((BAUD_RATE * 8L))) - 1 ) +#define BAUD_ACTUAL (F_CPU/(8 * ((BAUD_SETTING)+1))) +#define BAUD_ERROR (( 100*(BAUD_RATE - BAUD_ACTUAL) ) / BAUD_RATE) + +#if BAUD_ERROR >= 5 +#error BAUD_RATE error greater than 5% +#elif BAUD_ERROR <= -5 +#error BAUD_RATE error greater than -5% +#elif BAUD_ERROR >= 2 +#warning BAUD_RATE error greater than 2% +#elif BAUD_ERROR <= -2 +#warning BAUD_RATE error greater than -2% +#endif + +#if 0 +/* Switch in soft UART for hard baud rates */ +/* + * I don't understand what this was supposed to accomplish, where the + * constant "280" came from, or why automatically (and perhaps unexpectedly) + * switching to a soft uart is a good thing, so I'm undoing this in favor + * of a range check using the same calc used to config the BRG... + */ +#if (F_CPU/BAUD_RATE) > 280 // > 57600 for 16MHz +#ifndef SOFT_UART +#define SOFT_UART +#endif +#endif +#else // 0 +#if (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 > 250 +#error Unachievable baud rate (too slow) BAUD_RATE +#endif // baud rate slow check +#if (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 < 3 +#error Unachievable baud rate (too fast) BAUD_RATE +#endif // baud rate fastn check +#endif + +/* Watchdog settings */ +#define WATCHDOG_OFF (0) +#define WATCHDOG_16MS (_BV(WDE)) +#define WATCHDOG_32MS (_BV(WDP0) | _BV(WDE)) +#define WATCHDOG_64MS (_BV(WDP1) | _BV(WDE)) +#define WATCHDOG_125MS (_BV(WDP1) | _BV(WDP0) | _BV(WDE)) +#define WATCHDOG_250MS (_BV(WDP2) | _BV(WDE)) +#define WATCHDOG_500MS (_BV(WDP2) | _BV(WDP0) | _BV(WDE)) +#define WATCHDOG_1S (_BV(WDP2) | _BV(WDP1) | _BV(WDE)) +#define WATCHDOG_2S (_BV(WDP2) | _BV(WDP1) | _BV(WDP0) | _BV(WDE)) +#ifndef __AVR_ATmega8__ +#define WATCHDOG_4S (_BV(WDP3) | _BV(WDE)) +#define WATCHDOG_8S (_BV(WDP3) | _BV(WDP0) | _BV(WDE)) +#endif + +/* Function Prototypes */ +/* The main function is in init9, which removes the interrupt vector table */ +/* we don't need. It is also 'naked', which means the compiler does not */ +/* generate any entry or exit code itself. */ +int main(void) __attribute__ ((OS_main)) __attribute__ ((section (".init9"))); +void putch(char); +uint8_t getch(void); +static inline void getNch(uint8_t); /* "static inline" is a compiler hint to reduce code size */ +void verifySpace(); +static inline void flash_led(uint8_t); +uint8_t getLen(); +static inline void watchdogReset(); +void watchdogConfig(uint8_t x); +#ifdef SOFT_UART +void uartDelay() __attribute__ ((naked)); +#endif +void appStart(uint8_t rstFlags) __attribute__ ((naked)); + +/* + * NRWW memory + * Addresses below NRWW (Non-Read-While-Write) can be programmed while + * continuing to run code from flash, slightly speeding up programming + * time. Beware that Atmel data sheets specify this as a WORD address, + * while optiboot will be comparing against a 16-bit byte address. This + * means that on a part with 128kB of memory, the upper part of the lower + * 64k will get NRWW processing as well, even though it doesn't need it. + * That's OK. In fact, you can disable the overlapping processing for + * a part entirely by setting NRWWSTART to zero. This reduces code + * space a bit, at the expense of being slightly slower, overall. + * + * RAMSTART should be self-explanatory. It's bigger on parts with a + * lot of peripheral registers. + */ +#if defined(__AVR_ATmega168__) +#define RAMSTART (0x100) +#define NRWWSTART (0x3800) +#elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega32__) +#define RAMSTART (0x100) +#define NRWWSTART (0x7000) +#elif defined (__AVR_ATmega644P__) +#define RAMSTART (0x100) +#define NRWWSTART (0xE000) +// correct for a bug in avr-libc +#undef SIGNATURE_2 +#define SIGNATURE_2 0x0A +#elif defined (__AVR_ATmega1284P__) +#define RAMSTART (0x100) +#define NRWWSTART (0xE000) +#elif defined(__AVR_ATtiny84__) +#define RAMSTART (0x100) +#define NRWWSTART (0x0000) +#elif defined(__AVR_ATmega1280__) +#define RAMSTART (0x200) +#define NRWWSTART (0xE000) +#elif defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) +#define RAMSTART (0x100) +#define NRWWSTART (0x1800) +#endif + +/* C zero initialises all global variables. However, that requires */ +/* These definitions are NOT zero initialised, but that doesn't matter */ +/* This allows us to drop the zero init code, saving us memory */ +#define buff ((uint8_t*)(RAMSTART)) +#ifdef VIRTUAL_BOOT_PARTITION +#define rstVect (*(uint16_t*)(RAMSTART+SPM_PAGESIZE*2+4)) +#define wdtVect (*(uint16_t*)(RAMSTART+SPM_PAGESIZE*2+6)) +#endif + +/* + * Handle devices with up to 4 uarts (eg m1280.) Rather inelegantly. + * Note that mega8/m32 still needs special handling, because ubrr is handled + * differently. + */ +#if UART == 0 +# define UART_SRA UCSR0A +# define UART_SRB UCSR0B +# define UART_SRC UCSR0C +# define UART_SRL UBRR0L +# define UART_UDR UDR0 +#elif UART == 1 +#if !defined(UDR1) +#error UART == 1, but no UART1 on device +#endif +# define UART_SRA UCSR1A +# define UART_SRB UCSR1B +# define UART_SRC UCSR1C +# define UART_SRL UBRR1L +# define UART_UDR UDR1 +#elif UART == 2 +#if !defined(UDR2) +#error UART == 2, but no UART2 on device +#endif +# define UART_SRA UCSR2A +# define UART_SRB UCSR2B +# define UART_SRC UCSR2C +# define UART_SRL UBRR2L +# define UART_UDR UDR2 +#elif UART == 3 +#if !defined(UDR1) +#error UART == 3, but no UART3 on device +#endif +# define UART_SRA UCSR3A +# define UART_SRB UCSR3B +# define UART_SRC UCSR3C +# define UART_SRL UBRR3L +# define UART_UDR UDR3 +#endif + +/******************* SPI FLASH Code **********************************/ +// This code will handle the reading/erasing the external SPI FLASH memory +// assumed to have the SPI_CS on D8 on Moteino (Atmega328P) +#define SPI_MODE0 0x00 +#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR +#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR +#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR +#define SPI_CLOCK_DIV2 0x04 + +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) + #define FLASHSS_DDR DDRB + #define FLASHSS_PORT PORTB + #define FLASHSS PINB0 + #define SS PINB2 +#elif defined (__AVR_ATmega1284P__) || defined (__AVR_ATmega644P__) + #define FLASHSS_DDR DDRC + #define FLASHSS_PORT PORTC + #define FLASHSS PINC7 + #define SS PINB4 +#endif + +#define FLASH_SELECT { FLASHSS_PORT &= ~(_BV(FLASHSS)); } +#define FLASH_UNSELECT { FLASHSS_PORT |= _BV(FLASHSS); } + +#define SPIFLASH_STATUSWRITE 0x01 // write status register +#define SPIFLASH_STATUSREAD 0x05 // read status register +#define SPIFLASH_WRITEENABLE 0x06 // write enable +#define SPIFLASH_ARRAYREADLOWFREQ 0x03 // read array (low frequency) +#define SPIFLASH_BLOCKERASE_32K 0x52 // erase one 32K block of flash memory +#define SPIFLASH_BLOCKERASE_64K 0xD8 // erase one 32K block of flash memory +#define SPIFLASH_JEDECID 0x9F // read JEDEC ID +//#define DEBUG_ON // uncomment to enable Serial debugging + // (will output different characters depending on which path the bootloader takes) + +uint8_t SPI_transfer(uint8_t _data) { + SPDR = _data; + while (!(SPSR & _BV(SPIF))); + return SPDR; +} + +uint8_t FLASH_busy() +{ + FLASH_SELECT; + SPI_transfer(SPIFLASH_STATUSREAD); + uint8_t status = SPI_transfer(0); + FLASH_UNSELECT; + return status & 1; +} + +void FLASH_command(uint8_t cmd, uint8_t isWrite){ + if (isWrite) + { + FLASH_command(SPIFLASH_WRITEENABLE, 0); // Write Enable + FLASH_UNSELECT; + } + while(FLASH_busy()); //wait for chip to become available + FLASH_SELECT; + SPI_transfer(cmd); +} + +uint8_t FLASH_readByte(uint32_t addr) { + FLASH_command(SPIFLASH_ARRAYREADLOWFREQ, 0); + SPI_transfer(addr >> 16); + SPI_transfer(addr >> 8); + SPI_transfer(addr); + //SPI.transfer(0); //"dont care", needed with SPIFLASH_ARRAYREAD command only + uint8_t result = SPI_transfer(0); + FLASH_UNSELECT; + return result; +} + +void CheckFlashImage() { +#ifdef DEBUG_ON + putch('F'); +#endif + watchdogConfig(WATCHDOG_OFF); + + //SPI INIT +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) + DDRB |= _BV(FLASHSS) | _BV(SS) | _BV(PB3) | _BV(PB5); //OUTPUTS for FLASH_SS and SS, MOSI, SCK + FLASH_UNSELECT; //unselect FLASH chip + PORTB |= _BV(SS); //set SS HIGH +#elif defined (__AVR_ATmega1284P__) || defined (__AVR_ATmega644P__) + DDRC |= _BV(FLASHSS); //OUTPUT for FLASH_SS + DDRB |= _BV(SS) | _BV(PB5) | _BV(PB7); //OUTPUTS for SS, MOSI, SCK + FLASH_UNSELECT; //unselect FLASH chip + PORTB |= _BV(SS); //set SS HIGH +#endif + + //SPCR &= ~(_BV(DORD)); //MSB first + //SPCR = (SPCR & ~SPI_MODE_MASK) | SPI_MODE0 ; //SPI MODE 0 + //SPCR = (SPCR & ~SPI_CLOCK_MASK) | (SPI_CLOCK_DIV2 & SPI_CLOCK_MASK); //clock divider = 2 + //SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((SPI_CLOCK_DIV2 >> 2) & SPI_2XCLOCK_MASK); + + // Warning: if the SS pin ever becomes a LOW INPUT then SPI automatically switches to Slave, so the data direction of the SS pin MUST be kept as OUTPUT. + SPCR |= _BV(MSTR) | _BV(SPE); //enable SPI and set SPI to MASTER mode + + //read first byte of JEDECID, if chip is present it should return a non-0 and non-FF value + FLASH_SELECT; + SPI_transfer(SPIFLASH_JEDECID); + uint8_t deviceId = SPI_transfer(0); + FLASH_UNSELECT; + if (deviceId==0 || deviceId==0xFF) return; + + //global unprotect + FLASH_command(SPIFLASH_STATUSWRITE, 1); + SPI_transfer(0); + FLASH_UNSELECT; + + //check if any flash image exists on external FLASH chip + if (FLASH_readByte(0)=='F' && FLASH_readByte(1)=='L' && FLASH_readByte(2)=='X' && FLASH_readByte(6)==':' && FLASH_readByte(9)==':') + { +#ifdef DEBUG_ON + putch('L'); +#endif + + uint16_t imagesize = (FLASH_readByte(7)<<8) | FLASH_readByte(8); + if (imagesize%2!=0) return; //basic check that we got even # of bytes + + uint16_t b, i, nextAddress=0; + + LED_PIN |= _BV(LED); + for (i=0; i 0 + // Set up Timer 1 for timeout counter + TCCR1B = _BV(CS12) | _BV(CS10); // div 1024 +#endif +#ifndef SOFT_UART +#if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) + UCSRA = _BV(U2X); //Double speed mode USART + UCSRB = _BV(RXEN) | _BV(TXEN); // enable Rx & Tx + UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0); // config USART; 8N1 + UBRRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 ); +#else + UART_SRA = _BV(U2X0); //Double speed mode USART0 + UART_SRB = _BV(RXEN0) | _BV(TXEN0); + UART_SRC = _BV(UCSZ00) | _BV(UCSZ01); + UART_SRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 ); +#endif +#endif + + // Set up watchdog to trigger after 500ms + watchdogConfig(WATCHDOG_1S); + +#if (LED_START_FLASHES > 0) || defined(LED_DATA_FLASH) + /* Set LED pin as output */ + LED_DDR |= _BV(LED); +#endif + +#ifdef SOFT_UART + /* Set TX pin as output */ + UART_DDR |= _BV(UART_TX_BIT); +#endif + +#if LED_START_FLASHES > 0 + /* Flash onboard LED to signal entering of bootloader */ + flash_led(LED_START_FLASHES * 2); +#endif + + /* Forever loop */ + for (;;) { + /* get character from UART */ + ch = getch(); + + if(ch == STK_GET_PARAMETER) { + unsigned char which = getch(); + verifySpace(); + if (which == 0x82) { + /* + * Send optiboot version as "minor SW version" + */ + putch(OPTIBOOT_MINVER); + } else if (which == 0x81) { + putch(OPTIBOOT_MAJVER); + } else { + /* + * GET PARAMETER returns a generic 0x03 reply for + * other parameters - enough to keep Avrdude happy + */ + putch(0x03); + } + } + else if(ch == STK_SET_DEVICE) { + // SET DEVICE is ignored + getNch(20); + } + else if(ch == STK_SET_DEVICE_EXT) { + // SET DEVICE EXT is ignored + getNch(5); + } + else if(ch == STK_LOAD_ADDRESS) { + // LOAD ADDRESS + uint16_t newAddress; + newAddress = getch(); + newAddress = (newAddress & 0xff) | (getch() << 8); +#ifdef RAMPZ + // Transfer top bit to RAMPZ + RAMPZ = (newAddress & 0x8000) ? 1 : 0; +#endif + newAddress += newAddress; // Convert from word address to byte address + address = newAddress; + verifySpace(); + } + else if(ch == STK_UNIVERSAL) { + // UNIVERSAL command is ignored + getNch(4); + putch(0x00); + } + /* Write memory, length is big endian and is in bytes */ + else if(ch == STK_PROG_PAGE) { + // PROGRAM PAGE - we support flash programming only, not EEPROM + uint8_t *bufPtr; + uint16_t addrPtr; + + getch(); /* getlen() */ + length = getch(); + getch(); + + // If we are in RWW section, immediately start page erase + if (address < NRWWSTART) __boot_page_erase_short((uint16_t)(void*)address); + + // While that is going on, read in page contents + bufPtr = buff; + do *bufPtr++ = getch(); + while (--length); + + // If we are in NRWW section, page erase has to be delayed until now. + // Todo: Take RAMPZ into account (not doing so just means that we will + // treat the top of both "pages" of flash as NRWW, for a slight speed + // decrease, so fixing this is not urgent.) + if (address >= NRWWSTART) __boot_page_erase_short((uint16_t)(void*)address); + + // Read command terminator, start reply + verifySpace(); + + // If only a partial page is to be programmed, the erase might not be complete. + // So check that here + boot_spm_busy_wait(); + +#ifdef VIRTUAL_BOOT_PARTITION + if ((uint16_t)(void*)address == 0) { + // This is the reset vector page. We need to live-patch the code so the + // bootloader runs. + // + // Move RESET vector to WDT vector + uint16_t vect = buff[0] | (buff[1]<<8); + rstVect = vect; + wdtVect = buff[8] | (buff[9]<<8); + vect -= 4; // Instruction is a relative jump (rjmp), so recalculate. + buff[8] = vect & 0xff; + buff[9] = vect >> 8; + + // Add jump to bootloader at RESET vector + buff[0] = 0x7f; + buff[1] = 0xce; // rjmp 0x1d00 instruction + } +#endif + + // Copy buffer into programming buffer + bufPtr = buff; + addrPtr = (uint16_t)(void*)address; + ch = SPM_PAGESIZE / 2; + do { + uint16_t a; + a = *bufPtr++; + a |= (*bufPtr++) << 8; + __boot_page_fill_short((uint16_t)(void*)addrPtr,a); + addrPtr += 2; + } while (--ch); + + // Write from programming buffer + __boot_page_write_short((uint16_t)(void*)address); + boot_spm_busy_wait(); + +#if defined(RWWSRE) + // Reenable read access to flash + boot_rww_enable(); +#endif + + } + /* Read memory block mode, length is big endian. */ + else if(ch == STK_READ_PAGE) { + // READ PAGE - we only read flash + getch(); /* getlen() */ + length = getch(); + getch(); + + verifySpace(); + do { +#ifdef VIRTUAL_BOOT_PARTITION + // Undo vector patch in bottom page so verify passes + if (address == 0) ch=rstVect & 0xff; + else if (address == 1) ch=rstVect >> 8; + else if (address == 8) ch=wdtVect & 0xff; + else if (address == 9) ch=wdtVect >> 8; + else ch = pgm_read_byte_near(address); + address++; +#elif defined(RAMPZ) + // Since RAMPZ should already be set, we need to use EPLM directly. + // Also, we can use the autoincrement version of lpm to update "address" + // do putch(pgm_read_byte_near(address++)); + // while (--length); + // read a Flash and increment the address (may increment RAMPZ) + __asm__ ("elpm %0,Z+\n" : "=r" (ch), "=z" (address): "1" (address)); +#else + // read a Flash byte and increment the address + __asm__ ("lpm %0,Z+\n" : "=r" (ch), "=z" (address): "1" (address)); +#endif + putch(ch); + } while (--length); + } + + /* Get device signature bytes */ + else if(ch == STK_READ_SIGN) { + // READ SIGN - return what Avrdude wants to hear + verifySpace(); + putch(SIGNATURE_0); + putch(SIGNATURE_1); + putch(SIGNATURE_2); + } + else if (ch == STK_LEAVE_PROGMODE) { /* 'Q' */ + // Adaboot no-wait mod + watchdogConfig(WATCHDOG_16MS); + verifySpace(); + } + else { + // This covers the response to commands like STK_ENTER_PROGMODE + verifySpace(); + } + putch(STK_OK); + } +} + +void putch(char ch) { +#ifndef SOFT_UART + while (!(UART_SRA & _BV(UDRE0))); + UART_UDR = ch; +#else + __asm__ __volatile__ ( + " com %[ch]\n" // ones complement, carry set + " sec\n" + "1: brcc 2f\n" + " cbi %[uartPort],%[uartBit]\n" + " rjmp 3f\n" + "2: sbi %[uartPort],%[uartBit]\n" + " nop\n" + "3: rcall uartDelay\n" + " rcall uartDelay\n" + " lsr %[ch]\n" + " dec %[bitcnt]\n" + " brne 1b\n" + : + : + [bitcnt] "d" (10), + [ch] "r" (ch), + [uartPort] "I" (_SFR_IO_ADDR(UART_PORT)), + [uartBit] "I" (UART_TX_BIT) + : + "r25" + ); +#endif +} + +uint8_t getch(void) { + uint8_t ch; + +#ifdef LED_DATA_FLASH +#if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) + LED_PORT ^= _BV(LED); +#else + LED_PIN |= _BV(LED); +#endif +#endif + +#ifdef SOFT_UART + __asm__ __volatile__ ( + "1: sbic %[uartPin],%[uartBit]\n" // Wait for start edge + " rjmp 1b\n" + " rcall uartDelay\n" // Get to middle of start bit + "2: rcall uartDelay\n" // Wait 1 bit period + " rcall uartDelay\n" // Wait 1 bit period + " clc\n" + " sbic %[uartPin],%[uartBit]\n" + " sec\n" + " dec %[bitCnt]\n" + " breq 3f\n" + " ror %[ch]\n" + " rjmp 2b\n" + "3:\n" + : + [ch] "=r" (ch) + : + [bitCnt] "d" (9), + [uartPin] "I" (_SFR_IO_ADDR(UART_PIN)), + [uartBit] "I" (UART_RX_BIT) + : + "r25" +); +#else + while(!(UART_SRA & _BV(RXC0))) + ; + if (!(UART_SRA & _BV(FE0))) { + /* + * A Framing Error indicates (probably) that something is talking + * to us at the wrong bit rate. Assume that this is because it + * expects to be talking to the application, and DON'T reset the + * watchdog. This should cause the bootloader to abort and run + * the application "soon", if it keeps happening. (Note that we + * don't care that an invalid char is returned...) + */ + watchdogReset(); + } + + ch = UART_UDR; +#endif + +#ifdef LED_DATA_FLASH +#if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) + LED_PORT ^= _BV(LED); +#else + LED_PIN |= _BV(LED); +#endif +#endif + + return ch; +} + +#ifdef SOFT_UART +// AVR305 equation: #define UART_B_VALUE (((F_CPU/BAUD_RATE)-23)/6) +// Adding 3 to numerator simulates nearest rounding for more accurate baud rates +#define UART_B_VALUE (((F_CPU/BAUD_RATE)-20)/6) +#if UART_B_VALUE > 255 +#error Baud rate too slow for soft UART +#endif + +void uartDelay() { + __asm__ __volatile__ ( + "ldi r25,%[count]\n" + "1:dec r25\n" + "brne 1b\n" + "ret\n" + ::[count] "M" (UART_B_VALUE) + ); +} +#endif + +void getNch(uint8_t count) { + do getch(); while (--count); + verifySpace(); +} + +void verifySpace() { + if (getch() != CRC_EOP) { + watchdogConfig(WATCHDOG_16MS); // shorten WD timeout + while (1) // and busy-loop so that WD causes + ; // a reset and app start. + } + putch(STK_INSYNC); +} + +#if LED_START_FLASHES > 0 +void flash_led(uint8_t count) { + do { + TCNT1 = -(F_CPU/(1024*16)); + TIFR1 = _BV(TOV1); + while(!(TIFR1 & _BV(TOV1))); +#if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) + LED_PORT ^= _BV(LED); +#else + LED_PIN |= _BV(LED); +#endif + watchdogReset(); + } while (--count); +} +#endif + +// Watchdog functions. These are only safe with interrupts turned off. +void watchdogReset() { + __asm__ __volatile__ ( + "wdr\n" + ); +} + +void watchdogConfig(uint8_t x) { + WDTCSR = _BV(WDCE) | _BV(WDE); + WDTCSR = x; +} + +void appStart(uint8_t rstFlags) { + // save the reset flags in the designated register + // This can be saved in a main program by putting code in .init0 (which + // executes before normal c init code) to save R2 to a global variable. + __asm__ __volatile__ ("mov r2, %0\n" :: "r" (rstFlags)); + + watchdogConfig(WATCHDOG_OFF); + __asm__ __volatile__ ( +#ifdef VIRTUAL_BOOT_PARTITION + // Jump to WDT vector + "ldi r30,4\n" + "clr r31\n" +#else + // Jump to RST vector + "clr r30\n" + "clr r31\n" +#endif + "ijmp\n" + ); +} diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.hex b/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.hex new file mode 100644 index 0000000..58f396e --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.hex @@ -0,0 +1,67 @@ +:107C00001F92CDB7DEB7112484B714BE81FD06C024 +:107C100083FF03C08983F4D08981E3D185E0809319 +:107C2000810082E08093C00088E18093C10096E0EB +:107C30009093C20090E19093C400809360008EE026 +:107C4000809360003B9A86E028E13EEF91E030931C +:107C500085002093840096BBB09BFECF339AA895F5 +:107C60008150A9F7612C712C08E128E0F22EEE2456 +:107C7000E39435E0D32E41E1C42E13E08BD181345F +:107C800069F488D1898394D189818238F9F0813867 +:107C900011F485E001C083E076D17BC0823411F419 +:107CA00084E103C0853419F485E08ED172C0853536 +:107CB00049F470D1B82E6ED16B2C712C782A660CD9 +:107CC000771C66C0863521F484E07ED180E0E4CF65 +:107CD000843609F03FC05ED15DD1982E5BD161142E +:107CE00080E7780618F4F30117BFE895A12CBB24B0 +:107CF000B39450D1F50181935F019E12FACF6114C4 +:107D0000F0E77F0618F0F30117BFE89551D107B6E9 +:107D100000FCFDCFA301A0E0B1E08C9112969D0183 +:107D200021503109F901208190E0922BFA010C01D8 +:107D3000E7BEE89511244E5F5F4FA038F1E0BF0722 +:107D400061F7F301D7BEE89507B600FCFDCFC7BECB +:107D5000E8951FC0843769F41DD11CD1B82E1AD103 +:107D600027D1F30185913F010ED1BA94B110F9CF1B +:107D700010C0853739F41CD18EE105D185E903D1D6 +:107D80008FE08ACF813521F400936000F09260008B +:107D90000FD180E1F8D072CF8EBD0DB407FEFDCFBC +:107DA0008EB50895289885E0F7DF80E0F5DF289A02 +:107DB00081700895CF93C82F662321F060E086E09C +:107DC000F9DF289AEFDF8111FDCF28988C2FCF9112 +:107DD000E3CFCF92DF92EF92FF926B017C0160E0E4 +:107DE00083E0E8DF8E2DD8DF8D2DD6DF8C2DD4DF1C +:107DF00080E0D2DF289AFF90EF90DF90CF90089537 +:107E00009F92AF92BF92CF92DF92EF92FF920F9329 +:107E10001F93CF93DF9388E18093600010926000FE +:107E200084B18D6284B9289A2A9A8CB580658CBDFC +:107E300028988FE9B1DF80E0AFDF289A81508E3F2C +:107E400008F095C061E081E0B5DF80E0A5DF289A09 +:107E500060E070E0CB01BDDF863409F088C061E0EE +:107E600070E080E090E0B5DF8C3409F080C062E023 +:107E700070E080E090E0ADDF883509F078C066E022 +:107E800070E080E090E0A5DF8A3309F070C069E01F +:107E900070E080E090E09DDF8A3309F068C067E021 +:107EA00070E080E090E095DFC82F68E070E080E04F +:107EB00090E08FDFD0E0DC2FCC27C82BC0FD57C06F +:107EC000339AC12CD12C00E010E0BB24B39483E0A2 +:107ED000A82E95E0992E0C171D0770F5B801665F66 +:107EE0007F4F80E090E075DFE82EF12CB801655FF0 +:107EF0007F4F80E090E06DDFF82AF8010701B7BE00 +:107F0000E89511240E5F1F4FC8018F779927892BA1 +:107F100019F00C171D07F9F6F601A7BEE89507B68C +:107F200000FCFDCFF60197BEE89507B600FCFDCF3B +:107F3000F0E8CF0ED11CCFCF339881E187BFE89511 +:107F40002A9661E0C130D04810F482E501C088ED86 +:107F500031DF80E021DF80E01FDF80E01DDF289A35 +:107F600088E18093600088E080936000FFCFDF911C +:107F7000CF911F910F91FF90EF90DF90CF90BF9026 +:107F8000AF909F9008959091C00095FFFCCF809393 +:107F9000C6000895339A8091C00087FFFCCF80917E +:107FA000C00084FD01C0A8958091C600339A089551 +:107FB000F1DF803239F088E18093600088E08093BF +:107FC0006000FFCF84E1DFCFCF93C82FE3DFC15044 +:107FD000E9F7CF91EDCFE0E6F0E098E19083808380 +:107FE0000895282EE0E6F0E088E180831082EE27F5 +:047FF000FF270994CA +:027FFE0000057C +:0400000300007C007D +:00000001FF diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.lst b/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.lst new file mode 100644 index 0000000..75a47a7 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/optiboot_atmega328_pro_8MHz.lst @@ -0,0 +1,787 @@ + +optiboot_atmega328.elf: filformat elf32-avr + +Sektioner: +Idx Navn Størrelse VMA LMA Filoffs Just + 0 .data 00000000 00800100 00007ff4 00000468 2**0 + CONTENTS, ALLOC, LOAD, DATA + 1 .text 000003f4 00007c00 00007c00 00000074 2**1 + CONTENTS, ALLOC, LOAD, READONLY, CODE + 2 .version 00000002 00007ffe 00007ffe 00000468 2**0 + CONTENTS, READONLY + 3 .stab 000011c4 00000000 00000000 0000046c 2**2 + CONTENTS, READONLY, DEBUGGING + 4 .stabstr 00000ddc 00000000 00000000 00001630 2**0 + CONTENTS, READONLY, DEBUGGING + 5 .comment 00000027 00000000 00000000 0000240c 2**0 + CONTENTS, READONLY + +Disassemblering af sektion .text: + +00007c00
: + 7c00: 1f 92 push r1 + 7c02: cd b7 in r28, 0x3d ; 61 + 7c04: de b7 in r29, 0x3e ; 62 + 7c06: 11 24 eor r1, r1 + 7c08: 84 b7 in r24, 0x34 ; 52 + 7c0a: 14 be out 0x34, r1 ; 52 + 7c0c: 81 fd sbrc r24, 1 + 7c0e: 06 c0 rjmp .+12 ; 0x7c1c + 7c10: 83 ff sbrs r24, 3 + 7c12: 03 c0 rjmp .+6 ; 0x7c1a + 7c14: 89 83 std Y+1, r24 ; 0x01 + 7c16: f4 d0 rcall .+488 ; 0x7e00 + 7c18: 89 81 ldd r24, Y+1 ; 0x01 + 7c1a: e3 d1 rcall .+966 ; 0x7fe2 + 7c1c: 85 e0 ldi r24, 0x05 ; 5 + 7c1e: 80 93 81 00 sts 0x0081, r24 + 7c22: 82 e0 ldi r24, 0x02 ; 2 + 7c24: 80 93 c0 00 sts 0x00C0, r24 + 7c28: 88 e1 ldi r24, 0x18 ; 24 + 7c2a: 80 93 c1 00 sts 0x00C1, r24 + 7c2e: 96 e0 ldi r25, 0x06 ; 6 + 7c30: 90 93 c2 00 sts 0x00C2, r25 + 7c34: 90 e1 ldi r25, 0x10 ; 16 + 7c36: 90 93 c4 00 sts 0x00C4, r25 + 7c3a: 80 93 60 00 sts 0x0060, r24 + 7c3e: 8e e0 ldi r24, 0x0E ; 14 + 7c40: 80 93 60 00 sts 0x0060, r24 + 7c44: 3b 9a sbi 0x07, 3 ; 7 + 7c46: 86 e0 ldi r24, 0x06 ; 6 + 7c48: 28 e1 ldi r18, 0x18 ; 24 + 7c4a: 3e ef ldi r19, 0xFE ; 254 + 7c4c: 91 e0 ldi r25, 0x01 ; 1 + 7c4e: 30 93 85 00 sts 0x0085, r19 + 7c52: 20 93 84 00 sts 0x0084, r18 + 7c56: 96 bb out 0x16, r25 ; 22 + 7c58: b0 9b sbis 0x16, 0 ; 22 + 7c5a: fe cf rjmp .-4 ; 0x7c58 + 7c5c: 33 9a sbi 0x06, 3 ; 6 + 7c5e: a8 95 wdr + 7c60: 81 50 subi r24, 0x01 ; 1 + 7c62: a9 f7 brne .-22 ; 0x7c4e + 7c64: 61 2c mov r6, r1 + 7c66: 71 2c mov r7, r1 + 7c68: 08 e1 ldi r16, 0x18 ; 24 + 7c6a: 28 e0 ldi r18, 0x08 ; 8 + 7c6c: f2 2e mov r15, r18 + 7c6e: ee 24 eor r14, r14 + 7c70: e3 94 inc r14 + 7c72: 35 e0 ldi r19, 0x05 ; 5 + 7c74: d3 2e mov r13, r19 + 7c76: 41 e1 ldi r20, 0x11 ; 17 + 7c78: c4 2e mov r12, r20 + 7c7a: 13 e0 ldi r17, 0x03 ; 3 + 7c7c: 8b d1 rcall .+790 ; 0x7f94 + 7c7e: 81 34 cpi r24, 0x41 ; 65 + 7c80: 69 f4 brne .+26 ; 0x7c9c + 7c82: 88 d1 rcall .+784 ; 0x7f94 + 7c84: 89 83 std Y+1, r24 ; 0x01 + 7c86: 94 d1 rcall .+808 ; 0x7fb0 + 7c88: 89 81 ldd r24, Y+1 ; 0x01 + 7c8a: 82 38 cpi r24, 0x82 ; 130 + 7c8c: f9 f0 breq .+62 ; 0x7ccc + 7c8e: 81 38 cpi r24, 0x81 ; 129 + 7c90: 11 f4 brne .+4 ; 0x7c96 + 7c92: 85 e0 ldi r24, 0x05 ; 5 + 7c94: 01 c0 rjmp .+2 ; 0x7c98 + 7c96: 83 e0 ldi r24, 0x03 ; 3 + 7c98: 76 d1 rcall .+748 ; 0x7f86 + 7c9a: 7b c0 rjmp .+246 ; 0x7d92 + 7c9c: 82 34 cpi r24, 0x42 ; 66 + 7c9e: 11 f4 brne .+4 ; 0x7ca4 + 7ca0: 84 e1 ldi r24, 0x14 ; 20 + 7ca2: 03 c0 rjmp .+6 ; 0x7caa + 7ca4: 85 34 cpi r24, 0x45 ; 69 + 7ca6: 19 f4 brne .+6 ; 0x7cae + 7ca8: 85 e0 ldi r24, 0x05 ; 5 + 7caa: 8e d1 rcall .+796 ; 0x7fc8 + 7cac: 72 c0 rjmp .+228 ; 0x7d92 + 7cae: 85 35 cpi r24, 0x55 ; 85 + 7cb0: 49 f4 brne .+18 ; 0x7cc4 + 7cb2: 70 d1 rcall .+736 ; 0x7f94 + 7cb4: b8 2e mov r11, r24 + 7cb6: 6e d1 rcall .+732 ; 0x7f94 + 7cb8: 6b 2c mov r6, r11 + 7cba: 71 2c mov r7, r1 + 7cbc: 78 2a or r7, r24 + 7cbe: 66 0c add r6, r6 + 7cc0: 77 1c adc r7, r7 + 7cc2: 66 c0 rjmp .+204 ; 0x7d90 + 7cc4: 86 35 cpi r24, 0x56 ; 86 + 7cc6: 21 f4 brne .+8 ; 0x7cd0 + 7cc8: 84 e0 ldi r24, 0x04 ; 4 + 7cca: 7e d1 rcall .+764 ; 0x7fc8 + 7ccc: 80 e0 ldi r24, 0x00 ; 0 + 7cce: e4 cf rjmp .-56 ; 0x7c98 + 7cd0: 84 36 cpi r24, 0x64 ; 100 + 7cd2: 09 f0 breq .+2 ; 0x7cd6 + 7cd4: 3f c0 rjmp .+126 ; 0x7d54 + 7cd6: 5e d1 rcall .+700 ; 0x7f94 + 7cd8: 5d d1 rcall .+698 ; 0x7f94 + 7cda: 98 2e mov r9, r24 + 7cdc: 5b d1 rcall .+694 ; 0x7f94 + 7cde: 61 14 cp r6, r1 + 7ce0: 80 e7 ldi r24, 0x70 ; 112 + 7ce2: 78 06 cpc r7, r24 + 7ce4: 18 f4 brcc .+6 ; 0x7cec + 7ce6: f3 01 movw r30, r6 + 7ce8: 17 bf out 0x37, r17 ; 55 + 7cea: e8 95 spm + 7cec: a1 2c mov r10, r1 + 7cee: bb 24 eor r11, r11 + 7cf0: b3 94 inc r11 + 7cf2: 50 d1 rcall .+672 ; 0x7f94 + 7cf4: f5 01 movw r30, r10 + 7cf6: 81 93 st Z+, r24 + 7cf8: 5f 01 movw r10, r30 + 7cfa: 9e 12 cpse r9, r30 + 7cfc: fa cf rjmp .-12 ; 0x7cf2 + 7cfe: 61 14 cp r6, r1 + 7d00: f0 e7 ldi r31, 0x70 ; 112 + 7d02: 7f 06 cpc r7, r31 + 7d04: 18 f0 brcs .+6 ; 0x7d0c + 7d06: f3 01 movw r30, r6 + 7d08: 17 bf out 0x37, r17 ; 55 + 7d0a: e8 95 spm + 7d0c: 51 d1 rcall .+674 ; 0x7fb0 + 7d0e: 07 b6 in r0, 0x37 ; 55 + 7d10: 00 fc sbrc r0, 0 + 7d12: fd cf rjmp .-6 ; 0x7d0e + 7d14: a3 01 movw r20, r6 + 7d16: a0 e0 ldi r26, 0x00 ; 0 + 7d18: b1 e0 ldi r27, 0x01 ; 1 + 7d1a: 8c 91 ld r24, X + 7d1c: 12 96 adiw r26, 0x02 ; 2 + 7d1e: 9d 01 movw r18, r26 + 7d20: 21 50 subi r18, 0x01 ; 1 + 7d22: 31 09 sbc r19, r1 + 7d24: f9 01 movw r30, r18 + 7d26: 20 81 ld r18, Z + 7d28: 90 e0 ldi r25, 0x00 ; 0 + 7d2a: 92 2b or r25, r18 + 7d2c: fa 01 movw r30, r20 + 7d2e: 0c 01 movw r0, r24 + 7d30: e7 be out 0x37, r14 ; 55 + 7d32: e8 95 spm + 7d34: 11 24 eor r1, r1 + 7d36: 4e 5f subi r20, 0xFE ; 254 + 7d38: 5f 4f sbci r21, 0xFF ; 255 + 7d3a: a0 38 cpi r26, 0x80 ; 128 + 7d3c: f1 e0 ldi r31, 0x01 ; 1 + 7d3e: bf 07 cpc r27, r31 + 7d40: 61 f7 brne .-40 ; 0x7d1a + 7d42: f3 01 movw r30, r6 + 7d44: d7 be out 0x37, r13 ; 55 + 7d46: e8 95 spm + 7d48: 07 b6 in r0, 0x37 ; 55 + 7d4a: 00 fc sbrc r0, 0 + 7d4c: fd cf rjmp .-6 ; 0x7d48 + 7d4e: c7 be out 0x37, r12 ; 55 + 7d50: e8 95 spm + 7d52: 1f c0 rjmp .+62 ; 0x7d92 + 7d54: 84 37 cpi r24, 0x74 ; 116 + 7d56: 69 f4 brne .+26 ; 0x7d72 + 7d58: 1d d1 rcall .+570 ; 0x7f94 + 7d5a: 1c d1 rcall .+568 ; 0x7f94 + 7d5c: b8 2e mov r11, r24 + 7d5e: 1a d1 rcall .+564 ; 0x7f94 + 7d60: 27 d1 rcall .+590 ; 0x7fb0 + 7d62: f3 01 movw r30, r6 + 7d64: 85 91 lpm r24, Z+ + 7d66: 3f 01 movw r6, r30 + 7d68: 0e d1 rcall .+540 ; 0x7f86 + 7d6a: ba 94 dec r11 + 7d6c: b1 10 cpse r11, r1 + 7d6e: f9 cf rjmp .-14 ; 0x7d62 + 7d70: 10 c0 rjmp .+32 ; 0x7d92 + 7d72: 85 37 cpi r24, 0x75 ; 117 + 7d74: 39 f4 brne .+14 ; 0x7d84 + 7d76: 1c d1 rcall .+568 ; 0x7fb0 + 7d78: 8e e1 ldi r24, 0x1E ; 30 + 7d7a: 05 d1 rcall .+522 ; 0x7f86 + 7d7c: 85 e9 ldi r24, 0x95 ; 149 + 7d7e: 03 d1 rcall .+518 ; 0x7f86 + 7d80: 8f e0 ldi r24, 0x0F ; 15 + 7d82: 8a cf rjmp .-236 ; 0x7c98 + 7d84: 81 35 cpi r24, 0x51 ; 81 + 7d86: 21 f4 brne .+8 ; 0x7d90 + 7d88: 00 93 60 00 sts 0x0060, r16 + 7d8c: f0 92 60 00 sts 0x0060, r15 + 7d90: 0f d1 rcall .+542 ; 0x7fb0 + 7d92: 80 e1 ldi r24, 0x10 ; 16 + 7d94: f8 d0 rcall .+496 ; 0x7f86 + 7d96: 72 cf rjmp .-284 ; 0x7c7c + +00007d98 : +#define SPIFLASH_JEDECID 0x9F // read JEDEC ID +//#define DEBUG_ON // uncomment to enable Serial debugging + // (will output different characters depending on which path the bootloader takes) + +uint8_t SPI_transfer(uint8_t _data) { + SPDR = _data; + 7d98: 8e bd out 0x2e, r24 ; 46 + while (!(SPSR & _BV(SPIF))); + 7d9a: 0d b4 in r0, 0x2d ; 45 + 7d9c: 07 fe sbrs r0, 7 + 7d9e: fd cf rjmp .-6 ; 0x7d9a + return SPDR; + 7da0: 8e b5 in r24, 0x2e ; 46 +} + 7da2: 08 95 ret + +00007da4 : + +uint8_t FLASH_busy() +{ + FLASH_SELECT; + 7da4: 28 98 cbi 0x05, 0 ; 5 + SPI_transfer(SPIFLASH_STATUSREAD); + 7da6: 85 e0 ldi r24, 0x05 ; 5 + 7da8: f7 df rcall .-18 ; 0x7d98 + 7daa: 80 e0 ldi r24, 0x00 ; 0 + uint8_t status = SPI_transfer(0); + 7dac: f5 df rcall .-22 ; 0x7d98 + 7dae: 28 9a sbi 0x05, 0 ; 5 + 7db0: 81 70 andi r24, 0x01 ; 1 + FLASH_UNSELECT; + 7db2: 08 95 ret + +00007db4 : + return status & 1; +} + +void FLASH_command(uint8_t cmd, uint8_t isWrite){ + 7db4: cf 93 push r28 + 7db6: c8 2f mov r28, r24 + if (isWrite) + 7db8: 66 23 and r22, r22 + 7dba: 21 f0 breq .+8 ; 0x7dc4 + { + FLASH_command(SPIFLASH_WRITEENABLE, 0); // Write Enable + 7dbc: 60 e0 ldi r22, 0x00 ; 0 + 7dbe: 86 e0 ldi r24, 0x06 ; 6 + 7dc0: f9 df rcall .-14 ; 0x7db4 + 7dc2: 28 9a sbi 0x05, 0 ; 5 + FLASH_UNSELECT; + 7dc4: ef df rcall .-34 ; 0x7da4 + } + while(FLASH_busy()); //wait for chip to become available + 7dc6: 81 11 cpse r24, r1 + 7dc8: fd cf rjmp .-6 ; 0x7dc4 + 7dca: 28 98 cbi 0x05, 0 ; 5 + 7dcc: 8c 2f mov r24, r28 + FLASH_SELECT; + 7dce: cf 91 pop r28 + SPI_transfer(cmd); + 7dd0: e3 cf rjmp .-58 ; 0x7d98 + +00007dd2 : +} + +uint8_t FLASH_readByte(uint32_t addr) { + 7dd2: cf 92 push r12 + 7dd4: df 92 push r13 + 7dd6: ef 92 push r14 + 7dd8: ff 92 push r15 + 7dda: 6b 01 movw r12, r22 + 7ddc: 7c 01 movw r14, r24 + FLASH_command(SPIFLASH_ARRAYREADLOWFREQ, 0); + 7dde: 60 e0 ldi r22, 0x00 ; 0 + 7de0: 83 e0 ldi r24, 0x03 ; 3 + 7de2: e8 df rcall .-48 ; 0x7db4 + 7de4: 8e 2d mov r24, r14 + SPI_transfer(addr >> 16); + 7de6: d8 df rcall .-80 ; 0x7d98 + 7de8: 8d 2d mov r24, r13 + 7dea: d6 df rcall .-84 ; 0x7d98 + SPI_transfer(addr >> 8); + 7dec: 8c 2d mov r24, r12 + 7dee: d4 df rcall .-88 ; 0x7d98 + 7df0: 80 e0 ldi r24, 0x00 ; 0 + SPI_transfer(addr); + 7df2: d2 df rcall .-92 ; 0x7d98 + 7df4: 28 9a sbi 0x05, 0 ; 5 + 7df6: ff 90 pop r15 + //SPI.transfer(0); //"dont care", needed with SPIFLASH_ARRAYREAD command only + uint8_t result = SPI_transfer(0); + 7df8: ef 90 pop r14 + 7dfa: df 90 pop r13 + 7dfc: cf 90 pop r12 + FLASH_UNSELECT; + 7dfe: 08 95 ret + +00007e00 : + return result; +} + +void CheckFlashImage() { + 7e00: 9f 92 push r9 + 7e02: af 92 push r10 + 7e04: bf 92 push r11 + 7e06: cf 92 push r12 + 7e08: df 92 push r13 + 7e0a: ef 92 push r14 + 7e0c: ff 92 push r15 + 7e0e: 0f 93 push r16 + 7e10: 1f 93 push r17 + 7e12: cf 93 push r28 + 7e14: df 93 push r29 + "wdr\n" + ); +} + +void watchdogConfig(uint8_t x) { + WDTCSR = _BV(WDCE) | _BV(WDE); + 7e16: 88 e1 ldi r24, 0x18 ; 24 + 7e18: 80 93 60 00 sts 0x0060, r24 + WDTCSR = x; + 7e1c: 10 92 60 00 sts 0x0060, r1 +#endif + watchdogConfig(WATCHDOG_OFF); + + //SPI INIT +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) + DDRB |= _BV(FLASHSS) | _BV(SS) | _BV(PB3) | _BV(PB5); //OUTPUTS for FLASH_SS and SS, MOSI, SCK + 7e20: 84 b1 in r24, 0x04 ; 4 + 7e22: 8d 62 ori r24, 0x2D ; 45 + 7e24: 84 b9 out 0x04, r24 ; 4 + FLASH_UNSELECT; //unselect FLASH chip + 7e26: 28 9a sbi 0x05, 0 ; 5 + PORTB |= _BV(SS); //set SS HIGH + 7e28: 2a 9a sbi 0x05, 2 ; 5 + //SPCR = (SPCR & ~SPI_MODE_MASK) | SPI_MODE0 ; //SPI MODE 0 + //SPCR = (SPCR & ~SPI_CLOCK_MASK) | (SPI_CLOCK_DIV2 & SPI_CLOCK_MASK); //clock divider = 2 + //SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((SPI_CLOCK_DIV2 >> 2) & SPI_2XCLOCK_MASK); + + // Warning: if the SS pin ever becomes a LOW INPUT then SPI automatically switches to Slave, so the data direction of the SS pin MUST be kept as OUTPUT. + SPCR |= _BV(MSTR) | _BV(SPE); //enable SPI and set SPI to MASTER mode + 7e2a: 8c b5 in r24, 0x2c ; 44 + 7e2c: 80 65 ori r24, 0x50 ; 80 + 7e2e: 8c bd out 0x2c, r24 ; 44 + + //read first byte of JEDECID, if chip is present it should return a non-0 and non-FF value + FLASH_SELECT; + 7e30: 28 98 cbi 0x05, 0 ; 5 + SPI_transfer(SPIFLASH_JEDECID); + 7e32: 8f e9 ldi r24, 0x9F ; 159 + 7e34: b1 df rcall .-158 ; 0x7d98 + 7e36: 80 e0 ldi r24, 0x00 ; 0 + uint8_t deviceId = SPI_transfer(0); + 7e38: af df rcall .-162 ; 0x7d98 + 7e3a: 28 9a sbi 0x05, 0 ; 5 + 7e3c: 81 50 subi r24, 0x01 ; 1 + FLASH_UNSELECT; + 7e3e: 8e 3f cpi r24, 0xFE ; 254 + if (deviceId==0 || deviceId==0xFF) return; + 7e40: 08 f0 brcs .+2 ; 0x7e44 + 7e42: 95 c0 rjmp .+298 ; 0x7f6e + 7e44: 61 e0 ldi r22, 0x01 ; 1 + 7e46: 81 e0 ldi r24, 0x01 ; 1 + + //global unprotect + FLASH_command(SPIFLASH_STATUSWRITE, 1); + 7e48: b5 df rcall .-150 ; 0x7db4 + 7e4a: 80 e0 ldi r24, 0x00 ; 0 + 7e4c: a5 df rcall .-182 ; 0x7d98 + 7e4e: 28 9a sbi 0x05, 0 ; 5 + SPI_transfer(0); + 7e50: 60 e0 ldi r22, 0x00 ; 0 + 7e52: 70 e0 ldi r23, 0x00 ; 0 + 7e54: cb 01 movw r24, r22 + FLASH_UNSELECT; + 7e56: bd df rcall .-134 ; 0x7dd2 + + //check if any flash image exists on external FLASH chip + if (FLASH_readByte(0)=='F' && FLASH_readByte(1)=='L' && FLASH_readByte(2)=='X' && FLASH_readByte(6)==':' && FLASH_readByte(9)==':') + 7e58: 86 34 cpi r24, 0x46 ; 70 + 7e5a: 09 f0 breq .+2 ; 0x7e5e + 7e5c: 88 c0 rjmp .+272 ; 0x7f6e + 7e5e: 61 e0 ldi r22, 0x01 ; 1 + 7e60: 70 e0 ldi r23, 0x00 ; 0 + 7e62: 80 e0 ldi r24, 0x00 ; 0 + 7e64: 90 e0 ldi r25, 0x00 ; 0 + 7e66: b5 df rcall .-150 ; 0x7dd2 + 7e68: 8c 34 cpi r24, 0x4C ; 76 + 7e6a: 09 f0 breq .+2 ; 0x7e6e + 7e6c: 80 c0 rjmp .+256 ; 0x7f6e + 7e6e: 62 e0 ldi r22, 0x02 ; 2 + 7e70: 70 e0 ldi r23, 0x00 ; 0 + 7e72: 80 e0 ldi r24, 0x00 ; 0 + 7e74: 90 e0 ldi r25, 0x00 ; 0 + 7e76: ad df rcall .-166 ; 0x7dd2 + 7e78: 88 35 cpi r24, 0x58 ; 88 + 7e7a: 09 f0 breq .+2 ; 0x7e7e + 7e7c: 78 c0 rjmp .+240 ; 0x7f6e + 7e7e: 66 e0 ldi r22, 0x06 ; 6 + 7e80: 70 e0 ldi r23, 0x00 ; 0 + 7e82: 80 e0 ldi r24, 0x00 ; 0 + 7e84: 90 e0 ldi r25, 0x00 ; 0 + 7e86: a5 df rcall .-182 ; 0x7dd2 + 7e88: 8a 33 cpi r24, 0x3A ; 58 + 7e8a: 09 f0 breq .+2 ; 0x7e8e + 7e8c: 70 c0 rjmp .+224 ; 0x7f6e + 7e8e: 69 e0 ldi r22, 0x09 ; 9 + 7e90: 70 e0 ldi r23, 0x00 ; 0 + 7e92: 80 e0 ldi r24, 0x00 ; 0 + 7e94: 90 e0 ldi r25, 0x00 ; 0 + 7e96: 9d df rcall .-198 ; 0x7dd2 + 7e98: 8a 33 cpi r24, 0x3A ; 58 + 7e9a: 09 f0 breq .+2 ; 0x7e9e + 7e9c: 68 c0 rjmp .+208 ; 0x7f6e + 7e9e: 67 e0 ldi r22, 0x07 ; 7 + 7ea0: 70 e0 ldi r23, 0x00 ; 0 + 7ea2: 80 e0 ldi r24, 0x00 ; 0 + 7ea4: 90 e0 ldi r25, 0x00 ; 0 + 7ea6: 95 df rcall .-214 ; 0x7dd2 + 7ea8: c8 2f mov r28, r24 + 7eaa: 68 e0 ldi r22, 0x08 ; 8 + 7eac: 70 e0 ldi r23, 0x00 ; 0 + 7eae: 80 e0 ldi r24, 0x00 ; 0 + { +#ifdef DEBUG_ON + putch('L'); +#endif + + uint16_t imagesize = (FLASH_readByte(7)<<8) | FLASH_readByte(8); + 7eb0: 90 e0 ldi r25, 0x00 ; 0 + 7eb2: 8f df rcall .-226 ; 0x7dd2 + 7eb4: d0 e0 ldi r29, 0x00 ; 0 + 7eb6: dc 2f mov r29, r28 + 7eb8: cc 27 eor r28, r28 + 7eba: c8 2b or r28, r24 + 7ebc: c0 fd sbrc r28, 0 + 7ebe: 57 c0 rjmp .+174 ; 0x7f6e + 7ec0: 33 9a sbi 0x06, 3 ; 6 + 7ec2: c1 2c mov r12, r1 + 7ec4: d1 2c mov r13, r1 + 7ec6: 00 e0 ldi r16, 0x00 ; 0 + 7ec8: 10 e0 ldi r17, 0x00 ; 0 + 7eca: bb 24 eor r11, r11 + 7ecc: b3 94 inc r11 + 7ece: 83 e0 ldi r24, 0x03 ; 3 + 7ed0: a8 2e mov r10, r24 + if (imagesize%2!=0) return; //basic check that we got even # of bytes + 7ed2: 95 e0 ldi r25, 0x05 ; 5 + 7ed4: 99 2e mov r9, r25 + + uint16_t b, i, nextAddress=0; + + LED_PIN |= _BV(LED); + 7ed6: 0c 17 cp r16, r28 +#endif + + uint16_t imagesize = (FLASH_readByte(7)<<8) | FLASH_readByte(8); + if (imagesize%2!=0) return; //basic check that we got even # of bytes + + uint16_t b, i, nextAddress=0; + 7ed8: 1d 07 cpc r17, r29 + 7eda: 70 f5 brcc .+92 ; 0x7f38 + + LED_PIN |= _BV(LED); + for (i=0; i + boot_spm_busy_wait(); + // Write from programming buffer + __boot_page_write_short((uint16_t)(void*)nextAddress ); //(i+2-SPM_PAGESIZE) + 7ee8: e8 2e mov r14, r24 + 7eea: f1 2c mov r15, r1 + if (imagesize%2!=0) return; //basic check that we got even # of bytes + + uint16_t b, i, nextAddress=0; + + LED_PIN |= _BV(LED); + for (i=0; i +#ifdef DEBUG_ON + putch('*'); +#endif + + //read 2 bytes (16 bits) from flash image, transfer them to page buffer + b = FLASH_readByte(i+10); // flash image starts at position 10 on the external flash memory: FLX:XX:FLASH_IMAGE_BYTES_HERE...... (XX = two size bytes) + 7ef8: f8 2a or r15, r24 + 7efa: f8 01 movw r30, r16 + 7efc: 07 01 movw r0, r14 + 7efe: b7 be out 0x37, r11 ; 55 + 7f00: e8 95 spm + 7f02: 11 24 eor r1, r1 + 7f04: 0e 5f subi r16, 0xFE ; 254 + 7f06: 1f 4f sbci r17, 0xFF ; 255 + 7f08: c8 01 movw r24, r16 + b |= FLASH_readByte(i+11) << 8; //bytes are stored big endian on external flash, need to flip the bytes to little endian for transfer to internal flash + 7f0a: 8f 77 andi r24, 0x7F ; 127 + 7f0c: 99 27 eor r25, r25 + 7f0e: 89 2b or r24, r25 + 7f10: 19 f0 breq .+6 ; 0x7f18 + 7f12: 0c 17 cp r16, r28 + __boot_page_fill_short((uint16_t)(void*)i,b); + 7f14: 1d 07 cpc r17, r29 + 7f16: f9 f6 brne .-66 ; 0x7ed6 + 7f18: f6 01 movw r30, r12 + 7f1a: a7 be out 0x37, r10 ; 55 + 7f1c: e8 95 spm + + //when 1 page is full (or we're on the last page), write it to the internal flash memory + if ((i+2)%SPM_PAGESIZE==0 || (i+2==imagesize)) + 7f1e: 07 b6 in r0, 0x37 ; 55 + 7f20: 00 fc sbrc r0, 0 + 7f22: fd cf rjmp .-6 ; 0x7f1e + 7f24: f6 01 movw r30, r12 + 7f26: 97 be out 0x37, r9 ; 55 + 7f28: e8 95 spm + 7f2a: 07 b6 in r0, 0x37 ; 55 + 7f2c: 00 fc sbrc r0, 0 + 7f2e: fd cf rjmp .-6 ; 0x7f2a + 7f30: f0 e8 ldi r31, 0x80 ; 128 + { + __boot_page_erase_short((uint16_t)(void*)nextAddress); //(i+2-SPM_PAGESIZE) + 7f32: cf 0e add r12, r31 + 7f34: d1 1c adc r13, r1 + 7f36: cf cf rjmp .-98 ; 0x7ed6 + boot_spm_busy_wait(); + 7f38: 33 98 cbi 0x06, 3 ; 6 + 7f3a: 81 e1 ldi r24, 0x11 ; 17 + 7f3c: 87 bf out 0x37, r24 ; 55 + // Write from programming buffer + __boot_page_write_short((uint16_t)(void*)nextAddress ); //(i+2-SPM_PAGESIZE) + 7f3e: e8 95 spm + 7f40: 2a 96 adiw r28, 0x0a ; 10 + 7f42: 61 e0 ldi r22, 0x01 ; 1 + boot_spm_busy_wait(); + 7f44: c1 30 cpi r28, 0x01 ; 1 + 7f46: d0 48 sbci r29, 0x80 ; 128 + 7f48: 10 f4 brcc .+4 ; 0x7f4e + nextAddress += SPM_PAGESIZE; + 7f4a: 82 e5 ldi r24, 0x52 ; 82 + 7f4c: 01 c0 rjmp .+2 ; 0x7f50 + 7f4e: 88 ed ldi r24, 0xD8 ; 216 + 7f50: 31 df rcall .-414 ; 0x7db4 + } + } + LED_PIN &= ~_BV(LED); + 7f52: 80 e0 ldi r24, 0x00 ; 0 + +#if defined(RWWSRE) + // Reenable read access to flash + boot_rww_enable(); + 7f54: 21 df rcall .-446 ; 0x7d98 + 7f56: 80 e0 ldi r24, 0x00 ; 0 + 7f58: 1f df rcall .-450 ; 0x7d98 +#ifdef DEBUG_ON + putch('E'); +#endif + + //erase the first 32/64K block where flash image resided (atmega328 should be less than 31K, and atmega1284 can be up to 64K) + if (imagesize+10<=32768) FLASH_command(SPIFLASH_BLOCKERASE_32K, 1); + 7f5a: 80 e0 ldi r24, 0x00 ; 0 + 7f5c: 1d df rcall .-454 ; 0x7d98 + 7f5e: 28 9a sbi 0x05, 0 ; 5 + 7f60: 88 e1 ldi r24, 0x18 ; 24 + 7f62: 80 93 60 00 sts 0x0060, r24 + 7f66: 88 e0 ldi r24, 0x08 ; 8 + else FLASH_command(SPIFLASH_BLOCKERASE_64K, 1); + 7f68: 80 93 60 00 sts 0x0060, r24 + 7f6c: ff cf rjmp .-2 ; 0x7f6c + SPI_transfer(0); + 7f6e: df 91 pop r29 + 7f70: cf 91 pop r28 + 7f72: 1f 91 pop r17 + SPI_transfer(0); + 7f74: 0f 91 pop r16 + 7f76: ff 90 pop r15 + 7f78: ef 90 pop r14 + SPI_transfer(0); + 7f7a: df 90 pop r13 + 7f7c: cf 90 pop r12 + 7f7e: bf 90 pop r11 + FLASH_UNSELECT; + 7f80: af 90 pop r10 + "wdr\n" + ); +} + +void watchdogConfig(uint8_t x) { + WDTCSR = _BV(WDCE) | _BV(WDE); + 7f82: 9f 90 pop r9 + 7f84: 08 95 ret + +00007f86 : + } +} + +void putch(char ch) { +#ifndef SOFT_UART + while (!(UART_SRA & _BV(UDRE0))); + 7f86: 90 91 c0 00 lds r25, 0x00C0 + 7f8a: 95 ff sbrs r25, 5 + 7f8c: fc cf rjmp .-8 ; 0x7f86 + UART_UDR = ch; + 7f8e: 80 93 c6 00 sts 0x00C6, r24 + 7f92: 08 95 ret + +00007f94 : + +#ifdef LED_DATA_FLASH +#if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) + LED_PORT ^= _BV(LED); +#else + LED_PIN |= _BV(LED); + 7f94: 33 9a sbi 0x06, 3 ; 6 + [uartBit] "I" (UART_RX_BIT) + : + "r25" +); +#else + while(!(UART_SRA & _BV(RXC0))) + 7f96: 80 91 c0 00 lds r24, 0x00C0 + 7f9a: 87 ff sbrs r24, 7 + 7f9c: fc cf rjmp .-8 ; 0x7f96 + ; + if (!(UART_SRA & _BV(FE0))) { + 7f9e: 80 91 c0 00 lds r24, 0x00C0 + 7fa2: 84 fd sbrc r24, 4 + 7fa4: 01 c0 rjmp .+2 ; 0x7fa8 +} +#endif + +// Watchdog functions. These are only safe with interrupts turned off. +void watchdogReset() { + __asm__ __volatile__ ( + 7fa6: a8 95 wdr + * don't care that an invalid char is returned...) + */ + watchdogReset(); + } + + ch = UART_UDR; + 7fa8: 80 91 c6 00 lds r24, 0x00C6 + +#ifdef LED_DATA_FLASH +#if defined(__AVR_ATmega8__) || defined (__AVR_ATmega32__) + LED_PORT ^= _BV(LED); +#else + LED_PIN |= _BV(LED); + 7fac: 33 9a sbi 0x06, 3 ; 6 +#endif +#endif + + return ch; +} + 7fae: 08 95 ret + +00007fb0 : + do getch(); while (--count); + verifySpace(); +} + +void verifySpace() { + if (getch() != CRC_EOP) { + 7fb0: f1 df rcall .-30 ; 0x7f94 + 7fb2: 80 32 cpi r24, 0x20 ; 32 + 7fb4: 39 f0 breq .+14 ; 0x7fc4 + 7fb6: 88 e1 ldi r24, 0x18 ; 24 + "wdr\n" + ); +} + +void watchdogConfig(uint8_t x) { + WDTCSR = _BV(WDCE) | _BV(WDE); + 7fb8: 80 93 60 00 sts 0x0060, r24 + 7fbc: 88 e0 ldi r24, 0x08 ; 8 + WDTCSR = x; + 7fbe: 80 93 60 00 sts 0x0060, r24 + 7fc2: ff cf rjmp .-2 ; 0x7fc2 + +void verifySpace() { + if (getch() != CRC_EOP) { + watchdogConfig(WATCHDOG_16MS); // shorten WD timeout + while (1) // and busy-loop so that WD causes + ; // a reset and app start. + 7fc4: 84 e1 ldi r24, 0x14 ; 20 + } + putch(STK_INSYNC); + 7fc6: df cf rjmp .-66 ; 0x7f86 + +00007fc8 : + ::[count] "M" (UART_B_VALUE) + ); +} +#endif + +void getNch(uint8_t count) { + 7fc8: cf 93 push r28 + 7fca: c8 2f mov r28, r24 + do getch(); while (--count); + 7fcc: e3 df rcall .-58 ; 0x7f94 + 7fce: c1 50 subi r28, 0x01 ; 1 + 7fd0: e9 f7 brne .-6 ; 0x7fcc + 7fd2: cf 91 pop r28 + verifySpace(); +} + 7fd4: ed cf rjmp .-38 ; 0x7fb0 + +00007fd6 : + "wdr\n" + ); +} + +void watchdogConfig(uint8_t x) { + WDTCSR = _BV(WDCE) | _BV(WDE); + 7fd6: e0 e6 ldi r30, 0x60 ; 96 + 7fd8: f0 e0 ldi r31, 0x00 ; 0 + 7fda: 98 e1 ldi r25, 0x18 ; 24 + 7fdc: 90 83 st Z, r25 + WDTCSR = x; + 7fde: 80 83 st Z, r24 + 7fe0: 08 95 ret + +00007fe2 : + +void appStart(uint8_t rstFlags) { + // save the reset flags in the designated register + // This can be saved in a main program by putting code in .init0 (which + // executes before normal c init code) to save R2 to a global variable. + __asm__ __volatile__ ("mov r2, %0\n" :: "r" (rstFlags)); + 7fe2: 28 2e mov r2, r24 + "wdr\n" + ); +} + +void watchdogConfig(uint8_t x) { + WDTCSR = _BV(WDCE) | _BV(WDE); + 7fe4: e0 e6 ldi r30, 0x60 ; 96 + 7fe6: f0 e0 ldi r31, 0x00 ; 0 + 7fe8: 88 e1 ldi r24, 0x18 ; 24 + 7fea: 80 83 st Z, r24 + WDTCSR = x; + 7fec: 10 82 st Z, r1 + // This can be saved in a main program by putting code in .init0 (which + // executes before normal c init code) to save R2 to a global variable. + __asm__ __volatile__ ("mov r2, %0\n" :: "r" (rstFlags)); + + watchdogConfig(WATCHDOG_OFF); + __asm__ __volatile__ ( + 7fee: ee 27 eor r30, r30 + 7ff0: ff 27 eor r31, r31 + 7ff2: 09 94 ijmp diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/pin_defs.h b/hardware/MySensors/avr/bootloaders/DualOptiboot/pin_defs.h new file mode 100644 index 0000000..30b0a67 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/pin_defs.h @@ -0,0 +1,742 @@ +/*------------------------------------------------------------------------ */ +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) +/*------------------------------------------------------------------------ */ + +/* Onboard LED is connected to pin PB5 in Arduino NG, Diecimila, and Duemilanove + */ +#if !defined(LED) +#define LED B1 //D9 +#endif + +/* Ports for soft UART */ +#ifdef SOFT_UART +#define UART_PORT PORTD +#define UART_PIN PIND +#define UART_DDR DDRD +#define UART_TX_BIT 1 +#define UART_RX_BIT 0 +#endif +#endif + +#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega32__) + //Name conversion R.Wiersma + #define UCSR0A UCSRA + #define UDR0 UDR + #define UDRE0 UDRE + #define RXC0 RXC + #define FE0 FE + #define TIFR1 TIFR + #define WDTCSR WDTCR +#endif +#if defined(__AVR_ATmega32__) + #define WDCE WDTOE +#endif + +/* Luminet support */ +/*------------------------------------------------------------------------ */ +#if defined(__AVR_ATtiny84__) +/*------------------------------------------------------------------------ */ +/* Red LED is connected to pin PA4 */ +#if !defined(LED) +#define LED A4 +#endif + +/* Ports for soft UART - left port only for now. TX/RX on PA2/PA3 */ +#ifdef SOFT_UART +#define UART_PORT PORTA +#define UART_PIN PINA +#define UART_DDR DDRA +#define UART_TX_BIT 2 +#define UART_RX_BIT 3 +#endif +#endif + +/*------------------------------------------------------------------------ */ +/* Sanguino support (and other 40pin DIP cpus) */ +#if defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega32__) +/*------------------------------------------------------------------------ */ +/* Onboard LED is connected to pin PB0 on Sanguino */ +#if !defined(LED) +#define LED D7 //Moteino MEGA D15 +#endif + +/* Ports for soft UART */ +#ifdef SOFT_UART +#define UART_PORT PORTD +#define UART_PIN PIND +#define UART_DDR DDRD +#define UART_TX_BIT 1 +#define UART_RX_BIT 0 +#endif +#endif + +/*------------------------------------------------------------------------ */ +/* Mega support */ +#if defined(__AVR_ATmega1280__) +/*------------------------------------------------------------------------ */ +/* Onboard LED is connected to pin PB7 on Arduino Mega */ +#if !defined(LED) +#define LED B7 +#endif + +/* Ports for soft UART */ +#ifdef SOFT_UART +#define UART_PORT PORTE +#define UART_PIN PINE +#define UART_DDR DDRE +#define UART_TX_BIT 1 +#define UART_RX_BIT 0 +#endif +#endif + +/* + * ------------------------------------------------------------------------ + * A bunch of macros to enable the LED to be specifed as "B5" for bit 5 + * of port B, and similar. + */ + +#define A0 0x100 +#define A1 0x101 +#define A2 0x102 +#define A3 0x103 +#define A4 0x104 +#define A5 0x105 +#define A6 0x106 +#define A7 0x107 + +#define B0 0x200 +#define B1 0x201 +#define B2 0x202 +#define B3 0x203 +#define B4 0x204 +#define B5 0x205 +#define B6 0x206 +#define B7 0x207 + +#define C0 0x300 +#define C1 0x301 +#define C2 0x302 +#define C3 0x303 +#define C4 0x304 +#define C5 0x305 +#define C6 0x306 +#define C7 0x307 + +#define D0 0x400 +#define D1 0x401 +#define D2 0x402 +#define D3 0x403 +#define D4 0x404 +#define D5 0x405 +#define D6 0x406 +#define D7 0x407 + +#define E0 0x500 +#define E1 0x501 +#define E2 0x502 +#define E3 0x503 +#define E4 0x504 +#define E5 0x505 +#define E6 0x506 +#define E7 0x507 + +#define F0 0x600 +#define F1 0x601 +#define F2 0x602 +#define F3 0x603 +#define F4 0x604 +#define F5 0x605 +#define F6 0x606 +#define F7 0x607 + +#define G0 0x700 +#define G1 0x701 +#define G2 0x702 +#define G3 0x703 +#define G4 0x704 +#define G5 0x705 +#define G6 0x706 +#define G7 0x707 + +#define H0 0x800 +#define H1 0x801 +#define H2 0x802 +#define H3 0x803 +#define H4 0x804 +#define H5 0x805 +#define H6 0x806 +#define H7 0x807 + +#define J0 0xA00 +#define J1 0xA01 +#define J2 0xA02 +#define J3 0xA03 +#define J4 0xA04 +#define J5 0xA05 +#define J6 0xA06 +#define J7 0xA07 + +#define K0 0xB00 +#define K1 0xB01 +#define K2 0xB02 +#define K3 0xB03 +#define K4 0xB04 +#define K5 0xB05 +#define K6 0xB06 +#define K7 0xB07 + +#define L0 0xC00 +#define L1 0xC01 +#define L2 0xC02 +#define L3 0xC03 +#define L4 0xC04 +#define L5 0xC05 +#define L6 0xC06 +#define L7 0xC07 + + + +#if LED == B0 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB0 +#elif LED == B1 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB1 +#elif LED == B2 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB2 +#elif LED == B3 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB3 +#elif LED == B4 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB4 +#elif LED == B5 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB5 +#elif LED == B6 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB6 +#elif LED == B7 +#undef LED +#define LED_DDR DDRB +#define LED_PORT PORTB +#define LED_PIN PINB +#define LED PINB7 + +#elif LED == C0 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC0 +#elif LED == C1 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC1 +#elif LED == C2 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC2 +#elif LED == C3 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC3 +#elif LED == C4 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC4 +#elif LED == C5 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC5 +#elif LED == C6 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC6 +#elif LED == C7 +#undef LED +#define LED_DDR DDRC +#define LED_PORT PORTC +#define LED_PIN PINC +#define LED PINC7 + +#elif LED == D0 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND0 +#elif LED == D1 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND1 +#elif LED == D2 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND2 +#elif LED == D3 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND3 +#elif LED == D4 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND4 +#elif LED == D5 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND5 +#elif LED == D6 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND6 +#elif LED == D7 +#undef LED +#define LED_DDR DDRD +#define LED_PORT PORTD +#define LED_PIN PIND +#define LED PIND7 + +#elif LED == E0 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE0 +#elif LED == E1 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE1 +#elif LED == E2 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE2 +#elif LED == E3 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE3 +#elif LED == E4 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE4 +#elif LED == E5 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE5 +#elif LED == E6 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE6 +#elif LED == E7 +#undef LED +#define LED_DDR DDRE +#define LED_PORT PORTE +#define LED_PIN PINE +#define LED PINE7 + +#elif LED == F0 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF0 +#elif LED == F1 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF1 +#elif LED == F2 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF2 +#elif LED == F3 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF3 +#elif LED == F4 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF4 +#elif LED == F5 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF5 +#elif LED == F6 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF6 +#elif LED == F7 +#undef LED +#define LED_DDR DDRF +#define LED_PORT PORTF +#define LED_PIN PINF +#define LED PINF7 + +#elif LED == G0 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING0 +#elif LED == G1 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING1 +#elif LED == G2 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING2 +#elif LED == G3 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING3 +#elif LED == G4 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING4 +#elif LED == G5 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING5 +#elif LED == G6 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING6 +#elif LED == G7 +#undef LED +#define LED_DDR DDRG +#define LED_PORT PORTG +#define LED_PIN PING +#define LED PING7 + +#elif LED == H0 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH0 +#elif LED == H1 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH1 +#elif LED == H2 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH2 +#elif LED == H3 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH3 +#elif LED == H4 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH4 +#elif LED == H5 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH5 +#elif LED == H6 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH6 +#elif LED == H7 +#undef LED +#define LED_DDR DDRH +#define LED_PORT PORTH +#define LED_PIN PINH +#define LED PINH7 + +#elif LED == J0 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ0 +#elif LED == J1 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ1 +#elif LED == J2 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ2 +#elif LED == J3 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ3 +#elif LED == J4 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ4 +#elif LED == J5 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ5 +#elif LED == J6 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ6 +#elif LED == J7 +#undef LED +#define LED_DDR DDRJ +#define LED_PORT PORTJ +#define LED_PIN PINJ +#define LED PINJ7 + +#elif LED == K0 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK0 +#elif LED == K1 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK1 +#elif LED == K2 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK2 +#elif LED == K3 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK3 +#elif LED == K4 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK4 +#elif LED == K5 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK5 +#elif LED == K6 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK6 +#elif LED == K7 +#undef LED +#define LED_DDR DDRK +#define LED_PORT PORTK +#define LED_PIN PINK +#define LED PINK7 + +#elif LED == L0 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL0 +#elif LED == L1 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL1 +#elif LED == L2 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL2 +#elif LED == L3 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL3 +#elif LED == L4 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL4 +#elif LED == L5 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL5 +#elif LED == L6 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL6 +#elif LED == L7 +#undef LED +#define LED_DDR DDRL +#define LED_PORT PORTL +#define LED_PIN PINL +#define LED PINL7 + +#elif LED == A0 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA0 +#elif LED == A1 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA1 +#elif LED == A2 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA2 +#elif LED == A3 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA3 +#elif LED == A4 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA4 +#elif LED == A5 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA5 +#elif LED == A6 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA6 +#elif LED == A7 +#undef LED +#define LED_DDR DDRA +#define LED_PORT PORTA +#define LED_PIN PINA +#define LED PINA7 + +#else +#error ------------------------------------------- +#error Unrecognized LED name. Should be like "B5" +#error ------------------------------------------- +#endif diff --git a/hardware/MySensors/avr/bootloaders/DualOptiboot/stk500.h b/hardware/MySensors/avr/bootloaders/DualOptiboot/stk500.h new file mode 100644 index 0000000..ca0dd91 --- /dev/null +++ b/hardware/MySensors/avr/bootloaders/DualOptiboot/stk500.h @@ -0,0 +1,39 @@ +/* STK500 constants list, from AVRDUDE */ +#define STK_OK 0x10 +#define STK_FAILED 0x11 // Not used +#define STK_UNKNOWN 0x12 // Not used +#define STK_NODEVICE 0x13 // Not used +#define STK_INSYNC 0x14 // ' ' +#define STK_NOSYNC 0x15 // Not used +#define ADC_CHANNEL_ERROR 0x16 // Not used +#define ADC_MEASURE_OK 0x17 // Not used +#define PWM_CHANNEL_ERROR 0x18 // Not used +#define PWM_ADJUST_OK 0x19 // Not used +#define CRC_EOP 0x20 // 'SPACE' +#define STK_GET_SYNC 0x30 // '0' +#define STK_GET_SIGN_ON 0x31 // '1' +#define STK_SET_PARAMETER 0x40 // '@' +#define STK_GET_PARAMETER 0x41 // 'A' +#define STK_SET_DEVICE 0x42 // 'B' +#define STK_SET_DEVICE_EXT 0x45 // 'E' +#define STK_ENTER_PROGMODE 0x50 // 'P' +#define STK_LEAVE_PROGMODE 0x51 // 'Q' +#define STK_CHIP_ERASE 0x52 // 'R' +#define STK_CHECK_AUTOINC 0x53 // 'S' +#define STK_LOAD_ADDRESS 0x55 // 'U' +#define STK_UNIVERSAL 0x56 // 'V' +#define STK_PROG_FLASH 0x60 // '`' +#define STK_PROG_DATA 0x61 // 'a' +#define STK_PROG_FUSE 0x62 // 'b' +#define STK_PROG_LOCK 0x63 // 'c' +#define STK_PROG_PAGE 0x64 // 'd' +#define STK_PROG_FUSE_EXT 0x65 // 'e' +#define STK_READ_FLASH 0x70 // 'p' +#define STK_READ_DATA 0x71 // 'q' +#define STK_READ_FUSE 0x72 // 'r' +#define STK_READ_LOCK 0x73 // 's' +#define STK_READ_PAGE 0x74 // 't' +#define STK_READ_SIGN 0x75 // 'u' +#define STK_READ_OSCCAL 0x76 // 'v' +#define STK_READ_FUSE_EXT 0x77 // 'w' +#define STK_READ_OSCCAL_EXT 0x78 // 'x' From 05e6e0b4d116582a1b2856ae950da4f65b483f71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 5 May 2015 22:02:16 +0200 Subject: [PATCH 10/79] Updated boards.txt to reflect sensebender name, and corrected paths in platform.txt (fixed arduino 1.6.4 warnings) --- hardware/MySensors/avr/boards.txt | 2 +- hardware/MySensors/avr/platform.txt | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index 7220cad..d2ab777 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -1,5 +1,5 @@ -MysensorsMicro.name=Mysensors Micro +MysensorsMicro.name=Sensebender Micro MysensorsMicro.upload.tool=arduino:avrdude MysensorsMicro.upload.protocol=arduino diff --git a/hardware/MySensors/avr/platform.txt b/hardware/MySensors/avr/platform.txt index 332dfce..247f5cc 100644 --- a/hardware/MySensors/avr/platform.txt +++ b/hardware/MySensors/avr/platform.txt @@ -77,8 +77,9 @@ recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).* # AVR Uploader/Programmers tools # ------------------------------ -tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude -tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf +tools.avrdude.cmd.path={path}/bin/avrdude +tools.avrdude.config.path={path}/etc/avrdude.conf +tools.avrdude.path={runtime.tools.avrdude.path} tools.avrdude.upload.params.verbose=-v tools.avrdude.upload.params.quiet=-q -q From a1c71b49a7fb96f1e8ccbf5bfe274cce84db98dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Sun, 10 May 2015 14:02:33 +0200 Subject: [PATCH 11/79] Updated boards.txt to have to variants of sensebender micro : 1Mhz and 8Mhz --- hardware/MySensors/avr/boards.txt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index d2ab777..349cf25 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -1,3 +1,4 @@ +menu.cpu=Processor MysensorsMicro.name=Sensebender Micro @@ -19,4 +20,10 @@ MysensorsMicro.build.board=AVR_MICRO8 MysensorsMicro.build.core=arduino:arduino MysensorsMicro.build.variant=micro MysensorsMicro.build.mcu=atmega328p -MysensorsMicro.build.f_cpu=8000000L +#MysensorsMicro.build.f_cpu=8000000L + +MysensorsMicro.menu.cpu.8Mhz=Atmega328 8Mhz +MysensorsMicro.menu.cpu.8Mhz.build.f_cpu=8000000L + +MysensorsMicro.menu.cpu.1Mhz=Atmega328 1Mhz +MysensorsMicro.menu.cpu.1Mhz.build.f_cpu=1000000L \ No newline at end of file From 7fcdbb32d887f026b367b59f3a2ecb5db1bc0e16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 12 May 2015 21:23:09 +0200 Subject: [PATCH 12/79] Added running average methods to determine if we should send temperature / humidity reports --- .../SensebenderMicro/SensebenderMicro.ino | 119 ++++++++++++------ libraries/RunningAverage/RunningAverage.cpp | 101 +++++++++++++++ libraries/RunningAverage/RunningAverage.h | 56 +++++++++ .../examples/fillValue/fillValue.ino | 38 ++++++ .../examples/ra_MinMaxTest/ra_MinMaxTest.ino | 46 +++++++ .../examples/ra_hour/ra_hour.ino | 40 ++++++ .../examples/ra_test/ra_test.ino | 40 ++++++ libraries/RunningAverage/keywords.txt | 32 +++++ 8 files changed, 431 insertions(+), 41 deletions(-) create mode 100644 libraries/RunningAverage/RunningAverage.cpp create mode 100644 libraries/RunningAverage/RunningAverage.h create mode 100644 libraries/RunningAverage/examples/fillValue/fillValue.ino create mode 100644 libraries/RunningAverage/examples/ra_MinMaxTest/ra_MinMaxTest.ino create mode 100644 libraries/RunningAverage/examples/ra_hour/ra_hour.ino create mode 100644 libraries/RunningAverage/examples/ra_test/ra_test.ino create mode 100644 libraries/RunningAverage/keywords.txt diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 7c5a074..805d5ab 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -14,19 +14,22 @@ #include #include #include +#include +#include // Define a static node address, remove if you want auto address assignment //#define NODE_ADDRESS 3 -#define RELEASE "1.1" +#define RELEASE "1.2" + +#define AVERAGES 2 // Child sensor ID's #define CHILD_ID_TEMP 1 #define CHILD_ID_HUM 2 -#define CHILD_ID_BATT 199 // How many milli seconds between each measurement -#define MEASURE_INTERVAL 60000 +#define MEASURE_INTERVAL 1000 // FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller #define FORCE_TRANSMIT_INTERVAL 30 @@ -34,7 +37,7 @@ // When MEASURE_INTERVAL is 60000 and FORCE_TRANSMIT_INTERVAL is 30, we force a transmission every 30 minutes. // Between the forced transmissions a tranmission will only occur if the measured value differs from the previous measurement -//Pin definitions +// Pin definitions #define TEST_PIN A0 #define LED_PIN A2 #define ATSHA204_PIN 17 // A3 @@ -50,10 +53,10 @@ MySensor gw; // Sensor messages MyMessage msgHum(CHILD_ID_HUM, V_HUM); MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); -MyMessage msgBattery(CHILD_ID_BATT, V_VOLTAGE); // Global settings int measureCount = 0; +int sendBattery = 0; boolean isMetric = true; // Storage of old measurements @@ -61,14 +64,21 @@ float lastTemperature = -100; int lastHumidity = -100; long lastBattery = -100; -bool highfreq = true; +RunningAverage raHum(AVERAGES); +RunningAverage raTemp(AVERAGES); +/**************************************************** + * + * Setup code + * + ****************************************************/ void setup() { - +// clock_prescale_set(clock_div_8); // Switch to 1Mhz right after powerup. + pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); - Serial.begin(115200); + Serial.begin(19200); Serial.print(F("Sensebender Micro FW ")); Serial.print(RELEASE); Serial.flush(); @@ -79,6 +89,10 @@ void setup() { digitalWrite(TEST_PIN, HIGH); // Enable pullup if (!digitalRead(TEST_PIN)) testMode(); + // Make sure that ATSHA204 is not floating + pinMode(ATSHA204_PIN, INPUT); + digitalWrite(ATSHA204_PIN, HIGH); + digitalWrite(TEST_PIN,LOW); digitalWrite(LED_PIN, HIGH); @@ -99,19 +113,22 @@ void setup() { gw.present(CHILD_ID_HUM,S_HUM); isMetric = gw.getConfig().isMetric; - Serial.print("isMetric: "); Serial.println(isMetric); - + Serial.print(F("isMetric: ")); Serial.println(isMetric); + raHum.clear(); + raTemp.clear(); + sendTempHumidityMeasurements(false); } -// Main loop function +/*********************************************** + * + * Main loop function + * + ***********************************************/ void loop() { measureCount ++; + sendBattery ++; bool forceTransmit = false; - - // When we wake up the 5th time after power on, switch to 1Mhz clock - // This allows us to print debug messages on startup (as serial port is dependend on oscilator settings). - if ((measureCount == 5) && highfreq) switchClock(1< FORCE_TRANSMIT_INTERVAL) { // force a transmission forceTransmit = true; @@ -119,32 +136,52 @@ void loop() { } gw.process(); - sendBattLevel(forceTransmit); + sendTempHumidityMeasurements(forceTransmit); + if (sendBattery > 60) + { + sendBattLevel(forceTransmit); // Not needed to send battery info that often + sendBattery = 0; + } gw.sleep(MEASURE_INTERVAL); } -/* + +/********************************************* + * * Sends temperature and humidity from Si7021 sensor * * Parameters * - force : Forces transmission of a value (even if it's the same as previous measurement) - */ + * + *********************************************/ void sendTempHumidityMeasurements(bool force) { - if (force) { - lastHumidity = -100; - lastTemperature = -100; - } + bool tx = force; si7021_env data = humiditySensor.getHumidityAndTemperature(); + float oldAvgTemp = raTemp.getAverage(); + float oldAvgHum = raHum.getAverage(); - float temperature = (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths) / 100.0; - - int humidity = data.humidityPercent; + raTemp.addValue(data.celsiusHundredths / 100); + raHum.addValue(data.humidityPercent); + + float diffTemp = abs(oldAvgTemp - raTemp.getAverage()); + float diffHum = abs(oldAvgHum - raHum.getAverage()); - if ((lastTemperature != temperature) | (lastHumidity != humidity)) { + Serial.println(diffTemp); + Serial.println(diffHum); + + if (isnan(diffTemp)) tx = true; + if (diffTemp > 0.2) tx = true; + if (diffHum > 0.5) tx = true; + + if (tx) { + measureCount = 0; + float temperature = (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths) / 100.0; + + int humidity = data.humidityPercent; Serial.print("T: ");Serial.println(temperature); Serial.print("H: ");Serial.println(humidity); @@ -155,12 +192,14 @@ void sendTempHumidityMeasurements(bool force) } } -/* - * Sends battery information (both voltage, and battery percentage) +/******************************************** + * + * Sends battery information (battery percentage) * * Parameters * - force : Forces transmission of a value - */ + * + *******************************************/ void sendBattLevel(bool force) { if (force) lastBattery = -1; @@ -176,6 +215,11 @@ void sendBattLevel(bool force) } } +/******************************************* + * + * Internal battery ADC measuring + * + *******************************************/ long readVcc() { // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference @@ -202,18 +246,11 @@ long readVcc() { return result; // Vcc in millivolts } -void switchClock(unsigned char clk) -{ - cli(); - - CLKPR = 1< fillValue +// 0.2.03 - 2013-11-31 getElement +// 0.2.04 - 2014-07-03 added memory protection +// 0.2.05 - 2014-12-16 changed float -> double +// 0.2.06 - 2015-03-07 all size uint8_t +// 0.2.07 - 2015-03-16 added getMin() and getMax() functions (Eric Mulder) +// 0.2.08 - 2015-04-10 refactored getMin() and getMax() implementation +// +// Released to the public domain +// + +#include "RunningAverage.h" +#include + +RunningAverage::RunningAverage(uint8_t size) +{ + _size = size; + _ar = (double*) malloc(_size * sizeof(double)); + if (_ar == NULL) _size = 0; + clear(); +} + +RunningAverage::~RunningAverage() +{ + if (_ar != NULL) free(_ar); +} + +// resets all counters +void RunningAverage::clear() +{ + _cnt = 0; + _idx = 0; + _sum = 0.0; + _min = NAN; + _max = NAN; + for (uint8_t i = 0; i < _size; i++) + { + _ar[i] = 0.0; // keeps addValue simple + } +} + +// adds a new value to the data-set +void RunningAverage::addValue(double value) +{ + if (_ar == NULL) return; // allocation error + _sum -= _ar[_idx]; + _ar[_idx] = value; + _sum += _ar[_idx]; + _idx++; + if (_idx == _size) _idx = 0; // faster than % + // handle min max + if (_cnt == 0) _min = _max = value; + else if (value < _min) _min = value; + else if (value > _max) _max = value; + // update count as last otherwise if( _cnt == 0) above will fail + if (_cnt < _size) _cnt++; +} + +// returns the average of the data-set added sofar +double RunningAverage::getAverage() +{ + if (_cnt == 0) return NAN; + return _sum / _cnt; +} + +// returns the value of an element if exist, NAN otherwise +double RunningAverage::getElement(uint8_t idx) +{ + if (idx >=_cnt ) return NAN; + return _ar[idx]; +} + +// fill the average with a value +// the param number determines how often value is added (weight) +// number should preferably be between 1 and size +void RunningAverage::fillValue(double value, uint8_t number) +{ + clear(); // TODO conditional? if (clr) clear(); + + for (uint8_t i = 0; i < number; i++) + { + addValue(value); + } +} +// END OF FILE \ No newline at end of file diff --git a/libraries/RunningAverage/RunningAverage.h b/libraries/RunningAverage/RunningAverage.h new file mode 100644 index 0000000..c17240a --- /dev/null +++ b/libraries/RunningAverage/RunningAverage.h @@ -0,0 +1,56 @@ +// +// FILE: RunningAverage.h +// AUTHOR: Rob dot Tillaart at gmail dot com +// VERSION: 0.2.08 +// DATE: 2015-apr-10 +// PURPOSE: RunningAverage library for Arduino +// URL: http://arduino.cc/playground/Main/RunningAverage +// HISTORY: See RunningAverage.cpp +// +// Released to the public domain +// +// backwards compatibility +// clr() clear() +// add(x) addValue(x) +// avg() getAverage() + +#ifndef RunningAverage_h +#define RunningAverage_h + +#define RUNNINGAVERAGE_LIB_VERSION "0.2.08" + +#include "Arduino.h" + +class RunningAverage +{ +public: + RunningAverage(void); + RunningAverage(uint8_t); + ~RunningAverage(); + + void clear(); + void addValue(double); + void fillValue(double, uint8_t); + + double getAverage(); + // returns lowest value added to the data-set since last clear + double getMin() { return _min; }; + // returns highest value added to the data-set since last clear + double getMax() { return _max; }; + + double getElement(uint8_t idx); + uint8_t getSize() { return _size; } + uint8_t getCount() { return _cnt; } + +protected: + uint8_t _size; + uint8_t _cnt; + uint8_t _idx; + double _sum; + double * _ar; + double _min; + double _max; +}; + +#endif +// END OF FILE \ No newline at end of file diff --git a/libraries/RunningAverage/examples/fillValue/fillValue.ino b/libraries/RunningAverage/examples/fillValue/fillValue.ino new file mode 100644 index 0000000..aaf8900 --- /dev/null +++ b/libraries/RunningAverage/examples/fillValue/fillValue.ino @@ -0,0 +1,38 @@ +// +// FILE: fillValue.pde +// AUTHOR: Rob Tillaart +// DATE: 2012-12-30 +// +// PUPROSE: show working of fillValue +// + +#include "RunningAverage.h" + +RunningAverage myRA(10); +int samples = 0; + +void setup(void) +{ + Serial.begin(115200); + Serial.print("Demo RunningAverage lib - fillValue "); + Serial.print("Version: "); + Serial.println(RUNNINGAVERAGE_LIB_VERSION); + + myRA.fillValue(100,5); +} + +void loop(void) +{ + long rn = random(0, 100); + myRA.addValue(rn/100.0); + samples++; + Serial.print("Running Average: "); + Serial.println(myRA.getAverage(), 4); + + if (samples == 300) + { + samples = 0; + myRA.fillValue(100, 10); + } + delay(100); +} \ No newline at end of file diff --git a/libraries/RunningAverage/examples/ra_MinMaxTest/ra_MinMaxTest.ino b/libraries/RunningAverage/examples/ra_MinMaxTest/ra_MinMaxTest.ino new file mode 100644 index 0000000..437251a --- /dev/null +++ b/libraries/RunningAverage/examples/ra_MinMaxTest/ra_MinMaxTest.ino @@ -0,0 +1,46 @@ +// +// FILE: runningAverageMinMaxTest.ino +// AUTHOR: Rob Tillaart +// VERSION: 0.1.00 +// DATE: 2015-apr-10 +// +// PUPROSE: demo +// + +#include "RunningAverage.h" + +RunningAverage myRA(10); +int samples = 0; + +void setup(void) +{ + Serial.begin(115200); + Serial.println("\nDemo runningAverageMinMaxTest"); + Serial.print("Version: "); + Serial.println(RUNNINGAVERAGE_LIB_VERSION); + myRA.clear(); // explicitly start clean + + Serial.println("\nCNT\tMIN\tAVG\tMAX"); +} + +void loop(void) +{ + long rn = random(0, 1000); + myRA.addValue(rn * 0.001); + samples++; + Serial.print(samples); + Serial.print("\t"); + Serial.print(myRA.getMin(), 3); + Serial.print("\t"); + Serial.print(myRA.getAverage(), 3); + Serial.print("\t"); + Serial.println(myRA.getMax(), 3); + + if (samples == 100) + { + samples = 0; + myRA.clear(); + Serial.println("\nCNT\tMIN\tAVG\tMAX"); + } + delay(10); +} diff --git a/libraries/RunningAverage/examples/ra_hour/ra_hour.ino b/libraries/RunningAverage/examples/ra_hour/ra_hour.ino new file mode 100644 index 0000000..09d9214 --- /dev/null +++ b/libraries/RunningAverage/examples/ra_hour/ra_hour.ino @@ -0,0 +1,40 @@ +// +// FILE: runningAverageHour.pde +// AUTHOR: Rob Tillaart +// DATE: 2012-12-30 +// +// PUPROSE: show working of runningAverage per hour +// in 2 steps - last minute + last hour +// 3 or more steps also possible +// + +#include "RunningAverage.h" + +RunningAverage raMinute(60); +RunningAverage raHour(60); + +int samples = 0; + +void setup(void) +{ + Serial.begin(115200); + Serial.println("Demo RunningAverage lib - average per minute & hour"); + Serial.print("Version: "); + Serial.println(RUNNINGAVERAGE_LIB_VERSION); + raHour.clear(); + raMinute.clear(); +} + +void loop(void) +{ + long rn = random(0, 100); + raMinute.addValue(rn); + samples++; + + if (samples % 60 == 0) raHour.addValue(raMinute.getAverage()); + + Serial.print(" raMinute: "); + Serial.print(raMinute.getAverage(), 4); + Serial.print(" raHour: "); + Serial.println(raHour.getAverage(), 4); +} \ No newline at end of file diff --git a/libraries/RunningAverage/examples/ra_test/ra_test.ino b/libraries/RunningAverage/examples/ra_test/ra_test.ino new file mode 100644 index 0000000..146112e --- /dev/null +++ b/libraries/RunningAverage/examples/ra_test/ra_test.ino @@ -0,0 +1,40 @@ +// +// FILE: runningAverageTest.pde +// AUTHOR: Rob Tillaart +// VERSION: 0.1.01 +// DATE: 2012-12-30 +// +// PUPROSE: show working of runningAverage +// + +#include "RunningAverage.h" + +RunningAverage myRA(10); +int samples = 0; + +void setup(void) +{ + Serial.begin(115200); + Serial.println("Demo RunningAverage lib"); + Serial.print("Version: "); + Serial.println(RUNNINGAVERAGE_LIB_VERSION); + myRA.clear(); // explicitly start clean +} + +void loop(void) +{ + long rn = random(0, 1000); + myRA.addValue(rn * 0.001); + samples++; + Serial.print(samples); + Serial.print("\t Running Average: "); + Serial.println(myRA.getAverage(), 3); + + if (samples == 300) + { + samples = 0; + myRA.clear(); + Serial.println(); + } + delay(10); +} \ No newline at end of file diff --git a/libraries/RunningAverage/keywords.txt b/libraries/RunningAverage/keywords.txt new file mode 100644 index 0000000..3bac631 --- /dev/null +++ b/libraries/RunningAverage/keywords.txt @@ -0,0 +1,32 @@ +####################################### +# Syntax Coloring Map For RunningAverage +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +RunningAverage KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +clear KEYWORD2 +addValue KEYWORD2 +getAverage KEYWORD2 +getMin KEYWORD2 +getMax KEYWORD2 +fillValue KEYWORD2 +getElement KEYWORD2 +getSize KEYWORD2 +getCount KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + + +####################################### +# Constants (LITERAL1) +####################################### \ No newline at end of file From bf7372eeac80cb6594ec055a4faa29643991a92b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 12 May 2015 21:36:14 +0200 Subject: [PATCH 13/79] Corrected measurement interval back to 60 seconds (had set it to 1 second in order to verify functionality) --- .../MySensors/examples/SensebenderMicro/SensebenderMicro.ino | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 805d5ab..2bcba60 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -29,7 +29,7 @@ #define CHILD_ID_HUM 2 // How many milli seconds between each measurement -#define MEASURE_INTERVAL 1000 +#define MEASURE_INTERVAL 60000 // FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller #define FORCE_TRANSMIT_INTERVAL 30 @@ -117,6 +117,7 @@ void setup() { raHum.clear(); raTemp.clear(); sendTempHumidityMeasurements(false); + sendBattLevel(false); } From d5becd5ca1aa09771ce2c27c2779b5c9b278337e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 12 May 2015 22:14:28 +0200 Subject: [PATCH 14/79] Corrected 1Mhz operating frequency --- .../examples/SensebenderMicro/SensebenderMicro.ino | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 2bcba60..acc92ba 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -58,6 +58,7 @@ MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); int measureCount = 0; int sendBattery = 0; boolean isMetric = true; +boolean highfreq = true; // Storage of old measurements float lastTemperature = -100; @@ -73,12 +74,11 @@ RunningAverage raTemp(AVERAGES); * ****************************************************/ void setup() { -// clock_prescale_set(clock_div_8); // Switch to 1Mhz right after powerup. pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); - Serial.begin(19200); + Serial.begin(115200); Serial.print(F("Sensebender Micro FW ")); Serial.print(RELEASE); Serial.flush(); @@ -131,6 +131,12 @@ void loop() { sendBattery ++; bool forceTransmit = false; + if ((measureCount == 5) && highfreq) + { + clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. + highfreq = false; + } + if (measureCount > FORCE_TRANSMIT_INTERVAL) { // force a transmission forceTransmit = true; measureCount = 0; From 26d01ab0b643baeefc6996b6efaa05609e713d15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Thu, 14 May 2015 21:12:35 +0200 Subject: [PATCH 15/79] Added GW device to MySensors HW profile (not complete yet!) --- hardware/MySensors/avr/boards.txt | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index 349cf25..2a3c638 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -1,5 +1,8 @@ menu.cpu=Processor +###################################### +## Sensebender Micro + MysensorsMicro.name=Sensebender Micro MysensorsMicro.upload.tool=arduino:avrdude @@ -26,4 +29,29 @@ MysensorsMicro.menu.cpu.8Mhz=Atmega328 8Mhz MysensorsMicro.menu.cpu.8Mhz.build.f_cpu=8000000L MysensorsMicro.menu.cpu.1Mhz=Atmega328 1Mhz -MysensorsMicro.menu.cpu.1Mhz.build.f_cpu=1000000L \ No newline at end of file +MysensorsMicro.menu.cpu.1Mhz.build.f_cpu=1000000L + + +######################################## +## Gateway settings + +MysensorsGW.name=Sensebender Gateway +MysensorsGW.build.core=arduino:arduino +MysensorsGW.build.variant=GW +MysensorsGW.build.board=AVR_1284 +MysensorsGW.build.mcu=atmega1284p +MysensorsGW.build.f_cpu=20000000L + +MysensorsGW.upload.tool=arduino:avrdude +MysensorsGW.upload.protocol=arduino +MysensorsGW.upload.maximum_size=123720 +MysensorsGW.upload.maximum_data_size=16384 +MysensorsGW.upload.speed=115200 + +MysensorsGW.bootloader.tool=arduino:avrdude +MysensorsGW.bootloader.unlock_bits=0x3F +MysensorsGW.bootloader.lock_bits=0x0F +MysensorsGW.bootloader.low_fuses=0xE2 +MysensorsGW.bootloader.high_fuses=0xD2 +MysensorsGW.bootloader.extended_fuses=0xFE +MysensorsGW.bootloader.file=DualOptiboot/optiboot_atmega1284.hex From ecc04269c4ff57f46a3f7f2cf1f5f18d61faeaf4 Mon Sep 17 00:00:00 2001 From: Bruce Lacey Date: Mon, 25 May 2015 12:47:00 -0700 Subject: [PATCH 16/79] Created a small PingPongSensor that demonstrates node-to-node communication and tests communication reliability. --- .../examples/PingPongSensor/MYSLog.h | 44 +++++++++ .../PingPongSensor/PingPongSensor.ino | 99 +++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 libraries/MySensors/examples/PingPongSensor/MYSLog.h create mode 100644 libraries/MySensors/examples/PingPongSensor/PingPongSensor.ino diff --git a/libraries/MySensors/examples/PingPongSensor/MYSLog.h b/libraries/MySensors/examples/PingPongSensor/MYSLog.h new file mode 100644 index 0000000..ce4d37c --- /dev/null +++ b/libraries/MySensors/examples/PingPongSensor/MYSLog.h @@ -0,0 +1,44 @@ +/**** + * Formatted logging to the Serial console. + * Compiled in by setting LOGDEBUG + * + * 2015-05-25 Bruce Lacey V1.0 + * + * Based upon Arduino Playground prior art and should be moved to + * the MySensors library at some point as a common debug logging facility + */ +#ifndef MYSLog_h +#define MYSLog_h + +#define LOGDEBUG 1 + +#if defined ( LOGDEBUG ) + #define LOG(fmt, args... ) log( fmt, ## args ); +#else + #define log(fmt, args... ) +#endif + +void log(const char *fmt, ... ) { + char buff[128]; + va_list args; + va_start (args, fmt); + vsnprintf(buff, sizeof(buff), fmt, args); + va_end (args); + buff[sizeof(buff)/sizeof(buff[0])-1]='\0'; + Serial.print(buff); +} + +void log(const __FlashStringHelper *fmt, ... ){ + char buf[128]; // resulting string limited to 128 chars + va_list args; + va_start (args, fmt); +#ifdef __AVR__ + vsnprintf_P(buf, sizeof(buf), (const char *)fmt, args); // progmem for AVR +#else + vsnprintf(buf, sizeof(buf), (const char *)fmt, args); // for the rest of the world +#endif + va_end(args); + Serial.print(buf); +} + +#endif diff --git a/libraries/MySensors/examples/PingPongSensor/PingPongSensor.ino b/libraries/MySensors/examples/PingPongSensor/PingPongSensor.ino new file mode 100644 index 0000000..25a82e2 --- /dev/null +++ b/libraries/MySensors/examples/PingPongSensor/PingPongSensor.ino @@ -0,0 +1,99 @@ +/*** + * This is a simple sketch used to demenstrate and test node-to-node MySensor's communication. + * To use this sketch, assemble MySensors nodes - they need nothing more than a radio + * 1. Flash each node with the same sketch, open the console and type either 0 or 1 to the respective nodes to set thei ID + * 2. You only need to set the node id once, and restart the nodes + * 3. To being a ping-pong test, simply type T in the console for one of the nodes. + * + * 2015-05-25 Bruce Lacey v1.0 + */ + +#include +#include +#include "MYSLog.h" + +#define VSN "v1.0" + +// Define two generic nodes with a single child +#define YING 200 +#define YANG 201 +#define CHILD 1 + +// Sensor objects +MySensor gw; + +MyMessage mPing(CHILD, V_VAR1); //Ping message +MyMessage mPong(CHILD, V_VAR2); //Pong message + +void setup() { + + Serial.begin(115200); + + gw.begin(incomingMessage); // Node ids are written to EEPROM during sensor node configuration by entering a 0 or 1 + gw.present(CHILD, S_CUSTOM); // + + gw.sendSketchInfo( nodeTypeAsCharRepresentation( gw.getNodeId() ), VSN ); + LOG(F("\n%sReady.\n"), nodeTypeAsCharRepresentation(gw.getNodeId())); +} + +void loop() { + + // Interactive command and control + // Entering a number from 0 or 1 will write the node 200 (YING) or 201 (YANG) to EEPROM + // Entering T on either node will initiatve a ping-pong test. + if (Serial.available()) { + byte inChar = Serial.read(); + uint8_t node = gw.getNodeId(); + + // Manual Test Mode + if (inChar == 'T' || inChar == 't') { + LOG(F("T received - starting test...\n")); + MyMessage msg = mPong; + msg.sender = (node == YING ? YANG : YING); + sendPingOrPongResponse( msg ); + } + else if (inChar == '0' or inChar == '1') { + byte nodeID = 200 + (inChar - '0'); + setNodeId(nodeID); + } + else { + LOG("Invalid input\n"); + } + } + + // Process sensor messages + gw.process(); +} + +void incomingMessage(const MyMessage &message) { + + LOG(F("Received %s from %s\n"), msgTypeAsCharRepresentation((mysensor_data)message.type), nodeTypeAsCharRepresentation(message.sender)); + + delay(250); + sendPingOrPongResponse( message ); +} + +void sendPingOrPongResponse( MyMessage msg ) { + + MyMessage response = (msg.type == V_VAR1 ? mPong : mPing); + + LOG(F("Sending %s to %s\n"), msgTypeAsCharRepresentation( (mysensor_data)response.type ), nodeTypeAsCharRepresentation(msg.sender)); + + // Set payload to current time in millis to ensure each message is unique + response.set( millis() ); + response.setDestination(msg.sender); + gw.send(response); +} + +void setNodeId(byte nodeID) { + LOG(F("Setting node id to: %i.\n***Please restart the node for changes to take effect.\n"), nodeID); + eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, (byte)nodeID); +} + +const char * msgTypeAsCharRepresentation( mysensor_data mType ) { + return mType == V_VAR1 ? "Ping" : "Pong"; +} + +const char * nodeTypeAsCharRepresentation( uint8_t node ) { + return node == YING ? "Ying Node" : "Yang Node"; +} From cad5ca65fdd48e628136e8834a5df19da4d55c77 Mon Sep 17 00:00:00 2001 From: kluszczyn Date: Wed, 27 May 2015 19:33:45 +0200 Subject: [PATCH 17/79] Update PressureSensor.ino Calculate pressure in hPa with decimals (divide by 100.0 insted of 100) --- libraries/MySensors/examples/PressureSensor/PressureSensor.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino index c5743e6..8911e74 100644 --- a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino +++ b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino @@ -44,7 +44,7 @@ void setup() { } void loop() { - float pressure = bmp.readSealevelPressure(205)/100; // 205 meters above sealevel + float pressure = bmp.readSealevelPressure(205)/100.0; // 205 meters above sealevel float temperature = bmp.readTemperature(); if (!metric) { From 1aa3b3ec508d863f0ecdc1db0e14c90caf1b38f0 Mon Sep 17 00:00:00 2001 From: petewill Date: Fri, 5 Jun 2015 14:08:45 -0600 Subject: [PATCH 18/79] Irrigation Controller Jim's (BulldogLowell) irrigation controller code. --- .../IrrigationController.ino | 861 ++++++++++++++++++ 1 file changed, 861 insertions(+) create mode 100644 libraries/MySensors/examples/IrrigationController/IrrigationController.ino diff --git a/libraries/MySensors/examples/IrrigationController/IrrigationController.ino b/libraries/MySensors/examples/IrrigationController/IrrigationController.ino new file mode 100644 index 0000000..9e9ddc6 --- /dev/null +++ b/libraries/MySensors/examples/IrrigationController/IrrigationController.ino @@ -0,0 +1,861 @@ +/* +MySprinkler for MySensors + +Arduino Multi-Zone Sprinkler Control + +May 31, 2015 + +*** Version 2.0 + +*** Upgraded to http://MySensors.org version 1.4.1 +*** Expanded for up to 16 Valves +*** Setup for active low relay board or comment out #define ACTIVE_LOW to switch to active high +*** Switch to bitshift method vs byte arrays +*** Changed RUN_ALL_ZONES Vera device to 0 (was highest valve) +*** Added optional LCD display featuring remaining time, date last ran & current time +*** Features 'raindrop' and 'clock' icons which indicate sensor is updating valve data and clock respectively +*** Added single pushbutton menu to manually select which program to run (All Zones or a Single Zone) +*** Added option of naming your Zones programmatically or with Vera (V_VAR3 used to store names) + +Utilizing your Vera home automation controller and the MySensors.org gateway you can +control up to a sixteen zone irrigation system with only three digital pins. This sketch +will create NUMBER_OF_VALVES + 1 devices on your Vera controller + +This sketch features the following: + +* Allows you to cycle through All zones (RUN_ALL_ZONES) or individual zone (RUN_SINGLE_ZONE) control. +* Use the 0th controller to activate RUN_ALL_ZONES (each zone in numeric sequence 1 to n) + using Variable1 as the "ON" time in minutes in each of the vera devices created. +* Use the individual zone controller to activate a single zone. This feature uses + Variable2 as the "ON" time for each individual device/zone. +* Connect according to pinout below and uses Shift Registers as to allow the MySensors + standard radio configuration and still leave available digital pins +* Turning on any zone will stop the current process and begin that particular process. +* Turning off any zone will stop the current process and turn off all zones. +* To push your new time intervals for your zones, simply change the variable on your Vera and + your arduino will call to Vera once a minute and update accordingly. Variables will also be + requested when the device is first powered on. +* Pushbutton activation to RUN_ALL_ZONES, RUN_SINGLE_ZONE or halt the current program +* LED status indicator + +PARTS LIST: +Available from the MySensors store - http://www.mysensors.org/store/ +* Relays (8 channel) +* Female Pin Header Connector Strip +* Prototype Universal Printed Circuit Boards (PCB) +* NRF24L01 Radio +* Arduino (I used a Pro Mini) +* FTDI USB to TTL Serial Adapter +* Capacitors (10uf and .1uf) +* 3.3v voltage regulator +* Resistors (270 & 10K) +* Female Dupont Cables +* 1602 LCD (with I2C Interface) +* LED +* Push button +* Shift Register (SN74HC595) +* 2 Pole 5mm Pitch PCB Mount Screw Terminal Block +* 3 Pole 5mm Pitch PCB Mount Screw Terminal Block +* 22-24 gauge wire or similar (I used Cat5/Cat6 cable) +* 18 gauge wire (for relay) +* Irrigation Power Supply (24-Volt/750 mA Transformer) + + +INSTRUCTIONS: + +* A step-by-step setup video is available here: http://youtu.be/l4GPRTsuHkI +* After assembling your arduino, radio, decoupling capacitors, shift register(s), status LED, pushbutton LCD (I2C connected to + A4 and A5) and relays, and load the sketch. +* Following the instructions at https://MySensors.org include the device to your MySensors Gateway. +* Verify that each new device has a Variable1, Variable2 and Variable3. Populate data accordingly with whole minutes for + the RUN_ALL_ZONES routine (Variable1) and the RUN_SINGLE_ZONE routines (Variable 2). The values entered for times may be zero and + you may use the defaulet zone names by leaving Variable3 blank. +* Once you have entered values for each zone and each variable, save the settings by pressing the red save button on your Vera. +* Restart your arduino; verify the settings are loaded into your arduino with the serial monitor; the array will be printed + on the serial monitor. +* Your arduino should slow-flash, indicating that it is in ready mode. +* There are multiple debug serial prints that can be monitored to assure that it is operating properly. +* https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours + +Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain +*/ +// +#include +#include +#include +#include +#include +// +#define NUMBER_OF_VALVES 8 // Change this to set your valve count up to 16. +#define VALVE_RESET_TIME 7500UL // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state +#define RADIO_ID AUTO // Change this to fix your Radio ID or use Auto + +#define SKETCH_NAME "MySprinkler" +#define SKETCH_VERSION "2.0" +// +#define CHILD_ID_SPRINKLER 0 +// +#define ACTIVE_LOW // comment out this line if your relays are active high +// +#define DEBUG_ON // comment out to supress serial monitor output +// +#ifdef ACTIVE_LOW +#define BITSHIFT_VALVE_NUMBER ~(1U << (valveNumber-1)) +#define ALL_VALVES_OFF 0xFFFF +#else +#define BITSHIFT_VALVE_NUMBER (1U << (valveNumber-1)) +#define ALL_VALVES_OFF 0U +#endif +// +#ifdef DEBUG_ON +#define DEBUG_PRINT(x) Serial.print(x) +#define DEBUG_PRINTLN(x) Serial.println(x) +#define SERIAL_START(x) Serial.begin(x) +#else +#define DEBUG_PRINT(x) +#define DEBUG_PRINTLN(x) +#define SERIAL_START(x) +#endif +// +typedef enum { + STAND_BY_ALL_OFF, RUN_SINGLE_ZONE, RUN_ALL_ZONES, CYCLE_COMPLETE, ZONE_SELECT_MENU +} +SprinklerStates; +// +SprinklerStates state = STAND_BY_ALL_OFF; +SprinklerStates lastState; +byte menuState = 0; +unsigned long menuTimer; +byte countDownTime = 10; +// +int allZoneTime [NUMBER_OF_VALVES + 1]; +int valveSoloTime [NUMBER_OF_VALVES + 1]; +int valveNumber; +int lastValve; +unsigned long startMillis; +const int ledPin = 5; +const int waterButtonPin = 3; +boolean buttonPushed = false; +boolean showTime = true; +boolean clockUpdating = false; +boolean recentUpdate = true; +const char *dayOfWeek[] = { + "Null", "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday " +}; +// Name your Zones here or use Vera to edit them by adding a name in Variable3... +String valveNickName[17] = { + "All Zones", "Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5", "Zone 6", "Zone 7", "Zone 8", "Zone 9", "Zone 10", "Zone 11", "Zone 12", "Zone 13", "Zone 14", "Zone 15", "Zone 16" +}; +// +time_t lastTimeRun = 0; +//Setup Shift Register... +const int latchPin = 8; +const int clockPin = 4; +const int dataPin = 7; +// +byte clock[8] = {0x0, 0xe, 0x15, 0x17, 0x11, 0xe, 0x0}; // fetching time indicator +byte raindrop[8] = {0x4, 0x4, 0xA, 0xA, 0x11, 0xE, 0x0,}; // fetching Valve Data indicator +// Set the pins on the I2C chip used for LCD connections: +// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol +LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address to 0x27 +MySensor gw; +// +MyMessage msg1valve(CHILD_ID_SPRINKLER, V_LIGHT); +MyMessage var1valve(CHILD_ID_SPRINKLER, V_VAR1); +MyMessage var2valve(CHILD_ID_SPRINKLER, V_VAR2); +// +void setup() +{ + SERIAL_START(115200); + DEBUG_PRINTLN(F("Initialising...")); + pinMode(latchPin, OUTPUT); + pinMode(clockPin, OUTPUT); + pinMode(dataPin, OUTPUT); + pinMode(ledPin, OUTPUT); + pinMode(waterButtonPin, INPUT_PULLUP); + //pinMode(waterButtonPin, INPUT); + attachInterrupt(1, PushButton, RISING); //May need to change for your Arduino model + digitalWrite (ledPin, HIGH); + DEBUG_PRINTLN(F("Turning All Valves Off...")); + updateRelays(ALL_VALVES_OFF); + //delay(5000); + lcd.begin(16, 2); //(16 characters and 2 line display) + lcd.clear(); + lcd.backlight(); + lcd.createChar(0, clock); + lcd.createChar(1, raindrop); + // + //check for saved date in EEPROM + DEBUG_PRINTLN(F("Checking EEPROM for stored date:")); + delay(500); + if (gw.loadState(0) == 0xFF); // EEPROM flag + { + DEBUG_PRINTLN(F("Retreiving last run time from EEPROM...")); + for (int i = 0; i < 4 ; i++) + { + lastTimeRun = lastTimeRun << 8; + lastTimeRun = lastTimeRun | gw.loadState(i + 1); // assemble 4 bytes into an ussigned long epoch timestamp + } + } + gw.begin(getVariables, RADIO_ID, false); // Change 'false' to 'true' to create a Radio repeating node + gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + gw.present(i, S_LIGHT); + } + DEBUG_PRINTLN(F("Sensor Presentation Complete")); + // + digitalWrite (ledPin, LOW); + DEBUG_PRINTLN(F("Ready...")); + // + lcd.setCursor(0, 0); + lcd.print(F(" Syncing Time ")); + lcd.setCursor(15, 0); + lcd.write(byte(0)); + lcd.setCursor(0, 1); + int clockCounter = 0; + while (timeStatus() == timeNotSet && clockCounter < 21) + { + gw.process(); + gw.requestTime(receiveTime); + DEBUG_PRINTLN(F("Requesting time from Gateway:")); + delay(1000); + lcd.print("."); + clockCounter++; + if (clockCounter > 16) + { + DEBUG_PRINTLN(F("Failed initial clock synchronization!")); + lcd.clear(); + lcd.print(F(" Failed Clock ")); + lcd.setCursor(0, 1); + lcd.print(F(" Syncronization ")); + delay(2000); + break; + } + } + // + lcd.clear(); + //Update valve data when first powered on + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + lcd.print(F(" Updating ")); + lcd.setCursor(0, 1); + lcd.print(F(" Valve Data: ")); + lcd.print(i); + boolean flashIcon = false; + DEBUG_PRINT(F("Calling for Valve ")); + DEBUG_PRINT(i); + DEBUG_PRINTLN(F(" Data...")); + while (gw.process() == false) + { + lcd.setCursor(15, 0); + flashIcon = !flashIcon; + flashIcon ? lcd.write(byte(1)) : lcd.print(F(" ")); + gw.request(i, V_VAR1); + delay(100); + } + while (gw.process() == false) + { + lcd.setCursor(15, 0); + flashIcon = !flashIcon; + flashIcon ? lcd.write(byte(1)) : lcd.print(F(" ")); + gw.request(i, V_VAR2); + delay(100); + } + while (gw.process() == false) + { + lcd.setCursor(15, 0); + flashIcon = !flashIcon; + flashIcon ? lcd.write(byte(1)) : lcd.print(F(" ")); + gw.request(i, V_VAR3); + delay(100); + } + } + lcd.clear(); +} +// +void loop() +{ + gw.process(); + updateClock(); + updateDisplay(); + goGetValveTimes(); + // + if (buttonPushed) + { + menuTimer = millis(); + DEBUG_PRINTLN(F("Button Pressed")); + if (state == STAND_BY_ALL_OFF) + { + state = ZONE_SELECT_MENU; + menuState = 0; + } + else if (state == ZONE_SELECT_MENU) + { + menuState++; + if (menuState > NUMBER_OF_VALVES) + { + menuState = 0; + } + } + else + { + state = STAND_BY_ALL_OFF; + } + buttonPushed = false; + } + if (state == STAND_BY_ALL_OFF) + { + slowToggleLED (); + if (state != lastState) + { + updateRelays(ALL_VALVES_OFF); + DEBUG_PRINTLN(F("State Changed... all Zones off")); + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + delay(50); + gw.send(msg1valve.setSensor(i).set(false), false); + } + lcd.clear(); + lcd.setCursor(0,0); + lcd.print(F("** Irrigation **")); + lcd.setCursor(0,1); + lcd.print(F("** Halted **")); + delay(2000); + lastValve = -1; + } + } + // + else if (state == RUN_ALL_ZONES) + { + if (lastValve != valveNumber) + { + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + if (i == 0 || i == valveNumber) + { + gw.send(msg1valve.setSensor(i).set(true), false); + } + else + { + gw.send(msg1valve.setSensor(i).set(false), false); + } + } + } + lastValve = valveNumber; + fastToggleLed(); + if (state != lastState) + { + valveNumber = 1; + updateRelays(ALL_VALVES_OFF); + DEBUG_PRINTLN(F("State Changed, Running All Zones...")); + } + unsigned long nowMillis = millis(); + if (nowMillis - startMillis < VALVE_RESET_TIME) + { + updateRelays(ALL_VALVES_OFF); + } + else if (nowMillis - startMillis < (allZoneTime[valveNumber] * 60000UL)) + { + updateRelays(BITSHIFT_VALVE_NUMBER); + } + else + { + DEBUG_PRINTLN(F("Changing Valves...")); + updateRelays(ALL_VALVES_OFF); + startMillis = millis(); + valveNumber++; + if (valveNumber > NUMBER_OF_VALVES) + { + state = CYCLE_COMPLETE; + startMillis = millis(); + lastValve = -1; + lastTimeRun = now(); + saveDateToEEPROM(lastTimeRun); + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + gw.send(msg1valve.setSensor(i).set(false), false); + } + DEBUG_PRINT(F("State = ")); + DEBUG_PRINTLN(state); + } + } + } + // + else if (state == RUN_SINGLE_ZONE) + { + fastToggleLed(); + if (state != lastState) + { + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + if (i == 0 || i == valveNumber) + { + gw.send(msg1valve.setSensor(i).set(true), false); + } + else + { + gw.send(msg1valve.setSensor(i).set(false), false); + } + } + DEBUG_PRINTLN(F("State Changed, Single Zone Running...")); + DEBUG_PRINT(F("Zone: ")); + DEBUG_PRINTLN(valveNumber); + } + unsigned long nowMillis = millis(); + if (nowMillis - startMillis < VALVE_RESET_TIME) + { + updateRelays(ALL_VALVES_OFF); + } + else if (nowMillis - startMillis < (valveSoloTime [valveNumber] * 60000UL)) + { + updateRelays(BITSHIFT_VALVE_NUMBER); + } + else + { + updateRelays(ALL_VALVES_OFF); + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + gw.send(msg1valve.setSensor(i).set(false), false); + } + state = CYCLE_COMPLETE; + startMillis = millis(); + DEBUG_PRINT(F("State = ")); + DEBUG_PRINTLN(state); + } + lastTimeRun = now(); + } + else if (state == CYCLE_COMPLETE) + { + if (millis() - startMillis < 30000UL) + { + fastToggleLed(); + } + else + { + state = STAND_BY_ALL_OFF; + } + } + else if (state = ZONE_SELECT_MENU) + { + displayMenu(); + } + lastState = state; +} +// +void displayMenu(void) +{ + static byte lastMenuState = -1; + static int lastSecond; + if (menuState != lastMenuState) + { + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print(valveNickName[menuState]); + lcd.setCursor(0, 1); + lcd.print(F("Starting")); + DEBUG_PRINT(valveNickName[menuState]); + Serial.print(F(" Starting Shortly")); + } + int thisSecond = (millis() - menuTimer) / 1000UL; + if (thisSecond != lastSecond && thisSecond < 8) + { + lcd.print(F(".")); + Serial.print("."); + } + lastSecond = thisSecond; + if (millis() - menuTimer > 10000UL) + { + startMillis = millis(); + if (menuState == 0) + { + valveNumber = 1; + state = RUN_ALL_ZONES; + } + else + { + valveNumber = menuState; + state = RUN_SINGLE_ZONE; + } + } + else + { + + } + lastMenuState = menuState; +} +// +void updateRelays(int value) +{ + digitalWrite(latchPin, LOW); + shiftOut(dataPin, clockPin, MSBFIRST, highByte(value)); + shiftOut(dataPin, clockPin, MSBFIRST, lowByte(value)); + digitalWrite(latchPin, HIGH); +} +// +void PushButton() //interrupt with debounce +{ + static unsigned long last_interrupt_time = 0; + unsigned long interrupt_time = millis(); + if (interrupt_time - last_interrupt_time > 200) + { + buttonPushed = true; + } + last_interrupt_time = interrupt_time; +} +// +void fastToggleLed() +{ + static unsigned long fastLedTimer; + if (millis() - fastLedTimer >= 100UL) + { + digitalWrite(ledPin, !digitalRead(ledPin)); + fastLedTimer = millis (); + } +} +// +void slowToggleLED () +{ + static unsigned long slowLedTimer; + if (millis() - slowLedTimer >= 1250UL) + { + digitalWrite(ledPin, !digitalRead(ledPin)); + slowLedTimer = millis (); + } +} +// +void getVariables(const MyMessage &message) +{ + boolean zoneTimeUpdate = false; + if (message.isAck()) + { + DEBUG_PRINTLN(F("This is an ack from gateway")); + } + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + if (message.sensor == i) + { + if (message.type == V_LIGHT) + { + int switchState = atoi(message.data); + if (switchState == 0) + { + state = STAND_BY_ALL_OFF; + DEBUG_PRINTLN(F("Recieved Instruction to Cancel...")); + } + else + { + if (i == 0) + { + state = RUN_ALL_ZONES; + valveNumber = 1; + DEBUG_PRINTLN(F("Recieved Instruction to Run All Zones...")); + } + else + { + state = RUN_SINGLE_ZONE; + valveNumber = i; + DEBUG_PRINT(F("Recieved Instruction to Activate Zone: ")); + DEBUG_PRINTLN(i); + } + } + startMillis = millis(); + } + else if (message.type == V_VAR1) + { + int variable1 = atoi(message.data);// RUN_ALL_ZONES time + DEBUG_PRINT(F("Recieved variable1 valve:")); + DEBUG_PRINT(i); + DEBUG_PRINT(F(" = ")); + DEBUG_PRINTLN(variable1); + if (variable1 != allZoneTime[i]) + { + allZoneTime[i] = variable1; + + zoneTimeUpdate = true; + } + } + else if (message.type == V_VAR2) + { + int variable2 = atoi(message.data);// RUN_SINGLE_ZONE time + DEBUG_PRINT(F("Recieved variable2 valve:")); + DEBUG_PRINT(i); + DEBUG_PRINT(F(" = ")); + DEBUG_PRINTLN(variable2); + if (variable2 != valveSoloTime[i]) + { + valveSoloTime[i] = variable2; + zoneTimeUpdate = true; + } + } + else if (message.type == V_VAR3) + { + String newMessage = String(message.data); + if (newMessage.length() == 0) + { + DEBUG_PRINT(F("No Name Recieved for zone ")); + DEBUG_PRINTLN(i); + break; + } + if (newMessage.length() > 16) + { + newMessage.substring(0, 16); + } + valveNickName[i] = ""; + valveNickName[i] += newMessage; + DEBUG_PRINT(F("Recieved new name for zone ")); + DEBUG_PRINT(i); + DEBUG_PRINT(F(" and it is now called: ")); + DEBUG_PRINTLN(valveNickName[i]); + } + } + } + if (zoneTimeUpdate) + { + // + DEBUG_PRINTLN(F("New Zone Times Recieved...")); + for (byte i = 0; i <= NUMBER_OF_VALVES; i++) + { + if (i != 0) + { + DEBUG_PRINT(F("Zone ")); + DEBUG_PRINT(i); + DEBUG_PRINT(F(" individual time: ")); + DEBUG_PRINT(valveSoloTime[i]); + DEBUG_PRINT(F(" group time: ")); + DEBUG_PRINTLN(allZoneTime[i]); + recentUpdate = true; + } + } + } + else + { + recentUpdate = false; + } +} +// +void updateDisplay() +{ + static unsigned long lastUpdateTime; + static boolean displayToggle = false; + //static byte toggleCounter = 0; + static SprinklerStates lastDisplayState; + if (state != lastDisplayState || millis() - lastUpdateTime >= 3000UL) + { + displayToggle = !displayToggle; + switch (state) { + case STAND_BY_ALL_OFF: + // + fastClear(); + lcd.setCursor(0, 0); + if (displayToggle) + { + lcd.print(F(" System Ready ")); + if (clockUpdating) + { + lcd.setCursor(15, 0); + lcd.write(byte(0)); + } + lcd.setCursor(0, 1); + lcd.print(hourFormat12() < 10 ? F(" ") : F("")); + lcd.print(hourFormat12()); + lcd.print(minute() < 10 ? F(":0") : F(":")); + lcd.print(minute()); + lcd.print(isAM() ? F("am") : F("pm")); + lcd.print(month() < 10 ? F(" 0") : F(" ")); + lcd.print(month()); + lcd.print(day() < 10 ? F("/0") : F("/")); + lcd.print(day()); + lcd.print(F("/")); + lcd.print(year() % 100); + } + else + { + lcd.print(F(" Last Watered ")); + if (clockUpdating) + { + lcd.setCursor(15, 0); + lcd.write(byte(0)); + } + lcd.setCursor(0, 1); + lcd.print(dayOfWeek[weekday(lastTimeRun)]); + lcd.setCursor(11, 1); + lcd.print(month(lastTimeRun) < 10 ? F(" ") : F("")); + lcd.print(month(lastTimeRun)); + lcd.print(day(lastTimeRun) < 10 ? F("/0") : F("/")); + lcd.print(day(lastTimeRun)); + } + break; + case RUN_SINGLE_ZONE: + // + fastClear(); + lcd.setCursor(0, 0); + if (displayToggle) + { + lcd.print(F("Single Zone Mode")); + lcd.setCursor(0, 1); + lcd.print(F(" Zone:")); + if (valveNumber < 10) lcd.print(F("0")); + lcd.print(valveNumber); + lcd.print(F(" Active")); + } + else + { + lcd.print(F(" Time Remaining ")); + lcd.setCursor(0, 1); + if (valveSoloTime[valveNumber] == 0) + { + lcd.print(F(" No Valve Time ")); + } + else + { + unsigned long timeRemaining = (valveSoloTime[valveNumber] * 60) - ((millis() - startMillis) / 1000); + lcd.print(timeRemaining / 60 < 10 ? " 0" : " "); + lcd.print(timeRemaining / 60); + lcd.print("min"); + lcd.print(timeRemaining % 60 < 10 ? " 0" : " "); + lcd.print(timeRemaining % 60); + lcd.print("sec "); + } + } + break; + case RUN_ALL_ZONES: + // + fastClear(); + lcd.setCursor(0, 0); + if (displayToggle) + { + lcd.print(F(" All-Zone Mode ")); + lcd.setCursor(0, 1); + lcd.print(F(" Zone:")); + if (valveNumber < 10) lcd.print(F("0")); + lcd.print(valveNumber); + lcd.print(F(" Active ")); + } + else + { + lcd.print(F(" Time Remaining ")); + lcd.setCursor(0, 1); + int timeRemaining = (allZoneTime[valveNumber] * 60) - ((millis() - startMillis) / 1000); + lcd.print((timeRemaining / 60) < 10 ? " 0" : " "); + lcd.print(timeRemaining / 60); + lcd.print("min"); + lcd.print(timeRemaining % 60 < 10 ? " 0" : " "); + lcd.print(timeRemaining % 60); + lcd.print("sec "); + } + break; + case CYCLE_COMPLETE: + // + if (displayToggle) + { + lcd.setCursor(0, 0); + lcd.print(F(" Watering Cycle ")); + lcd.setCursor(0, 1); + lcd.print(F(" Complete ")); + } + else + { + int totalTimeRan = 0; + for (int i = 1; i < NUMBER_OF_VALVES + 1; i++) + { + totalTimeRan += allZoneTime[i]; + } + lcd.setCursor(0, 0); + lcd.print(F(" Total Time Run ")); + lcd.setCursor(0, 1); + lcd.print(totalTimeRan < 10 ? " 0" : " "); + lcd.print(totalTimeRan); + lcd.print(" Minutes "); + } + } + lastUpdateTime = millis(); + } + lastDisplayState = state; +} +void receiveTime(time_t newTime) +{ + DEBUG_PRINTLN(F("Time value received and updated...")); + int lastSecond = second(); + int lastMinute = minute(); + int lastHour = hour(); + setTime(newTime); + if (((second() != lastSecond) || (minute() != lastMinute) || (hour() != lastHour)) || showTime) + { + DEBUG_PRINTLN(F("Clock updated....")); + DEBUG_PRINT(F("Sensor's time currently set to:")); + DEBUG_PRINT(hourFormat12() < 10 ? F(" 0") : F(" ")); + DEBUG_PRINT(hourFormat12()); + DEBUG_PRINT(minute() < 10 ? F(":0") : F(":")); + DEBUG_PRINT(minute()); + DEBUG_PRINTLN(isAM() ? F("am") : F("pm")); + DEBUG_PRINT(month()); + DEBUG_PRINT(F("/")); + DEBUG_PRINT(day()); + DEBUG_PRINT(F("/")); + DEBUG_PRINTLN(year()); + DEBUG_PRINTLN(dayOfWeek[weekday()]); + showTime = false; + } + else + { + DEBUG_PRINTLN(F("Sensor's time did NOT need adjustment greater than 1 second.")); + } + clockUpdating = false; +} +void fastClear() +{ + lcd.setCursor(0, 0); + lcd.print(F(" ")); + lcd.setCursor(0, 1); + lcd.print(F(" ")); +} +// +void updateClock() +{ + static unsigned long lastVeraGetTime; + if (millis() - lastVeraGetTime >= 3600000UL) // updates clock time and gets zone times from vera once every hour + { + DEBUG_PRINTLN(F("Requesting time and valve data from Gateway...")); + lcd.setCursor(15, 0); + lcd.write(byte(0)); + clockUpdating = true; + gw.requestTime(receiveTime); + lastVeraGetTime = millis(); + } +} +// +void saveDateToEEPROM(unsigned long theDate) +{ + DEBUG_PRINTLN(F("Saving Last Run date")); + if (gw.loadState(0) != 0xFF) + { + gw.saveState(0, 0xFF); // EEPROM flag for last date saved stored in EEPROM (location zero) + } + // + for (int i = 1; i < 5; i++) + { + gw.saveState(5 - i, byte(theDate >> 8 * (i - 1))); // store epoch datestamp in 4 bytes of EEPROM starting in location one + } +} +// +void goGetValveTimes() +{ + static unsigned long valveUpdateTime; + static byte valveIndex = 1; + if (millis() - valveUpdateTime >= 300000UL / NUMBER_OF_VALVES)// update each valve once every 5 mins (distributes the traffic) + { + DEBUG_PRINTLN(F("Calling for Valve Data...")); + lcd.setCursor(15, 0); + lcd.write(byte(1)); //lcd.write(1); + gw.request(valveIndex, V_VAR1); + gw.request(valveIndex, V_VAR2); + gw.request(valveIndex, V_VAR3); + valveUpdateTime = millis(); + valveIndex++; + if (valveIndex > NUMBER_OF_VALVES + 1) + { + valveIndex = 1; + } + } +} From 17848db33db6a5941866814271bb2e30765d5353 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 6 Jun 2015 10:26:04 +0200 Subject: [PATCH 19/79] Fix compile error of LiquidCrystal library in Arduino IDE 1.6.x --- libraries/LiquidCrystal/LCD.cpp | 2 +- libraries/LiquidCrystal/LCD.h | 2 +- .../examples/IrrigationController/IrrigationController.ino | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/libraries/LiquidCrystal/LCD.cpp b/libraries/LiquidCrystal/LCD.cpp index f0e3068..77c0fb3 100644 --- a/libraries/LiquidCrystal/LCD.cpp +++ b/libraries/LiquidCrystal/LCD.cpp @@ -304,7 +304,7 @@ void LCD::createChar(uint8_t location, uint8_t charmap[]) } #ifdef __AVR__ -void LCD::createChar(uint8_t location, const prog_uchar charmap[]) +void LCD::createChar(uint8_t location, const unsigned char charmap[]) { location &= 0x7; // we only have 8 memory locations 0-7 diff --git a/libraries/LiquidCrystal/LCD.h b/libraries/LiquidCrystal/LCD.h index 126b935..1df775b 100644 --- a/libraries/LiquidCrystal/LCD.h +++ b/libraries/LiquidCrystal/LCD.h @@ -418,7 +418,7 @@ public: (0 to 7) @param charmap[in] the bitmap array representing each row of the character. */ - void createChar(uint8_t location, const prog_uchar charmap[]); + void createChar(uint8_t location, const unsigned char charmap[]); #endif // __AVR__ /*! diff --git a/libraries/MySensors/examples/IrrigationController/IrrigationController.ino b/libraries/MySensors/examples/IrrigationController/IrrigationController.ino index 9e9ddc6..bcbff1d 100644 --- a/libraries/MySensors/examples/IrrigationController/IrrigationController.ino +++ b/libraries/MySensors/examples/IrrigationController/IrrigationController.ino @@ -84,7 +84,10 @@ Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (p #include #include #include +#include #include + + // #define NUMBER_OF_VALVES 8 // Change this to set your valve count up to 16. #define VALVE_RESET_TIME 7500UL // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state From 910e310bad26a022b66fa365b841ad10cf836143 Mon Sep 17 00:00:00 2001 From: petewill Date: Sat, 6 Jun 2015 08:51:10 -0600 Subject: [PATCH 20/79] Updated Comments Additional library is no longer needed. Updated comments in code --- .../examples/IrrigationController/IrrigationController.ino | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/IrrigationController/IrrigationController.ino b/libraries/MySensors/examples/IrrigationController/IrrigationController.ino index 9e9ddc6..41e6eb9 100644 --- a/libraries/MySensors/examples/IrrigationController/IrrigationController.ino +++ b/libraries/MySensors/examples/IrrigationController/IrrigationController.ino @@ -75,7 +75,7 @@ INSTRUCTIONS: on the serial monitor. * Your arduino should slow-flash, indicating that it is in ready mode. * There are multiple debug serial prints that can be monitored to assure that it is operating properly. -* https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours +* ***THIS SHOULD NO LONGER BE NEEDED*** The standard MySensors library now works. https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads for the I2C library, or use yours Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (pete.will@mysensors.org) and is released to the public domain */ @@ -84,7 +84,10 @@ Contributed by Jim (BulldogLowell@gmail.com) with much contribution from Pete (p #include #include #include +#include #include + + // #define NUMBER_OF_VALVES 8 // Change this to set your valve count up to 16. #define VALVE_RESET_TIME 7500UL // Change this (in milliseconds) for the time you need your valves to hydraulically reset and change state From 6288c8997ea5fb6a907cf124e9886d66f94ed687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Sun, 7 Jun 2015 20:49:21 +0200 Subject: [PATCH 21/79] Added possibility to add battery voltage measurements as sensor value (to log battery voltages) --- .../SensebenderMicro/SensebenderMicro.ino | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index acc92ba..1cb0c7a 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -3,7 +3,7 @@ // // If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals // -// Battery voltage is repported as child sensorId 199, as well as battery percentage (Internal message) +// Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below) #include @@ -20,6 +20,9 @@ // Define a static node address, remove if you want auto address assignment //#define NODE_ADDRESS 3 +// Uncomment the line below, to transmit battery voltage as a normal sensor value +//#define BATT_SENSOR 199 + #define RELEASE "1.2" #define AVERAGES 2 @@ -54,6 +57,10 @@ MySensor gw; MyMessage msgHum(CHILD_ID_HUM, V_HUM); MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); +#ifdef BATT_SENSOR +MyMessage msgBatt(BATT_SENSOR, V_VOLTAGE); +#endif + // Global settings int measureCount = 0; int sendBattery = 0; @@ -112,6 +119,10 @@ void setup() { gw.present(CHILD_ID_TEMP,S_TEMP); gw.present(CHILD_ID_HUM,S_HUM); +#ifdef BATT_SENSOR + gw.present(BATT_SENSOR, S_POWER); +#endif + isMetric = gw.getConfig().isMetric; Serial.print(F("isMetric: ")); Serial.println(isMetric); raHum.clear(); @@ -171,18 +182,18 @@ void sendTempHumidityMeasurements(bool force) float oldAvgTemp = raTemp.getAverage(); float oldAvgHum = raHum.getAverage(); - raTemp.addValue(data.celsiusHundredths / 100); + raTemp.addValue(data.celsiusHundredths); raHum.addValue(data.humidityPercent); - float diffTemp = abs(oldAvgTemp - raTemp.getAverage()); + float diffTemp = abs(lastTemperature - data.celsiusHundredths/100); float diffHum = abs(oldAvgHum - raHum.getAverage()); - Serial.println(diffTemp); - Serial.println(diffHum); + Serial.print(F("TempDiff :"));Serial.println(diffTemp); + Serial.print(F("HumDiff :"));Serial.println(diffHum); if (isnan(diffTemp)) tx = true; - if (diffTemp > 0.2) tx = true; - if (diffHum > 0.5) tx = true; + if (diffTemp > 0.3) tx = true; + if (diffHum >= 0.5) tx = true; if (tx) { measureCount = 0; @@ -213,6 +224,11 @@ void sendBattLevel(bool force) long vcc = readVcc(); if (vcc != lastBattery) { lastBattery = vcc; + +#ifdef BATT_SENSOR + gw.send(msgBatt.set(vcc)); +#endif + // Calculate percentage vcc = vcc - 1900; // subtract 1.9V from vcc, as this is the lowest voltage we will operate at From 387aaba46e255f033b76d5fe4bc39a9866871e4f Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 8 Jun 2015 21:58:40 +0200 Subject: [PATCH 22/79] Fix error in V/S comments --- libraries/MySensors/MyMessage.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index ac9d4de..471bf49 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -45,7 +45,7 @@ typedef enum { typedef enum { V_TEMP, // S_TEMP V_HUM, // S_HUM - V_LIGHT, // S_LIGHT (Light level in uncalibrated percentage) + V_LIGHT, // S_LIGHT, S_DIMMER V_DIMMER, // S_DIMMER V_PRESSURE, // S_BARO V_FORECAST, // S_BARO @@ -60,13 +60,13 @@ typedef enum { V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER - V_WATT, // S_POWER + V_WATT, // S_POWER, S_LIGHT, S_DIMMER V_KWH, // S_POWER V_SCENE_ON, // S_SCENE_CONTROLLER V_SCENE_OFF, // S_SCENE_CONTROLLER V_HEATER, // S_HEATER V_HEATER_SW, // S_HEATER - V_LIGHT_LEVEL, // S_LIGHT_LEVEL + V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage) V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_UP, // S_COVER V_DOWN, // S_COVER @@ -111,7 +111,7 @@ typedef enum { S_MOTION, // V_TRIPPED, V_ARMED S_SMOKE, // V_TRIPPED, V_ARMED S_LIGHT, // V_LIGHT, V_WATT - S_DIMMER, // V_DIMMER, V_WATT + S_DIMMER, // V_LIGHT, V_DIMMER, V_WATT S_COVER, // V_UP, V_DOWN, V_STOP S_TEMP, // V_TEMP S_HUM, // V_HUM @@ -123,7 +123,7 @@ typedef enum { S_POWER, // V_WATT, V_KWH S_HEATER, // V_HEATER, V_HEATER_SW S_DISTANCE, // V_DISTANCE - S_LIGHT_LEVEL, // V_LIGHT + S_LIGHT_LEVEL, // V_LIGHT_LEVEL S_ARDUINO_NODE, S_ARDUINO_REPEATER_NODE, S_LOCK, // V_LOCK_STATUS From f642ec8bf6bea4545cf181bfba53236da888d212 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:05:45 +0200 Subject: [PATCH 23/79] Added optional description when presenting sensors. --- libraries/MySensors/MySensor.cpp | 4 ++-- libraries/MySensors/MySensor.h | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index cb0e026..184317a 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -483,8 +483,8 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } -void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck) { - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(LIBRARY_VERSION)); +void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char*description) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(description)); } void MySensor::sendSketchInfo(const char *name, const char *version, bool enableAck) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 9917b66..5798ac7 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -178,8 +178,9 @@ class MySensor * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. + * @param description A textual description of the sensor. Defaults to library version. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false); + void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=LIBRARY_VERSION); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From e111d64c3186a2691d8e66d72f7f715c09c8544e Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:47:44 +0200 Subject: [PATCH 24/79] Fix: Default to empty sensor description --- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 184317a..b953fd7 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -484,7 +484,7 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { } void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char*description) { - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(description)); + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } void MySensor::sendSketchInfo(const char *name, const char *version, bool enableAck) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 5798ac7..0c89604 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -180,7 +180,7 @@ class MySensor * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. * @param description A textual description of the sensor. Defaults to library version. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=LIBRARY_VERSION); + void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From b3bdc5213926ee5c2138183457a1e7fe6a9d2601 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:57:04 +0200 Subject: [PATCH 25/79] Added optionl sensor description on presentation --- libraries/MySensors/MySensor.cpp | 4 ++-- libraries/MySensors/MySensor.h | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 1af6a1b..3c18b79 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -235,8 +235,8 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } -void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck) { - sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(LIBRARY_VERSION)); +void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char *description) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } void MySensor::sendSketchInfo(const char *name, const char *version, bool enableAck) { diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 27d4777..35e90b3 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -120,8 +120,9 @@ class MySensor : public RF24 * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. + * @param description A textual description of the sensor. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false); + void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From 52916cb8fe3b0bdddca63f37346bcca1acb214bd Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 9 Jun 2015 23:58:16 +0200 Subject: [PATCH 26/79] Fix comment for presentation --- libraries/MySensors/MySensor.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 0c89604..1cda7d1 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -178,7 +178,7 @@ class MySensor * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. - * @param description A textual description of the sensor. Defaults to library version. + * @param description A textual description of the sensor. */ void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); From b482a8eb7a09fe46f8b58d38fb5944f5d651892a Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 10 Jun 2015 23:43:04 +0200 Subject: [PATCH 27/79] Change argument order for presentation description --- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 3c18b79..47a9b5a 100755 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -235,7 +235,7 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } -void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char *description) { +void MySensor::present(uint8_t childSensorId, uint8_t sensorType, const char *description, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 35e90b3..844e531 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -122,7 +122,7 @@ class MySensor : public RF24 * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. * @param description A textual description of the sensor. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); + void present(uint8_t sensorId, uint8_t sensorType, const char *description="", bool ack=false); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From 51d22c6936707e5f594786c473da0b32789f8bcc Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 10 Jun 2015 23:56:40 +0200 Subject: [PATCH 28/79] Change argument order in presentation --- libraries/MySensors/MySensor.cpp | 2 +- libraries/MySensors/MySensor.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index b953fd7..010cd19 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -483,7 +483,7 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } -void MySensor::present(uint8_t childSensorId, uint8_t sensorType, bool enableAck, const char*description) { +void MySensor::present(uint8_t childSensorId, uint8_t sensorType, const char*description, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 1cda7d1..8842a6f 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -177,10 +177,10 @@ class MySensor * * @param sensorId Select a unique sensor id for this sensor. Choose a number between 0-254. * @param sensorType The sensor type. See sensor typedef in MyMessage.h. - * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. * @param description A textual description of the sensor. + * @param ack Set this to true if you want destination node to send ack back to this node. Default is not to request any ack. */ - void present(uint8_t sensorId, uint8_t sensorType, bool ack=false, const char *description=""); + void present(uint8_t sensorId, uint8_t sensorType, const char *description="", bool ack=false); /** * Sends sketch meta information to the gateway. Not mandatory but a nice thing to do. From 938ade88232b12e364368e6004e2cf4d31008154 Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 14:33:37 +0200 Subject: [PATCH 29/79] Update DallasTemperatureSensor.ino Small code improvements --- .../DallasTemperatureSensor.ino | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 5ac41b4..0c2878b 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -32,8 +32,8 @@ #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) -OneWire oneWire(ONE_WIRE_BUS); -DallasTemperature sensors(&oneWire); +OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature. MySensor gw; float lastTemperature[MAX_ATTACHED_DS18B20]; int numSensors=0; @@ -44,8 +44,8 @@ MyMessage msg(0,V_TEMP); void setup() { - // Startup OneWire - sensors.begin(); + // Startup up the OneWire library + sensors.begin(); // Startup and initialize MySensors library. Set callback for incoming messages. gw.begin(); @@ -78,10 +78,11 @@ void loop() float temperature = static_cast(static_cast((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.; // Only send data if temperature has changed and no error - if (lastTemperature[i] != temperature && temperature != -127.00) { + if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) { // Send in the new temperature gw.send(msg.setSensor(i).set(temperature,1)); + // Save new temperatures for next compare lastTemperature[i]=temperature; } } From 8d7d63dfd9322a91bdf743fef6aeff39f78933cc Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 14:34:43 +0200 Subject: [PATCH 30/79] Update DallasTemperatureSensor.ino --- .../DallasTemperatureSensor/DallasTemperatureSensor.ino | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 0c2878b..05da63e 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -33,7 +33,7 @@ #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) -DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); // Pass the oneWire reference to Dallas Temperature. MySensor gw; float lastTemperature[MAX_ATTACHED_DS18B20]; int numSensors=0; @@ -45,10 +45,10 @@ MyMessage msg(0,V_TEMP); void setup() { // Startup up the OneWire library - sensors.begin(); + sensors.begin(); // Startup and initialize MySensors library. Set callback for incoming messages. - gw.begin(); + gw.begin(); // Send the sketch version information to the gateway and Controller gw.sendSketchInfo("Temperature Sensor", "1.0"); From d90e2d9aac642604f89960845fd4fbca744de72b Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 14:59:37 +0200 Subject: [PATCH 31/79] Update DallasTemperatureSensor.ino Updated version number to 1.1 since minor changes... --- .../DallasTemperatureSensor/DallasTemperatureSensor.ino | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 05da63e..dd74739 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -29,6 +29,8 @@ #include #include +#define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No + #define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected #define MAX_ATTACHED_DS18B20 16 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) @@ -51,7 +53,7 @@ void setup() gw.begin(); // Send the sketch version information to the gateway and Controller - gw.sendSketchInfo("Temperature Sensor", "1.0"); + gw.sendSketchInfo("Temperature Sensor", "1.1"); // Fetch the number of attached temperature sensors numSensors = sensors.getDeviceCount(); @@ -78,7 +80,11 @@ void loop() float temperature = static_cast(static_cast((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.; // Only send data if temperature has changed and no error + #if COMPARE_TEMP == 1 if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) { + #else + if (temperature != -127.00 && temperature != 85.00) { + #endif // Send in the new temperature gw.send(msg.setSensor(i).set(temperature,1)); From ed939e7efd3be3bfad8ac72778da844f5962a165 Mon Sep 17 00:00:00 2001 From: Kolbi Date: Wed, 17 Jun 2015 15:42:50 +0200 Subject: [PATCH 32/79] Update BatteryPoweredSensor.ino Made debugging informations (Serial Print) optionally through setting --- .../examples/BatteryPoweredSensor/BatteryPoweredSensor.ino | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino b/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino index 7dbd93b..40c51da 100644 --- a/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino +++ b/libraries/MySensors/examples/BatteryPoweredSensor/BatteryPoweredSensor.ino @@ -30,6 +30,8 @@ #include #include +#define DEBUG 1 // Debug enables Serial.print 1 = Yes 0 = No + int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point MySensor gw; @@ -50,7 +52,9 @@ void loop() { // get the battery Voltage int sensorValue = analogRead(BATTERY_SENSE_PIN); + #if DEBUG > 0 Serial.println(sensorValue); + #endif // 1M, 470K divider across battery and using internal ADC ref of 1.1V // Sense point is bypassed with 0.1 uF cap to reduce noise at that point @@ -59,6 +63,7 @@ void loop() float batteryV = sensorValue * 0.003363075; int batteryPcnt = sensorValue / 10; + #if DEBUG > 0 Serial.print("Battery Voltage: "); Serial.print(batteryV); Serial.println(" V"); @@ -66,6 +71,7 @@ void loop() Serial.print("Battery percent: "); Serial.print(batteryPcnt); Serial.println(" %"); + #endif if (oldBatteryPcnt != batteryPcnt) { // Power up radio after sleep From 1049246a88bf91484ed44f0be878c2fa379d0600 Mon Sep 17 00:00:00 2001 From: Patrick Fallberg Date: Sat, 20 Jun 2015 13:39:30 +0200 Subject: [PATCH 33/79] Make sure SPI backend is initialized in SPIFlash driver In some cases, SPIFlash driver hangs during initialization because it reads data from the SPI backend. But if SPI backend has not been initialized, this fails. --- libraries/MySensors/utility/SPIFlash.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/MySensors/utility/SPIFlash.cpp b/libraries/MySensors/utility/SPIFlash.cpp index 03d6a1a..ee6e1b0 100644 --- a/libraries/MySensors/utility/SPIFlash.cpp +++ b/libraries/MySensors/utility/SPIFlash.cpp @@ -56,6 +56,7 @@ void SPIFlash::unselect() { /// setup SPI, read device ID etc... boolean SPIFlash::initialize() { + SPI.begin(); _SPCR = SPCR; _SPSR = SPSR; pinMode(_slaveSelectPin, OUTPUT); From 872f694edeb40fb9c37a3d87a96571ff1b320f64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 23 Jun 2015 21:03:37 +0200 Subject: [PATCH 34/79] Updated sensebender Micro sketch, for better transmition handling (implemented thresholds on temperature / humidity measurements) --- .../SensebenderMicro/SensebenderMicro.ino | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 1cb0c7a..74b5d94 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -40,6 +40,11 @@ // When MEASURE_INTERVAL is 60000 and FORCE_TRANSMIT_INTERVAL is 30, we force a transmission every 30 minutes. // Between the forced transmissions a tranmission will only occur if the measured value differs from the previous measurement +// HUMI_TRANSMIT_THRESHOLD tells how much the humidity should have changed since last time it was transmitted. Likewise with +// TEMP_TRANSMIT_THRESHOLD for temperature threshold. +#define HUMI_TRANSMIT_THRESHOLD 0.5 +#define TEMP_TRANSMIT_THRESHOLD 0.5 + // Pin definitions #define TEST_PIN A0 #define LED_PIN A2 @@ -73,7 +78,6 @@ int lastHumidity = -100; long lastBattery = -100; RunningAverage raHum(AVERAGES); -RunningAverage raTemp(AVERAGES); /**************************************************** * @@ -109,6 +113,20 @@ void setup() { gw.begin(NULL,AUTO,false); #endif +// --- following code will heat up the sensor element, and wait until the temperature is +// within 0.3 degrees celcius of the initial temperature (measured at startup). +// This is to try and burn away residue humidity from manufacturing process. + int temperature = humiditySensor.getCelsiusHundredths(); + + humiditySensor.setHeater(true); + delay(500); + humiditySensor.setHeater(false); + + int t = 0; + do { + t = humiditySensor.getCelsiusHundredths() - temperature; + } while (abs(t) >30); +// --- digitalWrite(LED_PIN, LOW); humiditySensor.begin(); @@ -123,10 +141,10 @@ void setup() { gw.present(BATT_SENSOR, S_POWER); #endif + isMetric = gw.getConfig().isMetric; Serial.print(F("isMetric: ")); Serial.println(isMetric); raHum.clear(); - raTemp.clear(); sendTempHumidityMeasurements(false); sendBattLevel(false); } @@ -179,10 +197,8 @@ void sendTempHumidityMeasurements(bool force) bool tx = force; si7021_env data = humiditySensor.getHumidityAndTemperature(); - float oldAvgTemp = raTemp.getAverage(); float oldAvgHum = raHum.getAverage(); - raTemp.addValue(data.celsiusHundredths); raHum.addValue(data.humidityPercent); float diffTemp = abs(lastTemperature - data.celsiusHundredths/100); @@ -192,8 +208,8 @@ void sendTempHumidityMeasurements(bool force) Serial.print(F("HumDiff :"));Serial.println(diffHum); if (isnan(diffTemp)) tx = true; - if (diffTemp > 0.3) tx = true; - if (diffHum >= 0.5) tx = true; + if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true; + if (diffHum >= HUMI_TRANSMIT_THRESHOLD) tx = true; if (tx) { measureCount = 0; From f47ef2c248a20551eadf830141f2413fe267372f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 23 Jun 2015 22:03:56 +0200 Subject: [PATCH 35/79] Corrected a celcius/fahrenheit conversion, for the code that determines if it should transmit --- .../MySensors/examples/SensebenderMicro/SensebenderMicro.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 74b5d94..72467ab 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -201,13 +201,13 @@ void sendTempHumidityMeasurements(bool force) raHum.addValue(data.humidityPercent); - float diffTemp = abs(lastTemperature - data.celsiusHundredths/100); + float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100); float diffHum = abs(oldAvgHum - raHum.getAverage()); Serial.print(F("TempDiff :"));Serial.println(diffTemp); Serial.print(F("HumDiff :"));Serial.println(diffHum); - if (isnan(diffTemp)) tx = true; + if (isnan(diffHum)) tx = true; if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true; if (diffHum >= HUMI_TRANSMIT_THRESHOLD) tx = true; From e23baf9d5d16c1620aedbec266a9ef28accd72d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 23 Jun 2015 23:20:03 +0200 Subject: [PATCH 36/79] Removed "sensor conditioning code" as it made one of my sensors go haywire, so not the right thing to try and heat the sensor momentarily.. --- .../SensebenderMicro/SensebenderMicro.ino | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 72467ab..1dc3e77 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -113,23 +113,10 @@ void setup() { gw.begin(NULL,AUTO,false); #endif -// --- following code will heat up the sensor element, and wait until the temperature is -// within 0.3 degrees celcius of the initial temperature (measured at startup). -// This is to try and burn away residue humidity from manufacturing process. - int temperature = humiditySensor.getCelsiusHundredths(); - - humiditySensor.setHeater(true); - delay(500); - humiditySensor.setHeater(false); - - int t = 0; - do { - t = humiditySensor.getCelsiusHundredths() - temperature; - } while (abs(t) >30); -// --- + humiditySensor.begin(); + digitalWrite(LED_PIN, LOW); - humiditySensor.begin(); Serial.flush(); Serial.println(F(" - Online!")); gw.sendSketchInfo("Sensebender Micro", RELEASE); From 49370b67c6b9a817cbed0a3ebd74640f723245b3 Mon Sep 17 00:00:00 2001 From: petewill Date: Fri, 26 Jun 2015 07:19:35 -0600 Subject: [PATCH 37/79] Remove unnecessary define LIGHT_SENSOR_ANALOG_PIN is not used in the code. --- libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino index 441c65e..b3e4f49 100644 --- a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino +++ b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino @@ -22,7 +22,6 @@ #include #define CHILD_ID_LIGHT 0 -#define LIGHT_SENSOR_ANALOG_PIN 0 unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) BH1750 lightSensor; From 0300df686ec15ea09e6fa70ada36263fb62283f1 Mon Sep 17 00:00:00 2001 From: Robo Print Date: Sat, 27 Jun 2015 22:50:24 +0200 Subject: [PATCH 38/79] Updated versions of DallasTemperature and OneWire libraries --- .../DallasTemperature/DallasTemperature.cpp | 874 ++++++++++-------- .../DallasTemperature/DallasTemperature.h | 112 ++- .../DallasTemperature/{README => README.md} | 27 +- libraries/DallasTemperature/change.txt | 85 ++ .../examples/Alarm/Alarm.pde | 2 +- .../examples/AlarmHandler/AlarmHandler.pde | 3 +- .../examples/Multiple/Multiple.pde | 6 +- .../examples/Single/Single.pde | 2 +- .../examples/Tester/Tester.pde | 6 +- .../WaitForConversion/WaitForConversion.pde | 66 ++ .../WaitForConversion2/WaitForConversion2.pde | 80 ++ libraries/DallasTemperature/keywords.txt | 15 +- libraries/DallasTemperature/library.json | 39 + libraries/OneWire/OneWire.cpp | 64 +- libraries/OneWire/OneWire.h | 55 +- .../DS18x20_Temperature.pde | 25 +- 16 files changed, 1001 insertions(+), 460 deletions(-) rename libraries/DallasTemperature/{README => README.md} (84%) create mode 100644 libraries/DallasTemperature/change.txt create mode 100644 libraries/DallasTemperature/examples/WaitForConversion/WaitForConversion.pde create mode 100644 libraries/DallasTemperature/examples/WaitForConversion2/WaitForConversion2.pde create mode 100644 libraries/DallasTemperature/library.json diff --git a/libraries/DallasTemperature/DallasTemperature.cpp b/libraries/DallasTemperature/DallasTemperature.cpp index ea5b1e5..8cf7515 100644 --- a/libraries/DallasTemperature/DallasTemperature.cpp +++ b/libraries/DallasTemperature/DallasTemperature.cpp @@ -3,369 +3,491 @@ // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. +// Version 3.7.2 modified on Dec 6, 2011 to support Arduino 1.0 +// See Includes... +// Modified by Jordan Hochenbaum + #include "DallasTemperature.h" +#if ARDUINO >= 100 +#include "Arduino.h" +#else extern "C" { - #include "Arduino.h" +#include "WConstants.h" } +#endif DallasTemperature::DallasTemperature(OneWire* _oneWire) - #if REQUIRESALARMS - : _AlarmHandler(&defaultAlarmHandler) - #endif +#if REQUIRESALARMS + : _AlarmHandler(&defaultAlarmHandler) +#endif { - _wire = _oneWire; - devices = 0; - parasite = false; - conversionDelay = TEMP_9_BIT; + _wire = _oneWire; + devices = 0; + parasite = false; + bitResolution = 9; + waitForConversion = true; + checkForConversion = true; } -// initialize the bus +// initialise the bus void DallasTemperature::begin(void) { - DeviceAddress deviceAddress; + DeviceAddress deviceAddress; - _wire->reset_search(); - devices = 0; // Reset the number of devices when we enumerate wire devices + _wire->reset_search(); + devices = 0; // Reset the number of devices when we enumerate wire devices - while (_wire->search(deviceAddress)) - { - if (validAddress(deviceAddress)) + while (_wire->search(deviceAddress)) { - if (!parasite && readPowerSupply(deviceAddress)) parasite = true; + if (validAddress(deviceAddress)) + { + if (!parasite && readPowerSupply(deviceAddress)) parasite = true; - ScratchPad scratchPad; + ScratchPad scratchPad; - readScratchPad(deviceAddress, scratchPad); + readScratchPad(deviceAddress, scratchPad); - if (deviceAddress[0] == DS18S20MODEL) conversionDelay = TEMP_12_BIT; // 750 ms - else if (scratchPad[CONFIGURATION] > conversionDelay) conversionDelay = scratchPad[CONFIGURATION]; + bitResolution = max(bitResolution, getResolution(deviceAddress)); - devices++; + devices++; + } } - } } // returns the number of devices found on the bus uint8_t DallasTemperature::getDeviceCount(void) { - return devices; + return devices; } // returns true if address is valid -bool DallasTemperature::validAddress(uint8_t* deviceAddress) +bool DallasTemperature::validAddress(const uint8_t* deviceAddress) { - return (_wire->crc8(deviceAddress, 7) == deviceAddress[7]); + return (_wire->crc8(deviceAddress, 7) == deviceAddress[7]); } // finds an address at a given index on the bus // returns true if the device was found bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index) { - uint8_t depth = 0; + uint8_t depth = 0; - _wire->reset_search(); + _wire->reset_search(); - while (depth <= index && _wire->search(deviceAddress)) - { - if (depth == index && validAddress(deviceAddress)) return true; - depth++; - } + while (depth <= index && _wire->search(deviceAddress)) + { + if (depth == index && validAddress(deviceAddress)) return true; + depth++; + } - return false; + return false; } // attempt to determine if the device at the given address is connected to the bus -bool DallasTemperature::isConnected(uint8_t* deviceAddress) +bool DallasTemperature::isConnected(const uint8_t* deviceAddress) { - ScratchPad scratchPad; - return isConnected(deviceAddress, scratchPad); + ScratchPad scratchPad; + return isConnected(deviceAddress, scratchPad); } // attempt to determine if the device at the given address is connected to the bus // also allows for updating the read scratchpad -bool DallasTemperature::isConnected(uint8_t* deviceAddress, uint8_t* scratchPad) +bool DallasTemperature::isConnected(const uint8_t* deviceAddress, uint8_t* scratchPad) { - readScratchPad(deviceAddress, scratchPad); - return (_wire->crc8(scratchPad, 8) == scratchPad[SCRATCHPAD_CRC]); + readScratchPad(deviceAddress, scratchPad); + return (_wire->crc8(scratchPad, 8) == scratchPad[SCRATCHPAD_CRC]); } // read device's scratch pad -void DallasTemperature::readScratchPad(uint8_t* deviceAddress, uint8_t* scratchPad) +void DallasTemperature::readScratchPad(const uint8_t* deviceAddress, uint8_t* scratchPad) { - // send the command - _wire->reset(); - _wire->select(deviceAddress); - _wire->write(READSCRATCH); + // send the command + _wire->reset(); + _wire->select(deviceAddress); + _wire->write(READSCRATCH); - // read the response + // TODO => collect all comments & use simple loop + // byte 0: temperature LSB + // byte 1: temperature MSB + // byte 2: high alarm temp + // byte 3: low alarm temp + // byte 4: DS18S20: store for crc + // DS18B20 & DS1822: configuration register + // byte 5: internal use & crc + // byte 6: DS18S20: COUNT_REMAIN + // DS18B20 & DS1822: store for crc + // byte 7: DS18S20: COUNT_PER_C + // DS18B20 & DS1822: store for crc + // byte 8: SCRATCHPAD_CRC + // + // for(int i=0; i<9; i++) + // { + // scratchPad[i] = _wire->read(); + // } - // byte 0: temperature LSB - scratchPad[TEMP_LSB] = _wire->read(); - // byte 1: temperature MSB - scratchPad[TEMP_MSB] = _wire->read(); + // read the response - // byte 2: high alarm temp - scratchPad[HIGH_ALARM_TEMP] = _wire->read(); + // byte 0: temperature LSB + scratchPad[TEMP_LSB] = _wire->read(); - // byte 3: low alarm temp - scratchPad[LOW_ALARM_TEMP] = _wire->read(); + // byte 1: temperature MSB + scratchPad[TEMP_MSB] = _wire->read(); - // byte 4: - // DS18S20: store for crc - // DS18B20 & DS1822: configuration register - scratchPad[CONFIGURATION] = _wire->read(); + // byte 2: high alarm temp + scratchPad[HIGH_ALARM_TEMP] = _wire->read(); - // byte 5: - // internal use & crc - scratchPad[INTERNAL_BYTE] = _wire->read(); + // byte 3: low alarm temp + scratchPad[LOW_ALARM_TEMP] = _wire->read(); - // byte 6: - // DS18S20: COUNT_REMAIN - // DS18B20 & DS1822: store for crc - scratchPad[COUNT_REMAIN] = _wire->read(); + // byte 4: + // DS18S20: store for crc + // DS18B20 & DS1822: configuration register + scratchPad[CONFIGURATION] = _wire->read(); - // byte 7: - // DS18S20: COUNT_PER_C - // DS18B20 & DS1822: store for crc - scratchPad[COUNT_PER_C] = _wire->read(); + // byte 5: + // internal use & crc + scratchPad[INTERNAL_BYTE] = _wire->read(); - // byte 8: - // SCTRACHPAD_CRC - scratchPad[SCRATCHPAD_CRC] = _wire->read(); + // byte 6: + // DS18S20: COUNT_REMAIN + // DS18B20 & DS1822: store for crc + scratchPad[COUNT_REMAIN] = _wire->read(); - _wire->reset(); + // byte 7: + // DS18S20: COUNT_PER_C + // DS18B20 & DS1822: store for crc + scratchPad[COUNT_PER_C] = _wire->read(); + + // byte 8: + // SCTRACHPAD_CRC + scratchPad[SCRATCHPAD_CRC] = _wire->read(); + + _wire->reset(); } // writes device's scratch pad -void DallasTemperature::writeScratchPad(uint8_t* deviceAddress, const uint8_t* scratchPad) +void DallasTemperature::writeScratchPad(const uint8_t* deviceAddress, const uint8_t* scratchPad) { - _wire->reset(); - _wire->select(deviceAddress); - _wire->write(WRITESCRATCH); - _wire->write(scratchPad[HIGH_ALARM_TEMP]); // high alarm temp - _wire->write(scratchPad[LOW_ALARM_TEMP]); // low alarm temp - // DS18S20 does not use the configuration register - if (deviceAddress[0] != DS18S20MODEL) _wire->write(scratchPad[CONFIGURATION]); // configuration - _wire->reset(); - // save the newly written values to eeprom - _wire->write(COPYSCRATCH, parasite); - if (parasite) delay(10); // 10ms delay - _wire->reset(); + _wire->reset(); + _wire->select(deviceAddress); + _wire->write(WRITESCRATCH); + _wire->write(scratchPad[HIGH_ALARM_TEMP]); // high alarm temp + _wire->write(scratchPad[LOW_ALARM_TEMP]); // low alarm temp + // DS1820 and DS18S20 have no configuration register + if (deviceAddress[0] != DS18S20MODEL) _wire->write(scratchPad[CONFIGURATION]); // configuration + _wire->reset(); + _wire->select(deviceAddress); //<--this line was missing + // save the newly written values to eeprom + _wire->write(COPYSCRATCH, parasite); + delay(20); // <--- added 20ms delay to allow 10ms long EEPROM write operation (as specified by datasheet) + if (parasite) delay(10); // 10ms delay + _wire->reset(); } // reads the device's power requirements -bool DallasTemperature::readPowerSupply(uint8_t* deviceAddress) +bool DallasTemperature::readPowerSupply(const uint8_t* deviceAddress) { - bool ret = false; - _wire->reset(); - _wire->select(deviceAddress); - _wire->write(READPOWERSUPPLY); - if (_wire->read_bit() == 0) ret = true; - _wire->reset(); - return ret; + bool ret = false; + _wire->reset(); + _wire->select(deviceAddress); + _wire->write(READPOWERSUPPLY); + if (_wire->read_bit() == 0) ret = true; + _wire->reset(); + return ret; } -// returns the current resolution, 9-12 -uint8_t DallasTemperature::getResolution(uint8_t* deviceAddress) -{ - if (deviceAddress[0] == DS18S20MODEL) return 9; // this model has a fixed resolution - ScratchPad scratchPad; - readScratchPad(deviceAddress, scratchPad); - switch (scratchPad[CONFIGURATION]) - { - case TEMP_12_BIT: - return 12; - break; - case TEMP_11_BIT: - return 11; - break; - case TEMP_10_BIT: - return 10; - break; - case TEMP_9_BIT: - return 9; - break; - } +// set resolution of all devices to 9, 10, 11, or 12 bits +// if new resolution is out of range, it is constrained. +void DallasTemperature::setResolution(uint8_t newResolution) +{ + bitResolution = constrain(newResolution, 9, 12); + DeviceAddress deviceAddress; + for (int i=0; ireset(); - _wire->skip(); - _wire->write(STARTCONVO, parasite); + return bitResolution; +} - switch (conversionDelay) - { - case TEMP_9_BIT: - delay(94); - break; - case TEMP_10_BIT: - delay(188); - break; - case TEMP_11_BIT: - delay(375); - break; - case TEMP_12_BIT: - default: - delay(750); - break; - } +// returns the current resolution of the device, 9-12 +// returns 0 if device not found +uint8_t DallasTemperature::getResolution(const uint8_t* deviceAddress) +{ + // DS1820 and DS18S20 have no resolution configuration register + if (deviceAddress[0] == DS18S20MODEL) return 12; + + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + { + switch (scratchPad[CONFIGURATION]) + { + case TEMP_12_BIT: + return 12; + + case TEMP_11_BIT: + return 11; + + case TEMP_10_BIT: + return 10; + + case TEMP_9_BIT: + return 9; + } + } + return 0; +} + + +// sets the value of the waitForConversion flag +// TRUE : function requestTemperature() etc returns when conversion is ready +// FALSE: function requestTemperature() etc returns immediately (USE WITH CARE!!) +// (1) programmer has to check if the needed delay has passed +// (2) but the application can do meaningful things in that time +void DallasTemperature::setWaitForConversion(bool flag) +{ + waitForConversion = flag; +} + +// gets the value of the waitForConversion flag +bool DallasTemperature::getWaitForConversion() +{ + return waitForConversion; +} + + +// sets the value of the checkForConversion flag +// TRUE : function requestTemperature() etc will 'listen' to an IC to determine whether a conversion is complete +// FALSE: function requestTemperature() etc will wait a set time (worst case scenario) for a conversion to complete +void DallasTemperature::setCheckForConversion(bool flag) +{ + checkForConversion = flag; +} + +// gets the value of the waitForConversion flag +bool DallasTemperature::getCheckForConversion() +{ + return checkForConversion; +} + +bool DallasTemperature::isConversionAvailable(const uint8_t* deviceAddress) +{ + // Check if the clock has been raised indicating the conversion is complete + ScratchPad scratchPad; + readScratchPad(deviceAddress, scratchPad); + return scratchPad[0]; +} + + +// sends command for all devices on the bus to perform a temperature conversion +void DallasTemperature::requestTemperatures() +{ + _wire->reset(); + _wire->skip(); + _wire->write(STARTCONVO, parasite); + + // ASYNC mode? + if (!waitForConversion) return; + blockTillConversionComplete(bitResolution, NULL); } // sends command for one device to perform a temperature by address -void DallasTemperature::requestTemperaturesByAddress(uint8_t* deviceAddress) +// returns FALSE if device is disconnected +// returns TRUE otherwise +bool DallasTemperature::requestTemperaturesByAddress(const uint8_t* deviceAddress) { - _wire->reset(); - _wire->select(deviceAddress); - _wire->write(STARTCONVO, parasite); + _wire->reset(); + _wire->select(deviceAddress); + _wire->write(STARTCONVO, parasite); - switch (conversionDelay) - { - case TEMP_9_BIT: - delay(94); - break; - case TEMP_10_BIT: - delay(188); - break; - case TEMP_11_BIT: - delay(375); - break; - case TEMP_12_BIT: + // check device + ScratchPad scratchPad; + if (!isConnected(deviceAddress, scratchPad)) return false; + + // ASYNC mode? + if (!waitForConversion) return true; + blockTillConversionComplete(getResolution(deviceAddress), deviceAddress); + + return true; +} + +// returns number of milliseconds to wait till conversion is complete (based on IC datasheet) +int16_t DallasTemperature::millisToWaitForConversion(uint8_t bitResolution) +{ + switch (bitResolution) + { + case 9: + return 94; + case 10: + return 188; + case 11: + return 375; default: - delay(750); - break; - } + return 750; + } +} + +// Continue to check if the IC has responded with a temperature +void DallasTemperature::blockTillConversionComplete(uint8_t bitResolution, const uint8_t* deviceAddress) +{ + int delms = millisToWaitForConversion(bitResolution); + if (deviceAddress != NULL && checkForConversion && !parasite) + { + unsigned long timend = millis() + delms; + while(!isConversionAvailable(deviceAddress) && (millis() < timend)); + } + else + { + delay(delms); + } } // sends command for one device to perform a temp conversion by index -void DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex) +bool DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex) { - DeviceAddress deviceAddress; - getAddress(deviceAddress, deviceIndex); - requestTemperaturesByAddress(deviceAddress); + DeviceAddress deviceAddress; + getAddress(deviceAddress, deviceIndex); + return requestTemperaturesByAddress(deviceAddress); } - // Fetch temperature for device index float DallasTemperature::getTempCByIndex(uint8_t deviceIndex) { - DeviceAddress deviceAddress; - getAddress(deviceAddress, deviceIndex); - return getTempC((uint8_t*)deviceAddress); + DeviceAddress deviceAddress; + if (!getAddress(deviceAddress, deviceIndex)) + return DEVICE_DISCONNECTED_C; + return getTempC((uint8_t*)deviceAddress); } // Fetch temperature for device index float DallasTemperature::getTempFByIndex(uint8_t deviceIndex) { - return DallasTemperature::toFahrenheit(getTempCByIndex(deviceIndex)); + DeviceAddress deviceAddress; + if (!getAddress(deviceAddress, deviceIndex)) + return DEVICE_DISCONNECTED_F; + return getTempF((uint8_t*)deviceAddress); } -// reads scratchpad and returns the temperature in degrees C -float DallasTemperature::calculateTemperature(uint8_t* deviceAddress, uint8_t* scratchPad) +// reads scratchpad and returns fixed-point temperature, scaling factor 2^-7 +int16_t DallasTemperature::calculateTemperature(const uint8_t* deviceAddress, uint8_t* scratchPad) { - int16_t rawTemperature = (((int16_t)scratchPad[TEMP_MSB]) << 8) | scratchPad[TEMP_LSB]; + int16_t fpTemperature = + (((int16_t) scratchPad[TEMP_MSB]) << 11) | + (((int16_t) scratchPad[TEMP_LSB]) << 3); - switch (deviceAddress[0]) - { - case DS18B20MODEL: - case DS1822MODEL: - switch (scratchPad[CONFIGURATION]) - { - case TEMP_12_BIT: - return (float)rawTemperature * 0.0625; - break; - case TEMP_11_BIT: - return (float)(rawTemperature >> 1) * 0.125; - break; - case TEMP_10_BIT: - return (float)(rawTemperature >> 2) * 0.25; - break; - case TEMP_9_BIT: - return (float)(rawTemperature >> 3) * 0.5; - break; - } - break; - case DS18S20MODEL: - /* + /* + DS1820 and DS18S20 have a 9-bit temperature register. - Resolutions greater than 9 bits can be calculated using the data from - the temperature, COUNT REMAIN and COUNT PER °C registers in the - scratchpad. Note that the COUNT PER °C register is hard-wired to 16 - (10h). After reading the scratchpad, the TEMP_READ value is obtained - by truncating the 0.5°C bit (bit 0) from the temperature data. The - extended resolution temperature can then be calculated using the - following equation: + Resolutions greater than 9-bit can be calculated using the data from + the temperature, and COUNT REMAIN and COUNT PER °C registers in the + scratchpad. The resolution of the calculation depends on the model. - COUNT_PER_C - COUNT_REMAIN - TEMPERATURE = TEMP_READ - 0.25 + -------------------------- - COUNT_PER_C - */ + While the COUNT PER °C register is hard-wired to 16 (10h) in a + DS18S20, it changes with temperature in DS1820. - // Good spot. Thanks Nic Johns for your contribution - return (float)(rawTemperature >> 1) - 0.25 +((float)(scratchPad[COUNT_PER_C] - scratchPad[COUNT_REMAIN]) / (float)scratchPad[COUNT_PER_C] ); - break; - } + After reading the scratchpad, the TEMP_READ value is obtained by + truncating the 0.5°C bit (bit 0) from the temperature data. The + extended resolution temperature can then be calculated using the + following equation: + + COUNT_PER_C - COUNT_REMAIN + TEMPERATURE = TEMP_READ - 0.25 + -------------------------- + COUNT_PER_C + + Hagai Shatz simplified this to integer arithmetic for a 12 bits + value for a DS18S20, and James Cameron added legacy DS1820 support. + + See - http://myarduinotoy.blogspot.co.uk/2013/02/12bit-result-from-ds18s20.html + */ + + if (deviceAddress[0] == DS18S20MODEL) + fpTemperature = ((fpTemperature & 0xfff0) << 3) - 16 + + ( + ((scratchPad[COUNT_PER_C] - scratchPad[COUNT_REMAIN]) << 7) / + scratchPad[COUNT_PER_C] + ); + + return fpTemperature; } -// returns temperature in degrees C or DEVICE_DISCONNECTED if the + +// returns temperature in 1/128 degrees C or DEVICE_DISCONNECTED_RAW if the // device's scratch pad cannot be read successfully. -// the numeric value of DEVICE_DISCONNECTED is defined in -// DallasTemperature.h. it is a large negative number outside the +// the numeric value of DEVICE_DISCONNECTED_RAW is defined in +// DallasTemperature.h. It is a large negative number outside the // operating range of the device -float DallasTemperature::getTempC(uint8_t* deviceAddress) +int16_t DallasTemperature::getTemp(const uint8_t* deviceAddress) { - // TODO: Multiple devices (up to 64) on the same bus may take some time to negotiate a response - // What happens in case of collision? - - ScratchPad scratchPad; - if (isConnected(deviceAddress, scratchPad)) return calculateTemperature(deviceAddress, scratchPad); - return DEVICE_DISCONNECTED; + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) return calculateTemperature(deviceAddress, scratchPad); + return DEVICE_DISCONNECTED_RAW; } -// returns temperature in degrees F -float DallasTemperature::getTempF(uint8_t* deviceAddress) +// returns temperature in degrees C or DEVICE_DISCONNECTED_C if the +// device's scratch pad cannot be read successfully. +// the numeric value of DEVICE_DISCONNECTED_C is defined in +// DallasTemperature.h. It is a large negative number outside the +// operating range of the device +float DallasTemperature::getTempC(const uint8_t* deviceAddress) { - return toFahrenheit(getTempC(deviceAddress)); + return rawToCelsius(getTemp(deviceAddress)); +} + +// returns temperature in degrees F or DEVICE_DISCONNECTED_F if the +// device's scratch pad cannot be read successfully. +// the numeric value of DEVICE_DISCONNECTED_F is defined in +// DallasTemperature.h. It is a large negative number outside the +// operating range of the device +float DallasTemperature::getTempF(const uint8_t* deviceAddress) +{ + return rawToFahrenheit(getTemp(deviceAddress)); } // returns true if the bus requires parasite power bool DallasTemperature::isParasitePowerMode(void) { - return parasite; + return parasite; } #if REQUIRESALARMS @@ -390,65 +512,65 @@ the next temperature conversion. */ -// sets the high alarm temperature for a device in degrees celsius +// sets the high alarm temperature for a device in degrees Celsius // accepts a float, but the alarm resolution will ignore anything // after a decimal point. valid range is -55C - 125C -void DallasTemperature::setHighAlarmTemp(uint8_t* deviceAddress, char celsius) +void DallasTemperature::setHighAlarmTemp(const uint8_t* deviceAddress, char celsius) { - // make sure the alarm temperature is within the device's range - if (celsius > 125) celsius = 125; - else if (celsius < -55) celsius = -55; + // make sure the alarm temperature is within the device's range + if (celsius > 125) celsius = 125; + else if (celsius < -55) celsius = -55; - ScratchPad scratchPad; - if (isConnected(deviceAddress, scratchPad)) - { - scratchPad[HIGH_ALARM_TEMP] = (uint8_t)celsius; - writeScratchPad(deviceAddress, scratchPad); - } + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + { + scratchPad[HIGH_ALARM_TEMP] = (uint8_t)celsius; + writeScratchPad(deviceAddress, scratchPad); + } } -// sets the low alarm temperature for a device in degreed celsius +// sets the low alarm temperature for a device in degrees Celsius // accepts a float, but the alarm resolution will ignore anything // after a decimal point. valid range is -55C - 125C -void DallasTemperature::setLowAlarmTemp(uint8_t* deviceAddress, char celsius) +void DallasTemperature::setLowAlarmTemp(const uint8_t* deviceAddress, char celsius) { - // make sure the alarm temperature is within the device's range - if (celsius > 125) celsius = 125; - else if (celsius < -55) celsius = -55; + // make sure the alarm temperature is within the device's range + if (celsius > 125) celsius = 125; + else if (celsius < -55) celsius = -55; - ScratchPad scratchPad; - if (isConnected(deviceAddress, scratchPad)) - { - scratchPad[LOW_ALARM_TEMP] = (uint8_t)celsius; - writeScratchPad(deviceAddress, scratchPad); - } + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + { + scratchPad[LOW_ALARM_TEMP] = (uint8_t)celsius; + writeScratchPad(deviceAddress, scratchPad); + } } // returns a char with the current high alarm temperature or // DEVICE_DISCONNECTED for an address -char DallasTemperature::getHighAlarmTemp(uint8_t* deviceAddress) +char DallasTemperature::getHighAlarmTemp(const uint8_t* deviceAddress) { - ScratchPad scratchPad; - if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[HIGH_ALARM_TEMP]; - return DEVICE_DISCONNECTED; + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[HIGH_ALARM_TEMP]; + return DEVICE_DISCONNECTED_C; } // returns a char with the current low alarm temperature or // DEVICE_DISCONNECTED for an address -char DallasTemperature::getLowAlarmTemp(uint8_t* deviceAddress) +char DallasTemperature::getLowAlarmTemp(const uint8_t* deviceAddress) { - ScratchPad scratchPad; - if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[LOW_ALARM_TEMP]; - return DEVICE_DISCONNECTED; + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[LOW_ALARM_TEMP]; + return DEVICE_DISCONNECTED_C; } // resets internal variables used for the alarm search void DallasTemperature::resetAlarmSearch() { - alarmSearchJunction = -1; - alarmSearchExhausted = 0; - for(uint8_t i = 0; i < 7; i++) - alarmSearchAddress[i] = 0; + alarmSearchJunction = -1; + alarmSearchExhausted = 0; + for(uint8_t i = 0; i < 7; i++) + alarmSearchAddress[i] = 0; } // This is a modified version of the OneWire::search method. @@ -465,132 +587,152 @@ void DallasTemperature::resetAlarmSearch() // DallasTemperature::resetAlarmSearch() to start over. bool DallasTemperature::alarmSearch(uint8_t* newAddr) { - uint8_t i; - char lastJunction = -1; - uint8_t done = 1; + uint8_t i; + char lastJunction = -1; + uint8_t done = 1; - if (alarmSearchExhausted) return false; - if (!_wire->reset()) return false; + if (alarmSearchExhausted) return false; + if (!_wire->reset()) return false; - // send the alarm search command - _wire->write(0xEC, 0); + // send the alarm search command + _wire->write(0xEC, 0); - for(i = 0; i < 64; i++) - { - uint8_t a = _wire->read_bit( ); - uint8_t nota = _wire->read_bit( ); - uint8_t ibyte = i / 8; - uint8_t ibit = 1 << (i & 7); - - // I don't think this should happen, this means nothing responded, but maybe if - // something vanishes during the search it will come up. - if (a && nota) return false; - - if (!a && !nota) + for(i = 0; i < 64; i++) { - if (i == alarmSearchJunction) - { - // this is our time to decide differently, we went zero last time, go one. - a = 1; - alarmSearchJunction = lastJunction; - } - else if (i < alarmSearchJunction) - { - // take whatever we took last time, look in address - if (alarmSearchAddress[ibyte] & ibit) a = 1; - else + uint8_t a = _wire->read_bit( ); + uint8_t nota = _wire->read_bit( ); + uint8_t ibyte = i / 8; + uint8_t ibit = 1 << (i & 7); + + // I don't think this should happen, this means nothing responded, but maybe if + // something vanishes during the search it will come up. + if (a && nota) return false; + + if (!a && !nota) { - // Only 0s count as pending junctions, we've already exhasuted the 0 side of 1s - a = 0; - done = 0; - lastJunction = i; + if (i == alarmSearchJunction) + { + // this is our time to decide differently, we went zero last time, go one. + a = 1; + alarmSearchJunction = lastJunction; + } + else if (i < alarmSearchJunction) + { + // take whatever we took last time, look in address + if (alarmSearchAddress[ibyte] & ibit) a = 1; + else + { + // Only 0s count as pending junctions, we've already exhausted the 0 side of 1s + a = 0; + done = 0; + lastJunction = i; + } + } + else + { + // we are blazing new tree, take the 0 + a = 0; + alarmSearchJunction = i; + done = 0; + } + // OneWire search fix + // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 } - } - else - { - // we are blazing new tree, take the 0 - a = 0; - alarmSearchJunction = i; - done = 0; - } - // OneWire search fix - // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 + + if (a) alarmSearchAddress[ibyte] |= ibit; + else alarmSearchAddress[ibyte] &= ~ibit; + + _wire->write_bit(a); } - if (a) alarmSearchAddress[ibyte] |= ibit; - else alarmSearchAddress[ibyte] &= ~ibit; - - _wire->write_bit(a); - } - - if (done) alarmSearchExhausted = 1; - for (i = 0; i < 8; i++) newAddr[i] = alarmSearchAddress[i]; - return true; + if (done) alarmSearchExhausted = 1; + for (i = 0; i < 8; i++) newAddr[i] = alarmSearchAddress[i]; + return true; } -// returns true if device address has an alarm condition -bool DallasTemperature::hasAlarm(uint8_t* deviceAddress) +// returns true if device address might have an alarm condition +// (only an alarm search can verify this) +bool DallasTemperature::hasAlarm(const uint8_t* deviceAddress) { - ScratchPad scratchPad; - if (isConnected(deviceAddress, scratchPad)) - { - float temp = calculateTemperature(deviceAddress, scratchPad); + ScratchPad scratchPad; + if (isConnected(deviceAddress, scratchPad)) + { + char temp = calculateTemperature(deviceAddress, scratchPad) >> 7; - // check low alarm - if ((char)temp <= (char)scratchPad[LOW_ALARM_TEMP]) return true; + // check low alarm + if (temp <= (char)scratchPad[LOW_ALARM_TEMP]) return true; - // check high alarm - if ((char)temp >= (char)scratchPad[HIGH_ALARM_TEMP]) return true; - } + // check high alarm + if (temp >= (char)scratchPad[HIGH_ALARM_TEMP]) return true; + } - // no alarm - return false; + // no alarm + return false; } // returns true if any device is reporting an alarm condition on the bus bool DallasTemperature::hasAlarm(void) { - DeviceAddress deviceAddress; - resetAlarmSearch(); - return alarmSearch(deviceAddress); + DeviceAddress deviceAddress; + resetAlarmSearch(); + return alarmSearch(deviceAddress); } // runs the alarm handler for all devices returned by alarmSearch() void DallasTemperature::processAlarms(void) { - resetAlarmSearch(); - DeviceAddress alarmAddr; + resetAlarmSearch(); + DeviceAddress alarmAddr; - while (alarmSearch(alarmAddr)) - { - if (validAddress(alarmAddr)) - _AlarmHandler(alarmAddr); - } + while (alarmSearch(alarmAddr)) + { + if (validAddress(alarmAddr)) + _AlarmHandler(alarmAddr); + } } // sets the alarm handler void DallasTemperature::setAlarmHandler(AlarmHandler *handler) { - _AlarmHandler = handler; + _AlarmHandler = handler; } // The default alarm handler -void DallasTemperature::defaultAlarmHandler(uint8_t* deviceAddress) +void DallasTemperature::defaultAlarmHandler(const uint8_t* deviceAddress) { } #endif -// Convert float celsius to fahrenheit +// Convert float Celsius to Fahrenheit float DallasTemperature::toFahrenheit(float celsius) { - return (celsius * 1.8) + 32; + return (celsius * 1.8) + 32; } -// Convert float fahrenheit to celsius +// Convert float Fahrenheit to Celsius float DallasTemperature::toCelsius(float fahrenheit) { - return (fahrenheit - 32) / 1.8; + return (fahrenheit - 32) * 0.555555556; +} + +// convert from raw to Celsius +float DallasTemperature::rawToCelsius(int16_t raw) +{ + if (raw <= DEVICE_DISCONNECTED_RAW) + return DEVICE_DISCONNECTED_C; + // C = RAW/128 + return (float)raw * 0.0078125; +} + +// convert from raw to Fahrenheit +float DallasTemperature::rawToFahrenheit(int16_t raw) +{ + if (raw <= DEVICE_DISCONNECTED_RAW) + return DEVICE_DISCONNECTED_F; + // C = RAW/128 + // F = (C*1.8)+32 = (RAW/128*1.8)+32 = (RAW*0.0140625)+32 + return ((float)raw * 0.0140625) + 32; } #if REQUIRESNEW @@ -598,21 +740,21 @@ float DallasTemperature::toCelsius(float fahrenheit) // MnetCS - Allocates memory for DallasTemperature. Allows us to instance a new object void* DallasTemperature::operator new(unsigned int size) // Implicit NSS obj size { - void * p; // void pointer - p = malloc(size); // Allocate memory - memset((DallasTemperature*)p,0,size); // Initalise memory + void * p; // void pointer + p = malloc(size); // Allocate memory + memset((DallasTemperature*)p,0,size); // Initialise memory - //!!! CANT EXPLICITLY CALL CONSTRUCTOR - workaround by using an init() methodR - workaround by using an init() method - return (DallasTemperature*) p; // Cast blank region to NSS pointer + //!!! CANT EXPLICITLY CALL CONSTRUCTOR - workaround by using an init() methodR - workaround by using an init() method + return (DallasTemperature*) p; // Cast blank region to NSS pointer } -// MnetCS 2009 - Unallocates the memory used by this instance +// MnetCS 2009 - Free the memory used by this instance void DallasTemperature::operator delete(void* p) { - DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer - pNss->~DallasTemperature(); // Destruct the object + DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer + pNss->~DallasTemperature(); // Destruct the object - free(p); // Free the memory + free(p); // Free the memory } #endif diff --git a/libraries/DallasTemperature/DallasTemperature.h b/libraries/DallasTemperature/DallasTemperature.h index daf4ad1..93d9713 100644 --- a/libraries/DallasTemperature/DallasTemperature.h +++ b/libraries/DallasTemperature/DallasTemperature.h @@ -1,6 +1,8 @@ #ifndef DallasTemperature_h #define DallasTemperature_h +#define DALLASTEMPLIBVERSION "3.7.2" + // 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 @@ -20,9 +22,10 @@ #include // Model IDs -#define DS18S20MODEL 0x10 +#define DS18S20MODEL 0x10 // also DS1820 #define DS18B20MODEL 0x28 #define DS1822MODEL 0x22 +#define DS1825MODEL 0x3B // OneWire commands #define STARTCONVO 0x44 // Tells device to take a temperature reading and put it on the scratchpad @@ -51,7 +54,9 @@ #define TEMP_12_BIT 0x7F // 12 bit // Error Codes -#define DEVICE_DISCONNECTED -127 +#define DEVICE_DISCONNECTED_C -127 +#define DEVICE_DISCONNECTED_F -196.6 +#define DEVICE_DISCONNECTED_RAW -7040 typedef uint8_t DeviceAddress[8]; @@ -61,54 +66,71 @@ class DallasTemperature DallasTemperature(OneWire*); - // initalize bus + // initialise bus void begin(void); // returns the number of devices found on the bus uint8_t getDeviceCount(void); // returns true if address is valid - bool validAddress(uint8_t*); + bool validAddress(const uint8_t*); // finds an address at a given index on the bus - bool getAddress(uint8_t*, const uint8_t); + bool getAddress(uint8_t*, uint8_t); // attempt to determine if the device at the given address is connected to the bus - bool isConnected(uint8_t*); + bool isConnected(const uint8_t*); // attempt to determine if the device at the given address is connected to the bus // also allows for updating the read scratchpad - bool isConnected(uint8_t*, uint8_t*); + bool isConnected(const uint8_t*, uint8_t*); // read device's scratchpad - void readScratchPad(uint8_t*, uint8_t*); + void readScratchPad(const uint8_t*, uint8_t*); // write device's scratchpad - void writeScratchPad(uint8_t*, const uint8_t*); + void writeScratchPad(const uint8_t*, const uint8_t*); // read device's power requirements - bool readPowerSupply(uint8_t*); + bool readPowerSupply(const uint8_t*); - // returns the current resolution, 9-12 - uint8_t getResolution(uint8_t*); + // get global resolution + uint8_t getResolution(); + + // set global resolution to 9, 10, 11, or 12 bits + void setResolution(uint8_t); + + // returns the device resolution: 9, 10, 11, or 12 bits + uint8_t getResolution(const uint8_t*); // set resolution of a device to 9, 10, 11, or 12 bits - void setResolution(uint8_t*, uint8_t); - - // sends command for all devices on the bus to perform a temperature conversion + bool setResolution(const uint8_t*, uint8_t); + + // sets/gets the waitForConversion flag + void setWaitForConversion(bool); + bool getWaitForConversion(void); + + // sets/gets the checkForConversion flag + void setCheckForConversion(bool); + bool getCheckForConversion(void); + + // sends command for all devices on the bus to perform a temperature conversion void requestTemperatures(void); // sends command for one device to perform a temperature conversion by address - void requestTemperaturesByAddress(uint8_t*); + bool requestTemperaturesByAddress(const uint8_t*); // sends command for one device to perform a temperature conversion by index - void requestTemperaturesByIndex(uint8_t); + bool requestTemperaturesByIndex(uint8_t); + + // returns temperature raw value (12 bit integer of 1/16 degrees C) + int16_t getTemp(const uint8_t*); // returns temperature in degrees C - float getTempC(uint8_t*); + float getTempC(const uint8_t*); // returns temperature in degrees F - float getTempF(uint8_t*); + float getTempF(const uint8_t*); // Get temperature for device index (slow) float getTempCByIndex(uint8_t); @@ -118,26 +140,28 @@ class DallasTemperature // returns true if the bus requires parasite power bool isParasitePowerMode(void); + + bool isConversionAvailable(const uint8_t*); #if REQUIRESALARMS - typedef void AlarmHandler(uint8_t*); + typedef void AlarmHandler(const uint8_t*); // sets the high alarm temperature for a device // accepts a char. valid range is -55C - 125C - void setHighAlarmTemp(uint8_t*, const char); + void setHighAlarmTemp(const uint8_t*, char); // sets the low alarm temperature for a device // accepts a char. valid range is -55C - 125C - void setLowAlarmTemp(uint8_t*, const char); + void setLowAlarmTemp(const uint8_t*, char); // returns a signed char with the current high alarm temperature for a device // in the range -55C - 125C - char getHighAlarmTemp(uint8_t*); + char getHighAlarmTemp(const uint8_t*); // returns a signed char with the current low alarm temperature for a device // in the range -55C - 125C - char getLowAlarmTemp(uint8_t*); + char getLowAlarmTemp(const uint8_t*); // resets internal variables used for the alarm search void resetAlarmSearch(void); @@ -146,7 +170,7 @@ class DallasTemperature bool alarmSearch(uint8_t*); // returns true if ia specific device has an alarm - bool hasAlarm(uint8_t*); + bool hasAlarm(const uint8_t*); // returns true if any device is reporting an alarm on the bus bool hasAlarm(void); @@ -155,22 +179,28 @@ class DallasTemperature void processAlarms(void); // sets the alarm handler - void setAlarmHandler(AlarmHandler *); + void setAlarmHandler(const AlarmHandler *); // The default alarm handler - static void defaultAlarmHandler(uint8_t*); + static void defaultAlarmHandler(const uint8_t*); #endif - // convert from celcius to farenheit - static float toFahrenheit(const float); + // convert from Celsius to Fahrenheit + static float toFahrenheit(float); - // convert from farenheit to celsius - static float toCelsius(const float); + // convert from Fahrenheit to Celsius + static float toCelsius(float); + + // convert from raw to Celsius + static float rawToCelsius(int16_t); + + // convert from raw to Fahrenheit + static float rawToFahrenheit(int16_t); #if REQUIRESNEW - // initalize memory area + // initialize memory area void* operator new (unsigned int); // delete memory reference @@ -186,16 +216,26 @@ class DallasTemperature // used to determine the delay amount needed to allow for the // temperature conversion to take place - int conversionDelay; - + uint8_t bitResolution; + + // used to requestTemperature with or without delay + bool waitForConversion; + + // used to requestTemperature to dynamically check if a conversion is complete + bool checkForConversion; + // count of devices on the bus uint8_t devices; // Take a pointer to one wire instance OneWire* _wire; - // reads scratchpad and returns the temperature in degrees C - float calculateTemperature(uint8_t*, uint8_t*); + // reads scratchpad and returns the raw temperature + int16_t calculateTemperature(const uint8_t*, uint8_t*); + + int16_t millisToWaitForConversion(uint8_t); + + void blockTillConversionComplete(uint8_t, const uint8_t*); #if REQUIRESALARMS diff --git a/libraries/DallasTemperature/README b/libraries/DallasTemperature/README.md similarity index 84% rename from libraries/DallasTemperature/README rename to libraries/DallasTemperature/README.md index 829d266..b4ca8c2 100644 --- a/libraries/DallasTemperature/README +++ b/libraries/DallasTemperature/README.md @@ -4,10 +4,14 @@ Arduino Library for Dallas Temperature ICs Usage ----- -This library supports the following devices: - DS18B20 - DS18S20 - Please note there appears to be an issue with this series. - DS1822 +This library supports the following devices : + + +* DS18B20 +* DS18S20 - Please note there appears to be an issue with this series. +* DS1822 +* DS1820 + You will need a pull-up resistor of about 5 KOhm between the 1-Wire data line and your 5V power. If you are using the DS18B20, ground pins 1 and 3. The @@ -15,7 +19,18 @@ centre pin is the data line '1-wire'. We have included a "REQUIRESNEW" and "REQUIRESALARMS" definition. If you want to slim down the code feel free to use either of these by including -#define REQUIRESNEW or #define REQUIRESALARMS a the top of DallasTemperature.h + + + + #define REQUIRESNEW + +or + + #define REQUIRESALARMS + + +at the top of DallasTemperature.h + Credits ------- @@ -26,6 +41,8 @@ Miles Burton originally developed this library. Tim Newsome added support for multiple sensors on the same bus. Guil Barros [gfbarros@bappos.com] added getTempByAddress (v3.5) +Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0) + Website ------- diff --git a/libraries/DallasTemperature/change.txt b/libraries/DallasTemperature/change.txt new file mode 100644 index 0000000..42564ca --- /dev/null +++ b/libraries/DallasTemperature/change.txt @@ -0,0 +1,85 @@ + +This file contains the change history of the Dallas Temperature Control Library. + +VERSION 3.7.2 BETA +=================== +DATE: 6 DEC 2011 + +- Jordan Hochenbaum [jhochenbaum@gmail.com] updated library for compatibility with Arduino 1.0. + +VERSION 3.7.0 BETA +=================== +DATE: 11 JAN 2011 + +- Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0) + The library is backwards compatible with version 3.6.0 + + MAJOR: async modus + ------------------ +- Added - private bool waitForConversion. +This boolean is default set to true in the Constructor to keep the library backwards compatible. If this flag is true calls to requestTemperatures(), requestTemperaturesByAddress() et al, will be blocking with the appropiate time specified (in datasheet) for the resolution used. If the flag is set to false, requestTemperatures() et al, will return immediately after the conversion command is send over the 1-wire interface. The programmer is responsible to wait long enough before reading the temperature values. This enables the application to do other things while waiting for a new reading, like calculations, update LCD, read/write other IO lines etc. See examples. + +- Added - void setWaitForConversion(bool); +To set the flag to true or false, depending on the modus needed. + +- Added - bool getWaitForConversion(void); +To get the current value of the flag. + +- Changed - void requestTemperatures(void); +Added a test (false == waitForConversion) to return immediately after the conversion command instead of waiting until the conversion is ready. + +- Changed - bool requestTemperaturesByAddress(uint8_t*); +Added a test (false == waitForConversion) to return immediately after the conversion command instead of waiting until the conversion is ready. + + + MINOR version number + -------------------- +- Added - #define DALLASTEMPLIBVERSION "3.7.0" +To indicate the version number in .h file + + + MINOR internal var bitResolution + ---------------------------- +- Changed - private int conversionDelay - is renamed to - private int bitResolution +As this variable holds the resolution. The delay for the conversion is derived from it. + +- Changed - uint8_t getResolution(uint8_t* deviceAddress); +If the device is not connected, it returns 0, otherwise it returns the resolution of the device. + +- Changed - bool setResolution(uint8_t* deviceAddress, uint8_t newResolution); +If the device is not connected, it returns FALSE (fail), otherwise it returns TRUE (succes). + +- Added - uint8_t getResolution(); +Returns bitResolution. + +- Added - void setResolution(uint8_t newResolution) +Sets the internal variable bitResolution, and all devices to this value + + + MINOR check connected state + ---------------------------- +- Changed - bool requestTemperaturesByIndex(deviceIndex) +Changed return type from void to bool. The function returns false if the device identified with [deviceIndex] is not found on the bus and true otherwise. + +- Changed - bool requestTemperaturesByAddress(deviceAddress) +Changed return type from void to bool. The function returns false if the device identified with [deviceAddress] is not found on the bus and true otherwise. +Added code to handle the DS18S20 which has a 9 bit resolution separately. +Changed code so the blocking delay matches the bitResolution set in the device with deviceAddress. + +- Changed - bool requestTemperaturesByIndex(uint8_t deviceIndex) +Changed return type from void to bool. The function returns false if the device identified with [deviceIndex] is not found on the bus and true otherwise. + + + +VERSION 3.6.0 +============== +DATE: 2010-10-10 + +- no detailed change history known except: + +- The OneWire code has been derived from +http://www.arduino.cc/playground/Learning/OneWire. +- Miles Burton originally developed this library. +- Tim Newsome added support for multiple sensors on +the same bus. +- Guil Barros [gfbarros@bappos.com] added getTempByAddress (v3.5) diff --git a/libraries/DallasTemperature/examples/Alarm/Alarm.pde b/libraries/DallasTemperature/examples/Alarm/Alarm.pde index bd8af00..2aab5f5 100644 --- a/libraries/DallasTemperature/examples/Alarm/Alarm.pde +++ b/libraries/DallasTemperature/examples/Alarm/Alarm.pde @@ -2,7 +2,7 @@ #include // Data wire is plugged into port 2 on the Arduino -#define ONE_WIRE_BUS 3 +#define ONE_WIRE_BUS 2 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); diff --git a/libraries/DallasTemperature/examples/AlarmHandler/AlarmHandler.pde b/libraries/DallasTemperature/examples/AlarmHandler/AlarmHandler.pde index 05b3a5f..606c5df 100644 --- a/libraries/DallasTemperature/examples/AlarmHandler/AlarmHandler.pde +++ b/libraries/DallasTemperature/examples/AlarmHandler/AlarmHandler.pde @@ -2,8 +2,7 @@ #include // Data wire is plugged into port 2 on the Arduino -#define ONE_WIRE_BUS 3 -#define TEMPERATURE_PRECISION 9 +#define ONE_WIRE_BUS 2 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); diff --git a/libraries/DallasTemperature/examples/Multiple/Multiple.pde b/libraries/DallasTemperature/examples/Multiple/Multiple.pde index 86cc47d..9e7d6a8 100644 --- a/libraries/DallasTemperature/examples/Multiple/Multiple.pde +++ b/libraries/DallasTemperature/examples/Multiple/Multiple.pde @@ -2,7 +2,7 @@ #include // Data wire is plugged into port 2 on the Arduino -#define ONE_WIRE_BUS 3 +#define ONE_WIRE_BUS 2 #define TEMPERATURE_PRECISION 9 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) @@ -74,8 +74,8 @@ void setup(void) Serial.println(); // set the resolution to 9 bit - sensors.setResolution(insideThermometer, 9); - sensors.setResolution(outsideThermometer, 9); + sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION); + sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION); Serial.print("Device 0 Resolution: "); Serial.print(sensors.getResolution(insideThermometer), DEC); diff --git a/libraries/DallasTemperature/examples/Single/Single.pde b/libraries/DallasTemperature/examples/Single/Single.pde index 61cfcd0..784eb7a 100644 --- a/libraries/DallasTemperature/examples/Single/Single.pde +++ b/libraries/DallasTemperature/examples/Single/Single.pde @@ -2,7 +2,7 @@ #include // Data wire is plugged into port 2 on the Arduino -#define ONE_WIRE_BUS 3 +#define ONE_WIRE_BUS 2 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); diff --git a/libraries/DallasTemperature/examples/Tester/Tester.pde b/libraries/DallasTemperature/examples/Tester/Tester.pde index 8da0722..4f75839 100644 --- a/libraries/DallasTemperature/examples/Tester/Tester.pde +++ b/libraries/DallasTemperature/examples/Tester/Tester.pde @@ -2,7 +2,7 @@ #include // Data wire is plugged into port 2 on the Arduino -#define ONE_WIRE_BUS 3 +#define ONE_WIRE_BUS 2 #define TEMPERATURE_PRECISION 9 // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) @@ -52,9 +52,9 @@ void setup(void) Serial.println(); Serial.print("Setting resolution to "); - Serial.println(TEMPERATURE_PRECISION,DEC); + Serial.println(TEMPERATURE_PRECISION, DEC); - // set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions) + // set the resolution to TEMPERATURE_PRECISION bit (Each Dallas/Maxim device is capable of several different resolutions) sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION); Serial.print("Resolution actually set to: "); diff --git a/libraries/DallasTemperature/examples/WaitForConversion/WaitForConversion.pde b/libraries/DallasTemperature/examples/WaitForConversion/WaitForConversion.pde new file mode 100644 index 0000000..52c30be --- /dev/null +++ b/libraries/DallasTemperature/examples/WaitForConversion/WaitForConversion.pde @@ -0,0 +1,66 @@ +#include +#include + +// Data wire is plugged into port 2 on the Arduino +#define ONE_WIRE_BUS 2 + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +void setup(void) +{ + // start serial port + Serial.begin(115200); + Serial.println("Dallas Temperature Control Library - Async Demo"); + Serial.println("\nDemo shows the difference in length of the call\n\n"); + + // Start up the library + sensors.begin(); +} + +void loop(void) +{ + // Request temperature conversion (traditional) + Serial.println("Before blocking requestForConversion"); + unsigned long start = millis(); + + sensors.requestTemperatures(); + + unsigned long stop = millis(); + Serial.println("After blocking requestForConversion"); + Serial.print("Time used: "); + Serial.println(stop - start); + + // get temperature + Serial.print("Temperature: "); + Serial.println(sensors.getTempCByIndex(0)); + Serial.println("\n"); + + // Request temperature conversion - non-blocking / async + Serial.println("Before NON-blocking/async requestForConversion"); + start = millis(); + sensors.setWaitForConversion(false); // makes it async + sensors.requestTemperatures(); + sensors.setWaitForConversion(true); + stop = millis(); + Serial.println("After NON-blocking/async requestForConversion"); + Serial.print("Time used: "); + Serial.println(stop - start); + + + // 9 bit resolution by default + // Note the programmer is responsible for the right delay + // we could do something usefull here instead of the delay + int resolution = 9; + delay(750/ (1 << (12-resolution))); + + // get temperature + Serial.print("Temperature: "); + Serial.println(sensors.getTempCByIndex(0)); + Serial.println("\n\n\n\n"); + + delay(5000); +} diff --git a/libraries/DallasTemperature/examples/WaitForConversion2/WaitForConversion2.pde b/libraries/DallasTemperature/examples/WaitForConversion2/WaitForConversion2.pde new file mode 100644 index 0000000..f8e7700 --- /dev/null +++ b/libraries/DallasTemperature/examples/WaitForConversion2/WaitForConversion2.pde @@ -0,0 +1,80 @@ +// +// Sample of using Async reading of Dallas Temperature Sensors +// +#include +#include + +// Data wire is plugged into port 2 on the Arduino +#define ONE_WIRE_BUS 2 + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +DeviceAddress tempDeviceAddress; + +int resolution = 12; +unsigned long lastTempRequest = 0; +int delayInMillis = 0; +float temperature = 0.0; +int idle = 0; +// +// SETUP +// +void setup(void) +{ + Serial.begin(115200); + Serial.println("Dallas Temperature Control Library - Async Demo"); + Serial.print("Library Version: "); + Serial.println(DALLASTEMPLIBVERSION); + Serial.println("\n"); + + sensors.begin(); + sensors.getAddress(tempDeviceAddress, 0); + sensors.setResolution(tempDeviceAddress, resolution); + + sensors.setWaitForConversion(false); + sensors.requestTemperatures(); + delayInMillis = 750 / (1 << (12 - resolution)); + lastTempRequest = millis(); + + pinMode(13, OUTPUT); +} + +void loop(void) +{ + + if (millis() - lastTempRequest >= delayInMillis) // waited long enough?? + { + digitalWrite(13, LOW); + Serial.print(" Temperature: "); + temperature = sensors.getTempCByIndex(0); + Serial.println(temperature, resolution - 8); + Serial.print(" Resolution: "); + Serial.println(resolution); + Serial.print("Idle counter: "); + Serial.println(idle); + Serial.println(); + + idle = 0; + + // immediately after fetching the temperature we request a new sample + // in the async modus + // for the demo we let the resolution change to show differences + resolution++; + if (resolution > 12) resolution = 9; + + sensors.setResolution(tempDeviceAddress, resolution); + sensors.requestTemperatures(); + delayInMillis = 750 / (1 << (12 - resolution)); + lastTempRequest = millis(); + } + + digitalWrite(13, HIGH); + // we can do usefull things here + // for the demo we just count the idle time in millis + delay(1); + idle++; +} diff --git a/libraries/DallasTemperature/keywords.txt b/libraries/DallasTemperature/keywords.txt index a143d76..b80a269 100644 --- a/libraries/DallasTemperature/keywords.txt +++ b/libraries/DallasTemperature/keywords.txt @@ -7,8 +7,8 @@ ####################################### DallasTemperature KEYWORD1 OneWire KEYWORD1 -AlarmHandler KEYWORD1 -DeviceAddress KEYWORD1 +AlarmHandler KEYWORD1 +DeviceAddress KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) @@ -20,12 +20,14 @@ getTempC KEYWORD2 toFahrenheit KEYWORD2 getTempF KEYWORD2 getTempCByIndex KEYWORD2 -getTempFByIndex KEYWORD2 +getTempFByIndex KEYWORD2 +setWaitForConversion KEYWORD2 +getWaitForConversion KEYWORD2 requestTemperatures KEYWORD2 -requestTemperaturesByAddress KEYWORD2 -requestTemperaturesByIndex KEYWORD2 +requestTemperaturesByAddress KEYWORD2 +requestTemperaturesByIndex KEYWORD2 isParasitePowerMode KEYWORD2 -begin KEYWORD2 +begin KEYWORD2 getDeviceCount KEYWORD2 getAddress KEYWORD2 validAddress KEYWORD2 @@ -45,6 +47,7 @@ processAlarmss KEYWORD2 setAlarmHandlers KEYWORD2 defaultAlarmHandler KEYWORD2 calculateTemperature KEYWORD2 +millisToWaitForConversion KEYWORD2 ####################################### # Constants (LITERAL1) diff --git a/libraries/DallasTemperature/library.json b/libraries/DallasTemperature/library.json new file mode 100644 index 0000000..2222135 --- /dev/null +++ b/libraries/DallasTemperature/library.json @@ -0,0 +1,39 @@ +{ + "name": "DallasTemperature", + "keywords": "onewire, 1-wire, bus, sensor, temperature", + "description": "Arduino Library for Dallas Temperature ICs (DS18B20, DS18S20, DS1822, DS1820)", + "repository": + { + "type": "git", + "url": "https://github.com/milesburton/Arduino-Temperature-Control-Library.git" + }, + "authors": + [ + { + "name": "Miles Burton", + "email": "miles@mnetcs.com", + "url": "http://www.milesburton.com", + "maintainer": true + }, + { + "name": "Tim Newsome", + "email": "nuisance@casualhacker.net" + }, + { + "name": "Guil Barros", + "email": "gfbarros@bappos.com" + }, + { + "name": "Rob Tillaart", + "email": "rob.tillaart@gmail.com" + } + ], + "dependencies": + { + "name": "OneWire", + "authors": "Paul Stoffregen", + "frameworks": "arduino" + }, + "frameworks": "arduino", + "platforms": "atmelavr" +} diff --git a/libraries/OneWire/OneWire.cpp b/libraries/OneWire/OneWire.cpp index 5c3561a..631813f 100644 --- a/libraries/OneWire/OneWire.cpp +++ b/libraries/OneWire/OneWire.cpp @@ -4,6 +4,24 @@ Copyright (c) 2007, Jim Studt (original old version - many contributors since) The latest version of this library may be found at: http://www.pjrc.com/teensy/td_libs_OneWire.html +OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since +January 2010. At the time, it was in need of many bug fixes, but had +been abandoned the original author (Jim Studt). None of the known +contributors were interested in maintaining OneWire. Paul typically +works on OneWire every 6 to 12 months. Patches usually wait that +long. If anyone is interested in more actively maintaining OneWire, +please contact Paul. + +Version 2.2: + Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com + Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030 + Fix DS18B20 example negative temperature + Fix DS18B20 example's low res modes, Ken Butcher + Improve reset timing, Mark Tillotson + Add const qualifiers, Bertrik Sikken + Add initial value input to crc16, Bertrik Sikken + Add target_search() function, Scott Roberts + Version 2.1: Arduino 1.0 compatibility, Paul Stoffregen Improve temperature example, Paul Stoffregen @@ -136,13 +154,13 @@ uint8_t OneWire::reset(void) DIRECT_WRITE_LOW(reg, mask); DIRECT_MODE_OUTPUT(reg, mask); // drive output low interrupts(); - delayMicroseconds(500); + delayMicroseconds(480); noInterrupts(); DIRECT_MODE_INPUT(reg, mask); // allow it to float - delayMicroseconds(80); + delayMicroseconds(70); r = !DIRECT_READ(reg, mask); interrupts(); - delayMicroseconds(420); + delayMicroseconds(410); return r; } @@ -249,13 +267,13 @@ void OneWire::read_bytes(uint8_t *buf, uint16_t count) { // // Do a ROM select // -void OneWire::select( uint8_t rom[8]) +void OneWire::select(const uint8_t rom[8]) { - int i; + uint8_t i; write(0x55); // Choose ROM - for( i = 0; i < 8; i++) write(rom[i]); + for (i = 0; i < 8; i++) write(rom[i]); } // @@ -280,17 +298,30 @@ void OneWire::depower() // You do not need to do it for the first search, though you could. // void OneWire::reset_search() - { +{ // reset the search state LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; - for(int i = 7; ; i--) - { + for(int i = 7; ; i--) { ROM_NO[i] = 0; if ( i == 0) break; - } } +} + +// Setup the search to find the device type 'family_code' on the next call +// to search(*newAddr) if it is present. +// +void OneWire::target_search(uint8_t family_code) +{ + // set the search state to find SearchFamily type devices + ROM_NO[0] = family_code; + for (uint8_t i = 1; i < 8; i++) + ROM_NO[i] = 0; + LastDiscrepancy = 64; + LastFamilyDiscrepancy = 0; + LastDeviceFlag = FALSE; +} // // Perform a search. If this function returns a '1' then it has @@ -461,7 +492,7 @@ static const uint8_t PROGMEM dscrc_table[] = { // compared to all those delayMicrosecond() calls. But I got // confused, so I use this table from the examples.) // -uint8_t OneWire::crc8( uint8_t *addr, uint8_t len) +uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len) { uint8_t crc = 0; @@ -475,7 +506,7 @@ uint8_t OneWire::crc8( uint8_t *addr, uint8_t len) // Compute a Dallas Semiconductor 8 bit CRC directly. // this is much slower, but much smaller, than the lookup table. // -uint8_t OneWire::crc8( uint8_t *addr, uint8_t len) +uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len) { uint8_t crc = 0; @@ -493,23 +524,22 @@ uint8_t OneWire::crc8( uint8_t *addr, uint8_t len) #endif #if ONEWIRE_CRC16 -bool OneWire::check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc) +bool OneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc) { - uint16_t crc = ~crc16(input, len); + crc = ~crc16(input, len, crc); return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1]; } -uint16_t OneWire::crc16(uint8_t* input, uint16_t len) +uint16_t OneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc) { static const uint8_t oddparity[16] = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; - uint16_t crc = 0; // Starting seed is zero. for (uint16_t i = 0 ; i < len ; i++) { // Even though we're just copying a byte from the input, // we'll be doing 16-bit computation with it. uint16_t cdata = input[i]; - cdata = (cdata ^ (crc & 0xff)) & 0xff; + cdata = (cdata ^ crc) & 0xff; crc >>= 8; if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4]) diff --git a/libraries/OneWire/OneWire.h b/libraries/OneWire/OneWire.h index 2737b27..916c529 100644 --- a/libraries/OneWire/OneWire.h +++ b/libraries/OneWire/OneWire.h @@ -56,13 +56,44 @@ #define IO_REG_TYPE uint8_t #define IO_REG_ASM asm("r30") #define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) -#define DIRECT_MODE_INPUT(base, mask) ((*(base+1)) &= ~(mask)) -#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) |= (mask)) -#define DIRECT_WRITE_LOW(base, mask) ((*(base+2)) &= ~(mask)) -#define DIRECT_WRITE_HIGH(base, mask) ((*(base+2)) |= (mask)) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask)) + +#elif defined(__MK20DX128__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (1) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (*((base)+512)) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1) + +#elif defined(__SAM3X8E__) +// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due. +// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268 +// If you have trouble with OneWire on Arduino Due, please check the +// status of delayMicroseconds() before reporting a bug in OneWire! +#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask)) +#ifndef PROGMEM +#define PROGMEM +#endif +#ifndef pgm_read_byte +#define pgm_read_byte(addr) (*(const uint8_t *)(addr)) +#endif #elif defined(__PIC32MX__) -#include // is this necessary? #define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin))) #define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) #define IO_REG_TYPE uint32_t @@ -101,7 +132,7 @@ class OneWire uint8_t reset(void); // Issue a 1-Wire rom select command, you do the reset first. - void select( uint8_t rom[8]); + void select(const uint8_t rom[8]); // Issue a 1-Wire rom skip command, to address all on bus. void skip(void); @@ -137,6 +168,10 @@ class OneWire // Clear the search state so that if will start from the beginning again. void reset_search(); + // Setup the search to find the device type 'family_code' on the next call + // to search(*newAddr) if it is present. + void target_search(uint8_t family_code); + // Look for the next device. Returns 1 if a new address has been // returned. A zero might mean that the bus is shorted, there are // no devices, or you have already retrieved all of them. It @@ -149,7 +184,7 @@ class OneWire #if ONEWIRE_CRC // Compute a Dallas Semiconductor 8 bit CRC, these are used in the // ROM and scratchpad registers. - static uint8_t crc8( uint8_t *addr, uint8_t len); + static uint8_t crc8(const uint8_t *addr, uint8_t len); #if ONEWIRE_CRC16 // Compute the 1-Wire CRC16 and compare it against the received CRC. @@ -170,8 +205,9 @@ class OneWire // @param inverted_crc - The two CRC16 bytes in the received data. // This should just point into the received data, // *not* at a 16-bit integer. + // @param crc - The crc starting value (optional) // @return True, iff the CRC matches. - static bool check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc); + static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0); // Compute a Dallas Semiconductor 16 bit CRC. This is required to check // the integrity of data received from many 1-Wire devices. Note that the @@ -183,8 +219,9 @@ class OneWire // byte order than the two bytes you get from 1-Wire. // @param input - Array of bytes to checksum. // @param len - How many bytes to use. + // @param crc - The crc starting value (optional) // @return The CRC16, as defined by Dallas Semiconductor. - static uint16_t crc16(uint8_t* input, uint16_t len); + static uint16_t crc16(const uint8_t* input, uint16_t len, uint16_t crc = 0); #endif #endif }; diff --git a/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde b/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde index 1d632ca..68ca194 100644 --- a/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde +++ b/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde @@ -7,7 +7,7 @@ // The DallasTemperature library can do all this work for you! // http://milesburton.com/Dallas_Temperature_Control_Library -OneWire ds(10); // on pin 10 +OneWire ds(10); // on pin 10 (a 4.7K resistor is necessary) void setup(void) { Serial.begin(9600); @@ -62,7 +62,7 @@ void loop(void) { ds.reset(); ds.select(addr); - ds.write(0x44,1); // start conversion, with parasite power on at the end + ds.write(0x44, 1); // start conversion, with parasite power on at the end delay(1000); // maybe 750ms is enough, maybe not // we might do a ds.depower() here, but the reset will take care of it. @@ -72,7 +72,7 @@ void loop(void) { ds.write(0xBE); // Read Scratchpad Serial.print(" Data = "); - Serial.print(present,HEX); + Serial.print(present, HEX); Serial.print(" "); for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); @@ -83,21 +83,24 @@ void loop(void) { Serial.print(OneWire::crc8(data, 8), HEX); Serial.println(); - // convert the data to actual temperature - - unsigned int raw = (data[1] << 8) | data[0]; + // Convert the data to actual temperature + // because the result is a 16 bit signed integer, it should + // be stored to an "int16_t" type, which is always 16 bits + // even when compiled on a 32 bit processor. + int16_t raw = (data[1] << 8) | data[0]; if (type_s) { raw = raw << 3; // 9 bit resolution default if (data[7] == 0x10) { - // count remain gives full 12 bit resolution + // "count remain" gives full 12 bit resolution raw = (raw & 0xFFF0) + 12 - data[6]; } } else { byte cfg = (data[4] & 0x60); - if (cfg == 0x00) raw = raw << 3; // 9 bit resolution, 93.75 ms - else if (cfg == 0x20) raw = raw << 2; // 10 bit res, 187.5 ms - else if (cfg == 0x40) raw = raw << 1; // 11 bit res, 375 ms - // default is 12 bit resolution, 750 ms conversion time + // at lower res, the low bits are undefined, so let's zero them + if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms + else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms + else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms + //// default is 12 bit resolution, 750 ms conversion time } celsius = (float)raw / 16.0; fahrenheit = celsius * 1.8 + 32.0; From e47e596075282b122ac5d266ec6ad5c60ca8c978 Mon Sep 17 00:00:00 2001 From: Robo Print Date: Sat, 27 Jun 2015 23:00:37 +0200 Subject: [PATCH 39/79] Make DallasTemperature::millisToWaitForConversion() publicly available --- libraries/DallasTemperature/DallasTemperature.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/DallasTemperature/DallasTemperature.h b/libraries/DallasTemperature/DallasTemperature.h index 93d9713..189fc6b 100644 --- a/libraries/DallasTemperature/DallasTemperature.h +++ b/libraries/DallasTemperature/DallasTemperature.h @@ -116,7 +116,10 @@ class DallasTemperature // sends command for all devices on the bus to perform a temperature conversion void requestTemperatures(void); - + + // returns time to wait for a temperature conversion based on given resolution + int16_t millisToWaitForConversion(uint8_t); + // sends command for one device to perform a temperature conversion by address bool requestTemperaturesByAddress(const uint8_t*); @@ -233,8 +236,6 @@ class DallasTemperature // reads scratchpad and returns the raw temperature int16_t calculateTemperature(const uint8_t*, uint8_t*); - int16_t millisToWaitForConversion(uint8_t); - void blockTillConversionComplete(uint8_t, const uint8_t*); #if REQUIRESALARMS From dffec694626b8fc0a70eb97368a1bdc440b5bdc4 Mon Sep 17 00:00:00 2001 From: Robo Print Date: Sat, 27 Jun 2015 23:27:35 +0200 Subject: [PATCH 40/79] Non-blocking Dallas sensors temperature conversion => lower power usage --- .../DallasTemperatureSensor.ino | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino index 3c6c2c0..ade4edd 100644 --- a/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino +++ b/libraries/MySensors/examples/DallasTemperatureSensor/DallasTemperatureSensor.ino @@ -21,6 +21,8 @@ void setup() { // Startup OneWire sensors.begin(); + // requestTemperatures() will not block current thread + sensors.setWaitForConversion(false); // Startup and initialize MySensors library. Set callback for incoming messages. gw.begin(); @@ -44,7 +46,12 @@ void loop() gw.process(); // Fetch temperatures from Dallas sensors - sensors.requestTemperatures(); + sensors.requestTemperatures(); + + // query conversion time and sleep until conversion completed + int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution()); + // sleep() call can be replaced by wait() call if node need to process incoming messages (or if node is repeater) + gw.sleep(conversionTime); // Read temperatures and send them to controller for (int i=0; i Date: Sat, 4 Jul 2015 18:17:09 -0600 Subject: [PATCH 41/79] Example sketch for PWF Lightning Sensor --- .../LightningSensor/LightningSensor.ino | 121 +++++ .../PWF_Lightning_Sensor.txt | 10 + .../PWFusion_AS3935.cpp | 421 ++++++++++++++++++ .../PWFusion_AS3935.h | 96 ++++ 4 files changed, 648 insertions(+) create mode 100644 libraries/MySensors/examples/LightningSensor/LightningSensor.ino create mode 100644 libraries/PWF_AS3935_Lightning_Sensor/PWF_Lightning_Sensor.txt create mode 100644 libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.cpp create mode 100644 libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.h diff --git a/libraries/MySensors/examples/LightningSensor/LightningSensor.ino b/libraries/MySensors/examples/LightningSensor/LightningSensor.ino new file mode 100644 index 0000000..8d2bace --- /dev/null +++ b/libraries/MySensors/examples/LightningSensor/LightningSensor.ino @@ -0,0 +1,121 @@ +// This sketch is to integrate the Playing With Fusion AXS3935 Lightning Sensor Breakout Board +// with the MySensors environment and is based on a sketch provided by Playing With Fusion +// http://playingwithfusion.com/productview.php?pdid=22&catid=1001 +// +#include "MySensor.h" +// the lightning sensor can communicate via SPI or I2C. This sketch uses the SPI interface +#include "SPI.h" +// include Playing With Fusion AXS3935 libraries +#include "PWFusion_AS3935.h" + +// setup CS pins used for the connection with the lightning sensor +// other connections are controlled by the SPI library) +int8_t CS_PIN = 8; +int8_t SI_PIN = 7; +int8_t IRQ_PIN = 3; +volatile int8_t AS3935_ISR_Trig = 0; + +// #defines +#define AS3935_INDOORS 1 +#define AS3935_OUTDOORS 0 +#define AS3935_DIST_DIS 0 +#define AS3935_DIST_EN 1 +#define AS3935_CAPACITANCE 96 // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD +// prototypes +void AS3935_ISR(); + +PWF_AS3935 lightning0(CS_PIN, IRQ_PIN, SI_PIN); + +#define CHILD_ID_DISTANCE 1 +#define CHILD_ID_INTENSITY 2 +MySensor gw; +MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE); +MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1); + +void setup() +{ + gw.begin(); + + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("Lightning Sensor", "1.1"); + + // Register all sensors to gw (they will be created as child devices) + gw.present(CHILD_ID_DISTANCE, S_DISTANCE); + gw.present(CHILD_ID_INTENSITY, S_CUSTOM); + boolean metric = gw.getConfig().isMetric; + + Serial.begin(115200); + Serial.println("Playing With Fusion: AS3935 Lightning Sensor, SEN-39001"); + Serial.println("beginning boot procedure...."); + + // setup for the the SPI library: + SPI.begin(); // begin SPI + SPI.setClockDivider(SPI_CLOCK_DIV4); // SPI speed to SPI_CLOCK_DIV16/1MHz (max 2MHz, NEVER 500kHz!) + SPI.setDataMode(SPI_MODE1); // MAX31855 is a Mode 1 device + // --> clock starts low, read on rising edge + SPI.setBitOrder(MSBFIRST); // data sent to chip MSb first + + lightning0.AS3935_DefInit(); // set registers to default + // now update sensor cal for your application and power up chip + lightning0.AS3935_ManualCal(AS3935_CAPACITANCE, AS3935_OUTDOORS, AS3935_DIST_EN); + // AS3935_ManualCal Parameters: + // --> capacitance, in pF (marked on package) + // --> indoors/outdoors (AS3935_INDOORS:0 / AS3935_OUTDOORS:1) + // --> disturbers (AS3935_DIST_EN:1 / AS3935_DIST_DIS:2) + // function also powers up the chip + + // enable interrupt (hook IRQ pin to Arduino Uno/Mega interrupt input: 1 -> pin 3 ) + attachInterrupt(1, AS3935_ISR, RISING); + // dump the registry data to the serial port for troubleshooting purposes + lightning0.AS3935_PrintAllRegs(); + + // delay execution to allow chip to stabilize. + delay(1000); + +} + +void loop() +{ + + // This program only handles an AS3935 lightning sensor. It does nothing until + // an interrupt is detected on the IRQ pin. + while(0 == AS3935_ISR_Trig){} + + // reset interrupt flag + AS3935_ISR_Trig = 0; + + // now get interrupt source + uint8_t int_src = lightning0.AS3935_GetInterruptSrc(); + if(0 == int_src) + { + Serial.println("Unknown interrupt source"); + } + else if(1 == int_src) + { + uint8_t lightning_dist_km = lightning0.AS3935_GetLightningDistKm(); + uint32_t lightning_intensity = lightning0.AS3935_GetStrikeEnergyRaw(); + + Serial.print("Lightning detected! Distance to strike: "); + Serial.print(lightning_dist_km); + Serial.println(" kilometers"); + Serial.print("Lightning detected! Lightning Intensity: "); + Serial.println(lightning_intensity); + gw.send(msgDist.set(lightning_dist_km)); + gw.send(msgInt.set(lightning_intensity)); + } + else if(2 == int_src) + { + Serial.println("Disturber detected"); + } + else if(3 == int_src) + { + Serial.println("Noise level too high"); + } +} + +// this is irq handler for AS3935 interrupts, has to return void and take no arguments +// always make code in interrupt handlers fast and short +void AS3935_ISR() +{ + AS3935_ISR_Trig = 1; +} \ No newline at end of file diff --git a/libraries/PWF_AS3935_Lightning_Sensor/PWF_Lightning_Sensor.txt b/libraries/PWF_AS3935_Lightning_Sensor/PWF_Lightning_Sensor.txt new file mode 100644 index 0000000..ed26e7e --- /dev/null +++ b/libraries/PWF_AS3935_Lightning_Sensor/PWF_Lightning_Sensor.txt @@ -0,0 +1,10 @@ +Notes from AS3935 datasheet: +Register Map: Page 11, detailed version on Page 12 + +Max clock freq for SPI = 2MHz + +SPI command Structure: Page14 +To activate this SPI, the CS has to be set to low. A SPI command consists of two bytes serial command and the data are sampled on the falling +edge of SCLK (CPHA=1). The next table shows command structure, from the MSB (B15) to LSB (B0). The command stream has to be sent to +the SPI from the MSB (B15) to the LSB (B0). + diff --git a/libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.cpp b/libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.cpp new file mode 100644 index 0000000..1d2b8a0 --- /dev/null +++ b/libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.cpp @@ -0,0 +1,421 @@ +/*************************************************************************** +* File Name: PWFusion_AS3935.h +* Processor/Platform: Arduino Uno R3 (tested) +* Development Environment: Arduino 1.0.5 +* +* Designed for use with with Playing With Fusion AS3935 Lightning Sensor +* Breakout: SEN-39001. +* +* SEN-39001 (universal applications) +* ---> http://www.playingwithfusion.com/productview.php?pdid=22 +* +* Copyright © 2014 Playing With Fusion, Inc. +* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License. +* +* 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. +* ************************************************************************** +* REVISION HISTORY: +* Author Date Comments +* J. Steinlage 2014Aug20 Original version +* +* Playing With Fusion, Inc. invests time and resources developing open-source +* code. Please support Playing With Fusion and continued open-source +* development by buying products from Playing With Fusion! +* +* ************************************************************************** +* ADDITIONAL NOTES: +* This file contains functions to interface with the AS3935 Franklin +* Lightning Sensor manufactured by AMS. Originally designed for application +* on the Arduino Uno platform. +**************************************************************************/ +#include "PWFusion_AS3935.h" + +PWF_AS3935::PWF_AS3935(int8_t CSx, int8_t IRQx, int8_t SIx) +{ + _cs = CSx; + _si = SIx; + _irq = IRQx; + + // initalize the chip select pins + pinMode(_cs, OUTPUT); + pinMode(_si, OUTPUT); + pinMode(_irq, INPUT); + + digitalWrite(_cs, HIGH); // set pin high to initialize/clear SPI bus + digitalWrite(_si, LOW); // set pin low for SPI mode + +} + +uint8_t PWF_AS3935::_sing_reg_read(uint8_t RegAdd) +{ + digitalWrite(_cs, LOW); // set pin low to start talking to IC + // next pack command byte, send AS3935.... structure is shown below + // MODE Register Address/Direct Cmd + // B15-14 B13------------------8 + // 15 is always 0; B14, 0: Write/Direct Command, 1: Read + SPI.transfer((RegAdd & 0x3F) | 0x40); // simple write, nothing to read back + uint8_t RegData = SPI.transfer(0x00); // read register data from IC + digitalWrite(_cs, HIGH); // set pin high to end SPI session + + return RegData; +} + +void PWF_AS3935::_sing_reg_write(uint8_t RegAdd, uint8_t DataMask, uint8_t RegData) +{ + // start by reading original register data (only modifying what we need to) + uint8_t OrigRegData = _sing_reg_read(RegAdd); + + // calculate new register data... 'delete' old targeted data, replace with new data + // note: 'DataMask' must be bits targeted for replacement + // add'l note: this function does NOT shift values into the proper place... they need to be there already + uint8_t NewRegData = ((OrigRegData & ~DataMask) | (RegData & DataMask)); + + // now configure and write the updated register value + digitalWrite(_cs, LOW); // set pin low to start talking to IC + // next pack command byte, send AS3935.... structure is shown below + // MODE Register Address/Direct Cmd + // B15-14 B13------------------8 + // 15 is always 0; B14, 0: Write/Direct Command, 1: Read + SPI.transfer((RegAdd & 0x3F)); // simple write, nothing to read back + SPI.transfer(RegData); // write register data to IC + digitalWrite(_cs, HIGH); // set pin high to end SPI session +} + +void PWF_AS3935::AS3935_DefInit() +{ + _AS3935_Reset(); // reset registers to default +} + +void PWF_AS3935::_AS3935_Reset() +{ + // run PRESET_DEFAULT Direct Command to set all registers in default state + digitalWrite(_cs, LOW); // begin transfer + SPI.transfer(0x3C); // send first byte (write, PRESET_DEFAULT register) + SPI.transfer(0x96); // send second byte (direct command) + digitalWrite(_cs, HIGH); // end transfer + delay(2); // wait 2ms to complete +} + +void PWF_AS3935::_CalRCO() +{ + // run ALIB_RCO Direct Command to cal internal RCO + digitalWrite(_cs, LOW); // begin transfer + SPI.transfer(0x3D); // send first byte (write, CALIB_RCO register) + SPI.transfer(0x96); // send second byte (direct command) + digitalWrite(_cs, HIGH); // end transfer + delay(3); // wait 3ms to complete +} + +void PWF_AS3935::AS3935_PowerUp(void) +{ + // power-up sequence based on datasheet, pg 23/27 + // register 0x00, PWD bit: 0 (clears PWD) + _sing_reg_write(0x00, 0x01, 0x00); + _CalRCO(); // run RCO cal cmd + _sing_reg_write(0x08, 0x20, 0x20); // set DISP_SRCO to 1 + delay(2); + _sing_reg_write(0x08, 0x20, 0x00); // set DISP_SRCO to 0 + +} + +void PWF_AS3935::AS3935_PowerDown(void) +{ + // register 0x00, PWD bit: 0 (sets PWD) + _sing_reg_write(0x00, 0x01, 0x01); + Serial.println("AS3935 powered down"); +} + +void PWF_AS3935::AS3935_DisturberEn(void) +{ + // register 0x03, PWD bit: 5 (sets MASK_DIST) + _sing_reg_write(0x03, 0x20, 0x00); + Serial.println("disturber detection enabled"); +} + +void PWF_AS3935::AS3935_DisturberDis(void) +{ + // register 0x03, PWD bit: 5 (sets MASK_DIST) + _sing_reg_write(0x03, 0x20, 0x20); +} + +void PWF_AS3935::AS3935_SetIRQ_Output_Source(uint8_t irq_select) +{ + // set interrupt source - what to displlay on IRQ pin + // reg 0x08, bits 5 (TRCO), 6 (SRCO), 7 (LCO) + // only one should be set at once, I think + // 0 = NONE, 1 = TRCO, 2 = SRCO, 3 = LCO + + if(1 == irq_select) + { + _sing_reg_write(0x08, 0xE0, 0x20); // set only TRCO bit + } + else if(2 == irq_select) + { + _sing_reg_write(0x08, 0xE0, 0x40); // set only SRCO bit + } + else if(3 == irq_select) + { + _sing_reg_write(0x08, 0xE0, 0x80); // set only LCO bit + } + else // assume 0 + { + _sing_reg_write(0x08, 0xE0, 0x00); // clear IRQ pin display bits + } + +} + +void PWF_AS3935::AS3935_SetTuningCaps(uint8_t cap_val) +{ + // Assume only numbers divisible by 8 (because that's all the chip supports) + if(120 < cap_val) // cap_value out of range, assume highest capacitance + { + _sing_reg_write(0x08, 0x0F, 0x0F); // set capacitance bits to maximum + } + else + { + _sing_reg_write(0x08, 0x0F, (cap_val>>3)); // set capacitance bits + } + Serial.print("capacitance set to 8x"); + Serial.println((_sing_reg_read(0x08) & 0x0F)); +} + +uint8_t PWF_AS3935::AS3935_GetInterruptSrc(void) +{ + // definition of interrupt data on table 18 of datasheet + // for this function: + // 0 = unknown src, 1 = lightning detected, 2 = disturber, 3 = Noise level too high + delay(10); // wait 10ms before reading (2ms per pg 22 of datasheet) + uint8_t int_src = (_sing_reg_read(0x03) & 0x0F); // read register, get rid of non-interrupt data + if(0x08 == int_src) + { + return 1; // lightning caused interrupt + } + else if(0x04 == int_src) + { + return 2; // disturber detected + } + else if(0x01 == int_src) + { + return 3; // Noise level too high + } + else{return 0;} // interrupt result not expected + +} + +uint8_t PWF_AS3935::AS3935_GetLightningDistKm(void) +{ + uint8_t strike_dist = (_sing_reg_read(0x07) & 0x3F); // read register, get rid of non-distance data + return strike_dist; +} + +uint32_t PWF_AS3935::AS3935_GetStrikeEnergyRaw(void) +{ + uint32_t nrgy_raw = ((_sing_reg_read(0x06) & 0x1F) << 8); // MMSB, shift 8 bits left, make room for MSB + nrgy_raw |= _sing_reg_read(0x05); // read MSB + nrgy_raw <= 8; // shift 8 bits left, make room for LSB + nrgy_raw |= _sing_reg_read(0x04); // read LSB, add to others + + return nrgy_raw; +} + +uint8_t PWF_AS3935::AS3935_SetMinStrikes(uint8_t min_strk) +{ + // This function sets min strikes to the closest available number, rounding to the floor, + // where necessary, then returns the physical value that was set. Options are 1, 5, 9 or 16 strikes. + // see pg 22 of the datasheet for more info (#strikes in 17 min) + if(5 > min_strk) + { + _sing_reg_write(0x02, 0x30, 0x00); + return 1; + } + else if(9 > min_strk) + { + _sing_reg_write(0x02, 0x30, 0x10); + return 5; + } + else if(16 > min_strk) + { + _sing_reg_write(0x02, 0x30, 0x20); + return 9; + } + else + { + _sing_reg_write(0x02, 0x30, 0x30); + return 16; + } +} + +void PWF_AS3935::AS3935_SetIndoors(void) +{ + // AFE settings addres 0x00, bits 5:1 (10010, based on datasheet, pg 19, table 15) + // this is the default setting at power-up (AS3935 datasheet, table 9) + _sing_reg_write(0x00, 0x3E, 0x24); + Serial.println("set up for indoor operation"); +} + +void PWF_AS3935::AS3935_SetOutdoors(void) +{ + // AFE settings addres 0x00, bits 5:1 (01110, based on datasheet, pg 19, table 15) + _sing_reg_write(0x00, 0x3E, 0x1C); + Serial.println("set up for outdoor operation"); +} + +void PWF_AS3935::AS3935_ClearStatistics(void) +{ + // clear is accomplished by toggling CL_STAT bit 'high-low-high' (then set low to move on) + _sing_reg_write(0x02, 0x40, 0x40); // high + _sing_reg_write(0x02, 0x40, 0x00); // low + _sing_reg_write(0x02, 0x40, 0x40); // high +} + +uint8_t PWF_AS3935::AS3935_GetNoiseFloorLvl(void) +{ + // NF settings addres 0x01, bits 6:4 + // default setting of 010 at startup (datasheet, table 9) + uint8_t reg_raw = _sing_reg_read(0x01); // read register 0x01 + return ((reg_raw & 0x70)>>4); // should return value from 0-7, see table 16 for info +} + +void PWF_AS3935::AS3935_SetNoiseFloorLvl(uint8_t nf_sel) +{ + // NF settings addres 0x01, bits 6:4 + // default setting of 010 at startup (datasheet, table 9) + if(7 >= nf_sel) // nf_sel within expected range + { + _sing_reg_write(0x01, 0x70, ((nf_sel & 0x07)<<4)); + } + else + { // out of range, set to default (power-up value 010) + _sing_reg_write(0x01, 0x70, 0x20); + } +} + +uint8_t PWF_AS3935::AS3935_GetWatchdogThreshold(void) +{ + // This function is used to read WDTH. It is used to increase robustness to disturbers, + // though will make detection less efficient (see page 19, Fig 20 of datasheet) + // WDTH register: add 0x01, bits 3:0 + // default value of 0001 + // values should only be between 0x00 and 0x0F (0 and 7) + uint8_t reg_raw = _sing_reg_read(0x01); + return (reg_raw & 0x0F); +} + +void PWF_AS3935::AS3935_SetWatchdogThreshold(uint8_t wdth) +{ + // This function is used to modify WDTH. It is used to increase robustness to disturbers, + // though will make detection less efficient (see page 19, Fig 20 of datasheet) + // WDTH register: add 0x01, bits 3:0 + // default value of 0001 + // values should only be between 0x00 and 0x0F (0 and 7) + _sing_reg_write(0x01, 0x0F, (wdth & 0x0F)); +} + +uint8_t PWF_AS3935::AS3935_GetSpikeRejection(void) +{ + // This function is used to read SREJ (spike rejection). Similar to the Watchdog threshold, + // it is used to make the system more robust to disturbers, though will make general detection + // less efficient (see page 20-21, especially Fig 21 of datasheet) + // SREJ register: add 0x02, bits 3:0 + // default value of 0010 + // values should only be between 0x00 and 0x0F (0 and 7) + uint8_t reg_raw = _sing_reg_read(0x02); + return (reg_raw & 0x0F); +} + +void PWF_AS3935::AS3935_SetSpikeRejection(uint8_t srej) +{ + // This function is used to modify SREJ (spike rejection). Similar to the Watchdog threshold, + // it is used to make the system more robust to disturbers, though will make general detection + // less efficient (see page 20-21, especially Fig 21 of datasheet) + // WDTH register: add 0x02, bits 3:0 + // default value of 0010 + // values should only be between 0x00 and 0x0F (0 and 7) + _sing_reg_write(0x02, 0x0F, (srej & 0x0F)); +} + +void PWF_AS3935::AS3935_SetLCO_FDIV(uint8_t fdiv) +{ + // This function sets LCO_FDIV register. This is useful in the tuning of the antenna + // LCO_FDIV register: add 0x03, bits 7:6 + // default value: 00 + // set 0, 1, 2 or 3 for ratios of 16, 32, 64 and 128, respectively. + // See pg 23, Table 20 for more info. + _sing_reg_write(0x03, 0xC0, ((fdiv & 0x03) << 5)); +} + +void PWF_AS3935::AS3935_PrintAllRegs(void) +{ + Serial.print("Reg 0x00: "); + Serial.println(_sing_reg_read(0x00)); + Serial.print("Reg 0x01: "); + Serial.println(_sing_reg_read(0x01)); + Serial.print("Reg 0x02: "); + Serial.println(_sing_reg_read(0x02)); + Serial.print("Reg 0x03: "); + Serial.println(_sing_reg_read(0x03)); + Serial.print("Reg 0x04: "); + Serial.println(_sing_reg_read(0x04)); + Serial.print("Reg 0x05: "); + Serial.println(_sing_reg_read(0x05)); + Serial.print("Reg 0x06: "); + Serial.println(_sing_reg_read(0x06)); + Serial.print("Reg 0x07: "); + Serial.println(_sing_reg_read(0x07)); + Serial.print("Reg 0x08: "); + Serial.println(_sing_reg_read(0x08)); + uint32_t nrgy_val = AS3935_GetStrikeEnergyRaw(); + Serial.println(nrgy_val); +} + +void PWF_AS3935::AS3935_ManualCal(uint8_t capacitance, uint8_t location, uint8_t disturber) +{ + // start by powering up + AS3935_PowerUp(); + + // indoors/outdoors next... + if(1 == location) // set outdoors if 1 + { + AS3935_SetOutdoors(); + } + else // set indoors if anything but 1 + { + AS3935_SetIndoors(); + } + + // disturber cal + if(0 == disturber) // disabled if 0 + { + AS3935_DisturberDis(); + } + else // enabled if anything but 0 + { + AS3935_DisturberEn(); + } + + AS3935_SetIRQ_Output_Source(0); + + delay(500); + // capacitance first... directly write value here + AS3935_SetTuningCaps(capacitance); + + Serial.println("AS3935 manual cal complete"); +} +// a nice function would be to read the last 'x' strike data values.... + diff --git a/libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.h b/libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.h new file mode 100644 index 0000000..4f62f07 --- /dev/null +++ b/libraries/PWF_AS3935_Lightning_Sensor/PWFusion_AS3935.h @@ -0,0 +1,96 @@ +/*************************************************************************** +* File Name: PWFusion_AS3935.h +* Processor/Platform: Arduino Uno R3 (tested) +* Development Environment: Arduino 1.0.5 +* +* Designed for use with with Playing With Fusion AS3935 Lightning Sensor +* Breakout: SEN-39001. +* +* SEN-39001 (universal applications) +* ---> http://www.playingwithfusion.com/productview.php?pdid=22 +* +* Copyright © 2014 Playing With Fusion, Inc. +* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License. +* +* 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. +* ************************************************************************** +* REVISION HISTORY: +* Author Date Comments +* J. Steinlage 2014Aug20 Original version +* +* Playing With Fusion, Inc. invests time and resources developing open-source +* code. Please support Playing With Fusion and continued open-source +* development by buying products from Playing With Fusion! +* +* ************************************************************************** +* ADDITIONAL NOTES: +* This file contains functions to interface with the AS3935 Franklin +* Lightning Sensor manufactured by AMS. Originally designed for application +* on the Arduino Uno platform. +**************************************************************************/ +#ifndef PWF_AS3935_h +#define PWF_AS3935_h + +#include "Arduino.h" +#include "avr/pgmspace.h" +#include "util/delay.h" +#include "stdlib.h" +#include "SPI.h" + +class PWF_AS3935 +{ + public: + PWF_AS3935(int8_t CSx, int8_t IRQx, int8_t SIx); + void AS3935_ManualCal(uint8_t capacitance, uint8_t location, uint8_t disturber); + void AS3935_DefInit(void); + void AS3935_PowerUp(void); + void AS3935_PowerDown(void); + void AS3935_DisturberEn(void); + void AS3935_DisturberDis(void); + void AS3935_SetIRQ_Output_Source(uint8_t irq_select); + void AS3935_SetTuningCaps(uint8_t cap_val); + uint8_t AS3935_GetInterruptSrc(void); + uint8_t AS3935_GetLightningDistKm(void); + uint32_t AS3935_GetStrikeEnergyRaw(void); + uint8_t AS3935_SetMinStrikes(uint8_t min_strk); + void AS3935_ClearStatistics(void); + void AS3935_SetIndoors(void); + void AS3935_SetOutdoors(void); + uint8_t AS3935_GetNoiseFloorLvl(void); + void AS3935_SetNoiseFloorLvl(uint8_t nf_sel); + uint8_t AS3935_GetWatchdogThreshold(void); + void AS3935_SetWatchdogThreshold(uint8_t wdth); + uint8_t AS3935_GetSpikeRejection(void); + void AS3935_SetSpikeRejection(uint8_t srej); + void AS3935_SetLCO_FDIV(uint8_t fdiv); + void AS3935_PrintAllRegs(void); + + private: + int8_t _cs, _irq, _si; + uint8_t _sing_reg_read(uint8_t RegAdd); + void _sing_reg_write(uint8_t RegAdd, uint8_t DataMask, uint8_t RegData); + void _AS3935_Reset(void); + void _CalRCO(void); +}; + +#endif + + + + From 2665e93c5319828166eddf6eff1424d9f762a673 Mon Sep 17 00:00:00 2001 From: petewill Date: Mon, 6 Jul 2015 07:14:37 -0600 Subject: [PATCH 42/79] Rain Gauge Uploading initial rain gauge code and Vera files --- .../examples/RainGauge/D_RainSensor1.json | 523 +++++++++++++++ .../examples/RainGauge/D_RainSensor1.xml | 24 + .../examples/RainGauge/RainGauge.ino | 594 ++++++++++++++++++ .../examples/RainGauge/S_Rainsensor1.xml | 43 ++ 4 files changed, 1184 insertions(+) create mode 100644 libraries/MySensors/examples/RainGauge/D_RainSensor1.json create mode 100644 libraries/MySensors/examples/RainGauge/D_RainSensor1.xml create mode 100644 libraries/MySensors/examples/RainGauge/RainGauge.ino create mode 100644 libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml diff --git a/libraries/MySensors/examples/RainGauge/D_RainSensor1.json b/libraries/MySensors/examples/RainGauge/D_RainSensor1.json new file mode 100644 index 0000000..325391b --- /dev/null +++ b/libraries/MySensors/examples/RainGauge/D_RainSensor1.json @@ -0,0 +1,523 @@ +{ + "flashicon": "icons/Humidity_Sensor.swf", + "imgIconBody": "", + "imgIconDimmable": "", + "imgIconTurnable": "", + "imgIconMin": "", + "imgIconMax": "", + "halloIconsDir": "pics\/hallo", + "inScene": "0", + "DisplayStatus": {}, + "doc_url": { + "doc_language": 1, + "doc_manual": 1, + "doc_version": 1, + "doc_platform": 0, + "doc_page": "sensors" + }, + + "Tabs": [ + { + "Label": { + "lang_tag": "tabname_control", + "text": "Information" + }, + "Position": "0", + "TabType": "flash", + "SceneGroup": [ + { + "id": "1", + "top": "1.5", + "left": "0", + "x": "2", + "y": "2" + } + ], + "ControlGroup": [ + { + "id": "1", + "scenegroup": "1", + "type": "info" + }, + { + "id": "2", + "scenegroup": "1", + "type": "info" + } + ], + "Control": [ + { + "ControlGroup":"1", + "ControlPair": "1", + "ControlHeader": "1", + "top": "1", + "left": "0", + "x": "1.25", + "ControlType": "label", + "Label": { + "lang_tag": "rain_rate", + "text": "Rate of Rain" + }, + "Display": { + "Top": 20, + "Left": 50, + "Width": 75, + "Height": 20 + } + }, + { + "ControlGroup":"1", + "ControlPair": "1", + "ControlHeader": "1", + "top": "1", + "left": "1.25", + "x": "0.75", + "ControlType": "variable", + "Display": { + "Service": "urn:upnp-org:serviceId:RainSensor1", + "Variable": "CurrentRain", + "Top": 20, + "Left": 150, + "Width": 25, + "Height": 20 + } + }, + { + "ControlType": "label", + "Label": { + "lang_tag": "total_rain_unit", + "text": "mm/hr" + }, + "Display": { + "Top": 20, + "Left": 200, + "Width": 25, + "Height": 20 + } + }, + { + "ControlGroup":"2", + "ControlPair": "2", + "ControlHeader": "1", + "top": "0", + "left": "0", + "x": "1.25", + "ControlType": "label", + "Label": { + "lang_tag": "total_rain", + "text": "Rain Today:", + }, + "Display": { + "Top": 55, + "Left": 50, + "Width": 75, + "Height": 20 + } + }, + { + "ControlGroup":"2", + "ControlPair": "2", + "ControlHeader": "1", + "top": "0", + "left": "1.25", + "x": "0.75", + "ControlType": "variable", + "Display": { + "Service": "urn:upnp-org:serviceId:RainSensor1", + "Variable": "CurrentTRain", + "Top": 55, + "Left": 150, + "Width": 25, + "Height": 20 + } + }, + { + "ControlType": "label", + "Label": { + "lang_tag": "rain_rate_unit", + "text": "mm" + }, + "Display": { + "Top": 55, + "Left": 200, + "Width": 25, + "Height": 20 + } + }, + { + "ControlGroup":"3", + "ControlPair": "3", + "ControlHeader": "1", + "top": "0", + "left": "0", + "x": "1.25", + "ControlType": "label", + "Label": { + "lang_tag": "rain_forty", + "text": "Yesterday:" + }, + "Display": { + "Top": 80, + "Left": 50, + "Width": 75, + "Height": 20 + } + }, + { + "ControlGroup":"3", + "ControlPair": "3", + "ControlHeader": "1", + "top": "0", + "left": "1.25", + "x": "0.75", + "ControlType": "variable", + "Display": { + "Service": "urn:upnp-org:serviceId:VContainer1", + "Variable": "Variable2", + "Top": 80, + "Left": 150, + "Width": 25, + "Height": 20 + } + }, + { + "ControlType": "label", + "Label": { + "lang_tag": "rain_unit", + "text": "mm" + }, + "Display": { + "Top": 80, + "Left": 200, + "Width": 25, + "Height": 20 + } + }, + { + "ControlGroup":"4", + "ControlPair": "4", + "ControlHeader": "1", + "top": "0", + "left": "0", + "x": "1.25", + "ControlType": "label", + "Label": { + "lang_tag": "rain_seventy", + "text": "3 Days Ago:" + }, + "Display": { + "Top": 105, + "Left": 50, + "Width": 75, + "Height": 20 + } + }, + { + "ControlGroup":"4", + "ControlPair": "4", + "ControlHeader": "1", + "top": "0", + "left": "1.25", + "x": "0.75", + "ControlType": "variable", + "Display": { + "Service": "urn:upnp-org:serviceId:VContainer1", + "Variable": "Variable3", + "Top": 105, + "Left": 150, + "Width": 25, + "Height": 20 + } + }, + { + "ControlType": "label", + "Label": { + "lang_tag": "rain_unit1", + "text": "mm" + }, + "Display": { + "Top": 105, + "Left": 200, + "Width": 25, + "Height": 20 + } + }, + { + "ControlGroup":"5", + "ControlPair": "5", + "ControlHeader": "1", + "top": "0", + "left": "0", + "x": "1.25", + "ControlType": "label", + "Label": { + "lang_tag": "rain_forty", + "text": "4 Days Ago:" + }, + "Display": { + "Top": 130, + "Left": 50, + "Width": 75, + "Height": 20 + } + }, + { + "ControlGroup":"5", + "ControlPair": "5", + "ControlHeader": "1", + "top": "0", + "left": "1.25", + "x": "0.75", + "ControlType": "variable", + "Display": { + "Service": "urn:upnp-org:serviceId:VContainer1", + "Variable": "Variable4", + "Top": 130, + "Left": 150, + "Width": 25, + "Height": 20 + } + }, + { + "ControlType": "label", + "Label": { + "lang_tag": "rain_unit2", + "text": "mm" + }, + "Display": { + "Top": 130, + "Left": 200, + "Width": 25, + "Height": 20 + } + }, + { + "ControlGroup":"6", + "ControlPair": "6", + "ControlHeader": "1", + "top": "0", + "left": "0", + "x": "1.25", + "ControlType": "label", + "Label": { + "lang_tag": "rain_hundred", + "text": "5 Days Ago:" + }, + "Display": { + "Top": 155, + "Left": 50, + "Width": 75, + "Height": 20 + } + }, + { + "ControlGroup":"6", + "ControlPair": "6", + "ControlHeader": "1", + "top": "0", + "left": "1.25", + "x": "0.75", + "ControlType": "variable", + "Display": { + "Service": "urn:upnp-org:serviceId:VContainer1", + "Variable": "Variable5", + "Top": 155, + "Left": 150, + "Width": 25, + "Height": 20 + } + }, + { + "ControlType": "label", + "Label": { + "lang_tag": "rain_unit3", + "text": "mm" + }, + "Display": { + "Top": 155, + "Left": 200, + "Width": 25, + "Height": 20 + } + } + ] + }, + { + "Label": { + "lang_tag": "advanced", + "text": "Advanced" + }, + "Position": "1", + "TabType": "javascript", + "ScriptName": "shared.js", + "Function": "advanced_device" + }, + { + "Label": { + "lang_tag": "logs", + "text": "Logs" + }, + "Position": "2", + "TabType": "javascript", + "ScriptName": "shared.js", + "Function": "device_logs" + }, + { + "Label": { + "lang_tag": "notifications", + "text": "Notifications" + }, + "Position": "3", + "TabType": "javascript", + "ScriptName": "shared.js", + "Function": "device_notifications" + } + ], + "eventList2": [ + { + "id": 1, + "label": { + "lang_tag": "total_rain_goes_above", + "text": "Total rain goes above" + }, + "serviceId": "urn:upnp-org:serviceId:RainSensor1", + "norepeat": "1", + "argumentList": [ + { + "id": 1, + "dataType": "r8", + "name": "CurrentTRain", + "comparisson": ">", + "prefix": { + "lang_tag": "total_rain", + "text": "Total rain" + }, + "suffix": { + "lang_tag": "total_rain_unit", + "text": "mm" + }, + "HumanFriendlyText": { + "lang_tag": "hft_total_rain_goes_above", + "text": "Total rain for _DEVICE_NAME_ goes above _ARGUMENT_VALUE_" + } + } + ] + }, + { + "id": 2, + "label": { + "lang_tag": "total_rain_goes_below", + "text": "Total rain goes below" + }, + "serviceId": "urn:upnp-org:serviceId:RainSensor1", + "norepeat": "1", + "argumentList": [ + { + "id": 1, + "dataType": "r8", + "name": "CurrentTRain", + "comparisson": "<", + "prefix": { + "lang_tag": "total_rain", + "text": "Total rain" + }, + "suffix": { + "lang_tag": "total_rain_unit", + "text": "mm" + }, + "HumanFriendlyText": { + "lang_tag": "hft_total_rain_goes_below", + "text": "Total rain for _DEVICE_NAME_ goes below _ARGUMENT_VALUE_" + } + } + ] + }, + { + "id": 3, + "label": { + "lang_tag": "rain_rate_goes_above", + "text": "Current rain goes above" + }, + "serviceId": "urn:upnp-org:serviceId:RainSensor1", + "norepeat": "1", + "argumentList": [ + { + "id": 1, + "dataType": "r8", + "name": "CurrentRain", + "comparisson": ">", + "prefix": { + "lang_tag": "rain_rate", + "text": "Current rain" + }, + "suffix": { + "lang_tag": "rain_rate_unit", + "text": "mm/hr" + }, + "HumanFriendlyText": { + "lang_tag": "hft_rain_rate_goes_above", + "text": "Current rain for _DEVICE_NAME_ goes above _ARGUMENT_VALUE_" + } + } + ] + }, + { + "id": 4, + "label": { + "lang_tag": "rain_rate_goes_below", + "text": "Current rain goes below" + }, + "serviceId": "urn:upnp-org:serviceId:RainSensor1", + "norepeat": "1", + "argumentList": [ + { + "id": 1, + "dataType": "r8", + "name": "CurrentRain", + "comparisson": "<", + "prefix": { + "lang_tag": "rain_rate", + "text": "Current rain" + }, + "suffix": { + "lang_tag": "rain_rate_unit", + "text": "mm/hr" + }, + "HumanFriendlyText": { + "lang_tag": "hft_rain_rate_goes_below", + "text": "Current rain for _DEVICE_NAME_ goes below _ARGUMENT_VALUE_" + } + } + ] + }, + { + "id": 5, + "label": { + "lang_tag": "battery_level_goes_below", + "text": "Battery level goes below" + }, + "serviceId": "urn:micasaverde-com:serviceId:HaDevice1", + "argumentList": [ + { + "id": 1, + "prefix": { + "lang_tag": "Level", + "text": "Level" + }, + "dataType": "i4", + "name": "BatteryLevel", + "comparisson": "<", + "suffix": { + "lang_tag": "percent_sign", + "text": "%" + }, + "HumanFriendlyText": { + "lang_tag": "hft_battery_level_goes_below", + "text": "Battery level for _DEVICE_NAME_ go below _ARGUMENT_VALUE_%" + } + } + ] + } + ], + "DeviceType": "urn:schemas-micasaverde-com:device:RainSensor:1" +} \ No newline at end of file diff --git a/libraries/MySensors/examples/RainGauge/D_RainSensor1.xml b/libraries/MySensors/examples/RainGauge/D_RainSensor1.xml new file mode 100644 index 0000000..c0a7492 --- /dev/null +++ b/libraries/MySensors/examples/RainGauge/D_RainSensor1.xml @@ -0,0 +1,24 @@ + + + + 1 + 0 + + + urn:schemas-micasaverde-com:device:RainSensor:1 + 12 + D_RainSensor1.json + + + urn:schemas-upnp-org:service:RainSensor:1 + urn:upnp-org:serviceId:RainSensor1 + S_RainSensor1.xml + + + urn:schemas-micasaverde-com:service:HaDevice:1 + urn:micasaverde-com:serviceId:HaDevice1 + S_HaDevice1.xml + + + + \ No newline at end of file diff --git a/libraries/MySensors/examples/RainGauge/RainGauge.ino b/libraries/MySensors/examples/RainGauge/RainGauge.ino new file mode 100644 index 0000000..475eb0c --- /dev/null +++ b/libraries/MySensors/examples/RainGauge/RainGauge.ino @@ -0,0 +1,594 @@ +/* + Arduino Tipping Bucket Rain Gauge + + April 26, 2015 + + Version 1.4.1 alpha + + Arduino Tipping Bucket Rain Gauge + + Utilizing a tipping bucket sensor, your Vera home automation controller and the MySensors.org + gateway you can measure and sense local rain. This sketch will create two devices on your + Vera controller. One will display your total precipitation for the last 5 days. The other, + a sensor that changes state if there is recent rain (up to last 120 hours) above a threshold. + Both these settings are user definable. + + There is a build overview video here: https://youtu.be/1eMfKQaLROo + + This sketch features the following: + + * Allows you to set the rain threshold in mm + * Allows you to determine the tripped indicator window up to 120 hours. + * Displays the last 5 days of rain in Variable1 through Variable5 + of the Rain Sensor device + * Configuration changes to Sensor device updated every hour + * Should run on any Arduino + * Will retain Tripped/Not Tripped status and data in a power interruption, saving small amount + of data to EEPROM (Circular Buffer to maximize life of EEPROM) + * LED status indicator + * Optional Temp/Humidity (DHT-22 or DHT-11) and Light LUX (BH1750) sensors. To use, uncomment + #define DHT_ON and/or #define LUX_ON + * Optionally send total accumulation of each day's rainfall or send only individual days rainfall totals. + Comment out #define USE_DAILY to display individual daily rainfall. + + by @BulldogLowell and @PeteWill for free public use + + */ +#include +#include +#include +#include + +#define NODE_ID 24 //or AUTO to let controller assign +#define SKETCH_NAME "Rain Gauge" +#define SKETCH_VERSION "1.4.1a" + +#define DWELL_TIME 125 // this allows for radio to come back to power after a transmission, ideally 0 + +//#define DEBUG_ON // comment out this line to disable serial debug +#define DHT_ON // uncomment out this line to enable DHT sensor +#define LUX_ON // uncomment out this line to enable BH1750 sensor +//#define USE_DAILY // displays each time segment as an accumulation of prior periods inclusive. Comment out to display individual daily rainfall totals in the variables sent to your controller. + +#define CALIBRATE_FACTOR 60 // amount of rain per rain bucket tip e.g. 5 is .05mm +#define DHT_LUX_DELAY 300000 //Delay in milliseconds that the DHT and LUX sensors will wait before sending data + +#define CHILD_ID_RAIN_LOG 3 // Keeps track of accumulated rainfall +#define CHILD_ID_TRIPPED_INDICATOR 4 // Indicates Tripped when rain detected +#define EEPROM_BUFFER_LOCATION 0 // location of the EEPROM circular buffer +#define E_BUFFER_LENGTH 240 +#define RAIN_BUCKET_SIZE 120 + +#ifdef DEBUG_ON + #define DEBUG_PRINT(x) Serial.print(x) + #define DEBUG_PRINTLN(x) Serial.println(x) + #define SERIAL_START(x) Serial.begin(x) + #else + #define DEBUG_PRINT(x) + #define DEBUG_PRINTLN(x) + #define SERIAL_START(x) +#endif +// +MySensor gw; +// +MyMessage msgRainRate(CHILD_ID_RAIN_LOG, V_RAINRATE); +MyMessage msgRain(CHILD_ID_RAIN_LOG, V_RAIN); +// +MyMessage msgRainVAR1(CHILD_ID_RAIN_LOG, V_VAR1); +MyMessage msgRainVAR2(CHILD_ID_RAIN_LOG, V_VAR2); +MyMessage msgRainVAR3(CHILD_ID_RAIN_LOG, V_VAR3); +MyMessage msgRainVAR4(CHILD_ID_RAIN_LOG, V_VAR4); +MyMessage msgRainVAR5(CHILD_ID_RAIN_LOG, V_VAR5); +// +MyMessage msgTripped(CHILD_ID_TRIPPED_INDICATOR, V_TRIPPED); +MyMessage msgTrippedVar1(CHILD_ID_TRIPPED_INDICATOR, V_VAR1); +MyMessage msgTrippedVar2(CHILD_ID_TRIPPED_INDICATOR, V_VAR2); +// +#ifdef DHT_ON + #include + #define CHILD_ID_HUM 0 + #define CHILD_ID_TEMP 1 + #define HUMIDITY_SENSOR_DIGITAL_PIN 8 + DHT dht; + float lastTemp; + float lastHum; + boolean metric = true; + MyMessage msgHum(CHILD_ID_HUM, V_HUM); + MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); +#endif +// +#ifdef LUX_ON + //BH1750 is connected to SCL (analog input A5) and SDA (analog input A4) + #include + #include + #define CHILD_ID_LIGHT 2 + BH1750 lightSensor; + MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL); + unsigned int lastlux; + byte heartbeat = 10; //Used to send the light lux to gateway as soon as the device is restarted and after the DHT_LUX_DELAY has happened 10 times +#endif +unsigned long sensorPreviousMillis; +int eepromIndex; +int tipSensorPin = 3; // Pin the tipping bucket is connected to. Must be interrupt capable pin +int ledPin = 5; // Pin the LED is connected to. PWM capable pin required +unsigned long dataMillis; +unsigned long serialInterval = 600000UL; +const unsigned long oneHour = 3600000UL; +unsigned long lastTipTime; +unsigned long lastRainTime; //Used for rainRate calculation +unsigned int rainBucket [RAIN_BUCKET_SIZE] ; /* 24 hours x 5 Days = 120 hours */ +unsigned int rainRate = 0; +byte rainWindow = 72; //default rain window in hours. Will be overwritten with msgTrippedVar1. +volatile int wasTippedBuffer = 0; +int rainSensorThreshold = 50; //default rain sensor sensitivity in hundredths. Will be overwritten with msgTrippedVar2. +byte state = 0; +byte oldState = -1; +int lastRainRate = 0; +int lastMeasure = 0; +boolean gotTime = false; +byte lastHour; +byte currentHour; +// +void setup() +{ + SERIAL_START(115200); + // + // Set up the IO + pinMode(tipSensorPin, INPUT_PULLUP); + attachInterrupt (1, sensorTipped, FALLING); // depending on location of the hall effect sensor may need CHANGE + pinMode(ledPin, OUTPUT); + digitalWrite(ledPin, HIGH); + // + //Let's get the controller talking to the Arduino + gw.begin(getVariables, NODE_ID); + gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); + gw.wait(DWELL_TIME); + gw.present(CHILD_ID_RAIN_LOG, S_RAIN); + gw.wait(DWELL_TIME); + gw.present(CHILD_ID_TRIPPED_INDICATOR, S_MOTION); + gw.wait(DWELL_TIME); + DEBUG_PRINTLN(F("Sensor Presentation Complete")); + // + //Sync time with the server, this will be called hourly in order to keep time from creeping with the crystal + // + unsigned long functionTimeout = millis(); + while (timeStatus() == timeNotSet && millis() - functionTimeout < 30000UL) + { + gw.process(); + gw.requestTime(receiveTime); + DEBUG_PRINTLN(F("Getting Time")); + gw.wait(1000); // call once per second + DEBUG_PRINTLN(F(".")); + } + currentHour = hour(); + lastHour = hour(); + // + //retrieve from EEPROM stored values on a power cycle. + // + boolean isDataOnEeprom = false; + for (int i = 0; i < E_BUFFER_LENGTH; i++) + { + byte locator = gw.loadState(EEPROM_BUFFER_LOCATION + i); + if (locator == 0xFE) // found the EEPROM circular buffer index + { + eepromIndex = EEPROM_BUFFER_LOCATION + i; + DEBUG_PRINT(F("EEPROM Index ")); + DEBUG_PRINTLN(eepromIndex); + //Now that we have the buffer index let's populate the rainBucket[] with data from eeprom + loadRainArray(eepromIndex); + isDataOnEeprom = true; + break; + } + } + // + if (!isDataOnEeprom) // Added for the first time it is run on a new Arduino + { + DEBUG_PRINTLN(F("I didn't find valid EEPROM Index, so I'm writing one to location 0")); + eepromIndex = EEPROM_BUFFER_LOCATION; + gw.saveState(eepromIndex, 0xFE); + gw.saveState(eepromIndex + 1, 0xFE); + //then I will clear out any bad data + for (int i = 2; i <= E_BUFFER_LENGTH; i++) + { + gw.saveState(i, 0x00); + } + } + dataMillis = millis(); + lastTipTime = millis() - oneHour; //why is this -oneHour?? Doesn't millis() start at 0 when first powered on? + // + gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1); + gw.wait(DWELL_TIME); + gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2); + gw.wait(DWELL_TIME); + // +#ifdef DHT_ON + dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); + // Register all sensors to gw (they will be created as child devices) + gw.present(CHILD_ID_HUM, S_HUM); + gw.wait(DWELL_TIME); + gw.present(CHILD_ID_TEMP, S_TEMP); + gw.wait(DWELL_TIME); + metric = gw.getConfig().isMetric; + gw.wait(DWELL_TIME); +#endif + // +#ifdef LUX_ON + gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL); + gw.wait(DWELL_TIME); + lightSensor.begin(); +#endif + // + DEBUG_PRINTLN(F("Radio Setup Complete!")); + transmitRainData(); +} + +void loop() +{ + gw.process(); + if (state) + { + prettyFade(); // breathe if tripped + } + else + { + slowFlash(); // blink if not tripped + } +#ifdef DEBUG_ON // Serial Debug Block + if ( (millis() - dataMillis) >= serialInterval) + { + for (int i = 24; i <= 120; i = i + 24) + { + updateSerialData(i); + } + dataMillis = millis(); + } +#endif + // + // let's constantly check to see if the rain in the past rainWindow hours is greater than rainSensorThreshold + // + int measure = 0; // Check to see if we need to show sensor tripped in this block + for (int i = 0; i < rainWindow; i++) + { + measure += rainBucket [i]; + if (measure != lastMeasure) + { + // DEBUG_PRINT(F("measure value (total rainBucket within rainWindow): ")); + // DEBUG_PRINTLN(measure); + lastMeasure = measure; + } + } + // + state = (measure >= (rainSensorThreshold * 100)); + if (state != oldState) + { + gw.send(msgTripped.set(state)); + gw.wait(DWELL_TIME); + DEBUG_PRINT(F("New Sensor State... Sensor: ")); + DEBUG_PRINTLN(state ? "Tripped" : "Not Tripped"); + oldState = state; + } + // + unsigned long tipDelay = millis() - lastRainTime; + if (wasTippedBuffer) // if was tipped, then update the 24hour total and transmit to Vera + { + DEBUG_PRINTLN(F("Sensor Tipped")); + DEBUG_PRINT(F("rainBucket [0] value: ")); + DEBUG_PRINTLN(rainBucket [0]); + gw.send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); //Calculate the total rain for the day + gw.wait(DWELL_TIME); + wasTippedBuffer--; + rainRate = ((oneHour) / tipDelay); + if (rainRate != lastRainRate) + { + gw.send(msgRainRate.set(rainRate, 1)); + gw.wait(DWELL_TIME); + DEBUG_PRINT(F("RainRate= ")); + DEBUG_PRINTLN(rainRate); + lastRainRate = rainRate; + } + lastRainTime = lastTipTime; + } + // + currentHour = hour(); + if (currentHour != lastHour) + { + DEBUG_PRINTLN(F("One hour elapsed.")); + gw.send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); // send today's rainfall + gw.wait(DWELL_TIME); + gw.saveState(eepromIndex, highByte(rainBucket[0])); + gw.saveState(eepromIndex + 1, lowByte(rainBucket[0])); + DEBUG_PRINT(F("Saving rainBucket[0] to eeprom. rainBucket[0] = ")); + DEBUG_PRINTLN(rainBucket[0]); + for (int i = RAIN_BUCKET_SIZE - 1; i >= 0; i--)//cascade an hour of values back into the array + { + rainBucket [i + 1] = rainBucket [i]; + } + gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1); + gw.wait(DWELL_TIME); + gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2); + gw.wait(DWELL_TIME); + rainBucket[0] = 0; + eepromIndex = eepromIndex + 2; + if (eepromIndex > EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH) + { + eepromIndex = EEPROM_BUFFER_LOCATION; + } + DEBUG_PRINT(F("Writing to EEPROM. Index: ")); + DEBUG_PRINTLN(eepromIndex); + gw.saveState(eepromIndex, 0xFE); + gw.saveState(eepromIndex + 1, 0xFE); + gw.requestTime(receiveTime); // sync the time every hour + gw.wait(DWELL_TIME); + transmitRainData(); + rainRate = 0; + gw.send(msgRainRate.set(rainRate, 1)); + gw.wait(DWELL_TIME); + DEBUG_PRINTLN(F("Sending rainRate is 0 to controller")); + lastHour = currentHour; + } + if (millis() - sensorPreviousMillis > DHT_LUX_DELAY) + { + #ifdef DHT_ON //DHT Code + doDHT(); + #endif + #ifdef LUX_ON + doLUX(); + #endif + sensorPreviousMillis = millis(); + } +} +// +#ifdef DHT_ON +void doDHT(void) +{ + float temperature = dht.getTemperature(); + if (isnan(temperature)) + { + DEBUG_PRINTLN(F("Failed reading temperature from DHT")); + } else if (temperature != lastTemp) + { + lastTemp = temperature; + if (!metric) + { + temperature = dht.toFahrenheit(temperature); + } + gw.send(msgTemp.set(temperature, 1)); + gw.wait(DWELL_TIME); + DEBUG_PRINT(F("Temperature is: ")); + DEBUG_PRINTLN(temperature); + } + float humidity = dht.getHumidity();; + if (isnan(humidity)) + { + DEBUG_PRINTLN(F("Failed reading humidity from DHT")); + } else if (humidity != lastHum) + { + lastHum = humidity; + gw.send(msgHum.set(humidity, 1)); + gw.wait(DWELL_TIME); + DEBUG_PRINT(F("Humidity is: ")); + DEBUG_PRINTLN(humidity); + } +} +#endif +// +#ifdef LUX_ON +void doLUX(void) +{ + unsigned int lux = lightSensor.readLightLevel();// Get Lux value + DEBUG_PRINT(F("Current LUX Level: ")); + DEBUG_PRINTLN(lux); + heartbeat++; + if (lux != lastlux || heartbeat > 10) + { + gw.send(msg.set(lux)); + lastlux = lux; + } + if (heartbeat > 10) + { + heartbeat = 0; + } +} +#endif +// +void sensorTipped() +{ + unsigned long thisTipTime = millis(); + if (thisTipTime - lastTipTime > 100UL) + { + rainBucket[0] += CALIBRATE_FACTOR; // adds CALIBRATE_FACTOR hundredths of unit each tip + wasTippedBuffer++; + } + lastTipTime = thisTipTime; +} +// +int rainTotal(int hours) +{ + int total = 0; + for ( int i = 0; i <= hours; i++) + { + total += rainBucket [i]; + } + return total; +} + +void updateSerialData(int x) +{ + DEBUG_PRINT(F("Rain last ")); + DEBUG_PRINT(x); + DEBUG_PRINTLN(F(" hours: ")); + float tipCount = 0; + for (int i = 0; i < x; i++) + { + tipCount = tipCount + rainBucket [i]; + } + tipCount = tipCount / 100; + DEBUG_PRINTLN(tipCount); +} + +void loadRainArray(int value) // retrieve stored rain array from EEPROM on powerup +{ + for (int i = 0; i < RAIN_BUCKET_SIZE; i++) + { + value = value - 2; + if (value < EEPROM_BUFFER_LOCATION) + { + value = EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH; + } + DEBUG_PRINT(F("EEPROM location: ")); + DEBUG_PRINTLN(value); + byte rainValueHigh = gw.loadState(value); + byte rainValueLow = gw.loadState(value + 1); + unsigned int rainValue = rainValueHigh << 8; + rainValue |= rainValueLow; + rainBucket[i + 1] = rainValue; + // + DEBUG_PRINT(F("rainBucket[ value: ")); + DEBUG_PRINT(i + 1); + DEBUG_PRINT(F("] value: ")); + DEBUG_PRINTLN(rainBucket[i + 1]); + } +} + +void transmitRainData(void) +{ + DEBUG_PRINT(F("In transmitRainData. currentHour = ")); + DEBUG_PRINTLN(currentHour); + int rainUpdateTotal = 0; + for (int i = currentHour; i >= 0; i--) + { + rainUpdateTotal += rainBucket[i]; + DEBUG_PRINT(F("Adding rainBucket[")); + DEBUG_PRINT(i); + DEBUG_PRINTLN(F("] to rainUpdateTotal.")); + } + DEBUG_PRINT(F("TX Day 1: rainUpdateTotal = ")); + DEBUG_PRINTLN((float)rainUpdateTotal / 100.0); + gw.send(msgRainVAR1.set((float)rainUpdateTotal / 100.0, 1)); //Send current day rain totals (resets at midnight) + gw.wait(DWELL_TIME); +#ifdef USE_DAILY + rainUpdateTotal = 0; +#endif + for (int i = currentHour + 24; i > currentHour; i--) + { + rainUpdateTotal += rainBucket[i]; + DEBUG_PRINT(F("Adding rainBucket[")); + DEBUG_PRINT(i); + DEBUG_PRINTLN(F("] to rainUpdateTotal.")); + } + DEBUG_PRINT(F("TX Day 2: rainUpdateTotal = ")); + DEBUG_PRINTLN((float)rainUpdateTotal / 100.0); + gw.send(msgRainVAR2.set((float)rainUpdateTotal / 100.0, 1)); + gw.wait(DWELL_TIME); +#ifdef USE_DAILY + rainUpdateTotal = 0; +#endif + for (int i = currentHour + 48; i > currentHour + 24; i--) + { + rainUpdateTotal += rainBucket[i]; + DEBUG_PRINT(F("Adding rainBucket[")); + DEBUG_PRINT(i); + DEBUG_PRINTLN(F("] to rainUpdateTotal.")); + } + DEBUG_PRINT(F("TX Day 3: rainUpdateTotal = ")); + DEBUG_PRINTLN((float)rainUpdateTotal / 100.0); + gw.send(msgRainVAR3.set((float)rainUpdateTotal / 100.0, 1)); + gw.wait(DWELL_TIME); +#ifdef USE_DAILY + rainUpdateTotal = 0; +#endif + for (int i = currentHour + 72; i > currentHour + 48; i--) + { + rainUpdateTotal += rainBucket[i]; + DEBUG_PRINT(F("Adding rainBucket[")); + DEBUG_PRINT(i); + DEBUG_PRINTLN(F("] to rainUpdateTotal.")); + } + DEBUG_PRINT(F("TX Day 4: rainUpdateTotal = ")); + DEBUG_PRINTLN((float)rainUpdateTotal / 100.0); + gw.send(msgRainVAR4.set((float)rainUpdateTotal / 100.0, 1)); + gw.wait(DWELL_TIME); +#ifdef USE_DAILY + rainUpdateTotal = 0; +#endif + for (int i = currentHour + 96; i > currentHour + 72; i--) + { + rainUpdateTotal += rainBucket[i]; + DEBUG_PRINT(F("Adding rainBucket[")); + DEBUG_PRINT(i); + DEBUG_PRINTLN(F("] to rainUpdateTotal.")); + } + DEBUG_PRINT(F("TX Day 5: rainUpdateTotal = ")); + DEBUG_PRINTLN((float)rainUpdateTotal / 100.0); + gw.send(msgRainVAR5.set((float)rainUpdateTotal / 100.0, 1)); + gw.wait(DWELL_TIME); +} + +void getVariables(const MyMessage &message) +{ + if (message.sensor == CHILD_ID_RAIN_LOG) + { + // nothing to do here + } + else if (message.sensor == CHILD_ID_TRIPPED_INDICATOR) + { + if (message.type == V_VAR1) + { + rainWindow = atoi(message.data); + if (rainWindow > 120) + { + rainWindow = 120; + } + else if (rainWindow < 1) + { + rainWindow = 1; + } + if (rainWindow != atoi(message.data)) // if I changed the value back inside the boundries, push that number back to Vera + { + gw.send(msgTrippedVar1.set(rainWindow)); + } + } + else if (message.type == V_VAR2) + { + rainSensorThreshold = atoi(message.data); + if (rainSensorThreshold > 10000) + { + rainSensorThreshold = 10000; + } + else if (rainSensorThreshold < 1) + { + rainSensorThreshold = 1; + } + if (rainSensorThreshold != atoi(message.data)) // if I changed the value back inside the boundries, push that number back to Vera + { + gw.send(msgTrippedVar2.set(rainSensorThreshold)); + } + } + } +} + +void prettyFade(void) +{ + float val = (exp(sin(millis() / 2000.0 * PI)) - 0.36787944) * 108.0; + analogWrite(ledPin, val); +} + +void slowFlash(void) +{ + static boolean ledState = true; + static unsigned long pulseStart = millis(); + if (millis() - pulseStart < 100UL) + { + digitalWrite(ledPin, !ledState); + pulseStart = millis(); + } +} + +void receiveTime(unsigned long time) +{ + DEBUG_PRINTLN(F("Time received...")); + setTime(time); + char theTime[6]; + sprintf(theTime, "%d:%2d", hour(), minute()); + DEBUG_PRINTLN(theTime); +} diff --git a/libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml b/libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml new file mode 100644 index 0000000..f812265 --- /dev/null +++ b/libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml @@ -0,0 +1,43 @@ + + + + 1 + 0 + + + + CurrentTRain + yes + r8 + total_rain + + + CurrentRain + yes + r8 + rain_rate + + + + + GetCurrentTRain + + + RainValue + out + CurrentTRain + + + + + GetCurrentRain + + + RainValue + out + CurrentRain + + + + + \ No newline at end of file From ac749155b52b67f883a9cfaf53db03e2b0a1467b Mon Sep 17 00:00:00 2001 From: petewill Date: Tue, 7 Jul 2015 13:20:24 -0600 Subject: [PATCH 43/79] Moved Vera Files Moved files to Vera repository --- .../examples/RainGauge/D_RainSensor1.json | 523 ------------------ .../examples/RainGauge/D_RainSensor1.xml | 24 - .../examples/RainGauge/S_Rainsensor1.xml | 43 -- 3 files changed, 590 deletions(-) delete mode 100644 libraries/MySensors/examples/RainGauge/D_RainSensor1.json delete mode 100644 libraries/MySensors/examples/RainGauge/D_RainSensor1.xml delete mode 100644 libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml diff --git a/libraries/MySensors/examples/RainGauge/D_RainSensor1.json b/libraries/MySensors/examples/RainGauge/D_RainSensor1.json deleted file mode 100644 index 325391b..0000000 --- a/libraries/MySensors/examples/RainGauge/D_RainSensor1.json +++ /dev/null @@ -1,523 +0,0 @@ -{ - "flashicon": "icons/Humidity_Sensor.swf", - "imgIconBody": "", - "imgIconDimmable": "", - "imgIconTurnable": "", - "imgIconMin": "", - "imgIconMax": "", - "halloIconsDir": "pics\/hallo", - "inScene": "0", - "DisplayStatus": {}, - "doc_url": { - "doc_language": 1, - "doc_manual": 1, - "doc_version": 1, - "doc_platform": 0, - "doc_page": "sensors" - }, - - "Tabs": [ - { - "Label": { - "lang_tag": "tabname_control", - "text": "Information" - }, - "Position": "0", - "TabType": "flash", - "SceneGroup": [ - { - "id": "1", - "top": "1.5", - "left": "0", - "x": "2", - "y": "2" - } - ], - "ControlGroup": [ - { - "id": "1", - "scenegroup": "1", - "type": "info" - }, - { - "id": "2", - "scenegroup": "1", - "type": "info" - } - ], - "Control": [ - { - "ControlGroup":"1", - "ControlPair": "1", - "ControlHeader": "1", - "top": "1", - "left": "0", - "x": "1.25", - "ControlType": "label", - "Label": { - "lang_tag": "rain_rate", - "text": "Rate of Rain" - }, - "Display": { - "Top": 20, - "Left": 50, - "Width": 75, - "Height": 20 - } - }, - { - "ControlGroup":"1", - "ControlPair": "1", - "ControlHeader": "1", - "top": "1", - "left": "1.25", - "x": "0.75", - "ControlType": "variable", - "Display": { - "Service": "urn:upnp-org:serviceId:RainSensor1", - "Variable": "CurrentRain", - "Top": 20, - "Left": 150, - "Width": 25, - "Height": 20 - } - }, - { - "ControlType": "label", - "Label": { - "lang_tag": "total_rain_unit", - "text": "mm/hr" - }, - "Display": { - "Top": 20, - "Left": 200, - "Width": 25, - "Height": 20 - } - }, - { - "ControlGroup":"2", - "ControlPair": "2", - "ControlHeader": "1", - "top": "0", - "left": "0", - "x": "1.25", - "ControlType": "label", - "Label": { - "lang_tag": "total_rain", - "text": "Rain Today:", - }, - "Display": { - "Top": 55, - "Left": 50, - "Width": 75, - "Height": 20 - } - }, - { - "ControlGroup":"2", - "ControlPair": "2", - "ControlHeader": "1", - "top": "0", - "left": "1.25", - "x": "0.75", - "ControlType": "variable", - "Display": { - "Service": "urn:upnp-org:serviceId:RainSensor1", - "Variable": "CurrentTRain", - "Top": 55, - "Left": 150, - "Width": 25, - "Height": 20 - } - }, - { - "ControlType": "label", - "Label": { - "lang_tag": "rain_rate_unit", - "text": "mm" - }, - "Display": { - "Top": 55, - "Left": 200, - "Width": 25, - "Height": 20 - } - }, - { - "ControlGroup":"3", - "ControlPair": "3", - "ControlHeader": "1", - "top": "0", - "left": "0", - "x": "1.25", - "ControlType": "label", - "Label": { - "lang_tag": "rain_forty", - "text": "Yesterday:" - }, - "Display": { - "Top": 80, - "Left": 50, - "Width": 75, - "Height": 20 - } - }, - { - "ControlGroup":"3", - "ControlPair": "3", - "ControlHeader": "1", - "top": "0", - "left": "1.25", - "x": "0.75", - "ControlType": "variable", - "Display": { - "Service": "urn:upnp-org:serviceId:VContainer1", - "Variable": "Variable2", - "Top": 80, - "Left": 150, - "Width": 25, - "Height": 20 - } - }, - { - "ControlType": "label", - "Label": { - "lang_tag": "rain_unit", - "text": "mm" - }, - "Display": { - "Top": 80, - "Left": 200, - "Width": 25, - "Height": 20 - } - }, - { - "ControlGroup":"4", - "ControlPair": "4", - "ControlHeader": "1", - "top": "0", - "left": "0", - "x": "1.25", - "ControlType": "label", - "Label": { - "lang_tag": "rain_seventy", - "text": "3 Days Ago:" - }, - "Display": { - "Top": 105, - "Left": 50, - "Width": 75, - "Height": 20 - } - }, - { - "ControlGroup":"4", - "ControlPair": "4", - "ControlHeader": "1", - "top": "0", - "left": "1.25", - "x": "0.75", - "ControlType": "variable", - "Display": { - "Service": "urn:upnp-org:serviceId:VContainer1", - "Variable": "Variable3", - "Top": 105, - "Left": 150, - "Width": 25, - "Height": 20 - } - }, - { - "ControlType": "label", - "Label": { - "lang_tag": "rain_unit1", - "text": "mm" - }, - "Display": { - "Top": 105, - "Left": 200, - "Width": 25, - "Height": 20 - } - }, - { - "ControlGroup":"5", - "ControlPair": "5", - "ControlHeader": "1", - "top": "0", - "left": "0", - "x": "1.25", - "ControlType": "label", - "Label": { - "lang_tag": "rain_forty", - "text": "4 Days Ago:" - }, - "Display": { - "Top": 130, - "Left": 50, - "Width": 75, - "Height": 20 - } - }, - { - "ControlGroup":"5", - "ControlPair": "5", - "ControlHeader": "1", - "top": "0", - "left": "1.25", - "x": "0.75", - "ControlType": "variable", - "Display": { - "Service": "urn:upnp-org:serviceId:VContainer1", - "Variable": "Variable4", - "Top": 130, - "Left": 150, - "Width": 25, - "Height": 20 - } - }, - { - "ControlType": "label", - "Label": { - "lang_tag": "rain_unit2", - "text": "mm" - }, - "Display": { - "Top": 130, - "Left": 200, - "Width": 25, - "Height": 20 - } - }, - { - "ControlGroup":"6", - "ControlPair": "6", - "ControlHeader": "1", - "top": "0", - "left": "0", - "x": "1.25", - "ControlType": "label", - "Label": { - "lang_tag": "rain_hundred", - "text": "5 Days Ago:" - }, - "Display": { - "Top": 155, - "Left": 50, - "Width": 75, - "Height": 20 - } - }, - { - "ControlGroup":"6", - "ControlPair": "6", - "ControlHeader": "1", - "top": "0", - "left": "1.25", - "x": "0.75", - "ControlType": "variable", - "Display": { - "Service": "urn:upnp-org:serviceId:VContainer1", - "Variable": "Variable5", - "Top": 155, - "Left": 150, - "Width": 25, - "Height": 20 - } - }, - { - "ControlType": "label", - "Label": { - "lang_tag": "rain_unit3", - "text": "mm" - }, - "Display": { - "Top": 155, - "Left": 200, - "Width": 25, - "Height": 20 - } - } - ] - }, - { - "Label": { - "lang_tag": "advanced", - "text": "Advanced" - }, - "Position": "1", - "TabType": "javascript", - "ScriptName": "shared.js", - "Function": "advanced_device" - }, - { - "Label": { - "lang_tag": "logs", - "text": "Logs" - }, - "Position": "2", - "TabType": "javascript", - "ScriptName": "shared.js", - "Function": "device_logs" - }, - { - "Label": { - "lang_tag": "notifications", - "text": "Notifications" - }, - "Position": "3", - "TabType": "javascript", - "ScriptName": "shared.js", - "Function": "device_notifications" - } - ], - "eventList2": [ - { - "id": 1, - "label": { - "lang_tag": "total_rain_goes_above", - "text": "Total rain goes above" - }, - "serviceId": "urn:upnp-org:serviceId:RainSensor1", - "norepeat": "1", - "argumentList": [ - { - "id": 1, - "dataType": "r8", - "name": "CurrentTRain", - "comparisson": ">", - "prefix": { - "lang_tag": "total_rain", - "text": "Total rain" - }, - "suffix": { - "lang_tag": "total_rain_unit", - "text": "mm" - }, - "HumanFriendlyText": { - "lang_tag": "hft_total_rain_goes_above", - "text": "Total rain for _DEVICE_NAME_ goes above _ARGUMENT_VALUE_" - } - } - ] - }, - { - "id": 2, - "label": { - "lang_tag": "total_rain_goes_below", - "text": "Total rain goes below" - }, - "serviceId": "urn:upnp-org:serviceId:RainSensor1", - "norepeat": "1", - "argumentList": [ - { - "id": 1, - "dataType": "r8", - "name": "CurrentTRain", - "comparisson": "<", - "prefix": { - "lang_tag": "total_rain", - "text": "Total rain" - }, - "suffix": { - "lang_tag": "total_rain_unit", - "text": "mm" - }, - "HumanFriendlyText": { - "lang_tag": "hft_total_rain_goes_below", - "text": "Total rain for _DEVICE_NAME_ goes below _ARGUMENT_VALUE_" - } - } - ] - }, - { - "id": 3, - "label": { - "lang_tag": "rain_rate_goes_above", - "text": "Current rain goes above" - }, - "serviceId": "urn:upnp-org:serviceId:RainSensor1", - "norepeat": "1", - "argumentList": [ - { - "id": 1, - "dataType": "r8", - "name": "CurrentRain", - "comparisson": ">", - "prefix": { - "lang_tag": "rain_rate", - "text": "Current rain" - }, - "suffix": { - "lang_tag": "rain_rate_unit", - "text": "mm/hr" - }, - "HumanFriendlyText": { - "lang_tag": "hft_rain_rate_goes_above", - "text": "Current rain for _DEVICE_NAME_ goes above _ARGUMENT_VALUE_" - } - } - ] - }, - { - "id": 4, - "label": { - "lang_tag": "rain_rate_goes_below", - "text": "Current rain goes below" - }, - "serviceId": "urn:upnp-org:serviceId:RainSensor1", - "norepeat": "1", - "argumentList": [ - { - "id": 1, - "dataType": "r8", - "name": "CurrentRain", - "comparisson": "<", - "prefix": { - "lang_tag": "rain_rate", - "text": "Current rain" - }, - "suffix": { - "lang_tag": "rain_rate_unit", - "text": "mm/hr" - }, - "HumanFriendlyText": { - "lang_tag": "hft_rain_rate_goes_below", - "text": "Current rain for _DEVICE_NAME_ goes below _ARGUMENT_VALUE_" - } - } - ] - }, - { - "id": 5, - "label": { - "lang_tag": "battery_level_goes_below", - "text": "Battery level goes below" - }, - "serviceId": "urn:micasaverde-com:serviceId:HaDevice1", - "argumentList": [ - { - "id": 1, - "prefix": { - "lang_tag": "Level", - "text": "Level" - }, - "dataType": "i4", - "name": "BatteryLevel", - "comparisson": "<", - "suffix": { - "lang_tag": "percent_sign", - "text": "%" - }, - "HumanFriendlyText": { - "lang_tag": "hft_battery_level_goes_below", - "text": "Battery level for _DEVICE_NAME_ go below _ARGUMENT_VALUE_%" - } - } - ] - } - ], - "DeviceType": "urn:schemas-micasaverde-com:device:RainSensor:1" -} \ No newline at end of file diff --git a/libraries/MySensors/examples/RainGauge/D_RainSensor1.xml b/libraries/MySensors/examples/RainGauge/D_RainSensor1.xml deleted file mode 100644 index c0a7492..0000000 --- a/libraries/MySensors/examples/RainGauge/D_RainSensor1.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - 1 - 0 - - - urn:schemas-micasaverde-com:device:RainSensor:1 - 12 - D_RainSensor1.json - - - urn:schemas-upnp-org:service:RainSensor:1 - urn:upnp-org:serviceId:RainSensor1 - S_RainSensor1.xml - - - urn:schemas-micasaverde-com:service:HaDevice:1 - urn:micasaverde-com:serviceId:HaDevice1 - S_HaDevice1.xml - - - - \ No newline at end of file diff --git a/libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml b/libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml deleted file mode 100644 index f812265..0000000 --- a/libraries/MySensors/examples/RainGauge/S_Rainsensor1.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - 1 - 0 - - - - CurrentTRain - yes - r8 - total_rain - - - CurrentRain - yes - r8 - rain_rate - - - - - GetCurrentTRain - - - RainValue - out - CurrentTRain - - - - - GetCurrentRain - - - RainValue - out - CurrentRain - - - - - \ No newline at end of file From 5d7fe779e0615a9c45cbbc3d128737627ec7d4d1 Mon Sep 17 00:00:00 2001 From: windkh Date: Wed, 8 Jul 2015 22:37:38 +0200 Subject: [PATCH 44/79] Refactored forecast algorithm - reduced footprint by storing only the last few samples instead of all 180 - fixed wrong calculation: 65/1023 factor replaced with a conversion factor hPa to kPa - fixed error when 180 minutes were reached: sketch started at 5 min instead of 6 triggering a wrong average calculation Cleaned up code - removed unused variable - fixed unit Pa to hPa in serial print - introduced constants and enum for better readability Signed-off-by: windkh I agree to the CLA! --- .../PressureSensor/PressureSensor.ino | 351 ++++++++++-------- 1 file changed, 194 insertions(+), 157 deletions(-) diff --git a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino index 8911e74..dc4c213 100644 --- a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino +++ b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino @@ -6,7 +6,21 @@ #define BARO_CHILD 0 #define TEMP_CHILD 1 -unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in seconds) +const float ALTITUDE = 688; // <-- adapt this value to your own location's altitude. + +// Sleep time between reads (in seconds). Do not change this value as the forecast algorithm needs a sample every minute. +const unsigned long SLEEP_TIME = 60000; + +const char *weather[] = { "stable", "sunny", "cloudy", "unstable", "thunderstorm", "unknown" }; +enum FORECAST +{ + STABLE = 0, // "Stable Weather Pattern" + SUNNY = 1, // "Slowly rising Good Weather", "Clear/Sunny " + CLOUDY = 2, // "Slowly falling L-Pressure ", "Cloudy/Rain " + UNSTABLE = 3, // "Quickly rising H-Press", "Not Stable" + THUNDERSTORM = 4, // "Quickly falling L-Press", "Thunderstorm" + UNKNOWN = 5 // "Unknown (More Time needed) +}; Adafruit_BMP085 bmp = Adafruit_BMP085(); // Digital Pressure Sensor MySensor gw; @@ -14,206 +28,229 @@ MySensor gw; float lastPressure = -1; float lastTemp = -1; int lastForecast = -1; -const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; -int minutes; -float pressureSamples[7][6]; + +const int LAST_SAMPLES_COUNT = 5; +float lastPressureSamples[LAST_SAMPLES_COUNT]; + +// this CONVERSION_FACTOR is used to convert from Pa to kPa in forecast algorithm +// get kPa/h be dividing hPa by 10 +#define CONVERSION_FACTOR (1.0/10.0) + int minuteCount = 0; bool firstRound = true; float pressureAvg[7]; + float dP_dt; -boolean metric; +boolean metric; MyMessage tempMsg(TEMP_CHILD, V_TEMP); MyMessage pressureMsg(BARO_CHILD, V_PRESSURE); MyMessage forecastMsg(BARO_CHILD, V_FORECAST); -void setup() { - gw.begin(); - // Send the sketch version information to the gateway and Controller - gw.sendSketchInfo("Pressure Sensor", "1.0"); +void setup() +{ + gw.begin(); - if (!bmp.begin()) { - Serial.println("Could not find a valid BMP085 sensor, check wiring!"); - while (1) { } - } + // Send the sketch version information to the gateway and Controller + gw.sendSketchInfo("Pressure Sensor", "1.1"); - // Register sensors to gw (they will be created as child devices) - gw.present(BARO_CHILD, S_BARO); - gw.present(TEMP_CHILD, S_TEMP); - metric = gw.getConfig().isMetric; + if (!bmp.begin()) + { + Serial.println("Could not find a valid BMP085 sensor, check wiring!"); + while (1) {} + } + + // Register sensors to gw (they will be created as child devices) + gw.present(BARO_CHILD, S_BARO); + gw.present(TEMP_CHILD, S_TEMP); + metric = gw.getConfig().isMetric; } -void loop() { - float pressure = bmp.readSealevelPressure(205)/100.0; // 205 meters above sealevel - float temperature = bmp.readTemperature(); - - if (!metric) { - // Convert to fahrenheit - temperature = temperature * 9.0 / 5.0 + 32.0; - } - - int forecast = sample(pressure); +void loop() +{ + float pressure = bmp.readSealevelPressure(ALTITUDE) / 100.0; + float temperature = bmp.readTemperature(); - Serial.print("Temperature = "); - Serial.print(temperature); - Serial.println(metric?" *C":" *F"); - Serial.print("Pressure = "); - Serial.print(pressure); - Serial.println(" Pa"); - Serial.println(weather[forecast]); + if (!metric) + { + // Convert to fahrenheit + temperature = temperature * 9.0 / 5.0 + 32.0; + } + + int forecast = sample(pressure); + + Serial.print("Temperature = "); + Serial.print(temperature); + Serial.println(metric ? " *C" : " *F"); + Serial.print("Pressure = "); + Serial.print(pressure); + Serial.println(" hPa"); + Serial.print("Forecast = "); + Serial.println(weather[forecast]); - if (temperature != lastTemp) { - gw.send(tempMsg.set(temperature,1)); - lastTemp = temperature; - } + if (temperature != lastTemp) + { + gw.send(tempMsg.set(temperature, 1)); + lastTemp = temperature; + } - if (pressure != lastPressure) { - gw.send(pressureMsg.set(pressure, 0)); - lastPressure = pressure; - } + if (pressure != lastPressure) + { + gw.send(pressureMsg.set(pressure, 0)); + lastPressure = pressure; + } - if (forecast != lastForecast) { - gw.send(forecastMsg.set(weather[forecast])); - lastForecast = forecast; - } - - /* - DP/Dt explanation + if (forecast != lastForecast) + { + gw.send(forecastMsg.set(weather[forecast])); + lastForecast = forecast; + } - 0 = "Stable Weather Pattern" - 1 = "Slowly rising Good Weather", "Clear/Sunny " - 2 = "Slowly falling L-Pressure ", "Cloudy/Rain " - 3 = "Quickly rising H-Press", "Not Stable" - 4 = "Quickly falling L-Press", "Thunderstorm" - 5 = "Unknown (More Time needed) - */ - - gw.sleep(SLEEP_TIME); + gw.sleep(SLEEP_TIME); } -int sample(float pressure) { - // Algorithm found here - // http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf - if (minuteCount == 180) - minuteCount = 5; - - //From 0 to 5 min. - if (minuteCount <= 5){ - pressureSamples[0][minuteCount] = pressure; - } - //From 30 to 35 min. - if ((minuteCount <= 30) && (minuteCount >= 35)){ - pressureSamples[1][minuteCount - 30] = pressure; - } - //From 55 to 60 min. - if ((minuteCount <= 55) && (minuteCount >= 60)){ - pressureSamples[2][minuteCount - 55] = pressure; - } - //From 90 to 95 min. - if ((minuteCount <= 90) && (minuteCount >= 95)){ - pressureSamples[3][minuteCount - 90] = pressure; - } - //From 115 to 119 min. - if ((minuteCount <= 115) && (minuteCount >= 120)){ - pressureSamples[4][minuteCount - 115] = pressure; - } - //From 150 to 155 min. - if ((minuteCount <= 150) && (minuteCount >= 155)){ - pressureSamples[5][minuteCount - 150] = pressure; - } - //From 175 to 180 min. - if ((minuteCount <= 175) && (minuteCount >= 180)){ - pressureSamples[6][minuteCount - 175] = pressure; - } - +float getLastPressureSamplesAverage() +{ + float lastPressureSamplesAverage = 0; + for (int i = 0; i < LAST_SAMPLES_COUNT; i++) + { + lastPressureSamplesAverage += lastPressureSamples[i]; + } + lastPressureSamplesAverage /= LAST_SAMPLES_COUNT; + + return lastPressureSamplesAverage; +} + +// Algorithm found here +// http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf +// Pressure in hPa --> forecast done by calculating kPa/h +int sample(float pressure) +{ + // Calculate the average of the last n minutes. + int index = minuteCount % LAST_SAMPLES_COUNT; + lastPressureSamples[index] = pressure; minuteCount++; + if (minuteCount > 185) + { + minuteCount = 6; + } - if (minuteCount == 5) { - // Avg pressure in first 5 min, value averaged from 0 to 5 min. - pressureAvg[0] = ((pressureSamples[0][0] + pressureSamples[0][1] - + pressureSamples[0][2] + pressureSamples[0][3] - + pressureSamples[0][4] + pressureSamples[0][5]) / 6); - } else if (minuteCount == 35) { - // Avg pressure in 30 min, value averaged from 0 to 5 min. - pressureAvg[1] = ((pressureSamples[1][0] + pressureSamples[1][1] - + pressureSamples[1][2] + pressureSamples[1][3] - + pressureSamples[1][4] + pressureSamples[1][5]) / 6); - float change = (pressureAvg[1] - pressureAvg[0]); + if (minuteCount == 5) + { + pressureAvg[0] = getLastPressureSamplesAverage(); + } + else if (minuteCount == 35) + { + pressureAvg[1] = getLastPressureSamplesAverage(); + float change = (pressureAvg[1] - pressureAvg[0]) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour - dP_dt = ((65.0 / 1023.0) * 2 * change); // note this is for t = 0.5hour + { + dP_dt = change * 2; // note this is for t = 0.5hour + } else - dP_dt = (((65.0 / 1023.0) * change) / 1.5); // divide by 1.5 as this is the difference in time from 0 value. - } else if (minuteCount == 60) { - // Avg pressure at end of the hour, value averaged from 0 to 5 min. - pressureAvg[2] = ((pressureSamples[2][0] + pressureSamples[2][1] - + pressureSamples[2][2] + pressureSamples[2][3] - + pressureSamples[2][4] + pressureSamples[2][5]) / 6); - float change = (pressureAvg[2] - pressureAvg[0]); + { + dP_dt = change / 1.5; // divide by 1.5 as this is the difference in time from 0 value. + } + } + else if (minuteCount == 65) + { + pressureAvg[2] = getLastPressureSamplesAverage(); + float change = (pressureAvg[2] - pressureAvg[0]) * CONVERSION_FACTOR; if (firstRound) //first time initial 3 hour - dP_dt = ((65.0 / 1023.0) * change); //note this is for t = 1 hour + { + dP_dt = change; //note this is for t = 1 hour + } else - dP_dt = (((65.0 / 1023.0) * change) / 2); //divide by 2 as this is the difference in time from 0 value - } else if (minuteCount == 95) { - // Avg pressure at end of the hour, value averaged from 0 to 5 min. - pressureAvg[3] = ((pressureSamples[3][0] + pressureSamples[3][1] - + pressureSamples[3][2] + pressureSamples[3][3] - + pressureSamples[3][4] + pressureSamples[3][5]) / 6); - float change = (pressureAvg[3] - pressureAvg[0]); + { + dP_dt = change / 2; //divide by 2 as this is the difference in time from 0 value + } + } + else if (minuteCount == 95) + { + pressureAvg[3] = getLastPressureSamplesAverage(); + float change = (pressureAvg[3] - pressureAvg[0]) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour - dP_dt = (((65.0 / 1023.0) * change) / 1.5); // note this is for t = 1.5 hour + { + dP_dt = change / 1.5; // note this is for t = 1.5 hour + } else - dP_dt = (((65.0 / 1023.0) * change) / 2.5); // divide by 2.5 as this is the difference in time from 0 value - } else if (minuteCount == 120) { - // Avg pressure at end of the hour, value averaged from 0 to 5 min. - pressureAvg[4] = ((pressureSamples[4][0] + pressureSamples[4][1] - + pressureSamples[4][2] + pressureSamples[4][3] - + pressureSamples[4][4] + pressureSamples[4][5]) / 6); - float change = (pressureAvg[4] - pressureAvg[0]); + { + dP_dt = change / 2.5; // divide by 2.5 as this is the difference in time from 0 value + } + } + else if (minuteCount == 125) + { + pressureAvg[4] = getLastPressureSamplesAverage(); + float change = (pressureAvg[4] - pressureAvg[0]) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour - dP_dt = (((65.0 / 1023.0) * change) / 2); // note this is for t = 2 hour + { + dP_dt = change / 2; // note this is for t = 2 hour + } else - dP_dt = (((65.0 / 1023.0) * change) / 3); // divide by 3 as this is the difference in time from 0 value - } else if (minuteCount == 155) { - // Avg pressure at end of the hour, value averaged from 0 to 5 min. - pressureAvg[5] = ((pressureSamples[5][0] + pressureSamples[5][1] - + pressureSamples[5][2] + pressureSamples[5][3] - + pressureSamples[5][4] + pressureSamples[5][5]) / 6); - float change = (pressureAvg[5] - pressureAvg[0]); + { + dP_dt = change / 3; // divide by 3 as this is the difference in time from 0 value + } + } + else if (minuteCount == 155) + { + pressureAvg[5] = getLastPressureSamplesAverage(); + float change = (pressureAvg[5] - pressureAvg[0]) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour - dP_dt = (((65.0 / 1023.0) * change) / 2.5); // note this is for t = 2.5 hour + { + dP_dt = change / 2.5; // note this is for t = 2.5 hour + } else - dP_dt = (((65.0 / 1023.0) * change) / 3.5); // divide by 3.5 as this is the difference in time from 0 value - } else if (minuteCount == 180) { - // Avg pressure at end of the hour, value averaged from 0 to 5 min. - pressureAvg[6] = ((pressureSamples[6][0] + pressureSamples[6][1] - + pressureSamples[6][2] + pressureSamples[6][3] - + pressureSamples[6][4] + pressureSamples[6][5]) / 6); - float change = (pressureAvg[6] - pressureAvg[0]); + { + dP_dt = change / 3.5; // divide by 3.5 as this is the difference in time from 0 value + } + } + else if (minuteCount == 185) + { + pressureAvg[6] = getLastPressureSamplesAverage(); + float change = (pressureAvg[6] - pressureAvg[0]) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour - dP_dt = (((65.0 / 1023.0) * change) / 3); // note this is for t = 3 hour + { + dP_dt = change / 3; // note this is for t = 3 hour + } else - dP_dt = (((65.0 / 1023.0) * change) / 4); // divide by 4 as this is the difference in time from 0 value + { + dP_dt = change / 4; // divide by 4 as this is the difference in time from 0 value + } pressureAvg[0] = pressureAvg[5]; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past. firstRound = false; // flag to let you know that this is on the past 3 hour mark. Initialized to 0 outside main loop. } + int forecast = UNKNOWN; if (minuteCount < 35 && firstRound) //if time is less than 35 min on the first 3 hour interval. - return 5; // Unknown, more time needed + { + forecast = UNKNOWN; + } else if (dP_dt < (-0.25)) - return 4; // Quickly falling LP, Thunderstorm, not stable + { + forecast = THUNDERSTORM; + } else if (dP_dt > 0.25) - return 3; // Quickly rising HP, not stable weather + { + forecast = UNSTABLE; + } else if ((dP_dt > (-0.25)) && (dP_dt < (-0.05))) - return 2; // Slowly falling Low Pressure System, stable rainy weather + { + forecast = CLOUDY; + } else if ((dP_dt > 0.05) && (dP_dt < 0.25)) - return 1; // Slowly rising HP stable good weather - else if ((dP_dt > (-0.05)) && (dP_dt < 0.05)) - return 0; // Stable weather + { + forecast = SUNNY; + } + else if ((dP_dt >(-0.05)) && (dP_dt < 0.05)) + { + forecast = STABLE; + } else - return 5; // Unknown + { + forecast = UNKNOWN; + } + + return forecast; } - - - From fcb92436d9abd3a86c9b74d6732a3c26c620e856 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Thu, 9 Jul 2015 14:19:57 -0300 Subject: [PATCH 45/79] fix repeater loop for I_FIND_PARENT A repeater calls findParentNode() inside process() when receives a I_FIND_PARENT and nc.distance is invalid, this could cause a loop --- libraries/MySensors/MySensor.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 2e2d70e..099a927 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -302,6 +302,12 @@ void MySensor::setupNode() { } void MySensor::findParentNode() { + static boolean findingParentNode = false; + + if (findingParentNode) + return; + findingParentNode = true; + failedTransmissions = 0; // Set distance to max @@ -316,6 +322,7 @@ void MySensor::findParentNode() { // Wait for ping response. wait(2000); + findingParentNode = false; } boolean MySensor::sendRoute(MyMessage &message) { From 616b7d8b09e83aacf8821814765576204d85eaa7 Mon Sep 17 00:00:00 2001 From: "Bruce B. Lacey" Date: Sat, 11 Jul 2015 09:09:14 -0700 Subject: [PATCH 46/79] Changed the extended_fuses from 0xFE to 0x06 (set unused bits 3-7 to 0 instead of F) to improve compatibility with a broader range of programmers (e.g. ATMEL Dragon and USBTiny ISP v3). --- hardware/MySensors/avr/boards.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index 2a3c638..7fc0ec8 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -16,7 +16,7 @@ MysensorsMicro.bootloader.unlock_bits=0x3F MysensorsMicro.bootloader.lock_bits=0x0F MysensorsMicro.bootloader.low_fuses=0xE2 MysensorsMicro.bootloader.high_fuses=0xD2 -MysensorsMicro.bootloader.extended_fuses=0xFE +MysensorsMicro.bootloader.extended_fuses=0x06 MysensorsMicro.bootloader.file=DualOptiboot/optiboot_atmega328_pro_8MHz.hex MysensorsMicro.build.board=AVR_MICRO8 From 4abaa6ded34d22e3f3dd98d33d3d12450a537706 Mon Sep 17 00:00:00 2001 From: "Bruce B. Lacey" Date: Sat, 11 Jul 2015 09:31:30 -0700 Subject: [PATCH 47/79] Changed WITH_LEDS_BLINKING option to use the default LED pins as described on http://www.mysensors.org/build/advanced_gateway for consistency and backwards compatibility. Also corrected the LED on/off state to HIGH/LOW from LOW/HIGH respectively. --- libraries/MySensors/MyConfig.h | 6 +++--- libraries/MySensors/MySensor.cpp | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index c2148ab..11c8af1 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -58,11 +58,11 @@ // default LEDs blinking period in milliseconds #define DEFAULT_LED_BLINK_PERIOD 300 // The RX LED default pin -#define DEFAULT_RX_LED_PIN 8 +#define DEFAULT_RX_LED_PIN 6 // The TX LED default pin -#define DEFAULT_TX_LED_PIN 9 +#define DEFAULT_TX_LED_PIN 5 // The Error LED default pin -#define DEFAULT_ERR_LED_PIN 7 +#define DEFAULT_ERR_LED_PIN 4 /********************************** diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 2e2d70e..c32e44b 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -110,33 +110,33 @@ void MySensor::handleLedsBlinking() { // do the actual blinking if(countRx && countRx != 255) { // switch led on - digitalWrite(pinRx, LOW); + digitalWrite(pinRx, HIGH); } else if(!countRx) { // switching off - digitalWrite(pinRx, HIGH); + digitalWrite(pinRx, LOW); } if(countRx != 255) --countRx; if(countTx && countTx != 255) { // switch led on - digitalWrite(pinTx, LOW); + digitalWrite(pinTx, HIGH); } else if(!countTx) { // switching off - digitalWrite(pinTx, HIGH); + digitalWrite(pinTx, LOW); } if(countTx != 255) --countTx; if(countErr && countErr != 255) { // switch led on - digitalWrite(pinEr, LOW); + digitalWrite(pinEr, HIGH); } else if(!countErr) { // switching off - digitalWrite(pinEr, HIGH); + digitalWrite(pinEr, LOW); } if(countErr != 255) --countErr; @@ -182,9 +182,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b pinMode(pinEr, OUTPUT); // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); + digitalWrite(pinRx, LOW); + digitalWrite(pinTx, LOW); + digitalWrite(pinEr, LOW); // initialize counters countRx = 0; From 99917b43acac4c19ac90a9773821a769c85953c8 Mon Sep 17 00:00:00 2001 From: Yveaux Date: Thu, 16 Jul 2015 20:16:10 +0200 Subject: [PATCH 48/79] Allow disabling of LED/Inclusion pins LED/inclusion pins will always be controlled, even when not configured to use them. This fix will ignore pins when a negative pin number is passed. --- libraries/MySensors/MyGateway.cpp | 113 +++++++++++++++++------------- libraries/MySensors/MyGateway.h | 12 ++-- 2 files changed, 69 insertions(+), 56 deletions(-) diff --git a/libraries/MySensors/MyGateway.cpp b/libraries/MySensors/MyGateway.cpp index c65978f..63ce970 100644 --- a/libraries/MySensors/MyGateway.cpp +++ b/libraries/MySensors/MyGateway.cpp @@ -14,17 +14,20 @@ #include "utility/PinChangeInt.h" -uint8_t pinRx; -uint8_t pinTx; -uint8_t pinEr; +int8_t pinRx; +int8_t pinTx; +int8_t pinEr; boolean buttonTriggeredInclusion; volatile uint8_t countRx; volatile uint8_t countTx; volatile uint8_t countErr; boolean inclusionMode; // Keeps track on inclusion mode +#define LED_ON (LOW) +#define LED_OFF (HIGH) -MyGateway::MyGateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time, uint8_t _inclusion_pin, uint8_t _rx, uint8_t _tx, uint8_t _er) : MySensor(_cepin, _cspin) { + +MyGateway::MyGateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time, int8_t _inclusion_pin, int8_t _rx, int8_t _tx, int8_t _er) : MySensor(_cepin, _cspin) { pinInclusion = _inclusion_pin; inclusionTime = _inclusion_time; pinRx = _rx; @@ -56,23 +59,29 @@ void MyGateway::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e da countTx = 0; countErr = 0; - // Setup led pins - pinMode(pinRx, OUTPUT); - pinMode(pinTx, OUTPUT); - pinMode(pinEr, OUTPUT); - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); - + // Setup led pins & set initial state of leds + if (pinRx >= 0) + { + digitalWrite(pinRx, LED_OFF); + pinMode(pinRx, OUTPUT); + } + if (pinTx >= 0) + { + digitalWrite(pinTx, LED_OFF); + pinMode(pinTx, OUTPUT); + } + if (pinEr >= 0) + { + digitalWrite(pinEr, LED_OFF); + pinMode(pinEr, OUTPUT); + } // Setup digital in that triggers inclusion mode - pinMode(pinInclusion, INPUT); - digitalWrite(pinInclusion, HIGH); - - // Set initial state of leds - digitalWrite(pinRx, HIGH); - digitalWrite(pinTx, HIGH); - digitalWrite(pinEr, HIGH); - + if (pinInclusion >= 0) + { + pinMode(pinInclusion, INPUT); + // Add interrupt for inclusion button to pin + PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); + } // Start up the radio library setupRadio(paLevel, channel, dataRate); @@ -84,9 +93,6 @@ void MyGateway::begin(rf24_pa_dbm_e paLevel, uint8_t channel, rf24_datarate_e da MsTimer2::set(300, ledTimersInterrupt); MsTimer2::start(); - // Add interrupt for inclusion button to pin - PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING); - // Send startup log message on serial serial(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY); } @@ -257,34 +263,42 @@ void MyGateway::serial(MyMessage &msg) { void ledTimersInterrupt() { - if(countRx && countRx != 255) { - // switch led on - digitalWrite(pinRx, LOW); - } else if(!countRx) { - // switching off - digitalWrite(pinRx, HIGH); - } - if(countRx != 255) { countRx--; } + if (pinRx >= 0) + { + if(countRx && countRx != 255) { + // switch led on + digitalWrite(pinRx, LED_ON); + } else if(!countRx) { + // switching off + digitalWrite(pinRx, LED_OFF); + } + } + if(countRx != 255) { countRx--; } - if(countTx && countTx != 255) { - // switch led on - digitalWrite(pinTx, LOW); - } else if(!countTx) { - // switching off - digitalWrite(pinTx, HIGH); - } - if(countTx != 255) { countTx--; } - else if(inclusionMode) { countTx = 8; } - - if(countErr && countErr != 255) { - // switch led on - digitalWrite(pinEr, LOW); - } else if(!countErr) { - // switching off - digitalWrite(pinEr, HIGH); - } - if(countErr != 255) { countErr--; } + if (pinTx >= 0) + { + if(countTx && countTx != 255) { + // switch led on + digitalWrite(pinTx, LED_ON); + } else if(!countTx) { + // switching off + digitalWrite(pinTx, LED_OFF); + } + } + if(countTx != 255) { countTx--; } + else if(inclusionMode) { countTx = 8; } + if (pinEr >= 0) + { + if(countErr && countErr != 255) { + // switch led on + digitalWrite(pinEr, LED_ON); + } else if(!countErr) { + // switching off + digitalWrite(pinEr, LED_OFF); + } + } + if(countErr != 255) { countErr--; } } void MyGateway::rxBlink(uint8_t cnt) { @@ -296,4 +310,3 @@ void MyGateway::txBlink(uint8_t cnt) { void MyGateway::errBlink(uint8_t cnt) { if(countErr == 255) { countErr = cnt; } } - diff --git a/libraries/MySensors/MyGateway.h b/libraries/MySensors/MyGateway.h index 21a93d6..772154f 100644 --- a/libraries/MySensors/MyGateway.h +++ b/libraries/MySensors/MyGateway.h @@ -30,13 +30,13 @@ class MyGateway : public MySensor * @param _cepin The pin attached to RF24 Chip Enable on the RF module (default 9) * @param _cspin The pin attached to RF24 Chip Select (defualt 10) * @param _inclusion_time Time of inclusion mode (in minutes, default 1) - * @param _inclusion_pin Digital pin that triggers inclusion mode - * @param _rx Digital pin for receive led - * @param _tx Digital pin for transfer led - * @param _er Digital pin for error led + * @param _inclusion_pin Digital pin that triggers inclusion mode, negative value disables functionality. + * @param _rx Digital pin for receive led, negative value disables functionality. + * @param _tx Digital pin for transfer led, negative value disables functionality. + * @param _er Digital pin for error led, negative value disables functionality. * */ - MyGateway(uint8_t _cepin=DEFAULT_CE_PIN, uint8_t _cspin=DEFAULT_CS_PIN, uint8_t _inclusion_time = 1, uint8_t _inclusion_pin = 3, uint8_t _rx=6, uint8_t _tx=5, uint8_t _er=4); + MyGateway(uint8_t _cepin=DEFAULT_CE_PIN, uint8_t _cspin=DEFAULT_CS_PIN, uint8_t _inclusion_time = 1, int8_t _inclusion_pin=-1, int8_t _rx=-1, int8_t _tx=-1, int8_t _er=-1); /* Use this and pass a function that should be called when you want to process commands that arrive from radio network */ void begin(rf24_pa_dbm_e paLevel=RF24_PA_LEVEL_GW, uint8_t channel=RF24_CHANNEL, rf24_datarate_e dataRate=RF24_DATARATE, void (*dataCallback)(char *)=NULL); @@ -50,7 +50,7 @@ class MyGateway : public MySensor unsigned long inclusionStartTime; boolean useWriteCallback; void (*dataCallback)(char *); - uint8_t pinInclusion; + int8_t pinInclusion; uint8_t inclusionTime; uint8_t h2i(char c); From d72e20047b6fdce7d0e9edb445fd13fd4bc73336 Mon Sep 17 00:00:00 2001 From: windkh Date: Thu, 16 Jul 2015 21:48:08 +0200 Subject: [PATCH 49/79] Bugfix: new reference value is the average after 120min instead of average after 150min. Reduced footprint. I agree to the CLA. Signed-off-by: windkh --- .../PressureSensor/PressureSensor.ino | 44 ++++++++++++------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino index dc4c213..e8ed9cb 100644 --- a/libraries/MySensors/examples/PressureSensor/PressureSensor.ino +++ b/libraries/MySensors/examples/PressureSensor/PressureSensor.ino @@ -38,7 +38,10 @@ float lastPressureSamples[LAST_SAMPLES_COUNT]; int minuteCount = 0; bool firstRound = true; -float pressureAvg[7]; +// average value is used in forecast algorithm. +float pressureAvg; +// average after 2 hours is used as reference value for the next iteration. +float pressureAvg2; float dP_dt; boolean metric; @@ -122,6 +125,8 @@ float getLastPressureSamplesAverage() return lastPressureSamplesAverage; } + + // Algorithm found here // http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf // Pressure in hPa --> forecast done by calculating kPa/h @@ -139,12 +144,12 @@ int sample(float pressure) if (minuteCount == 5) { - pressureAvg[0] = getLastPressureSamplesAverage(); + pressureAvg = getLastPressureSamplesAverage(); } else if (minuteCount == 35) { - pressureAvg[1] = getLastPressureSamplesAverage(); - float change = (pressureAvg[1] - pressureAvg[0]) * CONVERSION_FACTOR; + float lastPressureAvg = getLastPressureSamplesAverage(); + float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour { dP_dt = change * 2; // note this is for t = 0.5hour @@ -156,8 +161,8 @@ int sample(float pressure) } else if (minuteCount == 65) { - pressureAvg[2] = getLastPressureSamplesAverage(); - float change = (pressureAvg[2] - pressureAvg[0]) * CONVERSION_FACTOR; + float lastPressureAvg = getLastPressureSamplesAverage(); + float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR; if (firstRound) //first time initial 3 hour { dP_dt = change; //note this is for t = 1 hour @@ -169,8 +174,8 @@ int sample(float pressure) } else if (minuteCount == 95) { - pressureAvg[3] = getLastPressureSamplesAverage(); - float change = (pressureAvg[3] - pressureAvg[0]) * CONVERSION_FACTOR; + float lastPressureAvg = getLastPressureSamplesAverage(); + float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour { dP_dt = change / 1.5; // note this is for t = 1.5 hour @@ -182,8 +187,9 @@ int sample(float pressure) } else if (minuteCount == 125) { - pressureAvg[4] = getLastPressureSamplesAverage(); - float change = (pressureAvg[4] - pressureAvg[0]) * CONVERSION_FACTOR; + float lastPressureAvg = getLastPressureSamplesAverage(); + pressureAvg2 = lastPressureAvg; // store for later use. + float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour { dP_dt = change / 2; // note this is for t = 2 hour @@ -195,8 +201,8 @@ int sample(float pressure) } else if (minuteCount == 155) { - pressureAvg[5] = getLastPressureSamplesAverage(); - float change = (pressureAvg[5] - pressureAvg[0]) * CONVERSION_FACTOR; + float lastPressureAvg = getLastPressureSamplesAverage(); + float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour { dP_dt = change / 2.5; // note this is for t = 2.5 hour @@ -208,8 +214,8 @@ int sample(float pressure) } else if (minuteCount == 185) { - pressureAvg[6] = getLastPressureSamplesAverage(); - float change = (pressureAvg[6] - pressureAvg[0]) * CONVERSION_FACTOR; + float lastPressureAvg = getLastPressureSamplesAverage(); + float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR; if (firstRound) // first time initial 3 hour { dP_dt = change / 3; // note this is for t = 3 hour @@ -218,7 +224,7 @@ int sample(float pressure) { dP_dt = change / 4; // divide by 4 as this is the difference in time from 0 value } - pressureAvg[0] = pressureAvg[5]; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past. + pressureAvg = pressureAvg2; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past. firstRound = false; // flag to let you know that this is on the past 3 hour mark. Initialized to 0 outside main loop. } @@ -252,5 +258,13 @@ int sample(float pressure) forecast = UNKNOWN; } + // uncomment when debugging + //Serial.print(F("Forecast at minute ")); + //Serial.print(minuteCount); + //Serial.print(F(" dP/dt = ")); + //Serial.print(dP_dt); + //Serial.print(F("kPa/h --> ")); + //Serial.println(weather[forecast]); + return forecast; } From 76493ff6a71771c47c0aae4e01d89a9aa088becb Mon Sep 17 00:00:00 2001 From: tekka007 Date: Tue, 21 Jul 2015 17:39:51 +0200 Subject: [PATCH 50/79] Sensebender OTA fix - fix OTA updates - update flash driver --- libraries/MySensors/MySensor.cpp | 60 ++++++---- libraries/MySensors/utility/SPIFlash.cpp | 142 +++++++++++++++-------- libraries/MySensors/utility/SPIFlash.h | 105 ++++++++++------- 3 files changed, 194 insertions(+), 113 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index c32e44b..b065d7c 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -74,24 +74,21 @@ MySensor::MySensor(MyTransport &_radio, MyHw &_hw #ifdef MY_OTA_FIRMWARE_FEATURE -// do a crc16 on the whole received firmware -bool MySensor::isValidFirmware() { - void* ptr = 0; - uint16_t crc = ~0; - int j; +// do a crc16 on the whole received firmware +bool MySensor::isValidFirmware() { + // init crc + uint16_t crc = ~0; for (uint16_t i = 0; i < fc.blocks * FIRMWARE_BLOCK_SIZE; ++i) { - uint8_t a = flash.readByte((uint16_t) ptr + i + FIRMWARE_START_OFFSET); - crc ^= a; - for (j = 0; j < 8; ++j) - { + crc ^= flash.readByte(i + FIRMWARE_START_OFFSET); + for (int8_t j = 0; j < 8; ++j) { if (crc & 1) crc = (crc >> 1) ^ 0xA001; else crc = (crc >> 1); } - } - return crc == fc.crc; + } + return crc == fc.crc; } #endif @@ -722,46 +719,61 @@ boolean MySensor::process() { // compare with current node configuration, if they differ, start fw fetch process if (memcmp(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig))) { debug(PSTR("fw update\n")); - fwUpdateOngoing = true; - fwBlock = fc.blocks; // copy new FW config memcpy(&fc,firmwareConfigResponse,sizeof(NodeFirmwareConfig)); // Init flash if (!flash.initialize()) { debug(PSTR("flash init fail\n")); + fwUpdateOngoing = false; + } else { + // erase lower 32K -> max flash size for ATMEGA328 + flash.blockErase32K(0); + // wait until flash erased + while ( flash.busy() ); + fwBlock = fc.blocks; + fwUpdateOngoing = true; + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; } - - } + return false; + } else debug(PSTR("fw update skipped\n")); } else if (type == ST_FIRMWARE_RESPONSE) { - // Save block to eeprom + // Save block to flash debug(PSTR("fw block %d\n"), fwBlock); - + // extract FW block ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data; // write to flash - flash.writeBytes(((fwBlock-1)*FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + flash.writeBytes( ((fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + // wait until flash written + while ( flash.busy() ); fwBlock--; - if (fwBlock == 0) { + if (!fwBlock) { // We're finished! Do a checksum and reboot. if (isValidFirmware()) { debug(PSTR("fw checksum ok\n")); // All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it) - uint16_t fwsize = FIRMWARE_BLOCK_SIZE*fc.blocks; flash.writeBytes(0, "FLXIMG:", 7); + // FW size in flash + uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks; flash.writeByte(7, fwsize >> 8); flash.writeByte(8, fwsize); + // end of header flash.writeByte(9, ':'); // Write the new firmware config to eeprom hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); hw_reboot(); } else { debug(PSTR("fw checksum fail\n")); + fwUpdateOngoing = false; } } + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; + return false; } - // Make sure packet request occurs next time process() is called by timing out requestTime. - fwRetry = MY_OTA_RETRY+1; - fwLastRequestTime = 0; - return false; + } #endif // Call incoming message callback if available diff --git a/libraries/MySensors/utility/SPIFlash.cpp b/libraries/MySensors/utility/SPIFlash.cpp index ee6e1b0..e250c17 100644 --- a/libraries/MySensors/utility/SPIFlash.cpp +++ b/libraries/MySensors/utility/SPIFlash.cpp @@ -1,20 +1,40 @@ -/* - * Copyright (c) 2013 by Felix Rusu - * SPI Flash memory library for arduino/moteino. - * This works with 256byte/page SPI flash memory - * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) - * Minimal modifications should allow chips that have different page size but modifications - * DEPENDS ON: Arduino SPI library - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ +// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com +// SPI Flash memory library for arduino/moteino. +// This works with 256byte/page SPI flash memory +// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) +// Minimal modifications should allow chips that have different page size but modifications +// DEPENDS ON: Arduino SPI library +// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment. +// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above) +// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4 +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This program 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 General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program. +// If not, see . +// +// Licence can be viewed at +// http://www.gnu.org/licenses/gpl-3.0.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code #include -byte SPIFlash::UNIQUEID[8]; +uint8_t SPIFlash::UNIQUEID[8]; /// IMPORTANT: NAND FLASH memory requires erase before write, because /// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s @@ -32,15 +52,22 @@ SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID) { /// Select the flash chip void SPIFlash::select() { - noInterrupts(); //save current SPI settings +#ifndef SPI_HAS_TRANSACTION + noInterrupts(); +#endif _SPCR = SPCR; _SPSR = SPSR; - //set FLASH chip SPI settings + +#ifdef SPI_HAS_TRANSACTION + SPI.beginTransaction(_settings); +#else + // set FLASH SPI settings SPI.setDataMode(SPI_MODE0); SPI.setBitOrder(MSBFIRST); SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present SPI.begin(); +#endif digitalWrite(_slaveSelectPin, LOW); } @@ -48,18 +75,25 @@ void SPIFlash::select() { void SPIFlash::unselect() { digitalWrite(_slaveSelectPin, HIGH); //restore SPI settings to what they were before talking to the FLASH chip +#ifdef SPI_HAS_TRANSACTION + SPI.endTransaction(); +#else + interrupts(); +#endif SPCR = _SPCR; SPSR = _SPSR; - interrupts(); } /// setup SPI, read device ID etc... boolean SPIFlash::initialize() { - SPI.begin(); _SPCR = SPCR; _SPSR = SPSR; pinMode(_slaveSelectPin, OUTPUT); +#ifdef SPI_HAS_TRANSACTION + _settings = SPISettings(4000000, MSBFIRST, SPI_MODE0); +#endif + unselect(); wakeup(); @@ -73,7 +107,7 @@ boolean SPIFlash::initialize() } /// Get the manufacturer and device ID bytes (as a short word) -word SPIFlash::readDeviceId() +uint16_t SPIFlash::readDeviceId() { #if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo command(SPIFLASH_IDREAD); // Read JEDEC ID @@ -81,7 +115,7 @@ word SPIFlash::readDeviceId() select(); SPI.transfer(SPIFLASH_IDREAD); #endif - word jedecid = SPI.transfer(0) << 8; + uint16_t jedecid = SPI.transfer(0) << 8; jedecid |= SPI.transfer(0); unselect(); return jedecid; @@ -90,47 +124,47 @@ word SPIFlash::readDeviceId() /// Get the 64 bit unique identifier, stores it in UNIQUEID[8]. Only needs to be called once, ie after initialize /// Returns the byte pointer to the UNIQUEID byte array /// Read UNIQUEID like this: -/// flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } +/// flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); } /// or like this: -/// flash.readUniqueId(); byte* MAC = flash.readUniqueId(); for (byte i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } -byte* SPIFlash::readUniqueId() +/// flash.readUniqueId(); uint8_t* MAC = flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); } +uint8_t* SPIFlash::readUniqueId() { command(SPIFLASH_MACREAD); SPI.transfer(0); SPI.transfer(0); SPI.transfer(0); SPI.transfer(0); - for (byte i=0;i<8;i++) + for (uint8_t i=0;i<8;i++) UNIQUEID[i] = SPI.transfer(0); unselect(); return UNIQUEID; } /// read 1 byte from flash memory -byte SPIFlash::readByte(long addr) { +uint8_t SPIFlash::readByte(uint32_t addr) { command(SPIFLASH_ARRAYREADLOWFREQ); SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); SPI.transfer(addr); - byte result = SPI.transfer(0); + uint8_t result = SPI.transfer(0); unselect(); return result; } /// read unlimited # of bytes -void SPIFlash::readBytes(long addr, void* buf, word len) { +void SPIFlash::readBytes(uint32_t addr, void* buf, uint16_t len) { command(SPIFLASH_ARRAYREAD); SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); SPI.transfer(addr); SPI.transfer(0); //"dont care" - for (word i = 0; i < len; ++i) - ((byte*) buf)[i] = SPI.transfer(0); + for (uint16_t i = 0; i < len; ++i) + ((uint8_t*) buf)[i] = SPI.transfer(0); unselect(); } /// Send a command to the flash chip, pass TRUE for isWrite when its a write command -void SPIFlash::command(byte cmd, boolean isWrite){ +void SPIFlash::command(uint8_t cmd, boolean isWrite){ #if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo DDRB |= B00000001; // Make sure the SS pin (PB0 - used by RFM12B on MoteinoLeo R1) is set as output HIGH! PORTB |= B00000001; @@ -156,7 +190,7 @@ boolean SPIFlash::busy() /* select(); SPI.transfer(SPIFLASH_STATUSREAD); - byte status = SPI.transfer(0); + uint8_t status = SPI.transfer(0); unselect(); return status & 1; */ @@ -164,11 +198,11 @@ boolean SPIFlash::busy() } /// return the STATUS register -byte SPIFlash::readStatus() +uint8_t SPIFlash::readStatus() { select(); SPI.transfer(SPIFLASH_STATUSREAD); - byte status = SPI.transfer(0); + uint8_t status = SPI.transfer(0); unselect(); return status; } @@ -177,7 +211,7 @@ byte SPIFlash::readStatus() /// Write 1 byte to flash memory /// WARNING: you can only write to previously erased memory locations (see datasheet) /// use the block erase commands to first clear memory (write 0xFFs) -void SPIFlash::writeByte(long addr, uint8_t byt) { +void SPIFlash::writeByte(uint32_t addr, uint8_t byt) { command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); @@ -186,20 +220,32 @@ void SPIFlash::writeByte(long addr, uint8_t byt) { unselect(); } -/// write 1-256 bytes to flash memory +/// write multiple bytes to flash memory (up to 64K) /// WARNING: you can only write to previously erased memory locations (see datasheet) /// use the block erase commands to first clear memory (write 0xFFs) -/// WARNING: if you write beyond a page boundary (or more than 256bytes), -/// the bytes will wrap around and start overwriting at the beginning of that same page -/// see datasheet for more details -void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) { - command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program - SPI.transfer(addr >> 16); - SPI.transfer(addr >> 8); - SPI.transfer(addr); - for (uint16_t i = 0; i < len; i++) - SPI.transfer(((byte*) buf)[i]); - unselect(); +/// This version handles both page alignment and data blocks larger than 256 bytes. +/// +void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len) { + uint16_t n; + uint16_t maxBytes = 256-(addr%256); // force the first set of bytes to stay within the first page + uint16_t offset = 0; + while (len>0) + { + n = (len<=maxBytes) ? len : maxBytes; + command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program + SPI.transfer(addr >> 16); + SPI.transfer(addr >> 8); + SPI.transfer(addr); + + for (uint16_t i = 0; i < n; i++) + SPI.transfer(((uint8_t*) buf)[offset + i]); + unselect(); + + addr+=n; // adjust the addresses and remaining bytes by what we've just transferred. + offset +=n; + len -= n; + maxBytes = 256; // now we can do up to 256 bytes per loop + } } /// erase entire flash memory array @@ -214,7 +260,7 @@ void SPIFlash::chipErase() { } /// erase a 4Kbyte block -void SPIFlash::blockErase4K(long addr) { +void SPIFlash::blockErase4K(uint32_t addr) { command(SPIFLASH_BLOCKERASE_4K, true); // Block Erase SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); @@ -223,7 +269,7 @@ void SPIFlash::blockErase4K(long addr) { } /// erase a 32Kbyte block -void SPIFlash::blockErase32K(long addr) { +void SPIFlash::blockErase32K(uint32_t addr) { command(SPIFLASH_BLOCKERASE_32K, true); // Block Erase SPI.transfer(addr >> 16); SPI.transfer(addr >> 8); diff --git a/libraries/MySensors/utility/SPIFlash.h b/libraries/MySensors/utility/SPIFlash.h index f0c071a..a308760 100644 --- a/libraries/MySensors/utility/SPIFlash.h +++ b/libraries/MySensors/utility/SPIFlash.h @@ -1,16 +1,36 @@ -/* - * Copyright (c) 2013 by Felix Rusu - * SPI Flash memory library for arduino/moteino. - * This works with 256byte/page SPI flash memory - * For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) - * Minimal modifications should allow chips that have different page size but modifications - * DEPENDS ON: Arduino SPI library - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ +// Copyright (c) 2013-2015 by Felix Rusu, LowPowerLab.com +// SPI Flash memory library for arduino/moteino. +// This works with 256byte/page SPI flash memory +// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes) +// Minimal modifications should allow chips that have different page size but modifications +// DEPENDS ON: Arduino SPI library +// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment. +// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above) +// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4 +// ********************************************************************************** +// License +// ********************************************************************************** +// This program is free software; you can redistribute it +// and/or modify it under the terms of the GNU General +// Public License as published by the Free Software +// Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This program 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 General Public +// License for more details. +// +// You should have received a copy of the GNU General +// Public License along with this program. +// If not, see . +// +// Licence can be viewed at +// http://www.gnu.org/licenses/gpl-3.0.txt +// +// Please maintain this license information along with authorship +// and copyright notices in any redistribution of this code #ifndef _SPIFLASH_H_ #define _SPIFLASH_H_ @@ -33,19 +53,19 @@ /// Assuming the WP pin is pulled up (to disable hardware write protection) /// To use any write commands the WEL bit in the status register must be set to 1. /// This is accomplished by sending a 0x06 command before any such write/erase command. -/// The WEL bit in the status register resets to the logical “0” state after a -/// device power-up or reset. In addition, the WEL bit will be reset to the logical “0” state automatically under the following conditions: -/// • Write Disable operation completes successfully -/// • Write Status Register operation completes successfully or aborts -/// • Protect Sector operation completes successfully or aborts -/// • Unprotect Sector operation completes successfully or aborts -/// • Byte/Page Program operation completes successfully or aborts -/// • Sequential Program Mode reaches highest unprotected memory location -/// • Sequential Program Mode reaches the end of the memory array -/// • Sequential Program Mode aborts -/// • Block Erase operation completes successfully or aborts -/// • Chip Erase operation completes successfully or aborts -/// • Hold condition aborts +/// The WEL bit in the status register resets to the logical ?0? state after a +/// device power-up or reset. In addition, the WEL bit will be reset to the logical ?0? state automatically under the following conditions: +/// ? Write Disable operation completes successfully +/// ? Write Status Register operation completes successfully or aborts +/// ? Protect Sector operation completes successfully or aborts +/// ? Unprotect Sector operation completes successfully or aborts +/// ? Byte/Page Program operation completes successfully or aborts +/// ? Sequential Program Mode reaches highest unprotected memory location +/// ? Sequential Program Mode reaches the end of the memory array +/// ? Sequential Program Mode aborts +/// ? Block Erase operation completes successfully or aborts +/// ? Chip Erase operation completes successfully or aborts +/// ? Hold condition aborts #define SPIFLASH_WRITEENABLE 0x06 // write enable #define SPIFLASH_WRITEDISABLE 0x04 // write disable @@ -69,21 +89,21 @@ class SPIFlash { public: - static byte UNIQUEID[8]; - SPIFlash(byte slaveSelectPin, uint16_t jedecID=0); + static uint8_t UNIQUEID[8]; + SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID=0); boolean initialize(); - void command(byte cmd, boolean isWrite=false); - byte readStatus(); - byte readByte(long addr); - void readBytes(long addr, void* buf, word len); - void writeByte(long addr, byte byt); - void writeBytes(long addr, const void* buf, uint16_t len); + void command(uint8_t cmd, boolean isWrite=false); + uint8_t readStatus(); + uint8_t readByte(uint32_t addr); + void readBytes(uint32_t addr, void* buf, uint16_t len); + void writeByte(uint32_t addr, uint8_t byt); + void writeBytes(uint32_t addr, const void* buf, uint16_t len); boolean busy(); void chipErase(); - void blockErase4K(long address); - void blockErase32K(long address); - word readDeviceId(); - byte* readUniqueId(); + void blockErase4K(uint32_t address); + void blockErase32K(uint32_t address); + uint16_t readDeviceId(); + uint8_t* readUniqueId(); void sleep(); void wakeup(); @@ -91,10 +111,13 @@ public: protected: void select(); void unselect(); - byte _slaveSelectPin; + uint8_t _slaveSelectPin; uint16_t _jedecID; - byte _SPCR; - byte _SPSR; + uint8_t _SPCR; + uint8_t _SPSR; +#ifdef SPI_HAS_TRANSACTION + SPISettings _settings; +#endif }; #endif \ No newline at end of file From 128aaacf70d916df6f0701e1e4c665a537521e00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Mon, 27 Jul 2015 00:18:49 +0200 Subject: [PATCH 51/79] Updated platform.txt / boards.txt to reflect AVR platform target, and removed atmega1284 as GW target --- hardware/MySensors/avr/boards.txt | 25 ------------------------- hardware/MySensors/avr/platform.txt | 2 +- 2 files changed, 1 insertion(+), 26 deletions(-) diff --git a/hardware/MySensors/avr/boards.txt b/hardware/MySensors/avr/boards.txt index 2a3c638..71b3220 100644 --- a/hardware/MySensors/avr/boards.txt +++ b/hardware/MySensors/avr/boards.txt @@ -30,28 +30,3 @@ MysensorsMicro.menu.cpu.8Mhz.build.f_cpu=8000000L MysensorsMicro.menu.cpu.1Mhz=Atmega328 1Mhz MysensorsMicro.menu.cpu.1Mhz.build.f_cpu=1000000L - - -######################################## -## Gateway settings - -MysensorsGW.name=Sensebender Gateway -MysensorsGW.build.core=arduino:arduino -MysensorsGW.build.variant=GW -MysensorsGW.build.board=AVR_1284 -MysensorsGW.build.mcu=atmega1284p -MysensorsGW.build.f_cpu=20000000L - -MysensorsGW.upload.tool=arduino:avrdude -MysensorsGW.upload.protocol=arduino -MysensorsGW.upload.maximum_size=123720 -MysensorsGW.upload.maximum_data_size=16384 -MysensorsGW.upload.speed=115200 - -MysensorsGW.bootloader.tool=arduino:avrdude -MysensorsGW.bootloader.unlock_bits=0x3F -MysensorsGW.bootloader.lock_bits=0x0F -MysensorsGW.bootloader.low_fuses=0xE2 -MysensorsGW.bootloader.high_fuses=0xD2 -MysensorsGW.bootloader.extended_fuses=0xFE -MysensorsGW.bootloader.file=DualOptiboot/optiboot_atmega1284.hex diff --git a/hardware/MySensors/avr/platform.txt b/hardware/MySensors/avr/platform.txt index 247f5cc..28f482c 100644 --- a/hardware/MySensors/avr/platform.txt +++ b/hardware/MySensors/avr/platform.txt @@ -5,7 +5,7 @@ # For more info: # https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification -name=MySensors Boards +name=MySensors AVR based boards version=1.6.0 # AVR compile variables From a22f712d60fd2cb404c5ab509dcb7405ec7332b1 Mon Sep 17 00:00:00 2001 From: Marcelo Aquino Date: Tue, 28 Jul 2015 11:32:52 -0300 Subject: [PATCH 52/79] respond to a I_FIND_PARENT after findParentNode() When a repeater receives a I_FIND_PARENT, it first update the nc.distance if is invalid and then respond the request --- libraries/MySensors/MySensor.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 099a927..19b03c4 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -781,14 +781,17 @@ boolean MySensor::process() { // If this node have an id, relay the message if (command == C_INTERNAL && type == I_FIND_PARENT) { - if (nc.distance == DISTANCE_INVALID) { - findParentNode(); - } else if (sender != nc.parentNodeId) { - // Relaying nodes should always answer ping messages - // Wait a random delay of 0-2 seconds to minimize collision - // between ping ack messages from other relaying nodes - wait(hw_millis() & 0x3ff); - sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); + if (sender != nc.parentNodeId) { + if (nc.distance == DISTANCE_INVALID) + findParentNode(); + + if (nc.distance != DISTANCE_INVALID) { + // Relaying nodes should always answer ping messages + // Wait a random delay of 0-2 seconds to minimize collision + // between ping ack messages from other relaying nodes + wait(hw_millis() & 0x3ff); + sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance)); + } } } else if (to == nc.nodeId) { // We should try to relay this message to another node From 79c4cee47535dba34d18ed84e023e14c1bd24e19 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 28 Jul 2015 19:44:46 +0200 Subject: [PATCH 53/79] Fix signing problem reported by @scalz http://forum.mysensors.org/topic/1021/security-introducing-signing-support-to-mysensors/103 --- libraries/MySensors/MySensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index b065d7c..6949e83 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -343,7 +343,7 @@ boolean MySensor::sendRoute(MyMessage &message) { #ifdef MY_SIGNING_FEATURE // If destination is known to require signed messages and we are the sender, sign this message unless it is an ACK or a handshake message - if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(msg) && + if (DO_SIGN(message.destination) && message.sender == nc.nodeId && !mGetAck(message) && mGetLength(message) && (mGetCommand(message) != C_INTERNAL || (message.type != I_GET_NONCE && message.type != I_GET_NONCE_RESPONSE && message.type != I_REQUEST_SIGNING && message.type != I_ID_REQUEST && message.type != I_ID_RESPONSE && From 8c2e835f92c549752a96a4e3fb30501038cc24ea Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 14:09:11 +0200 Subject: [PATCH 54/79] Added HVAC and some other new device types and variables from the development branch. --- libraries/MySensors/MyMessage.h | 109 +++++++++++++++--- .../AirQualitySensor/AirQualitySensor.ino | 2 +- .../examples/DustSensor/DustSensor.ino | 2 +- .../LightLuxSensor/LightLuxSensor.ino | 5 + 4 files changed, 103 insertions(+), 15 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 643bdb2..49e85cd 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -32,16 +32,106 @@ typedef enum { C_STREAM = 4 // For Firmware and other larger chunks of data that need to be divided into pieces. } mysensor_command; +// Type of sensor (used when presenting sensors) +typedef enum { + S_DOOR, // Door sensor, V_TRIPPED, V_ARMED + S_MOTION, // Motion sensor, V_TRIPPED, V_ARMED + S_SMOKE, // Smoke sensor, V_TRIPPED, V_ARMED + S_LIGHT, // Binary light or relay, V_STATUS (or V_LIGHT), V_WATT + S_BINARY=3, // Binary light or relay, V_STATUS (or V_LIGHT), V_WATT (same as S_LIGHT) + S_DIMMER, // Dimmable light or fan device, V_STATUS (on/off), V_DIMMER (dimmer level 0-100), V_WATT + S_COVER, // Blinds or window cover, V_UP, V_DOWN, V_STOP, V_DIMMER (open/close to a percentage) + S_TEMP, // Temperature sensor, V_TEMP + S_HUM, // Humidity sensor, V_HUM + S_BARO, // Barometer sensor, V_PRESSURE, V_FORECAST + S_WIND, // Wind sensor, V_WIND, V_GUST + S_RAIN, // Rain sensor, V_RAIN, V_RAINRATE + S_UV, // Uv sensor, V_UV + S_WEIGHT, // Personal scale sensor, V_WEIGHT, V_IMPEDANCE + S_POWER, // Power meter, V_WATT, V_KWH + S_HEATER, // Header device, V_HVAC_SETPOINT_HEAT, V_HVAC_FLOW_STATE + S_DISTANCE, // Distance sensor, V_DISTANCE + S_LIGHT_LEVEL, // Light level sensor, V_LIGHT_LEVEL (uncalibrated in percentage), V_LEVEL (light level in lux) + S_ARDUINO_NODE, // Used (internally) for presenting a non-repeating Arduino node + S_ARDUINO_REPEATER_NODE, // Used (internally) for presenting a repeating Arduino node + S_LOCK, // Lock device, V_LOCK_STATUS + S_IR, // Ir device, V_IR_SEND, V_IR_RECEIVE + S_WATER, // Water meter, V_FLOW, V_VOLUME + S_AIR_QUALITY, // Air quality sensor, V_LEVEL + S_CUSTOM, // Custom sensor + S_DUST, // Dust sensor, V_LEVEL + S_SCENE_CONTROLLER, // Scene controller device, V_SCENE_ON, V_SCENE_OFF. + S_RGB_LIGHT, // RGB light. Send color component data using V_RGB. Also supports V_WATT + S_RGBW_LIGHT, // RGB light with an additional White component. Send data using V_RGBW. Also supports V_WATT + S_COLOR_SENSOR, // Color sensor, send color information using V_RGB + S_HVAC, // Thermostat/HVAC device. V_HVAC_SETPOINT_HEAT, V_HVAC_SETPOINT_COLD, V_HVAC_FLOW_STATE, V_HVAC_FLOW_MODE + S_MULTIMETER, // Multimeter device, V_VOLTAGE, V_CURRENT, V_IMPEDANCE + S_SPRINKLER, // Sprinkler, V_STATUS (turn on/off), V_TRIPPED (if fire detecting device) + S_WATER_LEAK, // Water leak sensor, V_TRIPPED, V_ARMED + S_SOUND, // Sound sensor, V_TRIPPED, V_ARMED, V_LEVEL (sound level in dB) + S_VIBRATION, // Vibration sensor, V_TRIPPED, V_ARMED, V_LEVEL (vibration in Hz) + S_MOISTURE, // Moisture sensor, V_TRIPPED, V_ARMED, V_LEVEL (water content or moisture in percentage?) +} mysensor_sensor; + // Type of sensor data (for set/req/ack messages) typedef enum { - V_TEMP,V_HUM, V_LIGHT, V_DIMMER, V_PRESSURE, V_FORECAST, V_RAIN, - V_RAINRATE, V_WIND, V_GUST, V_DIRECTION, V_UV, V_WEIGHT, V_DISTANCE, - V_IMPEDANCE, V_ARMED, V_TRIPPED, V_WATT, V_KWH, V_SCENE_ON, V_SCENE_OFF, - V_HEATER, V_HEATER_SW, V_LIGHT_LEVEL, V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, - V_UP, V_DOWN, V_STOP, V_IR_SEND, V_IR_RECEIVE, V_FLOW, V_VOLUME, V_LOCK_STATUS, - V_DUST_LEVEL, V_VOLTAGE, V_CURRENT + V_TEMP, // S_TEMP + V_HUM, // S_HUM + V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, Used for setting binary (on/off) status. 1=on, 0=off + V_LIGHT=2, // S_LIGHT, S_DIMMER. Same as V_STATUS + V_PERCENTAGE, // S_DIMMER. Used for sending a percentage value (0-100). + V_DIMMER=3, // S_DIMMER. Same as V_PERCENTAGE. + V_PRESSURE, // S_BARO + V_FORECAST, // S_BARO + V_RAIN, // S_RAIN + V_RAINRATE, // S_RAIN + V_WIND, // S_WIND + V_GUST, // S_WIND + V_DIRECTION, // S_WIND + V_UV, // S_UV + V_WEIGHT, // S_WEIGHT + V_DISTANCE, // S_DISTANCE + V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT + V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER + V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER (for sprinklers with fire detection) + V_WATT, // S_POWER, S_LIGHT, S_DIMMER + V_KWH, // S_POWER + V_SCENE_ON, // S_SCENE_CONTROLLER + V_SCENE_OFF, // S_SCENE_CONTROLLER + V_HEATER, // Deprecated. Use V_HVAC_FLOW_STATE instead. + V_HVAC_FLOW_STATE=21, // HVAC flow state ("Off", "HeatOn", "CoolOn", or "AutoChangeOver"). S_HEATER, S_HVAC + V_HVAC_SPEED, // HVAC/Heater fan speed ("Min", "Normal", "Max", "Auto") + V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage) or S_LEVEL (light level in lux) + V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, + V_UP, // S_COVER + V_DOWN, // S_COVER + V_STOP, // S_COVER + V_IR_SEND, // S_IR + V_IR_RECEIVE, // S_IR + V_FLOW, // S_WATER + V_VOLUME, // S_WATER + V_LOCK_STATUS, // S_LOCK + V_LEVEL, // S_DUST, S_AIR_QUALITY, S_SOUND (dB), S_VIBRATION (hz), S_LIGHT_LEVEL (lux) + V_VOLTAGE, // S_MULTIMETER + V_CURRENT, // S_MULTIMETER + V_RGB, // S_RGB_LIGHT, S_COLOR_SENSOR. + // Used for sending color information for multi color LED lighting or color sensors. + // Sent as ASCII hex: RRGGBB (RR=red, GG=green, BB=blue component) + V_RGBW, // S_RGBW_LIGHT + // Used for sending color information to multi color LED lighting. + // Sent as ASCII hex: RRGGBBWW (WW=while component) + V_ID, // S_TEMP + // Used for sending in sensors hardware ids (i.e. OneWire DS1820b). + V_UNIT_PREFIX, // Allows sensors to send in a string representing the + // unit prefix to be displayed in GUI, not parsed by controller! E.g. cm, m, km, inch. + // Can be used for S_DISTANCE or gas concentration (S_DUST, S_AIR_QUALITY) + V_HVAC_SETPOINT_COLD, // HVAC cold setpoint (Integer between 0-100). S_HVAC + V_HVAC_SETPOINT_HEAT, // HVAC/Heater setpoint (Integer between 0-100). S_HEATER, S_HVAC + V_HVAC_FLOW_MODE, // Flow mode for HVAC ("Auto", "ContinuousOn", "PeriodicOn"). S_HVAC + } mysensor_data; + // Type of internal messages (for internal messages) typedef enum { I_BATTERY_LEVEL, I_TIME, I_VERSION, I_ID_REQUEST, I_ID_RESPONSE, @@ -50,13 +140,6 @@ typedef enum { I_REBOOT, I_GATEWAY_READY } mysensor_internal; -// Type of sensor (for presentation message) -typedef enum { - S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, - S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, - S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER -} mysensor_sensor; // Type of data stream (for streamed message) typedef enum { diff --git a/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino b/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino index efe12f3..a206300 100644 --- a/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino +++ b/libraries/MySensors/examples/AirQualitySensor/AirQualitySensor.ino @@ -59,7 +59,7 @@ float SmokeCurve[3] ={2.3,0.53,-0.44}; //two points are taken from MySensor gw; -MyMessage msg(CHILD_ID_MQ, V_VAR1); +MyMessage msg(CHILD_ID_MQ, V_LEVEL); void setup() diff --git a/libraries/MySensors/examples/DustSensor/DustSensor.ino b/libraries/MySensors/examples/DustSensor/DustSensor.ino index 4ebe804..8c3115d 100644 --- a/libraries/MySensors/examples/DustSensor/DustSensor.ino +++ b/libraries/MySensors/examples/DustSensor/DustSensor.ino @@ -36,7 +36,7 @@ float calcVoltage = 0; float dustDensity = 0; MySensor gw; -MyMessage dustMsg(CHILD_ID_DUST, V_DUST_LEVEL); +MyMessage dustMsg(CHILD_ID_DUST, V_LEVEL); void setup() { diff --git a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino index b3e4f49..df8be69 100644 --- a/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino +++ b/libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino @@ -26,7 +26,12 @@ unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) BH1750 lightSensor; MySensor gw; + +// V_LIGHT_LEVEL should only be used for uncalibrated light level 0-100%. +// If your controller supports the new V_LEVEL variable, use this instead for +// transmitting LUX light level. MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL); +// MyMessage msg(CHILD_ID_LIGHT, V_LEVEL); uint16_t lastlux; void setup() From 5bab725f81a98cd47d15c731a2d70754a8f229bc Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 14:41:57 +0200 Subject: [PATCH 55/79] Bump version to 1.5 --- libraries/MySensors/Version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/Version.h b/libraries/MySensors/Version.h index 437cd2c..c782265 100644 --- a/libraries/MySensors/Version.h +++ b/libraries/MySensors/Version.h @@ -6,6 +6,6 @@ #ifndef Version_h #define Version_h -#define LIBRARY_VERSION "1.5 b1" +#define LIBRARY_VERSION "1.5" #endif From 190479df6dd2fc5a159b9793ee88320649a4f895 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 15:34:23 +0200 Subject: [PATCH 56/79] Final 1.4 release --- libraries/MySensors/Version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/Version.h b/libraries/MySensors/Version.h index 82462b7..14ef8ff 100644 --- a/libraries/MySensors/Version.h +++ b/libraries/MySensors/Version.h @@ -6,6 +6,6 @@ #ifndef Version_h #define Version_h -#define LIBRARY_VERSION "1.4.1" +#define LIBRARY_VERSION "1.4.2" #endif From 34ace0bad7c6b4c1539e007dfb01ab5f801d7282 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 20:58:50 +0200 Subject: [PATCH 57/79] Fix spelling error on setpoint cool --- libraries/MySensors/MyMessage.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 6dc504b..129801f 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -86,8 +86,8 @@ typedef enum { typedef enum { V_TEMP, // S_TEMP V_HUM, // S_HUM - V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, Used for setting binary (on/off) status. 1=on, 0=off - V_LIGHT=2, // S_LIGHT, S_DIMMER. Same as V_STATUS + V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, S_HVAC, S_HEATER. Used for setting binary (on/off) status. 1=on, 0=off + V_LIGHT=2, // Same as V_STATUS V_PERCENTAGE, // S_DIMMER. Used for sending a percentage value (0-100). V_DIMMER=3, // S_DIMMER. Same as V_PERCENTAGE. V_PRESSURE, // S_BARO @@ -110,7 +110,7 @@ typedef enum { V_HEATER, // Deprecated. Use V_HVAC_FLOW_STATE instead. V_HVAC_FLOW_STATE=21, // HVAC flow state ("Off", "HeatOn", "CoolOn", or "AutoChangeOver"). S_HEATER, S_HVAC V_HVAC_SPEED, // HVAC/Heater fan speed ("Min", "Normal", "Max", "Auto") - V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage) or S_LEVEL (light level in lux) + V_LIGHT_LEVEL, // Used for sending light level in uncalibrated percentage. See also V_LEVEL (light level in lux). S_LIGHT_LEVEL V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5, V_UP, // S_COVER V_DOWN, // S_COVER @@ -134,7 +134,7 @@ typedef enum { V_UNIT_PREFIX, // Allows sensors to send in a string representing the // unit prefix to be displayed in GUI, not parsed by controller! E.g. cm, m, km, inch. // Can be used for S_DISTANCE or gas concentration (S_DUST, S_AIR_QUALITY) - V_HVAC_SETPOINT_COLD, // HVAC cold setpoint (Integer between 0-100). S_HVAC + V_HVAC_SETPOINT_COOL, // HVAC cool setpoint (Integer between 0-100). S_HVAC V_HVAC_SETPOINT_HEAT, // HVAC/Heater setpoint (Integer between 0-100). S_HEATER, S_HVAC V_HVAC_FLOW_MODE, // Flow mode for HVAC ("Auto", "ContinuousOn", "PeriodicOn"). S_HVAC From 237b080b2eeb3b0858b602a43099888036ffe6f9 Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:04:02 -0400 Subject: [PATCH 58/79] Create MockMySensors Arduino sketch to mock sensors for the MySensors Library This skecth is intended to crate fake sensors which register and respond to the controller Barduino 2015 ----------------- Comment/Uncomment the sensors you would like to test Arduino Uno R3 can support about 12 sensors before it runs out of memory. You probably need to turn of the MySensor Lib debug to save some memory Nest step will be to remove the read/write to the eprom and extend to support the v1.5 sensors --- libraries/MySensors/examples/MockMySensors | 1018 ++++++++++++++++++++ 1 file changed, 1018 insertions(+) create mode 100644 libraries/MySensors/examples/MockMySensors diff --git a/libraries/MySensors/examples/MockMySensors b/libraries/MySensors/examples/MockMySensors new file mode 100644 index 0000000..4397208 --- /dev/null +++ b/libraries/MySensors/examples/MockMySensors @@ -0,0 +1,1018 @@ +/* +* FakeMySensors +* +* This skecth is intended to crate fake sensors which register and respond to the controller +* +* Barduino 2015 +*/ + +#include +#include + +// SPI Pins +#define CE_PIN 9 +#define CS_PIN 10 + +// Wait times +#define LONG_WAIT 500 +#define SHORT_WAIT 50 + +#define SKETCH_NAME "FakeMySensors " +#define SKETCH_VERSION "v0.2" + +// Define Sensors ids +/* S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, + S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, + S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, + S_SCENE_CONTROLLER +*/ + +////#define ID_S_ARDUINO_NODE //auto defined in initialization +////#define ID_S_ARDUINO_REPEATER_NODE //auto defined in initialization + +//#define ID_S_DOOR 1 +//#define ID_S_MOTION 2 +//#define ID_S_SMOKE 3 +//#define ID_S_LIGHT 4 +//#define ID_S_DIMMER 5 +//#define ID_S_COVER 6 +//#define ID_S_TEMP 7 +//#define ID_S_HUM 8 +//#define ID_S_BARO 9 +//#define ID_S_WIND 10 +//#define ID_S_RAIN 11 +//#define ID_S_UV 12 +//#define ID_S_WEIGHT 13 +#define ID_S_POWER 14 +#define ID_S_HEATER 15 +#define ID_S_DISTANCE 16 +#define ID_S_LIGHT_LEVEL 17 +#define ID_S_LOCK 18 +#define ID_S_IR 19 +#define ID_S_WATER 20 +#define ID_S_AIR_QUALITY 21 +#define ID_S_DUST 22 +#define ID_S_SCENE_CONTROLLER 23 + +#define ID_S_CUSTOM 24 + +// Global Vars +unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds) +boolean metric = true; +long randNumber; + +// Instanciate MySersors Gateway +MySensor gw(CE_PIN,CS_PIN); + +//Instanciate Messages objects + +#ifdef ID_S_DOOR + MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED); +#endif + +#ifdef ID_S_MOTION + MyMessage msg_S_MOTION_A(ID_S_MOTION,V_ARMED); + MyMessage msg_S_MOTION_T(ID_S_MOTION,V_TRIPPED); +#endif + +#ifdef ID_S_SMOKE + MyMessage msg_S_SMOKE(ID_S_SMOKE,V_TRIPPED); +#endif + +#ifdef ID_S_LIGHT + MyMessage msg_S_LIGHT(ID_S_LIGHT,V_LIGHT); +#endif + +#ifdef ID_S_DIMMER + MyMessage msg_S_DIMMER(ID_S_DIMMER,V_DIMMER); +#endif + +#ifdef ID_S_COVER + MyMessage msg_S_COVER_U(ID_S_COVER,V_UP); + MyMessage msg_S_COVER_D(ID_S_COVER,V_DOWN); + MyMessage msg_S_COVER_S(ID_S_COVER,V_STOP); +#endif + +#ifdef ID_S_TEMP + MyMessage msg_S_TEMP(ID_S_TEMP,V_TEMP); +#endif + +#ifdef ID_S_HUM + MyMessage msg_S_HUM(ID_S_HUM,V_HUM); +#endif + +#ifdef ID_S_BARO + MyMessage msg_S_BARO_P(ID_S_BARO,V_PRESSURE); + MyMessage msg_S_BARO_F(ID_S_BARO,V_FORECAST); +#endif + +#ifdef ID_S_WIND + MyMessage msg_S_WIND_S(ID_S_WIND,V_WIND); + MyMessage msg_S_WIND_G(ID_S_WIND,V_GUST); + MyMessage msg_S_WIND_D(ID_S_WIND,V_DIRECTION); +#endif + +#ifdef ID_S_RAIN + MyMessage msg_S_RAIN_A(ID_S_RAIN,V_RAIN); + MyMessage msg_S_RAIN_R(ID_S_RAIN,V_RAINRATE); +#endif + +#ifdef ID_S_UV + MyMessage msg_S_UV(ID_S_UV,V_UV); +#endif + +#ifdef ID_S_WEIGHT + MyMessage msg_S_WEIGHT(ID_S_WEIGHT,V_WEIGHT); +#endif + +#ifdef ID_S_POWER + MyMessage msg_S_POWER_I(ID_S_POWER,V_IMPEDANCE); + MyMessage msg_S_POWER_W(ID_S_POWER,V_WATT); + MyMessage msg_S_POWER_K(ID_S_POWER,V_KWH); + MyMessage msg_S_POWER_V(ID_S_POWER,V_VOLTAGE); + MyMessage msg_S_POWER_C(ID_S_POWER,V_CURRENT); +#endif + +#ifdef ID_S_HEATER + MyMessage msg_S_HEATER_M(ID_S_HEATER,V_HEATER); + MyMessage msg_S_HEATER_S(ID_S_HEATER,V_HEATER_SW); +#endif + +#ifdef ID_S_DISTANCE + MyMessage msg_S_DISTANCE(ID_S_DISTANCE,V_DISTANCE); +#endif + +#ifdef ID_S_LIGHT_LEVEL + MyMessage msg_S_LIGHT_LEVEL(ID_S_LIGHT_LEVEL,V_LIGHT_LEVEL); +#endif + +#ifdef ID_S_LOCK + MyMessage msg_S_LOCK(ID_S_LOCK,V_LOCK_STATUS); +#endif + +#ifdef ID_S_IR + MyMessage msg_S_IR_S(ID_S_IR,V_IR_SEND); + MyMessage msg_S_IR_R(ID_S_IR,V_IR_RECEIVE); +#endif + +#ifdef ID_S_WATER + MyMessage msg_S_WATER_F(ID_S_WATER,V_FLOW); + MyMessage msg_S_WATER_V(ID_S_WATER,V_VOLUME); +#endif + +#ifdef ID_S_AIR_QUALITY + MyMessage msg_S_AIR_QUALITY(ID_S_AIR_QUALITY,V_VAR1); +#endif + +#ifdef ID_S_DUST + MyMessage msg_S_DUST(ID_S_DUST,V_DUST_LEVEL); +#endif + +#ifdef ID_S_SCENE_CONTROLLER + MyMessage msg_S_SCENE_CONTROLLER_ON(ID_S_SCENE_CONTROLLER,V_SCENE_ON); + MyMessage msg_S_SCENE_CONTROLLER_OF(ID_S_SCENE_CONTROLLER,V_SCENE_OFF); +#endif + +#ifdef ID_S_CUSTOM + MyMessage msg_S_CUSTOM_2(ID_S_CUSTOM,V_VAR2); + MyMessage msg_S_CUSTOM_3(ID_S_CUSTOM,V_VAR3); + MyMessage msg_S_CUSTOM_4(ID_S_CUSTOM,V_VAR4); + MyMessage msg_S_CUSTOM_5(ID_S_CUSTOM,V_VAR5); +#endif + + + + +void setup() +{ + // Random SEED + randomSeed(analogRead(0)); + + // Start the gateway + gw.begin(incomingMessage,254); + gw.wait(LONG_WAIT); + Serial.println("GW Started"); + + // Send the Sketch Version Information to the Gateway + Serial.print("Send Sketch Info: "); + gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); + Serial.print(SKETCH_NAME); + Serial.println(SKETCH_VERSION); + gw.wait(LONG_WAIT); + + // Get controller configuration + Serial.print("Get Config: "); + metric = gw.getConfig().isMetric; + Serial.println(metric ? "Metric":"Imperial"); + gw.wait(LONG_WAIT); + + // Register all sensors to gw (they will be created as child devices) + Serial.println("Presenting Nodes"); + Serial.println("________________"); + + #ifdef ID_S_DOOR + Serial.println(" S_DOOR"); + gw.present(ID_S_DOOR,S_DOOR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_MOTION + Serial.println(" S_MOTION"); + gw.present(ID_S_MOTION,S_MOTION); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SMOKE + Serial.println(" S_SMOKE"); + gw.present(ID_S_SMOKE,S_SMOKE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT + Serial.println(" S_LIGHT"); + gw.present(ID_S_LIGHT,S_LIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DIMMER + Serial.println(" S_DIMMER"); + gw.present(ID_S_DIMMER,S_DIMMER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_COVER + Serial.println(" S_COVER"; + gw.present(ID_S_COVER,S_COVER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_TEMP + Serial.println(" S_TMEP"); + gw.present(ID_S_TEMP,S_TEMP); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HUM + Serial.println(" S_HUM"); + gw.present(ID_S_HUM,S_HUM); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_BARO + Serial.println(" S_BARO"); + gw.present(ID_S_BARO,S_BARO); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WIND + Serial.println(" S_WIND"); + gw.present(ID_S_WIND,S_WIND); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_RAIN + Serial.println(" S_RAIN"); + gw.present(ID_S_RAIN,S_RAIN); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_UV + Serial.println(" S_UV"); + gw.present(ID_S_UV,S_UV); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WEIGHT + Serial.println(" S_WEIGHT"): + gw.present(ID_S_WEIGHT,S_WEIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_POWER + Serial.println(" S_POWER"); + gw.present(ID_S_POWER,S_POWER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HEATER + Serial.println(" S_HEATER"); + gw.present(ID_S_HEATER,S_HEATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DISTANCE + Serial.println(" S_DISTANCE"); + gw.present(ID_S_DISTANCE,S_DISTANCE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT_LEVEL + Serial.println(" S_LIGHT_LEVEL"); + gw.present(ID_S_LIGHT_LEVEL,S_LIGHT_LEVEL); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LOCK + Serial.println(" S_LOCK"); + gw.present(ID_S_LOCK,S_LOCK); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_IR + Serial.println(" S_IR"); + gw.present(ID_S_IR,S_IR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WATER + Serial.println(" S_WATER"); + gw.present(ID_S_WATER,S_WATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_AIR_QUALITY + Serial.println(" S_AIR_QUALITY"); + gw.present(ID_S_AIR_QUALITY,S_AIR_QUALITY); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DUST + Serial.println(" S_DUST"); + gw.present(ID_S_DUST,S_DUST); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + Serial.println(" S_SCENE_CONTROLLER"); + gw.present(ID_S_SCENE_CONTROLLER,S_SCENE_CONTROLLER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_CUSTOM + Serial.println(" S_CUSTOM"); + gw.present(ID_S_CUSTOM,S_CUSTOM); + gw.wait(SHORT_WAIT); + #endif + + + +Serial.println("________________"); + +} + +void loop() +{ + Serial.println(""); + Serial.println(""); + Serial.println(""); + Serial.println("#########################"); + randNumber=random(0,101); + + Serial.print("RandomNumber:"); + Serial.println(randNumber); + // Send fake battery level + Serial.println("Send Battery Level"); + gw.sendBatteryLevel(randNumber); + gw.wait(LONG_WAIT); + + // Request time + Serial.println("Request Time"); + gw.requestTime(receiveTime); + gw.wait(LONG_WAIT); + + //Read Sensors + #ifdef S_ID_DOOR + door(); + #endif + + #ifdef ID_S_MOTION + motion(); + #endif + + #ifdef ID_S_SMOKE + smoke(); + #endif + + #ifdef ID_S_LIGHT + light(); + #endif + + #ifdef ID_S_DIMMER + dimmer(); + #endif + + #ifdef ID_S_COVER + cover(); + #endif + + #ifdef ID_S_TEMP + temp(); + #endif + + #ifdef ID_S_HUM + hum(); + #endif + + #ifdef ID_S_BARO + baro(); + #endif + + #ifdef ID_S_WIND + wind(); + #endif + + #ifdef ID_S_RAIN + rain(); + #endif + + #ifdef ID_S_UV + uv(); + #endif + + #ifdef ID_S_WEIGHT + weight(); + #endif + + #ifdef ID_S_POWER + power(); + #endif + + #ifdef ID_S_HEATER + heater(); + #endif + + #ifdef ID_S_DISTANCE + distance(); + #endif + + #ifdef ID_S_LIGHT_LEVEL + light_level(); + #endif + + #ifdef ID_S_LOCK + lock(); + #endif + + #ifdef ID_S_IR + ir(); + #endif + + #ifdef ID_S_WATER + water(); + #endif + + #ifdef ID_S_AIR_QUALITY + air(); + #endif + + #ifdef ID_S_DUST + dust(); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + scene(); + #endif + + #ifdef ID_S_CUSTOM + custom(); + #endif + + gw.sendBatteryLevel(randNumber); + gw.wait(SHORT_WAIT); + gw.process(); + Serial.println("#########################"); + gw.wait(SLEEP_TIME); //sleep a bit +} + +// This is called when a new time value was received +void receiveTime(unsigned long controllerTime) { + + Serial.print("Time value received: "); + Serial.println(controllerTime); + +} + +//void door(){} + +#ifdef S_ID_DOOR +void door(){ + + Serial.print("Door is: " ); + + if (randNumber <= 50) { + Serial.println("Open"); + gw.send(msg_S_DOOR.set(1)); + } else { + Serial.println("Closed"); + gw.send(msg_S_DOOR.set(0)); + } + +} +#endif + +#ifdef ID_S_MOTION +void motion(){ + + Serial.print("Motion is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_MOTION_T.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_MOTION_T.set(0)); + } + +} +#endif + +#ifdef ID_S_SMOKE +void smoke(){ + + Serial.print("Smoke is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_SMOKE.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_SMOKE.set(0)); + } + +} +#endif + +#ifdef ID_S_LIGHT +void light(){ + + bool isLightOn = gw.loadState(ID_S_LIGHT); + + Serial.print("Light is: " ); + + if (isLightOn) { + Serial.println("On"); + gw.send(msg_S_LIGHT.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LIGHT.set(0)); + } + +} +#endif + +#ifdef ID_S_DIMMER +void dimmer(){ + + int dimmerVal = gw.loadState(ID_S_DIMMER); + + Serial.print("Dimmer is set to: " ); + Serial.println(dimmerVal); + + gw.send(msg_S_DIMMER.set(dimmerVal)); + +} +#endif + +#ifdef ID_S_COVER +void cover(){ + + int coverVal = gw.loadState(ID_S_COVER); + + Serial.print("Cover is : " ); + + switch (coverVal) { + case 0: + Serial.println("Opening"); + gw.send(msg_S_COVER_U.set(V_UP)); + break; + case 1: + Serial.println("Closing"); + gw.send(msg_S_COVER_D.set(V_DOWN)); + break; + default: + Serial.println("Idle"); + gw.send(msg_S_COVER_S.set(V_STOP)); + } + +} +#endif + +#ifdef ID_S_TEMP +void temp(){ + + Serial.print("Temperature is: " ); + Serial.println(map(randNumber,1,100,0,45)); + + gw.send(msg_S_TEMP.set(map(randNumber,1,100,0,45))); + +} +#endif + +#ifdef ID_S_HUM +void hum(){ + + Serial.print("Humitidty is: " ); + Serial.println(randNumber); + + gw.send(msg_S_HUM.set(randNumber)); + +} +#endif + +#ifdef ID_S_BARO +void baro(){ + + const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; + long pressure = map(randNumber,1,100,87000,108600); + int forecast = map(randNumber,1,100,0,5); + + Serial.print("Atmosferic Pressure is: " ); + Serial.println(pressure); + gw.send(msg_S_BARO_P.set(pressure)); + + Serial.print("Weather forecast: " ); + Serial.println(weather[forecast]); + gw.send(msg_S_BARO_F.set(weather[forecast])); + +} +#endif + +#ifdef ID_S_WIND +void wind(){ + + Serial.print("Wind Speed is: " ); + Serial.println(randNumber); + gw.send(msg_S_WIND_S.set(randNumber)); + + Serial.print("Wind Gust is: " ); + Serial.println(randNumber+10); + gw.send(msg_S_WIND_G.set(randNumber+10)); + + Serial.print("Wind Direction is: " ); + Serial.println(map(randNumber,1,100,0,360)); + gw.send(msg_S_WIND_D.set(map(randNumber,1,100,0,360))); + +} +#endif + +#ifdef ID_S_RAIN +void rain(){ + + Serial.print("Rain ammount is: " ); + Serial.println(randNumber); + + gw.send(msg_S_RAIN_A.set(randNumber)); + + Serial.print("Rain rate is: " ); + Serial.println(randNumber/60); + + gw.send(msg_S_RAIN_R.set(randNumber/60,1)); + +} +#endif + +#ifdef ID_S_UV +void uv(){ + + Serial.print("Ultra Violet level is: " ); + Serial.println(map(randNumber,1,100,0,15)); + + gw.send(msg_S_UV.set(map(randNumber,1,100,0,15))); + +} +#endif + +#ifdef ID_S_WEIGHT +void weight(){ + + Serial.print("Weight is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WEIGHT.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_POWER +void power(){ + + Serial.print("Impedance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_I.set(map(randNumber,1,100,0,150))); + + Serial.print("Watt is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_W.set(map(randNumber,1,100,0,150))); + + Serial.print("KWH is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_K.set(map(randNumber,1,100,0,150))); + + Serial.print("Voltage is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_V.set(map(randNumber,1,100,0,150))); + + Serial.print("Current is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_C.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_HEATER +void heater(){ + int heater_mode = gw.loadState(ID_S_HEATER); + bool heater_switch = gw.loadState(ID_S_HEATER+1); + + Serial.print("Heater mode is: " ); + + if (heater_mode == 0){ + Serial.println("Off"); + } + else if (heater_mode == 1){ + Serial.println("Heat On"); + } + else if (heater_mode == 2){ + Serial.println("Cool On"); + } + else if (heater_mode == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(heater_mode); + } + + gw.send(msg_S_HEATER_M.set(heater_mode)); + + Serial.print("Heater is: " ); + Serial.println(heater_switch?"On":"Off"); + + gw.send(msg_S_HEATER_S.set(heater_switch)); + +} +#endif + +#ifdef ID_S_DISTANCE +void distance(){ + + Serial.print("Distance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_DISTANCE.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LIGHT_LEVEL +void light_level(){ + + Serial.print("Light is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_LIGHT_LEVEL.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LOCK +void lock(){ + + bool isLocked = gw.loadState(ID_S_LOCK); + + Serial.print("Lock is: " ); + + if (isLocked) { + Serial.println("On"); + gw.send(msg_S_LOCK.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LOCK.set(0)); + } + +} +#endif + +#ifdef ID_S_IR +void ir(){ + + int irVal = gw.loadState(ID_S_IR); + + Serial.print("Infrared is: " ); + Serial.println(irVal); + + gw.send(msg_S_IR_S.set(irVal)); + +} +#endif + +#ifdef ID_S_WATER +void water(){ + + Serial.print("Water flow is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_F.set(map(randNumber,1,100,0,150))); + + Serial.print("Water volume is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_V.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_AIR_QUALITY +void air(){ + + Serial.print("Air Quality is: " ); + Serial.println(randNumber); + + gw.send(msg_S_AIR_QUALITY.set(randNumber)); + +} +#endif + +#ifdef ID_S_DUST +void dust(){ + + Serial.print("Dust level is: " ); + Serial.println(randNumber); + + gw.send(msg_S_DUST.set(randNumber)); + +} +#endif + +#ifdef ID_S_SCENE_CONTROLLER +void scene(){ + + bool isSceneOn = gw.loadState(ID_S_SCENE_CONTROLLER); + + Serial.print("Scene is: " ); + Serial.println(isSceneOn ? "On":"Off"); + + if(isSceneOn) + gw.send(msg_S_SCENE_CONTROLLER_ON.set(isSceneOn)); + else + gw.send(msg_S_SCENE_CONTROLLER_OF.set(isSceneOn)); + +} +#endif + +#ifdef ID_S_CUSTOM +void custom(){ + + Serial.print("Custom value is: " ); + Serial.println(randNumber); + + gw.send(msg_S_CUSTOM_2.set(randNumber)); + gw.send(msg_S_CUSTOM_3.set(randNumber)); + gw.send(msg_S_CUSTOM_4.set(randNumber)); + gw.send(msg_S_CUSTOM_5.set(randNumber)); + +} +#endif + + +void incomingMessage(const MyMessage &message) { + switch (message.type) { + #ifdef ID_S_LIGHT + case V_LIGHT: + gw.saveState(ID_S_LIGHT, message.getBool()); + Serial.print("Incoming change for ID_S_LIGHT:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()); + break; + #endif + + #ifdef ID_S_DIMMER + case V_DIMMER: + if ((message.getInt()<0)||(message.getInt()>100)) { + Serial.println( "V_DIMMER data invalid (should be 0..100)" ); + break; + } + gw.saveState(ID_S_DIMMER, message.getInt()); + Serial.print("Incoming change for ID_S_DIMMER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_COVER + case V_UP: + gw.saveState(ID_S_COVER, 0); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_UP"); + break; + + case V_DOWN: + gw.saveState(ID_S_COVER, 1); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_DOWN"); + break; + + case V_STOP: + gw.saveState(ID_S_COVER, 2); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_STOP"); + break; + #endif + + #ifdef ID_S_HEATER + case V_HEATER: + gw.saveState(ID_S_HEATER, message.getInt()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + + if (message.getInt() == 0){ + Serial.println("Off"); + } + else if (message.getInt() == 1){ + Serial.println("Heat On"); + } + else if (message.getInt() == 2){ + Serial.println("Cool On"); + } + else if (message.getInt() == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(message.getInt()); + } + break; + + case V_HEATER_SW: + gw.saveState(ID_S_HEATER+1, message.getBool()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println((message.getBool() ? "On":"Off")); + break; + #endif + + #ifdef ID_S_LOCK + case V_LOCK_STATUS: + gw.saveState(ID_S_LOCK, message.getBool()); + Serial.print("Incoming change for ID_S_LOCK:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()?"Locked":"Unlocked"); + break; + #endif + + #ifdef ID_S_IR + case V_IR_RECEIVE: + gw.saveState(ID_S_IR, message.getInt()); + Serial.print("Incoming change for ID_S_IR:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_SCENE_CONTROLLER + case V_SCENE_ON: + gw.saveState(ID_S_SCENE_CONTROLLER, 1); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("On"); + break; + case V_SCENE_OFF: + gw.saveState(ID_S_SCENE_CONTROLLER, 0); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("Off"); + break; + #endif + + default: + Serial.print("Unknown/UnImplemented message type:"); + Serial.println(message.type); + } + +} + + + + + + + From 0b2aa6dd16582bd47fd12071284262ce436bce97 Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:04:58 -0400 Subject: [PATCH 59/79] Delete MockMySensors --- libraries/MySensors/examples/MockMySensors | 1018 -------------------- 1 file changed, 1018 deletions(-) delete mode 100644 libraries/MySensors/examples/MockMySensors diff --git a/libraries/MySensors/examples/MockMySensors b/libraries/MySensors/examples/MockMySensors deleted file mode 100644 index 4397208..0000000 --- a/libraries/MySensors/examples/MockMySensors +++ /dev/null @@ -1,1018 +0,0 @@ -/* -* FakeMySensors -* -* This skecth is intended to crate fake sensors which register and respond to the controller -* -* Barduino 2015 -*/ - -#include -#include - -// SPI Pins -#define CE_PIN 9 -#define CS_PIN 10 - -// Wait times -#define LONG_WAIT 500 -#define SHORT_WAIT 50 - -#define SKETCH_NAME "FakeMySensors " -#define SKETCH_VERSION "v0.2" - -// Define Sensors ids -/* S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, - S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, - S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, - S_SCENE_CONTROLLER -*/ - -////#define ID_S_ARDUINO_NODE //auto defined in initialization -////#define ID_S_ARDUINO_REPEATER_NODE //auto defined in initialization - -//#define ID_S_DOOR 1 -//#define ID_S_MOTION 2 -//#define ID_S_SMOKE 3 -//#define ID_S_LIGHT 4 -//#define ID_S_DIMMER 5 -//#define ID_S_COVER 6 -//#define ID_S_TEMP 7 -//#define ID_S_HUM 8 -//#define ID_S_BARO 9 -//#define ID_S_WIND 10 -//#define ID_S_RAIN 11 -//#define ID_S_UV 12 -//#define ID_S_WEIGHT 13 -#define ID_S_POWER 14 -#define ID_S_HEATER 15 -#define ID_S_DISTANCE 16 -#define ID_S_LIGHT_LEVEL 17 -#define ID_S_LOCK 18 -#define ID_S_IR 19 -#define ID_S_WATER 20 -#define ID_S_AIR_QUALITY 21 -#define ID_S_DUST 22 -#define ID_S_SCENE_CONTROLLER 23 - -#define ID_S_CUSTOM 24 - -// Global Vars -unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds) -boolean metric = true; -long randNumber; - -// Instanciate MySersors Gateway -MySensor gw(CE_PIN,CS_PIN); - -//Instanciate Messages objects - -#ifdef ID_S_DOOR - MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED); -#endif - -#ifdef ID_S_MOTION - MyMessage msg_S_MOTION_A(ID_S_MOTION,V_ARMED); - MyMessage msg_S_MOTION_T(ID_S_MOTION,V_TRIPPED); -#endif - -#ifdef ID_S_SMOKE - MyMessage msg_S_SMOKE(ID_S_SMOKE,V_TRIPPED); -#endif - -#ifdef ID_S_LIGHT - MyMessage msg_S_LIGHT(ID_S_LIGHT,V_LIGHT); -#endif - -#ifdef ID_S_DIMMER - MyMessage msg_S_DIMMER(ID_S_DIMMER,V_DIMMER); -#endif - -#ifdef ID_S_COVER - MyMessage msg_S_COVER_U(ID_S_COVER,V_UP); - MyMessage msg_S_COVER_D(ID_S_COVER,V_DOWN); - MyMessage msg_S_COVER_S(ID_S_COVER,V_STOP); -#endif - -#ifdef ID_S_TEMP - MyMessage msg_S_TEMP(ID_S_TEMP,V_TEMP); -#endif - -#ifdef ID_S_HUM - MyMessage msg_S_HUM(ID_S_HUM,V_HUM); -#endif - -#ifdef ID_S_BARO - MyMessage msg_S_BARO_P(ID_S_BARO,V_PRESSURE); - MyMessage msg_S_BARO_F(ID_S_BARO,V_FORECAST); -#endif - -#ifdef ID_S_WIND - MyMessage msg_S_WIND_S(ID_S_WIND,V_WIND); - MyMessage msg_S_WIND_G(ID_S_WIND,V_GUST); - MyMessage msg_S_WIND_D(ID_S_WIND,V_DIRECTION); -#endif - -#ifdef ID_S_RAIN - MyMessage msg_S_RAIN_A(ID_S_RAIN,V_RAIN); - MyMessage msg_S_RAIN_R(ID_S_RAIN,V_RAINRATE); -#endif - -#ifdef ID_S_UV - MyMessage msg_S_UV(ID_S_UV,V_UV); -#endif - -#ifdef ID_S_WEIGHT - MyMessage msg_S_WEIGHT(ID_S_WEIGHT,V_WEIGHT); -#endif - -#ifdef ID_S_POWER - MyMessage msg_S_POWER_I(ID_S_POWER,V_IMPEDANCE); - MyMessage msg_S_POWER_W(ID_S_POWER,V_WATT); - MyMessage msg_S_POWER_K(ID_S_POWER,V_KWH); - MyMessage msg_S_POWER_V(ID_S_POWER,V_VOLTAGE); - MyMessage msg_S_POWER_C(ID_S_POWER,V_CURRENT); -#endif - -#ifdef ID_S_HEATER - MyMessage msg_S_HEATER_M(ID_S_HEATER,V_HEATER); - MyMessage msg_S_HEATER_S(ID_S_HEATER,V_HEATER_SW); -#endif - -#ifdef ID_S_DISTANCE - MyMessage msg_S_DISTANCE(ID_S_DISTANCE,V_DISTANCE); -#endif - -#ifdef ID_S_LIGHT_LEVEL - MyMessage msg_S_LIGHT_LEVEL(ID_S_LIGHT_LEVEL,V_LIGHT_LEVEL); -#endif - -#ifdef ID_S_LOCK - MyMessage msg_S_LOCK(ID_S_LOCK,V_LOCK_STATUS); -#endif - -#ifdef ID_S_IR - MyMessage msg_S_IR_S(ID_S_IR,V_IR_SEND); - MyMessage msg_S_IR_R(ID_S_IR,V_IR_RECEIVE); -#endif - -#ifdef ID_S_WATER - MyMessage msg_S_WATER_F(ID_S_WATER,V_FLOW); - MyMessage msg_S_WATER_V(ID_S_WATER,V_VOLUME); -#endif - -#ifdef ID_S_AIR_QUALITY - MyMessage msg_S_AIR_QUALITY(ID_S_AIR_QUALITY,V_VAR1); -#endif - -#ifdef ID_S_DUST - MyMessage msg_S_DUST(ID_S_DUST,V_DUST_LEVEL); -#endif - -#ifdef ID_S_SCENE_CONTROLLER - MyMessage msg_S_SCENE_CONTROLLER_ON(ID_S_SCENE_CONTROLLER,V_SCENE_ON); - MyMessage msg_S_SCENE_CONTROLLER_OF(ID_S_SCENE_CONTROLLER,V_SCENE_OFF); -#endif - -#ifdef ID_S_CUSTOM - MyMessage msg_S_CUSTOM_2(ID_S_CUSTOM,V_VAR2); - MyMessage msg_S_CUSTOM_3(ID_S_CUSTOM,V_VAR3); - MyMessage msg_S_CUSTOM_4(ID_S_CUSTOM,V_VAR4); - MyMessage msg_S_CUSTOM_5(ID_S_CUSTOM,V_VAR5); -#endif - - - - -void setup() -{ - // Random SEED - randomSeed(analogRead(0)); - - // Start the gateway - gw.begin(incomingMessage,254); - gw.wait(LONG_WAIT); - Serial.println("GW Started"); - - // Send the Sketch Version Information to the Gateway - Serial.print("Send Sketch Info: "); - gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); - Serial.print(SKETCH_NAME); - Serial.println(SKETCH_VERSION); - gw.wait(LONG_WAIT); - - // Get controller configuration - Serial.print("Get Config: "); - metric = gw.getConfig().isMetric; - Serial.println(metric ? "Metric":"Imperial"); - gw.wait(LONG_WAIT); - - // Register all sensors to gw (they will be created as child devices) - Serial.println("Presenting Nodes"); - Serial.println("________________"); - - #ifdef ID_S_DOOR - Serial.println(" S_DOOR"); - gw.present(ID_S_DOOR,S_DOOR); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_MOTION - Serial.println(" S_MOTION"); - gw.present(ID_S_MOTION,S_MOTION); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_SMOKE - Serial.println(" S_SMOKE"); - gw.present(ID_S_SMOKE,S_SMOKE); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_LIGHT - Serial.println(" S_LIGHT"); - gw.present(ID_S_LIGHT,S_LIGHT); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_DIMMER - Serial.println(" S_DIMMER"); - gw.present(ID_S_DIMMER,S_DIMMER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_COVER - Serial.println(" S_COVER"; - gw.present(ID_S_COVER,S_COVER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_TEMP - Serial.println(" S_TMEP"); - gw.present(ID_S_TEMP,S_TEMP); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_HUM - Serial.println(" S_HUM"); - gw.present(ID_S_HUM,S_HUM); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_BARO - Serial.println(" S_BARO"); - gw.present(ID_S_BARO,S_BARO); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_WIND - Serial.println(" S_WIND"); - gw.present(ID_S_WIND,S_WIND); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_RAIN - Serial.println(" S_RAIN"); - gw.present(ID_S_RAIN,S_RAIN); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_UV - Serial.println(" S_UV"); - gw.present(ID_S_UV,S_UV); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_WEIGHT - Serial.println(" S_WEIGHT"): - gw.present(ID_S_WEIGHT,S_WEIGHT); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_POWER - Serial.println(" S_POWER"); - gw.present(ID_S_POWER,S_POWER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_HEATER - Serial.println(" S_HEATER"); - gw.present(ID_S_HEATER,S_HEATER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_DISTANCE - Serial.println(" S_DISTANCE"); - gw.present(ID_S_DISTANCE,S_DISTANCE); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_LIGHT_LEVEL - Serial.println(" S_LIGHT_LEVEL"); - gw.present(ID_S_LIGHT_LEVEL,S_LIGHT_LEVEL); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_LOCK - Serial.println(" S_LOCK"); - gw.present(ID_S_LOCK,S_LOCK); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_IR - Serial.println(" S_IR"); - gw.present(ID_S_IR,S_IR); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_WATER - Serial.println(" S_WATER"); - gw.present(ID_S_WATER,S_WATER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_AIR_QUALITY - Serial.println(" S_AIR_QUALITY"); - gw.present(ID_S_AIR_QUALITY,S_AIR_QUALITY); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_DUST - Serial.println(" S_DUST"); - gw.present(ID_S_DUST,S_DUST); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_SCENE_CONTROLLER - Serial.println(" S_SCENE_CONTROLLER"); - gw.present(ID_S_SCENE_CONTROLLER,S_SCENE_CONTROLLER); - gw.wait(SHORT_WAIT); - #endif - - #ifdef ID_S_CUSTOM - Serial.println(" S_CUSTOM"); - gw.present(ID_S_CUSTOM,S_CUSTOM); - gw.wait(SHORT_WAIT); - #endif - - - -Serial.println("________________"); - -} - -void loop() -{ - Serial.println(""); - Serial.println(""); - Serial.println(""); - Serial.println("#########################"); - randNumber=random(0,101); - - Serial.print("RandomNumber:"); - Serial.println(randNumber); - // Send fake battery level - Serial.println("Send Battery Level"); - gw.sendBatteryLevel(randNumber); - gw.wait(LONG_WAIT); - - // Request time - Serial.println("Request Time"); - gw.requestTime(receiveTime); - gw.wait(LONG_WAIT); - - //Read Sensors - #ifdef S_ID_DOOR - door(); - #endif - - #ifdef ID_S_MOTION - motion(); - #endif - - #ifdef ID_S_SMOKE - smoke(); - #endif - - #ifdef ID_S_LIGHT - light(); - #endif - - #ifdef ID_S_DIMMER - dimmer(); - #endif - - #ifdef ID_S_COVER - cover(); - #endif - - #ifdef ID_S_TEMP - temp(); - #endif - - #ifdef ID_S_HUM - hum(); - #endif - - #ifdef ID_S_BARO - baro(); - #endif - - #ifdef ID_S_WIND - wind(); - #endif - - #ifdef ID_S_RAIN - rain(); - #endif - - #ifdef ID_S_UV - uv(); - #endif - - #ifdef ID_S_WEIGHT - weight(); - #endif - - #ifdef ID_S_POWER - power(); - #endif - - #ifdef ID_S_HEATER - heater(); - #endif - - #ifdef ID_S_DISTANCE - distance(); - #endif - - #ifdef ID_S_LIGHT_LEVEL - light_level(); - #endif - - #ifdef ID_S_LOCK - lock(); - #endif - - #ifdef ID_S_IR - ir(); - #endif - - #ifdef ID_S_WATER - water(); - #endif - - #ifdef ID_S_AIR_QUALITY - air(); - #endif - - #ifdef ID_S_DUST - dust(); - #endif - - #ifdef ID_S_SCENE_CONTROLLER - scene(); - #endif - - #ifdef ID_S_CUSTOM - custom(); - #endif - - gw.sendBatteryLevel(randNumber); - gw.wait(SHORT_WAIT); - gw.process(); - Serial.println("#########################"); - gw.wait(SLEEP_TIME); //sleep a bit -} - -// This is called when a new time value was received -void receiveTime(unsigned long controllerTime) { - - Serial.print("Time value received: "); - Serial.println(controllerTime); - -} - -//void door(){} - -#ifdef S_ID_DOOR -void door(){ - - Serial.print("Door is: " ); - - if (randNumber <= 50) { - Serial.println("Open"); - gw.send(msg_S_DOOR.set(1)); - } else { - Serial.println("Closed"); - gw.send(msg_S_DOOR.set(0)); - } - -} -#endif - -#ifdef ID_S_MOTION -void motion(){ - - Serial.print("Motion is: " ); - - if (randNumber <= 50) { - Serial.println("Active"); - gw.send(msg_S_MOTION_T.set(1)); - } else { - Serial.println("Quiet"); - gw.send(msg_S_MOTION_T.set(0)); - } - -} -#endif - -#ifdef ID_S_SMOKE -void smoke(){ - - Serial.print("Smoke is: " ); - - if (randNumber <= 50) { - Serial.println("Active"); - gw.send(msg_S_SMOKE.set(1)); - } else { - Serial.println("Quiet"); - gw.send(msg_S_SMOKE.set(0)); - } - -} -#endif - -#ifdef ID_S_LIGHT -void light(){ - - bool isLightOn = gw.loadState(ID_S_LIGHT); - - Serial.print("Light is: " ); - - if (isLightOn) { - Serial.println("On"); - gw.send(msg_S_LIGHT.set(1)); - } else { - Serial.println("Off"); - gw.send(msg_S_LIGHT.set(0)); - } - -} -#endif - -#ifdef ID_S_DIMMER -void dimmer(){ - - int dimmerVal = gw.loadState(ID_S_DIMMER); - - Serial.print("Dimmer is set to: " ); - Serial.println(dimmerVal); - - gw.send(msg_S_DIMMER.set(dimmerVal)); - -} -#endif - -#ifdef ID_S_COVER -void cover(){ - - int coverVal = gw.loadState(ID_S_COVER); - - Serial.print("Cover is : " ); - - switch (coverVal) { - case 0: - Serial.println("Opening"); - gw.send(msg_S_COVER_U.set(V_UP)); - break; - case 1: - Serial.println("Closing"); - gw.send(msg_S_COVER_D.set(V_DOWN)); - break; - default: - Serial.println("Idle"); - gw.send(msg_S_COVER_S.set(V_STOP)); - } - -} -#endif - -#ifdef ID_S_TEMP -void temp(){ - - Serial.print("Temperature is: " ); - Serial.println(map(randNumber,1,100,0,45)); - - gw.send(msg_S_TEMP.set(map(randNumber,1,100,0,45))); - -} -#endif - -#ifdef ID_S_HUM -void hum(){ - - Serial.print("Humitidty is: " ); - Serial.println(randNumber); - - gw.send(msg_S_HUM.set(randNumber)); - -} -#endif - -#ifdef ID_S_BARO -void baro(){ - - const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; - long pressure = map(randNumber,1,100,87000,108600); - int forecast = map(randNumber,1,100,0,5); - - Serial.print("Atmosferic Pressure is: " ); - Serial.println(pressure); - gw.send(msg_S_BARO_P.set(pressure)); - - Serial.print("Weather forecast: " ); - Serial.println(weather[forecast]); - gw.send(msg_S_BARO_F.set(weather[forecast])); - -} -#endif - -#ifdef ID_S_WIND -void wind(){ - - Serial.print("Wind Speed is: " ); - Serial.println(randNumber); - gw.send(msg_S_WIND_S.set(randNumber)); - - Serial.print("Wind Gust is: " ); - Serial.println(randNumber+10); - gw.send(msg_S_WIND_G.set(randNumber+10)); - - Serial.print("Wind Direction is: " ); - Serial.println(map(randNumber,1,100,0,360)); - gw.send(msg_S_WIND_D.set(map(randNumber,1,100,0,360))); - -} -#endif - -#ifdef ID_S_RAIN -void rain(){ - - Serial.print("Rain ammount is: " ); - Serial.println(randNumber); - - gw.send(msg_S_RAIN_A.set(randNumber)); - - Serial.print("Rain rate is: " ); - Serial.println(randNumber/60); - - gw.send(msg_S_RAIN_R.set(randNumber/60,1)); - -} -#endif - -#ifdef ID_S_UV -void uv(){ - - Serial.print("Ultra Violet level is: " ); - Serial.println(map(randNumber,1,100,0,15)); - - gw.send(msg_S_UV.set(map(randNumber,1,100,0,15))); - -} -#endif - -#ifdef ID_S_WEIGHT -void weight(){ - - Serial.print("Weight is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_WEIGHT.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_POWER -void power(){ - - Serial.print("Impedance is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_I.set(map(randNumber,1,100,0,150))); - - Serial.print("Watt is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_W.set(map(randNumber,1,100,0,150))); - - Serial.print("KWH is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_K.set(map(randNumber,1,100,0,150))); - - Serial.print("Voltage is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_V.set(map(randNumber,1,100,0,150))); - - Serial.print("Current is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_POWER_C.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_HEATER -void heater(){ - int heater_mode = gw.loadState(ID_S_HEATER); - bool heater_switch = gw.loadState(ID_S_HEATER+1); - - Serial.print("Heater mode is: " ); - - if (heater_mode == 0){ - Serial.println("Off"); - } - else if (heater_mode == 1){ - Serial.println("Heat On"); - } - else if (heater_mode == 2){ - Serial.println("Cool On"); - } - else if (heater_mode == 3){ - Serial.println("Auto Change Over"); - } - else { - Serial.print("Unknown Heater Mode: "); - Serial.println(heater_mode); - } - - gw.send(msg_S_HEATER_M.set(heater_mode)); - - Serial.print("Heater is: " ); - Serial.println(heater_switch?"On":"Off"); - - gw.send(msg_S_HEATER_S.set(heater_switch)); - -} -#endif - -#ifdef ID_S_DISTANCE -void distance(){ - - Serial.print("Distance is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_DISTANCE.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_LIGHT_LEVEL -void light_level(){ - - Serial.print("Light is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_LIGHT_LEVEL.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_LOCK -void lock(){ - - bool isLocked = gw.loadState(ID_S_LOCK); - - Serial.print("Lock is: " ); - - if (isLocked) { - Serial.println("On"); - gw.send(msg_S_LOCK.set(1)); - } else { - Serial.println("Off"); - gw.send(msg_S_LOCK.set(0)); - } - -} -#endif - -#ifdef ID_S_IR -void ir(){ - - int irVal = gw.loadState(ID_S_IR); - - Serial.print("Infrared is: " ); - Serial.println(irVal); - - gw.send(msg_S_IR_S.set(irVal)); - -} -#endif - -#ifdef ID_S_WATER -void water(){ - - Serial.print("Water flow is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_WATER_F.set(map(randNumber,1,100,0,150))); - - Serial.print("Water volume is: " ); - Serial.println(map(randNumber,1,100,0,150)); - - gw.send(msg_S_WATER_V.set(map(randNumber,1,100,0,150))); - -} -#endif - -#ifdef ID_S_AIR_QUALITY -void air(){ - - Serial.print("Air Quality is: " ); - Serial.println(randNumber); - - gw.send(msg_S_AIR_QUALITY.set(randNumber)); - -} -#endif - -#ifdef ID_S_DUST -void dust(){ - - Serial.print("Dust level is: " ); - Serial.println(randNumber); - - gw.send(msg_S_DUST.set(randNumber)); - -} -#endif - -#ifdef ID_S_SCENE_CONTROLLER -void scene(){ - - bool isSceneOn = gw.loadState(ID_S_SCENE_CONTROLLER); - - Serial.print("Scene is: " ); - Serial.println(isSceneOn ? "On":"Off"); - - if(isSceneOn) - gw.send(msg_S_SCENE_CONTROLLER_ON.set(isSceneOn)); - else - gw.send(msg_S_SCENE_CONTROLLER_OF.set(isSceneOn)); - -} -#endif - -#ifdef ID_S_CUSTOM -void custom(){ - - Serial.print("Custom value is: " ); - Serial.println(randNumber); - - gw.send(msg_S_CUSTOM_2.set(randNumber)); - gw.send(msg_S_CUSTOM_3.set(randNumber)); - gw.send(msg_S_CUSTOM_4.set(randNumber)); - gw.send(msg_S_CUSTOM_5.set(randNumber)); - -} -#endif - - -void incomingMessage(const MyMessage &message) { - switch (message.type) { - #ifdef ID_S_LIGHT - case V_LIGHT: - gw.saveState(ID_S_LIGHT, message.getBool()); - Serial.print("Incoming change for ID_S_LIGHT:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getBool()); - break; - #endif - - #ifdef ID_S_DIMMER - case V_DIMMER: - if ((message.getInt()<0)||(message.getInt()>100)) { - Serial.println( "V_DIMMER data invalid (should be 0..100)" ); - break; - } - gw.saveState(ID_S_DIMMER, message.getInt()); - Serial.print("Incoming change for ID_S_DIMMER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getInt()); - break; - #endif - - #ifdef ID_S_COVER - case V_UP: - gw.saveState(ID_S_COVER, 0); - Serial.print("Incoming change for ID_S_COVER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("V_UP"); - break; - - case V_DOWN: - gw.saveState(ID_S_COVER, 1); - Serial.print("Incoming change for ID_S_COVER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("V_DOWN"); - break; - - case V_STOP: - gw.saveState(ID_S_COVER, 2); - Serial.print("Incoming change for ID_S_COVER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("V_STOP"); - break; - #endif - - #ifdef ID_S_HEATER - case V_HEATER: - gw.saveState(ID_S_HEATER, message.getInt()); - Serial.print("Incoming change for ID_S_HEATER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - - if (message.getInt() == 0){ - Serial.println("Off"); - } - else if (message.getInt() == 1){ - Serial.println("Heat On"); - } - else if (message.getInt() == 2){ - Serial.println("Cool On"); - } - else if (message.getInt() == 3){ - Serial.println("Auto Change Over"); - } - else { - Serial.print("Unknown Heater Mode: "); - Serial.println(message.getInt()); - } - break; - - case V_HEATER_SW: - gw.saveState(ID_S_HEATER+1, message.getBool()); - Serial.print("Incoming change for ID_S_HEATER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println((message.getBool() ? "On":"Off")); - break; - #endif - - #ifdef ID_S_LOCK - case V_LOCK_STATUS: - gw.saveState(ID_S_LOCK, message.getBool()); - Serial.print("Incoming change for ID_S_LOCK:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getBool()?"Locked":"Unlocked"); - break; - #endif - - #ifdef ID_S_IR - case V_IR_RECEIVE: - gw.saveState(ID_S_IR, message.getInt()); - Serial.print("Incoming change for ID_S_IR:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println(message.getInt()); - break; - #endif - - #ifdef ID_S_SCENE_CONTROLLER - case V_SCENE_ON: - gw.saveState(ID_S_SCENE_CONTROLLER, 1); - Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("On"); - break; - case V_SCENE_OFF: - gw.saveState(ID_S_SCENE_CONTROLLER, 0); - Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); - Serial.print(message.sensor); - Serial.print(", New status: "); - Serial.println("Off"); - break; - #endif - - default: - Serial.print("Unknown/UnImplemented message type:"); - Serial.println(message.type); - } - -} - - - - - - - From a89469ebc8997cbca1a6d33c213dc54c1c24c1fd Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:17:53 -0400 Subject: [PATCH 60/79] Create MockMySensors.ino # FakeMySensors Arduino sketch to fake sensor for the MySensors Library This skecth is intended to crate fake sensors which register and respond to the controller Barduino 2015 ----------------- Comment/Uncomment the sensors you would like to test Arduino Uno R3 can support about 12 sensors before it runs out of memory. You probably need to turn of the MySensor Lib debug to save some memory Nest step will be to remove the read/write to the eprom and extend to support the v1.5 sensors --- .../examples/MockMySensors/MockMySensors.ino | 1018 +++++++++++++++++ 1 file changed, 1018 insertions(+) create mode 100644 libraries/MySensors/examples/MockMySensors/MockMySensors.ino diff --git a/libraries/MySensors/examples/MockMySensors/MockMySensors.ino b/libraries/MySensors/examples/MockMySensors/MockMySensors.ino new file mode 100644 index 0000000..4397208 --- /dev/null +++ b/libraries/MySensors/examples/MockMySensors/MockMySensors.ino @@ -0,0 +1,1018 @@ +/* +* FakeMySensors +* +* This skecth is intended to crate fake sensors which register and respond to the controller +* +* Barduino 2015 +*/ + +#include +#include + +// SPI Pins +#define CE_PIN 9 +#define CS_PIN 10 + +// Wait times +#define LONG_WAIT 500 +#define SHORT_WAIT 50 + +#define SKETCH_NAME "FakeMySensors " +#define SKETCH_VERSION "v0.2" + +// Define Sensors ids +/* S_DOOR, S_MOTION, S_SMOKE, S_LIGHT, S_DIMMER, S_COVER, S_TEMP, S_HUM, S_BARO, S_WIND, + S_RAIN, S_UV, S_WEIGHT, S_POWER, S_HEATER, S_DISTANCE, S_LIGHT_LEVEL, S_ARDUINO_NODE, + S_ARDUINO_REPEATER_NODE, S_LOCK, S_IR, S_WATER, S_AIR_QUALITY, S_CUSTOM, S_DUST, + S_SCENE_CONTROLLER +*/ + +////#define ID_S_ARDUINO_NODE //auto defined in initialization +////#define ID_S_ARDUINO_REPEATER_NODE //auto defined in initialization + +//#define ID_S_DOOR 1 +//#define ID_S_MOTION 2 +//#define ID_S_SMOKE 3 +//#define ID_S_LIGHT 4 +//#define ID_S_DIMMER 5 +//#define ID_S_COVER 6 +//#define ID_S_TEMP 7 +//#define ID_S_HUM 8 +//#define ID_S_BARO 9 +//#define ID_S_WIND 10 +//#define ID_S_RAIN 11 +//#define ID_S_UV 12 +//#define ID_S_WEIGHT 13 +#define ID_S_POWER 14 +#define ID_S_HEATER 15 +#define ID_S_DISTANCE 16 +#define ID_S_LIGHT_LEVEL 17 +#define ID_S_LOCK 18 +#define ID_S_IR 19 +#define ID_S_WATER 20 +#define ID_S_AIR_QUALITY 21 +#define ID_S_DUST 22 +#define ID_S_SCENE_CONTROLLER 23 + +#define ID_S_CUSTOM 24 + +// Global Vars +unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds) +boolean metric = true; +long randNumber; + +// Instanciate MySersors Gateway +MySensor gw(CE_PIN,CS_PIN); + +//Instanciate Messages objects + +#ifdef ID_S_DOOR + MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED); +#endif + +#ifdef ID_S_MOTION + MyMessage msg_S_MOTION_A(ID_S_MOTION,V_ARMED); + MyMessage msg_S_MOTION_T(ID_S_MOTION,V_TRIPPED); +#endif + +#ifdef ID_S_SMOKE + MyMessage msg_S_SMOKE(ID_S_SMOKE,V_TRIPPED); +#endif + +#ifdef ID_S_LIGHT + MyMessage msg_S_LIGHT(ID_S_LIGHT,V_LIGHT); +#endif + +#ifdef ID_S_DIMMER + MyMessage msg_S_DIMMER(ID_S_DIMMER,V_DIMMER); +#endif + +#ifdef ID_S_COVER + MyMessage msg_S_COVER_U(ID_S_COVER,V_UP); + MyMessage msg_S_COVER_D(ID_S_COVER,V_DOWN); + MyMessage msg_S_COVER_S(ID_S_COVER,V_STOP); +#endif + +#ifdef ID_S_TEMP + MyMessage msg_S_TEMP(ID_S_TEMP,V_TEMP); +#endif + +#ifdef ID_S_HUM + MyMessage msg_S_HUM(ID_S_HUM,V_HUM); +#endif + +#ifdef ID_S_BARO + MyMessage msg_S_BARO_P(ID_S_BARO,V_PRESSURE); + MyMessage msg_S_BARO_F(ID_S_BARO,V_FORECAST); +#endif + +#ifdef ID_S_WIND + MyMessage msg_S_WIND_S(ID_S_WIND,V_WIND); + MyMessage msg_S_WIND_G(ID_S_WIND,V_GUST); + MyMessage msg_S_WIND_D(ID_S_WIND,V_DIRECTION); +#endif + +#ifdef ID_S_RAIN + MyMessage msg_S_RAIN_A(ID_S_RAIN,V_RAIN); + MyMessage msg_S_RAIN_R(ID_S_RAIN,V_RAINRATE); +#endif + +#ifdef ID_S_UV + MyMessage msg_S_UV(ID_S_UV,V_UV); +#endif + +#ifdef ID_S_WEIGHT + MyMessage msg_S_WEIGHT(ID_S_WEIGHT,V_WEIGHT); +#endif + +#ifdef ID_S_POWER + MyMessage msg_S_POWER_I(ID_S_POWER,V_IMPEDANCE); + MyMessage msg_S_POWER_W(ID_S_POWER,V_WATT); + MyMessage msg_S_POWER_K(ID_S_POWER,V_KWH); + MyMessage msg_S_POWER_V(ID_S_POWER,V_VOLTAGE); + MyMessage msg_S_POWER_C(ID_S_POWER,V_CURRENT); +#endif + +#ifdef ID_S_HEATER + MyMessage msg_S_HEATER_M(ID_S_HEATER,V_HEATER); + MyMessage msg_S_HEATER_S(ID_S_HEATER,V_HEATER_SW); +#endif + +#ifdef ID_S_DISTANCE + MyMessage msg_S_DISTANCE(ID_S_DISTANCE,V_DISTANCE); +#endif + +#ifdef ID_S_LIGHT_LEVEL + MyMessage msg_S_LIGHT_LEVEL(ID_S_LIGHT_LEVEL,V_LIGHT_LEVEL); +#endif + +#ifdef ID_S_LOCK + MyMessage msg_S_LOCK(ID_S_LOCK,V_LOCK_STATUS); +#endif + +#ifdef ID_S_IR + MyMessage msg_S_IR_S(ID_S_IR,V_IR_SEND); + MyMessage msg_S_IR_R(ID_S_IR,V_IR_RECEIVE); +#endif + +#ifdef ID_S_WATER + MyMessage msg_S_WATER_F(ID_S_WATER,V_FLOW); + MyMessage msg_S_WATER_V(ID_S_WATER,V_VOLUME); +#endif + +#ifdef ID_S_AIR_QUALITY + MyMessage msg_S_AIR_QUALITY(ID_S_AIR_QUALITY,V_VAR1); +#endif + +#ifdef ID_S_DUST + MyMessage msg_S_DUST(ID_S_DUST,V_DUST_LEVEL); +#endif + +#ifdef ID_S_SCENE_CONTROLLER + MyMessage msg_S_SCENE_CONTROLLER_ON(ID_S_SCENE_CONTROLLER,V_SCENE_ON); + MyMessage msg_S_SCENE_CONTROLLER_OF(ID_S_SCENE_CONTROLLER,V_SCENE_OFF); +#endif + +#ifdef ID_S_CUSTOM + MyMessage msg_S_CUSTOM_2(ID_S_CUSTOM,V_VAR2); + MyMessage msg_S_CUSTOM_3(ID_S_CUSTOM,V_VAR3); + MyMessage msg_S_CUSTOM_4(ID_S_CUSTOM,V_VAR4); + MyMessage msg_S_CUSTOM_5(ID_S_CUSTOM,V_VAR5); +#endif + + + + +void setup() +{ + // Random SEED + randomSeed(analogRead(0)); + + // Start the gateway + gw.begin(incomingMessage,254); + gw.wait(LONG_WAIT); + Serial.println("GW Started"); + + // Send the Sketch Version Information to the Gateway + Serial.print("Send Sketch Info: "); + gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION); + Serial.print(SKETCH_NAME); + Serial.println(SKETCH_VERSION); + gw.wait(LONG_WAIT); + + // Get controller configuration + Serial.print("Get Config: "); + metric = gw.getConfig().isMetric; + Serial.println(metric ? "Metric":"Imperial"); + gw.wait(LONG_WAIT); + + // Register all sensors to gw (they will be created as child devices) + Serial.println("Presenting Nodes"); + Serial.println("________________"); + + #ifdef ID_S_DOOR + Serial.println(" S_DOOR"); + gw.present(ID_S_DOOR,S_DOOR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_MOTION + Serial.println(" S_MOTION"); + gw.present(ID_S_MOTION,S_MOTION); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SMOKE + Serial.println(" S_SMOKE"); + gw.present(ID_S_SMOKE,S_SMOKE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT + Serial.println(" S_LIGHT"); + gw.present(ID_S_LIGHT,S_LIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DIMMER + Serial.println(" S_DIMMER"); + gw.present(ID_S_DIMMER,S_DIMMER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_COVER + Serial.println(" S_COVER"; + gw.present(ID_S_COVER,S_COVER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_TEMP + Serial.println(" S_TMEP"); + gw.present(ID_S_TEMP,S_TEMP); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HUM + Serial.println(" S_HUM"); + gw.present(ID_S_HUM,S_HUM); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_BARO + Serial.println(" S_BARO"); + gw.present(ID_S_BARO,S_BARO); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WIND + Serial.println(" S_WIND"); + gw.present(ID_S_WIND,S_WIND); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_RAIN + Serial.println(" S_RAIN"); + gw.present(ID_S_RAIN,S_RAIN); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_UV + Serial.println(" S_UV"); + gw.present(ID_S_UV,S_UV); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WEIGHT + Serial.println(" S_WEIGHT"): + gw.present(ID_S_WEIGHT,S_WEIGHT); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_POWER + Serial.println(" S_POWER"); + gw.present(ID_S_POWER,S_POWER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_HEATER + Serial.println(" S_HEATER"); + gw.present(ID_S_HEATER,S_HEATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DISTANCE + Serial.println(" S_DISTANCE"); + gw.present(ID_S_DISTANCE,S_DISTANCE); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LIGHT_LEVEL + Serial.println(" S_LIGHT_LEVEL"); + gw.present(ID_S_LIGHT_LEVEL,S_LIGHT_LEVEL); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_LOCK + Serial.println(" S_LOCK"); + gw.present(ID_S_LOCK,S_LOCK); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_IR + Serial.println(" S_IR"); + gw.present(ID_S_IR,S_IR); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_WATER + Serial.println(" S_WATER"); + gw.present(ID_S_WATER,S_WATER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_AIR_QUALITY + Serial.println(" S_AIR_QUALITY"); + gw.present(ID_S_AIR_QUALITY,S_AIR_QUALITY); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_DUST + Serial.println(" S_DUST"); + gw.present(ID_S_DUST,S_DUST); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + Serial.println(" S_SCENE_CONTROLLER"); + gw.present(ID_S_SCENE_CONTROLLER,S_SCENE_CONTROLLER); + gw.wait(SHORT_WAIT); + #endif + + #ifdef ID_S_CUSTOM + Serial.println(" S_CUSTOM"); + gw.present(ID_S_CUSTOM,S_CUSTOM); + gw.wait(SHORT_WAIT); + #endif + + + +Serial.println("________________"); + +} + +void loop() +{ + Serial.println(""); + Serial.println(""); + Serial.println(""); + Serial.println("#########################"); + randNumber=random(0,101); + + Serial.print("RandomNumber:"); + Serial.println(randNumber); + // Send fake battery level + Serial.println("Send Battery Level"); + gw.sendBatteryLevel(randNumber); + gw.wait(LONG_WAIT); + + // Request time + Serial.println("Request Time"); + gw.requestTime(receiveTime); + gw.wait(LONG_WAIT); + + //Read Sensors + #ifdef S_ID_DOOR + door(); + #endif + + #ifdef ID_S_MOTION + motion(); + #endif + + #ifdef ID_S_SMOKE + smoke(); + #endif + + #ifdef ID_S_LIGHT + light(); + #endif + + #ifdef ID_S_DIMMER + dimmer(); + #endif + + #ifdef ID_S_COVER + cover(); + #endif + + #ifdef ID_S_TEMP + temp(); + #endif + + #ifdef ID_S_HUM + hum(); + #endif + + #ifdef ID_S_BARO + baro(); + #endif + + #ifdef ID_S_WIND + wind(); + #endif + + #ifdef ID_S_RAIN + rain(); + #endif + + #ifdef ID_S_UV + uv(); + #endif + + #ifdef ID_S_WEIGHT + weight(); + #endif + + #ifdef ID_S_POWER + power(); + #endif + + #ifdef ID_S_HEATER + heater(); + #endif + + #ifdef ID_S_DISTANCE + distance(); + #endif + + #ifdef ID_S_LIGHT_LEVEL + light_level(); + #endif + + #ifdef ID_S_LOCK + lock(); + #endif + + #ifdef ID_S_IR + ir(); + #endif + + #ifdef ID_S_WATER + water(); + #endif + + #ifdef ID_S_AIR_QUALITY + air(); + #endif + + #ifdef ID_S_DUST + dust(); + #endif + + #ifdef ID_S_SCENE_CONTROLLER + scene(); + #endif + + #ifdef ID_S_CUSTOM + custom(); + #endif + + gw.sendBatteryLevel(randNumber); + gw.wait(SHORT_WAIT); + gw.process(); + Serial.println("#########################"); + gw.wait(SLEEP_TIME); //sleep a bit +} + +// This is called when a new time value was received +void receiveTime(unsigned long controllerTime) { + + Serial.print("Time value received: "); + Serial.println(controllerTime); + +} + +//void door(){} + +#ifdef S_ID_DOOR +void door(){ + + Serial.print("Door is: " ); + + if (randNumber <= 50) { + Serial.println("Open"); + gw.send(msg_S_DOOR.set(1)); + } else { + Serial.println("Closed"); + gw.send(msg_S_DOOR.set(0)); + } + +} +#endif + +#ifdef ID_S_MOTION +void motion(){ + + Serial.print("Motion is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_MOTION_T.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_MOTION_T.set(0)); + } + +} +#endif + +#ifdef ID_S_SMOKE +void smoke(){ + + Serial.print("Smoke is: " ); + + if (randNumber <= 50) { + Serial.println("Active"); + gw.send(msg_S_SMOKE.set(1)); + } else { + Serial.println("Quiet"); + gw.send(msg_S_SMOKE.set(0)); + } + +} +#endif + +#ifdef ID_S_LIGHT +void light(){ + + bool isLightOn = gw.loadState(ID_S_LIGHT); + + Serial.print("Light is: " ); + + if (isLightOn) { + Serial.println("On"); + gw.send(msg_S_LIGHT.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LIGHT.set(0)); + } + +} +#endif + +#ifdef ID_S_DIMMER +void dimmer(){ + + int dimmerVal = gw.loadState(ID_S_DIMMER); + + Serial.print("Dimmer is set to: " ); + Serial.println(dimmerVal); + + gw.send(msg_S_DIMMER.set(dimmerVal)); + +} +#endif + +#ifdef ID_S_COVER +void cover(){ + + int coverVal = gw.loadState(ID_S_COVER); + + Serial.print("Cover is : " ); + + switch (coverVal) { + case 0: + Serial.println("Opening"); + gw.send(msg_S_COVER_U.set(V_UP)); + break; + case 1: + Serial.println("Closing"); + gw.send(msg_S_COVER_D.set(V_DOWN)); + break; + default: + Serial.println("Idle"); + gw.send(msg_S_COVER_S.set(V_STOP)); + } + +} +#endif + +#ifdef ID_S_TEMP +void temp(){ + + Serial.print("Temperature is: " ); + Serial.println(map(randNumber,1,100,0,45)); + + gw.send(msg_S_TEMP.set(map(randNumber,1,100,0,45))); + +} +#endif + +#ifdef ID_S_HUM +void hum(){ + + Serial.print("Humitidty is: " ); + Serial.println(randNumber); + + gw.send(msg_S_HUM.set(randNumber)); + +} +#endif + +#ifdef ID_S_BARO +void baro(){ + + const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"}; + long pressure = map(randNumber,1,100,87000,108600); + int forecast = map(randNumber,1,100,0,5); + + Serial.print("Atmosferic Pressure is: " ); + Serial.println(pressure); + gw.send(msg_S_BARO_P.set(pressure)); + + Serial.print("Weather forecast: " ); + Serial.println(weather[forecast]); + gw.send(msg_S_BARO_F.set(weather[forecast])); + +} +#endif + +#ifdef ID_S_WIND +void wind(){ + + Serial.print("Wind Speed is: " ); + Serial.println(randNumber); + gw.send(msg_S_WIND_S.set(randNumber)); + + Serial.print("Wind Gust is: " ); + Serial.println(randNumber+10); + gw.send(msg_S_WIND_G.set(randNumber+10)); + + Serial.print("Wind Direction is: " ); + Serial.println(map(randNumber,1,100,0,360)); + gw.send(msg_S_WIND_D.set(map(randNumber,1,100,0,360))); + +} +#endif + +#ifdef ID_S_RAIN +void rain(){ + + Serial.print("Rain ammount is: " ); + Serial.println(randNumber); + + gw.send(msg_S_RAIN_A.set(randNumber)); + + Serial.print("Rain rate is: " ); + Serial.println(randNumber/60); + + gw.send(msg_S_RAIN_R.set(randNumber/60,1)); + +} +#endif + +#ifdef ID_S_UV +void uv(){ + + Serial.print("Ultra Violet level is: " ); + Serial.println(map(randNumber,1,100,0,15)); + + gw.send(msg_S_UV.set(map(randNumber,1,100,0,15))); + +} +#endif + +#ifdef ID_S_WEIGHT +void weight(){ + + Serial.print("Weight is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WEIGHT.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_POWER +void power(){ + + Serial.print("Impedance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_I.set(map(randNumber,1,100,0,150))); + + Serial.print("Watt is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_W.set(map(randNumber,1,100,0,150))); + + Serial.print("KWH is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_K.set(map(randNumber,1,100,0,150))); + + Serial.print("Voltage is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_V.set(map(randNumber,1,100,0,150))); + + Serial.print("Current is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_POWER_C.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_HEATER +void heater(){ + int heater_mode = gw.loadState(ID_S_HEATER); + bool heater_switch = gw.loadState(ID_S_HEATER+1); + + Serial.print("Heater mode is: " ); + + if (heater_mode == 0){ + Serial.println("Off"); + } + else if (heater_mode == 1){ + Serial.println("Heat On"); + } + else if (heater_mode == 2){ + Serial.println("Cool On"); + } + else if (heater_mode == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(heater_mode); + } + + gw.send(msg_S_HEATER_M.set(heater_mode)); + + Serial.print("Heater is: " ); + Serial.println(heater_switch?"On":"Off"); + + gw.send(msg_S_HEATER_S.set(heater_switch)); + +} +#endif + +#ifdef ID_S_DISTANCE +void distance(){ + + Serial.print("Distance is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_DISTANCE.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LIGHT_LEVEL +void light_level(){ + + Serial.print("Light is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_LIGHT_LEVEL.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_LOCK +void lock(){ + + bool isLocked = gw.loadState(ID_S_LOCK); + + Serial.print("Lock is: " ); + + if (isLocked) { + Serial.println("On"); + gw.send(msg_S_LOCK.set(1)); + } else { + Serial.println("Off"); + gw.send(msg_S_LOCK.set(0)); + } + +} +#endif + +#ifdef ID_S_IR +void ir(){ + + int irVal = gw.loadState(ID_S_IR); + + Serial.print("Infrared is: " ); + Serial.println(irVal); + + gw.send(msg_S_IR_S.set(irVal)); + +} +#endif + +#ifdef ID_S_WATER +void water(){ + + Serial.print("Water flow is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_F.set(map(randNumber,1,100,0,150))); + + Serial.print("Water volume is: " ); + Serial.println(map(randNumber,1,100,0,150)); + + gw.send(msg_S_WATER_V.set(map(randNumber,1,100,0,150))); + +} +#endif + +#ifdef ID_S_AIR_QUALITY +void air(){ + + Serial.print("Air Quality is: " ); + Serial.println(randNumber); + + gw.send(msg_S_AIR_QUALITY.set(randNumber)); + +} +#endif + +#ifdef ID_S_DUST +void dust(){ + + Serial.print("Dust level is: " ); + Serial.println(randNumber); + + gw.send(msg_S_DUST.set(randNumber)); + +} +#endif + +#ifdef ID_S_SCENE_CONTROLLER +void scene(){ + + bool isSceneOn = gw.loadState(ID_S_SCENE_CONTROLLER); + + Serial.print("Scene is: " ); + Serial.println(isSceneOn ? "On":"Off"); + + if(isSceneOn) + gw.send(msg_S_SCENE_CONTROLLER_ON.set(isSceneOn)); + else + gw.send(msg_S_SCENE_CONTROLLER_OF.set(isSceneOn)); + +} +#endif + +#ifdef ID_S_CUSTOM +void custom(){ + + Serial.print("Custom value is: " ); + Serial.println(randNumber); + + gw.send(msg_S_CUSTOM_2.set(randNumber)); + gw.send(msg_S_CUSTOM_3.set(randNumber)); + gw.send(msg_S_CUSTOM_4.set(randNumber)); + gw.send(msg_S_CUSTOM_5.set(randNumber)); + +} +#endif + + +void incomingMessage(const MyMessage &message) { + switch (message.type) { + #ifdef ID_S_LIGHT + case V_LIGHT: + gw.saveState(ID_S_LIGHT, message.getBool()); + Serial.print("Incoming change for ID_S_LIGHT:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()); + break; + #endif + + #ifdef ID_S_DIMMER + case V_DIMMER: + if ((message.getInt()<0)||(message.getInt()>100)) { + Serial.println( "V_DIMMER data invalid (should be 0..100)" ); + break; + } + gw.saveState(ID_S_DIMMER, message.getInt()); + Serial.print("Incoming change for ID_S_DIMMER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_COVER + case V_UP: + gw.saveState(ID_S_COVER, 0); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_UP"); + break; + + case V_DOWN: + gw.saveState(ID_S_COVER, 1); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_DOWN"); + break; + + case V_STOP: + gw.saveState(ID_S_COVER, 2); + Serial.print("Incoming change for ID_S_COVER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("V_STOP"); + break; + #endif + + #ifdef ID_S_HEATER + case V_HEATER: + gw.saveState(ID_S_HEATER, message.getInt()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + + if (message.getInt() == 0){ + Serial.println("Off"); + } + else if (message.getInt() == 1){ + Serial.println("Heat On"); + } + else if (message.getInt() == 2){ + Serial.println("Cool On"); + } + else if (message.getInt() == 3){ + Serial.println("Auto Change Over"); + } + else { + Serial.print("Unknown Heater Mode: "); + Serial.println(message.getInt()); + } + break; + + case V_HEATER_SW: + gw.saveState(ID_S_HEATER+1, message.getBool()); + Serial.print("Incoming change for ID_S_HEATER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println((message.getBool() ? "On":"Off")); + break; + #endif + + #ifdef ID_S_LOCK + case V_LOCK_STATUS: + gw.saveState(ID_S_LOCK, message.getBool()); + Serial.print("Incoming change for ID_S_LOCK:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getBool()?"Locked":"Unlocked"); + break; + #endif + + #ifdef ID_S_IR + case V_IR_RECEIVE: + gw.saveState(ID_S_IR, message.getInt()); + Serial.print("Incoming change for ID_S_IR:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println(message.getInt()); + break; + #endif + + #ifdef ID_S_SCENE_CONTROLLER + case V_SCENE_ON: + gw.saveState(ID_S_SCENE_CONTROLLER, 1); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("On"); + break; + case V_SCENE_OFF: + gw.saveState(ID_S_SCENE_CONTROLLER, 0); + Serial.print("Incoming change for ID_S_SCENE_CONTROLLER:"); + Serial.print(message.sensor); + Serial.print(", New status: "); + Serial.println("Off"); + break; + #endif + + default: + Serial.print("Unknown/UnImplemented message type:"); + Serial.println(message.type); + } + +} + + + + + + + From bb39d1f548c21ca2bcb014487b99a6d9b9337259 Mon Sep 17 00:00:00 2001 From: Barduino Date: Thu, 30 Jul 2015 15:18:13 -0400 Subject: [PATCH 61/79] Create README.md --- .../MySensors/examples/MockMySensors/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 libraries/MySensors/examples/MockMySensors/README.md diff --git a/libraries/MySensors/examples/MockMySensors/README.md b/libraries/MySensors/examples/MockMySensors/README.md new file mode 100644 index 0000000..8b15212 --- /dev/null +++ b/libraries/MySensors/examples/MockMySensors/README.md @@ -0,0 +1,15 @@ +# FakeMySensors +Arduino sketch to fake sensor for the MySensors Library + +This skecth is intended to crate fake sensors which register and respond to the controller + +Barduino 2015 +----------------- + +Comment/Uncomment the sensors you would like to test + +Arduino Uno R3 can support about 12 sensors before it runs out of memory. +You probably need to turn of the MySensor Lib debug to save some memory + +Nest step will be to remove the read/write to the eprom +and extend to support the v1.5 sensors From 3fed88a3277fda211c9e58ed36279fe200590c86 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Thu, 30 Jul 2015 21:38:13 +0200 Subject: [PATCH 62/79] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ebb4f31..b803e58 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Arduino ======= -MySensors Arduino Library v1.4 +MySensors Arduino Library v1.5 Please visit www.mysensors.org for more information From 668a5f649b4fee50d4bd7035b7f376cfca2c0c45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Thu, 30 Jul 2015 22:34:47 +0200 Subject: [PATCH 63/79] Better "control" for determining if humiidty changes should fire off a transmission --- .../examples/SensebenderMicro/SensebenderMicro.ino | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 1dc3e77..02b88d3 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -15,7 +15,7 @@ #include #include #include -#include +//#include // Define a static node address, remove if you want auto address assignment //#define NODE_ADDRESS 3 @@ -149,7 +149,7 @@ void loop() { if ((measureCount == 5) && highfreq) { - clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. +// clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. highfreq = false; } @@ -182,21 +182,20 @@ void loop() { void sendTempHumidityMeasurements(bool force) { bool tx = force; - + si7021_env data = humiditySensor.getHumidityAndTemperature(); - float oldAvgHum = raHum.getAverage(); raHum.addValue(data.humidityPercent); float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100); - float diffHum = abs(oldAvgHum - raHum.getAverage()); + float diffHum = abs(lastHumidity - raHum.getAverage()); Serial.print(F("TempDiff :"));Serial.println(diffTemp); Serial.print(F("HumDiff :"));Serial.println(diffHum); if (isnan(diffHum)) tx = true; if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true; - if (diffHum >= HUMI_TRANSMIT_THRESHOLD) tx = true; + if (diffHum > HUMI_TRANSMIT_THRESHOLD) tx = true; if (tx) { measureCount = 0; @@ -246,7 +245,7 @@ void sendBattLevel(bool force) * Internal battery ADC measuring * *******************************************/ -long readVcc() { +long readVcc() {/* // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) @@ -270,6 +269,7 @@ long readVcc() { result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 return result; // Vcc in millivolts + */ } /**************************************************** From 5cdc2ebb19f01cecaad89913a33f50da9ae6d567 Mon Sep 17 00:00:00 2001 From: Barduino Date: Fri, 31 Jul 2015 10:18:02 -0400 Subject: [PATCH 64/79] Update README.md Removed fake my sensors reference --- libraries/MySensors/examples/MockMySensors/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/MockMySensors/README.md b/libraries/MySensors/examples/MockMySensors/README.md index 8b15212..24e2ce9 100644 --- a/libraries/MySensors/examples/MockMySensors/README.md +++ b/libraries/MySensors/examples/MockMySensors/README.md @@ -1,4 +1,4 @@ -# FakeMySensors +# MockMySensors Arduino sketch to fake sensor for the MySensors Library This skecth is intended to crate fake sensors which register and respond to the controller From 48f3e78ec89d6dd426eafdc0e370d63b97a3c19f Mon Sep 17 00:00:00 2001 From: Barduino Date: Fri, 31 Jul 2015 10:19:05 -0400 Subject: [PATCH 65/79] Update MockMySensors.ino Removed FakeMySensors reference --- libraries/MySensors/examples/MockMySensors/MockMySensors.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/MockMySensors/MockMySensors.ino b/libraries/MySensors/examples/MockMySensors/MockMySensors.ino index 4397208..2eb1629 100644 --- a/libraries/MySensors/examples/MockMySensors/MockMySensors.ino +++ b/libraries/MySensors/examples/MockMySensors/MockMySensors.ino @@ -1,5 +1,5 @@ /* -* FakeMySensors +* MockMySensors * * This skecth is intended to crate fake sensors which register and respond to the controller * From c562f0f173de61c2c179eb2b9c2bb67def16c079 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Fri, 31 Jul 2015 20:47:22 +0200 Subject: [PATCH 66/79] fix #114 --- NodeJsController/NodeJsController.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NodeJsController/NodeJsController.js b/NodeJsController/NodeJsController.js index 2c40fb4..4afba5f 100644 --- a/NodeJsController/NodeJsController.js +++ b/NodeJsController/NodeJsController.js @@ -364,7 +364,7 @@ function saveSketchVersion(sender, payload, db) { } function sendTime(destination, sensor, gw) { - var payload = new Date().getTime(); + var payload = new Date().getTime()/1000; var command = C_INTERNAL; var acknowledge = 0; // no ack var type = I_TIME; From 656ba2e4ab6586b695efa201a3aa6c1f9d924763 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 1 Aug 2015 00:05:09 +0200 Subject: [PATCH 67/79] Codebender adoption Had to make some chnages to make the code work on codebender (which seems to run a bit older version of AVR-LIBC. The compiler didn't like array constructor initializations either.. --- libraries/MySensors/MyConfig.h | 3 +- libraries/MySensors/MyHwATMega328.h | 28 ++++++++++++++++++- libraries/MySensors/MySigningAtsha204Soft.cpp | 4 ++- libraries/MySensors/MySigningAtsha204Soft.h | 2 +- 4 files changed, 32 insertions(+), 5 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 11c8af1..098a1f9 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -94,8 +94,7 @@ #define MY_RANDOMSEED_PIN 7 // A7 - Pin used for random generation (do not connect anything to this) // Key to use for HMAC calculation in MySigningAtsha204Soft (32 bytes) -#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,\ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 +#define MY_HMAC_KEY 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 /********************************** diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 17a4222..12698d4 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -37,13 +37,39 @@ #include #endif +#if defined __AVR_ATmega328P__ +#ifndef sleep_bod_disable +#define sleep_bod_disable() \ +do { \ + unsigned char tempreg; \ + __asm__ __volatile__("in %[tempreg], %[mcucr]" "\n\t" \ + "ori %[tempreg], %[bods_bodse]" "\n\t" \ + "out %[mcucr], %[tempreg]" "\n\t" \ + "andi %[tempreg], %[not_bodse]" "\n\t" \ + "out %[mcucr], %[tempreg]" \ + : [tempreg] "=&d" (tempreg) \ + : [mcucr] "I" _SFR_IO_ADDR(MCUCR), \ + [bods_bodse] "i" (_BV(BODS) | _BV(BODSE)), \ + [not_bodse] "i" (~_BV(BODSE))); \ +} while (0) +#endif +#endif + + // Define these as macros to save valuable space #define hw_init() Serial.begin(BAUD_RATE) #define hw_watchdogReset() wdt_reset() #define hw_reboot() wdt_enable(WDTO_15MS); while (1) #define hw_millis() millis() #define hw_readConfig(__pos) (eeprom_read_byte((uint8_t*)(__pos))) -#define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value))) + +#ifndef eeprom_update_byte + #define hw_writeConfig(loc, val) if((uint8_t)(val) != eeprom_read_byte((uint8_t*)(loc))) { eeprom_write_byte((uint8_t*)(loc), (val)); } +#else + #define hw_writeConfig(__pos, __value) (eeprom_update_byte((uint8_t*)(__pos), (__value))) +#endif + +// #define hw_readConfigBlock(__buf, __pos, __length) (eeprom_read_block((__buf), (void*)(__pos), (__length))) #define hw_writeConfigBlock(__pos, __buf, __length) (eeprom_write_block((void*)(__pos), (void*)__buf, (__length))) diff --git a/libraries/MySensors/MySigningAtsha204Soft.cpp b/libraries/MySensors/MySigningAtsha204Soft.cpp index d552c17..043d367 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.cpp +++ b/libraries/MySensors/MySigningAtsha204Soft.cpp @@ -61,6 +61,9 @@ static void DEBUG_SIGNING_PRINTBUF(const __FlashStringHelper* str, uint8_t* buf, #define DEBUG_SIGNING_PRINTBUF(str, buf, sz) #endif +// Initialize hmacKey from MyConfig.h (codebender didn't like static initialization in constructor) +uint8_t MySigningAtsha204Soft::hmacKey[32] = { MY_HMAC_KEY }; + MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, #ifdef MY_SECURE_NODE_WHITELISTING uint8_t nof_whitelist_entries, const whitelist_entry_t* the_whitelist, @@ -70,7 +73,6 @@ MySigningAtsha204Soft::MySigningAtsha204Soft(bool requestSignatures, : MySigning(requestSignatures), rndPin(randomseedPin), - hmacKey({MY_HMAC_KEY}), #ifdef MY_SECURE_NODE_WHITELISTING whitlist_sz(nof_whitelist_entries), whitelist(the_whitelist), diff --git a/libraries/MySensors/MySigningAtsha204Soft.h b/libraries/MySensors/MySigningAtsha204Soft.h index e516618..5d8090e 100644 --- a/libraries/MySensors/MySigningAtsha204Soft.h +++ b/libraries/MySensors/MySigningAtsha204Soft.h @@ -73,7 +73,7 @@ private: bool verification_ongoing; uint8_t current_nonce[NONCE_NUMIN_SIZE_PASSTHROUGH]; uint8_t temp_message[32]; - uint8_t hmacKey[32]; + static uint8_t hmacKey[32]; uint8_t rndPin; uint8_t hmac[32]; void calculateSignature(MyMessage &msg); From b9a5d6d5e1f7bf9efd155e6777445bbb9fae537e Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 1 Aug 2015 00:08:03 +0200 Subject: [PATCH 68/79] Add standard header to the Sensbender sketch --- .../SensebenderMicro/SensebenderMicro.ino | 38 ++++++++++++++++--- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index b86de21..32e959d 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -1,9 +1,35 @@ -// Default sensor sketch for Sensebender Micro module -// Act as a temperature / humidity sensor by default. -// -// If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals -// -// Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below) +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Thomas Bowman Mørch + * + * DESCRIPTION + * Default sensor sketch for Sensebender Micro module + * Act as a temperature / humidity sensor by default. + * + * If A0 is held low while powering on, it will enter testmode, which verifies all on-board peripherals + * + * Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below) + * + */ #include From b1005042bf92068f9837b48e4eb480f095f11f87 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 1 Aug 2015 11:09:27 +0200 Subject: [PATCH 69/79] Fix #146 --- .../MySensors/examples/EthernetGateway/EthernetGateway.ino | 2 +- libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index 383cbdf..fe19206 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -92,7 +92,7 @@ // NRFRF24L01 radio driver (set low transmit power by default) -MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW); //MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) diff --git a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino index 867c8be..0bb722d 100644 --- a/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino +++ b/libraries/MySensors/examples/MQTTGateway/MQTTGateway.ino @@ -118,7 +118,7 @@ byte TCP_MAC[] = { 0x02, 0xDE, 0xAD, 0x00, 0x00, 0x42 }; // Mac-address - You sh ////////////////////////////////////////////////////////////////// // NRFRF24L01 radio driver (set low transmit power by default) -MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW); +MyTransportNRF24 transport(RADIO_CE_PIN, RADIO_SPI_SS_PIN, RF24_PA_LEVEL_GW); //MyTransportRFM69 transport; // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h) From b28a28ddd6a2501c77579e758e58d82284a4027e Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Sat, 1 Aug 2015 22:13:11 +0200 Subject: [PATCH 70/79] Add ParkingSensor --- .../Adafruit_NeoPixel/Adafruit_NeoPixel.cpp | 1029 +++++++++++++++++ .../Adafruit_NeoPixel/Adafruit_NeoPixel.h | 97 ++ libraries/Adafruit_NeoPixel/COPYING | 794 +++++++++++++ libraries/Adafruit_NeoPixel/README.md | 12 + .../examples/buttoncycler/buttoncycler.ino | 165 +++ .../examples/simple/simple.ino | 45 + .../examples/strandtest/strandtest.ino | 131 +++ libraries/Adafruit_NeoPixel/keywords.txt | 29 + .../Adafruit_NeoPixel/library.properties | 9 + .../examples/ParkingSensor/ParkingSensor.ino | 164 +++ 10 files changed, 2475 insertions(+) create mode 100755 libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp create mode 100755 libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.h create mode 100755 libraries/Adafruit_NeoPixel/COPYING create mode 100755 libraries/Adafruit_NeoPixel/README.md create mode 100755 libraries/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino create mode 100755 libraries/Adafruit_NeoPixel/examples/simple/simple.ino create mode 100755 libraries/Adafruit_NeoPixel/examples/strandtest/strandtest.ino create mode 100755 libraries/Adafruit_NeoPixel/keywords.txt create mode 100755 libraries/Adafruit_NeoPixel/library.properties create mode 100644 libraries/MySensors/examples/ParkingSensor/ParkingSensor.ino diff --git a/libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp b/libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp new file mode 100755 index 0000000..af6386c --- /dev/null +++ b/libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.cpp @@ -0,0 +1,1029 @@ +/*------------------------------------------------------------------------- + Arduino library to control a wide variety of WS2811- and WS2812-based RGB + LED devices such as Adafruit FLORA RGB Smart Pixels and NeoPixel strips. + Currently handles 400 and 800 KHz bitstreams on 8, 12 and 16 MHz ATmega + MCUs, with LEDs wired for RGB or GRB color order. 8 MHz MCUs provide + output on PORTB and PORTD, while 16 MHz chips can handle most output pins + (possible exception with upper PORT registers on the Arduino Mega). + + Written by Phil Burgess / Paint Your Dragon for Adafruit Industries, + contributions by PJRC and other members of the open source community. + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing products + from Adafruit! + + ------------------------------------------------------------------------- + This file is part of the Adafruit NeoPixel library. + + NeoPixel 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 3 of + the License, or (at your option) any later version. + + NeoPixel 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 NeoPixel. If not, see + . + -------------------------------------------------------------------------*/ + +#include "Adafruit_NeoPixel.h" + +Adafruit_NeoPixel::Adafruit_NeoPixel(uint16_t n, uint8_t p, uint8_t t) : + numLEDs(n), numBytes(n * 3), pin(p), brightness(0), + pixels(NULL), type(t), endTime(0) +#ifdef __AVR__ + ,port(portOutputRegister(digitalPinToPort(p))), + pinMask(digitalPinToBitMask(p)) +#endif +{ + if((pixels = (uint8_t *)malloc(numBytes))) { + memset(pixels, 0, numBytes); + } + if(t & NEO_GRB) { // GRB vs RGB; might add others if needed + rOffset = 1; + gOffset = 0; + bOffset = 2; + } else if (t & NEO_BRG) { + rOffset = 1; + gOffset = 2; + bOffset = 0; + } else { + rOffset = 0; + gOffset = 1; + bOffset = 2; + } + +} + +Adafruit_NeoPixel::~Adafruit_NeoPixel() { + if(pixels) free(pixels); + pinMode(pin, INPUT); +} + +void Adafruit_NeoPixel::begin(void) { + pinMode(pin, OUTPUT); + digitalWrite(pin, LOW); +} + +void Adafruit_NeoPixel::show(void) { + + if(!pixels) return; + + // Data latch = 50+ microsecond pause in the output stream. Rather than + // put a delay at the end of the function, the ending time is noted and + // the function will simply hold off (if needed) on issuing the + // subsequent round of data until the latch time has elapsed. This + // allows the mainline code to start generating the next frame of data + // rather than stalling for the latch. + while(!canShow()); + // endTime is a private member (rather than global var) so that mutliple + // instances on different pins can be quickly issued in succession (each + // instance doesn't delay the next). + + // In order to make this code runtime-configurable to work with any pin, + // SBI/CBI instructions are eschewed in favor of full PORT writes via the + // OUT or ST instructions. It relies on two facts: that peripheral + // functions (such as PWM) take precedence on output pins, so our PORT- + // wide writes won't interfere, and that interrupts are globally disabled + // while data is being issued to the LEDs, so no other code will be + // accessing the PORT. The code takes an initial 'snapshot' of the PORT + // state, computes 'pin high' and 'pin low' values, and writes these back + // to the PORT register as needed. + + noInterrupts(); // Need 100% focus on instruction timing + +#ifdef __AVR__ + + volatile uint16_t + i = numBytes; // Loop counter + volatile uint8_t + *ptr = pixels, // Pointer to next byte + b = *ptr++, // Current byte value + hi, // PORT w/output bit set high + lo; // PORT w/output bit set low + + // Hand-tuned assembly code issues data to the LED drivers at a specific + // rate. There's separate code for different CPU speeds (8, 12, 16 MHz) + // for both the WS2811 (400 KHz) and WS2812 (800 KHz) drivers. The + // datastream timing for the LED drivers allows a little wiggle room each + // way (listed in the datasheets), so the conditions for compiling each + // case are set up for a range of frequencies rather than just the exact + // 8, 12 or 16 MHz values, permitting use with some close-but-not-spot-on + // devices (e.g. 16.5 MHz DigiSpark). The ranges were arrived at based + // on the datasheet figures and have not been extensively tested outside + // the canonical 8/12/16 MHz speeds; there's no guarantee these will work + // close to the extremes (or possibly they could be pushed further). + // Keep in mind only one CPU speed case actually gets compiled; the + // resulting program isn't as massive as it might look from source here. + +// 8 MHz(ish) AVR --------------------------------------------------------- +#if (F_CPU >= 7400000UL) && (F_CPU <= 9500000UL) + +#ifdef NEO_KHZ400 + if((type & NEO_SPDMASK) == NEO_KHZ800) { // 800 KHz bitstream +#endif + + volatile uint8_t n1, n2 = 0; // First, next bits out + + // Squeezing an 800 KHz stream out of an 8 MHz chip requires code + // specific to each PORT register. At present this is only written + // to work with pins on PORTD or PORTB, the most likely use case -- + // this covers all the pins on the Adafruit Flora and the bulk of + // digital pins on the Arduino Pro 8 MHz (keep in mind, this code + // doesn't even get compiled for 16 MHz boards like the Uno, Mega, + // Leonardo, etc., so don't bother extending this out of hand). + // Additional PORTs could be added if you really need them, just + // duplicate the else and loop and change the PORT. Each add'l + // PORT will require about 150(ish) bytes of program space. + + // 10 instruction clocks per bit: HHxxxxxLLL + // OUT instructions: ^ ^ ^ (T=0,2,7) + +#ifdef PORTD // PORTD isn't present on ATtiny85, etc. + + if(port == &PORTD) { + + hi = PORTD | pinMask; + lo = PORTD & ~pinMask; + n1 = lo; + if(b & 0x80) n1 = hi; + + // Dirty trick: RJMPs proceeding to the next instruction are used + // to delay two clock cycles in one instruction word (rather than + // using two NOPs). This was necessary in order to squeeze the + // loop down to exactly 64 words -- the maximum possible for a + // relative branch. + + asm volatile( + "headD:" "\n\t" // Clk Pseudocode + // Bit 7: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo + "out %[port] , %[n1]" "\n\t" // 1 PORT = n1 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 6" "\n\t" // 1-2 if(b & 0x40) + "mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "rjmp .+0" "\n\t" // 2 nop nop + // Bit 6: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo + "out %[port] , %[n2]" "\n\t" // 1 PORT = n2 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 5" "\n\t" // 1-2 if(b & 0x20) + "mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "rjmp .+0" "\n\t" // 2 nop nop + // Bit 5: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo + "out %[port] , %[n1]" "\n\t" // 1 PORT = n1 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 4" "\n\t" // 1-2 if(b & 0x10) + "mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "rjmp .+0" "\n\t" // 2 nop nop + // Bit 4: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo + "out %[port] , %[n2]" "\n\t" // 1 PORT = n2 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 3" "\n\t" // 1-2 if(b & 0x08) + "mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "rjmp .+0" "\n\t" // 2 nop nop + // Bit 3: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo + "out %[port] , %[n1]" "\n\t" // 1 PORT = n1 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 2" "\n\t" // 1-2 if(b & 0x04) + "mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "rjmp .+0" "\n\t" // 2 nop nop + // Bit 2: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo + "out %[port] , %[n2]" "\n\t" // 1 PORT = n2 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 1" "\n\t" // 1-2 if(b & 0x02) + "mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "rjmp .+0" "\n\t" // 2 nop nop + // Bit 1: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n2] , %[lo]" "\n\t" // 1 n2 = lo + "out %[port] , %[n1]" "\n\t" // 1 PORT = n1 + "rjmp .+0" "\n\t" // 2 nop nop + "sbrc %[byte] , 0" "\n\t" // 1-2 if(b & 0x01) + "mov %[n2] , %[hi]" "\n\t" // 0-1 n2 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "sbiw %[count], 1" "\n\t" // 2 i-- (don't act on Z flag yet) + // Bit 0: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi + "mov %[n1] , %[lo]" "\n\t" // 1 n1 = lo + "out %[port] , %[n2]" "\n\t" // 1 PORT = n2 + "ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ + "sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 0x80) + "mov %[n1] , %[hi]" "\n\t" // 0-1 n1 = hi + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo + "brne headD" "\n" // 2 while(i) (Z flag set above) + : [byte] "+r" (b), + [n1] "+r" (n1), + [n2] "+r" (n2), + [count] "+w" (i) + : [port] "I" (_SFR_IO_ADDR(PORTD)), + [ptr] "e" (ptr), + [hi] "r" (hi), + [lo] "r" (lo)); + + } else if(port == &PORTB) { + +#endif // PORTD + + // Same as above, just switched to PORTB and stripped of comments. + hi = PORTB | pinMask; + lo = PORTB & ~pinMask; + n1 = lo; + if(b & 0x80) n1 = hi; + + asm volatile( + "headB:" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n2] , %[lo]" "\n\t" + "out %[port] , %[n1]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 6" "\n\t" + "mov %[n2] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "rjmp .+0" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n1] , %[lo]" "\n\t" + "out %[port] , %[n2]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 5" "\n\t" + "mov %[n1] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "rjmp .+0" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n2] , %[lo]" "\n\t" + "out %[port] , %[n1]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 4" "\n\t" + "mov %[n2] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "rjmp .+0" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n1] , %[lo]" "\n\t" + "out %[port] , %[n2]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 3" "\n\t" + "mov %[n1] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "rjmp .+0" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n2] , %[lo]" "\n\t" + "out %[port] , %[n1]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 2" "\n\t" + "mov %[n2] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "rjmp .+0" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n1] , %[lo]" "\n\t" + "out %[port] , %[n2]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 1" "\n\t" + "mov %[n1] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "rjmp .+0" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n2] , %[lo]" "\n\t" + "out %[port] , %[n1]" "\n\t" + "rjmp .+0" "\n\t" + "sbrc %[byte] , 0" "\n\t" + "mov %[n2] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "sbiw %[count], 1" "\n\t" + "out %[port] , %[hi]" "\n\t" + "mov %[n1] , %[lo]" "\n\t" + "out %[port] , %[n2]" "\n\t" + "ld %[byte] , %a[ptr]+" "\n\t" + "sbrc %[byte] , 7" "\n\t" + "mov %[n1] , %[hi]" "\n\t" + "out %[port] , %[lo]" "\n\t" + "brne headB" "\n" + : [byte] "+r" (b), [n1] "+r" (n1), [n2] "+r" (n2), [count] "+w" (i) + : [port] "I" (_SFR_IO_ADDR(PORTB)), [ptr] "e" (ptr), [hi] "r" (hi), + [lo] "r" (lo)); + +#ifdef PORTD + } // endif PORTB +#endif + +#ifdef NEO_KHZ400 + } else { // end 800 KHz, do 400 KHz + + // Timing is more relaxed; unrolling the inner loop for each bit is + // not necessary. Still using the peculiar RJMPs as 2X NOPs, not out + // of need but just to trim the code size down a little. + // This 400-KHz-datastream-on-8-MHz-CPU code is not quite identical + // to the 800-on-16 code later -- the hi/lo timing between WS2811 and + // WS2812 is not simply a 2:1 scale! + + // 20 inst. clocks per bit: HHHHxxxxxxLLLLLLLLLL + // ST instructions: ^ ^ ^ (T=0,4,10) + + volatile uint8_t next, bit; + + hi = *port | pinMask; + lo = *port & ~pinMask; + next = lo; + bit = 8; + + asm volatile( + "head20:" "\n\t" // Clk Pseudocode (T = 0) + "st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2) + "sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 128) + "mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 4) + "st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 6) + "mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 7) + "dec %[bit]" "\n\t" // 1 bit-- (T = 8) + "breq nextbyte20" "\n\t" // 1-2 if(bit == 0) + "rol %[byte]" "\n\t" // 1 b <<= 1 (T = 10) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 12) + "rjmp .+0" "\n\t" // 2 nop nop (T = 14) + "rjmp .+0" "\n\t" // 2 nop nop (T = 16) + "rjmp .+0" "\n\t" // 2 nop nop (T = 18) + "rjmp head20" "\n\t" // 2 -> head20 (next bit out) + "nextbyte20:" "\n\t" // (T = 10) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 12) + "nop" "\n\t" // 1 nop (T = 13) + "ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 14) + "ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 16) + "sbiw %[count], 1" "\n\t" // 2 i-- (T = 18) + "brne head20" "\n" // 2 if(i != 0) -> (next byte) + : [port] "+e" (port), + [byte] "+r" (b), + [bit] "+r" (bit), + [next] "+r" (next), + [count] "+w" (i) + : [hi] "r" (hi), + [lo] "r" (lo), + [ptr] "e" (ptr)); + } +#endif + +// 12 MHz(ish) AVR -------------------------------------------------------- +#elif (F_CPU >= 11100000UL) && (F_CPU <= 14300000UL) + +#ifdef NEO_KHZ400 + if((type & NEO_SPDMASK) == NEO_KHZ800) { // 800 KHz bitstream +#endif + + // In the 12 MHz case, an optimized 800 KHz datastream (no dead time + // between bytes) requires a PORT-specific loop similar to the 8 MHz + // code (but a little more relaxed in this case). + + // 15 instruction clocks per bit: HHHHxxxxxxLLLLL + // OUT instructions: ^ ^ ^ (T=0,4,10) + + volatile uint8_t next; + +#ifdef PORTD + + if(port == &PORTD) { + + hi = PORTD | pinMask; + lo = PORTD & ~pinMask; + next = lo; + if(b & 0x80) next = hi; + + // Don't "optimize" the OUT calls into the bitTime subroutine; + // we're exploiting the RCALL and RET as 3- and 4-cycle NOPs! + asm volatile( + "headD:" "\n\t" // (T = 0) + "out %[port], %[hi]" "\n\t" // (T = 1) + "rcall bitTimeD" "\n\t" // Bit 7 (T = 15) + "out %[port], %[hi]" "\n\t" + "rcall bitTimeD" "\n\t" // Bit 6 + "out %[port], %[hi]" "\n\t" + "rcall bitTimeD" "\n\t" // Bit 5 + "out %[port], %[hi]" "\n\t" + "rcall bitTimeD" "\n\t" // Bit 4 + "out %[port], %[hi]" "\n\t" + "rcall bitTimeD" "\n\t" // Bit 3 + "out %[port], %[hi]" "\n\t" + "rcall bitTimeD" "\n\t" // Bit 2 + "out %[port], %[hi]" "\n\t" + "rcall bitTimeD" "\n\t" // Bit 1 + // Bit 0: + "out %[port] , %[hi]" "\n\t" // 1 PORT = hi (T = 1) + "rjmp .+0" "\n\t" // 2 nop nop (T = 3) + "ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 5) + "out %[port] , %[next]" "\n\t" // 1 PORT = next (T = 6) + "mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 7) + "sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 0x80) (T = 8) + "mov %[next] , %[hi]" "\n\t" // 0-1 next = hi (T = 9) + "nop" "\n\t" // 1 (T = 10) + "out %[port] , %[lo]" "\n\t" // 1 PORT = lo (T = 11) + "sbiw %[count], 1" "\n\t" // 2 i-- (T = 13) + "brne headD" "\n\t" // 2 if(i != 0) -> (next byte) + "rjmp doneD" "\n\t" + "bitTimeD:" "\n\t" // nop nop nop (T = 4) + "out %[port], %[next]" "\n\t" // 1 PORT = next (T = 5) + "mov %[next], %[lo]" "\n\t" // 1 next = lo (T = 6) + "rol %[byte]" "\n\t" // 1 b <<= 1 (T = 7) + "sbrc %[byte], 7" "\n\t" // 1-2 if(b & 0x80) (T = 8) + "mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 9) + "nop" "\n\t" // 1 (T = 10) + "out %[port], %[lo]" "\n\t" // 1 PORT = lo (T = 11) + "ret" "\n\t" // 4 nop nop nop nop (T = 15) + "doneD:" "\n" + : [byte] "+r" (b), + [next] "+r" (next), + [count] "+w" (i) + : [port] "I" (_SFR_IO_ADDR(PORTD)), + [ptr] "e" (ptr), + [hi] "r" (hi), + [lo] "r" (lo)); + + } else if(port == &PORTB) { + +#endif // PORTD + + hi = PORTB | pinMask; + lo = PORTB & ~pinMask; + next = lo; + if(b & 0x80) next = hi; + + // Same as above, just set for PORTB & stripped of comments + asm volatile( + "headB:" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port], %[hi]" "\n\t" + "rcall bitTimeB" "\n\t" + "out %[port] , %[hi]" "\n\t" + "rjmp .+0" "\n\t" + "ld %[byte] , %a[ptr]+" "\n\t" + "out %[port] , %[next]" "\n\t" + "mov %[next] , %[lo]" "\n\t" + "sbrc %[byte] , 7" "\n\t" + "mov %[next] , %[hi]" "\n\t" + "nop" "\n\t" + "out %[port] , %[lo]" "\n\t" + "sbiw %[count], 1" "\n\t" + "brne headB" "\n\t" + "rjmp doneB" "\n\t" + "bitTimeB:" "\n\t" + "out %[port], %[next]" "\n\t" + "mov %[next], %[lo]" "\n\t" + "rol %[byte]" "\n\t" + "sbrc %[byte], 7" "\n\t" + "mov %[next], %[hi]" "\n\t" + "nop" "\n\t" + "out %[port], %[lo]" "\n\t" + "ret" "\n\t" + "doneB:" "\n" + : [byte] "+r" (b), [next] "+r" (next), [count] "+w" (i) + : [port] "I" (_SFR_IO_ADDR(PORTB)), [ptr] "e" (ptr), [hi] "r" (hi), + [lo] "r" (lo)); + +#ifdef PORTD + } +#endif + +#ifdef NEO_KHZ400 + } else { // 400 KHz + + // 30 instruction clocks per bit: HHHHHHxxxxxxxxxLLLLLLLLLLLLLLL + // ST instructions: ^ ^ ^ (T=0,6,15) + + volatile uint8_t next, bit; + + hi = *port | pinMask; + lo = *port & ~pinMask; + next = lo; + bit = 8; + + asm volatile( + "head30:" "\n\t" // Clk Pseudocode (T = 0) + "st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2) + "sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 128) + "mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 4) + "rjmp .+0" "\n\t" // 2 nop nop (T = 6) + "st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 8) + "rjmp .+0" "\n\t" // 2 nop nop (T = 10) + "rjmp .+0" "\n\t" // 2 nop nop (T = 12) + "rjmp .+0" "\n\t" // 2 nop nop (T = 14) + "nop" "\n\t" // 1 nop (T = 15) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 17) + "rjmp .+0" "\n\t" // 2 nop nop (T = 19) + "dec %[bit]" "\n\t" // 1 bit-- (T = 20) + "breq nextbyte30" "\n\t" // 1-2 if(bit == 0) + "rol %[byte]" "\n\t" // 1 b <<= 1 (T = 22) + "rjmp .+0" "\n\t" // 2 nop nop (T = 24) + "rjmp .+0" "\n\t" // 2 nop nop (T = 26) + "rjmp .+0" "\n\t" // 2 nop nop (T = 28) + "rjmp head30" "\n\t" // 2 -> head30 (next bit out) + "nextbyte30:" "\n\t" // (T = 22) + "nop" "\n\t" // 1 nop (T = 23) + "ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 24) + "ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 26) + "sbiw %[count], 1" "\n\t" // 2 i-- (T = 28) + "brne head30" "\n" // 1-2 if(i != 0) -> (next byte) + : [port] "+e" (port), + [byte] "+r" (b), + [bit] "+r" (bit), + [next] "+r" (next), + [count] "+w" (i) + : [hi] "r" (hi), + [lo] "r" (lo), + [ptr] "e" (ptr)); + } +#endif + +// 16 MHz(ish) AVR -------------------------------------------------------- +#elif (F_CPU >= 15400000UL) && (F_CPU <= 19000000L) + +#ifdef NEO_KHZ400 + if((type & NEO_SPDMASK) == NEO_KHZ800) { // 800 KHz bitstream +#endif + + // WS2811 and WS2812 have different hi/lo duty cycles; this is + // similar but NOT an exact copy of the prior 400-on-8 code. + + // 20 inst. clocks per bit: HHHHHxxxxxxxxLLLLLLL + // ST instructions: ^ ^ ^ (T=0,5,13) + + volatile uint8_t next, bit; + + hi = *port | pinMask; + lo = *port & ~pinMask; + next = lo; + bit = 8; + + asm volatile( + "head20:" "\n\t" // Clk Pseudocode (T = 0) + "st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2) + "sbrc %[byte], 7" "\n\t" // 1-2 if(b & 128) + "mov %[next], %[hi]" "\n\t" // 0-1 next = hi (T = 4) + "dec %[bit]" "\n\t" // 1 bit-- (T = 5) + "st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 7) + "mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 8) + "breq nextbyte20" "\n\t" // 1-2 if(bit == 0) (from dec above) + "rol %[byte]" "\n\t" // 1 b <<= 1 (T = 10) + "rjmp .+0" "\n\t" // 2 nop nop (T = 12) + "nop" "\n\t" // 1 nop (T = 13) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 15) + "nop" "\n\t" // 1 nop (T = 16) + "rjmp .+0" "\n\t" // 2 nop nop (T = 18) + "rjmp head20" "\n\t" // 2 -> head20 (next bit out) + "nextbyte20:" "\n\t" // (T = 10) + "ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 11) + "ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 13) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 15) + "nop" "\n\t" // 1 nop (T = 16) + "sbiw %[count], 1" "\n\t" // 2 i-- (T = 18) + "brne head20" "\n" // 2 if(i != 0) -> (next byte) + : [port] "+e" (port), + [byte] "+r" (b), + [bit] "+r" (bit), + [next] "+r" (next), + [count] "+w" (i) + : [ptr] "e" (ptr), + [hi] "r" (hi), + [lo] "r" (lo)); + +#ifdef NEO_KHZ400 + } else { // 400 KHz + + // The 400 KHz clock on 16 MHz MCU is the most 'relaxed' version. + + // 40 inst. clocks per bit: HHHHHHHHxxxxxxxxxxxxLLLLLLLLLLLLLLLLLLLL + // ST instructions: ^ ^ ^ (T=0,8,20) + + volatile uint8_t next, bit; + + hi = *port | pinMask; + lo = *port & ~pinMask; + next = lo; + bit = 8; + + asm volatile( + "head40:" "\n\t" // Clk Pseudocode (T = 0) + "st %a[port], %[hi]" "\n\t" // 2 PORT = hi (T = 2) + "sbrc %[byte] , 7" "\n\t" // 1-2 if(b & 128) + "mov %[next] , %[hi]" "\n\t" // 0-1 next = hi (T = 4) + "rjmp .+0" "\n\t" // 2 nop nop (T = 6) + "rjmp .+0" "\n\t" // 2 nop nop (T = 8) + "st %a[port], %[next]" "\n\t" // 2 PORT = next (T = 10) + "rjmp .+0" "\n\t" // 2 nop nop (T = 12) + "rjmp .+0" "\n\t" // 2 nop nop (T = 14) + "rjmp .+0" "\n\t" // 2 nop nop (T = 16) + "rjmp .+0" "\n\t" // 2 nop nop (T = 18) + "rjmp .+0" "\n\t" // 2 nop nop (T = 20) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 22) + "nop" "\n\t" // 1 nop (T = 23) + "mov %[next] , %[lo]" "\n\t" // 1 next = lo (T = 24) + "dec %[bit]" "\n\t" // 1 bit-- (T = 25) + "breq nextbyte40" "\n\t" // 1-2 if(bit == 0) + "rol %[byte]" "\n\t" // 1 b <<= 1 (T = 27) + "nop" "\n\t" // 1 nop (T = 28) + "rjmp .+0" "\n\t" // 2 nop nop (T = 30) + "rjmp .+0" "\n\t" // 2 nop nop (T = 32) + "rjmp .+0" "\n\t" // 2 nop nop (T = 34) + "rjmp .+0" "\n\t" // 2 nop nop (T = 36) + "rjmp .+0" "\n\t" // 2 nop nop (T = 38) + "rjmp head40" "\n\t" // 2 -> head40 (next bit out) + "nextbyte40:" "\n\t" // (T = 27) + "ldi %[bit] , 8" "\n\t" // 1 bit = 8 (T = 28) + "ld %[byte] , %a[ptr]+" "\n\t" // 2 b = *ptr++ (T = 30) + "rjmp .+0" "\n\t" // 2 nop nop (T = 32) + "st %a[port], %[lo]" "\n\t" // 2 PORT = lo (T = 34) + "rjmp .+0" "\n\t" // 2 nop nop (T = 36) + "sbiw %[count], 1" "\n\t" // 2 i-- (T = 38) + "brne head40" "\n" // 1-2 if(i != 0) -> (next byte) + : [port] "+e" (port), + [byte] "+r" (b), + [bit] "+r" (bit), + [next] "+r" (next), + [count] "+w" (i) + : [ptr] "e" (ptr), + [hi] "r" (hi), + [lo] "r" (lo)); + } +#endif + +#else + #error "CPU SPEED NOT SUPPORTED" +#endif + +#elif defined(__arm__) + +#if defined(__MK20DX128__) || defined(__MK20DX256__) // Teensy 3.0 & 3.1 +#define CYCLES_800_T0H (F_CPU / 4000000) +#define CYCLES_800_T1H (F_CPU / 1250000) +#define CYCLES_800 (F_CPU / 800000) +#define CYCLES_400_T0H (F_CPU / 2000000) +#define CYCLES_400_T1H (F_CPU / 833333) +#define CYCLES_400 (F_CPU / 400000) + + uint8_t *p = pixels, + *end = p + numBytes, pix, mask; + volatile uint8_t *set = portSetRegister(pin), + *clr = portClearRegister(pin); + uint32_t cyc; + + ARM_DEMCR |= ARM_DEMCR_TRCENA; + ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA; + +#ifdef NEO_KHZ400 + if((type & NEO_SPDMASK) == NEO_KHZ800) { // 800 KHz bitstream +#endif + cyc = ARM_DWT_CYCCNT + CYCLES_800; + while(p < end) { + pix = *p++; + for(mask = 0x80; mask; mask >>= 1) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_800); + cyc = ARM_DWT_CYCCNT; + *set = 1; + if(pix & mask) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_800_T1H); + } else { + while(ARM_DWT_CYCCNT - cyc < CYCLES_800_T0H); + } + *clr = 1; + } + } + while(ARM_DWT_CYCCNT - cyc < CYCLES_800); +#ifdef NEO_KHZ400 + } else { // 400 kHz bitstream + cyc = ARM_DWT_CYCCNT + CYCLES_400; + while(p < end) { + pix = *p++; + for(mask = 0x80; mask; mask >>= 1) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_400); + cyc = ARM_DWT_CYCCNT; + *set = 1; + if(pix & mask) { + while(ARM_DWT_CYCCNT - cyc < CYCLES_400_T1H); + } else { + while(ARM_DWT_CYCCNT - cyc < CYCLES_400_T0H); + } + *clr = 1; + } + } + while(ARM_DWT_CYCCNT - cyc < CYCLES_400); + } +#endif + + + + + +#elif defined(__MKL26Z64__) // Teensy-LC + +#if F_CPU == 48000000 + uint8_t *p = pixels, + pix, count, dly, + bitmask = digitalPinToBitMask(pin); + volatile uint8_t *reg = portSetRegister(pin); + uint32_t num = numBytes; + asm volatile( + "L%=_begin:" "\n\t" + "ldrb %[pix], [%[p], #0]" "\n\t" + "lsl %[pix], #24" "\n\t" + "movs %[count], #7" "\n\t" + "L%=_loop:" "\n\t" + "lsl %[pix], #1" "\n\t" + "bcs L%=_loop_one" "\n\t" + "L%=_loop_zero:" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #4" "\n\t" + "L%=_loop_delay_T0H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T0H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #13" "\n\t" + "L%=_loop_delay_T0L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T0L" "\n\t" + "b L%=_next" "\n\t" + "L%=_loop_one:" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #13" "\n\t" + "L%=_loop_delay_T1H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T1H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #4" "\n\t" + "L%=_loop_delay_T1L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_loop_delay_T1L" "\n\t" + "nop" "\n\t" + "L%=_next:" "\n\t" + "sub %[count], #1" "\n\t" + "bne L%=_loop" "\n\t" + "lsl %[pix], #1" "\n\t" + "bcs L%=_last_one" "\n\t" + "L%=_last_zero:" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #4" "\n\t" + "L%=_last_delay_T0H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T0H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #10" "\n\t" + "L%=_last_delay_T0L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T0L" "\n\t" + "b L%=_repeat" "\n\t" + "L%=_last_one:" + "strb %[bitmask], [%[reg], #0]" "\n\t" + "movs %[dly], #13" "\n\t" + "L%=_last_delay_T1H:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T1H" "\n\t" + "strb %[bitmask], [%[reg], #4]" "\n\t" + "movs %[dly], #1" "\n\t" + "L%=_last_delay_T1L:" "\n\t" + "sub %[dly], #1" "\n\t" + "bne L%=_last_delay_T1L" "\n\t" + "nop" "\n\t" + "L%=_repeat:" "\n\t" + "add %[p], #1" "\n\t" + "sub %[num], #1" "\n\t" + "bne L%=_begin" "\n\t" + "L%=_done:" "\n\t" + : [p] "+r" (p), + [pix] "=&r" (pix), + [count] "=&r" (count), + [dly] "=&r" (dly), + [num] "+r" (num) + : [bitmask] "r" (bitmask), + [reg] "r" (reg) + ); +#else +#error "Sorry, only 48 MHz is supported, please set Tools > CPU Speed to 48 MHz" +#endif + + +#else // Arduino Due + + #define SCALE VARIANT_MCK / 2UL / 1000000UL + #define INST (2UL * F_CPU / VARIANT_MCK) + #define TIME_800_0 ((int)(0.40 * SCALE + 0.5) - (5 * INST)) + #define TIME_800_1 ((int)(0.80 * SCALE + 0.5) - (5 * INST)) + #define PERIOD_800 ((int)(1.25 * SCALE + 0.5) - (5 * INST)) + #define TIME_400_0 ((int)(0.50 * SCALE + 0.5) - (5 * INST)) + #define TIME_400_1 ((int)(1.20 * SCALE + 0.5) - (5 * INST)) + #define PERIOD_400 ((int)(2.50 * SCALE + 0.5) - (5 * INST)) + + int pinMask, time0, time1, period, t; + Pio *port; + volatile WoReg *portSet, *portClear, *timeValue, *timeReset; + uint8_t *p, *end, pix, mask; + + pmc_set_writeprotect(false); + pmc_enable_periph_clk((uint32_t)TC3_IRQn); + TC_Configure(TC1, 0, + TC_CMR_WAVE | TC_CMR_WAVSEL_UP | TC_CMR_TCCLKS_TIMER_CLOCK1); + TC_Start(TC1, 0); + + pinMask = g_APinDescription[pin].ulPin; // Don't 'optimize' these into + port = g_APinDescription[pin].pPort; // declarations above. Want to + portSet = &(port->PIO_SODR); // burn a few cycles after + portClear = &(port->PIO_CODR); // starting timer to minimize + timeValue = &(TC1->TC_CHANNEL[0].TC_CV); // the initial 'while'. + timeReset = &(TC1->TC_CHANNEL[0].TC_CCR); + p = pixels; + end = p + numBytes; + pix = *p++; + mask = 0x80; + +#ifdef NEO_KHZ400 + if((type & NEO_SPDMASK) == NEO_KHZ800) { // 800 KHz bitstream +#endif + time0 = TIME_800_0; + time1 = TIME_800_1; + period = PERIOD_800; +#ifdef NEO_KHZ400 + } else { // 400 KHz bitstream + time0 = TIME_400_0; + time1 = TIME_400_1; + period = PERIOD_400; + } +#endif + + for(t = time0;; t = time0) { + if(pix & mask) t = time1; + while(*timeValue < period); + *portSet = pinMask; + *timeReset = TC_CCR_CLKEN | TC_CCR_SWTRG; + while(*timeValue < t); + *portClear = pinMask; + if(!(mask >>= 1)) { // This 'inside-out' loop logic utilizes + if(p >= end) break; // idle time to minimize inter-byte delays. + pix = *p++; + mask = 0x80; + } + } + while(*timeValue < period); // Wait for last bit + TC_Stop(TC1, 0); + +#endif // end Arduino Due + +#endif // end Architecture select + + interrupts(); + endTime = micros(); // Save EOD time for latch on next call +} + +// Set the output pin number +void Adafruit_NeoPixel::setPin(uint8_t p) { + pinMode(pin, INPUT); + pin = p; + pinMode(p, OUTPUT); + digitalWrite(p, LOW); +#ifdef __AVR__ + port = portOutputRegister(digitalPinToPort(p)); + pinMask = digitalPinToBitMask(p); +#endif +} + +// Set pixel color from separate R,G,B components: +void Adafruit_NeoPixel::setPixelColor( + uint16_t n, uint8_t r, uint8_t g, uint8_t b) { + if(n < numLEDs) { + if(brightness) { // See notes in setBrightness() + r = (r * brightness) >> 8; + g = (g * brightness) >> 8; + b = (b * brightness) >> 8; + } + uint8_t *p = &pixels[n * 3]; + p[rOffset] = r; + p[gOffset] = g; + p[bOffset] = b; + } +} + +// Set pixel color from 'packed' 32-bit RGB color: +void Adafruit_NeoPixel::setPixelColor(uint16_t n, uint32_t c) { + if(n < numLEDs) { + uint8_t + r = (uint8_t)(c >> 16), + g = (uint8_t)(c >> 8), + b = (uint8_t)c; + if(brightness) { // See notes in setBrightness() + r = (r * brightness) >> 8; + g = (g * brightness) >> 8; + b = (b * brightness) >> 8; + } + uint8_t *p = &pixels[n * 3]; + p[rOffset] = r; + p[gOffset] = g; + p[bOffset] = b; + } +} + +// Convert separate R,G,B into packed 32-bit RGB color. +// Packed format is always RGB, regardless of LED strand color order. +uint32_t Adafruit_NeoPixel::Color(uint8_t r, uint8_t g, uint8_t b) { + return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; +} + +// Query color from previously-set pixel (returns packed 32-bit RGB value) +uint32_t Adafruit_NeoPixel::getPixelColor(uint16_t n) const { + if(n >= numLEDs) { + // Out of bounds, return no color. + return 0; + } + uint8_t *p = &pixels[n * 3]; + uint32_t c = ((uint32_t)p[rOffset] << 16) | + ((uint32_t)p[gOffset] << 8) | + (uint32_t)p[bOffset]; + // Adjust this back up to the true color, as setting a pixel color will + // scale it back down again. + if(brightness) { // See notes in setBrightness() + //Cast the color to a byte array + uint8_t * c_ptr =reinterpret_cast(&c); + c_ptr[0] = (c_ptr[0] << 8)/brightness; + c_ptr[1] = (c_ptr[1] << 8)/brightness; + c_ptr[2] = (c_ptr[2] << 8)/brightness; + } + return c; // Pixel # is out of bounds +} + +// Returns pointer to pixels[] array. Pixel data is stored in device- +// native format and is not translated here. Application will need to be +// aware whether pixels are RGB vs. GRB and handle colors appropriately. +uint8_t *Adafruit_NeoPixel::getPixels(void) const { + return pixels; +} + +uint16_t Adafruit_NeoPixel::numPixels(void) const { + return numLEDs; +} + +// Adjust output brightness; 0=darkest (off), 255=brightest. This does +// NOT immediately affect what's currently displayed on the LEDs. The +// next call to show() will refresh the LEDs at this level. However, +// this process is potentially "lossy," especially when increasing +// brightness. The tight timing in the WS2811/WS2812 code means there +// aren't enough free cycles to perform this scaling on the fly as data +// is issued. So we make a pass through the existing color data in RAM +// and scale it (subsequent graphics commands also work at this +// brightness level). If there's a significant step up in brightness, +// the limited number of steps (quantization) in the old data will be +// quite visible in the re-scaled version. For a non-destructive +// change, you'll need to re-render the full strip data. C'est la vie. +void Adafruit_NeoPixel::setBrightness(uint8_t b) { + // Stored brightness value is different than what's passed. + // This simplifies the actual scaling math later, allowing a fast + // 8x8-bit multiply and taking the MSB. 'brightness' is a uint8_t, + // adding 1 here may (intentionally) roll over...so 0 = max brightness + // (color values are interpreted literally; no scaling), 1 = min + // brightness (off), 255 = just below max brightness. + uint8_t newBrightness = b + 1; + if(newBrightness != brightness) { // Compare against prior value + // Brightness has changed -- re-scale existing data in RAM + uint8_t c, + *ptr = pixels, + oldBrightness = brightness - 1; // De-wrap old brightness value + uint16_t scale; + if(oldBrightness == 0) scale = 0; // Avoid /0 + else if(b == 255) scale = 65535 / oldBrightness; + else scale = (((uint16_t)newBrightness << 8) - 1) / oldBrightness; + for(uint16_t i=0; i> 8; + } + brightness = newBrightness; + } +} + +//Return the brightness value +uint8_t Adafruit_NeoPixel::getBrightness(void) const { + return brightness - 1; +} + +void Adafruit_NeoPixel::clear() { + memset(pixels, 0, numBytes); +} diff --git a/libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.h b/libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.h new file mode 100755 index 0000000..264c199 --- /dev/null +++ b/libraries/Adafruit_NeoPixel/Adafruit_NeoPixel.h @@ -0,0 +1,97 @@ +/*-------------------------------------------------------------------- + This file is part of the Adafruit NeoPixel library. + + NeoPixel 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 3 of + the License, or (at your option) any later version. + + NeoPixel 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 NeoPixel. If not, see + . + --------------------------------------------------------------------*/ + +#ifndef ADAFRUIT_NEOPIXEL_H +#define ADAFRUIT_NEOPIXEL_H + +#if (ARDUINO >= 100) + #include +#else + #include + #include +#endif + +// 'type' flags for LED pixels (third parameter to constructor): +#define NEO_RGB 0x00 // Wired for RGB data order +#define NEO_GRB 0x01 // Wired for GRB data order +#define NEO_BRG 0x04 + +#define NEO_COLMASK 0x01 +#define NEO_KHZ800 0x02 // 800 KHz datastream +#define NEO_SPDMASK 0x02 +// Trinket flash space is tight, v1 NeoPixels aren't handled by default. +// Remove the ifndef/endif to add support -- but code will be bigger. +// Conversely, can comment out the #defines to save space on other MCUs. +#ifndef __AVR_ATtiny85__ +#define NEO_KHZ400 0x00 // 400 KHz datastream +#endif + +class Adafruit_NeoPixel { + + public: + + // Constructor: number of LEDs, pin number, LED type + Adafruit_NeoPixel(uint16_t n, uint8_t p=6, uint8_t t=NEO_GRB + NEO_KHZ800); + ~Adafruit_NeoPixel(); + + void + begin(void), + show(void), + setPin(uint8_t p), + setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b), + setPixelColor(uint16_t n, uint32_t c), + setBrightness(uint8_t), + clear(); + uint8_t + *getPixels(void) const, + getBrightness(void) const; + uint16_t + numPixels(void) const; + static uint32_t + Color(uint8_t r, uint8_t g, uint8_t b); + uint32_t + getPixelColor(uint16_t n) const; + inline bool + canShow(void) { return (micros() - endTime) >= 50L; } + + private: + + const uint16_t + numLEDs, // Number of RGB LEDs in strip + numBytes; // Size of 'pixels' buffer below + uint8_t + pin, // Output pin number + brightness, + *pixels, // Holds LED color values (3 bytes each) + rOffset, // Index of red byte within each 3-byte pixel + gOffset, // Index of green byte + bOffset; // Index of blue byte + const uint8_t + type; // Pixel flags (400 vs 800 KHz, RGB vs GRB color) + uint32_t + endTime; // Latch timing reference +#ifdef __AVR__ + const volatile uint8_t + *port; // Output PORT register + uint8_t + pinMask; // Output PORT bitmask +#endif + +}; + +#endif // ADAFRUIT_NEOPIXEL_H diff --git a/libraries/Adafruit_NeoPixel/COPYING b/libraries/Adafruit_NeoPixel/COPYING new file mode 100755 index 0000000..7dcf8e8 --- /dev/null +++ b/libraries/Adafruit_NeoPixel/COPYING @@ -0,0 +1,794 @@ + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + + +LGPL ADDENDUM: + + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/libraries/Adafruit_NeoPixel/README.md b/libraries/Adafruit_NeoPixel/README.md new file mode 100755 index 0000000..2eeda47 --- /dev/null +++ b/libraries/Adafruit_NeoPixel/README.md @@ -0,0 +1,12 @@ +Adafruit NeoPixel library +========================= + +Arduino library for controlling single-wire-based LED pixels and strip such as the [Adafruit 60 LED/meter Digital LED strip][strip], the [Adafruit FLORA RGB Smart Pixel][flora], the [Adafruit Breadboard-friendly RGB Smart Pixel][pixel], the [Adafruit NeoPixel Stick][stick], and the [Adafruit NeoPixel Shield][shield]. + +After downloading, rename folder to 'Adafruit_NeoPixel' and install in Arduino Libraries folder. Restart Arduino IDE, then open File->Sketchbook->Library->Adafruit_NeoPixel->strandtest sketch. + +[flora]: http://adafruit.com/products/1060 +[strip]: http://adafruit.com/products/1138 +[pixel]: http://adafruit.com/products/1312 +[stick]: http://adafruit.com/products/1426 +[shield]: http://adafruit.com/products/1430 diff --git a/libraries/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino b/libraries/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino new file mode 100755 index 0000000..45d9c6a --- /dev/null +++ b/libraries/Adafruit_NeoPixel/examples/buttoncycler/buttoncycler.ino @@ -0,0 +1,165 @@ +// This is a demonstration on how to use an input device to trigger changes on your neo pixels. +// You should wire a momentary push button to connect from ground to a digital IO pin. When you +// press the button it will change to a new pixel animation. Note that you need to press the +// button once to start the first animation! + +#include + +#define BUTTON_PIN 2 // Digital IO pin connected to the button. This will be + // driven with a pull-up resistor so the switch should + // pull the pin to ground momentarily. On a high -> low + // transition the button press logic will execute. + +#define PIXEL_PIN 6 // Digital IO pin connected to the NeoPixels. + +#define PIXEL_COUNT 16 + +// Parameter 1 = number of pixels in strip, neopixel stick has 8 +// Parameter 2 = pin number (most are valid) +// Parameter 3 = pixel type flags, add together as needed: +// NEO_RGB Pixels are wired for RGB bitstream +// NEO_GRB Pixels are wired for GRB bitstream, correct for neopixel stick +// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels) +// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick +Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800); + +bool oldState = HIGH; +int showType = 0; + +void setup() { + pinMode(BUTTON_PIN, INPUT_PULLUP); + strip.begin(); + strip.show(); // Initialize all pixels to 'off' +} + +void loop() { + // Get current button state. + bool newState = digitalRead(BUTTON_PIN); + + // Check if state changed from high to low (button press). + if (newState == LOW && oldState == HIGH) { + // Short delay to debounce button. + delay(20); + // Check if button is still low after debounce. + newState = digitalRead(BUTTON_PIN); + if (newState == LOW) { + showType++; + if (showType > 9) + showType=0; + startShow(showType); + } + } + + // Set the last button state to the old state. + oldState = newState; +} + +void startShow(int i) { + switch(i){ + case 0: colorWipe(strip.Color(0, 0, 0), 50); // Black/off + break; + case 1: colorWipe(strip.Color(255, 0, 0), 50); // Red + break; + case 2: colorWipe(strip.Color(0, 255, 0), 50); // Green + break; + case 3: colorWipe(strip.Color(0, 0, 255), 50); // Blue + break; + case 4: theaterChase(strip.Color(127, 127, 127), 50); // White + break; + case 5: theaterChase(strip.Color(127, 0, 0), 50); // Red + break; + case 6: theaterChase(strip.Color( 0, 0, 127), 50); // Blue + break; + case 7: rainbow(20); + break; + case 8: rainbowCycle(20); + break; + case 9: theaterChaseRainbow(50); + break; + } +} + +// Fill the dots one after the other with a color +void colorWipe(uint32_t c, uint8_t wait) { + for(uint16_t i=0; i +#include + +// Which pin on the Arduino is connected to the NeoPixels? +// On a Trinket or Gemma we suggest changing this to 1 +#define PIN 6 + +// How many NeoPixels are attached to the Arduino? +#define NUMPIXELS 16 + +// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. +// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest +// example for more information on possible values. +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); + +int delayval = 500; // delay for half a second + +void setup() { + // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket +#if defined (__AVR_ATtiny85__) + if (F_CPU == 16000000) clock_prescale_set(clock_div_1); +#endif + // End of trinket special code + + pixels.begin(); // This initializes the NeoPixel library. +} + +void loop() { + + // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one. + + for(int i=0;i +#include + +#define PIN 6 + +// Parameter 1 = number of pixels in strip +// Parameter 2 = Arduino pin number (most are valid) +// Parameter 3 = pixel type flags, add together as needed: +// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) +// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) +// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) +// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) +Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800); + +// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across +// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input +// and minimize distance between Arduino and first pixel. Avoid connecting +// on a live circuit...if you must, connect GND first. + +void setup() { + // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket +#if defined (__AVR_ATtiny85__) + if (F_CPU == 16000000) clock_prescale_set(clock_div_1); +#endif + // End of trinket special code + + + strip.begin(); + strip.show(); // Initialize all pixels to 'off' +} + +void loop() { + // Some example procedures showing how to display to the pixels: + colorWipe(strip.Color(255, 0, 0), 50); // Red + colorWipe(strip.Color(0, 255, 0), 50); // Green + colorWipe(strip.Color(0, 0, 255), 50); // Blue + // Send a theater pixel chase in... + theaterChase(strip.Color(127, 127, 127), 50); // White + theaterChase(strip.Color(127, 0, 0), 50); // Red + theaterChase(strip.Color( 0, 0, 127), 50); // Blue + + rainbow(20); + rainbowCycle(20); + theaterChaseRainbow(50); +} + +// Fill the dots one after the other with a color +void colorWipe(uint32_t c, uint8_t wait) { + for(uint16_t i=0; i +sentence=Arduino library for controlling single-wire-based LED pixels and strip. +paragraph=Arduino library for controlling single-wire-based LED pixels and strip. +category=Display +url=https://github.com/adafruit/Adafruit_NeoPixel +architectures=* diff --git a/libraries/MySensors/examples/ParkingSensor/ParkingSensor.ino b/libraries/MySensors/examples/ParkingSensor/ParkingSensor.ino new file mode 100644 index 0000000..d54e599 --- /dev/null +++ b/libraries/MySensors/examples/ParkingSensor/ParkingSensor.ino @@ -0,0 +1,164 @@ +/** + * The MySensors Arduino library handles the wireless radio link and protocol + * between your home built sensors/actuators and HA controller of choice. + * The sensors forms a self healing radio network with optional repeaters. Each + * repeater and gateway builds a routing tables in EEPROM which keeps track of the + * network topology allowing messages to be routed to nodes. + * + * Created by Henrik Ekblad + * Copyright (C) 2013-2015 Sensnology AB + * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors + * + * Documentation: http://www.mysensors.org + * Support Forum: http://forum.mysensors.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + ******************************* + * + * REVISION HISTORY + * Version 1.0 - Created by Henrik Ekblad + * + * DESCRIPTION + * Parking sensor using a neopixel led ring and distance sensor (HC-SR04). + * Configure the digital pins used for distance sensor and neopixels below. + * NOTE! Remeber to feed leds and distance sensor serparatly from your Arduino. + * It will probably not survive feeding more than a couple of LEDs. You + * can also adjust intesity below to reduce the power requirements. + * + * Sends parking status to the controller as a DOOR sensor if SEND_STATUS_TO_CONTROLLER + * is defined below. You can also use this _standalone_ without any radio by + * removing the SEND_STATUS_TO_CONTROLLER define. + */ + +#define SEND_STATUS_TO_CONTROLLER // Put a comment on this line for standalone mode + +#include +#include + +#ifdef SEND_STATUS_TO_CONTROLLER +#include +#include +#endif + +#define NEO_PIN 4 // NeoPixels input pin + +#define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor. +#define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor. + +#define NUMPIXELS 24 // Number of nexpixels in ring/strip +#define MAX_INTESITY 20 // Intesity of leds (in percentage). Remeber more intesity requires more power. + +// The maximum rated measuring range for the HC-SR04 is about 400-500cm. +#define MAX_DISTANCE 100 // Max distance we want to start indicating green (in cm) +#define PANIC_DISTANCE 5 // Mix distance we red warning indication should be active (in cm) +#define PARKED_DISTANCE 20 // Distance when "parked signal" should be sent to controller (in cm) + +// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest +// example for more information on possible values. + +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, NEO_PIN, NEO_GRB + NEO_KHZ400); + +NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. + +#ifdef SEND_STATUS_TO_CONTROLLER +#define CHILD_ID 1 +MySensor gw; +MyMessage msg(CHILD_ID,V_TRIPPED); +int oldParkedStatus=-1; +int sendInterval = 5000; // Send park status at maximum every 5 second. +unsigned long lastSend; +#endif + +int blinkInterval = 100; // blink interval (milliseconds) +unsigned long lastBlinkPeriod; +bool blinkColor = true; + +// To make a fading motion on the led ring/tape we only move one pixel/distDebounce time +int distDebounce = 30; +unsigned long lastDebouncePeriod; +int numLightPixels=0; +int skipZero=0; + +void setup() { + Serial.begin(115200); + Serial.println("Starting distance sensor"); + pixels.begin(); // This initializes the NeoPixel library. + Serial.println("Neopixels initialized"); +#ifdef SEND_STATUS_TO_CONTROLLER + gw.begin(); + gw.sendSketchInfo("Parking Sensor", "1.0"); + gw.present(CHILD_ID, S_DOOR, "Parking Status"); +#endif +} + +void loop() { + unsigned long now = millis(); + + int fullDist = sonar.ping_cm(); +// Serial.println(fullDist); + int displayDist = min(fullDist, MAX_DISTANCE); + if (displayDist == 0 && skipZero<10) { + // Try to filter zero readings + skipZero++; + return; + } + // Check if it is time to alter the leds + if (now-lastDebouncePeriod > distDebounce) { + lastDebouncePeriod = now; + +#ifdef SEND_STATUS_TO_CONTROLLER + // Update parked status + int parked = displayDist != 0 && displayDist sendInterval) { + if (parked) + Serial.println("Car Parked"); + else + Serial.println("Car Gone"); + gw.send(msg.set(parked)); + oldParkedStatus = parked; + lastSend = now; + } +#endif + + if (displayDist == 0) { + // No reading from sensor, assume no object found + numLightPixels--; + } else { + skipZero = 0; + int newLightPixels = NUMPIXELS - (NUMPIXELS*(displayDist-PANIC_DISTANCE)/MAX_DISTANCE); + if (newLightPixels>numLightPixels) { + // Fast raise + numLightPixels += max((newLightPixels - numLightPixels) / 2, 1); + } else if (newLightPixels=NUMPIXELS) { + // Do some intense red blinking + if (now-lastBlinkPeriod > blinkInterval) { + blinkColor = !blinkColor; + lastBlinkPeriod = now; + } + for(int i=0;i Date: Sun, 2 Aug 2015 13:15:11 +0200 Subject: [PATCH 71/79] OTA stability - add OTA-ongoing check - reduce OTA code size --- libraries/MySensors/MySensor.cpp | 62 ++++++++++++++++---------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 4f3e930..bdab9c2 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -522,7 +522,7 @@ boolean MySensor::process() { #ifdef MY_OTA_FIRMWARE_FEATURE unsigned long enter = hw_millis(); if (fwUpdateOngoing && (enter - fwLastRequestTime > MY_OTA_RETRY_DELAY)) { - if (fwRetry == 0) { + if (!fwRetry) { debug(PSTR("fw upd fail\n")); // Give up. We have requested MY_OTA_RETRY times without any packet in return. fwUpdateOngoing = false; @@ -746,38 +746,38 @@ boolean MySensor::process() { return false; } else debug(PSTR("fw update skipped\n")); } else if (type == ST_FIRMWARE_RESPONSE) { - // Save block to flash - debug(PSTR("fw block %d\n"), fwBlock); - // extract FW block - ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data; - // write to flash - flash.writeBytes( ((fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); - // wait until flash written - while ( flash.busy() ); - fwBlock--; - if (!fwBlock) { - // We're finished! Do a checksum and reboot. - if (isValidFirmware()) { - debug(PSTR("fw checksum ok\n")); - // All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it) - flash.writeBytes(0, "FLXIMG:", 7); - // FW size in flash - uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks; - flash.writeByte(7, fwsize >> 8); - flash.writeByte(8, fwsize); - // end of header - flash.writeByte(9, ':'); - // Write the new firmware config to eeprom - hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); - hw_reboot(); - } else { - debug(PSTR("fw checksum fail\n")); + if (fwUpdateOngoing) { + // Save block to flash + debug(PSTR("fw block %d\n"), fwBlock); + // extract FW block + ReplyFWBlock *firmwareResponse = (ReplyFWBlock *)msg.data; + // write to flash + flash.writeBytes( ((fwBlock - 1) * FIRMWARE_BLOCK_SIZE) + FIRMWARE_START_OFFSET, firmwareResponse->data, FIRMWARE_BLOCK_SIZE); + // wait until flash written + while ( flash.busy() ); + fwBlock--; + if (!fwBlock) { + // We're finished! Do a checksum and reboot. fwUpdateOngoing = false; - } + if (isValidFirmware()) { + debug(PSTR("fw checksum ok\n")); + // All seems ok, write size and signature to flash (DualOptiboot will pick this up and flash it) + uint16_t fwsize = FIRMWARE_BLOCK_SIZE * fc.blocks; + uint8_t OTAbuffer[10] = {'F','L','X','I','M','G',':',(fwsize >> 8),fwsize,':'}; + flash.writeBytes(0, OTAbuffer, 10); + // Write the new firmware config to eeprom + hw_writeConfigBlock((void*)&fc, (void*)EEPROM_FIRMWARE_TYPE_ADDRESS, sizeof(NodeFirmwareConfig)); + hw_reboot(); + } else { + debug(PSTR("fw checksum fail\n")); + } + } + // reset flags + fwRetry = MY_OTA_RETRY+1; + fwLastRequestTime = 0; + } else { + debug(PSTR("No fw update ongoing\n")); } - // reset flags - fwRetry = MY_OTA_RETRY+1; - fwLastRequestTime = 0; return false; } From d98bacb56764428f5871a69bd887f5e9c37972dd Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Mon, 3 Aug 2015 20:22:30 +0200 Subject: [PATCH 72/79] Fix EthernetGateway connect problem. Reported by Carh H here: http://forum.mysensors.org/topic/1736/release-1-5-and-ethernet-gateway --- .../MySensors/examples/EthernetGateway/EthernetGateway.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino index fe19206..5148648 100644 --- a/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino +++ b/libraries/MySensors/examples/EthernetGateway/EthernetGateway.ino @@ -135,7 +135,7 @@ void output(const char *fmt, ... ) { vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args); va_end (args); Serial.print(serialBuffer); - client.write(serialBuffer); + server.write(serialBuffer); } void setup() From f7204cfcab106a079a09606205a223a0d45e697a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Mon, 3 Aug 2015 22:38:29 +0200 Subject: [PATCH 73/79] Enable OTA wait period after each transmission, if A1 is held low during bootup --- .../SensebenderMicro/SensebenderMicro.ino | 37 ++++++++++++++++--- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 9ac53de..64ded83 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -29,6 +29,12 @@ * * Battery voltage is as battery percentage (Internal message), and optionally as a sensor value (See defines below) * + * + * Version 1.3 - Thomas Bowman Mørch + * Improved transmission logic, eliminating spurious transmissions (when temperatuere / humidity fluctuates 1 up and down between measurements) + * + * Added OTA boot mode, need to hold A1 low while applying power. (uses slightly more power as it's waiting for bootloader messages) + * */ @@ -49,7 +55,7 @@ // Uncomment the line below, to transmit battery voltage as a normal sensor value //#define BATT_SENSOR 199 -#define RELEASE "1.2" +#define RELEASE "1.3" #define AVERAGES 2 @@ -60,6 +66,9 @@ // How many milli seconds between each measurement #define MEASURE_INTERVAL 60000 +// How many milli seconds should we wait for OTA? +#define OTA_WAIT_PERIOD 1000 + // FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller #define FORCE_TRANSMIT_INTERVAL 30 @@ -73,6 +82,7 @@ // Pin definitions #define TEST_PIN A0 +#define OTA_ENABLE A1 #define LED_PIN A2 #define ATSHA204_PIN 17 // A3 @@ -97,6 +107,8 @@ int measureCount = 0; int sendBattery = 0; boolean isMetric = true; boolean highfreq = true; +boolean ota_enabled = false; +boolean transmission_occured = false; // Storage of old measurements float lastTemperature = -100; @@ -126,11 +138,17 @@ void setup() { digitalWrite(TEST_PIN, HIGH); // Enable pullup if (!digitalRead(TEST_PIN)) testMode(); + pinMode(OTA_ENABLE, INPUT); + digitalWrite(OTA_ENABLE, HIGH); + if (!digitalRead(OTA_ENABLE)) ota_enabled = true; + // Make sure that ATSHA204 is not floating pinMode(ATSHA204_PIN, INPUT); digitalWrite(ATSHA204_PIN, HIGH); digitalWrite(TEST_PIN,LOW); + digitalWrite(OTA_ENABLE, LOW); // remove pullup, save some power. + digitalWrite(LED_PIN, HIGH); #ifdef NODE_ADDRESS @@ -169,13 +187,14 @@ void setup() { * ***********************************************/ void loop() { + measureCount ++; sendBattery ++; bool forceTransmit = false; - + transmission_occured = false; if ((measureCount == 5) && highfreq) { -// clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. + clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. highfreq = false; } @@ -192,7 +211,11 @@ void loop() { sendBattLevel(forceTransmit); // Not needed to send battery info that often sendBattery = 0; } - + + if (ota_enabled & transmission_occured) { + gw.wait(OTA_WAIT_PERIOD); + } + gw.sleep(MEASURE_INTERVAL); } @@ -235,6 +258,7 @@ void sendTempHumidityMeasurements(bool force) gw.send(msgHum.set(humidity)); lastTemperature = temperature; lastHumidity = humidity; + transmission_occured = true; } } @@ -263,6 +287,7 @@ void sendBattLevel(bool force) long percent = vcc / 14.0; gw.sendBatteryLevel(percent); + transmission_occured = true; } } @@ -271,7 +296,7 @@ void sendBattLevel(bool force) * Internal battery ADC measuring * *******************************************/ -long readVcc() {/* +long readVcc() { // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) @@ -295,7 +320,7 @@ long readVcc() {/* result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 return result; // Vcc in millivolts - */ + } /**************************************************** From 8e73752a037a4885ffa59d657954386ae22b46e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Mon, 3 Aug 2015 22:56:49 +0200 Subject: [PATCH 74/79] changed wait period to 300 mili seconds (@tekka recons 100-200mSeconds is enough, just want to be on the safe side, added serial debug string to indicate OTA FW updates enabled --- .../examples/SensebenderMicro/SensebenderMicro.ino | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 64ded83..87d0424 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -67,7 +67,7 @@ #define MEASURE_INTERVAL 60000 // How many milli seconds should we wait for OTA? -#define OTA_WAIT_PERIOD 1000 +#define OTA_WAIT_PERIOD 300 // FORCE_TRANSMIT_INTERVAL, this number of times of wakeup, the sensor is forced to report all values to the controller #define FORCE_TRANSMIT_INTERVAL 30 @@ -140,7 +140,9 @@ void setup() { pinMode(OTA_ENABLE, INPUT); digitalWrite(OTA_ENABLE, HIGH); - if (!digitalRead(OTA_ENABLE)) ota_enabled = true; + if (!digitalRead(OTA_ENABLE)) { + ota_enabled = true; + } // Make sure that ATSHA204 is not floating pinMode(ATSHA204_PIN, INPUT); @@ -178,6 +180,8 @@ void setup() { raHum.clear(); sendTempHumidityMeasurements(false); sendBattLevel(false); + if (ota_enabled) Serial.println("OTA FW update enabled"); + } From 3cf4bb65af79f810f2bd1ec9d18c4079718ba7a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Mon, 3 Aug 2015 23:02:19 +0200 Subject: [PATCH 75/79] don't scale CPU Freq, if OTA FW Updates are enabled --- .../MySensors/examples/SensebenderMicro/SensebenderMicro.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino index 87d0424..e14f5a8 100644 --- a/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino +++ b/libraries/MySensors/examples/SensebenderMicro/SensebenderMicro.ino @@ -198,7 +198,7 @@ void loop() { transmission_occured = false; if ((measureCount == 5) && highfreq) { - clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. + if (!ota_enabled) clock_prescale_set(clock_div_8); // Switch to 1Mhz for the reminder of the sketch, save power. highfreq = false; } From cb83bfbdb3ed32ef57040cff9954b390ec9a2528 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 4 Aug 2015 21:00:32 +0200 Subject: [PATCH 76/79] Inverse the default rx/tx/err led behaviour and introduce WITH_LEDS_BLINKING_INVERSE option in MyConfig. This allows easy inversing of led blink behavior depending on how the leds were connected. Introduce hw-macro for digitalWrite used by the LED blinking. --- libraries/MySensors/MyConfig.h | 9 ++++++++- libraries/MySensors/MyHwATMega328.h | 2 ++ libraries/MySensors/MySensor.cpp | 18 +++++++++--------- libraries/MySensors/MySensor.h | 8 ++++++++ 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 098a1f9..88db782 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -53,7 +53,14 @@ // but now can be used in any sensor node. Also the LEDs can now be // disabled in the gateway. -// #define WITH_LEDS_BLINKING +//#define WITH_LEDS_BLINKING + +// The following setting allows you to inverse the blinking feature WITH_LEDS_BLINKING +// When WITH_LEDS_BLINKING_INVERSE is enabled LEDSs are normally turned on and switches +// off when blinking + +//#define WITH_LEDS_BLINKING_INVERSE + // default LEDs blinking period in milliseconds #define DEFAULT_LED_BLINK_PERIOD 300 diff --git a/libraries/MySensors/MyHwATMega328.h b/libraries/MySensors/MyHwATMega328.h index 12698d4..9e42b55 100644 --- a/libraries/MySensors/MyHwATMega328.h +++ b/libraries/MySensors/MyHwATMega328.h @@ -57,6 +57,8 @@ do { \ // Define these as macros to save valuable space + +#define hw_digitalWrite(__pin, __value) (digitalWrite(__pin, __value)) #define hw_init() Serial.begin(BAUD_RATE) #define hw_watchdogReset() wdt_reset() #define hw_reboot() wdt_enable(WDTO_15MS); while (1) diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index bdab9c2..9d6ecb8 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -107,33 +107,33 @@ void MySensor::handleLedsBlinking() { // do the actual blinking if(countRx && countRx != 255) { // switch led on - digitalWrite(pinRx, HIGH); + hw_digitalWrite(pinRx, LED_ON); } else if(!countRx) { // switching off - digitalWrite(pinRx, LOW); + hw_digitalWrite(pinRx, LED_OFF); } if(countRx != 255) --countRx; if(countTx && countTx != 255) { // switch led on - digitalWrite(pinTx, HIGH); + hw_digitalWrite(pinTx, LED_ON); } else if(!countTx) { // switching off - digitalWrite(pinTx, LOW); + hw_digitalWrite(pinTx, LED_OFF); } if(countTx != 255) --countTx; if(countErr && countErr != 255) { // switch led on - digitalWrite(pinEr, HIGH); + hw_digitalWrite(pinEr, LED_ON); } else if(!countErr) { // switching off - digitalWrite(pinEr, LOW); + hw_digitalWrite(pinEr, LED_OFF); } if(countErr != 255) --countErr; @@ -179,9 +179,9 @@ void MySensor::begin(void (*_msgCallback)(const MyMessage &), uint8_t _nodeId, b pinMode(pinEr, OUTPUT); // Set initial state of leds - digitalWrite(pinRx, LOW); - digitalWrite(pinTx, LOW); - digitalWrite(pinEr, LOW); + hw_digitalWrite(pinRx, LED_OFF); + hw_digitalWrite(pinTx, LED_OFF); + hw_digitalWrite(pinEr, LED_OFF); // initialize counters countRx = 0; diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index abf7283..0a54987 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -52,6 +52,14 @@ typedef MyHwATMega328 MyHwDriver; #define debug(x,...) #endif +#ifdef WITH_LEDS_BLINKING_INVERSE +#define LED_ON 0x1 +#define LED_OFF 0x0 +#else +#define LED_ON 0x0 +#define LED_OFF 0x1 +#endif + // EEPROM start address for mysensors library data #define EEPROM_START 0 From 2343d8ae8fb72bdcab467b158eb77c09af6fda5d Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Tue, 4 Aug 2015 21:38:10 +0200 Subject: [PATCH 77/79] Added sendHeatbeat() Allow a sensor to send a "dummy" message to controller to say "I'm still alive!". The payload will be an incremental uint16. --- libraries/MySensors/MyMessage.h | 3 ++- libraries/MySensors/MySensor.cpp | 5 +++++ libraries/MySensors/MySensor.h | 7 +++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/libraries/MySensors/MyMessage.h b/libraries/MySensors/MyMessage.h index 129801f..03a203c 100644 --- a/libraries/MySensors/MyMessage.h +++ b/libraries/MySensors/MyMessage.h @@ -146,7 +146,8 @@ typedef enum { I_BATTERY_LEVEL, I_TIME, I_VERSION, I_ID_REQUEST, I_ID_RESPONSE, I_INCLUSION_MODE, I_CONFIG, I_FIND_PARENT, I_FIND_PARENT_RESPONSE, I_LOG_MESSAGE, I_CHILDREN, I_SKETCH_NAME, I_SKETCH_VERSION, - I_REBOOT, I_GATEWAY_READY, I_REQUEST_SIGNING, I_GET_NONCE, I_GET_NONCE_RESPONSE + I_REBOOT, I_GATEWAY_READY, I_REQUEST_SIGNING, I_GET_NONCE, I_GET_NONCE_RESPONSE, + I_HEARTBEAT } mysensor_internal; diff --git a/libraries/MySensors/MySensor.cpp b/libraries/MySensors/MySensor.cpp index 9d6ecb8..5558d6a 100644 --- a/libraries/MySensors/MySensor.cpp +++ b/libraries/MySensors/MySensor.cpp @@ -487,6 +487,11 @@ void MySensor::sendBatteryLevel(uint8_t value, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_BATTERY_LEVEL, enableAck).set(value)); } +void MySensor::sendHeartbeat(void) { + sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_HEARTBEAT, false).set(heartbeat++)); + +} + void MySensor::present(uint8_t childSensorId, uint8_t sensorType, const char *description, bool enableAck) { sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, childSensorId, C_PRESENTATION, sensorType, enableAck).set(childSensorId==NODE_SENSOR_ID?LIBRARY_VERSION:description)); } diff --git a/libraries/MySensors/MySensor.h b/libraries/MySensors/MySensor.h index 0a54987..9b9e8dd 100644 --- a/libraries/MySensors/MySensor.h +++ b/libraries/MySensors/MySensor.h @@ -219,6 +219,12 @@ class MySensor */ void sendBatteryLevel(uint8_t level, bool ack=false); + /** + * Send a heartbeat message (I'm alive!) to the gateway/controller. + * The payload will be an incremental 16 bit integer value starting at 1 when sensor is powered on. + */ + void sendHeartbeat(void); + /** * Requests a value from gateway or some other sensor in the radio network. * Make sure to add callback-method in begin-method to handle request responses. @@ -373,6 +379,7 @@ class MySensor char convBuf[MAX_PAYLOAD*2+1]; #endif uint8_t failedTransmissions; + uint16_t heartbeat; void (*timeCallback)(unsigned long); // Callback for requested time messages void (*msgCallback)(const MyMessage &); // Callback for incoming messages from other nodes and gateway. From 9faaf8e6f8c395c2ef19cc7195652914f41bd053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=B8rch?= Date: Tue, 4 Aug 2015 22:33:06 +0200 Subject: [PATCH 78/79] Initial support for SAMD device in development branch --- hardware/MySensors/samd/boards.txt | 42 +++ .../CorrectADCResponse/CorrectADCResponse.ino | 210 +++++++++++ .../SAMD_AnalogCorrection/library.properties | 8 + .../src/SAMD_AnalogCorrection.cpp | 31 ++ .../src/SAMD_AnalogCorrection.h | 24 ++ hardware/MySensors/samd/libraries/SPI/SPI.cpp | 200 ++++++++++ hardware/MySensors/samd/libraries/SPI/SPI.h | 153 ++++++++ .../BarometricPressureSensor.ino | 143 +++++++ .../DigitalPotControl/DigitalPotControl.ino | 71 ++++ .../MySensors/samd/libraries/SPI/keywords.txt | 31 ++ .../MySensors/samd/libraries/Wire/Wire.cpp | 355 ++++++++++++++++++ hardware/MySensors/samd/libraries/Wire/Wire.h | 104 +++++ .../SFRRanger_reader/SFRRanger_reader.pde | 87 +++++ .../digital_potentiometer.pde | 39 ++ .../examples/master_reader/master_reader.pde | 32 ++ .../examples/master_writer/master_writer.pde | 31 ++ .../slave_receiver/slave_receiver.pde | 38 ++ .../examples/slave_sender/slave_sender.pde | 32 ++ .../samd/libraries/Wire/keywords.txt | 32 ++ hardware/MySensors/samd/platform.txt | 143 +++++++ .../mysensors_gw/debug_scripts/variant.gdb | 31 ++ .../gcc/flash_with_bootloader.ld | 211 +++++++++++ .../gcc/flash_without_bootloader.ld | 212 +++++++++++ .../openocd_scripts/mysensors_gw.cfg | 30 ++ .../samd/variants/mysensors_gw/pins_arduino.h | 21 ++ .../samd/variants/mysensors_gw/variant.cpp | 221 +++++++++++ .../samd/variants/mysensors_gw/variant.h | 201 ++++++++++ 27 files changed, 2733 insertions(+) create mode 100644 hardware/MySensors/samd/boards.txt create mode 100644 hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/examples/CorrectADCResponse/CorrectADCResponse.ino create mode 100644 hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/library.properties create mode 100644 hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.cpp create mode 100644 hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.h create mode 100644 hardware/MySensors/samd/libraries/SPI/SPI.cpp create mode 100644 hardware/MySensors/samd/libraries/SPI/SPI.h create mode 100644 hardware/MySensors/samd/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino create mode 100644 hardware/MySensors/samd/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino create mode 100644 hardware/MySensors/samd/libraries/SPI/keywords.txt create mode 100644 hardware/MySensors/samd/libraries/Wire/Wire.cpp create mode 100644 hardware/MySensors/samd/libraries/Wire/Wire.h create mode 100644 hardware/MySensors/samd/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.pde create mode 100644 hardware/MySensors/samd/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.pde create mode 100644 hardware/MySensors/samd/libraries/Wire/examples/master_reader/master_reader.pde create mode 100644 hardware/MySensors/samd/libraries/Wire/examples/master_writer/master_writer.pde create mode 100644 hardware/MySensors/samd/libraries/Wire/examples/slave_receiver/slave_receiver.pde create mode 100644 hardware/MySensors/samd/libraries/Wire/examples/slave_sender/slave_sender.pde create mode 100644 hardware/MySensors/samd/libraries/Wire/keywords.txt create mode 100644 hardware/MySensors/samd/platform.txt create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/debug_scripts/variant.gdb create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_with_bootloader.ld create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_without_bootloader.ld create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/openocd_scripts/mysensors_gw.cfg create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/pins_arduino.h create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/variant.cpp create mode 100644 hardware/MySensors/samd/variants/mysensors_gw/variant.h diff --git a/hardware/MySensors/samd/boards.txt b/hardware/MySensors/samd/boards.txt new file mode 100644 index 0000000..1728623 --- /dev/null +++ b/hardware/MySensors/samd/boards.txt @@ -0,0 +1,42 @@ +# Copyright (c) 2014-2015 Arduino LLC. All right reserved. +# +# 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 + +mysensors_gw_native.name=Sensebender GW (Native USB Port) +mysensors_gw_native.vid.0=0x2341 +mysensors_gw_native.pid.0=0x804d +mysensors_gw_native.vid.1=0x2341 +mysensors_gw_native.pid.1=0x004d +mysensors_gw_native.upload.tool=bossac +mysensors_gw_native.upload.protocol=sam-ba +mysensors_gw_native.upload.maximum_size=262144 +mysensors_gw_native.upload.use_1200bps_touch=true +mysensors_gw_native.upload.wait_for_upload_port=true +mysensors_gw_native.upload.native_usb=true +mysensors_gw_native.build.mcu=cortex-m0plus +mysensors_gw_native.build.f_cpu=48000000L +mysensors_gw_native.build.usb_product="Arduino Zero" +mysensors_gw_native.build.usb_manufacturer="Arduino LLC" +mysensors_gw_native.build.board=SAMD_ZERO +mysensors_gw_native.build.core=arduino:arduino +mysensors_gw_native.build.extra_flags=-D__SAMD21G18A__ {build.usb_flags} +mysensors_gw_native.build.ldscript=linker_scripts/gcc/flash_with_bootloader.ld +mysensors_gw_native.build.openocdscript=openocd_scripts/mysensors_gw.cfg +mysensors_gw_native.build.variant=mysensors_gw +mysensors_gw_native.build.variant_system_lib= +mysensors_gw_native.build.vid=0x2341 +mysensors_gw_native.build.pid=0x804d +mysensors_gw_native.bootloader.tool=openocd +mysensors_gw_native.bootloader.file=zero/samd21_sam_ba.bin diff --git a/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/examples/CorrectADCResponse/CorrectADCResponse.ino b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/examples/CorrectADCResponse/CorrectADCResponse.ino new file mode 100644 index 0000000..2b74538 --- /dev/null +++ b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/examples/CorrectADCResponse/CorrectADCResponse.ino @@ -0,0 +1,210 @@ +/* + This sketch easily and quickly finds the right ADC correction values for a particular Arduino ZERO board. + The correction values that are found are only valid for the board where the sketch is executed. + + This example code is in the public domain. + + Written 6 May 2015 by Claudio Indellicati +*/ + +/* + How to use this sketch + + 1) Remove any connection cable, shield or jumper from your Arduino ZERO + 2) Connect pin A1 to the nearest GND pin using the shortest jumper possible + 3) Connect pin A2 to the 3.3V pin using the shortest jumper possible + 4) Connect the Arduino ZERO to your PC using a USB cable plugged in the USB programming port of the board + 5) Upload this sketch and leave the board powered on for at least one minute + 6) Open the Serial Monitor and press the reset button on the Arduino ZERO + 7) At the and of the procedure you can find logged + - the offset and gain values for the board where the sketch has been just executed + - the instruction line to copy/paste in the final sketch +*/ + +#include "SAMD_AnalogCorrection.h" + +#define ADC_GND_PIN A1 +#define ADC_3V3_PIN A2 + +#define ADC_READS_SHIFT 8 +#define ADC_READS_COUNT (1 << ADC_READS_SHIFT) + +#define ADC_MIN_GAIN 0x0400 +#define ADC_UNITY_GAIN 0x0800 +#define ADC_MAX_GAIN (0x1000 - 1) +#define ADC_RESOLUTION_BITS 12 +#define ADC_RANGE (1 << ADC_RESOLUTION_BITS) +#define ADC_TOP_VALUE (ADC_RANGE - 1) + +#define MAX_TOP_VALUE_READS 10 + +void setup() +{ + Serial.begin(9600); + + Serial.println("\r\nCalibrating ADC with factory values"); + + analogReadResolution(ADC_RESOLUTION_BITS); + + Serial.println("\r\nReading GND and 3.3V ADC levels"); + Serial.print(" "); + readGndLevel(); + Serial.print(" "); + read3V3Level(); + + int offsetCorrectionValue = 0; + uint16_t gainCorrectionValue = ADC_UNITY_GAIN; + + Serial.print("\r\nOffset correction (@gain = "); + Serial.print(gainCorrectionValue); + Serial.println(" (unity gain))"); + + // Set default correction values and enable correction + analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); + + for (int offset = 0; offset < (int)(ADC_OFFSETCORR_MASK >> 1); ++offset) + { + analogReadCorrection(offset, gainCorrectionValue); + + Serial.print(" Offset = "); + Serial.print(offset); + Serial.print(", "); + + if (readGndLevel() == 0) + { + offsetCorrectionValue = offset; + break; + } + } + + Serial.println("\r\nGain correction"); + + uint8_t topValueReadsCount = 0U; + + uint16_t minGain = 0U, + maxGain = 0U; + + analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); + Serial.print(" Gain = "); + Serial.print(gainCorrectionValue); + Serial.print(", "); + uint16_t highLevelRead = read3V3Level(); + + if (highLevelRead < ADC_TOP_VALUE) + { + for (uint16_t gain = ADC_UNITY_GAIN + 1; gain <= ADC_MAX_GAIN; ++gain) + { + analogReadCorrection(offsetCorrectionValue, gain); + + Serial.print(" Gain = "); + Serial.print(gain); + Serial.print(", "); + highLevelRead = read3V3Level(); + + if (highLevelRead == ADC_TOP_VALUE) + { + if (minGain == 0U) + minGain = gain; + + if (++topValueReadsCount >= MAX_TOP_VALUE_READS) + { + maxGain = minGain; + break; + } + + maxGain = gain; + } + + if (highLevelRead > ADC_TOP_VALUE) + break; + } + } + else if (highLevelRead >= ADC_TOP_VALUE) + { + if (highLevelRead == ADC_TOP_VALUE) + maxGain = ADC_UNITY_GAIN; + + for (uint16_t gain = ADC_UNITY_GAIN - 1; gain >= ADC_MIN_GAIN; --gain) + { + analogReadCorrection(offsetCorrectionValue, gain); + + Serial.print(" Gain = "); + Serial.print(gain); + Serial.print(", "); + highLevelRead = read3V3Level(); + + if (highLevelRead == ADC_TOP_VALUE) + { + if (maxGain == 0U) + maxGain = gain; + + minGain = gain; + } + + if (highLevelRead < ADC_TOP_VALUE) + break; + } + } + + gainCorrectionValue = (minGain + maxGain) >> 1; + + analogReadCorrection(offsetCorrectionValue, gainCorrectionValue); + + Serial.println("\r\nReadings after corrections"); + Serial.print(" "); + readGndLevel(); + Serial.print(" "); + read3V3Level(); + + Serial.println("\r\n=================="); + Serial.println("\r\nCorrection values:"); + Serial.print(" Offset = "); + Serial.println(offsetCorrectionValue); + Serial.print(" Gain = "); + Serial.println(gainCorrectionValue); + Serial.println("\r\nAdd the next line to your sketch:"); + Serial.print(" analogReadCorrection("); + Serial.print(offsetCorrectionValue); + Serial.print(", "); + Serial.print(gainCorrectionValue); + Serial.println(");"); + Serial.println("\r\n=================="); +} + +void loop() +{ +} + +uint16_t readGndLevel() +{ + uint32_t readAccumulator = 0; + + for (int i = 0; i < ADC_READS_COUNT; ++i) + readAccumulator += analogRead(ADC_GND_PIN); + + uint16_t readValue = readAccumulator >> ADC_READS_SHIFT; + + Serial.print("ADC(GND) = "); + Serial.println(readValue); + + return readValue; +} + +uint16_t read3V3Level() +{ + uint32_t readAccumulator = 0; + + for (int i = 0; i < ADC_READS_COUNT; ++i) + readAccumulator += analogRead(ADC_3V3_PIN); + + uint16_t readValue = readAccumulator >> ADC_READS_SHIFT; + + if (readValue < (ADC_RANGE >> 1)) + readValue += ADC_RANGE; + + Serial.print("ADC(3.3V) = "); + Serial.println(readValue); + + return readValue; +} + diff --git a/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/library.properties b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/library.properties new file mode 100644 index 0000000..e12ada2 --- /dev/null +++ b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/library.properties @@ -0,0 +1,8 @@ +name=SAMD_AnalogCorrection +version=1.0 +author=Arduino +maintainer=Arduino +sentence=Sets and enables the digital correction logic of the SAMD ADC. +paragraph=Useful to correct the values returned by the ADC. +url= +architectures=samd diff --git a/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.cpp b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.cpp new file mode 100644 index 0000000..1681b0a --- /dev/null +++ b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.cpp @@ -0,0 +1,31 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 "SAMD_AnalogCorrection.h" + +void analogReadCorrection (int offset, uint16_t gain) +{ + // Set correction values + ADC->OFFSETCORR.reg = ADC_OFFSETCORR_OFFSETCORR(offset); + ADC->GAINCORR.reg = ADC_GAINCORR_GAINCORR(gain); + + // Enable digital correction logic + ADC->CTRLB.bit.CORREN = 1; + while(ADC->STATUS.bit.SYNCBUSY); +} + diff --git a/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.h b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.h new file mode 100644 index 0000000..5edb91e --- /dev/null +++ b/hardware/MySensors/samd/libraries/SAMD_AnalogCorrection/src/SAMD_AnalogCorrection.h @@ -0,0 +1,24 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + + 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 +*/ + +#pragma once + +#include + +void analogReadCorrection (int offset, uint16_t gain); + diff --git a/hardware/MySensors/samd/libraries/SPI/SPI.cpp b/hardware/MySensors/samd/libraries/SPI/SPI.cpp new file mode 100644 index 0000000..e4af046 --- /dev/null +++ b/hardware/MySensors/samd/libraries/SPI/SPI.cpp @@ -0,0 +1,200 @@ +/* + * SPI Master library for Arduino Zero. + * Copyright (c) 2015 Arduino LLC + * + * 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 "SPI.h" +#include +#include +#include + +#define SPI_IMODE_NONE 0 +#define SPI_IMODE_EXTINT 1 +#define SPI_IMODE_GLOBAL 2 + +const SPISettings DEFAULT_SPI_SETTINGS = SPISettings(); + +SPIClass::SPIClass(SERCOM *p_sercom, uint8_t uc_pinMISO, uint8_t uc_pinSCK, uint8_t uc_pinMOSI) +{ + initialized = false; + assert(p_sercom != NULL); + _p_sercom = p_sercom; + + _uc_pinMiso = uc_pinMISO; + _uc_pinSCK = uc_pinSCK; + _uc_pinMosi = uc_pinMOSI; +} + +void SPIClass::begin() +{ + init(); + + // PIO init + pinPeripheral(_uc_pinMiso, g_APinDescription[_uc_pinMiso].ulPinType); + pinPeripheral(_uc_pinSCK, g_APinDescription[_uc_pinSCK].ulPinType); + pinPeripheral(_uc_pinMosi, g_APinDescription[_uc_pinMosi].ulPinType); + + config(DEFAULT_SPI_SETTINGS); +} + +void SPIClass::init() +{ + if (initialized) + return; + interruptMode = SPI_IMODE_NONE; + interruptSave = 0; + interruptMask = 0; + initialized = true; +} + +void SPIClass::config(SPISettings settings) +{ + _p_sercom->disableSPI(); + + _p_sercom->initSPI(SPI_PAD_2_SCK_3, SERCOM_RX_PAD_0, SPI_CHAR_SIZE_8_BITS, settings.bitOrder); + _p_sercom->initSPIClock(settings.dataMode, settings.clockFreq); + + _p_sercom->enableSPI(); +} + +void SPIClass::end() +{ + _p_sercom->resetSPI(); + initialized = false; +} + +#ifndef interruptsStatus +#define interruptsStatus() __interruptsStatus() +static inline unsigned char __interruptsStatus(void) __attribute__((always_inline, unused)); +static inline unsigned char __interruptsStatus(void) +{ + // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0497a/CHDBIBGJ.html + return (__get_PRIMASK() ? 0 : 1); +} +#endif + +void SPIClass::usingInterrupt(int interruptNumber) +{ + if ((interruptNumber == NOT_AN_INTERRUPT) || (interruptNumber == EXTERNAL_INT_NMI)) + return; + + uint8_t irestore = interruptsStatus(); + noInterrupts(); + + if (interruptNumber >= EXTERNAL_NUM_INTERRUPTS) + interruptMode = SPI_IMODE_GLOBAL; + else + { + interruptMode |= SPI_IMODE_EXTINT; + interruptMask |= (1 << interruptNumber); + } + + if (irestore) + interrupts(); +} + +void SPIClass::beginTransaction(SPISettings settings) +{ + if (interruptMode != SPI_IMODE_NONE) + { + if (interruptMode & SPI_IMODE_GLOBAL) + { + interruptSave = interruptsStatus(); + noInterrupts(); + } + else if (interruptMode & SPI_IMODE_EXTINT) + EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(interruptMask); + } + + config(settings); +} + +void SPIClass::endTransaction(void) +{ + if (interruptMode != SPI_IMODE_NONE) + { + if (interruptMode & SPI_IMODE_GLOBAL) + { + if (interruptSave) + interrupts(); + } + else if (interruptMode & SPI_IMODE_EXTINT) + EIC->INTENSET.reg = EIC_INTENSET_EXTINT(interruptMask); + } +} + +void SPIClass::setBitOrder(BitOrder order) +{ + if (order == LSBFIRST) { + _p_sercom->setDataOrderSPI(LSB_FIRST); + } else { + _p_sercom->setDataOrderSPI(MSB_FIRST); + } +} + +void SPIClass::setDataMode(uint8_t mode) +{ + switch (mode) + { + case SPI_MODE0: + _p_sercom->setClockModeSPI(SERCOM_SPI_MODE_0); + break; + + case SPI_MODE1: + _p_sercom->setClockModeSPI(SERCOM_SPI_MODE_1); + break; + + case SPI_MODE2: + _p_sercom->setClockModeSPI(SERCOM_SPI_MODE_2); + break; + + case SPI_MODE3: + _p_sercom->setClockModeSPI(SERCOM_SPI_MODE_3); + break; + + default: + break; + } +} + +void SPIClass::setClockDivider(uint8_t div) +{ + if (div < SPI_MIN_CLOCK_DIVIDER) { + _p_sercom->setBaudrateSPI(SPI_MIN_CLOCK_DIVIDER); + } else { + _p_sercom->setBaudrateSPI(div); + } +} + +byte SPIClass::transfer(uint8_t data) +{ + // Writing the data + _p_sercom->writeDataSPI(data); + + // Read data + return _p_sercom->readDataSPI() & 0xFF; +} + +void SPIClass::attachInterrupt() { + // Should be enableInterrupt() +} + +void SPIClass::detachInterrupt() { + // Should be disableInterrupt() +} + +SPIClass SPI( &sercom4, PIN_SPI_MISO, PIN_SPI_SCK, PIN_SPI_MOSI ); diff --git a/hardware/MySensors/samd/libraries/SPI/SPI.h b/hardware/MySensors/samd/libraries/SPI/SPI.h new file mode 100644 index 0000000..6259d2d --- /dev/null +++ b/hardware/MySensors/samd/libraries/SPI/SPI.h @@ -0,0 +1,153 @@ +/* + * SPI Master library for Arduino Zero. + * Copyright (c) 2015 Arduino LLC + * + * 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 _SPI_H_INCLUDED +#define _SPI_H_INCLUDED + +#include + +// SPI_HAS_TRANSACTION means SPI has +// - beginTransaction() +// - endTransaction() +// - usingInterrupt() +// - SPISetting(clock, bitOrder, dataMode) +#define SPI_HAS_TRANSACTION 1 + +#define SPI_MODE0 0x02 +#define SPI_MODE1 0x00 +#define SPI_MODE2 0x03 +#define SPI_MODE3 0x01 + +#if defined(__SAMD21G18A__) + // Even if not specified on the datasheet, the SAMD21G18A MCU + // doesn't operate correctly with clock dividers lower than 4. + // This allows a theoretical maximum SPI clock speed of 12Mhz + #define SPI_MIN_CLOCK_DIVIDER 4 + // Other SAMD21xxxxx MCU may be affected as well +#else + #define SPI_MIN_CLOCK_DIVIDER 2 +#endif + +class SPISettings { + public: + SPISettings(uint32_t clock, BitOrder bitOrder, uint8_t dataMode) { + if (__builtin_constant_p(clock)) { + init_AlwaysInline(clock, bitOrder, dataMode); + } else { + init_MightInline(clock, bitOrder, dataMode); + } + } + + // Default speed set to 4MHz, SPI mode set to MODE 0 and Bit order set to MSB first. + SPISettings() { init_AlwaysInline(4000000, MSBFIRST, SPI_MODE0); } + + private: + void init_MightInline(uint32_t clock, BitOrder bitOrder, uint8_t dataMode) { + init_AlwaysInline(clock, bitOrder, dataMode); + } + + void init_AlwaysInline(uint32_t clock, BitOrder bitOrder, uint8_t dataMode) __attribute__((__always_inline__)) { + this->clockFreq = (clock >= (F_CPU / SPI_MIN_CLOCK_DIVIDER) ? F_CPU / SPI_MIN_CLOCK_DIVIDER : clock); + + this->bitOrder = (bitOrder == MSBFIRST ? MSB_FIRST : LSB_FIRST); + + switch (dataMode) + { + case SPI_MODE0: + this->dataMode = SERCOM_SPI_MODE_0; break; + case SPI_MODE1: + this->dataMode = SERCOM_SPI_MODE_1; break; + case SPI_MODE2: + this->dataMode = SERCOM_SPI_MODE_2; break; + case SPI_MODE3: + this->dataMode = SERCOM_SPI_MODE_3; break; + default: + this->dataMode = SERCOM_SPI_MODE_0; break; + } + } + + uint32_t clockFreq; + SercomSpiClockMode dataMode; + SercomDataOrder bitOrder; + + friend class SPIClass; +}; + +class SPIClass { + public: + SPIClass(SERCOM *p_sercom, uint8_t uc_pinMISO, uint8_t uc_pinSCK, uint8_t uc_pinMOSI); + + byte transfer(uint8_t data); + inline void transfer(void *buf, size_t count); + + // Transaction Functions + void usingInterrupt(int interruptNumber); + void beginTransaction(SPISettings settings); + void endTransaction(void); + + // SPI Configuration methods + void attachInterrupt(); + void detachInterrupt(); + + void begin(); + void end(); + + void setBitOrder(BitOrder order); + void setDataMode(uint8_t uc_mode); + void setClockDivider(uint8_t uc_div); + + private: + void init(); + void config(SPISettings settings); + + SERCOM *_p_sercom; + uint8_t _uc_pinMiso; + uint8_t _uc_pinMosi; + uint8_t _uc_pinSCK; + bool initialized; + uint8_t interruptMode; + char interruptSave; + uint32_t interruptMask; +}; + +void SPIClass::transfer(void *buf, size_t count) +{ + // TODO: Optimize for faster block-transfer + uint8_t *buffer = reinterpret_cast(buf); + for (size_t i=0; i 0 + extern SPIClass SPI; +#endif + +// For compatibility with sketches designed for AVR @ 16 MHz +// New programs should use SPI.beginTransaction to set the SPI clock +#if F_CPU == 48000000 + #define SPI_CLOCK_DIV2 6 + #define SPI_CLOCK_DIV4 12 + #define SPI_CLOCK_DIV8 24 + #define SPI_CLOCK_DIV16 48 + #define SPI_CLOCK_DIV32 96 + #define SPI_CLOCK_DIV64 192 + #define SPI_CLOCK_DIV128 255 +#endif + +#endif diff --git a/hardware/MySensors/samd/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino b/hardware/MySensors/samd/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino new file mode 100644 index 0000000..8104fcb --- /dev/null +++ b/hardware/MySensors/samd/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino @@ -0,0 +1,143 @@ +/* + SCP1000 Barometric Pressure Sensor Display + + Shows the output of a Barometric Pressure Sensor on a + Uses the SPI library. For details on the sensor, see: + http://www.sparkfun.com/commerce/product_info.php?products_id=8161 + http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ + + This sketch adapted from Nathan Seidle's SCP1000 example for PIC: + http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip + + Circuit: + SCP1000 sensor attached to pins 6, 7, 10 - 13: + DRDY: pin 6 + CSB: pin 7 + MOSI: pin 11 + MISO: pin 12 + SCK: pin 13 + + created 31 July 2010 + modified 14 August 2010 + by Tom Igoe + */ + +// the sensor communicates using SPI, so include the library: +#include + +//Sensor's memory register addresses: +const int PRESSURE = 0x1F; //3 most significant bits of pressure +const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure +const int TEMPERATURE = 0x21; //16 bit temperature reading +const byte READ = 0b11111100; // SCP1000's read command +const byte WRITE = 0b00000010; // SCP1000's write command + +// pins used for the connection with the sensor +// the other you need are controlled by the SPI library): +const int dataReadyPin = 6; +const int chipSelectPin = 7; + +void setup() { + Serial.begin(9600); + + // start the SPI library: + SPI.begin(); + + // initalize the data ready and chip select pins: + pinMode(dataReadyPin, INPUT); + pinMode(chipSelectPin, OUTPUT); + + //Configure SCP1000 for low noise configuration: + writeRegister(0x02, 0x2D); + writeRegister(0x01, 0x03); + writeRegister(0x03, 0x02); + // give the sensor time to set up: + delay(100); +} + +void loop() { + //Select High Resolution Mode + writeRegister(0x03, 0x0A); + + // don't do anything until the data ready pin is high: + if (digitalRead(dataReadyPin) == HIGH) { + //Read the temperature data + int tempData = readRegister(0x21, 2); + + // convert the temperature to celsius and display it: + float realTemp = (float)tempData / 20.0; + Serial.print("Temp[C]="); + Serial.print(realTemp); + + + //Read the pressure data highest 3 bits: + byte pressure_data_high = readRegister(0x1F, 1); + pressure_data_high &= 0b00000111; //you only needs bits 2 to 0 + + //Read the pressure data lower 16 bits: + unsigned int pressure_data_low = readRegister(0x20, 2); + //combine the two parts into one 19-bit number: + long pressure = ((pressure_data_high << 16) | pressure_data_low) / 4; + + // display the temperature: + Serial.println("\tPressure [Pa]=" + String(pressure)); + } +} + +//Read from or write to register from the SCP1000: +unsigned int readRegister(byte thisRegister, int bytesToRead ) { + byte inByte = 0; // incoming byte from the SPI + unsigned int result = 0; // result to return + Serial.print(thisRegister, BIN); + Serial.print("\t"); + // SCP1000 expects the register name in the upper 6 bits + // of the byte. So shift the bits left by two bits: + thisRegister = thisRegister << 2; + // now combine the address and the command into one byte + byte dataToSend = thisRegister & READ; + Serial.println(thisRegister, BIN); + // take the chip select low to select the device: + digitalWrite(chipSelectPin, LOW); + // send the device the register you want to read: + SPI.transfer(dataToSend); + // send a value of 0 to read the first byte returned: + result = SPI.transfer(0x00); + // decrement the number of bytes left to read: + bytesToRead--; + // if you still have another byte to read: + if (bytesToRead > 0) { + // shift the first byte left, then get the second byte: + result = result << 8; + inByte = SPI.transfer(0x00); + // combine the byte you just got with the previous one: + result = result | inByte; + // decrement the number of bytes left to read: + bytesToRead--; + } + // take the chip select high to de-select: + digitalWrite(chipSelectPin, HIGH); + // return the result: + return(result); +} + + +//Sends a write command to SCP1000 + +void writeRegister(byte thisRegister, byte thisValue) { + + // SCP1000 expects the register address in the upper 6 bits + // of the byte. So shift the bits left by two bits: + thisRegister = thisRegister << 2; + // now combine the register address and the command into one byte: + byte dataToSend = thisRegister | WRITE; + + // take the chip select low to select the device: + digitalWrite(chipSelectPin, LOW); + + SPI.transfer(dataToSend); //Send register location + SPI.transfer(thisValue); //Send value to record into register + + // take the chip select high to de-select: + digitalWrite(chipSelectPin, HIGH); +} + diff --git a/hardware/MySensors/samd/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino b/hardware/MySensors/samd/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino new file mode 100644 index 0000000..b135a74 --- /dev/null +++ b/hardware/MySensors/samd/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino @@ -0,0 +1,71 @@ +/* + Digital Pot Control + + This example controls an Analog Devices AD5206 digital potentiometer. + The AD5206 has 6 potentiometer channels. Each channel's pins are labeled + A - connect this to voltage + W - this is the pot's wiper, which changes when you set it + B - connect this to ground. + + The AD5206 is SPI-compatible,and to command it, you send two bytes, + one with the channel number (0 - 5) and one with the resistance value for the + channel (0 - 255). + + The circuit: + * All A pins of AD5206 connected to +5V + * All B pins of AD5206 connected to ground + * An LED and a 220-ohm resisor in series connected from each W pin to ground + * CS - to digital pin 10 (SS pin) + * SDI - to digital pin 11 (MOSI pin) + * CLK - to digital pin 13 (SCK pin) + + created 10 Aug 2010 + by Tom Igoe + + Thanks to Heather Dewey-Hagborg for the original tutorial, 2005 + +*/ + + +// inslude the SPI library: +#include + + +// set pin 10 as the slave select for the digital pot: +const int slaveSelectPin = 10; + +void setup() { + // set the slaveSelectPin as an output: + pinMode (slaveSelectPin, OUTPUT); + // initialize SPI: + SPI.begin(); +} + +void loop() { + // go through the six channels of the digital pot: + for (int channel = 0; channel < 6; channel++) { + // change the resistance on this channel from min to max: + for (int level = 0; level < 255; level++) { + digitalPotWrite(channel, level); + delay(10); + } + // wait a second at the top: + delay(100); + // change the resistance on this channel from max to min: + for (int level = 0; level < 255; level++) { + digitalPotWrite(channel, 255 - level); + delay(10); + } + } + +} + +void digitalPotWrite(int address, int value) { + // take the SS pin low to select the chip: + digitalWrite(slaveSelectPin, LOW); + // send in the address and value via SPI: + SPI.transfer(address); + SPI.transfer(value); + // take the SS pin high to de-select the chip: + digitalWrite(slaveSelectPin, HIGH); +} diff --git a/hardware/MySensors/samd/libraries/SPI/keywords.txt b/hardware/MySensors/samd/libraries/SPI/keywords.txt new file mode 100644 index 0000000..47738f9 --- /dev/null +++ b/hardware/MySensors/samd/libraries/SPI/keywords.txt @@ -0,0 +1,31 @@ +####################################### +# Syntax Coloring Map SPI +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +SPI KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +begin KEYWORD2 +end KEYWORD2 +transfer KEYWORD2 +#setBitOrder KEYWORD2 +setDataMode KEYWORD2 +setClockDivider KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### +SPI_MODE0 LITERAL1 +SPI_MODE1 LITERAL1 +SPI_MODE2 LITERAL1 +SPI_MODE3 LITERAL1 + +SPI_CONTINUE LITERAL1 +SPI_LAST LITERAL1 diff --git a/hardware/MySensors/samd/libraries/Wire/Wire.cpp b/hardware/MySensors/samd/libraries/Wire/Wire.cpp new file mode 100644 index 0000000..aabc1ef --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/Wire.cpp @@ -0,0 +1,355 @@ +/* + * TWI/I2C library for Arduino Zero + * Copyright (c) 2015 Arduino LLC. All rights reserved. + * + * 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 + */ + +extern "C" { +#include +} + +#include +#include + +#include "Wire.h" + +TwoWire::TwoWire(SERCOM * s) +{ + this->sercom = s; + transmissionBegun = false; +} + +void TwoWire::begin(void) { + //Master Mode + sercom->initMasterWIRE(TWI_CLOCK); + sercom->enableWIRE(); + + pinPeripheral(PIN_WIRE_SDA, g_APinDescription[PIN_WIRE_SDA].ulPinType); + pinPeripheral(PIN_WIRE_SCL, g_APinDescription[PIN_WIRE_SCL].ulPinType); +} + +void TwoWire::begin(uint8_t address) { + //Slave mode + sercom->initSlaveWIRE(address); + sercom->enableWIRE(); +} + +void TwoWire::setClock(uint32_t frequency) { + // dummy funtion +} + +uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit) +{ + if(quantity == 0) + { + return 0; + } + + size_t byteRead = 0; + + if(sercom->startTransmissionWIRE(address, WIRE_READ_FLAG)) + { + // Read first data + rxBuffer.store_char(sercom->readDataWIRE()); + + // Connected to slave + //while(toRead--) + for(byteRead = 0; byteRead < quantity; ++byteRead) + { + if( byteRead == quantity - 1) // Stop transmission + { + sercom->prepareNackBitWIRE(); // Prepare NACK to stop slave transmission + //sercom->readDataWIRE(); // Clear data register to send NACK + sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); // Send Stop + } + else // Continue transmission + { + sercom->prepareAckBitWIRE(); // Prepare Acknowledge + sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_READ); // Prepare the ACK command for the slave + rxBuffer.store_char( sercom->readDataWIRE() ); // Read data and send the ACK + } + } + } + + return byteRead; +} + +uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity) +{ + return requestFrom(address, quantity, true); +} + +void TwoWire::beginTransmission(uint8_t address) { + // save address of target and clear buffer + txAddress = address; + txBuffer.clear(); + + transmissionBegun = true; +} + +// Errors: +// 0 : Success +// 1 : Data too long +// 2 : NACK on transmit of address +// 3 : NACK on transmit of data +// 4 : Other error +uint8_t TwoWire::endTransmission(bool stopBit) +{ + transmissionBegun = false ; + + // Check if there are data to send + if ( txBuffer.available() == 0) + { + return 4 ; + } + + // Start I2C transmission + if ( !sercom->startTransmissionWIRE( txAddress, WIRE_WRITE_FLAG ) ) + { + sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); + return 2 ; // Address error + } + + // Send all buffer + while( txBuffer.available() ) + { + // Trying to send data + if ( !sercom->sendDataMasterWIRE( txBuffer.read_char() ) ) + { + sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); + return 3 ; // Nack or error + } + + if(txBuffer.available() == 0) + { + sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); + } + } + + return 0; +} + +uint8_t TwoWire::endTransmission() +{ + return endTransmission(true); +} + +size_t TwoWire::write(uint8_t ucData) +{ + if(sercom->isMasterWIRE()) + { + // No writing, without begun transmission or a full buffer + if ( !transmissionBegun || txBuffer.isFull() ) + { + return 0 ; + } + + txBuffer.store_char( ucData ) ; + + return 1 ; + } + else + { + if(sercom->sendDataSlaveWIRE( ucData )) + { + return 1; + } + } + + return 0; +} + +size_t TwoWire::write(const uint8_t *data, size_t quantity) +{ + //Try to store all data + for(size_t i = 0; i < quantity; ++i) + { + //Return the number of data stored, when the buffer is full (if write return 0) + if(!write(data[i])) + return i; + } + + //All data stored + return quantity; +} + +int TwoWire::available(void) +{ + return rxBuffer.available(); +} + +int TwoWire::read(void) +{ + return rxBuffer.read_char(); +} + +int TwoWire::peek(void) +{ + return rxBuffer.peek(); +} + +void TwoWire::flush(void) +{ + // Do nothing, use endTransmission(..) to force + // data transfer. +} + +void TwoWire::onReceive(void(*function)(int)) +{ + onReceiveCallback = function; +} + +void TwoWire::onRequest(void(*function)(void)) +{ + onRequestCallback = function; +} + +void TwoWire::onService(void) +{ + if ( sercom->isSlaveWIRE() ) + { + //Received data + if(sercom->isDataReadyWIRE()) + { + //Store data + rxBuffer.store_char(sercom->readDataWIRE()); + + //Stop or Restart detected + if(sercom->isStopDetectedWIRE() || sercom->isRestartDetectedWIRE()) + { + //Calling onReceiveCallback, if exists + if(onReceiveCallback) + { + onReceiveCallback(available()); + } + } + } + + //Address Match + if(sercom->isAddressMatch()) + { + //Is a request ? + if(sercom->isMasterReadOperationWIRE()) + { + //Calling onRequestCallback, if exists + if(onRequestCallback) + { + onRequestCallback(); + } + } + } + } +} + +/* +void TwoWire::onService(void) +{ + // Retrieve interrupt status + uint32_t sr = TWI_GetStatus(twi); + + if (status == SLAVE_IDLE && TWI_STATUS_SVACC(sr)) { + TWI_DisableIt(twi, TWI_IDR_SVACC); + TWI_EnableIt(twi, TWI_IER_RXRDY | TWI_IER_GACC | TWI_IER_NACK + | TWI_IER_EOSACC | TWI_IER_SCL_WS | TWI_IER_TXCOMP); + + srvBufferLength = 0; + srvBufferIndex = 0; + + // Detect if we should go into RECV or SEND status + // SVREAD==1 means *master* reading -> SLAVE_SEND + if (!TWI_STATUS_SVREAD(sr)) { + status = SLAVE_RECV; + } else { + status = SLAVE_SEND; + + // Alert calling program to generate a response ASAP + if (onRequestCallback) + onRequestCallback(); + else + // create a default 1-byte response + write((uint8_t) 0); + } + } + + if (status != SLAVE_IDLE) { + if (TWI_STATUS_TXCOMP(sr) && TWI_STATUS_EOSACC(sr)) { + if (status == SLAVE_RECV && onReceiveCallback) { + // Copy data into rxBuffer + // (allows to receive another packet while the + // user program reads actual data) + for (uint8_t i = 0; i < srvBufferLength; ++i) + rxBuffer[i] = srvBuffer[i]; + rxBufferIndex = 0; + rxBufferLength = srvBufferLength; + + // Alert calling program + onReceiveCallback( rxBufferLength); + } + + // Transfer completed + TWI_EnableIt(twi, TWI_SR_SVACC); + TWI_DisableIt(twi, TWI_IDR_RXRDY | TWI_IDR_GACC | TWI_IDR_NACK + | TWI_IDR_EOSACC | TWI_IDR_SCL_WS | TWI_IER_TXCOMP); + status = SLAVE_IDLE; + } + } + + if (status == SLAVE_RECV) { + if (TWI_STATUS_RXRDY(sr)) { + if (srvBufferLength < BUFFER_LENGTH) + srvBuffer[srvBufferLength++] = TWI_ReadByte(twi); + } + } + + if (status == SLAVE_SEND) { + if (TWI_STATUS_TXRDY(sr) && !TWI_STATUS_NACK(sr)) { + uint8_t c = 'x'; + if (srvBufferIndex < srvBufferLength) + c = srvBuffer[srvBufferIndex++]; + TWI_WriteByte(twi, c); + } + } +} +*/ + +#if WIRE_INTERFACES_COUNT > 0 +/*static void Wire_Init(void) { + pmc_enable_periph_clk(WIRE_INTERFACE_ID); + PIO_Configure( + g_APinDescription[PIN_WIRE_SDA].pPort, + g_APinDescription[PIN_WIRE_SDA].ulPinType, + g_APinDescription[PIN_WIRE_SDA].ulPin, + g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration); + PIO_Configure( + g_APinDescription[PIN_WIRE_SCL].pPort, + g_APinDescription[PIN_WIRE_SCL].ulPinType, + g_APinDescription[PIN_WIRE_SCL].ulPin, + g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration); + + NVIC_DisableIRQ(WIRE_ISR_ID); + NVIC_ClearPendingIRQ(WIRE_ISR_ID); + NVIC_SetPriority(WIRE_ISR_ID, 0); + NVIC_EnableIRQ(WIRE_ISR_ID); +}*/ + + +TwoWire Wire(&sercom3); + +void SERCOM3_Handler(void) { + Wire.onService(); +} + +#endif diff --git a/hardware/MySensors/samd/libraries/Wire/Wire.h b/hardware/MySensors/samd/libraries/Wire/Wire.h new file mode 100644 index 0000000..844168e --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/Wire.h @@ -0,0 +1,104 @@ +/* + * TWI/I2C library for Arduino Zero + * Copyright (c) 2015 Arduino LLC. All rights reserved. + * + * 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 TwoWire_h +#define TwoWire_h + +#include "Stream.h" +#include "variant.h" + +#include "SERCOM.h" +#include "RingBuffer.h" + +#define BUFFER_LENGTH 32 + +class TwoWire : public Stream +{ + public: + TwoWire(SERCOM *s); + void begin(); + void begin(uint8_t); + void setClock(uint32_t); // dummy function + + void beginTransmission(uint8_t); + uint8_t endTransmission(bool stopBit); + uint8_t endTransmission(void); + + uint8_t requestFrom(uint8_t address, size_t quantity, bool stopBit); + uint8_t requestFrom(uint8_t address, size_t quantity); + + size_t write(uint8_t data); + size_t write(const uint8_t * data, size_t quantity); + + virtual int available(void); + virtual int read(void); + virtual int peek(void); + virtual void flush(void); + void onReceive(void(*)(int)); + void onRequest(void(*)(void)); + + using Print::write; + + void onService(void); + + private: + SERCOM * sercom; + bool transmissionBegun; + + // RX Buffer + RingBuffer rxBuffer; + + //TX buffer + RingBuffer txBuffer; + uint8_t txAddress; + + + // Service buffer + //uint8_t srvBuffer[BUFFER_LENGTH]; + //uint8_t srvBufferIndex; + //uint8_t srvBufferLength; + + // Callback user functions + void (*onRequestCallback)(void); + void (*onReceiveCallback)(int); + + // TWI state + //enum TwoWireStatus + //{ + // UNINITIALIZED, + // MASTER_IDLE, + // MASTER_SEND, + // MASTER_RECV, + // SLAVE_IDLE, + // SLAVE_RECV, + // SLAVE_SEND + //}; + //TwoWireStatus status; + + // TWI clock frequency + static const uint32_t TWI_CLOCK = 100000; + + // Timeouts + //static const uint32_t RECV_TIMEOUT = 100000; + //static const uint32_t XMIT_TIMEOUT = 100000; +}; + +extern TwoWire Wire; + +#endif diff --git a/hardware/MySensors/samd/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.pde b/hardware/MySensors/samd/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.pde new file mode 100644 index 0000000..9c41c18 --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.pde @@ -0,0 +1,87 @@ +// I2C SRF10 or SRF08 Devantech Ultrasonic Ranger Finder +// by Nicholas Zambetti +// and James Tichenor + +// Demonstrates use of the Wire library reading data from the +// Devantech Utrasonic Rangers SFR08 and SFR10 + +// Created 29 April 2006 + +// This example code is in the public domain. + + +#include + +void setup() +{ + Wire.begin(); // join i2c bus (address optional for master) + Serial.begin(9600); // start serial communication at 9600bps +} + +int reading = 0; + +void loop() +{ + // step 1: instruct sensor to read echoes + Wire.beginTransmission(112); // transmit to device #112 (0x70) + // the address specified in the datasheet is 224 (0xE0) + // but i2c adressing uses the high 7 bits so it's 112 + Wire.write(byte(0x00)); // sets register pointer to the command register (0x00) + Wire.write(byte(0x50)); // command sensor to measure in "inches" (0x50) + // use 0x51 for centimeters + // use 0x52 for ping microseconds + Wire.endTransmission(); // stop transmitting + + // step 2: wait for readings to happen + delay(70); // datasheet suggests at least 65 milliseconds + + // step 3: instruct sensor to return a particular echo reading + Wire.beginTransmission(112); // transmit to device #112 + Wire.write(byte(0x02)); // sets register pointer to echo #1 register (0x02) + Wire.endTransmission(); // stop transmitting + + // step 4: request reading from sensor + Wire.requestFrom(112, 2); // request 2 bytes from slave device #112 + + // step 5: receive reading from sensor + if(2 <= Wire.available()) // if two bytes were received + { + reading = Wire.read(); // receive high byte (overwrites previous reading) + reading = reading << 8; // shift high byte to be high 8 bits + reading |= Wire.read(); // receive low byte as lower 8 bits + Serial.println(reading); // print the reading + } + + delay(250); // wait a bit since people have to read the output :) +} + + +/* + +// The following code changes the address of a Devantech Ultrasonic Range Finder (SRF10 or SRF08) +// usage: changeAddress(0x70, 0xE6); + +void changeAddress(byte oldAddress, byte newAddress) +{ + Wire.beginTransmission(oldAddress); + Wire.write(byte(0x00)); + Wire.write(byte(0xA0)); + Wire.endTransmission(); + + Wire.beginTransmission(oldAddress); + Wire.write(byte(0x00)); + Wire.write(byte(0xAA)); + Wire.endTransmission(); + + Wire.beginTransmission(oldAddress); + Wire.write(byte(0x00)); + Wire.write(byte(0xA5)); + Wire.endTransmission(); + + Wire.beginTransmission(oldAddress); + Wire.write(byte(0x00)); + Wire.write(newAddress); + Wire.endTransmission(); +} + +*/ diff --git a/hardware/MySensors/samd/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.pde b/hardware/MySensors/samd/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.pde new file mode 100644 index 0000000..38da1c5 --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.pde @@ -0,0 +1,39 @@ +// I2C Digital Potentiometer +// by Nicholas Zambetti +// and Shawn Bonkowski + +// Demonstrates use of the Wire library +// Controls AD5171 digital potentiometer via I2C/TWI + +// Created 31 March 2006 + +// This example code is in the public domain. + +// This example code is in the public domain. + + +#include + +void setup() +{ + Wire.begin(); // join i2c bus (address optional for master) +} + +byte val = 0; + +void loop() +{ + Wire.beginTransmission(44); // transmit to device #44 (0x2c) + // device address is specified in datasheet + Wire.write(byte(0x00)); // sends instruction byte + Wire.write(val); // sends potentiometer value byte + Wire.endTransmission(); // stop transmitting + + val++; // increment value + if(val == 64) // if reached 64th position (max) + { + val = 0; // start over from lowest value + } + delay(500); +} + diff --git a/hardware/MySensors/samd/libraries/Wire/examples/master_reader/master_reader.pde b/hardware/MySensors/samd/libraries/Wire/examples/master_reader/master_reader.pde new file mode 100644 index 0000000..4124d7d --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/examples/master_reader/master_reader.pde @@ -0,0 +1,32 @@ +// Wire Master Reader +// by Nicholas Zambetti + +// Demonstrates use of the Wire library +// Reads data from an I2C/TWI slave device +// Refer to the "Wire Slave Sender" example for use with this + +// Created 29 March 2006 + +// This example code is in the public domain. + + +#include + +void setup() +{ + Wire.begin(); // join i2c bus (address optional for master) + Serial.begin(9600); // start serial for output +} + +void loop() +{ + Wire.requestFrom(2, 6); // request 6 bytes from slave device #2 + + while(Wire.available()) // slave may send less than requested + { + char c = Wire.read(); // receive a byte as character + Serial.print(c); // print the character + } + + delay(500); +} diff --git a/hardware/MySensors/samd/libraries/Wire/examples/master_writer/master_writer.pde b/hardware/MySensors/samd/libraries/Wire/examples/master_writer/master_writer.pde new file mode 100644 index 0000000..ccaa036 --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/examples/master_writer/master_writer.pde @@ -0,0 +1,31 @@ +// Wire Master Writer +// by Nicholas Zambetti + +// Demonstrates use of the Wire library +// Writes data to an I2C/TWI slave device +// Refer to the "Wire Slave Receiver" example for use with this + +// Created 29 March 2006 + +// This example code is in the public domain. + + +#include + +void setup() +{ + Wire.begin(); // join i2c bus (address optional for master) +} + +byte x = 0; + +void loop() +{ + Wire.beginTransmission(4); // transmit to device #4 + Wire.write("x is "); // sends five bytes + Wire.write(x); // sends one byte + Wire.endTransmission(); // stop transmitting + + x++; + delay(500); +} diff --git a/hardware/MySensors/samd/libraries/Wire/examples/slave_receiver/slave_receiver.pde b/hardware/MySensors/samd/libraries/Wire/examples/slave_receiver/slave_receiver.pde new file mode 100644 index 0000000..60dd4bd --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/examples/slave_receiver/slave_receiver.pde @@ -0,0 +1,38 @@ +// Wire Slave Receiver +// by Nicholas Zambetti + +// Demonstrates use of the Wire library +// Receives data as an I2C/TWI slave device +// Refer to the "Wire Master Writer" example for use with this + +// Created 29 March 2006 + +// This example code is in the public domain. + + +#include + +void setup() +{ + Wire.begin(4); // join i2c bus with address #4 + Wire.onReceive(receiveEvent); // register event + Serial.begin(9600); // start serial for output +} + +void loop() +{ + delay(100); +} + +// function that executes whenever data is received from master +// this function is registered as an event, see setup() +void receiveEvent(int howMany) +{ + while(1 < Wire.available()) // loop through all but the last + { + char c = Wire.read(); // receive byte as a character + Serial.print(c); // print the character + } + int x = Wire.read(); // receive byte as an integer + Serial.println(x); // print the integer +} diff --git a/hardware/MySensors/samd/libraries/Wire/examples/slave_sender/slave_sender.pde b/hardware/MySensors/samd/libraries/Wire/examples/slave_sender/slave_sender.pde new file mode 100644 index 0000000..d3b238a --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/examples/slave_sender/slave_sender.pde @@ -0,0 +1,32 @@ +// Wire Slave Sender +// by Nicholas Zambetti + +// Demonstrates use of the Wire library +// Sends data as an I2C/TWI slave device +// Refer to the "Wire Master Reader" example for use with this + +// Created 29 March 2006 + +// This example code is in the public domain. + + +#include + +void setup() +{ + Wire.begin(2); // join i2c bus with address #2 + Wire.onRequest(requestEvent); // register event +} + +void loop() +{ + delay(100); +} + +// function that executes whenever data is requested by master +// this function is registered as an event, see setup() +void requestEvent() +{ + Wire.write("hello "); // respond with message of 6 bytes + // as expected by master +} diff --git a/hardware/MySensors/samd/libraries/Wire/keywords.txt b/hardware/MySensors/samd/libraries/Wire/keywords.txt new file mode 100644 index 0000000..e75e929 --- /dev/null +++ b/hardware/MySensors/samd/libraries/Wire/keywords.txt @@ -0,0 +1,32 @@ +####################################### +# Syntax Coloring Map For Wire +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +beginTransmission KEYWORD2 +endTransmission KEYWORD2 +requestFrom KEYWORD2 +send KEYWORD2 +receive KEYWORD2 +onReceive KEYWORD2 +onRequest KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + +Wire KEYWORD2 +Wire1 KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/hardware/MySensors/samd/platform.txt b/hardware/MySensors/samd/platform.txt new file mode 100644 index 0000000..b493921 --- /dev/null +++ b/hardware/MySensors/samd/platform.txt @@ -0,0 +1,143 @@ +# Copyright (c) 2014-2015 Arduino LLC. All right reserved. +# +# 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 + +# Arduino SAMD Core and platform. +# +# For more info: +# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification + +name=Mysensors SAMD (32-bits ARM Cortex-M0+) Boards +version=1.0.0 + +# Compile variables +# ----------------- + +compiler.warning_flags=-w +compiler.warning_flags.none=-w +compiler.warning_flags.default= +compiler.warning_flags.more=-Wall +compiler.warning_flags.all=-Wall -Wextra + +compiler.path={runtime.tools.arm-none-eabi-gcc.path}/bin/ +compiler.c.cmd=arm-none-eabi-gcc +compiler.c.flags=-mcpu={build.mcu} -mthumb -c -g -Os {compiler.warning_flags} -std=gnu11 -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -MMD +compiler.c.elf.cmd=arm-none-eabi-gcc +compiler.c.elf.flags=-Os -Wl,--gc-sections -save-temps +compiler.S.cmd=arm-none-eabi-gcc +compiler.S.flags=-c -g -x assembler-with-cpp +compiler.cpp.cmd=arm-none-eabi-g++ +compiler.cpp.flags=-mcpu={build.mcu} -mthumb -c -g -Os {compiler.warning_flags} -std=gnu++11 -ffunction-sections -fdata-sections -fno-threadsafe-statics -nostdlib --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -MMD +compiler.ar.cmd=arm-none-eabi-ar +compiler.ar.flags=rcs +compiler.objcopy.cmd=arm-none-eabi-objcopy +compiler.objcopy.eep.flags=-O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 +compiler.elf2hex.flags=-O binary +compiler.elf2hex.cmd=arm-none-eabi-objcopy +compiler.ldflags=-mcpu={build.mcu} -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align +compiler.size.cmd=arm-none-eabi-size +compiler.define=-DARDUINO= + +# this can be overriden in boards.txt +build.extra_flags= + +# These can be overridden in platform.local.txt +compiler.c.extra_flags= +compiler.c.elf.extra_flags= +#compiler.c.elf.extra_flags=-v +compiler.cpp.extra_flags= +compiler.S.extra_flags= +compiler.ar.extra_flags= +compiler.elf2hex.extra_flags= + +compiler.arm.cmsis.path="-I{runtime.tools.CMSIS.path}/CMSIS/Include/" "-I{runtime.tools.CMSIS.path}/Device/ATMEL/" + +# USB Flags +# --------- +build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} -DUSBCON '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' + +# Default usb manufacturer will be replaced at compile time using +# numeric vendor ID if available or by board's specific value. +build.usb_manufacturer="Unknown" + + +# Compile patterns +# ---------------- + +## Compile c files +recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {compiler.arm.cmsis.path} {includes} "{source_file}" -o "{object_file}" + +## Compile c++ files +recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {compiler.arm.cmsis.path} {includes} "{source_file}" -o "{object_file}" + +## Compile S files +recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {compiler.arm.cmsis.path} {includes} "{source_file}" -o "{object_file}" + +## Create archives +recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}" + +## Combine gc-sections, archives, and objects +recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" --specs=nano.specs --specs=nosys.specs {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} -Wl,--start-group -lm "{build.path}/{archive_file}" -Wl,--end-group + +## Create output (bin file) +recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin" + +## Save hex +recipe.output.tmp_file={build.project_name}.bin +recipe.output.save_file={build.project_name}.{build.variant}.bin + +## Compute size +recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf" +recipe.size.regex=\.text\s+([0-9]+).* + + +# Uploader tools +# -------------- + +# +# BOSSA +# +tools.bossac.path={runtime.tools.bossac-1.6-arduino.path} +tools.bossac.cmd=bossac +tools.bossac.cmd.windows=bossac.exe + +tools.bossac.upload.params.verbose=-i -d +tools.bossac.upload.params.quiet= +tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -i -e -w -v "{build.path}/{build.project_name}.bin" -R + +# +# OpenOCD sketch upload +# + +tools.openocd.path={runtime.tools.openocd.path} +tools.openocd.cmd=bin/openocd +tools.openocd.cmd.windows=bin/openocd.exe + +tools.openocd.upload.params.verbose=-d2 +tools.openocd.upload.params.quiet=-d0 +tools.openocd.upload.pattern="{path}/{cmd}" {upload.verbose} -s "{path}/share/openocd/scripts/" -f "{runtime.platform.path}/variants/{build.variant}/{build.openocdscript}" -c "telnet_port disabled; program {{{build.path}/{build.project_name}.bin}} verify reset 0x00002000; shutdown" + +tools.openocd.program.params.verbose=-d2 +tools.openocd.program.params.quiet=-d0 +tools.openocd.program.pattern="{path}/{cmd}" {program.verbose} -s "{path}/share/openocd/scripts/" -f "{runtime.platform.path}/variants/{build.variant}/{build.openocdscript}" -c "telnet_port disabled; program {{{build.path}/{build.project_name}.elf}} verify reset; shutdown" + +tools.openocd.erase.params.verbose=-d3 +tools.openocd.erase.params.quiet=-d0 +tools.openocd.erase.pattern= + +tools.openocd.bootloader.params.verbose=-d2 +tools.openocd.bootloader.params.quiet=-d0 +tools.openocd.bootloader.pattern="{path}/{cmd}" {bootloader.verbose} -s "{path}/share/openocd/scripts/" -f "{runtime.platform.path}/variants/{build.variant}/{build.openocdscript}" -c "telnet_port disabled; init; halt; at91samd bootloader 0; program {{{runtime.platform.path}/bootloaders/{bootloader.file}}} verify reset; shutdown" + diff --git a/hardware/MySensors/samd/variants/mysensors_gw/debug_scripts/variant.gdb b/hardware/MySensors/samd/variants/mysensors_gw/debug_scripts/variant.gdb new file mode 100644 index 0000000..3c37ffd --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/debug_scripts/variant.gdb @@ -0,0 +1,31 @@ +# +# Arduino Zero OpenOCD script. +# +# Copyright (c) 2014-2015 Arduino LLC. All right reserved. +# +# 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 +# + +# Define 'reset' command +define reset + +info reg + +break main + +# End of 'reset' command +end + +target remote | openocd -c "interface cmsis-dap" -c "set CHIPNAME at91samd21g18" -f target/at91samdXX.cfg -c "gdb_port pipe; log_output openocd.log" diff --git a/hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_with_bootloader.ld b/hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_with_bootloader.ld new file mode 100644 index 0000000..4475f95 --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_with_bootloader.ld @@ -0,0 +1,211 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + + 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 +*/ + +/* Linker script to configure memory regions. + * Need modifying for a specific board. + * FLASH.ORIGIN: starting address of flash + * FLASH.LENGTH: length of flash + * RAM.ORIGIN: starting address of RAM bank 0 + * RAM.LENGTH: length of RAM bank 0 + */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000+0x2000, LENGTH = 0x00040000-0x2000 /* First 8KB used by bootloader */ + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000 +} + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be defined in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __end__ + * end + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.isr_vector)) + *(.text*) + + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + + KEEP(*(.eh_frame*)) + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(vtable) + *(.data*) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + . = ALIGN(4); + /* All data end */ + __data_end__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __end__ = .; + PROVIDE(end = .); + *(.heap*) + __HeapLimit = .; + } > RAM + + /* .stack_dummy section doesn't contains any symbols. It is only + * used for linker to calculate size of stack sections, and assign + * values to stack symbols later */ + .stack_dummy (COPY): + { + *(.stack*) + } > RAM + + /* Set stack top to end of RAM, and stack limit move down by + * size of stack_dummy section */ + __StackTop = ORIGIN(RAM) + LENGTH(RAM); + __StackLimit = __StackTop - SIZEOF(.stack_dummy); + PROVIDE(__stack = __StackTop); + + __ram_end__ = ORIGIN(RAM) + LENGTH(RAM) -1 ; + + /* Check if data + heap + stack exceeds RAM limit */ + ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") +} diff --git a/hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_without_bootloader.ld b/hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_without_bootloader.ld new file mode 100644 index 0000000..0162f07 --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/linker_scripts/gcc/flash_without_bootloader.ld @@ -0,0 +1,212 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + + 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 +*/ + +/* Linker script to configure memory regions. + * Need modifying for a specific board. + * FLASH.ORIGIN: starting address of flash + * FLASH.LENGTH: length of flash + * RAM.ORIGIN: starting address of RAM bank 0 + * RAM.LENGTH: length of RAM bank 0 + */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x00040000 + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000 +} + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be defined in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __copy_table_start__ + * __copy_table_end__ + * __zero_table_start__ + * __zero_table_end__ + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __end__ + * end + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + * __ram_end__ + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.isr_vector)) + *(.text*) + + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + + KEEP(*(.eh_frame*)) + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + __exidx_end = .; + + /* To copy multiple ROM to RAM sections, + * uncomment .copy.table section and, + * define __STARTUP_COPY_MULTIPLE in startup_ARMCMx.S */ + /* + .copy.table : + { + . = ALIGN(4); + __copy_table_start__ = .; + LONG (__etext) + LONG (__data_start__) + LONG (__data_end__ - __data_start__) + LONG (__etext2) + LONG (__data2_start__) + LONG (__data2_end__ - __data2_start__) + __copy_table_end__ = .; + } > FLASH + */ + + /* To clear multiple BSS sections, + * uncomment .zero.table section and, + * define __STARTUP_CLEAR_BSS_MULTIPLE in startup_ARMCMx.S */ + /* + .zero.table : + { + . = ALIGN(4); + __zero_table_start__ = .; + LONG (__bss_start__) + LONG (__bss_end__ - __bss_start__) + LONG (__bss2_start__) + LONG (__bss2_end__ - __bss2_start__) + __zero_table_end__ = .; + } > FLASH + */ + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(vtable) + *(.data*) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + . = ALIGN(4); + /* All data end */ + __data_end__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __end__ = .; + PROVIDE(end = .); + *(.heap*) + __HeapLimit = .; + } > RAM + + /* .stack_dummy section doesn't contains any symbols. It is only + * used for linker to calculate size of stack sections, and assign + * values to stack symbols later */ + .stack_dummy (COPY): + { + *(.stack*) + } > RAM + + /* Set stack top to end of RAM, and stack limit move down by + * size of stack_dummy section */ + __StackTop = ORIGIN(RAM) + LENGTH(RAM) ; + __StackLimit = __StackTop - SIZEOF(.stack_dummy); + PROVIDE(__stack = __StackTop); + + __ram_end__ = ORIGIN(RAM) + LENGTH(RAM) -1 ; + + /* Check if data + heap + stack exceeds RAM limit */ + ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") +} diff --git a/hardware/MySensors/samd/variants/mysensors_gw/openocd_scripts/mysensors_gw.cfg b/hardware/MySensors/samd/variants/mysensors_gw/openocd_scripts/mysensors_gw.cfg new file mode 100644 index 0000000..36c65c3 --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/openocd_scripts/mysensors_gw.cfg @@ -0,0 +1,30 @@ +# +# Arduino Zero OpenOCD script. +# +# Copyright (c) 2014-2015 Arduino LLC. All right reserved. +# +# 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 +# + +source [find interface/cmsis-dap.cfg] + +# chip name +set CHIPNAME at91samd21g18 +set ENDIAN little + +# choose a port here +set telnet_port 0 + +source [find target/at91samdXX.cfg] diff --git a/hardware/MySensors/samd/variants/mysensors_gw/pins_arduino.h b/hardware/MySensors/samd/variants/mysensors_gw/pins_arduino.h new file mode 100644 index 0000000..db0e40c --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/pins_arduino.h @@ -0,0 +1,21 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + + 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 +*/ + +// API compatibility +#include "variant.h" + diff --git a/hardware/MySensors/samd/variants/mysensors_gw/variant.cpp b/hardware/MySensors/samd/variants/mysensors_gw/variant.cpp new file mode 100644 index 0000000..84df403 --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/variant.cpp @@ -0,0 +1,221 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + + 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 +*/ +/* + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * + Pin number + ZERO Board pin | PIN | Label/Name | Comments (* is for default peripheral in use) + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | Digital Low | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 0 | 0 -> RX | PA11 | | EIC/EXTINT[11] ADC/AIN[19] PTC/X[3] *SERCOM0/PAD[3] SERCOM2/PAD[3] TCC0/WO[3] TCC1/WO[1] + * | 1 | 1 <- TX | PA10 | | EIC/EXTINT[10] ADC/AIN[18] PTC/X[2] *SERCOM0/PAD[2] TCC0/WO[2] TCC1/WO[0] + * | 2 | 2 | PA14 | | EIC/EXTINT[14] SERCOM2/PAD[2] SERCOM4/PAD[2] TC3/WO[0] TCC0/WO[4] + * | 3 | ~3 | PA09 | | EIC/EXTINT[9] ADC/AIN[17] PTC/X[1] SERCOM0/PAD[1] SERCOM2/PAD[1] *TCC0/WO[1] TCC1/WO[3] + * | 4 | ~4 | PA08 | | EIC/NMI ADC/AIN[16] PTC/X[0] SERCOM0/PAD[0] SERCOM2/PAD[0] *TCC0/WO[0] TCC1/WO[2] + * | 5 | ~5 | PA15 | | EIC/EXTINT[15] SERCOM2/PAD[3] SERCOM4/PAD[3] *TC3/WO[1] TCC0/WO[5] + * | 6 | ~6 | PA20 | | EIC/EXTINT[4] PTC/X[8] SERCOM5/PAD[2] SERCOM3/PAD[2] *TCC0/WO[6] + * | 7 | 7 | PA21 | | EIC/EXTINT[5] PTC/X[9] SERCOM5/PAD[3] SERCOM3/PAD[3] TCC0/WO[7] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | Digital High | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 8 | ~8 | PA06 | | EIC/EXTINT[6] ADC/AIN[6] AC/AIN[2] PTC/Y[4] SERCOM0/PAD[2] *TCC1/WO[0] + * | 9 | ~9 | PA07 | | EIC/EXTINT[7] ADC/AIN[7] AC/AIN[3] PTC/Y[5] SERCOM0/PAD[3] *TCC1/WO[1] + * | 10 | ~10 | PA18 | | EIC/EXTINT[2] PTC/X[6] +SERCOM1/PAD[2] SERCOM3/PAD[2] *TC3/WO[0] TCC0/WO[2] + * | 11 | ~11 | PA16 | | EIC/EXTINT[0] PTC/X[4] +SERCOM1/PAD[0] SERCOM3/PAD[0] *TCC2/WO[0] TCC0/WO[6] + * | 12 | ~12 | PA19 | | EIC/EXTINT[3] PTC/X[7] +SERCOM1/PAD[3] SERCOM3/PAD[3] TC3/WO[1] *TCC0/WO[3] + * | 13 | ~13 | PA17 | LED | EIC/EXTINT[1] PTC/X[5] +SERCOM1/PAD[1] SERCOM3/PAD[1] *TCC2/WO[1] TCC0/WO[7] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | Analog Connector | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 14 | A0 | PA02 | A0 | EIC/EXTINT[2] *ADC/AIN[0] DAC/VOUT PTC/Y[0] + * | 15 | A1 | PB08 | A1 | EIC/EXTINT[8] *ADC/AIN[2] PTC/Y[14] SERCOM4/PAD[0] TC4/WO[0] + * | 16 | A2 | PB09 | A2 | EIC/EXTINT[9] *ADC/AIN[3] PTC/Y[15] SERCOM4/PAD[1] TC4/WO[1] + * | 17 | A3 | PA04 | A3 | EIC/EXTINT[4] *ADC/AIN[4] AC/AIN[0] PTC/Y[2] SERCOM0/PAD[0] TCC0/WO[0] + * | 18 | A4 | PA05 | A4 | EIC/EXTINT[5] *ADC/AIN[5] AC/AIN[1] PTC/Y[5] SERCOM0/PAD[1] TCC0/WO[1] + * | 19 | A5 | PB02 | A5 | EIC/EXTINT[2] *ADC/AIN[10] PTC/Y[8] SERCOM5/PAD[0] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | Wire | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 20 | SDA | PA22 | SDA | EIC/EXTINT[6] PTC/X[10] *SERCOM3/PAD[0] SERCOM5/PAD[0] TC4/WO[0] TCC0/WO[4] + * | 21 | SCL | PA23 | SCL | EIC/EXTINT[7] PTC/X[11] *SERCOM3/PAD[1] SERCOM5/PAD[1] TC4/WO[1] TCC0/WO[5] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | |SPI (Legacy ICSP) | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 22 | 1 | PA12 | MISO | EIC/EXTINT[12] SERCOM2/PAD[0] *SERCOM4/PAD[0] TCC2/WO[0] TCC0/WO[6] + * | | 2 | | 5V0 | + * | 23 | 4 | PB10 | MOSI | EIC/EXTINT[10] *SERCOM4/PAD[2] TC5/WO[0] TCC0/WO[4] + * | 24 | 3 | PB11 | SCK | EIC/EXTINT[11] *SERCOM4/PAD[3] TC5/WO[1] TCC0/WO[5] + * | | 5 | | RESET | + * | | 6 | | GND | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | LEDs | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 25 | | PB03 | RX | + * | 26 | | PA27 | TX | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | USB | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 27 | | PA28 | USB_HOST_ENABLE | EIC/EXTINT[8] + * | 28 | | PA24 | USB_NEGATIVE | *USB/DM + * | 29 | | PA25 | USB_POSITIVE | *USB/DP + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | EDBG | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 30 | | PB22 | EDBG_UART TX | *SERCOM5/PAD[2] + * | 31 | | PB23 | EDBG_UART RX | *SERCOM5/PAD[3] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 32 | | PA22 | EDBG_SDA | Pin 20 (SDA) + * | 33 | | PA23 | EDBG_SCL | Pin 21 (SCL) + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 34 | | PA19 | EDBG_MISO | EIC/EXTINT[3] *SERCOM1/PAD[3] SERCOM3/PAD[3] TC3/WO[1] TCC0/WO[3] + * | 35 | | PA16 | EDBG_MOSI | EIC/EXTINT[0] *SERCOM1/PAD[0] SERCOM3/PAD[0] TCC2/WO[0] TCC0/WO[6] + * | 36 | | PA18 | EDBG_SS | EIC/EXTINT[2] *SERCOM1/PAD[2] SERCOM3/PAD[2] TC3/WO[0] TCC0/WO[2] + * | 37 | | PA17 | EDBG_SCK | EIC/EXTINT[1] *SERCOM1/PAD[1] SERCOM3/PAD[1] TCC2/WO[1] TCC0/WO[7] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | 38 | ATN | PA13 | EDBG_GPIO0 | EIC/EXTINT[13] SERCOM2/PAD[1] SERCOM4/PAD[1] *TCC2/WO[1] TCC0/WO[7] + * | 39 | | PA21 | EDBG_GPIO1 | Pin 7 + * | 40 | | PA06 | EDBG_GPIO2 | Pin 8 + * | 41 | | PA07 | EDBG_GPIO3 | Pin 9 + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | GND | | | + * | 42 | AREF | PA03 | | EIC/EXTINT[3] *[ADC|DAC]/VREFA ADC/AIN[1] PTC/Y[1] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | |32.768KHz Crystal | | | + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + * | | | PA00 | XIN32 | EIC/EXTINT[0] SERCOM1/PAD[0] TCC2/WO[0] + * | | | PA01 | XOUT32 | EIC/EXTINT[1] SERCOM1/PAD[1] TCC2/WO[1] + * +------------+------------------+--------+-----------------+-------------------------------------------------------------------------------------------------------- + */ + + +#include "variant.h" + +/* + * Pins descriptions + */ +const PinDescription g_APinDescription[]= +{ + // 0..13 - Digital pins + // ---------------------- + // 0/1 - SERCOM/UART (Serial1) + { PORTA, 11, PIO_SERCOM, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_11 }, // RX: SERCOM0/PAD[3] + { PORTA, 10, PIO_SERCOM, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_10 }, // TX: SERCOM0/PAD[2] + + // 2..12 + // Digital Low + { PORTA, 14, PIO_DIGITAL, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_14 }, + { PORTA, 9, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM0_CH1, TCC0_CH1, EXTERNAL_INT_9 }, // TCC0/WO[1] + { PORTA, 8, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM0_CH0, TCC0_CH0, EXTERNAL_INT_NMI }, // TCC0/WO[0] + { PORTA, 15, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM3_CH1, TC3_CH1, EXTERNAL_INT_15 }, // TC3/WO[1] + { PORTA, 20, PIO_TIMER_ALT, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM0_CH6, TCC0_CH6, EXTERNAL_INT_4 }, // TCC0/WO[6] + { PORTA, 21, PIO_DIGITAL, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_5 }, + + // Digital High + { PORTA, 6, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM1_CH0, TCC1_CH0, EXTERNAL_INT_4 }, // TCC1/WO[0] + { PORTA, 7, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM1_CH1, TCC1_CH1, EXTERNAL_INT_5 }, // TCC1/WO[1] + { PORTA, 18, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM3_CH0, TC3_CH0, EXTERNAL_INT_2 }, // TC3/WO[0] + { PORTA, 16, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM2_CH0, TCC2_CH0, EXTERNAL_INT_0 }, // TCC2/WO[0] + { PORTA, 19, PIO_TIMER_ALT, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM0_CH3, TCC0_CH3, EXTERNAL_INT_3 }, // TCC0/WO[3] + + // 13 (LED) + { PORTA, 17, PIO_PWM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM2_CH1, NOT_ON_TIMER, EXTERNAL_INT_1 }, // TCC2/WO[1] + + // 14..19 - Analog pins + // -------------------- + { PORTA, 2, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // ADC/AIN[0] + { PORTB, 8, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel2, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_8 }, // ADC/AIN[2] + { PORTB, 9, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel3, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_9 }, // ADC/AIN[3] + { PORTA, 4, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel4, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_4 }, // ADC/AIN[4] + { PORTA, 5, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel5, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_5 }, // ADC/AIN[5] + { PORTB, 2, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel10, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // ADC/AIN[10] + + // 20..21 I2C pins (SDA/SCL and also EDBG:SDA/SCL) + // ---------------------- + { PORTA, 22, PIO_SERCOM, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_6 }, // SDA: SERCOM3/PAD[0] + { PORTA, 23, PIO_SERCOM, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_7 }, // SCL: SERCOM3/PAD[1] + + // 22..24 - SPI pins (ICSP:MISO,SCK,MOSI) + // ---------------------- + { PORTA, 12, PIO_SERCOM_ALT, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_12 }, // MISO: SERCOM4/PAD[0] + { PORTB, 10, PIO_SERCOM_ALT, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_10 }, // MOSI: SERCOM4/PAD[2] + { PORTB, 11, PIO_SERCOM_ALT, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_11 }, // SCK: SERCOM4/PAD[3] + + // 25..26 - RX/TX LEDS (PB03/PA27) + // -------------------- + { PORTB, 3, PIO_OUTPUT, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // used as output only + { PORTA, 27, PIO_OUTPUT, PIN_ATTR_DIGITAL, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // used as output only + + // 27..29 - USB + // -------------------- + { PORTA, 28, PIO_COM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // USB Host enable + { PORTA, 24, PIO_COM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // USB/DM + { PORTA, 25, PIO_COM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // USB/DP + + // 30..41 - EDBG + // ---------------------- + // 30/31 - EDBG/UART + { PORTB, 22, PIO_SERCOM_ALT, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // TX: SERCOM5/PAD[2] + { PORTB, 23, PIO_SERCOM_ALT, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // RX: SERCOM5/PAD[3] + + // 32/33 I2C (SDA/SCL and also EDBG:SDA/SCL) + { PORTA, 22, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SDA: SERCOM3/PAD[0] + { PORTA, 23, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SCL: SERCOM3/PAD[1] + + // 34..37 - EDBG/SPI + { PORTA, 19, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MISO: SERCOM1/PAD[3] + { PORTA, 16, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MOSI: SERCOM1/PAD[0] + { PORTA, 18, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SS: SERCOM1/PAD[2] + { PORTA, 17, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SCK: SERCOM1/PAD[1] + + // 38..41 - EDBG/Digital + { PORTA, 13, PIO_PWM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM0_CH5, NOT_ON_TIMER, EXTERNAL_INT_13 }, // EIC/EXTINT[13] *TCC2/WO[1] TCC0/WO[7] + { PORTA, 21, PIO_PWM_ALT, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM0_CH7, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // Pin 7 + { PORTA, 6, PIO_PWM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM1_CH0, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // Pin 8 + { PORTA, 7, PIO_PWM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM), No_ADC_Channel, PWM1_CH1, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // Pin 9 + + // 42 (AREF) + { PORTA, 3, PIO_ANALOG, PIN_ATTR_ANALOG, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // DAC/VREFP + + // ---------------------- + // 43 - Alternate use of A0 (DAC output) + { PORTA, 2, PIO_ANALOG, PIN_ATTR_ANALOG, DAC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // DAC/VOUT +} ; + +const void* g_apTCInstances[TCC_INST_NUM+TC_INST_NUM]={ TCC0, TCC1, TCC2, TC3, TC4, TC5 } ; + +// Multi-serial objects instantiation +SERCOM sercom0( SERCOM0 ) ; +SERCOM sercom1( SERCOM1 ) ; +SERCOM sercom2( SERCOM2 ) ; +SERCOM sercom3( SERCOM3 ) ; +SERCOM sercom4( SERCOM4 ) ; +SERCOM sercom5( SERCOM5 ) ; + +Uart Serial1( &sercom0, PIN_SERIAL1_RX, PIN_SERIAL1_TX, PAD_SERIAL1_RX, PAD_SERIAL1_TX ) ; +Uart Serial( &sercom5, PIN_SERIAL_RX, PIN_SERIAL_TX, PAD_SERIAL_RX, PAD_SERIAL_TX ) ; +void SERCOM0_Handler() +{ + Serial1.IrqHandler(); +} + +void SERCOM5_Handler() +{ + Serial.IrqHandler(); +} + diff --git a/hardware/MySensors/samd/variants/mysensors_gw/variant.h b/hardware/MySensors/samd/variants/mysensors_gw/variant.h new file mode 100644 index 0000000..a1f1506 --- /dev/null +++ b/hardware/MySensors/samd/variants/mysensors_gw/variant.h @@ -0,0 +1,201 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + + 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 _VARIANT_ARDUINO_ZERO_ +#define _VARIANT_ARDUINO_ZERO_ + +/*---------------------------------------------------------------------------- + * Definitions + *----------------------------------------------------------------------------*/ + +/** Frequency of the board main oscillator */ +#define VARIANT_MAINOSC (32768ul) + +/** Master clock frequency */ +#define VARIANT_MCK (48000000ul) + +/*---------------------------------------------------------------------------- + * Headers + *----------------------------------------------------------------------------*/ + +#include "WVariant.h" + +#ifdef __cplusplus +#include "SERCOM.h" +#include "Uart.h" +#endif // __cplusplus + +#ifdef __cplusplus +extern "C" +{ +#endif // __cplusplus + +/*---------------------------------------------------------------------------- + * Pins + *----------------------------------------------------------------------------*/ + +// Number of pins defined in PinDescription array +#define PINS_COUNT (26u) +#define NUM_DIGITAL_PINS (14u) +#define NUM_ANALOG_INPUTS (6u) +#define NUM_ANALOG_OUTPUTS (1u) + +#define digitalPinToPort(P) ( &(PORT->Group[g_APinDescription[P].ulPort]) ) +#define digitalPinToBitMask(P) ( 1 << g_APinDescription[P].ulPin ) +//#define analogInPinToBit(P) ( ) +#define portOutputRegister(port) ( &(port->OUT.reg) ) +#define portInputRegister(port) ( &(port->IN.reg) ) +#define portModeRegister(port) ( &(port->DIR.reg) ) +#define digitalPinHasPWM(P) ( g_APinDescription[P].ulPWMChannel != NOT_ON_PWM || g_APinDescription[P].ulTCChannel != NOT_ON_TIMER ) + +/* + * digitalPinToTimer(..) is AVR-specific and is not defined for SAMD + * architecture. If you need to check if a pin supports PWM you must + * use digitalPinHasPWM(..). + * + * https://github.com/arduino/Arduino/issues/1833 + */ +// #define digitalPinToTimer(P) + +// Interrupts +#define digitalPinToInterrupt(P) ( g_APinDescription[P].ulExtInt ) + +// LEDs +#define PIN_LED_13 (13u) +#define PIN_LED_RXL (25u) +#define PIN_LED_TXL (26u) +#define PIN_LED PIN_LED_13 +#define PIN_LED2 PIN_LED_RXL +#define PIN_LED3 PIN_LED_TXL +#define LED_BUILTIN PIN_LED_13 + +/* + * Analog pins + */ +#define PIN_A0 (14ul) +#define PIN_A1 (15ul) +#define PIN_A2 (16ul) +#define PIN_A3 (17ul) +#define PIN_A4 (18ul) +#define PIN_A5 (19ul) + +static const uint8_t A0 = PIN_A0 ; +static const uint8_t A1 = PIN_A1 ; +static const uint8_t A2 = PIN_A2 ; +static const uint8_t A3 = PIN_A3 ; +static const uint8_t A4 = PIN_A4 ; +static const uint8_t A5 = PIN_A5 ; +#define ADC_RESOLUTION 12 + +// Other pins +#define PIN_ATN (38ul) +static const uint8_t ATN = PIN_ATN; + +/* + * Serial interfaces + */ +// Serial (EDBG) +#define PIN_SERIAL_RX (31ul) +#define PIN_SERIAL_TX (30ul) +#define PAD_SERIAL_TX (UART_TX_PAD_2) +#define PAD_SERIAL_RX (SERCOM_RX_PAD_3) + +// Serial1 +#define PIN_SERIAL1_RX (0ul) +#define PIN_SERIAL1_TX (1ul) +#define PAD_SERIAL1_TX (UART_TX_PAD_2) +#define PAD_SERIAL1_RX (SERCOM_RX_PAD_3) + +/* + * SPI Interfaces + */ +#define SPI_INTERFACES_COUNT 1 + +#define PIN_SPI_MISO (22u) +#define PIN_SPI_MOSI (23u) +#define PIN_SPI_SCK (24u) + +static const uint8_t SS = PIN_A2 ; // SERCOM4 last PAD is present on A2 but HW SS isn't used. Set here only for reference. +static const uint8_t MOSI = PIN_SPI_MOSI ; +static const uint8_t MISO = PIN_SPI_MISO ; +static const uint8_t SCK = PIN_SPI_SCK ; + +/* + * Wire Interfaces + */ +#define WIRE_INTERFACES_COUNT 1 + +#define PIN_WIRE_SDA (20u) +#define PIN_WIRE_SCL (21u) + +/* + * USB + */ +#define PIN_USB_HOST_ENABLE (27ul) +#define PIN_USB_DM (28ul) +#define PIN_USB_DP (29ul) + +#ifdef __cplusplus +} +#endif + +/*---------------------------------------------------------------------------- + * Arduino objects - C++ only + *----------------------------------------------------------------------------*/ + +#ifdef __cplusplus + +/* ========================= + * ===== SERCOM DEFINITION + * ========================= +*/ +extern SERCOM sercom0; +extern SERCOM sercom1; +extern SERCOM sercom2; +extern SERCOM sercom3; +extern SERCOM sercom4; +extern SERCOM sercom5; + +extern Uart Serial; +extern Uart Serial1; + +#endif + +// These serial port names are intended to allow libraries and architecture-neutral +// sketches to automatically default to the correct port name for a particular type +// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, +// the first hardware serial port whose RX/TX pins are not dedicated to another use. +// +// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor +// +// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial +// +// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library +// +// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. +// +// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX +// pins are NOT connected to anything by default. +#define SERIAL_PORT_USBVIRTUAL SerialUSB +#define SERIAL_PORT_MONITOR Serial +// Serial has no physical pins broken out, so it's not listed as HARDWARE port +#define SERIAL_PORT_HARDWARE Serial1 +#define SERIAL_PORT_HARDWARE_OPEN Serial1 + +#endif /* _VARIANT_ARDUINO_ZERO_ */ + From 1652d4b8209c9dd5f7ddfaccde3b887de586bbc1 Mon Sep 17 00:00:00 2001 From: Henrik Ekblad Date: Wed, 5 Aug 2015 09:26:48 +0200 Subject: [PATCH 79/79] Make sure RF69_IRQ_PIN and RF69_IRQ_NUM always is defined Without this compile breaks on Mega 2560. --- libraries/MySensors/MyConfig.h | 2 -- libraries/MySensors/utility/RFM69.h | 10 ++++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/libraries/MySensors/MyConfig.h b/libraries/MySensors/MyConfig.h index 88db782..a339c52 100644 --- a/libraries/MySensors/MyConfig.h +++ b/libraries/MySensors/MyConfig.h @@ -144,6 +144,4 @@ #define RFM69_ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes! - - #endif diff --git a/libraries/MySensors/utility/RFM69.h b/libraries/MySensors/utility/RFM69.h index 23eb044..452a2ae 100644 --- a/libraries/MySensors/utility/RFM69.h +++ b/libraries/MySensors/utility/RFM69.h @@ -36,13 +36,19 @@ #define RF69_MAX_DATA_LEN 61 // to take advantage of the built in AES/CRC we want to limit the frame size to the internal FIFO size (66 bytes - 3 bytes overhead) #define RF69_SPI_CS SS // SS is the SPI slave select pin, for instance D10 on atmega328 -// INT0 on AVRs should be connected to RFM69's DIO0 (ex on Atmega328 it's D2, on Atmega644/1284 it's D2) -#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) || defined(__AVR_ATmega32U4__) +// INT0 on AVRs should be connected to RFM69's DIO0 (ex on ATmega328 it's D2, on ATmega644/1284 it's D2) +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__) #define RF69_IRQ_PIN 2 #define RF69_IRQ_NUM 0 #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__) #define RF69_IRQ_PIN 2 #define RF69_IRQ_NUM 2 +#elif defined(__AVR_ATmega32U4__) + #define RF69_IRQ_PIN 3 + #define RF69_IRQ_NUM 0 +#else + #define RF69_IRQ_PIN 2 + #define RF69_IRQ_NUM 0 #endif #define CSMA_LIMIT -90 // upper RX signal sensitivity threshold in dBm for carrier sense access