Keeping a straight line using a gyro sensor. Pro Preview

The gyro sensor indicates the angle of the turn the robot made. We certainly can use this to create a robot that could perfectly follow a direction, right? Now we'll show you the easiest way to do it.

To access the full video please subscribe to


  • #1279
  • 08 May 2019

This program is exactly the same as following a line with one color sensor. The idea is to move straight, when we're in the right direction (the gyro sensor shows 0 degrees), and to turn, when the gyro is not showing 0 in order to get back to the right direction.

content picture

However, this would be complicated. In general the program represents a series of constant turns, also known as "duck walking". The back line from the line following task will be replaced by the imaginary line that we want to follow. The target value will be 0, but we can modify it for the angle needed. The algorithm is as follows:

  • If the gyro sensor shows less than 0 degrees, we turn towards 0 degrees - in this case we turn right.

content picture

  • If the gyro sensor shows more than 0 degrees, we turn towards 0 degrees again. In this case we turn left.

content picture

And we're ready! We have a program with which our robot will always follow the same direction, even if we try to push it away from its path.

Like in line following, this program could be done with both switch and wait blocks.

This is the simplest algorithm for following a direction, but it's not the smoothest. Fortunately, line following is exactly the same task as direction following. Therefore, you could check the tutorials for line following with 3 or more states or proportional line following. The logic is exactly the same.

Courses and lessons with this Tutorial

This Tutorial is used in the following courses and lessons

Image for Level D2. "Seafaring". Robotics with LEGO
  • 24
  • 2:49
  • 107
Image for Lesson 5 - Following a direction
  • 5
  • 3
  • 8
  • 3d_rotation 0
Image for Robotics with LEGO - Level 2.5 - Maritime Journey
  • 42
  • 3:52
  • 133
Image for Lesson 5 - Personal Yacht
  • 7
  • 3
  • 10
  • 3d_rotation 0