예제 #1
0
    def __init__(self):
        self.i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21))
        self.sensor = bme280_float.BME280(address=0x76, i2c=self.i2c)

        self.temp = -1
        self.pressure = -1
        self.humidity = -1
예제 #2
0
def init_bme():
    # Initialise the i2c interface. We use SCL-to-D1, SDA-to-D2.
    # pin 5 (= D1) SCL naar BME280-SCL.
    # pin 4 (= D2) SDA naar BME280-SDA.
    i2c = I2C(sda=Pin(4), scl=Pin(5))
    bme = bme280_float.BME280(i2c=i2c)
    return (bme)
    def __init__(self):
        freq(160000000)
        self._i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)
        self._bme = bme280_float.BME280(i2c=self._i2c)
        self._adc = ADC(Pin(37))
        self._lis3dh = LIS3DH_I2C(self._i2c, address=0x19, int1=Pin(15))
        self._lis3dh.set_tap(tap=1,
                             threshold=10,
                             time_limit=10,
                             time_latency=20,
                             time_window=255)
        self._touchPad = TouchPad(Pin(32))
        self._blueled = Pin(4, Pin.OUT)
        self._blueled.off()
        self._mqttClient = None
        self._nb_leds = 4
        self._clock_pin = 14
        self._data_pin = 13
        self._empty_pin = 12
        self._spi = SPI(1,
                        baudrate=10000000,
                        sck=Pin(self._clock_pin),
                        mosi=Pin(self._data_pin),
                        miso=Pin(self._empty_pin))
        self._leds = DotStar(self._spi, self._nb_leds)
        for i in range(0, self._nb_leds):
            self._leds[i] = (0, 0, 0)

        try:
            self._oled = ssd1306.SSD1306_I2C(128, 64, self._i2c, 0x3c)
        except Exception as e:
            self._oled = None
            print("Exception occurred when initializing OLED.")
            print("Exception: " + str(e))
예제 #4
0
def main():
    start_time = utime.ticks_ms()
    # Turn LED for the duration of the program
    led = Pin(LED_PIN, Pin.OUT, value=1)
    # Show some information on the onboard OLED
    reset = Pin(SSD1306_SCL_RST, Pin.OUT, value=1)
    i2c_oled = I2C(
        scl=Pin(SSD1306_SCL, Pin.IN, Pin.PULL_UP),
        sda=Pin(SSD1306_SDA, Pin.IN, Pin.PULL_UP),
        freq=SSD1306_FREQ
    )
    oled = ssd1306.SSD1306_I2C(64, 32, i2c_oled)
    # BME280 temperature, pressure and humidity readings
    data = b""
    try:
        i2c_bme = I2C(scl=Pin(BME280_SCL), sda=Pin(BME280_SDA), freq=BME280_FREQ)
        bme = bme280.BME280(i2c=i2c_bme)
        temperature, pressure, humidity = bme.read_compensated_data()
    except (OSError, ValueError, NameError) as e:
        print(e)
        data += b"\x00\x00\x00"
        oled.text(ubinascii.hexlify(data), 0, 16)
        oled.text("ERROR!", 0, 24)
    else:
        print("Measurements:", temperature, "c", pressure, "Pa", humidity, "%")
        # Manipulate sensor values so that they occupy 1 byte each
        # Note how a +128 offset is used for the temperature (c) reading to
        # maintain 1 byte signed
        TEMP_OFFSET = const(128)
        data += round(temperature + TEMP_OFFSET).to_bytes(1, "big")
        data += round(pressure / 1000).to_bytes(1, "big")
        data += round(humidity).to_bytes(1, "big")
        # LoRaWAN / TTN send
        lora = uLoRa(
            cs=LORA_CS,
            sck=LORA_SCK,
            mosi=LORA_MOSI,
            miso=LORA_MISO,
            irq=LORA_IRQ,
            rst=LORA_RST,
            ttn_config=TTN_CONFIG,
            datarate=LORA_DATARATE,
            fport=LORA_FPORT
        )
        print("Sending packet...", lora.frame_counter, ubinascii.hexlify(data))
        lora.send_data(data, len(data), lora.frame_counter)
        print(len(data), "bytes sent!")
        lora.frame_counter += 1
        oled.text(ubinascii.hexlify(data), 0, 16)
        oled.text("SENT!", 0, 24)
    finally:
        oled.show()
        utime.sleep_ms(PROGRAM_WAIT_MS)
        led.off()
        deepsleep(PROGRAM_LOOP_MS - (utime.ticks_ms() - start_time))
