cyber:bot Ping))) Roaming Program

With the Ping))) and servo subsystems working correctly, we can combine them with motor control to make the cyber:bot roam. This program has several places where you can easily customize it for better performance in your own environment.

  • If ping_servo_test is not already open, open it with the micro:bit Python Editor.  
  • Change the project's name to ping_servo_roaming
  • Enter the script below, and then click Save.
  • Click Send to micro:bit.  
  • Disconnect the USB cable from the cyber:bot robot's micro:bit and put the cyber:bot on the floor.
  • Set the cyber:bot board’s PWR switch in position 2.
  • The cyber:bot should drive around, sweeping its Ping))) sensor from side to side, and turn away from obstacles.
# ping_servo_roaming

from cyberbot import *
from ping import *

# angles for L/R sweep scan
theta = [0, 30, 60, 90, 120, 150, 180, 165, 135, 105, 75, 45, 15]
# Offset from CW limit to actual 0 degree theta is 12 degrees
offset = 12

speed = 0
distance = 300
wL = 64
wR = 64
index = 0

bot(22).tone(2000, 300)

def turn_away(index):
    angle = theta[index] - 90

    if angle > 0:
        wL = 64
        wR = -64
    else:
        wL = -64
        wR = 64

    bot(18).servo_speed(wL)
    bot(19).servo_speed(-wR)    
    sleep(500)

while True:
    bot(17).servo_angle ( theta[index] + offset )
    sleep(150)
    distance = ping(16).distance('cm')

    #print("theta = %d, distance = %d" % (theta[index], distance))

    if distance >= 25:
        wL = 64
        wR = 64
    else:
        turn_away(index)

    bot(18).servo_speed(wL)
    bot(19).servo_speed(-wR)    

    index += 1
    if index > 12:
        index = 0
        #print("\r\r")


Try This - Improve your Code

You can easily modify the Ping_Servo_Roaming.py code for different behaviors based on your environment. For example, the turn_away(index) definition simply tests whether the close object is on the left or right of the robot:

def turn_away(index):
    angle = theta[index] - 90
    #print("angle = %d" % angle)

    if angle > 0:
        wL = 64
        wR = -64
    else:
        wL = -64
        wR = 64

More angle conditions could be evaluated by adding multiple elif statements and appropriate motor speeds. For example, if the object is on the left, it may only be necessary to make a slight correction with a right turn, rather than pivoting in place as shown above. An object detected in front of the cyber:bot may mean turn around, rather than turn away. These are all customizations you can make.  

Also, consider the distance at which objects are considered “close” together with the cyber:bot’s speed:

    if distance >= 25:
        wL = 64
        wR = 64
    else:
        turn_away(index)

The detection distance and speed need to work together. Driving fast with a short detection distance is a sure way to hit the wall!

Try different combinations of wL, wR, and threshold values for distance.