microPython基于esp32的mpu6050在OLED显示实验
时间: 2023-12-09 15:05:28 浏览: 297
本实验使用esp32开发板和OLED显示屏,通过I2C通信协议连接MPU6050传感器,实时读取MPU6050的三轴加速度和三轴角速度数据,并通过OLED显示在屏幕上。
硬件连接:
- SDA引脚连接到esp32的GPIO21引脚
- SCL引脚连接到esp32的GPIO22引脚
- VCC引脚连接到esp32的3.3V电源引脚
- GND引脚连接到esp32的GND引脚
代码实现:
首先需要导入必要的库文件,包括I2C和SSD1306 OLED驱动库。
```python
from machine import I2C, Pin
import ssd1306
import time
```
然后定义I2C和OLED驱动器的引脚和地址。
```python
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)
```
接下来初始化MPU6050传感器,设置采样率和滤波器等参数。
```python
def init_mpu6050():
i2c.writeto_mem(0x68, 0x6B, b'\x00') # 唤醒MPU6050
i2c.writeto_mem(0x68, 0x1B, b'\x18') # 设置陀螺仪量程为±2000°/s
i2c.writeto_mem(0x68, 0x1C, b'\x08') # 设置加速度传感器量程为±4g
i2c.writeto_mem(0x68, 0x1A, b'\x03') # 设置数字低通滤波器为42Hz
```
读取MPU6050的三轴加速度和三轴角速度数据。
```python
def read_mpu6050():
data = i2c.readfrom_mem(0x68, 0x3B, 14)
ax = (data[0] << 8) | data[1]
ay = (data[2] << 8) | data[3]
az = (data[4] << 8) | data[5]
gx = (data[8] << 8) | data[9]
gy = (data[10] << 8) | data[11]
gz = (data[12] << 8) | data[13]
ax = twos_comp(ax) / 16384.0
ay = twos_comp(ay) / 16384.0
az = twos_comp(az) / 16384.0
gx = twos_comp(gx) / 131.0
gy = twos_comp(gy) / 131.0
gz = twos_comp(gz) / 131.0
return ax, ay, az, gx, gy, gz
```
将读取到的数据显示在OLED屏幕上。
```python
while True:
oled.fill(0)
ax, ay, az, gx, gy, gz = read_mpu6050()
oled.text("Acc: %.2f, %.2f, %.2f" % (ax, ay, az), 0, 0)
oled.text("Gyr: %.2f, %.2f, %.2f" % (gx, gy, gz), 0, 15)
oled.show()
time.sleep(0.1)
```
完整代码:
```python
from machine import I2C, Pin
import ssd1306
import time
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)
def twos_comp(val):
if val & (1 << 15):
val = val - (1 << 16)
return val
def init_mpu6050():
i2c.writeto_mem(0x68, 0x6B, b'\x00') # 唤醒MPU6050
i2c.writeto_mem(0x68, 0x1B, b'\x18') # 设置陀螺仪量程为±2000°/s
i2c.writeto_mem(0x68, 0x1C, b'\x08') # 设置加速度传感器量程为±4g
i2c.writeto_mem(0x68, 0x1A, b'\x03') # 设置数字低通滤波器为42Hz
def read_mpu6050():
data = i2c.readfrom_mem(0x68, 0x3B, 14)
ax = (data[0] << 8) | data[1]
ay = (data[2] << 8) | data[3]
az = (data[4] << 8) | data[5]
gx = (data[8] << 8) | data[9]
gy = (data[10] << 8) | data[11]
gz = (data[12] << 8) | data[13]
ax = twos_comp(ax) / 16384.0
ay = twos_comp(ay) / 16384.0
az = twos_comp(az) / 16384.0
gx = twos_comp(gx) / 131.0
gy = twos_comp(gy) / 131.0
gz = twos_comp(gz) / 131.0
return ax, ay, az, gx, gy, gz
init_mpu6050()
while True:
oled.fill(0)
ax, ay, az, gx, gy, gz = read_mpu6050()
oled.text("Acc: %.2f, %.2f, %.2f" % (ax, ay, az), 0, 0)
oled.text("Gyr: %.2f, %.2f, %.2f" % (gx, gy, gz), 0, 15)
oled.show()
time.sleep(0.1)
```
阅读全文