예제 #5
0
    def armSensors(self):
        '''Arm available sensors by attaching their drivers
        '''

        for sensor in self.available_sensors:

            if sensor == 'BME280':
                bme280s = bme280.BME280(address=0x76, i2c=self.i2c)
                self.available_sensors[sensor]['reader'] = bme280s
                self.logger.log('info', 'Sensor BME280 armed')

            if sensor == 'MS5611':
                ms5611 = MS5611.MS5611(bus=self.i2c)
                self.available_sensors[sensor]['reader'] = ms5611
예제 #6
0
from machine import I2C, Timer, Pin
import sh1106
import bme280_float as bme280
from time import sleep
import network, utime
import ujson as json
import uP_-_14_40_-_oled_bme_280_IFTTT_modules as modules

led = Pin(21, Pin.OUT)

i2c = I2C(0)

display = sh1106.SH1106_I2C(128, 64, i2c, None, 0x3c)

bme = bme280.BME280(   i2c=i2c,
                       mode=bme280.BME280_OSAMPLE_8,
                       address=bme280.BME280_I2CADDR ) # Works ok with explicity settings

with open("/wifi_settings_ifttt.json") as credentials_json:   # This pattern allows you to open and read an existing file.
    settings = json.loads(credentials_json.read())

url = "https://maker.ifttt.com/trigger/uPython/with/key/" + settings["ifttt_key"]

wlan = network.WLAN(network.STA_IF) # This will create a station interface object.
                                    # To create an access point, use AP_IF (not covered here).


def timer_isr(event):
    led.on()
    temperature, pressure, humidity = bme.values # multiple assignment from tuple to variables
    print("")
예제 #7
0
from machine import Pin, I2C
#https://github.com/robert-hh/BME280
import bme280_float as bme280

#Read data from the sensor
i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
bme = bme280.BME280(i2c=i2c)
data = bme.values

