What are infrared sensors?
The infrared sensor, also known as IR sensor, is a device that detects reflected light and can thus differentiate between black and white or dark and light.
It´s a digital component as it only returns two values (0 and 1). It returns a 0 when it detects black (black absorbs the light, so the light reflected, which is what the sensor measures, is zero) and when it detects white, it returns 1. The IR sensors are used in everyday objects such as:
- Microwave ovens
- Garage doors
- Burglar alarms
- Streetlights (they light up as it gets dark and go off as day breaks)
- Cars (they detect whether it´s night-time or if there is fog to switch on the headlights)
|So let´s get down to work. We will make two examples that use the infrared sensor to make a buzzer ring and to light up an LED. You will need:
Before you start, you will need to watch the video on how to calibrate the infrared sensors.
Got it? Let´s go.
Making the buzzer ring when the IR sensor detects black
As we have already seen, the IR sensor can differentiate between black and white. Before we start with the program, we will connect the components to the controller board as shown in the diagram. The IR sensor to digital pin 3 and the buzzer to digital pin 5.
In this example, we have declared a variable called colour_detected which represents the infrared sensor. We have added a condition (that the colour detected is black) so that the buzzer sounds. To check that it works, we can place the IR sensor about 3 centimetres from a white surface and place a hand between the sensor and this surface. What happens? Does the buzzer ring?
Making an LED light up when both IR sensors detect black
Now we will make an LED light up only when both IR sensors detect the colour black. We will use the same process to do this as always. We will connect the IR sensors to digital pins 2 and 3 and the LED to PIN 7 as shown in the diagram:
Then we program the controller board so that the LED lights up when both sensors detect the colour black. On this occasion, two conditions are required for our desired instructions to be executed (in this case, for the LED to light up). Using the block and the Logic section, we can add the two conditions to the program.
So there you go, now you know how to program using infrared sensors. Programming a line follower will be a piece of cake!