TA的每日心情 | 奋斗 2019-10-1 12:54 |
---|
签到天数: 313 天 连续签到: 1 天 [LV.8]以坛为家I
|
为了方便随时知道时间,我们可以利用Raspberry Pi Zero W和LCD1602显示屏做一个数字时钟,在使用树莓派开发的时候不忘时间,下面介绍具体实现方法,为了减少连接线的数量,笔者决定使用树莓派ZERO W的I2C接口来驱动LCD1602所以我们需要一个IIC/I2C/接口LCD1602液晶屏转接板
首先将LCD1602和转换板按下图焊接
然后用四根杜邦线将转换板上GND VCC SDA SCL分别连接到Raspberry Pi Zero W的GND VCC SDA SCL,参考下面排针GPIO定义即为Pin9 Pin1 Pin3 Pin5
连接好后将树莓派ZERO W上电,进入终端输入如下命令
sudo raspi-config按下图操作打开I2C
然后安装i2c-tools和python-smbus
sudo apt-get install i2c-tools python-smbus接着输入如下命令查看I2C接口连接设备的物理地址
i2cdetect -y 1
可以看到LCD1602位置为3f,接着创建一个数字时钟显示的python脚本lcd1602.py
sudo vi lcd1602.py复制粘贴如下代码进去
import smbusimport timeimport osfrom time import gmtime, strftime, localtimeos.environ['TZ'] = 'Asia/Shanghai'time.tzset()bus = smbus.SMBus(1)addr = 0x3fdef writeCommand(command): bus.write_byte(addr, 0b1100 | command << 4) time.sleep(0.005) bus.write_byte(addr, 0b1000 | command << 4) time.sleep(0.005)def writeWord(word): for i in range(0,len(word)): asciiCode = ord(word) bus.write_byte(addr, 0b1101 |(asciiCode >> 4 & 0x0F) << 4) time.sleep(0.0005) bus.write_byte(addr, 0b1001 |(asciiCode >> 4 & 0x0F) << 4) time.sleep(0.0005) bus.write_byte(addr, 0b1101 |(asciiCode & 0x0F) << 4) time.sleep(0.0005) bus.write_byte(addr, 0b1001 | (asciiCode & 0x0F) << 4) time.sleep(0.0005)# initwriteCommand(0b0010)# 4-byte mode, 2 line codewriteCommand(0b0010)writeCommand(0b1111)# set cursor modewriteCommand(0b0000)writeCommand(0b1100)# cursor shift modewriteCommand(0b0000)writeCommand(0b0110)writeWord("Welcome")clear = Truetime.sleep(1)while(1): # first line first column writeCommand(0b1000) writeCommand(0b0000) writeWord(strftime("%Y-%m-%d, %a ", localtime())) # second line first column writeCommand(0b1100) writeCommand(0b0000) writeWord(strftime("%H:%M:%S", localtime())) time.sleep(0.2)然后按ESC键后输入:wq保存脚本,接着输入如下命令运行脚本
python lcd1602.pyLCD1602液晶屏上会显示如下日期和实时时间
|
|