继续树莓派4B+OLED:开机自动显示IP地址
因為有了之前(樹莓派:Adafruit的I2C SSD1306 OLED驅動)那篇的基礎,想干脆讓它開機自動顯示IP地址。
首先當然找獲取IP的代碼。記得前幾年抄過一段,所以又找了出來:
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])當時調用很簡單,因為我是用無線的,所以歷史代碼調用用了這一句:
ip = get_ip_address('wlan0')
然而今天再拿出來試居然報錯了。解決起來倒是非常簡單,加個“b”類型前綴即可:
ip = get_ip_address(b'wlan0')結合示例中的代碼,另存了一份代碼,命名為s.py,完整代碼如下:
import timeimport Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306from PIL import Image from PIL import ImageDraw from PIL import ImageFont#import subprocess import socket import fcntl import struct #import commandsdef 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])ip = get_ip_address(b'wlan0')RST = None # on the PiOLED this pin isnt used DC = 23 SPI_PORT = 0 SPI_DEVICE = 0disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)disp.begin() disp.clear() disp.display()width = disp.width height = disp.height image = Image.new('1', (width, height))draw = ImageDraw.Draw(image)draw.rectangle((0,0,width,height), outline=0, fill=0)padding = -2 top = padding bottom = height-padding x = 0font = ImageFont.truetype('/usr/share/fonts/truetype/noto/NotoMono-Regular.ttf', 14)draw.rectangle((0,0,width,height), outline=0, fill=0)#cmd = "hostname -I" #IP = subprocess.check_output(cmd, shell = True )draw.text((x, top), ip, font=font, fill=255) disp.image(image) disp.display()然后就是設置開機自動執行了。意外的,并沒有想象中順利,無論是使用/etc/rc.local還是crontab -e。沒有深究,感覺是要么python相關的庫調取不到,要么bash環境有問題。
最終使用systemd解決。
在/usr/lib/systemd/system下新建一個后綴為.service的文件(我用了showip-oled.service),內容如下:
[Unit] Description=Show IP on OLED After=network.target[Service] Type=oneshot ExecStart=/usr/bin/python3 -u /home/pi/Adafruit_Python_SSD1306/examples/s.py Restart=on-failure RestartSec=6 User=pi[Install] WantedBy=multi-user.target具體含義可以參考:Systemd的使用指南 - 簡書 (jianshu.com)https://www.jianshu.com/p/7fd8b6ea336e
?因為獲取IP并展示在OLED屏幕上只需要在開機時執行,因此Type用了oneshot。一開始沒有加Restart和RestartSec,結果測試時發現腳本運行到獲取ip相關的地方會報錯,因此最終還是加上了這兩項。
Service文件保存(含新建、修改等)后可以執行sudo systemctl daemon-reload讓系統重刷一下。然后嘗試?sudo systemctl start showip-oled.service 看看是否能正常運行,并用sudo systemctl status showip-oled.service 確認。最后運行下?sudo systemctl enable showip-oled.service 使能自動運行。
最后就可以正式測試了。由于我發現樹莓派關機后只要不撤電源線,OLED仍可繼續顯示,因此建議關機后先把電源也斷開,確保OLED無任何顯示,之后再給樹莓派通電。正常情況下應該能顯示IP地址了。如果還是不行,可以再用?sudo systemctl status showip-oled.service 看看還有啥錯。
總結
以上是生活随笔為你收集整理的继续树莓派4B+OLED:开机自动显示IP地址的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2-6_Cleaning_Data
- 下一篇: EPON OLT光模块RSSI问题分析报