Răsfoiți Sursa

NewRemoteLibrary added

sfreundel 4 ani în urmă
părinte
comite
abd80cc7b2

+ 334 - 0
lib/NewRemoteSwitch/NewRemoteReceiver.cpp

@@ -0,0 +1,334 @@
+/*
+ * NewRemoteSwitch library v1.2.0 (20140128) made by Randy Simons http://randysimons.nl/
+ * See NewRemoteReceiver.h for details.
+ *
+ * License: GPLv3. See license.txt
+ */
+
+#include "NewRemoteReceiver.h"
+
+#define RESET_STATE _state = -1 // Resets state to initial position.
+
+/************
+* NewRemoteReceiver
+
+Protocol. (Copied from Wieltje, http://www.circuitsonline.net/forum/view/message/1181410#1181410,
+but with slightly different timings, as measured on my device.)
+		_   _
+'0':   | |_| |_____ (T,T,T,5T)
+		_       _
+'1':   | |_____| |_	(T,5T,T,T)
+		_   _
+dim:   | |_| |_     (T,T,T,T)
+
+T = short period of ~260µs. However, this code tries
+to figure out the correct period
+
+A full frame looks like this:
+
+- start pulse: 1T high, 10.44T low
+- 26 bit:  Address
+- 1  bit:  group bit
+- 1  bit:  on/off/[dim]
+- 4  bit:  unit
+- [4 bit:  dim level. Present of [dim] is chosen, but might be present anyway...]
+- stop pulse: 1T high, 40T low
+
+************/
+
+#ifdef ESP8266
+    // interrupt handler and related code must be in RAM on ESP8266,
+    #define RECEIVE_ATTR ICACHE_RAM_ATTR
+	#define CALLBACK_SIGNATURE (_callback)(receivedCode.period, receivedCode.address, receivedCode.groupBit, receivedCode.unit, receivedCode.switchType)
+#else
+    #define RECEIVE_ATTR
+	#define CALLBACK_SIGNATURE (_callback)(receivedCode.period, receivedCode.address, receivedCode.groupBit, receivedCode.unit, receivedCode.switchType)
+#endif
+
+int8_t NewRemoteReceiver::_interrupt;
+volatile short NewRemoteReceiver::_state;
+byte NewRemoteReceiver::_minRepeats;
+NewRemoteReceiverCallBack NewRemoteReceiver::_callback;
+boolean NewRemoteReceiver::_inCallback = false;
+boolean NewRemoteReceiver::_enabled = false;
+
+void NewRemoteReceiver::init(int8_t interrupt, byte minRepeats, NewRemoteReceiverCallBack callback) {
+	_interrupt = interrupt;
+	_minRepeats = minRepeats;
+	_callback = callback;
+
+	enable();
+	if (_interrupt >= 0) {
+		attachInterrupt(_interrupt, interruptHandler, CHANGE);
+	}
+}
+
+void NewRemoteReceiver::enable() {
+	RESET_STATE;
+	_enabled = true;
+}
+
+void NewRemoteReceiver::disable() {
+	_enabled = false;
+}
+
+void NewRemoteReceiver::deinit() {
+	_enabled = false;
+	if (_interrupt >= 0) {
+		detachInterrupt(_interrupt);
+	}
+}
+
+void RECEIVE_ATTR NewRemoteReceiver::interruptHandler() {
+	// This method is written as compact code to keep it fast. While breaking up this method into more
+	// methods would certainly increase the readability, it would also be much slower to execute.
+	// Making calls to other methods is quite expensive on AVR. As These interrupt handlers are called
+	// many times a second, calling other methods should be kept to a minimum.
+
+	if (!_enabled) {
+		return;
+	}
+
+	static byte receivedBit;		// Contains "bit" currently receiving
+	static NewRemoteCode receivedCode;		// Contains received code
+	static NewRemoteCode previousCode;		// Contains previous received code
+	static byte repeats = 0;		// The number of times the an identical code is received in a row.
+	static unsigned long edgeTimeStamp[3] = {0, };	// Timestamp of edges
+	static unsigned int min1Period, max1Period, min5Period, max5Period;
+	static bool skip;
+
+	// Filter out too short pulses. This method works as a low pass filter.
+	edgeTimeStamp[1] = edgeTimeStamp[2];
+	edgeTimeStamp[2] = micros();
+
+	if (skip) {
+		skip = false;
+		return;
+	}
+
+	if (_state >= 0 && edgeTimeStamp[2]-edgeTimeStamp[1] < min1Period) {
+		// Last edge was too short.
+		// Skip this edge, and the next too.
+		skip = true;
+		return;
+	}
+
+	unsigned int duration = edgeTimeStamp[1] - edgeTimeStamp[0];
+	edgeTimeStamp[0] = edgeTimeStamp[1];
+
+	// Note that if state>=0, duration is always >= 1 period.
+	if (_state == -1) {
+		// wait for the long low part of a stop bit.
+		// Stopbit: 1T high, 40T low
+		// By default 1T is 260µs, but for maximum compatibility go as low as 120µs
+		if (duration > 4800 && duration < 15000) { // =40*120µs, minimal time between two edges before decoding starts.
+			// Sync signal received.. Preparing for decoding
+			repeats = 0;
+
+			receivedCode.period = duration / 40; // Measured signal is 40T, so 1T (period) is measured signal / 40.
+
+			// Allow for large error-margin. ElCheapo-hardware :(
+			min1Period = receivedCode.period * 3 / 10; // Lower limit for 1 period is 0.3 times measured period; high signals can "linger" a bit sometimes, making low signals quite short.
+			max1Period = receivedCode.period * 3; // Upper limit for 1 period is 3 times measured period
+			min5Period = receivedCode.period * 3; // Lower limit for 5 periods is 3 times measured period
+			max5Period = receivedCode.period * 8; // Upper limit for 5 periods is 8 times measured period
+		}
+		else {
+			return;
+		}
+	} else if (_state == 0) { // Verify start bit part 1 of 2
+		// Duration must be ~1T
+		if (duration > max1Period) {
+			RESET_STATE;
+			return;
+		}
+		// Start-bit passed. Do some clean-up.
+		receivedCode.address = receivedCode.unit = receivedCode.dimLevel = 0;
+	} else if (_state == 1) { // Verify start bit part 2 of 2
+		// Duration must be ~10.44T
+
+    //                Position wird nicht erreicht
+    //                SFL
+    //
+    //      digitalWrite(LED_BUILTIN, HIGH);// turning LED on
+    //
+    //
+		if (duration < 7 * receivedCode.period || duration > 15 * receivedCode.period) {
+      			RESET_STATE;
+			return;
+		}
+	} else if (_state < 148) { // state 146 is first edge of stop-sequence. All bits before that adhere to default protocol, with exception of dim-bit
+		receivedBit <<= 1;
+
+//                Position wird nicht erreicht
+//                SFL
+//
+//                digitalWrite(LED_BUILTIN, HIGH);// turning LED on
+//
+//
+
+		// One bit consists out of 4 bit parts.
+		// bit part durations can ONLY be 1 or 5 periods.
+		if (duration <= max1Period) {
+			receivedBit &= B1110; // Clear LSB of receivedBit
+		} else if (duration >= min5Period && duration <= max5Period) {
+			receivedBit |= B1; // Set LSB of receivedBit
+		} else if (
+			// Check if duration matches the second part of stopbit (duration must be ~40T), and ...
+			(duration >= 20 * receivedCode.period && duration <= 80 * receivedCode.period) &&
+			// if first part op stopbit was a short signal (short signal yielded a 0 as second bit in receivedBit), and ...
+			((receivedBit & B10) == B00) &&
+			// we are in a state in which a stopbit is actually valid, only then ...
+			(_state == 147 || _state == 131) ) {
+				// If a dim-level was present...
+				if (_state == 147) {
+					// mark received switch signal as signal-with-dim
+                    receivedCode.dimLevelPresent = true;
+				}
+
+				// a valid signal was found!
+				if (
+						receivedCode.address != previousCode.address ||
+						receivedCode.unit != previousCode.unit ||
+						receivedCode.dimLevelPresent != previousCode.dimLevelPresent ||
+						receivedCode.dimLevel != previousCode.dimLevel ||
+						receivedCode.groupBit != previousCode.groupBit ||
+						receivedCode.switchType != previousCode.switchType
+					) { // memcmp isn't deemed safe
+					repeats=0;
+					previousCode = receivedCode;
+				}
+
+				repeats++;
+
+				if (repeats>=_minRepeats) {
+					if (!_inCallback) {
+						_inCallback = true;
+						CALLBACK_SIGNATURE;
+						_inCallback = false;
+					}
+					// Reset after callback.
+					RESET_STATE;
+					return;
+				}
+
+				// Reset for next round
+				_state=0; // no need to wait for another sync-bit!
+				return;
+		}
+		else { // Otherwise the entire sequence is invalid
+			RESET_STATE;
+			return;
+		}
+
+		if (_state % 4 == 1) { // Last bit part? Note: this is the short version of "if ( (_state-2) % 4 == 3 )"
+			// There are 3 valid options for receivedBit:
+			// 0, indicated by short short short long == B0001.
+			// 1, short long shot short == B0100.
+			// dim, short shot short shot == B0000.
+			// Everything else: inconsistent data, trash the whole sequence.
+
+
+			if (_state < 106) {
+				// States 2 - 105 are address bit states
+
+				receivedCode.address <<= 1;
+
+				// Decode bit. Only 4 LSB's of receivedBit are used; trim the rest.
+				switch (receivedBit & B1111) {
+					case B0001: // Bit "0" received.
+						// receivedCode.address |= 0; But let's not do that, as it is wasteful.
+						break;
+					case B0100: // Bit "1" received.
+						receivedCode.address |= 1;
+						break;
+					default: // Bit was invalid. Abort.
+						RESET_STATE;
+						return;
+				}
+			} else if (_state < 110) {
+				// States 106 - 109 are group bit states.
+				switch (receivedBit & B1111) {
+					case B0001: // Bit "0" received.
+						receivedCode.groupBit = false;
+						break;
+					case B0100: // Bit "1" received.
+						receivedCode.groupBit = true;
+						break;
+					default: // Bit was invalid. Abort.
+						RESET_STATE;
+						return;
+				}
+			} else if (_state < 114) {
+				// States 110 - 113 are switch bit states.
+				switch (receivedBit & B1111) {
+					case B0001: // Bit "0" received.
+						receivedCode.switchType = NewRemoteCode::off;
+						break;
+					case B0100: // Bit "1" received. Note: this might turn out to be a on_with_dim signal.
+						receivedCode.switchType = NewRemoteCode::on;
+						break;
+					case B0000: // Bit "dim" received.
+						receivedCode.switchType = NewRemoteCode::dim;
+						break;
+					default: // Bit was invalid. Abort.
+						RESET_STATE;
+						return;
+				}
+			} else if (_state < 130){
+				// States 114 - 129 are unit bit states.
+				receivedCode.unit <<= 1;
+
+				// Decode bit.
+				switch (receivedBit & B1111) {
+					case B0001: // Bit "0" received.
+						// receivedCode.unit |= 0; But let's not do that, as it is wasteful.
+						break;
+					case B0100: // Bit "1" received.
+						receivedCode.unit |= 1;
+						break;
+					default: // Bit was invalid. Abort.
+						RESET_STATE;
+						return;
+				}
+
+			} else if (_state < 146) {
+				// States 130 - 145 are dim bit states.
+                // Depending on hardware, these bits can be present, even if switchType is NewRemoteCode::on or NewRemoteCode::off
+
+				receivedCode.dimLevel <<= 1;
+
+				// Decode bit.
+				switch (receivedBit & B1111) {
+					case B0001: // Bit "0" received.
+						// receivedCode.dimLevel |= 0; But let's not do that, as it is wasteful.
+						break;
+					case B0100: // Bit "1" received.
+						receivedCode.dimLevel |= 1;
+						break;
+					default: // Bit was invalid. Abort.
+						RESET_STATE;
+						return;
+				}
+			}
+		}
+	}
+
+	_state++;
+        digitalWrite(LED_BUILTIN, LOW);// turning LED off
+	return;
+}
+
+boolean NewRemoteReceiver::isReceiving(int waitMillis) {
+	unsigned long startTime=millis();
+
+	int waited; // Signed int!
+	do {
+		if (_state >= 34) { // Abort if a significant part of a code (start pulse + 8 bits) has been received
+			return true;
+		}
+		waited = (millis()-startTime);
+	} while(waited>=0 && waited <= waitMillis); // Yes, clock wraps every 50 days. And then you'd have to wait for a looooong time.
+
+	return false;
+}

