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(): 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)
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)
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()
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)
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
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)
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()
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)
from machine import Pin from machine import Signal from machine import ADC 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)
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)
class Node: 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 def setup_sensor(self): """ Configure the sensor to use Master Controlled Mode. Also, enable clock stretching and disable interruptions. Sensor read out is suppressed during ongoing ADC conversions. Returns ------- The number of acklowledges the sensor sent back. Should be 3. """ devices = self.i2c.scan() if not scan_address in devices: message = 'Sensor "{}" does not seem to be available!\n' sys.stderr.write(message.format(scan_address)) return write_register(self.i2c, register_config, 0b00001001) write_register(self.i2c, register_mod1, 0b10000101) def connect_wifi(self): """ Connect the node to a wireless network. The wireless network must be defined in the `config.json` file. """ self.station.active(True) config = self.config['wifi'] self.station.connect(config['ssid'], config['password']) for i in range(10): if self.station.isconnected(): break sys.stdout.write('Waiting for connection to be established...\n') time.sleep(1) else: message = 'Could not establish connection...\n' sys.stderr.write(message.format(ack)) led.on() def update_savings(self, savings): """ Update the remote servers with the new savings. """ url = 'https://api.thingspeak.com/update' url += '?api_key={key}&field1={savings}' url = url.format(key=self.config['thingspeak_key'], savings=savings) reply = urequests.get(url) return reply def send_readings(self): """ Send magnetic sensor values from a file to the server detailed on the file config.json. """ url = 'http://{host}:{port}/analyze'.format(**self.config['server']) response = urequests.post(url, data=bytearray(ring)) def callibrate(self): """ Callibrate the sensor and set the threshold for coin detection. """ total = 0 count = 10 for i in range(count): reply, (x, y, z, t), ack = read_sensor(self.i2c) total += x self.threshold = 0.8 * total / count def loop(self): """ Read and send coin values forever. """ i = 0 while True: i = i % num_measures reply, (x, y, z, t), ack = read_sensor(self.i2c) # Make sure we never try to store a value higher than the size of # the `t_array` elements position = i * 4 ring[position] = time.ticks_us() % 65536 ring[position + 1] = x ring[position + 2] = y ring[position + 3] = z if self.countdown is None: if x < self.threshold: self.countdown = 150 else: self.countdown -= 1 if self.countdown == 0: print('Sending readings...') self.send_readings() print('Readings sent!') self.countdown = None i += 1
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()
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
from machine import Pin, Timer, Signal from ktane_lib.constants import CONSTANTS # Constants: DEFAULT_FREQ = 200 SEGMENTS = [ Signal(Pin(pin, Pin.OUT), invert=True) for pin in [13, 19, 11, 10, 20, 12, 14] ] DIGITS = [Signal(Pin(pin, Pin.OUT), invert=True) for pin in [18, 16, 22, 17]] for digit in DIGITS: digit.off() DP = Signal(Pin(4, Pin.OUT), invert=True) COLON = Signal(Pin(6, Pin.OUT), invert=True) COLON.off() L3 = Signal(Pin(21, Pin.OUT), invert=True) L3.off() class SevenSegment: workspace = [10, 10, 10, 10] def __init__(self, frequency=DEFAULT_FREQ): self.timer = None self.digit = 0 self.value = self.workspace self.decimal_pos = None self.colon = False self.start(frequency)
wifi.active(True) wifi.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD) while not wifi.isconnected(): pass print('WiFi connected. Local IP: ', wifi.ifconfig()[0]) # Print free memory print("Free memory: " + str(gc.mem_free()) + " bytes.") # Set two timer update_time = ticks_ms() - QUERY_DELAY blink_time = ticks_ms() - BLINK_DELAY # Turn off all LEDs led_2.off() led_1.off() led_0.off() # 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
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)
dcMotorB.forward(forwardSpeed) elif car_backward == cmdIdx: print('cmd: car_backward') ledLight.on() dcMotorA.backward(backwardSpeed) dcMotorB.backward(backwardSpeed) elif car_left == cmdIdx: print('cmd: car_left') ledLight.on() dcMotorA.backward(backwardSpeed) dcMotorB.forward(backwardSpeed) elif car_right == cmdIdx: print('cmd: car_right ') ledLight.on() dcMotorA.forward(backwardSpeed) dcMotorB.backward(backwardSpeed) elif car_stop == cmdIdx: print('cmd: car_stop') ledLight.off() dcMotorA.stop() dcMotorB.stop() resHtml = web_page() 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.')
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)
# -*- 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()
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)
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)
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)
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 if buttonPulse.value(): if not buttonPulse_hit: buttonPulse_hit = True if buttonPulse_hit: # Flash the status light as it pulses ledStatus.off() pulseOut.high()