HOW to Use Photo Interrupter with ESP32
Description
This kit contains a photo interrupter which mainly uses 1 ITR-9608 photoelectric switch. It is a photoelectric switch optical switch sensor.
Working Principle
When the paper is put in the slot, C is connected with VCC and the signal end S of the sensor are high levels; then the red LED will be off. Otherwise, the red LED will be on.
Required Components
Connection Diagram
Test Code
//*************************************************************************************
/*
* Filename : Photo_Interrupt
* Description : Light snap sensor counting
* Auther : http://www.keyestudio.com
*/
int PushCounter = 0; //The count variable is assigned an initial value of 0
int State = 0; //Store the current state of the sensor output
int lastState = 0; //Stores the state of the last sensor output
void setup() {
Serial.begin(9600);//Set the baud rate to 9600
pinMode(15, INPUT);//Set the light snap sensor pin to input mode
}
void loop() {
State = digitalRead(15);//Read current state
if (State != lastState) {//If the state is different from the last read
if (State == 1) {//block the light
PushCounter = PushCounter + 1;//Count + 1
Serial.println(PushCounter);//Print count
}
}
lastState = State;//Update state
}
//*************************************************************************************
Code Explanation
Logic setting:
Test Result
Connect the wires according to the experimental wiring diagram, compile and upload the code to the ESP32. After uploading successfully,we will use a USB cable to power on,open the serial monitor and set the baud rate to 9600.
The serial monitor will display the PushCounter data. Every time when the object passes through the slot of the sensor, the PushCounter data will increase by 1 continuously, as shown below;