Exemplo n.º 1
0
    def __init__(self):
        self.bus = I2C(scl=Pin(self.SCL), sda=Pin(self.SDA))
        self.int = Signal(self.INT, Pin.IN, Pin.PULL_UP, invert=True)
        #self.int = Pin(self.INT, Pin.IN, Pin.PULL_UP)
        self.timer = Timer(-1)

        # Enable outputs, bits 4-7
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_IODIR, 0b00001111]))

        # Reverse Polarity, bits 0-3
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_IPOL, 0b00001111]))

        # Enable pullups, bits 0-3
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_GPPU, 0b00001111]))

        # Set interrupt to open-drain
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_IOCON, 0b00000100]))

        # Compare against DEFVAL
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_INTCON, 0b00001111]))

        # Enable Interrupt on Change
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_GPINTEN, 0b00001111]))

        # Turn off all lights
        self.all_off()
Exemplo n.º 2
0
def main():
    from machine import Pin, Signal
    import time
    import hwconfig

    def toggle(aPin):
        aPin.value(not aPin.value())

    red = Signal(hwconfig.LED_RED, Pin.OUT, value=1, invert=True)
    blue = Signal(hwconfig.LED_BLUE, Pin.OUT, invert=True)

    do_measure = Signal(hwconfig.D5, Pin.IN, Pin.PULL_UP, invert=True)

    last_time = time.ticks_ms()
    cnt = 0

    print("If D5 is off then it just toggles 2 leds.")
    print(
        "If D5 is on then it toggles 2 leds as fast as it can and measures time"
    )
    while True:
        toggle(red)
        toggle(blue)

        if do_measure.value():
            cnt += 1
            now = time.ticks_ms()
            delta = time.ticks_diff(now, last_time)
            if delta > 1000:
                print("toggled 2 pins: {}/s".format(cnt * 1000 / delta))
                cnt = 0
                last_time = time.ticks_ms()
        else:
            time.sleep_ms(50)
Exemplo n.º 3
0
 def __init__(self, addr: int) -> None:
     uart = UART(UART_NUM,
                 CONSTANTS.UART.BAUD_RATE,
                 tx=Pin(TX_PIN),
                 rx=Pin(RX_PIN))
     tx_en = Pin(TX_EN_PIN, Pin.OUT)
     KtaneBase.__init__(self, addr, uart, tx_en, LOG, idle, ticks_us)
     self.status_red = Signal(Pin(STATUS_RED, Pin.OUT), invert=True)
     self.status_green = Signal(Pin(STATUS_GREEN, Pin.OUT), invert=True)
     self.set_mode(CONSTANTS.MODES.SLEEP)
Exemplo n.º 4
0
    def __init__(self, pin_id, invert=False):
        """Initialize a new heartbeat.

        Args:
            pin_id (int): Which pin to toggle.
            invert (bool): Whether the pin should be considered "active low".
                See the ``invert`` parameter of MicroPython's ``Signal``.
        """
        self._sig = Signal(pin_id, Pin.OUT, invert=invert)
        self._sig.off()
Exemplo n.º 5
0
    def _wait_for_sta_connection(self, a_sta_name):
        status_led = Signal(Pin(2, Pin.OUT), invert=True)

        MAX_CONNECT_TIME_MS = 20000
        start = time.ticks_ms()
        deadline = start + MAX_CONNECT_TIME_MS

        now = start
        print("connecting to wifi '{}' ...".format(a_sta_name))
        status = 0
        while now < deadline:
            new_status = self.sta_if.status()
            if new_status != status:
                status = new_status
                print("status: {}".format(self._if_status_string(status)))

                if self._connecting_finished(status):
                    break

            time.sleep_ms(50)
            now = time.ticks_ms()
            status_led.value(not status_led.value())

        if self.sta_if.isconnected():
            print("DONE (finished in {} ms)".format(now-start))
            print(self.sta_if.ifconfig())
            status_led.on()
            time.sleep_ms(500)
        else:
            print("FAILED (finished in {} ms)".format(now-start))

        status_led.off()
