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:
- Use the micro:bit Python Editor to open the script roaming_with_whiskers.
- Rename the script by setting the project name to 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.
- Click Save to keep a copy of your work
- Click Send to micro:bit to flash the script.
- 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()