Hello! I want to control the brightness of lamps by infrared remote control. I use the following sketch.
int AC_pin = 10;
volatile uint16_t dim = 33 * 2;
uint8_t dimmer=2; // 0 = max, 255 = min
int irPin = 4;
int ledPin = 8;
int start_bit = 2200; //Start bit threshold (Microseconds)
int bin_1 = 1000; //Binary 1 threshold (Microseconds)
int bin_0 = 400; //Binary 0 threshold (Microseconds)
boolean statusLed = false;
void setup()
{
pinMode(AC_pin, OUTPUT);
attachInterrupt(0, FrontUp, RISING);
pinMode(irPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void FrontUp()
{
detachInterrupt(0);
delayMicroseconds(dim+1200);
digitalWrite(AC_pin, HIGH);
delayMicroseconds(20);
digitalWrite(AC_pin, LOW);
attachInterrupt(0, FrontDown, FALLING);
}
void FrontDown()
{
detachInterrupt(0);
delayMicroseconds(dim);
digitalWrite(AC_pin, HIGH);
delayMicroseconds(20);
digitalWrite(AC_pin, LOW);
attachInterrupt(0, FrontUp, RISING);
}
void loop()
{
int key = getIRKey();
if (key != 0)
{
if (key == 144)
{
toggleLed();
dim = 33 * 2;
}
else if (key == 145)
{
toggleLed();
dim = 33 * 255;
}
delay(15);
}
}
void toggleLed()
{
if (statusLed)
{
digitalWrite(ledPin, LOW);
}
else
{
digitalWrite(ledPin, HIGH);
}
statusLed = !statusLed;
}
int getIRKey() {
int data[12];
int i;
while(pulseIn(irPin, LOW) < start_bit); //Wait for a start bit
for(i = 0 ; i < 11 ; i++)
data[i] = pulseIn(irPin, LOW); //Start measuring bits, I only want low pulses
for(i = 0 ; i < 11 ; i++) //Parse them
{
if(data[i] > bin_1) //is it a 1?
data[i] = 1;
else if(data[i] > bin_0) //is it a 0?
data[i] = 0;
else
return -1; //Flag the data as invalid; I don't know what it is! Return -1 on invalid data
}
int result = 0;
for(i = 0 ; i < 11 ; i++) //Convert data bits to integer
if(data[i] == 1) result |= (1<<i);
return result; //Return key number
}
Now press the buttons works rarely. If I'm not mistaken, this problem arises because of the function delayMicroseconds. When dim = 33 * 2 trigger buttons on the remote probability is much higher than for dim = 33 * 255. Individually, sketches, which are engaged in the processing of signals from the remote control and control the brightness of the lamp are working well.
I think that should somehow parallelize handling the lamp brightness and catch signals from the remote control. To create these two streams have to use two microprocessors. Please tell me whether you can properly control the brightness of the lamp and catch signals from the remote control using one microprocessor?