/*
The RPR220 is a reflective sensor that consists of an infrared LED and a phototransistor. When an object reflects the infrared light emitted by the LED back to the phototransistor, the sensor's output changes. Here's an example of Arduino code to read the output of an RPR220 reflective sensor:
This code initializes the IR LED and the phototransistor pins, and then reads the analog value from the phototransistor in the loop. If the sensor value is greater than the defined threshold, it considers an object as detected.
Make sure to connect the sensor to your Arduino as follows:
Connect the IR LED's anode (usually the longer leg) to the IR_LED_PIN (pin 7 in the example) and the cathode to GND through a current-limiting resistor (e.g., 220 ohms).
Connect the phototransistor's collector to the 5V supply through a pull-up resistor (e.g., 10k ohms), and the emitter to GND. Connect the collector to the PHOTO_TRANSISTOR_PIN (A0 in the example).
You may need to adjust the DETECTION_THRESHOLD value based on your specific application and ambient lighting conditions.
*/
// Define the sensor pins
#define IR_LED_PIN 7
#define PHOTO_TRANSISTOR_PIN A0
// Define the threshold for object detection
#define DETECTION_THRESHOLD 600
void setup() {
// Initialize the serial communication
Serial.begin(9600);
// Set the IR LED pin as output
pinMode(IR_LED_PIN, OUTPUT);
digitalWrite(IR_LED_PIN, HIGH); // Turn ON the IR LED
// Set the phototransistor pin as input
pinMode(PHOTO_TRANSISTOR_PIN, INPUT);
}
void loop() {
// Read the analog value from the phototransistor
int sensorValue = analogRead(PHOTO_TRANSISTOR_PIN);
// Print the sensor value to the serial monitor
Serial.print("Sensor value: ");
Serial.println(sensorValue);
// Check if an object is detected
if (sensorValue > DETECTION_THRESHOLD) {
Serial.println("Object detected!");
} else {
Serial.println("No object detected.");
}
// Wait for a moment before the next reading
delay(500);
}
Comments