Dimma med Nexa och en Arduino, *nya bekymmer*

PIC, AVR, Arduino, Raspberry Pi, Basic Stamp, PLC mm.
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Dimma med Nexa och en Arduino, *nya bekymmer*

Inlägg av Jonaz »

Försöker dimma en led tejpen med en Nexa fjärrkontroll som skickar antingen 1 eller 0 till en arduino.
Att få led tejpen på eller av är inga problem, men jag vill att när man trycker på "on" på sändaren så skall led tejpen fedas upp och ner tills jag trycker "on" i gen från Nexa sändaren. Kodningen funkar var för sig, men hur skall jag få ihop det i slut programmet, det som händer nu är att varje gång jag trycker "on" så fedas den upp ett steg.
Har kämpat med detta nu någon vecka och får inte till, började bli väldigt snurrigt med all kod så jag började om helt, och nu så jag skulle behöva lite hjälp.

Denna fedar upp och ner tills jag trycker på knappen.

Kod: Markera allt

// this constant won't change:
const int  buttonPin = 8;    // the pin that the pushbutton is attached to
const int ledPin = 9;       // the pin that the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
 
}

void fade(){
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter++;
      
    } else {
      // if the current state is LOW then the button
      // wend from on to off:
      
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;


  // turns on the LED every four button pushes by
  // checking the modulo of the button push counter.
  // the modulo function gives you the remainder of
  // the division of two numbers:
  if (buttonPushCounter % 2 == 0) {
    analogWrite(ledPin, brightness);    
     delay(40);
  // will change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }     
  } else {
    analogWrite(ledPin, brightness);
  }

}
void loop() {
  fade();
}

Här är koden med själva Nexan också utan fadekoden inlagd.

Kod: Markera allt

