---
title: "Activity: Lane Guidance"
date: "2021-06-03"
categories: ["Activities", "All"]
tags: ["Branching", "Iteration", "Algorithm Design", "Ultrasonic", "IR", "Motors", "Maths", "Advanced"]
codingSkills: ["Branching", "Iteration", "Algorithm Design", "Maths"]
roverConcepts: ["Ultrasonic", "IR", "Motors"]
excerpt: "Learn iteration, branching, algorithm design, maths, and how to use the motors, ultrasonic, and IR sensors."
featuredImage: "/images/resources/lane-guidance.png"
---


Program rovers to stay in the middle of a lane marked out by walls. This is a simplification of the lane assist technology in cars. Use the front ultrasonic sensor and both IR sensors on either side of the rover to determine where walls are and drive as smoothly through the middle of the path as you can. Don’t run into the walls!

### Activity Demonstration

<iframe width="560" height="315" src="https://www.youtube.com/embed/gK6SzjarP_U" title="Lane Guidance Activity Demonstration" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>

### Setup

Create a curving walled passage on the floor. The walls can be anything from books to wooden blocks, as long as they are solid and high enough to be detected by the IR and ultrasonic sensors. Tight passages and sharp corners greatly increase the difficulty. You can also add coloured tape as traffic markers through the passage that the robot must stop or turn around at.

### Here’s Our Approach

The core of this problem is that if the wall on the left is closer than the one on the right you need to turn right. This can be done with IF statements. Make sure you can do it with IF statements first before looking at this solution. Once you’re confident with this check out the PID example to make it even smoother.

#### Stage 1 - Read Sensors

Using clear variable names can make code easier to read and follow. We use variables to calculate the difference between the distances read by the two IR distance sensors.

**Stage 2 - Calculate Motor Speeds**

The math scale block lets you convert a number from one range to another. We used -35 and 35 because that suited the width of the passage we were using. That was about the maximum difference that would be possible between the left and right distance sensor readings. We converted that to -7 and 7 so that there would be a maximum difference of 14cm/s between the motors speeds.

The left and right motor speeds are then calculated by adding/subtracting this value to a base forward speed so the rover always moves forward.

![](/images/content/871b48-laneguidance-answer.png)

Example Code