+ 120 - 0
lib/NewRemoteSwitch/NewRemoteReceiver.h

@@ -0,0 +1,120 @@
+/*
+ * NewRemoteSwitch library v1.2.0 (20140128) made by Randy Simons http://randysimons.nl/
+ *
+ * License: GPLv3. See license.txt
+ */
+
+#ifndef NewRemoteReceiver_h
+#define NewRemoteReceiver_h
+
+#include <Arduino.h>
+
+typedef enum SwitchType {
+   off = 0,
+    on = 1,
+    dim = 2
+  } switchType;
+
+struct NewRemoteCode {
+	enum SwitchType {
+   off = 0,
+    on = 1,
+    dim = 2
+  };
+	unsigned int period;		// Detected duration in microseconds of 1T in the received signal
+	unsigned long address;		// Address of received code. [0..2^26-1]
+	boolean groupBit;			// Group bit set or not
+	SwitchType switchType;		// off, on, dim, on_with_dim.
+	byte unit;					// Unit code of received code [0..15]
+	boolean dimLevelPresent;	// Dim level present or not. Will be available for switchType dim, but might be available for on or off too, depending on remote.
+	byte dimLevel;				// Dim level [0..15]. Will be available if switchType is dim, on_with_dim or off_with_dim.
+};
+
+#ifdef ESP8266
+#include <functional>
+#define CALLBACK_SIGNATUREH typedef std::function<void(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType)> NewRemoteReceiverCallBack
+#else
+#define CALLBACK_SIGNATUREH typedef void (*NewRemoteReceiverCallBack)(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType)
+#endif
+CALLBACK_SIGNATUREH;
+
+
+/**
+* See RemoteSwitch for introduction.
+*
+* NewRemoteReceiver decodes the signal received from a 433MHz-receiver, like the "KlikAanKlikUit"-system
+* as well as the signal sent by the RemoteSwtich class. When a correct signal is received,
+* a user-defined callback function is called.
+*
+* Note that in the callback function, the interrupts are still disabled. You can enabled them, if needed.
+* A call to the callback must be finished before NewRemoteReceiver will call the callback function again, thus
+* there is no re-entrant problem.
+*
+* When sending your own code using NewRemoteSwich, disable() the receiver first.
+*
+* This is a pure static class, for simplicity and to limit memory-use.
+*/
+
+		
+class NewRemoteReceiver {
+	public:
+		/**
+		* Initializes the decoder.
+		*
+		* If interrupt >= 0, init will register pin <interrupt> to this library.
+		* If interrupt < 0, no interrupt is registered. In that case, you have to call interruptHandler()
+		* yourself whenever the output of the receiver changes, or you can use InterruptChain.
+		*
+		* @param interrupt 	The interrupt as is used by Arduino's attachInterrupt function. See attachInterrupt for details.
+							If < 0, you must call interruptHandler() yourself.
+		* @param minRepeats The number of times the same code must be received in a row before the callback is calles
+		* @param callback Pointer to a callback function, with signature void (*func)(NewRemoteCode)
+		*/
+		static void init(int8_t interrupt, byte minRepeats, NewRemoteReceiverCallBack callback);
+
+		/**
+		* Enable decoding. No need to call enable() after init().
+		*/
+		static void enable();
+
+		/**
+		* Disable decoding. You can re-enable decoding by calling enable();
+		*/
+		static void disable();
+
+		/**
+		* Deinitializes the decoder. Disables decoding and detaches the interrupt handler. If you want to
+		* re-enable decoding, call init() again.
+		*/
+		static void deinit();
+
+		/**
+		* Tells wether a signal is being received. If a compatible signal is detected within the time out, isReceiving returns true.
+		* Since it makes no sense to transmit while another transmitter is active, it's best to wait for isReceiving() to false.
+		* By default it waits for 150ms, in which a (relative slow) KaKu signal can be broadcasted three times.
+		*
+		* Note: isReceiving() depends on interrupts enabled. Thus, when disabled()'ed, or when interrupts are disabled (as is
+		* the case in the callback), isReceiving() will not work properly.
+		*
+		* @param waitMillis number of milliseconds to monitor for signal.
+		* @return boolean If after waitMillis no signal was being processed, returns false. If before expiration a signal was being processed, returns true.
+		*/
+		static boolean isReceiving(int waitMillis = 150);
+
+		/**
+		 * Called every time the signal level changes (high to low or vice versa). Usually called by interrupt.
+		 */
+		static void interruptHandler();
+
+	private:
+
+		static int8_t _interrupt;					// Radio input interrupt
+		volatile static short _state;				// State of decoding process.
+		static byte _minRepeats;
+		static NewRemoteReceiverCallBack _callback;
+		static boolean _inCallback;					// When true, the callback function is being executed; prevents re-entrance.
+		static boolean _enabled;					// If true, monitoring and decoding is enabled. If false, interruptHandler will return immediately.
+
+};
+
+#endif

