コード例 #1
0
    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))
コード例 #2
0
ファイル: sign80.py プロジェクト: pelrun/signmatrix
def main():
    machine.freq(160000000)

    c = MQTTClient("HSBNE-small-sign", "10.0.1.253", user="", password="")
    c.set_callback(sub_cb)
    c.set_last_will("devices/small-sign/state", "offline", retain=True)
    c.connect()
    c.subscribe("devices/small-sign/#")
    c.publish("devices/small-sign/state", "online", retain=True)
    c.publish("devices/main-sign/ip",
              network.WLAN(network.STA_IF).ifconfig()[0],
              retain=True)

    sign = SignMatrix()
    try:
        while True:
            while c.check_msg():
                pass
            if enable != 0:
                sign.set_delay(delay)
                sign.scroller(text)
            else:
                c.wait_msg()
    except KeyboardInterrupt:
        c.publish("devices/small-sign/state", "offline", retain=True, qos=1)
        c.disconnect()
コード例 #3
0
def main():
    esp.osdebug(None)
    print("CPU frequency is {}".format(machine.freq()))
    machine.freq(80000000)
    print("CPU frequency is {}".format(machine.freq()))

    if wifi.connect(ssid, password):
        print("Starting webrepl")
        if webrepl.listen_s is None:
            webrepl.start()
        else:
            print("Webrepl already started")
        # pwm.init(pin=pwm_pin, frequency=pwm_frequency)
        client_id = wifi.station.config("dhcp_hostname")
        topic_sub = "shellies/shellyem3-ECFABCC7F0F4/emeter/0/power"
        topic_pub = "iot/sonoff/" + client_id + "/"
        mqtt.connect(client_id,
                     mqtt_server,
                     topic_sub,
                     topic_pub,
                     user=mqtt_user,
                     password=mqtt_pass)
    else:
        print("Wifi did not connect")
    restart_and_reconnect()
コード例 #4
0
ファイル: app.py プロジェクト: ryabukha/micro_esp
def do_disable_wifi():
    network.WLAN(0).active(0)
    network.WLAN(1).active(0)
    print('wifi is disabled')
    machine.freq(80000000)
    print(machine.freq())
    return False
コード例 #5
0
    def __init__(self, get_pin=None, put_pin=None, sm_freq=1_000_000):
        self.get_done = False
        self.sm_get_nr = 0
        if get_pin is not None:
            if (sm_freq * 2) > machine.freq():
                raise (ValueError, "frequency too high")
            self.sm_get = rp2.StateMachine(self.sm_get_nr,
                                           self.sm_get_pulses,
                                           freq=sm_freq * 2,
                                           jmp_pin=get_pin,
                                           in_base=get_pin,
                                           set_base=get_pin)
            self.sm_get.irq(self.irq_finished)
        else:
            self.sm_get = None

        self.put_done = False
        self.sm_put_nr = 4
        if put_pin is not None:
            if (sm_freq) > machine.freq():
                raise (ValueError, "frequency too high")
            self.sm_put = rp2.StateMachine(self.sm_put_nr,
                                           self.sm_put_pulses,
                                           freq=sm_freq,
                                           out_base=put_pin)
            self.sm_put.irq(self.irq_finished)
        else:
            self.sm_put = None
コード例 #6
0
ファイル: demo_bar_oled.py プロジェクト: kxion/micropython
def demo():
    machine.freq(160000000)
    print('demonstration led-bar... Ctrl-C to stop')
    bar.demo_bar(0.1)
    print('demonstration OLED... Ctrl-C to stop')
    oled.demo(oled.i2c, 'Micropython rock-and-roll!!')
    machine.freq(80000000)
コード例 #7
0
def read(SCK=15, DAT=13):
    """ reads a raw value from hx711 """

    data = Pin(DAT, Pin.IN)
    sck = Pin(SCK, Pin.OUT, value=0)
    
    initialFreq = freq() # so we can slow it down afterwards
    freq(160000000) # hx711 needs a high clock frequency :o
    
    value = 0
    
    if data.value() == 0:

        for i in range(24):
            sck.value(1)
            sck.value(0)
            value = value << 1 | data.value()

        for j in range(1):
            sck.value(1)
            sck.value(0)

        # convert 2's complement to integer
        if value & (1 << (24 - 1)):
            value -= 1 << 24

        freq(initialFreq) # back to initialFreq
    
    return value
