IR Beam Sensor

Parts Used

  • A pair of IR Beam Sensor

  • 2 Jumper Wires

Time Spent

Approximately 1.5 hours

The Code

#define SENSORPIN 4

// variables will change:
int sensorState = 0, lastState=0;         // variable for reading the pushbutton status

void setup() {
  // initialize the sensor pin as an input:
  pinMode(SENSORPIN, INPUT);
  digitalWrite(SENSORPIN, HIGH); // turn on the pullup

  Serial.begin(9600);
}

void loop(){
  // read the state of the pushbutton value:
  sensorState = digitalRead(SENSORPIN);

  // check if the sensor beam is broken
  // if it is, the sensorState is LOW:


  if (sensorState && !lastState) {
    Serial.println("Unbroken");
  }
  if (!sensorState && lastState) {
    Serial.println("Broken");
  }
  lastState = sensorState;
}

Issues

I tried to use the digital pin of the IR receiver as a direct output without connecting to Arduino. Instead, I tried to connect the digital output pin to an LED. It didn’t work. The LED wouldn’t turn on no matter of the receiver state. When I unplugged the ground pin of the receiver, the LED turned on. I tested with the example code and all parts are functional. I think this has something to do with the pull up resistor in the tutorial. More researches to be done.

Results