/*
 * 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;
unsigned short 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!      
      // switchType == 1 means on, switchType == 0 means off.
      if (receivedCode.switchType == 1) {
        digitalWrite(13, HIGH);                           //<<<<< Här är det TILL
      } else if (receivedCode.switchType == 0) {
        digitalWrite(13, LOW);                          //<<<<< Här är det FRÅN
      }
    }
  }
}

Någon som kan komma på några idéer hur jag skall få ihop dessa?
Senast redigerad av Jonaz 25 februari 2017, 10:40:01, redigerad totalt 2 gånger.
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Ingen? :humm:
Användarvisningsbild
Magnus_K
EF Sponsor
Inlägg: 5854
Blev medlem: 4 januari 2010, 17:53:25
Ort: Skogen mellan Uppsala-Gävle

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Magnus_K »

Nu ska vi se om jag hänger med. Aldrig meckat med NEXA-grejer men det verkar roligt.

Du har alltså en LED-tejp som drivs av en Arduino med NEXA-mottagare. När du laddar den "nedre" koden så tänds/släcks LED 13 på Arduinon precis som den ska när du slår på/av NEXA-fjärren?
När du sedan laddar den övre koden så fade:as tejpen upp och ner så länge du håller inne knappen på Arduinon, precis som det ska?

Du vill nu alltså få igång fade:ningen av tejpen genom ett ON från NEXA-fjärrisen, och sedan släcka den med ett OFF?

Om jag tolkat ovan rätt så tycker jag ju att det ska gå att få till.
Skulle det inte fungera, att till en början:

Ändra nedre koden så istället för att sätta 13 hög/låg nedan så skapar du en variabel i stil med receivedCmd = 1; resp receivedCmd = 0;

Kod: Markera allt

if (receivedCode.switchType == 1) {
        receivedCmd = 1;                           //<<<<< Här är det TILL
      } else if (receivedCode.switchType == 0) {
        receivedCmd = 0;                          //<<<<< Här är det FRÅN
I övre koden ger du då buttonState värdet på den variabeln, typ buttonState = receivedCmd

Kod: Markera allt

void fade(){
  buttonState = receivedCmd;
För att få det att rulla så lägger du in din fade-funktion i det nedre programmet och anropar funktionen efter varje koll av receivedCmd.
Skulle det lira så kan du ju gå vidare och ge buttonState = receivedCode.switchType direkt osv. men lättast är nog att ta en sak i tagen, som du redan gjort.

Ps. Jag suger ganska hårt på det här men förhoppningsvis kanske det ger dig något Ds.
Användarvisningsbild
Magnus_K
EF Sponsor
Inlägg: 5854
Blev medlem: 4 januari 2010, 17:53:25
Ort: Skogen mellan Uppsala-Gävle

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Magnus_K »

Om inte annat så lägg upp koden här som får LED-tejpen att stega ett steg i taget med fjärrisen, alltså ditt egna försök som inte fungerar riktigt.
Det kanske är lättare att utgå ifrån.
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Den verkar fastna i sig själv på något vis.
Har fått till det att den dimmarar upp och ner, men när när man klickar på on igen så skall den stanna i dimmningen, men där händer inget, den fortsätter bara, den går inte heller att släcka, då däremot stannar dimmningen.

Verkar fastna när man skickar on, och nästa on gör ingen skillnad.. Koden kommer straxt.
Användarvisningsbild
Magnus_K
EF Sponsor
Inlägg: 5854
Blev medlem: 4 januari 2010, 17:53:25
Ort: Skogen mellan Uppsala-Gävle

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Magnus_K »

Snyggt, då är det säkert bara att den fastnar i någon loop eller så. Det här ska säkert gå att få ordning på!
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Man har prövat så många olika kombinationer så man är helt snurrig...
Känns som signalerna från nexan inte kommer fram i programmet, kan det vara för att fade(); ligger i loop?

Programmet i sin helhet.

Kod: Markera allt

#include <NewRemoteReceiver.h>

const int ledPin = 9;       // the pin that the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 1;     // previous state of the button
boolean codeLearned = false;
unsigned long learnedAddress;
unsigned short learnedUnit;
int receivedCmd = 0;
//int buttonState = receivedCmd;

void setup() {
  // LED-pin as output
  pinMode(9, 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() {Serial.begin(9600);
  // Blink led until a code has been learned
  if (!codeLearned) {
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(500);
    
  }////fade();
  
  {
fade();

  }
}

// 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!     
      // switchType == 1 means on, switchType == 0 means off.
      if (receivedCode.switchType == 1) {
        digitalWrite(13, HIGH);
        receivedCmd = 1;
        
        //analogWrite(ledPin, brightness);//<<<<< Här är det TILL
      } else if (receivedCode.switchType == 0) {
        digitalWrite(13, LOW); 
        digitalWrite(9, LOW);   //<<<<< Här är det FRÅN
        receivedCmd = 0; 
      }
    }
  }
}

void fade(){

buttonState = receivedCmd;
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
  if (receivedCmd == HIGH)
    {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter++;
     
    } else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off");
      
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;


  // turns on the LED every four button pushes by
  // checking the modulo of the button push counter.
  // the modulo function gives you the remainder of
  // the division of two numbers:
  if (buttonPushCounter % 2 == 0) {
    analogWrite(ledPin, brightness);    
     delay(40);
  // will change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }    
  } else {
    analogWrite(ledPin, brightness); //Här tänds gamla värdet från av 
  }
}
Det känns som man är nära lösningen hela tiden.
Användarvisningsbild
Magnus_K
EF Sponsor
Inlägg: 5854
Blev medlem: 4 januari 2010, 17:53:25
Ort: Skogen mellan Uppsala-Gävle

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Magnus_K »

Du är nog väldigt nära också. Ska mecka lite i mitt IDE. Har så svårt att läsa när indenteringen (?) är lite tokig.
Återkommer inom kort!
Användarvisningsbild
Magnus_K
EF Sponsor
Inlägg: 5854
Blev medlem: 4 januari 2010, 17:53:25
Ort: Skogen mellan Uppsala-Gävle

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Magnus_K »

Måste läsa lite om den NewRemoteReceiver::init(0, 2, processCode);.
Som det ser ut nu så tycker jag det ser ut som att den bara kör en "upplärningskod" en gång (i setup()), och sen inget mer. Känns som att det måste finnas något i main_loopen så den hela tiden lyssnar på inkommande signal.
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Det stämmer att den gör det,tills den har fått kontakt med sändaren, sedan fortsätter programmet under void processCode(NewRemoteCode receivedCode)
kan lägga upp h filen.
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Kod: Markera allt

/*
 * NewRemoteSwitch library v1.0.0 (20121229) made by Randy Simons http://randysimons.nl/
 *
 * License: GPLv3. See license.txt
 */