コード例 #8
0
ファイル: sdtest.py プロジェクト: xinghuaman/ulx3s-misc
def run():
    # some SD cards won't work in 4-bit mode unless freq() is explicitely set
    freq(240 * 1000 * 1000)  # 80/160/240 MHz, faster CPU = faster SD card
    #sd=SDCard(slot=3) # 1-bit mode
    sd = SDCard()  # 4-bit mode
    mount(sd, "/sd")
    print(listdir("/sd"))
    f = open("/sd/long_file.bin", "rb")  # any 1-10 MB long file
    b = bytearray(16 * 1024)
    i = 0
    t1 = ticks_ms()
    while f.readinto(b):
        i += 1
    t2 = ticks_ms()
    print("%d KB in %d ms => %d KB/s file read" %
          (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 //
           (t2 - t1)))
    f.close()
    umount("/sd")
    i = 0
    t1 = ticks_ms()
    while i < 256:
        sd.readblocks(i, b)
        i += 1
    t2 = ticks_ms()
    print("%d KB in %d ms => %d KB/s raw sector read" %
          (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 //
           (t2 - t1)))
    sd.deinit()
コード例 #9
0
def test():
    freq(160000000)
    print('Test for IR receiver. Assumes NEC protocol.')
    p = Pin(13, Pin.IN)
    ir = NEC_IR(p, cb)
    loop = asyncio.get_event_loop()
    loop.run_forever()
コード例 #10
0
    def light_sleep(cls, duration):
        #for start_callback in cls._start_light_sleep_callbacks:
        #  start_callback()

        machine.freq(PowerPlan.freq_min)
        machine.lightsleep(duration)
        machine.freq(cls._used_plan.frequency)
コード例 #11
0
def __main__(args):
    if len(args) < 3:
        print("Current CPU Frequency: {} MHz".format(machine.freq() / 1000 /
                                                     1000))
    elif len(args) == 3:
        print("Setting CPU Frequency to: {} MHz".format(int(args[2])))
        machine.freq(int(args[2]) * 1000 * 1000)
コード例 #12
0
ファイル: rfsocket.py プロジェクト: DavidVentura/iot_home
 def __init__(self, pin, chann=ANSLUT, remote_id=0, timings=RFTimings):
     machine.freq(160000000)
     self._pin = pin
     self._chann = chann
     self._remote_id = (remote_id & (2**26 - 1)) or default_remote_id()
     self._timings = timings
     self._status = [False, False, False]
コード例 #13
0
def main_init():
    global status_dict
    machine.freq(DEVICE_FREQ)

    if (wlan_wrapper.init_wifi(WLAN_SSID,
                               WLAN_KEY,
                               DHCP_HOSTNAME,
                               timeout=None)):
        status_dict.update(hostname=wlan_wrapper.wlan.config('dhcp_hostname'))
        print('Wifi initialised')

    if (uart_wrapper.init() is not None):
        print('Uart initialised')

    init_mqtt()
    mqtt_wrapper.mqtt_client.publish(MQTT_TOPIC,
                                     '# {} is up'.format(DHCP_HOSTNAME))
    print('MQTT initialised')

    init_publish_timer()
    init_heartbeat_timer()

    frequency_counter = init_frequency_counter()

    return frequency_counter
コード例 #14
0
 async def start(self):
     try:
         hw.log.info("Starting device...")
         set_gc()
         collect()
         await self.__setup_button()
         collect()
         await self.__setup_ble()
         collect()
         await self.__setup_wifi()
         collect()
         await self.__setup_http()
         collect()
         await self.__setup_mqtt()
         collect()
         await self.__setup_scheduler()
         collect()
         await self.__setup_devices()
         collect()
         hw.log.info("Device started.")
     except BaseException as e:
         hw.log.error(
             "Start device failed! Exception: %s\nEntering error mode.", e)
         freq(LOWER_POWER_FEQ)
         self.__in_error_mode = True
         self.__setup_led()
         raise e
     get_event_loop().run_forever()