+ 168 - 0
lib/NewRemoteSwitch/NewRemoteTransmitter.cpp

@@ -0,0 +1,168 @@
+/*
+ * NewRemoteSwitch library v1.2.0 (20140128) made by Randy Simons http://randysimons.nl/
+ * See NewRemoteTransmitter.h for details.
+ *
+ * License: GPLv3. See license.txt
+ */
+
+#include "NewRemoteTransmitter.h"
+#ifdef ESP8266
+    // interrupt handler and related code must be in RAM on ESP8266,
+    #define RECEIVE_ATTR ICACHE_RAM_ATTR
+#else
+    #define RECEIVE_ATTR
+#endif
+
+NewRemoteTransmitter::NewRemoteTransmitter(unsigned long address, byte pin, unsigned int periodusec, byte repeats) {
+	_address = address;
+	_pin = pin;
+	_periodusec = periodusec;
+	_repeats = (1 << repeats) - 1; // I.e. _repeats = 2^repeats - 1
+
+	pinMode(_pin, OUTPUT);
+}
+
+void NewRemoteTransmitter::sendGroup(boolean switchOn) {
+	for (int8_t i = _repeats; i >= 0; i--) {
+		_sendStartPulse();
+
+		_sendAddress();
+
+		// Do send group bit
+		_sendBit(true);
+
+		// Switch on | off
+		_sendBit(switchOn);
+
+		// No unit. Is this actually ignored?..
+		_sendUnit(0);
+
+		_sendStopPulse();
+	}
+}
+
+void NewRemoteTransmitter::sendUnit(byte unit, boolean switchOn) {
+	for (int8_t i = _repeats; i >= 0; i--) {
+		_sendStartPulse();
+
+		_sendAddress();
+
+		// No group bit
+		_sendBit(false);
+
+		// Switch on | off
+		_sendBit(switchOn);
+
+		_sendUnit(unit);
+
+		_sendStopPulse();
+	}
+}
+
+void NewRemoteTransmitter::sendDim(byte unit, byte dimLevel) {
+	for (int8_t i = _repeats; i >= 0; i--) {
+		_sendStartPulse();
+
+		_sendAddress();
+
+		// No group bit
+		_sendBit(false);
+
+		// Switch type 'dim'
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec);
+
+		_sendUnit(unit);
+
+		for (int8_t j=3; j>=0; j--) {
+		   _sendBit(dimLevel & 1<<j);
+		}
+
+		_sendStopPulse();
+	}
+}
+
+void NewRemoteTransmitter::sendGroupDim(byte dimLevel) {
+	for (int8_t i = _repeats; i >= 0; i--) {
+		_sendStartPulse();
+
+		_sendAddress();
+
+		// No group bit
+		_sendBit(true);
+
+		// Switch type 'dim'
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec);
+
+		_sendUnit(0);
+
+		for (int8_t j=3; j>=0; j--) {
+		   _sendBit(dimLevel & 1<<j);
+		}
+
+		_sendStopPulse();
+	}
+}
+
+void NewRemoteTransmitter::_sendStartPulse(){
+	digitalWrite(_pin, HIGH);
+	delayMicroseconds(_periodusec);
+	digitalWrite(_pin, LOW);
+	delayMicroseconds(_periodusec * 10 + (_periodusec >> 1)); // Actually 10.5T insteat of 10.44T. Close enough.
+}
+
+void NewRemoteTransmitter::_sendAddress() {
+	for (int8_t i=25; i>=0; i--) {
+	   _sendBit((_address >> i) & 1);
+	}
+}
+
+void NewRemoteTransmitter::_sendUnit(byte unit) {
+	for (int8_t i=3; i>=0; i--) {
+	   _sendBit(unit & 1<<i);
+	}
+}
+
+void NewRemoteTransmitter::_sendStopPulse() {
+	digitalWrite(_pin, HIGH);
+	delayMicroseconds(_periodusec);
+	digitalWrite(_pin, LOW);
+	delayMicroseconds(_periodusec * 40);
+}
+
+void NewRemoteTransmitter::_sendBit(boolean isBitOne) {
+	if (isBitOne) {
+		// Send '1'
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec * 5);
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec);
+	} else {
+		// Send '0'
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, HIGH);
+		delayMicroseconds(_periodusec);
+		digitalWrite(_pin, LOW);
+		delayMicroseconds(_periodusec * 5);
+	}
+}

