加速度計

加速度計

MicroPython 程式碼範例 運行在 Raspberry Pi Pico 2 W 微控制器上 在麵包板上,​​連接到三軸數位加速度計模組 (ADXL345) 和 OLED 顯示模組 (SSD1306)。 透過繞著 X 軸和 Y 軸旋轉加速度計,在 OLED 顯示器上繪製和旋轉 3D 形狀。

加速度計測量繞 x、y 和 z 軸的加速度. 在機器人學中,確定機器人的位置和運動至關重要。. 在這個腳本中,我們繪製一個三維形狀,並使用加速度計控制其旋轉。.

在 Thonny 中建立一個名為 accelerometer.py 的新檔案。. 將以下程式碼複製並貼上到您建立的文件中。.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
print("\nAccelerometer")

# DESCRIPTION

# An accelerometer measures acceleration around the x, y and z axis. 
# In robotics, it is essential in determining the robot position and movement.
# In this script, we draw a 3D shape, and control its rotation using the accelerometer.

# CONNECTIONS REQUIRED

# Connect ADXL345 module using only the 4 pins on the right side
#   Pins: GND => GND, VCC => VCC, SDA => GP6, SCL => GP7

from machine import Pin, SoftI2C
from oled import OLED
from adxl345 import ADXL345
from cube import Cube
from math import atan2, sqrt, degrees

accel = ADXL345(SoftI2C(sda=Pin(6), scl=Pin(7)))
oled = OLED(scl_pin=15, sda_pin=14)
cube = Cube(scaleX=1, scaleY=1.4, scaleZ=0.2)

try:
    while True:
                
        # Calculate pitch (rotation around y-axis, 360 degrees)
        # and roll (rotaton around x-axis, 180 degrees)
        # using x, y and z from the accelerometer.
        # Yaw (rotation around vertical z-axis) needs
        # a different sensor, a magnetometer or a gyroscope.        
        x, y, z = accel.read()
        pitch = atan2(-x, sqrt(y*y + z*z))
        roll = atan2(y, z)
        
        cube.draw(display=oled.display, angleX=-degrees(roll), angleY=-degrees(pitch)) 

except KeyboardInterrupt:
    print("\nInterrupted by user!")

finally:
    oled.reset()

回到頂部

讓教師和學生更容易參與動手發明創造.
© 2026 Inventor Pi, Inc.
Inventor Pi, Inc.是一家註冊的 501(c)(3) 非營利組織