#ifndef NewRemoteReceiver_h
#define NewRemoteReceiver_h

#include <Arduino.h>

struct NewRemoteCode {
	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
	unsigned short switchType;	// 0: swich off; 1: switch on; 2: set dim level
	unsigned short unit;		// Unit code of received code [0..15]
	unsigned short dimLevel;	// Dim level [0..15] iff switchType == 2
};

typedef void (*NewRemoteReceiverCallBack)(NewRemoteCode);

/**
* See RemoteSwitch for introduction.
*
* NewRemoteReceiver decodes the signal received from a 433MHz-receiver, like the "KlikAanKlikUit"-system
* as well as the signal sent by the RemoteSwtich class. When a correct signal is received,
* a user-defined callback function is called.
*
* Note that in the callback function, the interrupts are still disabled. You can enabled them, if needed.
* A call to the callback must be finished before NewRemoteReceiver will call the callback function again, thus
* there is no re-entrant problem.
*
* When sending your own code using NewRemoteSwich, disable() the receiver first.
*
* This is a pure static class, for simplicity and to limit memory-use.
*/

class NewRemoteReceiver {
	public:
		/**
		* Initializes the decoder.
		*
		* If interrupt >= 0, init will register pin <interrupt> to this library.
		* If interrupt < 0, no interrupt is registered. In that case, you have to call interruptHandler()
		* yourself whenever the output of the receiver changes, or you can use InterruptChain.
		*
		* @param interrupt 	The interrupt as is used by Arduino's attachInterrupt function. See attachInterrupt for details.
							If < 0, you must call interruptHandler() yourself.
		* @param minRepeats The number of times the same code must be received in a row before the callback is calles
		* @param callback Pointer to a callback function, with signature void (*func)(NewRemoteCode)
		*/
		static void init(short interrupt, unsigned short 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 unsigned short _interrupt;			// Radio input interrupt
		volatile static unsigned short _state;		// State of decoding process. There are 49 states, 1 for "waiting for signal" and 48 for decoding the 48 edges in a valid code.
		static unsigned short _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
CPP Filen

Kod: Markera allt

/*
 * NewRemoteSwitch library v1.0.0 (20121229) made by Randy Simons http://randysimons.nl/
 * See NewRemoteReceiver.h for details.
 *
 * License: GPLv3. See license.txt
 */

#include "NewRemoteReceiver.h"


/************
* NewRemoteReceiver

Protocol. (Copied from Wieltje, http://www.circuitsonline.net/forum/view/message/1181410#1181410,
but with slightly different timings, as measured on my device.)
		_   _
'0':   | |_| |_____ (T,T,T,5T)
		_       _
'1':   | |_____| |_	(T,5T,T,T)
		_   _
dim:   | |_| |_     (T,T,T,T)

T = short period of ~260µs. However, this code tries
to figure out the correct period

A full frame looks like this:

- start pulse: 1T high, 10.44T low
- 26 bit:  Address
- 1  bit:  group bit
- 1  bit:  on/off/[dim]
- 4  bit:  unit
- [4 bit:  dim level. Only present of [dim] is chosen]
- stop pulse: 1T high, 40T low

************/

unsigned short NewRemoteReceiver::_interrupt;
volatile unsigned short NewRemoteReceiver::_state;
unsigned short NewRemoteReceiver::_minRepeats;
NewRemoteReceiverCallBack NewRemoteReceiver::_callback;
boolean NewRemoteReceiver::_inCallback = false;
boolean NewRemoteReceiver::_enabled = false;

void NewRemoteReceiver::init(short interrupt, unsigned short minRepeats, NewRemoteReceiverCallBack callback) {
	_interrupt = interrupt;
	_minRepeats = minRepeats;
	_callback = callback;

	enable();
	if (_interrupt >= 0) {
		attachInterrupt(_interrupt, interruptHandler, CHANGE);
	}
}

void NewRemoteReceiver::enable() {
	_state = -1;
	_enabled = true;
}

void NewRemoteReceiver::disable() {
	_enabled = false;
}

void NewRemoteReceiver::deinit() {
	_enabled = false;
	if (_interrupt >= 0) {
		detachInterrupt(_interrupt);
	}
}

void NewRemoteReceiver::interruptHandler() {
	if (!_enabled) {
		return;
	}

	static unsigned short receivedBit;		// Contains "bit" currently receiving
	static NewRemoteCode receivedCode;		// Contains received code
	static NewRemoteCode previousCode;		// Contains previous received code
	static unsigned short 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 260us, but for maximum compatiblity go as low as 120us
		if (duration > 4800) { // =40*120us, minimal time between two edges before decoding starts.
			// Sync signal received.. Preparing for decoding
			repeats = 0;

			receivedCode.period = duration / 40; // Measured signal is 40T, so 1T (period) is measured signal / 40.

			// Allow for large error-margin. ElCheapo-hardware :(
			min1Period = receivedCode.period * 3 / 10; // Lower limit for 1 period is 0.3 times measured period; high signals can "linger" a bit sometimes, making low signals quite short.
			max1Period = receivedCode.period * 3; // Upper limit for 1 period is 3 times measured period
			min5Period = receivedCode.period * 3; // Lower limit for 5 periods is 3 times measured period
			max5Period = receivedCode.period * 8; // Upper limit for 5 periods is 8 times measured period
		}
		else {
			return;
		}
	} else if (_state == 0) { // Verify start bit part 1 of 2
		// Duration must be ~1T
		if (duration > max1Period) {
			_state = -1;
			return;
		}
		// Start-bit passed. Do some clean-up.
		receivedCode.address = receivedCode.unit = receivedCode.dimLevel = 0;
	} else if (_state == 1) { // Verify start bit part 2 of 2
		// Duration must be ~10.44T
		if (duration < 7 * receivedCode.period || duration > 15 * receivedCode.period) {
			_state = -1;
			return;
		}
	} else if (_state < 146) { // state 146 is first edge of stop-sequence. All bits before that adhere to default protocol, with exception of dim-bit
		receivedBit <<= 1;

		// One bit consists out of 4 bit parts.
		// bit part durations can ONLY be 1 or 5 periods.
		if (duration <= max1Period) {
			receivedBit &= B1110; // Clear LSB of receivedBit
		}
		else if (duration >= min5Period && duration <= max5Period) {
			receivedBit |= B1; // Set LSB of receivedBit
		}
		else { // Otherwise the entire sequence is invalid
			_state = -1;
			return;
		}

		if (_state % 4 == 1) { // Last bit part? Note: this is the short version of "if ( (_state-2) % 4 == 3 )"
			// There are 3 valid options for receivedBit:
			// 0, indicated by short short short long == B0001.
			// 1, short long shot short == B0100.
			// dim, short shot short shot == B0000.
			// Everything else: inconsistent data, trash the whole sequence.


			if (_state < 106) {
				// States 2 - 105 are address bit states

				receivedCode.address <<= 1;

				// Decode bit. Only 4 LSB's of receivedBit are used; trim the rest.
				switch (receivedBit & B1111) {
					case B0001: // Bit "0" received.
						// receivedCode.address |= 0; But let's not do that, as it is wasteful.
						break;
					case B0100: // Bit "1" received.
						receivedCode.address |= 1;
						break;
					default: // Bit was invalid. Abort.
						_state = -1;
						return;
				}
			} else if (_state < 110) {
				// States 106 - 109 are group bit states.
				switch (receivedBit & B1111) {
					case B0001: // Bit "0" received.
						receivedCode.groupBit = false;
						break;
					case B0100: // Bit "1" received.
						receivedCode.groupBit = true;
						break;
					default: // Bit was invalid. Abort.
						_state = -1;
						return;
				}
			} else if (_state < 114) {
				// States 110 - 113 are switch bit states.
				switch (receivedBit & B1111) {
					case B0001: // Bit "0" received.
						receivedCode.switchType = 0;
						break;
					case B0100: // Bit "1" received.
						receivedCode.switchType = 1;
						break;
					case B0000: // Bit "dim" receivd.
						receivedCode.switchType = 2;
						break;
					default: // Bit was invalid. Abort.
						_state = -1;
						return;
				}
			} else if (_state < 130){
				// States 114 - 129 are unit bit states.
				receivedCode.unit <<= 1;

				// Decode bit.
				switch (receivedBit & B1111) {
					case B0001: // Bit "0" received.
						// receivedCode.unit |= 0; But let's not do that, as it is wasteful.
						break;
					case B0100: // Bit "1" received.
						receivedCode.unit |= 1;
						break;
					default: // Bit was invalid. Abort.
						_state = -1;
						return;
				}

				// Only if there is a dim-action chosen the dim-bits are present in the signal.
				// Thus, if switchType is on or off, skip these dim-bits.
				if (_state == 129 && receivedCode.switchType != 2) {
					_state = 145; // 4 bits x 4 states = 16 states to skip.
				}
			} else if (_state < 146){
				// States 130 - 145 are dim bit states. Note that these are skipped unless switchType == 2.
				receivedCode.dimLevel <<= 1;

				// Decode bit.
				switch (receivedBit) {
					case B0001: // Bit "0" received.
						// receivedCode.dimLevel |= 0; But let's not do that, as it is wasteful.
						break;
					case B0100: // Bit "1" receivd.
						receivedCode.dimLevel |= 1;
						break;
					default: // Bit was invalid. Abort.
						_state = -1;
						return;
				}
			}
		}
	} else if (_state == 146) { // Verify stop bit part 1 of 2
		// Duration must be ~1T
		if (duration < min1Period || duration > max1Period) {
			_state = -1;
			return;
		}
	} else if (_state == 147) { // Verify stop bit part 2 of 2
		// Duration must be ~40T
		if (duration < 20 * receivedCode.period || duration > 80 * receivedCode.period) {
			_state = -1;
			return;
		}

		// receivedCode is a valid code!

		if (
				receivedCode.address != previousCode.address ||
				receivedCode.unit != previousCode.unit ||
				receivedCode.dimLevel != previousCode.dimLevel ||
				receivedCode.groupBit != previousCode.groupBit ||
				receivedCode.switchType != previousCode.switchType
			) { // memcmp isn't deemed safe
			repeats=0;
			previousCode = receivedCode;
		}

		repeats++;

		if (repeats>=_minRepeats) {
			if (!_inCallback) {
				_inCallback = true;
				(_callback)(receivedCode);
				_inCallback = false;
			}
			// Reset after callback.
			_state=-1;
			return;
		}

		// Reset for next round
		_state=0; // no need to wait for another sync-bit!
		return;
	}

	_state++;
	return;
}

boolean NewRemoteReceiver::isReceiving(int waitMillis) {
	unsigned long startTime=millis();

	int waited; // Signed int!
	do {
		if (_state >= 34) { // Abort if a significant part of a code (start pulse + 8 bits) has been received
			return true;
		}
		waited = (millis()-startTime);
	} while(waited>=0 && waited <= waitMillis); // Yes, clock wraps every 50 days. And then you'd have to wait for a looooong time.

	return false;
}
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Här är hela biblioteket.
NewRemoteSwitch.rar
Du har inte behörighet att öppna de filer som bifogats till detta inlägg.
Användarvisningsbild
Magnus_K
EF Sponsor
Inlägg: 5854
Blev medlem: 4 januari 2010, 17:53:25
Ort: Skogen mellan Uppsala-Gävle

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Magnus_K »

Hur är det kopplat? LED-tejpen drivs av något som är kopplat till pinne 9 och pinne 13 använder du bara som debugger/indikator?

Vad exakt händer nu när du trycker on och off?
Ser att du skrev det ovan...
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

"Hur är det kopplat? LED-tejpen drivs av något som är kopplat till pinne 9 och pinne 13 använder du bara som debugger/indikator?"
Korrekt!

Pinne 9 till transitor och vidare.
Användarvisningsbild
Jonaz
Inlägg: 2326
Blev medlem: 4 november 2003, 22:06:33
Ort: Huddinge

Re: Dimma med Nexa och en Arduino, lite problem..

Inlägg av Jonaz »

Jag *Tror* problemet är är att fade(); i ligger i loopen och där kommer man inte ur.

Men jag är definitivt inte säker..
Skriv svar