+ 115 - 0
lib/NewRemoteSwitch/NewRemoteTransmitter.h

@@ -0,0 +1,115 @@
+/*
+ * NewRemoteSwitch library v1.2.0 (20140128) made by Randy Simons http://randysimons.nl/
+ *
+ * License: GPLv3. See license.txt
+ */
+
+#ifndef NewRemoteTransmitter_h
+#define NewRemoteTransmitter_h
+
+#include <Arduino.h>
+
+
+/**
+* NewRemoteTransmitter provides a generic class for simulation of common RF remote controls, like the A-series
+* 'Klik aan Klik uit'-system (http://www.klikaanklikuit.nl/), used to remotely switch lights etc.
+*
+* This class is meant for new-style remotes, usually accompanied by receivers with "code learning"
+* capabilities. For other remotes, use the RemoteTransmitter class.
+*
+* Hardware required for this library: a 433MHz/434MHz SAW oscillator transmitter, e.g.
+* http://www.sparkfun.com/products/10534
+* http://www.conrad.nl/goto/?product=130428
+*
+* Notes:
+* - I measured the period length with an oscilloscope, using a A-series KAKU transmitter. Other devices
+*   or manufacturers may use other period length. Use the ShowReceivedCodeNewRemote example to find the
+*   period length for your devices.
+* - You can copy the address of your "real" remotes, so you won't have to learn new codes into the receivers.
+*   In effect this duplicates a remote. But you can also pick a random number in the range 0..2^26-1.
+*/
+class NewRemoteTransmitter {
+	public:
+		/**
+		* Constructor.
+		*
+		* To obtain the correct period length, use the ShowReceivedCodeNewRemote example, or you
+		* can use an oscilloscope.
+		*
+		* @param address	Address of this transmitter [0..2^26-1] Duplicate the address of your hardware, or choose a random number.
+		* @param pin		Output pin on Arduino to which the transmitter is connected
+		* @param periodusec	Duration of one period, in microseconds. One bit takes 8 periods (but only 4 for 'dim' signal).
+		* @param repeats	[0..8] The 2log-Number of times the signal is repeated. The actual number of repeats will be 2^repeats. 2 would be bare minimum, 4 seems robust, 8 is maximum (and overkill).
+		*/
+		NewRemoteTransmitter(unsigned long address, byte pin, unsigned int periodusec = 260, byte repeats = 4);
+
+		/**
+		 * Send on/off command to the address group.
+		 *
+		 * @param switchOn  True to send "on" signal, false to send "off" signal.
+		 */
+		void sendGroup(boolean switchOn);
+
+		/**
+		 * Send on/off command to an unit on the current address.
+		 *
+		 * @param unit      [0..15] target unit.
+		 * @param switchOn  True to send "on" signal, false to send "off" signal.
+		 */
+		void sendUnit(byte unit, boolean switchOn);
+
+		/**
+		 * Send dim value to an unit on the current address. This will also switch on the device.
+		 * Note that low bound can be limited on the dimmer itself. Setting a dimLevel of 0
+		 * may not actually turn off the device.
+		 *
+		 * @param unit      [0..15] target unit.
+		 * @param dimLevel  [0..15] Dim level. 0 for off, 15 for brightest level.
+		 */
+		void sendDim(byte unit, byte dimLevel);
+		
+		/**
+		 * Send dim value the current address group. This will also switch on the device.
+		 * Note that low bound can be limited on the dimmer itself. Setting a dimLevel of 0
+		 * may not actually turn off the device.
+		 *
+		 * @param dimLevel  [0..15] Dim level. 0 for off, 15 for brightest level.
+		 */
+		void sendGroupDim(byte dimLevel);
+
+	protected:
+		unsigned long _address;		// Address of this transmitter.
+		byte _pin;					// Transmitter output pin
+		unsigned int _periodusec;	// Oscillator period in microseconds
+		byte _repeats;				// Number over repetitions of one telegram
+
+		/**
+		 * Transmits start-pulse
+		 */
+		void _sendStartPulse();
+
+		/**
+		 * Transmits address part
+		 */
+		void _sendAddress();
+
+		/**
+		 * Transmits unit part.
+		 *
+		 * @param unit      [0-15] target unit.
+		 */
+		void _sendUnit(byte unit);
+
+		/**
+		 * Transmits stop pulse.
+		 */
+		void _sendStopPulse();
+
+		/**
+		 * Transmits a single bit.
+		 *
+		 * @param isBitOne	True, to send '1', false to send '0'.
+		 */
+		void _sendBit(boolean isBitOne);
+};
+#endif

