Learn how to detect distance using an ultrasonic sensor
- What you’ll learn
- Things’s you’ll needs
- Lets code!
- What the code means
- Roving Robot
What you’ll learn
In this lesson you will learn how to detect distances using a HC-SR04 ultrasonic distance sensor.
Things’s you’ll needs
Before you begin, you’ll need to make sure you have a couple of things before you start this lesson:
- A SMARS robot
- A USB Cable to connect to your computer
- A Computer that can run the Arduino IDE
- A HC-SR04 ultrasonic sensor
- Connect the SMARS to the USB cable, and the USB Cable to your computer
- Launch the Arduino IDE on your computer
- Create a new Sketch, by clicking the
You can download the code below from GitHub, but its better to type it in yourself line by line, as you will get to understand what each line means.
Type the following lines:
What the code means
The next section explains what each piece of code means.
Verify the code
Once you have typed in the code, click the Verify button (the Tick at the top of the screen). This will check that you’ve not made any typing mistakes.
If it says ‘Success: Done verifying’ then you have code that is ready to be uploaded.
If you get an error message, read the message and look at the area of code it is having a problem with and compare it to the code at the top of this page.
Set the Connection
Select the Arduino connection using the dropdown box next to the upload arrow button. You will see a list of boards to choose from. SMARS robots use the
Arduino/Generic UNO board type. Select the Port your SMARS is connected to (you should see this in the list).
Click OK to continue.
Upload the code
You are now ready to upload this code to your SMARS robot. Press the upload button (the arrow next to the verify button), to upload the program to your robot.
This page was first created on 24 November 2019, and was last updated on 08 March 2020