Example 9 Custom Functions Drive, Turn_right and Turn_left

not found

What does this code do?

In this code the robot moves forward until abs = distance, then rotates right by 180 degrees and finally rotates left by 360 degrees.

Functions Used

cmpc( clear_motor_postition_counter )

abs(absolute)

gmpc(get_motor_position_counter)

mav(motor port, velocity)

msleep( distance in ms)

Function Implementation

 1#!/usr/bin/python3
 2import os, sys
 3sys.path.append("/usr/lib")
 4from kipr import *
 5
 6def drive(distance, speed):
 7    cmpc(0)  # Clear motor position counter for motor 0
 8    cmpc(3)  # Clear motor position counter for motor 3
 9    while abs(gmpc(0)) < distance and abs(gmpc(3)) < distance:
10        mav(0, speed)  # Move motor 0 at speed
11        mav(3, speed)  # Move motor 3 at speed
12    mav(0, 0)  # Stop motor 0
13    mav(3, 0)  # Stop motor 3
14    msleep(20)
15
16def turn_right(distance, speed):
17    cmpc(0)  # Clear motor position counter for motor 0
18    cmpc(3)  # Clear motor position counter for motor 3
19    while abs(gmpc(3)) < distance:
20        mav(0, -speed)  # Move motor 0 backward
21        mav(3, speed)   # Move motor 3 forward
22    mav(0, 0)  # Stop motor 0
23    mav(3, 0)  # Stop motor 3
24    msleep(20)
25
26def turn_left(distance, speed):
27    cmpc(0)  # Clear motor position counter for motor 0
28    cmpc(3)  # Clear motor position counter for motor 3
29    while abs(gmpc(0)) < distance:
30        mav(0, speed)   # Move motor 0 forward
31        mav(3, -speed)  # Move motor 3 backward
32    mav(0, 0)  # Stop motor 0
33    mav(3, 0)  # Stop motor 3
34    msleep(20)
35
36def main():
37    drive(1000, 500)          # Drive forward for a distance of 1000 at speed 500
38    turn_right(2300, 750)     # Turn right for a distance of 2300 at speed 750
39    turn_left(4300, 750)      # Turn left for a distance of 4300 at speed 750
40
41if __name__ == "__main__":
42    main()

Rookie Tips

Make sure you use cmpc to reset both of your robot’s positions before running the code. If you don’t reset both of the motors, there is a large chance your code wouldn’t work.