+ 55 - 0
lib/NewRemoteSwitch/README.md

@@ -0,0 +1,55 @@
+NewRemoteSwitch library v1.2.0 (20140128) for Arduino 1.0
+Made by Randy Simons http://randysimons.nl/
+
+This library provides an easy class for Arduino, to send and receive signals
+used by some common "new style" 433MHz remote control switches.
+
+There are two styles of remote:
+ - "old style", which uses switches or a dial to set the house code. Use the
+	RemoteSwitch library instead.
+ - "new style", which use a button on the receivers to "learn" a signal. Use
+   this library.
+
+License: GPLv3. See ./NewRemoteSwitch/license.txt
+
+Latest source and wiki: https://bitbucket.org/fuzzillogic/433mhzforarduino
+
+
+Installation of library:
+ - Make sure Arduino is closed
+ - Copy the directory NewRemoteSwitch to the Arduino library directory (usually
+   <Sketchbook directory>/libraries/)
+   See http://arduino.cc/en/Guide/Libraries for detailed instructions.
+ 
+Default installation demo:
+ - Connect the data-out-pin of a 433MHz receiver to digital pin 2. See photo.
+  (Note: your hardware may have a different pin configuration!)
+ - Start Arduino, and open the example: File -> Examples -> NewRemoteSwitch ->
+   ShowReceivedCode or ShowReceivedCodeNewRemote.
+ - Compile, upload and run
+ - Open serial monitor in Arduino (115200 baud)
+ - Press buttons on a 433MHz-remote, and watch the serial monitor
+ 
+
+Changelog:
+NewRemoteSwitch library v1.2.0 (20140128) for Arduino 1.0
+ - Revisited receiving dim-levels. Now it is always optional, check
+   dimLevelPresent to see if it was transmitted.
+   This change might break your code, as SwitchType::on_with_dim is removed.
+ - Added NewRemoteTransmitter::sendGroupDim.
+ - Added Dimmer example. Thanks to a Bitcoin donation, I could actually test it!
+
+NewRemoteSwitch library v1.1.0 (20130601) for Arduino 1.0
+ - BUGFIX: in many occasions, when receiving a dim-level, the code was rejected
+   even if the signal was correct.
+ - Support decoding A-series transmitters which transmit a dim-level in
+   combination with an on-signal, instead of a dim-signal.
+ - Uses NewRemodeCode::on, ::off, ::dim, ::on_with_dim instead of 0, 1, 2 and 3,
+   for better readability. This change is backwards compatible.
+ - Updated examples to use the new NewRemodeCode::on, ::off, ::dim and
+   ::on_with_dim notation.
+ - Reduced memory usage (Flash, RAM)
+
+NewRemoteSwitch library v1.0.0 (20121229) for Arduino 1.0
+ - Support for receiving A-series Klik-aan-klik-uit remote. (NewRemoteReceiver)
+ - With examples to test and demonstrate.

