This page has moved into the new guide: Ranger 2-Way › EV3

EV3 beginner examples: TOF2 dual-eye laser

Back to the TOF2 dual-eye laser product page

This page has 6 examples for people who have never written a program: every example comes with a ready-made program file you can download and run, plus a plain-language step-by-step explanation. Start with example 1 and work through in order.

Before you start

  1. Use the EV3 edition of the sensor (RJ12 plug), plugged into port 1 of the EV3.
  2. Turn the EV3 on first, then plug in the sensor. If the number never changes, unplug the sensor and plug it back in.
  3. Examples that drive use the LEGO Education base robot: left wheel motor on B, right wheel motor on C.
  4. The sensor shows up on the EV3 as an "Infrared Sensor". That is normal: read its values with the infrared sensor blocks.

Every example comes in 5 software versions; pick the one you use: (examples marked "Pybricks / EV3 MicroPython / clev3r only" come in those 3 versions only, because the EV3-G and Classroom blocks cannot read that mode)

Software Who it suits How to open the example file
EV3-G (official software) School computer labs, WRO teams (the most common in Taiwan) Download the .ev3 file, choose "File → Open Project" in the EV3 software, then "Download and Run" at the bottom right.
EV3 Classroom First time with EV3, want the same blocks as SPIKE Download the .lmsp file, choose "Open" on the EV3 Classroom home screen, connect the EV3 and press "Download and Run" at the bottom right.
Pybricks v4 Want to learn typed code, works in the browser Open code.pybricks.com in Chrome; the EV3 needs the Pybricks firmware first (currently Beta). Drag the .py file into the editor and press Run.
EV3 MicroPython v2.0 Already using the official LEGO EV3 MicroPython Use the official LEGO "EV3 MicroPython" microSD boot card + the VS Code extension; paste the program into main.py and press F5 to download and run.
clev3r Already using clev3r (EV3 Basic) Open the .bp file in clev3r, press "Compile and download", then run it from the MBC_ folder in the EV3 file browser.

The 5 values used on this page

Name Range Where it comes from
Average distance of both eyes 0 ~ 100 (1 unit = 1.2 cm, 100 = nothing ahead) Mode 0
Left eye distance 0 ~ 100 (1 unit = 1.2 cm) Mode 1, value 1
Right eye distance 0 ~ 100 (1 unit = 1.2 cm) Mode 1, value 2
Left eye distance (mm) 0 ~ 1200 mm Mode 5, value 1 (Pybricks / EV3 MicroPython / clev3r only)
Right eye distance (mm) 0 ~ 1200 mm Mode 5, value 2 (Pybricks / EV3 MicroPython / clev3r only)

Example list:

  1. Measure how far away something is
  2. Stop 30 cm before the wall
  3. Obstacle avoider: back up and turn
  4. Follow the leader: keep a fixed distance
  5. Left eye, right eye: dodge obstacles on both sides
  6. Stop precisely in millimetres: stop 20 cm before the wall (Pybricks / EV3 MicroPython / clev3r only)

Example 1: Measure how far away something is

What this example does: Move your hand back and forth in front of the sensor and the EV3 screen shows the distance. This example shows both the "raw sensor number" and the value "converted to centimetres".

What you need:

  • TOF2 dual-eye laser (EV3 edition)
  • A box or wall as an obstacle
  • EV3 brick

How to connect: TOF2 dual-eye laser in port 1, lasers facing forward.

Download the program (pick your software):

⬇ EV3-G (official software) | ⬇ EV3 Classroom | ⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0 | ⬇ clev3r

EV3-G (official software) blocks

TOF2 dual-eye laser Measure how far away something is(EV3-G (official software))

(Too small? Click the picture to open it full size.)

EV3 Classroom blocks

TOF2 dual-eye laser Measure how far away something is(EV3 Classroom)

(Too small? Click the picture to open it full size.)

Pybricks v4 code
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 01:量量看前面有多遠
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:TOF2 雙眼雷射插 1 號孔
# 這個範例會做什麼:用手在感應器前面前後移動,EV3 螢幕會顯示距離。這個範例同時顯示「感應器原始數字」和「換算成公分」。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port, Color
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = LUMPDevice(Port.S1)       # TOF2 雙眼雷射插 1 號孔


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read(0)[0]


