2017年2月25日 星期六

樹莓派3 LCD 資訊看板 Raspberry Pi 3 LCD Info Board


利用 16x2 LCD顯示屏偱環顯示:

1. 當前日期和時間
2. 樹莓派 IP 地址
3. 室內溫度和濕度
4. CPU溫度和使用
5. RAM使用情況
6. SD卡使用情況


電子零件:
  1. 麵包皮 x 1
  2. LCD 16x2 字元顯示屏 x 1
  3. 10K可變電阻 x 1
  4. DHT11 溫度、濕度感應器 x 1
  5. 開關按鈕 x 1
  6. 陶瓷電容 x 1
  7. 330Ω 電阻 x 1
  8. 10KΩ電阻 x 2
  9. 母對公、公對公杜邦線數條 



接駁圖:































運作短片:



驅動 LCD 及 DHT11 須安裝以下兩個 Libraries:

1.
apt-get install git
git clone git://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git
cd Adafruit-Raspberry-Pi-Python-Code

cd Adafruit_CharLCD

sudo python setup.py install

2.
git clone https://github.com/adafruit/Adafruit_Python_DHT.git

cd Adafruit_Python_DHT

sudo python setup.py install


Python 程式碼:

#!/usr/bin/python
import Adafruit_CharLCD as LCD
import Adafruit_DHT
import RPi.GPIO as gpio
import time
from datetime import datetime
import os

# Raspberry Pi pin configuration:
lcd_rs        = 25
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 17
lcd_d6        = 18
lcd_d7        = 22
lcd_backlight = 8
btn_1         = 19

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

# Initialize the LCD
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                           lcd_columns, lcd_rows, lcd_backlight)
lcd.set_backlight(0)

# Initialize the DHT11
sensor = Adafruit_DHT.DHT11
sensor_pin = 26

# Setup tact button
gpio.setmode(gpio.BCM)
gpio.setup(btn_1, gpio.IN)    # set btn_1 as input (button)

seq = 1    # init global sequence, today and time
today = ''
now = ''

# Define a threaded callback function to run in another thread when events are detected
def buttonPressed(pin):
    global seq, today, now
    lcd.clear()
    if seq == 1:
      # Get IP address
      ip = ""
      try:
        ip = os.popen('ip addr show eth0').read().split("inet ")[1].split("/")[0]
      except:
        try:
          ip = os.popen('ip addr show wlan0').read().split("inet ")[1].split("/")[0]
        except:
          lcd.message('No IP address found')
      # Show IP address
      lcd.message("IP Address:\n")
      lcd.message(ip)
    elif seq == 2:
      # Show Temperature and Humidity
      lcd.message("   LOADING...")
      hum, temp = Adafruit_DHT.read_retry(sensor, sensor_pin)
      if hum is not None and temp is not None:
        lcd.set_cursor(0,0)
        t = "  Temp: " + str(temp)
        h = "   Hum: " + str(hum) + "%"
        lcd.message(t + chr(223) + "C\n")
        lcd.message(h)
    elif seq == 3:
        # Show cpu temperature and usage
        lcd.message("CPU TEMP: ")
        lcd.message(getCPUtemp() + chr(223) + "C\n")
        lcd.message("CPU USE:  " + getCPUuse() + "%")
    elif seq == 4:
        # Show ram usage
        showRAM()
    elif seq == 5:
        # Show sdcard usage
        sd_info = getSdcardInfo()
        lcd.message(" SD Size: " + sd_info[0] + "\n")
        lcd.message(" SD Use : " + sd_info[3])
    elif seq == 6:
        # Show Date and Time info
        getDateTime()
        lcd.message(today)
        lcd.message(now)

    seq = seq + 1
    if seq == 7:
      seq = 1

def showRAM():
    ram = getRAMUsage()
    free_ram = int(ram[2]) / 1000
    total_ram = float(ram[0])
    ram_usage = round(float(ram[1]) / total_ram * 100, 1)
    lcd.message("FREE RAM: " + str(free_ram) + "MB\n")
    lcd.message("RAM USE:  " + str(ram_usage) + "%")

def getDateTime():
    global today, now
    n = datetime.now()
    today = "   " + n.strftime('%d/%m/%Y') + "\n"
    now = "    " + n.strftime('%H:%M:%S')

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

# 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 RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMUsage():
    p = os.popen('free')
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i==2:
            return(line.split()[1:4])

# 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 getSdcardInfo():
    p = os.popen("df -h /")
    i = 0
    while 1:
        i = i +1
        line = p.readline()
        if i==2:
            return(line.split()[1:5])


# when a changing edge is detected on port 19, regardless of whatever
# else is happening in the program, the function buttonPressed will be run
gpio.add_event_detect(btn_1, gpio.FALLING, callback=buttonPressed)

try:
  print "Program will finish if you press CTRL+C\n"
  getDateTime()
  lcd.message(today)
  lcd.message(now)

  while True:
    if seq == 1:
        getDateTime()
        lcd.set_cursor(0,1)
        lcd.message(now)
    time.sleep(1)
    print(seq)

finally:
  gpio.cleanup()



沒有留言:

張貼留言