BIN
lib/NewRemoteSwitch/docs/hardware setup.jpg


+ 23 - 0
lib/NewRemoteSwitch/docs/new kaku protocol.txt

@@ -0,0 +1,23 @@
+= Protocol of klikaanklikuit A-series devices =
+
+Copied from Wieltje, http://www.circuitsonline.net/forum/view/message/1181410#1181410,
+but with slightly different timings, as measured on my device.
+        _   _
+'0':   | |_| |_____ (T,T,T,5T)
+        _       _
+'1':   | |_____| |_ (T,5T,T,T)
+        _   _
+'dim': | |_| |_     (T,T,T,T)
+
+T = short period of ~260µs. Use the ShowReceivedCodeNewRemote example to find the
+actual period length for your devices.
+
+A full frame looks like this:
+
+- start pulse: 1T high, 10.44T low
+- 26 bit:  Address
+- 1  bit:  group bit
+- 1  bit:  on/off/[dim]
+- 4  bit:  unit
+- [4 bit:  dim level. Only present of [dim] is chosen]
+- stop pulse: 1T high, 40T low

+ 64 - 0
lib/NewRemoteSwitch/examples/LearnCode/LearnCode.ino

@@ -0,0 +1,64 @@
+/*
+ * Demo for RF remote switch receiver. 
+ * This example is for the new KaKu / Home Easy type of remotes!
+ *
+ * For details, see NewRemoteReceiver.h!
+ *
+ * With this sketch you can control a LED connected to digital pin 13,
+ * after the sketch learned the code. After start, the LED starts to blink,
+ * until a valid code has been received. The led stops blinking. Now you
+ * can control the LED with the remote.
+ *
+ * Note: only unit-switches are supported in this sketch, no group or dim.
+ *
+ * Set-up: connect the receiver to digital pin 2 and a LED to digital pin 13.
+ */
+
+#include <NewRemoteReceiver.h>
+
+boolean codeLearned = false;
+unsigned long learnedAddress;
+byte learnedUnit;
+
+void setup() {
+  // LED-pin as output
+  pinMode(13, OUTPUT);
+
+  // Init a new receiver on interrupt pin 0, minimal 2 identical repeats, and callback set to processCode.
+  NewRemoteReceiver::init(0, 2, processCode);
+}
+
+void loop() {
+  // Blink led until a code has been learned
+  if (!codeLearned) {
+    digitalWrite(13, HIGH);
+    delay(500);
+    digitalWrite(13, LOW);
+    delay(500);
+  }
+}
+
+// Callback function is called only when a valid code is received.
+void processCode(NewRemoteCode receivedCode) {
+  // A code has been received.
+  // Do we already know the code?
+  if (!codeLearned) {
+    // No! Let's learn the received code.
+    learnedAddress = receivedCode.address;
+    learnedUnit = receivedCode.unit;
+    codeLearned = true;    
+  } else {
+    // Yes!    
+    // Is the received code identical to the learned code?
+    if (receivedCode.address == learnedAddress && receivedCode.unit == learnedUnit) {
+      // Yes!
+      // Switch the LED off if the received code was "off".
+      // Anything else (on, dim, on_with_dim) will switch the LED on.
+      if (receivedCode.switchType == NewRemoteCode::off) {
+        digitalWrite(13, LOW);
+      } else {
+        digitalWrite(13, HIGH);
+      }
+    }
+  }
+}

+ 55 - 0
lib/NewRemoteSwitch/examples/LightShow/LightShow.ino

@@ -0,0 +1,55 @@
+/**
+ * Demo for RF remote switch receiver.
+ * For details, see NewRemoteReceiver.h!
+ *
+ * Connect the transmitter to digital pin 11.
+ *
+ * This sketch demonstrates the use of the NewRemoteTransmitter class.
+ *
+ * When run, this sketch switches some pre-defined devices on and off in a loop.
+ *
+ * NOTE: the actual receivers have the address and group numbers in this example
+ * are only for demonstration! If you want to duplicate an existing remote, please
+ * try the "retransmitter"-example instead.
+ * 
+ * To use this actual example, you'd need to "learn" the used code in the receivers
+ * This sketch is unsuited for that.
+ * 
+ */
+
+#include <NewRemoteTransmitter.h>
+
+// Create a transmitter on address 123, using digital pin 11 to transmit, 
+// with a period duration of 260ms (default), repeating the transmitted
+// code 2^3=8 times.
+NewRemoteTransmitter transmitter(123, 11, 260, 3);
+
+void setup() {
+}
+
+void loop() {  
+  // Switch unit 2 off
+  transmitter.sendUnit(2, false);
+
+  // Switch all devices in the group off
+  transmitter.sendGroup(false);
+
+  // Set unit 1 to dim-level 3 (range 0-15)
+  transmitter.sendDim(1, 3);  
+
+  // Wait 5 seconds
+  delay(5000);
+  
+
+  // Switch unit 2 on
+  transmitter.sendUnit(2, true);
+
+  // Switch all devices in the group on
+  transmitter.sendGroup(true);
+
+  // Set unit 1 to dim-level 15, full brightness.
+  transmitter.sendDim(1, 15);
+
+  // Wait 5 seconds
+  delay(5000);
+}