# ---------- 程式從這裡開始 ----------
# 先清除螢幕
ev3.screen.clear()
# 一直重複
while True:
    # 第 1 行顯示感應器讀到的原始數字(0~100)
    ev3.screen.draw_text(0, 0, "RAW " + str(read_dist()) + "      ", Color.BLACK, Color.WHITE)
    # 第 2 行顯示換算後的公分:數字 × 1.2
    ev3.screen.draw_text(0, 16, "CM " + str(read_dist() * 1.2) + "      ", Color.BLACK, Color.WHITE)
    # 等 0.1 秒
    wait(100)
EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 01:量量看前面有多遠
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:TOF2 雙眼雷射插 1 號孔
# 這個範例會做什麼:用手在感應器前面前後移動,EV3 螢幕會顯示距離。這個範例同時顯示「感應器原始數字」和「換算成公分」。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.iodevices import Ev3devSensor
from pybricks.parameters import Port, Color
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = Ev3devSensor(Port.S1)     # TOF2 雙眼雷射插 1 號孔


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read('IR-PROX')[0]


# ---------- 程式從這裡開始 ----------
# 先清除螢幕
ev3.screen.clear()
# 一直重複
while True:
    # 第 1 行顯示感應器讀到的原始數字(0~100)
    ev3.screen.draw_text(0, 0, "RAW " + str(read_dist()) + "      ", Color.BLACK, Color.WHITE)
    # 第 2 行顯示換算後的公分:數字 × 1.2
    ev3.screen.draw_text(0, 16, "CM " + str(read_dist() * 1.2) + "      ", Color.BLACK, Color.WHITE)
    # 等 0.1 秒
    wait(100)
clev3r code
' ============================================================
' TOF2 雙眼雷射測距感應器 EV3 新手範例 01:量量看前面有多遠
' 軟體:clev3r
' 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
' 這個範例會做什麼:用手在感應器前面前後移動,EV3 螢幕會顯示距離。這個範例同時顯示「感應器原始數字」和「換算成公分」。
' 讀值:dist=左右兩眼的平均距離(0 ~ 100(1 格=1.2 公分,100=前面沒東西))
' ============================================================
folder "prjs" "MBC_tof2_ex01"

' TOF2 雙眼雷射插 1 號孔,使用模式 0
Sensor.SetMode(1, 0)
LCD.Clear()

' 先清除螢幕
LCD.Clear()
' 一直重複
While "True"
  ' 第 1 行顯示感應器讀到的原始數字(0~100)
  LCD.Text(1, 0, 0, 1, "RAW " + Sensor.ReadRawValue(1, 0) + "      ")
  ' 第 2 行顯示換算後的公分:數字 × 1.2
  LCD.Text(1, 0, 16, 1, "CM " + Sensor.ReadRawValue(1, 0) * 1.2 + "      ")
  ' 等 0.1 秒
  Program.Delay(100)
EndWhile

Step by step:

  1. Clear the screen first
  2. Repeat forever
    • Row 1 shows the raw sensor value (0~100)
    • Row 2 shows centimetres: value × 1.2
    • Wait 0.1 s

What you should see: The closer your hand, the smaller the number; with your hand away (nothing within 120 cm) RAW reads 100.

FAQ:

  • The number does not match a ruler? On EV3, 1 unit = 1.2 cm (for example 25 = 30 cm); 100 means nothing within 120 cm ahead.
  • The number stays at 0 or never changes? Turn the EV3 on before plugging in the sensor, or unplug and plug it back in; make sure there is no protective film over the laser.

Example 2: Stop 30 cm before the wall

What this example does: The robot drives forward and stops when something is within 30 cm (sensor value 25).

What you need:

  • EV3 brick + Education base robot (left wheel on B, right wheel on C)
  • TOF2 dual-eye laser (EV3 edition)
  • A box or wall as an obstacle

How to connect: TOF2 dual-eye laser in port 1, mounted at the front with the lasers facing straight ahead, about 5 cm above the ground.

Download the program (pick your software):

⬇ EV3-G (official software) | ⬇ EV3 Classroom | ⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0 | ⬇ clev3r

EV3-G (official software) blocks

TOF2 dual-eye laser Stop 30 cm before the wall(EV3-G (official software))

(Too small? Click the picture to open it full size.)

EV3 Classroom blocks

TOF2 dual-eye laser Stop 30 cm before the wall(EV3 Classroom)

(Too small? Click the picture to open it full size.)

Pybricks v4 code
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 02:前方 30 公分停車
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:車子往前開,看到前面 30 公分(感應器數字 25)以內有東西就停下來。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = LUMPDevice(Port.S1)       # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read(0)[0]


