from machine import I2C,Pin
import ugfx,time

BME280_ADDR = 0x76
BME280_REGISTER_CHIPID = 0xD0
BME280_REGISTER_PRESSUREDATA = 0xF7
BME280_REGISTER_CONTROL = 0xF4
BME280_REGISTER_CONFIG = 0xF5

ugfx.init()
ugfx.clear(ugfx.WHITE)

i2c = I2C(sda=Pin(26),scl=Pin(27),freq=200000)

ugfx.string(0,0,"Finding sensor","PermanentMarker22",ugfx.BLACK)
ugfx.flush()

try:
  buf = i2c.readfrom_mem(BME280_ADDR,BME280_REGISTER_CHIPID,1)
except OSError as e:
  ugfx.string(25,25,"No sensor :(","PermanentMarker22",ugfx.BLACK)
  ugfx.flush()
  time.sleep(2)
  raise RuntimeError("Sensor not found")

if (buf[0] != 0x60):
  ugfx.string(25,25,"Device is not a BME280.","PermanentMarker22",ugfx.BLACK)
  ugfx.flush()
  time.sleep(2)
  raise RuntimeError("Sensor not found")

# Sensor found, initialise / turn sensors on.
i2c.writeto_mem(BME280_ADDR,BME280_REGISTER_CONTROL,b'\x07')

# Start a loop to read the sensor value :)
while 1:
  ugfx.clear(ugfx.WHITE)
  data = i2c.readfrom_mem(BME280_ADDR,BME280_REGISTER_PRESSUREDATA,3)
  result=0
  for b in data:
   result = result * 256 + int(b)
  ugfx.string(0,0,"Pressure:" + str(result),"PermanentMarker22",ugfx.BLACK)
  ugfx.flush()
  time.sleep(2)