Exemplo n.º 6
0
    def set_outputs(self, a_params):
        """ It processes parameters given as a dictionary of "output_name": "value".
        "output_name" must exist in self.pins_out and "value" must be either 0 or 1.
        """

        for output, value in a_params.items():
            if output.decode() in self.pins_out and value.decode() in ("0",
                                                                       "1"):
                pin = Signal(eval("hwconfig." + output.decode()),
                             Pin.OUT,
                             invert=True)
                pin.value(int(value))
            else:
                print("not using {}={}".format(output, value))
Exemplo n.º 7
0
def main():
    pin = Pin(('GPIO_1', 5), Pin.OUT)
    led = Signal(pin, invert=True)
    led.off()
    led_status = 'OFF'

    while True:
        reported = {'state': {'reported': {}}}

        reported['state']['reported']['led'] = led_status

        degu.update_shadow(ujson.dumps(reported))

        received = degu.get_shadow()
        if received:
            try:
                desired = ujson.loads(received)
                try:
                    led_status = desired['state']['desired']['led']
                except:
                    pass
                if led_status == 'ON':
                    led.on()
                else:
                    led.off()
            except:
                pass

        time.sleep(1)
Exemplo n.º 8
0
class E32CB:

    pwm_fan_freq = 25000
    pwm_base_freq = 1000
    pwm_min = 0
    pwm_max = 1023

    i2c = I2C(scl=Pin(22), sda=Pin(21))
    uart = UART(2, 9600)

    q1 = Mosfet(Pin(33), pwm_base_freq, pwm_max)
    q2 = Mosfet(Pin(25), pwm_base_freq, pwm_max)
    q3 = Mosfet(Pin(27), pwm_base_freq, pwm_max)
    q4 = Mosfet(Pin(14), pwm_base_freq, pwm_max)
    q5 = Mosfet(Pin(13), pwm_base_freq, pwm_max)
    q6 = Mosfet(Pin(4), pwm_base_freq, pwm_max)
    q7 = Mosfet(Pin(18), pwm_base_freq, pwm_max)

    q8 = Signal(Pin(19, Pin.OUT), invert=True)

    @classmethod
    def invert_pwm(cls, pwm):
        return cls.pwm_min + (cls.pwm_max - pwm)

    @staticmethod
    def led(value):
        Pin(32, Pin.OUT).value(value)

    @staticmethod
    def fan(value):
        PWM(Pin(23), freq=pwm_fan_freq, duty=value)
Exemplo n.º 9
0
    def __init__(self,
                 en_pin_nr,
                 voltage,
                 settle_time_ms,
                 inverse_pol=False,
                 default_state=SUPPLY_STATE_DISABLED):
        self.EnPin = Signal(en_pin_nr, mode=Pin.OUT, invert=inverse_pol)

        if default_state is self.SUPPLY_STATE_ENABLED:
            self.Enable()
        else:
            self.EnCount = 0
            self.EnPin.off()

        self.Voltage = voltage
        self.SettleTime = settle_time_ms
Exemplo n.º 10
0
def main():
    from machine import Pin, Signal
    from utime import sleep

    pin = Pin(0, Pin.IN)  # set GPIO4 as input with pullup
    pir = Signal(pin, invert=False)  # let's use Signals, eh?
    detected = False
    while True:
        if not detected and pir.value():  # gone HIGH
            print("A Visitor!")
            mp3.play_track(urandom.getrandbits(BITS) +
                           1)  # since the MP3 doesn't recognize song 0
            detected = True
        elif detected and not pir.value():  # gone LOW
            print("Bye!")
            detected = False
            sleep(60 * 20)  # sleep 20 minutes
Exemplo n.º 11
0
class Heartbeat:
    """Toggle an output pin in a repeating pattern."""

    def __init__(self, pin_id, invert=False):
        """Initialize a new heartbeat.

        Args:
            pin_id (int): Which pin to toggle.
            invert (bool): Whether the pin should be considered "active low".
                See the ``invert`` parameter of MicroPython's ``Signal``.
        """
        self._sig = Signal(pin_id, Pin.OUT, invert=invert)
        self._sig.off()

    async def beat(self, sch):
        """Perform the heartbeat.

        Pass this function to ``create_task`` of Perthensis' ``Scheduler``.

        Note that it will set the pin to "on" for 2 seconds before starting the
        pattern. This is supposed to make board resets clearly visible.
        """
        self._sig.on()
        await sch.sleep(2)

        while True:
            for idx, delay in enumerate(PATTERN):
                self._sig.on() if idx % 2 == 0 else self._sig.off()
                await sch.sleep_ms(delay)
