树莓派iic驱动OLED 显示当前日期和时间

 1 #!/usr/bin/env python  
 2   
 3 import time  
 4 import datetime as datetime  
 5 from luma.core.interface.serial import i2c, spi  
 6 from luma.core.render import canvas  
 7 from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
 8 from PIL import ImageDraw, Image,ImageFont  
 9   
10 device = sh1106(port=1, address=0x3C)  
11 font = ImageFont.load_default()  
12 fontYear = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 18)  
13 font2 = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 16)  
14   
15 def Show(d,fullDt):     
16       
17     y =  fullDt.strftime('%Y-')  
18     dt = fullDt.strftime('%m-%d')  
19     tm = fullDt.strftime('%H:%M:%S')    
20   
21     with canvas(d) as draw:          
22         draw.text((40, 0), "TIME", font=fontYear,fill=255)  
23         draw.text((10, 22), y, font=font2, fill=255)  
24         draw.text((60, 22), dt, font=font2, fill=255)  
25         draw.text((20, 44), tm, font=font2, fill=255)
26   
27 def main():  
28     nowDt = datetime.datetime.now() + datetime.timedelta(hours=8)  
29     while True:  
30         Show(device,nowDt)  
31         nowDt = nowDt + datetime.timedelta(seconds=1)  
32         time.sleep(1)  
33   
34 if __name__ == "__main__":  
35     main()  

 环境配置:

sudo apt-get install -y python-smbus  
sudo apt-get install -y i2c-tools  

运行一下

 sudo i2cdetect -y 1

正常情况下默认在0x3C处有标注,这就说明接线成功了。

sudo apt-get install libfreetype6-dev libjpeg-dev build-essential  

安装python3相关

sudo apt-get install python3-dev python3-pip  
sudo -H pip3 install --upgrade luma.oled  

 

 

posted @ 2018-06-01 15:37  憨八龟  阅读(1071)  评论(0编辑  收藏  举报