使用树莓派3B驱动1602,显示当前CPU等信息

昨天看到了树莓派边上的一块1602,闲得无聊就研究了一下驱动这块屏幕,反正放着也是浪费233

准备工作

这里我参考了这篇文章:基于PHP探针和Python爬虫的服务器监控
首先我们要连上这块屏幕,文章中使用的是4位工作模式,所以数据线不需要接八根,只要接四根就行了,连接如下:

1602上的引脚树莓派上的引脚
VSS接地
VDD接5V电源
VO液晶对比度调节,接电位器中间的引脚
RS寄存器选择,接GPIO27
RW读写选择,接GND
EN使能信号,接GPIO22
D0数据位0,不接
D1数据位1,不接
D2数据位2,不接
D3数据位3,不接
D4数据位4,接GPIO25
D5数据位5,接GPIO24
D6数据位6,接GPIO23
D7数据位7,接GPIO18
A液晶屏背光+,接3V或5V
K液晶屏背光-,接地

接完后大概长这样(真乱233):

编写运行程序

屏幕接好了,我们就能控制它的显示了
首先安装一下1602驱动的库

git clone https://github.com/adafruit/Adafruit_Python_CharLCD.git
cd Adafruit_Python_CharLCD
sudo python3 setup.py install

安装完后用下面的脚本来测试是否能正常显示

#!/usr/bin/python
# Example using a character LCD connected to a Raspberry Pi or BeagleBone Black.
import time

import Adafruit_CharLCD as LCD


# Raspberry Pi pin configuration:
lcd_rs        = 27  # Note this might need to be changed to 21 for older revision Pi's.
lcd_en        = 22
lcd_d4        = 25
lcd_d5        = 24
lcd_d6        = 23
lcd_d7        = 18
lcd_backlight = 4

# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows    = 2


lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                           lcd_columns, lcd_rows, lcd_backlight)

# Print a two line message
lcd.message('0123456789abcdef\nabcdef0123456789')

如果正常,那么显示应该是这样的(那个电位器需要自己调整):

实现功能

随便写了写,可以显示当前的CPU占用、温度、时间、日期、内存占用、磁盘占用、本地空气质量、气温以及湿度
脚本如下:

#!/usr/bin/python
import time
import Adafruit_CharLCD as LCD
import os
import socket
import fcntl
import struct
import urllib
import urllib.request
import json

# Raspberry Pi pin configuration:
lcd_rs        = 27  # Note this might need to be changed to 21 for older revision Pi's.
lcd_en        = 22
lcd_d4        = 25
lcd_d5        = 24
lcd_d6        = 23
lcd_d7        = 18
lcd_backlight = 4

# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows    = 2

# Initialize the LCD using the pins above.
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                           lcd_columns, lcd_rows, lcd_backlight)
lcd.clear() 
#lcd.message('0123456789abcdef\nabcdef0123456789')

#lcd.clear()
#lcd.show_cursor(True)
#lcd.message('Show cursor')

# Return CPU temperature as a character string                                      
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    return(res.replace("temp=","").replace("'C\n",""))

# Return RAM information (unit=kb) in a list                                       
# Index 0: total RAM                                                               
# Index 1: used RAM                                                                 
# Index 2: free RAM                                                                 
def getRAMinfo():
    p = os.popen('free')
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i==2:
            return(line.split()[1:4])

# Return % of CPU used by user as a character string                                
def getCPUuse():
    return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))

# Return information about disk space as a list (unit included)                     
# Index 0: total disk space                                                         
# Index 1: used disk space                                                         
# Index 2: remaining disk space                                                     
# Index 3: percentage of disk used                                                  
def getDiskSpace():
    p = os.popen("df -h /")
    i = 0
    while 1:
        i = i +1
        line = p.readline()
        if i==2:
            return(line.split()[1:5])

def getInfo1():
    # CPU informatiom
    CPU_temp = getCPUtemperature()
    CPU_usage = getCPUuse()
    print('CPU:'+CPU_usage+'% ' + CPU_temp + 'C   \n' + time.strftime('%H:%M:%S   %m/%d',time.localtime()))
    return 'CPU:'+CPU_usage+'% ' + CPU_temp + 'C   \n' + time.strftime('%H:%M:%S   %m/%d',time.localtime(time.time()))

def getInfo2():
    # RAM information
    # Output is in kb, here I convert it in Mb for readability
    RAM_stats = getRAMinfo()
    RAM_total = round(int(RAM_stats[0]) / 1000,1)
    RAM_used = round(int(RAM_stats[1]) / 1000,1)
    RAM_free = round(int(RAM_stats[2]) / 1000,1)

    # Disk information
    DISK_stats = getDiskSpace()
    DISK_total = DISK_stats[0]
    DISK_used = DISK_stats[1]
    DISK_perc = DISK_stats[3]
    print('   mem:' + str(int(RAM_used)) + 'MB\n   disk:' + str(DISK_perc))
    return '   mem:' + str(int(RAM_used)) + 'MB\n   disk:' + str(DISK_perc)

count = 0
last_aqi = 0
last_temp = 0
last_sd = 0
def getInfo3():
    global count
    global last_aqi
    global last_temp
    global last_sd
    try:
        if count == 0:
            f = urllib.request.urlopen('http://api.waqi.info/feed/@7687/?token=737aa093c7d9c16b7c6fdc1b70af2fb02bf01e11')
            result = json.loads(f.read().decode('utf-8'))
            last_aqi = result['data']['aqi']
            f = urllib.request.urlopen('https://www.sojson.com/open/api/weather/json.shtml?city=%E6%98%86%E5%B1%B1')
            result = json.loads(f.read().decode('utf-8'))
            last_temp = result['data']['wendu']
            last_sd = result['data']['shidu']
        elif count > 15:
            count = -1
        count+=1
        lcd.clear()
        print('Kunshan AQI:'+str(last_aqi)+'\nwendu:' + str(last_temp) + 'C  ' + last_sd)
        return 'Kunshan AQI:'+str(last_aqi)+'\nwendu:' + str(last_temp) + 'C  ' + last_sd
    except Exception as e:
        print(e)
        print('kunshan AQI:\nget fail')
        return 'kunshan AQI:\nget fail'


while(True):
    lcd.clear()
    lcd.message(getInfo1())
    time.sleep(1)
    lcd.message(getInfo1())
    time.sleep(1)
    lcd.message(getInfo1())
    time.sleep(1)
    lcd.message(getInfo1())
    time.sleep(1)
    lcd.message(getInfo1())
    time.sleep(1)
    lcd.message(getInfo1())
    time.sleep(1)
    lcd.clear()
    lcd.message(getInfo2())
    time.sleep(5)
    lcd.message(getInfo3())
    time.sleep(5)

显示效果如下:

5 Comments

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注