diff options
Diffstat (limited to 'examples')
28 files changed, 258 insertions, 177 deletions
diff --git a/examples/SDdatalogger/boot.py b/examples/SDdatalogger/boot.py index 4ac94bbaa4..bc42cef2e9 100644 --- a/examples/SDdatalogger/boot.py +++ b/examples/SDdatalogger/boot.py @@ -8,18 +8,18 @@ import pyb -pyb.LED(3).on() # indicate we are waiting for switch press -pyb.delay(2000) # wait for user to maybe press the switch -switch_value = pyb.Switch()() # sample the switch at end of delay -pyb.LED(3).off() # indicate that we finished waiting for the switch +pyb.LED(3).on() # indicate we are waiting for switch press +pyb.delay(2000) # wait for user to maybe press the switch +switch_value = pyb.Switch()() # sample the switch at end of delay +pyb.LED(3).off() # indicate that we finished waiting for the switch -pyb.LED(4).on() # indicate that we are selecting the mode +pyb.LED(4).on() # indicate that we are selecting the mode if switch_value: - pyb.usb_mode('VCP+MSC') - pyb.main('cardreader.py') # if switch was pressed, run this + pyb.usb_mode("VCP+MSC") + pyb.main("cardreader.py") # if switch was pressed, run this else: - pyb.usb_mode('VCP+HID') - pyb.main('datalogger.py') # if switch wasn't pressed, run this + pyb.usb_mode("VCP+HID") + pyb.main("datalogger.py") # if switch wasn't pressed, run this -pyb.LED(4).off() # indicate that we finished selecting the mode +pyb.LED(4).off() # indicate that we finished selecting the mode diff --git a/examples/SDdatalogger/datalogger.py b/examples/SDdatalogger/datalogger.py index 0690c20bb9..3d6f98b389 100644 --- a/examples/SDdatalogger/datalogger.py +++ b/examples/SDdatalogger/datalogger.py @@ -17,17 +17,17 @@ while True: # start if switch is pressed if switch(): - pyb.delay(200) # delay avoids detection of multiple presses - blue.on() # blue LED indicates file open - log = open('/sd/log.csv', 'w') # open file on SD (SD: '/sd/', flash: '/flash/) + pyb.delay(200) # delay avoids detection of multiple presses + blue.on() # blue LED indicates file open + log = open("/sd/log.csv", "w") # open file on SD (SD: '/sd/', flash: '/flash/) # until switch is pressed again while not switch(): - t = pyb.millis() # get time - x, y, z = accel.filtered_xyz() # get acceleration data - log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file + t = pyb.millis() # get time + x, y, z = accel.filtered_xyz() # get acceleration data + log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file # end after switch is pressed again - log.close() # close file - blue.off() # blue LED indicates file closed - pyb.delay(200) # delay avoids detection of multiple presses + log.close() # close file + blue.off() # blue LED indicates file closed + pyb.delay(200) # delay avoids detection of multiple presses diff --git a/examples/accel_i2c.py b/examples/accel_i2c.py index d635e3ccc1..7229c22899 100644 --- a/examples/accel_i2c.py +++ b/examples/accel_i2c.py @@ -17,10 +17,10 @@ accel_pwr.value(1) i2c = I2C(1, baudrate=100000) addrs = i2c.scan() print("Scanning devices:", [hex(x) for x in addrs]) -if 0x4c not in addrs: +if 0x4C not in addrs: print("Accelerometer is not detected") -ACCEL_ADDR = 0x4c +ACCEL_ADDR = 0x4C ACCEL_AXIS_X_REG = 0 ACCEL_MODE_REG = 7 diff --git a/examples/accellog.py b/examples/accellog.py index a2fbe1437d..e8b5d101da 100644 --- a/examples/accellog.py +++ b/examples/accellog.py @@ -2,19 +2,19 @@ import pyb -accel = pyb.Accel() # create object of accelerometer -blue = pyb.LED(4) # create object of blue LED +accel = pyb.Accel() # create object of accelerometer +blue = pyb.LED(4) # create object of blue LED # open file to write data - /sd/ is the SD-card, /flash/ the internal memory -log = open('/sd/log.csv', 'w') +log = open("/sd/log.csv", "w") -blue.on() # turn on blue LED +blue.on() # turn on blue LED # do 100 times (if the board is connected via USB, you can't write longer because the PC tries to open the filesystem which messes up your file.) for i in range(100): - t = pyb.millis() # get time since reset - x, y, z = accel.filtered_xyz() # get acceleration data - log.write('{},{},{},{}\n'.format(t,x,y,z)) # write data to file + t = pyb.millis() # get time since reset + x, y, z = accel.filtered_xyz() # get acceleration data + log.write("{},{},{},{}\n".format(t, x, y, z)) # write data to file -log.close() # close file -blue.off() # turn off LED +log.close() # close file +blue.off() # turn off LED diff --git a/examples/asmled.py b/examples/asmled.py index 917d9ba03c..09a06c184a 100644 --- a/examples/asmled.py +++ b/examples/asmled.py @@ -2,8 +2,8 @@ # this version is overly verbose and uses word stores @micropython.asm_thumb def flash_led(r0): - movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xffff) - movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7fff) + movw(r1, (stm.GPIOA + stm.GPIO_BSRRL) & 0xFFFF) + movt(r1, ((stm.GPIOA + stm.GPIO_BSRRL) >> 16) & 0x7FFF) movw(r2, 1 << 13) movt(r2, 0) movw(r3, 0) @@ -17,8 +17,8 @@ def flash_led(r0): str(r2, [r1, 0]) # delay for a bit - movw(r4, 5599900 & 0xffff) - movt(r4, (5599900 >> 16) & 0xffff) + movw(r4, 5599900 & 0xFFFF) + movt(r4, (5599900 >> 16) & 0xFFFF) label(delay_on) sub(r4, r4, 1) cmp(r4, 0) @@ -28,8 +28,8 @@ def flash_led(r0): str(r3, [r1, 0]) # delay for a bit - movw(r4, 5599900 & 0xffff) - movt(r4, (5599900 >> 16) & 0xffff) + movw(r4, 5599900 & 0xFFFF) + movt(r4, (5599900 >> 16) & 0xFFFF) label(delay_off) sub(r4, r4, 1) cmp(r4, 0) @@ -41,6 +41,7 @@ def flash_led(r0): cmp(r0, 0) bgt(loop1) + # flash LED #2 using inline assembler # this version uses half-word sortes, and the convenience assembler operation 'movwt' @micropython.asm_thumb @@ -81,5 +82,6 @@ def flash_led_v2(r0): cmp(r0, 0) bgt(loop1) + flash_led(5) flash_led_v2(5) diff --git a/examples/asmsum.py b/examples/asmsum.py index 07e71c7384..f465b25afd 100644 --- a/examples/asmsum.py +++ b/examples/asmsum.py @@ -22,6 +22,7 @@ def asm_sum_words(r0, r1): mov(r0, r2) + @micropython.asm_thumb def asm_sum_bytes(r0, r1): @@ -46,12 +47,13 @@ def asm_sum_bytes(r0, r1): mov(r0, r2) + import array -b = array.array('l', (100, 200, 300, 400)) +b = array.array("l", (100, 200, 300, 400)) n = asm_sum_words(len(b), b) print(b, n) -b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80)) +b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80)) n = asm_sum_bytes(len(b), b) print(b, n) diff --git a/examples/bluetooth/ble_advertising.py b/examples/bluetooth/ble_advertising.py index 3a06beb740..3fb1281f63 100644 --- a/examples/bluetooth/ble_advertising.py +++ b/examples/bluetooth/ble_advertising.py @@ -26,9 +26,12 @@ def advertising_payload(limited_disc=False, br_edr=False, name=None, services=No def _append(adv_type, value): nonlocal payload - payload += struct.pack('BB', len(value) + 1, adv_type) + value + payload += struct.pack("BB", len(value) + 1, adv_type) + value - _append(_ADV_TYPE_FLAGS, struct.pack('B', (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04))) + _append( + _ADV_TYPE_FLAGS, + struct.pack("B", (0x01 if limited_disc else 0x02) + (0x00 if br_edr else 0x04)), + ) if name: _append(_ADV_TYPE_NAME, name) @@ -44,7 +47,7 @@ def advertising_payload(limited_disc=False, br_edr=False, name=None, services=No _append(_ADV_TYPE_UUID128_COMPLETE, b) # See org.bluetooth.characteristic.gap.appearance.xml - _append(_ADV_TYPE_APPEARANCE, struct.pack('<h', appearance)) + _append(_ADV_TYPE_APPEARANCE, struct.pack("<h", appearance)) return payload @@ -54,32 +57,36 @@ def decode_field(payload, adv_type): result = [] while i + 1 < len(payload): if payload[i + 1] == adv_type: - result.append(payload[i + 2:i + payload[i] + 1]) + result.append(payload[i + 2 : i + payload[i] + 1]) i += 1 + payload[i] return result def decode_name(payload): n = decode_field(payload, _ADV_TYPE_NAME) - return str(n[0], 'utf-8') if n else '' + return str(n[0], "utf-8") if n else "" def decode_services(payload): services = [] for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE): - services.append(bluetooth.UUID(struct.unpack('<h', u)[0])) + services.append(bluetooth.UUID(struct.unpack("<h", u)[0])) for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE): - services.append(bluetooth.UUID(struct.unpack('<d', u)[0])) + services.append(bluetooth.UUID(struct.unpack("<d", u)[0])) for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE): services.append(bluetooth.UUID(u)) return services def demo(): - payload = advertising_payload(name='micropython', services=[bluetooth.UUID(0x181A), bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')]) + payload = advertising_payload( + name="micropython", + services=[bluetooth.UUID(0x181A), bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")], + ) print(payload) print(decode_name(payload)) print(decode_services(payload)) -if __name__ == '__main__': + +if __name__ == "__main__": demo() diff --git a/examples/bluetooth/ble_temperature.py b/examples/bluetooth/ble_temperature.py index d901e2af1c..01d2f7441f 100644 --- a/examples/bluetooth/ble_temperature.py +++ b/examples/bluetooth/ble_temperature.py @@ -10,26 +10,36 @@ import time from ble_advertising import advertising_payload from micropython import const -_IRQ_CENTRAL_CONNECT = const(1 << 0) -_IRQ_CENTRAL_DISCONNECT = const(1 << 1) + +_IRQ_CENTRAL_CONNECT = const(1 << 0) +_IRQ_CENTRAL_DISCONNECT = const(1 << 1) # org.bluetooth.service.environmental_sensing _ENV_SENSE_UUID = bluetooth.UUID(0x181A) # org.bluetooth.characteristic.temperature -_TEMP_CHAR = (bluetooth.UUID(0x2A6E), bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,) -_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),) +_TEMP_CHAR = ( + bluetooth.UUID(0x2A6E), + bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY, +) +_ENV_SENSE_SERVICE = ( + _ENV_SENSE_UUID, + (_TEMP_CHAR,), +) # org.bluetooth.characteristic.gap.appearance.xml _ADV_APPEARANCE_GENERIC_THERMOMETER = const(768) + class BLETemperature: - def __init__(self, ble, name='mpy-temp'): + def __init__(self, ble, name="mpy-temp"): self._ble = ble self._ble.active(True) self._ble.irq(handler=self._irq) ((self._handle,),) = self._ble.gatts_register_services((_ENV_SENSE_SERVICE,)) self._connections = set() - self._payload = advertising_payload(name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER) + self._payload = advertising_payload( + name=name, services=[_ENV_SENSE_UUID], appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER + ) self._advertise() def _irq(self, event, data): @@ -46,7 +56,7 @@ class BLETemperature: def set_temperature(self, temp_deg_c, notify=False): # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius. # Write the local value, ready for a central to read. - self._ble.gatts_write(self._handle, struct.pack('<h', int(temp_deg_c * 100))) + self._ble.gatts_write(self._handle, struct.pack("<h", int(temp_deg_c * 100))) if notify: for conn_handle in self._connections: # Notify connected centrals to issue a read. @@ -72,5 +82,5 @@ def demo(): time.sleep_ms(1000) -if __name__ == '__main__': +if __name__ == "__main__": demo() diff --git a/examples/bluetooth/ble_temperature_central.py b/examples/bluetooth/ble_temperature_central.py index 5c23a06453..14ea694a9e 100644 --- a/examples/bluetooth/ble_temperature_central.py +++ b/examples/bluetooth/ble_temperature_central.py @@ -9,33 +9,41 @@ import micropython from ble_advertising import decode_services, decode_name from micropython import const -_IRQ_CENTRAL_CONNECT = const(1 << 0) -_IRQ_CENTRAL_DISCONNECT = const(1 << 1) -_IRQ_GATTS_WRITE = const(1 << 2) -_IRQ_GATTS_READ_REQUEST = const(1 << 3) -_IRQ_SCAN_RESULT = const(1 << 4) -_IRQ_SCAN_COMPLETE = const(1 << 5) -_IRQ_PERIPHERAL_CONNECT = const(1 << 6) -_IRQ_PERIPHERAL_DISCONNECT = const(1 << 7) -_IRQ_GATTC_SERVICE_RESULT = const(1 << 8) -_IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9) -_IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10) -_IRQ_GATTC_READ_RESULT = const(1 << 11) -_IRQ_GATTC_WRITE_STATUS = const(1 << 12) -_IRQ_GATTC_NOTIFY = const(1 << 13) -_IRQ_GATTC_INDICATE = const(1 << 14) -_IRQ_ALL = const(0xffff) + +_IRQ_CENTRAL_CONNECT = const(1 << 0) +_IRQ_CENTRAL_DISCONNECT = const(1 << 1) +_IRQ_GATTS_WRITE = const(1 << 2) +_IRQ_GATTS_READ_REQUEST = const(1 << 3) +_IRQ_SCAN_RESULT = const(1 << 4) +_IRQ_SCAN_COMPLETE = const(1 << 5) +_IRQ_PERIPHERAL_CONNECT = const(1 << 6) +_IRQ_PERIPHERAL_DISCONNECT = const(1 << 7) +_IRQ_GATTC_SERVICE_RESULT = const(1 << 8) +_IRQ_GATTC_CHARACTERISTIC_RESULT = const(1 << 9) +_IRQ_GATTC_DESCRIPTOR_RESULT = const(1 << 10) +_IRQ_GATTC_READ_RESULT = const(1 << 11) +_IRQ_GATTC_WRITE_STATUS = const(1 << 12) +_IRQ_GATTC_NOTIFY = const(1 << 13) +_IRQ_GATTC_INDICATE = const(1 << 14) +_IRQ_ALL = const(0xFFFF) # org.bluetooth.service.environmental_sensing _ENV_SENSE_UUID = bluetooth.UUID(0x181A) # org.bluetooth.characteristic.temperature _TEMP_UUID = bluetooth.UUID(0x2A6E) -_TEMP_CHAR = (_TEMP_UUID, bluetooth.FLAG_READ|bluetooth.FLAG_NOTIFY,) -_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR,),) +_TEMP_CHAR = ( + _TEMP_UUID, + bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY, +) +_ENV_SENSE_SERVICE = ( + _ENV_SENSE_UUID, + (_TEMP_CHAR,), +) # org.bluetooth.characteristic.gap.appearance.xml _ADV_APPEARANCE_GENERIC_THERMOMETER = const(768) + class BLETemperatureCentral: def __init__(self, ble): self._ble = ble @@ -72,8 +80,10 @@ class BLETemperatureCentral: if connectable and _ENV_SENSE_UUID in decode_services(adv_data): # Found a potential device, remember it and stop scanning. self._addr_type = addr_type - self._addr = bytes(addr) # Note: addr buffer is owned by caller so need to copy it. - self._name = decode_name(adv_data) or '?' + self._addr = bytes( + addr + ) # Note: addr buffer is owned by caller so need to copy it. + self._name = decode_name(adv_data) or "?" self._ble.gap_scan(None) elif event == _IRQ_SCAN_COMPLETE: @@ -104,7 +114,9 @@ class BLETemperatureCentral: # Connected device returned a service. conn_handle, start_handle, end_handle, uuid = data if conn_handle == self._conn_handle and uuid == _ENV_SENSE_UUID: - self._ble.gattc_discover_characteristics(self._conn_handle, start_handle, end_handle) + self._ble.gattc_discover_characteristics( + self._conn_handle, start_handle, end_handle + ) elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: # Connected device returned a characteristic. @@ -132,7 +144,6 @@ class BLETemperatureCentral: if self._notify_callback: self._notify_callback(self._value) - # Returns true if we've successfully connected and discovered characteristics. def is_connected(self): return self._conn_handle is not None and self._value_handle is not None @@ -174,7 +185,7 @@ class BLETemperatureCentral: def _update_value(self, data): # Data is sint16 in degrees Celsius with a resolution of 0.01 degrees Celsius. - self._value = struct.unpack('<h', data)[0] / 100 + self._value = struct.unpack("<h", data)[0] / 100 return self._value def value(self): @@ -189,12 +200,12 @@ def demo(): def on_scan(addr_type, addr, name): if addr_type is not None: - print('Found sensor:', addr_type, addr, name) + print("Found sensor:", addr_type, addr, name) central.connect() else: nonlocal not_found not_found = True - print('No sensor found.') + print("No sensor found.") central.scan(callback=on_scan) @@ -204,7 +215,7 @@ def demo(): if not_found: return - print('Connected') + print("Connected") # Explicitly issue reads, using "print" as the callback. while central.is_connected(): @@ -216,7 +227,8 @@ def demo(): # print(central.value()) # time.sleep_ms(2000) - print('Disconnected') + print("Disconnected") + -if __name__ == '__main__': +if __name__ == "__main__": demo() diff --git a/examples/bluetooth/ble_uart_peripheral.py b/examples/bluetooth/ble_uart_peripheral.py index 14f7102725..c013d96ec9 100644 --- a/examples/bluetooth/ble_uart_peripheral.py +++ b/examples/bluetooth/ble_uart_peripheral.py @@ -4,24 +4,37 @@ import bluetooth from ble_advertising import advertising_payload from micropython import const -_IRQ_CENTRAL_CONNECT = const(1 << 0) -_IRQ_CENTRAL_DISCONNECT = const(1 << 1) -_IRQ_GATTS_WRITE = const(1 << 2) -_UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E') -_UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_NOTIFY,) -_UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,) -_UART_SERVICE = (_UART_UUID, (_UART_TX, _UART_RX,),) +_IRQ_CENTRAL_CONNECT = const(1 << 0) +_IRQ_CENTRAL_DISCONNECT = const(1 << 1) +_IRQ_GATTS_WRITE = const(1 << 2) + +_UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E") +_UART_TX = ( + bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"), + bluetooth.FLAG_NOTIFY, +) +_UART_RX = ( + bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"), + bluetooth.FLAG_WRITE, +) +_UART_SERVICE = ( + _UART_UUID, + (_UART_TX, _UART_RX,), +) # org.bluetooth.characteristic.gap.appearance.xml _ADV_APPEARANCE_GENERIC_COMPUTER = const(128) + class BLEUART: - def __init__(self, ble, name='mpy-uart', rxbuf=100): + def __init__(self, ble, name="mpy-uart", rxbuf=100): self._ble = ble self._ble.active(True) self._ble.irq(handler=self._irq) - ((self._tx_handle, self._rx_handle,),) = self._ble.gatts_register_services((_UART_SERVICE,)) + ((self._tx_handle, self._rx_handle,),) = self._ble.gatts_register_services( + (_UART_SERVICE,) + ) # Increase the size of the rx buffer and enable append mode. self._ble.gatts_set_buffer(self._rx_handle, rxbuf, True) self._connections = set() @@ -82,7 +95,7 @@ def demo(): uart = BLEUART(ble) def on_rx(): - print('rx: ', uart.read().decode().strip()) + print("rx: ", uart.read().decode().strip()) uart.irq(handler=on_rx) nums = [4, 8, 15, 16, 23, 42] @@ -90,7 +103,7 @@ def demo(): try: while True: - uart.write(str(nums[i]) + '\n') + uart.write(str(nums[i]) + "\n") i = (i + 1) % len(nums) time.sleep_ms(1000) except KeyboardInterrupt: @@ -99,5 +112,5 @@ def demo(): uart.close() -if __name__ == '__main__': +if __name__ == "__main__": demo() diff --git a/examples/bluetooth/ble_uart_repl.py b/examples/bluetooth/ble_uart_repl.py index 430a571a69..9e8a38ff4b 100644 --- a/examples/bluetooth/ble_uart_repl.py +++ b/examples/bluetooth/ble_uart_repl.py @@ -15,7 +15,7 @@ _MP_STREAM_POLL = const(3) _MP_STREAM_POLL_RD = const(0x0001) # TODO: Remove this when STM32 gets machine.Timer. -if hasattr(machine, 'Timer'): +if hasattr(machine, "Timer"): _timer = machine.Timer(-1) else: _timer = None @@ -24,11 +24,13 @@ else: def schedule_in(handler, delay_ms): def _wrap(_arg): handler() + if _timer: _timer.init(mode=machine.Timer.ONE_SHOT, period=delay_ms, callback=_wrap) else: micropython.schedule(_wrap, None) + # Simple buffering stream to support the dupterm requirements. class BLEUARTStream(io.IOBase): def __init__(self, uart): @@ -38,7 +40,7 @@ class BLEUARTStream(io.IOBase): def _on_rx(self): # Needed for ESP32. - if hasattr(os, 'dupterm_notify'): + if hasattr(os, "dupterm_notify"): os.dupterm_notify(None) def read(self, sz=None): @@ -74,7 +76,7 @@ class BLEUARTStream(io.IOBase): def start(): ble = bluetooth.BLE() - uart = BLEUART(ble, name='mpy-repl') + uart = BLEUART(ble, name="mpy-repl") stream = BLEUARTStream(uart) os.dupterm(stream) diff --git a/examples/conwaylife.py b/examples/conwaylife.py index 323f42e850..44c1a507be 100644 --- a/examples/conwaylife.py +++ b/examples/conwaylife.py @@ -1,46 +1,51 @@ -#import essential libraries +# import essential libraries import pyb -lcd = pyb.LCD('x') +lcd = pyb.LCD("x") lcd.light(1) # do 1 iteration of Conway's Game of Life def conway_step(): - for x in range(128): # loop over x coordinates - for y in range(32): # loop over y coordinates + for x in range(128): # loop over x coordinates + for y in range(32): # loop over y coordinates # count number of neighbours - num_neighbours = (lcd.get(x - 1, y - 1) + - lcd.get(x, y - 1) + - lcd.get(x + 1, y - 1) + - lcd.get(x - 1, y) + - lcd.get(x + 1, y) + - lcd.get(x + 1, y + 1) + - lcd.get(x, y + 1) + - lcd.get(x - 1, y + 1)) + num_neighbours = ( + lcd.get(x - 1, y - 1) + + lcd.get(x, y - 1) + + lcd.get(x + 1, y - 1) + + lcd.get(x - 1, y) + + lcd.get(x + 1, y) + + lcd.get(x + 1, y + 1) + + lcd.get(x, y + 1) + + lcd.get(x - 1, y + 1) + ) # check if the centre cell is alive or not self = lcd.get(x, y) # apply the rules of life if self and not (2 <= num_neighbours <= 3): - lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies + lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies elif not self and num_neighbours == 3: - lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born + lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born + # randomise the start def conway_rand(): - lcd.fill(0) # clear the LCD - for x in range(128): # loop over x coordinates - for y in range(32): # loop over y coordinates - lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly + lcd.fill(0) # clear the LCD + for x in range(128): # loop over x coordinates + for y in range(32): # loop over y coordinates + lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly + # loop for a certain number of frames, doing iterations of Conway's Game of Life def conway_go(num_frames): for i in range(num_frames): - conway_step() # do 1 iteration - lcd.show() # update the LCD + conway_step() # do 1 iteration + lcd.show() # update the LCD pyb.delay(50) + # testing conway_rand() conway_go(100) diff --git a/examples/hwapi/button_reaction.py b/examples/hwapi/button_reaction.py index b72e813e4c..e5a139a575 100644 --- a/examples/hwapi/button_reaction.py +++ b/examples/hwapi/button_reaction.py @@ -4,14 +4,16 @@ from hwconfig import LED, BUTTON # machine.time_pulse_us() function demo -print("""\ +print( + """\ Let's play an interesting game: You click button as fast as you can, and I tell you how slow you are. Ready? Cliiiiick! -""") +""" +) while 1: - delay = machine.time_pulse_us(BUTTON, 1, 10*1000*1000) + delay = machine.time_pulse_us(BUTTON, 1, 10 * 1000 * 1000) if delay < 0: print("Well, you're *really* slow") else: diff --git a/examples/hwapi/hwconfig_console.py b/examples/hwapi/hwconfig_console.py index bbcc0e816e..1b49d52379 100644 --- a/examples/hwapi/hwconfig_console.py +++ b/examples/hwapi/hwconfig_console.py @@ -1,7 +1,6 @@ # This is hwconfig for "emulation" for cases when there's no real hardware. # It just prints information to console. class LEDClass: - def __init__(self, id): self.id = "LED(%d):" % id diff --git a/examples/hwapi/hwconfig_pyboard.py b/examples/hwapi/hwconfig_pyboard.py index fb260033e5..a74a1ae151 100644 --- a/examples/hwapi/hwconfig_pyboard.py +++ b/examples/hwapi/hwconfig_pyboard.py @@ -1,13 +1,13 @@ from machine import Pin, Signal # Red LED on pin LED_RED also kown as A13 -LED = Signal('LED_RED', Pin.OUT) +LED = Signal("LED_RED", Pin.OUT) # Green LED on pin LED_GREEN also known as A14 -LED2 = Signal('LED_GREEN', Pin.OUT) +LED2 = Signal("LED_GREEN", Pin.OUT) # Yellow LED on pin LED_YELLOW also known as A15 -LED3 = Signal('LED_YELLOW', Pin.OUT) +LED3 = Signal("LED_YELLOW", Pin.OUT) # Blue LED on pin LED_BLUE also known as B4 -LED4 = Signal('LED_BLUE', Pin.OUT) +LED4 = Signal("LED_BLUE", Pin.OUT) diff --git a/examples/ledangle.py b/examples/ledangle.py index 8c8d9e99d9..3d47e8f72d 100644 --- a/examples/ledangle.py +++ b/examples/ledangle.py @@ -1,5 +1,6 @@ import pyb + def led_angle(seconds_to_run_for): # make LED objects l1 = pyb.LED(1) diff --git a/examples/mandel.py b/examples/mandel.py index bbb8086470..2f3d7da235 100644 --- a/examples/mandel.py +++ b/examples/mandel.py @@ -3,13 +3,14 @@ try: except: pass + def mandelbrot(): # returns True if c, complex, is in the Mandelbrot set - #@micropython.native + # @micropython.native def in_set(c): z = 0 for i in range(40): - z = z*z + c + z = z * z + c if abs(z) > 60: return False return True @@ -21,7 +22,9 @@ def mandelbrot(): lcd.set(u, v) lcd.show() + # PC testing import lcd + lcd = lcd.LCD(128, 32) mandelbrot() diff --git a/examples/micropython.py b/examples/micropython.py index f91da94f41..5b87ba192e 100644 --- a/examples/micropython.py +++ b/examples/micropython.py @@ -2,7 +2,9 @@ # Dummy function decorators + def nodecor(x): return x + bytecode = native = viper = nodecor diff --git a/examples/natmod/features2/test.py b/examples/natmod/features2/test.py index 2e9db00f44..5ac80120d7 100644 --- a/examples/natmod/features2/test.py +++ b/examples/natmod/features2/test.py @@ -2,20 +2,22 @@ import array + def isclose(a, b): return abs(a - b) < 1e-3 + def test(): tests = [ isclose(add(0.1, 0.2), 0.3), isclose(add_f(0.1, 0.2), 0.3), ] - ar = array.array('f', [1, 2, 3.5]) + ar = array.array("f", [1, 2, 3.5]) productf(ar) tests.append(isclose(ar[0], 7)) - if 'add_d' in globals(): + if "add_d" in globals(): tests.append(isclose(add_d(0.1, 0.2), 0.3)) print(tests) @@ -23,4 +25,5 @@ def test(): if not all(tests): raise SystemExit(1) + test() diff --git a/examples/network/http_server.py b/examples/network/http_server.py index e3a66e8283..76be3ab817 100644 --- a/examples/network/http_server.py +++ b/examples/network/http_server.py @@ -10,6 +10,7 @@ HTTP/1.0 200 OK Hello #%d from MicroPython! """ + def main(micropython_optimize=False): s = socket.socket() diff --git a/examples/network/http_server_simplistic.py b/examples/network/http_server_simplistic.py index 67ecb1ad7a..71949419e6 100644 --- a/examples/network/http_server_simplistic.py +++ b/examples/network/http_server_simplistic.py @@ -12,6 +12,7 @@ HTTP/1.0 200 OK Hello #%d from MicroPython! """ + def main(): s = socket.socket() ai = socket.getaddrinfo("0.0.0.0", 8080) diff --git a/examples/network/http_server_simplistic_commented.py b/examples/network/http_server_simplistic_commented.py index b58e9eeb60..da042c6c8a 100644 --- a/examples/network/http_server_simplistic_commented.py +++ b/examples/network/http_server_simplistic_commented.py @@ -20,6 +20,7 @@ HTTP/1.0 200 OK Hello #%d from MicroPython! """ + def main(): s = socket.socket() diff --git a/examples/network/http_server_ssl.py b/examples/network/http_server_ssl.py index 47d83bf247..1116c71e99 100644 --- a/examples/network/http_server_ssl.py +++ b/examples/network/http_server_ssl.py @@ -1,4 +1,5 @@ import ubinascii as binascii + try: import usocket as socket except: @@ -9,30 +10,32 @@ import ussl as ssl # This self-signed key/cert pair is randomly generated and to be used for # testing/demonstration only. You should always generate your own key/cert. key = binascii.unhexlify( - b'3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef' - b'610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f' - b'872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0' - b'd05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d' - b'd9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86' - b'8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483' - b'02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102' - b'2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044' - b'6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f') + b"3082013b020100024100cc20643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef" + b"610a6a6ba14abb891745cd18a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f" + b"872d0203010001024100bb17a54aeb3dd7ae4edec05e775ca9632cf02d29c2a089b563b0" + b"d05cdf95aeca507de674553f28b4eadaca82d5549a86058f9996b07768686a5b02cb240d" + b"d9f1022100f4a63f5549e817547dca97b5c658038e8593cb78c5aba3c4642cc4cd031d86" + b"8f022100d598d870ffe4a34df8de57047a50b97b71f4d23e323f527837c9edae88c79483" + b"02210098560c89a70385c36eb07fd7083235c4c1184e525d838aedf7128958bedfdbb102" + b"2051c0dab7057a8176ca966f3feb81123d4974a733df0f958525f547dfd1c271f9022044" + b"6c2cafad455a671a8cf398e642e1be3b18a3d3aec2e67a9478f83c964c4f1f" +) cert = binascii.unhexlify( - b'308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355' - b'0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504' - b'070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106' - b'0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61' - b'6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075' - b'310b30090603550406130258583114301206035504080c0b54686550726f76696e636531' - b'10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958' - b'595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468' - b'65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20' - b'643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18' - b'a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a' - b'864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8' - b'e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef' - b'979b57f0b3') + b"308201d53082017f020203e8300d06092a864886f70d01010505003075310b3009060355" + b"0406130258583114301206035504080c0b54686550726f76696e63653110300e06035504" + b"070c075468654369747931133011060355040a0c0a436f6d70616e7958595a3113301106" + b"0355040b0c0a436f6d70616e7958595a3114301206035504030c0b546865486f73744e61" + b"6d65301e170d3139313231383033333935355a170d3239313231353033333935355a3075" + b"310b30090603550406130258583114301206035504080c0b54686550726f76696e636531" + b"10300e06035504070c075468654369747931133011060355040a0c0a436f6d70616e7958" + b"595a31133011060355040b0c0a436f6d70616e7958595a3114301206035504030c0b5468" + b"65486f73744e616d65305c300d06092a864886f70d0101010500034b003048024100cc20" + b"643fd3d9c21a0acba4f48f61aadd675f52175a9dcf07fbef610a6a6ba14abb891745cd18" + b"a1d4c056580d8ff1a639460f867013c8391cdc9f2e573b0f872d0203010001300d06092a" + b"864886f70d0101050500034100b0513fe2829e9ecbe55b6dd14c0ede7502bde5d46153c8" + b"e960ae3ebc247371b525caeb41bbcf34686015a44c50d226e66aef0a97a63874ca5944ef" + b"979b57f0b3" +) CONTENT = b"""\ @@ -41,6 +44,7 @@ HTTP/1.0 200 OK Hello #%d from MicroPython! """ + def main(use_stream=True): s = socket.socket() diff --git a/examples/pins.py b/examples/pins.py index aafdb48133..3a8472e8a6 100644 --- a/examples/pins.py +++ b/examples/pins.py @@ -4,6 +4,7 @@ import pyb import pins_af + def af(): max_name_width = 0 max_af_width = 0 @@ -13,21 +14,22 @@ def af(): max_af_width = max(max_af_width, len(af_entry[1])) for pin_entry in pins_af.PINS_AF: pin_name = pin_entry[0] - print('%-*s ' % (max_name_width, pin_name), end='') + print("%-*s " % (max_name_width, pin_name), end="") for af_entry in pin_entry[1:]: - print('%2d: %-*s ' % (af_entry[0], max_af_width, af_entry[1]), end='') - print('') + print("%2d: %-*s " % (af_entry[0], max_af_width, af_entry[1]), end="") + print("") + def pins(): - mode_str = { pyb.Pin.IN : 'IN', - pyb.Pin.OUT_PP : 'OUT_PP', - pyb.Pin.OUT_OD : 'OUT_OD', - pyb.Pin.AF_PP : 'AF_PP', - pyb.Pin.AF_OD : 'AF_OD', - pyb.Pin.ANALOG : 'ANALOG' } - pull_str = { pyb.Pin.PULL_NONE : '', - pyb.Pin.PULL_UP : 'PULL_UP', - pyb.Pin.PULL_DOWN : 'PULL_DOWN' } + mode_str = { + pyb.Pin.IN: "IN", + pyb.Pin.OUT_PP: "OUT_PP", + pyb.Pin.OUT_OD: "OUT_OD", + pyb.Pin.AF_PP: "AF_PP", + pyb.Pin.AF_OD: "AF_OD", + pyb.Pin.ANALOG: "ANALOG", + } + pull_str = {pyb.Pin.PULL_NONE: "", pyb.Pin.PULL_UP: "PULL_UP", pyb.Pin.PULL_DOWN: "PULL_DOWN"} width = [0, 0, 0, 0] rows = [] for pin_entry in pins_af.PINS_AF: @@ -42,17 +44,17 @@ def pins(): pin_af = pin.af() for af_entry in pin_entry[1:]: if pin_af == af_entry[0]: - af_str = '%d: %s' % (pin_af, af_entry[1]) + af_str = "%d: %s" % (pin_af, af_entry[1]) break else: - af_str = '%d' % pin_af + af_str = "%d" % pin_af else: - af_str = '' + af_str = "" row.append(af_str) for col in range(len(width)): width[col] = max(width[col], len(row[col])) rows.append(row) for row in rows: for col in range(len(width)): - print('%-*s ' % (width[col], row[col]), end='') - print('') + print("%-*s " % (width[col], row[col]), end="") + print("") diff --git a/examples/pyb.py b/examples/pyb.py index b303777e5a..67620e793a 100644 --- a/examples/pyb.py +++ b/examples/pyb.py @@ -1,17 +1,22 @@ # pyboard testing functions for CPython import time + def delay(n): - #time.sleep(float(n) / 1000) + # time.sleep(float(n) / 1000) pass + rand_seed = 1 + + def rng(): global rand_seed # for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure" rand_seed = (rand_seed * 653276) % 8388593 return rand_seed + # LCD testing object for PC # uses double buffering class LCD: @@ -30,12 +35,12 @@ class LCD: self.buf1[y][x] = self.buf2[y][x] = value def show(self): - print('') # blank line to separate frames + print("") # blank line to separate frames for y in range(self.height): for x in range(self.width): self.buf1[y][x] = self.buf2[y][x] for y in range(self.height): - row = ''.join(['*' if self.buf1[y][x] else ' ' for x in range(self.width)]) + row = "".join(["*" if self.buf1[y][x] else " " for x in range(self.width)]) print(row) def get(self, x, y): diff --git a/examples/switch.py b/examples/switch.py index 0efaf22675..c099a35298 100644 --- a/examples/switch.py +++ b/examples/switch.py @@ -24,6 +24,7 @@ orange_led = pyb.LED(3) blue_led = pyb.LED(4) all_leds = (red_led, green_led, orange_led, blue_led) + def run_loop(leds=all_leds): """ Start the loop. @@ -31,15 +32,16 @@ def run_loop(leds=all_leds): :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects """ - print('Loop started.\nPress Ctrl+C to break out of the loop.') + print("Loop started.\nPress Ctrl+C to break out of the loop.") while 1: try: if switch(): [led.on() for led in leds] else: [led.off() for led in leds] - except OSError: # VCPInterrupt # Ctrl+C in interpreter mode. + except OSError: # VCPInterrupt # Ctrl+C in interpreter mode. break -if __name__ == '__main__': + +if __name__ == "__main__": run_loop() diff --git a/examples/unix/ffi_example.py b/examples/unix/ffi_example.py index 3c3c3d2396..a8f02c766e 100644 --- a/examples/unix/ffi_example.py +++ b/examples/unix/ffi_example.py @@ -24,12 +24,14 @@ print("errno value:", errno.get()) perror("perror after error") print() + def cmp(pa, pb): a = uctypes.bytearray_at(pa, 1) b = uctypes.bytearray_at(pb, 1) print("cmp:", a, b) return a[0] - b[0] + cmp_cb = ffi.callback("i", cmp, "PP") print("callback:", cmp_cb) diff --git a/examples/unix/machine_bios.py b/examples/unix/machine_bios.py index f62e4dbdb4..878f3fd8f3 100644 --- a/examples/unix/machine_bios.py +++ b/examples/unix/machine_bios.py @@ -6,4 +6,4 @@ import umachine as machine -print(hex(machine.mem16[0xc0000])) +print(hex(machine.mem16[0xC0000])) |