예제 #1
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)
예제 #2
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)
예제 #3
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()
예제 #4
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)
예제 #5
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)
예제 #6
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
예제 #7
0
파일: main.py 프로젝트: palmtoy/Exercise
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)
예제 #8
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()
예제 #9
0
class Heartbeat:
    def __init__(self, scheduler, pin_id, invert=False):
        self._sig = Signal(pin_id, Pin.OUT, invert=invert)
        self._sig.off()
        scheduler.create_task(self._cycle)

    async def _cycle(self, sch):
        self._sig.on()
        await sch.sleep(2)
        while True:
            self._sig.on()
            await sch.sleep_ms(50)
            self._sig.off()
            await sch.sleep_ms(100)
            self._sig.on()
            await sch.sleep_ms(100)
            self._sig.off()
            await sch.sleep_ms(750)
예제 #10
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)
p2 = Pin('P2', Pin.OUT_PP)
p3 = Pin('P3', Pin.OUT_PP)
top_led = Signal(p0, invert=False)
bot_led = Signal(p1, invert=False)
left_led = Signal(p2, invert=False)
right_led = Signal(p3, invert=False)

# Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are
# returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the
# camera resolution. "merge=True" must be set to merge overlapping color blobs for color codes.
while(True):
    clock.tick()
    img = sensor.snapshot()
    for blob in img.find_blobs(thresholds, pixels_threshold=200, area_threshold=200, merge=True):
        img.draw_rectangle(blob.rect())
        img.draw_cross(blob.cx(), blob.cy())
        img.draw_string(blob.x() + 1, blob.y() + 1, "Yellow Ball")
       # Area = blob.area()
        #print("Area of blob is:", Area)
        print ("x=",blob.x(),"y=",blob.y())
    if   (blob.x())<=160: left_led.on()
    elif  (blob.x())>=160: left_led.off()
    if   (blob.y())<=120: top_led.on()
    elif  (blob.y())>=120: top_led.off()
    if   (blob.x())>=160: right_led.on()
    elif  (blob.x())<=160: right_led.off()
    if   (blob.y())>=120: bot_led.on()
    elif  (blob.y())<=120: bot_led.off()


예제 #12
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
예제 #13
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()
from machine import Signal, Pin
from time import sleep

ledPin2 = machine.Pin(2, machine.Pin.OUT)
led2 = Signal(ledPin2, invert=True)
led2.off()

while True:
    led2.on()
    sleep(0.5)
    led2.off()
    sleep(0.25)
예제 #15
0
파일: main.py 프로젝트: palmtoy/Exercise
try:
    import usocket as socket
except:
    import socket

import gc

from dcmotor import DCMotor
from machine import Pin, Signal, PWM

gc.collect()

ledLight = Signal(Pin(2, Pin.OUT), invert=True)  # GPIO2 ( D4 )
ledLight.on()
pwmFrequency = 500
enablePin = PWM(Pin(4), pwmFrequency)  # GPIO4 ( D2 )
pin1 = Pin(5, Pin.OUT)  # GPIO5 ( D1 )
pin2 = Pin(14, Pin.OUT)  # GPIO14 ( D5 )
dcMotorA = DCMotor(pin1, pin2, enablePin)

pin3 = Pin(12, Pin.OUT)  # GPIO12 ( D6 )
pin4 = Pin(13, Pin.OUT)  # GPIO13 ( D7 )
dcMotorB = DCMotor(pin3, pin4, enablePin)

forwardSpeed = 100
backwardSpeed = 80