def main():
    from machine import Pin, Signal
    from utime import sleep

    pin2 = Pin(2, Pin.IN, Pin.PULL_UP)  # set GPIO2 as input with pullup
    button = Signal(pin2, invert=True)  # let's use Signals, eh?
    pressed = False

    do_connect()  # On boot, connect.
    while True:
        if not pressed and button.value():  # falling edge - button was pressed
            print("Button Pressed")
            pressed = True
            do_post()
        elif pressed and not button.value():  # rising edge - released button
            print("Button Released")
            pressed = False
        sleep(0.01)
Exemplo n.º 13
0
class Sonoff():
    led = Signal(Pin(13, Pin.OUT, value=1), invert=True)
    relay = Pin(12, Pin.OUT, value=0)
    button = Pin(0, Pin.IN, Pin.PULL_UP)
    mqtt = MQTTClient(CLIENT, SERVER)
    q = []

    def __init__(self):
        self.q.insert(0, self.led.value())

    def sub_cb(self, topic, msg):
        if topic == T_IN:
            # set state
            self.q.insert(0, int(msg == M_ON))

    def notify(self, topic, msg):
        task = loop.create_task(self.pub_msg(topic, msg))

    async def pub_msg(self, topic, msg):
        self.mqtt.publish(topic, msg)

    async def push_button(self):
        while True:
            start = time.ticks_ms()
            while self.button.value() == 0:
                pass
            pushed = time.ticks_diff(time.ticks_ms(), start)
            if pushed > 20:
                self.notify(T_OUT, M_BUTTON)
                self.q.insert(0, not self.led.value())
                pushed = 0
            await asyncio.sleep_ms(10)

    async def switch(self):
        while True:
            if self.q:
                state = self.q.pop()
                self.relay(state)
                self.led(state)
                if state == 1:
                    self.notify(T_RESULT, R_ON)
                    self.notify(T_OUT, M_ON)
                else:
                    self.notify(T_RESULT, R_OFF)
                    self.notify(T_OUT, M_OFF)
            await asyncio.sleep_ms(500)

    async def main(self):
        self.mqtt.connect()
        self.mqtt.set_callback(self.sub_cb)
        self.mqtt.subscribe(T_IN)
        task1 = loop.create_task(self.switch())
        task2 = loop.create_task(self.push_button())
        while True:
            self.mqtt.check_msg()
            await asyncio.sleep_ms(500)
        print('exiting')
Exemplo n.º 14
0
    def __init__(self):
        """
        Initialize the node.

        Performs the hardware setup and configuration loading from
        `config.json` file.
        """
        machine.freq(160000000)

        self.led = Signal(Pin(2, Pin.OUT), invert=True)
        self.led.off()

        self.i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)

        self.station = WLAN(STA_IF)

        self.config = json.load(open('config.json'))

        self.countdown = None
Exemplo n.º 15
0
    def __init__(self):
        """ Creates pins for use later."""
        # pins to use - just names from hwconfig
        self.pins_pullup = [
            "D{}".format(i) for i in (5, 6, 7)
        ]  # pin supporting pull up (connect to GND for change)
        self.pins_out = ["LED_RED", "LED_BLUE"]

        # objects to use
        self.pv_pullup = [(name,
                           Signal(eval("hwconfig.{}".format(name)),
                                  Pin.IN,
                                  Pin.PULL_UP,
                                  invert=True)) for name in self.pins_pullup]
        self.pv_in = []
        self.pv_out = [(name,
                        Signal(eval("hwconfig.{}".format(name)),
                               Pin.OUT,
                               invert=True)) for name in self.pins_out]
Exemplo n.º 16
0
def blink_user_led(interval, times: int = 1) -> None:
    user_led = Signal(Pin(SERVICE_LED_PIN, Pin.OUT), invert=True)
    for _ in range(times):
        user_led.on()
        time.sleep(interval)
        user_led.off()
        time.sleep(interval)
