Advertisement
microrobotics

RPR220 Reflective Sensor

May 4th, 2023
1,118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. 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:
  3.  
  4. 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.
  5.  
  6. Make sure to connect the sensor to your Arduino as follows:
  7.  
  8. 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).
  9.  
  10. 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).
  11.  
  12. You may need to adjust the DETECTION_THRESHOLD value based on your specific application and ambient lighting conditions.
  13. */
  14.  
  15. // Define the sensor pins
  16. #define IR_LED_PIN 7
  17. #define PHOTO_TRANSISTOR_PIN A0
  18.  
  19. // Define the threshold for object detection
  20. #define DETECTION_THRESHOLD 600
  21.  
  22. void setup() {
  23.   // Initialize the serial communication
  24.   Serial.begin(9600);
  25.  
  26.   // Set the IR LED pin as output
  27.   pinMode(IR_LED_PIN, OUTPUT);
  28.   digitalWrite(IR_LED_PIN, HIGH); // Turn ON the IR LED
  29.  
  30.   // Set the phototransistor pin as input
  31.   pinMode(PHOTO_TRANSISTOR_PIN, INPUT);
  32. }
  33.  
  34. void loop() {
  35.   // Read the analog value from the phototransistor
  36.   int sensorValue = analogRead(PHOTO_TRANSISTOR_PIN);
  37.  
  38.   // Print the sensor value to the serial monitor
  39.   Serial.print("Sensor value: ");
  40.   Serial.println(sensorValue);
  41.  
  42.   // Check if an object is detected
  43.   if (sensorValue > DETECTION_THRESHOLD) {
  44.     Serial.println("Object detected!");
  45.   } else {
  46.     Serial.println("No object detected.");
  47.   }
  48.  
  49.   // Wait for a moment before the next reading
  50.   delay(500);
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement