使用LCD和触摸传感器
pybaord的pyb对LCD设备也进行了封装,可以使用官方的LCD显示屏。将LCD屏连接到开发板,连接后。
使用LCD
先用REPL来做个实验,在MicroPython提示符中输入以下指令。请确保LCD面板连接到pyboard的方式正确。
>>> import pyb
>>> lcd = pyb.LCD('X')
>>> lcd.light(True)
>>> lcd.write('Hello uPy!\n')
用下面的代码可以显示文字动画效果:
import pyb
lcd = pyb.LCD('X')
lcd.light(True)
for x in range(-80, 128):
lcd.fill(0)
lcd.text('Hello uPy!', x, 10, 1)
lcd.show()
pyb.delay(25)
使用触摸传感器
pyboard要读取MBPR121触摸传感器的数据,需要使用I2C总线,MPR121电容式触摸传感器的地址为90。
可以先用下面的命令进行尝试:
>>> import pyb
>>> i2c = pyb.I2C(1, pyb.I2C.MASTER)
>>> i2c.mem_write(4, 90, 0x5e)
>>> touch = i2c.mem_read(1, 90, 0)[0]
在import pyb后
第一行命令实例化一个I2C对象
第二行命令启用4个触摸传感器。
第三行读取触摸状态,touch变量保存了4个触摸按钮的状态(A、B、X、Y)。
触摸时由于电路和触摸的稳定性问题,可能会出现抖动的情况,可以使用一个去抖动的组件,设置阈值和去抖参数,就可以轻松准确的读取触摸状态和电极电压水平。
"""
Driver for the MPR121 capacitive touch sensor.
This chip is on the LCD32MKv1 skin.
"""
import pyb
# register definitions
TOUCH_STATUS = const(0x00)
ELE0_FILT_DATA = const(0x04)
ELE0_TOUCH_THRESH = const(0x41)
DEBOUNCE = const(0x5b)
ELEC_CONFIG = const(0x5e)
class MPR121:
def __init__(self, i2c):
self.i2c = i2c
self.addr = 90 # I2C address of the MPR121
# enable ELE0 - ELE3
self.enable_elec(4)
def enable_elec(self, n):
"""Enable the first n electrodes."""
self.i2c.mem_write(n & 0xf, self.addr, ELEC_CONFIG)
def threshold(self, elec, touch, release):
"""
Set touch/release threshold for an electrode.
Eg threshold(0, 12, 6).
"""
buf = bytearray((touch, release))
self.i2c.mem_write(buf, self.addr, ELE0_TOUCH_THRESH + 2 * elec)
def debounce(self, touch, release):
"""
Set touch/release debounce count for all electrodes.
Eg debounce(3, 3).
"""
self.i2c.mem_write((touch & 7) | (release & 7) << 4, self.addr, DEBOUNCE)
def touch_status(self, elec=None):
"""Get the touch status of an electrode (or all electrodes)."""
status = self.i2c.mem_read(2, self.addr, TOUCH_STATUS)
status = status[0] | status[1] << 8
if elec is None:
return status
else:
return status & (1 << elec) != 0
def elec_voltage(self, elec):
"""Get the voltage on an electrode."""
data = self.i2c.mem_read(2, self.addr, ELE0_FILT_DATA + 2 * elec)
return data[0] | data[1] << 8
将此代码复制到您的pyboard(Flash或SD卡,在顶层目录或 lib/ 目录),命名为mpr121.py,然后尝试:
>>> import pyb
>>> import mpr121
>>> m = mpr121.MPR121(pyb.I2C(1, pyb.I2C.MASTER))
>>> for i in range(100):
... print(m.touch_status())
... pyb.delay(100)
...
这会持续打印所有电极的触摸状态。可以尝试依次触摸每个。
注意:LCD面板被置于Y方向,那需要使用以下代码初始化I2C总线:
>>> m = mpr121.MPR121(pyb.I2C(2, pyb.I2C.MASTER))