#Print the data
print("temperature:" + data[0])
print("pressure:" + data[1])
print("humidity:" + data[2])
예제 #8
0
def TakeMeasurement(CONF_WEATHER):
    from machine import Pin, I2C, ADC
    from math import pow, sqrt, fabs
    from time import sleep
    import sys
    import bme280_float  # https://github.com/robert-hh/BME280

    result = {}

    def convertToF(tempC):
        return tempC * 1.8 + 32

    i2c = I2C(scl=Pin(5), sda=Pin(4))
    bme = bme280_float.BME280(i2c=i2c)

    # wait a sec
    sleep(1)

    # read data from bme280
    bme_data_tph = bme.read_compensated_data()

    # Get Temperature
    # result['temp_C'] = bme_data_tph[0] + CONF_WEATHER['TEMP_CORR']
    # result['temp_F'] = convertToF(result['temp_C'])
    temp_C = bme_data_tph[0] + CONF_WEATHER['TEMP_CORR']
    result['temp_F'] = convertToF(temp_C)

    # output = ['Temp: %.2f °C, %.2f °F; ' % (result['temp_C'], result['temp_F'])]
    output = ['Temp: %.2f °C, %.2f °F; ' % (temp_C, result['temp_F'])]

    # Get Humidity
    result['humidity'] = bme_data_tph[2]
    output.append('Humidity: %.2f %%; ' % result['humidity'])

    # Get Pressure
    # result['measured_Pres_hPa'] = bme_data_tph[1] / 100
    measured_Pres_hPa = bme_data_tph[1] / 100
    result['measured_Pres_inHg'] = bme_data_tph[1] / 3386.38867
    # output.append('Pressure: %.2f hPa, %.2f inHg; ' % (result['measured_Pres_hPa'], result['measured_Pres_inHg']))
    output.append('Pressure: %.2f hPa, %.2f inHg; ' %
                  (measured_Pres_hPa, result['measured_Pres_inHg']))

    # Calculate Relative Pressure
    # SLPressure_hPa = (((measured_Pres_hPa * 100.0)/pow((1-(float(CONF_WEATHER['ELEVATION']))/44330), 5.255))/100.0)
    # https://keisan.casio.com/exec/system/1224575267
    SLPressure_hPa = measured_Pres_hPa * pow(
        1 - .0065 * CONF_WEATHER['ELEVATION'] /
        (temp_C + 273.15 + .0065 * CONF_WEATHER['ELEVATION']), -5.257)
    result['rel_Pres_Rounded_hPa'] = round(SLPressure_hPa)
    result['rel_Pres_inHg'] = (SLPressure_hPa) / 33.8638867
    output.append('Pressure rel: %d hPa, %.2f inHg; ' %
                  (result['rel_Pres_Rounded_hPa'], result['rel_Pres_inHg']))

    # Get Dewpoint
    # result['dewPt_C'] = bme.dew_point
    # result['dewPt_F'] = convertToF(result['dewPt_C'])
    result['dewPt_F'] = convertToF(bme.dew_point)
    # output.append('Dewpoint: %.2f °C, %.2f °F; ' % (result['dewPt_C'], result['dewPt_F']))
    output.append('Dewpoint: %.2f °F; ' % result['dewPt_F'])

    # Dewpoint Spread
    result['dewPtSpread_F'] = result['temp_F'] - result['dewPt_F']
    output.append('Dewpoint Spread: %.2f °F; ' % result['dewPtSpread_F'])

    # Calculate HI (heatindex) --> HI starts working above 26.7°C
    # Reference: https://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
    # Calculation is in Fahrenheit
    if temp_C > 26.7:
        c1 = -42.379
        c2 = 2.04901523
        c3 = 10.14333127
        c4 = -0.22475541
        c5 = -6.83783e-3
        c6 = -5.481717e-2
        c7 = 1.22874e-3
        c8 = 8.5282e-4
        c9 = -1.99e-6

        T = result['temp_F']
        R = result['humidity']
        Tsq = T * T
        Rsq = R * R

        result['heatIndex_F'] = (c1 + c2 * T + c3 * R + c4 * T * R + c5 * Tsq +
                                 c6 * Rsq + c7 * Tsq * R + c8 * T * Rsq +
                                 c9 * Tsq * Rsq)

        if T <= 112 and R < 13:
            result['heatIndex_F'] -= ((13 - R) / 4) * sqrt(
                (17 - fabs(T - 95.0)) / 17)
        if T <= 87 and R > 85:
            result['heatIndex_F'] += ((R - 85) / 10) * ((87 - T) / 5)

        output.append('HeatIndex: %.2f °F; ' % result['heatIndex_F'])
    else:
        result['heatIndex_F'] = result['temp_F']
        print('Not warm enough (less than 80.1 °F) for Heat Index')

    # Battery Voltage
    # Voltage Divider R1 = 220k+100k+220k = 540K and R2 = 100k
    calib_factor = 5.1315  # varies -- fix for your battery
    adc = ADC(0)
    raw = adc.read()
    result['volt'] = raw * calib_factor / 1024
    output.append('Voltage: %.2f V\n' % result['volt'])

    #print(''.join(output))
    for item in output:
        print('%s' % item, end='')
    del output
    # round floats to 2 decimal places
    result = dict(
        zip(
            result,
            map(lambda x: round(x, 2) if isinstance(x, float) else x,
                result.values())))

    del bme
    del sys.modules['bme280_float']

    return result
예제 #9
0
파일: main.py 프로젝트: ionhedes/cansat19
        print(" ! LoRa off\n")

    try:
        uart_com = UART(1, pins=("P3", "P4"), baudrate=9600)
        print(" . UART communication init complete\n")
    except:
        print(" ! UART raised an exception\n")

    try:
        i2c = I2C(0, I2C.MASTER, baudrate=100000)
        print(" . I2C init complete\n")
    except:
        print(" ! I2C raised an exception\n")

    try:
        bme = bme280_float.BME280(i2c=i2c, address=0x77)
        print(" . BME280 - temperature/pressure/humidity sensor ON\n")
    except:
        print(" ! BME280 - temperature/pressure/humidity sensor OFF\n")

    try:
        imu = MPU6050(i2c)
        print(" . MPU6050 - accelerometer/gyroscope ON\n")
    except:
        print(" ! MPU6050 - accelerometer/gyroscope OFF\n")

    try:
        ccs = CCS811.CCS811(i2c=i2c, addr=91)
        print(" . CCS811 - environmental sensor ON\n")
    except:
        print(" ! CCS811 - environmental sensor OFF\n")