# ---------- 程式從這裡開始 ----------
# 兩輪用 30 的力量往前開
left_motor.dc(30)
right_motor.dc(30)
# 等到距離小於 25(約 30 公分)
while not (read_dist() < 25):
    wait(10)
# 停車
left_motor.brake()
right_motor.brake()
# 嗶一聲
ev3.speaker.beep()
EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 02:前方 30 公分停車
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:車子往前開,看到前面 30 公分(感應器數字 25)以內有東西就停下來。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import Ev3devSensor
from pybricks.parameters import Port
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = Ev3devSensor(Port.S1)     # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read('IR-PROX')[0]


# ---------- 程式從這裡開始 ----------
# 兩輪用 30 的力量往前開
left_motor.dc(30)
right_motor.dc(30)
# 等到距離小於 25(約 30 公分)
while not (read_dist() < 25):
    wait(10)
# 停車
left_motor.brake()
right_motor.brake()
# 嗶一聲
ev3.speaker.beep()
clev3r code
' ============================================================
' TOF2 雙眼雷射測距感應器 EV3 新手範例 02:前方 30 公分停車
' 軟體:clev3r
' 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
' 這個範例會做什麼:車子往前開,看到前面 30 公分(感應器數字 25)以內有東西就停下來。
' 讀值:dist=左右兩眼的平均距離(0 ~ 100(1 格=1.2 公分,100=前面沒東西))
' ============================================================
folder "prjs" "MBC_tof2_ex02"

' TOF2 雙眼雷射插 1 號孔,使用模式 0
Sensor.SetMode(1, 0)
LCD.Clear()

' 兩輪用 30 的力量往前開
Motor.StartPower("B", 30)
Motor.StartPower("C", 30)
' 等到距離小於 25(約 30 公分)
While Sensor.ReadRawValue(1, 0) >= 25
  Program.Delay(10)
EndWhile
' 停車
Motor.Stop("BC", "True")
' 嗶一聲
Speaker.Tone(50, 1000, 100)
Speaker.Wait()

Step by step:

  1. Both wheels drive forward at power 30
  2. Wait until the distance is less than 25 (about 30 cm)
  3. Stop
  4. Beep

What you should see: The robot drives forward, stops about 30 cm from the obstacle and beeps.

FAQ:

  • It stops too late or hits the wall? A faster robot needs more braking distance: lower 30 or raise 25.
  • The number does not match a ruler? On EV3, 1 unit = 1.2 cm (for example 25 = 30 cm); 100 means nothing within 120 cm ahead.

Example 3: Obstacle avoider: back up and turn

What this example does: The robot keeps driving forward; when something is too close it backs up a little, spins a little, then carries on. Put it on the floor with some boxes and it finds its own way around.

What you need:

  • EV3 brick + Education base robot (left wheel on B, right wheel on C)
  • TOF2 dual-eye laser (EV3 edition)
  • A box or wall as an obstacle

How to connect: TOF2 dual-eye laser in port 1, mounted at the front with the lasers facing straight ahead, about 5 cm above the ground.

Download the program (pick your software):

⬇ EV3-G (official software) | ⬇ EV3 Classroom | ⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0 | ⬇ clev3r

EV3-G (official software) blocks

TOF2 dual-eye laser Obstacle avoider: back up and turn(EV3-G (official software))

(Too small? Click the picture to open it full size.)

EV3 Classroom blocks

TOF2 dual-eye laser Obstacle avoider: back up and turn(EV3 Classroom)

(Too small? Click the picture to open it full size.)

Pybricks v4 code
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 03:避障車:看到東西就後退轉彎
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:車子一直往前開,前面太近就後退一點、原地轉一下,再繼續往前。放在有箱子的地上,它會自己繞開。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = LUMPDevice(Port.S1)       # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read(0)[0]


# ---------- 程式從這裡開始 ----------
# 一直重複
while True:
    # 如果前面距離小於 25(約 30 公分)
    if read_dist() < 25:
        # 先後退
        left_motor.dc(-30)
        right_motor.dc(-30)
        # 退 0.5 秒
        wait(500)
        # 左輪往前、右輪往後:原地向右轉
        left_motor.dc(30)
        right_motor.dc(-30)
        # 轉 0.5 秒
        wait(500)
    else:
        # 前面沒東西:往前開
        left_motor.dc(30)
        right_motor.dc(30)
EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 03:避障車:看到東西就後退轉彎
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:車子一直往前開,前面太近就後退一點、原地轉一下,再繼續往前。放在有箱子的地上,它會自己繞開。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import Ev3devSensor
from pybricks.parameters import Port
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = Ev3devSensor(Port.S1)     # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read('IR-PROX')[0]