Exemplo n.º 17
0
Arquivo: wires.py Projeto: gre7g/ktane
 def __init__(self) -> None:
     KtaneHardware.__init__(self, self.read_config())
     self.handlers.update({
         CONSTANTS.PROTOCOL.PACKET_TYPE.REQUEST_ID:
         self.request_id,
         CONSTANTS.PROTOCOL.PACKET_TYPE.CONFIGURE:
         self.configure,
         CONSTANTS.PROTOCOL.PACKET_TYPE.START:
         self.start,
         CONSTANTS.PROTOCOL.PACKET_TYPE.STOP:
         self.stop,
         CONSTANTS.PROTOCOL.PACKET_TYPE.DISARMED:
         self.disarmed,
     })
     self.serial_number = b""
     self.post_pins = [
         Pin(pin_num, Pin.IN, Pin.PULL_UP) for pin_num in POSTS
     ]
     self.posts = [Signal(pin, invert=True) for pin in self.post_pins]
     self.wires = [
         Signal(Pin(pin_num, Pin.OUT), invert=True) for pin_num in WIRES
     ]
Exemplo n.º 18
0
def main():
    gc.collect()
    genWebObj = CGenWeb()
    switchState = False
    switchObj = Signal(Pin(0, Pin.OUT),
                       invert=True)  # GPIO0; Relay: NO ( normally open )
    switchObj.off()
    # ledObj = Signal(Pin(2, Pin.OUT), invert=True) # GPIO2; ESP01S
    # ledObj.off()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    s.listen(2)
    while True:
        try:
            if gc.mem_free() < G_GC_THRESHOLD:
                gc.collect()
            conn, addr = s.accept()
            conn.settimeout(3.0)
            print('Received HTTP GET connection request from %s' % str(addr))
            request = conn.recv(1024)
            conn.settimeout(None)
            request = str(request)
            print('GET Rquest Content = %s' % request)
            switch_on = request.find('/?switch_on')
            switch_off = request.find('/?switch_off')
            if switch_on == G_CMD_IDX:
                print('Switch ON -> GPIO2')
                switchState = True
                switchObj.on()
                # ledObj.on()
            if switch_off == G_CMD_IDX:
                print('Switch OFF -> GPIO2')
                switchState = False
                switchObj.off()
                # ledObj.off()
            resHtml = genWebObj.getWebPage(switchState)
            conn.send('HTTP/1.1 200 OK\n')
            conn.send('Content-Type: text/html\n')
            conn.send('Connection: closed.\n\n')
            conn.sendall(resHtml)
            conn.close()
        except OSError as e:
            conn.close()
            print('Connection closed. OSError =', e)
Exemplo n.º 19
0
class Supply:

    SUPPLY_STATE_DISABLED = const(0)
    SUPPLY_STATE_ENABLED = const(1)

    def __init__(self,
                 en_pin_nr,
                 voltage,
                 settle_time_ms,
                 inverse_pol=False,
                 default_state=SUPPLY_STATE_DISABLED):
        self.EnPin = Signal(en_pin_nr, mode=Pin.OUT, invert=inverse_pol)

        if default_state is self.SUPPLY_STATE_ENABLED:
            self.Enable()
        else:
            self.EnCount = 0
            self.EnPin.off()

        self.Voltage = voltage
        self.SettleTime = settle_time_ms

    def Enable(self):
        self.EnCount += 1
        # print("[Supply] Enable count: {}".format(self.EnCount))

        if self.EnCount is 1:
            # print("[Supply] Enabling supply")
            self.EnPin.on()
            utime.sleep_ms(self.SettleTime)
        return 0

    def Disable(self):
        if self.EnCount is 0:
            # print("[Supply] Supply cannot be disabled")
            return -1

        self.EnCount -= 1
        # print("[Supply] Enable count: {}".format(self.EnCount))

        if self.EnCount is 0:
            # print("[Supply] Disabling supply")
            self.EnPin.off()
            utime.sleep_ms(self.SettleTime)

        return 0

    def IsEnabled(self):
        return self.EnCount > 0
