Continuing our discussion from the previous tutorial things get a whole lot more interesting when you use odometry to figure how much your robot strayed off the straight and narrow.

Lets start by building a simple script to on which we can test the theory using the same model we were using earlier.

#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.parameters import Button, Port, Stop
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.tools import wait
leftMotor = Motor(Port.B)
rightMotor = Motor(Port.C)
gyro = GyroSensor(Port.S4)
gyro.reset_angle(0)
leftMotor.run_angle(25,360,Stop.HOLD,False)
rightMotor.run_angle(25,270,Stop.HOLD,True)
wait(8000)
angleOut = gyro.angle()
print("gyro phase I",angleOut)

Nothing too it. We import the required classes, define our motors and the gyro sensor and then use one of the commands I mentioned earlier to move the two wheels different amounts. Finishing by printing out the angle returned by our gyro.

Here are the figures. We’re interested at this point between the difference in distance that the left and right motors travelled. We have 360 — 270, so the difference is 90 clicks.

We than divided this number by distance between the two wheels, so in our case 90 / 125 or 0.44. Using trigonometry this time we can work out the angle that we’re off the line by and correct it.

The script will print out the value measured by the gyro, using trig we take the arctan of 0.44 which returns 24 degrees, the same value returned the gyro.

Ok, I understand your brain is hurting. No worries there is a built in command to help you out with this sort of thing too, it’s called DriveBase. Here is 2cents script showing in action.

#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.parameters import Button, Port, Stop
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.tools import wait
from pybricks.robotics import DriveBase
leftMotor = Motor(Port.B)
rightMotor = Motor(Port.C)
gyro = GyroSensor(Port.S2)
gyro.reset_angle(0)
wheelDiam = 56
wheelDist = 114
speed = 50
angle = 0
robot = DriveBase(leftMotor, rightMotor, wheelDiam, wheelDist)while True:
robot.drive(speed,angle)
wait(1000)
leftAngle = leftMotor.angle()
rightAngle = rightMotor.angle()
print("figures",leftAngle, rightAngle, gyro.angle())

What does it do. It takes two parameters, the speed and the angle you want to drive at, simple as that. Note it takes those odometry parameters with it is initialized too. Note the wheel diameter and the distance between them.

Coding for 35+ years, enjoying using and learning Swift/iOS development. Writer @ Better Programming, @The StartUp, @Mac O’Clock, Level Up Coding & More

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store