Navigate and Avoid Obstacles

An interesting thing about these IR detectors is that their outputs are just like the whiskers.  When no object is detected, the output is high; when an object is detected, the output is low.  You could modify the script roaming_with_whiskers so that it works with the IR detectors with just a few changes.  Here are the steps it takes:

  • Open the script roaming_with_whiskers and rename it as roaming_with_IR.
  • Replace the read_digital calls with ir_detect calls:
    irL = bot(14, 13).ir_detect(37500)
    irR = bot(1, 2).ir_detect(37500)
  • Change all the variables in the if statement from whisker_left and whisker_right to irL and irR.
    if irL == 0 and irR == 0:     
        backwards()                                 
        right()
    elif irL == 1 and irR == 0:   
        backwards()                                  
        left()
    elif irL == 0 and irR == 1:  
        backwards()                                   
        right()
    else:                                           
        forward()

Example script: roaming_with_ir

  • After modifying your script as described above, double-check that it matches roaming_with_ir below.
  • Re-save the script and flash it to your micro:bit module.
  • Disconnect the cyber:bot from its programming cable and place it where it can roam and avoid obstacles.
  • Set the power switch to position 2.
  • Watch your cyber:bot roam. It should behave like roaming_with_whiskers, aside from the fact that it doesn't actually run into objects before changing direction.
# roaming_with_IR

from cyberbot import *        
        
def forward():
    bot(18).servo_speed(75)
    bot(19).servo_speed(-75)

def backwards():
    bot(18).servo_speed(-75)
    bot(19).servo_speed(75)
    sleep(250)

def right():
    bot(18).servo_speed(75)
    bot(19).servo_speed(75)
    sleep(250)

def left():
    bot(18).servo_speed(-75)
    bot(19).servo_speed(-75)
    sleep(250)

while True:
    irL = bot(14, 13).ir_detect(37500)
    irR = bot(1, 2).ir_detect(37500)
    
    if irL == 0 and irR == 0:     
        backwards()                                 
        right()
    elif irL == 1 and irR == 0:   
        backwards()                                  
        left()
    elif irL == 0 and irR == 1:  
        backwards()                                   
        right()
    else:                                           
        forward()