Exemple #1
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()
Exemple #2
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)
Exemple #3
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))
Exemple #4
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)
Exemple #5
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
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)
Exemple #7
0
    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
    try:
        from mpu6050 import MPU6050
        imu = MPU6050(i2c, accel_sf=10)
        print("Gyro+Accelerometer/Compass MPU id: " + hex(imu.whoami))
    except:
        from mpu9250 import MPU9250
        imu = MPU9250(i2c)
    print("Gyro+Accelerometer/Compass {} id: {}".format(
        imu.__class__.__name__, hex(imu.whoami)))
else:
    print('No motion sensor detected')

SENSITIVITY = 3

#for i in range(1000):
while 1:
    x, y, z = motion.acceleration
    blue.value(abs(x) > SENSITIVITY)
    green.value(abs(y) > SENSITIVITY)
    red.value(abs(z) > SENSITIVITY)
    time.sleep_ms(100)

print('Done')
Exemple #8
0
	print('Network Configuration (IP/GW/DNS1/DNS2): ', wlan.ifconfig())

def do_post(uptime):
	headers = {'X-AIO-Key': X_AIO_Key,'Content-Type': 'application/json'}
	url='https://io.adafruit.com/api/v2/'+User+'/feeds/'+Feed+'/data.json'
	data = json.dumps({"value": uptime/60000})
	# POST response
	response = urequests.post(url, headers=headers, data=data)
	# if not response.ok:
	#	print ("Error Posting to Adafruit") # what should we do?
	response.close()

ap = network.WLAN(network.AP_IF) # let's make sure we don't boot as an Access Point
ap.active(False)
while True:
	if not pressed and button.value():  # falling edge - button was pressed
		print("Button Pressed")
		LED(0,brightness,0)
		pressed = True
		uptime = utime.ticks_ms()
		# if connecting, posting and/or pressing button > 30s, let's launch WebREPL and debug...
		tim = Timer(-1)
		tim.init(period=30000, mode=Timer.ONE_SHOT, callback=lambda t:upgrade.start())
		do_connect()
		do_post(uptime)
	elif pressed and not button.value():   # rising edge - released button
		print("Button Released")
		LED(0,0,brightness)
		pressed = False
		tim.deinit()
	utime.sleep(0.01)
Exemple #9
0
mqtt_clientid_ = ubinascii.hexlify(unique_id()).decode('ascii')
mq_ = MQTTClient(mqtt_clientid_, mqtt_server_)
mq_.connect()

while True:
    anemVal_ = anem_.value()
    vaneVal_ = vane_.value()
    now_ = ticks_ms()

    if anemVal_ != anemLastVal_:
        anemDebounceTime_ = now_

    if (ticks_diff(now_, anemDebounceTime_) > debounceDelay_):
        if (anemVal_ != anemState_):
            anemState_ = anemVal_
            ledsig_.value(anemState_)
            if (anemState_ == 1):
                anemLastTime_ = anemTime_
                anemTime_ = anemDebounceTime_
                anemDuration_ = ticks_diff(anemTime_, anemLastTime_)
                speeds_.append(toSpeed(anemDuration_))

    if vaneVal_ != vaneLastVal_:
        vaneDebounceTime_ = now_

    if anemTime_ > 0:
        if (ticks_diff(now_, vaneDebounceTime_) > debounceDelay_):
            if (vaneVal_ != vaneState_):
                vaneState_ = vaneVal_
                if (vaneState_ == 0):
                    vaneTime_ = vaneDebounceTime_
Exemple #10
0
import time
from machine import u2if, Pin, Signal


def get_state_string(value):
    return "LOW" if value == Pin.LOW else "HIGH"


switch = Pin(u2if.GP9, Pin.IN, pull=Pin.PULL_UP)

for _ in range(10):
    input_value = switch.value()
    print("switch state : %s" % get_state_string(input_value))
    time.sleep(1)

switch_invert = Signal(Pin(u2if.GP8, Pin.IN, pull=Pin.PULL_UP), invert=True)

for _ in range(10):
    input_value = switch_invert.value()
    print("switch (inverted) state : %s" % get_state_string(input_value))
    time.sleep(1)
Exemple #11
0
from machine import Pin, Signal

RED_RGB_PIN = 15
BLUE_PIN = 2

