You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Raspberry Pi Pico驱动16x2 LCD出现NameError错误求助

Raspberry Pi Pico驱动16x2 LCD报错修复方案

问题现象

运行代码时触发如下错误:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "lcd_pico.py", line 26, in setupLCD
NameError: name 'send2LCD4' isn't defined

原因是lcd_pico.py中调用了多个未定义的核心函数,包括send2LCD4、send2LCD8、longDelay、returnHome和moveCursorRight。

修复步骤

在lcd_pico.py中补充缺失的函数,完整代码如下:

import machine
import utime

rs = machine.Pin(16, machine.Pin.OUT)
e = machine.Pin(17, machine.Pin.OUT)
d4 = machine.Pin(18, machine.Pin.OUT)
d5 = machine.Pin(19, machine.Pin.OUT)
d6 = machine.Pin(20, machine.Pin.OUT)
d7 = machine.Pin(21, machine.Pin.OUT)

def pulse_enable():
    e.value(1)
    utime.sleep_us(1)
    e.value(0)
    utime.sleep_us(50)

def send2LCD4(bits):
    d4.value((bits >> 0) & 1)
    d5.value((bits >> 1) & 1)
    d6.value((bits >> 2) & 1)
    d7.value((bits >> 3) & 1)
    pulse_enable()

def send2LCD8(bits):
    send2LCD4((bits >> 4) & 0x0F)
    send2LCD4(bits & 0x0F)

def longDelay(ms):
    utime.sleep_ms(ms)

def returnHome():
    rs.value(0)
    send2LCD8(0b00000010)
    longDelay(2)
    rs.value(1)

def moveCursorRight():
    rs.value(0)
    send2LCD8(0b00000110)
    longDelay(1)
    rs.value(1)

def setCursor(line, pos):
    b = 0
    if line == 1:
        b = 0
    elif line == 2:
        b = 40
    returnHome()
    for i in range(0, b + pos):
        moveCursorRight()

def clearScreen():
    rs.value(0)
    send2LCD8(0b00000001) # clear screen
    longDelay(2) # clear screen needs a long delay
    rs.value(1)

def setupLCD():
    rs.value(0)
    send2LCD4(0b0011)
    send2LCD4(0b0011)
    send2LCD4(0b0011)
    send2LCD4(0b0010)
    send2LCD8(0b00101000)
    send2LCD8(0b00001100) # lcd on, blink off, cursor off.
    send2LCD8(0b00000110) # increment cursor, no display shift
    send2LCD8(0b00000001) # clear screen
    longDelay(2) # clear screen needs a long delay
    rs.value(1)

def displayString(row, col, input_string):
    setCursor(row, col)
    for x in input_string:
        send2LCD8(ord(x))
        longDelay(10)

关键函数说明

  • pulse_enable():生成LCD所需的使能脉冲,触发数据接收
  • send2LCD4():向LCD发送4位指令/数据(适配4位通信模式)
  • send2LCD8():将8位数据拆分为两次4位发送
  • longDelay():封装毫秒级延迟,简化代码调用
  • returnHome():将光标移回屏幕左上角
  • moveCursorRight():将光标向右移动一位

验证运行

保持main.py代码不变,重新运行即可看到LCD正常循环显示预设文本:

from lcd_pico import *
setupLCD()
displayString(1,0,"WELCOME")
displayString(2,0,"TO")
longDelay(4000)
displayString(1,0,"CIRCUIT")
displayString(2,0,"DIGEST")
longDelay(4000)
while(True):
    displayString(1,0,"CIRCUIT")
    displayString(2,0,"DIGEST")
    longDelay(1000)
    clearScreen()
    longDelay(500)

内容的提问来源于stack exchange,提问作者Christian Morogan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:10:50