These small cheap devices (pic below) are extremely useful in many situations where you want to know is something is close by, whether that be an object or a black/white line etc.
They work by sending out an IR beam and looking for it coming back. Therefore it has to reflect off a surface for it to work. In reality most surfaces will reflect back some of the IR. They have a small turn screw to adjust the sensitivity so that you could just detect objects very close by or look for ones further afield. The effective range is from around 3mm to 10cm – depending on the type of surface being reflected. The better at reflecting IR then the longer the detectable distance would be. The video below goes into hooking this up and using with our Lego projects, source code for the model built is listed below the video.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <Servo.h> // This library is installed by default, no need to install it. #define SENSE_PIN 2 // Input from IR Sensor pin, goes low if something in front of sensor Servo myservo; // create servo object to control a servo void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object pinMode(SENSE_PIN,INPUT); myservo.write(180); // set servo to start pos } void loop() { while(digitalRead(SENSE_PIN)==1); // wait for an object in front of sensor delay(1000); // small delay to allow fingers to get out of the way! myservo.write(0); // tell servo to go to end position delay(500); // wait to make sure servo reached end position myservo.write(180); // return back to start delay(500); // ensure has returned back to start before continuing } |
That’s it for now, in the next article we’ll look at how to hook up Lego Classic 9V motors to our Arduino’s so that we can give some “Brains” to our builds.