A lot of Apple products ships with the small white IR remote and i was wondering if anybody have used this to control a Arduino using an IR-sensor?
actually i did it today. i'm not 100% happy with the results, it works but not very reliable. i just used a resistor, maybe i need a capacitor as well?
here is my code:
int ir_pin = 2; //Sensor pin 1 wired through a 220 ohm resistor
int led_pin = 13; //"Ready to Recieve" flag, not needed but nice
int debug = 1; //Serial connection must be started to debug
int start_bit = 2000; //Start bit threshold (Microseconds)
int bin_1 = 1000; //Binary 1 threshold (Microseconds)
int bin_0 = 400; //Binary 0 threshold (Microseconds)
void setup() {
pinMode(led_pin, OUTPUT); //This shows when we're ready to receive
pinMode(ir_pin, INPUT);
digitalWrite(led_pin, LOW); //not ready yet
Serial.begin(9600);
}
void loop() {
int key = getIRKey(); //Fetch the key
Serial.println(result); //sends result to serial for debugging
}
int getIRKey() {
int data[31];
int keysequence[5];
digitalWrite(led_pin, HIGH); //Ok, i'm ready to recieve
while(pulseIn(ir_pin, HIGH) < start_bit) { //Wait for a start bit
}
for(int i=0;i<31;i++) {
data[i] = pulseIn(ir_pin, HIGH); //Start measuring bits, I only want high pulses
}
digitalWrite(led_pin, LOW);
for(int i=0;i<31;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 {
data[i] = 2; //Flag the data as invalid; I don't know what it is!
}
}
}
for(int i=0;i<31;i++) { //Pre-check data for errors
if(data[i] > 1) {
return -1; //Return -1 on invalid data
}
}
for(int i=0;i<31;i++){ //monitors the bit sequence for the specified key 111100001
if(data[i-9] == 1 && data[i-8] == 1 && data[i-7] == 1 && data[i-6] == 1 && data[i-5] == 0 && data[i-4] == 0 && data[i-3] == 0 && data[i-2] == 0 && data[i-1] == 1 ) {
for(int j=0;j<5;j++) { //if found the key sequence, copy the following 5 bits to to new array keysequence
keysequence[j] = data[i+j]; //matches the both arrays over each other for copy
}
}
}
int result = 0;
int seed = 1;
for(int i=0;i<5;i++) { //Convert bits to integer
if(keysequence[i] == 1) {
result += seed;
}
seed = seed * 2;
}
return result; //Return key number
}
Did you ever improve on this? I can't get it to work. I get -1 every time.
Tested working.