red_pin = Pin(RED_RGB_PIN, Pin.OUT)
blue_pin = Pin(BLUE_PIN, Pin.OUT)

red_pin.value(1)
blue_pin.value(0)

red = Signal(red_pin, invert=False)
blue = Signal(blue_pin, invert=True)

red.value(1)
blue.value(1)

red.on()
blue.on()
Exemple #12
0
import time
from machine import u2if, Pin, Signal

# Initialize GPIO to output and set the value HIGH
led = Pin(u2if.GP3, Pin.OUT, value=Pin.HIGH)
time.sleep(1)
# Switch off the led
led.value(Pin.LOW)

# Active-low RGB led
led_r = Signal(Pin(u2if.GP6, Pin.OUT), invert=True)
led_g = Signal(Pin(u2if.GP7, Pin.OUT), invert=True)
led_b = Signal(Pin(u2if.GP8, Pin.OUT), invert=True)

# Switch on the three colors
led_r.value(Pin.HIGH)
led_g.on()  # == .value(Pin.HIGH)
led_b.on()
time.sleep(1)
# Switch off the three colors
led_r.off()
led_g.value(Pin.LOW)  # == .value(Pin.LOW)
led_b.value(Pin.LOW)
Exemple #13
0
class LEDBTN(object):
    ''' LED Button driver using mcp23008 '''

    SCL = 5
    SDA = 4
    INT = 2

    BASE_ADDR = 0x20

    MCP23008_IODIR = 0x00
    MCP23008_IPOL = 0x01
    MCP23008_GPINTEN = 0x02
    MCP23008_DEFVAL = 0x03
    MCP23008_INTCON = 0x04
    MCP23008_IOCON = 0x05
    MCP23008_GPPU = 0x06
    MCP23008_INTF = 0x07
    MCP23008_INTCAP = 0x08
    MCP23008_GPIO = 0x09
    MCP23008_OLAT = 0x0A

    buttondict = {'b': 0b00001000,
                  'g': 0b00000100,
                  'y': 0b00000010,
                  'r': 0b00000001}

    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()

        # Register Interrupt for Button Presses
        #self.int.irq(trigger=Pin.IRQ_FALLING, handler=int_callback)

    def all_off(self):
        ''' Turns all lights off '''

        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_GPIO, 0x0]))

    def all_on(self):
        ''' Turns all lights on '''

        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_GPIO, 0xF0]))

    def blink(self, color, time_on):
        ''' Blink an LED for a specified time, but return immediately '''
        print("Blinking Value: %s" % hex(self.buttondict[color] << 4))
        self.bus.writeto(
            self.BASE_ADDR,
            bytearray([self.MCP23008_GPIO, self.buttondict[color] << 4]))
        print("Setting timer: ", int(time_on * 1000), "ms")
        self.timer.init(
            period=int(time_on * 1000),
            mode=Timer.ONE_SHOT,
            callback=lambda t: self.light_off(color))

    def light_on(self, code):
        ''' Turns on a single light '''

        print("Called lighton for %s" % code)
        val = self.bus.readfrom_mem(self.BASE_ADDR, self.MCP23008_GPIO, 1)[0] & 0xF0
        print("Orig Value: %s" % hex(val))
        newval = val | self.buttondict[code] << 4
        print("New Value: %s" % hex(newval))
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_GPIO, newval]))

    def light_off(self, code):
        ''' Turns off a single light '''

        print("Called lightoff for %s" % code)
        val = self.bus.readfrom_mem(self.BASE_ADDR, self.MCP23008_GPIO, 1)[0] & 0xF0
        print("Orig Value: %s" % hex(val))
        newval = val ^ self.buttondict[code] << 4
        print("New Value: %s" % hex(newval))
        self.bus.writeto(self.BASE_ADDR, bytearray([self.MCP23008_GPIO, newval]))

    def get_pressed(self):
        ''' Returns pressed button after it is released '''

        print("Waiting for button press")
        #global button_pressed

        # Interrupt already waiting, read until clear
        while self.int.value():
            print("Clearing existing interrupt")
            val = self.bus.readfrom_mem(self.BASE_ADDR, self.MCP23008_INTCAP, 1)[0] & 0x0F
            print("Button read val: %s" % hex(val))
            #button_pressed = False

        # Stall until interrupt fires
        #while not button_pressed:
        while not self.int.value():
            time.sleep(0.1)

        # Read value that caused interrupt
        val = self.bus.readfrom_mem(self.BASE_ADDR, self.MCP23008_INTCAP, 1)[0] & 0x0F
        #button_pressed = False

        print("Button read val: %s" % hex(val))

        for key in self.buttondict:
            if val == self.buttondict[key]:
                return key
        print("This should never happen")
        return False