# ---------- 程式從這裡開始 ----------
# 一直重複
while True:
    # 如果前面距離小於 25(約 30 公分)
    if read_dist() < 25:
        # 先後退
        left_motor.dc(-30)
        right_motor.dc(-30)
        # 退 0.5 秒
        wait(500)
        # 左輪往前、右輪往後:原地向右轉
        left_motor.dc(30)
        right_motor.dc(-30)
        # 轉 0.5 秒
        wait(500)
    else:
        # 前面沒東西:往前開
        left_motor.dc(30)
        right_motor.dc(30)
clev3r code
' ============================================================
' TOF2 雙眼雷射測距感應器 EV3 新手範例 03:避障車:看到東西就後退轉彎
' 軟體:clev3r
' 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
' 這個範例會做什麼:車子一直往前開,前面太近就後退一點、原地轉一下,再繼續往前。放在有箱子的地上,它會自己繞開。
' 讀值:dist=左右兩眼的平均距離(0 ~ 100(1 格=1.2 公分,100=前面沒東西))
' ============================================================
folder "prjs" "MBC_tof2_ex03"

' TOF2 雙眼雷射插 1 號孔,使用模式 0
Sensor.SetMode(1, 0)
LCD.Clear()

' 一直重複
While "True"
  ' 如果前面距離小於 25(約 30 公分)
  If Sensor.ReadRawValue(1, 0) < 25 Then
    ' 先後退
    Motor.StartPower("B", -30)
    Motor.StartPower("C", -30)
    ' 退 0.5 秒
    Program.Delay(500)
    ' 左輪往前、右輪往後:原地向右轉
    Motor.StartPower("B", 30)
    Motor.StartPower("C", -30)
    ' 轉 0.5 秒
    Program.Delay(500)
  Else
    ' 前面沒東西:往前開
    Motor.StartPower("B", 30)
    Motor.StartPower("C", 30)
  EndIf
EndWhile

Step by step:

  1. Repeat forever
    • If the distance ahead is less than 25 (about 30 cm)
      • Back up first
      • Back up for 0.5 s
      • Left wheel forward, right wheel backward: spin right on the spot
      • Turn for 0.5 s
      • Otherwise:
        • Nothing ahead: drive forward

What you should see: The robot backs up and turns right when it meets an obstacle, then keeps going.

FAQ:

  • It does not turn enough and keeps hitting the same box? Make the 0.5 s turn longer (for example 0.8).
  • The number does not match a ruler? On EV3, 1 unit = 1.2 cm (for example 25 = 30 cm); 100 means nothing within 120 cm ahead.

Example 4: Follow the leader: keep a fixed distance

What this example does: Hold a book in front of the robot: move it forward and the robot follows, push it back and the robot reverses, always keeping about 30 cm. This is proportional control: "correct by as much as the error".

What you need:

  • EV3 brick + Education base robot (left wheel on B, right wheel on C)
  • TOF2 dual-eye laser (EV3 edition)
  • A book or a board

How to connect: TOF2 dual-eye laser in port 1, mounted at the front with the lasers facing straight ahead, about 5 cm above the ground.

Download the program (pick your software):

⬇ EV3-G (official software) | ⬇ EV3 Classroom | ⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0 | ⬇ clev3r

EV3-G (official software) blocks

TOF2 dual-eye laser Follow the leader: keep a fixed distance(EV3-G (official software))

(Too small? Click the picture to open it full size.)

EV3 Classroom blocks

TOF2 dual-eye laser Follow the leader: keep a fixed distance(EV3 Classroom)

(Too small? Click the picture to open it full size.)

Pybricks v4 code
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 04:跟車:保持固定距離
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:拿一本書放在車子前面,往前移車子就跟上、往後推車子就退後,一直保持約 30 公分。用的是「差多少就補多少」的比例控制。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = LUMPDevice(Port.S1)       # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read(0)[0]


# ---------- 程式從這裡開始 ----------
# 一直重複
while True:
    # 馬達力量 power =(距離 − 25)× 2:太遠是正數往前、太近是負數往後
    power = (read_dist() - 25) * 2
    # 如果 power 大於 50
    if power > 50:
        # 最快只用 50,比較安全
        power = 50
    # 兩輪用 power 一起前進或後退
    left_motor.dc(power)
    right_motor.dc(power)
EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 04:跟車:保持固定距離
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:拿一本書放在車子前面,往前移車子就跟上、往後推車子就退後,一直保持約 30 公分。用的是「差多少就補多少」的比例控制。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import Ev3devSensor
from pybricks.parameters import Port
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = Ev3devSensor(Port.S1)     # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_dist():
    # 左右兩眼的平均距離:0 ~ 100(1 格=1.2 公分,100=前面沒東西)
    return sensor.read('IR-PROX')[0]


# ---------- 程式從這裡開始 ----------
# 一直重複
while True:
    # 馬達力量 power =(距離 − 25)× 2:太遠是正數往前、太近是負數往後
    power = (read_dist() - 25) * 2
    # 如果 power 大於 50
    if power > 50:
        # 最快只用 50,比較安全
        power = 50
    # 兩輪用 power 一起前進或後退
    left_motor.dc(power)
    right_motor.dc(power)
clev3r code
' ============================================================
' TOF2 雙眼雷射測距感應器 EV3 新手範例 04:跟車:保持固定距離
' 軟體:clev3r
' 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
' 這個範例會做什麼:拿一本書放在車子前面,往前移車子就跟上、往後推車子就退後,一直保持約 30 公分。用的是「差多少就補多少」的比例控制。
' 讀值:dist=左右兩眼的平均距離(0 ~ 100(1 格=1.2 公分,100=前面沒東西))
' ============================================================
folder "prjs" "MBC_tof2_ex04"

' TOF2 雙眼雷射插 1 號孔,使用模式 0
Sensor.SetMode(1, 0)
LCD.Clear()

' 一直重複
While "True"
  ' 馬達力量 power =(距離 − 25)× 2:太遠是正數往前、太近是負數往後
  power = (Sensor.ReadRawValue(1, 0) - 25) * 2
  ' 如果 power 大於 50
  If power > 50 Then
    ' 最快只用 50,比較安全
    power = 50
  EndIf
  ' 兩輪用 power 一起前進或後退
  Motor.StartPower("B", power)
  Motor.StartPower("C", power)
EndWhile

Step by step:

  1. Repeat forever
    • Motor power = (distance − 25) × 2: too far is positive (forward), too close is negative (backward)
    • If power is greater than 50
      • Limit it to 50 to be safe
    • Both wheels drive forward or backward with power

What you should see: Book forward, robot follows; book back, robot reverses; book still, robot stops at about 30 cm. With nothing ahead the robot drives forward at power 50.

FAQ:

  • The robot shakes back and forth around the target? Lower × 2 (for example × 1).
  • The number does not match a ruler? On EV3, 1 unit = 1.2 cm (for example 25 = 30 cm); 100 means nothing within 120 cm ahead.

Example 5: Left eye, right eye: dodge obstacles on both sides

What this example does: The dual-eye laser reads the left and right eyes separately. Too close on the left means swerve right, too close on the right means swerve left, nothing means go straight.

What you need:

  • EV3 brick + Education base robot (left wheel on B, right wheel on C)
  • TOF2 dual-eye laser (EV3 edition)
  • A box or wall as an obstacle

How to connect: TOF2 dual-eye laser in port 1, mounted at the front with the lasers facing straight ahead, about 5 cm above the ground. Left and right are as seen from behind the sensor, looking the way it faces (left = J5, right = J3).

Download the program (pick your software):

⬇ EV3-G (official software) | ⬇ EV3 Classroom | ⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0 | ⬇ clev3r

EV3-G (official software) blocks

TOF2 dual-eye laser Left eye, right eye: dodge obstacles on both sides(EV3-G (official software))

(Too small? Click the picture to open it full size.)

EV3 Classroom blocks

TOF2 dual-eye laser Left eye, right eye: dodge obstacles on both sides(EV3 Classroom)

(Too small? Click the picture to open it full size.)

Pybricks v4 code
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 05:左眼右眼:閃開兩邊的障礙物
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:雙眼雷射可以分別讀左眼和右眼。左邊太近就往右閃,右邊太近就往左閃,都沒東西就直走。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port, Color
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = LUMPDevice(Port.S1)       # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_left():
    # 左眼距離:0 ~ 100(1 格=1.2 公分)
    return sensor.read(1)[0]


def read_right():
    # 右眼距離:0 ~ 100(1 格=1.2 公分)
    return sensor.read(1)[1]