Exemplo n.º 20
0
def test():
    dout = Pin(Pin.board.Y5, Pin.OUT_PP, value=0)  # Define pins
    ckout = Pin(Pin.board.Y6, Pin.OUT_PP,
                value=0)  # Don't assert clock until data is set
    din = Pin(Pin.board.Y7, Pin.IN)
    ckin = Pin(Pin.board.Y8, Pin.IN)
    reset = Pin(Pin.board.Y4, Pin.OPEN_DRAIN)
    sig_reset = Signal(reset, invert=True)

    channel = SynCom(False, ckin, ckout, din, dout, sig_reset, 10000)

    loop = asyncio.get_event_loop()
    loop.create_task(heartbeat())
    loop.create_task(channel.start(initiator_task))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        ckout.value(0)
Exemplo n.º 21
0
def main():
    path = 'thing/' + zcoap.eui64()
    reported = {'state': {'reported': {}}}

    addr = zcoap.gw_addr()
    port = 5683
    cli = zcoap.client((addr, port))

    pin = Pin(('GPIO_1', 5), Pin.OUT)
    led = Signal(pin, invert=True)
    led.off()
    led_status = 'OFF'

    while True:
        reported['state']['reported']['led'] = led_status

        cli.request_post(path, ujson.dumps(reported))

        received = cli.request_get(path)
        if received:
            try:
                desired = ujson.loads(received)
                try:
                    led_status = desired['state']['desired']['led']
                except:
                    pass
                if led_status == 'ON':
                    led.on()
                else:
                    led.off()
            except:
                pass

        time.sleep(1)

    cli.close()
Exemplo n.º 22
0
    def __init__(self, i2c, pin_setup=DEFAULT_PIN_SETUP):
        """Initialize Joy Bonnet specific Pins and ADC reader (for the joystick) """
        self.i2c = i2c
        self.adc = ADS1015(i2c=i2c, address=72)
        self.pin_setup = pin_setup
        self.last_state = {}  # retain the last state of buttons
        self.x_center = self.adc.read(rate=0, channel1=1)  # around 833
        self.y_center = self.adc.read(rate=0, channel1=0)  # around 824
        self.x_thresold = 10  # minimum thresold around the center value
        self.y_thresold = 10  # minimum thresold around the center value
        # maximum & scale
        self.x_max = 1652
        self.y_max = 1652
        self.x_scale = 100 / (self.x_max / 2
                              )  # scale to retreive value between -100 & +100
        self.y_scale = 100 / (self.y_max / 2)

        for name, pinname in self.pin_setup.items():
            if not pinname:  # skip unassigned button
                continue
            p = Pin(pinname, Pin.IN, Pin.PULL_UP)
            self.pin_setup[name] = Signal(
                p, invert=True)  # replace PinName by Signal(Pin) Instance
            self.last_state[name] = False  # Initialize last know button state
Exemplo n.º 23
0
# create network class
wlan = network.WLAN(network.STA_IF)

# define inputs
# INTRUDER_PIN = D1 (GPIO5)
INTRUDER_PIN = Pin(5, Pin.IN, Pin.PULL_UP)
# SET_UNSET_PIN = D2 (GPIO4)
SET_UNSET_PIN = Pin(4, Pin.IN, Pin.PULL_UP)
# SECOND_INTRUDER_PIN = D4 (GPIO2)
SECOND_INTRUDER_PIN = Pin(2, Pin.IN, Pin.PULL_UP)

# define outputs
# esp LED
WIFI_LED_PIN = Pin(16, Pin.OUT)
wifi_LED = Signal(WIFI_LED_PIN, invert=True)

