树莓派上使用 LCD1602 显示状态
手頭有一塊 LCD1602顯示屏,于是嘗試著用樹莓派控制它的顯示。網上直接找到現成的例子,操作成功,在此記錄。
?
樹莓派版本:Model 3B+
樹莓派系統:Raspbian Stretch with desktop and recommended software,April 2019
參考資料:《樹莓派+LCD1602實現系統監控: IP/時鐘/溫度/內存》。
在樹莓派電源關閉時,根據參考資料中的連接方式(截圖如下)連接樹莓派、LCD顯示屏和電位器,因為很多引腳需要連接正負極,樹莓派上沒有足夠多的5v,所以我用了一個面包板。
連接好后如下圖所示。我的線太長了,顯得有些亂,大家接線的時候小心短路。
樹莓派開機。
LCD 顯示屏就會亮,但沒有顯示內容。
將參考資料中的兩個 python 文件保存至樹莓派中的同一文件夾下,長文件命名為1602led.py,短文件命名為1602.py。代碼如下,點擊+展開:
#!/usr/bin/python# # based on code from lrvick and LiquidCrystal # lrvic - https://github.com/lrvick/raspi-hd44780/blob/master/hd44780.py # LiquidCrystal - https://github.com/arduino/Arduino/blob/master/libraries/LiquidCrystal/LiquidCrystal.cpp # from time import sleepclass lcd1602:# commandsLCD_CLEARDISPLAY = 0x01LCD_RETURNHOME = 0x02LCD_ENTRYMODESET = 0x04LCD_DISPLAYCONTROL = 0x08LCD_CURSORSHIFT = 0x10LCD_FUNCTIONSET = 0x20LCD_SETCGRAMADDR = 0x40LCD_SETDDRAMADDR = 0x80# flags for display entry modeLCD_ENTRYRIGHT = 0x00LCD_ENTRYLEFT = 0x02LCD_ENTRYSHIFTINCREMENT = 0x01LCD_ENTRYSHIFTDECREMENT = 0x00# flags for display on/off controlLCD_DISPLAYON = 0x04LCD_DISPLAYOFF = 0x00LCD_CURSORON = 0x02LCD_CURSOROFF = 0x00LCD_BLINKON = 0x01LCD_BLINKOFF = 0x00# flags for display/cursor shiftLCD_DISPLAYMOVE = 0x08LCD_CURSORMOVE = 0x00# flags for display/cursor shiftLCD_DISPLAYMOVE = 0x08LCD_CURSORMOVE = 0x00LCD_MOVERIGHT = 0x04LCD_MOVELEFT = 0x00# flags for function setLCD_8BITMODE = 0x10LCD_4BITMODE = 0x00LCD_2LINE = 0x08LCD_1LINE = 0x00LCD_5x10DOTS = 0x04LCD_5x8DOTS = 0x00def __init__(self, pin_rs=14, pin_e=15, pins_db=[17, 18, 27, 22], GPIO = None):# Emulate the old behavior of using RPi.GPIO if we haven't been given# an explicit GPIO interface to useif not GPIO:import RPi.GPIO as GPIOself.GPIO = GPIOself.pin_rs = pin_rsself.pin_e = pin_eself.pins_db = pins_dbself.GPIO.setmode(GPIO.BCM)self.GPIO.setwarnings(False)self.GPIO.setup(self.pin_e, GPIO.OUT)self.GPIO.setup(self.pin_rs, GPIO.OUT)for pin in self.pins_db:self.GPIO.setup(pin, GPIO.OUT)self.write4bits(0x33) # initializationself.write4bits(0x32) # initializationself.write4bits(0x28) # 2 line 5x7 matrixself.write4bits(0x0C) # turn cursor off 0x0E to enable cursorself.write4bits(0x06) # shift cursor right self.displaycontrol = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFFself.displayfunction = self.LCD_4BITMODE | self.LCD_1LINE | self.LCD_5x8DOTSself.displayfunction |= self.LCD_2LINE""" Initialize to default text direction (for romance languages) """self.displaymode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode) # set the entry mode self.clear()def begin(self, cols, lines):if (lines > 1):self.numlines = linesself.displayfunction |= self.LCD_2LINEself.currline = 0def home(self):self.write4bits(self.LCD_RETURNHOME) # set cursor position to zeroself.delayMicroseconds(3000) # this command takes a long time!def clear(self):self.write4bits(self.LCD_CLEARDISPLAY) # command to clear displayself.delayMicroseconds(3000) # 3000 microsecond sleep, clearing the display takes a long timedef setCursor(self, col, row):self.row_offsets = [ 0x00, 0x40, 0x14, 0x54 ]if ( row > self.numlines ): row = self.numlines - 1 # we count rows starting w/0 self.write4bits(self.LCD_SETDDRAMADDR | (col + self.row_offsets[row]))def noDisplay(self): """ Turn the display off (quickly) """self.displaycontrol &= ~self.LCD_DISPLAYONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)def display(self):""" Turn the display on (quickly) """self.displaycontrol |= self.LCD_DISPLAYONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)def noCursor(self):""" Turns the underline cursor on/off """self.displaycontrol &= ~self.LCD_CURSORONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)def cursor(self):""" Cursor On """self.displaycontrol |= self.LCD_CURSORONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)def noBlink(self):""" Turn on and off the blinking cursor """self.displaycontrol &= ~self.LCD_BLINKONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)def noBlink(self):""" Turn on and off the blinking cursor """self.displaycontrol &= ~self.LCD_BLINKONself.write4bits(self.LCD_DISPLAYCONTROL | self.displaycontrol)def DisplayLeft(self):""" These commands scroll the display without changing the RAM """self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT)def scrollDisplayRight(self):""" These commands scroll the display without changing the RAM """self.write4bits(self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT);def leftToRight(self):""" This is for text that flows Left to Right """self.displaymode |= self.LCD_ENTRYLEFTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode);def rightToLeft(self):""" This is for text that flows Right to Left """self.displaymode &= ~self.LCD_ENTRYLEFTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode)def autoscroll(self):""" This will 'right justify' text from the cursor """self.displaymode |= self.LCD_ENTRYSHIFTINCREMENTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode)def noAutoscroll(self): """ This will 'left justify' text from the cursor """self.displaymode &= ~self.LCD_ENTRYSHIFTINCREMENTself.write4bits(self.LCD_ENTRYMODESET | self.displaymode)def write4bits(self, bits, char_mode=False):""" Send command to LCD """self.delayMicroseconds(1000) # 1000 microsecond sleep bits=bin(bits)[2:].zfill(8)self.GPIO.output(self.pin_rs, char_mode)for pin in self.pins_db:self.GPIO.output(pin, False)for i in range(4):if bits[i] == "1":self.GPIO.output(self.pins_db[::-1][i], True)self.pulseEnable()for pin in self.pins_db:self.GPIO.output(pin, False)for i in range(4,8):if bits[i] == "1":self.GPIO.output(self.pins_db[::-1][i-4], True)self.pulseEnable()def delayMicroseconds(self, microseconds):seconds = microseconds / float(1000000) # divide microseconds by 1 million for seconds sleep(seconds)def pulseEnable(self):self.GPIO.output(self.pin_e, False)self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be > 450ns self.GPIO.output(self.pin_e, True)self.delayMicroseconds(1) # 1 microsecond pause - enable pulse must be > 450ns self.GPIO.output(self.pin_e, False)self.delayMicroseconds(1) # commands need > 37us to settledef message(self, text):""" Send string to LCD. Newline wraps to second line"""for char in text:if char == '\n':self.write4bits(0xC0) # next lineelse:self.write4bits(ord(char),True)if __name__ == '__main__':lcd = lcd1602()lcd.clear()lcd.message("hello world!") 1602led.py #!/usr/bin/pythonfrom lcd1602 import * from datetime import * import commandsdef get_cpu_temp():tmp = open('/sys/class/thermal/thermal_zone0/temp')cpu = tmp.read()tmp.close()return '{:.2f}'.format( float(cpu)/1000 ) + ' C'def get_gpu_temp():tmp = commands.getoutput('vcgencmd measure_temp|awk -F= \'{print $2}\'').replace('\'C','')gpu = float(tmp)return '{:.2f}'.format( gpu ) + ' C'def get_time_now():return datetime.now().strftime(' %H:%M:%S\n %Y-%m-%d')def get_ip_info():return commands.getoutput('ifconfig wlan0|grep inet|awk -Faddr: \'{print $2}\'|awk \'{print $1}\'')def get_mem_info():total= commands.getoutput('free -m|grep Mem:|awk \'{print $2}\'') free = commands.getoutput('free -m|grep cache:|awk \'{print $4}\'')return 'MEM:\n ' + free +' / '+ total +' M'lcd = lcd1602() lcd.clear()if __name__ == '__main__':while(1):lcd.clear()lcd.message( get_ip_info() )sleep(5)lcd.clear()lcd.message( get_time_now() )sleep(5)lcd.clear()lcd.message( get_mem_info() )sleep(5)lcd.clear()lcd.message( 'CPU: ' + get_cpu_temp()+'\n' )lcd.message( 'GPU: ' + get_gpu_temp() )sleep(5) 1602.py代碼需用 python2.7 運行,終端進入對應的文件夾下,執行?python 1602.py?,就能發現顯示屏變化了。注意,可能需要旋轉電位器轉軸來矯正顯示屏。
運行結果:
?
該程序是無限循環的,終止程序后(control+C),顯示屏會保留最后狀態。
相關文章
?
轉載于:https://www.cnblogs.com/zhenqichai/p/raspberry-pi-GPIO-control-lcd-1602.html
總結
以上是生活随笔為你收集整理的树莓派上使用 LCD1602 显示状态的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RS-485通信协议(ModBus版)
- 下一篇: 原理图端口符号_电气原理图与接线图的区别