+ 63 - 0
lib/NewRemoteSwitch/examples/Retransmitter/Retransmitter.ino

@@ -0,0 +1,63 @@
+/*
+ * Demo for RF remote switch receiver.
+ * For details, see NewRemoteReceiver.h!
+ *
+ * Connect the transmitter to digital pin 11, and the receiver to digital pin 2.
+ *
+ * When run, this sketch waits for a valid code from a new-style the receiver,
+ * decodes it, and retransmits it after 5 seconds.
+ */
+
+#include <NewRemoteReceiver.h>
+#include <NewRemoteTransmitter.h>
+
+void setup() {
+  // See example ShowReceivedCode for info on this
+  NewRemoteReceiver::init(0, 2, retransmitter);
+}
+
+void loop() {
+}
+
+void retransmitter(NewRemoteCode receivedCode) {
+  // Disable the receiver; otherwise it might pick up the retransmit as well.
+  NewRemoteReceiver::disable();
+
+  // Need interrupts for delay()
+  interrupts();
+
+  // Wait 5 seconds before sending.
+  delay(5000);
+
+  // Create a new transmitter with the received address and period, use digital pin 11 as output pin
+
+  NewRemoteTransmitter transmitter(receivedCode.address, 11, receivedCode.period);
+
+  if (receivedCode.switchType == NewRemoteCode::dim || 
+    (receivedCode.switchType == NewRemoteCode::on && receivedCode.dimLevelPresent)) {
+    // Dimmer signal received
+
+    if (receivedCode.groupBit) {
+      transmitter.sendGroupDim(receivedCode.dimLevel);
+    } 
+    else {
+      transmitter.sendDim(receivedCode.unit, receivedCode.dimLevel);
+    }
+  } 
+  else {
+    // On/Off signal received
+    bool isOn = receivedCode.switchType == NewRemoteCode::on;
+
+    if (receivedCode.groupBit) {
+      // Send to the group
+      transmitter.sendGroup(isOn);
+    } 
+    else {
+      // Send to a single unit
+      transmitter.sendUnit(receivedCode.unit, isOn);
+    }
+  }
+
+  NewRemoteReceiver::enable();
+}
+

+ 55 - 0
lib/NewRemoteSwitch/examples/ShowReceivedCode/ShowReceivedCode.ino

@@ -0,0 +1,55 @@
+/*
+* Demo for RF remote switch receiver.
+* For details, see RemoteReceiver.h!
+*
+* This sketch shows the received signals on the serial port.
+* Connect the receiver to digital pin 2 on arduino and digital pin 1 on ESP8266.
+* Detected codes example:
+ Code: 8233372 Period: 273
+ unit: 1
+ groupBit: 0
+ switchType: 0
+*/
+
+#include <NewRemoteReceiver.h>
+
+void setup() {
+  Serial.begin(115200);
+
+  // Initialize receiver on interrupt 0 (= digital pin 2) for arduino uno, calls the callback "showCode"
+  // after 1 identical codes have been received in a row. (thus, keep the button pressed
+  // for a moment), on esp8266 use on interrupt 5 = digital pin 1
+  //
+  // See the interrupt-parameter of attachInterrupt for possible values (and pins)
+  // to connect the receiver.
+
+  // if you don't see codes try to reset your board after upload
+  
+    #ifdef ESP8266
+      NewRemoteReceiver::init(5, 2, showCode);
+    #else
+      NewRemoteReceiver::init(0, 2, showCode);
+    #endif
+    Serial.println("Receiver initialized");    
+}
+
+void loop() {
+
+}
+
+// Callback function is called only when a valid code is received.
+void showCode(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType) {
+
+  // Print the received code.
+  Serial.print("Code: ");
+  Serial.print(address);
+  Serial.print(" Period: ");
+  Serial.println(period);
+  Serial.print(" unit: ");
+  Serial.println(unit);
+  Serial.print(" groupBit: ");
+  Serial.println(groupBit);
+  Serial.print(" switchType: ");
+  Serial.println(switchType);
+
+}

+ 12 - 0
lib/NewRemoteSwitch/keywords.txt

@@ -0,0 +1,12 @@
+NewRemoteReceiver	KEYWORD1
+NewRemoteCode	KEYWORD1
+isReceiving	KEYWORD2
+init	KEYWORD2
+enable	KEYWORD2
+disable	KEYWORD2
+deinit	KEYWORD2
+NewRemoteTransmitter	KEYWORD1
+sendGroup	KEYWORD2
+sendUnit	KEYWORD2
+sendDim	KEYWORD2
+sendGroupDim	KEYWORD2

+ 674 - 0
lib/NewRemoteSwitch/license.txt

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.

+ 47 - 0
src/decoder.cpp