# BME280 with OLED display

from machine import Pin, I2C, RTC
import ssd1306, time, bme280_float
from tinypico import set_dotstar_power

set_dotstar_power(False)
rtc = RTC()
i2c = I2C(scl=Pin(21), sda=Pin(22))
oled = ssd1306.SSD1306_I2C(128, 32, i2c, 0x3c)  # small display
bme = bme280_float.BME280(i2c=i2c)

oled.contrast(0)  #set contrast to low


def display_temperature():
    temp, pres, hum = bme.values
    oled.fill(0)
    oled.text('T: ' + temp, 0, 0, 1)
    oled.show()


def display_humidity():
    temp, pres, hum = bme.values
    oled.fill(0)
    oled.text('H: ' + hum, 0, 0, 1)
    oled.show()


def display_pressure():
    temp, pres, hum = bme.values
예제 #11
0
import bme280_float as bme280
from utime import sleep_ms
import sys

uid = 'BME280SN004'

sleep_ms(1000)

SDA_PIN = machine.Pin(16)
SCL_PIN = machine.Pin(17)
SCL_FREQ = 400000
i2c = machine.I2C(0, sda=SDA_PIN, scl=SCL_PIN, freq=SCL_FREQ)

try:
    BME280_I2CADDR = 0x76
    bme = bme280.BME280(i2c=i2c, address=BME280_I2CADDR)
except:
    try:
        BME280_I2CADDR = 0x77
        bme = bme280.BME280(i2c=i2c, address=BME280_I2CADDR)
    except Exception as e:
        machine.reset()

while True:
    try:
        val = bme.values
    except:
        sleep_ms(1000)
        try:
            val = bme.values
        except:
예제 #12
0
class sensors:
    with open("config.py") as json_data_file:
        conf = ujson.load(json_data_file)

    import utime
    led = Pin(2, Pin.OUT)  #internal LED is on pin 2

    i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)
    print('Scanning i2c bus...')
    devices = i2c.scan()
    if len(devices) == 0:
        print("No i2c device !")
    else:
        print('i2c devices found:', len(devices))
        for device in devices:
            print("Decimal address: ", device, " | Hexa address: ",
                  hex(device))

    onewirePin = machine.Pin(15)
    wire = onewire.OneWire(onewirePin)
    try:
        ds = ds18x20.DS18X20(wire)
        roms = ds.scan()
        # roms.append(roms[0])
        if roms == []:
            roms = 0
        for rom in roms:
            print('      DS18b20  devices:', int.from_bytes(rom, 'little'),
                  hex(int.from_bytes(rom, 'little')))
    except Exception as e:
        conf['Run_DS18B20'] = 'false'
        print("      DS18B20 start error - ", e)

#////////////////// INA setup /////////////////////////
    try:
        SHUNT_OHMS = 0.1
        ina = INA219(SHUNT_OHMS, i2c)
        print('INA219 instance created')
    except Exception as e:
        print("      INA start error - ", e)

    try:
        ina.configure()  # gain defaults to 3.2A. ina219.py line 132
        print('     INA219 instance configure run')
    except Exception as e:
        print('INA configure failed, possibly not connected. Error=', e)

#////////////////// BME setup /////////////////////////
    try:
        bme = bme280_float.BME280(i2c=i2c)
        print('BME started')
    except Exception as e:
        print('BME start failed, possibly not connected. Error=', e)

