def __init__():
        if(VC0706.wlan == None):
            VC0706.wlan = sendData.connectLocalBox()
            rtc = RTC()
            rtc.ntp_sync('fr.pool.ntp.org')

        if(VC0706.sd == None):
            mountSDCard()


        if(VC0706.uart == None):
            VC0706.uart = UART(2, baudrate=38400, pins=('G8','G7'), timeout_chars=5, bits=8, parity=None, stop=1)
            VC0706.uart.readall()
            setsize(VC0706_160x120)
            reset()
        gc.enable()
Beispiel #2
0
    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)
Beispiel #3
0
class DS3231:
    def __init__(self):
        self.ds3231 = I2C(0, I2C.MASTER, baudrate=100000, pins=('GP15', 'GP10'))
        self.rtc = RTC()
        
    def loadTime(self):
        if DS3231_I2C_ADDR in self.ds3231.scan():
            data = self.ds3231.readfrom_mem(DS3231_I2C_ADDR, 0, 7)
            ss=bcd2dec(data[0] & 0b01111111)
            mm=bcd2dec(data[1] & 0b01111111)
            if data[2] & 0b01000000 > 0:
                hh=bcd2dec(data[2] & 0b00011111)
                if data[2] & 0b00100000 >0:
                    hh+=12
            else:
                hh=bcd2dec(data[2] & 0b00111111)
            DD=bcd2dec(data[4] & 0b00111111)
            MM=bcd2dec(data[5] & 0b00011111)
            YY=bcd2dec(data[6])
            if data[5] & 0b10000000 > 0:
                YY=YY+2000
            else:
                YY=YY+1900
            self.rtc.init((YY,MM,DD,hh,mm,ss))
        else:
            print("DS3231 not found on I2C bus at %d" % DS3231_I2C_ADDR)


    def saveTime(self):
        (YY,MM,DD,hh,mm,ss,micro,tz) = self.rtc.now()
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 0,dec2bcd(ss));
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 1,dec2bcd(mm));
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 2,dec2bcd(hh));
        self.ds3231.writeto_mem(DS3231_I2C_ADDR, 4,dec2bcd(DD));
        if YY >= 2000:
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5,dec2bcd(MM) | 0b10000000);
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6,dec2bcd(YY-2000));
        else:
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 5,dec2bcd(MM));
            self.ds3231.writeto_mem(DS3231_I2C_ADDR, 6,dec2bcd(YY-1900));
Beispiel #4
0
    def set_alarm(self, now, json_metadata):
        import json
        json_dict = json.loads(json_metadata)

        # Now we know the time too
        self.rtc = RTC(datetime=now)
        list_int = json_dict["wakeup"][:6]
        time_str = ",".join([str(x) for x in list_int])

        self.log("Setting alarm for " + time_str)
        self.rtc.alarm(time=tuple(list_int))

        if self.rtc.alarm_left() == 0:
            self.log("Alarm failed, setting for +1 hour")
            self.rtc.alarm(time=3600000)

        del json
import pycom
import math
import gc

from network import WLAN
from mqtt import MQTTClient

execfile('/flash/Wi-Fi/Wi-Fi.py')

f_device = open('/flash/Config/Device_Details.txt', 'r')

device_setting = f_device.readline()
device_strings = [i.strip() for i in device_setting.split(',')]
f_device.close()

rtc = RTC()
adc = ADC()
echo = Pin(Pin.exp_board.G7, mode=Pin.IN)
trigger = Pin(Pin.exp_board.G8, mode=Pin.OUT)
trigger(0)
chrono = Timer.Chrono()
pycom.heartbeat(False)

def settimeout(duration):
     pass

client = MQTTClient("garage", "your mqtt broker host", user="******", password="******", port=mqtt port here)
client.settimeout = settimeout
client.connect()
mqtt_topic = "garagedoor"
Beispiel #6
0
from machine import RTC
import time
import server

print('main start')


def birdFeeder():
    import servoTest
    servoTest.run(5)


p1 = Pin(2, Pin.OUT)

if (alarm.init()):
    print('alarm triggered')
    p1.off()

    f = open('alarm.log', 'a')
    f.write(str(RTC().datetime()) + ": alarm triggered \n")
    f.close()

    #birdFeeder()

    time.sleep_ms(60000)
    alarm.manualStart()
else:
    p1.on()
    print('normal boot, no alarm')
    server.start()
Beispiel #7
0
def main():
    import time
    print("time:", time.time())

    from machine import RTC
    print("RTC datetime:", RTC().now())
Beispiel #8
0
class MBusDevice:
    """Class that encapulates/emulates a single MBus device"""
    def __init__(self, primary_address, secondary_address, manufacturer,
                 meter_type):
        self._primary_address = primary_address
        self._secondary_address = secondary_address
        self._manufacturer = manufacturer
        self._type = meter_type
        self._access_number = random.randint(0, 255)
        self._records = []
        self._rsp_ud2 = []
        self._selected = False
        self.rtc = RTC()

    def get_time(self):
        """Returns the current time, as known by this MBus device"""
        return "%02u:%02u:%02u (%d)" % self.rtc.datetime()[4:8]

    def select(self):
        """Puts this MBus device in the 'selected' state"""
        if not self._selected:
            self._selected = True
            self.log("device {} is now selected".format(
                self._secondary_address))

    def deselect(self):
        """Puts this MBus device in an 'unselected' state"""
        if self._selected:
            self._selected = False
            self.log("device {} is now deselected".format(
                self._secondary_address))

    def is_selected(self):
        """Returns the current selection state for this MBus device"""
        return self._selected

    def log(self, message):
        print("[{}][debug   ] {}".format(self.get_time(), message))

    def update(self):
        for record in self._records:
            record.update()
        self.log("Device with ID {} has updated its data".format(
            self._secondary_address))
        self.seal()

    def add_record(self, record):
        self._records.append(record)

    def seal(self):
        self._rsp_ud2 = self.get_rsp_ud2()

    def get_primary_address(self):
        """Returns the primary address for this MBus device"""
        return self._primary_address

    def get_secondary_address(self):
        """Returns the secondary address for this MBus device"""
        return self._secondary_address

    def matches_secondary_address(self, search_string):
        """Returns true if the secondary address of this MBus device matches the provided search string"""
        pattern = re.compile(search_string.replace('f', '[0-9]'))
        if pattern.match(self._secondary_address):
            return True
        return False

    def get_manufacturer_id(self):
        """Returns the manufacturer id for this MBus device"""
        return self._manufacturer

    def get_type(self):
        """Returns the MBus attribute 'type' for this MBus device"""
        return self._type

    def get_address_bytes(self):
        """Returns the secondary address for this MBus device, as a byte array"""
        resp_bytes = []
        resp_bytes.append(self._secondary_address[6])
        resp_bytes.append(self._secondary_address[7])
        resp_bytes.append(self._secondary_address[4])
        resp_bytes.append(self._secondary_address[5])
        resp_bytes.append(self._secondary_address[2])
        resp_bytes.append(self._secondary_address[3])
        resp_bytes.append(self._secondary_address[0])
        resp_bytes.append(self._secondary_address[1])
        resp_str = []
        resp_str.append(resp_bytes[0] + resp_bytes[1])
        resp_str.append(resp_bytes[2] + resp_bytes[3])
        resp_str.append(resp_bytes[4] + resp_bytes[5])
        resp_str.append(resp_bytes[6] + resp_bytes[7])
        ret = [x for x in resp_str]
        return ret

    def get_manufacturer_bytes(self):
        """Returns the manufacturer id for this MBus device, as a byte array"""
        manufacturer = self._manufacturer.upper()
        id = ((ord(manufacturer[0]) - 64) * 32 * 32 +
              (ord(manufacturer[1]) - 64) * 32 + (ord(manufacturer[2]) - 64))
        if 0x0421 <= id <= 0x6b5a:
            return self.manufacturer_encode(id, 2)
        return False

    def manufacturer_encode(self, value, size):
        """Converts a manufacturer id to its byte equivalent"""
        if value is None or value == False:
            return None
        data = []
        for i in range(0, size):
            data.append((value >> (i * 8)) & 0xFF)
        return data

    def calculate_checksum(self, message):
        """Calculates the checksum of the provided data"""
        return sum([int(x, 16) if type(x) == str else x
                    for x in message]) & 0xFF

    def get_latest_values(self):
        return self._rsp_ud2

    def get_rsp_ud2(self):
        """Generates a RSP_UD2 response message"""
        resp_bytes = []
        resp_bytes.append(0x68)  # start
        resp_bytes.append(0xFF)  # length
        resp_bytes.append(0xFF)  # length
        resp_bytes.append(0x68)  # start
        resp_bytes.append(0x08)  # C
        resp_bytes.append(self._primary_address)  # A
        resp_bytes.append(0x72)  # CI
        resp_bytes.extend(self.get_address_bytes())
        resp_bytes.extend(self.get_manufacturer_bytes())
        resp_bytes.append(0x01)  # version
        resp_bytes.append(self._type)  # medium (heat)
        resp_bytes.append(self._access_number)  # access no
        resp_bytes.append(0x00)  # status
        resp_bytes.append(0x00)  # configuration 1
        resp_bytes.append(0x00)  # configuration 2
        for record in self._records:
            resp_bytes.extend(record.get_bytes())
        resp_bytes.append(self.calculate_checksum(resp_bytes[4:]))
        resp_bytes.append(0x16)  # stop
        length = len(resp_bytes) - 9 + 3
        resp_bytes[1] = length
        resp_bytes[2] = length
        ret = [
            "{:>2}".format(hex(x)[2:]).replace(' ', '0')
            if type(x) == int else x for x in resp_bytes
        ]
        if self._access_number < 255:
            self._access_number = self._access_number + 1
        else:
            self._access_number = 1
        return ''.join(ret).upper()