def web_page():
    html = """
<html>
예제 #16
0
파일: main.py 프로젝트: palmtoy/Exercise
def main():
    gc.collect()

    genWebObj = CGenWeb()

    ledLight = Signal(Pin(2, Pin.OUT), invert=False)  # GPIO2 ( P2 )
    sleep(0.1)
    ledLight.on()

    dcMotorLT = CDcMotor(15, 4)  # GPIO15 ( P15 ), GPIO4 ( P4 )
    sleep(0.1)
    dcMotorLT.stop()

    dcMotorLB = CDcMotor(16, 17)  # GPIO16 ( P16 ), GPIO17 ( P17 )
    sleep(0.1)
    dcMotorLB.stop()

    dcMotorRT = CDcMotor(5, 18)  # GPIO5 ( P5 ), # GPIO18 ( P18 )
    sleep(0.1)
    dcMotorRT.stop()

    dcMotorRB = CDcMotor(19, 23)  # GPIO19 ( P19 ), GPIO23 ( P23 )
    sleep(0.1)
    dcMotorRB.stop()

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 80))
    sock.listen(2)
    while True:
        try:
            if gc.mem_free() < G_GC_THRESHOLD:
                gc.collect()
            conn, addr = sock.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)
            speed_up = request.find('/?speed_up')
            slow_down = request.find('/?slow_down')
            left_front = request.find('/?left_front')
            car_forward = request.find('/?car_forward')
            right_front = request.find('/?right_front')
            car_left = request.find('/?car_left')
            car_stop = request.find('/?car_stop')
            car_right = request.find('/?car_right')
            turn_left = request.find('/?turn_left')
            car_backward = request.find('/?car_backward')
            turn_right = request.find('/?turn_right')
            if speed_up == G_CMD_IDX:
                print('cmd: speed_up')
                ledLight.on()
                dcMotorLT.speedUp()
                dcMotorLB.speedUp()
                dcMotorRT.speedUp()
                dcMotorRB.speedUp()
            elif slow_down == G_CMD_IDX:
                print('cmd: slow_down')
                ledLight.on()
                dcMotorLT.slowDown()
                dcMotorLB.slowDown()
                dcMotorRT.slowDown()
                dcMotorRB.slowDown()
            elif left_front == G_CMD_IDX:
                print('cmd: left_front')
                ledLight.on()
                dcMotorLB.forward(G_TURN_SPEED)
                dcMotorRT.forward(G_TURN_SPEED)
                dcMotorLT.stop()
                dcMotorRB.stop()
            elif car_forward == G_CMD_IDX:
                print('cmd: car_forward')
                ledLight.on()
                dcMotorLT.forward(G_FORWARD_SPEED)
                dcMotorLB.forward(G_FORWARD_SPEED)
                dcMotorRT.forward(G_FORWARD_SPEED)
                dcMotorRB.forward(G_FORWARD_SPEED)
            elif right_front == G_CMD_IDX:
                print('cmd: right_front')
                ledLight.on()
                dcMotorLT.forward(G_TURN_SPEED)
                dcMotorRB.forward(G_TURN_SPEED)
                dcMotorLB.stop()
                dcMotorRT.stop()
            elif car_left == G_CMD_IDX:
                print('cmd: car_left')
                ledLight.on()
                dcMotorLT.backward(G_TURN_SPEED)
                dcMotorLB.forward(G_TURN_SPEED)
                dcMotorRT.forward(G_TURN_SPEED)
                dcMotorRB.backward(G_TURN_SPEED)
            elif car_stop == G_CMD_IDX:
                print('cmd: car_stop')
                ledLight.off()
                dcMotorLT.stop()
                dcMotorLB.stop()
                dcMotorRT.stop()
                dcMotorRB.stop()
            elif car_right == G_CMD_IDX:
                print('cmd: car_right')
                ledLight.on()
                dcMotorLT.forward(G_TURN_SPEED)
                dcMotorLB.backward(G_TURN_SPEED)
                dcMotorRT.backward(G_TURN_SPEED)
                dcMotorRB.forward(G_TURN_SPEED)
            elif turn_left == G_CMD_IDX:
                print('cmd: turn_left')
                ledLight.on()
                dcMotorLT.backward(G_TURN_SPEED)
                dcMotorLB.backward(G_TURN_SPEED)
                dcMotorRT.forward(G_TURN_SPEED)
                dcMotorRB.forward(G_TURN_SPEED)
            elif car_backward == G_CMD_IDX:
                print('cmd: car_backward')
                ledLight.on()
                dcMotorLT.backward(G_BACKWARD_SPEED)
                dcMotorLB.backward(G_BACKWARD_SPEED)
                dcMotorRT.backward(G_BACKWARD_SPEED)
                dcMotorRB.backward(G_BACKWARD_SPEED)
            elif turn_right == G_CMD_IDX:
                print('cmd: turn_right')
                ledLight.on()
                dcMotorLT.forward(G_TURN_SPEED)
                dcMotorLB.forward(G_TURN_SPEED)
                dcMotorRT.backward(G_TURN_SPEED)
                dcMotorRB.backward(G_TURN_SPEED)
            resHtml = genWebObj.getWebPage()
            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)
예제 #17
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()
예제 #18
0
import zcoap
import time
import ujson

if __name__ == '__main__':
    path = 'thing/' + zcoap.eui64()
    reported = {'state':{'reported':{}}}


    pin = Pin(('GPIO_1', 7), Pin.OUT)
    led1 = Signal(pin, invert=True)
    led1.off()

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

        reported['state']['reported']['message'] = 'OK'
        print(ujson.dumps(reported))
        cli.request_post(path, ujson.dumps(reported))

        received = cli.request_get(path)

        if received:
            led1.on()

        time.sleep(5)

        cli.close()
예제 #19
0
wifi = WLAN(STA_IF)
pot = ADC(0)

# Leds
led_0 = Signal(LED_0_PIN, Pin.OUT, invert=True)
led_2 = Signal(LED_2_PIN, Pin.OUT, invert=False)
led_1 = Signal(LED_1_PIN, Pin.OUT, invert=False)

# Insertion detection
insertion = Signal(INSERTION_PIN, Pin.IN)

# Read brightness from trim pot at A0 and set it
brightness = set_matrix_brightness(pot, display, 0)

# Draw WiFi symbol
led_0.on()
led_2.on()
symbols.draw(symbols.WIFI, matrix=display, display=1, clear=True)
sleep(0.5)

# Enable garbage collector
gc.enable()

# Connect to WiFi
if not wifi.isconnected():
    print("Connecting to WiFI '" + secrets.WIFI_SSID + '"')
    wifi.active(True)
    wifi.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD)
    while not wifi.isconnected():
        pass
예제 #20
0
        data = self.i2c.readfrom_mem(self.addr, 0, 2)
        return 0.01 * 2**(data[0] >> 4) * ((data[0] & 0x0f) << 8 | data[1])


from machine import Pin, Signal
import utime
import machine, SystemLink

i2c = machine.I2C('X')
hdc = HDC2080(i2c)
opt = OPT3001(i2c)
led_b = Signal('X4', Pin.OUT, value=0, invert=True)

fred2 = SystemLink.SystemLink('fred2', 'STRING')
fred2.connect()

while True:
    hdc.measure()
    opt.measure()
    led_b.on()
    while not hdc.is_ready():
        machine.idle()
    print(hdc.temperature(), hdc.humidity())
    while not opt.is_ready():
        machine.idle()
    print(opt.lux())
    if fred2.status():
        fred2.put(str(hdc.temperature()))
    led_b.off()
    utime.sleep(1)
예제 #21
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
from machine import Signal, Pin, ADC
from time import sleep

ledPin2 = machine.Pin(2, machine.Pin.OUT)
Led2 = Signal(ledPin2, invert=True)

adc = ADC(0)

val = 0

while True:
    val = adc.read()
    print(val)
    if val < 100:
        Led2.on()
    else:
        Led2.off()
    sleep(0.25)
예제 #23
0
파일: main.py 프로젝트: palmtoy/Exercise
def main():
    gc.collect()

    ledLight = Signal(Pin(2, Pin.OUT), invert=False)  # GPIO2 ( D2 )
    sleep(0.1)
    ledLight.on()
    dcMotorA = DCMotor(4, 5)  # GPIO4 ( D4 ), GPIO5 ( D5 )
    sleep(0.1)
    dcMotorA.stop()
    servoB = CServo(15)  # GPIO15 ( D15 )

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 80))
    sock.listen(5)
    while True:
        try:
            if gc.mem_free() < G_GC_THRESHOLD:
                gc.collect()
            conn, addr = sock.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)
            car_direction = request.find('/?car_direction')
            turn_left = request.find('/?turn_left')
            car_forward = request.find('/?car_forward')
            turn_right = request.find('/?turn_right')
            speed_up = request.find('/?speed_up')
            car_stop = request.find('/?car_stop')
            slow_down = request.find('/?slow_down')
            car_backward = request.find('/?car_backward')
            if car_direction == G_CMD_IDX:
                endIdx = request.find(' HTTP/')
                subReq = request[G_CMD_IDX:endIdx]
                startIdx = subReq.find('=') + 1
                virtualAngle = int(subReq[startIdx:])
                print('cmd: car_direction, virtualAngle =', virtualAngle)
                ledLight.on()
                servoB.carDirection(virtualAngle)
            elif turn_left == G_CMD_IDX:
                print('cmd: turn_left')
                ledLight.on()
                servoB.turnLeft()
            elif car_forward == G_CMD_IDX:
                print('cmd: car_forward')
                ledLight.on()
                dcMotorA.forward(G_FORWARD_SPEED)
            elif turn_right == G_CMD_IDX:
                print('cmd: turn_right')
                ledLight.on()
                servoB.turnRight()
            elif speed_up == G_CMD_IDX:
                print('cmd: speed_up')
                ledLight.on()
                dcMotorA.speedUp()
            elif car_stop == G_CMD_IDX:
                print('cmd: car_stop')
                ledLight.off()
                dcMotorA.stop()
            elif slow_down == G_CMD_IDX:
                print('cmd: slow_down')
                ledLight.on()
                dcMotorA.slowDown()
            elif car_backward == G_CMD_IDX:
                print('cmd: car_backward')
                ledLight.on()
                dcMotorA.backward(G_BACKWARD_SPEED)
            resHtml = getWebPage()
            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)
예제 #24
0
    # The duty cycle & frequency have been emperically tuned
    # here to maximize the HV charge. This results in around
    # 250V on the HV capacitor. Setting duty cycle higher generally
    # just causes more current flow/waste in the HV transformer.
    hvpwm.freq(2500)
    hvpwm.duty_u16(800)  #range 0 to 65535, 800 = 1.22% duty cycle


#hvpwm pin drives the HV transformer
pwm_off()

# Status LEDs:
ledHv = Signal(Pin(6, Pin.OUT))  #HV 'on' LED (based on feedback)
ledArm = Signal(Pin(27, Pin.OUT))  #Arm 'on' LED
ledStatus = Signal(Pin(7, Pin.OUT))  #Simple status LED
ledStatus.on()

# Due to original PCB being single-layer milled board, these buttons
# used different "active" status to simplify the board routing. This
# was left the same for final PCB.
buttonArm = Signal(Pin(28, Pin.IN, pull=Pin.PULL_DOWN))
buttonPulse = Signal(Pin(11, Pin.IN, pull=Pin.PULL_UP), invert=True)

# The 'charged' input routes to two pins, one of them is an ADC pin.
# Technically could just use the ADC pin as digital input, but again
# for 'technical debt' reasons left as two pins.
charged = Signal(Pin(18, Pin.IN), invert=True)

# The 'pulseOut' pin drives the gate of the switch via transformer.
pulse_out_pin = 14
pulseOut = Pin(pulse_out_pin, Pin.OUT)