# ---------- 程式從這裡開始 ----------
# 一直重複
while True:
    # 螢幕第 1 行顯示左眼距離
    ev3.screen.draw_text(0, 0, "LEFT " + str(read_left()) + "      ", Color.BLACK, Color.WHITE)
    # 螢幕第 2 行顯示右眼距離
    ev3.screen.draw_text(0, 16, "RIGHT " + str(read_right()) + "      ", Color.BLACK, Color.WHITE)
    # 如果左眼距離小於 25
    if read_left() < 25:
        # 左邊太近:左輪轉、右輪停,車子往右閃
        left_motor.dc(30)
        right_motor.dc(0)
    # 否則,如果右眼距離小於 25
    elif read_right() < 25:
        # 右邊太近:往左閃
        left_motor.dc(0)
        right_motor.dc(30)
    else:
        # 兩邊都沒東西:直走
        left_motor.dc(30)
        right_motor.dc(30)
EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 05:左眼右眼:閃開兩邊的障礙物
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:雙眼雷射可以分別讀左眼和右眼。左邊太近就往右閃,右邊太近就往左閃,都沒東西就直走。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import Ev3devSensor
from pybricks.parameters import Port, Color
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = Ev3devSensor(Port.S1)     # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_left():
    # 左眼距離:0 ~ 100(1 格=1.2 公分)
    return sensor.read('IR-SEEK')[0]


def read_right():
    # 右眼距離:0 ~ 100(1 格=1.2 公分)
    return sensor.read('IR-SEEK')[1]


# ---------- 程式從這裡開始 ----------
# 一直重複
while True:
    # 螢幕第 1 行顯示左眼距離
    ev3.screen.draw_text(0, 0, "LEFT " + str(read_left()) + "      ", Color.BLACK, Color.WHITE)
    # 螢幕第 2 行顯示右眼距離
    ev3.screen.draw_text(0, 16, "RIGHT " + str(read_right()) + "      ", Color.BLACK, Color.WHITE)
    # 如果左眼距離小於 25
    if read_left() < 25:
        # 左邊太近:左輪轉、右輪停,車子往右閃
        left_motor.dc(30)
        right_motor.dc(0)
    # 否則,如果右眼距離小於 25
    elif read_right() < 25:
        # 右邊太近:往左閃
        left_motor.dc(0)
        right_motor.dc(30)
    else:
        # 兩邊都沒東西:直走
        left_motor.dc(30)
        right_motor.dc(30)
clev3r code
' ============================================================
' TOF2 雙眼雷射測距感應器 EV3 新手範例 05:左眼右眼:閃開兩邊的障礙物
' 軟體:clev3r
' 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
' 這個範例會做什麼:雙眼雷射可以分別讀左眼和右眼。左邊太近就往右閃,右邊太近就往左閃,都沒東西就直走。
' 讀值:left=左眼距離(0 ~ 100(1 格=1.2 公分));right=右眼距離(0 ~ 100(1 格=1.2 公分))
' ============================================================
folder "prjs" "MBC_tof2_ex05"

' TOF2 雙眼雷射插 1 號孔,使用模式 1
Sensor.SetMode(1, 1)
LCD.Clear()

' 一直重複
While "True"
  ' 螢幕第 1 行顯示左眼距離
  LCD.Text(1, 0, 0, 1, "LEFT " + Sensor.ReadRawValue(1, 0) + "      ")
  ' 螢幕第 2 行顯示右眼距離
  LCD.Text(1, 0, 16, 1, "RIGHT " + Sensor.ReadRawValue(1, 1) + "      ")
  ' 如果左眼距離小於 25
  If Sensor.ReadRawValue(1, 0) < 25 Then
    ' 左邊太近:左輪轉、右輪停,車子往右閃
    Motor.StartPower("B", 30)
    Motor.StartPower("C", 0)
  ' 否則,如果右眼距離小於 25
  ElseIf Sensor.ReadRawValue(1, 1) < 25 Then
    ' 右邊太近:往左閃
    Motor.StartPower("B", 0)
    Motor.StartPower("C", 30)
  Else
    ' 兩邊都沒東西:直走
    Motor.StartPower("B", 30)
    Motor.StartPower("C", 30)
  EndIf
EndWhile

Step by step:

  1. Repeat forever
    • Screen row 1 shows the left eye distance
    • Screen row 2 shows the right eye distance
    • If the left eye distance is less than 25
      • Too close on the left: left wheel runs, right wheel stops, the robot swerves right
      • Otherwise:
        • Otherwise, if the right eye distance is less than 25
          • Too close on the right: swerve left
          • Otherwise:
            • Nothing on either side: go straight

What you should see: Cover the left eye with your hand and the robot turns right; cover the right eye and it turns left; cover nothing and it goes straight.