コード例 #15
0
def test():
   start_fq = machine.freq() // 1000000
   for fq in (240, 160, 80):
       machine.freq(fq)
       time.sleep(1)
       test_times(500000)
   machine.freq(start_fq)
コード例 #16
0
ファイル: irremote.py プロジェクト: yangzl2014/Mixly_Arduino
def resume(pin, c):
    print('Test for IR receiver. Assumes NEC protocol.')
    if platform == 'esp8266':
        freq(160000000)
    p = Pin(pin, Pin.IN)  #19
    ir = NEC_IR(p, c, True)  # Assume r/c uses extended addressing
    loop = asyncio.get_event_loop()
    loop.run_forever()
コード例 #17
0
ファイル: dome.py プロジェクト: wlatanowicz/telescopy
def start_dome():
    machine.freq(160000000)

    loop = uasyncio.get_event_loop()
    loop.create_task(DeviceHandler.main())
    loop.create_task(uasyncio.start_server(conn_handler, "0.0.0.0", 8081))
    loop.run_forever()
    loop.close()
コード例 #18
0
ファイル: dmain.py プロジェクト: marsex/asmon_structure
def boot():
    esp.osdebug(None)
    machine.freq()          # get the current frequency of the CPU
    machine.freq(240000000) # set the CPU frequency to 240 MHz
    print('\n\nStarting WiFi System\n\n')
    print(wifi.start())

    print('\n\nStarting OFFLINE System\n\n')
    print(off_sys.start())
コード例 #19
0
async def main():
    #  ESP32 oletusnopeus on 160 MHZ, lasketaan CPU lämmöntuoton vuoksi
    machine.freq(80000000)
    # Taustalle menevät prosessit
    asyncio.create_task(sensori.lue_co2_looppi())
    asyncio.create_task(kerro_tilannetta())

    while True:
        await asyncio.sleep(5)
コード例 #20
0
def pwr(mode=None):
    from machine import freq
    if mode is not None and mode.lower().strip() == 'norm':
        freq(80000000)
        return 'LOW MODE: CPU 8Mhz'
    if mode is not None and mode.lower().strip() == 'boost':
        freq(160000000)
        return 'HIGH MODE: CPU 16Mhz'
    return '{} ? boost or norm'.format(mode)
コード例 #21
0
ファイル: http_control.py プロジェクト: ignalex/esp
def cpu_freq(value=['80']):
    "80 or 160"
    import machine
    try:
        machine.freq(int(value[0]) * 1000000)
        return 'CPU changed to ' + str(machine.freq())
    except Exception as e:
        print(e)
        return str(e)
コード例 #22
0
 def __init__(self):
     freq(240 * 1000 * 1000)
     self.busy = Pin(35, Pin.IN)
     self.csn = Pin(26, Pin.OUT)
     self.csn.on()
     self.spi = SPI(2, baudrate=20*1000000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB,\
       mosi=Pin(25), sck=Pin(0), miso=Pin(22))
     self.vf = st7789vfont.st7789vfont(self.csn, self.busy, self.spi)
     self.pl = st7789poly.st7789poly(self.csn, self.busy, self.spi)
コード例 #23
0
ファイル: main.py プロジェクト: simfu/microrfgw
def main():
    init_net()
    mqtt_cli = init_mqtt()
    webrepl.start(password=config.ws_pass)
    machine.freq(160000000)
    log("Waiting for messages")
    while 1:
        mqtt_cli.check_msg()
        time.sleep(0.5)
    mqtt_cli.disconnect()
コード例 #24
0
ファイル: art.py プロジェクト: zelotoj/micropython-async
def test():
    print('Test for IR receiver. Assumes NEC protocol.')
    if platform == 'pyboard':
        p = Pin('X3', Pin.IN)
    elif platform == 'esp8266':
        freq(160000000)
        p = Pin(13, Pin.IN)
    ir = NEC_IR(p, cb, True)  # Assume r/c uses extended addressing
    loop = asyncio.get_event_loop()
    loop.run_forever()
