ラズベリーパイpicoでCO2測定③OLEDでグラフ表示をする習作
CO2濃度は短時間に大きく変化するので、グラフ表示をできると便利だと思いました。OLED(ssd1306)で、CO2濃度を数値表示と同時に時系列で棒グラフに表示できるようにしたい。はじめに、ラズパイPICOについている温度センサーで得た温度をグラフ化することを習作として始めてみました。データを得ることが簡単だからです。Windows上のThonny上でmicroPythonでコーディングしました。######################################################## SSD1306 OLED Display I2C Tests with the Raspberry Pi Pico# 2021/5/6 by BenzennYa# ssd1306 package from# https://github.com/raspberrypi/pico-micropython-examples/tree/master/i2c/1306oled########################################################from machine import Pin, I2Cfrom ssd1306 import SSD1306_I2Cimport utime#pix_res_x = 128 # SSD1306 horizontal resolutionpix_res_y = 64 # SSD1306 vertical resolutioni2c_dev = I2C(1,scl=Pin(15),sda=Pin(14),freq=100000) # start I2C on I2C1 (GPIO 26/27)i2c_addr = [hex(ii) for ii in i2c_dev.scan()] # get I2C address in hex formatoled = SSD1306_I2C(pix_res_x, pix_res_y, i2c_dev) # oled controller#----画面表示---oled.fill(0) #OLEDの表示を消すoled.text("Temp: C",20,0) #数値表示用の固定文oled.line(0,15,0,64,1) #グラフ軸oled.text("20",2,38,1)oled.text("40",2,10,1)oled.show()#gx=0 #グラフx軸初期化#------------------#onbord temperature の初期設定sensor_temp = machine.ADC(4)conversion_factor = 3.3 / (65535)#----温度数値とグラフの表示---while True: for gx in range(98): reading = sensor_temp.read_u16() * conversion_factor #温度を取得し補正する temperature = 27 - (reading - 0.706)/0.001721 temp = int(temperature+.5) # 温度を整数値に oled.text(str(temp),65,0) # 温度数値表示 oled.show() utime.sleep(0.01) # 時間をおいて(実験のため0.01秒としたが、実際は60秒くらいで) # 温度数値を消去 for v in range(8): oled.line(64,v,80,v,0) oled.show() # oled.line(gx+20,64,gx+20,64-temp,1) # 棒グラフを書く oled.line(gx+21,64,gx+21,15,0) # 一つ先の棒グラフを消す oled.show() #oled show #横軸97picselで先頭に戻す if gx == 97: gx=0#-----------以上です。ラズパイPICO内の/Libディレクトリにssd1306.pyを収めて、上のコードと一緒に走らせます。ssd1306.pyは上のコードの最初のコメント最後に記してあります。ssd1306.pyはOLEDのコントロールをしているのですが、このコマンドがなかなか見つからず苦労しました。ネットから見つけて、上のコードに生かしたのはoled.line(横開始位置,縦開始位置,横終了位置,縦終了位置,1)で、最後の’1’は点灯、'0'は消灯です。具体的にはoled.line(gx+20,64,gx+20,64-temp,1) # 棒グラフを書くやoled.line(64,v,80,v,0) #数値消去に使うです。これで、なんとかグラフ化と数値表示ができそうです。CO2測定器ができたところで、改めで丁寧に解説しようと思っています。