FAQ:

  • Left and right are swapped? Left and right are as seen from behind the robot, looking the same way as the sensor (left = J5, right = J3); facing the sensor, they are the other way round. If they are still swapped, the sensor may be mounted backwards (lasers facing back or upside down), or swap the numbers in the two tank steps.
  • The number does not match a ruler? On EV3, 1 unit = 1.2 cm (for example 25 = 30 cm); 100 means nothing within 120 cm ahead.

Example 6: Stop precisely in millimetres: stop 20 cm before the wall

Pybricks v4 / EV3 MicroPython v2.0 / clev3r only (the EV3-G and Classroom blocks cannot read this mode)

What this example does: In mode 0 one unit is 1.2 cm, not precise enough to stop at "exactly 20 cm". Mode 5 gives the left and right eye in millimetres (1 unit = 1 mm): this example averages the two (the same as mode 3), drives forward showing millimetres and stops below 200 mm. It uses mode 5 because on the stock EV3 firmware switching to mode 3 sometimes fails, while mode 5 always switches.

What you need:

  • EV3 brick + Education base robot (left wheel on B, right wheel on C)
  • TOF2 dual-eye laser (EV3 edition, firmware v4.0 or later)
  • A box or wall as an obstacle

How to connect: TOF2 dual-eye laser in port 1, mounted at the front with the lasers facing straight ahead, about 5 cm above the ground.

Download the program (pick your software):

⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0 | ⬇ clev3r

(The code is the example; no screenshot needed.)

Pybricks v4 code
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 06:用公釐精準停車:20 公分前停
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:模式 0 的距離 1 格=1.2 公分,比賽要停在「剛好 20 公分」不夠準。模式 5 直接給左右兩眼的公釐(1 格=1 公釐),這個範例把兩眼平均(跟模式 3 一樣),一邊往前開一邊顯示公釐,小於 200 公釐就停。用模式 5 是因為 EV3 原廠韌體切到模式 3 偶爾切不過去,模式 5 每次都切得過去。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port, Color
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = LUMPDevice(Port.S1)       # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_leftMm():
    # 左眼距離(公釐):0 ~ 1200 mm
    return sensor.read(5)[0]


def read_rightMm():
    # 右眼距離(公釐):0 ~ 1200 mm
    return sensor.read(5)[1]


# ---------- 程式從這裡開始 ----------
# 清除螢幕
ev3.screen.clear()
# 兩輪用 30 的力量往前開
left_motor.dc(30)
right_motor.dc(30)
# mm = 左右兩眼公釐的平均(跟模式 3 一樣)
mm = (read_leftMm() + read_rightMm()) / 2
# 一直往前,直到距離小於 200 公釐(20 公分)
while not (mm < 200):
    # 第 1 行顯示目前距離(公釐)
    ev3.screen.draw_text(0, 0, "MM " + str(mm) + "      ", Color.BLACK, Color.WHITE)
    # 再讀一次左右兩眼,重新算平均
    mm = (read_leftMm() + read_rightMm()) / 2
# 停車
left_motor.brake()
right_motor.brake()
# 嗶一聲
ev3.speaker.beep()
# 停下來後再讀一次
mm = (read_leftMm() + read_rightMm()) / 2
# 停下來後再顯示一次距離,看停得準不準
ev3.screen.draw_text(0, 0, "MM " + str(mm) + "      ", Color.BLACK, Color.WHITE)
EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# TOF2 雙眼雷射測距感應器 EV3 新手範例 06:用公釐精準停車:20 公分前停
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:模式 0 的距離 1 格=1.2 公分,比賽要停在「剛好 20 公分」不夠準。模式 5 直接給左右兩眼的公釐(1 格=1 公釐),這個範例把兩眼平均(跟模式 3 一樣),一邊往前開一邊顯示公釐,小於 200 公釐就停。用模式 5 是因為 EV3 原廠韌體切到模式 3 偶爾切不過去,模式 5 每次都切得過去。
# ============================================================

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.iodevices import Ev3devSensor
from pybricks.parameters import Port, Color
from pybricks.tools import wait

ev3 = EV3Brick()
sensor = Ev3devSensor(Port.S1)     # TOF2 雙眼雷射插 1 號孔
left_motor = Motor(Port.B)        # 左輪
right_motor = Motor(Port.C)       # 右輪


def read_leftMm():
    # 左眼距離(公釐):0 ~ 1200 mm
    return sensor.read('IR-CAL')[0]


def read_rightMm():
    # 右眼距離(公釐):0 ~ 1200 mm
    return sensor.read('IR-CAL')[1]


