Move master branch from from mios git repo

This commit is contained in:
hek
2014-01-23 00:23:15 +01:00
commit 609d9e5be9
352 changed files with 53418 additions and 0 deletions
@@ -0,0 +1,291 @@
/***************************************************
This is a library for the BMP085 Barometric Pressure & Temp Sensor
Designed specifically to work with the Adafruit BMP085 Breakout
----> https://www.adafruit.com/products/391
These displays use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_BMP085.h"
#include <util/delay.h>
Adafruit_BMP085::Adafruit_BMP085() {
}
boolean Adafruit_BMP085::begin(uint8_t mode) {
if (mode > BMP085_ULTRAHIGHRES)
mode = BMP085_ULTRAHIGHRES;
oversampling = mode;
Wire.begin();
if (read8(0xD0) != 0x55) return false;
/* read calibration data */
ac1 = read16(BMP085_CAL_AC1);
ac2 = read16(BMP085_CAL_AC2);
ac3 = read16(BMP085_CAL_AC3);
ac4 = read16(BMP085_CAL_AC4);
ac5 = read16(BMP085_CAL_AC5);
ac6 = read16(BMP085_CAL_AC6);
b1 = read16(BMP085_CAL_B1);
b2 = read16(BMP085_CAL_B2);
mb = read16(BMP085_CAL_MB);
mc = read16(BMP085_CAL_MC);
md = read16(BMP085_CAL_MD);
#if (BMP085_DEBUG == 1)
Serial.print("ac1 = "); Serial.println(ac1, DEC);
Serial.print("ac2 = "); Serial.println(ac2, DEC);
Serial.print("ac3 = "); Serial.println(ac3, DEC);
Serial.print("ac4 = "); Serial.println(ac4, DEC);
Serial.print("ac5 = "); Serial.println(ac5, DEC);
Serial.print("ac6 = "); Serial.println(ac6, DEC);
Serial.print("b1 = "); Serial.println(b1, DEC);
Serial.print("b2 = "); Serial.println(b2, DEC);
Serial.print("mb = "); Serial.println(mb, DEC);
Serial.print("mc = "); Serial.println(mc, DEC);
Serial.print("md = "); Serial.println(md, DEC);
#endif
}
uint16_t Adafruit_BMP085::readRawTemperature(void) {
write8(BMP085_CONTROL, BMP085_READTEMPCMD);
_delay_ms(5);
#if BMP085_DEBUG == 1
Serial.print("Raw temp: "); Serial.println(read16(BMP085_TEMPDATA));
#endif
return read16(BMP085_TEMPDATA);
}
uint32_t Adafruit_BMP085::readRawPressure(void) {
uint32_t raw;
write8(BMP085_CONTROL, BMP085_READPRESSURECMD + (oversampling << 6));
if (oversampling == BMP085_ULTRALOWPOWER)
_delay_ms(5);
else if (oversampling == BMP085_STANDARD)
_delay_ms(8);
else if (oversampling == BMP085_HIGHRES)
_delay_ms(14);
else
_delay_ms(26);
raw = read16(BMP085_PRESSUREDATA);
raw <<= 8;
raw |= read8(BMP085_PRESSUREDATA+2);
raw >>= (8 - oversampling);
/* this pull broke stuff, look at it later?
if (oversampling==0) {
raw <<= 8;
raw |= read8(BMP085_PRESSUREDATA+2);
raw >>= (8 - oversampling);
}
*/
#if BMP085_DEBUG == 1
Serial.print("Raw pressure: "); Serial.println(raw);
#endif
return raw;
}
int32_t Adafruit_BMP085::readPressure(void) {
int32_t UT, UP, B3, B5, B6, X1, X2, X3, p;
uint32_t B4, B7;
UT = readRawTemperature();
UP = readRawPressure();
#if BMP085_DEBUG == 1
// use datasheet numbers!
UT = 27898;
UP = 23843;
ac6 = 23153;
ac5 = 32757;
mc = -8711;
md = 2868;
b1 = 6190;
b2 = 4;
ac3 = -14383;
ac2 = -72;
ac1 = 408;
ac4 = 32741;
oversampling = 0;
#endif
// do temperature calculations
X1=(UT-(int32_t)(ac6))*((int32_t)(ac5))/pow(2,15);
X2=((int32_t)mc*pow(2,11))/(X1+(int32_t)md);
B5=X1 + X2;
#if BMP085_DEBUG == 1
Serial.print("X1 = "); Serial.println(X1);
Serial.print("X2 = "); Serial.println(X2);
Serial.print("B5 = "); Serial.println(B5);
#endif
// do pressure calcs
B6 = B5 - 4000;
X1 = ((int32_t)b2 * ( (B6 * B6)>>12 )) >> 11;
X2 = ((int32_t)ac2 * B6) >> 11;
X3 = X1 + X2;
B3 = ((((int32_t)ac1*4 + X3) << oversampling) + 2) / 4;
#if BMP085_DEBUG == 1
Serial.print("B6 = "); Serial.println(B6);
Serial.print("X1 = "); Serial.println(X1);
Serial.print("X2 = "); Serial.println(X2);
Serial.print("B3 = "); Serial.println(B3);
#endif
X1 = ((int32_t)ac3 * B6) >> 13;
X2 = ((int32_t)b1 * ((B6 * B6) >> 12)) >> 16;
X3 = ((X1 + X2) + 2) >> 2;
B4 = ((uint32_t)ac4 * (uint32_t)(X3 + 32768)) >> 15;
B7 = ((uint32_t)UP - B3) * (uint32_t)( 50000UL >> oversampling );
#if BMP085_DEBUG == 1
Serial.print("X1 = "); Serial.println(X1);
Serial.print("X2 = "); Serial.println(X2);
Serial.print("B4 = "); Serial.println(B4);
Serial.print("B7 = "); Serial.println(B7);
#endif
if (B7 < 0x80000000) {
p = (B7 * 2) / B4;
} else {
p = (B7 / B4) * 2;
}
X1 = (p >> 8) * (p >> 8);
X1 = (X1 * 3038) >> 16;
X2 = (-7357 * p) >> 16;
#if BMP085_DEBUG == 1
Serial.print("p = "); Serial.println(p);
Serial.print("X1 = "); Serial.println(X1);
Serial.print("X2 = "); Serial.println(X2);
#endif
p = p + ((X1 + X2 + (int32_t)3791)>>4);
#if BMP085_DEBUG == 1
Serial.print("p = "); Serial.println(p);
#endif
return p;
}
float Adafruit_BMP085::readTemperature(void) {
int32_t UT, X1, X2, B5; // following ds convention
float temp;
UT = readRawTemperature();
#if BMP085_DEBUG == 1
// use datasheet numbers!
UT = 27898;
ac6 = 23153;
ac5 = 32757;
mc = -8711;
md = 2868;
#endif
// step 1
X1 = (UT - (int32_t)ac6) * ((int32_t)ac5) / pow(2,15);
X2 = ((int32_t)mc * pow(2,11)) / (X1+(int32_t)md);
B5 = X1 + X2;
temp = (B5+8)/pow(2,4);
temp /= 10;
return temp;
}
float Adafruit_BMP085::readAltitude(float sealevelPressure) {
float altitude;
float pressure = readPressure();
altitude = 44330 * (1.0 - pow(pressure /sealevelPressure,0.1903));
return altitude;
}
/*********************************************************************/
uint8_t Adafruit_BMP085::read8(uint8_t a) {
uint8_t ret;
Wire.beginTransmission(BMP085_I2CADDR); // start transmission to device
#if (ARDUINO >= 100)
Wire.write(a); // sends register address to read from
#else
Wire.send(a); // sends register address to read from
#endif
Wire.endTransmission(); // end transmission
Wire.beginTransmission(BMP085_I2CADDR); // start transmission to device
Wire.requestFrom(BMP085_I2CADDR, 1);// send data n-bytes read
#if (ARDUINO >= 100)
ret = Wire.read(); // receive DATA
#else
ret = Wire.receive(); // receive DATA
#endif
Wire.endTransmission(); // end transmission
return ret;
}
uint16_t Adafruit_BMP085::read16(uint8_t a) {
uint16_t ret;
Wire.beginTransmission(BMP085_I2CADDR); // start transmission to device
#if (ARDUINO >= 100)
Wire.write(a); // sends register address to read from
#else
Wire.send(a); // sends register address to read from
#endif
Wire.endTransmission(); // end transmission
Wire.beginTransmission(BMP085_I2CADDR); // start transmission to device
Wire.requestFrom(BMP085_I2CADDR, 2);// send data n-bytes read
#if (ARDUINO >= 100)
ret = Wire.read(); // receive DATA
ret <<= 8;
ret |= Wire.read(); // receive DATA
#else
ret = Wire.receive(); // receive DATA
ret <<= 8;
ret |= Wire.receive(); // receive DATA
#endif
Wire.endTransmission(); // end transmission
return ret;
}
void Adafruit_BMP085::write8(uint8_t a, uint8_t d) {
Wire.beginTransmission(BMP085_I2CADDR); // start transmission to device
#if (ARDUINO >= 100)
Wire.write(a); // sends register address to read from
Wire.write(d); // write data
#else
Wire.send(a); // sends register address to read from
Wire.send(d); // write data
#endif
Wire.endTransmission(); // end transmission
}
@@ -0,0 +1,71 @@
/***************************************************
This is a library for the BMP085 Barometric Pressure & Temp Sensor
Designed specifically to work with the Adafruit BMP085 Breakout
----> https://www.adafruit.com/products/391
These displays use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Wire.h"
#define BMP085_DEBUG 0
#define BMP085_I2CADDR 0x77
#define BMP085_ULTRALOWPOWER 0
#define BMP085_STANDARD 1
#define BMP085_HIGHRES 2
#define BMP085_ULTRAHIGHRES 3
#define BMP085_CAL_AC1 0xAA // R Calibration data (16 bits)
#define BMP085_CAL_AC2 0xAC // R Calibration data (16 bits)
#define BMP085_CAL_AC3 0xAE // R Calibration data (16 bits)
#define BMP085_CAL_AC4 0xB0 // R Calibration data (16 bits)
#define BMP085_CAL_AC5 0xB2 // R Calibration data (16 bits)
#define BMP085_CAL_AC6 0xB4 // R Calibration data (16 bits)
#define BMP085_CAL_B1 0xB6 // R Calibration data (16 bits)
#define BMP085_CAL_B2 0xB8 // R Calibration data (16 bits)
#define BMP085_CAL_MB 0xBA // R Calibration data (16 bits)
#define BMP085_CAL_MC 0xBC // R Calibration data (16 bits)
#define BMP085_CAL_MD 0xBE // R Calibration data (16 bits)
#define BMP085_CONTROL 0xF4
#define BMP085_TEMPDATA 0xF6
#define BMP085_PRESSUREDATA 0xF6
#define BMP085_READTEMPCMD 0x2E
#define BMP085_READPRESSURECMD 0x34
class Adafruit_BMP085 {
public:
Adafruit_BMP085();
boolean begin(uint8_t mode = BMP085_ULTRAHIGHRES); // by default go highres
float readTemperature(void);
int32_t readPressure(void);
float readAltitude(float sealevelPressure = 101325); // std atmosphere
uint16_t readRawTemperature(void);
uint32_t readRawPressure(void);
private:
uint8_t read8(uint8_t addr);
uint16_t read16(uint8_t addr);
void write8(uint8_t addr, uint8_t data);
uint8_t oversampling;
int16_t ac1, ac2, ac3, b1, b2, mb, mc, md;
uint16_t ac4, ac5, ac6;
};
+22
View File
@@ -0,0 +1,22 @@
This is a library for the Adafruit BMP085 Barometric Pressure + Temp sensor
Designed specifically to work with the Adafruit BMP085 Breakout
----> https://www.adafruit.com/products/391
These displays use I2C to communicate, 2 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Check out the links above for our tutorials and wiring diagrams
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_BMP085. Check that the Adafruit_BMP085 folder contains Adafruit_BMP085.cpp and Adafruit_BMP085.h
Place the Adafruit_BMP085 library folder your <arduinosketchfolder>/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.
@@ -0,0 +1,62 @@
#include <Wire.h>
#include <Adafruit_BMP085.h>
/***************************************************
This is an example for the BMP085 Barometric Pressure & Temp Sensor
Designed specifically to work with the Adafruit BMP085 Breakout
----> https://www.adafruit.com/products/391
These displays use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Nano/Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Nano/Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here
Adafruit_BMP085 bmp;
void setup() {
Serial.begin(9600);
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
while (1) {}
}
}
void loop() {
Serial.print("Temperature = ");
Serial.print(bmp.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bmp.readPressure());
Serial.println(" Pa");
// Calculate altitude assuming 'standard' barometric
// pressure of 1013.25 millibar = 101325 Pascal
Serial.print("Altitude = ");
Serial.print(bmp.readAltitude());
Serial.println(" meters");
// you can get a more precise measurement of altitude
// if you know the current sea level pressure which will
// vary with weather and such. If it is 1015 millibars
// that is equal to 101500 Pascals.
Serial.print("Real altitude = ");
Serial.print(bmp.readAltitude(101500));
Serial.println(" meters");
Serial.println();
delay(500);
}
+84
View File
@@ -0,0 +1,84 @@
// Please read Bounce.h for information about the liscence and authors
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Bounce2.h"
Bounce::Bounce() {
this->interval_millis = 10;
}
void Bounce::attach(int pin) {
this->pin = pin;
debouncedState = unstableState = digitalRead(pin);
#ifdef BOUNCE_LOCK-OUT
previous_millis = 0;
#else
previous_millis = millis();
#endif
}
void Bounce::interval(unsigned long interval_millis)
{
this->interval_millis = interval_millis;
}
bool Bounce::update()
{
#ifdef BOUNCE_LOCK-OUT
stateChanged = false;
// Ignore everything if we are locked out
if (millis() - previous_millis >= interval_millis) {
uint8_t currentState = digitalRead(pin);
if (debouncedState != currentState ) {
previous_millis = millis();
debouncedState = currentState;
stateChanged = true;
}
}
return stateChanged;
#else
// Lire l'etat de l'interrupteur dans une variable temporaire.
uint8_t currentState = digitalRead(pin);
stateChanged = false;
// Redemarrer le compteur timeStamp tant et aussi longtemps que
// la lecture ne se stabilise pas.
if ( currentState != unstableState ) {
previous_millis = millis();
} else if ( millis() - previous_millis >= interval_millis ) {
// Rendu ici, la lecture est stable
// Est-ce que la lecture est différente de l'etat emmagasine de l'interrupteur?
if ( currentState != debouncedState ) {
debouncedState = currentState;
stateChanged = true;
}
}
unstableState = currentState;
return stateChanged;
#endif
}
uint8_t Bounce::read()
{
return debouncedState;
}
+64
View File
@@ -0,0 +1,64 @@
/*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * *
Main code by Thomas O Fredericks (tof@t-o-f.info)
Previous contributions by Eric Lowry, Jim Schimpf and Tom Harkaway
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// Uncomment the following line for "LOCK-OUT" debounce method
//#define BOUNCE_LOCK-OUT
#ifndef Bounce2_h
#define Bounce2_h
#include <inttypes.h>
class Bounce
{
public:
// Create an instance of the bounce library
Bounce();
// Attach to a pin (and also sets initial state)
void attach(int pin);
// Sets the debounce interval
void interval(unsigned long interval_millis);
// Updates the pin
// Returns 1 if the state changed
// Returns 0 if the state did not change
bool update();
// Returns the updated pin state
uint8_t read();
protected:
int debounce();
unsigned long previous_millis, interval_millis;
uint8_t debouncedState;
uint8_t unstableState;
uint8_t pin;
uint8_t stateChanged;
};
#endif
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2013 thomasfredericks
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.
+1
View File
@@ -0,0 +1 @@
Please visit https://github.com/thomasfredericks/Bounce-Arduino-Wiring for latest code and documentation.
@@ -0,0 +1,52 @@
#include <Bounce2.h>
/*
DESCRIPTION
====================
Simple example of the bounce library that switches the debug LED when a button is pressed.
CIRCUIT
====================
https://raw.github.com/thomasfredericks/Bounce-Arduino-Wiring/master/Bounce/examples/circuit-bounce-change-duration-retrigger.png
*/
#define BUTTON_PIN 2
#define LED_PIN 13
// Instantiate a Bounce object
Bounce debouncer = Bounce();
void setup() {
// Setup the button
pinMode(BUTTON_PIN,INPUT);
// Activate internal pull-up
digitalWrite(BUTTON_PIN,HIGH);
// After setting up the button, setup debouncer
debouncer.attach(BUTTON_PIN);
debouncer.interval(5);
//Setup the LED
pinMode(LED_PIN,OUTPUT);
}
void loop() {
// Update the debouncer
debouncer.update();
// Get the update value
int value = debouncer.read();
// Turn on or off the LED
if ( value == HIGH) {
digitalWrite(LED_PIN, HIGH );
} else {
digitalWrite(LED_PIN, LOW );
}
}
@@ -0,0 +1,50 @@
#include <Bounce2.h>
// Detect the falling edge
// Circuit :
// https://raw.github.com/thomasfredericks/Bounce-Arduino-Wiring/master/Bounce/examples/circuit-bounce-change-duration-retrigger.png
#define BUTTON_PIN 2
#define LED_PIN 13
int ledState = LOW;
// Instantiate a Bounce object
Bounce debouncer = Bounce();
void setup() {
// Setup the button
pinMode(BUTTON_PIN,INPUT);
digitalWrite(BUTTON_PIN,HIGH);
// After setting up the button, setup Bounce object
debouncer.attach(BUTTON_PIN);
debouncer.interval(500);
//Setup the LED
pinMode(LED_PIN,OUTPUT);
digitalWrite(LED_PIN,ledState);
}
void loop() {
boolean stateChanged = debouncer.update();
int state = debouncer.read();
// Detect the falling edge
if ( stateChanged && state == LOW ) {
if ( ledState == LOW ) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN,ledState);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

@@ -0,0 +1,78 @@
#include <Bounce2.h>
/*
DESCRIPTION
====================
Simple example of the bounce library that sets three states for a button through the duration of the press.
Open the Serial Monitor (57600 baud) for debug messages.
CIRCUIT
====================
https://raw.github.com/thomasfredericks/Bounce-Arduino-Wiring/master/Bounce/examples/circuit-bounce-change-duration-retrigger.png
*/
#define BUTTON_PIN 2
#define LED_PIN 13
// Instantiate a Bounce object
Bounce debouncer = Bounce();
// The current buttonState
// 0 : released
// 1 : pressed less than 2 seconds
// 2 : pressed longer than 2 seconds
int buttonState;
unsigned long buttonPressTimeStamp;
void setup() {
Serial.begin(57600);
// Setup the button
pinMode(BUTTON_PIN,INPUT);
// Activate internal pull-up
digitalWrite(BUTTON_PIN,HIGH);
// After setting up the button, setup debouncer
debouncer.attach(BUTTON_PIN);
debouncer.interval(5);
//Setup the LED
pinMode(LED_PIN,OUTPUT);
}
void loop() {
// Update the debouncer and get the changed state
boolean changed = debouncer.update();
if ( changed ) {
// Get the update value
int value = debouncer.read();
if ( value == HIGH) {
digitalWrite(LED_PIN, HIGH );
buttonState = 0;
Serial.println("Button released (state 0)");
} else {
digitalWrite(LED_PIN, LOW );
buttonState = 1;
Serial.println("Button pressed (state 1)");
buttonPressTimeStamp = millis();
}
}
if ( buttonState == 1 ) {
if ( millis() - buttonPressTimeStamp >= 2000 ) {
buttonState = 2;
Serial.println("Button held for two seconds (state 2)");
}
}
}
@@ -0,0 +1,85 @@
#include <Bounce2.h>
/*
DESCRIPTION
====================
Simple example of the bounce library that shows how to retrigger an event when a button is held down.
In this case, the debug LED will blink every 500 ms as long as the button is held down.
Open the Serial Monitor (57600 baud) for debug messages.
CIRCUIT
====================
https://raw.github.com/thomasfredericks/Bounce-Arduino-Wiring/master/Bounce/examples/circuit-bounce-change-duration-retrigger.png
*/
#define BUTTON_PIN 2
#define LED_PIN 13
// Instantiate a Bounce object
Bounce debouncer = Bounce();
int buttonState;
unsigned long buttonPressTimeStamp;
int ledState;
void setup() {
Serial.begin(57600);
// Setup the button
pinMode(BUTTON_PIN,INPUT);
// Activate internal pull-up
digitalWrite(BUTTON_PIN,HIGH);
// After setting up the button, setup debouncer
debouncer.attach(BUTTON_PIN);
debouncer.interval(5);
//Setup the LED
pinMode(LED_PIN,OUTPUT);
digitalWrite(LED_PIN,ledState);
}
void loop() {
// Update the debouncer and get the changed state
boolean changed = debouncer.update();
if ( changed ) {
// Get the update value
int value = debouncer.read();
if ( value == HIGH) {
ledState = LOW;
digitalWrite(LED_PIN, ledState );
buttonState = 0;
Serial.println("Button released (state 0)");
} else {
ledState = HIGH;
digitalWrite(LED_PIN, ledState );
buttonState = 1;
Serial.println("Button pressed (state 1)");
buttonPressTimeStamp = millis();
}
}
if ( buttonState == 1 ) {
if ( millis() - buttonPressTimeStamp >= 500 ) {
buttonPressTimeStamp = millis();
if ( ledState == HIGH ) ledState = LOW;
else if ( ledState == LOW ) ledState = HIGH;
digitalWrite(LED_PIN, ledState );
Serial.println("Retriggering button");
}
}
}
+206
View File
@@ -0,0 +1,206 @@
/******************************************************************
DHT Temperature & Humidity Sensor library for Arduino.
Features:
- Support for DHT11 and DHT22/AM2302/RHT03
- Auto detect sensor model
- Very low memory footprint
- Very small code
http://www.github.com/markruys/arduino-DHT
Written by Mark Ruys, mark@paracas.nl.
BSD license, check license.txt for more information.
All text above must be included in any redistribution.
Datasheets:
- http://www.micro4you.com/files/sensor/DHT11.pdf
- http://www.adafruit.com/datasheets/DHT22.pdf
- http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Weather/RHT03.pdf
- http://meteobox.tk/files/AM2302.pdf
Changelog:
2013-06-10: Initial version
2013-06-12: Refactored code
2013-07-01: Add a resetTimer method
******************************************************************/
#include "DHT.h"
void DHT::setup(uint8_t pin, DHT_MODEL_t model)
{
DHT::pin = pin;
DHT::model = model;
DHT::resetTimer(); // Make sure we do read the sensor in the next readSensor()
if ( model == AUTO_DETECT) {
DHT::model = DHT22;
readSensor();
if ( error == ERROR_TIMEOUT ) {
DHT::model = DHT11;
// Warning: in case we auto detect a DHT11, you should wait at least 1000 msec
// before your first read request. Otherwise you will get a time out error.
}
}
}
void DHT::resetTimer()
{
DHT::lastReadTime = millis() - 3000;
}
float DHT::getHumidity()
{
readSensor();
return humidity;
}
float DHT::getTemperature()
{
readSensor();
return temperature;
}
#ifndef OPTIMIZE_SRAM_SIZE
const char* DHT::getStatusString()
{
switch ( error ) {
case DHT::ERROR_TIMEOUT:
return "TIMEOUT";
case DHT::ERROR_CHECKSUM:
return "CHECKSUM";
default:
return "OK";
}
}
#else
// At the expense of 26 bytes of extra PROGMEM, we save 11 bytes of
// SRAM by using the following method:
prog_char P_OK[] PROGMEM = "OK";
prog_char P_TIMEOUT[] PROGMEM = "TIMEOUT";
prog_char P_CHECKSUM[] PROGMEM = "CHECKSUM";
const char *DHT::getStatusString() {
prog_char *c;
switch ( error ) {
case DHT::ERROR_CHECKSUM:
c = P_CHECKSUM; break;
case DHT::ERROR_TIMEOUT:
c = P_TIMEOUT; break;
default:
c = P_OK; break;
}
static char buffer[9];
strcpy_P(buffer, c);
return buffer;
}
#endif
void DHT::readSensor()
{
// Make sure we don't poll the sensor too often
// - Max sample rate DHT11 is 1 Hz (duty cicle 1000 ms)
// - Max sample rate DHT22 is 0.5 Hz (duty cicle 2000 ms)
unsigned long startTime = millis();
if ( (unsigned long)(startTime - lastReadTime) < (model == DHT11 ? 999L : 1999L) ) {
return;
}
lastReadTime = startTime;
temperature = NAN;
humidity = NAN;
// Request sample
digitalWrite(pin, LOW); // Send start signal
pinMode(pin, OUTPUT);
if ( model == DHT11 ) {
delay(18);
}
else {
// This will fail for a DHT11 - that's how we can detect such a device
delayMicroseconds(800);
}
pinMode(pin, INPUT);
digitalWrite(pin, HIGH); // Switch bus to receive data
// We're going to read 83 edges:
// - First a FALLING, RISING, and FALLING edge for the start bit
// - Then 40 bits: RISING and then a FALLING edge per bit
// To keep our code simple, we accept any HIGH or LOW reading if it's max 85 usecs long
word rawHumidity;
word rawTemperature;
word data;
for ( int8_t i = -3 ; i < 2 * 40; i++ ) {
byte age;
startTime = micros();
do {
age = (unsigned long)(micros() - startTime);
if ( age > 90 ) {
error = ERROR_TIMEOUT;
return;
}
}
while ( digitalRead(pin) == (i & 1) ? HIGH : LOW );
if ( i >= 0 && (i & 1) ) {
// Now we are being fed our 40 bits
data <<= 1;
// A zero max 30 usecs, a one at least 68 usecs.
if ( age > 30 ) {
data |= 1; // we got a one
}
}
switch ( i ) {
case 31:
rawHumidity = data;
break;
case 63:
rawTemperature = data;
data = 0;
break;
}
}
// Verify checksum
if ( (byte)(((byte)rawHumidity) + (rawHumidity >> 8) + ((byte)rawTemperature) + (rawTemperature >> 8)) != data ) {
error = ERROR_CHECKSUM;
return;
}
// Store readings
if ( model == DHT11 ) {
humidity = rawHumidity >> 8;
temperature = rawTemperature >> 8;
}
else {
humidity = rawHumidity * 0.1;
if ( rawTemperature & 0x8000 ) {
rawTemperature = -(int16_t)(rawTemperature & 0x7FFF);
}
temperature = ((int16_t)rawTemperature) * 0.1;
}
error = ERROR_NONE;
}
+96
View File
@@ -0,0 +1,96 @@
/******************************************************************
DHT Temperature & Humidity Sensor library for Arduino.
Features:
- Support for DHT11 and DHT22/AM2302/RHT03
- Auto detect sensor model
- Very low memory footprint
- Very small code
http://www.github.com/markruys/arduino-DHT
Written by Mark Ruys, mark@paracas.nl.
BSD license, check license.txt for more information.
All text above must be included in any redistribution.
Datasheets:
- http://www.micro4you.com/files/sensor/DHT11.pdf
- http://www.adafruit.com/datasheets/DHT22.pdf
- http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Weather/RHT03.pdf
- http://meteobox.tk/files/AM2302.pdf
Changelog:
2013-06-10: Initial version
2013-06-12: Refactored code
2013-07-01: Add a resetTimer method
******************************************************************/
#ifndef dht_h
#define dht_h
#if ARDUINO < 100
#include <WProgram.h>
#else
#include <Arduino.h>
#endif
class DHT
{
public:
typedef enum {
AUTO_DETECT,
DHT11,
DHT22,
AM2302, // Packaged DHT22
RHT03 // Equivalent to DHT22
}
DHT_MODEL_t;
typedef enum {
ERROR_NONE = 0,
ERROR_TIMEOUT,
ERROR_CHECKSUM
}
DHT_ERROR_t;
void setup(uint8_t pin, DHT_MODEL_t model=AUTO_DETECT);
void resetTimer();
float getTemperature();
float getHumidity();
DHT_ERROR_t getStatus() { return error; };
const char* getStatusString();
DHT_MODEL_t getModel() { return model; }
int getMinimumSamplingPeriod() { return model == DHT11 ? 1000 : 2000; }
int8_t getNumberOfDecimalsTemperature() { return model == DHT11 ? 0 : 1; };
int8_t getLowerBoundTemperature() { return model == DHT11 ? 0 : -40; };
int8_t getUpperBoundTemperature() { return model == DHT11 ? 50 : 125; };
int8_t getNumberOfDecimalsHumidity() { return 0; };
int8_t getLowerBoundHumidity() { return model == DHT11 ? 20 : 0; };
int8_t getUpperBoundHumidity() { return model == DHT11 ? 90 : 100; };
static float toFahrenheit(float fromCelcius) { return 1.8 * fromCelcius + 32.0; };
static float toCelsius(float fromFahrenheit) { return (fromFahrenheit - 32.0) / 1.8; };
protected:
void readSensor();
float temperature;
float humidity;
uint8_t pin;
private:
DHT_MODEL_t model;
DHT_ERROR_t error;
unsigned long lastReadTime;
};
#endif /*dht_h*/
+49
View File
@@ -0,0 +1,49 @@
DHT
===
An Arduino library for reading the DHT family of temperature and humidity sensors.
Written by Mark Ruys, <mark@paracas.nl>.
Features
--------
- Support for DHT11 and DHT22, AM2302, RHT03
- Auto detect sensor model
- Low memory footprint
- Very small code
Usage
-----
```
#include "DHT.h"
DHT dht;
void setup()
{
Serial.begin(9600);
dht.setup(2); // data pin 2
}
void loop()
{
delay(dht.getMinimumSamplingPeriod());
Serial.print(dht.getHumidity());
Serial.print("\t");
Serial.print(dht.getTemperature());
}
```
Also check out the [example] how to read out your sensor. For all the options, see [dht.h][header].
Installation
------------
Place the [DHT][download] library folder in your `<arduinosketchfolder>/libraries/` folder. You may need to create the `libraries` subfolder if its your first library. Restart the Arduino IDE.
[download]: https://github.com/markruys/arduino-DHT/archive/master.zip "Download DHT library"
[example]: https://github.com/markruys/arduino-DHT/blob/master/examples/DHT_Test/DHT_Test.pde "Show DHT example"
[header]: https://github.com/markruys/arduino-DHT/blob/master/DHT.h "Show header file"
@@ -0,0 +1,29 @@
#include "DHT.h"
DHT dht;
void setup()
{
Serial.begin(9600);
Serial.println();
Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");
dht.setup(2); // data pin 2
}
void loop()
{
delay(dht.getMinimumSamplingPeriod());
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
Serial.print(dht.getStatusString());
Serial.print("\t");
Serial.print(humidity, 1);
Serial.print("\t\t");
Serial.print(temperature, 1);
Serial.print("\t\t");
Serial.println(dht.toFahrenheit(temperature), 1);
}
+42
View File
@@ -0,0 +1,42 @@
#######################################
# Syntax Coloring Map For DHT
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
DHT KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
setup KEYWORD2
getTemperature KEYWORD2
getHumidity KEYWORD2
getStatus KEYWORD2
getStatusString KEYWORD2
getModel KEYWORD2
getMinimumSamplingPeriod KEYWORD2
toFahrenheit KEYWORD2
toCelsius KEYWORD2
#######################################
# Instances (KEYWORD2)
#######################################
#######################################
# Constants (LITERAL1)
#######################################
AUTO_DETECT LITERAL1
DHT11 LITERAL1
DHT22 LITERAL1
AM2302 LITERAL1
RHT03 LITERAL1
ERROR_NONE LITERAL1
ERROR_TIMEOUT LITERAL1
ERROR_CHECKSUM LITERAL1
+26
View File
@@ -0,0 +1,26 @@
Software License Agreement (BSD License)
Copyright (c) 2013, Mark Ruys. 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 University of California, Berkeley nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS AND 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.
Binary file not shown.
@@ -0,0 +1,618 @@
// 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.
#include "DallasTemperature.h"
extern "C" {
#include "Arduino.h"
}
DallasTemperature::DallasTemperature(OneWire* _oneWire)
#if REQUIRESALARMS
: _AlarmHandler(&defaultAlarmHandler)
#endif
{
_wire = _oneWire;
devices = 0;
parasite = false;
conversionDelay = TEMP_9_BIT;
}
// initialize the bus
void DallasTemperature::begin(void)
{
DeviceAddress deviceAddress;
_wire->reset_search();
devices = 0; // Reset the number of devices when we enumerate wire devices
while (_wire->search(deviceAddress))
{
if (validAddress(deviceAddress))
{
if (!parasite && readPowerSupply(deviceAddress)) parasite = true;
ScratchPad scratchPad;
readScratchPad(deviceAddress, scratchPad);
if (deviceAddress[0] == DS18S20MODEL) conversionDelay = TEMP_12_BIT; // 750 ms
else if (scratchPad[CONFIGURATION] > conversionDelay) conversionDelay = scratchPad[CONFIGURATION];
devices++;
}
}
}
// returns the number of devices found on the bus
uint8_t DallasTemperature::getDeviceCount(void)
{
return devices;
}
// returns true if address is valid
bool DallasTemperature::validAddress(uint8_t* deviceAddress)
{
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;
_wire->reset_search();
while (depth <= index && _wire->search(deviceAddress))
{
if (depth == index && validAddress(deviceAddress)) return true;
depth++;
}
return false;
}
// attempt to determine if the device at the given address is connected to the bus
bool DallasTemperature::isConnected(uint8_t* deviceAddress)
{
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)
{
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)
{
// send the command
_wire->reset();
_wire->select(deviceAddress);
_wire->write(READSCRATCH);
// read the response
// byte 0: temperature LSB
scratchPad[TEMP_LSB] = _wire->read();
// byte 1: temperature MSB
scratchPad[TEMP_MSB] = _wire->read();
// byte 2: high alarm temp
scratchPad[HIGH_ALARM_TEMP] = _wire->read();
// byte 3: low alarm temp
scratchPad[LOW_ALARM_TEMP] = _wire->read();
// byte 4:
// DS18S20: store for crc
// DS18B20 & DS1822: configuration register
scratchPad[CONFIGURATION] = _wire->read();
// byte 5:
// internal use & crc
scratchPad[INTERNAL_BYTE] = _wire->read();
// byte 6:
// DS18S20: COUNT_REMAIN
// DS18B20 & DS1822: store for crc
scratchPad[COUNT_REMAIN] = _wire->read();
// 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)
{
_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();
}
// reads the device's power requirements
bool DallasTemperature::readPowerSupply(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;
}
// 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 a device to 9, 10, 11, or 12 bits
void DallasTemperature::setResolution(uint8_t* deviceAddress, uint8_t newResolution)
{
ScratchPad scratchPad;
if (isConnected(deviceAddress, scratchPad))
{
// DS18S20 has a fixed 9-bit resolution
if (deviceAddress[0] != DS18S20MODEL)
{
switch (newResolution)
{
case 12:
scratchPad[CONFIGURATION] = TEMP_12_BIT;
break;
case 11:
scratchPad[CONFIGURATION] = TEMP_11_BIT;
break;
case 10:
scratchPad[CONFIGURATION] = TEMP_10_BIT;
break;
case 9:
default:
scratchPad[CONFIGURATION] = TEMP_9_BIT;
break;
}
writeScratchPad(deviceAddress, scratchPad);
}
}
}
// sends command for all devices on the bus to perform a temperature
void DallasTemperature::requestTemperatures(void)
{
_wire->reset();
_wire->skip();
_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:
default:
delay(750);
break;
}
}
// sends command for one device to perform a temperature by address
void DallasTemperature::requestTemperaturesByAddress(uint8_t* deviceAddress)
{
_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:
default:
delay(750);
break;
}
}
// sends command for one device to perform a temp conversion by index
void DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex)
{
DeviceAddress deviceAddress;
getAddress(deviceAddress, deviceIndex);
requestTemperaturesByAddress(deviceAddress);
}
// Fetch temperature for device index
float DallasTemperature::getTempCByIndex(uint8_t deviceIndex)
{
DeviceAddress deviceAddress;
getAddress(deviceAddress, deviceIndex);
return getTempC((uint8_t*)deviceAddress);
}
// Fetch temperature for device index
float DallasTemperature::getTempFByIndex(uint8_t deviceIndex)
{
return DallasTemperature::toFahrenheit(getTempCByIndex(deviceIndex));
}
// reads scratchpad and returns the temperature in degrees C
float DallasTemperature::calculateTemperature(uint8_t* deviceAddress, uint8_t* scratchPad)
{
int16_t rawTemperature = (((int16_t)scratchPad[TEMP_MSB]) << 8) | scratchPad[TEMP_LSB];
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:
/*
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:
COUNT_PER_C - COUNT_REMAIN
TEMPERATURE = TEMP_READ - 0.25 + --------------------------
COUNT_PER_C
*/
// 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;
}
}
// returns temperature in degrees C or DEVICE_DISCONNECTED 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
// operating range of the device
float DallasTemperature::getTempC(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;
}
// returns temperature in degrees F
float DallasTemperature::getTempF(uint8_t* deviceAddress)
{
return toFahrenheit(getTempC(deviceAddress));
}
// returns true if the bus requires parasite power
bool DallasTemperature::isParasitePowerMode(void)
{
return parasite;
}
#if REQUIRESALARMS
/*
ALARMS:
TH and TL Register Format
BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0
S 2^6 2^5 2^4 2^3 2^2 2^1 2^0
Only bits 11 through 4 of the temperature register are used
in the TH and TL comparison since TH and TL are 8-bit
registers. If the measured temperature is lower than or equal
to TL or higher than or equal to TH, an alarm condition exists
and an alarm flag is set inside the DS18B20. This flag is
updated after every temperature measurement; therefore, if the
alarm condition goes away, the flag will be turned off after
the next temperature conversion.
*/
// 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)
{
// 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);
}
}
// sets the low alarm temperature for a device in degreed 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)
{
// 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);
}
}
// returns a char with the current high alarm temperature or
// DEVICE_DISCONNECTED for an address
char DallasTemperature::getHighAlarmTemp(uint8_t* deviceAddress)
{
ScratchPad scratchPad;
if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[HIGH_ALARM_TEMP];
return DEVICE_DISCONNECTED;
}
// returns a char with the current low alarm temperature or
// DEVICE_DISCONNECTED for an address
char DallasTemperature::getLowAlarmTemp(uint8_t* deviceAddress)
{
ScratchPad scratchPad;
if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[LOW_ALARM_TEMP];
return DEVICE_DISCONNECTED;
}
// 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;
}
// This is a modified version of the OneWire::search method.
//
// Also added the OneWire search fix documented here:
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295
//
// Perform an alarm search. If this function returns a '1' then it has
// enumerated the next device and you may retrieve the ROM from the
// OneWire::address variable. If there are no devices, no further
// devices, or something horrible happens in the middle of the
// enumeration then a 0 is returned. If a new device is found then
// its address is copied to newAddr. Use
// DallasTemperature::resetAlarmSearch() to start over.
bool DallasTemperature::alarmSearch(uint8_t* newAddr)
{
uint8_t i;
char lastJunction = -1;
uint8_t done = 1;
if (alarmSearchExhausted) return false;
if (!_wire->reset()) return false;
// 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)
{
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 exhasuted 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
}
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;
}
// returns true if device address has an alarm condition
bool DallasTemperature::hasAlarm(uint8_t* deviceAddress)
{
ScratchPad scratchPad;
if (isConnected(deviceAddress, scratchPad))
{
float temp = calculateTemperature(deviceAddress, scratchPad);
// check low alarm
if ((char)temp <= (char)scratchPad[LOW_ALARM_TEMP]) return true;
// check high alarm
if ((char)temp >= (char)scratchPad[HIGH_ALARM_TEMP]) return true;
}
// 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);
}
// runs the alarm handler for all devices returned by alarmSearch()
void DallasTemperature::processAlarms(void)
{
resetAlarmSearch();
DeviceAddress alarmAddr;
while (alarmSearch(alarmAddr))
{
if (validAddress(alarmAddr))
_AlarmHandler(alarmAddr);
}
}
// sets the alarm handler
void DallasTemperature::setAlarmHandler(AlarmHandler *handler)
{
_AlarmHandler = handler;
}
// The default alarm handler
void DallasTemperature::defaultAlarmHandler(uint8_t* deviceAddress)
{
}
#endif
// Convert float celsius to fahrenheit
float DallasTemperature::toFahrenheit(float celsius)
{
return (celsius * 1.8) + 32;
}
// Convert float fahrenheit to celsius
float DallasTemperature::toCelsius(float fahrenheit)
{
return (fahrenheit - 32) / 1.8;
}
#if REQUIRESNEW
// 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
//!!! 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
void DallasTemperature::operator delete(void* p)
{
DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer
pNss->~DallasTemperature(); // Destruct the object
free(p); // Free the memory
}
#endif
@@ -0,0 +1,213 @@
#ifndef DallasTemperature_h
#define DallasTemperature_h
// 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.
// set to true to include code for new and delete operators
#ifndef REQUIRESNEW
#define REQUIRESNEW false
#endif
// set to true to include code implementing alarm search functions
#ifndef REQUIRESALARMS
#define REQUIRESALARMS true
#endif
#include <inttypes.h>
#include <OneWire.h>
// Model IDs
#define DS18S20MODEL 0x10
#define DS18B20MODEL 0x28
#define DS1822MODEL 0x22
// OneWire commands
#define STARTCONVO 0x44 // Tells device to take a temperature reading and put it on the scratchpad
#define COPYSCRATCH 0x48 // Copy EEPROM
#define READSCRATCH 0xBE // Read EEPROM
#define WRITESCRATCH 0x4E // Write to EEPROM
#define RECALLSCRATCH 0xB8 // Reload from last known
#define READPOWERSUPPLY 0xB4 // Determine if device needs parasite power
#define ALARMSEARCH 0xEC // Query bus for devices with an alarm condition
// Scratchpad locations
#define TEMP_LSB 0
#define TEMP_MSB 1
#define HIGH_ALARM_TEMP 2
#define LOW_ALARM_TEMP 3
#define CONFIGURATION 4
#define INTERNAL_BYTE 5
#define COUNT_REMAIN 6
#define COUNT_PER_C 7
#define SCRATCHPAD_CRC 8
// Device resolution
#define TEMP_9_BIT 0x1F // 9 bit
#define TEMP_10_BIT 0x3F // 10 bit
#define TEMP_11_BIT 0x5F // 11 bit
#define TEMP_12_BIT 0x7F // 12 bit
// Error Codes
#define DEVICE_DISCONNECTED -127
typedef uint8_t DeviceAddress[8];
class DallasTemperature
{
public:
DallasTemperature(OneWire*);
// initalize 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*);
// finds an address at a given index on the bus
bool getAddress(uint8_t*, const uint8_t);
// attempt to determine if the device at the given address is connected to the bus
bool isConnected(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*);
// read device's scratchpad
void readScratchPad(uint8_t*, uint8_t*);
// write device's scratchpad
void writeScratchPad(uint8_t*, const uint8_t*);
// read device's power requirements
bool readPowerSupply(uint8_t*);
// returns the current resolution, 9-12
uint8_t getResolution(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
void requestTemperatures(void);
// sends command for one device to perform a temperature conversion by address
void requestTemperaturesByAddress(uint8_t*);
// sends command for one device to perform a temperature conversion by index
void requestTemperaturesByIndex(uint8_t);
// returns temperature in degrees C
float getTempC(uint8_t*);
// returns temperature in degrees F
float getTempF(uint8_t*);
// Get temperature for device index (slow)
float getTempCByIndex(uint8_t);
// Get temperature for device index (slow)
float getTempFByIndex(uint8_t);
// returns true if the bus requires parasite power
bool isParasitePowerMode(void);
#if REQUIRESALARMS
typedef void AlarmHandler(uint8_t*);
// sets the high alarm temperature for a device
// accepts a char. valid range is -55C - 125C
void setHighAlarmTemp(uint8_t*, const char);
// sets the low alarm temperature for a device
// accepts a char. valid range is -55C - 125C
void setLowAlarmTemp(uint8_t*, const char);
// returns a signed char with the current high alarm temperature for a device
// in the range -55C - 125C
char getHighAlarmTemp(uint8_t*);
// returns a signed char with the current low alarm temperature for a device
// in the range -55C - 125C
char getLowAlarmTemp(uint8_t*);
// resets internal variables used for the alarm search
void resetAlarmSearch(void);
// search the wire for devices with active alarms
bool alarmSearch(uint8_t*);
// returns true if ia specific device has an alarm
bool hasAlarm(uint8_t*);
// returns true if any device is reporting an alarm on the bus
bool hasAlarm(void);
// runs the alarm handler for all devices returned by alarmSearch()
void processAlarms(void);
// sets the alarm handler
void setAlarmHandler(AlarmHandler *);
// The default alarm handler
static void defaultAlarmHandler(uint8_t*);
#endif
// convert from celcius to farenheit
static float toFahrenheit(const float);
// convert from farenheit to celsius
static float toCelsius(const float);
#if REQUIRESNEW
// initalize memory area
void* operator new (unsigned int);
// delete memory reference
void operator delete(void*);
#endif
private:
typedef uint8_t ScratchPad[9];
// parasite power on or off
bool parasite;
// used to determine the delay amount needed to allow for the
// temperature conversion to take place
int conversionDelay;
// 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*);
#if REQUIRESALARMS
// required for alarmSearch
uint8_t alarmSearchAddress[8];
char alarmSearchJunction;
uint8_t alarmSearchExhausted;
// the alarm handler function pointer
AlarmHandler *_AlarmHandler;
#endif
};
#endif
+51
View File
@@ -0,0 +1,51 @@
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
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
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
Credits
-------
The OneWire code has been derived from
http://www.arduino.cc/playground/Learning/OneWire.
Miles Burton <miles@mnetcs.com> originally developed this library.
Tim Newsome <nuisance@casualhacker.net> added support for multiple sensors on
the same bus.
Guil Barros [gfbarros@bappos.com] added getTempByAddress (v3.5)
Website
-------
You can find the latest version of the library at
http://milesburton.com/index.php?title=Dallas_Temperature_Control_Library
License
-------
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
@@ -0,0 +1,162 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
// 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);
// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// locate devices on the bus
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// search for devices on the bus and assign based on an index.
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");
// show the addresses we found on the bus
Serial.print("Device 0 Address: ");
printAddress(insideThermometer);
Serial.println();
Serial.print("Device 0 Alarms: ");
printAlarms(insideThermometer);
Serial.println();
Serial.print("Device 1 Address: ");
printAddress(outsideThermometer);
Serial.println();
Serial.print("Device 1 Alarms: ");
printAlarms(outsideThermometer);
Serial.println();
Serial.println("Setting alarm temps...");
// alarm when temp is higher than 30C
sensors.setHighAlarmTemp(insideThermometer, 30);
// alarm when temp is lower than -10C
sensors.setLowAlarmTemp(insideThermometer, -10);
// alarm when temp is higher than 31C
sensors.setHighAlarmTemp(outsideThermometer, 31);
// alarn when temp is lower than 27C
sensors.setLowAlarmTemp(outsideThermometer, 27);
Serial.print("New Device 0 Alarms: ");
printAlarms(insideThermometer);
Serial.println();
Serial.print("New Device 1 Alarms: ");
printAlarms(outsideThermometer);
Serial.println();
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.print(DallasTemperature::toFahrenheit(tempC));
}
void printAlarms(uint8_t deviceAddress[])
{
char temp;
temp = sensors.getHighAlarmTemp(deviceAddress);
Serial.print("High Alarm: ");
Serial.print(temp, DEC);
Serial.print("C/");
Serial.print(DallasTemperature::toFahrenheit(temp));
Serial.print("F | Low Alarm: ");
temp = sensors.getLowAlarmTemp(deviceAddress);
Serial.print(temp, DEC);
Serial.print("C/");
Serial.print(DallasTemperature::toFahrenheit(temp));
Serial.print("F");
}
// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
Serial.print("Device Address: ");
printAddress(deviceAddress);
Serial.print(" ");
printTemperature(deviceAddress);
Serial.println();
}
void checkAlarm(DeviceAddress deviceAddress)
{
if (sensors.hasAlarm(deviceAddress))
{
Serial.print("ALARM: ");
printData(deviceAddress);
}
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
Serial.println("DONE");
// Method 1:
// check each address individually for an alarm condition
checkAlarm(insideThermometer);
checkAlarm(outsideThermometer);
/*
// Alternate method:
// Search the bus and iterate through addresses of devices with alarms
// space for the alarm device's address
DeviceAddress alarmAddr;
Serial.println("Searching for alarms...");
// resetAlarmSearch() must be called before calling alarmSearch()
sensors.resetAlarmSearch();
// alarmSearch() returns 0 when there are no devices with alarms
while (sensors.alarmSearch(alarmAddr))
{
Serial.print("ALARM: ");
printData(alarmAddr);
}
*/
}
@@ -0,0 +1,145 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define TEMPERATURE_PRECISION 9
// 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);
// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;
// function that will be called when an alarm condition exists during DallasTemperatures::processAlarms();
void newAlarmHandler(uint8_t* deviceAddress)
{
Serial.println("Alarm Handler Start");
printAlarmInfo(deviceAddress);
printTemp(deviceAddress);
Serial.println();
Serial.println("Alarm Handler Finish");
}
void printCurrentTemp(DeviceAddress deviceAddress)
{
printAddress(deviceAddress);
printTemp(deviceAddress);
Serial.println();
}
void printAddress(DeviceAddress deviceAddress)
{
Serial.print("Address: ");
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
Serial.print(" ");
}
void printTemp(DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
if (tempC != DEVICE_DISCONNECTED)
{
Serial.print("Current Temp C: ");
Serial.print(tempC);
}
else Serial.print("DEVICE DISCONNECTED");
Serial.print(" ");
}
void printAlarmInfo(DeviceAddress deviceAddress)
{
char temp;
printAddress(deviceAddress);
temp = sensors.getHighAlarmTemp(deviceAddress);
Serial.print("High Alarm: ");
Serial.print(temp, DEC);
Serial.print("C");
Serial.print(" Low Alarm: ");
temp = sensors.getLowAlarmTemp(deviceAddress);
Serial.print(temp, DEC);
Serial.print("C");
Serial.print(" ");
}
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// locate devices on the bus
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// search for devices on the bus and assign based on an index
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");
Serial.print("Device insideThermometer ");
printAlarmInfo(insideThermometer);
Serial.println();
Serial.print("Device outsideThermometer ");
printAlarmInfo(outsideThermometer);
Serial.println();
// set alarm ranges
Serial.println("Setting alarm temps...");
sensors.setHighAlarmTemp(insideThermometer, 26);
sensors.setLowAlarmTemp(insideThermometer, 22);
sensors.setHighAlarmTemp(outsideThermometer, 25);
sensors.setLowAlarmTemp(outsideThermometer, 21);
Serial.print("New insideThermometer ");
printAlarmInfo(insideThermometer);
Serial.println();
Serial.print("New outsideThermometer ");
printAlarmInfo(outsideThermometer);
Serial.println();
// attach alarm handler
sensors.setAlarmHandler(&newAlarmHandler);
}
void loop(void)
{
// ask the devices to measure the temperature
sensors.requestTemperatures();
// if an alarm condition exists as a result of the most recent
// requestTemperatures() request, it exists until the next time
// requestTemperatures() is called AND there isn't an alarm condition
// on the device
if (sensors.hasAlarm())
{
Serial.println("Oh noes! There is at least one alarm on the bus.");
}
// call alarm handler function defined by sensors.setAlarmHandler
// for each device reporting an alarm
sensors.processAlarms();
if (!sensors.hasAlarm())
{
// just print out the current temperature
printCurrentTemp(insideThermometer);
printCurrentTemp(outsideThermometer);
}
delay(1000);
}
@@ -0,0 +1,140 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define TEMPERATURE_PRECISION 9
// 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);
// arrays to hold device addresses
DeviceAddress insideThermometer, outsideThermometer;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// locate devices on the bus
Serial.print("Locating devices...");
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// report parasite power requirements
Serial.print("Parasite power is: ");
if (sensors.isParasitePowerMode()) Serial.println("ON");
else Serial.println("OFF");
// assign address manually. the addresses below will beed to be changed
// to valid device addresses on your bus. device address can be retrieved
// by using either oneWire.search(deviceAddress) or individually via
// sensors.getAddress(deviceAddress, index)
//insideThermometer = { 0x28, 0x1D, 0x39, 0x31, 0x2, 0x0, 0x0, 0xF0 };
//outsideThermometer = { 0x28, 0x3F, 0x1C, 0x31, 0x2, 0x0, 0x0, 0x2 };
// search for devices on the bus and assign based on an index. ideally,
// you would do this to initially discover addresses on the bus and then
// use those addresses and manually assign them (see above) once you know
// the devices on your bus (and assuming they don't change).
//
// method 1: by index
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");
// method 2: search()
// search() looks 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 might be a good idea to
// check the CRC to make sure you didn't get garbage. The order is
// deterministic. You will always get the same devices in the same order
//
// Must be called before search()
//oneWire.reset_search();
// assigns the first address found to insideThermometer
//if (!oneWire.search(insideThermometer)) Serial.println("Unable to find address for insideThermometer");
// assigns the seconds address found to outsideThermometer
//if (!oneWire.search(outsideThermometer)) Serial.println("Unable to find address for outsideThermometer");
// show the addresses we found on the bus
Serial.print("Device 0 Address: ");
printAddress(insideThermometer);
Serial.println();
Serial.print("Device 1 Address: ");
printAddress(outsideThermometer);
Serial.println();
// set the resolution to 9 bit
sensors.setResolution(insideThermometer, 9);
sensors.setResolution(outsideThermometer, 9);
Serial.print("Device 0 Resolution: ");
Serial.print(sensors.getResolution(insideThermometer), DEC);
Serial.println();
Serial.print("Device 1 Resolution: ");
Serial.print(sensors.getResolution(outsideThermometer), DEC);
Serial.println();
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
// zero pad the address if necessary
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.print(DallasTemperature::toFahrenheit(tempC));
}
// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
Serial.print("Resolution: ");
Serial.print(sensors.getResolution(deviceAddress));
Serial.println();
}
// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
Serial.print("Device Address: ");
printAddress(deviceAddress);
Serial.print(" ");
printTemperature(deviceAddress);
Serial.println();
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
Serial.println("DONE");
// print the device information
printData(insideThermometer);
printData(outsideThermometer);
}
@@ -0,0 +1,33 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// 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(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(sensors.getTempCByIndex(0));
}
@@ -0,0 +1,109 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
// 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);
// arrays to hold device address
DeviceAddress insideThermometer;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// locate devices on the bus
Serial.print("Locating devices...");
sensors.begin();
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
// report parasite power requirements
Serial.print("Parasite power is: ");
if (sensors.isParasitePowerMode()) Serial.println("ON");
else Serial.println("OFF");
// assign address manually. the addresses below will beed to be changed
// to valid device addresses on your bus. device address can be retrieved
// by using either oneWire.search(deviceAddress) or individually via
// sensors.getAddress(deviceAddress, index)
//insideThermometer = { 0x28, 0x1D, 0x39, 0x31, 0x2, 0x0, 0x0, 0xF0 };
// Method 1:
// search for devices on the bus and assign based on an index. ideally,
// you would do this to initially discover addresses on the bus and then
// use those addresses and manually assign them (see above) once you know
// the devices on your bus (and assuming they don't change).
if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
// method 2: search()
// search() looks 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 might be a good idea to
// check the CRC to make sure you didn't get garbage. The order is
// deterministic. You will always get the same devices in the same order
//
// Must be called before search()
//oneWire.reset_search();
// assigns the first address found to insideThermometer
//if (!oneWire.search(insideThermometer)) Serial.println("Unable to find address for insideThermometer");
// show the addresses we found on the bus
Serial.print("Device 0 Address: ");
printAddress(insideThermometer);
Serial.println();
// set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions)
sensors.setResolution(insideThermometer, 9);
Serial.print("Device 0 Resolution: ");
Serial.print(sensors.getResolution(insideThermometer), DEC);
Serial.println();
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
// method 1 - slower
//Serial.print("Temp C: ");
//Serial.print(sensors.getTempC(deviceAddress));
//Serial.print(" Temp F: ");
//Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit
// method 2 - faster
float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// It responds almost immediately. Let's print out the data
printTemperature(insideThermometer); // Use a simple function to print out the data
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
@@ -0,0 +1,124 @@
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define TEMPERATURE_PRECISION 9
// 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);
int numberOfDevices; // Number of temperature devices found
DeviceAddress tempDeviceAddress; // We'll use this variable to store a found device address
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
// Grab a count of devices on the wire
numberOfDevices = sensors.getDeviceCount();
// locate devices on the bus
Serial.print("Locating devices...");
Serial.print("Found ");
Serial.print(numberOfDevices, DEC);
Serial.println(" devices.");
// report parasite power requirements
Serial.print("Parasite power is: ");
if (sensors.isParasitePowerMode()) Serial.println("ON");
else Serial.println("OFF");
// Loop through each device, print out address
for(int i=0;i<numberOfDevices; i++)
{
// Search the wire for address
if(sensors.getAddress(tempDeviceAddress, i))
{
Serial.print("Found device ");
Serial.print(i, DEC);
Serial.print(" with address: ");
printAddress(tempDeviceAddress);
Serial.println();
Serial.print("Setting resolution to ");
Serial.println(TEMPERATURE_PRECISION,DEC);
// set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions)
sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);
Serial.print("Resolution actually set to: ");
Serial.print(sensors.getResolution(tempDeviceAddress), DEC);
Serial.println();
}else{
Serial.print("Found ghost device at ");
Serial.print(i, DEC);
Serial.print(" but could not detect address. Check power and cabling");
}
}
}
// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
// method 1 - slower
//Serial.print("Temp C: ");
//Serial.print(sensors.getTempC(deviceAddress));
//Serial.print(" Temp F: ");
//Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit
// method 2 - faster
float tempC = sensors.getTempC(deviceAddress);
Serial.print("Temp C: ");
Serial.print(tempC);
Serial.print(" Temp F: ");
Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// Loop through each device, print out temperature data
for(int i=0;i<numberOfDevices; i++)
{
// Search the wire for address
if(sensors.getAddress(tempDeviceAddress, i))
{
// Output the device ID
Serial.print("Temperature for device: ");
Serial.println(i,DEC);
// It responds almost immediately. Let's print out the data
printTemperature(tempDeviceAddress); // Use a simple function to print out the data
}
//else ghost device! Check your power requirements and cabling
}
}
// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
for (uint8_t i = 0; i < 8; i++)
{
if (deviceAddress[i] < 16) Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
+52
View File
@@ -0,0 +1,52 @@
#######################################
# Syntax Coloring Map For Ultrasound
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
DallasTemperature KEYWORD1
OneWire KEYWORD1
AlarmHandler KEYWORD1
DeviceAddress KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
setResolution KEYWORD2
getResolution KEYWORD2
getTempC KEYWORD2
toFahrenheit KEYWORD2
getTempF KEYWORD2
getTempCByIndex KEYWORD2
getTempFByIndex KEYWORD2
requestTemperatures KEYWORD2
requestTemperaturesByAddress KEYWORD2
requestTemperaturesByIndex KEYWORD2
isParasitePowerMode KEYWORD2
begin KEYWORD2
getDeviceCount KEYWORD2
getAddress KEYWORD2
validAddress KEYWORD2
isConnected KEYWORD2
readScratchPad KEYWORD2
writeScratchPad KEYWORD2
readPowerSupply KEYWORD2
setHighAlarmTemp KEYWORD2
setLowAlarmTemp KEYWORD2
getHighAlarmTemp KEYWORD2
getLowAlarmTemp KEYWORD2
resetAlarmSearch KEYWORD2
alarmSearch KEYWORD2
hasAlarm KEYWORD2
toCelsius KEYWORD2
processAlarmss KEYWORD2
setAlarmHandlers KEYWORD2
defaultAlarmHandler KEYWORD2
calculateTemperature KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
File diff suppressed because it is too large Load Diff
+118
View File
@@ -0,0 +1,118 @@
/*
* IRremote
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.htm http://arcfn.com
* Edited by Mitra to add new controller SANYO
*
* Interrupt code based on NECIRrcv by Joe Knapp
* http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
* Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
*
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
*/
#ifndef IRremote_h
#define IRremote_h
// The following are compile-time library options.
// If you change them, recompile the library.
// If DEBUG is defined, a lot of debugging output will be printed during decoding.
// TEST must be defined for the IRtest unittests to work. It will make some
// methods virtual, which will be slightly slower, which is why it is optional.
// #define DEBUG
// #define TEST
// Results returned from the decoder
class decode_results {
public:
int decode_type; // NEC, SONY, RC5, UNKNOWN
unsigned int panasonicAddress; // This is only used for decoding Panasonic data
unsigned long value; // Decoded value
int bits; // Number of bits in decoded value
volatile unsigned int *rawbuf; // Raw intervals in .5 us ticks
int rawlen; // Number of records in rawbuf.
};
// Values for decode_type
#define NEC 1
#define SONY 2
#define RC5 3
#define RC6 4
#define DISH 5
#define SHARP 6
#define PANASONIC 7
#define JVC 8
#define SANYO 9
#define MITSUBISHI 10
#define UNKNOWN -1
// Decoded value for NEC when a repeat code is received
#define REPEAT 0xffffffff
// main class for receiving IR
class IRrecv
{
public:
IRrecv(int recvpin);
void blink13(int blinkflag);
int decode(decode_results *results);
void enableIRIn();
void resume();
private:
// These are called by decode
int getRClevel(decode_results *results, int *offset, int *used, int t1);
long decodeNEC(decode_results *results);
long decodeSony(decode_results *results);
long decodeSanyo(decode_results *results);
long decodeMitsubishi(decode_results *results);
long decodeRC5(decode_results *results);
long decodeRC6(decode_results *results);
long decodePanasonic(decode_results *results);
long decodeJVC(decode_results *results);
long decodeHash(decode_results *results);
int compare(unsigned int oldval, unsigned int newval);
}
;
// Only used for testing; can remove virtual for shorter code
#ifdef TEST
#define VIRTUAL virtual
#else
#define VIRTUAL
#endif
class IRsend
{
public:
IRsend() {}
void sendNEC(unsigned long data, int nbits);
void sendSony(unsigned long data, int nbits);
// Neither Sanyo nor Mitsubishi send is implemented yet
// void sendSanyo(unsigned long data, int nbits);
// void sendMitsubishi(unsigned long data, int nbits);
void sendRaw(unsigned int buf[], int len, int hz);
void sendRC5(unsigned long data, int nbits);
void sendRC6(unsigned long data, int nbits);
void sendDISH(unsigned long data, int nbits);
void sendSharp(unsigned long data, int nbits);
void sendPanasonic(unsigned int address, unsigned long data);
void sendJVC(unsigned long data, int nbits, int repeat); // *Note instead of sending the REPEAT constant if you want the JVC repeat signal sent, send the original code value and change the repeat argument from 0 to 1. JVC protocol repeats by skipping the header NOT by sending a separate code value like NEC does.
// private:
void enableIROut(int khz);
VIRTUAL void mark(int usec);
VIRTUAL void space(int usec);
}
;
// Some useful constants
#define USECPERTICK 50 // microseconds per clock interrupt tick
#define RAWBUF 100 // Length of raw duration buffer
// Marks tend to be 100us too long, and spaces 100us too short
// when received due to sensor lag.
#define MARK_EXCESS 100
#endif
+464
View File
@@ -0,0 +1,464 @@
/*
* IRremote
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html
*
* Modified by Paul Stoffregen <paul@pjrc.com> to support other boards and timers
*
* Interrupt code based on NECIRrcv by Joe Knapp
* http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
* Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
*
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
*/
#ifndef IRremoteint_h
#define IRremoteint_h
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
// define which timer to use
//
// Uncomment the timer you wish to use on your board. If you
// are using another library which uses timer2, you have options
// to switch IRremote to use a different timer.
// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//#define IR_USE_TIMER1 // tx = pin 11
#define IR_USE_TIMER2 // tx = pin 9
//#define IR_USE_TIMER3 // tx = pin 5
//#define IR_USE_TIMER4 // tx = pin 6
//#define IR_USE_TIMER5 // tx = pin 46
// Teensy 1.0
#elif defined(__AVR_AT90USB162__)
#define IR_USE_TIMER1 // tx = pin 17
// Teensy 2.0
#elif defined(__AVR_ATmega32U4__)
//#define IR_USE_TIMER1 // tx = pin 14
//#define IR_USE_TIMER3 // tx = pin 9
#define IR_USE_TIMER4_HS // tx = pin 10
// Teensy++ 1.0 & 2.0
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
//#define IR_USE_TIMER1 // tx = pin 25
#define IR_USE_TIMER2 // tx = pin 1
//#define IR_USE_TIMER3 // tx = pin 16
// Sanguino
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
//#define IR_USE_TIMER1 // tx = pin 13
#define IR_USE_TIMER2 // tx = pin 14
// Atmega8
#elif defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__)
#define IR_USE_TIMER1 // tx = pin 9
#elif defined( __AVR_ATtinyX4__ )
#define IR_USE_TIMER1 // tx = pin 6
// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, etc
#else
//#define IR_USE_TIMER1 // tx = pin 9
#define IR_USE_TIMER2 // tx = pin 3
#endif
#ifdef F_CPU
#define SYSCLOCK F_CPU // main Arduino clock
#else
#define SYSCLOCK 16000000 // main Arduino clock
#endif
#define ERR 0
#define DECODED 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
// Pulse parms are *50-100 for the Mark and *50+100 for the space
// First MARK is the one after the long gap
// pulse parameters in usec
#define NEC_HDR_MARK 9000
#define NEC_HDR_SPACE 4500
#define NEC_BIT_MARK 560
#define NEC_ONE_SPACE 1600
#define NEC_ZERO_SPACE 560
#define NEC_RPT_SPACE 2250
#define SONY_HDR_MARK 2400
#define SONY_HDR_SPACE 600
#define SONY_ONE_MARK 1200
#define SONY_ZERO_MARK 600
#define SONY_RPT_LENGTH 45000
#define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround
// SA 8650B
#define SANYO_HDR_MARK 3500 // seen range 3500
#define SANYO_HDR_SPACE 950 // seen 950
#define SANYO_ONE_MARK 2400 // seen 2400
#define SANYO_ZERO_MARK 700 // seen 700
#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
#define SANYO_RPT_LENGTH 45000
// Mitsubishi RM 75501
// 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7
// #define MITSUBISHI_HDR_MARK 250 // seen range 3500
#define MITSUBISHI_HDR_SPACE 350 // 7*50+100
#define MITSUBISHI_ONE_MARK 1950 // 41*50-100
#define MITSUBISHI_ZERO_MARK 750 // 17*50-100
// #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
// #define MITSUBISHI_RPT_LENGTH 45000
#define RC5_T1 889
#define RC5_RPT_LENGTH 46000
#define RC6_HDR_MARK 2666
#define RC6_HDR_SPACE 889
#define RC6_T1 444
#define RC6_RPT_LENGTH 46000
#define SHARP_BIT_MARK 245
#define SHARP_ONE_SPACE 1805
#define SHARP_ZERO_SPACE 795
#define SHARP_GAP 600000
#define SHARP_TOGGLE_MASK 0x3FF
#define SHARP_RPT_SPACE 3000
#define DISH_HDR_MARK 400
#define DISH_HDR_SPACE 6100
#define DISH_BIT_MARK 400
#define DISH_ONE_SPACE 1700
#define DISH_ZERO_SPACE 2800
#define DISH_RPT_SPACE 6200
#define DISH_TOP_BIT 0x8000
#define PANASONIC_HDR_MARK 3502
#define PANASONIC_HDR_SPACE 1750
#define PANASONIC_BIT_MARK 502
#define PANASONIC_ONE_SPACE 1244
#define PANASONIC_ZERO_SPACE 400
#define JVC_HDR_MARK 8000
#define JVC_HDR_SPACE 4000
#define JVC_BIT_MARK 600
#define JVC_ONE_SPACE 1600
#define JVC_ZERO_SPACE 550
#define JVC_RPT_LENGTH 60000
#define SHARP_BITS 15
#define DISH_BITS 16
#define TOLERANCE 25 // percent tolerance in measurements
#define LTOL (1.0 - TOLERANCE/100.)
#define UTOL (1.0 + TOLERANCE/100.)
#define _GAP 5000 // Minimum map between transmissions
#define GAP_TICKS (_GAP/USECPERTICK)
#define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK))
#define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1))
#ifndef DEBUG
int MATCH(int measured, int desired) {return measured >= TICKS_LOW(desired) && measured <= TICKS_HIGH(desired);}
int MATCH_MARK(int measured_ticks, int desired_us) {return MATCH(measured_ticks, (desired_us + MARK_EXCESS));}
int MATCH_SPACE(int measured_ticks, int desired_us) {return MATCH(measured_ticks, (desired_us - MARK_EXCESS));}
// Debugging versions are in IRremote.cpp
#endif
// receiver states
#define STATE_IDLE 2
#define STATE_MARK 3
#define STATE_SPACE 4
#define STATE_STOP 5
// information for the interrupt handler
typedef struct {
uint8_t recvpin; // pin for IR data from detector
uint8_t rcvstate; // state machine
uint8_t blinkflag; // TRUE to enable blinking of pin 13 on IR processing
unsigned int timer; // state timer, counts 50uS ticks.
unsigned int rawbuf[RAWBUF]; // raw data
uint8_t rawlen; // counter of entries in rawbuf
}
irparams_t;
// Defined in IRremote.cpp
extern volatile irparams_t irparams;
// IR detector output is active low
#define MARK 0
#define SPACE 1
#define TOPBIT 0x80000000
#define NEC_BITS 32
#define SONY_BITS 12
#define SANYO_BITS 12
#define MITSUBISHI_BITS 16
#define MIN_RC5_SAMPLES 11
#define MIN_RC6_SAMPLES 1
#define PANASONIC_BITS 48
#define JVC_BITS 16
// defines for timer2 (8 bits)
#if defined(IR_USE_TIMER2)
#define TIMER_RESET
#define TIMER_ENABLE_PWM (TCCR2A |= _BV(COM2B1))
#define TIMER_DISABLE_PWM (TCCR2A &= ~(_BV(COM2B1)))
#define TIMER_ENABLE_INTR (TIMSK2 = _BV(OCIE2A))
#define TIMER_DISABLE_INTR (TIMSK2 = 0)
#define TIMER_INTR_NAME TIMER2_COMPA_vect
#define TIMER_CONFIG_KHZ(val) ({ \
const uint8_t pwmval = SYSCLOCK / 2000 / (val); \
TCCR2A = _BV(WGM20); \
TCCR2B = _BV(WGM22) | _BV(CS20); \
OCR2A = pwmval; \
OCR2B = pwmval / 3; \
})
#define TIMER_COUNT_TOP (SYSCLOCK * USECPERTICK / 1000000)
#if (TIMER_COUNT_TOP < 256)
#define TIMER_CONFIG_NORMAL() ({ \
TCCR2A = _BV(WGM21); \
TCCR2B = _BV(CS20); \
OCR2A = TIMER_COUNT_TOP; \
TCNT2 = 0; \
})
#else
#define TIMER_CONFIG_NORMAL() ({ \
TCCR2A = _BV(WGM21); \
TCCR2B = _BV(CS21); \
OCR2A = TIMER_COUNT_TOP / 8; \
TCNT2 = 0; \
})
#endif
#if defined(CORE_OC2B_PIN)
#define TIMER_PWM_PIN CORE_OC2B_PIN /* Teensy */
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN 9 /* Arduino Mega */
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define TIMER_PWM_PIN 14 /* Sanguino */
#else
#define TIMER_PWM_PIN 3 /* Arduino Duemilanove, Diecimila, LilyPad, etc */
#endif
// defines for timer1 (16 bits)
#elif defined(IR_USE_TIMER1)
#define TIMER_RESET
#define TIMER_ENABLE_PWM (TCCR1A |= _BV(COM1A1))
#define TIMER_DISABLE_PWM (TCCR1A &= ~(_BV(COM1A1)))
#if defined(__AVR_ATmega8P__) || defined(__AVR_ATmega8__)
#define TIMER_ENABLE_INTR (TIMSK = _BV(OCIE1A))
#define TIMER_DISABLE_INTR (TIMSK = 0)
#else
#define TIMER_ENABLE_INTR (TIMSK1 = _BV(OCIE1A))
#define TIMER_DISABLE_INTR (TIMSK1 = 0)
#endif
#if defined(__AVR_ATtinyX4__)
#define TIMER_INTR_NAME TIM1_COMPA_vect
#else
#define TIMER_INTR_NAME TIMER1_COMPA_vect
#endif
#define TIMER_CONFIG_KHZ(val) ({ \
const uint16_t pwmval = SYSCLOCK / 2000 / (val); \
TCCR1A = _BV(WGM11); \
TCCR1B = _BV(WGM13) | _BV(CS10); \
ICR1 = pwmval; \
OCR1A = pwmval / 3; \
})
#define TIMER_CONFIG_NORMAL() ({ \
TCCR1A = 0; \
TCCR1B = _BV(WGM12) | _BV(CS10); \
OCR1A = SYSCLOCK * USECPERTICK / 1000000; \
TCNT1 = 0; \
})
#if defined(CORE_OC1A_PIN)
#define TIMER_PWM_PIN CORE_OC1A_PIN /* Teensy */
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN 11 /* Arduino Mega */
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define TIMER_PWM_PIN 13 /* Sanguino */
#elif defined(__AVR_ATtinyX4__)
#define TIMER_PWM_PIN 6 /* ATTiny84 */
#else
#define TIMER_PWM_PIN 9 /* Arduino Duemilanove, Diecimila, LilyPad, etc */
#endif
// defines for timer3 (16 bits)
#elif defined(IR_USE_TIMER3)
#define TIMER_RESET
#define TIMER_ENABLE_PWM (TCCR3A |= _BV(COM3A1))
#define TIMER_DISABLE_PWM (TCCR3A &= ~(_BV(COM3A1)))
#define TIMER_ENABLE_INTR (TIMSK3 = _BV(OCIE3A))
#define TIMER_DISABLE_INTR (TIMSK3 = 0)
#define TIMER_INTR_NAME TIMER3_COMPA_vect
#define TIMER_CONFIG_KHZ(val) ({ \
const uint16_t pwmval = SYSCLOCK / 2000 / (val); \
TCCR3A = _BV(WGM31); \
TCCR3B = _BV(WGM33) | _BV(CS30); \
ICR3 = pwmval; \
OCR3A = pwmval / 3; \
})
#define TIMER_CONFIG_NORMAL() ({ \
TCCR3A = 0; \
TCCR3B = _BV(WGM32) | _BV(CS30); \
OCR3A = SYSCLOCK * USECPERTICK / 1000000; \
TCNT3 = 0; \
})
#if defined(CORE_OC3A_PIN)
#define TIMER_PWM_PIN CORE_OC3A_PIN /* Teensy */
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN 5 /* Arduino Mega */
#else
#error "Please add OC3A pin number here\n"
#endif
// defines for timer4 (10 bits, high speed option)
#elif defined(IR_USE_TIMER4_HS)
#define TIMER_RESET
#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1))
#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1)))
#define TIMER_ENABLE_INTR (TIMSK4 = _BV(TOIE4))
#define TIMER_DISABLE_INTR (TIMSK4 = 0)
#define TIMER_INTR_NAME TIMER4_OVF_vect
#define TIMER_CONFIG_KHZ(val) ({ \
const uint16_t pwmval = SYSCLOCK / 2000 / (val); \
TCCR4A = (1<<PWM4A); \
TCCR4B = _BV(CS40); \
TCCR4C = 0; \
TCCR4D = (1<<WGM40); \
TCCR4E = 0; \
TC4H = pwmval >> 8; \
OCR4C = pwmval; \
TC4H = (pwmval / 3) >> 8; \
OCR4A = (pwmval / 3) & 255; \
})
#define TIMER_CONFIG_NORMAL() ({ \
TCCR4A = 0; \
TCCR4B = _BV(CS40); \
TCCR4C = 0; \
TCCR4D = 0; \
TCCR4E = 0; \
TC4H = (SYSCLOCK * USECPERTICK / 1000000) >> 8; \
OCR4C = (SYSCLOCK * USECPERTICK / 1000000) & 255; \
TC4H = 0; \
TCNT4 = 0; \
})
#if defined(CORE_OC4A_PIN)
#define TIMER_PWM_PIN CORE_OC4A_PIN /* Teensy */
#elif defined(__AVR_ATmega32U4__)
#define TIMER_PWM_PIN 13 /* Leonardo */
#else
#error "Please add OC4A pin number here\n"
#endif
// defines for timer4 (16 bits)
#elif defined(IR_USE_TIMER4)
#define TIMER_RESET
#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1))
#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1)))
#define TIMER_ENABLE_INTR (TIMSK4 = _BV(OCIE4A))
#define TIMER_DISABLE_INTR (TIMSK4 = 0)
#define TIMER_INTR_NAME TIMER4_COMPA_vect
#define TIMER_CONFIG_KHZ(val) ({ \
const uint16_t pwmval = SYSCLOCK / 2000 / (val); \
TCCR4A = _BV(WGM41); \
TCCR4B = _BV(WGM43) | _BV(CS40); \
ICR4 = pwmval; \
OCR4A = pwmval / 3; \
})
#define TIMER_CONFIG_NORMAL() ({ \
TCCR4A = 0; \
TCCR4B = _BV(WGM42) | _BV(CS40); \
OCR4A = SYSCLOCK * USECPERTICK / 1000000; \
TCNT4 = 0; \
})
#if defined(CORE_OC4A_PIN)
#define TIMER_PWM_PIN CORE_OC4A_PIN
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN 6 /* Arduino Mega */
#else
#error "Please add OC4A pin number here\n"
#endif
// defines for timer5 (16 bits)
#elif defined(IR_USE_TIMER5)
#define TIMER_RESET
#define TIMER_ENABLE_PWM (TCCR5A |= _BV(COM5A1))
#define TIMER_DISABLE_PWM (TCCR5A &= ~(_BV(COM5A1)))
#define TIMER_ENABLE_INTR (TIMSK5 = _BV(OCIE5A))
#define TIMER_DISABLE_INTR (TIMSK5 = 0)
#define TIMER_INTR_NAME TIMER5_COMPA_vect
#define TIMER_CONFIG_KHZ(val) ({ \
const uint16_t pwmval = SYSCLOCK / 2000 / (val); \
TCCR5A = _BV(WGM51); \
TCCR5B = _BV(WGM53) | _BV(CS50); \
ICR5 = pwmval; \
OCR5A = pwmval / 3; \
})
#define TIMER_CONFIG_NORMAL() ({ \
TCCR5A = 0; \
TCCR5B = _BV(WGM52) | _BV(CS50); \
OCR5A = SYSCLOCK * USECPERTICK / 1000000; \
TCNT5 = 0; \
})
#if defined(CORE_OC5A_PIN)
#define TIMER_PWM_PIN CORE_OC5A_PIN
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN 46 /* Arduino Mega */
#else
#error "Please add OC5A pin number here\n"
#endif
#else // unknown timer
#error "Internal code configuration error, no known IR_USE_TIMER# defined\n"
#endif
// defines for blinking the LED
#if defined(CORE_LED0_PIN)
#define BLINKLED CORE_LED0_PIN
#define BLINKLED_ON() (digitalWrite(CORE_LED0_PIN, HIGH))
#define BLINKLED_OFF() (digitalWrite(CORE_LED0_PIN, LOW))
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define BLINKLED 13
#define BLINKLED_ON() (PORTB |= B10000000)
#define BLINKLED_OFF() (PORTB &= B01111111)
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define BLINKLED 0
#define BLINKLED_ON() (PORTD |= B00000001)
#define BLINKLED_OFF() (PORTD &= B11111110)
#else
#define BLINKLED 13
#define BLINKLED_ON() (PORTB |= B00100000)
#define BLINKLED_OFF() (PORTB &= B11011111)
#endif
#endif
+458
View File
@@ -0,0 +1,458 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. 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 not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the 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
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
@@ -0,0 +1,167 @@
/*
* IRrecord: record and play back IR signals as a minimal
* An IR detector/demodulator must be connected to the input RECV_PIN.
* An IR LED must be connected to the output PWM pin 3.
* A button must be connected to the input BUTTON_PIN; this is the
* send button.
* A visible LED can be connected to STATUS_PIN to provide status.
*
* The logic is:
* If the button is pressed, send the IR code.
* If an IR code is received, record it.
*
* Version 0.11 September, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
int RECV_PIN = 11;
int BUTTON_PIN = 12;
int STATUS_PIN = 13;
IRrecv irrecv(RECV_PIN);
IRsend irsend;
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
pinMode(BUTTON_PIN, INPUT);
pinMode(STATUS_PIN, OUTPUT);
}
// Storage for the recorded code
int codeType = -1; // The type of code
unsigned long codeValue; // The code value if not raw
unsigned int rawCodes[RAWBUF]; // The durations if raw
int codeLen; // The length of the code
int toggle = 0; // The RC5/6 toggle state
// Stores the code for later playback
// Most of this code is just logging
void storeCode(decode_results *results) {
codeType = results->decode_type;
int count = results->rawlen;
if (codeType == UNKNOWN) {
Serial.println("Received unknown code, saving as raw");
codeLen = results->rawlen - 1;
// To store raw codes:
// Drop first value (gap)
// Convert from ticks to microseconds
// Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
for (int i = 1; i <= codeLen; i++) {
if (i % 2) {
// Mark
rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS;
Serial.print(" m");
}
else {
// Space
rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS;
Serial.print(" s");
}
Serial.print(rawCodes[i - 1], DEC);
}
Serial.println("");
}
else {
if (codeType == NEC) {
Serial.print("Received NEC: ");
if (results->value == REPEAT) {
// Don't record a NEC repeat value as that's useless.
Serial.println("repeat; ignoring.");
return;
}
}
else if (codeType == SONY) {
Serial.print("Received SONY: ");
}
else if (codeType == RC5) {
Serial.print("Received RC5: ");
}
else if (codeType == RC6) {
Serial.print("Received RC6: ");
}
else {
Serial.print("Unexpected codeType ");
Serial.print(codeType, DEC);
Serial.println("");
}
Serial.println(results->value, HEX);
codeValue = results->value;
codeLen = results->bits;
}
}
void sendCode(int repeat) {
if (codeType == NEC) {
if (repeat) {
irsend.sendNEC(REPEAT, codeLen);
Serial.println("Sent NEC repeat");
}
else {
irsend.sendNEC(codeValue, codeLen);
Serial.print("Sent NEC ");
Serial.println(codeValue, HEX);
}
}
else if (codeType == SONY) {
irsend.sendSony(codeValue, codeLen);
Serial.print("Sent Sony ");
Serial.println(codeValue, HEX);
}
else if (codeType == RC5 || codeType == RC6) {
if (!repeat) {
// Flip the toggle bit for a new button press
toggle = 1 - toggle;
}
// Put the toggle bit into the code to send
codeValue = codeValue & ~(1 << (codeLen - 1));
codeValue = codeValue | (toggle << (codeLen - 1));
if (codeType == RC5) {
Serial.print("Sent RC5 ");
Serial.println(codeValue, HEX);
irsend.sendRC5(codeValue, codeLen);
}
else {
irsend.sendRC6(codeValue, codeLen);
Serial.print("Sent RC6 ");
Serial.println(codeValue, HEX);
}
}
else if (codeType == UNKNOWN /* i.e. raw */) {
// Assume 38 KHz
irsend.sendRaw(rawCodes, codeLen, 38);
Serial.println("Sent raw");
}
}
int lastButtonState;
void loop() {
// If button pressed, send the code.
int buttonState = digitalRead(BUTTON_PIN);
if (lastButtonState == HIGH && buttonState == LOW) {
Serial.println("Released");
irrecv.enableIRIn(); // Re-enable receiver
}
if (buttonState) {
Serial.println("Pressed, sending");
digitalWrite(STATUS_PIN, HIGH);
sendCode(lastButtonState == buttonState);
digitalWrite(STATUS_PIN, LOW);
delay(50); // Wait a bit between retransmissions
}
else if (irrecv.decode(&results)) {
digitalWrite(STATUS_PIN, HIGH);
storeCode(&results);
irrecv.resume(); // resume receiver
digitalWrite(STATUS_PIN, LOW);
}
lastButtonState = buttonState;
}
@@ -0,0 +1,28 @@
/*
* IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
}
@@ -0,0 +1,81 @@
/*
* IRremote: IRrecvDump - dump details of IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
*/
#include <IRremote.h>
int RECV_PIN = 8;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(115200);
irrecv.enableIRIn(); // Start the receiver
}
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
// void * to work around compiler issue
//void dump(void *v) {
// decode_results *results = (decode_results *)v
void dump(decode_results *results) {
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.print("Unknown encoding: ");
}
else if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
else if (results->decode_type == PANASONIC) {
Serial.print("Decoded PANASONIC - Address: ");
Serial.print(results->panasonicAddress,HEX);
Serial.print(" Value: ");
}
else if (results->decode_type == JVC) {
Serial.print("Decoded JVC: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 0; i < count; i++) {
if ((i % 2) == 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println("");
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
dump(&results);
irrecv.resume(); // Receive the next value
}
}
@@ -0,0 +1,85 @@
/*
* IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
int RECV_PIN = 11;
int RELAY_PIN = 4;
IRrecv irrecv(RECV_PIN);
decode_results results;
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
// void * to work around compiler issue
//void dump(void *v) {
// decode_results *results = (decode_results *)v
void dump(decode_results *results) {
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.println("Could not decode message");
}
else {
if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
}
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 0; i < count; i++) {
if ((i % 2) == 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println("");
}
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
int on = 0;
unsigned long last = millis();
void loop() {
if (irrecv.decode(&results)) {
// If it's been at least 1/4 second since the last
// IR received, toggle the relay
if (millis() - last > 250) {
on = !on;
digitalWrite(RELAY_PIN, on ? HIGH : LOW);
digitalWrite(13, on ? HIGH : LOW);
dump(&results);
}
last = millis();
irrecv.resume(); // Receive the next value
}
}
@@ -0,0 +1,25 @@
/*
* IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to Arduino PWM pin 3.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
IRsend irsend;
void setup()
{
Serial.begin(9600);
}
void loop() {
if (Serial.read() != -1) {
for (int i = 0; i < 3; i++) {
irsend.sendSony(0xa90, 12); // Sony TV power code
delay(40);
}
}
}
@@ -0,0 +1,190 @@
/*
* IRremote: IRtest unittest
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*
* Note: to run these tests, edit IRremote/IRremote.h to add "#define TEST"
* You must then recompile the library by removing IRremote.o and restarting
* the arduino IDE.
*/
#include <IRremote.h>
#include <IRremoteInt.h>
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
// void * to work around compiler issue
//void dump(void *v) {
// decode_results *results = (decode_results *)v
void dump(decode_results *results) {
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.println("Could not decode message");
}
else {
if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
}
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 0; i < count; i++) {
if ((i % 2) == 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println("");
}
IRrecv irrecv(0);
decode_results results;
class IRsendDummy :
public IRsend
{
public:
// For testing, just log the marks/spaces
#define SENDLOG_LEN 128
int sendlog[SENDLOG_LEN];
int sendlogcnt;
IRsendDummy() :
IRsend() {
}
void reset() {
sendlogcnt = 0;
}
void mark(int time) {
sendlog[sendlogcnt] = time;
if (sendlogcnt < SENDLOG_LEN) sendlogcnt++;
}
void space(int time) {
sendlog[sendlogcnt] = -time;
if (sendlogcnt < SENDLOG_LEN) sendlogcnt++;
}
// Copies the dummy buf into the interrupt buf
void useDummyBuf() {
int last = SPACE;
irparams.rcvstate = STATE_STOP;
irparams.rawlen = 1; // Skip the gap
for (int i = 0 ; i < sendlogcnt; i++) {
if (sendlog[i] < 0) {
if (last == MARK) {
// New space
irparams.rawbuf[irparams.rawlen++] = (-sendlog[i] - MARK_EXCESS) / USECPERTICK;
last = SPACE;
}
else {
// More space
irparams.rawbuf[irparams.rawlen - 1] += -sendlog[i] / USECPERTICK;
}
}
else if (sendlog[i] > 0) {
if (last == SPACE) {
// New mark
irparams.rawbuf[irparams.rawlen++] = (sendlog[i] + MARK_EXCESS) / USECPERTICK;
last = MARK;
}
else {
// More mark
irparams.rawbuf[irparams.rawlen - 1] += sendlog[i] / USECPERTICK;
}
}
}
if (irparams.rawlen % 2) {
irparams.rawlen--; // Remove trailing space
}
}
};
IRsendDummy irsenddummy;
void verify(unsigned long val, int bits, int type) {
irsenddummy.useDummyBuf();
irrecv.decode(&results);
Serial.print("Testing ");
Serial.print(val, HEX);
if (results.value == val && results.bits == bits && results.decode_type == type) {
Serial.println(": OK");
}
else {
Serial.println(": Error");
dump(&results);
}
}
void testNEC(unsigned long val, int bits) {
irsenddummy.reset();
irsenddummy.sendNEC(val, bits);
verify(val, bits, NEC);
}
void testSony(unsigned long val, int bits) {
irsenddummy.reset();
irsenddummy.sendSony(val, bits);
verify(val, bits, SONY);
}
void testRC5(unsigned long val, int bits) {
irsenddummy.reset();
irsenddummy.sendRC5(val, bits);
verify(val, bits, RC5);
}
void testRC6(unsigned long val, int bits) {
irsenddummy.reset();
irsenddummy.sendRC6(val, bits);
verify(val, bits, RC6);
}
void test() {
Serial.println("NEC tests");
testNEC(0x00000000, 32);
testNEC(0xffffffff, 32);
testNEC(0xaaaaaaaa, 32);
testNEC(0x55555555, 32);
testNEC(0x12345678, 32);
Serial.println("Sony tests");
testSony(0xfff, 12);
testSony(0x000, 12);
testSony(0xaaa, 12);
testSony(0x555, 12);
testSony(0x123, 12);
Serial.println("RC5 tests");
testRC5(0xfff, 12);
testRC5(0x000, 12);
testRC5(0xaaa, 12);
testRC5(0x555, 12);
testRC5(0x123, 12);
Serial.println("RC6 tests");
testRC6(0xfffff, 20);
testRC6(0x00000, 20);
testRC6(0xaaaaa, 20);
testRC6(0x55555, 20);
testRC6(0x12345, 20);
}
void setup()
{
Serial.begin(9600);
test();
}
void loop() {
}
@@ -0,0 +1,290 @@
/*
* Test send/receive functions of IRremote, using a pair of Arduinos.
*
* Arduino #1 should have an IR LED connected to the send pin (3).
* Arduino #2 should have an IR detector/demodulator connected to the
* receive pin (11) and a visible LED connected to pin 3.
*
* The cycle:
* Arduino #1 will wait 2 seconds, then run through the tests.
* It repeats this forever.
* Arduino #2 will wait for at least one second of no signal
* (to synchronize with #1). It will then wait for the same test
* signals. It will log all the status to the serial port. It will
* also indicate status through the LED, which will flash each time a test
* is completed. If there is an error, it will light up for 5 seconds.
*
* The test passes if the LED flashes 19 times, pauses, and then repeats.
* The test fails if the LED lights for 5 seconds.
*
* The test software automatically decides which board is the sender and which is
* the receiver by looking for an input on the send pin, which will indicate
* the sender. You should hook the serial port to the receiver for debugging.
*
* Copyright 2010 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
int RECV_PIN = 11;
int LED_PIN = 3;
IRrecv irrecv(RECV_PIN);
IRsend irsend;
decode_results results;
#define RECEIVER 1
#define SENDER 2
#define ERROR 3
int mode;
void setup()
{
Serial.begin(9600);
// Check RECV_PIN to decide if we're RECEIVER or SENDER
if (digitalRead(RECV_PIN) == HIGH) {
mode = RECEIVER;
irrecv.enableIRIn();
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
Serial.println("Receiver mode");
}
else {
mode = SENDER;
Serial.println("Sender mode");
}
}
// Wait for the gap between tests, to synchronize with
// the sender.
// Specifically, wait for a signal followed by a gap of at last gap ms.
void waitForGap(int gap) {
Serial.println("Waiting for gap");
while (1) {
while (digitalRead(RECV_PIN) == LOW) {
}
unsigned long time = millis();
while (digitalRead(RECV_PIN) == HIGH) {
if (millis() - time > gap) {
return;
}
}
}
}
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
void dump(decode_results *results) {
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.println("Could not decode message");
}
else {
if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
}
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 0; i < count; i++) {
if ((i % 2) == 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println("");
}
// Test send or receive.
// If mode is SENDER, send a code of the specified type, value, and bits
// If mode is RECEIVER, receive a code and verify that it is of the
// specified type, value, and bits. For success, the LED is flashed;
// for failure, the mode is set to ERROR.
// The motivation behind this method is that the sender and the receiver
// can do the same test calls, and the mode variable indicates whether
// to send or receive.
void test(char *label, int type, unsigned long value, int bits) {
if (mode == SENDER) {
Serial.println(label);
if (type == NEC) {
irsend.sendNEC(value, bits);
}
else if (type == SONY) {
irsend.sendSony(value, bits);
}
else if (type == RC5) {
irsend.sendRC5(value, bits);
}
else if (type == RC6) {
irsend.sendRC6(value, bits);
}
else {
Serial.print(label);
Serial.println("Bad type!");
}
delay(200);
}
else if (mode == RECEIVER) {
irrecv.resume(); // Receive the next value
unsigned long max_time = millis() + 30000;
Serial.print(label);
// Wait for decode or timeout
while (!irrecv.decode(&results)) {
if (millis() > max_time) {
Serial.println("Timeout receiving data");
mode = ERROR;
return;
}
}
if (type == results.decode_type && value == results.value && bits == results.bits) {
Serial.println (": OK");
digitalWrite(LED_PIN, HIGH);
delay(20);
digitalWrite(LED_PIN, LOW);
}
else {
Serial.println(": BAD");
dump(&results);
mode = ERROR;
}
}
}
// Test raw send or receive. This is similar to the test method,
// except it send/receives raw data.
void testRaw(char *label, unsigned int *rawbuf, int rawlen) {
if (mode == SENDER) {
Serial.println(label);
irsend.sendRaw(rawbuf, rawlen, 38 /* kHz */);
delay(200);
}
else if (mode == RECEIVER ) {
irrecv.resume(); // Receive the next value
unsigned long max_time = millis() + 30000;
Serial.print(label);
// Wait for decode or timeout
while (!irrecv.decode(&results)) {
if (millis() > max_time) {
Serial.println("Timeout receiving data");
mode = ERROR;
return;
}
}
// Received length has extra first element for gap
if (rawlen != results.rawlen - 1) {
Serial.print("Bad raw length ");
Serial.println(results.rawlen, DEC);
mode = ERROR;
return;
}
for (int i = 0; i < rawlen; i++) {
long got = results.rawbuf[i+1] * USECPERTICK;
// Adjust for extra duration of marks
if (i % 2 == 0) {
got -= MARK_EXCESS;
}
else {
got += MARK_EXCESS;
}
// See if close enough, within 25%
if (rawbuf[i] * 1.25 < got || got * 1.25 < rawbuf[i]) {
Serial.println(": BAD");
dump(&results);
mode = ERROR;
return;
}
}
Serial.println (": OK");
digitalWrite(LED_PIN, HIGH);
delay(20);
digitalWrite(LED_PIN, LOW);
}
}
// This is the raw data corresponding to NEC 0x12345678
unsigned int sendbuf[] = { /* NEC format */
9000, 4500,
560, 560, 560, 560, 560, 560, 560, 1690, /* 1 */
560, 560, 560, 560, 560, 1690, 560, 560, /* 2 */
560, 560, 560, 560, 560, 1690, 560, 1690, /* 3 */
560, 560, 560, 1690, 560, 560, 560, 560, /* 4 */
560, 560, 560, 1690, 560, 560, 560, 1690, /* 5 */
560, 560, 560, 1690, 560, 1690, 560, 560, /* 6 */
560, 560, 560, 1690, 560, 1690, 560, 1690, /* 7 */
560, 1690, 560, 560, 560, 560, 560, 560, /* 8 */
560};
void loop() {
if (mode == SENDER) {
delay(2000); // Delay for more than gap to give receiver a better chance to sync.
}
else if (mode == RECEIVER) {
waitForGap(1000);
}
else if (mode == ERROR) {
// Light up for 5 seconds for error
digitalWrite(LED_PIN, HIGH);
delay(5000);
digitalWrite(LED_PIN, LOW);
mode = RECEIVER; // Try again
return;
}
// The test suite.
test("SONY1", SONY, 0x123, 12);
test("SONY2", SONY, 0x000, 12);
test("SONY3", SONY, 0xfff, 12);
test("SONY4", SONY, 0x12345, 20);
test("SONY5", SONY, 0x00000, 20);
test("SONY6", SONY, 0xfffff, 20);
test("NEC1", NEC, 0x12345678, 32);
test("NEC2", NEC, 0x00000000, 32);
test("NEC3", NEC, 0xffffffff, 32);
test("NEC4", NEC, REPEAT, 32);
test("RC51", RC5, 0x12345678, 32);
test("RC52", RC5, 0x0, 32);
test("RC53", RC5, 0xffffffff, 32);
test("RC61", RC6, 0x12345678, 32);
test("RC62", RC6, 0x0, 32);
test("RC63", RC6, 0xffffffff, 32);
// Tests of raw sending and receiving.
// First test sending raw and receiving raw.
// Then test sending raw and receiving decoded NEC
// Then test sending NEC and receiving raw
testRaw("RAW1", sendbuf, 67);
if (mode == SENDER) {
testRaw("RAW2", sendbuf, 67);
test("RAW3", NEC, 0x12345678, 32);
}
else {
test("RAW2", NEC, 0x12345678, 32);
testRaw("RAW3", sendbuf, 67);
}
}
@@ -0,0 +1,29 @@
/*
* IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to Arduino PWM pin 3.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
*/
#include <IRremote.h>
#define PanasonicAddress 0x4004 // Panasonic address (Pre data)
#define PanasonicPower 0x100BCBD // Panasonic Power button
#define JVCPower 0xC5E8
IRsend irsend;
void setup()
{
}
void loop() {
irsend.sendPanasonic(PanasonicAddress,PanasonicPower); // This should turn your TV on and off
irsend.sendJVC(JVCPower, 16,0); // hex value, 16 bits, no repeat
delayMicroseconds(50); // see http://www.sbprojects.com/knowledge/ir/jvc.php for information
irsend.sendJVC(JVCPower, 16,1); // hex value, 16 bits, repeat
delayMicroseconds(50);
}
+50
View File
@@ -0,0 +1,50 @@
#######################################
# Syntax Coloring Map For IRremote
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
decode_results KEYWORD1
IRrecv KEYWORD1
IRsend KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
blink13 KEYWORD2
decode KEYWORD2
enableIRIn KEYWORD2
resume KEYWORD2
enableIROut KEYWORD2
sendNEC KEYWORD2
sendSony KEYWORD2
sendSanyo KEYWORD2
sendMitsubishi KEYWORD2
sendRaw KEYWORD2
sendRC5 KEYWORD2
sendRC6 KEYWORD2
sendDISH KEYWORD2
sendSharp KEYWORD2
sendPanasonic KEYWORD2
sendJVC KEYWORD2
#
#######################################
# Constants (LITERAL1)
#######################################
NEC LITERAL1
SONY LITERAL1
SANYO LITERAL1
MITSUBISHI LITERAL1
RC5 LITERAL1
RC6 LITERAL1
DISH LITERAL1
SHARP LITERAL1
PANASONIC LITERAL1
JVC LITERAL1
UNKNOWN LITERAL1
REPEAT LITERAL1
+14
View File
@@ -0,0 +1,14 @@
This is the IRremote library for the Arduino.
To download from github (http://github.com/shirriff/Arduino-IRremote), click on the "Downloads" link in the upper right, click "Download as zip", and get a zip file. Unzip it and rename the directory shirriff-Arduino-IRremote-nnn to IRremote
To install, move the downloaded IRremote directory to:
arduino-1.x/libraries/IRremote
where arduino-1.x is your Arduino installation directory
After installation you should have files such as:
arduino-1.x/libraries/IRremote/IRremote.cpp
For details on the library see the Wiki on github or the blog post http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html
Copyright 2009-2012 Ken Shirriff
+107
View File
@@ -0,0 +1,107 @@
/*
* IntereruptChain library v1.3.0 (20130601)
*
* Copyright 2011-2013 by Randy Simons http://randysimons.nl/
*
* License: GPLv3. See license.txt
*/
#include <InterruptChain.h>
void InterruptChainLink::init(InterruptCallback callbackIn, InterruptChainLink *nextIn) {
callback = callbackIn;
next = nextIn;
}
InterruptChainLink *InterruptChain::chain[MAX_INTERRUPTS] = {NULL};
byte InterruptChain::mode[MAX_INTERRUPTS] = {CHANGE};
void InterruptChain::setMode(byte interruptNr, byte modeIn) {
mode[interruptNr] = modeIn;
}
void InterruptChain::addInterruptCallback(byte interruptNr, InterruptCallback callback) {
InterruptChainLink *prevLink = chain[interruptNr]; // Note: the chain-array is NULL initialized, so the first time prevLink is indeed NULL
chain[interruptNr] = (InterruptChainLink *) malloc(sizeof(InterruptChainLink)); // malloc instead of new, due to the lack of new / delete support in AVR-libc
chain[interruptNr]->init(callback, prevLink);
enable(interruptNr);
}
void InterruptChain::enable(byte interruptNr) {
switch (interruptNr) {
case 0:
attachInterrupt(0, InterruptChain::processInterrupt0, mode[0]);
break;
case 1:
attachInterrupt(1, InterruptChain::processInterrupt1, mode[1]);
break;
case 2:
attachInterrupt(2, InterruptChain::processInterrupt2, mode[2]);
break;
case 3:
attachInterrupt(3, InterruptChain::processInterrupt3, mode[3]);
break;
case 4:
attachInterrupt(4, InterruptChain::processInterrupt4, mode[4]);
break;
case 5:
attachInterrupt(5, InterruptChain::processInterrupt5, mode[5]);
break;
}
}
void InterruptChain::disable(byte interruptNr) {
detachInterrupt(interruptNr);
}
void InterruptChain::processInterrupt0() {
InterruptChainLink *current = chain[0];
while(current) {
(current->callback)();
current = current->next;
}
}
void InterruptChain::processInterrupt1() {
InterruptChainLink *current = chain[1];
while(current) {
(current->callback)();
current = current->next;
}
}
void InterruptChain::processInterrupt2() {
InterruptChainLink *current = chain[2];
while(current) {
(current->callback)();
current = current->next;
}
}
void InterruptChain::processInterrupt3() {
InterruptChainLink *current = chain[3];
while(current) {
(current->callback)();
current = current->next;
}
}
void InterruptChain::processInterrupt4() {
InterruptChainLink *current = chain[4];
while(current) {
(current->callback)();
current = current->next;
}
}
void InterruptChain::processInterrupt5() {
InterruptChainLink *current = chain[5];
while(current) {
(current->callback)();
current = current->next;
}
}
+90
View File
@@ -0,0 +1,90 @@
/*
* IntereruptChain library v1.3.0 (20130601)
*
* Copyright 2011-2013 by Randy Simons http://randysimons.nl/
*
* License: GPLv3. See license.txt
*/
#ifndef InterruptChain_h
#define InterruptChain_h
#include <Arduino.h>
// Arduino Mega has 6 interrupts. For smaller Arduinos and / or to save a few bytes memory you can lower it to 2 or even 1. Don't go higher than 6 tho.
#define MAX_INTERRUPTS 6
typedef void (*InterruptCallback)();
/**
* For internal use
*/
class InterruptChainLink {
public:
InterruptChainLink *next;
InterruptCallback callback;
void init(InterruptCallback callbackIn, InterruptChainLink *nextIn);
void processInterrupt();
};
class InterruptChain {
public:
/**
* Add an interrupt handler on interrupt pin interruptNr. The callback is of the same type as
* Arduino's standard attachInterrupt().
*
* So, instead of attachInterrupt(0, callback, CHANGE); you can use
* InterruptChain::addInterruptCallback(0, callback);
*
* You can add more than one callback to a single interrupt! The callbacks are called in
* the reversed order in which they were added.
* addInterruptCallback will also call this.enable(interruptNr).
*
*/
static void addInterruptCallback(byte interruptNr, InterruptCallback callbackIn);
/**
* Enables interrupt handling by InterruptChain for given interrupt pin. Note that this
* is different from Arduino's interrupts(), which will enable _all_ interrupts on the CPU.
*
* @param interruptNr The interrupt pin number for which to enable handling.
*/
static void enable(byte interruptNr);
/**
* Disables interrupt handling by InterruptChain for given interrupt pin. Note that this
* is different from Arduino's noInterrupts(), which will disable _all_ interrupts on the CPU.
*
* @param interruptNr The interrupt pin number for which to disable handling.
*/
static void disable(byte interruptNr);
/**
* Set the interrupt mode for given interrupt pin. By default the interrupt mode is CHANGE.
* If you need this changed, best to call setMode before adding interrupt handlers.
*
* @param interruptNr Interrupt to set
* @param modeIn LOW, CHANGE, RISING or FALLING
*/
static void setMode(byte interruptNr, byte modeIn);
private:
static InterruptChainLink *chain[MAX_INTERRUPTS];
static byte mode[MAX_INTERRUPTS];
static void processInterrupt0();
static void processInterrupt1();
static void processInterrupt2();
static void processInterrupt3();
static void processInterrupt4();
static void processInterrupt5();
};
#endif
+36
View File
@@ -0,0 +1,36 @@
InterruptChain library v1.3.0 (20130601) for Arduino 1.0
Made by Randy Simons http://randysimons.nl/
This library allows for daisychaining the interrupts, i.e. you can attach
more than one interrupt handler to a single interrupt.
See the examples for usage. See InterruptChainLib.h for details!
License: GPLv3. See ./InterruptChain/license.txt
Latest source and wiki: https://bitbucket.org/fuzzillogic/433mhzforarduino
Installation of library:
- Make sure Arduino is closed
- Copy the directory InterruptChain to the Arduino library directory (usually
<Sketchbook directory>/libraries/)
See http://arduino.cc/en/Guide/Libraries for detailed instructions.
Examples are provided.
Changelog:
InterruptChain library v1.3.0 (20130601) for Arduino 1.0
- Dropped support for Arduino pre-1.0
- Doesn't use recursion internally, and fewer function calls. This should save
some extra bytes in RAM, at the cost of moderately increased Flash usage.
InterruptChain library v1.2.0 (20120213) for Arduino 0022/1.0
- Support for Arduino 1.0.
InterruptChain library v1.1.0 (20110921) for Arduino 0022
- Added enable, disable. Expanded setMode.
InterruptChain library v1.0.0 (20110919) for Arduino 0022
- First release
@@ -0,0 +1,52 @@
/**
* Demo of a chained interrupt handler.
*
* This sketch duplicates the signal on digital pin 2 to digital pin 13 (the LED) and
* echos the value on the serial line. (so open up the serial console @ 9600 baud)
*
* Hardware setup for this example:
* - Attach a switch from ground to pin 2, or use a wire from ground to pin 2.
*/
#include <InterruptChain.h>
void echoLed() {
digitalWrite(13, digitalRead(2));
}
void echoSerial() {
// Within interrupts handlers, interrupts are disabled.
// However, Serial doesn't seem to like it when interrupts are disabled,
// causing hangs when the transmit buffer is full.
// First, disable the interrupt chain, to prevent race conditions.
// Then enable interrupts.
InterruptChain::disable(0);
interrupts();
if (digitalRead(2)) {
Serial.println("The signal is HIGH!");
} else {
Serial.println("The signal is LOW!");
}
// Disabling interrupts before enabling the interrupt chain.
noInterrupts();
InterruptChain::enable(0);
}
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
// Enable internal pull-up on pin 2.
// This is merely for this demo; it is not required for interrupt handling.
digitalWrite(2, HIGH);
// Links two callback to interrupt 0 with default mode CHANGE.
InterruptChain::addInterruptCallback(0, echoLed);
InterruptChain::addInterruptCallback(0, echoSerial);
}
void loop() {
// You can do other stuff here!
}
@@ -0,0 +1,109 @@
/*
* This sketch demonstrates how to use InterruptChain to receive and
* decode remote switches (old and new) and remote sensors.
*
* Basically, this sketch combines the features of the ShowReceivedCode
* and ShowReceivedCodeNewKaku examples of RemoteSwitch and the
* ThermoHygroReceiver of RemoteSensor all at the same time!
*
* After uploading, enable the serial monitor at 115200 baud.
* When you press buttons on a 433MHz remote control, as supported by
* RemoteSwitch or NewRemoteSwitch, the code will be echoed.
* At the same time, if data of a remote thermo/hygro-sensor is
* received, as supported by RemoteSensor, it will be echoed as well.
*
* Setup:
* - connect a 433MHz receiver on digital pin 2.
*/
#include <RemoteReceiver.h>
#include <NewRemoteReceiver.h>
#include <SensorReceiver.h>
#include <InterruptChain.h>
void setup() {
Serial.begin(115200);
// Interrupt -1 to indicate you will call the interrupt handler with InterruptChain
RemoteReceiver::init(-1, 2, showOldCode);
// Again, interrupt -1 to indicate you will call the interrupt handler with InterruptChain
NewRemoteReceiver::init(-1, 2, showNewCode);
// And once more, interrupt -1 to indicate you will call the interrupt handler with InterruptChain
SensorReceiver::init(-1, showTempHumi);
// On interrupt, call the interrupt handlers of remote and sensor receivers
InterruptChain::addInterruptCallback(0, RemoteReceiver::interruptHandler);
InterruptChain::addInterruptCallback(0, NewRemoteReceiver::interruptHandler);
InterruptChain::addInterruptCallback(0, SensorReceiver::interruptHandler);
}
void loop() {
// You can do other stuff here!
}
// shows the received code sent from an old-style remote switch
void showOldCode(unsigned long receivedCode, unsigned int period) {
// Print the received code.
Serial.print("Code: ");
Serial.print(receivedCode);
Serial.print(", period: ");
Serial.print(period);
Serial.println("us.");
}
// Shows the received code sent from an new-style remote switch
void showNewCode(NewRemoteCode receivedCode) {
// Print the received code.
Serial.print("Addr ");
Serial.print(receivedCode.address);
if (receivedCode.groupBit) {
Serial.print(" group");
} else {
Serial.print(" unit ");
Serial.print(receivedCode.unit);
}
switch (receivedCode.switchType) {
case NewRemoteCode::off:
Serial.print(" off");
break;
case NewRemoteCode::on:
Serial.print(" on");
break;
case NewRemoteCode::dim:
Serial.print(" dim level ");
Serial.print(receivedCode.dimLevel);
break;
case NewRemoteCode::on_with_dim:
Serial.print(" on with dim level ");
Serial.print(receivedCode.dimLevel);
break;
}
Serial.print(", period: ");
Serial.print(receivedCode.period);
Serial.println("us.");
}
// Shows the received sensor data
void showTempHumi(byte *data) {
// is data a ThermoHygro-device?
if ((data[3] & 0x1f) == 0x1e) {
// Yes!
byte channel, randomId;
int temp;
byte humidity;
// Decode the data
SensorReceiver::decodeThermoHygro(data, channel, randomId, temp, humidity);
// Print temperature. Note: temp is 10x the actual temperature!
Serial.print("Temperature: ");
Serial.print(temp / 10); // units
Serial.print('.');
Serial.println(temp % 10); // decimal
}
}
+5
View File
@@ -0,0 +1,5 @@
InterruptChain KEYWORD1
addInterruptCallback KEYWORD2
setMode KEYWORD2
enable KEYWORD2
disable KEYWORD2
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+206
View File
@@ -0,0 +1,206 @@
/*
MsTimer2.h - Using timer2 with 1ms resolution
Javier Valencia <javiervalencia80@gmail.com>
History:
29/Dec/11 - V0.6 added support for ATmega32u4, AT90USB646, AT90USB1286 (paul@pjrc.com)
some improvements added by Bill Perry
note: uses timer4 on Atmega32u4
29/May/09 - V0.5 added support for Atmega1280 (thanks to Manuel Negri)
19/Mar/09 - V0.4 added support for ATmega328P (thanks to Jerome Despatis)
11/Jun/08 - V0.3
changes to allow working with different CPU frequencies
added support for ATMega128 (using timer2)
compatible with ATMega48/88/168/8
10/May/08 - V0.2 added some security tests and volatile keywords
9/May/08 - V0.1 released working on ATMEGA168 only
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 <MsTimer2.h>
unsigned long MsTimer2::msecs;
void (*MsTimer2::func)();
volatile unsigned long MsTimer2::count;
volatile char MsTimer2::overflowing;
volatile unsigned int MsTimer2::tcnt2;
void MsTimer2::set(unsigned long ms, void (*f)()) {
float prescaler = 0.0;
if (ms == 0)
msecs = 1;
else
msecs = ms;
func = f;
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TIMSK2 &= ~(1<<TOIE2);
TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
TCCR2B &= ~(1<<WGM22);
ASSR &= ~(1<<AS2);
TIMSK2 &= ~(1<<OCIE2A);
if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) { // prescaler set to 64
TCCR2B |= (1<<CS22);
TCCR2B &= ~((1<<CS21) | (1<<CS20));
prescaler = 64.0;
} else if (F_CPU < 1000000UL) { // prescaler set to 8
TCCR2B |= (1<<CS21);
TCCR2B &= ~((1<<CS22) | (1<<CS20));
prescaler = 8.0;
} else { // F_CPU > 16Mhz, prescaler set to 128
TCCR2B |= ((1<<CS22) | (1<<CS20));
TCCR2B &= ~(1<<CS21);
prescaler = 128.0;
}
#elif defined (__AVR_ATmega8__)
TIMSK &= ~(1<<TOIE2);
TCCR2 &= ~((1<<WGM21) | (1<<WGM20));
TIMSK &= ~(1<<OCIE2);
ASSR &= ~(1<<AS2);
if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) { // prescaler set to 64
TCCR2 |= (1<<CS22);
TCCR2 &= ~((1<<CS21) | (1<<CS20));
prescaler = 64.0;
} else if (F_CPU < 1000000UL) { // prescaler set to 8
TCCR2 |= (1<<CS21);
TCCR2 &= ~((1<<CS22) | (1<<CS20));
prescaler = 8.0;
} else { // F_CPU > 16Mhz, prescaler set to 128
TCCR2 |= ((1<<CS22) && (1<<CS20));
TCCR2 &= ~(1<<CS21);
prescaler = 128.0;
}
#elif defined (__AVR_ATmega128__)
TIMSK &= ~(1<<TOIE2);
TCCR2 &= ~((1<<WGM21) | (1<<WGM20));
TIMSK &= ~(1<<OCIE2);
if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) { // prescaler set to 64
TCCR2 |= ((1<<CS21) | (1<<CS20));
TCCR2 &= ~(1<<CS22);
prescaler = 64.0;
} else if (F_CPU < 1000000UL) { // prescaler set to 8
TCCR2 |= (1<<CS21);
TCCR2 &= ~((1<<CS22) | (1<<CS20));
prescaler = 8.0;
} else { // F_CPU > 16Mhz, prescaler set to 256
TCCR2 |= (1<<CS22);
TCCR2 &= ~((1<<CS21) | (1<<CS20));
prescaler = 256.0;
}
#elif defined (__AVR_ATmega32U4__)
TCCR4B = 0;
TCCR4A = 0;
TCCR4C = 0;
TCCR4D = 0;
TCCR4E = 0;
if (F_CPU >= 16000000L) {
TCCR4B = (1<<CS43) | (1<<PSR4);
prescaler = 128.0;
} else if (F_CPU >= 8000000L) {
TCCR4B = (1<<CS42) | (1<<CS41) | (1<<CS40) | (1<<PSR4);
prescaler = 64.0;
} else if (F_CPU >= 4000000L) {
TCCR4B = (1<<CS42) | (1<<CS41) | (1<<PSR4);
prescaler = 32.0;
} else if (F_CPU >= 2000000L) {
TCCR4B = (1<<CS42) | (1<<CS40) | (1<<PSR4);
prescaler = 16.0;
} else if (F_CPU >= 1000000L) {
TCCR4B = (1<<CS42) | (1<<PSR4);
prescaler = 8.0;
} else if (F_CPU >= 500000L) {
TCCR4B = (1<<CS41) | (1<<CS40) | (1<<PSR4);
prescaler = 4.0;
} else {
TCCR4B = (1<<CS41) | (1<<PSR4);
prescaler = 2.0;
}
tcnt2 = (int)((float)F_CPU * 0.001 / prescaler) - 1;
OCR4C = tcnt2;
return;
#else
#error Unsupported CPU type
#endif
tcnt2 = 256 - (int)((float)F_CPU * 0.001 / prescaler);
}
void MsTimer2::start() {
count = 0;
overflowing = 0;
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TCNT2 = tcnt2;
TIMSK2 |= (1<<TOIE2);
#elif defined (__AVR_ATmega128__)
TCNT2 = tcnt2;
TIMSK |= (1<<TOIE2);
#elif defined (__AVR_ATmega8__)
TCNT2 = tcnt2;
TIMSK |= (1<<TOIE2);
#elif defined (__AVR_ATmega32U4__)
TIFR4 = (1<<TOV4);
TCNT4 = 0;
TIMSK4 = (1<<TOIE4);
#endif
}
void MsTimer2::stop() {
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TIMSK2 &= ~(1<<TOIE2);
#elif defined (__AVR_ATmega128__)
TIMSK &= ~(1<<TOIE2);
#elif defined (__AVR_ATmega8__)
TIMSK &= ~(1<<TOIE2);
#elif defined (__AVR_ATmega32U4__)
TIMSK4 = 0;
#endif
}
void MsTimer2::_overflow() {
count += 1;
if (count >= msecs && !overflowing) {
overflowing = 1;
count = count - msecs; // subtract ms to catch missed overflows
// set to 0 if you don't want this.
(*func)();
overflowing = 0;
}
}
#if defined (__AVR_ATmega32U4__)
ISR(TIMER4_OVF_vect) {
#else
ISR(TIMER2_OVF_vect) {
#endif
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega48__) || defined (__AVR_ATmega88__) || defined (__AVR_ATmega328P__) || defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
TCNT2 = MsTimer2::tcnt2;
#elif defined (__AVR_ATmega128__)
TCNT2 = MsTimer2::tcnt2;
#elif defined (__AVR_ATmega8__)
TCNT2 = MsTimer2::tcnt2;
#elif defined (__AVR_ATmega32U4__)
// not necessary on 32u4's high speed timer4
#endif
MsTimer2::_overflow();
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef MsTimer2_h
#define MsTimer2_h
#ifdef __AVR__
#include <avr/interrupt.h>
#else
#error MsTimer2 library only works on AVR architecture
#endif
namespace MsTimer2 {
extern unsigned long msecs;
extern void (*func)();
extern volatile unsigned long count;
extern volatile char overflowing;
extern volatile unsigned int tcnt2;
void set(unsigned long ms, void (*f)());
void start();
void stop();
void _overflow();
}
#endif
@@ -0,0 +1,42 @@
char dummyvar; // to get Arduinoi IDE to include core headers properly
/*
MsTimer2 is a small and very easy to use library to interface Timer2 with
humans. It's called MsTimer2 because it "hardcodes" a resolution of 1
millisecond on timer2
For Details see: http://www.arduino.cc/playground/Main/MsTimer2
*/
#include <MsTimer2.h>
// Switch on LED on and off each half second
#if defined(ARDUINO) && ARDUINO >= 100
const int led_pin = LED_BUILTIN; // 1.0 built in LED pin var
#else
#if defined(CORE_LED0_PIN)
const int led_pin = CORE_LED0_PIN; // 3rd party LED pin define
#else
const int led_pin = 13; // default to pin 13
#endif
#endif
void flash()
{
static boolean output = HIGH;
digitalWrite(led_pin, output);
output = !output;
}
void setup()
{
pinMode(led_pin, OUTPUT);
MsTimer2::set(500, flash); // 500ms period
MsTimer2::start();
}
void loop()
{
}
+4
View File
@@ -0,0 +1,4 @@
MsTimer2 KEYWORD1
set KEYWORD2
start KEYWORD2
stop KEYWORD2
+245
View File
@@ -0,0 +1,245 @@
/*
The Sensor Net Arduino library adds a new layer on top of the RF24 library.
It handles radio network routing, relaying and ids.
Created by Henrik Ekblad <henrik.ekblad@gmail.com>
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.
*/
#include "Gateway.h"
Gateway::Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time) : Relay(_cepin, _cspin) {
ledMode = false;
inclusionTime = _inclusion_time;
}
Gateway::Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion, uint8_t _inclusion_time, uint8_t _rx, uint8_t _tx, uint8_t _er) : Relay(_cepin, _cspin) {
ledMode = true;
pinInclusion = _inclusion;
inclusionTime = _inclusion_time;
pinRx = _rx;
pinTx = _tx;
pinEr = _er;
}
void Gateway::begin(uint8_t _radioId) {
radioId = 0;
distance = 0;
inclusionMode = 0;
buttonTriggeredInclusion = false;
countRx = 0;
countTx = 0;
countErr = 0;
if (ledMode) {
// Setup led pins
pinMode(pinRx, OUTPUT);
pinMode(pinTx, OUTPUT);
pinMode(pinEr, OUTPUT);
digitalWrite(pinRx, LOW);
digitalWrite(pinTx, LOW);
digitalWrite(pinEr, LOW);
// 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);
}
// Set baudrate of serial link
Serial.begin(BAUD_RATE);
// Start up the radio library
setupRadio();
RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID);
RF24::startListening();
// Send startup log message on serial
serial(PSTR("0;0;%d;%d;Arduino startup complete.\n"), M_INTERNAL, I_LOG_MESSAGE);
}
boolean Gateway::isLedMode() {
return ledMode;
}
void Gateway::startInclusionInterrupt() {
buttonTriggeredInclusion = true;
}
void Gateway::checkButtonTriggeredInclusion() {
if (buttonTriggeredInclusion) {
// Ok, someone pressed the inclusion button on the gateway
// start inclusion mode for 1 munute.
serial(PSTR("0;0;%d;%d;Inclusion started by button.\n"), M_INTERNAL, I_LOG_MESSAGE);
buttonTriggeredInclusion = false;
setInclusionMode(true);
}
}
void Gateway::checkInclusionFinished() {
if (inclusionMode && millis()-inclusionStartTime>60000L*inclusionTime) {
// inclusionTimeInMinutes minute(s) has passed.. stop inclusion mode
setInclusionMode(false);
}
}
void Gateway::parseAndSend(String inputString) {
boolean ok;
char *str, *p, *value;
int i = 0;
uint16_t sensorRadioId;
uint8_t childId;
uint8_t messageType;
uint8_t type;
// Copy command to char* buffer
inputString.toCharArray(commandBuffer, MAX_RECEIVE_LENGTH);
// Extract command data coming on serial line
for (str = strtok_r(commandBuffer, ";", &p); // split using semicolon
str && i < 5; // loop while str is not null an max 5 times
str = strtok_r(NULL, ";", &p) // get subsequent tokens
) {
switch (i) {
case 0: // Radioid (destination)
sensorRadioId = atoi(str);
break;
case 1: // Childid
childId = atoi(str);
break;
case 2: // Message type
messageType = atoi(str);
break;
case 3: // Data type
type = atoi(str);
break;
case 4: // Variable value
value = str;
break;
}
i++;
}
if (sensorRadioId==GATEWAY_ADDRESS && messageType==M_INTERNAL) {
// Handle messages directed to gateway
if (type == I_VERSION) {
// Request for version
serial(PSTR("0;0;%d;%d;%s\n"),M_INTERNAL, I_VERSION, LIBRARY_VERSION);
} else if (type == I_INCLUSION_MODE) {
// Request to change inclusion mode
setInclusionMode(atoi(value) == 1);
}
} else {
txBlink(1);
ok = sendData(GATEWAY_ADDRESS, sensorRadioId, childId, messageType, type, value, strlen(value), false);
if (!ok) {
errBlink(1);
}
}
}
void Gateway::setInclusionMode(boolean newMode) {
if (newMode != inclusionMode)
inclusionMode = newMode;
// Send back mode change on serial line to ack command
serial(PSTR("0;0;%d;%d;%d\n"), M_INTERNAL, I_INCLUSION_MODE, inclusionMode?1:0);
if (inclusionMode) {
inclusionStartTime = millis();
}
}
// Override normal validate to add error blink if crc check fails
uint8_t Gateway::validate() {
uint8_t res = Sensor::validate();
if (res == VALIDATE_BAD_CRC) {
errBlink(1);
}
return res;
}
void Gateway::processRadioMessage() {
if (messageAvailable()) {
// A new message was received from one of the sensors
message_s msg = getMessage();
if (msg.header.messageType == M_PRESENTATION && inclusionMode) {
rxBlink(3);
} else {
rxBlink(1);
}
// Pass along the message from sensors to serial line
serial(msg);
}
checkButtonTriggeredInclusion();
checkInclusionFinished();
}
void Gateway::serial(const char *fmt, ... ) {
va_list args;
va_start (args, fmt );
vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args);
va_end (args);
Serial.print(serialBuffer);
}
void Gateway::serial(message_s msg) {
serial(PSTR("%d;%d;%d;%d;%s\n"),msg.header.from, msg.header.childId, msg.header.messageType, msg.header.type, msg.data);
}
void Gateway::ledTimersInterrupt() {
if(countRx && countRx != 255) {
// switch led on
digitalWrite(pinRx, LOW);
} else if(!countRx) {
// switching off
digitalWrite(pinRx, HIGH);
}
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--; }
}
void Gateway::rxBlink(uint8_t cnt) {
if(countRx == 255) { countRx = cnt; }
}
void Gateway::txBlink(uint8_t cnt) {
if(countTx == 255 && !inclusionMode) { countTx = cnt; }
}
void Gateway::errBlink(uint8_t cnt) {
if(countErr == 255) { countErr = cnt; }
}
+82
View File
@@ -0,0 +1,82 @@
/*
The Sensor Net Arduino library adds a new layer on top of the RF24 library.
It handles radio network routing, relaying and ids.
Created by Henrik Ekblad <henrik.ekblad@gmail.com>
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.
*/
#ifndef Gateway_h
#define Gateway_h
#include "Relay.h"
#define MAX_RECEIVE_LENGTH 50 // Max buffersize needed for messages coming from vera
#define MAX_SEND_LENGTH 120 // Max buffersize needed for messages coming from vera
class Gateway : public Relay
{
public:
/**
* Constructor
*
* Creates a new instance of Gateway class.
* If you don't use status leds and/or inclusion mode button on your arduino gateway
* you can disable this functionality by calling the 2 argument constructor.
*
* @param _cepin The pin attached to RF24 Chip Enable on the RF module
* @param _cspin The pin attached to RF24 Chip Select
* @param _inclusion Digital pin that triggers inclusion mode
* @param _inclusion_time Time of inclusion mode (in minutes)
* @param _rx Digital pin for receive led
* @param _tx Digital pin for transfer led
* @param _er Digital pin for error led
*
*/
Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion_time);
Gateway(uint8_t _cepin, uint8_t _cspin, uint8_t _inclusion, uint8_t _inclusion_time, uint8_t _rx, uint8_t _tx, uint8_t _er);
void begin(uint8_t _radioId = 0);
void processRadioMessage();
void parseAndSend(String inputString);
boolean isLedMode();
void ledTimersInterrupt();
void startInclusionInterrupt();
private:
char commandBuffer[MAX_RECEIVE_LENGTH];
char serialBuffer[MAX_SEND_LENGTH]; // Buffer for building string when sending data to vera
unsigned long inclusionStartTime;
boolean inclusionMode; // Keeps track on inclusion mode
boolean buttonTriggeredInclusion;
volatile uint8_t countRx;
volatile uint8_t countTx;
volatile uint8_t countErr;
boolean ledMode;
uint8_t pinInclusion;
uint8_t inclusionTime;
uint8_t pinRx;
uint8_t pinTx;
uint8_t pinEr;
uint8_t validate();
void serial(message_s msg);
void interruptStartInclusion();
void checkButtonTriggeredInclusion();
void setInclusionMode(boolean newMode);
void serial(const char *fmt, ... );
void checkInclusionFinished();
void ledTimers();
void rxBlink(uint8_t cnt);
void txBlink(uint8_t cnt);
void errBlink(uint8_t cnt);
};
#endif
+212
View File
@@ -0,0 +1,212 @@
/*
The Sensor Net Arduino library adds a new layer on top of the RF24 library.
It handles radio network routing, relaying and ids.
Created by Henrik Ekblad <henrik.ekblad@gmail.com>
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.
*/
#include "Relay.h"
Relay::Relay(uint8_t _cepin, uint8_t _cspin) : Sensor(_cepin, _cspin) {
isRelay = true;
}
void Relay::begin(uint8_t _radioId) {
Sensor::begin(_radioId);
// Read routing table from EEPROM
for (int i=0;i<sizeof(childNodeTable);i++) {
childNodeTable[i] = EEPROM.read(EEPROM_ROUTES_ADDRESS+i);
}
// Start listening for incoming messages
RF24::startListening();
}
boolean Relay::send(message_s message, int length) {
bool ok = true;
uint8_t route = getChildRoute(msg.header.to);
if (route>0 && route<255 && message.header.to != GATEWAY_ADDRESS) {
debug(PSTR("Routing message.\n"));
// Message destination is not gateway and is in routing table for this node.
// Send it downstream
sendWrite(route, message, length);
} else if (radioId != GATEWAY_ADDRESS) {
debug(PSTR("Sending message back towards gw.\n"));
// Should be routed back to gateway. Sensor code knows how to do this.
ok = Sensor::send(message, length);
}
}
boolean Relay::messageAvailable() {
uint8_t pipe;
boolean available = RF24::available(&pipe);
if (available) {
uint8_t len = RF24::getDynamicPayloadSize()-sizeof(msg.header);
readMessage();
boolean ok = validate() == VALIDATE_OK;
debug(PSTR("Message crc %s.\n"),ok?"ok":"error");
if (ok) {
if (msg.header.messageType == M_INTERNAL &&
msg.header.type == I_PING) {
// We always answer ping messages
debug(PSTR("Answer ping message.\n"));
// Wait a random delay of 0-2 seconds to minimize collision
// between ping ack messages from other relaying nodes
randomSeed(millis());
delay(random(2000));
ltoa(distance, convBuffer, 10);
uint8_t to = msg.header.from;
debug(PSTR("Answer ping message. %d\n"), strlen(convBuffer));
buildMsg(radioId, to, NODE_CHILD_ID, M_INTERNAL, I_PING_ACK, convBuffer,strlen(convBuffer), false);
sendWrite(to, msg, strlen(convBuffer));
} else if (msg.header.to == radioId) {
// This message is addressed to this node
if (msg.header.messageType == M_INTERNAL) {
// Handle all internal messages to this node
if (msg.header.type == I_RELAY_NODE && msg.header.to != GATEWAY_ADDRESS) {
// Someone at sensor net gateway side wants this node to refresh its relay node
findRelay();
// Send relay information back to sensor net gateway node device.
sendInternal(I_RELAY_NODE, ltoa(relayId, convBuffer, 10));
return false;
} else if (msg.header.type == I_CHILDREN && msg.header.to != GATEWAY_ADDRESS) {
debug(PSTR("Route command received"));
if (strncmp(msg.data,"F", 1) == 0) {
// Send in as many children we can fit in a message (binary)
sendChildren();
} else if (strncmp(msg.data,"C", 1) == 0) {
// Clears child relay data for this node
clearChildRoutes();
}
return false;
}
// Return rest of internal messages back to sketch...
return true;
} else {
// If this is variable message from sensor net gateway. Send ack back.
debug(PSTR("Message addressed for this node.\n"));
if (msg.header.from == GATEWAY_ADDRESS &&
msg.header.messageType == M_SET_VARIABLE) {
// Send back ack message to sensor net gateway
sendVariableAck();
}
// Return message to waiting sketch...
return true;
}
} else {
// We should probably try to relay this message
relayMessage(len, pipe);
}
}
}
return false;
}
void Relay::relayMessage(uint8_t length, uint8_t pipe) {
uint8_t route = getChildRoute(msg.header.to);
if (route>0 && route<255) {
debug(PSTR("Routing message to child node.\n"));
// This message should be forwarded to a child node. If we send message
// to this nodes pipe then all children will receive it because the are
// all listening to this nodes pipe.
//
// +----B
// -A
// +----C------D
//
// We're node C, Message comes from A and has destination D
//
// lookup route in table and send message there
sendWrite(route, msg, length);
} else if (pipe == CURRENT_NODE_PIPE) {
// A message comes from a child node and we have no
// route for it.
//
// +----B
// -A
// +----C------D <-- Message comes from D
//
// We're node C
//
// Message should be passed to node A (this nodes relay)
debug(PSTR("Routing message to relay.\n"));
// This message should be routed back towards sensor net gateway
sendWrite(relayId, msg, length);
// Add this child to our "routing table" if it not already exist
addChildRoute(msg.header.from, msg.header.last);
} else {
// We're snooped a message directed to gateway from another branch
// Make sure to remove the sender node from our routing table.
//
// +-----B <-- Message comes from here
// -A
// +-----C <-- We're here
//
// So the sender of message should never be in our
// routing table.
//
// We could also end up in this else-statement if message
// destination has no route.
// This can happen if a node never has sent any message to
// sensor net gateway (which will build up routing information in all nodes
// that gets passed).
if (radioId == GATEWAY_ADDRESS) {
// We should perhaps inform gateway about the no-route situation?!
debug(PSTR("Unknown route from GW\n"));
} else {
debug(PSTR("Remove child node from routing table.\n"));
removeChildRoute(msg.header.from);
}
}
}
void Relay::addChildRoute(uint8_t childId, uint8_t route) {
if (childNodeTable[childId] != route) {
childNodeTable[childId] = route;
EEPROM.write(EEPROM_ROUTES_ADDRESS+childId, route);
}
}
void Relay::removeChildRoute(uint8_t childId) {
if (childNodeTable[childId] != 0xff) {
childNodeTable[childId] = 0xff;
EEPROM.write(EEPROM_ROUTES_ADDRESS+childId, 0xff);
}
}
uint8_t Relay::getChildRoute(uint8_t childId) {
return childNodeTable[childId];
}
void Relay::clearChildRoutes() {
debug(PSTR("Clear child routing data\n"));
for (int i=0;i< sizeof(childNodeTable); i++) {
removeChildRoute(i);
}
sendInternal(I_CHILDREN, "");
}
void Relay::sendChildren() {
// Send in which children that is using this node as an relay.
debug(PSTR("Send child info to sensor gateway.\n"));
sendInternal(I_CHILDREN, "not implemented");
// TODO: Fix this
}
+60
View File
@@ -0,0 +1,60 @@
/*
The Sensor Net Arduino library adds a new layer on top of the RF24 library.
It handles radio network routing, relaying and ids.
Created by Henrik Ekblad <henrik.ekblad@gmail.com>
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.
*/
#ifndef Relay_h
#define Relay_h
#include "Sensor.h"
#ifdef DEBUG
#define debug(x,...) debugPrint(x, ##__VA_ARGS__)
#else
#define debug(x,...)
#endif
#define EEPROM_ROUTES_ADDRESS ((uint8_t)3) // Where to start storing routing information in EEPROM. Will allocate 256 bytes.
class Relay : public Sensor
{
public:
/**
* Constructor
*
* Creates a new instance of Relay class.
*
* @param _cepin The pin attached to RF24 Chip Enable on the RF module
* @param _cspin The pin attached to RF24 Chip Select
*/
Relay(uint8_t _cepin, uint8_t _cspin);
void begin(uint8_t _radioId);
boolean messageAvailable();
boolean send(message_s message, int length);
protected:
private:
uint8_t childNodeTable[256]; // Buffer to store child node information. Store this in EEPROM
uint8_t getChildRoute(uint8_t childId);
void addChildRoute(uint8_t childId, uint8_t route);
void removeChildRoute(uint8_t childId);
void clearChildRoutes();
void sendChildren();
void relayMessage(uint8_t length, uint8_t pipe);
};
#endif
+541
View File
@@ -0,0 +1,541 @@
/*
The Sensor Net Arduino library adds a new layer on top of the RF24 library.
It handles radio network routing, relaying and ids.
Created by Henrik Ekblad <henrik.ekblad@gmail.com>
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.
*/
#include "Sensor.h"
Sensor::Sensor(uint8_t _cepin, uint8_t _cspin) : RF24(_cepin, _cspin) {
isRelay = false;
}
void Sensor::setupRadio() {
failedTransmissions = 0;
// Start up the radio library
RF24::begin();
RF24::enableDynamicPayloads();
RF24::setAutoAck(true);
RF24::setRetries(15, 15);
//RF24::setChannel(70);
RF24::setDataRate(RF24_1MBPS);
RF24::setCRCLength(RF24_CRC_16);
// All (relaying) nodes listen to broadcast pipe (for PING messages)
RF24::openReadingPipe(BROADCAST_PIPE, BASE_RADIO_ID + BROADCAST_ADDRESS);
}
void Sensor::begin(uint8_t _radioId) {
radioId = _radioId;
debug(PSTR("Started %s.\n"), isRelay?"relay":"sensor");
setupRadio();
// Fetch relay from EEPROM
relayId = EEPROM.read(EEPROM_RELAY_ID_ADDRESS);
// Fetch distance from eeprom
distance = EEPROM.read(EEPROM_DISTANCE_ADDRESS);
if (relayId == 0xff) {
// No relay previously fetched and stored in eeprom. Try to find one.
findRelay();
}
debug(PSTR("Relay=%d, distance=%d\n"), relayId, distance);
initializeRadioId();
// Open reading pipe for messages directed to this node
RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID+radioId);
// Send presentation for this radio node
sendSensorPresentation(NODE_CHILD_ID, isRelay? S_ARDUINO_RELAY : S_ARDUINO_NODE);
// Send relay information back to sensor net gateway.
sendInternal(I_RELAY_NODE, itoa(relayId, convBuffer, 10));
// Initialize ack message header
ack.header.version = PROTOCOL_VERSION;
ack.header.binary = 0;
ack.header.from = radioId;
ack.header.to = GATEWAY_ADDRESS;
ack.header.messageType = M_SET_VARIABLE;
}
uint8_t Sensor::getRadioId() {
return radioId;
}
void Sensor::initializeRadioId() {
if (radioId == AUTO) {
radioId = EEPROM.read(EEPROM_RADIO_ID_ADDRESS);
if (radioId == 0xFF || radioId == 0) {
radioId = AUTO;
debug(PSTR("No radio id found in EEPROM fetching one from sensor net gateway\n"));
// No radio id has been fetched yet ant EEPROM is unwritten.
// Request new id from sensor net gateway. Use radioId 4095 temporarily
// to be able to receive my correct nodeId.
RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID+radioId);
radioId = atoi(getInternal(I_REQUEST_ID));
// Write id to EEPROM
if (radioId == AUTO) { // sensor net gateway will return max id if all sensor id are taken
debug(PSTR("Sensor network is full! You already have the maximum of sensors!\n"));
while (1) {} // Wait here. Nothing else we can do...
} else {
debug(PSTR("Radio id received: %d\n"), radioId);
EEPROM.write(EEPROM_RADIO_ID_ADDRESS, radioId);
}
}
debug(PSTR("Radio id stored in EEPROM was: %d\n"), radioId);
}
}
void Sensor::findRelay() {
// This can be improved by using status = read_register(OBSERVE_TX,&observe_tx,1) on the
// sending side.. the problem is getting this information here without too much fuss.
// Stay in this method until one or more relay nodes answers ping message.
if (radioId == GATEWAY_ADDRESS)
return; // Gateway has no business here!
failedTransmissions = 0;
// Open a reading pipe for current radioId (if it differs from broadcast)
if (radioId != BROADCAST_PIPE) {
RF24::openReadingPipe(CURRENT_NODE_PIPE, BASE_RADIO_ID+radioId);
}
distance = 255;
uint8_t oldRelayId = relayId;
while (distance == 255) {
// Send ping message to BROADCAST_ADDRESS (to which all nodes listens and should reply to)
buildMsg(radioId, BROADCAST_ADDRESS, NODE_CHILD_ID, M_INTERNAL, I_PING, "", 0, false);
sendWrite(BROADCAST_ADDRESS, msg, 0);
// Wait for replies for max 10 seconds (or when buffer for all relay nodes have been filled up)
unsigned long enter = millis();
uint8_t neighborDistanceToGW;
// Wait for ack responses 5 seconds
while (millis() - enter < 5000) {
if (messageAvailable()) {
if (msg.header.messageType == M_INTERNAL &&
msg.header.type == I_PING_ACK &&
msg.header.to == radioId) {
neighborDistanceToGW = atoi(msg.data);
if (neighborDistanceToGW<distance-1) {
// Found a neighbor closer to GW than previously found
distance = neighborDistanceToGW + 1;
relayId = msg.header.from;
debug(PSTR("Using relay %d. Distance is %d\n"), msg.header.from, neighborDistanceToGW);
if (neighborDistanceToGW == 0) // We found gateway. Search no more.
break;
} else {
debug(PSTR("Discarded relay %d. Distance is %d\n"), msg.header.from, neighborDistanceToGW);
}
}
}
}
if (distance == 255) {
debug(PSTR("No relay nodes was found. Trying again in 10 seconds.\n"));
delay(10000);
}
}
// Store new relay address in EEPROM
if (relayId != oldRelayId) {
EEPROM.write(EEPROM_RELAY_ID_ADDRESS, relayId);
EEPROM.write(EEPROM_DISTANCE_ADDRESS, distance);
}
// Always listen to relay pipe (relay broadcasts messages that might be for this
// nodes children)
RF24::openReadingPipe(RELAY_PIPE, BASE_RADIO_ID + relayId);
}
void Sensor::buildMsg(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binary) {
msg.header.version = PROTOCOL_VERSION;
msg.header.binary = binary;
msg.header.from = from;
msg.header.to = to;
msg.header.childId = childId;
msg.header.messageType = messageType;
msg.header.type = type;
strncpy(msg.data, data, length);
if(length < sizeof(msg.data)-1) {
memset(&msg.data[length], 0, sizeof(msg.data) - 1 - length);
}
}
boolean Sensor::sendData(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binary) {
bool ok = false;
if (length < sizeof(msg.data)) {
buildMsg(from, to, childId, messageType, type, data, length, binary);
return send(msg,length);
} else {
debug(PSTR("Message too large\n"));
}
return false;
}
boolean Sensor::sendVariableAck() {
ack.header.childId = msg.header.childId;
ack.header.type = msg.header.type;
strncpy(ack.data, msg.data, sizeof(ack.data)-1); // will terminate properly not exceeding message.data
return send(ack,strlen(ack.data));
}
boolean Sensor::send(message_s message, int length) {
debug(PSTR("Relaying message back to gateway.\n"));
// We're a sensor node. Always send messages back to relay node
bool ok = sendWrite(relayId, message, length);
if (!ok && radioId != GATEWAY_ADDRESS) {
// Failure when sending to relay node. The relay node might be down and we
// need to find another route to gateway. Max 20 retries before giving up.
if (failedTransmissions>20) {
findRelay();
}
failedTransmissions++;
} else {
failedTransmissions = 0;
}
return ok;
}
boolean Sensor::sendWrite(uint8_t dest, message_s message, int length) {
// Add current radioId to last-field and calculate crc
message.header.last = radioId;
message.header.crc = crc8Message(message);
debug(PSTR("Sending: from=%d, to=%d, childId=%d, mtype=%d, type=%d, crc=%d, '%s', sent via %d\n"),
message.header.from,message.header.to, message.header.childId, message.header.messageType, message.header.type, message.header.crc, message.data, dest);
RF24::stopListening();
bool ok = false;
RF24::openWritingPipe(BASE_RADIO_ID + dest);
int retry = 5;
do {
ok = RF24::write(&message, min(MAX_MESSAGE_LENGTH, sizeof(message.header) + length));
}
while ( !ok && --retry );
RF24::startListening();
if (ok) {
debug(PSTR("Sent successfully\n"));
} else {
debug(PSTR("Send failed. No ack received.\n"));
}
return ok;
}
void Sensor::sendInternal(uint8_t variableType, const char *value) {
sendData(radioId, GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, variableType, value, strlen(value), false);
}
// This will be added in 1.4
/*void Sensor::sendVariable(uint8_t childId, uint8_t variableType,
const char *value, length) {
sendData(radioId, GATEWAY_ADDRESS, childId, M_SET_VARIABLE, variableType, value, length, true);
}*/
void Sensor::sendVariable(uint8_t childId, uint8_t variableType,
const char *value) {
sendData(radioId, GATEWAY_ADDRESS, childId, M_SET_VARIABLE, variableType, value, strlen(value), false);
}
void Sensor::sendVariable(uint8_t childId, uint8_t variableType, double value, int decimals) {
sendVariable(childId, variableType, dtostrf(value,2,decimals,convBuffer));
}
void Sensor::sendVariable(uint8_t childId, uint8_t variableType, int value) {
sendVariable(childId, variableType, itoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t childId, uint8_t variableType, long value) {
sendVariable(childId, variableType, ltoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t childId, uint8_t variableType, unsigned long value) {
sendVariable(childId, variableType, ltoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t childId, uint8_t variableType, unsigned int value) {
sendVariable(childId, variableType, ltoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType,
const char *value) {
sendData(radioId, nodeId, childId, M_SET_VARIABLE, variableType, value, strlen(value), false);
}
void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, double value, int decimals) {
sendVariable(nodeId, childId, variableType, dtostrf(value,2,decimals,convBuffer));
}
void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, int value) {
sendVariable(nodeId, childId, variableType, itoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, long value) {
sendVariable(nodeId, childId, variableType, ltoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, unsigned long value) {
sendVariable(nodeId, childId, variableType, ltoa(value, convBuffer, 10));
}
void Sensor::sendVariable(uint8_t nodeId, uint8_t childId, uint8_t variableType, unsigned int value) {
sendVariable(nodeId, childId, variableType, ltoa(value, convBuffer, 10));
}
void Sensor::sendSensorPresentation(uint8_t childId, uint8_t sensorType) {
sendData(radioId, GATEWAY_ADDRESS, childId, M_PRESENTATION, sensorType, LIBRARY_VERSION, strlen(LIBRARY_VERSION), false);
}
void Sensor::requestStatus(uint8_t childId, uint8_t variableType) {
sendData(radioId, GATEWAY_ADDRESS, childId, M_REQ_VARIABLE, variableType, "", 0, false);
}
void Sensor::requestStatus(uint8_t nodeId, int8_t childId, uint8_t variableType) {
sendData(radioId, nodeId, childId, M_REQ_VARIABLE, variableType, "", 0, false);
}
void Sensor::sendBatteryLevel(int value) {
sendInternal(I_BATTERY_LEVEL, ltoa(value, convBuffer, 10));
}
char* Sensor::get(uint8_t nodeId, uint8_t childId, uint8_t sendType, uint8_t receiveType, uint8_t variableType) {
while (1) {
sendData(radioId, nodeId, childId, sendType, variableType, "", 0, false);
uint8_t i = 0;
while (i < 100) { // 5 seconds timeout before re-sending status request
while (messageAvailable()) {
// Check that it is right type of message and not a routing message
if (msg.header.messageType == receiveType &&
msg.header.type == variableType &&
msg.header.childId == childId) {
return msg.data;
}
}
delay(50);
i++;
}
}
return NULL;
}
char* Sensor::getStatus(uint8_t childId, uint8_t variableType) {
return get(GATEWAY_ADDRESS, childId, M_REQ_VARIABLE, M_ACK_VARIABLE, variableType);
}
char * Sensor::getStatus(uint8_t nodeId, int8_t childId, uint8_t variableType) {
return get(nodeId, childId, M_REQ_VARIABLE, M_ACK_VARIABLE, variableType);
}
char* Sensor::getInternal(uint8_t variableType) {
return get(GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, M_INTERNAL, variableType);
}
unsigned long Sensor::getTime() {
return atol(getInternal(I_TIME));
}
void Sensor::requestTime() {
sendData(radioId, GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, I_TIME, "", 0, false);
}
bool Sensor::isMetricSystem() {
return getInternal(I_UNIT)[0] == 'M';
}
void Sensor::requestIsMetricSystem() {
sendData(radioId, GATEWAY_ADDRESS, NODE_CHILD_ID, M_INTERNAL, I_UNIT, "", 0, false);
}
boolean Sensor::messageAvailable() {
if (RF24::available()) {
readMessage();
boolean ok = validate() == VALIDATE_OK;
debug(PSTR("Mess crc %s.\n"),ok?"ok":"error");
if (ok && msg.header.to == radioId) {
// This message is addressed to this node
debug(PSTR("Message addressed for this node.\n"));
if (msg.header.from == GATEWAY_ADDRESS &&
// If this is variable message from sensor net gateway. Send ack back.
msg.header.messageType == M_SET_VARIABLE) {
// Send back ack message to sensor net gateway
sendVariableAck();
}
// Return message to waiting sketch...
return true;
}
}
return false;
}
message_s Sensor::waitForMessage() {
while (1) {
if (messageAvailable()) {
return msg;
}
}
}
message_s Sensor::getMessage() {
return msg;
}
message_s Sensor::readMessage() {
uint8_t len = RF24::getDynamicPayloadSize();
bool done = RF24::read(&msg, len);
// Make sure string gets terminated ok.
msg.data[len - sizeof(header_s) ] = '\0';
debug(PSTR("Received: from=%d, to=%d, childId=%d, mtype=%d, type=%d, crc=%d, '%s'\n"),
msg.header.from,msg.header.to, msg.header.childId, msg.header.messageType, msg.header.type,msg.header.crc, msg.data);
return msg;
}
/*
* raw CRC 8 bit calculation
*/
uint8_t Sensor::crc8Raw ( uint8_t *data_in, uint8_t number_of_bytes_to_read )
{
uint8_t crc;
uint8_t loop_count;
uint8_t bit_counter;
uint8_t data;
uint8_t feedback_bit;
crc = CRC8INIT;
for (loop_count = 0; loop_count != number_of_bytes_to_read; loop_count++)
{
data = data_in[loop_count];
bit_counter = 8;
do {
feedback_bit = (crc ^ data) & 0x01;
if ( feedback_bit == 0x01 ) {
crc = crc ^ CRC8POLY;
}
crc = (crc >> 1) & 0x7F;
if ( feedback_bit == 0x01 ) {
crc = crc | 0x80;
}
data = data >> 1;
bit_counter--;
} while (bit_counter > 0);
}
return crc;
}
/*
* calculate CRC8 on message_s data taking care of data structure and protocol version
*/
uint8_t Sensor::crc8Message(message_s var_msg) {
// Must set crc to a constant value.
var_msg.header.crc = 0;
// fill unused space by zeroes for string data only
if(!var_msg.header.binary) {
uint8_t len = strlen(var_msg.data);
if(len < sizeof(var_msg.data)-1) {
memset(&var_msg.data[len], 0, sizeof(var_msg.data) - 1 - len);
}
}
return crc8Raw((uint8_t*)&var_msg, (uint8_t)sizeof(var_msg));
}
/*
uint8_t Sensor::crc8Message(message_s var_msg) {
struct {
message_s msg;
uint8_t protocol_version;
} crc_data;
memcpy(&crc_data, &var_msg, sizeof(var_msg));
crc_data.protocol_version = PROTOCOL_VERSION;
// some clean up needed for repeated result
crc_data.msg.header.crc = 0;
// fill unused space by zeroes for string data only
if(!crc_data.msg.header.binary) {
uint8_t len = strlen(crc_data.msg.data);
if(len < sizeof(crc_data.msg.data)-1) {
memset(&crc_data.msg.data[len], 0, sizeof(crc_data.msg.data) - 1 - len);
}
}
return crc8Raw((uint8_t*)&crc_data, (uint8_t)sizeof(crc_data));
} */
/*
* true if message is consistent *
*/
bool Sensor::checkCRC(message_s var_msg) {
uint8_t oldCrc = var_msg.header.crc;
//debug(PSTR("CRC: in %d, calc %d\n"),oldCrc, crc8Message(var_msg));
return (oldCrc == crc8Message(var_msg))?true:false;
}
uint8_t Sensor::validate() {
bool crc_check = checkCRC(msg);
bool version_check = (msg.header.version == PROTOCOL_VERSION);
if(!version_check) return VALIDATE_BAD_VERSION;
if(!crc_check) return VALIDATE_BAD_CRC;
return VALIDATE_OK;
}
#ifdef DEBUG
void Sensor::debugPrint(const char *fmt, ... ) {
char fmtBuffer[300];
if (radioId == GATEWAY_ADDRESS) {
// prepend debug message to be handled correctly by gw
Serial.print("0;0;4;11;");
}
va_list args;
va_start (args, fmt );
vsnprintf_P(fmtBuffer, 300, fmt, args);
va_end (args);
if (radioId == GATEWAY_ADDRESS) {
// Truncte message if this is gateway node
vsnprintf_P(fmtBuffer, 97, fmt, args);
fmtBuffer[96] = '\n';
fmtBuffer[97] = '\0';
} else {
vsnprintf_P(fmtBuffer, 299, fmt, args);
}
va_end (args);
Serial.print(fmtBuffer);
//Serial.println(freeRam());
}
#endif
#ifdef DEBUG
int Sensor::freeRam (void) {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
#endif
+279
View File
@@ -0,0 +1,279 @@
/*
The Sensor Net Arduino library adds a new layer on top of the RF24 library.
It handles radio network routing, relaying and ids.
Created by Henrik Ekblad <henrik.ekblad@gmail.com>
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.
*/
#ifndef Sensor_h
#define Sensor_h
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <Arduino.h>
#include <stddef.h>
#include <SPI.h>
#include <EEPROM.h>
#include <avr/progmem.h>
#include <stdarg.h>
#define DEBUG // Turn on/off debug mode by having/removing this define
#ifdef DEBUG
#define debug(x,...) debugPrint(x, ##__VA_ARGS__)
#else
#define debug(x,...)
#endif
#define LIBRARY_VERSION "1.2+"
#define PROTOCOL_VERSION 1
#define BAUD_RATE 115200
#define AUTO 0xFF // 0-254. Id 255 is reserved for auto initialization of radioId.
#define NODE_CHILD_ID 0xFF // Node child id is always created for when a new sensor is detected
#define EEPROM_RADIO_ID_ADDRESS 0 // Where to store radio id in EEPROM
#define EEPROM_RELAY_ID_ADDRESS 1 // Where to store relay id in EEPROM
#define EEPROM_DISTANCE_ADDRESS 2 // Where to store distance to gateway in EEPROM
// This is the radioId for sensor net gateway receiver sketch (where all sensors should send their data).
// This is also act as base value for sensor radioId
#define BASE_RADIO_ID 0xABCDABC000LL
#define GATEWAY_ADDRESS ((uint8_t)0)
#define BROADCAST_ADDRESS ((uint8_t)0xFF)
#define MAX_MESSAGE_LENGTH 32
#define CURRENT_NODE_PIPE ((uint8_t)1)
#define BROADCAST_PIPE ((uint8_t)2)
#define RELAY_PIPE ((uint8_t)3)
#define CRC8INIT 0x00
#define CRC8POLY 0x18 //0X18 = X^8+X^5+X^4+X^0
// Message types
typedef enum {
M_PRESENTATION = 0,
M_SET_VARIABLE = 1,
M_REQ_VARIABLE = 2,
M_ACK_VARIABLE = 3,
M_INTERNAL = 4
} messageType;
// Sensor variables that can be used in sketches
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
} variableType;
// Internal messages
typedef enum {
I_BATTERY_LEVEL, I_BATTERY_DATE, I_LAST_TRIP, I_TIME, I_VERSION, I_REQUEST_ID,
I_INCLUSION_MODE, I_RELAY_NODE, I_LAST_UPDATE, I_PING, I_PING_ACK,
I_LOG_MESSAGE, I_CHILDREN, I_UNIT
} internalMessageType;
// Sensor types
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_RELAY, S_LOCK, S_IR, S_WATER
} sensor;
// Possible return values by validate() when doing crc check of received message.
enum {
VALIDATE_OK, VALIDATE_BAD_CRC, VALIDATE_BAD_VERSION
};
// The message structure
typedef struct {
uint8_t crc : 8; // 8 bits crc
uint8_t version : 3; // 3 bits protocol version
uint8_t binary : 1; // 1 bit. Data is binary and should be encoded when sent to sensor net gateway
uint8_t from : 8; // 8 bits. RadioId of sender node
uint8_t to : 8; // 8 bits. RadioId of destination node
uint8_t last : 8; // 8 bits. RadioId of last node this message passed
uint8_t childId : 8; // 1 byte. Up to MAX_CHILD_DEVICES child sensors per radioId
uint8_t messageType : 4; // 4 bits. Type of message. See messageType
uint8_t type : 8; // 8 bits. variableType or deviceType depending on messageType
} header_s;
typedef struct {
header_s header;
char data[MAX_MESSAGE_LENGTH - sizeof(header_s) + 1]; // Each message can transfer a payload. Add one extra byte for \0
} message_s;
class Sensor : public RF24
{
public:
/**
* Constructor
*
* Creates a new instance of Sensor class.
*
* @param _cepin The pin attached to RF24 Chip Enable on the RF module
* @param _cspin The pin attached to RF24 Chip Select
*/
Sensor(uint8_t _cepin, uint8_t _cspin);
/**
* Begin operation of the sensor net library
*
* Call this in setup(), before calling any other sensor net library methods.
* @param _radioId The unique id (1-254) for this sensor. Specify 255 for auto id mode.
*/
void begin(uint8_t _radioId);
uint8_t getRadioId();
/**
* The arduino node must send a presentation of all the sensors connected before any
* variable changes will be registered on sensor net gateway side.
* Usually it's good to present all sensors when arduino starts up (setup).
* Note that gateway must be in include mode to register new devices.
*
* @param childId The unique child id for the different sensors connected to this arduino. 0-254.
* @param sensorType Sensor types to create. They will be numbered from 0 up to 127.
*/
void sendSensorPresentation(uint8_t childId, uint8_t sensorType);
/**
* Sends a variable change to sensor net gateway (or another sensor if radioId is specified)
*
* @param radioId The radioId of other node in radio network (used for communicating between sensors)
* @param childId The child id for which to update variable. Value can be 0-254.
* @param variableType The variableType to update
* @param value New value of the variable
*/
void sendVariable(uint8_t childId, uint8_t variableType, const char *value);
void sendVariable(uint8_t childId, uint8_t variableType, double value, int decimals);
void sendVariable(uint8_t childId, uint8_t variableType, unsigned long value);
void sendVariable(uint8_t childId, uint8_t variableType, long value);
void sendVariable(uint8_t childId, uint8_t variableType, unsigned int value);
void sendVariable(uint8_t childId, uint8_t variableType, int value);
void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, const char *value);
void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, double value, int decimals);
void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, unsigned long value);
void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, long value);
void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, unsigned int value);
void sendVariable(uint8_t radioId, uint8_t childId, uint8_t variableType, int value);
/**
* Sends battery status to sensor net gateway for this radio node.
* @param value Set a value between 0-100(%)
*/
void sendBatteryLevel(int value);
/**
* Requests a variable value from sensor net gateway (or another sensor). This method will not wait for an answer.
* You should use mesageAvailable/getMessage to pick up the response.
*
* @param radioId The radioId of other node in radio network (used when fetching from other node)
* @param childId The unique child id for the different sensors connected to this arduino. 0-254.
* @param variableType The variableType to fetch
*/
void requestStatus(uint8_t childId, uint8_t variableType);
void requestStatus(uint8_t radioId, int8_t childId, uint8_t variableType);
/**
* Requests status for a sensor variable from sensor net gateway. Waits until message arrives.
*
* @param radioId The radioId of other node in radio network (used when fetching from other node)
* @param childId The unique child id for the different sensors connected to this arduino. 0-254.
* @param variableType The variableType to fetch
* @return The variable value
*/
char *getStatus(uint8_t childId, uint8_t variableType);
char *getStatus(uint8_t radioId, int8_t childId, uint8_t variableType);
/**
* Fetches time from sensor net gateway
*/
void requestTime();
unsigned long getTime();
/**
* Fetches unit setting from sensor net gateway. Returns true if metric system has been selected which means
* that sensor should report it's information in: celsius, meter, cm, gram, km/h, m/s etc..
* If false is returned the sensor should report data in imperial system which means
* fahrenheit, feet, gallon, mph etc...
*/
void requestIsMetricSystem();
bool isMetricSystem();
/**
* Busy waits until there is a message for this node available to be read
*/
message_s waitForMessage(void);
/**
* Returns true if there is a message addressed for this node is available to be read
*/
boolean messageAvailable(void);
/**
* Returns the last received message
*/
message_s getMessage(void);
/**
* Validates consistency of the message including CRC and protocol version
*/
uint8_t validate();
#ifdef DEBUG
void debugPrint(const char *fmt, ... );
int freeRam();
#endif
protected:
uint8_t failedTransmissions;
boolean isRelay;
uint8_t radioId;
uint8_t distance; // This nodes distance to sensor net gateway (number of hops)
uint8_t relayId;
message_s msg; // Buffer for incoming messages.
char convBuffer[20];
void setupRadio();
void findRelay();
boolean send(message_s message, int length);
boolean sendWrite(uint8_t dest, message_s message, int length);
message_s readMessage(void);
void buildMsg(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binary);
void sendInternal(uint8_t variableType, const char *value);
boolean sendVariableAck();
boolean sendData(uint8_t from, uint8_t to, uint8_t childId, uint8_t messageType, uint8_t type, const char *data, uint8_t length, boolean binaryMessage);
private:
message_s ack; // Buffer for ack messages.
void initializeRadioId();
uint8_t crc8Raw(uint8_t *data_in, uint8_t number_of_bytes_to_read);
uint8_t crc8Message(message_s);
bool checkCRC(message_s);
char* get(uint8_t nodeId, uint8_t childId, uint8_t sendType, uint8_t receiveType, uint8_t variableType);
char *getInternal(uint8_t variableType);
};
#endif
+63
View File
@@ -0,0 +1,63 @@
/* please read copyright-notice at EOF */
#include <stdint.h>
#define CRC8INIT 0x00
#define CRC8POLY 0x18 //0X18 = X^8+X^5+X^4+X^0
uint8_t crc8( uint8_t *data, uint16_t number_of_bytes_in_data )
{
uint8_t crc;
uint16_t loop_count;
uint8_t bit_counter;
uint8_t b;
uint8_t feedback_bit;
crc = CRC8INIT;
for (loop_count = 0; loop_count != number_of_bytes_in_data; loop_count++)
{
b = data[loop_count];
bit_counter = 8;
do {
feedback_bit = (crc ^ b) & 0x01;
if ( feedback_bit == 0x01 ) {
crc = crc ^ CRC8POLY;
}
crc = (crc >> 1) & 0x7F;
if ( feedback_bit == 0x01 ) {
crc = crc | 0x80;
}
b = b >> 1;
bit_counter--;
} while (bit_counter > 0);
}
return crc;
}
/*
This code is from Colin O'Flynn - Copyright (c) 2002
only minor changes by M.Thomas 9/2004
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.
*/
+41
View File
@@ -0,0 +1,41 @@
#ifndef CRC8_H_
#define CRC8_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
uint8_t crc8( uint8_t* data, uint16_t number_of_bytes_in_data );
#ifdef __cplusplus
}
#endif
#endif
/*
This is based on code from :
Copyright (c) 2002 Colin O'Flynn
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.
*/
#include "crc8.c"
@@ -0,0 +1,20 @@
/*
*
* This sketch clears radioId, relayId and routing info in EEPROM
*
*/
#include <SPI.h>
#include <EEPROM.h>
void setup()
{
for (int i=0;i<512;i++) {
EEPROM.write(i, 0xff);
}
}
void loop()
{
// Nothing to do here...
}
@@ -0,0 +1,70 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <DallasTemperature.h>
#include <OneWire.h>
#include <RF24.h>
#include <Sensor.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define ONE_WIRE_BUS 3 // Pin where dallase sensor is connected
unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds)
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
Sensor gw(9, 10);
Sleep sleep;
#define MAX_ATTACHED_DS18B20 16
float lastTemperature[MAX_ATTACHED_DS18B20];
int numSensors=0;
boolean metric = true;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
sensors.begin();
gw.begin(RADIO_ID);
// Fetch the number of attached sensors
numSensors = sensors.getDeviceCount();
// Register all sensors to gw (they will be created as child devices)
for (int i=0; i<numSensors; i++) {
gw.sendSensorPresentation(i, S_TEMP);
}
metric = gw.isMetricSystem();
}
void loop()
{
sensors.requestTemperatures(); // Fetch temperatures from Dallas
delay(100);
for (int i=0; i<numSensors; i++) {
// Fetch and round temperature to one decimal
float temperature = static_cast<float>(static_cast<int>((metric?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) {
gw.powerUp(); // Powerup introduces a small delay (which is missing in radio.write powerup)
// Send variable (using registered shortcut) to gw
gw.sendVariable(i, V_TEMP, temperature, 1);
lastTemperature[i]=temperature;
}
}
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
delay(500);
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime
}
@@ -0,0 +1,58 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
#include <NewPing.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID 8
#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 MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned long SLEEP_TIME = 5; // Sleep time between reads (in seconds)
Sensor gw(9, 10);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
Sleep sleep;
int lastDist;
boolean metric;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
// Register all sensors to gw (they will be created as child devices)
gw.sendSensorPresentation(0, S_DISTANCE);
metric = gw.isMetricSystem();
}
void loop()
{
int dist = metric?sonar.ping_cm():sonar.ping_in();
Serial.print("Ping: ");
Serial.print(dist); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println(metric?" cm":" in");
if (dist != lastDist) {
gw.sendVariable(0, V_DISTANCE, dist);
lastDist = dist;
}
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
delay(1000); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime
}
@@ -0,0 +1,118 @@
// Use this sensor to measure KWH and Watt of your house meeter
// You need to set the correct pulsefactor of your meeter (blinks per KWH).
// The sensor starts by fetching current KWH value from gateway.
// Reports both KWH and Watt back to gateway.
//
// Unfortunately millis() won't increment when the Arduino is in
// sleepmode. So we cannot make this sensor sleep if we also want
// to calculate/report watt-number.
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your light sensor. (Only 2 and 3 generates interrupt!)
#define PULSE_FACTOR 1000 // Nummber of blinks per KWH of your meeter
#define SLEEP_MODE false // Watt-value can only be reported when sleep mode is false.
#define MAX_WATT 10000 // Max watt value to report. This filetrs outliers.
unsigned long SEND_FREQUENCY = 20; // Minimum time between send (in seconds). We don't wnat to spam the gateway.
#define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
#define CHILD_ID 5 // Id of the sensor child
Sensor gw(9,10);
Sleep sleep;
//double kwhPerBlink = 1.0/((double)PULSE_FACTOR);
double ppwh = ((double)PULSE_FACTOR)/1000; // Pulses per watt hour
volatile unsigned long pulseCount = 0;
volatile unsigned long lastBlink = 0;
volatile unsigned long watt = 0;
unsigned long oldPulseCount = 0;
unsigned long oldWatt = 0;
double oldKwh;
unsigned long lastSend;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
// Register this device as power sensor
gw.sendSensorPresentation(CHILD_ID, S_POWER);
// Fetch last known pulse count value from gw
pulseCount = oldPulseCount = atol(gw.getStatus(CHILD_ID, V_VAR1));
Serial.print("Last pulse count from gw:");
Serial.println(pulseCount);
attachInterrupt(INTERRUPT, onPulse, RISING);
lastSend=millis();
}
void loop()
{
unsigned long now = millis();
// Only send values at a maximum frequency or woken up from sleep
if (SLEEP_MODE || now - lastSend > 1000*SEND_FREQUENCY) {
// New watt value has been calculated
if (!SLEEP_MODE && watt != oldWatt) {
// Check that we dont get unresonable large watt value.
// could hapen when long wraps or false interrupt triggered
if (watt<((unsigned long)MAX_WATT)) {
gw.sendVariable(CHILD_ID, V_WATT, watt); // Send watt value to gw
}
Serial.print("Watt:");
Serial.println(watt);
oldWatt = watt;
}
// Pulse cout has changed
if (pulseCount != oldPulseCount) {
gw.sendVariable(CHILD_ID, V_VAR1, pulseCount); // Send kwh value to gw
double kwh = ((double)pulseCount/((double)PULSE_FACTOR));
oldPulseCount = pulseCount;
//Serial.print("Pulse count:");
//Serial.println(pulseCount);
if (kwh != oldKwh) {
gw.sendVariable(CHILD_ID, V_KWH, kwh, 4); // Send kwh value to gw
//Serial.print("KWH:");
//Serial.println(kwh);
oldKwh = kwh;
}
}
lastSend = now;
}
if (SLEEP_MODE) {
delay(300); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SEND_FREQUENCY * 1000); //sleep for: sleepTime
}
}
void onPulse()
{
if (!SLEEP_MODE) {
unsigned long newBlink = micros();
unsigned long interval = newBlink-lastBlink;
if (interval<10000L) { // Sometimes we get interrupt on RISING
return;
}
watt = (3600000000.0 /interval) / ppwh;
lastBlink = newBlink;
}
pulseCount++;
}
@@ -0,0 +1,74 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
#include <DHT.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define CHILD_ID_HUM 0
#define CHILD_ID_TEMP 1
#define HUMIDITY_SENSOR_DIGITAL_PIN 3
unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds)
Sensor gw(9, 10);
DHT dht;
Sleep sleep;
float lastTemp;
float lastHum;
boolean metric = true;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN);
// Register all sensors to gw (they will be created as child devices)
gw.sendSensorPresentation(CHILD_ID_HUM, S_HUM);
gw.sendSensorPresentation(CHILD_ID_TEMP, S_TEMP);
metric = gw.isMetricSystem();
}
void loop()
{
delay(dht.getMinimumSamplingPeriod());
float temperature = dht.getTemperature();
if (isnan(temperature)) {
Serial.println("Failed reading temperature from DHT");
} else if (temperature != lastTemp) {
lastTemp = temperature;
if (!metric) {
temperature = dht.toFahrenheit(temperature);
}
gw.sendVariable(CHILD_ID_TEMP, V_TEMP, temperature, 1);
Serial.print("T: ");
Serial.println(temperature);
}
float humidity = dht.getHumidity();
if (isnan(humidity)) {
Serial.println("Failed reading humidity from DHT");
} else if (humidity != lastHum) {
lastHum = humidity;
gw.sendVariable(CHILD_ID_HUM, V_HUM, humidity, 1);
Serial.print("H: ");
Serial.println(humidity);
}
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
delay(1000); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime
}
@@ -0,0 +1,119 @@
// Example sketch showing how to control ir devices
// An IR LED must be connected to Arduino PWM pin 3.
// An optional ir receiver can be connected to PWM pin 8.
// All receied ir signals will be sent to gateway device stored in VAR_1.
// When binary light on is clicked - sketch will send volume up ir command
// When binary light off is clicked - sketch will send volume down ir command
#include <Sensor.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <IRremote.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
int RECV_PIN = 8;
#define CHILD_1 3 // childId
IRsend irsend;
IRrecv irrecv(RECV_PIN);
decode_results results;
Sensor gw(9,10);
void setup()
{
Serial.begin(BAUD_RATE); // Used to write debug info
irrecv.enableIRIn(); // Start the ir receiver
gw.begin(RADIO_ID);
// Register a sensors to gw. Use binary light for test purposes.
gw.sendSensorPresentation(CHILD_1, S_LIGHT);
}
void loop()
{
if (gw.messageAvailable()) {
message_s message = gw.getMessage();
int incomingRelayStatus = atoi(message.data);
if (incomingRelayStatus == 1) {
irsend.sendNEC(0x1EE17887, 32); // Vol up yamaha ysp-900
} else {
irsend.sendNEC(0x1EE1F807, 32); // Vol down yamaha ysp-900
}
// Start receiving ir again...
irrecv.enableIRIn();
}
if (irrecv.decode(&results)) {
char buffer[10];
sprintf(buffer, "%08lx", results.value);
dump(&results);
// Send ir result to gw
gw.sendVariable(CHILD_1, V_VAR1, buffer);
irrecv.resume(); // Receive the next value
}
}
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
// void * to work around compiler issue
//void dump(void *v) {
// decode_results *results = (decode_results *)v
void dump(decode_results *results) {
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.print("Unknown encoding: ");
}
else if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
else if (results->decode_type == PANASONIC) {
Serial.print("Decoded PANASONIC - Address: ");
Serial.print(results->panasonicAddress,HEX);
Serial.print(" Value: ");
}
else if (results->decode_type == JVC) {
Serial.print("Decoded JVC: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 0; i < count; i++) {
if ((i % 2) == 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println("");
}
@@ -0,0 +1,47 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <RF24.h>
#include <EEPROM.h>
#include <Sensor.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define CHILD_ID_LIGHT 0
#define LIGHT_SENSOR_ANALOG_PIN 0
unsigned long SLEEP_TIME = 30; // Sleep time between reads (in seconds)
Sensor gw(9,10);
int lastLightLevel;
Sleep sleep;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
// Register all sensors to gateway (they will be created as child devices)
gw.sendSensorPresentation(CHILD_ID_LIGHT, S_LIGHT_LEVEL);
}
void loop()
{
int lightLevel = (1023-analogRead(LIGHT_SENSOR_ANALOG_PIN))/10.23;
Serial.println(lightLevel);
if (lightLevel != lastLightLevel) {
gw.sendVariable(CHILD_ID_LIGHT, V_LIGHT_LEVEL, lightLevel);
lastLightLevel = lightLevel;
}
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
delay(1000); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SLEEP_TIME * 1000); //sleep for: sleepTime
}
@@ -0,0 +1,45 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your motion sensor. (Only 2 and 3 generates interrupt!)
#define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
#define CHILD_ID 0 // Id of the sensor child
Sensor gw(9,10);
Sleep sleep;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
pinMode(DIGITAL_INPUT_SENSOR, INPUT); // sets the motion sensor digital pin as input
// Register all sensors to gw (they will be created as child devices)
gw.sendSensorPresentation(CHILD_ID, S_MOTION);
}
void loop()
{
// Read digital motion value
boolean tripped = digitalRead(DIGITAL_INPUT_SENSOR) == HIGH;
Serial.println(tripped);
gw.sendVariable(CHILD_ID, V_TRIPPED, tripped?"1":"0"); // Send tripped value to gw
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
delay(200); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepInterrupt(INTERRUPT,CHANGE);
}
@@ -0,0 +1,198 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
#include <Wire.h>
#include <Adafruit_BMP085.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define LIGHT_SENSOR_ANALOG_PIN 0
unsigned long SLEEP_TIME = 60; // Sleep time between reads (in seconds)
Adafruit_BMP085 bmp = Adafruit_BMP085(); // Digital Pressure Sensor
Sensor gw(9, 10);
float lastPressure = -1;
float lastTemp = -1;
int lastForecast = -1;
Sleep sleep;
char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"};
int minutes;
float pressureSamples[180];
int minuteCount = 0;
bool firstRound = true;
float pressureAvg[7];
float dP_dt;
boolean metric;
void setup() {
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
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.sendSensorPresentation(0, S_BARO);
gw.sendSensorPresentation(1, S_TEMP);
metric = gw.isMetricSystem();
}
void loop() {
float pressure = bmp.readPressure();
float temperature = bmp.readTemperature();
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(" Pa");
Serial.println(weather[forecast]);
if (temperature != lastTemp) {
gw.sendVariable(1, V_TEMP, temperature,1);
lastTemp = temperature;
}
if (pressure != lastPressure) {
gw.sendVariable(0, V_PRESSURE, pressure, 0);
lastPressure = pressure;
}
if (forecast != lastForecast) {
gw.sendVariable(0, V_FORECAST, weather[forecast]);
lastForecast = forecast;
}
/*
DP/Dt explanation
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)
*/
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
delay(1000); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SLEEP_TIME * 1000); // sleep to conserve power
}
int sample(float pressure) {
// Algorithm found here
// http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf
if (minuteCount > 180)
minuteCount = 6;
pressureSamples[minuteCount] = pressure;
minuteCount++;
if (minuteCount == 5) {
// Avg pressure in first 5 min, value averaged from 0 to 5 min.
pressureAvg[0] = ((pressureSamples[1] + pressureSamples[2]
+ pressureSamples[3] + pressureSamples[4] + pressureSamples[5])
/ 5);
} else if (minuteCount == 35) {
// Avg pressure in 30 min, value averaged from 0 to 5 min.
pressureAvg[1] = ((pressureSamples[30] + pressureSamples[31]
+ pressureSamples[32] + pressureSamples[33]
+ pressureSamples[34]) / 5);
float change = (pressureAvg[1] - pressureAvg[0]);
if (firstRound) // first time initial 3 hour
dP_dt = ((65.0 / 1023.0) * 2 * change); // 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[55] + pressureSamples[56]
+ pressureSamples[57] + pressureSamples[58]
+ pressureSamples[59]) / 5);
float change = (pressureAvg[2] - pressureAvg[0]);
if (firstRound) //first time initial 3 hour
dP_dt = ((65.0 / 1023.0) * 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[90] + pressureSamples[91]
+ pressureSamples[92] + pressureSamples[93]
+ pressureSamples[94]) / 5);
float change = (pressureAvg[3] - pressureAvg[0]);
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * 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[115] + pressureSamples[116]
+ pressureSamples[117] + pressureSamples[118]
+ pressureSamples[119]) / 5);
float change = (pressureAvg[4] - pressureAvg[0]);
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * 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[150] + pressureSamples[151]
+ pressureSamples[152] + pressureSamples[153]
+ pressureSamples[154]) / 5);
float change = (pressureAvg[5] - pressureAvg[0]);
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * 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[175] + pressureSamples[176]
+ pressureSamples[177] + pressureSamples[178]
+ pressureSamples[179]) / 5);
float change = (pressureAvg[6] - pressureAvg[0]);
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * 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
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.
}
if (minuteCount < 35 && firstRound) //if time is less than 35 min on the first 3 hour interval.
return 5; // Unknown, more time needed
else if (dP_dt < (-0.25))
return 4; // Quickly falling LP, Thunderstorm, not stable
else if (dP_dt > 0.25)
return 3; // Quickly rising HP, not stable weather
else if ((dP_dt > (-0.25)) && (dP_dt < (-0.05)))
return 2; // Slowly falling Low Pressure System, stable rainy weather
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
else
return 5; // Unknown
}
@@ -0,0 +1,69 @@
// Example sketch showing how to control physical relays.
#include <Relay.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define RELAY_1 3 // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define NUMBER_OF_RELAYS 2
#define RELAY_ON 0
#define RELAY_OFF 1
Relay gw(9,10);
void setup()
{
Serial.begin(BAUD_RATE); // Used to write debug info
gw.begin(RADIO_ID);
// Register all sensors to gw (they will be created as child devices)
for (int i=0; i<NUMBER_OF_RELAYS;i++) {
gw.sendSensorPresentation(RELAY_1+i, S_LIGHT);
}
// Fetch relay status
for (int i=0; i<NUMBER_OF_RELAYS;i++) {
// Make sure relays are off when starting up
digitalWrite(RELAY_1+i, RELAY_OFF);
// Then set relay pins in output mode
pinMode(RELAY_1+i, OUTPUT);
// Request/wait for relay status
gw.getStatus(RELAY_1+i, V_LIGHT);
setRelayStatus(gw.getMessage()); // Wait here until status message arrive from gw
}
}
/*
* Example on how to asynchronously check for new messages from gw
*/
void loop()
{
if (gw.messageAvailable()) {
message_s message = gw.getMessage();
setRelayStatus(message);
}
}
void setRelayStatus(message_s message) {
if (message.header.messageType=M_SET_VARIABLE &&
message.header.type==V_LIGHT) {
int incomingRelayStatus = atoi(message.data);
// Change relay state
digitalWrite(message.header.childId, incomingRelayStatus==1?RELAY_ON:RELAY_OFF);
// Write some debug info
Serial.print("Incoming change for relay on pin:");
Serial.print(message.header.childId);
Serial.print(", New status: ");
Serial.println(incomingRelayStatus);
}
}
@@ -0,0 +1,96 @@
// Example sketch för a "light switch" where you can control light or something
// else from both vera and a local physical button (connected between digital
// pin 3 and +5V).
#include <Relay.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define RELAY_PIN 4 // Arduino Digital I/O pin number for relay
#define BUTTON_PIN 3 // Arduino Digital I/O pin number for button (with 10k pulldown)
#define CHILD_ID 1 // Id of the sensor child
#define RELAY_ON 0
#define RELAY_OFF 1
int buttVal;
int previousVal;
int state;
int switched = 0;
long pressTime = 0; // the last time the button pin was pressed
long debounce = 200; // the debounce time, increase if the output flickers
Relay gw(9,10);
void setup()
{
Serial.begin(BAUD_RATE); // Used to write debug info
gw.begin(RADIO_ID);
// Set buttonPin as Input
pinMode(BUTTON_PIN, INPUT);
buttVal = digitalRead(BUTTON_PIN); //read initial state
// Register all sensors to gw (they will be created as child devices)
gw.sendSensorPresentation(CHILD_ID, S_LIGHT);
// Make sure relays are off when starting up
digitalWrite(RELAY_PIN, RELAY_OFF);
// Then set relay pins in output mode
pinMode(RELAY_PIN, OUTPUT);
// Request/wait for relay status
gw.getStatus(CHILD_ID, V_LIGHT);
setRelayStatus(gw.getMessage()); // Wait here until status message arrive from gw
}
/*
* Example on how to asynchronously check for new messages from gw
*/
void loop()
{
if (gw.messageAvailable()) {
// ot new messsage from gw
message_s message = gw.getMessage();
setRelayStatus(message);
}
buttVal = digitalRead(BUTTON_PIN); // read input value and store it in val
if (buttVal == HIGH && previousVal == LOW) {
// Start counter from when button was pressed
pressTime = millis();
switched = 0;
}
if (buttVal == HIGH && switched == 0 && millis() - pressTime > debounce) {
// Switch state if button pressed more than 200 msec
state = state==1?0:1;
gw.sendVariable(CHILD_ID, V_LIGHT, state); // We will receive an ack message
switched = 1; // No more switches until button is released
}
previousVal = buttVal;
}
void setRelayStatus(message_s message) {
if (message.header.type==V_LIGHT) { // This could be M_ACK_VARIABLE or M_SET_VARIABLE
state = atoi(message.data);
// Change relay state
digitalWrite(RELAY_PIN, state==1?RELAY_ON:RELAY_OFF);
// Write some debug info
Serial.print(message.header.messageType == M_ACK_VARIABLE ? "Button":"Gateway");
Serial.print(" change. New state: ");
Serial.println(state == 1 ?"on":"off" );
}
}
@@ -0,0 +1,31 @@
// Example sketch showing how to create a node thay relays messages
// from nodes far from gateway back to gateway.
// Important here is that node uses Relay-class and calls
// gw.messageAvailable() frequently. This sketch should not
// sleep.
#include <Relay.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
Relay gw(9,10);
void setup()
{
Serial.begin(BAUD_RATE); // Used to write debug info
gw.begin(RADIO_ID);
}
void loop()
{
if (gw.messageAvailable()) {
// Incoming message for this node...
}
}
@@ -0,0 +1,71 @@
// Example showing how to create an atuator for a servo.
// Connect red to +5V, Black or brown to GND and the last cable to Digital pin 3.
// The servo consumes much power and should probably have its own powersource.'
// The arduino might spontanally restart if too much power is used (happend
// to me when servo tried to pass the extreme positions = full load).
#include <Sensor.h>
#include <SPI.h>
#include <EEPROM.h>
#include <Servo.h>
#include <RF24.h>
#define SERVO_DIGITAL_OUT_PIN 3
#define SERVO_MIN 30 // Fine tune your servos min. 0-180
#define SERVO_MAX 180 // Fine tune your servos max. 0-180
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define CHILD_ID 10 // Id of the sensor child
Sensor gw(9, 10);
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created Sensor gw(9,10);
void setup()
{
Serial.begin(BAUD_RATE);
gw.begin(RADIO_ID);
myservo.attach(SERVO_DIGITAL_OUT_PIN);
// Register all sensors to gw (they will be created as child devices)
gw.sendSensorPresentation(CHILD_ID, S_COVER);
// Fetch servo state at startup
gw.getStatus(CHILD_ID, V_DIMMER);
setRelayStatus(gw.getMessage()); // Wait here until status message arrive from gw
}
void loop()
{
if (gw.messageAvailable()) {
// New messsage from gw
message_s message = gw.getMessage();
setRelayStatus(message);
}
}
void setRelayStatus(message_s message) {
if (message.header.type==V_DIMMER) { // This could be M_ACK_VARIABLE or M_SET_VARIABLE
int val = atoi(message.data);
myservo.write(SERVO_MIN + (SERVO_MAX-SERVO_MIN)/100 * val); // sets the servo position 0-180
// Write some debug info
Serial.print("Servo changed. new state: ");
Serial.println(val);
} else if (message.header.type==V_UP) {
Serial.println("Servo UP command");
myservo.write(SERVO_MAX);
gw.sendVariable(CHILD_ID, V_DIMMER, 100);
} else if (message.header.type==V_DOWN) {
Serial.println("Servo DOWN command");
myservo.write(SERVO_MIN);
gw.sendVariable(CHILD_ID, V_DIMMER, 0);
} else if (message.header.type==V_STOP) {
Serial.println("Servo STOP command");
// Servo is pretty fast.. don't think we have time to send a stop
}
}
@@ -0,0 +1,47 @@
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define DIGITAL_INPUT_SOIL_SENSOR 3 // Digital input did you attach your soil sensor.
#define INTERRUPT DIGITAL_INPUT_SOIL_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
#define CHILD_ID 0 // Id of the sensor child
Sensor gw(9, 10);
Sleep sleep;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
pinMode(DIGITAL_INPUT_SOIL_SENSOR, INPUT); // sets the soil sensor digital pin as input
// Register all sensors to gw (they will be created as child devices)
gw.sendSensorPresentation(CHILD_ID, S_MOTION);
}
int lastSoilValue = -1;
void loop()
{
// Read digital soil value
int soilValue = digitalRead(DIGITAL_INPUT_SOIL_SENSOR); // 1 = Not triggered, 0 = In soil with water
if (soilValue != lastSoilValue) {
Serial.println(soilValue);
gw.sendVariable(CHILD_ID, V_TRIPPED, soilValue==0?"1":"0"); // Send the inverse to gw as tripped should be when no water in soil
lastSoilValue = soilValue;
}
// Power down the radio. Note that the radio will get powered back up
// on the next write() call.
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepInterrupt(INTERRUPT,CHANGE);
}
@@ -0,0 +1,68 @@
// Example sketch showing how to request time from vera
// and how to set a cutom variable on a sensor
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
#include <Time.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define CHILD_ID 0 // Id of the sensor child
Sensor gw(9, 10);
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
// Register any sensortype. This example we just create a motion sensor.
gw.sendSensorPresentation(CHILD_ID, S_MOTION);
setSyncProvider(getTime);
setSyncInterval(3600); // get time from gw every hour
}
unsigned long getTime() {
return gw.getTime(); // Vera is time provider
}
void loop()
{
// long time = gw.getTime();
// setTime(time);
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.print(month());
Serial.print(" ");
Serial.print(year());
Serial.println();
// Ok now send time back to gw and store in in Variable1
// of the motion sensor device
gw.sendVariable(CHILD_ID, V_VAR1, minute());
// wait 10 seconds...
delay(10000);
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
@@ -0,0 +1,151 @@
//
// Use this sensor to measure volume and flow of your house watermeter.
// You need to set the correct pulsefactor of your meter (pulses per m3).
// The sensor starts by fetching current volume reading from gateway (VAR 1).
// Reports both volume and flow back to gateway.
//
// Unfortunately millis() won't increment when the Arduino is in
// sleepmode. So we cannot make this sensor sleep if we also want
// to calculate/report flow.
//
// Sensor on pin 3
//
//
//
#include <Relay.h>
#include <Sleep_n0m1.h>
#include <SPI.h>
#include <EEPROM.h>
#include <RF24.h>
#include <Sensor.h>
// Set RADIO_ID to something unique in your sensor network (1-254)
// or set to AUTO if you want gw to assign a RADIO_ID for you.
#define RADIO_ID AUTO
#define DIGITAL_INPUT_SENSOR 3 // The digital input you attached your sensor. (Only 2 and 3 generates interrupt!)
#define PULSE_FACTOR 1000 // Nummber of blinks per m3 of your meter (One rotation/liter)
#define SLEEP_MODE false // flowvalue can only be reported when sleep mode is false.
#define MAX_FLOW 40 // Max flow (l/min) value to report. This filetrs outliers.
unsigned long SEND_FREQUENCY = 20; // Minimum time between send (in seconds). We don't want to spam the gateway.
#define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
#define CHILD_ID 5 // Id of the sensor child
Sensor gw(9,10);
//enable sleep
Sleep sleep;
double ppl = ((double)PULSE_FACTOR)/1000; // Pulses per liter
volatile unsigned long pulseCount = 0;
volatile unsigned long lastBlink = 0;
volatile double flow = 0;
unsigned long oldPulseCount = 0;
unsigned long newBlink = 0;
double oldflow = 0;
double volume;
double oldvolume;
unsigned long lastSend;
unsigned long lastPulse;
unsigned long currentTime;
boolean metric;
void setup()
{
Serial.begin(BAUD_RATE); // Used to type in characters
gw.begin(RADIO_ID);
// Register this device as Waterflow sensor
gw.sendSensorPresentation(CHILD_ID, S_WATER);
// Fetch last known pulse count value from gw
pulseCount = oldPulseCount = atol(gw.getStatus(CHILD_ID, V_VAR1));
//Serial.print("Last pulse count from gw:");
//Serial.println(pulseCount);
attachInterrupt(INTERRUPT, onPulse, RISING);
lastSend = millis();
}
void loop()
{
currentTime = millis();
// Only send values at a maximum frequency or woken up from sleep
if (SLEEP_MODE || currentTime - lastSend > 1000*SEND_FREQUENCY) {
// New flow value has been calculated
if (!SLEEP_MODE && flow != oldflow) {
// Check that we dont get unresonable large flow value.
// could hapen when long wraps or false interrupt triggered
if (flow<((unsigned long)MAX_FLOW)) {
gw.sendVariable(CHILD_ID, V_FLOW, flow, 2); // Send flow value to gw
}
//Serial.print("l/min:");
//Serial.println(flow);
oldflow = flow;
}
// No Pulse count in 2min
//Serial.print("currentTime");
//Serial.println(currentTime);
//Serial.print("lastPulse");
//Serial.println(lastPulse);
if(currentTime - lastPulse > 120000){
flow = 0;
}
// Pulse count has changed
if (pulseCount != oldPulseCount) {
gw.sendVariable(CHILD_ID, V_VAR1, pulseCount); // Send volumevalue to gw VAR1
double volume = ((double)pulseCount/((double)PULSE_FACTOR));
oldPulseCount = pulseCount;
//Serial.print("Pulse count:");
//Serial.println(pulseCount);
if (volume != oldvolume) {
gw.sendVariable(CHILD_ID, V_VOLUME, volume, 3); // Send volume value to gw
//Serial.print("m3:");
//Serial.println(volume, 3);
oldvolume = volume;
}
}
lastSend = currentTime;
}
if (SLEEP_MODE) {
delay(300); //delay to allow serial to fully print before sleep
gw.powerDown();
sleep.pwrDownMode(); //set sleep mode
sleep.sleepDelay(SEND_FREQUENCY * 1000); //sleep for: sleepTime
}
}
void onPulse()
{
if (!SLEEP_MODE) {
unsigned long newBlink = micros();
unsigned long interval = newBlink-lastBlink;
lastPulse = millis();
if (interval<500000L) {
// Sometimes we get interrupt on RISING, 500000 = 0.5sek debounce ( max 120 l/min)
return;
}
flow = (60000000.0 /interval) / ppl;
lastBlink = newBlink;
//Serial.println(flow, 4);
}
pulseCount++;
}
+231
View File
@@ -0,0 +1,231 @@
// ---------------------------------------------------------------------------
// Created by Tim Eckel - teckel@leethost.com
// Copyright 2012 License: GNU GPL v3 http://www.gnu.org/licenses/gpl-3.0.html
//
// See "NewPing.h" for purpose, syntax, version history, links, and more.
// ---------------------------------------------------------------------------
#include "NewPing.h"
// ---------------------------------------------------------------------------
// NewPing constructor
// ---------------------------------------------------------------------------
NewPing::NewPing(uint8_t trigger_pin, uint8_t echo_pin, int max_cm_distance) {
_triggerBit = digitalPinToBitMask(trigger_pin); // Get the port register bitmask for the trigger pin.
_echoBit = digitalPinToBitMask(echo_pin); // Get the port register bitmask for the echo pin.
_triggerOutput = portOutputRegister(digitalPinToPort(trigger_pin)); // Get the output port register for the trigger pin.
_echoInput = portInputRegister(digitalPinToPort(echo_pin)); // Get the input port register for the echo pin.
_triggerMode = (uint8_t *) portModeRegister(digitalPinToPort(trigger_pin)); // Get the port mode register for the trigger pin.
_maxEchoTime = min(max_cm_distance, MAX_SENSOR_DISTANCE) * US_ROUNDTRIP_CM + (US_ROUNDTRIP_CM / 2); // Calculate the maximum distance in uS.
#if DISABLE_ONE_PIN == true
*_triggerMode |= _triggerBit; // Set trigger pin to output.
#endif
}
// ---------------------------------------------------------------------------
// Standard ping methods
// ---------------------------------------------------------------------------
unsigned int NewPing::ping() {
if (!ping_trigger()) return NO_ECHO; // Trigger a ping, if it returns false, return NO_ECHO to the calling function.
while (*_echoInput & _echoBit) // Wait for the ping echo.
if (micros() > _max_time) return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
return (micros() - (_max_time - _maxEchoTime) - 5); // Calculate ping time, 5uS of overhead.
}
unsigned int NewPing::ping_in() {
unsigned int echoTime = NewPing::ping(); // Calls the ping method and returns with the ping echo distance in uS.
return NewPingConvert(echoTime, US_ROUNDTRIP_IN); // Convert uS to inches.
}
unsigned int NewPing::ping_cm() {
unsigned int echoTime = NewPing::ping(); // Calls the ping method and returns with the ping echo distance in uS.
return NewPingConvert(echoTime, US_ROUNDTRIP_CM); // Convert uS to centimeters.
}
unsigned int NewPing::ping_median(uint8_t it) {
unsigned int uS[it], last;
uint8_t j, i = 0;
uS[0] = NO_ECHO;
while (i < it) {
last = ping(); // Send ping.
if (last == NO_ECHO) { // Ping out of range.
it--; // Skip, don't include as part of median.
last = _maxEchoTime; // Adjust "last" variable so delay is correct length.
} else { // Ping in range, include as part of median.
if (i > 0) { // Don't start sort till second ping.
for (j = i; j > 0 && uS[j - 1] < last; j--) // Insertion sort loop.
uS[j] = uS[j - 1]; // Shift ping array to correct position for sort insertion.
} else j = 0; // First ping is starting point for sort.
uS[j] = last; // Add last ping to array in sorted position.
i++; // Move to next ping.
}
if (i < it) delay(PING_MEDIAN_DELAY - (last >> 10)); // Millisecond delay between pings.
}
return (uS[it >> 1]); // Return the ping distance median.
}
// ---------------------------------------------------------------------------
// Standard ping method support functions (not called directly)
// ---------------------------------------------------------------------------
boolean NewPing::ping_trigger() {
#if DISABLE_ONE_PIN != true
*_triggerMode |= _triggerBit; // Set trigger pin to output.
#endif
*_triggerOutput &= ~_triggerBit; // Set the trigger pin low, should already be low, but this will make sure it is.
delayMicroseconds(4); // Wait for pin to go low, testing shows it needs 4uS to work every time.
*_triggerOutput |= _triggerBit; // Set trigger pin high, this tells the sensor to send out a ping.
delayMicroseconds(10); // Wait long enough for the sensor to realize the trigger pin is high. Sensor specs say to wait 10uS.
*_triggerOutput &= ~_triggerBit; // Set trigger pin back to low.
#if DISABLE_ONE_PIN != true
*_triggerMode &= ~_triggerBit; // Set trigger pin to input (when using one Arduino pin this is technically setting the echo pin to input as both are tied to the same Arduino pin).
#endif
_max_time = micros() + MAX_SENSOR_DELAY; // Set a timeout for the ping to trigger.
while (*_echoInput & _echoBit && micros() <= _max_time) {} // Wait for echo pin to clear.
while (!(*_echoInput & _echoBit)) // Wait for ping to start.
if (micros() > _max_time) return false; // Something went wrong, abort.
_max_time = micros() + _maxEchoTime; // Ping started, set the timeout.
return true; // Ping started successfully.
}
// ---------------------------------------------------------------------------
// Timer interrupt ping methods (won't work with ATmega8 and ATmega128)
// ---------------------------------------------------------------------------
void NewPing::ping_timer(void (*userFunc)(void)) {
if (!ping_trigger()) return; // Trigger a ping, if it returns false, return without starting the echo timer.
timer_us(ECHO_TIMER_FREQ, userFunc); // Set ping echo timer check every ECHO_TIMER_FREQ uS.
}
boolean NewPing::check_timer() {
if (micros() > _max_time) { // Outside the timeout limit.
timer_stop(); // Disable timer interrupt
return false; // Cancel ping timer.
}
if (!(*_echoInput & _echoBit)) { // Ping echo received.
timer_stop(); // Disable timer interrupt
ping_result = (micros() - (_max_time - _maxEchoTime) - 13); // Calculate ping time, 13uS of overhead.
return true; // Return ping echo true.
}
return false; // Return false because there's no ping echo yet.
}
// ---------------------------------------------------------------------------
// Timer2/Timer4 interrupt methods (can be used for non-ultrasonic needs)
// ---------------------------------------------------------------------------
// Variables used for timer functions
void (*intFunc)();
void (*intFunc2)();
unsigned long _ms_cnt_reset;
volatile unsigned long _ms_cnt;
void NewPing::timer_us(unsigned int frequency, void (*userFunc)(void)) {
timer_setup(); // Configure the timer interrupt.
intFunc = userFunc; // User's function to call when there's a timer event.
#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
OCR4C = min((frequency>>2) - 1, 255); // Every count is 4uS, so divide by 4 (bitwise shift right 2) subtract one, then make sure we don't go over 255 limit.
TIMSK4 = (1<<TOIE4); // Enable Timer4 interrupt.
#else
OCR2A = min((frequency>>2) - 1, 255); // Every count is 4uS, so divide by 4 (bitwise shift right 2) subtract one, then make sure we don't go over 255 limit.
TIMSK2 |= (1<<OCIE2A); // Enable Timer2 interrupt.
#endif
}
void NewPing::timer_ms(unsigned long frequency, void (*userFunc)(void)) {
timer_setup(); // Configure the timer interrupt.
intFunc = NewPing::timer_ms_cntdwn; // Timer events are sent here once every ms till user's frequency is reached.
intFunc2 = userFunc; // User's function to call when user's frequency is reached.
_ms_cnt = _ms_cnt_reset = frequency; // Current ms counter and reset value.
#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
OCR4C = 249; // Every count is 4uS, so 1ms = 250 counts - 1.
TIMSK4 = (1<<TOIE4); // Enable Timer4 interrupt.
#else
OCR2A = 249; // Every count is 4uS, so 1ms = 250 counts - 1.
TIMSK2 |= (1<<OCIE2A); // Enable Timer2 interrupt.
#endif
}
void NewPing::timer_stop() { // Disable timer interrupt.
#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
TIMSK4 = 0;
#else
TIMSK2 &= ~(1<<OCIE2A);
#endif
}
// ---------------------------------------------------------------------------
// Timer2/Timer4 interrupt method support functions (not called directly)
// ---------------------------------------------------------------------------
void NewPing::timer_setup() {
#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
timer_stop(); // Disable Timer4 interrupt.
TCCR4A = TCCR4C = TCCR4D = TCCR4E = 0;
TCCR4B = (1<<CS42) | (1<<CS41) | (1<<CS40) | (1<<PSR4); // Set Timer4 prescaler to 64 (4uS/count, 4uS-1020uS range).
TIFR4 = (1<<TOV4);
TCNT4 = 0; // Reset Timer4 counter.
#else
timer_stop(); // Disable Timer2 interrupt.
ASSR &= ~(1<<AS2); // Set clock, not pin.
TCCR2A = (1<<WGM21); // Set Timer2 to CTC mode.
TCCR2B = (1<<CS22); // Set Timer2 prescaler to 64 (4uS/count, 4uS-1020uS range).
TCNT2 = 0; // Reset Timer2 counter.
#endif
}
void NewPing::timer_ms_cntdwn() {
if (!_ms_cnt--) { // Count down till we reach zero.
intFunc2(); // Scheduled time reached, run the main timer event function.
_ms_cnt = _ms_cnt_reset; // Reset the ms timer.
}
}
#if defined (__AVR_ATmega32U4__) // Use Timer4 for ATmega32U4 (Teensy/Leonardo).
ISR(TIMER4_OVF_vect) {
#else
ISR(TIMER2_COMPA_vect) {
#endif
if(intFunc) intFunc(); // If wrapped function is set, call it.
}
// ---------------------------------------------------------------------------
// Conversion methods (rounds result to nearest inch or cm).
// ---------------------------------------------------------------------------
unsigned int NewPing::convert_in(unsigned int echoTime) {
return NewPingConvert(echoTime, US_ROUNDTRIP_IN); // Convert uS to inches.
}
unsigned int NewPing::convert_cm(unsigned int echoTime) {
return NewPingConvert(echoTime, US_ROUNDTRIP_CM); // Convert uS to centimeters.
}
+162
View File
@@ -0,0 +1,162 @@
// ---------------------------------------------------------------------------
// NewPing Library - v1.5 - 08/15/2012
//
// AUTHOR/LICENSE:
// Created by Tim Eckel - teckel@leethost.com
// Copyright 2012 License: GNU GPL v3 http://www.gnu.org/licenses/gpl-3.0.html
//
// LINKS:
// Project home: http://code.google.com/p/arduino-new-ping/
// Blog: http://arduino.cc/forum/index.php/topic,106043.0.html
//
// DISCLAIMER:
// This software is furnished "as is", without technical support, and with no
// warranty, express or implied, as to its usefulness for any purpose.
//
// BACKGROUND:
// When I first received an ultrasonic sensor I was not happy with how poorly
// it worked. Quickly I realized the problem wasn't the sensor, it was the
// available ping and ultrasonic libraries causing the problem. The NewPing
// library totally fixes these problems, adds many new features, and breaths
// new life into these very affordable distance sensors.
//
// FEATURES:
// * Works with many different ultrasonic sensor models: SR04, SRF05, SRF06, DYP-ME007 & Parallax PING)))™.
// * Interface with all but the SRF06 sensor using only one Arduino pin.
// * Doesn't lag for a full second if no ping/echo is received.
// * Ping sensors consistently and reliably at up to 30 times per second.
// * Timer interrupt method for event-driven sketches.
// * Built-in digital filter method ping_median() for easy error correction.
// * Uses port registers for a faster pin interface and smaller code size.
// * Allows you to set a maximum distance where pings beyond that distance are read as no ping "clear".
// * Ease of using multiple sensors (example sketch with 15 sensors).
// * More accurate distance calculation (cm, inches & uS).
// * Doesn't use pulseIn, which is slow and gives incorrect results with some ultrasonic sensor models.
// * Actively developed with features being added and bugs/issues addressed.
//
// CONSTRUCTOR:
// NewPing sonar(trigger_pin, echo_pin [, max_cm_distance])
// trigger_pin & echo_pin - Arduino pins connected to sensor trigger and echo.
// NOTE: To use the same Arduino pin for trigger and echo, specify the same pin for both values.
// max_cm_distance - [Optional] Maximum distance you wish to sense. Default=500cm.
//
// SYNTAX:
// sonar.ping() - Send a ping and get the echo time (in microseconds) as a result.
// sonar.ping_in() - Send a ping and get the distance in whole inches.
// sonar.ping_cm() - Send a ping and get the distance in whole centimeters.
// sonar.ping_median(iterations) - Do multiple pings (default=5), discard out of range pings and return median in microseconds.
// sonar.convert_in(echoTime) - Convert echoTime from microseconds to inches (rounds to nearest inch).
// sonar.convert_cm(echoTime) - Convert echoTime from microseconds to centimeters (rounds to nearest cm).
// sonar.ping_timer(function) - Send a ping and call function to test if ping is complete.
// sonar.check_timer() - Check if ping has returned within the set distance limit.
// NewPing::timer_us(frequency, function) - Call function every frequency microseconds.
// NewPing::timer_ms(frequency, function) - Call function every frequency milliseconds.
// NewPing::timer_stop() - Stop the timer.
//
// HISTORY:
// 08/15/2012 v1.5 - Added ping_median() method which does a user specified
// number of pings (default=5) and returns the median ping in microseconds
// (out of range pings ignored). This is a very effective digital filter.
// Optimized for smaller compiled size (even smaller than skteches that
// don't use a library).
//
// 07/14/2012 v1.4 - Added support for the Parallax PING)))™ sensor. Interface
// with all but the SRF06 sensor using only one Arduino pin. You can also
// interface with the SRF06 using one pin if you install a 0.1uf capacitor
// on the trigger and echo pins of the sensor then tie the trigger pin to
// the Arduino pin (doesn't work with Teensy). To use the same Arduino pin
// for trigger and echo, specify the same pin for both values. Various bug
// fixes.
//
// 06/08/2012 v1.3 - Big feature addition, event-driven ping! Uses Timer2
// interrupt, so be mindful of PWM or timing conflicts messing with Timer2
// may cause (namely PWM on pins 3 & 11 on Arduino, PWM on pins 9 and 10 on
// Mega, and Tone library). Simple to use timer interrupt functions you can
// use in your sketches totaly unrelated to ultrasonic sensors (don't use if
// you're also using NewPing's ping_timer because both use Timer2 interrupts).
// Loop counting ping method deleted in favor of timing ping method after
// inconsistant results kept surfacing with the loop timing ping method.
// Conversion to cm and inches now rounds to the nearest cm or inch. Code
// optimized to save program space and fixed a couple minor bugs here and
// there. Many new comments added as well as line spacing to group code
// sections for better source readability.
//
// 05/25/2012 v1.2 - Lots of code clean-up thanks to Adruino Forum members.
// Rebuilt the ping timing code from scratch, ditched the pulseIn code as it
// doesn't give correct results (at least with ping sensors). The NewPing
// library is now VERY accurate and the code was simplified as a bonus.
// Smaller and faster code as well. Fixed some issues with very close ping
// results when converting to inches. All functions now return 0 only when
// there's no ping echo (out of range) and a positive value for a successful
// ping. This can effectively be used to detect if something is out of range
// or in-range and at what distance. Now compatible with Arduino 0023.
//
// 05/16/2012 v1.1 - Changed all I/O functions to use low-level port registers
// for ultra-fast and lean code (saves from 174 to 394 bytes). Tested on both
// the Arduino Uno and Teensy 2.0 but should work on all Arduino-based
// platforms because it calls standard functions to retrieve port registers
// and bit masks. Also made a couple minor fixes to defines.
//
// 05/15/2012 v1.0 - Initial release.
// ---------------------------------------------------------------------------
#ifndef NewPing_h
#define NewPing_h
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#include <pins_arduino.h>
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
// Shoudln't need to changed these values unless you have a specific need to do so.
#define MAX_SENSOR_DISTANCE 500 // Maximum sensor distance can be as high as 500cm, no reason to wait for ping longer than sound takes to travel this distance and back.
#define US_ROUNDTRIP_IN 146 // Microseconds (uS) it takes sound to travel round-trip 1 inch (2 inches total), uses integer to save compiled code space.
#define US_ROUNDTRIP_CM 57 // Microseconds (uS) it takes sound to travel round-trip 1cm (2cm total), uses integer to save compiled code space.
#define DISABLE_ONE_PIN false // Set to "true" to save up to 26 bytes of compiled code space if you're not using one pin sensor connections.
// Probably shoudln't change these values unless you really know what you're doing.
#define NO_ECHO 0 // Value returned if there's no ping echo within the specified MAX_SENSOR_DISTANCE or max_cm_distance.
#define MAX_SENSOR_DELAY 18000 // Maximum uS it takes for sensor to start the ping (SRF06 is the highest measured, just under 18ms).
#define ECHO_TIMER_FREQ 24 // Frequency to check for a ping echo (every 24uS is about 0.4cm accuracy).
#define PING_MEDIAN_DELAY 29 // Millisecond delay between pings in the ping_median method.
// Conversion from uS to distance (round result to nearest cm or inch).
#define NewPingConvert(echoTime, conversionFactor) (max((echoTime + conversionFactor / 2) / conversionFactor, (echoTime ? 1 : 0)))
class NewPing {
public:
NewPing(uint8_t trigger_pin, uint8_t echo_pin, int max_cm_distance = MAX_SENSOR_DISTANCE);
unsigned int ping();
unsigned int ping_in();
unsigned int ping_cm();
unsigned int ping_median(uint8_t it = 5);
unsigned int convert_in(unsigned int echoTime);
unsigned int convert_cm(unsigned int echoTime);
void ping_timer(void (*userFunc)(void));
boolean check_timer();
unsigned long ping_result;
static void timer_us(unsigned int frequency, void (*userFunc)(void));
static void timer_ms(unsigned long frequency, void (*userFunc)(void));
static void timer_stop();
private:
boolean ping_trigger();
boolean ping_wait_timer();
uint8_t _triggerBit;
uint8_t _echoBit;
volatile uint8_t *_triggerOutput;
volatile uint8_t *_triggerMode;
volatile uint8_t *_echoInput;
unsigned int _maxEchoTime;
unsigned long _max_time;
static void timer_setup();
static void timer_ms_cntdwn();
};
#endif
@@ -0,0 +1,74 @@
// ---------------------------------------------------------------------------
// This example code was used to successfully communicate with 15 ultrasonic sensors. You can adjust
// the number of sensors in your project by changing SONAR_NUM and the number of NewPing objects in the
// "sonar" array. You also need to change the pins for each sensor for the NewPing objects. Each sensor
// is pinged at 33ms intervals. So, one cycle of all sensors takes 495ms (33 * 15 = 495ms). The results
// are sent to the "oneSensorCycle" function which currently just displays the distance data. Your project
// would normally process the sensor results in this function (for example, decide if a robot needs to
// turn and call the turn function). Keep in mind this example is event-driven. Your complete sketch needs
// to be written so there's no "delay" commands and the loop() cycles at faster than a 33ms rate. If other
// processes take longer than 33ms, you'll need to increase PING_INTERVAL so it doesn't get behind.
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define SONAR_NUM 15 // Number or sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).
unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM]; // Where the ping distances are stored.
uint8_t currentSensor = 0; // Keeps track of which sensor is active.
NewPing sonar[SONAR_NUM] = { // Sensor object array.
NewPing(41, 42, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
NewPing(43, 44, MAX_DISTANCE),
NewPing(45, 20, MAX_DISTANCE),
NewPing(21, 22, MAX_DISTANCE),
NewPing(23, 24, MAX_DISTANCE),
NewPing(25, 26, MAX_DISTANCE),
NewPing(27, 28, MAX_DISTANCE),
NewPing(29, 30, MAX_DISTANCE),
NewPing(31, 32, MAX_DISTANCE),
NewPing(34, 33, MAX_DISTANCE),
NewPing(35, 36, MAX_DISTANCE),
NewPing(37, 38, MAX_DISTANCE),
NewPing(39, 40, MAX_DISTANCE),
NewPing(50, 51, MAX_DISTANCE),
NewPing(52, 53, MAX_DISTANCE)
};
void setup() {
Serial.begin(115200);
pingTimer[0] = millis() + 75; // First ping starts at 75ms, gives time for the Arduino to chill before starting.
for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}
void loop() {
for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
if (millis() >= pingTimer[i]) { // Is it this sensor's time to ping?
pingTimer[i] += PING_INTERVAL * SONAR_NUM; // Set next time this sensor will be pinged.
if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
sonar[currentSensor].timer_stop(); // Make sure previous timer is canceled before starting a new ping (insurance).
currentSensor = i; // Sensor being accessed.
cm[currentSensor] = 0; // Make distance zero in case there's no ping echo for this sensor.
sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
}
}
// The rest of your code would go here.
}
void echoCheck() { // If ping received, set the sensor distance to array.
if (sonar[currentSensor].check_timer())
cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}
void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
for (uint8_t i = 0; i < SONAR_NUM; i++) {
Serial.print(i);
Serial.print("=");
Serial.print(cm[i]);
Serial.print("cm ");
}
Serial.println();
}
@@ -0,0 +1,46 @@
// ---------------------------------------------------------------------------
// This example shows how to use NewPing's ping_timer method which uses the Timer2 interrupt to get the
// ping time. The advantage of using this method over the standard ping method is that it permits a more
// event-driven sketch which allows you to appear to do two things at once. An example would be to ping
// an ultrasonic sensor for a possible collision while at the same time navigating. This allows a
// properly developed sketch to multitask. Be aware that because the ping_timer method uses Timer2,
// other features or libraries that also use Timer2 would be effected. For example, the PWM function on
// pins 3 & 11 on Arduino Uno (pins 9 and 11 on Arduino Mega) and the Tone library. Note, only the PWM
// functionality of the pins is lost (as they use Timer2 to do PWM), the pins are still available to use.
// NOTE: For Teensy/Leonardo (ATmega32U4) the library uses Timer4 instead of Timer2.
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
unsigned int pingSpeed = 50; // How frequently are we going to send out a ping (in milliseconds). 50ms would be 20 times a second.
unsigned long pingTimer; // Holds the next ping time.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
pingTimer = millis(); // Start now.
}
void loop() {
// Notice how there's no delays in this sketch to allow you to do other processing in-line while doing distance pings.
if (millis() >= pingTimer) { // pingSpeed milliseconds since last ping, do another ping.
pingTimer += pingSpeed; // Set the next ping time.
sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status.
}
// Do other stuff here, really. Think of it as multi-tasking.
}
void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status.
// Don't do anything here!
if (sonar.check_timer()) { // This is how you check to see if the ping was received.
// Here's where you can add code.
Serial.print("Ping: ");
Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Ping returned, uS result in ping_result, convert to cm with US_ROUNDTRIP_CM.
Serial.println("cm");
}
// Don't do anything here!
}
@@ -0,0 +1,23 @@
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
}
@@ -0,0 +1,25 @@
// ---------------------------------------------------------------------------
// While the NewPing library's primary goal is to interface with ultrasonic sensors, interfacing with
// the Timer2 interrupt was a result of creating an interrupt-based ping method. Since these Timer2
// interrupt methods were built, the library may as well provide the functionality to use these methods
// in your sketches. This shows how simple it is (no ultrasonic sensor required). Keep in mind that
// these methods use Timer2, as does NewPing's ping_timer method for using ultrasonic sensors. You
// can't use ping_timer at the same time you're using timer_ms or timer_us as all use the same timer.
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define LED_PIN 13 // Pin with LED attached.
void setup() {
pinMode(LED_PIN, OUTPUT);
NewPing::timer_ms(500, toggleLED); // Create a Timer2 interrupt that calls toggleLED in your sketch once every 500 milliseconds.
}
void loop() {
// Do anything here, the Timer2 interrupt will take care of the flashing LED without your intervention.
}
void toggleLED() {
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle the LED.
}
+29
View File
@@ -0,0 +1,29 @@
###################################
# Syntax Coloring Map For NewPing
###################################
###################################
# Datatypes (KEYWORD1)
###################################
NewPing KEYWORD1
###################################
# Methods and Functions (KEYWORD2)
###################################
ping KEYWORD2
ping_in KEYWORD2
ping_cm KEYWORD2
ping_median KEYWORD2
ping_timer KEYWORD2
check_timer KEYWORD2
timer_us KEYWORD2
timer_ms KEYWORD2
timer_stop KEYWORD2
convert_in KEYWORD2
convert_cm KEYWORD2
###################################
# Constants (LITERAL1)
###################################
@@ -0,0 +1,318 @@
/*
* NewRemoteSwitch library v1.1.0 (20130601) made by Randy Simons http://randysimons.nl/
* See NewRemoteReceiver.h for details.
*
* License: GPLv3. See license.txt
*/
#include "NewRemoteReceiver.h"
/************
* NewRemoteReceiver
Protocol. (Copied from Wieltje, http://www.circuitsonline.net/forum/view/message/1181410#1181410,
but with slightly different timings, as measured on my device.)
_ _
'0': | |_| |_____ (T,T,T,5T)
_ _
'1': | |_____| |_ (T,5T,T,T)
_ _
dim: | |_| |_ (T,T,T,T)
T = short period of ~260µs. However, this code tries
to figure out the correct period
A full frame looks like this:
- start pulse: 1T high, 10.44T low
- 26 bit: Address
- 1 bit: group bit
- 1 bit: on/off/[dim]
- 4 bit: unit
- [4 bit: dim level. Only present of [dim] is chosen]
- stop pulse: 1T high, 40T low
************/
int8_t NewRemoteReceiver::_interrupt;
volatile short NewRemoteReceiver::_state;
byte NewRemoteReceiver::_minRepeats;
NewRemoteReceiverCallBack NewRemoteReceiver::_callback;
boolean NewRemoteReceiver::_inCallback = false;
boolean NewRemoteReceiver::_enabled = false;
void NewRemoteReceiver::init(int8_t interrupt, byte minRepeats, NewRemoteReceiverCallBack callback) {
_interrupt = interrupt;
_minRepeats = minRepeats;
_callback = callback;
enable();
if (_interrupt >= 0) {
attachInterrupt(_interrupt, interruptHandler, CHANGE);
}
}
void NewRemoteReceiver::enable() {
_state = -1;
_enabled = true;
}
void NewRemoteReceiver::disable() {
_enabled = false;
}
void NewRemoteReceiver::deinit() {
_enabled = false;
if (_interrupt >= 0) {
detachInterrupt(_interrupt);
}
}
void NewRemoteReceiver::interruptHandler() {
// This method is written as compact code to keep it fast. While breaking up this method into more
// methods would certainly increase the readability, it would also be much slower to execute.
// Making calls to other methods is quite expensive on AVR. As These interrupt handlers are called
// many times a second, calling other methods should be kept to a minimum.
if (!_enabled) {
return;
}
static byte receivedBit; // Contains "bit" currently receiving
static NewRemoteCode receivedCode; // Contains received code
static NewRemoteCode previousCode; // Contains previous received code
static byte repeats = 0; // The number of times the an identical code is received in a row.
static unsigned long edgeTimeStamp[3] = {0, }; // Timestamp of edges
static unsigned int min1Period, max1Period, min5Period, max5Period;
static bool skip;
// Filter out too short pulses. This method works as a low pass filter.
edgeTimeStamp[1] = edgeTimeStamp[2];
edgeTimeStamp[2] = micros();
if (skip) {
skip = false;
return;
}
if (_state >= 0 && edgeTimeStamp[2]-edgeTimeStamp[1] < min1Period) {
// Last edge was too short.
// Skip this edge, and the next too.
skip = true;
return;
}
unsigned int duration = edgeTimeStamp[1] - edgeTimeStamp[0];
edgeTimeStamp[0] = edgeTimeStamp[1];
// Note that if state>=0, duration is always >= 1 period.
if (_state == -1) {
// wait for the long low part of a stop bit.
// Stopbit: 1T high, 40T low
// By default 1T is 260µs, but for maximum compatibility go as low as 120µs
if (duration > 4800) { // =40*120µs, minimal time between two edges before decoding starts.
// Sync signal received.. Preparing for decoding
repeats = 0;
receivedCode.period = duration / 40; // Measured signal is 40T, so 1T (period) is measured signal / 40.
// Allow for large error-margin. ElCheapo-hardware :(
min1Period = receivedCode.period * 3 / 10; // Lower limit for 1 period is 0.3 times measured period; high signals can "linger" a bit sometimes, making low signals quite short.
max1Period = receivedCode.period * 3; // Upper limit for 1 period is 3 times measured period
min5Period = receivedCode.period * 3; // Lower limit for 5 periods is 3 times measured period
max5Period = receivedCode.period * 8; // Upper limit for 5 periods is 8 times measured period
}
else {
return;
}
} else if (_state == 0) { // Verify start bit part 1 of 2
// Duration must be ~1T
if (duration > max1Period) {
_state = -1;
return;
}
// Start-bit passed. Do some clean-up.
receivedCode.address = receivedCode.unit = receivedCode.dimLevel = 0;
} else if (_state == 1) { // Verify start bit part 2 of 2
// Duration must be ~10.44T
if (duration < 7 * receivedCode.period || duration > 15 * receivedCode.period) {
_state = -1;
return;
}
} else if (_state < 148) { // state 146 is first edge of stop-sequence. All bits before that adhere to default protocol, with exception of dim-bit
receivedBit <<= 1;
// One bit consists out of 4 bit parts.
// bit part durations can ONLY be 1 or 5 periods.
if (duration <= max1Period) {
receivedBit &= B1110; // Clear LSB of receivedBit
} else if (duration >= min5Period && duration <= max5Period) {
receivedBit |= B1; // Set LSB of receivedBit
} else if (
// Check if duration matches the second part of stopbit (duration must be ~40T), and ...
(duration >= 20 * receivedCode.period && duration <= 80 * receivedCode.period) &&
// if first part op stopbit was a short signal (short signal yielded a 0 as second bit in receivedBit), and ...
((receivedBit & B10) == B00) &&
// we are in a state in which a stopbit is actually valid, only then ...
(_state == 147 || _state == 131) ) {
// If a dim-level was present...
if (_state == 147) {
// ... test if it was an "on" signal ...
if (receivedCode.switchType == NewRemoteCode::on) {
// ... set the appropriate switch type
receivedCode.switchType = NewRemoteCode::on_with_dim;
} else {
// ... otherwise it was wrong (e.g. off-signal with dim)
_state = -1;
return;
}
}
// a valid signal was found!
if (
receivedCode.address != previousCode.address ||
receivedCode.unit != previousCode.unit ||
receivedCode.dimLevel != previousCode.dimLevel ||
receivedCode.groupBit != previousCode.groupBit ||
receivedCode.switchType != previousCode.switchType
) { // memcmp isn't deemed safe
repeats=0;
previousCode = receivedCode;
}
repeats++;
if (repeats>=_minRepeats) {
if (!_inCallback) {
_inCallback = true;
(_callback)(receivedCode);
_inCallback = false;
}
// Reset after callback.
_state=-1;
return;
}
// Reset for next round
_state=0; // no need to wait for another sync-bit!
return;
}
else { // Otherwise the entire sequence is invalid
_state = -1;
return;
}
if (_state % 4 == 1) { // Last bit part? Note: this is the short version of "if ( (_state-2) % 4 == 3 )"
// There are 3 valid options for receivedBit:
// 0, indicated by short short short long == B0001.
// 1, short long shot short == B0100.
// dim, short shot short shot == B0000.
// Everything else: inconsistent data, trash the whole sequence.
if (_state < 106) {
// States 2 - 105 are address bit states
receivedCode.address <<= 1;
// Decode bit. Only 4 LSB's of receivedBit are used; trim the rest.
switch (receivedBit & B1111) {
case B0001: // Bit "0" received.
// receivedCode.address |= 0; But let's not do that, as it is wasteful.
break;
case B0100: // Bit "1" received.
receivedCode.address |= 1;
break;
default: // Bit was invalid. Abort.
_state = -1;
return;
}
} else if (_state < 110) {
// States 106 - 109 are group bit states.
switch (receivedBit & B1111) {
case B0001: // Bit "0" received.
receivedCode.groupBit = false;
break;
case B0100: // Bit "1" received.
receivedCode.groupBit = true;
break;
default: // Bit was invalid. Abort.
_state = -1;
return;
}
} else if (_state < 114) {
// States 110 - 113 are switch bit states.
switch (receivedBit & B1111) {
case B0001: // Bit "0" received.
receivedCode.switchType = NewRemoteCode::off;
break;
case B0100: // Bit "1" received. Note: this might turn out to be a on_with_dim signal.
receivedCode.switchType = NewRemoteCode::on;
break;
case B0000: // Bit "dim" received.
receivedCode.switchType = NewRemoteCode::dim;
break;
default: // Bit was invalid. Abort.
_state = -1;
return;
}
} else if (_state < 130){
// States 114 - 129 are unit bit states.
receivedCode.unit <<= 1;
// Decode bit.
switch (receivedBit & B1111) {
case B0001: // Bit "0" received.
// receivedCode.unit |= 0; But let's not do that, as it is wasteful.
break;
case B0100: // Bit "1" received.
receivedCode.unit |= 1;
break;
default: // Bit was invalid. Abort.
_state = -1;
return;
}
} else if (_state < 146) {
// States 130 - 145 are dim bit states.
// If switchType == 0 these are never present.
// If switchType == 2 these are always present.
// If switchType == 1 these are or are not present, depending on the revision of the transmitter.
receivedCode.dimLevel <<= 1;
// Decode bit.
switch (receivedBit & B1111) {
case B0001: // Bit "0" received.
// receivedCode.dimLevel |= 0; But let's not do that, as it is wasteful.
break;
case B0100: // Bit "1" received.
receivedCode.dimLevel |= 1;
break;
default: // Bit was invalid. Abort.
_state = -1;
return;
}
}
}
}
_state++;
return;
}
boolean NewRemoteReceiver::isReceiving(int waitMillis) {
unsigned long startTime=millis();
int waited; // Signed int!
do {
if (_state >= 34) { // Abort if a significant part of a code (start pulse + 8 bits) has been received
return true;
}
waited = (millis()-startTime);
} while(waited>=0 && waited <= waitMillis); // Yes, clock wraps every 50 days. And then you'd have to wait for a looooong time.
return false;
}
@@ -0,0 +1,107 @@
/*
* NewRemoteSwitch library v1.1.0 (20130601) made by Randy Simons http://randysimons.nl/
*
* License: GPLv3. See license.txt
*/
#ifndef NewRemoteReceiver_h
#define NewRemoteReceiver_h
#include <Arduino.h>
struct NewRemoteCode {
enum SwitchType {
off = 0,
on = 1,
dim = 2,
on_with_dim = 3
};
unsigned int period; // Detected duration in microseconds of 1T in the received signal
unsigned long address; // Address of received code. [0..2^26-1]
boolean groupBit; // Group bit set or not
SwitchType switchType; // off, on, dim, on_with_dim.
byte unit; // Unit code of received code [0..15]
byte dimLevel; // Dim level [0..15] iff switchType == 2
};
typedef void (*NewRemoteReceiverCallBack)(NewRemoteCode);
/**
* See RemoteSwitch for introduction.
*
* NewRemoteReceiver decodes the signal received from a 433MHz-receiver, like the "KlikAanKlikUit"-system
* as well as the signal sent by the RemoteSwtich class. When a correct signal is received,
* a user-defined callback function is called.
*
* Note that in the callback function, the interrupts are still disabled. You can enabled them, if needed.
* A call to the callback must be finished before NewRemoteReceiver will call the callback function again, thus
* there is no re-entrant problem.
*
* When sending your own code using NewRemoteSwich, disable() the receiver first.
*
* This is a pure static class, for simplicity and to limit memory-use.
*/
class NewRemoteReceiver {
public:
/**
* Initializes the decoder.
*
* If interrupt >= 0, init will register pin <interrupt> to this library.
* If interrupt < 0, no interrupt is registered. In that case, you have to call interruptHandler()
* yourself whenever the output of the receiver changes, or you can use InterruptChain.
*
* @param interrupt The interrupt as is used by Arduino's attachInterrupt function. See attachInterrupt for details.
If < 0, you must call interruptHandler() yourself.
* @param minRepeats The number of times the same code must be received in a row before the callback is calles
* @param callback Pointer to a callback function, with signature void (*func)(NewRemoteCode)
*/
static void init(int8_t interrupt, byte minRepeats, NewRemoteReceiverCallBack callback);
/**
* Enable decoding. No need to call enable() after init().
*/
static void enable();
/**
* Disable decoding. You can re-enable decoding by calling enable();
*/
static void disable();
/**
* Deinitializes the decoder. Disables decoding and detaches the interrupt handler. If you want to
* re-enable decoding, call init() again.
*/
static void deinit();
/**
* Tells wether a signal is being received. If a compatible signal is detected within the time out, isReceiving returns true.
* Since it makes no sense to transmit while another transmitter is active, it's best to wait for isReceiving() to false.
* By default it waits for 150ms, in which a (relative slow) KaKu signal can be broadcasted three times.
*
* Note: isReceiving() depends on interrupts enabled. Thus, when disabled()'ed, or when interrupts are disabled (as is
* the case in the callback), isReceiving() will not work properly.
*
* @param waitMillis number of milliseconds to monitor for signal.
* @return boolean If after waitMillis no signal was being processed, returns false. If before expiration a signal was being processed, returns true.
*/
static boolean isReceiving(int waitMillis = 150);
/**
* Called every time the signal level changes (high to low or vice versa). Usually called by interrupt.
*/
static void interruptHandler();
private:
static int8_t _interrupt; // Radio input interrupt
volatile static short _state; // State of decoding process.
static byte _minRepeats;
static NewRemoteReceiverCallBack _callback;
static boolean _inCallback; // When true, the callback function is being executed; prevents re-entrance.
static boolean _enabled; // If true, monitoring and decoding is enabled. If false, interruptHandler will return immediately.
};
#endif
@@ -0,0 +1,134 @@
/*
* NewRemoteSwitch library v1.1.0 (20130601) made by Randy Simons http://randysimons.nl/
* See NewRemoteTransmitter.h for details.
*
* License: GPLv3. See license.txt
*/
#include "NewRemoteTransmitter.h"
NewRemoteTransmitter::NewRemoteTransmitter(unsigned long address, byte pin, unsigned int periodusec, byte repeats) {
_address = address;
_pin = pin;
_periodusec = periodusec;
_repeats = (1 << repeats) - 1; // I.e. _repeats = 2^repeats - 1
pinMode(_pin, OUTPUT);
}
void NewRemoteTransmitter::sendGroup(boolean switchOn) {
for (int8_t i = _repeats; i >= 0; i--) {
_sendStartPulse();
_sendAddress();
// Do send group bit
_sendBit(true);
// Switch on | off
_sendBit(switchOn);
// No unit. Is this actually ignored?..
_sendUnit(0);
_sendStopPulse();
}
}
void NewRemoteTransmitter::sendUnit(byte unit, boolean switchOn) {
for (int8_t i = _repeats; i >= 0; i--) {
_sendStartPulse();
_sendAddress();
// No group bit
_sendBit(false);
// Switch on | off
_sendBit(switchOn);
_sendUnit(unit);
_sendStopPulse();
}
}
void NewRemoteTransmitter::sendDim(byte unit, byte dimLevel) {
for (int8_t i = _repeats; i >= 0; i--) {
_sendStartPulse();
_sendAddress();
// No group bit
_sendBit(false);
// Switch type 'dim'
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec);
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec);
_sendUnit(unit);
for (int8_t j=3; j>=0; j--) {
_sendBit(dimLevel & 1<<j);
}
_sendStopPulse();
}
}
void NewRemoteTransmitter::_sendStartPulse(){
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec * 10 + (_periodusec >> 1)); // Actually 10.5T insteat of 10.44T. Close enough.
}
void NewRemoteTransmitter::_sendAddress() {
for (int8_t i=25; i>=0; i--) {
_sendBit((_address >> i) & 1);
}
}
void NewRemoteTransmitter::_sendUnit(byte unit) {
for (int8_t i=3; i>=0; i--) {
_sendBit(unit & 1<<i);
}
}
void NewRemoteTransmitter::_sendStopPulse() {
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec * 40);
}
void NewRemoteTransmitter::_sendBit(boolean isBitOne) {
if (isBitOne) {
// Send '1'
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec * 5);
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec);
} else {
// Send '0'
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec);
digitalWrite(_pin, HIGH);
delayMicroseconds(_periodusec);
digitalWrite(_pin, LOW);
delayMicroseconds(_periodusec * 5);
}
}
@@ -0,0 +1,103 @@
/*
* NewRemoteSwitch library v1.1.0 (20130601) made by Randy Simons http://randysimons.nl/
*
* License: GPLv3. See license.txt
*/
#ifndef NewRemoteTransmitter_h
#define NewRemoteTransmitter_h
#include <Arduino.h>
/**
* NewRemoteTransmitter provides a generic class for simulation of common RF remote controls, like the A-series
* 'Klik aan Klik uit'-system (http://www.klikaanklikuit.nl/), used to remotely switch lights etc.
*
* This class is meant for new-style remotes, usually accompanied by receivers with "code learning"
* capabilities. For other remotes, use the RemoteTransmitter class.
*
* Hardware required for this library: a 433MHz/434MHz SAW oscillator transmitter, e.g.
* http://www.sparkfun.com/products/10534
* http://www.conrad.nl/goto/?product=130428
*
* Notes:
* - I measured the period length with an oscilloscope, using a A-series KAKU transmitter. Other devices
* or manufacturers may use other period length. Use the ShowReceivedCodeNewRemote example to find the
* period length for your devices.
* - You can copy the address of your "real" remotes, so you won't have to learn new codes into the receivers.
* In effect this duplicates a remote. But you can also pick a random number in the range 0..2^26-1.
*/
class NewRemoteTransmitter {
public:
/**
* Constructor.
*
* To obtain the correct period length, use the ShowReceivedCodeNewRemote example, or you
* can use an oscilloscope.
*
* @param address Address of this transmitter [0..2^26-1] Duplicate the address of your hardware, or choose a random number.
* @param pin Output pin on Arduino to which the transmitter is connected
* @param periodusec Duration of one period, in microseconds. One bit takes 8 periods (but only 4 for 'dim' signal).
* @param repeats [0..8] The 2log-Number of times the signal is repeated. The actual number of repeats will be 2^repeats. 2 would be bare minimum, 4 seems robust, 8 is maximum (and overkill).
*/
NewRemoteTransmitter(unsigned long address, byte pin, unsigned int periodusec = 260, byte repeats = 4);
/**
* Send on/off command to the address group.
*
* @param switchOn True to send "on" signal, false to send "off" signal.
*/
void sendGroup(boolean switchOn);
/**
* Send on/off command to an unit on the current address.
*
* @param unit [0..15] target unit.
* @param switchOn True to send "on" signal, false to send "off" signal.
*/
void sendUnit(byte unit, boolean switchOn);
/**
* Send dim value to an unit on the current address.
*
* @param unit [0..15] target unit.
* @param dimLevel [0..15] Dim level. 0 for off, 15 for brightest level.
*/
void sendDim(byte unit, byte dimLevel);
protected:
unsigned long _address; // Address of this transmitter.
byte _pin; // Transmitter output pin
unsigned int _periodusec; // Oscillator period in microseconds
byte _repeats; // Number over repetitions of one telegram
/**
* Transmits start-pulse
*/
void _sendStartPulse();
/**
* Transmits address part
*/
void _sendAddress();
/**
* Transmits unit part.
*
* @param unit [0-15] target unit.
*/
void _sendUnit(byte unit);
/**
* Transmits stop pulse.
*/
void _sendStopPulse();
/**
* Transmits a single bit.
*
* @param isBitOne True, to send '1', false to send '0'.
*/
void _sendBit(boolean isBitOne);
};
#endif
+48
View File
@@ -0,0 +1,48 @@
NewRemoteSwitch library v1.1.0 (BETA) for Arduino 1.0
Made by Randy Simons http://randysimons.nl/
This library provides an easy class for Arduino, to send and receive signals
used by some common "new style" 433MHz remote control switches.
There are two styles of remote:
- "old style", which uses switches or a dial to set the house code. Use the
RemoteSwitch library instead.
- "new style", which use a button on the receivers to "learn" a signal. Use
this library.
License: GPLv3. See ./NewRemoteSwitch/license.txt
Latest source and wiki: https://bitbucket.org/fuzzillogic/433mhzforarduino
Installation of library:
- Make sure Arduino is closed
- Copy the directory NewRemoteSwitch to the Arduino library directory (usually
<Sketchbook directory>/libraries/)
See http://arduino.cc/en/Guide/Libraries for detailed instructions.
Default installation demo:
- Connect the data-out-pin of a 433MHz receiver to digital pin 2. See photo.
(Note: your hardware may have a different pin configuration!)
- Start Arduino, and open the example: File -> Examples -> NewRemoteSwitch ->
ShowReceivedCode or ShowReceivedCodeNewRemote.
- Compile, upload and run
- Open serial monitor in Arduino (115200 baud)
- Press buttons on a 433MHz-remote, and watch the serial monitor
Changelog:
NewRemoteSwitch library v1.1.0 (20130601) for Arduino 1.0
- BUGFIX: in many occasions, when receiving a dim-level, the code was rejected
even if the signal was correct.
- Support decoding A-series transmitters which transmit a dim-level in
combination with an on-signal, instead of a dim-signal.
- Uses NewRemodeCode::on, ::off, ::dim, ::on_with_dim instead of 0, 1, 2 and 3,
for better readability. This change is backwards compatible.
- Updated examples to use the new NewRemodeCode::on, ::off, ::dim and
::on_with_dim notation.
- Reduced memory usage (Flash, RAM)
NewRemoteSwitch library v1.0.0 (20121229) for Arduino 1.0
- Support for receiving A-series Klik-aan-klik-uit remote. (NewRemoteReceiver)
- With examples to test and demonstrate.
Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

