Driving the robot using the compass

Now, all that remains for us to do is use the compass bearing to steer our robot to the desired angle.

Create the following compassDrive.py script:

#!/usr/bin/env python3 #compassDrive.py import XLoBorg3 as XLoBorg import rover_drive as drive import time MARGIN=10 #turn until within 10degs LEFT="l"; RIGHT="r"; DONE="#" def calDir(target, current, margin=MARGIN): target=target%360 current=current%360 delta=(target-current)%360 print("Target=%f Current=%f Delta=%f"%(target,current,delta)) if delta <= margin: CMD=DONE else: if delta>180: CMD=LEFT else: CMD=RIGHT return CMD def main(): myCompass=XLoBorg.compass() myBot=drive.motor() while(True): print("Enter target angle:") ANGLE=input() try: angleTarget=float(ANGLE) ...

Get Raspberry Pi 3 Cookbook for Python Programmers - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.