def setup(): global led global relays from config import led_pin, relay1_pin, relay2_pin try: relays['relay1'] = machine.Signal(machine.Pin(relay1_pin, machine.Pin.OUT), invert=True) except (OSError, ValueError): print(b"Couldn't config pin {}".format(relay1_pin)) try: relays['relay2'] = machine.Signal(machine.Pin(relay2_pin, machine.Pin.OUT), invert=True) except (OSError, ValueError): print(b"Couldn't config pin {}".format(relay2_pin)) connect_and_subscribe() sensor_count = initOW(ow_pin) if sensor_count > 0: tim = machine.Timer(-1) # timer startConv() tim.init(period=300000, mode=machine.Timer.PERIODIC, callback=startConv) # 5 min
def __init__(self, loopPeriod, masterAddress, masterPort, diagnosticList, ledStatusPinNumber, ledStatusPinInvert=True, wifiTimeout=5000, wifiFailureSleep=30000, blinkUpdatePeriod=1000, wifiFailureBlinkUpdatePeriod=250): print('MainApp instantiated') self.wifi = wifi.WIFIManager(wifiTimeout, ledStatusPinNumber, ledStatusPinInvert) self.loopPeriod = loopPeriod self.masterAddress = masterAddress self.masterPort = masterPort self.wifiFailureSleep = wifiFailureSleep self.diagnosticList = diagnosticList dataFormat = '' for d in self.diagnosticList: dataFormat = dataFormat + d.getDataFormat() self.packet = Packet(dataFormat) self.ledStatusPin = machine.Signal(machine.Pin(ledStatusPinNumber, machine.Pin.OUT), invert=ledStatusPinInvert) self.blinkUpdatePeriod = blinkUpdatePeriod self.wifiFailureBlinkUpdatePeriod = wifiFailureBlinkUpdatePeriod
def __init__(self, pin_number, invert=True): self._button_signal = machine.Signal(machine.Pin( pin_number, machine.Pin.IN), invert=invert) self._last_button_press = (None, None) self._last_known_button_press = (None, None)
def __init__(self): pin = machine.Pin(2, machine.Pin.OUT) self._led = machine.Signal(pin, invert=True) self._wlan = self.connectWlan() if self._wlan: upip.install('urequests') self._led.off() self._blindOpen = False self._counter = 0 self._gustCounter = 0 self._notificationCooldown = 0 self._hallSensor = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP) self._hallSensor.irq(handler=self.onHallSensor, trigger=machine.Pin.IRQ_RISING) self._switchSensor = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP) self._switchSensor.irq(handler=self.onSwitch, trigger=machine.Pin.IRQ_FALLING | machine.Pin.IRQ_RISING) self._switchTicks = utime.ticks_ms() # 1 = store ouvert # 0 = store fermé if self._switchSensor.value(): self._blindOpen = True self.measureWindSpeed()
def __init__(self, pirPinNumber, ledDebugPinNumber=-1, ledDebugPinInvert=True): self.pirPin = machine.Pin(pirPinNumber, machine.Pin.IN) self.debugPin = None if (ledDebugPinNumber >= 0): self.debugPin = machine.Signal(machine.Pin(ledDebugPinNumber, machine.Pin.OUT), invert=ledDebugPinInvert)
def init_leds(): """ Initialize the on-board LED which is on pin5 and active low """ # The on-board led of the Wemos Lolin32 is low active onboard = machine.Signal(machine.Pin(OB_LED_PIN, machine.Pin.OUT, value=1), invert=OB_LED_INVERT) red = machine.Pin(RED_LED_PIN, machine.Pin.OUT) green = machine.Pin(GRN_LED_PIN, machine.Pin.OUT) return onboard, red, green
def stop_led(req, resp): yield from picoweb.start_response(resp) machine.PWM(machine.Pin(LED_PIN)).deinit() if LED_INVERT == True: machine.Signal(machine.Pin(LED_PIN, machine.Pin.OUT), invert=True).off() else: machine.Pin(LED_PIN, machine.Pin.OUT).off() yield from resp.awrite("<br>Turned the LED off") yield from resp.awrite("<br><a href='/led_on'>Turn it back on</a>") yield from resp.awrite("<br><a href='/'>Back to Menu</a>")
def switches(**state): pins = [machine.Signal(machine.Pin(n, machine.Pin.OUT), invert=True) for n in (5, 18, 19)] print(state) if state: for i, pin in enumerate(pins): value = state.get(str(i)) print('Pin command', i, pin, value) if value is not None: print('Setting pin %s to %s' % (pin, value)) pin.value(value) return {str(i): 'ON' if pin.value() else 'OFF' for i, pin in enumerate(pins)}
def __init__(self, timeout=5000, ledStatusPin=2, ledStatusPinInverted=True): ''' Args: timeout (uint): maximum time, in milliseconds, to wait for a successful (re)connection ledStatusPin (uint): if > 0, the LED identified by the GPIO pin ledStatusPin will be used (by disconnecting it) to signal a successful connection ledStatusPinInverted (bool): if ledStatusPin > 0, selects the polarity of the LED ''' self.timeout = timeout self.ledStatusPin = None self.status = WIFI_RECONNECTED if (ledStatusPin >= 0): self.ledStatusPin = machine.Signal(machine.Pin( ledStatusPin, machine.Pin.OUT), invert=ledStatusPinInverted)
def __init__(self): with open(CONFIG_FILE) as f: self._config = json.loads(f.read()) # self._adc = machine.ADC(machine.Pin(34)) # self._adc.atten(self._adc.ATTN_11DB) # 150 to 1750mV self._id = binascii.hexlify(machine.unique_id()).decode() self._base_publish_topic = 'fis/from/{}'.format(self._id) self._base_subscribe_topic = 'fis/to/{}'.format(self._id) print('\nCORE: node ID: {}\n'.format(self._id)) self.apps = dict(config=ConfigApp(self), ) # type: typing.Dict[str, BaseApp] self._apps_tasks = dict() # type: typing.Dict[str, asyncio.Corutine] self._status_led = machine.Signal(machine.Pin(2, machine.Pin.OUT)) # last will message used for offline notification last_will = [ '{}/status'.format(self._base_publish_topic), json.dumps(dict(online=False)), True, 1 ] self._connection = MQTTConnection( status_led=self._status_led, wifi_creds=self._config.get('wlans'), client_id='esp-{}'.format(self._id), user=self._config.get('broker-username'), password=self._config.get('broker-password'), server=self._config.get('broker'), will=last_will, keepalive=30, # TODO ? wifi_coro=self._on_wifi_state_change, connect_coro=self._on_estabilished_connection, subs_cb=self._on_message_sync, clean=False, ) self._connection.DEBUG = True # 64 running tasks queue capacity, 64 waiting tasks queue capacity, self._loop = asyncio.get_event_loop(64, 64) # type: AbstractEventLoop
import machine import time pin = machine.Pin(2, machine.Pin.OUT) pin = machine.Signal(2, invert=True) def toggle(p): p.value(not p.value())
if config.get('sensor_type') == 'MAX6675': from max6675 import MAX6675 as Sensor else: from max31855 import MAX31855 as Sensor reflow_profiles = LoadProfiles(config['default_alloy']) temp_sensor = Sensor(hwspi=config['sensor_pins']['hwspi'], cs=config['sensor_pins']['cs'], miso=config['sensor_pins']['miso'], sck=config['sensor_pins']['sck'], offset=config['sensor_offset'], cache_time=int(1000 / config['sampling_hz'])) heater = machine.Signal(machine.Pin(config['heater_pins']['heater'], machine.Pin.OUT), invert=config['heater_pins']['heater_active_low']) heater.off() buzzer = Buzzer(config['buzzer_pin']) def measure_temp(): global TEMP_GUI_LAST_UPDATE while True: try: t = temp_sensor.get_temp() except Exception as e: t = str(e) gui.temp_update(t) gc.collect() utime.sleep_ms(int(1000 / config['display_refresh_hz']))
return wrapper app = http.App(__name__) # app.debug = True pins = { 'smoke': machine.ADC(machine.Pin(34)), 'temperature': machine.ADC(machine.Pin(36)), 'dht': dht.DHT22(machine.Pin(4)), 'switch': [ machine.Signal(machine.Pin(n, machine.Pin.OUT), invert=True) for n in (5, 18, 19) ] } pins['smoke'].atten( machine.ADC.ATTN_0DB ) # https://docs.micropython.org/en/latest/esp32/quickref.html#ADC.atten pins['temperature'].atten( machine.ADC.ATTN_11DB ) # https://docs.micropython.org/en/latest/esp32/quickref.html#ADC.atten @app.route('/') def index(): values = {} for route, callback in app.endpoints.items():
import machine import time button = machine.Signal(12, machine.Pin.IN,machine.Pin.PULL_UP) led = machine.Signal(14, machine.Pin.OUT) button.value() while True: val=button.value() if val : led.value(1) print("rec") else: led.value(0) print("nrecv") time.sleep(0.5)
import dht import machine import network import time from umqtt.simple import MQTTClient SSID = 'HelloWorld' NETWORK_PASS = '******' SENSOR_NAME = 'room_humidity_1' MQTT_TOPIC = 'sensor_net/room_humidity' MQTT_SERVER = '192.168.42.1' DHT_SENSOR_PIN = 14 red_led = machine.Signal(0, machine.Pin.OUT, invert=True) blue_led = machine.Signal(2, machine.Pin.OUT, invert=True) red_led.off() blue_led.off() temp_sensor = machine.ADC(0) # Disable access point interface ap_if = network.WLAN(network.AP_IF) ap_if.active(False) # Station (client) interface sta_if = network.WLAN(network.STA_IF) def toggle(pin): pin.value(not pin.value())
def run(): global _color_id PROTECTED_FILES = ["/main.py", "/boot.py", "/_boot.py"] class FileServerError(Exception): pass def setup_fallback_ap(): unique_id = ubinascii.hexlify(machine.unique_id()).upper().decode() interfaces.ap.active(True) interfaces.ap.config( essid="Kyanit {}".format(unique_id), password="******", authmode=network.AUTH_WPA_WPA2_PSK, ) async def leds_ap_mode(neop): # when fallback AP is active trigger = False while True: trigger = not trigger for idx in range(3): neop[idx] = (0, 0, 64) if idx == 0 and trigger else (0, 0, 0) neop.write() await runner.sleep_ms(250) async def check_wlan_connection(): global _color_id while True: await runner.sleep(30) if not interfaces.wlan.isconnected(): _color_id = "BBB" elif _color_id == "BBB": _color_id = colorid.from_number( int( ure.search("\d+$", interfaces.wlan.ifconfig()[0]).group(0) ) # noqa ) def action_file_list(*args): return httpsrv.response( 200, ujson.dumps( [ path for path in uos.listdir("/") if "\x00" not in path # ignore garbage files and uos.stat(path)[0] == 32768 # noqa and path not in PROTECTED_FILES # noqa ] ), httpsrv.CT_JSON, ) def action_files(method, loc, params, headers, conn, addr): if "/" in loc[7:]: # only files in root dir are allowed raise FileServerError("not on root") file_name = loc[6:] if file_name in PROTECTED_FILES: raise FileServerError("restricted") try: stat = uos.stat(file_name) except OSError: if method == "GET" or method == "DELETE" or "rename" in params: return httpsrv.response(404, '"File Not Found"', httpsrv.CT_JSON) else: if stat[0] != 32768: raise FileServerError("restricted") if method == "DELETE": uos.remove(file_name) return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) if method == "GET": with open(file_name, "rb") as file: # read from file, send to conn httpsrv.send_response( conn, **(httpsrv.response(200, content_type=httpsrv.CT_PLAIN)) ) httpsrv.readall_from(file, into=conn) return None # response already assembled above elif method == "PUT": if "rename" in params: uos.rename(file_name, params["rename"]) return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) with open(file_name, "wb") as file: # write to file, receive from conn httpsrv.readall_from(conn, into=file) return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) async def reboot(): await runner.sleep(.1) print("KYANIT Hard Reset!") machine.reset() def action_reboot(method, loc, params, headers, conn, addr): runner.stop(exc=RebootError) runner.get_event_loop().create_task(reboot()) return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) def action_state(method, loc, params, headers, conn, addr): return httpsrv.response( 200, ujson.dumps( { "unique_id": ubinascii.hexlify( machine.unique_id() ).decode().upper(), "micropython_version": uos.uname().version[ 1:uos.uname().version.index(" ") ], "firmware_version": __version__, "color_id": _color_id, "free_memory": gc.mem_free(), "free_flash": uos.statvfs("/")[0] * uos.statvfs("/")[3], "run_state": [ "ERROR {}".format(runner.get_error()[0]) if runner.get_error() is not None else "", "STOPPED", "CODE.PY MISSING", "CODE.PY IMPORTED", "CODE.PY MAIN", ][runner.get_state()], "error_traceback": [ line.strip() for line in runner.get_error()[1].split("\n") if line and "Traceback" not in line ] if runner.get_error() is not None else None, # noqa } ), httpsrv.CT_JSON, ) def action_runner_start(method, loc, params, headers, conn, addr): runner.start() return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) def action_runner_stop(method, loc, params, headers, conn, addr): runner.stop(force=True if "force" in loc else False, exc=StoppedError) return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) def action_netvar(method, loc, params, headers, conn, addr): if method == "POST": Netvar.inbound(ujson.loads(httpsrv.readall_from(conn).getvalue().decode())) return httpsrv.response(200, '"OK"', httpsrv.CT_JSON) if method == "GET": return httpsrv.response( 200, ujson.dumps(Netvar.outbound()), httpsrv.CT_JSON ) # Start in fallback AP mode if the button is pressed fallback_ap_mode = False button = machine.Signal(machine.Pin(BUTTON_PIN, machine.Pin.IN), invert=True) if button.value(): fallback_ap_mode = True # Try connecting to WLAN if not in fallback AP, else activate AP if not fallback_ap_mode: try: wlan_info = ujson.load(open("/wlan.json")) ssid = wlan_info["ssid"] password = wlan_info["password"] ifconfig = wlan_info["ifconfig"] if "ifconfig" in wlan_info else "dhcp" except Exception: # fall back to AP, if can't get JSON, or malformed fallback_ap_mode = True setup_fallback_ap() else: if not interfaces.wlan_connect( ssid, password, ifconfig=ifconfig, timeout=20 ): # fall back to AP, if can't connect interfaces.wlan.active(False) fallback_ap_mode = True setup_fallback_ap() else: fallback_ap_mode = True setup_fallback_ap() # Show fallback AP mode on LEDs if fallback_ap_mode: neop = neopixel.NeoPixel(machine.Pin(LEDS_PIN), 3) loop = runner.get_event_loop() loop.create_task(leds_ap_mode(neop)) # Set Color ID _color_id = colorid.from_number( int(ure.search("\d+$", interfaces.wlan.ifconfig()[0]).group(0)) # noqa ) # Set up HTTP server http_server = httpsrv.HTTPServer(port=3300) # File actions http_server.register("GET", "^/files$", action_file_list) http_server.register("GET", "^/files/$", action_file_list) http_server.register("GET", "^/files/.*", action_files) http_server.register("PUT", "^/files/.*", action_files) http_server.register("DELETE", "^/files/.*", action_files) # System actions http_server.register("GET", "^/sys/state$", action_state) http_server.register("POST", "^/sys/reboot$", action_reboot) http_server.register("POST", "^/sys/reboot/soft$", action_reboot) # Runner actions http_server.register("POST", "^/sys/start$", action_runner_start) http_server.register("POST", "^/sys/stop$", action_runner_stop) http_server.register("POST", "^/sys/stop/force$", action_runner_stop) # Netvar actions http_server.register("GET", "^/netvar$", action_netvar) http_server.register("POST", "^/netvar$", action_netvar) # RUN loop = runner.get_event_loop() loop.create_task(http_server.catch_requests()) if not fallback_ap_mode: # start code.py if not in fallback AP mode loop.create_task(check_wlan_connection()) loop.create_task(runner.starter_coro()) try: loop.run_forever() except Exception: # close socket, so we can restart http_server.close() raise
def __init__(self, input_pins, output_pins, server=None, client_id=None, listen_topics=None, msg_topic=None, device_topic=None, static_ip=None, user=None, password=None, rev=None, state_topic=None, avail_topic=None): self.switching_delay = 0.1 self.input_hw = [] self.output_hw = [] # Init GPIO setup ### if type(input_pins[0]) is list: state_topic_temp = [] for i, switch in enumerate(input_pins): state_topic_temp.append(state_topic + '_%d' % i) self.output_hw.append([]) self.input_hw.append([]) for m, pin in enumerate(switch): self.input_hw[i].append( machine.Pin(pin, machine.Pin.IN, machine.Pin.PULL_UP)) self.output_hw[i].append( machine.Signal(machine.Pin(output_pins[i][m], machine.Pin.OUT, machine.Pin.PULL_UP, value=1), invert=True)) else: state_topic_temp = state_topic for i, pin in enumerate(output_pins): self.input_hw.append( machine.Pin(input_pins[i], machine.Pin.IN, machine.Pin.PULL_UP)) self.output_hw.append( machine.Signal(machine.Pin(pin, machine.Pin.OUT, machine.Pin.PULL_UP, value=1), invert=True)) # #### ErrorLog.__init__(self, log_filename='error.log') self.PBit() # Class can be activated without MQTTcommander if server is not None and client_id is not None and device_topic is not None: MQTTCommander.__init__(self, server=server, client_id=client_id, device_topic=device_topic, msg_topic=msg_topic, state_topic=state_topic_temp, avail_topic=avail_topic, listen_topics=listen_topics, static_ip=static_ip, user=user, password=password) utime.sleep(1)
import machine import time import os import _thread import socket ## Set up i/o pots_solenoid_pin = machine.Pin(16, machine.Pin.OUT) tomato_solenoid_pin = machine.Pin(17, machine.Pin.OUT) # Relays to control solenoids are active-low tomato_solenoid = machine.Signal(tomato_solenoid_pin, invert=True) pots_solenoid = machine.Signal(pots_solenoid_pin, invert=True) tomato_solenoid.off() pots_solenoid.off() ## Start web app # # Code mostly lifted from https://randomnerdtutorials.com/esp32-esp8266-micropython-web-server/ def web_page(): if tomato_solenoid.value() == 1: tomato_state = "ON" else: tomato_state = "OFF" if pots_solenoid.value() == 1: pots_state = "ON"
# This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) import uos, machine #uos.dupterm(None, 1) # disable REPL on UART(0) import gc import ujson import network import utime import micropython AP_IF = network.WLAN(network.AP_IF) gc.collect() LED = machine.PWM(machine.Pin(13), duty=500, freq=2) RELAY = machine.Signal(12, machine.Pin.OUT) BUTTON = machine.Pin(0, machine.Pin.IN) REPL = bytearray((False, )) #machine.freq(160000000) try: with open('cfg.json', 'r') as jcfg: cfg = ujson.load(jcfg) except Exception as e: cfg = dict() def POWER_ON(publish=False): print("POWER ON") RELAY.on() LED.duty(900)
def __init_led(pin_led, is_low_active): led = machine.Signal( machine.Pin(pin_led, machine.Pin.OUT, value=is_low_active), invert=True if is_low_active else False ) return led
#hardware platform: FireBeetle-ESP8266 import machine import time IR=machine.Signal(15,machine.Signal.IN) #create Button object from pin15,Set Pin15 to input (D4) led=machine.Signal(13,machine.Signal.OUT) #create LED object from pin13,Set Pin13 to output (D2) while True: a=led.value(IR.value()) #Gets the state of the Button and passes the state to the LED if a==1: print("Obstacle") else: print("Nothing") time.sleep(0.1)
import machine import time DIAGNOSTIC_LED = None try: with open('config/diagnostic_led.pin', 'r') as fp: invert = False value = int(fp.read()) if value < 0: value = -value invert = True DIAGNOSTIC_LED = machine.Signal(value, machine.Pin.OUT, invert=invert) DIAGNOSTIC_LED.off() except: pass def blink_forever(cycle_period_ms): while True: blink_once(cycle_period_ms) def blink_n(cycle_period_ms, count): i = 0 while i < count: blink_once(cycle_period_ms) i += 1 def blink_once(cycle_period_ms): half_period = cycle_period_ms // 2
# coding=utf-8 # (C) Copyright 2019 Josef Kolar (xkolar71) # Licenced under MIT. # Part of bachelor thesis. import binascii import network import json import time import upip import machine MAX_ATTEMPTS = 3 status = machine.Signal(machine.Pin(2, machine.Pin.OUT)) wlans = json.load(open('./config.json')).get('wlans') sta_if = network.WLAN(network.STA_IF) sta_if.active(True) wlan_i = 0 while True: attempt = 0 print('Attempt to connect to {}.'.format(wlans[wlan_i][0])) sta_if.connect(*wlans[wlan_i]) # Connect to an AP while not sta_if.isconnected() and attempt <= MAX_ATTEMPTS: status.on() time.sleep(1) status.off()
import machine led = machine.Signal(14, machine.Pin.OUT, invert=True) led.on() led.off() import time while True: led.on() time.sleep(0.5) led.off() time.sleep(0.5)