Exemple #14
0
led2 = Signal(4, Pin.OUT, invert=False)
led3 = Signal(5, Pin.OUT, invert=False)
led4 = Signal(14, Pin.OUT, invert=False)
led5 = Signal(12, Pin.OUT, invert=False)
led6 = Signal(13, Pin.OUT, invert=False)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.4.1", 80))

while 1:
    time.sleep(1)
    try:
        msg = s.recv(10).decode("utf-8")
        # print(msg)
        if msg == 'led1on':
            led1.value(1)
            message = 'led1 on'
            s.send(message.encode('utf-8'))
            print('led1 on')
        if msg == 'led1off':
            led1.value(0)
            message = 'led1 off'
            s.send(message.encode('utf-8'))
            print('led1 off')
        if msg == 'led2on':
            led2.value(1)
            message = 'led2 on'
            s.send(message.encode('utf-8'))
            print('led2 on')
        if msg == 'led2off':
            led2.value(0)
Exemple #15
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)
# Set time from NTP server
print('Setting time from NTP...')
try:
    settime()
except OSError as error:
    print('Failed to set time from NTP: ' + str(error))
    pass
print('Now: {}'.format(localtime()))

# #############################################################################

# Main loop
while True:

    # If power jack is removed, lower brightness
    if insertion.value() == 0:
        display.brightness(0)
    else:
        # Read brightness from trim pot at A0 and set on display
        brightness = set_matrix_brightness(pot, display, brightness)

    # Turn off the display at night (if configured)
    current_hour = localtime()[3]
    if (current_hour >= secrets.DISPLAY_OFF_START
            or current_hour < secrets.DISPLAY_OFF_END):
        # If we're in night mode, turn off the display
        display.off()
    else:
        # If the display was off, turn it on and reset update_time to trigger a refresh
        if display.is_off():
            display.on()
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)
Exemple #18
0
# -*- coding: utf-8 -*-
"""
   程式說明請參閱3-24頁
"""

from machine import Pin, Signal

ledPin = Pin(2, Pin.OUT, value=1)
led = Signal(ledPin, invert=True)
led.value(1)
led.value(0)
led.on()
led.off()
Exemple #19
0
if __name__ == "__main__":
    print("Initialising.....")
    # initialise intruder class
    intruder = Notifier()
    intruder.set_action1("INTRUDER+DETECTED")

    # initialise second intruder class
    second_intruder = Notifier()
    second_intruder.set_action1("SECOND+INTRUDER+DETECTED")

    # initialise set_unset class
    set_unset = Notifier()
    set_unset.set_action1("Alarm+set")
    set_unset.set_action2("Alarm+unset")

    # connect to the network
    wifi_connect()

    # pause for 10 seconds to prevent multiple reboots
    time.sleep(10)

    # main loop
    print("Running main routine...")
    while True:
        intruder.check_signal(intruder_signal.value())
        second_intruder.check_signal(second_intruder_signal.value())
        set_unset.check_signal(set_unset_signal.value())
        if not wlan.isconnected():
            time.sleep(10)
            reset()
Exemple #20
0
# Originally 'pulseOut' directly drove the transformer so we increased
# slew rate & drive. This wasn't enough so MOSFET was added to design,
# but the high slew & drive is left set. Potentially we could modulate
# the drive signal slightly by adjusting drive strength?
machine.mem32[0x4 + 0x04 * pulse_out_pin + 0x4001c000] = 0b1110011
pulseOut.low()

enabled = False
oldButtonArm = False
buttonPulse_hit = False

timeout_start = utime.ticks_ms()

while True:
    # Arm button 'toggles' output on/off
    if buttonArm.value() and oldButtonArm == False:
        oldButtonArm = True

        if enabled == False:
            enabled = True
            ledArm.on()
            timeout_start = utime.ticks_ms()
        else:
            enabled = False
            ledArm.off()
            pwm_off()
            timeout_start = utime.ticks_ms()
            buttonPulse_hit = False

    if buttonArm.value() == False:
        oldButtonArm = False