LoginSignup
12
13

More than 3 years have passed since last update.

Raspberry Pi PicoのmicroPythonでI2CとADCを使ってみる

Last updated at Posted at 2021-02-07

Raspberry Pi Pico

まだ、Arduino IDEに対応していないので、TonneyにてmicroPythonを使っています。

I2CでLCD制御、ADCで温度センサーを取得する

Raspberry Pi Picoに温度センサーが実装されています。
手持ちの秋月のI2C接続小型LCDモジュール(AE-AQM0802A)を使いました。

ソースコード

# MicroPython for Rapperry Pi Pico
import utime

class ST7032():

    def __init__(self, i2c, addr=0x3e):
        self.i2c = i2c
        self.addr = addr
        self.buf = bytearray(2)
        self.initDisplay()

    def writeCmd(self, cmd):
        self.buf[0] = 0x00
        self.buf[1] = cmd
        self.i2c.writeto(self.addr, self.buf)

    def writeData(self, char):
        self.buf[0] = 0x40
        self.buf[1] = char
        self.i2c.writeto(self.addr, self.buf)

    def initDisplay(self):
        self.i2c.writeto(self.addr, b'\x00\x38')
        self.i2c.writeto(self.addr, b'\x00\x39')
        self.i2c.writeto(self.addr, b'\x00\x14')
        self.i2c.writeto(self.addr, b'\x00\x73')
        self.i2c.writeto(self.addr, b'\x00\x56')
        self.i2c.writeto(self.addr, b'\x00\x6c')
        self.i2c.writeto(self.addr, b'\x00\x38')
        self.i2c.writeto(self.addr, b'\x00\x0C')
        self.i2c.writeto(self.addr, b'\x00\x01')

    def clear(self):
        self.writeCmd(0x01)
        utime.sleep(0.01)
        self.writeCmd(0x02)
        utime.sleep(0.01)

    def home(self):
        self.write_cmd(0x02)
        utime.sleep(0.01)

    def setContrast(self, contrast):
        if contrast < 0:
            contrast = 0
        if contrast > 0x0f:
            contrast = 0x0f
        self.writeCmd(0x39)
        self.writeCmd(0x70 + contrast)

    def setCursor(self, x, y):
        if x < 0: x = 0
        if y < 0: y = 0
        addr = y * 0x40 + x
        self.writeCmd(0x80 + addr)

    def print(self, str):
        for c in str:
            self.writeData(ord(c))

if __name__ == '__main__':

    import utime
    from machine import Pin, I2C
    from ST7032 import ST7032

    sensor_temp = machine.ADC(4)
    conversion_factor = 3.3 / (65535)

    i2c=I2C(0, scl=Pin(17), sda=Pin(16), freq=100000)

    lcd = ST7032(i2c) 
    lcd.setContrast(1)
    lcd.clear()

    while True:
        reading = sensor_temp.read_u16() * conversion_factor

        temperature = 27 - (reading - 0.706)/0.001721
        tempStr = "  {:5.1f}C".format(temperature)
        lcd.setCursor(0, 0)
        lcd.print('Temp:')
        lcd.setCursor(0, 1)
        lcd.print(tempStr)
        utime.sleep(1)

参考

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13