#////////////////// ADS1115 setup /////////////////////
#ads1115 set up, , 0x48 default, 0x4a->connect ADDR pin to SDA
    try:
        addr = 0x4a
        gain = 0
        ads1115A = ads1x15.ADS1115(i2c, addr, gain)
        print("ADS1115A started")
    except Exception as e:
        print('ADS1115A start failed, possibly not connected. Error=', e)

    try:
        addr = 0x48
        gain = 0
        ads1115B = ads1x15.ADS1115(i2c, addr, gain)
        print("ADS1115B started")

    except Exception as e:
        print('ADS1115B start failed, possibly not connected. Error=', e)
#___________________________________________________________________________________________
#////////////////// INIT /// /////////////////////////

    def __init__(self):
        for key in self.conf.keys():
            print(key, "---", self.conf[key])

        print('new sensors instance created')

    def debugPrint1(self, message):
        if self.conf['debugPrint1'] == 'True':
            print(message)

    def connectWifi(self):
        import network
        sta_if = network.WLAN(network.STA_IF)
        print('\n', 'sta_if.active = ', sta_if.active(), '\n')
        sta_if.active(True)
        print('\n', 'sta_if.active = ', sta_if.active(), '\n')
        networks = sta_if.scan()

        if not sta_if.isconnected():
            print('        connecting to network...')

            print('\n', '        No. of networks = ', len(networks), '\n')
            print('        networks = ', networks, '\n')
            try:
                sta_if.ifconfig((self.conf['IP_Address'], '255.255.255.0',
                                 '10.10.10.1', '10.10.10.1'))
                sta_if.connect(self.conf['ssid'], self.conf['password'])
                self.udpAddr = '10.10.10.1'
            except Exception as e:
                print('connect wifi failure, error =', e)
                pass

            counter = 0
            while not sta_if.isconnected():
                utime.sleep(0.25)
                print("\r>", counter, end='')
                counter += 1
                self.flashLed()
                if counter > 100:
                    machine.reset()
                pass
        print('\n', '    CONNECTED!! network config:', sta_if.isconnected(),
              '\n', sta_if.ifconfig(), '\n')

    def flashLed(self):
        self.led.value(not self.led.value())

    def getVoltage(self):
        value = [0, 1, 2, 3]
        voltage = [0, 1, 2, 3]
        calibration = 1
        for i in range(4):  # 0 - 3
            #           def read(self, rate=4, channel1=0, channel2=None):, line 156 ads1x15.py
            try:
                value[i] = self.ads1115A.read(4, i)
                voltage[i] = self.ads1115A.raw_to_v(value[i])
                if i == 2:
                    calibration = 6.09
                elif i == 3:
                    calibration = 6.11
                self.insertIntoSigKdata("electrical.ads1115-1." + str(i),
                                        voltage[i] * calibration)
                calibration = 1
            except Exception as e:
                pass

        try:
            calibration = 6.09
            value = self.ads1115B.read(4, 0, 1)
            voltage = self.ads1115B.raw_to_v(value)
            self.insertIntoSigKdata("electrical.ads1115-2.1",
                                    voltage * calibration)
            calibration = 6.09
            value = self.ads1115B.read(4, 2, 3)
            voltage = self.ads1115B.raw_to_v(value)
            self.insertIntoSigKdata("electrical.ads1115-2.2",
                                    voltage * calibration)
        except Exception as e:
            pass

    def getPressure(self, destination):

        try:
            vals = self.bme.read_compensated_data()
        except Exception as e:
            print('BME failed, possibly not connected. Error=', e)
            pass
        else:
            temp = vals[0]
            pres = vals[1]
            hum = vals[2]
            if destination == 'signalk':
                self.insertIntoSigKdata("environment.outside.humidity",
                                        hum)  # insertIntoSigKdata(path, value)
                self.utime.sleep_ms(100)
                self.insertIntoSigKdata("environment.outside.temperature",
                                        temp + 273.15)
                self.utime.sleep_ms(100)
                self.insertIntoSigKdata("environment.outside.pressure", pres)
                self.utime.sleep_ms(100)
            elif destination == 'influxdb':
                print(' would send to udp here')

    def getCurrent(self):
        try:
            self.insertIntoSigKdata("esp.currentSensor.voltage",
                                    self.ina.voltage())
            self.utime.sleep_ms(100)
            self.insertIntoSigKdata("esp.currentSensor.current",
                                    self.ina.current())
            self.utime.sleep_ms(100)
            self.insertIntoSigKdata("esp.currentSensor.power",
                                    self.ina.power())

        except Exception as e:
            print('INA1 read failed, Error=', e)
            pass

    def getTemp(self):
        try:
            self.ds.convert_temp()
            utime.sleep_ms(200)
            for rom in (self.roms):
                value = self.ds.read_temp(rom)
                if rom == (b'(\x7f@V\x05\x00\x00\xaf'):
                    path = "esp.propulsion.alternator.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)
                elif rom == (b"('\xd4V\x05\x00\x00\x88"):
                    path = "esp.propulsion.exhaust.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)
                elif rom == (b'(a\xdeV\x05\x00\x00\xf2'):
                    path = "esp.propulsion.head.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)
                elif rom == (b'(\xdd\xdfU\x05\x00\x00\xcd'):
                    path = "esp.electrical.batteries.housebank.temperature"
                    self.insertIntoSigKdata(path, value + 273.15)

        except Exception as e:
            print("DS18B20 error Error=", e)
            pass

    def insertIntoSigKdata(self, path, value):
        _sigKdata = {"updates": [{"values": []}]}
        _sigKdata["updates"][0]["values"].append({
            "path": path,
            "value": value
        })
        self.sendToUDP(ujson.dumps(_sigKdata), '10.10.10.1',
                       self.conf['sigK_udp-port'])
        try:
            self.debugPrint1(_sigKdata)
        except Exception as e:
            print("debug print error=", e)

    def sendToUDP(self, message, udpAddr, udpPort):
        try:
            s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
            s.sendto(message, (udpAddr, int(udpPort)))
            s.close()
        except Exception as e:
            print("UDP sending error=", e)
            pass

    def str_to_bool(self, s):
        return str(s).lower() in ("yes", "true", "t", "1")

    def checkConnection(self):
        wlan = network.WLAN(network.STA_IF)
        if not wlan.isconnected():
            print('Not connected to wifi, rebooting...')
            machine.reset()

    def reboot(self):
        print("..rebooting..")
        machine.reset()

    def dataBasesend(self):  #which sensors to send, triggered by timer
        self.flashLed()

    def datasend(self):  #which sensors to send, triggered by timer
        self.flashLed()
        self.insertIntoSigKdata("esp.heartbeat.led", self.led.value())
        if self.conf['Run_BME280'] == 'True':
            self.getPressure('signalk')
        if self.conf['Run_ADS1115'] == 'True':
            self.getVoltage()
        if self.conf['Run_INA-219'] == 'True':
            self.getCurrent()
        if self.conf['Run_DS18B20'] == 'True':
            self.getTemp()
        self.checkConnection()

    def sendi2c(self):
        devices = self.i2c.scan()
        if len(devices) == 0:
            print("No i2c device !")
        else:
            print('i2c devices found:', len(devices))
            for device in devices:
                print("Decimal address: ", device, " | Hexa address: ",
                      hex(device))