Beispiel #9
0
#hardware platform: FireBeetle-ESP8266

from machine import RTC
import time

rtc = RTC()  #create RTC object
print(rtc.datetime(
))  #print time(year, month, day, hour, minute, second, microsecond, tzinfo)

#rtc.datetime((2017,5,20,5,0,0,0,0))    #you can use this to set current time

print(rtc.datetime())
time.sleep(3.5)
print(rtc.datetime())
print(rtc.memory())  #print the memory of rtc
rtc.memory("dfrobot" + str(rtc.datetime()[6]))  #set rtc memory
Beispiel #10
0
    timerLed = True
    timerBeep = False


olab = Env()  # for initialized equipment

from os import urandom
from time import sleep, sleep_ms, sleep_us, ticks_ms, ticks_diff
from machine import Pin, I2C, PWM, SPI, Timer, RTC

from util.colors import *
from util.pinout import set_pinout
from util.io_config import get_from_file

pinout = set_pinout()  # set board pinout
rtc = RTC()  # real time
io_conf = get_from_file()  # read configuration for peripherals

# I2C address:
LCD_ADDR = 0x27
OLED_ADDR = 0x3c

if Env.isTimer:
    from machine import Timer
    tim1 = Timer(0)


# -------------------------------- common terminal function ---------------
def getVer():
    return "octopusLAB - lib.version: " + Env.ver + " > " + Env.verDat
Beispiel #11
0
#
# Copyright (c) 2006-2019, RT-Thread Development Team
#
# SPDX-License-Identifier: MIT License
#
# Change Logs:
# Date           Author       Notes
# 2019-06-13     SummerGift   first version
#

from machine import RTC

rtc = RTC()  # Create an RTC device object
rtc.init((2019, 6, 5, 2, 10, 22, 30, 0))  # Set initialization time
print(rtc.now())  # Get the current time
rtc.deinit()  # Reset time to January 1, 2015
print(rtc.now())  # Get the current time
Beispiel #12
0
if not 'LaunchPad' in mch and not 'WiPy' in mch:
    raise Exception('Board not supported!')

def rtc_ticks_ms(rtc):
    timedate = rtc.now()
    return (timedate[5] * 1000) + (timedate[6] // 1000)

rtc_irq_count = 0

def alarm_handler (rtc_o):
    global rtc_irq
    global rtc_irq_count
    if rtc_irq.flags() & RTC.ALARM0:
        rtc_irq_count += 1

rtc = RTC()
rtc.alarm(time=500, repeat=True)
rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler)

# active mode
time.sleep_ms(1000)
rtc.alarm_cancel()
print(rtc_irq_count == 2)
rtc_irq_count = 0
rtc.alarm(time=200, repeat=True)
time.sleep_ms(1000)
rtc.alarm_cancel()
print(rtc_irq_count == 5)

rtc_irq_count = 0
rtc.alarm(time=100, repeat=True)
Beispiel #13
0
class TerkinDevice:
    def __init__(self, name=None, version=None, settings=None):

        self.name = name
        self.version = version
        self.settings = settings

        # Conditionally enable terminal on UART0. Default: False.
        self.terminal = Terminal(self.settings)
        self.terminal.start()

        self.device_id = get_device_id()

        self.networking = None
        self.telemetry = None

        self.wdt = None
        self.rtc = None

        self.status = DeviceStatus()

    @property
    def appname(self):
        return '{} {}'.format(self.name, self.version)

    def start_networking(self):
        log.info('Starting networking')

        from terkin.network import NetworkManager, WiFiException

        self.networking = NetworkManager(device=self, settings=self.settings)

        # Start WiFi.
        try:
            self.networking.start_wifi()

            # Wait for network interface to come up.
            self.networking.wait_for_nic()

            self.status.networking = True

        except WiFiException:
            log.error('Network connectivity not available, WiFi failed')
            self.status.networking = False

        # Initialize LoRa device.
        if self.settings.get('networking.lora.antenna_attached'):
            try:
                self.networking.start_lora()
            except:
                log.exception('Unable to start LoRa subsystem')
        else:
            log.info(
                "[LoRa] Disabling LoRa interface as no antenna has been attached. "
                "ATTENTION: Running LoRa without antenna will wreck your device."
            )

        # Inform about networking status.
        #self.networking.print_status()

    def start_watchdog(self):
        """
        The WDT is used to restart the system when the application crashes and
        ends up into a non recoverable state. After enabling, the application
        must "feed" the watchdog periodically to prevent it from expiring and
        resetting the system.
        """
        # https://docs.pycom.io/firmwareapi/pycom/machine/wdt.html

        if not self.settings.get('main.watchdog.enabled', False):
            log.info('Skipping watchdog timer (WDT)')
            return

        watchdog_timeout = self.settings.get('main.watchdog.timeout', 10000)
        log.info('Starting the watchdog timer (WDT) with timeout {}ms'.format(
            watchdog_timeout))

        from machine import WDT
        self.wdt = WDT(timeout=watchdog_timeout)

        # Feed Watchdog once.
        self.wdt.feed()

    def feed_watchdog(self):
        if self.wdt is not None:
            log.info('Feeding Watchdog')
            self.wdt.feed()

    def start_rtc(self):
        """
        The RTC is used to keep track of the date and time.
        """
        # https://docs.pycom.io/firmwareapi/pycom/machine/rtc.html
        # https://medium.com/@chrismisztur/pycom-uasyncio-installation-94931fc71283
        import time
        from machine import RTC
        self.rtc = RTC()
        # TODO: Use values from configuration settings here.
        self.rtc.ntp_sync("pool.ntp.org", 360)
        while not self.rtc.synced():
            time.sleep_ms(50)
        log.info('RTC: %s', self.rtc.now())

    def run_gc(self):
        """
        Run a garbage collection.
        https://docs.pycom.io/firmwareapi/micropython/gc.html
        """
        import gc
        gc.collect()

    def configure_rgb_led(self):
        """
        https://docs.pycom.io/tutorials/all/rgbled.html
        """
        import pycom

        # Enable or disable heartbeat.
        rgb_led_heartbeat = self.settings.get('main.rgb_led.heartbeat', True)
        pycom.heartbeat(rgb_led_heartbeat)
        pycom.heartbeat_on_boot(rgb_led_heartbeat)

        # Alternative signalling.
        # Todo: Run this in a separate thread in order not to delay execution of main program flow.
        if not rgb_led_heartbeat:
            for _ in range(2):
                pycom.rgbled(0x001100)
                time.sleep(0.15)
                pycom.rgbled(0x000000)
                time.sleep(0.10)

    def power_off_lte_modem(self):
        """
        We don't use LTE yet.

        https://community.hiveeyes.org/t/lte-modem-des-pycom-fipy-komplett-stilllegen/2161
        https://forum.pycom.io/topic/4877/deepsleep-on-batteries/10
        """

        import pycom
        """
        if not pycom.lte_modem_en_on_boot():
            log.info('Skip turning off LTE modem')
            return
        """

        log.info('Turning off LTE modem')
        try:
            from network import LTE

            # Invoking this will cause `LTE.deinit()` to take around 6(!) seconds.
            #log.info('Enabling LTE modem on boot')
            #pycom.lte_modem_en_on_boot(True)

            log.info('Turning off LTE modem on boot')
            pycom.lte_modem_en_on_boot(False)

            log.info('Invoking LTE.deinit()')
            lte = LTE()
            lte.deinit()

        except:
            log.exception('Shutting down LTE modem failed')

    def power_off_bluetooth(self):
        """
        We don't use Bluetooth yet.
        """
        log.info('Turning off Bluetooth')
        try:
            from network import Bluetooth
            bluetooth = Bluetooth()
            bluetooth.deinit()
        except:
            log.exception('Shutting down Bluetooth failed')

    def start_telemetry(self):
        log.info('Starting telemetry')

        self.telemetry = TelemetryManager()

        # Read all designated telemetry targets from configuration settings.
        telemetry_targets = self.settings.get('telemetry.targets')

        # Compute list of all _enabled_ telemetry targets.
        telemetry_candidates = []
        for telemetry_target in telemetry_targets:
            if telemetry_target.get('enabled', False):
                telemetry_candidates.append(telemetry_target)

        # Create adapter objects for each enabled telemetry target.
        for telemetry_target in telemetry_candidates:
            try:
                self.create_telemetry_adapter(telemetry_target)
                self.feed_watchdog()

            except:
                log.exception(
                    'Creating telemetry adapter failed for target: %s',
                    telemetry_target)

    def create_telemetry_adapter(self, telemetry_target):
        # Create adapter object.
        telemetry_adapter = TelemetryAdapter(
            device=self,
            endpoint=telemetry_target['endpoint'],
            address=telemetry_target.get('address'),
            data=telemetry_target.get('data'),
            topology=telemetry_target.get('topology'),
            format=telemetry_target.get('format'),
            content_encoding=telemetry_target.get('encode'),
        )

        # Setup telemetry adapter.
        telemetry_adapter.setup()

        self.telemetry.add_adapter(telemetry_adapter)

    def enable_serial(self):
        # Disable these two lines if you don't want serial access.
        # The Pycom forum tells us that this is already incorporated into
        # more recent firmwares, so this is probably a thing of the past.
        #uart = machine.UART(0, 115200)
        #os.dupterm(uart)
        pass

    def print_bootscreen(self):
        """
        Print bootscreen.

        This contains important details about your device
        and the operating system running on it.
        """

        if not self.settings.get('main.logging.enabled', False):
            return

        # Todo: Maybe refactor to TerkinDatalogger.
        from uio import StringIO
        buffer = StringIO()

        def add(item=''):
            buffer.write(item)
            buffer.write('\n')

        # Program name and version.
        title = '{} {}'.format(self.name, self.version)

        add()
        add('=' * len(title))
        add(title)
        add('=' * len(title))

        # Machine runtime information.
        add('CPU freq     {} MHz'.format(machine.freq() / 1000000))
        add('Device id    {}'.format(self.device_id))
        add()

        # System memory info (in bytes)
        machine.info()
        add()

        # TODO: Python runtime information.
        add('{:8}: {}'.format('Python', sys.version))
        """
        >>> import os; os.uname()
        (sysname='FiPy', nodename='FiPy', release='1.20.0.rc7', version='v1.9.4-2833cf5 on 2019-02-08', machine='FiPy with ESP32', lorawan='1.0.2', sigfox='1.0.1')
        """
        runtime_info = os.uname()
        for key in dir(runtime_info):
            if key == '__class__':
                continue
            value = getattr(runtime_info, key)
            #print('value:', value)
            add('{:8}: {}'.format(key, value))
        add()
        add()

        # Todo: Add program authors, contributors and credits.

        log.info('\n' + buffer.getvalue())

    def power_off(self):
        self.networking.stop()

    def hibernate(self, interval, deep=False):

        #logging.enable_logging()

        if deep:

            # Prepare and invoke deep sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.deepsleep

            log.info('Preparing deep sleep')

            # Set wake up mode.
            self.set_wakeup_mode()

            # Invoke deep sleep.
            log.info('Entering deep sleep for {} seconds'.format(interval))
            self.terminal.stop()
            machine.deepsleep(int(interval * 1000))

        else:

            log.info('Entering light sleep for {} seconds'.format(interval))

            # Invoke light sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.sleep
            # https://docs.micropython.org/en/latest/library/machine.html#machine.lightsleep
            #
            # As "machine.sleep" seems to be a noop on Pycom MicroPython,
            # we will just use the regular "time.sleep" here.
            # machine.sleep(int(interval * 1000))
            time.sleep(interval)

    def resume(self):
        log.info('Reset cause and wakeup reason: %s',
                 MachineResetCause.humanize())

    def set_wakeup_mode(self):

        # Set wake up parameters.
        """
        The arguments are:

        - pins: a list or tuple containing the GPIO to setup for deepsleep wakeup.

        - mode: selects the way the configured GPIOs can wake up the module.
          The possible values are: machine.WAKEUP_ALL_LOW and machine.WAKEUP_ANY_HIGH.

        - enable_pull: if set to True keeps the pull up or pull down resistors enabled
          during deep sleep. If this variable is set to True, then ULP or capacitive touch
          wakeup cannot be used in combination with GPIO wakeup.

        -- https://community.hiveeyes.org/t/deep-sleep-with-fipy-esp32-on-micropython/1792/12

        This will yield a wake up reason like::

            'wakeup_reason': {'code': 1, 'message': 'PIN'}

        """

        # Todo: ``enable_pull`` or not?

        # From documentation.
        # machine.pin_sleep_wakeup(pins=['P8'], mode=machine.WAKEUP_ALL_LOW, enable_pull=True)

        # Let's try.
        #machine.pin_sleep_wakeup(pins=['P8'], mode=machine.WAKEUP_ALL_LOW, enable_pull=False)
        pass
