前一阵用废旧的树莓派做了一个NAS服务器,手里还要一块闲置的LCD 1602 液晶屏模块,可以用来实时显示IP,作为NAS的服务器输出显示。
在树莓派上LCD 1602 液晶屏模块的使用非常简单,可以用 I2C 方式的驱动,只要使能0,5V,tx,tf四根线就可实现使能,屏幕上自带调压电阻可以调整亮度对比度。极大的简化LED接线和驱动使用。带 I2C 模块的 1602 屏幕背面如图所示。
第一步,线序超级简单,不要接错了。
GND — GND
VCC — 接树莓派 5V
SDA — I2C 数据
SCL — I2C 时钟
第二步,启用树莓派的I2C功能。
sudo apt-get install -y python-smbus
sudo apt-get install -y i2c-tools
第三步,使能I2C
sudo raspi-config
选择I2C
第四步,用 Python 控制 LCD1602 显示需要的信息。
平时用来显示时间的程序代码例 测试程序test.py:
import smbus
import time
import sys
import LCD1602 as LCD
if __name__ == '__main__':
LCD.init_lcd()
time.sleep(1)
LCD.print_lcd(2, 0, '测试程序test')
for x in xrange(1, 4):
LCD.turn_light(0)
LCD.print_lcd(4, 1, 'LIGHT OFF')
time.sleep(0.5)
LCD.turn_light(1)
LCD.print_lcd(4, 1, 'LIGHT ON ')
time.sleep(0.5)
LCD.turn_light(0)
while True:
now = time.strftime('%m/%d %H:%M:%S', time.localtime(time.time()))
LCD.print_lcd(1, 1, now)
time.sleep(0.2)
注意1,LCD1602模块不显示可以调整一下电阻,亮度太高也不行的。
注意2,LCD1602驱动在程序里作为一个python导入模块使用。找不到的,用我下面共享的,保存为LCD1602.py作为驱动和程序放在同目录即可。怎么样开机自动运行参考我的另一篇文章:树莓派Python程序开机自启动(Linux下Python程序开机自启动)
LCD1602.py驱动程序代码
import time
import smbus
BUS = smbus.SMBus(1)
LCD_ADDR = 0x27
BLEN = 1 #turn on/off background light
def turn_light(key):
global BLEN
BLEN = key
if key ==1 :
BUS.write_byte(LCD_ADDR ,0x08)
else:
BUS.write_byte(LCD_ADDR ,0x00)
def write_word(addr, data):
global BLEN
temp = data
if BLEN == 1:
temp |= 0x08
else:
temp &= 0xF7
BUS.write_byte(addr ,temp)
def send_command(comm):
# Send bit7-4 firstly
buf = comm & 0xF0
buf |= 0x04 # RS = 0, RW = 0, EN = 1
write_word(LCD_ADDR ,buf)
time.sleep(0.002)
buf &= 0xFB # Make EN = 0
write_word(LCD_ADDR ,buf)
# Send bit3-0 secondly
buf = (comm & 0x0F) << 4
buf |= 0x04 # RS = 0, RW = 0, EN = 1
write_word(LCD_ADDR ,buf)
time.sleep(0.002)
buf &= 0xFB # Make EN = 0
write_word(LCD_ADDR ,buf)
def send_data(data):
# Send bit7-4 firstly
buf = data & 0xF0
buf |= 0x05 # RS = 1, RW = 0, EN = 1
write_word(LCD_ADDR ,buf)
time.sleep(0.002)
buf &= 0xFB # Make EN = 0
write_word(LCD_ADDR ,buf)
# Send bit3-0 secondly
buf = (data & 0x0F) << 4
buf |= 0x05 # RS = 1, RW = 0, EN = 1
write_word(LCD_ADDR ,buf)
time.sleep(0.002)
buf &= 0xFB # Make EN = 0
write_word(LCD_ADDR ,buf)
def init_lcd():
try:
send_command(0x33) # Must initialize to 8-line mode at first
time.sleep(0.005)
send_command(0x32) # Then initialize to 4-line mode
time.sleep(0.005)
send_command(0x28) # 2 Lines & 5*7 dots
time.sleep(0.005)
send_command(0x0C) # Enable display without cursor
time.sleep(0.005)
send_command(0x01) # Clear Screen
BUS.write_byte(LCD_ADDR ,0x08)
except:
return False
else:
return True
def clear_lcd():
send_command(0x01) # Clear Screen
def print_lcd(x, y, str):
if x < 0:
x = 0
if x > 15:
x = 15
if y <0:
y = 0
if y > 1:
y = 1
# Move cursor
addr = 0x80 + 0x40 * y + x
send_command(addr)
for chr in str:
send_data(ord(chr))
if __name__ == '__main__':
init_lcd()
print_lcd(0, 0, 'Hello, world!')```