@@ -0,0 +1,47 @@
+// *****************************************************************************************
+// ************************************************************
+// **************************************
+// *
+// * Header Files
+// * 
+// *
+#include <Arduino.h>
+
+static unsigned long oldSensor; 
+
+// *****************************************************************************************
+// ************************************************************
+// **************************************
+// *
+// * Functions Declaration and Implementation
+// * 
+// *
+
+// *
+// * Decode incomming messages
+// * 
+void decoder (unsigned long sensor, unsigned int protocol) {
+
+    switch(sensor) {
+
+       case 0x46BB06: Serial.print("PIR Sensor activated\n"); break;
+       
+       case 0x0551: Serial.print("Button A - on pressed\n"); break;
+       case 0x1151: Serial.print("Button B - on pressed\n"); break;
+       case 0x1451: Serial.print("Button C - on pressed\n"); break;
+       case 0x1511: Serial.print("Button D - on pressed\n"); break;
+       
+       case 0x0554: Serial.print("Button A - off pressed\n"); break;
+       case 0x1154: Serial.print("Button B - off pressed\n"); break;
+       case 0x1454: Serial.print("Button C - off pressed\n"); break;
+       case 0x1514: Serial.print("Button D - off pressed\n"); break;
+
+       case 0x155F: Serial.print("Button released ?\n"); break;
+       
+       default:     Serial.print("default case - ");    
+                    Serial.print("Received 0x");
+                    Serial.println(sensor,HEX);
+                    break;                           
+    }
+  return;
+}

+ 6 - 4
src/main.cpp

@@ -6,20 +6,18 @@
 // * 
 // * 
 // *
 // *
 
 
-#define NewRemoteRcv   0
+#define NewRemoteRcv   1
 #if NewRemoteRcv
 #if NewRemoteRcv
   #include <NewRemoteReceiver.h>
   #include <NewRemoteReceiver.h>
 #else
 #else
   #include <RCSwitch.h>
   #include <RCSwitch.h>
 #endif
 #endif
 
 
+#include <Arduino.h>
 #include <Thread.h>
 #include <Thread.h>
 #include <Wire.h>
 #include <Wire.h>
 #include <LiquidCrystal_I2C.h>
 #include <LiquidCrystal_I2C.h>
 
 
-LiquidCrystal_I2C lcd(0x27, 16, 2); // display type 16x2
-
-
 #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
 #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
 #include <avr/power.h>
 #include <avr/power.h>
 #include <avr/wdt.h>
 #include <avr/wdt.h>
@@ -67,6 +65,8 @@ int freeRam () {
 // * 
 // * 
 // *
 // *
 
 
+LiquidCrystal_I2C lcd(0x27, 16, 2); // display type 16x2
+
 bool BoardRunning = false;
 bool BoardRunning = false;
 
 
 Thread myThreadLed = Thread();
 Thread myThreadLed = Thread();
@@ -98,6 +98,8 @@ unsigned long switchReceivedValue = 0;
 // * 
 // * 
 // *
 // *
 
 
+void showCode(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType);
+
 // *
 // *
 // * Thread - Toggle LED
 // * Thread - Toggle LED
 // * 
 // * 

+ 83 - 0
src/output.cpp

@@ -0,0 +1,83 @@
+// *****************************************************************************************
+// ************************************************************
+// **************************************
+// *
+// * Header Files
+// * 
+// *
+#include <Arduino.h>
+
+// *****************************************************************************************
+// ************************************************************
+// **************************************
+// *
+// * Functions Declaration and Implementation
+// * 
+// *
+
+
+static const char* bin2tristate(const char* bin);
+static char * dec2binWzerofill(unsigned long Dec, unsigned int bitLength);
+
+void output(unsigned long decimal, unsigned int length, unsigned int delay, unsigned int* raw, unsigned int protocol) {
+
+  const char* b = dec2binWzerofill(decimal, length);
+  Serial.print("Decimal: ");
+  Serial.print(decimal);
+  Serial.print(" (");
+  Serial.print( length );
+  Serial.print("Bit) Binary: ");
+  Serial.print( b );
+  Serial.print("\nTri-State: ");
+  Serial.print( bin2tristate( b) );
+  Serial.print("\nPulseLength: ");
+  Serial.print(delay);
+  Serial.print(" microseconds");
+  Serial.print(" Protocol: ");
+  Serial.println(protocol);  
+
+  Serial.println();
+  Serial.println();
+}
+
+static const char* bin2tristate(const char* bin) {
+  static char returnValue[50];
+  int pos = 0;
+  int pos2 = 0;
+  while (bin[pos]!='\0' && bin[pos+1]!='\0') {
+    if (bin[pos]=='0' && bin[pos+1]=='0') {
+      returnValue[pos2] = '0';
+    } else if (bin[pos]=='1' && bin[pos+1]=='1') {
+      returnValue[pos2] = '1';
+    } else if (bin[pos]=='0' && bin[pos+1]=='1') {
+      returnValue[pos2] = 'F';
+    } else {
+      return "not applicable";
+    }
+    pos = pos+2;
+    pos2++;
+  }
+  returnValue[pos2] = '\0';
+  return returnValue;
+}
+
+static char * dec2binWzerofill(unsigned long Dec, unsigned int bitLength) {
+  static char bin[64]; 
+  unsigned int i=0;
+
+  while (Dec > 0) {
+    bin[32+i++] = ((Dec & 1) > 0) ? '1' : '0';
+    Dec = Dec >> 1;
+  }
+
+  for (unsigned int j = 0; j< bitLength; j++) {
+    if (j >= bitLength - i) {
+      bin[j] = bin[ 31 + i - (j - (bitLength - i)) ];
+    } else {
+      bin[j] = '0';
+    }
+  }
+  bin[bitLength] = '\0';
+  
+  return bin;
+}