【Raspberry Pi Zero W 试用体验】使用LCD1602制作数字时钟

  • 辛迪可乐
  • LV5工程师
  • |      2017-07-23 21:44:16
  • 浏览量 2284
  • 回复:1
本帖最后由 辛迪可乐 于 2017-7-23 22:06 编辑 我们可以利用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
接着创建一个数字时钟显示的python脚本lcd1602.py
sudo vi lcd1602.py
复制粘贴如下代码进去
import smbus

import time

import os

from time import gmtime, strftime, localtime



os.environ = 'Asia/Shanghai'

time.tzset()



bus = smbus.SMBus(1)

addr = 0x3f



def 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)



# init

writeCommand(0b0010)



# 4-byte mode, 2 line code

writeCommand(0b0010)

writeCommand(0b1111)



# set cursor mode

writeCommand(0b0000)

writeCommand(0b1100)



# cursor shift mode

writeCommand(0b0000)

writeCommand(0b0110)



writeWord("Welcome")

clear = True

time.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.py
LCD1602液晶屏上会显示如下日期和实时时间
  • 0
  • 收藏
  • 举报
  • 分享
我来回复

登录后可评论,请 登录注册

所有回答 数量:1
黄莨元 2017-08-03
有点厉害
0   回复
举报
发布
x
收藏成功!点击 我的收藏 查看收藏的全部帖子