diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint diff --git a/.pylintrc b/.pylintrc index cd65e95..d8f0ee8 100644 --- a/.pylintrc +++ b/.pylintrc @@ -119,7 +119,8 @@ spelling-store-unknown-words=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. -notes=FIXME,XXX,TODO +# notes=FIXME,XXX,TODO +notes=FIXME,XXX [TYPECHECK] diff --git a/adafruit_lis3dh.py b/adafruit_lis3dh.py index 5cd2318..85c03fb 100755 --- a/adafruit_lis3dh.py +++ b/adafruit_lis3dh.py @@ -43,38 +43,38 @@ # Register addresses: # pylint: disable=bad-whitespace -_REG_OUTADC1_L = const(0x08) -_REG_WHOAMI = const(0x0F) -_REG_TEMPCFG = const(0x1F) -_REG_CTRL1 = const(0x20) -_REG_CTRL3 = const(0x22) -_REG_CTRL4 = const(0x23) -_REG_CTRL5 = const(0x24) -_REG_OUT_X_L = const(0x28) -_REG_INT1SRC = const(0x31) -_REG_CLICKCFG = const(0x38) -_REG_CLICKSRC = const(0x39) -_REG_CLICKTHS = const(0x3A) -_REG_TIMELIMIT = const(0x3B) +_REG_OUTADC1_L = const(0x08) +_REG_WHOAMI = const(0x0F) +_REG_TEMPCFG = const(0x1F) +_REG_CTRL1 = const(0x20) +_REG_CTRL3 = const(0x22) +_REG_CTRL4 = const(0x23) +_REG_CTRL5 = const(0x24) +_REG_OUT_X_L = const(0x28) +_REG_INT1SRC = const(0x31) +_REG_CLICKCFG = const(0x38) +_REG_CLICKSRC = const(0x39) +_REG_CLICKTHS = const(0x3A) +_REG_TIMELIMIT = const(0x3B) _REG_TIMELATENCY = const(0x3C) -_REG_TIMEWINDOW = const(0x3D) +_REG_TIMEWINDOW = const(0x3D) # Register value constants: -RANGE_16_G = const(0b11) # +/- 16g -RANGE_8_G = const(0b10) # +/- 8g -RANGE_4_G = const(0b01) # +/- 4g -RANGE_2_G = const(0b00) # +/- 2g (default value) -DATARATE_1344_HZ = const(0b1001) # 1.344 KHz -DATARATE_400_HZ = const(0b0111) # 400Hz -DATARATE_200_HZ = const(0b0110) # 200Hz -DATARATE_100_HZ = const(0b0101) # 100Hz -DATARATE_50_HZ = const(0b0100) # 50Hz -DATARATE_25_HZ = const(0b0011) # 25Hz -DATARATE_10_HZ = const(0b0010) # 10 Hz -DATARATE_1_HZ = const(0b0001) # 1 Hz -DATARATE_POWERDOWN = const(0) -DATARATE_LOWPOWER_1K6HZ = const(0b1000) -DATARATE_LOWPOWER_5KHZ = const(0b1001) +RANGE_16_G = const(0b11) # +/- 16g +RANGE_8_G = const(0b10) # +/- 8g +RANGE_4_G = const(0b01) # +/- 4g +RANGE_2_G = const(0b00) # +/- 2g (default value) +DATARATE_1344_HZ = const(0b1001) # 1.344 KHz +DATARATE_400_HZ = const(0b0111) # 400Hz +DATARATE_200_HZ = const(0b0110) # 200Hz +DATARATE_100_HZ = const(0b0101) # 100Hz +DATARATE_50_HZ = const(0b0100) # 50Hz +DATARATE_25_HZ = const(0b0011) # 25Hz +DATARATE_10_HZ = const(0b0010) # 10 Hz +DATARATE_1_HZ = const(0b0001) # 1 Hz +DATARATE_POWERDOWN = const(0) +DATARATE_LOWPOWER_1K6HZ = const(0b1000) +DATARATE_LOWPOWER_5KHZ = const(0b1001) # Other constants STANDARD_GRAVITY = 9.806 @@ -86,11 +86,12 @@ class LIS3DH: """Driver base for the LIS3DH accelerometer.""" + def __init__(self, int1=None, int2=None): # Check device ID. device_id = self._read_register_byte(_REG_WHOAMI) if device_id != 0x33: - raise RuntimeError('Failed to find LIS3DH!') + raise RuntimeError("Failed to find LIS3DH!") # Reboot self._write_register_byte(_REG_CTRL5, 0x80) time.sleep(0.01) # takes 5ms @@ -156,7 +157,7 @@ def acceleration(self): elif accel_range == RANGE_2_G: divider = 16380 - x, y, z = struct.unpack(' 3: - raise ValueError('ADC must be a value 1 to 3!') + raise ValueError("ADC must be a value 1 to 3!") - return struct.unpack(' 0 - def set_tap(self, tap, threshold, *, - time_limit=10, time_latency=20, time_window=255, click_cfg=None): + def set_tap( + self, + tap, + threshold, + *, + time_limit=10, + time_latency=20, + time_window=255, + click_cfg=None + ): """ The tap detection parameters. @@ -271,9 +281,11 @@ def set_tap(self, tap, threshold, *, :param int click_cfg: CLICK_CFG register value. """ if (tap < 0 or tap > 2) and click_cfg is None: - raise ValueError('Tap must be 0 (disabled), 1 (single tap), or 2 (double tap)!') + raise ValueError( + "Tap must be 0 (disabled), 1 (single tap), or 2 (double tap)!" + ) if threshold > 127 or threshold < 0: - raise ValueError('Threshold out of range (0-127)') + raise ValueError("Threshold out of range (0-127)") ctrl3 = self._read_register_byte(_REG_CTRL3) if tap == 0 and click_cfg is None: @@ -315,7 +327,8 @@ class LIS3DH_I2C(LIS3DH): """Driver for the LIS3DH accelerometer connected over I2C.""" def __init__(self, i2c, *, address=0x18, int1=None, int2=None): - import adafruit_bus_device.i2c_device as i2c_device + import adafruit_bus_device.i2c_device as i2c_device # pylint: disable=import-outside-toplevel + self._i2c = i2c_device.I2CDevice(i2c, address) self._buffer = bytearray(6) super().__init__(int1=int1, int2=int2) @@ -338,7 +351,8 @@ class LIS3DH_SPI(LIS3DH): """Driver for the LIS3DH accelerometer connected over SPI.""" def __init__(self, spi, cs, *, baudrate=100000, int1=None, int2=None): - import adafruit_bus_device.spi_device as spi_device + import adafruit_bus_device.spi_device as spi_device # pylint: disable=import-outside-toplevel + self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate) self._buffer = bytearray(6) super().__init__(int1=int1, int2=int2) @@ -349,12 +363,12 @@ def _read_register(self, register, length): else: self._buffer[0] = (register | 0xC0) & 0xFF # Read multiple, bit 6&7 high. with self._spi as spi: - spi.write(self._buffer, start=0, end=1) # pylint: disable=no-member - spi.readinto(self._buffer, start=0, end=length) # pylint: disable=no-member + spi.write(self._buffer, start=0, end=1) # pylint: disable=no-member + spi.readinto(self._buffer, start=0, end=length) # pylint: disable=no-member return self._buffer def _write_register_byte(self, register, value): self._buffer[0] = register & 0x7F # Write, bit 7 low. self._buffer[1] = value & 0xFF with self._spi as spi: - spi.write(self._buffer, start=0, end=2) # pylint: disable=no-member + spi.write(self._buffer, start=0, end=2) # pylint: disable=no-member diff --git a/docs/conf.py b/docs/conf.py index e50d147..0421f04 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,9 +11,9 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.viewcode', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.viewcode", ] # Uncomment the below if you use native CircuitPython modules such as @@ -20,29 +21,36 @@ # autodoc module docs will fail to generate with a warning. # autodoc_mock_imports = ["digitalio", "micropython", "ucollections"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "BusDevice": ( + "https://circuitpython.readthedocs.io/projects/busdevice/en/latest/", + None, + ), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit VL53L0X Library' -copyright = u'2017 Tony DiCola' -author = u'Tony DiCola' +project = u"Adafruit VL53L0X Library" +copyright = u"2017 Tony DiCola" +author = u"Tony DiCola" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = u"1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = u"1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -54,7 +62,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -66,7 +74,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -80,59 +88,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitVL53L0XLibrarydoc' +htmlhelp_basename = "AdafruitVL53L0XLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitVL53L0XLibrary.tex', u'Adafruit VL53L0X Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitVL53L0XLibrary.tex", + u"Adafruit VL53L0X Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -140,8 +151,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'adafruitVL53L0Xlibrary', u'Adafruit VL53L0X Library Documentation', - [author], 1) + ( + master_doc, + "adafruitVL53L0Xlibrary", + u"Adafruit VL53L0X Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -150,7 +166,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitVL53L0XLibrary', u'Adafruit VL53L0X Library Documentation', - author, 'AdafruitVL53L0XLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitVL53L0XLibrary", + u"Adafruit VL53L0X Library Documentation", + author, + "AdafruitVL53L0XLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/lis3dh_adc.py b/examples/lis3dh_adc.py index edc169f..e179231 100644 --- a/examples/lis3dh_adc.py +++ b/examples/lis3dh_adc.py @@ -6,13 +6,14 @@ import board import busio import adafruit_lis3dh + # Uncomment if using SPI -#import digitalio +# import digitalio # Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available; # otherwise check I2C pins. -if hasattr(board, 'ACCELEROMETER_SCL'): +if hasattr(board, "ACCELEROMETER_SCL"): i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19) else: @@ -24,9 +25,9 @@ # cs = digitalio.DigitalInOut(board.D5) # Set to correct CS pin! # lis3dh = adafruit_lis3dh.LIS3DH_SPI(spi, cs) -#PyGamer I2C Setup: -#i2c = busio.I2C(board.SCL, board.SDA) -#lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19) +# PyGamer I2C Setup: +# i2c = busio.I2C(board.SCL, board.SDA) +# lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19) # Loop forever printing ADC readings. @@ -35,5 +36,5 @@ adc1_raw = lis3dh.read_adc_raw(1) # Or read the ADC value in millivolts: adc1_mV = lis3dh.read_adc_mV(1) - print('ADC 1 = {} ({} mV)'.format(adc1_raw, adc1_mV)) + print("ADC 1 = {} ({} mV)".format(adc1_raw, adc1_mV)) time.sleep(1) diff --git a/examples/lis3dh_simpletest.py b/examples/lis3dh_simpletest.py index 8cba2a2..f4e8ebf 100644 --- a/examples/lis3dh_simpletest.py +++ b/examples/lis3dh_simpletest.py @@ -6,7 +6,7 @@ # Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available; # otherwise check I2C pins. -if hasattr(board, 'ACCELEROMETER_SCL'): +if hasattr(board, "ACCELEROMETER_SCL"): i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) @@ -21,10 +21,10 @@ # int1 = digitalio.DigitalInOut(board.D6) # Set to correct pin for interrupt! # lis3dh = adafruit_lis3dh.LIS3DH_SPI(spi, cs, int1=int1) -#PyGamer I2C Setup: -#i2c = busio.I2C(board.SCL, board.SDA) -#int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) -#lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) +# PyGamer I2C Setup: +# i2c = busio.I2C(board.SCL, board.SDA) +# int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) +# lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) # Set range of accelerometer (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G). @@ -34,7 +34,9 @@ while True: # Read accelerometer values (in m / s ^ 2). Returns a 3-tuple of x, y, # z axis values. Divide them by 9.806 to convert to Gs. - x, y, z = [value / adafruit_lis3dh.STANDARD_GRAVITY for value in lis3dh.acceleration] + x, y, z = [ + value / adafruit_lis3dh.STANDARD_GRAVITY for value in lis3dh.acceleration + ] print("x = %0.3f G, y = %0.3f G, z = %0.3f G" % (x, y, z)) # Small delay to keep things responsive but give time for interrupt processing. time.sleep(0.1) diff --git a/examples/lis3dh_spinner.py b/examples/lis3dh_spinner.py index 8d27154..75c2349 100644 --- a/examples/lis3dh_spinner.py +++ b/examples/lis3dh_spinner.py @@ -20,18 +20,17 @@ # Configuration: ACCEL_RANGE = adafruit_lis3dh.RANGE_16_G # Accelerometer range. -TAP_THRESHOLD = 20 # Accelerometer tap threshold. Higher values - # mean you need to tap harder to start a spin. -SPINNER_DECAY = 0.5 # Decay rate for the spinner. Set to a value - # from 0 to 1.0 where lower values mean the - # spinner slows down faster. -PRIMARY_COLOR = (0, 255, 0) # Color of the spinner dots. -SECONDARY_COLOR = (0, 0, 0) # Background color of the spinner. +TAP_THRESHOLD = 20 # Accelerometer tap threshold. Higher values +# mean you need to tap harder to start a spin. +SPINNER_DECAY = 0.5 # Decay rate for the spinner. Set to a value +# from 0 to 1.0 where lower values mean the +# spinner slows down faster. +PRIMARY_COLOR = (0, 255, 0) # Color of the spinner dots. +SECONDARY_COLOR = (0, 0, 0) # Background color of the spinner. # Define a class that represents the fidget spinner. class FidgetSpinner: - def __init__(self, decay=0.5): self._decay = decay self._velocity = 0.0 @@ -46,8 +45,8 @@ def get_position(self, delta): # Increment elapsed time and compute the current velocity after a # decay of the initial velocity. self._elapsed += delta - current_velocity = self._velocity*math.pow(self._decay, self._elapsed) - self._position += current_velocity*delta + current_velocity = self._velocity * math.pow(self._decay, self._elapsed) + self._position += current_velocity * delta # Make sure the position stays within values that range from 0 to <10. self._position = math.fmod(self._position, 10.0) if self._position < 0.0: @@ -90,7 +89,9 @@ def get_position(self, delta): while True: # Read the raw click detection register value and check if there was # a click detected. - clicksrc = lis3dh._read_register_byte(_REG_CLICKSRC) # pylint: disable=protected-access + clicksrc = lis3dh._read_register_byte( + _REG_CLICKSRC + ) # pylint: disable=protected-access if clicksrc & 0b01000000 > 0: # Click was detected! Quickly read 32 values from the accelerometer # FIFO and look for the maximum magnitude values. diff --git a/examples/lis3dh_spinner_advanced.py b/examples/lis3dh_spinner_advanced.py index c0412e2..19662bf 100644 --- a/examples/lis3dh_spinner_advanced.py +++ b/examples/lis3dh_spinner_advanced.py @@ -27,21 +27,21 @@ # Configuration: ACCEL_RANGE = adafruit_lis3dh.RANGE_16_G # Accelerometer range. -TAP_THRESHOLD = 20 # Accelerometer tap threshold. Higher values - # mean you need to tap harder to start a spin. -SPINNER_DECAY = 0.5 # Decay rate for the spinner. Set to a value - # from 0 to 1.0 where lower values mean the - # spinner slows down faster. +TAP_THRESHOLD = 20 # Accelerometer tap threshold. Higher values +# mean you need to tap harder to start a spin. +SPINNER_DECAY = 0.5 # Decay rate for the spinner. Set to a value +# from 0 to 1.0 where lower values mean the +# spinner slows down faster. # Define list of color combinations. Pressing button A will cycle through # these combos. Each tuple entry (line) should be a 2-tuple of 3-tuple RGB # values (0-255). COLORS = ( - ((255, 0, 0), (0, 0, 0)), # Red to black - ((0, 255, 0), (0, 0, 0)), # Green to black - ((0, 0, 255), (0, 0, 0)), # Blue to black - ((255, 0, 0), (0, 255, 0)), # Red to green - ((255, 0, 0), (0, 0, 255)), # Red to blue - ((0, 255, 0), (0, 0, 255)) # Green to blue + ((255, 0, 0), (0, 0, 0)), # Red to black + ((0, 255, 0), (0, 0, 0)), # Green to black + ((0, 0, 255), (0, 0, 0)), # Blue to black + ((255, 0, 0), (0, 255, 0)), # Red to green + ((255, 0, 0), (0, 0, 255)), # Red to blue + ((0, 255, 0), (0, 0, 255)), # Green to blue ) @@ -50,7 +50,8 @@ def lerp(x, x0, x1, y0, y1): """Linearly interpolate a value y given range y0...y1 that is proportional to x in range x0...x1 . """ - return y0 + (x-x0)*((y1-y0)/(x1-x0)) + return y0 + (x - x0) * ((y1 - y0) / (x1 - x0)) + def color_lerp(x, x0, x1, c0, c1): """Linearly interpolate RGB colors (3-tuples of byte values) given x @@ -58,9 +59,11 @@ def color_lerp(x, x0, x1, c0, c1): """ r0, g0, b0 = c0 r1, g1, b1 = c1 - return (int(lerp(x, x0, x1, r0, r1)), - int(lerp(x, x0, x1, g0, g1)), - int(lerp(x, x0, x1, b0, b1))) + return ( + int(lerp(x, x0, x1, r0, r1)), + int(lerp(x, x0, x1, g0, g1)), + int(lerp(x, x0, x1, b0, b1)), + ) # Define a class that represents the fidget spinner. The spinner only has a @@ -70,7 +73,6 @@ def color_lerp(x, x0, x1, c0, c1): # position. Since the position moves between values 0 to 10 it can easily map # to pixel positions around the Circuit Playground Express board. class FidgetSpinner: - def __init__(self, decay=0.5): """Create an instance of the fidget spinner. Specify the decay rate as a value from 0 to 1 (continuous, floating point)--lower decay rate @@ -96,9 +98,9 @@ def get_position(self, delta): # Increment elapsed time and compute the current velocity after a # decay of the initial velocity. self._elapsed += delta - current_velocity = self._velocity*math.pow(self._decay, self._elapsed) + current_velocity = self._velocity * math.pow(self._decay, self._elapsed) # Update position based on the current_velocity and elapsed time. - self._position += current_velocity*delta + self._position += current_velocity * delta # Make sure the position stays within values that range from 0 to <10. self._position = math.fmod(self._position, 10.0) if self._position < 0.0: @@ -111,7 +113,6 @@ def get_position(self, delta): # secondary color (3-tuple of RGB bytes) and will render a frame of spinner # animation. class DiscreteDotAnimation: - def __init__(self, pixels, dots=2): """Create an instance of a simple discrete dot animation. The dots parameter controls how many dots are rendered on the display (each @@ -130,13 +131,12 @@ def update(self, position, primary, secondary): # position. self._pixels.fill(secondary) for i in range(self._dots): - pos = int(position + i*self._dot_offset) % self._pixels.n + pos = int(position + i * self._dot_offset) % self._pixels.n self._pixels[pos] = primary self._pixels.show() class SmoothAnimation: - def __init__(self, pixels, frequency=2.0): """Create an instance of a smooth sine-wave based animation that sweeps around the board based on spinner position. Frequency specifies how @@ -145,8 +145,8 @@ def __init__(self, pixels, frequency=2.0): self._pixels = pixels # Precompute some of the sine wave math factors so they aren't # recomputed in every loop iteration. - self._sin_scale = 2.0*math.pi*frequency/pixels.n - self._phase_scale = 2.0*math.pi/10.0 + self._sin_scale = 2.0 * math.pi * frequency / pixels.n + self._phase_scale = 2.0 * math.pi / 10.0 def update(self, position, primary, secondary): """Update the animation given the current spinner position and @@ -156,9 +156,9 @@ def update(self, position, primary, secondary): # the pixels. Each pixel color is computed based on interpolating # color based on its position around the board, and a phase offset that # changes based on fidget spinner position. - phase = self._phase_scale*position + phase = self._phase_scale * position for i in range(self._pixels.n): - x = math.sin(self._sin_scale*i - phase) + x = math.sin(self._sin_scale * i - phase) self._pixels[i] = color_lerp(x, -1.0, 1.0, primary, secondary) self._pixels.show() @@ -207,12 +207,14 @@ def update(self, position, primary, secondary): # Other global state for the spinner animation: last = time.monotonic() # Keep track of the last time the loop ran. -color_index = 0 # Keep track of the currently selected color combo. -animations = (DiscreteDotAnimation(pixels, 1), # Define list of animations. - DiscreteDotAnimation(pixels, 2), # Button B presses cycle - SmoothAnimation(pixels, 1), # through these animations. - SmoothAnimation(pixels, 2)) -animation_index = 0 # Keep track of currently selected animation. +color_index = 0 # Keep track of the currently selected color combo. +animations = ( + DiscreteDotAnimation(pixels, 1), # Define list of animations. + DiscreteDotAnimation(pixels, 2), # Button B presses cycle + SmoothAnimation(pixels, 1), # through these animations. + SmoothAnimation(pixels, 2), +) +animation_index = 0 # Keep track of currently selected animation. # Main loop will run forever checking for click/taps from accelerometer and # then spinning the spinner. @@ -225,7 +227,9 @@ def update(self, position, primary, secondary): # Read the raw click detection register value and check if there was # a click detected. Remember only the X axis causes clicks because of # the register configuration set previously. - clicksrc = lis3dh._read_register_byte(_REG_CLICKSRC) # pylint: disable=protected-access + clicksrc = lis3dh._read_register_byte( + _REG_CLICKSRC + ) # pylint: disable=protected-access if clicksrc & 0b01000000 > 0: # Click was detected! Quickly read 32 values from the accelerometer # and look for the maximum magnitude values. Because the diff --git a/examples/lis3dh_tap.py b/examples/lis3dh_tap.py index 014bba8..5eb8c74 100644 --- a/examples/lis3dh_tap.py +++ b/examples/lis3dh_tap.py @@ -6,13 +6,15 @@ # Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available; # otherwise check I2C pins. -if hasattr(board, 'ACCELEROMETER_SCL'): +if hasattr(board, "ACCELEROMETER_SCL"): i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) else: i2c = busio.I2C(board.SCL, board.SDA) - int1 = digitalio.DigitalInOut(board.D9) # Set this to the correct pin for the interrupt! + int1 = digitalio.DigitalInOut( + board.D9 + ) # Set this to the correct pin for the interrupt! lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1) # Hardware SPI setup: @@ -39,5 +41,5 @@ # Loop forever printing if a double tap is detected. while True: if lis3dh.tapped: - print('Tapped!') + print("Tapped!") time.sleep(0.01) diff --git a/setup.py b/setup.py index a2ff987..1a3f094 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ # Always prefer setuptools over distutils from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -14,47 +15,38 @@ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file -with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( - name='adafruit-circuitpython-lis3dh', - + name="adafruit-circuitpython-lis3dh", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='CircuitPython library for LIS3DH accelerometer.', + setup_requires=["setuptools_scm"], + description="CircuitPython library for LIS3DH accelerometer.", long_description=long_description, - long_description_content_type='text/x-rst', - + long_description_content_type="text/x-rst", # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_LIS3DH', - + url="https://github.com/adafruit/Adafruit_CircuitPython_LIS3DH", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=['Adafruit-Blinka'], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka"], # Choose your license - license='MIT', - + license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Topic :: System :: Hardware', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", ], - # What does your project relate to? - keywords='adafruit accelerometer lis3dh acceleration hardware micropython circuitpython', - + keywords="adafruit accelerometer lis3dh acceleration hardware micropython circuitpython", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). - py_modules=['adafruit_lis3dh'], -) \ No newline at end of file + py_modules=["adafruit_lis3dh"], +)