예제 #13
0
# legacy tested method for bmp280
def bmp280_get_sensor_values():
    from machine import I2C, Pin
    from bmp280 import BMP280
    bus = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
    bmp = BMP280(bus, addr=I2C_ADDRESS)
    return bmp.temperature, bmp.pressure, None

# i think this one works on both sensors
# assumes SCL -> D1 Pin(5) and SDA -> D2 Pin(4)
# temperature, pressure, humidity
def bme280_get_sensor_values()
    from machine import I2C, Pin
    import bme280_float
    bus = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
    bme = bme280_float.BME280(i2c=bus, address=I2C_ADDRESS)
    return bme.read_compensated_data()

def send_gauge(name, value, port=STATSD_PORT, host=STATSD_HOST):
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(name + ":" + str(value) + "|g", (host, port))

def do_sleep(stime):
    import machine

    # configure RTC.ALARM0 to be able to wake the device
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

    # set RTC.ALARM0 to fire after 10 seconds (waking the device)
예제 #14
0
def bme_main():
    from machine import I2C
    from machine import Pin
    from machine import Timer
    from machine import freq
    from utime import sleep
    import math
    import bme280_float

    freq(160000000)
    led = ledEnclosed(True)
    tim = Timer(-1)
    tim.init(period=300,mode=Timer.PERIODIC,callback=lambda t:led())

    i2c=I2C(scl=Pin(4),sda=Pin(5),freq=400000)
    print(i2c.scan()) 
    oled = ssd1306.SSD1306_I2C(128,64,i2c)
    bme280 = bme280_float.BME280(i2c=i2c)

    ame = bytearray(b'\xe3\xf3\x33\x33\xb3\x33\x33\x33\xff\xff\x33\xb3\x33\x33\xf3\xf3\xff\xff\x00\x00\x08\x11\x22\x00\xff\xff\x00\x08\x51\x80\xc0\xff')
   
    hare = bytearray(b'\xfc\xfc\x0c\x0c\x0c\x0c\x0c\x0c\xfc\xfc\x00\x00\x00\x10\x10\x90\x90\xff\x90\x90\x10\x10\x00\x00\xff\xff\x18\x18\x18\x18\x18\x18\xff\xff\x00\x04\x04\xf4\x94\x94\x94\x97\x94\x94\xf4\x04\x04\x00\x7f\x7f\x30\x30\x30\x30\x30\x30\x7f\x7f\x00\x00\x00\x7f\x04\x04\x04\x04\x04\x24\x7f\x00\x00\x00')

    yuki = bytearray(b'\xf3\xf3\x33\xb3\xb3\xb3\x33\xb3\xb3\xb3\x33\xff\xff\x33\xb3\xb3\xb3\x33\xb3\xb3\xb3\x33\xf3\xf3\x0f\x0f\x00\x04\x04\x04\x20\x24\x24\x24\x20\x23\x2f\x20\x24\x24\x24\xe0\x04\x04\x04\x00\x0f\x0f\x00\x00\x00\x00\x00\x00\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22\x3f\x00\x00\x00\x00\x00\x00')

    kumori = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7f\x49\x49\x49\x49\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfd\xfd\x05\x25\x25\x25\xb5\x25\x05\xff\xff\x05\x25\x25\x25\xb5\x25\x05\x05\xfd\x00\x00\x00\x00\x03\x03\x00\x01\x09\x09\x49\x49\x68\x5b\x4b\x48\x59\x69\x49\x89\x09\x08\x01\x03\x00\x00')

    f = framebuf.FrameBuffer(hare,24,24,framebuf.MONO_VLSB)
    f1 = framebuf.FrameBuffer(kumori,24,24,framebuf.MONO_VLSB)
    r,s,ntp = net()
    
    #get ds3231 device functions
    dsrtc_rd, dsrtc_upk, dsrtc_alarm1, dsrtc_chk = dsrtc(i2c)
    dsrtc_chk(c=1)
    dsrtc_alarm1(23,42)

    y=64
    oled.text('HI',0,64-16,1)
    oled.show()
    while True:
        x = dsrtc_rd()
        t,p,h=bme280.read_compensated_data()
        bme = bme280.values
        s(bme[0] + ' ' + bme[1] + ' ' + bme[2] + '\n') 
        t = '{:02x}:{:02x}:{:02x}'.format(x[2],x[1],x[0])
        oled.text(t,0,0,1)
        oled.text(bme[0],0,12,1)
        oled.text(bme[1],0,24,1)
        oled.text(bme[2],0,36,1)

        if p<100200:
            oled.blit(f1,96,y,0)
        else:
            oled.blit(f,96,y,0)

        oled.show()
        sleep(0.05)
  
        #blank out buffer no need to show
        oled.text(t,0,0,0)
        oled.text(bme[0],0,12,0)
        oled.text(bme[1],0,24,0)
        oled.text(bme[2],0,36,0)
        
        oled.fill_rect(96,y,24,24,0)

        if y>-24:
          y=y-2
        else:
          y=64

        a=dsrtc_chk()
        c = a[0] & 0x01  
        if c==1:
            print('alarm')
            oled.text('Alarm',0,64-8,1)
            dsrtc_chk(c=1)
        else:
            oled.text('Alarm',0,64-8,0)