@@ -0,0 +1,23 @@
= Protocol of klikaanklikuit A-series devices =
Copied from Wieltje, http://www.circuitsonline.net/forum/view/message/1181410#1181410,
but with slightly different timings, as measured on my device.
_ _
'0': | |_| |_____ (T,T,T,5T)
_ _
'1': | |_____| |_ (T,5T,T,T)
_ _
'dim': | |_| |_ (T,T,T,T)
T = short period of ~260µs. Use the ShowReceivedCodeNewRemote example to find the
actual period length for your devices.
A full frame looks like this:
- start pulse: 1T high, 10.44T low
- 26 bit: Address
- 1 bit: group bit
- 1 bit: on/off/[dim]
- 4 bit: unit
- [4 bit: dim level. Only present of [dim] is chosen]
- stop pulse: 1T high, 40T low
@@ -0,0 +1,64 @@
/*
* Demo for RF remote switch receiver.
* This example is for the new KaKu / Home Easy type of remotes!
*
* For details, see NewRemoteReceiver.h!
*
* With this sketch you can control a LED connected to digital pin 13,
* after the sketch learned the code. After start, the LED starts to blink,
* until a valid code has been received. The led stops blinking. Now you
* can control the LED with the remote.
*
* Note: only unit-switches are supported in this sketch, no group or dim.
*
* Set-up: connect the receiver to digital pin 2 and a LED to digital pin 13.
*/
#include <NewRemoteReceiver.h>
boolean codeLearned = false;
unsigned long learnedAddress;
byte learnedUnit;
void setup() {
// LED-pin as output
pinMode(13, OUTPUT);
// Init a new receiver on interrupt pin 0, minimal 2 identical repeats, and callback set to processCode.
NewRemoteReceiver::init(0, 2, processCode);
}
void loop() {
// Blink led until a code has been learned
if (!codeLearned) {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
}
// Callback function is called only when a valid code is received.
void processCode(NewRemoteCode receivedCode) {
// A code has been received.
// Do we already know the code?
if (!codeLearned) {
// No! Let's learn the received code.
learnedAddress = receivedCode.address;
learnedUnit = receivedCode.unit;
codeLearned = true;
} else {
// Yes!
// Is the received code identical to the learned code?
if (receivedCode.address == learnedAddress && receivedCode.unit == learnedUnit) {
// Yes!
// Switch the LED off if the received code was "off".
// Anything else (on, dim, on_with_dim) will switch the LED on.
if (receivedCode.switchType == NewRemoteCode::off) {
digitalWrite(13, LOW);
} else {
digitalWrite(13, HIGH);
}
}
}
}
@@ -0,0 +1,55 @@
/**
* Demo for RF remote switch receiver.
* For details, see NewRemoteReceiver.h!
*
* Connect the transmitter to digital pin 11.
*
* This sketch demonstrates the use of the NewRemoteTransmitter class.
*
* When run, this sketch switches some pre-defined devices on and off in a loop.
*
* NOTE: the actual receivers have the address and group numbers in this example
* are only for demonstration! If you want to duplicate an existing remote, please
* try the "retransmitter"-example instead.
*
* To use this actual example, you'd need to "learn" the used code in the receivers
* This sketch is unsuited for that.
*
*/
#include <NewRemoteTransmitter.h>
// Create a transmitter on address 123, using digital pin 11 to transmit,
// with a period duration of 260ms (default), repeating the transmitted
// code 2^3=8 times.
NewRemoteTransmitter transmitter(123, 11, 260, 3);
void setup() {
}
void loop() {
// Switch unit 2 off
transmitter.sendUnit(2, false);
// Switch all devices in the group off
transmitter.sendGroup(false);
// Set unit 1 to dim-level 3 (range 0-15)
transmitter.sendDim(1, 3);
// Wait 5 seconds
delay(5000);
// Switch unit 2 on
transmitter.sendUnit(2, true);
// Switch all devices in the group on
transmitter.sendGroup(true);
// Set unit 1 to dim-level 15, full brightness.
transmitter.sendDim(1, 15);
// Wait 5 seconds
delay(5000);
}
@@ -0,0 +1,53 @@
/*
* Demo for RF remote switch receiver.
* For details, see NewRemoteReceiver.h!
*
* Connect the transmitter to digital pin 11, and the receiver to digital pin 2.
*
* When run, this sketch waits for a valid code from a new-style the receiver,
* decodes it, and retransmits it after 5 seconds.
*/
#include <NewRemoteReceiver.h>
#include <NewRemoteTransmitter.h>
void setup() {
// See example ShowReceivedCode for info on this
NewRemoteReceiver::init(0, 2, retransmitter);
}
void loop() {
}
void retransmitter(NewRemoteCode receivedCode) {
// Disable the receiver; otherwise it might pick up the retransmit as well.
NewRemoteReceiver::disable();
// Need interrupts for delay()
interrupts();
// Wait 5 seconds before sending.
delay(5000);
// Create a new transmitter with the received address and period, use digital pin 11 as output pin
NewRemoteTransmitter transmitter(receivedCode.address, 11, receivedCode.period);
if (receivedCode.switchType == NewRemoteCode::dim) {
// Dimmer signal received
transmitter.sendDim(receivedCode.unit, receivedCode.dimLevel);
} else {
// On/Off signal received
bool isOn = receivedCode.switchType == NewRemoteCode::on || receivedCode.switchType == NewRemoteCode::on_with_dim;
if (receivedCode.groupBit) {
// Send to the group
transmitter.sendGroup(isOn);
} else {
// Send to a single unit
transmitter.sendUnit(receivedCode.unit, isOn);
}
}
NewRemoteReceiver::enable();
}
@@ -0,0 +1,65 @@
/*
* Demo for RF remote switch receiver.
* This example is for the new KaKu / Home Easy type of remotes!
* For details, see NewRemoteReceiver.h!
*
* This sketch shows the received signals on the serial port.
* Connect the receiver to digital pin 2.
*/
#include <NewRemoteReceiver.h>
void setup() {
Serial.begin(115200);
// Initialize receiver on interrupt 0 (= digital pin 2), calls the callback "showCode"
// after 2 identical codes have been received in a row. (thus, keep the button pressed
// for a moment)
//
// See the interrupt-parameter of attachInterrupt for possible values (and pins)
// to connect the receiver.
NewRemoteReceiver::init(0, 2, showCode);
}
void loop() {
}
// Callback function is called only when a valid code is received.
void showCode(NewRemoteCode receivedCode) {
// Note: interrupts are disabled. You can re-enable them if needed.
// Print the received code.
Serial.print("Addr ");
Serial.print(receivedCode.address);
if (receivedCode.groupBit) {
Serial.print(" group");
} else {
Serial.print(" unit ");
Serial.print(receivedCode.unit);
}
switch (receivedCode.switchType) {
case NewRemoteCode::off:
Serial.print(" off");
break;
case NewRemoteCode::on:
Serial.print(" on");
break;
case NewRemoteCode::dim:
Serial.print(" dim level ");
Serial.print(receivedCode.dimLevel);
break;
case NewRemoteCode::on_with_dim:
Serial.print(" on with dim level ");
Serial.print(receivedCode.dimLevel);
break;
}
Serial.print(", period: ");
Serial.print(receivedCode.period);
Serial.println("us.");
}
+11
View File
@@ -0,0 +1,11 @@
NewRemoteReceiver KEYWORD1
NewRemoteCode KEYWORD1
isReceiving KEYWORD2
init KEYWORD2
enable KEYWORD2
disable KEYWORD2
deinit KEYWORD2
NewRemoteTransmitter KEYWORD1
sendGroup KEYWORD2
sendUnit KEYWORD2
sendDim KEYWORD2
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+527
View File
@@ -0,0 +1,527 @@
/*
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
Version 2.1:
Arduino 1.0 compatibility, Paul Stoffregen
Improve temperature example, Paul Stoffregen
DS250x_PROM example, Guillermo Lovato
PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com
Improvements from Glenn Trewitt:
- crc16() now works
- check_crc16() does all of calculation/checking work.
- Added read_bytes() and write_bytes(), to reduce tedious loops.
- Added ds2408 example.
Delete very old, out-of-date readme file (info is here)
Version 2.0: Modifications by Paul Stoffregen, January 2010:
http://www.pjrc.com/teensy/td_libs_OneWire.html
Search fix from Robin James
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27
Use direct optimized I/O in all cases
Disable interrupts during timing critical sections
(this solves many random communication errors)
Disable interrupts during read-modify-write I/O
Reduce RAM consumption by eliminating unnecessary
variables and trimming many to 8 bits
Optimize both crc8 - table version moved to flash
Modified to work with larger numbers of devices - avoids loop.
Tested in Arduino 11 alpha with 12 sensors.
26 Sept 2008 -- Robin James
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27
Updated to work with arduino-0008 and to include skip() as of
2007/07/06. --RJL20
Modified to calculate the 8-bit CRC directly, avoiding the need for
the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010
-- Tom Pollard, Jan 23, 2008
Jim Studt's original library was modified by Josh Larios.
Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008
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.
Much of the code was inspired by Derek Yerger's code, though I don't
think much of that remains. In any event that was..
(copyleft) 2006 by Derek Yerger - Free to distribute freely.
The CRC code was excerpted and inspired by the Dallas Semiconductor
sample code bearing this copyright.
//---------------------------------------------------------------------------
// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved.
//
// 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 DALLAS SEMICONDUCTOR 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.
//
// Except as contained in this notice, the name of Dallas Semiconductor
// shall not be used except as stated in the Dallas Semiconductor
// Branding Policy.
//--------------------------------------------------------------------------
*/
#include "OneWire.h"
OneWire::OneWire(uint8_t pin)
{
pinMode(pin, INPUT);
bitmask = PIN_TO_BITMASK(pin);
baseReg = PIN_TO_BASEREG(pin);
#if ONEWIRE_SEARCH
reset_search();
#endif
}
// Perform the onewire reset function. We will wait up to 250uS for
// the bus to come high, if it doesn't then it is broken or shorted
// and we return a 0;
//
// Returns 1 if a device asserted a presence pulse, 0 otherwise.
//
uint8_t OneWire::reset(void)
{
IO_REG_TYPE mask = bitmask;
volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg;
uint8_t r;
uint8_t retries = 125;
noInterrupts();
DIRECT_MODE_INPUT(reg, mask);
interrupts();
// wait until the wire is high... just in case
do {
if (--retries == 0) return 0;
delayMicroseconds(2);
} while ( !DIRECT_READ(reg, mask));
noInterrupts();
DIRECT_WRITE_LOW(reg, mask);
DIRECT_MODE_OUTPUT(reg, mask); // drive output low
interrupts();
delayMicroseconds(500);
noInterrupts();
DIRECT_MODE_INPUT(reg, mask); // allow it to float
delayMicroseconds(80);
r = !DIRECT_READ(reg, mask);
interrupts();
delayMicroseconds(420);
return r;
}
//
// Write a bit. Port and bit is used to cut lookup time and provide
// more certain timing.
//
void OneWire::write_bit(uint8_t v)
{
IO_REG_TYPE mask=bitmask;
volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg;
if (v & 1) {
noInterrupts();
DIRECT_WRITE_LOW(reg, mask);
DIRECT_MODE_OUTPUT(reg, mask); // drive output low
delayMicroseconds(10);
DIRECT_WRITE_HIGH(reg, mask); // drive output high
interrupts();
delayMicroseconds(55);
} else {
noInterrupts();
DIRECT_WRITE_LOW(reg, mask);
DIRECT_MODE_OUTPUT(reg, mask); // drive output low
delayMicroseconds(65);
DIRECT_WRITE_HIGH(reg, mask); // drive output high
interrupts();
delayMicroseconds(5);
}
}
//
// Read a bit. Port and bit is used to cut lookup time and provide
// more certain timing.
//
uint8_t OneWire::read_bit(void)
{
IO_REG_TYPE mask=bitmask;
volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg;
uint8_t r;
noInterrupts();
DIRECT_MODE_OUTPUT(reg, mask);
DIRECT_WRITE_LOW(reg, mask);
delayMicroseconds(3);
DIRECT_MODE_INPUT(reg, mask); // let pin float, pull up will raise
delayMicroseconds(10);
r = DIRECT_READ(reg, mask);
interrupts();
delayMicroseconds(53);
return r;
}
//
// Write a byte. The writing code uses the active drivers to raise the
// pin high, if you need power after the write (e.g. DS18S20 in
// parasite power mode) then set 'power' to 1, otherwise the pin will
// go tri-state at the end of the write to avoid heating in a short or
// other mishap.
//
void OneWire::write(uint8_t v, uint8_t power /* = 0 */) {
uint8_t bitMask;
for (bitMask = 0x01; bitMask; bitMask <<= 1) {
OneWire::write_bit( (bitMask & v)?1:0);
}
if ( !power) {
noInterrupts();
DIRECT_MODE_INPUT(baseReg, bitmask);
DIRECT_WRITE_LOW(baseReg, bitmask);
interrupts();
}
}
void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) {
for (uint16_t i = 0 ; i < count ; i++)
write(buf[i]);
if (!power) {
noInterrupts();
DIRECT_MODE_INPUT(baseReg, bitmask);
DIRECT_WRITE_LOW(baseReg, bitmask);
interrupts();
}
}
//
// Read a byte
//
uint8_t OneWire::read() {
uint8_t bitMask;
uint8_t r = 0;
for (bitMask = 0x01; bitMask; bitMask <<= 1) {
if ( OneWire::read_bit()) r |= bitMask;
}
return r;
}
void OneWire::read_bytes(uint8_t *buf, uint16_t count) {
for (uint16_t i = 0 ; i < count ; i++)
buf[i] = read();
}
//
// Do a ROM select
//
void OneWire::select( uint8_t rom[8])
{
int i;
write(0x55); // Choose ROM
for( i = 0; i < 8; i++) write(rom[i]);
}
//
// Do a ROM skip
//
void OneWire::skip()
{
write(0xCC); // Skip ROM
}
void OneWire::depower()
{
noInterrupts();
DIRECT_MODE_INPUT(baseReg, bitmask);
interrupts();
}
#if ONEWIRE_SEARCH
//
// You need to use this function to start a search again from the beginning.
// 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--)
{
ROM_NO[i] = 0;
if ( i == 0) break;
}
}
//
// Perform a search. If this function returns a '1' then it has
// enumerated the next device and you may retrieve the ROM from the
// OneWire::address variable. If there are no devices, no further
// devices, or something horrible happens in the middle of the
// enumeration then a 0 is returned. If a new device is found then
// its address is copied to newAddr. Use OneWire::reset_search() to
// start over.
//
// --- Replaced by the one from the Dallas Semiconductor web site ---
//--------------------------------------------------------------------------
// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing
// search state.
// Return TRUE : device found, ROM number in ROM_NO buffer
// FALSE : device not found, end of search
//
uint8_t OneWire::search(uint8_t *newAddr)
{
uint8_t id_bit_number;
uint8_t last_zero, rom_byte_number, search_result;
uint8_t id_bit, cmp_id_bit;
unsigned char rom_byte_mask, search_direction;
// initialize for search
id_bit_number = 1;
last_zero = 0;
rom_byte_number = 0;
rom_byte_mask = 1;
search_result = 0;
// if the last call was not the last one
if (!LastDeviceFlag)
{
// 1-Wire reset
if (!reset())
{
// reset the search
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
return FALSE;
}
// issue the search command
write(0xF0);
// loop to do the search
do
{
// read a bit and its complement
id_bit = read_bit();
cmp_id_bit = read_bit();
// check for no devices on 1-wire
if ((id_bit == 1) && (cmp_id_bit == 1))
break;
else
{
// all devices coupled have 0 or 1
if (id_bit != cmp_id_bit)
search_direction = id_bit; // bit write value for search
else
{
// if this discrepancy if before the Last Discrepancy
// on a previous next then pick the same as last time
if (id_bit_number < LastDiscrepancy)
search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0);
else
// if equal to last pick 1, if not then pick 0
search_direction = (id_bit_number == LastDiscrepancy);
// if 0 was picked then record its position in LastZero
if (search_direction == 0)
{
last_zero = id_bit_number;
// check for Last discrepancy in family
if (last_zero < 9)
LastFamilyDiscrepancy = last_zero;
}
}
// set or clear the bit in the ROM byte rom_byte_number
// with mask rom_byte_mask
if (search_direction == 1)
ROM_NO[rom_byte_number] |= rom_byte_mask;
else
ROM_NO[rom_byte_number] &= ~rom_byte_mask;
// serial number search direction write bit
write_bit(search_direction);
// increment the byte counter id_bit_number
// and shift the mask rom_byte_mask
id_bit_number++;
rom_byte_mask <<= 1;
// if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask
if (rom_byte_mask == 0)
{
rom_byte_number++;
rom_byte_mask = 1;
}
}
}
while(rom_byte_number < 8); // loop until through all ROM bytes 0-7
// if the search was successful then
if (!(id_bit_number < 65))
{
// search successful so set LastDiscrepancy,LastDeviceFlag,search_result
LastDiscrepancy = last_zero;
// check for last device
if (LastDiscrepancy == 0)
LastDeviceFlag = TRUE;
search_result = TRUE;
}
}
// if no device found then reset counters so next 'search' will be like a first
if (!search_result || !ROM_NO[0])
{
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
search_result = FALSE;
}
for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i];
return search_result;
}
#endif
#if ONEWIRE_CRC
// The 1-Wire CRC scheme is described in Maxim Application Note 27:
// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products"
//
#if ONEWIRE_CRC8_TABLE
// This table comes from Dallas sample code where it is freely reusable,
// though Copyright (C) 2000 Dallas Semiconductor Corporation
static const uint8_t PROGMEM dscrc_table[] = {
0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65,
157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220,
35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98,
190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255,
70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7,
219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154,
101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36,
248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185,
140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205,
17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80,
175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238,
50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115,
202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139,
87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22,
233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168,
116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53};
//
// Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM
// and the registers. (note: this might better be done without to
// table, it would probably be smaller and certainly fast enough
// 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 crc = 0;
while (len--) {
crc = pgm_read_byte(dscrc_table + (crc ^ *addr++));
}
return crc;
}
#else
//
// 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 crc = 0;
while (len--) {
uint8_t inbyte = *addr++;
for (uint8_t i = 8; i; i--) {
uint8_t mix = (crc ^ inbyte) & 0x01;
crc >>= 1;
if (mix) crc ^= 0x8C;
inbyte >>= 1;
}
}
return crc;
}
#endif
#if ONEWIRE_CRC16
bool OneWire::check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc)
{
uint16_t crc = ~crc16(input, len);
return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1];
}
uint16_t OneWire::crc16(uint8_t* input, uint16_t len)
{
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;
crc >>= 8;
if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4])
crc ^= 0xC001;
cdata <<= 6;
crc ^= cdata;
cdata <<= 1;
crc ^= cdata;
}
return crc;
}
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More