Receiver PWM signal switches light modes
[copter_light.git] / pwm_in.ino
blob0ee5ec50e87685c8e06d55037a41d0f506a846fb
1 int PWM_IN_PIN = 0;
3 //micros when the pin goes HIGH
4 volatile unsigned long timer_start = 0;
5 //difference between timer_start and micros() is the length of time that the pin 
6 //was HIGH - the PWM pulse length. volatile int pulse_time; 
7 //this is the time that the last interrupt occurred. 
8 //you can use this to determine if your receiver has a signal or not. 
9 volatile int last_interrupt_time; //calcSignal is the interrupt handler 
10 volatile int pulse_time;
11 void calcSignal() 
13     //record the interrupt time so that we can tell if the receiver has a signal from the transmitter 
14     last_interrupt_time = micros(); 
15     //if the pin has gone HIGH, record the microseconds since the Arduino started up 
16     if(digitalRead(PWM_IN_PIN) == HIGH) 
17     { 
18         timer_start = micros();
19     } 
20     //otherwise, the pin has gone LOW 
21     else
22     { 
23         //only worry about this if the timer has actually started
24         if(timer_start != 0)
25         { 
26             //record the pulse time
27             pulse_time = ((volatile int)micros() - timer_start);
28             //restart the timer
29             timer_start = 0;
30         }
31     } 
32
34 void setup_pwm_in(int pin)
36   PWM_IN_PIN = pin;
37   attachInterrupt(digitalPinToInterrupt(pin), calcSignal, CHANGE);
40 int read_pwm()
42   uint8_t oldSREG = SREG;
43   cli();  //disable interrupts to get a consistent value
44   int ret = pulse_time;
45   SREG = oldSREG;
46   return ret;
49 inline long map(long x, long in_min, long in_max, long out_min, long out_max)
51   return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
54 template <typename T> T limit(T x, T a, T b)
56     return (x<a) ? a : (x>b) ? b : x;
59 #define MINPULSE 1000
60 #define MAXPULSE 2040
62 byte get_mode(unsigned int rotaryPulse, unsigned int numSteps)
64   return limit(map(rotaryPulse, MINPULSE, MAXPULSE, 0, numSteps), 0L, (long)numSteps-1);