Example Code for Arduino-LED Control

Control the LED light with the Photo Interrupter. The LED light will turn on when the Photo Interrupter is blocked; otherwise, it will turn off.

Hardware Preparation

Software Preparation

  • arduino IDE
  • MindPlus

Wiring Diagram

Connect the Photo Interrupter to the P7 pin on the I/O Expansion Shield, and connect the LED light to the P4 pin.

Sample Code

#define led 4
#define PI 7

void setup() {
  pinMode(led, OUTPUT);   // Set LED pin as output
  pinMode(PI, INPUT);     // Set Photo Interrupter pin as input
}

void loop() {
  int P = digitalRead(PI);   // Read the digital value of the Photo Interrupter
  if (P == 1) {              // Check if the Photo Interrupter is blocked
    digitalWrite(led, HIGH); // If yes (blocked), turn on the LED
  } else {
    digitalWrite(led, LOW);  // If not (not blocked), turn off the LED
  }
}

Result

After the program is successfully downloaded, the LED light will turn on when the Photo Interrupter is blocked; otherwise, the LED light will turn off.

Was this article helpful?

TOP