我使用带有I2C的Raspberry Pi和16x2 LCD显示器来显示日期,时间(包括秒)和设备的IP地址。
脚本位于cron表中,并计划每分钟运行一次。在脚本本身中,秒数每秒重新加载。
代码仅适用于五分钟,然后显示的文本开始中断。我对Python不是很有经验,所以我感谢任何反馈,以使这些代码更正确。
cron表条目只是:
* * * * * python /home/pi/display.py
我主要是操纵代码的底部:
#!/usr/bin/env python
import time
import smbus
import socket
import fcntl
import struct
BUS = smbus.SMBus(1)
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(addr, bl):
global LCD_ADDR
global BLEN
LCD_ADDR = addr
BLEN = bl
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():
send_command(0x01) # Clear Screen
def openlight(): # Enable the backlight
BUS.write_byte(0x27,0x08)
BUS.close()
def write(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))
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,
struct.pack('256s', ifname[:15])
)[20:24])
if __name__ == '__main__':
init(0x27, 1)
write(0, 1, 'IP: ' + get_ip_address('wlan0'))
write(0, 0, time.strftime('%b')) #month
write(4, 0, time.strftime('%d')) #day of month
write(8, 0, time.strftime('%H:')) #hour
write(11, 0, time.strftime('%M:')) #minute
while True:
write(14, 0, time.strftime('%S'))#second
time.sleep(1)
答案 0 :(得分:0)
请使用这是您的解决方案
import time
import datetime
from RPLCD.gpio import CharLCD
from RPi import GPIO
GPIO.setmode (GPIO.BCM)
GPIO.setwarnings(False)
lcd = CharLCD(numbering_mode=GPIO.BCM, pin_rs=22, pin_rw=24, pin_e=23, pins_data=[26, 12, 16, 27],cols=16, rows=2,auto_linebreaks=True)
lcd.cursor_pos = (0,1)
lcd.write_string(u'WELCOME SAJANARORA517')
while 1:
lcd.cursor_pos =(1,10)
lcd.write_string("%s" %time.strftime("%H:%M:%S"))
lcd.cursor_pos = (1,0)
lcd.write_string("%s" %time.strftime("%d/%m/%y"))