Infrared Obstacle Avoidance Sensor with micro:bit
An infrared obstacle avoidance sensor receives a signal when there is an object blocking its path.
In this guide, you will learn to connect an infrared obstacle avoidance sensor with the micro:bit, and get it to turn an LED off when an obstacle such as your hand or a piece of white paper is in its path.
Complete this guide to learn the basics and use it in your own projects. Some examples of what it can be used for include security alarm systems or an obstacle avoidance robot.
|Parts Used in This Guide|
Step 1 The Module
Let's take a closer look at the infrared obstacle avoidance sensor!
It has three pins:
- Output (OUT)
- Ground (GND)
- Voltage Common Connector (VCC)
Step 2 Connect module to breadboard
Step 3 Connect P0 to OUT
Step 4 Connect GND to GND
Step 5 Connect 3.3V to VCC
Step 6 Connect GND to LED (Negative lead)
Step 7 Add a resistor
Step 8 Connect P1 to resistor
Step 9 on start block
- Open up MakeCode editor and ttart a new project
- Now get a 'set pull pin P0 to up' block. To get one, click on 'Pins' and 'more ...' tab
- Place this in the 'on start' block.
Step 10 Add the variable!
- To start off, create a variable. You can do so by clicking on the 'Variables' tab and choosing 'Make a variable'.
- Name this variable 'avoidPin'.
- Next, click on the 'Pins' tab and drag and drop a 'digital read pin P0' block.
- Attach it to 'set ... to' block.
Step 11 The loop!
- To create the loop, click on the 'Logic' tab and drag and drop a 'if ... then ... ' block.
- Again in the 'Logic' tab, grab a '0 = 0' block and change its values to 'avoidPin' and '1' accordingly.
- In the 'Pins' tab, grab a digital write pin P0 to 0 block.
- Attach this block to 'then ...' Change its value to 'P0' and '1'.
- Right-click on it and select 'Duplicate', and place this copy underneath it.
- Change the values for it to 'P1' and '1'
- Click on the blue cog icon next to 'if' and drag and drop an 'else' block.
- Attach it to 'if'. You should not have an 'else' statement in the loop.
- Duplicate 'digital write pin P0 to 1' and make two copies of this.
- Change their values so that you have a 'digital write pin P0 to 0' and 'digital write pin P1 to 0'
Step 12 Show number!
- From 'Basic' tab, drag and drop a 'show number ...' block.
- Replace its value '0' with 'avoidPin'
Step 13 Upload the code
It's time to upload the code and test it out!
- Connect your micro:bit to the computer using a microUSB cable
- Click on 'Download' button in MakeCode editor.
- The downloaded .hex file will be in your 'Downloads' folder
- Drag and drop the .hex file to the MICROBIT drive
With the micro:bit powered up and with the code on it, the LED should now light up and the screen should show '1'. Move a hand over the IR obstacle avoidance sensor and the screen should change to '0'. The LED will also not be light up.