# ---------- 程式從這裡開始 ----------
# 清除螢幕
ev3.screen.clear()
# 兩輪用 30 的力量往前開
left_motor.dc(30)
right_motor.dc(30)
# mm = 左右兩眼公釐的平均(跟模式 3 一樣)
mm = (read_leftMm() + read_rightMm()) / 2
# 一直往前,直到距離小於 200 公釐(20 公分)
while not (mm < 200):
    # 第 1 行顯示目前距離(公釐)
    ev3.screen.draw_text(0, 0, "MM " + str(mm) + "      ", Color.BLACK, Color.WHITE)
    # 再讀一次左右兩眼,重新算平均
    mm = (read_leftMm() + read_rightMm()) / 2
# 停車
left_motor.brake()
right_motor.brake()
# 嗶一聲
ev3.speaker.beep()
# 停下來後再讀一次
mm = (read_leftMm() + read_rightMm()) / 2
# 停下來後再顯示一次距離,看停得準不準
ev3.screen.draw_text(0, 0, "MM " + str(mm) + "      ", Color.BLACK, Color.WHITE)
clev3r code
' ============================================================
' TOF2 雙眼雷射測距感應器 EV3 新手範例 06:用公釐精準停車:20 公分前停
' 軟體:clev3r
' 接法:TOF2 雙眼雷射插 1 號孔;左輪馬達接 B、右輪馬達接 C
' 這個範例會做什麼:模式 0 的距離 1 格=1.2 公分,比賽要停在「剛好 20 公分」不夠準。模式 5 直接給左右兩眼的公釐(1 格=1 公釐),這個範例把兩眼平均(跟模式 3 一樣),一邊往前開一邊顯示公釐,小於 200 公釐就停。用模式 5 是因為 EV3 原廠韌體切到模式 3 偶爾切不過去,模式 5 每次都切得過去。
' 讀值:leftMm=左眼距離(公釐)(0 ~ 1200 mm);rightMm=右眼距離(公釐)(0 ~ 1200 mm)
' ============================================================
folder "prjs" "MBC_tof2_ex06"

' TOF2 雙眼雷射插 1 號孔,使用模式 5
Sensor.SetMode(1, 5)
LCD.Clear()

' 清除螢幕
LCD.Clear()
' 兩輪用 30 的力量往前開
Motor.StartPower("B", 30)
Motor.StartPower("C", 30)
' mm = 左右兩眼公釐的平均(跟模式 3 一樣)
mm = (Sensor.ReadRawValue(1, 0) + Sensor.ReadRawValue(1, 1)) / 2
' 一直往前,直到距離小於 200 公釐(20 公分)
While mm >= 200
  ' 第 1 行顯示目前距離(公釐)
  LCD.Text(1, 0, 0, 1, "MM " + mm + "      ")
  ' 再讀一次左右兩眼,重新算平均
  mm = (Sensor.ReadRawValue(1, 0) + Sensor.ReadRawValue(1, 1)) / 2
EndWhile
' 停車
Motor.Stop("BC", "True")
' 嗶一聲
Speaker.Tone(50, 1000, 100)
Speaker.Wait()
' 停下來後再讀一次
mm = (Sensor.ReadRawValue(1, 0) + Sensor.ReadRawValue(1, 1)) / 2
' 停下來後再顯示一次距離,看停得準不準
LCD.Text(1, 0, 0, 1, "MM " + mm + "      ")

Step by step:

  1. Clear the screen
  2. Both wheels drive forward at power 30
  3. mm = average of the left and right eye in mm (the same as mode 3)
  4. Keep driving until the distance is less than 200 mm (20 cm)
    • Row 1 shows the current distance (mm)
    • Read both eyes again and recompute the average
  5. Stop
  6. Beep
  7. Read once more after stopping
  8. Show the distance once more after stopping to check the accuracy

What you should see: The robot drives forward with the millimetre value falling, stops about 20 cm before the obstacle and beeps; the number shown after stopping should be close to 200.

FAQ:

  • The number after stopping is much lower than 200? A faster robot needs more braking distance: lower 30 or raise 200 (for example 230).
  • The number stays at 0 or never changes? This mode needs sensor firmware v4.0 (2026-10) or later; update older firmware first.
  • Why is there no EV3-G / Classroom version? This example uses a new mode (firmware v4, 2026-10). The EV3-G and Classroom infrared blocks cannot read it; only Pybricks, EV3 MicroPython and clev3r can.

Still stuck? Leave a message on Contact us with the software you use and a screenshot of your program, and we will help.

Email for a quoteBuying Guide