Merge branch 'master' into development

Conflicts:
	libraries/MySensors/MyGateway.cpp
	libraries/MySensors/MyGateway.h
	libraries/MySensors/MyMessage.h
	libraries/MySensors/examples/LightLuxSensor/LightLuxSensor.ino
This commit is contained in:
Henrik Ekblad
2015-07-30 14:15:26 +02:00
30 changed files with 2547 additions and 719 deletions
-25
View File
@@ -30,28 +30,3 @@ MysensorsMicro.menu.cpu.8Mhz.build.f_cpu=8000000L
MysensorsMicro.menu.cpu.1Mhz=Atmega328 1Mhz
MysensorsMicro.menu.cpu.1Mhz.build.f_cpu=1000000L
########################################
## Gateway settings
MysensorsGW.name=Sensebender Gateway
MysensorsGW.build.core=arduino:arduino
MysensorsGW.build.variant=GW
MysensorsGW.build.board=AVR_1284
MysensorsGW.build.mcu=atmega1284p
MysensorsGW.build.f_cpu=20000000L
MysensorsGW.upload.tool=arduino:avrdude
MysensorsGW.upload.protocol=arduino
MysensorsGW.upload.maximum_size=123720
MysensorsGW.upload.maximum_data_size=16384
MysensorsGW.upload.speed=115200
MysensorsGW.bootloader.tool=arduino:avrdude
MysensorsGW.bootloader.unlock_bits=0x3F
MysensorsGW.bootloader.lock_bits=0x0F
MysensorsGW.bootloader.low_fuses=0xE2
MysensorsGW.bootloader.high_fuses=0xD2
MysensorsGW.bootloader.extended_fuses=0xFE
MysensorsGW.bootloader.file=DualOptiboot/optiboot_atmega1284.hex
+1 -1
View File
@@ -5,7 +5,7 @@
# For more info:
# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification
name=MySensors Boards
name=MySensors AVR based boards
version=1.6.0
# AVR compile variables
File diff suppressed because it is too large Load Diff
+78 -37
View File
@@ -1,6 +1,8 @@
#ifndef DallasTemperature_h
#define DallasTemperature_h
#define DALLASTEMPLIBVERSION "3.7.2"
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
@@ -20,9 +22,10 @@
#include <OneWire.h>
// Model IDs
#define DS18S20MODEL 0x10
#define DS18S20MODEL 0x10 // also DS1820
#define DS18B20MODEL 0x28
#define DS1822MODEL 0x22
#define DS1825MODEL 0x3B
// OneWire commands
#define STARTCONVO 0x44 // Tells device to take a temperature reading and put it on the scratchpad
@@ -51,7 +54,9 @@
#define TEMP_12_BIT 0x7F // 12 bit
// Error Codes
#define DEVICE_DISCONNECTED -127
#define DEVICE_DISCONNECTED_C -127
#define DEVICE_DISCONNECTED_F -196.6
#define DEVICE_DISCONNECTED_RAW -7040
typedef uint8_t DeviceAddress[8];
@@ -61,54 +66,74 @@ class DallasTemperature
DallasTemperature(OneWire*);
// initalize bus
// initialise bus
void begin(void);
// returns the number of devices found on the bus
uint8_t getDeviceCount(void);
// returns true if address is valid
bool validAddress(uint8_t*);
bool validAddress(const uint8_t*);
// finds an address at a given index on the bus
bool getAddress(uint8_t*, const uint8_t);
bool getAddress(uint8_t*, uint8_t);
// attempt to determine if the device at the given address is connected to the bus
bool isConnected(uint8_t*);
bool isConnected(const uint8_t*);
// attempt to determine if the device at the given address is connected to the bus
// also allows for updating the read scratchpad
bool isConnected(uint8_t*, uint8_t*);
bool isConnected(const uint8_t*, uint8_t*);
// read device's scratchpad
void readScratchPad(uint8_t*, uint8_t*);
void readScratchPad(const uint8_t*, uint8_t*);
// write device's scratchpad
void writeScratchPad(uint8_t*, const uint8_t*);
void writeScratchPad(const uint8_t*, const uint8_t*);
// read device's power requirements
bool readPowerSupply(uint8_t*);
bool readPowerSupply(const uint8_t*);
// returns the current resolution, 9-12
uint8_t getResolution(uint8_t*);
// get global resolution
uint8_t getResolution();
// set global resolution to 9, 10, 11, or 12 bits
void setResolution(uint8_t);
// returns the device resolution: 9, 10, 11, or 12 bits
uint8_t getResolution(const uint8_t*);
// set resolution of a device to 9, 10, 11, or 12 bits
void setResolution(uint8_t*, uint8_t);
// sends command for all devices on the bus to perform a temperature conversion
bool setResolution(const uint8_t*, uint8_t);
// sets/gets the waitForConversion flag
void setWaitForConversion(bool);
bool getWaitForConversion(void);
// sets/gets the checkForConversion flag
void setCheckForConversion(bool);
bool getCheckForConversion(void);
// sends command for all devices on the bus to perform a temperature conversion
void requestTemperatures(void);
// returns time to wait for a temperature conversion based on given resolution
int16_t millisToWaitForConversion(uint8_t);
// sends command for one device to perform a temperature conversion by address
void requestTemperaturesByAddress(uint8_t*);
bool requestTemperaturesByAddress(const uint8_t*);
// sends command for one device to perform a temperature conversion by index
void requestTemperaturesByIndex(uint8_t);
bool requestTemperaturesByIndex(uint8_t);
// returns temperature raw value (12 bit integer of 1/16 degrees C)
int16_t getTemp(const uint8_t*);
// returns temperature in degrees C
float getTempC(uint8_t*);
float getTempC(const uint8_t*);
// returns temperature in degrees F
float getTempF(uint8_t*);
float getTempF(const uint8_t*);
// Get temperature for device index (slow)
float getTempCByIndex(uint8_t);
@@ -118,26 +143,28 @@ class DallasTemperature
// returns true if the bus requires parasite power
bool isParasitePowerMode(void);
bool isConversionAvailable(const uint8_t*);
#if REQUIRESALARMS
typedef void AlarmHandler(uint8_t*);
typedef void AlarmHandler(const uint8_t*);
// sets the high alarm temperature for a device
// accepts a char. valid range is -55C - 125C
void setHighAlarmTemp(uint8_t*, const char);
void setHighAlarmTemp(const uint8_t*, char);
// sets the low alarm temperature for a device
// accepts a char. valid range is -55C - 125C
void setLowAlarmTemp(uint8_t*, const char);
void setLowAlarmTemp(const uint8_t*, char);
// returns a signed char with the current high alarm temperature for a device
// in the range -55C - 125C
char getHighAlarmTemp(uint8_t*);
char getHighAlarmTemp(const uint8_t*);
// returns a signed char with the current low alarm temperature for a device
// in the range -55C - 125C
char getLowAlarmTemp(uint8_t*);
char getLowAlarmTemp(const uint8_t*);
// resets internal variables used for the alarm search
void resetAlarmSearch(void);
@@ -146,7 +173,7 @@ class DallasTemperature
bool alarmSearch(uint8_t*);
// returns true if ia specific device has an alarm
bool hasAlarm(uint8_t*);
bool hasAlarm(const uint8_t*);
// returns true if any device is reporting an alarm on the bus
bool hasAlarm(void);
@@ -155,22 +182,28 @@ class DallasTemperature
void processAlarms(void);
// sets the alarm handler
void setAlarmHandler(AlarmHandler *);
void setAlarmHandler(const AlarmHandler *);
// The default alarm handler
static void defaultAlarmHandler(uint8_t*);
static void defaultAlarmHandler(const uint8_t*);
#endif
// convert from celcius to farenheit
static float toFahrenheit(const float);
// convert from Celsius to Fahrenheit
static float toFahrenheit(float);
// convert from farenheit to celsius
static float toCelsius(const float);
// convert from Fahrenheit to Celsius
static float toCelsius(float);
// convert from raw to Celsius
static float rawToCelsius(int16_t);
// convert from raw to Fahrenheit
static float rawToFahrenheit(int16_t);
#if REQUIRESNEW
// initalize memory area
// initialize memory area
void* operator new (unsigned int);
// delete memory reference
@@ -186,16 +219,24 @@ class DallasTemperature
// used to determine the delay amount needed to allow for the
// temperature conversion to take place
int conversionDelay;
uint8_t bitResolution;
// used to requestTemperature with or without delay
bool waitForConversion;
// used to requestTemperature to dynamically check if a conversion is complete
bool checkForConversion;
// count of devices on the bus
uint8_t devices;
// Take a pointer to one wire instance
OneWire* _wire;
// reads scratchpad and returns the temperature in degrees C
float calculateTemperature(uint8_t*, uint8_t*);
// reads scratchpad and returns the raw temperature
int16_t calculateTemperature(const uint8_t*, uint8_t*);
void blockTillConversionComplete(uint8_t, const uint8_t*);
#if REQUIRESALARMS
@@ -4,10 +4,14 @@ Arduino Library for Dallas Temperature ICs
Usage
-----
This library supports the following devices:
DS18B20
DS18S20 - Please note there appears to be an issue with this series.
DS1822
This library supports the following devices :
* DS18B20
* DS18S20 - Please note there appears to be an issue with this series.
* DS1822
* DS1820
You will need a pull-up resistor of about 5 KOhm between the 1-Wire data line
and your 5V power. If you are using the DS18B20, ground pins 1 and 3. The
@@ -15,7 +19,18 @@ centre pin is the data line '1-wire'.
We have included a "REQUIRESNEW" and "REQUIRESALARMS" definition. If you
want to slim down the code feel free to use either of these by including
#define REQUIRESNEW or #define REQUIRESALARMS a the top of DallasTemperature.h
#define REQUIRESNEW
or
#define REQUIRESALARMS
at the top of DallasTemperature.h
Credits
-------
@@ -26,6 +41,8 @@ Miles Burton <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)
Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0)
Website
-------
+85
View File
@@ -0,0 +1,85 @@
This file contains the change history of the Dallas Temperature Control Library.
VERSION 3.7.2 BETA
===================
DATE: 6 DEC 2011
- Jordan Hochenbaum [jhochenbaum@gmail.com] updated library for compatibility with Arduino 1.0.
VERSION 3.7.0 BETA
===================
DATE: 11 JAN 2011
- Rob Tillaart [rob.tillaart@gmail.com] added async modus (v3.7.0)
The library is backwards compatible with version 3.6.0
MAJOR: async modus
------------------
- Added - private bool waitForConversion.
This boolean is default set to true in the Constructor to keep the library backwards compatible. If this flag is true calls to requestTemperatures(), requestTemperaturesByAddress() et al, will be blocking with the appropiate time specified (in datasheet) for the resolution used. If the flag is set to false, requestTemperatures() et al, will return immediately after the conversion command is send over the 1-wire interface. The programmer is responsible to wait long enough before reading the temperature values. This enables the application to do other things while waiting for a new reading, like calculations, update LCD, read/write other IO lines etc. See examples.
- Added - void setWaitForConversion(bool);
To set the flag to true or false, depending on the modus needed.
- Added - bool getWaitForConversion(void);
To get the current value of the flag.
- Changed - void requestTemperatures(void);
Added a test (false == waitForConversion) to return immediately after the conversion command instead of waiting until the conversion is ready.
- Changed - bool requestTemperaturesByAddress(uint8_t*);
Added a test (false == waitForConversion) to return immediately after the conversion command instead of waiting until the conversion is ready.
MINOR version number
--------------------
- Added - #define DALLASTEMPLIBVERSION "3.7.0"
To indicate the version number in .h file
MINOR internal var bitResolution
----------------------------
- Changed - private int conversionDelay - is renamed to - private int bitResolution
As this variable holds the resolution. The delay for the conversion is derived from it.
- Changed - uint8_t getResolution(uint8_t* deviceAddress);
If the device is not connected, it returns 0, otherwise it returns the resolution of the device.
- Changed - bool setResolution(uint8_t* deviceAddress, uint8_t newResolution);
If the device is not connected, it returns FALSE (fail), otherwise it returns TRUE (succes).
- Added - uint8_t getResolution();
Returns bitResolution.
- Added - void setResolution(uint8_t newResolution)
Sets the internal variable bitResolution, and all devices to this value
MINOR check connected state
----------------------------
- Changed - bool requestTemperaturesByIndex(deviceIndex)
Changed return type from void to bool. The function returns false if the device identified with [deviceIndex] is not found on the bus and true otherwise.
- Changed - bool requestTemperaturesByAddress(deviceAddress)
Changed return type from void to bool. The function returns false if the device identified with [deviceAddress] is not found on the bus and true otherwise.
Added code to handle the DS18S20 which has a 9 bit resolution separately.
Changed code so the blocking delay matches the bitResolution set in the device with deviceAddress.
- Changed - bool requestTemperaturesByIndex(uint8_t deviceIndex)
Changed return type from void to bool. The function returns false if the device identified with [deviceIndex] is not found on the bus and true otherwise.
VERSION 3.6.0
==============
DATE: 2010-10-10
- no detailed change history known except:
- The OneWire code has been derived from
http://www.arduino.cc/playground/Learning/OneWire.
- Miles Burton <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)
@@ -2,7 +2,7 @@
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
@@ -2,8 +2,7 @@
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define TEMPERATURE_PRECISION 9
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
@@ -2,7 +2,7 @@
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 9
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
@@ -74,8 +74,8 @@ void setup(void)
Serial.println();
// set the resolution to 9 bit
sensors.setResolution(insideThermometer, 9);
sensors.setResolution(outsideThermometer, 9);
sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);
sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION);
Serial.print("Device 0 Resolution: ");
Serial.print(sensors.getResolution(insideThermometer), DEC);
@@ -2,7 +2,7 @@
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
@@ -2,7 +2,7 @@
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 3
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 9
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
@@ -52,9 +52,9 @@ void setup(void)
Serial.println();
Serial.print("Setting resolution to ");
Serial.println(TEMPERATURE_PRECISION,DEC);
Serial.println(TEMPERATURE_PRECISION, DEC);
// set the resolution to 9 bit (Each Dallas/Maxim device is capable of several different resolutions)
// set the resolution to TEMPERATURE_PRECISION bit (Each Dallas/Maxim device is capable of several different resolutions)
sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);
Serial.print("Resolution actually set to: ");
@@ -0,0 +1,66 @@
#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(115200);
Serial.println("Dallas Temperature Control Library - Async Demo");
Serial.println("\nDemo shows the difference in length of the call\n\n");
// Start up the library
sensors.begin();
}
void loop(void)
{
// Request temperature conversion (traditional)
Serial.println("Before blocking requestForConversion");
unsigned long start = millis();
sensors.requestTemperatures();
unsigned long stop = millis();
Serial.println("After blocking requestForConversion");
Serial.print("Time used: ");
Serial.println(stop - start);
// get temperature
Serial.print("Temperature: ");
Serial.println(sensors.getTempCByIndex(0));
Serial.println("\n");
// Request temperature conversion - non-blocking / async
Serial.println("Before NON-blocking/async requestForConversion");
start = millis();
sensors.setWaitForConversion(false); // makes it async
sensors.requestTemperatures();
sensors.setWaitForConversion(true);
stop = millis();
Serial.println("After NON-blocking/async requestForConversion");
Serial.print("Time used: ");
Serial.println(stop - start);
// 9 bit resolution by default
// Note the programmer is responsible for the right delay
// we could do something usefull here instead of the delay
int resolution = 9;
delay(750/ (1 << (12-resolution)));
// get temperature
Serial.print("Temperature: ");
Serial.println(sensors.getTempCByIndex(0));
Serial.println("\n\n\n\n");
delay(5000);
}
@@ -0,0 +1,80 @@
//
// Sample of using Async reading of Dallas Temperature Sensors
//
#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);
DeviceAddress tempDeviceAddress;
int resolution = 12;
unsigned long lastTempRequest = 0;
int delayInMillis = 0;
float temperature = 0.0;
int idle = 0;
//
// SETUP
//
void setup(void)
{
Serial.begin(115200);
Serial.println("Dallas Temperature Control Library - Async Demo");
Serial.print("Library Version: ");
Serial.println(DALLASTEMPLIBVERSION);
Serial.println("\n");
sensors.begin();
sensors.getAddress(tempDeviceAddress, 0);
sensors.setResolution(tempDeviceAddress, resolution);
sensors.setWaitForConversion(false);
sensors.requestTemperatures();
delayInMillis = 750 / (1 << (12 - resolution));
lastTempRequest = millis();
pinMode(13, OUTPUT);
}
void loop(void)
{
if (millis() - lastTempRequest >= delayInMillis) // waited long enough??
{
digitalWrite(13, LOW);
Serial.print(" Temperature: ");
temperature = sensors.getTempCByIndex(0);
Serial.println(temperature, resolution - 8);
Serial.print(" Resolution: ");
Serial.println(resolution);
Serial.print("Idle counter: ");
Serial.println(idle);
Serial.println();
idle = 0;
// immediately after fetching the temperature we request a new sample
// in the async modus
// for the demo we let the resolution change to show differences
resolution++;
if (resolution > 12) resolution = 9;
sensors.setResolution(tempDeviceAddress, resolution);
sensors.requestTemperatures();
delayInMillis = 750 / (1 << (12 - resolution));
lastTempRequest = millis();
}
digitalWrite(13, HIGH);
// we can do usefull things here
// for the demo we just count the idle time in millis
delay(1);
idle++;
}
+9 -6
View File
@@ -7,8 +7,8 @@
#######################################
DallasTemperature KEYWORD1
OneWire KEYWORD1
AlarmHandler KEYWORD1
DeviceAddress KEYWORD1
AlarmHandler KEYWORD1
DeviceAddress KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
@@ -20,12 +20,14 @@ getTempC KEYWORD2
toFahrenheit KEYWORD2
getTempF KEYWORD2
getTempCByIndex KEYWORD2
getTempFByIndex KEYWORD2
getTempFByIndex KEYWORD2
setWaitForConversion KEYWORD2
getWaitForConversion KEYWORD2
requestTemperatures KEYWORD2
requestTemperaturesByAddress KEYWORD2
requestTemperaturesByIndex KEYWORD2
requestTemperaturesByAddress KEYWORD2
requestTemperaturesByIndex KEYWORD2
isParasitePowerMode KEYWORD2
begin KEYWORD2
begin KEYWORD2
getDeviceCount KEYWORD2
getAddress KEYWORD2
validAddress KEYWORD2
@@ -45,6 +47,7 @@ processAlarmss KEYWORD2
setAlarmHandlers KEYWORD2
defaultAlarmHandler KEYWORD2
calculateTemperature KEYWORD2
millisToWaitForConversion KEYWORD2
#######################################
# Constants (LITERAL1)
+39
View File
@@ -0,0 +1,39 @@
{
"name": "DallasTemperature",
"keywords": "onewire, 1-wire, bus, sensor, temperature",
"description": "Arduino Library for Dallas Temperature ICs (DS18B20, DS18S20, DS1822, DS1820)",
"repository":
{
"type": "git",
"url": "https://github.com/milesburton/Arduino-Temperature-Control-Library.git"
},
"authors":
[
{
"name": "Miles Burton",
"email": "miles@mnetcs.com",
"url": "http://www.milesburton.com",
"maintainer": true
},
{
"name": "Tim Newsome",
"email": "nuisance@casualhacker.net"
},
{
"name": "Guil Barros",
"email": "gfbarros@bappos.com"
},
{
"name": "Rob Tillaart",
"email": "rob.tillaart@gmail.com"
}
],
"dependencies":
{
"name": "OneWire",
"authors": "Paul Stoffregen",
"frameworks": "arduino"
},
"frameworks": "arduino",
"platforms": "atmelavr"
}
+63 -56
View File
@@ -41,12 +41,55 @@ typedef enum {
C_STREAM = 4 // For Firmware and other larger chunks of data that need to be divided into pieces.
} mysensor_command;
// Type of sensor (used when presenting sensors)
typedef enum {
S_DOOR, // Door sensor, V_TRIPPED, V_ARMED
S_MOTION, // Motion sensor, V_TRIPPED, V_ARMED
S_SMOKE, // Smoke sensor, V_TRIPPED, V_ARMED
S_LIGHT, // Binary light or relay, V_STATUS (or V_LIGHT), V_WATT
S_BINARY=3, // Binary light or relay, V_STATUS (or V_LIGHT), V_WATT (same as S_LIGHT)
S_DIMMER, // Dimmable light or fan device, V_STATUS (on/off), V_DIMMER (dimmer level 0-100), V_WATT
S_COVER, // Blinds or window cover, V_UP, V_DOWN, V_STOP, V_DIMMER (open/close to a percentage)
S_TEMP, // Temperature sensor, V_TEMP
S_HUM, // Humidity sensor, V_HUM
S_BARO, // Barometer sensor, V_PRESSURE, V_FORECAST
S_WIND, // Wind sensor, V_WIND, V_GUST
S_RAIN, // Rain sensor, V_RAIN, V_RAINRATE
S_UV, // Uv sensor, V_UV
S_WEIGHT, // Personal scale sensor, V_WEIGHT, V_IMPEDANCE
S_POWER, // Power meter, V_WATT, V_KWH
S_HEATER, // Header device, V_HVAC_SETPOINT_HEAT, V_HVAC_FLOW_STATE
S_DISTANCE, // Distance sensor, V_DISTANCE
S_LIGHT_LEVEL, // Light level sensor, V_LIGHT_LEVEL (uncalibrated in percentage), V_LEVEL (light level in lux)
S_ARDUINO_NODE, // Used (internally) for presenting a non-repeating Arduino node
S_ARDUINO_REPEATER_NODE, // Used (internally) for presenting a repeating Arduino node
S_LOCK, // Lock device, V_LOCK_STATUS
S_IR, // Ir device, V_IR_SEND, V_IR_RECEIVE
S_WATER, // Water meter, V_FLOW, V_VOLUME
S_AIR_QUALITY, // Air quality sensor, V_LEVEL
S_CUSTOM, // Custom sensor
S_DUST, // Dust sensor, V_LEVEL
S_SCENE_CONTROLLER, // Scene controller device, V_SCENE_ON, V_SCENE_OFF.
S_RGB_LIGHT, // RGB light. Send color component data using V_RGB. Also supports V_WATT
S_RGBW_LIGHT, // RGB light with an additional White component. Send data using V_RGBW. Also supports V_WATT
S_COLOR_SENSOR, // Color sensor, send color information using V_RGB
S_HVAC, // Thermostat/HVAC device. V_HVAC_SETPOINT_HEAT, V_HVAC_SETPOINT_COLD, V_HVAC_FLOW_STATE, V_HVAC_FLOW_MODE
S_MULTIMETER, // Multimeter device, V_VOLTAGE, V_CURRENT, V_IMPEDANCE
S_SPRINKLER, // Sprinkler, V_STATUS (turn on/off), V_TRIPPED (if fire detecting device)
S_WATER_LEAK, // Water leak sensor, V_TRIPPED, V_ARMED
S_SOUND, // Sound sensor, V_TRIPPED, V_ARMED, V_LEVEL (sound level in dB)
S_VIBRATION, // Vibration sensor, V_TRIPPED, V_ARMED, V_LEVEL (vibration in Hz)
S_MOISTURE, // Moisture sensor, V_TRIPPED, V_ARMED, V_LEVEL (water content or moisture in percentage?)
} mysensor_sensor;
// Type of sensor data (for set/req/ack messages)
typedef enum {
V_TEMP, // S_TEMP
V_HUM, // S_HUM
V_LIGHT, // S_LIGHT, S_DIMMER
V_DIMMER, // S_DIMMER
V_STATUS, // S_LIGHT, S_DIMMER, S_SPRINKLER, Used for setting binary (on/off) status. 1=on, 0=off
V_LIGHT=2, // S_LIGHT, S_DIMMER. Same as V_STATUS
V_PERCENTAGE, // S_DIMMER. Used for sending a percentage value (0-100).
V_DIMMER=3, // S_DIMMER. Same as V_PERCENTAGE.
V_PRESSURE, // S_BARO
V_FORECAST, // S_BARO
V_RAIN, // S_RAIN
@@ -59,14 +102,15 @@ typedef enum {
V_DISTANCE, // S_DISTANCE
V_IMPEDANCE, // S_MULTIMETER, S_WEIGHT
V_ARMED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER
V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER
V_TRIPPED, // S_DOOR, S_MOTION, S_SMOKE, S_SPRINKLER (for sprinklers with fire detection)
V_WATT, // S_POWER, S_LIGHT, S_DIMMER
V_KWH, // S_POWER
V_SCENE_ON, // S_SCENE_CONTROLLER
V_SCENE_OFF, // S_SCENE_CONTROLLER
V_HEATER, // S_HEATER
V_HEATER_SW, // S_HEATER
V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage)
V_HEATER, // Deprecated. Use V_HVAC_FLOW_STATE instead.
V_HVAC_FLOW_STATE=21, // HVAC flow state ("Off", "HeatOn", "CoolOn", or "AutoChangeOver"). S_HEATER, S_HVAC
V_HVAC_SPEED, // HVAC/Heater fan speed ("Min", "Normal", "Max", "Auto")
V_LIGHT_LEVEL, // S_LIGHT_LEVEL (light level in uncalibrated percentage) or S_LEVEL (light level in lux)
V_VAR1, V_VAR2, V_VAR3, V_VAR4, V_VAR5,
V_UP, // S_COVER
V_DOWN, // S_COVER
@@ -76,27 +120,27 @@ typedef enum {
V_FLOW, // S_WATER
V_VOLUME, // S_WATER
V_LOCK_STATUS, // S_LOCK
V_DUST_LEVEL, // S_DUST
V_LEVEL, // S_DUST, S_AIR_QUALITY, S_SOUND (dB), S_VIBRATION (hz), S_LIGHT_LEVEL (lux)
V_VOLTAGE, // S_MULTIMETER
V_CURRENT, // S_MULTIMETER
V_RGB, // S_RGB_LIGHT, S_COLOR_SENSOR.
// Used for sending color information for led lighting or color sensors.
// Sent as ascii hex. RRGGBB (RR=red, GG=green, BB=blue component)
V_RGBW, // S_RGB_LIGHT
// Used for sending color information to led lighting.
// Sent as ascii hex. RRGGBBWW (WW=while component)
// Used for sending color information for multi color LED lighting or color sensors.
// Sent as ASCII hex: RRGGBB (RR=red, GG=green, BB=blue component)
V_RGBW, // S_RGBW_LIGHT
// Used for sending color information to multi color LED lighting.
// Sent as ASCII hex: RRGGBBWW (WW=while component)
V_ID, // S_TEMP
// Used for reporting the sensor internal ids (E.g. DS1820b).
V_LIGHT_LEVEL_LUX, // S_LIGHT, Light level in lux
// Used for sending in sensors hardware ids (i.e. OneWire DS1820b).
V_UNIT_PREFIX, // Allows sensors to send in a string representing the
// unit prefix to be displayed in GUI, not parsed! E.g. cm, m, km, inch.
// Can be used for S_DISTANCE
V_SOUND_DB, // S_SOUND sound level in db
V_VIBRATION_HZ, // S_VIBRATION vibration i Hz
V_ENCODER_VALUE, // S_ROTARY_ENCODER. Rotary encoder value.
// unit prefix to be displayed in GUI, not parsed by controller! E.g. cm, m, km, inch.
// Can be used for S_DISTANCE or gas concentration (S_DUST, S_AIR_QUALITY)
V_HVAC_SETPOINT_COLD, // HVAC cold setpoint (Integer between 0-100). S_HVAC
V_HVAC_SETPOINT_HEAT, // HVAC/Heater setpoint (Integer between 0-100). S_HEATER, S_HVAC
V_HVAC_FLOW_MODE, // Flow mode for HVAC ("Auto", "ContinuousOn", "PeriodicOn"). S_HVAC
} mysensor_data;
// Type of internal messages (for internal messages)
typedef enum {
I_BATTERY_LEVEL, I_TIME, I_VERSION, I_ID_REQUEST, I_ID_RESPONSE,
@@ -105,43 +149,6 @@ typedef enum {
I_REBOOT, I_GATEWAY_READY, I_REQUEST_SIGNING, I_GET_NONCE, I_GET_NONCE_RESPONSE
} mysensor_internal;
// Type of sensor (for presentation message)
typedef enum {
S_DOOR, // V_TRIPPED, V_ARMED
S_MOTION, // V_TRIPPED, V_ARMED
S_SMOKE, // V_TRIPPED, V_ARMED
S_LIGHT, // V_LIGHT, V_WATT
S_DIMMER, // V_LIGHT, V_DIMMER, V_WATT
S_COVER, // V_UP, V_DOWN, V_STOP
S_TEMP, // V_TEMP
S_HUM, // V_HUM
S_BARO, // V_PRESSURE, V_FORECAST
S_WIND, // V_WIND, V_GUST
S_RAIN, // V_RAIN, V_RAINRATE
S_UV, // V_UV
S_WEIGHT, // V_WEIGHT, V_IMPEDANCE
S_POWER, // V_WATT, V_KWH
S_HEATER, // V_HEATER, V_HEATER_SW
S_DISTANCE, // V_DISTANCE
S_LIGHT_LEVEL, // V_LIGHT_LEVEL
S_ARDUINO_NODE,
S_ARDUINO_REPEATER_NODE,
S_LOCK, // V_LOCK_STATUS
S_IR, // V_IR_SEND, V_IR_RECEIVE
S_WATER, // V_FLOW, V_VOLUME
S_AIR_QUALITY, // V_VAR1
S_CUSTOM,
S_DUST, // V_DUST_LEVEL
S_SCENE_CONTROLLER, // V_SCENE_ON, V_SCENE_OFF.
S_RGB_LIGHT, // Send data using V_RGB or V_RGBW
S_COLOR_SENSOR, // Send data using V_RGB
S_MULTIMETER, // V_VOLTAGE, V_CURRENT, V_IMPEDANCE
S_SPRINKLER, // V_TRIPPED, V_ARMED
S_WATER_LEAK, // V_TRIPPED, V_ARMED
S_SOUND, // V_TRIPPED, V_ARMED, V_SOUND_DB
S_VIBRATION, // V_TRIPPED, V_ARMED, V_VIBRATION_HZ
S_ROTARY_ENCODER, // V_ENCODER_VALUE
} mysensor_sensor;
// Type of data stream (for streamed message)
typedef enum {
@@ -77,7 +77,7 @@ float SmokeCurve[3] ={2.3,0.53,-0.44}; //two points are taken from
MySensor gw;
MyMessage msg(CHILD_ID_MQ, V_VAR1);
MyMessage msg(CHILD_ID_MQ, V_LEVEL);
void setup()
@@ -48,6 +48,8 @@ void setup()
{
// Startup up the OneWire library
sensors.begin();
// requestTemperatures() will not block current thread
sensors.setWaitForConversion(false);
// Startup and initialize MySensors library. Set callback for incoming messages.
gw.begin();
@@ -71,7 +73,12 @@ void loop()
gw.process();
// Fetch temperatures from Dallas sensors
sensors.requestTemperatures();
sensors.requestTemperatures();
// query conversion time and sleep until conversion completed
int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution());
// sleep() call can be replaced by wait() call if node need to process incoming messages (or if node is repeater)
gw.sleep(conversionTime);
// Read temperatures and send them to controller
for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {
@@ -94,6 +101,3 @@ void loop()
}
gw.sleep(SLEEP_TIME);
}
@@ -57,7 +57,7 @@ float calcVoltage = 0;
float dustDensity = 0;
MySensor gw;
MyMessage dustMsg(CHILD_ID_DUST, V_DUST_LEVEL);
MyMessage dustMsg(CHILD_ID_DUST, V_LEVEL);
void setup()
{
@@ -43,12 +43,16 @@
#include <Wire.h>
#define CHILD_ID_LIGHT 0
#define LIGHT_SENSOR_ANALOG_PIN 0
unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
BH1750 lightSensor;
MySensor gw;
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL_LUX);
// V_LIGHT_LEVEL should only be used for uncalibrated light level 0-100%.
// If your controller supports the new V_LEVEL variable, use this instead for
// transmitting LUX light level.
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL);
// MyMessage msg(CHILD_ID_LIGHT, V_LEVEL);
uint16_t lastlux;
void setup()
@@ -0,0 +1,121 @@
// This sketch is to integrate the Playing With Fusion AXS3935 Lightning Sensor Breakout Board
// with the MySensors environment and is based on a sketch provided by Playing With Fusion
// http://playingwithfusion.com/productview.php?pdid=22&catid=1001
//
#include "MySensor.h"
// the lightning sensor can communicate via SPI or I2C. This sketch uses the SPI interface
#include "SPI.h"
// include Playing With Fusion AXS3935 libraries
#include "PWFusion_AS3935.h"
// setup CS pins used for the connection with the lightning sensor
// other connections are controlled by the SPI library)
int8_t CS_PIN = 8;
int8_t SI_PIN = 7;
int8_t IRQ_PIN = 3;
volatile int8_t AS3935_ISR_Trig = 0;
// #defines
#define AS3935_INDOORS 1
#define AS3935_OUTDOORS 0
#define AS3935_DIST_DIS 0
#define AS3935_DIST_EN 1
#define AS3935_CAPACITANCE 96 // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD
// prototypes
void AS3935_ISR();
PWF_AS3935 lightning0(CS_PIN, IRQ_PIN, SI_PIN);
#define CHILD_ID_DISTANCE 1
#define CHILD_ID_INTENSITY 2
MySensor gw;
MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE);
MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1);
void setup()
{
gw.begin();
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Lightning Sensor", "1.1");
// Register all sensors to gw (they will be created as child devices)
gw.present(CHILD_ID_DISTANCE, S_DISTANCE);
gw.present(CHILD_ID_INTENSITY, S_CUSTOM);
boolean metric = gw.getConfig().isMetric;
Serial.begin(115200);
Serial.println("Playing With Fusion: AS3935 Lightning Sensor, SEN-39001");
Serial.println("beginning boot procedure....");
// setup for the the SPI library:
SPI.begin(); // begin SPI
SPI.setClockDivider(SPI_CLOCK_DIV4); // SPI speed to SPI_CLOCK_DIV16/1MHz (max 2MHz, NEVER 500kHz!)
SPI.setDataMode(SPI_MODE1); // MAX31855 is a Mode 1 device
// --> clock starts low, read on rising edge
SPI.setBitOrder(MSBFIRST); // data sent to chip MSb first
lightning0.AS3935_DefInit(); // set registers to default
// now update sensor cal for your application and power up chip
lightning0.AS3935_ManualCal(AS3935_CAPACITANCE, AS3935_OUTDOORS, AS3935_DIST_EN);
// AS3935_ManualCal Parameters:
// --> capacitance, in pF (marked on package)
// --> indoors/outdoors (AS3935_INDOORS:0 / AS3935_OUTDOORS:1)
// --> disturbers (AS3935_DIST_EN:1 / AS3935_DIST_DIS:2)
// function also powers up the chip
// enable interrupt (hook IRQ pin to Arduino Uno/Mega interrupt input: 1 -> pin 3 )
attachInterrupt(1, AS3935_ISR, RISING);
// dump the registry data to the serial port for troubleshooting purposes
lightning0.AS3935_PrintAllRegs();
// delay execution to allow chip to stabilize.
delay(1000);
}
void loop()
{
// This program only handles an AS3935 lightning sensor. It does nothing until
// an interrupt is detected on the IRQ pin.
while(0 == AS3935_ISR_Trig){}
// reset interrupt flag
AS3935_ISR_Trig = 0;
// now get interrupt source
uint8_t int_src = lightning0.AS3935_GetInterruptSrc();
if(0 == int_src)
{
Serial.println("Unknown interrupt source");
}
else if(1 == int_src)
{
uint8_t lightning_dist_km = lightning0.AS3935_GetLightningDistKm();
uint32_t lightning_intensity = lightning0.AS3935_GetStrikeEnergyRaw();
Serial.print("Lightning detected! Distance to strike: ");
Serial.print(lightning_dist_km);
Serial.println(" kilometers");
Serial.print("Lightning detected! Lightning Intensity: ");
Serial.println(lightning_intensity);
gw.send(msgDist.set(lightning_dist_km));
gw.send(msgInt.set(lightning_intensity));
}
else if(2 == int_src)
{
Serial.println("Disturber detected");
}
else if(3 == int_src)
{
Serial.println("Noise level too high");
}
}
// this is irq handler for AS3935 interrupts, has to return void and take no arguments
// always make code in interrupt handlers fast and short
void AS3935_ISR()
{
AS3935_ISR_Trig = 1;
}␍
@@ -35,7 +35,21 @@
#define BARO_CHILD 0
#define TEMP_CHILD 1
unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in seconds)
const float ALTITUDE = 688; // <-- adapt this value to your own location's altitude.
// Sleep time between reads (in seconds). Do not change this value as the forecast algorithm needs a sample every minute.
const unsigned long SLEEP_TIME = 60000;
const char *weather[] = { "stable", "sunny", "cloudy", "unstable", "thunderstorm", "unknown" };
enum FORECAST
{
STABLE = 0, // "Stable Weather Pattern"
SUNNY = 1, // "Slowly rising Good Weather", "Clear/Sunny "
CLOUDY = 2, // "Slowly falling L-Pressure ", "Cloudy/Rain "
UNSTABLE = 3, // "Quickly rising H-Press", "Not Stable"
THUNDERSTORM = 4, // "Quickly falling L-Press", "Thunderstorm"
UNKNOWN = 5 // "Unknown (More Time needed)
};
Adafruit_BMP085 bmp = Adafruit_BMP085(); // Digital Pressure Sensor
MySensor gw;
@@ -43,206 +57,243 @@ MySensor gw;
float lastPressure = -1;
float lastTemp = -1;
int lastForecast = -1;
const char *weather[] = {"stable","sunny","cloudy","unstable","thunderstorm","unknown"};
int minutes;
float pressureSamples[7][6];
const int LAST_SAMPLES_COUNT = 5;
float lastPressureSamples[LAST_SAMPLES_COUNT];
// this CONVERSION_FACTOR is used to convert from Pa to kPa in forecast algorithm
// get kPa/h be dividing hPa by 10
#define CONVERSION_FACTOR (1.0/10.0)
int minuteCount = 0;
bool firstRound = true;
float pressureAvg[7];
// average value is used in forecast algorithm.
float pressureAvg;
// average after 2 hours is used as reference value for the next iteration.
float pressureAvg2;
float dP_dt;
boolean metric;
boolean metric;
MyMessage tempMsg(TEMP_CHILD, V_TEMP);
MyMessage pressureMsg(BARO_CHILD, V_PRESSURE);
MyMessage forecastMsg(BARO_CHILD, V_FORECAST);
void setup() {
gw.begin();
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Pressure Sensor", "1.0");
void setup()
{
gw.begin();
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
while (1) { }
}
// Send the sketch version information to the gateway and Controller
gw.sendSketchInfo("Pressure Sensor", "1.1");
// Register sensors to gw (they will be created as child devices)
gw.present(BARO_CHILD, S_BARO);
gw.present(TEMP_CHILD, S_TEMP);
metric = gw.getConfig().isMetric;
if (!bmp.begin())
{
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
while (1) {}
}
// Register sensors to gw (they will be created as child devices)
gw.present(BARO_CHILD, S_BARO);
gw.present(TEMP_CHILD, S_TEMP);
metric = gw.getConfig().isMetric;
}
void loop() {
float pressure = bmp.readSealevelPressure(205)/100.0; // 205 meters above sealevel
float temperature = bmp.readTemperature();
if (!metric) {
// Convert to fahrenheit
temperature = temperature * 9.0 / 5.0 + 32.0;
}
int forecast = sample(pressure);
void loop()
{
float pressure = bmp.readSealevelPressure(ALTITUDE) / 100.0;
float temperature = bmp.readTemperature();
Serial.print("Temperature = ");
Serial.print(temperature);
Serial.println(metric?" *C":" *F");
Serial.print("Pressure = ");
Serial.print(pressure);
Serial.println(" Pa");
Serial.println(weather[forecast]);
if (!metric)
{
// Convert to fahrenheit
temperature = temperature * 9.0 / 5.0 + 32.0;
}
int forecast = sample(pressure);
Serial.print("Temperature = ");
Serial.print(temperature);
Serial.println(metric ? " *C" : " *F");
Serial.print("Pressure = ");
Serial.print(pressure);
Serial.println(" hPa");
Serial.print("Forecast = ");
Serial.println(weather[forecast]);
if (temperature != lastTemp) {
gw.send(tempMsg.set(temperature,1));
lastTemp = temperature;
}
if (temperature != lastTemp)
{
gw.send(tempMsg.set(temperature, 1));
lastTemp = temperature;
}
if (pressure != lastPressure) {
gw.send(pressureMsg.set(pressure, 0));
lastPressure = pressure;
}
if (pressure != lastPressure)
{
gw.send(pressureMsg.set(pressure, 0));
lastPressure = pressure;
}
if (forecast != lastForecast) {
gw.send(forecastMsg.set(weather[forecast]));
lastForecast = forecast;
}
/*
DP/Dt explanation
if (forecast != lastForecast)
{
gw.send(forecastMsg.set(weather[forecast]));
lastForecast = forecast;
}
0 = "Stable Weather Pattern"
1 = "Slowly rising Good Weather", "Clear/Sunny "
2 = "Slowly falling L-Pressure ", "Cloudy/Rain "
3 = "Quickly rising H-Press", "Not Stable"
4 = "Quickly falling L-Press", "Thunderstorm"
5 = "Unknown (More Time needed)
*/
gw.sleep(SLEEP_TIME);
gw.sleep(SLEEP_TIME);
}
int sample(float pressure) {
// Algorithm found here
// http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf
if (minuteCount == 180)
minuteCount = 5;
//From 0 to 5 min.
if (minuteCount <= 5){
pressureSamples[0][minuteCount] = pressure;
}
//From 30 to 35 min.
if ((minuteCount <= 30) && (minuteCount >= 35)){
pressureSamples[1][minuteCount - 30] = pressure;
}
//From 55 to 60 min.
if ((minuteCount <= 55) && (minuteCount >= 60)){
pressureSamples[2][minuteCount - 55] = pressure;
}
//From 90 to 95 min.
if ((minuteCount <= 90) && (minuteCount >= 95)){
pressureSamples[3][minuteCount - 90] = pressure;
}
//From 115 to 119 min.
if ((minuteCount <= 115) && (minuteCount >= 120)){
pressureSamples[4][minuteCount - 115] = pressure;
}
//From 150 to 155 min.
if ((minuteCount <= 150) && (minuteCount >= 155)){
pressureSamples[5][minuteCount - 150] = pressure;
}
//From 175 to 180 min.
if ((minuteCount <= 175) && (minuteCount >= 180)){
pressureSamples[6][minuteCount - 175] = pressure;
}
float getLastPressureSamplesAverage()
{
float lastPressureSamplesAverage = 0;
for (int i = 0; i < LAST_SAMPLES_COUNT; i++)
{
lastPressureSamplesAverage += lastPressureSamples[i];
}
lastPressureSamplesAverage /= LAST_SAMPLES_COUNT;
return lastPressureSamplesAverage;
}
// Algorithm found here
// http://www.freescale.com/files/sensors/doc/app_note/AN3914.pdf
// Pressure in hPa --> forecast done by calculating kPa/h
int sample(float pressure)
{
// Calculate the average of the last n minutes.
int index = minuteCount % LAST_SAMPLES_COUNT;
lastPressureSamples[index] = pressure;
minuteCount++;
if (minuteCount > 185)
{
minuteCount = 6;
}
if (minuteCount == 5) {
// Avg pressure in first 5 min, value averaged from 0 to 5 min.
pressureAvg[0] = ((pressureSamples[0][0] + pressureSamples[0][1]
+ pressureSamples[0][2] + pressureSamples[0][3]
+ pressureSamples[0][4] + pressureSamples[0][5]) / 6);
} else if (minuteCount == 35) {
// Avg pressure in 30 min, value averaged from 0 to 5 min.
pressureAvg[1] = ((pressureSamples[1][0] + pressureSamples[1][1]
+ pressureSamples[1][2] + pressureSamples[1][3]
+ pressureSamples[1][4] + pressureSamples[1][5]) / 6);
float change = (pressureAvg[1] - pressureAvg[0]);
if (minuteCount == 5)
{
pressureAvg = getLastPressureSamplesAverage();
}
else if (minuteCount == 35)
{
float lastPressureAvg = getLastPressureSamplesAverage();
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
if (firstRound) // first time initial 3 hour
dP_dt = ((65.0 / 1023.0) * 2 * change); // note this is for t = 0.5hour
{
dP_dt = change * 2; // note this is for t = 0.5hour
}
else
dP_dt = (((65.0 / 1023.0) * change) / 1.5); // divide by 1.5 as this is the difference in time from 0 value.
} else if (minuteCount == 60) {
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
pressureAvg[2] = ((pressureSamples[2][0] + pressureSamples[2][1]
+ pressureSamples[2][2] + pressureSamples[2][3]
+ pressureSamples[2][4] + pressureSamples[2][5]) / 6);
float change = (pressureAvg[2] - pressureAvg[0]);
{
dP_dt = change / 1.5; // divide by 1.5 as this is the difference in time from 0 value.
}
}
else if (minuteCount == 65)
{
float lastPressureAvg = getLastPressureSamplesAverage();
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
if (firstRound) //first time initial 3 hour
dP_dt = ((65.0 / 1023.0) * change); //note this is for t = 1 hour
{
dP_dt = change; //note this is for t = 1 hour
}
else
dP_dt = (((65.0 / 1023.0) * change) / 2); //divide by 2 as this is the difference in time from 0 value
} else if (minuteCount == 95) {
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
pressureAvg[3] = ((pressureSamples[3][0] + pressureSamples[3][1]
+ pressureSamples[3][2] + pressureSamples[3][3]
+ pressureSamples[3][4] + pressureSamples[3][5]) / 6);
float change = (pressureAvg[3] - pressureAvg[0]);
{
dP_dt = change / 2; //divide by 2 as this is the difference in time from 0 value
}
}
else if (minuteCount == 95)
{
float lastPressureAvg = getLastPressureSamplesAverage();
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * change) / 1.5); // note this is for t = 1.5 hour
{
dP_dt = change / 1.5; // note this is for t = 1.5 hour
}
else
dP_dt = (((65.0 / 1023.0) * change) / 2.5); // divide by 2.5 as this is the difference in time from 0 value
} else if (minuteCount == 120) {
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
pressureAvg[4] = ((pressureSamples[4][0] + pressureSamples[4][1]
+ pressureSamples[4][2] + pressureSamples[4][3]
+ pressureSamples[4][4] + pressureSamples[4][5]) / 6);
float change = (pressureAvg[4] - pressureAvg[0]);
{
dP_dt = change / 2.5; // divide by 2.5 as this is the difference in time from 0 value
}
}
else if (minuteCount == 125)
{
float lastPressureAvg = getLastPressureSamplesAverage();
pressureAvg2 = lastPressureAvg; // store for later use.
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * change) / 2); // note this is for t = 2 hour
{
dP_dt = change / 2; // note this is for t = 2 hour
}
else
dP_dt = (((65.0 / 1023.0) * change) / 3); // divide by 3 as this is the difference in time from 0 value
} else if (minuteCount == 155) {
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
pressureAvg[5] = ((pressureSamples[5][0] + pressureSamples[5][1]
+ pressureSamples[5][2] + pressureSamples[5][3]
+ pressureSamples[5][4] + pressureSamples[5][5]) / 6);
float change = (pressureAvg[5] - pressureAvg[0]);
{
dP_dt = change / 3; // divide by 3 as this is the difference in time from 0 value
}
}
else if (minuteCount == 155)
{
float lastPressureAvg = getLastPressureSamplesAverage();
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * change) / 2.5); // note this is for t = 2.5 hour
{
dP_dt = change / 2.5; // note this is for t = 2.5 hour
}
else
dP_dt = (((65.0 / 1023.0) * change) / 3.5); // divide by 3.5 as this is the difference in time from 0 value
} else if (minuteCount == 180) {
// Avg pressure at end of the hour, value averaged from 0 to 5 min.
pressureAvg[6] = ((pressureSamples[6][0] + pressureSamples[6][1]
+ pressureSamples[6][2] + pressureSamples[6][3]
+ pressureSamples[6][4] + pressureSamples[6][5]) / 6);
float change = (pressureAvg[6] - pressureAvg[0]);
{
dP_dt = change / 3.5; // divide by 3.5 as this is the difference in time from 0 value
}
}
else if (minuteCount == 185)
{
float lastPressureAvg = getLastPressureSamplesAverage();
float change = (lastPressureAvg - pressureAvg) * CONVERSION_FACTOR;
if (firstRound) // first time initial 3 hour
dP_dt = (((65.0 / 1023.0) * change) / 3); // note this is for t = 3 hour
{
dP_dt = change / 3; // note this is for t = 3 hour
}
else
dP_dt = (((65.0 / 1023.0) * change) / 4); // divide by 4 as this is the difference in time from 0 value
pressureAvg[0] = pressureAvg[5]; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past.
{
dP_dt = change / 4; // divide by 4 as this is the difference in time from 0 value
}
pressureAvg = pressureAvg2; // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past.
firstRound = false; // flag to let you know that this is on the past 3 hour mark. Initialized to 0 outside main loop.
}
int forecast = UNKNOWN;
if (minuteCount < 35 && firstRound) //if time is less than 35 min on the first 3 hour interval.
return 5; // Unknown, more time needed
{
forecast = UNKNOWN;
}
else if (dP_dt < (-0.25))
return 4; // Quickly falling LP, Thunderstorm, not stable
{
forecast = THUNDERSTORM;
}
else if (dP_dt > 0.25)
return 3; // Quickly rising HP, not stable weather
{
forecast = UNSTABLE;
}
else if ((dP_dt > (-0.25)) && (dP_dt < (-0.05)))
return 2; // Slowly falling Low Pressure System, stable rainy weather
{
forecast = CLOUDY;
}
else if ((dP_dt > 0.05) && (dP_dt < 0.25))
return 1; // Slowly rising HP stable good weather
else if ((dP_dt > (-0.05)) && (dP_dt < 0.05))
return 0; // Stable weather
{
forecast = SUNNY;
}
else if ((dP_dt >(-0.05)) && (dP_dt < 0.05))
{
forecast = STABLE;
}
else
return 5; // Unknown
{
forecast = UNKNOWN;
}
// uncomment when debugging
//Serial.print(F("Forecast at minute "));
//Serial.print(minuteCount);
//Serial.print(F(" dP/dt = "));
//Serial.print(dP_dt);
//Serial.print(F("kPa/h --> "));
//Serial.println(weather[forecast]);
return forecast;
}
@@ -0,0 +1,594 @@
/*
Arduino Tipping Bucket Rain Gauge
April 26, 2015
Version 1.4.1 alpha
Arduino Tipping Bucket Rain Gauge
Utilizing a tipping bucket sensor, your Vera home automation controller and the MySensors.org
gateway you can measure and sense local rain. This sketch will create two devices on your
Vera controller. One will display your total precipitation for the last 5 days. The other,
a sensor that changes state if there is recent rain (up to last 120 hours) above a threshold.
Both these settings are user definable.
There is a build overview video here: https://youtu.be/1eMfKQaLROo
This sketch features the following:
* Allows you to set the rain threshold in mm
* Allows you to determine the tripped indicator window up to 120 hours.
* Displays the last 5 days of rain in Variable1 through Variable5
of the Rain Sensor device
* Configuration changes to Sensor device updated every hour
* Should run on any Arduino
* Will retain Tripped/Not Tripped status and data in a power interruption, saving small amount
of data to EEPROM (Circular Buffer to maximize life of EEPROM)
* LED status indicator
* Optional Temp/Humidity (DHT-22 or DHT-11) and Light LUX (BH1750) sensors. To use, uncomment
#define DHT_ON and/or #define LUX_ON
* Optionally send total accumulation of each day's rainfall or send only individual days rainfall totals.
Comment out #define USE_DAILY to display individual daily rainfall.
by @BulldogLowell and @PeteWill for free public use
*/
#include <SPI.h>
#include <MySensor.h>
#include <math.h>
#include <Time.h>
#define NODE_ID 24 //or AUTO to let controller assign
#define SKETCH_NAME "Rain Gauge"
#define SKETCH_VERSION "1.4.1a"
#define DWELL_TIME 125 // this allows for radio to come back to power after a transmission, ideally 0
//#define DEBUG_ON // comment out this line to disable serial debug
#define DHT_ON // uncomment out this line to enable DHT sensor
#define LUX_ON // uncomment out this line to enable BH1750 sensor
//#define USE_DAILY // displays each time segment as an accumulation of prior periods inclusive. Comment out to display individual daily rainfall totals in the variables sent to your controller.
#define CALIBRATE_FACTOR 60 // amount of rain per rain bucket tip e.g. 5 is .05mm
#define DHT_LUX_DELAY 300000 //Delay in milliseconds that the DHT and LUX sensors will wait before sending data
#define CHILD_ID_RAIN_LOG 3 // Keeps track of accumulated rainfall
#define CHILD_ID_TRIPPED_INDICATOR 4 // Indicates Tripped when rain detected
#define EEPROM_BUFFER_LOCATION 0 // location of the EEPROM circular buffer
#define E_BUFFER_LENGTH 240
#define RAIN_BUCKET_SIZE 120
#ifdef DEBUG_ON
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define SERIAL_START(x) Serial.begin(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#define SERIAL_START(x)
#endif
//
MySensor gw;
//
MyMessage msgRainRate(CHILD_ID_RAIN_LOG, V_RAINRATE);
MyMessage msgRain(CHILD_ID_RAIN_LOG, V_RAIN);
//
MyMessage msgRainVAR1(CHILD_ID_RAIN_LOG, V_VAR1);
MyMessage msgRainVAR2(CHILD_ID_RAIN_LOG, V_VAR2);
MyMessage msgRainVAR3(CHILD_ID_RAIN_LOG, V_VAR3);
MyMessage msgRainVAR4(CHILD_ID_RAIN_LOG, V_VAR4);
MyMessage msgRainVAR5(CHILD_ID_RAIN_LOG, V_VAR5);
//
MyMessage msgTripped(CHILD_ID_TRIPPED_INDICATOR, V_TRIPPED);
MyMessage msgTrippedVar1(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
MyMessage msgTrippedVar2(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
//
#ifdef DHT_ON
#include <DHT.h>
#define CHILD_ID_HUM 0
#define CHILD_ID_TEMP 1
#define HUMIDITY_SENSOR_DIGITAL_PIN 8
DHT dht;
float lastTemp;
float lastHum;
boolean metric = true;
MyMessage msgHum(CHILD_ID_HUM, V_HUM);
MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
#endif
//
#ifdef LUX_ON
//BH1750 is connected to SCL (analog input A5) and SDA (analog input A4)
#include <BH1750.h>
#include <Wire.h>
#define CHILD_ID_LIGHT 2
BH1750 lightSensor;
MyMessage msg(CHILD_ID_LIGHT, V_LIGHT_LEVEL);
unsigned int lastlux;
byte heartbeat = 10; //Used to send the light lux to gateway as soon as the device is restarted and after the DHT_LUX_DELAY has happened 10 times
#endif
unsigned long sensorPreviousMillis;
int eepromIndex;
int tipSensorPin = 3; // Pin the tipping bucket is connected to. Must be interrupt capable pin
int ledPin = 5; // Pin the LED is connected to. PWM capable pin required
unsigned long dataMillis;
unsigned long serialInterval = 600000UL;
const unsigned long oneHour = 3600000UL;
unsigned long lastTipTime;
unsigned long lastRainTime; //Used for rainRate calculation
unsigned int rainBucket [RAIN_BUCKET_SIZE] ; /* 24 hours x 5 Days = 120 hours */
unsigned int rainRate = 0;
byte rainWindow = 72; //default rain window in hours. Will be overwritten with msgTrippedVar1.
volatile int wasTippedBuffer = 0;
int rainSensorThreshold = 50; //default rain sensor sensitivity in hundredths. Will be overwritten with msgTrippedVar2.
byte state = 0;
byte oldState = -1;
int lastRainRate = 0;
int lastMeasure = 0;
boolean gotTime = false;
byte lastHour;
byte currentHour;
//
void setup()
{
SERIAL_START(115200);
//
// Set up the IO
pinMode(tipSensorPin, INPUT_PULLUP);
attachInterrupt (1, sensorTipped, FALLING); // depending on location of the hall effect sensor may need CHANGE
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
//
//Let's get the controller talking to the Arduino
gw.begin(getVariables, NODE_ID);
gw.sendSketchInfo(SKETCH_NAME, SKETCH_VERSION);
gw.wait(DWELL_TIME);
gw.present(CHILD_ID_RAIN_LOG, S_RAIN);
gw.wait(DWELL_TIME);
gw.present(CHILD_ID_TRIPPED_INDICATOR, S_MOTION);
gw.wait(DWELL_TIME);
DEBUG_PRINTLN(F("Sensor Presentation Complete"));
//
//Sync time with the server, this will be called hourly in order to keep time from creeping with the crystal
//
unsigned long functionTimeout = millis();
while (timeStatus() == timeNotSet && millis() - functionTimeout < 30000UL)
{
gw.process();
gw.requestTime(receiveTime);
DEBUG_PRINTLN(F("Getting Time"));
gw.wait(1000); // call once per second
DEBUG_PRINTLN(F("."));
}
currentHour = hour();
lastHour = hour();
//
//retrieve from EEPROM stored values on a power cycle.
//
boolean isDataOnEeprom = false;
for (int i = 0; i < E_BUFFER_LENGTH; i++)
{
byte locator = gw.loadState(EEPROM_BUFFER_LOCATION + i);
if (locator == 0xFE) // found the EEPROM circular buffer index
{
eepromIndex = EEPROM_BUFFER_LOCATION + i;
DEBUG_PRINT(F("EEPROM Index "));
DEBUG_PRINTLN(eepromIndex);
//Now that we have the buffer index let's populate the rainBucket[] with data from eeprom
loadRainArray(eepromIndex);
isDataOnEeprom = true;
break;
}
}
//
if (!isDataOnEeprom) // Added for the first time it is run on a new Arduino
{
DEBUG_PRINTLN(F("I didn't find valid EEPROM Index, so I'm writing one to location 0"));
eepromIndex = EEPROM_BUFFER_LOCATION;
gw.saveState(eepromIndex, 0xFE);
gw.saveState(eepromIndex + 1, 0xFE);
//then I will clear out any bad data
for (int i = 2; i <= E_BUFFER_LENGTH; i++)
{
gw.saveState(i, 0x00);
}
}
dataMillis = millis();
lastTipTime = millis() - oneHour; //why is this -oneHour?? Doesn't millis() start at 0 when first powered on?
//
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
gw.wait(DWELL_TIME);
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
gw.wait(DWELL_TIME);
//
#ifdef DHT_ON
dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN);
// Register all sensors to gw (they will be created as child devices)
gw.present(CHILD_ID_HUM, S_HUM);
gw.wait(DWELL_TIME);
gw.present(CHILD_ID_TEMP, S_TEMP);
gw.wait(DWELL_TIME);
metric = gw.getConfig().isMetric;
gw.wait(DWELL_TIME);
#endif
//
#ifdef LUX_ON
gw.present(CHILD_ID_LIGHT, S_LIGHT_LEVEL);
gw.wait(DWELL_TIME);
lightSensor.begin();
#endif
//
DEBUG_PRINTLN(F("Radio Setup Complete!"));
transmitRainData();
}
void loop()
{
gw.process();
if (state)
{
prettyFade(); // breathe if tripped
}
else
{
slowFlash(); // blink if not tripped
}
#ifdef DEBUG_ON // Serial Debug Block
if ( (millis() - dataMillis) >= serialInterval)
{
for (int i = 24; i <= 120; i = i + 24)
{
updateSerialData(i);
}
dataMillis = millis();
}
#endif
//
// let's constantly check to see if the rain in the past rainWindow hours is greater than rainSensorThreshold
//
int measure = 0; // Check to see if we need to show sensor tripped in this block
for (int i = 0; i < rainWindow; i++)
{
measure += rainBucket [i];
if (measure != lastMeasure)
{
// DEBUG_PRINT(F("measure value (total rainBucket within rainWindow): "));
// DEBUG_PRINTLN(measure);
lastMeasure = measure;
}
}
//
state = (measure >= (rainSensorThreshold * 100));
if (state != oldState)
{
gw.send(msgTripped.set(state));
gw.wait(DWELL_TIME);
DEBUG_PRINT(F("New Sensor State... Sensor: "));
DEBUG_PRINTLN(state ? "Tripped" : "Not Tripped");
oldState = state;
}
//
unsigned long tipDelay = millis() - lastRainTime;
if (wasTippedBuffer) // if was tipped, then update the 24hour total and transmit to Vera
{
DEBUG_PRINTLN(F("Sensor Tipped"));
DEBUG_PRINT(F("rainBucket [0] value: "));
DEBUG_PRINTLN(rainBucket [0]);
gw.send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); //Calculate the total rain for the day
gw.wait(DWELL_TIME);
wasTippedBuffer--;
rainRate = ((oneHour) / tipDelay);
if (rainRate != lastRainRate)
{
gw.send(msgRainRate.set(rainRate, 1));
gw.wait(DWELL_TIME);
DEBUG_PRINT(F("RainRate= "));
DEBUG_PRINTLN(rainRate);
lastRainRate = rainRate;
}
lastRainTime = lastTipTime;
}
//
currentHour = hour();
if (currentHour != lastHour)
{
DEBUG_PRINTLN(F("One hour elapsed."));
gw.send(msgRain.set((float)rainTotal(currentHour) / 100, 1)); // send today's rainfall
gw.wait(DWELL_TIME);
gw.saveState(eepromIndex, highByte(rainBucket[0]));
gw.saveState(eepromIndex + 1, lowByte(rainBucket[0]));
DEBUG_PRINT(F("Saving rainBucket[0] to eeprom. rainBucket[0] = "));
DEBUG_PRINTLN(rainBucket[0]);
for (int i = RAIN_BUCKET_SIZE - 1; i >= 0; i--)//cascade an hour of values back into the array
{
rainBucket [i + 1] = rainBucket [i];
}
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR1);
gw.wait(DWELL_TIME);
gw.request(CHILD_ID_TRIPPED_INDICATOR, V_VAR2);
gw.wait(DWELL_TIME);
rainBucket[0] = 0;
eepromIndex = eepromIndex + 2;
if (eepromIndex > EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH)
{
eepromIndex = EEPROM_BUFFER_LOCATION;
}
DEBUG_PRINT(F("Writing to EEPROM. Index: "));
DEBUG_PRINTLN(eepromIndex);
gw.saveState(eepromIndex, 0xFE);
gw.saveState(eepromIndex + 1, 0xFE);
gw.requestTime(receiveTime); // sync the time every hour
gw.wait(DWELL_TIME);
transmitRainData();
rainRate = 0;
gw.send(msgRainRate.set(rainRate, 1));
gw.wait(DWELL_TIME);
DEBUG_PRINTLN(F("Sending rainRate is 0 to controller"));
lastHour = currentHour;
}
if (millis() - sensorPreviousMillis > DHT_LUX_DELAY)
{
#ifdef DHT_ON //DHT Code
doDHT();
#endif
#ifdef LUX_ON
doLUX();
#endif
sensorPreviousMillis = millis();
}
}
//
#ifdef DHT_ON
void doDHT(void)
{
float temperature = dht.getTemperature();
if (isnan(temperature))
{
DEBUG_PRINTLN(F("Failed reading temperature from DHT"));
} else if (temperature != lastTemp)
{
lastTemp = temperature;
if (!metric)
{
temperature = dht.toFahrenheit(temperature);
}
gw.send(msgTemp.set(temperature, 1));
gw.wait(DWELL_TIME);
DEBUG_PRINT(F("Temperature is: "));
DEBUG_PRINTLN(temperature);
}
float humidity = dht.getHumidity();;
if (isnan(humidity))
{
DEBUG_PRINTLN(F("Failed reading humidity from DHT"));
} else if (humidity != lastHum)
{
lastHum = humidity;
gw.send(msgHum.set(humidity, 1));
gw.wait(DWELL_TIME);
DEBUG_PRINT(F("Humidity is: "));
DEBUG_PRINTLN(humidity);
}
}
#endif
//
#ifdef LUX_ON
void doLUX(void)
{
unsigned int lux = lightSensor.readLightLevel();// Get Lux value
DEBUG_PRINT(F("Current LUX Level: "));
DEBUG_PRINTLN(lux);
heartbeat++;
if (lux != lastlux || heartbeat > 10)
{
gw.send(msg.set(lux));
lastlux = lux;
}
if (heartbeat > 10)
{
heartbeat = 0;
}
}
#endif
//
void sensorTipped()
{
unsigned long thisTipTime = millis();
if (thisTipTime - lastTipTime > 100UL)
{
rainBucket[0] += CALIBRATE_FACTOR; // adds CALIBRATE_FACTOR hundredths of unit each tip
wasTippedBuffer++;
}
lastTipTime = thisTipTime;
}
//
int rainTotal(int hours)
{
int total = 0;
for ( int i = 0; i <= hours; i++)
{
total += rainBucket [i];
}
return total;
}
void updateSerialData(int x)
{
DEBUG_PRINT(F("Rain last "));
DEBUG_PRINT(x);
DEBUG_PRINTLN(F(" hours: "));
float tipCount = 0;
for (int i = 0; i < x; i++)
{
tipCount = tipCount + rainBucket [i];
}
tipCount = tipCount / 100;
DEBUG_PRINTLN(tipCount);
}
void loadRainArray(int value) // retrieve stored rain array from EEPROM on powerup
{
for (int i = 0; i < RAIN_BUCKET_SIZE; i++)
{
value = value - 2;
if (value < EEPROM_BUFFER_LOCATION)
{
value = EEPROM_BUFFER_LOCATION + E_BUFFER_LENGTH;
}
DEBUG_PRINT(F("EEPROM location: "));
DEBUG_PRINTLN(value);
byte rainValueHigh = gw.loadState(value);
byte rainValueLow = gw.loadState(value + 1);
unsigned int rainValue = rainValueHigh << 8;
rainValue |= rainValueLow;
rainBucket[i + 1] = rainValue;
//
DEBUG_PRINT(F("rainBucket[ value: "));
DEBUG_PRINT(i + 1);
DEBUG_PRINT(F("] value: "));
DEBUG_PRINTLN(rainBucket[i + 1]);
}
}
void transmitRainData(void)
{
DEBUG_PRINT(F("In transmitRainData. currentHour = "));
DEBUG_PRINTLN(currentHour);
int rainUpdateTotal = 0;
for (int i = currentHour; i >= 0; i--)
{
rainUpdateTotal += rainBucket[i];
DEBUG_PRINT(F("Adding rainBucket["));
DEBUG_PRINT(i);
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
}
DEBUG_PRINT(F("TX Day 1: rainUpdateTotal = "));
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
gw.send(msgRainVAR1.set((float)rainUpdateTotal / 100.0, 1)); //Send current day rain totals (resets at midnight)
gw.wait(DWELL_TIME);
#ifdef USE_DAILY
rainUpdateTotal = 0;
#endif
for (int i = currentHour + 24; i > currentHour; i--)
{
rainUpdateTotal += rainBucket[i];
DEBUG_PRINT(F("Adding rainBucket["));
DEBUG_PRINT(i);
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
}
DEBUG_PRINT(F("TX Day 2: rainUpdateTotal = "));
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
gw.send(msgRainVAR2.set((float)rainUpdateTotal / 100.0, 1));
gw.wait(DWELL_TIME);
#ifdef USE_DAILY
rainUpdateTotal = 0;
#endif
for (int i = currentHour + 48; i > currentHour + 24; i--)
{
rainUpdateTotal += rainBucket[i];
DEBUG_PRINT(F("Adding rainBucket["));
DEBUG_PRINT(i);
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
}
DEBUG_PRINT(F("TX Day 3: rainUpdateTotal = "));
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
gw.send(msgRainVAR3.set((float)rainUpdateTotal / 100.0, 1));
gw.wait(DWELL_TIME);
#ifdef USE_DAILY
rainUpdateTotal = 0;
#endif
for (int i = currentHour + 72; i > currentHour + 48; i--)
{
rainUpdateTotal += rainBucket[i];
DEBUG_PRINT(F("Adding rainBucket["));
DEBUG_PRINT(i);
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
}
DEBUG_PRINT(F("TX Day 4: rainUpdateTotal = "));
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
gw.send(msgRainVAR4.set((float)rainUpdateTotal / 100.0, 1));
gw.wait(DWELL_TIME);
#ifdef USE_DAILY
rainUpdateTotal = 0;
#endif
for (int i = currentHour + 96; i > currentHour + 72; i--)
{
rainUpdateTotal += rainBucket[i];
DEBUG_PRINT(F("Adding rainBucket["));
DEBUG_PRINT(i);
DEBUG_PRINTLN(F("] to rainUpdateTotal."));
}
DEBUG_PRINT(F("TX Day 5: rainUpdateTotal = "));
DEBUG_PRINTLN((float)rainUpdateTotal / 100.0);
gw.send(msgRainVAR5.set((float)rainUpdateTotal / 100.0, 1));
gw.wait(DWELL_TIME);
}
void getVariables(const MyMessage &message)
{
if (message.sensor == CHILD_ID_RAIN_LOG)
{
// nothing to do here
}
else if (message.sensor == CHILD_ID_TRIPPED_INDICATOR)
{
if (message.type == V_VAR1)
{
rainWindow = atoi(message.data);
if (rainWindow > 120)
{
rainWindow = 120;
}
else if (rainWindow < 1)
{
rainWindow = 1;
}
if (rainWindow != atoi(message.data)) // if I changed the value back inside the boundries, push that number back to Vera
{
gw.send(msgTrippedVar1.set(rainWindow));
}
}
else if (message.type == V_VAR2)
{
rainSensorThreshold = atoi(message.data);
if (rainSensorThreshold > 10000)
{
rainSensorThreshold = 10000;
}
else if (rainSensorThreshold < 1)
{
rainSensorThreshold = 1;
}
if (rainSensorThreshold != atoi(message.data)) // if I changed the value back inside the boundries, push that number back to Vera
{
gw.send(msgTrippedVar2.set(rainSensorThreshold));
}
}
}
}
void prettyFade(void)
{
float val = (exp(sin(millis() / 2000.0 * PI)) - 0.36787944) * 108.0;
analogWrite(ledPin, val);
}
void slowFlash(void)
{
static boolean ledState = true;
static unsigned long pulseStart = millis();
if (millis() - pulseStart < 100UL)
{
digitalWrite(ledPin, !ledState);
pulseStart = millis();
}
}
void receiveTime(unsigned long time)
{
DEBUG_PRINTLN(F("Time received..."));
setTime(time);
char theTime[6];
sprintf(theTime, "%d:%2d", hour(), minute());
DEBUG_PRINTLN(theTime);
}
@@ -40,6 +40,11 @@
// When MEASURE_INTERVAL is 60000 and FORCE_TRANSMIT_INTERVAL is 30, we force a transmission every 30 minutes.
// Between the forced transmissions a tranmission will only occur if the measured value differs from the previous measurement
// HUMI_TRANSMIT_THRESHOLD tells how much the humidity should have changed since last time it was transmitted. Likewise with
// TEMP_TRANSMIT_THRESHOLD for temperature threshold.
#define HUMI_TRANSMIT_THRESHOLD 0.5
#define TEMP_TRANSMIT_THRESHOLD 0.5
// Pin definitions
#define TEST_PIN A0
#define LED_PIN A2
@@ -73,7 +78,6 @@ int lastHumidity = -100;
long lastBattery = -100;
RunningAverage raHum(AVERAGES);
RunningAverage raTemp(AVERAGES);
/****************************************************
*
@@ -109,9 +113,10 @@ void setup() {
gw.begin(NULL,AUTO,false);
#endif
humiditySensor.begin();
digitalWrite(LED_PIN, LOW);
humiditySensor.begin();
Serial.flush();
Serial.println(F(" - Online!"));
gw.sendSketchInfo("Sensebender Micro", RELEASE);
@@ -123,10 +128,10 @@ void setup() {
gw.present(BATT_SENSOR, S_POWER);
#endif
isMetric = gw.getConfig().isMetric;
Serial.print(F("isMetric: ")); Serial.println(isMetric);
raHum.clear();
raTemp.clear();
sendTempHumidityMeasurements(false);
sendBattLevel(false);
}
@@ -179,21 +184,19 @@ void sendTempHumidityMeasurements(bool force)
bool tx = force;
si7021_env data = humiditySensor.getHumidityAndTemperature();
float oldAvgTemp = raTemp.getAverage();
float oldAvgHum = raHum.getAverage();
raTemp.addValue(data.celsiusHundredths);
raHum.addValue(data.humidityPercent);
float diffTemp = abs(lastTemperature - data.celsiusHundredths/100);
float diffTemp = abs(lastTemperature - (isMetric ? data.celsiusHundredths : data.fahrenheitHundredths)/100);
float diffHum = abs(oldAvgHum - raHum.getAverage());
Serial.print(F("TempDiff :"));Serial.println(diffTemp);
Serial.print(F("HumDiff :"));Serial.println(diffHum);
if (isnan(diffTemp)) tx = true;
if (diffTemp > 0.3) tx = true;
if (diffHum >= 0.5) tx = true;
if (isnan(diffHum)) tx = true;
if (diffTemp > TEMP_TRANSMIT_THRESHOLD) tx = true;
if (diffHum >= HUMI_TRANSMIT_THRESHOLD) tx = true;
if (tx) {
measureCount = 0;
+47 -17
View File
@@ -4,6 +4,24 @@ Copyright (c) 2007, Jim Studt (original old version - many contributors since)
The latest version of this library may be found at:
http://www.pjrc.com/teensy/td_libs_OneWire.html
OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since
January 2010. At the time, it was in need of many bug fixes, but had
been abandoned the original author (Jim Studt). None of the known
contributors were interested in maintaining OneWire. Paul typically
works on OneWire every 6 to 12 months. Patches usually wait that
long. If anyone is interested in more actively maintaining OneWire,
please contact Paul.
Version 2.2:
Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com
Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030
Fix DS18B20 example negative temperature
Fix DS18B20 example's low res modes, Ken Butcher
Improve reset timing, Mark Tillotson
Add const qualifiers, Bertrik Sikken
Add initial value input to crc16, Bertrik Sikken
Add target_search() function, Scott Roberts
Version 2.1:
Arduino 1.0 compatibility, Paul Stoffregen
Improve temperature example, Paul Stoffregen
@@ -136,13 +154,13 @@ uint8_t OneWire::reset(void)
DIRECT_WRITE_LOW(reg, mask);
DIRECT_MODE_OUTPUT(reg, mask); // drive output low
interrupts();
delayMicroseconds(500);
delayMicroseconds(480);
noInterrupts();
DIRECT_MODE_INPUT(reg, mask); // allow it to float
delayMicroseconds(80);
delayMicroseconds(70);
r = !DIRECT_READ(reg, mask);
interrupts();
delayMicroseconds(420);
delayMicroseconds(410);
return r;
}
@@ -249,13 +267,13 @@ void OneWire::read_bytes(uint8_t *buf, uint16_t count) {
//
// Do a ROM select
//
void OneWire::select( uint8_t rom[8])
void OneWire::select(const uint8_t rom[8])
{
int i;
uint8_t i;
write(0x55); // Choose ROM
for( i = 0; i < 8; i++) write(rom[i]);
for (i = 0; i < 8; i++) write(rom[i]);
}
//
@@ -280,17 +298,30 @@ void OneWire::depower()
// You do not need to do it for the first search, though you could.
//
void OneWire::reset_search()
{
{
// reset the search state
LastDiscrepancy = 0;
LastDeviceFlag = FALSE;
LastFamilyDiscrepancy = 0;
for(int i = 7; ; i--)
{
for(int i = 7; ; i--) {
ROM_NO[i] = 0;
if ( i == 0) break;
}
}
}
// Setup the search to find the device type 'family_code' on the next call
// to search(*newAddr) if it is present.
//
void OneWire::target_search(uint8_t family_code)
{
// set the search state to find SearchFamily type devices
ROM_NO[0] = family_code;
for (uint8_t i = 1; i < 8; i++)
ROM_NO[i] = 0;
LastDiscrepancy = 64;
LastFamilyDiscrepancy = 0;
LastDeviceFlag = FALSE;
}
//
// Perform a search. If this function returns a '1' then it has
@@ -461,7 +492,7 @@ static const uint8_t PROGMEM dscrc_table[] = {
// compared to all those delayMicrosecond() calls. But I got
// confused, so I use this table from the examples.)
//
uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len)
{
uint8_t crc = 0;
@@ -475,7 +506,7 @@ uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
// Compute a Dallas Semiconductor 8 bit CRC directly.
// this is much slower, but much smaller, than the lookup table.
//
uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len)
{
uint8_t crc = 0;
@@ -493,23 +524,22 @@ uint8_t OneWire::crc8( uint8_t *addr, uint8_t len)
#endif
#if ONEWIRE_CRC16
bool OneWire::check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc)
bool OneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc)
{
uint16_t crc = ~crc16(input, len);
crc = ~crc16(input, len, crc);
return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1];
}
uint16_t OneWire::crc16(uint8_t* input, uint16_t len)
uint16_t OneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc)
{
static const uint8_t oddparity[16] =
{ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
uint16_t crc = 0; // Starting seed is zero.
for (uint16_t i = 0 ; i < len ; i++) {
// Even though we're just copying a byte from the input,
// we'll be doing 16-bit computation with it.
uint16_t cdata = input[i];
cdata = (cdata ^ (crc & 0xff)) & 0xff;
cdata = (cdata ^ crc) & 0xff;
crc >>= 8;
if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4])
+46 -9
View File
@@ -56,13 +56,44 @@
#define IO_REG_TYPE uint8_t
#define IO_REG_ASM asm("r30")
#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0)
#define DIRECT_MODE_INPUT(base, mask) ((*(base+1)) &= ~(mask))
#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) |= (mask))
#define DIRECT_WRITE_LOW(base, mask) ((*(base+2)) &= ~(mask))
#define DIRECT_WRITE_HIGH(base, mask) ((*(base+2)) |= (mask))
#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask))
#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask))
#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask))
#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask))
#elif defined(__MK20DX128__)
#define PIN_TO_BASEREG(pin) (portOutputRegister(pin))
#define PIN_TO_BITMASK(pin) (1)
#define IO_REG_TYPE uint8_t
#define IO_REG_ASM
#define DIRECT_READ(base, mask) (*((base)+512))
#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0)
#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1)
#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1)
#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1)
#elif defined(__SAM3X8E__)
// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due.
// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268
// If you have trouble with OneWire on Arduino Due, please check the
// status of delayMicroseconds() before reporting a bug in OneWire!
#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER))
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
#define IO_REG_TYPE uint32_t
#define IO_REG_ASM
#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0)
#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask))
#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask))
#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask))
#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask))
#ifndef PROGMEM
#define PROGMEM
#endif
#ifndef pgm_read_byte
#define pgm_read_byte(addr) (*(const uint8_t *)(addr))
#endif
#elif defined(__PIC32MX__)
#include <plib.h> // is this necessary?
#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin)))
#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin))
#define IO_REG_TYPE uint32_t
@@ -101,7 +132,7 @@ class OneWire
uint8_t reset(void);
// Issue a 1-Wire rom select command, you do the reset first.
void select( uint8_t rom[8]);
void select(const uint8_t rom[8]);
// Issue a 1-Wire rom skip command, to address all on bus.
void skip(void);
@@ -137,6 +168,10 @@ class OneWire
// Clear the search state so that if will start from the beginning again.
void reset_search();
// Setup the search to find the device type 'family_code' on the next call
// to search(*newAddr) if it is present.
void target_search(uint8_t family_code);
// Look for the next device. Returns 1 if a new address has been
// returned. A zero might mean that the bus is shorted, there are
// no devices, or you have already retrieved all of them. It
@@ -149,7 +184,7 @@ class OneWire
#if ONEWIRE_CRC
// Compute a Dallas Semiconductor 8 bit CRC, these are used in the
// ROM and scratchpad registers.
static uint8_t crc8( uint8_t *addr, uint8_t len);
static uint8_t crc8(const uint8_t *addr, uint8_t len);
#if ONEWIRE_CRC16
// Compute the 1-Wire CRC16 and compare it against the received CRC.
@@ -170,8 +205,9 @@ class OneWire
// @param inverted_crc - The two CRC16 bytes in the received data.
// This should just point into the received data,
// *not* at a 16-bit integer.
// @param crc - The crc starting value (optional)
// @return True, iff the CRC matches.
static bool check_crc16(uint8_t* input, uint16_t len, uint8_t* inverted_crc);
static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0);
// Compute a Dallas Semiconductor 16 bit CRC. This is required to check
// the integrity of data received from many 1-Wire devices. Note that the
@@ -183,8 +219,9 @@ class OneWire
// byte order than the two bytes you get from 1-Wire.
// @param input - Array of bytes to checksum.
// @param len - How many bytes to use.
// @param crc - The crc starting value (optional)
// @return The CRC16, as defined by Dallas Semiconductor.
static uint16_t crc16(uint8_t* input, uint16_t len);
static uint16_t crc16(const uint8_t* input, uint16_t len, uint16_t crc = 0);
#endif
#endif
};
@@ -7,7 +7,7 @@
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library
OneWire ds(10); // on pin 10
OneWire ds(10); // on pin 10 (a 4.7K resistor is necessary)
void setup(void) {
Serial.begin(9600);
@@ -62,7 +62,7 @@ void loop(void) {
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
ds.write(0x44, 1); // start conversion, with parasite power on at the end
delay(1000); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
@@ -72,7 +72,7 @@ void loop(void) {
ds.write(0xBE); // Read Scratchpad
Serial.print(" Data = ");
Serial.print(present,HEX);
Serial.print(present, HEX);
Serial.print(" ");
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
@@ -83,21 +83,24 @@ void loop(void) {
Serial.print(OneWire::crc8(data, 8), HEX);
Serial.println();
// convert the data to actual temperature
unsigned int raw = (data[1] << 8) | data[0];
// Convert the data to actual temperature
// because the result is a 16 bit signed integer, it should
// be stored to an "int16_t" type, which is always 16 bits
// even when compiled on a 32 bit processor.
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// count remain gives full 12 bit resolution
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw << 3; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw << 2; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw << 1; // 11 bit res, 375 ms
// default is 12 bit resolution, 750 ms conversion time
// at lower res, the low bits are undefined, so let's zero them
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
//// default is 12 bit resolution, 750 ms conversion time
}
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
@@ -0,0 +1,10 @@
Notes from AS3935 datasheet:
Register Map: Page 11, detailed version on Page 12
Max clock freq for SPI = 2MHz
SPI command Structure: Page14
To activate this SPI, the CS has to be set to low. A SPI command consists of two bytes serial command and the data are sampled on the falling
edge of SCLK (CPHA=1). The next table shows command structure, from the MSB (B15) to LSB (B0). The command stream has to be sent to
the SPI from the MSB (B15) to the LSB (B0).
@@ -0,0 +1,421 @@
/***************************************************************************
* File Name: PWFusion_AS3935.h
* Processor/Platform: Arduino Uno R3 (tested)
* Development Environment: Arduino 1.0.5
*
* Designed for use with with Playing With Fusion AS3935 Lightning Sensor
* Breakout: SEN-39001.
*
* SEN-39001 (universal applications)
* ---> http://www.playingwithfusion.com/productview.php?pdid=22
*
* Copyright © 2014 Playing With Fusion, Inc.
* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* **************************************************************************
* REVISION HISTORY:
* Author Date Comments
* J. Steinlage 2014Aug20 Original version
*
* Playing With Fusion, Inc. invests time and resources developing open-source
* code. Please support Playing With Fusion and continued open-source
* development by buying products from Playing With Fusion!
*
* **************************************************************************
* ADDITIONAL NOTES:
* This file contains functions to interface with the AS3935 Franklin
* Lightning Sensor manufactured by AMS. Originally designed for application
* on the Arduino Uno platform.
**************************************************************************/
#include "PWFusion_AS3935.h"
PWF_AS3935::PWF_AS3935(int8_t CSx, int8_t IRQx, int8_t SIx)
{
_cs = CSx;
_si = SIx;
_irq = IRQx;
// initalize the chip select pins
pinMode(_cs, OUTPUT);
pinMode(_si, OUTPUT);
pinMode(_irq, INPUT);
digitalWrite(_cs, HIGH); // set pin high to initialize/clear SPI bus
digitalWrite(_si, LOW); // set pin low for SPI mode
}
uint8_t PWF_AS3935::_sing_reg_read(uint8_t RegAdd)
{
digitalWrite(_cs, LOW); // set pin low to start talking to IC
// next pack command byte, send AS3935.... structure is shown below
// MODE Register Address/Direct Cmd
// B15-14 B13------------------8
// 15 is always 0; B14, 0: Write/Direct Command, 1: Read
SPI.transfer((RegAdd & 0x3F) | 0x40); // simple write, nothing to read back
uint8_t RegData = SPI.transfer(0x00); // read register data from IC
digitalWrite(_cs, HIGH); // set pin high to end SPI session
return RegData;
}
void PWF_AS3935::_sing_reg_write(uint8_t RegAdd, uint8_t DataMask, uint8_t RegData)
{
// start by reading original register data (only modifying what we need to)
uint8_t OrigRegData = _sing_reg_read(RegAdd);
// calculate new register data... 'delete' old targeted data, replace with new data
// note: 'DataMask' must be bits targeted for replacement
// add'l note: this function does NOT shift values into the proper place... they need to be there already
uint8_t NewRegData = ((OrigRegData & ~DataMask) | (RegData & DataMask));
// now configure and write the updated register value
digitalWrite(_cs, LOW); // set pin low to start talking to IC
// next pack command byte, send AS3935.... structure is shown below
// MODE Register Address/Direct Cmd
// B15-14 B13------------------8
// 15 is always 0; B14, 0: Write/Direct Command, 1: Read
SPI.transfer((RegAdd & 0x3F)); // simple write, nothing to read back
SPI.transfer(RegData); // write register data to IC
digitalWrite(_cs, HIGH); // set pin high to end SPI session
}
void PWF_AS3935::AS3935_DefInit()
{
_AS3935_Reset(); // reset registers to default
}
void PWF_AS3935::_AS3935_Reset()
{
// run PRESET_DEFAULT Direct Command to set all registers in default state
digitalWrite(_cs, LOW); // begin transfer
SPI.transfer(0x3C); // send first byte (write, PRESET_DEFAULT register)
SPI.transfer(0x96); // send second byte (direct command)
digitalWrite(_cs, HIGH); // end transfer
delay(2); // wait 2ms to complete
}
void PWF_AS3935::_CalRCO()
{
// run ALIB_RCO Direct Command to cal internal RCO
digitalWrite(_cs, LOW); // begin transfer
SPI.transfer(0x3D); // send first byte (write, CALIB_RCO register)
SPI.transfer(0x96); // send second byte (direct command)
digitalWrite(_cs, HIGH); // end transfer
delay(3); // wait 3ms to complete
}
void PWF_AS3935::AS3935_PowerUp(void)
{
// power-up sequence based on datasheet, pg 23/27
// register 0x00, PWD bit: 0 (clears PWD)
_sing_reg_write(0x00, 0x01, 0x00);
_CalRCO(); // run RCO cal cmd
_sing_reg_write(0x08, 0x20, 0x20); // set DISP_SRCO to 1
delay(2);
_sing_reg_write(0x08, 0x20, 0x00); // set DISP_SRCO to 0
}
void PWF_AS3935::AS3935_PowerDown(void)
{
// register 0x00, PWD bit: 0 (sets PWD)
_sing_reg_write(0x00, 0x01, 0x01);
Serial.println("AS3935 powered down");
}
void PWF_AS3935::AS3935_DisturberEn(void)
{
// register 0x03, PWD bit: 5 (sets MASK_DIST)
_sing_reg_write(0x03, 0x20, 0x00);
Serial.println("disturber detection enabled");
}
void PWF_AS3935::AS3935_DisturberDis(void)
{
// register 0x03, PWD bit: 5 (sets MASK_DIST)
_sing_reg_write(0x03, 0x20, 0x20);
}
void PWF_AS3935::AS3935_SetIRQ_Output_Source(uint8_t irq_select)
{
// set interrupt source - what to displlay on IRQ pin
// reg 0x08, bits 5 (TRCO), 6 (SRCO), 7 (LCO)
// only one should be set at once, I think
// 0 = NONE, 1 = TRCO, 2 = SRCO, 3 = LCO
if(1 == irq_select)
{
_sing_reg_write(0x08, 0xE0, 0x20); // set only TRCO bit
}
else if(2 == irq_select)
{
_sing_reg_write(0x08, 0xE0, 0x40); // set only SRCO bit
}
else if(3 == irq_select)
{
_sing_reg_write(0x08, 0xE0, 0x80); // set only LCO bit
}
else // assume 0
{
_sing_reg_write(0x08, 0xE0, 0x00); // clear IRQ pin display bits
}
}
void PWF_AS3935::AS3935_SetTuningCaps(uint8_t cap_val)
{
// Assume only numbers divisible by 8 (because that's all the chip supports)
if(120 < cap_val) // cap_value out of range, assume highest capacitance
{
_sing_reg_write(0x08, 0x0F, 0x0F); // set capacitance bits to maximum
}
else
{
_sing_reg_write(0x08, 0x0F, (cap_val>>3)); // set capacitance bits
}
Serial.print("capacitance set to 8x");
Serial.println((_sing_reg_read(0x08) & 0x0F));
}
uint8_t PWF_AS3935::AS3935_GetInterruptSrc(void)
{
// definition of interrupt data on table 18 of datasheet
// for this function:
// 0 = unknown src, 1 = lightning detected, 2 = disturber, 3 = Noise level too high
delay(10); // wait 10ms before reading (2ms per pg 22 of datasheet)
uint8_t int_src = (_sing_reg_read(0x03) & 0x0F); // read register, get rid of non-interrupt data
if(0x08 == int_src)
{
return 1; // lightning caused interrupt
}
else if(0x04 == int_src)
{
return 2; // disturber detected
}
else if(0x01 == int_src)
{
return 3; // Noise level too high
}
else{return 0;} // interrupt result not expected
}
uint8_t PWF_AS3935::AS3935_GetLightningDistKm(void)
{
uint8_t strike_dist = (_sing_reg_read(0x07) & 0x3F); // read register, get rid of non-distance data
return strike_dist;
}
uint32_t PWF_AS3935::AS3935_GetStrikeEnergyRaw(void)
{
uint32_t nrgy_raw = ((_sing_reg_read(0x06) & 0x1F) << 8); // MMSB, shift 8 bits left, make room for MSB
nrgy_raw |= _sing_reg_read(0x05); // read MSB
nrgy_raw <= 8; // shift 8 bits left, make room for LSB
nrgy_raw |= _sing_reg_read(0x04); // read LSB, add to others
return nrgy_raw;
}
uint8_t PWF_AS3935::AS3935_SetMinStrikes(uint8_t min_strk)
{
// This function sets min strikes to the closest available number, rounding to the floor,
// where necessary, then returns the physical value that was set. Options are 1, 5, 9 or 16 strikes.
// see pg 22 of the datasheet for more info (#strikes in 17 min)
if(5 > min_strk)
{
_sing_reg_write(0x02, 0x30, 0x00);
return 1;
}
else if(9 > min_strk)
{
_sing_reg_write(0x02, 0x30, 0x10);
return 5;
}
else if(16 > min_strk)
{
_sing_reg_write(0x02, 0x30, 0x20);
return 9;
}
else
{
_sing_reg_write(0x02, 0x30, 0x30);
return 16;
}
}
void PWF_AS3935::AS3935_SetIndoors(void)
{
// AFE settings addres 0x00, bits 5:1 (10010, based on datasheet, pg 19, table 15)
// this is the default setting at power-up (AS3935 datasheet, table 9)
_sing_reg_write(0x00, 0x3E, 0x24);
Serial.println("set up for indoor operation");
}
void PWF_AS3935::AS3935_SetOutdoors(void)
{
// AFE settings addres 0x00, bits 5:1 (01110, based on datasheet, pg 19, table 15)
_sing_reg_write(0x00, 0x3E, 0x1C);
Serial.println("set up for outdoor operation");
}
void PWF_AS3935::AS3935_ClearStatistics(void)
{
// clear is accomplished by toggling CL_STAT bit 'high-low-high' (then set low to move on)
_sing_reg_write(0x02, 0x40, 0x40); // high
_sing_reg_write(0x02, 0x40, 0x00); // low
_sing_reg_write(0x02, 0x40, 0x40); // high
}
uint8_t PWF_AS3935::AS3935_GetNoiseFloorLvl(void)
{
// NF settings addres 0x01, bits 6:4
// default setting of 010 at startup (datasheet, table 9)
uint8_t reg_raw = _sing_reg_read(0x01); // read register 0x01
return ((reg_raw & 0x70)>>4); // should return value from 0-7, see table 16 for info
}
void PWF_AS3935::AS3935_SetNoiseFloorLvl(uint8_t nf_sel)
{
// NF settings addres 0x01, bits 6:4
// default setting of 010 at startup (datasheet, table 9)
if(7 >= nf_sel) // nf_sel within expected range
{
_sing_reg_write(0x01, 0x70, ((nf_sel & 0x07)<<4));
}
else
{ // out of range, set to default (power-up value 010)
_sing_reg_write(0x01, 0x70, 0x20);
}
}
uint8_t PWF_AS3935::AS3935_GetWatchdogThreshold(void)
{
// This function is used to read WDTH. It is used to increase robustness to disturbers,
// though will make detection less efficient (see page 19, Fig 20 of datasheet)
// WDTH register: add 0x01, bits 3:0
// default value of 0001
// values should only be between 0x00 and 0x0F (0 and 7)
uint8_t reg_raw = _sing_reg_read(0x01);
return (reg_raw & 0x0F);
}
void PWF_AS3935::AS3935_SetWatchdogThreshold(uint8_t wdth)
{
// This function is used to modify WDTH. It is used to increase robustness to disturbers,
// though will make detection less efficient (see page 19, Fig 20 of datasheet)
// WDTH register: add 0x01, bits 3:0
// default value of 0001
// values should only be between 0x00 and 0x0F (0 and 7)
_sing_reg_write(0x01, 0x0F, (wdth & 0x0F));
}
uint8_t PWF_AS3935::AS3935_GetSpikeRejection(void)
{
// This function is used to read SREJ (spike rejection). Similar to the Watchdog threshold,
// it is used to make the system more robust to disturbers, though will make general detection
// less efficient (see page 20-21, especially Fig 21 of datasheet)
// SREJ register: add 0x02, bits 3:0
// default value of 0010
// values should only be between 0x00 and 0x0F (0 and 7)
uint8_t reg_raw = _sing_reg_read(0x02);
return (reg_raw & 0x0F);
}
void PWF_AS3935::AS3935_SetSpikeRejection(uint8_t srej)
{
// This function is used to modify SREJ (spike rejection). Similar to the Watchdog threshold,
// it is used to make the system more robust to disturbers, though will make general detection
// less efficient (see page 20-21, especially Fig 21 of datasheet)
// WDTH register: add 0x02, bits 3:0
// default value of 0010
// values should only be between 0x00 and 0x0F (0 and 7)
_sing_reg_write(0x02, 0x0F, (srej & 0x0F));
}
void PWF_AS3935::AS3935_SetLCO_FDIV(uint8_t fdiv)
{
// This function sets LCO_FDIV register. This is useful in the tuning of the antenna
// LCO_FDIV register: add 0x03, bits 7:6
// default value: 00
// set 0, 1, 2 or 3 for ratios of 16, 32, 64 and 128, respectively.
// See pg 23, Table 20 for more info.
_sing_reg_write(0x03, 0xC0, ((fdiv & 0x03) << 5));
}
void PWF_AS3935::AS3935_PrintAllRegs(void)
{
Serial.print("Reg 0x00: ");
Serial.println(_sing_reg_read(0x00));
Serial.print("Reg 0x01: ");
Serial.println(_sing_reg_read(0x01));
Serial.print("Reg 0x02: ");
Serial.println(_sing_reg_read(0x02));
Serial.print("Reg 0x03: ");
Serial.println(_sing_reg_read(0x03));
Serial.print("Reg 0x04: ");
Serial.println(_sing_reg_read(0x04));
Serial.print("Reg 0x05: ");
Serial.println(_sing_reg_read(0x05));
Serial.print("Reg 0x06: ");
Serial.println(_sing_reg_read(0x06));
Serial.print("Reg 0x07: ");
Serial.println(_sing_reg_read(0x07));
Serial.print("Reg 0x08: ");
Serial.println(_sing_reg_read(0x08));
uint32_t nrgy_val = AS3935_GetStrikeEnergyRaw();
Serial.println(nrgy_val);
}
void PWF_AS3935::AS3935_ManualCal(uint8_t capacitance, uint8_t location, uint8_t disturber)
{
// start by powering up
AS3935_PowerUp();
// indoors/outdoors next...
if(1 == location) // set outdoors if 1
{
AS3935_SetOutdoors();
}
else // set indoors if anything but 1
{
AS3935_SetIndoors();
}
// disturber cal
if(0 == disturber) // disabled if 0
{
AS3935_DisturberDis();
}
else // enabled if anything but 0
{
AS3935_DisturberEn();
}
AS3935_SetIRQ_Output_Source(0);
delay(500);
// capacitance first... directly write value here
AS3935_SetTuningCaps(capacitance);
Serial.println("AS3935 manual cal complete");
}
// a nice function would be to read the last 'x' strike data values....
@@ -0,0 +1,96 @@
/***************************************************************************
* File Name: PWFusion_AS3935.h
* Processor/Platform: Arduino Uno R3 (tested)
* Development Environment: Arduino 1.0.5
*
* Designed for use with with Playing With Fusion AS3935 Lightning Sensor
* Breakout: SEN-39001.
*
* SEN-39001 (universal applications)
* ---> http://www.playingwithfusion.com/productview.php?pdid=22
*
* Copyright © 2014 Playing With Fusion, Inc.
* SOFTWARE LICENSE AGREEMENT: This code is released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* **************************************************************************
* REVISION HISTORY:
* Author Date Comments
* J. Steinlage 2014Aug20 Original version
*
* Playing With Fusion, Inc. invests time and resources developing open-source
* code. Please support Playing With Fusion and continued open-source
* development by buying products from Playing With Fusion!
*
* **************************************************************************
* ADDITIONAL NOTES:
* This file contains functions to interface with the AS3935 Franklin
* Lightning Sensor manufactured by AMS. Originally designed for application
* on the Arduino Uno platform.
**************************************************************************/
#ifndef PWF_AS3935_h
#define PWF_AS3935_h
#include "Arduino.h"
#include "avr/pgmspace.h"
#include "util/delay.h"
#include "stdlib.h"
#include "SPI.h"
class PWF_AS3935
{
public:
PWF_AS3935(int8_t CSx, int8_t IRQx, int8_t SIx);
void AS3935_ManualCal(uint8_t capacitance, uint8_t location, uint8_t disturber);
void AS3935_DefInit(void);
void AS3935_PowerUp(void);
void AS3935_PowerDown(void);
void AS3935_DisturberEn(void);
void AS3935_DisturberDis(void);
void AS3935_SetIRQ_Output_Source(uint8_t irq_select);
void AS3935_SetTuningCaps(uint8_t cap_val);
uint8_t AS3935_GetInterruptSrc(void);
uint8_t AS3935_GetLightningDistKm(void);
uint32_t AS3935_GetStrikeEnergyRaw(void);
uint8_t AS3935_SetMinStrikes(uint8_t min_strk);
void AS3935_ClearStatistics(void);
void AS3935_SetIndoors(void);
void AS3935_SetOutdoors(void);
uint8_t AS3935_GetNoiseFloorLvl(void);
void AS3935_SetNoiseFloorLvl(uint8_t nf_sel);
uint8_t AS3935_GetWatchdogThreshold(void);
void AS3935_SetWatchdogThreshold(uint8_t wdth);
uint8_t AS3935_GetSpikeRejection(void);
void AS3935_SetSpikeRejection(uint8_t srej);
void AS3935_SetLCO_FDIV(uint8_t fdiv);
void AS3935_PrintAllRegs(void);
private:
int8_t _cs, _irq, _si;
uint8_t _sing_reg_read(uint8_t RegAdd);
void _sing_reg_write(uint8_t RegAdd, uint8_t DataMask, uint8_t RegData);
void _AS3935_Reset(void);
void _CalRCO(void);
};
#endif