树莓派4B(Ubuntu20.04)使用LCD1602液晶屏开机自动显示IP及其他信息

树莓派4B装了Ubuntu20.04当做便携服务器在使用,为了便携,自然是不接网线使用WiFi,不接显示屏使用SSH远程连接工具,那就面临一个问题,在没有固定分配IP的情况下,怎么不通过接显示器获取IP用来远程连接呢?搜索看了下,最方便的应该就是开机自启自动显示IP等信息了。

在这里插入图片描述

  • Ubuntu20.04 Python环境下,获取IP、磁盘存储占用等配置信息
    • 获取IP
    import socket
    def getIP():
    	ip = socket.gethostbyname(socket.gethostname())
    	return 'IP:'+ str(ip)
    
    • 获取MAC
    import uuid
    def getMAC():
    	node = uuid.getnode()
    	macHex = uuid.UUID(int=node).hex[-12:]
    	MAC = []
    	for i in range(len(macHex))[::2]:
    		MAC.append(macHex[i:i+2])
    	MAC =':'.join(MAC)
    	return 'MAC:' + str(MAC)
    
    • 获取磁盘占用
    import os
    def getDisk():
    	 disk = os.statvfs("/")
    	 disk_size = disk.f_bsize * disk.f_blocks / (1024 ** 3)  # 1G = 1024M  1M = 1024KB 1KB = 1024bytes
    	 sizeStr = str("%s" % format(disk_size, '.2f'))
    	 disk_used = disk.f_bsize * (disk.f_blocks - disk.f_bfree) / (1024 ** 3)
    	 usedStr = str("%s" % format(disk_used, '.2f'))
    	 return usedStr +  "/" + sizeStr
    
  • 接入OLED屏幕,点亮屏幕显示
    import time
    import smbus
    BUS = smbus.SMBus(1)
    LCD_ADDR = 0x27
    BLEN = 1 #turn on/off background light
    def turn_light(key):
        global BLEN
        BLEN = key
        if key ==1 :
            BUS.write_byte(LCD_ADDR ,0x08)
        else:
            BUS.write_byte(LCD_ADDR ,0x00)
    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_lcd():
        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_lcd():
        send_command(0x01) # Clear Screen
    def print_lcd(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))
    if __name__ == '__main__':
        init_lcd()
        print_lcd(0, 0, 'Hello, world!')
    
    • 点亮显示
    #!/user/bin/env python 
    import smbus
    import datetime
    import time
    import pytz as pytz
    import sys
    import LCD1602 as LCD
    import os
    import socket
    import uuid
    def getIP():
    	ip = socket.gethostbyname(socket.gethostname())
    	return 'IP:'+ str(ip)
    def getMAC():
    	node = uuid.getnode()
    	macHex = uuid.UUID(int=node).hex[-12:]
    	MAC = []
    	for i in range(len(macHex))[::2]:
    		MAC.append(macHex[i:i+2])
    	MAC =':'.join(MAC)
    	return 'MAC:' + str(MAC)
    def getDisk():
    	 disk = os.statvfs("/")
    	 disk_size = disk.f_bsize * disk.f_blocks / (1024 ** 3)  # 1G = 1024M  1M = 1024KB 1KB = 1024bytes
    	 sizeStr = str("%s" % format(disk_size, '.2f'))
    	 disk_used = disk.f_bsize * (disk.f_blocks - disk.f_bfree) / (1024 ** 3)
    	 usedStr = str("%s" % format(disk_used, '.2f'))
    	 return usedStr +  "/" + sizeStr
    if __name__ == '__main__':  
        LCD.init_lcd()
        time.sleep(1)
        ipStr = getIP()
        LCD.print_lcd(0, 0, ipStr)
        for x in range(1, 4):
            LCD.turn_light(0)
            LCD.print_lcd(4, 1, 'LIGHT OFF')
            time.sleep(0.5)
            LCD.turn_light(1)
            LCD.print_lcd(4, 1, 'LIGHT ON ')
            time.sleep(0.5)
        LCD.turn_light(0)
        while True:
            tz = pytz.timezone('Asia/Shanghai')  # 东八区
            show = getDisk() + " " + str(datetime.datetime.fromtimestamp(int(time.time()), tz).strftime('%H:%M'))
            LCD.print_lcd(0, 1, show )
            time.sleep(0.2)
    
  • 设置开机自启动
    • 建立rc-local.service文件,如果存在的话可以不用创建
      sudo vim /etc/systemd/system/rc-local.service
    • 将下列内容复制进rc-local.service文件
      [Unit]
      Description=/etc/rc.local Compatibility
      ConditionPathExists=/etc/rc.local
      [Service]
      Type=forking
      ExecStart=/etc/rc.local start
      TimeoutSec=0
      StandardOutput=tty
      RemainAfterExit=yes
      SysVStartPriority=99
      [Install]
      WantedBy=multi-user.target
      
    • 创建文件rc.local
      sudo vim /etc/rc.local
    • 将下列内容复制进rc.local文件(对应脚本的位置和虚拟环境的位置自行修改)
      #!/bin/sh -e
      ##
      ## rc.local
      ##
      ## This script is executed at the end of each multiuser runlevel.
      ## Make sure that the script will "exit 0" on success or any other
      ## value on error.
      ##
      ## In order to enable or disable this script just change the execution
      ## bits.
      ##
      ## By default this script does nothing.
      # eaudio --start
      nohup /root/.virtualenvs/dj3/bin/python3 -u /opt/pi/getpi.py > test.out 2>&1 &
      
    • 给rc.local加上权限
      sudo chmod +x /etc/rc.local
    • 启用服务
      sudo systemctl enable rc-local
    • 启动服务并检查状态
      sudo systemctl start rc-local.service
      sudo systemctl status rc-local.service
    • 重启系统测试
      reboot
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

isSamle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值