IR Sensor Experiments

After completing the IR sensor project, test yourself by trying these experiments.

1 Make a LED blink three times when there's an object within the sensing distance. Turn off the LED when there's no object in front.

Notice that with the code on the right, the LED will continue to blink when there's an object in front.
void setup() {
  pinMode(13, OUTPUT);  // internal LED
  pinMode(2, INPUT);    // IR input
}

void loop() {
  int v = digitalRead(2);
  if (v == LOW) {
    // object detected
    // blink LED 3 times
    for (int i=0; i<3; i++) {
      digitalWrite(13, HIGH);   
      delay(250); // short delay for fast blink
      digitalWrite(13, LOW);   
      delay(250); // short delay for fast blink
    }
  } else {
    // no object detected
    digitalWrite(13, LOW);   
  } 
}
2 Similar to experiment 1 above but after blinking three times the LED remains off even when there's an object in front. Turn off the LED when there's no object in front.
void setup() {
  pinMode(13, OUTPUT);  // internal LED
  pinMode(2, INPUT);    // IR input
}
int hasBlinked = false;  // flag to remember whether LED has blinked or not

void loop() {
  int v = digitalRead(2);
  if (v == LOW) {
    // object detected
    if (hasBlinked == false) {
      // blink LED 3 times
      for (int i=0; i<3; i++) {
        digitalWrite(13, HIGH);   
        delay(250); // short delay for fast blink
        digitalWrite(13, LOW);   
        delay(250); // short delay for fast blink
      }
    }
    hasBlinked = true;  // remember LED has blinked
  } else {
    // no object detected
    digitalWrite(13, LOW);
    hasBlinked = false; // reset flag
  } 
  delay(10);   
}
3 Make a LED blink real fast when there's an object within the sensing distance, and slow when there's no object in front.
void setup() {
  pinMode(13, OUTPUT);  // internal LED
  pinMode(2, INPUT);    // IR input
}
int ledOn = false;  // flag to toggle led on and off

void loop() {
  int v = digitalRead(2);
  if (v == LOW) {
    // object detected
    delay(100); // short delay for fast blink
  } else {
    // no object detected
    delay(1000); // long delay for slow blink
  } 
  ledOn = !ledOn; // toggle led
  digitalWrite(13, ledOn);  // the ! symbol inverts the value
}