IMU 9-Axis Gyro × EV3 × Pybricks
Interactive tutorialEV3
First time? Try the interactive tutorial in your browser first, then follow the steps below with your hub.
This page covers Pybricks v4 / EV3 MicroPython v2 only: how to set it up for the IMU 9-Axis Gyro on MINDSTORMS EV3, how to read every value, the commands it supports and examples. Use the switcher above to change product, host or software.
Setup
What you need
- Sensor: IMU 9-Axis Gyro (EV3 edition, RJ12 plug).
- Brick: LEGO MINDSTORMS EV3.
- Software (pick one):
- Pybricks v4: open code.pybricks.com in Chrome; the EV3 needs the Pybricks firmware first (the stable release now includes EV3 firmware, v4.1.1 as of 2026-10).
- EV3 MicroPython v2.0: the official LEGO "EV3 MicroPython" microSD boot card + the "LEGO MINDSTORMS EV3 MicroPython" extension for VS Code. Pick this if you already use it.
Install the software
Pybricks v4
- Open code.pybricks.com in Chrome.
- Follow the website to switch the EV3 to Pybricks firmware. The stable code.pybricks.com now includes EV3 firmware (v4.1.1 as of 2026-10). The examples on this site were first bench-tested on v4.0.0b10; v4.1.1 uses the same code.
- To open an example: drag the
.pyfile into the editor and press Run.
EV3 MicroPython v2.0
- Boot the EV3 from the official LEGO EV3 MicroPython microSD card.
- Install the "LEGO MINDSTORMS EV3 MicroPython" extension in VS Code.
- To open an example: paste the program into
main.pyand press F5 to download and run.
Make the software see the sensor
The beginner examples need no library; they read the sensor data directly:
- Pybricks v4 uses
LUMPDevice(Port.S1);sensor.read(mode)returns that mode's values. - EV3 MicroPython v2.0: always read with
Ev3devSensor. For products that show up as an infrared sensor, do not useInfraredSensor: every mode change waits about 1.1 s, andbuttons()/beacon()/keypad()raise errors or change the values. - Both can read modes that EV3-G and Classroom cannot, so examples marked "Pybricks / EV3 MicroPython / clev3r only" run here too.
Important
Do not switch modes often inside the main loop. The EV3 hardware adds a communication wait every time a sensor mode changes. Pick one mode for the task and keep it for the whole run.
Wiring
- Plug the sensor into EV3 port 1 with the cable (any of 1
4 works; use the same port asPort.S1Port.S4in the program). - Turn the EV3 on first, then plug in the sensor.
- Latch up, push the plug in gently.
Note
The EV3 treats the IMU as an original gyro sensor; the examples read it with
GyroSensor.Tested on Pybricks v4 (2026-11-02, 11/11 checks):
angle()andreset_angle(0)work normally.speed()returns the magnetometer heading (not degrees per second); for angular rate, read mode 2 withLUMPDevice(see example 7 in the EV3 beginner examples). Aftercalibrate()it takes about 3.5 s before readings come back (same as the LEGO gyro).
First test
- Open example 1 on this page and run it (F5 for the MicroPython version).
- If the number on the EV3 screen changes with what is in front of the sensor, everything is connected.
FAQ
- Cannot find Pybricks firmware for the EV3? Use the stable code.pybricks.com (EV3 v4.1.1 built in since 2026-10); the old ev3dev-based Pybricks (microSD card) is a different system and does not apply here.
- The number never changes? Unplug the sensor and plug it back in (the EV3 must be on first).
- The program reacts unevenly? The main loop reads different modes in turn and waits at every switch. Use one mode only.
- Error when importing a library? The library file must be imported into the same Pybricks project, and its file name must match the
importname exactly.
Reading values
Code assumes port 1 and reads raw modes with LUMPDevice; EV3 MicroPython v2 works the same way.
gyro 3D heading headingGyro3D
| Range | Meaning |
|---|---|
-32768~32767 ° |
heading from the 3D quaternion, degrees, 0 at boot/zero, accumulates past 360 (wraps at ±32767, ~91 turns) |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
headingGyro3D = sensor.read(0)[0] # gyro 3D heading:-32768~32767 °mode 0 · int16 · GYRO-ANG 1×int16(盤點:mode0 = 陀螺 3D,INO:232-234) (locked mode: firmware and hosts will not change it)
fused heading headingFused
| Range | Meaning |
|---|---|
-32768~32767 ° |
3D gyro heading slowly corrected by the magnetometer, degrees, relative to the zero point; may exceed 360 |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
headingFused = sensor.read(1)[0] # fused heading:-32768~32767 °mode 1 · int16 · GYRO-RATE 1×int16 = 融合航向(EV3 定案:不改) (locked mode: firmware and hosts will not change it)
gyro 1D heading headingGyro1D
| Range | Meaning |
|---|---|
-32768~32767 ° |
heading integrated about the yaw axis only, degrees, 0 at boot/zero; may exceed 360 |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
headingGyro1D = sensor.read(3)[0] # gyro 1D heading:-32768~32767 °mode 3 · int16 · GYRO-G&A 2×int16 [陀螺 1D, 磁力航向] (locked mode: firmware and hosts will not change it)
magnetic heading headingMag
| Range | Meaning |
|---|---|
-32768~32767 ° |
tilt-compensated magnetometer heading, degrees, relative to the zero point |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
headingMag = sensor.read(3)[1] # magnetic heading:-32768~32767 °mode 3 · int16 (locked mode: firmware and hosts will not change it)
yaw rate yawRate
| Range | Meaning |
|---|---|
-32768~32767 0.1 dps |
angular rate about the yaw axis (getYawAxis()), 0.1 deg/s, same sign as the heading |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
yawRate = sensor.read(2)[0] # yaw rate:-32768~32767 0.1 dpsmode 2 · int16 · GYRO-FAS 1×int16(#67 新增,原本 0)
pitch angle pitch
| Range | Meaning |
|---|---|
-90~+90 ° |
elevation of the board's printed X axis above horizontal: +90 pointing up, −90 pointing down, 0 level (from the gravity vector) |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
pitch = sensor.read(6)[0] # pitch angle:-90~+90 °mode 6 · int16 · TILT-ANG 1×int16(#67 新增,原本 0)
pitch rate pitchRate
| Range | Meaning |
|---|---|
-32768~32767 0.1 dps |
angular rate about the board's printed X axis, 0.1 °/s (right-hand rule, CCW seen from +X is positive); this is gyro X, not the derivative of 06 |
from pybricks.iodevices import LUMPDevice
from pybricks.parameters import Port
sensor = LUMPDevice(Port.S1) # sensor on port 1
pitchRate = sensor.read(5)[0] # pitch rate:-32768~32767 0.1 dpsmode 5 · int16 · TILT-RATE 1×int16(#67:取代 #65 統一時放的 ID,ID 移到模式 4)
Not readable here:magnetometer trust, magnetic disturbance, face up, gyro axis 1~3, accel axis 1~3, mag axis 1~3, command status. Use Arduino / mBlock / micro:bit for these.
Commands
The EV3 port is read-only, so this software cannot send commands: calibrate with the button on the sensor and change settings over Arduino I2C, mBlock or micro:bit.
Examples
Example 1: See how far the robot has turned
What this example does: The angle is reset to 0 when the program starts; turn the robot by hand and the screen shows how many degrees it has turned.
What you need:
- IMU gyro (EV3 edition)
- EV3 brick
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 01:看看機器人轉了幾度
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔
# 這個範例會做什麼:程式開始時角度歸零,然後用手轉動機器人,螢幕會顯示轉了幾度。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import GyroSensor
from pybricks.parameters import Port, Color
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 先把角度歸零(這時候不要動機器人)
gyro.reset_angle(0)
# 清除螢幕
ev3.screen.clear()
# 一直重複
while True:
# 螢幕第 1 行顯示目前角度
ev3.screen.draw_text(0, 0, "ANGLE " + str(read_angle()) + " ", Color.BLACK, Color.WHITE)
# 等 0.1 秒
wait(100)EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 01:看看機器人轉了幾度
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔
# 這個範例會做什麼:程式開始時角度歸零,然後用手轉動機器人,螢幕會顯示轉了幾度。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import GyroSensor
from pybricks.parameters import Port, Color
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 先把角度歸零(這時候不要動機器人)
gyro.reset_angle(0)
# 清除螢幕
ev3.screen.clear()
# 一直重複
while True:
# 螢幕第 1 行顯示目前角度
ev3.screen.draw_text(0, 0, "ANGLE " + str(read_angle()) + " ", Color.BLACK, Color.WHITE)
# 等 0.1 秒
wait(100)Step by step:
- Reset the angle to 0 first (do not move the robot now)
- Clear the screen
- Repeat forever
- Screen row 1 shows the current angle
- Wait 0.1 s
What you should see: One full turn is about 360; turning the other way goes negative. Turn back to where you started and the number returns to about 0.
FAQ:
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
- The angle changes the opposite way to what the example says? The sensor may be mounted upside down. Examples 2 and 3 use the absolute value so they are not affected; for examples 4 and 5 swap "+" and "−" in the program.
Example 2: Turn right 90 degrees on the spot
What this example does: Turning with the gyro is much more accurate than "turn for N seconds": keep turning until the angle reaches 90, then stop.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition)
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 02:原地右轉 90 度
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:靠陀螺儀轉彎,比「轉幾秒」準很多:一直轉,直到角度到 90 度才停。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零
gyro.reset_angle(0)
# 左輪往前、右輪往後:原地向右轉(慢一點比較準)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度的絕對值大於等於 90
while not (abs(read_angle()) >= 90):
wait(10)
# 轉到 90 度:停車
left_motor.brake()
right_motor.brake()
# 嗶一聲
ev3.speaker.beep()EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 02:原地右轉 90 度
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:靠陀螺儀轉彎,比「轉幾秒」準很多:一直轉,直到角度到 90 度才停。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零
gyro.reset_angle(0)
# 左輪往前、右輪往後:原地向右轉(慢一點比較準)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度的絕對值大於等於 90
while not (abs(read_angle()) >= 90):
wait(10)
# 轉到 90 度:停車
left_motor.brake()
right_motor.brake()
# 嗶一聲
ev3.speaker.beep()Step by step:
- Reset the angle to 0
- Left wheel forward, right wheel backward: spin right on the spot (slower is more accurate)
- Wait until the absolute value of the angle is 90 or more
- Reached 90 degrees: stop
- Beep
What you should see: The robot spins right about 90 degrees, stops and beeps.
FAQ:
- It always overshoots by a few degrees? The robot needs a moment to stop. Try 85 instead of 90, or lower the turning speed 20.
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
- The angle changes the opposite way to what the example says? The sensor may be mounted upside down. Examples 2 and 3 use the absolute value so they are not affected; for examples 4 and 5 swap "+" and "−" in the program.
Example 3: Drive a square
What this example does: Repeat "drive straight 2 s + turn right 90 degrees" 4 times and you get a square.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition)
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 03:走正方形
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:把「直走 2 秒+右轉 90 度」重複 4 次,就是一個正方形。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 下面的動作重複 4 次
for i in range(4):
# 直走
left_motor.dc(30)
right_motor.dc(30)
# 走 2 秒
wait(2000)
# 停一下
left_motor.brake()
right_motor.brake()
# 角度歸零
gyro.reset_angle(0)
# 左輪往前、右輪往後:原地向右轉(慢一點比較準)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度的絕對值大於等於 90
while not (abs(read_angle()) >= 90):
wait(10)
# 轉到 90 度:停車
left_motor.brake()
right_motor.brake()
# 走完嗶一聲
ev3.speaker.beep()EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 03:走正方形
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:把「直走 2 秒+右轉 90 度」重複 4 次,就是一個正方形。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 下面的動作重複 4 次
for i in range(4):
# 直走
left_motor.dc(30)
right_motor.dc(30)
# 走 2 秒
wait(2000)
# 停一下
left_motor.brake()
right_motor.brake()
# 角度歸零
gyro.reset_angle(0)
# 左輪往前、右輪往後:原地向右轉(慢一點比較準)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度的絕對值大於等於 90
while not (abs(read_angle()) >= 90):
wait(10)
# 轉到 90 度:停車
left_motor.brake()
right_motor.brake()
# 走完嗶一聲
ev3.speaker.beep()Step by step:
- Repeat the steps below 4 times
- Go straight
- Drive for 2 s
- Stop for a moment
- Reset the angle to 0
- Left wheel forward, right wheel backward: spin right on the spot (slower is more accurate)
- Wait until the absolute value of the angle is 90 or more
- Reached 90 degrees: stop
- Beep when done
What you should see: The robot drives a square and ends up near where it started.
FAQ:
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
- The angle changes the opposite way to what the example says? The sensor may be mounted upside down. Examples 2 and 3 use the absolute value so they are not affected; for examples 4 and 5 swap "+" and "−" in the program.
Example 4: Drive straight with automatic correction
What this example does: Two wheels are never exactly the same speed, so a robot drifts when driving straight. Use the gyro to see how many degrees it drifted and steer back the other way, and the robot drives really straight.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition)
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 04:走直線自動修正
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:兩個輪子不可能完全一樣快,車子直走久了會歪。用陀螺儀看歪了幾度,就往反方向補回來,車子就能走得很直。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零:現在的方向就是「正前方」
gyro.reset_angle(0)
# 一直重複
while True:
# 修正力量 fix = 角度 × 2
fix = read_angle() * 2
# 往右歪(角度變大):左輪減速、右輪加速,把車頭拉回來
left_motor.dc(30 - fix)
right_motor.dc(30 + fix)EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 04:走直線自動修正
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:兩個輪子不可能完全一樣快,車子直走久了會歪。用陀螺儀看歪了幾度,就往反方向補回來,車子就能走得很直。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零:現在的方向就是「正前方」
gyro.reset_angle(0)
# 一直重複
while True:
# 修正力量 fix = 角度 × 2
fix = read_angle() * 2
# 往右歪(角度變大):左輪減速、右輪加速,把車頭拉回來
left_motor.dc(30 - fix)
right_motor.dc(30 + fix)Step by step:
- Reset the angle: the current heading is "straight ahead"
- Repeat forever
- Correction fix = angle × 2
- Drifting right (angle grows): slow the left wheel, speed up the right wheel to pull the nose back
What you should see: The robot drives straight; push its nose off course by hand and it turns back to the original heading and carries on.
FAQ:
- It drifts more and more, or even spins? The correction is the wrong way round: swap "30 − fix" and "30 + fix".
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
- The angle changes the opposite way to what the example says? The sensor may be mounted upside down. Examples 2 and 3 use the absolute value so they are not affected; for examples 4 and 5 swap "+" and "−" in the program.
Example 5: Compass that will not give up: turns itself back to the original heading
What this example does: The robot sits still. Turn it away by hand and it turns itself back to the original heading. This is the basic "turn back to straight ahead" used in competitions.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition)
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 05:不倒的指南針:自己轉回原來的方向
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:車子停在原地。你用手把它轉走,它會自己原地轉回原來的方向。這就是比賽中「轉回正前方」的基本做法。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零:記住現在的方向
gyro.reset_angle(0)
# 一直重複
while True:
# 修正力量 fix = 角度 × 1:轉走越多,轉回來越用力
fix = read_angle() * 1
# 左輪=-fix、右輪=+fix:原地往反方向轉回去
left_motor.dc(0 - fix)
right_motor.dc(fix)EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 05:不倒的指南針:自己轉回原來的方向
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:車子停在原地。你用手把它轉走,它會自己原地轉回原來的方向。這就是比賽中「轉回正前方」的基本做法。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零:記住現在的方向
gyro.reset_angle(0)
# 一直重複
while True:
# 修正力量 fix = 角度 × 1:轉走越多,轉回來越用力
fix = read_angle() * 1
# 左輪=-fix、右輪=+fix:原地往反方向轉回去
left_motor.dc(0 - fix)
right_motor.dc(fix)Step by step:
- Reset the angle: remember the current heading
- Repeat forever
- Correction fix = angle × 1: the further it is turned away, the harder it turns back
- Left wheel = −fix, right wheel = +fix: spin back the other way on the spot
What you should see: Turn the robot away by hand; let go and it turns back to the original heading and stops.
FAQ:
- It keeps spinning and never stops? The direction is reversed: swap "−fix" and "+fix".
- It shakes around the target? Lower × 1 (for example × 0.6).
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
- The angle changes the opposite way to what the example says? The sensor may be mounted upside down. Examples 2 and 3 use the absolute value so they are not affected; for examples 4 and 5 swap "+" and "−" in the program.
Example 6: Pitch angle: slow down on a slope
Pybricks v4 / EV3 MicroPython v2.0 / clev3r only (the EV3-G and Classroom blocks cannot read this mode)
What this example does: Mode 6 is the "pitch angle": how many degrees the nose is up or down, 0 when flat. The robot drives at speed 50 on flat ground and slows to 20 as soon as the pitch angle passes 8 degrees on a slope (up or down), so it is less likely to tip or run away.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition, firmware v4.0 or later)
- A ramp or a small slope made from books
How to connect: IMU gyro in port 1, mounted flat on the robot with the board's printed X axis parallel to the robot's forward direction.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
(The code is the example; no screenshot needed.)
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 06:俯仰角:上坡就減速
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:模式 6 是「俯仰角」:車頭上抬或下壓幾度,平放是 0。車子在平地用 50 的速度跑,一上坡(或下坡)俯仰角超過 8 度就放慢到 20,比較不會翻車或衝太快。
# ============================================================
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) # IMU 陀螺儀插 1 號孔(當一般 UART 裝置讀原始值)
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_tilt():
# 俯仰角(車頭上抬或下壓幾度):-90 ~ +90 度,平放=0(板子絲印 X 軸)
return sensor.read(6)[0]
# ---------- 程式從這裡開始 ----------
# 清除螢幕
ev3.screen.clear()
# 一直重複
while True:
# 第 1 行顯示俯仰角(度)
ev3.screen.draw_text(0, 0, "TILT " + str(read_tilt()) + " ", Color.BLACK, Color.WHITE)
# 如果俯仰角的絕對值大於 8 度
if abs(read_tilt()) > 8:
# 在坡上(俯仰角超過 8 度):放慢到 20
left_motor.dc(20)
right_motor.dc(20)
# 第 2 行顯示 SLOPE
ev3.screen.draw_text(0, 16, "SLOPE ", Color.BLACK, Color.WHITE)
else:
# 平地:用 50 往前開
left_motor.dc(50)
right_motor.dc(50)
# 第 2 行顯示 FLAT
ev3.screen.draw_text(0, 16, "FLAT ", Color.BLACK, Color.WHITE)EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 06:俯仰角:上坡就減速
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:模式 6 是「俯仰角」:車頭上抬或下壓幾度,平放是 0。車子在平地用 50 的速度跑,一上坡(或下坡)俯仰角超過 8 度就放慢到 20,比較不會翻車或衝太快。
# ============================================================
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) # IMU 陀螺儀插 1 號孔(當一般 UART 裝置讀原始值)
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_tilt():
# 俯仰角(車頭上抬或下壓幾度):-90 ~ +90 度,平放=0(板子絲印 X 軸)
return sensor.read('TILT-ANG')[0]
# ---------- 程式從這裡開始 ----------
# 清除螢幕
ev3.screen.clear()
# 一直重複
while True:
# 第 1 行顯示俯仰角(度)
ev3.screen.draw_text(0, 0, "TILT " + str(read_tilt()) + " ", Color.BLACK, Color.WHITE)
# 如果俯仰角的絕對值大於 8 度
if abs(read_tilt()) > 8:
# 在坡上(俯仰角超過 8 度):放慢到 20
left_motor.dc(20)
right_motor.dc(20)
# 第 2 行顯示 SLOPE
ev3.screen.draw_text(0, 16, "SLOPE ", Color.BLACK, Color.WHITE)
else:
# 平地:用 50 往前開
left_motor.dc(50)
right_motor.dc(50)
# 第 2 行顯示 FLAT
ev3.screen.draw_text(0, 16, "FLAT ", Color.BLACK, Color.WHITE)Step by step:
- Clear the screen
- Repeat forever
- Row 1 shows the pitch angle (degrees)
- If the absolute value of the pitch angle is greater than 8 degrees
- On a slope (pitch over 8 degrees): slow down to 20
- Row 2 shows SLOPE
- Otherwise:
- Flat ground: drive forward at 50
- Row 2 shows FLAT
What you should see: On flat ground the robot drives fast and the screen shows FLAT with an angle near 0; on the ramp the angle grows, SLOPE appears and the robot clearly slows down; back on flat ground it speeds up again.
FAQ:
- The angle is not 0 on flat ground? The sensor is not flat, or is mounted turned by 90 degrees (pitch uses the printed X axis of the board).
- Going uphill the angle is negative? Normal: the sign depends on how it is mounted. This example uses the absolute value, so it slows down both uphill and downhill.
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
- 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 gyro blocks cannot read it; only Pybricks, EV3 MicroPython and clev3r can.
Example 7: Warn when turning too fast
Pybricks v4 / EV3 MicroPython v2.0 / clev3r only (the EV3-G and Classroom blocks cannot read this mode)
What this example does: Mode 2 is the "turning rate": how many degrees per second the robot is turning right now (× 10). The angle tells you how far it turned; the rate tells you how fast. This example shows the rate and beeps when it is too high (over 90 degrees per second, i.e. 900), handy for checking whether the robot skids in turns.
What you need:
- IMU gyro (EV3 edition, firmware v4.0 or later)
- EV3 brick
How to connect: IMU gyro in port 1, mounted flat on the robot.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
(The code is the example; no screenshot needed.)
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 07:轉太快就警告
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔
# 這個範例會做什麼:模式 2 是「轉向角速度」:現在每秒轉幾度(×10)。角度告訴你轉了多少,角速度告訴你轉得多快。這個範例把角速度顯示出來,轉太快(超過每秒 90 度,也就是 900)就嗶一聲,可以拿來檢查機器人轉彎會不會甩尾。
# ============================================================
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) # IMU 陀螺儀插 1 號孔(當一般 UART 裝置讀原始值)
def read_rate():
# 轉向的角速度(每秒幾度 × 10):±3000 左右,正負跟角度同方向;100=每秒 10 度
return sensor.read(2)[0]
# ---------- 程式從這裡開始 ----------
# 清除螢幕
ev3.screen.clear()
# 一直重複
while True:
# 第 1 行顯示角速度(每秒幾度 × 10)
ev3.screen.draw_text(0, 0, "RATE " + str(read_rate()) + " ", Color.BLACK, Color.WHITE)
# 如果角速度的絕對值大於 900(每秒 90 度)
if abs(read_rate()) > 900:
# 轉太快(超過每秒 90 度):嗶一聲
ev3.speaker.beep()
# 等 0.1 秒
wait(100)EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 07:轉太快就警告
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔
# 這個範例會做什麼:模式 2 是「轉向角速度」:現在每秒轉幾度(×10)。角度告訴你轉了多少,角速度告訴你轉得多快。這個範例把角速度顯示出來,轉太快(超過每秒 90 度,也就是 900)就嗶一聲,可以拿來檢查機器人轉彎會不會甩尾。
# ============================================================
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) # IMU 陀螺儀插 1 號孔(當一般 UART 裝置讀原始值)
def read_rate():
# 轉向的角速度(每秒幾度 × 10):±3000 左右,正負跟角度同方向;100=每秒 10 度
return sensor.read('GYRO-FAS')[0]
# ---------- 程式從這裡開始 ----------
# 清除螢幕
ev3.screen.clear()
# 一直重複
while True:
# 第 1 行顯示角速度(每秒幾度 × 10)
ev3.screen.draw_text(0, 0, "RATE " + str(read_rate()) + " ", Color.BLACK, Color.WHITE)
# 如果角速度的絕對值大於 900(每秒 90 度)
if abs(read_rate()) > 900:
# 轉太快(超過每秒 90 度):嗶一聲
ev3.speaker.beep()
# 等 0.1 秒
wait(100)Step by step:
- Clear the screen
- Repeat forever
- Row 1 shows the turning rate (degrees per second × 10)
- If the absolute value of the rate is greater than 900 (90 degrees per second)
- Turning too fast (over 90 degrees per second): beep
- Wait 0.1 s
What you should see: With the robot still the number is near 0; turn it slowly by hand and it reads a few hundred; flick it quickly and it passes 900 with a beep. Turning the other way gives negative numbers.
FAQ:
- It beeps even when the robot is still? Raise 900, or check that the sensor is firmly mounted and not shaking.
- 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 gyro blocks cannot read it; only Pybricks, EV3 MicroPython and clev3r can.
Example 8: Turn to a set heading (absolute angle)
What this example does: Reset once when the program starts so "straight ahead" is 0 degrees, then never reset again: turn to 90, then 180, then back to 0. Every heading is measured from the starting direction, so the small overshoot of each turn does not add up turn after turn. This is the way most competition programs turn.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition)
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 08:轉到指定方向(絕對角度)
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:程式開始時歸零一次,記住「正前方」是 0 度,之後中間都不再歸零,依序轉到 90 度、180 度、再轉回 0 度。所有方向都以「開始時的正前方」為準,每次轉過頭的一點點誤差不會一次一次累加,比賽最常用這種寫法。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零:記住現在的方向是「正前方」0 度(只歸零這一次)
gyro.reset_angle(0)
# 如果現在的角度小於 90
if read_angle() < 90:
# 還沒到 90 度:原地向右轉(左輪往前、右輪往後)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 90
while not (read_angle() >= 90):
wait(10)
else:
# 超過 90 度:原地向左轉(左輪往後、右輪往前)
left_motor.dc(-20)
right_motor.dc(20)
# 等到角度小於等於 90
while not (read_angle() <= 90):
wait(10)
# 到 90 度:停車
left_motor.brake()
right_motor.brake()
# 停 1 秒
wait(1000)
# 如果現在的角度小於 180
if read_angle() < 180:
# 還沒到 180 度:原地向右轉(左輪往前、右輪往後)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 180
while not (read_angle() >= 180):
wait(10)
else:
# 超過 180 度:原地向左轉(左輪往後、右輪往前)
left_motor.dc(-20)
right_motor.dc(20)
# 等到角度小於等於 180
while not (read_angle() <= 180):
wait(10)
# 到 180 度:停車
left_motor.brake()
right_motor.brake()
# 停 1 秒
wait(1000)
# 如果現在的角度小於 0
if read_angle() < 0:
# 還沒到 0 度:原地向右轉(左輪往前、右輪往後)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 0
while not (read_angle() >= 0):
wait(10)
else:
# 超過 0 度:原地向左轉(左輪往後、右輪往前)
left_motor.dc(-20)
right_motor.dc(20)
# 等到角度小於等於 0
while not (read_angle() <= 0):
wait(10)
# 到 0 度:停車
left_motor.brake()
right_motor.brake()
# 停 1 秒
wait(1000)
# 轉完嗶一聲
ev3.speaker.beep()EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 08:轉到指定方向(絕對角度)
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:程式開始時歸零一次,記住「正前方」是 0 度,之後中間都不再歸零,依序轉到 90 度、180 度、再轉回 0 度。所有方向都以「開始時的正前方」為準,每次轉過頭的一點點誤差不會一次一次累加,比賽最常用這種寫法。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零:記住現在的方向是「正前方」0 度(只歸零這一次)
gyro.reset_angle(0)
# 如果現在的角度小於 90
if read_angle() < 90:
# 還沒到 90 度:原地向右轉(左輪往前、右輪往後)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 90
while not (read_angle() >= 90):
wait(10)
else:
# 超過 90 度:原地向左轉(左輪往後、右輪往前)
left_motor.dc(-20)
right_motor.dc(20)
# 等到角度小於等於 90
while not (read_angle() <= 90):
wait(10)
# 到 90 度:停車
left_motor.brake()
right_motor.brake()
# 停 1 秒
wait(1000)
# 如果現在的角度小於 180
if read_angle() < 180:
# 還沒到 180 度:原地向右轉(左輪往前、右輪往後)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 180
while not (read_angle() >= 180):
wait(10)
else:
# 超過 180 度:原地向左轉(左輪往後、右輪往前)
left_motor.dc(-20)
right_motor.dc(20)
# 等到角度小於等於 180
while not (read_angle() <= 180):
wait(10)
# 到 180 度:停車
left_motor.brake()
right_motor.brake()
# 停 1 秒
wait(1000)
# 如果現在的角度小於 0
if read_angle() < 0:
# 還沒到 0 度:原地向右轉(左輪往前、右輪往後)
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 0
while not (read_angle() >= 0):
wait(10)
else:
# 超過 0 度:原地向左轉(左輪往後、右輪往前)
left_motor.dc(-20)
right_motor.dc(20)
# 等到角度小於等於 0
while not (read_angle() <= 0):
wait(10)
# 到 0 度:停車
left_motor.brake()
right_motor.brake()
# 停 1 秒
wait(1000)
# 轉完嗶一聲
ev3.speaker.beep()Step by step:
- Reset the angle: the current direction is "straight ahead", 0 degrees (the only reset)
- If the angle is less than 90
- Not yet at 90 degrees: spin right on the spot (left wheel forward, right wheel back)
- Wait until the angle is 90 or more
- Otherwise:
- Past 90 degrees: spin left on the spot (left wheel back, right wheel forward)
- Wait until the angle is 90 or less
- At 90 degrees: stop
- Pause 1 s
- If the angle is less than 180
- Not yet at 180 degrees: spin right on the spot (left wheel forward, right wheel back)
- Wait until the angle is 180 or more
- Otherwise:
- Past 180 degrees: spin left on the spot (left wheel back, right wheel forward)
- Wait until the angle is 180 or less
- At 180 degrees: stop
- Pause 1 s
- If the angle is less than 0
- Not yet at 0 degrees: spin right on the spot (left wheel forward, right wheel back)
- Wait until the angle is 0 or more
- Otherwise:
- Past 0 degrees: spin left on the spot (left wheel back, right wheel forward)
- Wait until the angle is 0 or less
- At 0 degrees: stop
- Pause 1 s
- Beep when done
What you should see: The robot turns right to 90 degrees (facing right) and pauses 1 s, turns right again to 180 degrees (facing backwards) and pauses 1 s, then turns left back to 0 degrees, facing the starting direction again, and beeps. In tests it ends up within about ±3 degrees of the start.
FAQ:
- It always overshoots by a few degrees? The robot needs a moment to stop. Lower the turning speed 20 (for example to 15), or take a few degrees off the right-turn targets (for example 87 instead of 90, 177 instead of 180).
- It keeps spinning, or turns the wrong way? The sensor may be mounted upside down. Mount the IMU flat with its top side up, so that turning clockwise as seen from above (turning right) makes the angle bigger.
- Why not reset before every turn? Each reset turns the last overshoot into the new "straight ahead", so the error adds up turn after turn. Resetting only once at the start measures every heading from the starting direction, so the error does not build up.
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
Example 9: Turn another 90 degrees from where you are (relative angle)
What this example does: Reset once when the program starts, then repeat 4 times: read the angle "now", set the target to now + 90 degrees, and turn right until it is reached. Every turn starts from the current direction, which is easy to understand; but the overshoot of each turn carries over to the next. Compare it with the "absolute angle" of example 8 to see the difference.
What you need:
- EV3 brick + Education base robot (left wheel on B, right wheel on C)
- IMU gyro (EV3 edition)
How to connect: IMU gyro in port 1, mounted flat and firmly on the robot (no wobble). The robot must be still when the program starts.
Download the program (pick your software):
⬇ Pybricks v4 | ⬇ EV3 MicroPython v2.0
Pybricks v4 code
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 09:從現在的方向再轉 90 度(相對角度)
# 軟體:Pybricks v4(用 Chrome 打開 https://code.pybricks.com ,EV3 版目前是 Beta)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:程式開始時歸零一次,然後重複 4 次:先看「現在」的角度,目標就是現在再加 90 度,右轉到目標就停。每次都以「現在的方向」為準,寫法很直覺;但每次轉過頭的幾度會留到下一次,跟範例 8 的「絕對角度」比一比就知道差在哪。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零(這時候不要動機器人)
gyro.reset_angle(0)
# 下面的動作重複 4 次
for i in range(4):
# 目標 target = 現在的角度 + 90:以「現在」為準再轉 90 度
target = read_angle() + 90
# 左輪往前、右輪往後:原地向右轉
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 target
while not (read_angle() >= target):
wait(10)
# 轉到了:停車
left_motor.brake()
right_motor.brake()
# 停 0.5 秒
wait(500)
# 轉完 4 次嗶一聲
ev3.speaker.beep()EV3 MicroPython v2.0 code
#!/usr/bin/env pybricks-micropython
# ============================================================
# IMU 陀螺儀感應器 EV3 新手範例 09:從現在的方向再轉 90 度(相對角度)
# 軟體:樂高官方 EV3 MicroPython v2.0(microSD 開機卡+VS Code「LEGO MINDSTORMS EV3 MicroPython」擴充套件)
# 接法:IMU 陀螺儀插 1 號孔;左輪馬達接 B、右輪馬達接 C
# 這個範例會做什麼:程式開始時歸零一次,然後重複 4 次:先看「現在」的角度,目標就是現在再加 90 度,右轉到目標就停。每次都以「現在的方向」為準,寫法很直覺;但每次轉過頭的幾度會留到下一次,跟範例 8 的「絕對角度」比一比就知道差在哪。
# ============================================================
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, GyroSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ev3 = EV3Brick()
gyro = GyroSensor(Port.S1) # IMU 陀螺儀插 1 號孔
left_motor = Motor(Port.B) # 左輪
right_motor = Motor(Port.C) # 右輪
def read_angle():
# 機器人轉了幾度:連續累加(轉一圈=360,可超過 360)
return gyro.angle()
# ---------- 程式從這裡開始 ----------
# 角度歸零(這時候不要動機器人)
gyro.reset_angle(0)
# 下面的動作重複 4 次
for i in range(4):
# 目標 target = 現在的角度 + 90:以「現在」為準再轉 90 度
target = read_angle() + 90
# 左輪往前、右輪往後:原地向右轉
left_motor.dc(20)
right_motor.dc(-20)
# 等到角度大於等於 target
while not (read_angle() >= target):
wait(10)
# 轉到了:停車
left_motor.brake()
right_motor.brake()
# 停 0.5 秒
wait(500)
# 轉完 4 次嗶一聲
ev3.speaker.beep()Step by step:
- Reset the angle (keep the robot still)
- Repeat the steps below 4 times
- Target = current angle + 90: turn another 90 degrees from where you are now
- Left wheel forward, right wheel back: spin right on the spot
- Wait until the angle is target or more
- Reached it: stop
- Pause 0.5 s
- Beep after 4 turns
What you should see: The robot spins right 4 times, about 90 degrees each, and beeps after one full turn. Look closely at the final direction: it may be a few degrees off the starting direction.
FAQ:
- After 4 turns it is not exactly back to the starting direction? That is normal. The overshoot of each turn carries over to the next (the next turn adds 90 to the overshot direction), so after 4 turns it may be a few degrees off. To stop the error building up, use the "absolute angle" way of example 8: reset only at the start and use fixed targets 90, 180, 270, 360.
- It always overshoots by a few degrees? The robot needs a moment to stop. Lower the turning speed 20, or try + 87 instead of + 90.
- It keeps spinning and never stops? The sensor may be mounted upside down (the angle gets smaller when turning right). Mount the IMU flat with its top side up.
- The robot is still but the angle slowly drifts? The robot must be completely still at power-on or reset. Put it down, unplug the sensor and plug it back in, then try again.
Still stuck? Leave a message on Contact us with the software you use and a screenshot of your program, and we will help.
More questions
- The EV3 shows an infrared sensor? Expected: the sensor emulates a LEGO sensor so the stock blocks can read it.
- A short freeze when switching modes? The EV3 needs about 1 s per mode change. Stick to one mode during a run.
Still stuck? Contact us with your software and a screenshot of the program.
Downloads
Sources
- Host and software list:
_build/guides.json - Values and commands:
_build/protocol/imu.json(single source of truth) - Setup:
_build/guides/software/ev3-pybricks.en.md、_build/guides/product/imu/ev3-pybricks.en.md - Examples:
sensors/imu/ev3-examples.md