Beispiel #14
0
def settime():
   RTC().datetime(localtime(getntp()))
   print(time.localtime())
Beispiel #15
0
class WifiClock:
    def __init__(self):

        # Initialize SPI
        self._spi = SPI(-1,
                        baudrate=10000000,
                        polarity=1,
                        phase=0,
                        sck=Pin(_SPI_CLK_PIN),
                        mosi=Pin(_SPI_MOSI_PIN),
                        miso=Pin(_SPI_MISO_PIN))
        self._cs = Pin(_SPI_CS_PIN)
        self._cs.init(self._cs.OUT, True)

        # Initialize LEDs
        self.red_led = Pin(_RED_LED_PIN, Pin.OUT)
        self.green_led = Pin(_GREEN_LED_PIN, Pin.OUT)
        self.blue_led = Pin(_BLUE_LED_PIN, Pin.OUT)

        # Initialize buttons with interrupts
        self.mode_button = Pin(_MODE_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
        self.mode_button.irq(trigger=Pin.IRQ_FALLING,
                             handler=self.mode_button_callback)
        self.incr_button = Pin(_INCR_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
        self.incr_button.irq(trigger=Pin.IRQ_FALLING,
                             handler=self.incr_button_callback)
        self.decr_button = Pin(_DECR_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
        self.decr_button.irq(trigger=Pin.IRQ_FALLING,
                             handler=self.decr_button_callback)

        # Initialize current number and current decimal points
        self.current_num = None
        self.current_dp = 0b000000

        # Initialize timer and rtc
        self.sta_if = network.WLAN(network.STA_IF)
        self.rtc = RTC()
        self.timer = Timer(1)

        for command, data in (
            (_SHUTDOWN, 0),
            (_SCAN_LIMIT, 7),
            (_DECODE_MODE, 0xFF),
            (_INTENSITY, 0xa),
            (_SHUTDOWN, 1),
        ):
            self._register(command, data)

        self.display_clear()
        self.red_led.value(0)
        self.green_led.value(0)
        self.blue_led.value(0)

    # Connect to wifi
    def connect_to_wifi(self, ssid, password):
        if not self.sta_if.isconnected():
            print('Connecting to network...')
            self.sta_if.active(True)
            self.sta_if.connect(ssid, password)
            while not self.sta_if.isconnected():
                print('.', end='')
                time.sleep(1)
        print('Connected!')

    # Set time manually
    def set_time(self, hour, minute, second):
        self.rtc.datetime((2019, 1, 1, 0, hour, minute, second, 0))

    # Set time using ntp server (must be connected to wifi)
    def set_time_ntp(self, utc_offset):
        ntptime.settime()
        d = self.rtc.datetime()

        hour = d[4] + utc_offset

        if hour < 0:
            hour = 24 + hour
        elif hour > 23:
            hour = hour - 24

        d = (d[0], d[1], d[2], d[3], hour, d[5], d[6], d[7])
        self.rtc.datetime(d)

    # Start a 24 hour clock (call after setting the time either with set_time or set_time_ntp)
    def start_clock24(self):
        self.timer.init(period=1000,
                        mode=Timer.PERIODIC,
                        callback=self.clock_timer_callback)

    # Set the display brightness
    def display_brightness(self, value):
        if 0 <= value <= 15:
            self._register(_INTENSITY, value)
        else:
            raise ValueError("Brightness out of range")

    # Clear the display
    def display_clear(self):
        self._register(_DECODE_MODE, 0xFF)
        for i in range(6):
            self._register(_DIGIT_DICT[i], 0x0F)

        self.current_num = None

    # Write a decimal value to the display, dp is 6 bit binary value representing where to put decimal points
    def write_num(self, value, dp=0b000000):
        self._register(_DECODE_MODE, 0xFF)

        if (0 <= value <= _MAX_VALUE_DEC) and (_MIN_VALUE_DP <= dp <=
                                               _MAX_VALUE_DP):
            self.current_num = value
            self.current_dp = dp

            for i in range(6):
                current_value = value % 10

                if dp & 1:

                    self._register(_DIGIT_DICT[i], current_value | _DP)
                else:
                    self._register(_DIGIT_DICT[i], current_value)

                dp = dp >> 1
                value = value // 10

        elif (0 > value >= _MIN_VALUE_DEC) and (_MIN_VALUE_DP <= dp <=
                                                _MAX_VALUE_DP):
            self.current_num = value
            self.current_dp = dp

            value = -value
            self._register(_DIGIT5, 0xA)

            for i in range(5):
                current_value = value % 10

                if dp & 1:

                    self._register(_DIGIT_DICT[i], current_value | _DP)
                else:
                    self._register(_DIGIT_DICT[i], current_value)

                dp = dp >> 1
                value = value // 10

        else:
            raise ValueError("Value out of range")

    # Write literal hex value to the display
    def write_hex(self, value):
        self._register(_DECODE_MODE, 0x0)
        if 0x0 <= value <= _MAX_VALUE_HEX:

            self.current_num = value

            for i in range(6):
                self._register(_DIGIT_DICT[i], _HEX_TO_SEG[value % 16])
                value = value // 16
        else:
            raise ValueError("Value out of range")

    # Toggle an LED
    @staticmethod
    def toggle_led(led):
        led.value(not (led.value()))

    # Increment the current number on the display
    def increment_num(self, hex=False):
        if self.current_num is None:
            raise ValueError("No value to increment")
        else:

            if hex:
                if (self.current_num + 1) > _MAX_VALUE_HEX:
                    self.current_num = -1

                self.write_hex(self.current_num + 1)
            else:

                if (self.current_num + 1) > _MAX_VALUE_DEC:
                    self.current_num = -1

                self.write_num(self.current_num + 1, self.current_dp)

    # Decrement the current number on the display
    def decrement_num(self, hex=False):
        if self.current_num is None:
            raise ValueError("No value to decrement")
        else:

            if hex:
                if (self.current_num - 1) < _MIN_VALUE_HEX:
                    self.current_num = 1

                self.write_hex(self.current_num - 1)
            else:

                if (self.current_num - 1) < _MIN_VALUE_DEC:
                    self.current_num = 1

                self.write_num(self.current_num - 1, self.current_dp)

    # Callback for Mode button
    def mode_button_callback(self, pin):
        if self._debounce(self.mode_button):
            self.toggle_led(self.red_led)

    # Callback for Incr Button
    def incr_button_callback(self, pin):
        if self._debounce(self.incr_button):
            self.increment_num()

    # Callback for Decr button
    def decr_button_callback(self, pin):
        if self._debounce(self.decr_button):
            self.decrement_num()

    # Callback for clock after calling start_clock24
    def clock_timer_callback(self, tim):
        self._update_clock24()

    # Callback for other timer uses
    def timer_callback(self, tim):
        self.increment_num()

    # Read hours, minutes, and seconds from rtc and and write to the display
    def _update_clock24(self):
        current_time = self.rtc.datetime()

        hours = current_time[4]
        minutes = current_time[5]
        seconds = current_time[6]

        time_str = ''

        if hours < 10:
            time_str += '0'
        time_str += str(hours)

        if minutes < 10:
            time_str += '0'
        time_str += str(minutes)

        if seconds < 10:
            time_str += '0'
        time_str += str(seconds)

        self.write_num(int(time_str), 0b010100)

    # Send commands to MAX7219
    def _register(self, command, data):
        self._cs.value(0)
        self._spi.write(bytearray([command, data]))
        self._cs.value(1)

    # Debounce function for debouncing buttons
    @staticmethod
    def _debounce(button):
        flag = 0

        for i in range(_DEBOUNCE_SAMPLES):
            flag = button.value()
            if button.value():
                return not flag

        return not flag
Beispiel #16
0
from machine import RTC

rtc = RTC()
print(rtc.now())
Beispiel #17
0
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('ZyXEL8B32A8', '73NHW74UKJ33X')
        while not wlan.isconnected():
            pass
    print("Oh Yes! Get connected")
    print("Connected to " + str(wlan.config("essid")))
    print("MAC Address: " + str(ubinascii.hexlify(wlan.config('mac'), ':').decode()))
    print("IP Address: " + wlan.ifconfig()[0])

connect()

#Clock UTC time
ntptime.settime()
rtc = RTC()
year, month, day, weekday, hours, minutes, seconds, microseconds = rtc.datetime()
rtc.datetime((year, month, day, weekday, hours - 4, minutes, seconds, microseconds))
ntptime.host = "pool.ntp.org"

#Hardware timer - 1
tim1 = Timer(1)
tim1.init(period=15000, mode=Timer.PERIODIC, callback=lambda t:printtime(rtc.datetime()))

#Variables
#LEDs
green = Pin(21, Pin.OUT)
red = Pin(32, Pin.OUT)

#Buttons
button_red = Pin(25, Pin.IN, Pin.PULL_DOWN)
Beispiel #18
0
import untplib

c=untplib.NTPClient()
resp=c.request('0.uk.pool.ntp.org', version=3, port=123)
print("Offset is ", resp.offset)

from machine import RTC
import time

rtc = RTC()
print("Adjusting clock by ", resp.offset, "seconds")
rtc.init(time.localtime(time.time() + resp.offset))
def set_rtc( tm ):
    # time.struct_time
    year, month, day, hour, min, sec, wday, yday = tm
    print( year, month, day, hour, min, sec, wday, yday )
	# (year, month, day, weekday, hours, minutes, seconds, sub-seconds)
    RTC().datetime( (tm[0],tm[1],tm[2],tm[6],tm[3],tm[4],tm[5],0) )
Beispiel #20
0
from jq6500 import Player
from machine import I2C, Pin, UART, unique_id
from mqtt import MQTTClient
import micropython
import time
import ubinascii
import mlx90614
import machine
import math

player = Player(port=1, volume=30)
uart = UART(2, 115200)

from machine import RTC
rtc = RTC()


def conexion():
    try:
        i2c = I2C(scl=Pin(22), sda=Pin(21), freq=50000)
        sensor = mlx90614.MLX90614(i2c)
    except:
        print("conectando...")
        time.sleep(2)
        conexion()


def Conexion_MQTT():
    client_id = b"Covid_" + ubinascii.hexlify(unique_id())
    #client_id = b"covid"
    mqtt_server = 'mantenimiento.elite.local'
Beispiel #21
0
 def __init__(self):
     self.ds3231 = I2C(0, I2C.MASTER, baudrate=100000, pins=('GP15', 'GP10'))
     self.rtc = RTC()
Beispiel #22
0
from machine import RTC

rtc = RTC()
# for 22nd of June 2017 at 10:30am (TZ 0)
rtc.init((2017, 6, 22, 10, 30, 0, 0, 0))
print(rtc.now())
Beispiel #23
0
    while True:
        pass

#----------------------------------------------------------
# Step 2: connect NTP server and synchronize RTC with NTP

while True:
    try:
        # synchronize RTC with NTP server
        ntptime.settime()
        break
    except OSError:
        print('NTP server: connection timeout...')

# create an RTC object
rtc = RTC()

#----------------------------------------------------------
# step 3: display clock (hours and minutes)

DIGITS = [
    [0x7f,0x41,0x7f], # 0
    [0x21,0x7f,0x01], # 1
    [0x4f,0x49,0x79], # 2
    [0x49,0x49,0x7f], # 3
    [0x78,0x08,0x7f], # 4
    [0x79,0x49,0x4f], # 5
    [0x7f,0x49,0x4f], # 6
    [0x40,0x40,0x7f], # 7
    [0x7f,0x49,0x7f], # 8
    [0x79,0x49,0x7f]  # 9
Beispiel #24
0
    print('network config:', sta_if.ifconfig())


def pressure_altitude(pressure, qnh=1013.25):
    altitude = 44330.0 * (1.0 - pow(pressure / qnh, (1.0 / 5.255)))
    return altitude


i2c1 = I2C(id=1, scl=Pin(I2C1_PIN_SCL), sda=Pin(I2C1_PIN_SDA), speed=400000)
if i2c1.is_ready(BME280_I2CADDR):
    BME_present = True

i2c1.deinit()

if RTC_present:
    rtc = RTC()
    # print("RTC = ", rtc.now())
else:
    print("No RTC")

uart = UART(1,
            tx=GNSS_PIN_TX,
            rx=GNSS_PIN_RX,
            timeout=1000,
            buffer_size=256,
            baudrate=9600)

# Max Performance Mode (default)
ubx_cont = bytearray(
    [0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x08, 0x00, 0x21, 0x91])
Beispiel #25
0
from machine import Pin
from machine import ADC
from machine import PWM
import time

## I2C and OLED Initialization
i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4))
oled = ssd1306.SSD1306_I2C(128, 32, i2c)

## Date Variables
big_month = [1, 3, 5, 7, 8, 10, 12]
week_day = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
init_date = [2019, 1, 1, 0, 0, 0, 0, 0]

## RTC Intializaion
rtc = RTC()
rtc.datetime(tuple(init_date))

global button, state, set_mode, modes_size

button = 'NULL'
state = 'HOME'
modes = ['SET_TIME', 'EXIT']
modes_size = len(modes)
set_mode = 0

## Display Settings


def display(content, Page, Mark):
Beispiel #26
0
class TerkinDevice:
    """ """
    def __init__(self, application_info: ApplicationInfo):

        self.application_info = application_info
        self.platform_info = application_info.platform_info

        self.name = application_info.name
        self.version = application_info.version
        self.settings = application_info.settings

        self.status = DeviceStatus()
        self.watchdog = Watchdog(device=self, settings=self.settings)

        # Conditionally enable terminal on UART0. Default: False.
        try:
            self.terminal = Terminal(self.settings)
            self.terminal.start()
        except Exception as ex:
            log.exc(ex, 'Enabling Terminal failed')

        self.device_id = get_device_id()

        self.networking = None
        self.telemetry = None

        self.rtc = None

    def start_networking(self):
        """ """
        log.info('Starting networking')

        from terkin.network import NetworkManager, WiFiException

        self.networking = NetworkManager(device=self, settings=self.settings)

        if self.settings.get('networking.wifi.enabled'):
            # Start WiFi.
            try:
                self.networking.start_wifi()

            except Exception as ex:
                log.exc(ex, 'Starting WiFi networking failed')
                self.status.networking = False
                return

            # Wait for network stack to come up.
            try:
                self.networking.wait_for_ip_stack(timeout=5)
                self.status.networking = True
            except Exception as ex:
                log.exc(ex, 'IP stack not available')
                self.status.networking = False

            try:
                self.networking.start_services()
            except Exception as ex:
                log.exc(ex, 'Starting network services failed')
        else:
            log.info("[WiFi] interface disabled in settings.")

        # Initialize LoRa device.
        if self.settings.get('networking.lora.enabled'):
            if self.settings.get('networking.lora.antenna_attached'):
                try:
                    self.networking.start_lora()
                    self.status.networking = True
                except Exception as ex:
                    log.exc(ex, 'Unable to start LoRa subsystem')
                    self.status.networking = False
            else:
                log.info(
                    "[LoRa] Disabling LoRa interface as no antenna has been attached. "
                    "ATTENTION: Running LoRa without antenna will wreck your device."
                )
        else:
            log.info("[LoRa] interface disabled in settings.")

        # Inform about networking status.
        #self.networking.print_status()

    def start_rtc(self):
        """The RTC is used to keep track of the date and time."""
        # https://docs.pycom.io/firmwareapi/pycom/machine/rtc.html
        # https://medium.com/@chrismisztur/pycom-uasyncio-installation-94931fc71283
        import time
        from machine import RTC
        self.rtc = RTC()
        # TODO: Use values from configuration settings here.
        self.rtc.ntp_sync("pool.ntp.org", 360)
        while not self.rtc.synced():
            time.sleep_ms(50)
        log.info('RTC: %s', self.rtc.now())

    def run_gc(self):
        """Curate the garbage collector.
        https://docs.pycom.io/firmwareapi/micropython/gc.html
        
        For a "quick fix", issue the following periodically.
        https://community.hiveeyes.org/t/timing-things-on-micropython-for-esp32/2329/9


        """
        import gc
        log.info('Start curating the garbage collector')
        gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
        log.info('Collecting garbage')
        gc.collect()
        #log.info('Curating the garbage collector finished')
        log.info('Curating the garbage collector finished. Free memory: %s',
                 gc.mem_free())

    def configure_rgb_led(self):
        """https://docs.pycom.io/tutorials/all/rgbled.html"""
        if self.platform_info.vendor == self.platform_info.MICROPYTHON.Pycom:
            import pycom
            # Enable or disable heartbeat.
            rgb_led_heartbeat = self.settings.get('main.rgb_led.heartbeat',
                                                  True)
            terkin_blink_pattern = self.settings.get('main.rgb_led.terkin',
                                                     False)
            if terkin_blink_pattern:
                rgb_led_heartbeat = False
            pycom.heartbeat(rgb_led_heartbeat)
            pycom.heartbeat_on_boot(rgb_led_heartbeat)

    def blink_led(self, color, count=1):
        """

        :param color: 
        :param count:  (Default value = 1)

        """
        if self.platform_info.vendor == self.platform_info.MICROPYTHON.Pycom:
            import pycom
            terkin_blink_pattern = self.settings.get('main.rgb_led.terkin',
                                                     False)
            if terkin_blink_pattern:
                for _ in range(count):
                    pycom.rgbled(color)
                    time.sleep(0.15)
                    pycom.rgbled(0x000000)
                    time.sleep(0.10)

    def start_telemetry(self):
        """ """
        log.info('Starting telemetry')

        self.telemetry = TelemetryManager()

        # Read all designated telemetry targets from configuration settings.
        telemetry_targets = self.settings.get('telemetry.targets')

        # Compute list of all _enabled_ telemetry targets.
        telemetry_candidates = []
        for telemetry_target in telemetry_targets:
            if telemetry_target.get('enabled', False):
                telemetry_candidates.append(telemetry_target)

        # Create adapter objects for each enabled telemetry target.
        for telemetry_target in telemetry_candidates:
            try:
                self.create_telemetry_adapter(telemetry_target)
                self.watchdog.feed()

            except Exception as ex:
                log.exc(ex, 'Creating telemetry adapter failed for target: %s',
                        telemetry_target)

    def create_telemetry_adapter(self, telemetry_target):
        """

        :param telemetry_target: 

        """
        # Create adapter object.
        telemetry_adapter = TelemetryAdapter(
            device=self,
            endpoint=telemetry_target['endpoint'],
            address=telemetry_target.get('address'),
            data=telemetry_target.get('data'),
            topology=telemetry_target.get('topology'),
            format=telemetry_target.get('format'),
            content_encoding=telemetry_target.get('encode'),
        )

        # Setup telemetry adapter.
        telemetry_adapter.setup()

        self.telemetry.add_adapter(telemetry_adapter)

    def enable_serial(self):
        """ """
        # Disable these two lines if you don't want serial access.
        # The Pycom forum tells us that this is already incorporated into
        # more recent firmwares, so this is probably a thing of the past.
        #uart = machine.UART(0, 115200)
        #os.dupterm(uart)
        pass

    def print_bootscreen(self):
        """Print bootscreen.
        
        This contains important details about your device
        and the operating system running on it.


        """

        if not self.settings.get('main.logging.enabled', False):
            return

        # Todo: Maybe refactor to TerkinDatalogger.
        from uio import StringIO
        buffer = StringIO()

        def add(item=''):
            """

            :param item:  (Default value = '')

            """
            buffer.write(item)
            buffer.write('\n')

        # Program name and version.
        title = '{} {}'.format(self.name, self.version)

        add()
        add('=' * len(title))
        add(title)
        add('=' * len(title))

        # Machine runtime information.
        frequency = machine.freq() / 1000000

        add('Device id    {}'.format(self.device_id))
        add()
        add('CPU freq     {}   MHz'.format(frequency))
        try:
            import pycom
            free_heap = pycom.get_free_heap()
            add('{:13}{:>7} {}'.format('Free heap', free_heap[0] / 1000.0,
                                       'kB'))
            add('{:13}{:>7} {}'.format('Free PSRAM', free_heap[1] / 1000.0,
                                       'kB'))
        except:
            pass
        add()

        # System memory info (in bytes).
        """
        if hasattr(machine, 'info'):
            machine.info()
            add()
        """

        # TODO: Python runtime information.
        add('{:8}: {}'.format('Python', sys.version))
        """
        >>> import os; os.uname()
        (sysname='FiPy', nodename='FiPy', release='1.20.0.rc7', version='v1.9.4-2833cf5 on 2019-02-08', machine='FiPy with ESP32', lorawan='1.0.2', sigfox='1.0.1')
        """
        runtime_info = os.uname()
        for key in dir(runtime_info):
            if key == '__class__':
                continue
            value = getattr(runtime_info, key)
            #print('value:', value)
            add('{:8}: {}'.format(key, value))
        add()

        # Todo: Add program authors, contributors and credits.

        log.info('\n' + buffer.getvalue())

    def power_off(self):
        """ """
        self.networking.stop()

    def power_off_lte_modem(self):
        """
        We don't use LTE yet.

        Important
        =========
        Once the LTE radio is initialized, it must be de-initialized
        before going to deepsleep in order to ensure minimum power consumption.
        This is required due to the LTE radio being powered independently and
        allowing use cases which require the system to be taken out from
        deepsleep by an event from the LTE network (data or SMS received for
        instance).

        Note
        ====
        When using the expansion board and the FiPy together, the RTS/CTS
        jumpers MUST be removed as those pins are being used by the LTE radio.
        Keeping those jumpers in place will lead to erratic operation and
        higher current consumption specially while in deepsleep.

        -- https://forum.pycom.io/topic/3090/fipy-current-consumption-analysis/17

        See also
        ========
        - https://community.hiveeyes.org/t/lte-modem-des-pycom-fipy-komplett-stilllegen/2161
        - https://forum.pycom.io/topic/4877/deepsleep-on-batteries/10
        """

        log.info('Turning off LTE modem')
        try:
            import pycom
            from network import LTE

            log.info('Turning off LTE modem on boot')
            pycom.lte_modem_en_on_boot(False)

            # Disables LTE modem completely. This presumably reduces the power
            # consumption to the minimum. Call this before entering deepsleep.
            log.info('Invoking LTE.deinit()')
            lte = LTE()
            lte.deinit(detach=False, reset=True)

        except Exception as ex:
            log.exc(ex, 'Shutting down LTE modem failed')

    def power_off_bluetooth(self):
        """We don't use Bluetooth yet."""

        if self.platform_info.vendor == self.platform_info.MICROPYTHON.Vanilla:
            log.warning(
                "FIXME: Skip touching Bluetooth on vanilla MicroPython "
                "platforms as we don't use Bluetooth yet")
            return

        log.info('Turning off Bluetooth')
        try:
            from network import Bluetooth
            bluetooth = Bluetooth()
            bluetooth.deinit()
        except Exception as ex:
            log.exc(ex, 'Shutting down Bluetooth failed')

    def hibernate(self, interval, lightsleep=False, deepsleep=False):
        """

        :param interval: 
        :param lightsleep:  (Default value = False)
        :param deepsleep:  (Default value = False)

        """

        #logging.enable_logging()

        if deepsleep:

            # Prepare and invoke deep sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.deepsleep

            log.info('Preparing deep sleep')

            # Set wake up mode.
            self.set_wakeup_mode()

            # Invoke deep sleep.
            log.info('Entering deep sleep for {} seconds'.format(interval))
            self.terminal.stop()
            machine.deepsleep(int(interval * 1000))

        else:

            # Adjust watchdog for interval.
            self.watchdog.adjust_for_interval(interval)

            # Invoke light sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.sleep
            # https://docs.micropython.org/en/latest/library/machine.html#machine.lightsleep
            #
            # As "machine.sleep" seems to be a noop on Pycom MicroPython,
            # we will just use the regular "time.sleep" here.
            # machine.sleep(int(interval * 1000))
            machine.idle()

            if lightsleep:
                log.info(
                    'Entering light sleep for {} seconds'.format(interval))
                machine.sleep(int(interval * 1000))

            else:
                # Normal wait.
                log.info('Waiting for {} seconds'.format(interval))
                time.sleep(interval)

    def resume(self):
        """ """
        try:
            from terkin.pycom import MachineResetCause
            log.info('Reset cause and wakeup reason: %s',
                     MachineResetCause().humanize())
        except Exception as ex:
            log.exc(ex, 'Could not determine reset cause and wakeup reason')

    def set_wakeup_mode(self):
        """ """

        # Set wake up parameters.
        """
        The arguments are:

        - pins: a list or tuple containing the GPIO to setup for deepsleep wakeup.

        - mode: selects the way the configured GPIOs can wake up the module.
          The possible values are: machine.WAKEUP_ALL_LOW and machine.WAKEUP_ANY_HIGH.

        - enable_pull: if set to True keeps the pull up or pull down resistors enabled
          during deep sleep. If this variable is set to True, then ULP or capacitive touch
          wakeup cannot be used in combination with GPIO wakeup.

        -- https://community.hiveeyes.org/t/deep-sleep-with-fipy-esp32-on-micropython/1792/12

        This will yield a wake up reason like::

            'wakeup_reason': {'code': 1, 'message': 'PIN'}

        """

        # Todo: ``enable_pull`` or not?

        # From documentation.
        # machine.pin_sleep_wakeup(pins=['P8'], mode=machine.WAKEUP_ALL_LOW, enable_pull=True)

        # Let's try.
        #log.info('Configuring Pin 4 for wakeup from deep sleep')
        #machine.pin_sleep_wakeup(pins=['P4'], mode=machine.WAKEUP_ALL_LOW, enable_pull=True)
        #machine.pin_sleep_wakeup(pins=['P4'], mode=machine.WAKEUP_ANY_HIGH, enable_pull=True)
        pass
Beispiel #27
0
日期:2019.7
作者:01Studio
'''

# 导入相关模块
from machine import Pin, I2C, RTC, Timer
from ssd1306 import SSD1306_I2C

# 定义星期和时间(时分秒)显示字符列表
week = ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']
time_list = ['', '', '']

# 初始化所有相关对象
i2c = I2C(sda=Pin(13), scl=Pin(14))  #I2C初始化:sda--> 13, scl --> 14
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
rtc = RTC()

# 首次上电配置时间,按顺序分别是:年,月,日,星期,时,分,秒,次秒级;这里做了
# 一个简单的判断,检查到当前年份不对就修改当前时间,开发者可以根据自己实际情况来
# 修改。
if rtc.datetime()[0] != 2019:
    rtc.datetime((2019, 4, 1, 0, 0, 0, 0, 0))


def RTC_Run(tim):

    datetime = rtc.datetime()  # 获取当前时间

    oled.fill(0)  # 清屏显示黑色背景
    oled.text('01Studio', 0, 0)  # 首行显示01Studio
    oled.text('RTC Clock', 0, 15)  # 次行显示实验名称
Beispiel #28
0
def timezone_correction(hours_to_add):
    rtc = RTC()
    ntp_clock = list(rtc.datetime())  # teeme listiks, kuna vaja muuta
    ntp_clock[4] += hours_to_add
    rtc.datetime(
        tuple(ntp_clock))  #uuenda real time clock rtc muudetud kellajaga
Beispiel #29
0
 def __init__(self, logger_name="LOG"):
     self.level = _level
     self.LOGGER_NAME = logger_name
     self.rtc = RTC()
Beispiel #30
0
"""

response_500 = """HTTP/1.0 500 INTERNAL SERVER ERROR
<h1>500 Internal Server Error</h1>
"""

response_template = """HTTP/1.0 200 OK
%s
"""

import machine
import ntptime, utime
from machine import RTC
from time import sleep

rtc = RTC()
try:
    seconds = ntptime.time()
except:
    seconds = 0
rtc.datetime(utime.localtime(seconds))


def time():
    body = """<html>
<body>
<h1>Time</h1>
<p>%s</p>
</body>
</html>
""" % str(rtc.datetime())
Beispiel #31
0
class Display(object):
    IMG_DIR = '/flash/imgs'

    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)

    def log(self, msg, end='\n'):
        time = "%d, %d, %d, %d, %d, %d" % self.rtc.now()[:-2]
        msg = time + ", " + msg
        if self.logfile:
            self.logfile.write(msg + end)
        print(msg, end=end)

    def feed_wdt(self):
        if self.wdt:
            self.wdt.feed()

    def connect_wifi(self):
        from network import WLAN

        if not self.cfg:
            raise ValueError("Can't initialise wifi, no config")

        self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys()))
        wlan = WLAN(0, WLAN.STA)
        wlan.ifconfig(config='dhcp')
        while not wlan.isconnected():
            nets = wlan.scan()
            for network in nets:
                if network.ssid in self.cfg.wifi.keys():
                    self.log('Connecting to ' + network.ssid)
                    self.feed_wdt() # just in case
                    wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid]))
                    while not wlan.isconnected():
                        idle()
                    break

            self.feed_wdt() # just in case
            sleep_ms(2000)

        self.log('Connected as %s' % wlan.ifconfig()[0])

    @staticmethod
    def reset_cause():
        import machine
        val = machine.reset_cause()
        if val == machine.POWER_ON:
            return "power"
        elif val == machine.HARD_RESET:
            return "hard"
        elif val == machine.WDT_RESET:
            return "wdt"
        elif val == machine.DEEPSLEEP_RESET:
            return "sleep"
        elif val == machine.SOFT_RESET:
            return "soft"

    def set_alarm(self, now, json_metadata):
        import json
        json_dict = json.loads(json_metadata)

        # Now we know the time too
        self.rtc = RTC(datetime=now)
        list_int = json_dict["wakeup"][:6]
        time_str = ",".join([str(x) for x in list_int])

        self.log("Setting alarm for " + time_str)
        self.rtc.alarm(time=tuple(list_int))

        if self.rtc.alarm_left() == 0:
            self.log("Alarm failed, setting for +1 hour")
            self.rtc.alarm(time=3600000)

        del json

    def display_file_image(self, file_obj):
        towrite = 15016
        max_chunk = 250
        while towrite > 0:
            c = max_chunk if towrite > max_chunk else towrite
            buff = file_obj.read(c)
            self.epd.upload_image_data(buff, delay_us=2000)
            self.feed_wdt()
            towrite -= c

        self.epd.display_update()

    def display_no_config(self):
        self.log("Displaying no config msg")
        with open(Display.IMG_DIR + '/no_config.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_low_battery(self):
        self.log("Displaying low battery msg")
        with open(Display.IMG_DIR + '/low_battery.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_cannot_connect(self):
        self.log("Displaying no server comms msg")
        with open(Display.IMG_DIR + '/no_server.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_no_wifi(self):
        self.log("Displaying no wifi msg")
        with open(Display.IMG_DIR + '/no_wifi.bin', 'rb') as pic:
            self.display_file_image(pic)

    def check_battery_level(self):
        now_batt = 200
        last_batt = self.battery.battery_raw()
        while now_batt > last_batt:
            sleep_ms(50)
            last_batt = now_batt
            self.feed_wdt()
            now_batt = self.battery.battery_raw()
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))

        if not self.battery.safe():
            self.log("Battery voltage (%d) low! Turning off" % self.battery.battery_raw())
            self.feed_wdt()
            self.display_low_battery()
            return False
        else:
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))
        return True

    def run_deepsleep(self):

        if not self.run():
            # RTC wasn't set, try to sleep forever
            self.rtc.alarm(time=2000000000)

        # Set the wakeup (why do it earlier?)
        rtc_i = self.rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP)

        self.log("Going to sleep, waking in %dms" % self.rtc.alarm_left())

        # Close files on the SD card
        if self.sd:
            self.logfile.close()
            self.logfile = None
            unmount('/sd')
            self.sd.deinit()

        # Turn the screen off
        self.epd.disable()

        if not self.wifi_pin():
            # Basically turn off
            deepsleep()
        else:
            self.log("DEBUG MODE: Staying awake")
            pass
            # Do nothing, allow network connections in

    def run(self):

        woken = self.wifi_pin()
        self.epd.enable()

        if not self.check_battery_level():
            return False

        try:
            self.epd.get_sensor_data()
        except ValueError:
            self.log("Can't communicate with display, flashing light and giving up")
            heartbeat(True)
            sleep_ms(15000)
            return True

        if self.rtc.alarm_left() > 0:
            self.log("Woken up but the timer is still running, refreshing screen only")
            self.epd.display_update()
            self.feed_wdt()
            return True

        try:
            self.cfg = Config.load(sd=self.sd)
            self.log("Loaded config")
        except (OSError, ValueError) as e:
            self.log("Failed to load config: " + str(e))
            self.display_no_config()
            try:
                self.connect_wifi()
            except:
                pass # everything

            while True:
                sleep_ms(10)
                self.feed_wdt()

        self.feed_wdt()

        self.connect_wifi()

        content = b''
        try:
            self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port))
            c = Connect(self.cfg.host, self.cfg.port, debug=self.debug)

            self.feed_wdt()

            cause = Display.reset_cause()
            if woken:
                cause = "user"

            self.log("Reset cause: " + cause)

            if len(self.cfg.upload_path) > 0:
                temp = self.epd.get_sensor_data() # we read this already
                c.post(self.cfg.upload_path,
                       battery=self.battery.value(),
                       reset=cause,
                       screen=temp)

            self.log("Fetching metadata from " + self.cfg.metadata_path)
            metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json')

            # This will set the time to GMT, not localtime
            self.set_alarm(c.last_fetch_time, metadata)

            self.feed_wdt()
            del metadata
            del self.battery
            self.log("Fetching image from " + self.cfg.image_path)
            self.epd.image_erase_frame_buffer()
            self.feed_wdt()

            length, socket = c.get_object(self.cfg.image_path)

            if length != 15016:
                raise ValueError("Wrong data size for image: %d" % length)

            self.feed_wdt()

        except (RuntimeError, ValueError, OSError) as e:
            self.log("Failed to get remote info: " + str(e))
            self.display_cannot_connect()
            self.rtc.alarm(time=3600000)
            return True

        sleep_ms(1000) # How do we make the write to display more reliable?
        self.feed_wdt()
        self.log("Uploading to display")
        self.display_file_image(socket)
        c.get_object_done() # close off socket

        if self.cfg.src == "sd":
            # If we've got a working config from SD instead of flash
            self.log("Transferring working config")
            Config.transfer()
            self.log("SUCCESS")

        self.log("Finished. Mem free: %d" % gc.mem_free())
        return True
Beispiel #32
0
while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS:
    attempt_count += 1
    sleep_ms(1000)

if attempt_count == MAX_ATTEMPTS:
    print('could not connect to the WiFi network')
    sys.exit()

# set time using NTP server on the internet

import ntptime    #NTP-time (from pool.ntp.org) 
import utime
ntptime.settime()
tm = utime.localtime(utime.mktime(utime.localtime()) + 8 * 3600)
tm=tm[0:3] + (0,) + tm[3:6] + (0,)
rtc = RTC()
rtc.datetime(tm)

ContinueOn = True
while ContinueOn :

  
  getBtn()
  
  if pressed (btnL, True) :
    ContinueOn = False
  
  elif pressed(btnA,True) :                 
    #LED buttun pressed and released
    if ledOn :
      # if led is previously ON, now turn it off by outputing High voltage
Beispiel #33
0
    sign = (data[2] >> 7) & 1
    if sign == 0:
        return round(temp, 2)
    return round(-1 * temp, 2)


def extractHumidity(data):
    return data[1] * 0.5


def extractPressure(data):
    pres = (data[4] << 8) + data[5] + 50000
    return pres / 100

sendData.connectLocalBox('/flash/config.json')
rtc = RTC()
rtc.ntp_sync('fr.pool.ntp.org')

bt = Bluetooth()
try:
    bt.start_scan(-1)
except:
    bt.stop_scan()
    bt.start_scan(-1)

while True:
    try:
        adv = bt.get_adv()
        if adv:
            data = str(adv.data, "utf-8")
            data = str(data.split("#")[1][:8], "utf-8")
Beispiel #34
0
from BME280 import *
from CORRECTEUR_PID import *
from ODOMETRIE import *
from BME280 import *
from machine import I2C
from machine import SD
from machine import RTC
from machine import Timer
from VL6180X import *
import os
import time
from math import pi
import _thread

#Ini RTC (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
Time_Rtc = RTC()
Time_Rtc.init((2019, 11, 16, 15, 14, 0, 0, 0))

#ini carte sd
sd = SD()
os.mount(sd, "/sd")

f = open("/sd/test.csv", "w")
f.write(
    "heure; minute; seconde; x; y ; angle; temperature; humidite; pression; luminosite; Distance;\r\n"
)
f.close()

#ini Bus I2c
bus_i2c = I2C()
bus_i2c.init(I2C.MASTER, baudrate=400000)
Beispiel #35
0
from machine import Pin, Timer, PWM, RTC, ADC
from time import sleep

button = Pin(34, Pin.IN)

year = int(input("Year? "))
month = int(input("Month? "))
day = int(input("Day? "))
weekday = int(input("Weekday? "))
hour = int(input("Hour? "))
minute = int(input("Minute? "))
second = int(input("Second? "))
microsecond = int(input("Microsecond? "))

rtc = RTC()
rtc.datetime((year, month, day, weekday, hour, minute, second, microsecond))
adc = ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
tim0 = Timer(0)
week = [
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"
]
tim0.init(period=30000, mode=Timer.PERIODIC, callback=lambda t: display())
tim1 = Timer(1)
tim1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: choice())
pwm0 = PWM(Pin(16), freq=10, duty=256)
pwm1 = PWM(Pin(17), freq=10, duty=256)
mode = 0
prev = 0
Beispiel #36
0
def Try_Start():
    try:
        tim = Timer(1)
        tim.init(period=500,
                 mode=Timer.PERIODIC,
                 callback=lambda t: Display_Time())

    except:
        rtc.datetime(Get_Time())
        tim.deinit()
        Try_Start()


if __name__ == '__main__':
    n = 100
    pin = Pin(13, Pin.OUT)
    np = NeoPixel(pin, n)

    (Hours1_1, Hours1_2, Hours2_1, Hours2_2) = (0, 0, 0, 0)
    (Mints1_1, Mints1_2, Mints2_1, Mints2_2) = (0, 0, 0, 0)
    Secos1 = 0
    Secos2 = 0

    #RGB = (255,20,147)

    #Np_List = []

    rtc = RTC()
    rtc.datetime(Get_Time())
    Try_Start()
Beispiel #37
0
# Init wifi
#
print("Initializing WiFi")
SSID = ''
KEY = ''

wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
for net in nets:
    if net.ssid == SSID:
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, KEY), timeout=5000)
        while not wlan.isconnected():
            machine.idle()  # save power while waiting
        print('WLAN connection succeeded!')
        print(wlan.ifconfig()
              )  # Print the connection settings, IP, Subnet mask, Gateway, DNS
        break

#
# Setup the time of the device
#
print("Initializing NTP time server")
rtc = RTC()
rtc.ntp_sync("pool.ntp.org")  # Sync with time server

uart = UART(0, baudrate=115200)
os.dupterm(uart)

print("Start executing main.py")
machine.main('main.py')
#1. 测试button 和 pause() 2.是否可以正确跳出循环
from machine import RTC, Pin, I2C, SPI
from time import sleep
import ssd1306
rtc = RTC()
rtc.datetime((2019, 9, 25, 4, 16, 5, 0, 0))
rtc.datetime()
# init button
button_A = Pin(12, Pin.IN, Pin.PULL_UP)
button_B = Pin(13, Pin.IN)
button_C = Pin(14, Pin.IN, Pin.PULL_UP)
# counter indicates the current operate element in datetime
counter = 0

# construct an I2C bus in LED
i2c = I2C(-1, Pin(5), Pin(4))
oled = ssd1306.SSD1306_I2C(128, 32, i2c)


# write and show real time
def week(n_week):
    if (n_week == 1): return 'Monday'
    elif (n_week == 2): return 'Tuesday'
    elif (n_week == 3): return 'Wednesday'
    elif (n_week == 4): return 'Thursday'
    elif (n_week == 5): return 'Friday'
    elif (n_week == 6): return 'Saturday'
    elif (n_week == 7): return 'Sunday'
    return 'Monday'

Beispiel #39
0
# MicroPython for the IOT - Chapter 5
# Example use of the utime library
# Note: This example only works on the WiPy
# Note: This example will not on your PC.
import machine
import sys
import utime

# Since we don't have a RTC, we have to set the current time
# initialized the RTC in the WiPy machine library
from machine import RTC

# Init with default time and date
rtc = RTC()
# Init with a specific time and date. We use a specific
# datetime, but we could get this from a network time
# service.
rtc = RTC(datetime=(2017, 7, 15, 21, 32, 11, 0, None))


# Get a random number from 0-1 from a 2^24 bit random value
def get_rand():
    return machine.rng() / (2**24 - 1)


# Format the time (epoch) for a better view
def format_time(tm_data):
    # Use a special shortcut to unpack tuple: *tm_data
    return "{0}-{1:0>2}-{2:0>2} {3:0>2}:{4:0>2}:{5:0>2}".format(*tm_data)

Beispiel #40
0
# main.py -- put your code here!
import pycom
import time
import sendData
from machine import RTC

pycom.heartbeat(False)

try:
    sendData.connectLocalBox('/flash/config.json')
    rtc = RTC()
    rtc.ntp_sync('fr.pool.ntp.org')
    pycom.rgbled(0x00FF00)
    time.sleep(0.2)
    pycom.rgbled(0)
    time.sleep(0.2)
    pycom.rgbled(0x00FF00)
    time.sleep(0.2)
    pycom.rgbled(0)

except Exception as e:
    print(e)
    pycom.rgbled(0xFF0000)
    time.sleep(0.2)
    pycom.rgbled(0)
    time.sleep(0.2)
    pycom.rgbled(0xFF0000)
    time.sleep(0.2)
    pycom.rgbled(0)
def test_lte_ntp(hw, max_drift_secs=4):
    _logger.info("Starting LTE test...")
    pycom_util.reset_rgbled()

    global failures
    _logger.info("Testing LTE connectivity...")

    chrono = machine.Timer.Chrono()
    chrono.start()

    with CheckStep(FLAG_SD_CARD, suppress_exception=True):
        hw.mount_sd_card()

    ou_id = None
    cc = None
    cs = None

    with CheckStep(FLAG_COMM_CONFIG, suppress_exception=True):
        import os
        import co2unit_comm
        os.chdir(hw.SDCARD_MOUNT_POINT)
        ou_id, cc, cs = co2unit_comm.read_comm_config(hw)

    with CheckStep(FLAG_TIME_SOURCE, suppress_exception=True):
        hw.sync_to_most_reliable_rtc()

    lte = None
    signal_quality = None

    try:
        with CheckStep(FLAG_LTE_FW_API):
            from network import LTE

        with CheckStep(FLAG_LTE_INIT):
            # _logger.info("Give LTE a moment to boot")
            # LTE init seems to be successful more often if we give it time first
            # time.sleep_ms(1000)
            # wdt.feed()

            _logger.info("Init LTE...")
            chrono.reset()
            pycom.nvs_set("lte_on", True)
            lte = LTE()
            _logger.info("LTE init ok (%d ms)", chrono.read_ms())
    except:
        return failures

    try:
        with CheckStep(FLAG_LTE_ATTACH):
            _logger.info("LTE attaching... (up to 2 minutes)")
            chrono.reset()
            lte.attach()
            try:
                while True:
                    wdt.feed()
                    if lte.isattached(): break
                    if chrono.read_ms() > 150 * 1000:
                        raise TimeoutError("Timeout during LTE attach")
                    time.sleep_ms(50)
            finally:
                signal_quality = pycom_util.lte_signal_quality(lte)
                _logger.info("Signal quality: %s", signal_quality)
                import co2unit_errors
                co2unit_errors.info(
                    hw,
                    "Self-test. LTE attached: {}. Signal quality {}".format(
                        lte.isattached(), signal_quality))

            _logger.info("LTE attach ok (%d ms). Connecting...",
                         chrono.read_ms())

        if signal_quality["rssi_raw"] in range(0, 31):
            led_show_scalar(signal_quality["rssi_raw"], [0, 31])

        with CheckStep(FLAG_LTE_CONNECT):
            chrono.reset()
            lte.connect()
            while True:
                wdt.feed()
                if lte.isconnected(): break
                if chrono.read_ms() > 120 * 1000:
                    raise TimeoutError("Timeout during LTE connect")
                time.sleep_ms(50)
            _logger.info("LTE connect ok (%d ms)", chrono.read_ms())

        with CheckStep(FLAG_COMM_PING, suppress_exception=True):
            import co2unit_comm
            for sync_dest in cc.sync_dest:
                co2unit_comm.send_alive_ping(sync_dest, ou_id, cc, cs)
                wdt.feed()

        with CheckStep(FLAG_NTP_FETCH, suppress_exception=True):
            from machine import RTC
            import timeutil

            chrono.reset()
            irtc = RTC()
            ts = timeutil.fetch_ntp_time(cc.ntp_host if cc else None)
            idrift = ts - time.mktime(irtc.now())
            if abs(idrift) < max_drift_secs:
                _logger.info("Drift from NTP: %s s; within threshold (%d s)",
                             idrift, max_drift_secs)
            else:
                ntp_tuple = time.gmtime(ts)
                irtc = RTC()
                irtc.init(ntp_tuple)
                hw.ertc.save_time()
                _logger.info("RTC set from NTP %s; drift was %d s", ntp_tuple,
                             idrift)
            failures &= ~FLAG_TIME_SOURCE  # Clear FLAG_TIME_SOURCE if previously set
            _logger.info("Got time with NTP (%d ms). Shutting down...",
                         chrono.read_ms())
            wdt.feed()

        with CheckStep(FLAG_LTE_SHUTDOWN):
            if lte:
                try:
                    if lte.isconnected():
                        chrono.reset()
                        lte.disconnect()
                        _logger.info("LTE disconnected (%d ms)",
                                     chrono.read_ms())
                        wdt.feed()
                    if lte.isattached():
                        chrono.reset()
                        lte.dettach()
                        _logger.info("LTE detached (%d ms)", chrono.read_ms())
                        wdt.feed()
                finally:
                    chrono.reset()
                    lte.deinit()
                    pycom.nvs_set("lte_on", False)
                    _logger.info("LTE deinit-ed (%d ms)", chrono.read_ms())
                    wdt.feed()
    except:
        pass

    show_boot_flags()
    _logger.info("Failures after LTE test: 0x%04x", failures)
    display_errors_led()

    if signal_quality and signal_quality["rssi_raw"] in range(0, 32):
        led_show_scalar(signal_quality["rssi_raw"], [0, 31])

    pycom.rgbled(0x0)
Beispiel #42
0
print(os.getcwd())
# create a new file
f = open('test.txt', 'w')
n_w = f.write(test_bytes)
print(n_w == len(test_bytes))
f.close()
f = open('test.txt', 'r')
r = bytes(f.read(), 'ascii')
# check that we can write and read it correctly
print(r == test_bytes)
f.close()
os.remove('test.txt')
os.chdir('..')
os.rmdir('test')

ls = os.listdir()
print('test' not in ls)
print(ls)

# test the real time clock
rtc = RTC()
while rtc.now()[6] > 800:
    pass

time1 = rtc.now()
time.sleep_ms(1000)
time2 = rtc.now()
print(time2[5] - time1[5] == 1)
print(time2[6] - time1[6] < 5000) # microseconds

Beispiel #43
0
    ax, ay, az, gx, gy, gz = imu.read_accelerometer_gyro_data()
    oled.text('Gyroscope:', 25, 35)
    oled.text(str(gx), 25, 45)
    return gx


p19 = Pin(19, Pin.IN)
p18 = Pin(18, Pin.OUT)
p19.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt)

i2c = I2C(-1, scl=Pin(21), sda=Pin(22))  #sets I2C bus at pins 22 and 21
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height,
                           i2c)  #oled object of class SSD1306
rtc = RTC()
rtc.datetime((2019, 1, 1, 0, 11, 20, 0,
              0))  #2019 January first zero hours zero seconds ect

imu = ICM20948()

while True:
    if button:
        print('interrupt')
        p18.on()
        sdelay(3)
        p18.off()
        button = False
    print_time()
    gx = print_Gyro()
    oled.show()
Beispiel #44
0
def getTemperature():
	global ADC_PIN_TMP36
	global T_MAX_MV
	global V_TO_MV
	global ADC_MAX_VAL
	global PRECISION_SCALE
	global OFFSET_MV
	global SCALE_FACTOR

	adc_tmp36 = ADC(0)
	apin_tmp36 = adc_tmp36.channel(pin=ADC_PIN_TMP36)
	rawTemp = 0
	for x in range(0, 100):
		adc_value = apin_tmp36.value()
		# read value (0~1024) then converted in mV then scaled to get more precision
		tMV = adc_value * (T_MAX_MV /  ADC_MAX_VAL)* PRECISION_SCALE
		# convert th mV received to temperature
		rawTemp += (tMV - OFFSET_MV) / 10

	return (rawTemp/100)

rtc = RTC()
rtc.ntp_sync('fr.pool.ntp.org')
sendData.connectLocalBox()

while 1==1:
	data = '{"temperature": %s, "timestamp": "%s", "battery" : %s}' % (getTemperature(),rtc.now(), readBatteryVoltage.readBatteryLevel())
	sendData.sendData(host='http://192.168.1.15', port=1338, data=data)
	time.sleep(300)
Beispiel #45
0
'''
RTC test for the CC3200 based boards.
'''

from machine import RTC
import os
import time

mch = os.uname().machine
if not 'LaunchPad' in mch and not 'WiPy' in mch:
    raise Exception('Board not supported!')

rtc = RTC()
print(rtc)
print(rtc.now()[:6])

rtc = RTC(datetime=(2015, 8, 29, 9, 0, 0, 0, None))
print(rtc.now()[:6])

rtc.deinit()
print(rtc.now()[:6])

rtc.init((2015, 8, 29, 9, 0, 0, 0, None))
print(rtc.now()[:6])
seconds = rtc.now()[5]
time.sleep_ms(1000)
print(rtc.now()[5] - seconds == 1)
seconds = rtc.now()[5]
time.sleep_ms(2000)
print(rtc.now()[5] - seconds == 2)