# define signals
intruder_signal = Signal(INTRUDER_PIN, invert=True)
set_unset_signal = Signal(SET_UNSET_PIN, invert=True)
second_intruder_signal = Signal(SECOND_INTRUDER_PIN, invert=True)
"""The Notifier class checks the inputs from a signal and depending on the
input triggers certain external actions, in this case triggering a webhook
using IFTTT.

The class has the following methods for direct use:

    check_signal(signal_input) - checks the signal and triggers the webhook
        if the signal state has changed.
    set_action1(str) - sets the action(value1) to be sent with the webhook.
    set_action2(str) - sets the action(value2) to be sent with the webhook.
Exemplo n.º 24
0

def sendData(x):
    global sendData_
    sendData_ = True


debounceDelay_ = 20
vane_pin_ = 5
anem_pin_ = 4
led_pin_ = 2

vane_ = Pin(vane_pin_, Pin.IN, Pin.PULL_UP)
anem_ = Pin(anem_pin_, Pin.IN, Pin.PULL_UP)
led_ = Pin(led_pin_, Pin.OUT)
ledsig_ = Signal(led_, invert=True)

anemDebounceTime_ = 0
vaneDebounceTime_ = 0
anemTime_ = 0
anemLastTime_ = 0
anemLastVal_ = anem_.value()
vaneLastVal_ = vane_.value()
anemState_ = 1
vaneState_ = 0
speeds_ = []
directions_ = []

sendData_ = False
sendTimer_ = Timer(-1)
sendTimer_.init(period=2000, mode=Timer.PERIODIC, callback=sendData)
Exemplo n.º 25
0
class KtaneHardware(KtaneBase):
    mode: int

    def __init__(self, addr: int) -> None:
        uart = UART(UART_NUM,
                    CONSTANTS.UART.BAUD_RATE,
                    tx=Pin(TX_PIN),
                    rx=Pin(RX_PIN))
        tx_en = Pin(TX_EN_PIN, Pin.OUT)
        KtaneBase.__init__(self, addr, uart, tx_en, LOG, idle, ticks_us)
        self.status_red = Signal(Pin(STATUS_RED, Pin.OUT), invert=True)
        self.status_green = Signal(Pin(STATUS_GREEN, Pin.OUT), invert=True)
        self.set_mode(CONSTANTS.MODES.SLEEP)

    def set_mode(self, mode: int) -> None:
        self.mode = mode
        if mode == CONSTANTS.MODES.SLEEP:
            LOG.info("mode=sleep")
            self.status_green.off()
            self.status_red.off()
        elif mode in [CONSTANTS.MODES.ARMED, CONSTANTS.MODES.READY]:
            LOG.info("mode=armed or ready")
            self.status_green.off()
            self.status_red.on()
        elif mode == CONSTANTS.MODES.DISARMED:
            LOG.info("mode=disarmed")
            self.status_green.on()
            self.status_red.off()

    def check_queued_tasks(self, was_idle):
        if self.queued & CONSTANTS.QUEUED_TASKS.STRIKE:
            was_idle = False
            self.strike()
            state = disable_irq()
            self.queued &= ~CONSTANTS.QUEUED_TASKS.STRIKE
            enable_irq(state)

        if self.queued & CONSTANTS.QUEUED_TASKS.DISARMED:
            was_idle = False
            self.disarmed()
            state = disable_irq()
            self.queued &= ~CONSTANTS.QUEUED_TASKS.DISARMED
            enable_irq(state)

        if was_idle:
            self.idle()

    def unable_to_arm(self) -> None:
        LOG.info("error")
        self.queue_packet(
            QueuedPacket(CONSTANTS.MODULES.MASTER_ADDR,
                         CONSTANTS.PROTOCOL.PACKET_TYPE.ERROR))

    def disarmed(self):
        LOG.info("disarmed")
        self.queue_packet(
            QueuedPacket(CONSTANTS.MODULES.MASTER_ADDR,
                         CONSTANTS.PROTOCOL.PACKET_TYPE.DISARMED))
        self.set_mode(CONSTANTS.MODES.DISARMED)

    def strike(self):
        LOG.info("strike")
        self.queue_packet(
            QueuedPacket(CONSTANTS.MODULES.MASTER_ADDR,
                         CONSTANTS.PROTOCOL.PACKET_TYPE.STRIKE))

    def stop(self, _source: int, _dest: int, _payload: bytes) -> bool:
        LOG.info("stop")
        self.set_mode(CONSTANTS.MODES.SLEEP)
        return False
import socket
import select
import errno
import sys
from machine import Signal, Pin

led1 = Signal(0, Pin.OUT, invert=False)
led2 = Signal(4, Pin.OUT, invert=False)
led3 = Signal(5, Pin.OUT, invert=False)
led1.value(0)
led2.value(0)
led3.value(0)

HEADER_LENGTH = 10

IP = "192.168.43.165"
PORT = 1234


def f(a, b):
    a = str(a)
    return a + (b - len(a)) * ' '


#my_username = input("Username: ")
my_username = '******'
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client_socket.connect((IP, PORT))
client_socket.setblocking(False)
Exemplo n.º 27
0
def main():
    # prepare bme device
    i2c = I2C(scl=Pin(hwconfig.D1), sda=Pin(hwconfig.D2))
    bme = BME280(i2c=i2c)

    # inputs
    switch_name = "D5"
    button = Signal(hwconfig.BTN_USER, Pin.IN, invert=True)
    switch = Signal(eval("hwconfig." + switch_name),
                    Pin.IN,
                    Pin.PULL_UP,
                    invert=True)

    # outputs
    led = Signal(hwconfig.LED_BLUE, Pin.OUT, invert=True)

    # load thingspeak api key
    thingspeak_cfg = "thingspeak.cfg"

    try:
        f = open(thingspeak_cfg, "r")
        api_key = f.read()
        api_key = api_key.strip()
        f.close()
    except:
        print("error reading api key from {}".format(thingspeak_cfg))
        api_key = None

    print(
        "Press USER button to see values. Press {} to upload to thingspeak.com"
        .format(switch_name))

    upload_interval_s = 1
    last_upload_time = 0

    while True:
        t, h, p = (bme.temperature, bme.humidity, bme.pressure)
        tv = float(t.replace("C", ""))
        hv = float(h.replace("%", ""))
        pv = float(p.replace("hPa", ""))

        if button.value():
            print(t, p, h)

        now = time.time()
        if switch.value():
            print(t, p, h)
            if api_key is not None:
                if now - last_upload_time > upload_interval_s:
                    print("uploading...")
                    data = {
                        "api_key": api_key,
                        "field1": tv,
                        "field2": hv,
                        "field3": pv
                    }
                    upload_to_thingspeak(data, led)

                    last_upload_time = now
                else:
                    print("you are too quick...")
            else:
                print(
                    "not uploading. Save api key in {}".format(thingspeak_cfg))

        time.sleep_ms(100)
Exemplo n.º 28
0
import machine, time
from machine import Pin, Signal
#blue led on pin 21
green = Signal(Pin(17, Pin.OUT))
red = Signal(Pin(5, Pin.OUT))
blue = Signal(Pin(2, Pin.OUT))

red.off()
blue.off()
green.off()
red.on()
blue.on()
green.on()

green

if not 'i2c' in dir():
    i2c = machine.I2C(0, sda=21, scl=22)
#init only one time
if not 'tft' in dir():
    tft = m5stack.Display()

import machine, time
if not 'i2c' in dir():
    i2c = machine.I2C(0, sda=21, scl=22)

MOTION_ID = const(104)
if MOTION_ID in i2c.scan():
    print('motion sensor detected on i2cbus')
    # load motion sensor logic,
    # two different devices share the same ID, try and retry
Exemplo n.º 29
0
from machine import Pin, Signal

valve_pin = Pin(22, Pin.OUT)
valve = Signal(valve_pin, invert=False)


def open():
    valve.off()


def close():
    valve.on()


def status():
    return 'stopped' if valve.value() else 'flowing'


close()
Exemplo n.º 30
0
# - Single Neopixel for Status
# - Simple push button

# See accompanying Fritzing diagram for circuitry.
# Still to do:
#    - Make upgrade module *really* work
#    - Make a box - thinking matchbox.

from machine import Pin, Signal, Timer, RTC
import os, utime, machine, esp, network, urequests, json
from neopixel import NeoPixel
import upgrade

pin0 = Pin(0, Pin.OUT)               # set GPIO0 to output to drive NeoPixels
pin2 = Pin(2, Pin.IN, Pin.PULL_UP)   # set GPIO12 as input with pullup
button = Signal(pin2, invert=True)   # let's use Signals, eh?
pressed = False
brightness = 128

# Change these to match your unique identifiers
# - wifi 
SSID = 'FooBar'
Password = '******'
# - io.adafruit.com 
X_AIO_Key = '4f50c52123232312334ac7582c63ed'
User = '******'
Feed = 'Feed-Name'

np = NeoPixel(pin0, 1) 
np[0] = (0,0, brightness)
np.write()