コード例 #25
0
ファイル: util.py プロジェクト: pramodag/ulnoiot
def file_hashs():
    speed = machine.freq()
    machine.freq(160000000)  # we want to be fast for this
    p = os.getcwd()
    if p == "":
        p = "/"
    os.chdir("/")
    _file_hashs("")
    os.chdir(p)
    machine.freq(speed)  # restore speed
コード例 #26
0
def hashlist(root="/"):
    speed = machine.freq()
    machine.freq(160000000)  # we want to be fast for this
    p = os.getcwd()
    if p == "":
        p = "/"
    os.chdir("/")
    _hashlist(root)
    os.chdir(p)
    machine.freq(speed)  # restore speed
コード例 #27
0
ファイル: main.py プロジェクト: fosses/nodo-sensor-wifi-mod
def start(wdt=None):
    freq(80000000)
    #	timer = Timer(2)
    print("iniciando...")
    print(wake_reason())
    if wdt is None:
        wdt = WDT(timeout=240000)
    # Inicializa habilitación de los sensores de material particulado.
    hpma_pin = Pin(16, Pin.OUT)  #Se?al de activaci?n de transistor
    pms_pin = Pin(4, Pin.OUT)  #Se?al de activaci?n de transistor
    #	hpma_pin.value(0)
    #	pms_pin.value(0)

    # Configura buses de comunicación.
    uart = UART(2, baudrate=115200, rx=32, tx=17, timeout=1000)
    uart2 = UART(1, baudrate=9600, rx=33, tx=2, timeout=1000)
    i2c = I2C(sda=Pin(21, Pin.PULL_UP), scl=Pin(22, Pin.PULL_UP), freq=20000)
    spi = SPI(sck=Pin(14), mosi=Pin(13), miso=Pin(15))
    cs = Pin(5, Pin.OUT)

    # Inicia logger. Interfaz para SD.
    logger = Logger(spi=spi, cs=cs)
    logger.success("Estacion inicializada")
    # Sincroniza NTP
    _time.setntp(logger=logger)

    #Crea publicadores
    publishers = []
    for pub in config.publishers(logger):
        publishers.append(
            Publisher(host=pub["host"],
                      token=pub["token"],
                      port=pub["port"],
                      format_=pub["format"],
                      logger=logger,
                      wdt=wdt))
    attr = config.attributes()
    attr["version"] = VERSIONSW
    atrpub = dumps(attr)
    #	print("iniciando timer")
    #	timer.init(period=540000, mode=Timer.PERIODIC, callback=lambda t:readandpublish(None,uart, uart2, i2c, spi, logger, hpma_pin, pms_pin, publishers, atrpub))
    #	print("timer iniciado")
    readandpublish(None, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin,
                   publishers, atrpub)
    # Vuelve a intentar insertar las telemetrias pendientes desde la bd
    freq(240000000)
    for pub in publishers:
        pub.dbPublish(atrpub, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin,
                      publishers)
    logger.success("Ciclo de funcionamiento exitoso")
    logger.close()
    #	state = disable_irq()
    #	timer.deinit()
    return
コード例 #28
0
def test():
    # Define pin according to platform
    if platform == 'pyboard':
        pin = Pin('X3', Pin.IN)
    elif platform == 'esp8266':
        freq(160000000)
        pin = Pin(13, Pin.IN)
    elif platform == 'esp32' or platform == 'esp32_LoBo':
        pin = Pin(23, Pin.IN)
    irg = IR_GET(pin)
    print('Waiting for IR data...')
    return irg.acquire()
コード例 #29
0
def main():
    while True:
        if isOn():
            print("!!! starting up")
            machine.freq(160000000)
            wlan.active(True)
            run()
        else:
            print("zzzzz")
            wlan.active(False)
            machine.freq(80000000)
            utime.sleep(2)  #replace with esp8266 light sleep?
コード例 #30
0
def main():
    from machine import Signal, Pin, freq
    import hwconfig
    import time
    import gc

    btn_fetch = Signal(hwconfig.D6, Pin.IN, Pin.PULL_UP, invert=True)
    btn_turbo = Signal(hwconfig.D5, Pin.IN, Pin.PULL_UP, invert=True)
    blue_led = Signal(hwconfig.LED_BLUE, Pin.OUT, invert=True)
    red_led = Signal(hwconfig.LED_RED, Pin.OUT, invert=True)

    print("Connect D6 to GND to fetch data")
    print("Keep D5 pressed to speed up clock")
    while True:
        if btn_fetch.value():
            print("fetching")
            params = {
                "stopId": "Technik",
                "optDir": -1,
                "nRows": 4,
                "showArrivals": "n",
                "optTime": "now",
                "allLines": "y"
            }

            red_led.on()
            time_fetch = time.ticks_ms()
            xml = get_ivb_xml(params)
            time_fetch = time.ticks_diff(time.ticks_ms(), time_fetch)
            red_led.off()

            gc.collect()

            blue_led.on()
            speed_up = btn_turbo.value()
            if speed_up:
                freq(160000000)
                print("speeding up")
            time_parse = time.ticks_ms()
            smart_info = extract_bus_plan(xml)
            time_parse = time.ticks_diff(time.ticks_ms(), time_parse)
            if speed_up:
                freq(80000000)
            blue_led.off()

            gc.collect()
            print(smart_info)
            print("fetched in {} ms, parsed in {} ms".format(
                time_fetch, time_parse))

        gc.collect()
        time.sleep_ms(100)
コード例 #31
0
ファイル: stats_api.py プロジェクト: fadushin/esp8266
 def get_machine_stats(self):
     import machine
     import ubinascii
     id = "0x{}".format(ubinascii.hexlify(machine.unique_id()).decode().upper())
     return {
         'freq': machine.freq(),
         'unique_id': id
     }
コード例 #32
0
ファイル: machine.py プロジェクト: 19emtuck/micropython
machine test for the CC3200 based boards.
'''

import machine
import os
from network import WLAN

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

wifi = WLAN()

print(machine)
machine.idle()
print(machine.freq() == (80000000,))
print(machine.unique_id() == wifi.mac())

machine.main('main.py')

rand_nums = []
for i in range(0, 100):
    rand = machine.rng()
    if rand not in rand_nums:
        rand_nums.append(rand)
    else:
        print('RNG number repeated')
        break

for i in range(0, 10):
    machine.idle()
コード例 #33
0
ファイル: main.py プロジェクト: wuub/micropython-rfsocket
#!/usr/bin/env python3
import usocket
from machine import Pin, freq, reset
from rfsocket import Esp8266Timings, RFSocket
from webrepl import start

freq(160000000)  # unfortuneately, on lower settings it's almost unusable
start()
rf_pin = Pin(0, Pin.OUT)


REMOTES = {}


def remote(remote_id_str):
    remote_id = int(remote_id_str)
    if remote_id not in REMOTES:
        REMOTES[remote_id] = RFSocket(rf_pin, RFSocket.ANSLUT, remote_id=remote_id, timings=Esp8266Timings)
    return REMOTES[remote_id]


def switch_on(remote_id_str, switch_num_str):
    switch_num = int(switch_num_str)
    r = remote(remote_id_str)
    r.on(switch_num)
    return r.status()


def switch_off(remote_id_str, switch_num_str):
    switch_num = int(switch_num_str)
    r = remote(remote_id_str)
コード例 #34
0
ファイル: beer.py プロジェクト: dries007/MicroPythonUtils
import machine
import gc
import micropython
import network
import time
import ds3231
import lcdi2c
import ubinascii
import sys
import socket
import websocket
import uhashlib
import json

esp.osdebug(None)
machine.freq(160000000)
micropython.alloc_emergency_exception_buf(200)

wlan = network.WLAN(network.STA_IF)
ap = network.WLAN(network.AP_IF)

SOFT_RESET = const(4)
SLEEP_RESET = const(5)
HARD_RESET = const(6)

print()
print('FLASH ID:    %s' % hex(esp.flash_id()))
print('WLAN MAC:    %s' % ':'.join('%02X' % b for b in wlan.config("mac")))
print('AP MAC:      %s' % ':'.join('%02X' % b for b in ap.config("mac")))

gc.collect()