Compare commits

..
Author SHA1 Message Date
David Lechner 73d794dfb8 @pybricks/ide-docs v2.1.0 2021-12-16 15:39:57 -06:00
David Lechner dd77c548d2 v3.1.0 2021-12-16 15:35:09 -06:00
David Lechner 022afabd30 pybricks.robotics: add type hint for curve()
This method was added in 30803fc.
2021-12-16 15:33:00 -06:00
David Lechner ce17123325 pybricks._common: remove type hint for integral_range()
This was removed in e061617.

Also fix import of Axis while we are touching this file.
2021-12-16 15:29:44 -06:00
Laurens Valk f2346df4e5 pybricks.iodevices: Hide LWP3Device
This is not part of the upcoming release.

Hiding is nicer than adding not-ready disclaimers throughout, especially since this information is very easy to access via our beta channel.
2021-12-01 15:39:05 +01:00
Laurens Valk 94c659ba6d pybricks.geometry: Hide module and IMU examples.
This is not part of the upcoming release.

Hiding is nicer than adding not-ready disclaimers throughout, especially since this information is very easy to access via our beta channel.
2021-12-01 15:39:04 +01:00
Laurens Valk 9c0298bad0 doc/main/index: Drop beta note.
This is a normal release.
2021-12-01 15:39:04 +01:00
Laurens Valk 602b21fe9d doc/main/hubs: Hide Prime Hub.
This is not part of the upcoming release.

Hiding is nicer than adding not-ready disclaimers throughout, especially
since this information is very easy to access via our beta channel.
2021-12-01 15:39:04 +01:00
169 changed files with 3879 additions and 6900 deletions
+2 -14
View File
@@ -3,19 +3,7 @@
name: Build Python package and docs
on:
push:
tags-ignore:
- "*"
pull_request:
paths:
- doc/**
- src/**
- poetry.lock
- poetry.toml
- pyproject.toml
- setup.cfg
on: [ push, pull_request ]
jobs:
build:
@@ -47,7 +35,7 @@ jobs:
run: poetry run doc8
- name: Build html docs for Read the Docs
run: poetry run make -C doc html
- name: Install IDE docs dependencies
- name: Instal IDE docs dependencies
run: |
sudo apt-get update
sudo apt-get install dvisvgm preview-latex-style texlive texlive-fonts-extra texlive-latex-extra
-36
View File
@@ -1,36 +0,0 @@
name: pybricks_jedi
on: [push, pull_request]
jobs:
test:
if: github.ref_type != 'tag'
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.10"
- run: pipx install poetry
- run: poetry install
working-directory: ./jedi
- run: poetry run pytest -vv
working-directory: ./jedi
publish:
if: github.ref_type == 'tag' && startsWith(github.ref_name, 'pybricks_jedi/')
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.10"
- run: pipx install poetry
- run: poetry install
working-directory: ./jedi
- run: poetry build
working-directory: ./jedi
- run: poetry publish
working-directory: ./jedi
env:
POETRY_PYPI_TOKEN_PYPI: ${{ secrets.PYPI_PYBRICKS_JEDI_TOKEN }}
-23
View File
@@ -1,23 +0,0 @@
name: Release @pybricks/jedi
on:
push:
tags:
- '@pybricks/jedi/**'
jobs:
publish_ide_docs:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v3
with:
node-version: '16.x'
registry-url: 'https://registry.npmjs.org'
- run: ./build.py
working-directory: npm/jedi
- run: yarn publish
working-directory: npm/jedi/build
env:
NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
+1 -3
View File
@@ -26,9 +26,8 @@ build/
build-*/
_build/
# Tests
# Test failure outputs
######################
.pytest_cache/
tests/*.exp
tests/*.out
@@ -58,4 +57,3 @@ genrst/
# Virtual environment
######################
.venv/
.python-version
+3 -24
View File
@@ -1,24 +1,10 @@
{
"files.exclude": {
"**/__pycache__": true,
},
"python.autoComplete.extraPaths": ["jedi/src"],
"python.pythonPath": "${workspaceFolder}/.venv",
"python.formatting.provider": "black",
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.pycodestyleEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.enabled": true,
"[python]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "ms-python.python"
},
"python.languageServer": "Pylance",
"python.testing.pytestArgs": [
"jedi/tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"files.associations": {"*.inc": "restructuredtext"},
"restructuredtext.confPath": "${workspaceFolder}/doc/main",
"spellright.language": [
@@ -48,12 +34,5 @@
"plaintext",
"python",
"restructuredtext",
],
"rewrap.wrappingColumn": 78,
"python.analysis.extraPaths": [
"jedi/src"
],
"yaml.schemas": {
"https://json.schemastore.org/github-workflow.json": "file:///home/david/work/pybricks/pybricks-api/.github/workflows/build.yml"
},
]
}
-1
View File
@@ -78,4 +78,3 @@ thermistor
toctree
TODO
UART
utf-8
-39
View File
@@ -2,45 +2,6 @@
<!-- refer to https://keepachangelog.com/en/1.0.0/ for guidance -->
## Unreleased
### Added
- Code auto-completion for `EssentialHub`.
### Fixed
- Fixed some type hints in `parameters` submodule.
## 3.2.0b1-r3 - 2022-06-26
### Fixed
- Fixed more type hints and improved compatibility with jedi.
## 3.2.0b1-r2 - 2022-06-24
### Changed
- Moved remaining type hints from `.pyi` files to the python stub modules, and
fixed numerous errors in the type hints throughout.
## 3.2.0b1-r1 - 2022-06-09
## Added
- Added `__init__.py` to `pybricks` package.
## 3.2.0b1 - 2022-06-02
### Added
- Code auto-completion for `hub.charger`, `hub.imu` and `hub.system`.
- Moved typing from several `.pyi` files to the actual python modules.
### Fixed
- Fixed code completion for `DCMotor` and `Motor` classes in MS Python VS Code extension.
- Fixed missing `DCMotor` type in `ev3devices`.
- Fixed type hint for `Motor.reset_angle()` in `pupdevices`.
### Changed
- Setter for acceleration can now also be used to set acceleration and
deceleration to different values, using a two-valued tuple.
## 3.1.0 - 2021-12-16
### Added
+5 -82
View File
@@ -32,91 +32,14 @@ will actually be implemented.
- pybricks.tools.wait: Add example of waiting.
- pybricks.pupdevices: Fix all sensor class ports.
- umath.sin: Fix spelling of Hypotenuse.
- If an import path makes no sense, just use the file path without
extensions:
- If an import path makes no sense, just use the file path without extensions:
- .vscode/settings: Fix file associations.
- The subject briefly describes _what_ was changed. Use a short full sentence
as in the examples above.
- The subject briefly describes _what_ was changed. Use a short full sentence as in the examples above.
- The body describes _why_ the change was made, e.g. `The word "sensor" was
spelled incorrectly`.
[commits]: https://github.com/pybricks/pybricks-api/commits/master
**General docstring principles:**
The stubs libraries in this repository have two different purposes:
1. Auto-generating documentation with Sphinx. For this purpose, the
documentation should be concise and clear.
2. Provide autocomplete and intellisense in code editors. For this purpose,
the code needs to be 100% correct. This way, computers can parse your code
correctly and tell you when something is wrong.
Since these objectives don't always align, we address these separately in the
stubs library:
1. The first line(s) of the docstring contain the function or method signature
as it should be displayed in the human-readable documentation.
2. The real function signature can be as complex as it needs to be to make it
correct for intellisense. Overloads can be uses if needed.
In the rare case where the docstring signature is the same as the typed
version, we'll still include it for consistency.
**Docstring details:**
Make sure to look at existing function signatures and docstrings for
inspiration when documenting new functionality. As an example, consider:
```python
def run_until_stalled(
self,
speed: Number,
then: Stop = Stop.COAST,
duty_limit: Optional[Number] = None,
) -> int:
"""
run_until_stalled(speed, then=Stop.COAST, duty_limit=None) -> int: deg
Runs the motor at a constant speed until it stalls.
Arguments:
speed (Number, deg/s): Speed of the motor.
then (Stop): What to do after coming to a standstill.
duty_limit (Number, %): Duty cycle limit during this
command. This is useful to avoid applying the full motor
torque to a geared or lever mechanism. If it is ``None``, the
duty limit won't be changed during this command.
Returns:
Angle at which the motor becomes stalled.
"""
```
The real method signature at the top contains the full detail, including the
type of each argument and return value.
The docstring starts with the signature. Use more than one signature if needed
to represent overloaded methods. The signatures are written in the way they
should be displayed in the docs:
- Argument types are omitted because they are also shown with the argument
description below.
- Default values should be given (``then=Stop.COAST``).
- The return type should be given (``-> int``). When applicable, include
the unit of the return value, so it becomes ``-> int: deg``
Then follows a concise description of what this method, function, or class
does.
Then follows a list of arguments:
- For each argument, include the expected type and unit if applicable, e.g.
``(int)`` or ``(Number, deg/s)``.
- Use ``Number`` when ``int`` and ``float`` are both allowed.
- If the description is long, use the indentation shown above.
- Make it readable. Instead
of ``Union[float, SupportsFloat, complex, SupportsComplex]``,
just say _float or complex_.
Then follows a description of the return value. The type is omitted here since
it is already include in the docstring signature.
**Development environment:**
@@ -126,8 +49,8 @@ Prerequisites:
- [Python 3][python]
- [Poetry][poetry]
Information on installing prerequisites can be found on the
[pybricks-micropython contributor's guide][contributing].
Information on installing prerequisites can be found on the [pybricks-micropython
wiki][wiki].
Initial setup:
@@ -167,4 +90,4 @@ Linting:
[git]: https://git-scm.com/
[python]: https://www.python.org/
[poetry]: https://python-poetry.org/
[contributing]: https://github.com/pybricks/pybricks-micropython/blob/master/CONTRIBUTING.md
[wiki]: https://github.com/pybricks-micropython/wiki
+1 -1
View File
@@ -11,7 +11,7 @@ TAG = main
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(TAG) $(O)
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) -t $(TAG) $(O)
.PHONY: help Makefile
+110 -154
View File
@@ -27,20 +27,21 @@ from docutils import nodes
from docutils.parsers.rst.directives import flag
from docutils.parsers.rst import Directive
from sphinx.application import Sphinx
from sphinx.addnodes import pending_xref
from sphinx.environment import BuildEnvironment
from sphinx.util.nodes import make_refnode
import toml
TOP_DIR = os.path.abspath(os.path.join("..", ".."))
sys.path.insert(0, os.path.join(TOP_DIR, "src"))
sys.path.append(os.path.abspath("../common/extensions"))
TOP_DIR = os.path.abspath(os.path.join('..', '..'))
sys.path.insert(0, os.path.join(TOP_DIR, 'src'))
sys.path.append(os.path.abspath('../common/extensions'))
from pybricks.hubs import EV3Brick # noqa E402
from pybricks.media.ev3dev import Image # noqa E402
from pybricks._common import Speaker # noqa E402
# ON_RTD is whether we are on readthedocs.org
# this line of code grabbed from docs.readthedocs.org
ON_RTD = os.environ.get("READTHEDOCS", None) == "True"
ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
_pyproject = toml.load(os.path.join(TOP_DIR, "pyproject.toml"))
_pyproject = toml.load(os.path.join(TOP_DIR, 'pyproject.toml'))
# -- General configuration ------------------------------------------------
@@ -52,29 +53,27 @@ _pyproject = toml.load(os.path.join(TOP_DIR, "pyproject.toml"))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.mathjax",
# Custom Pybricks extensions
"color",
"classlink",
"requirements",
"requirements-static",
"versionchanged",
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
'sphinx.ext.mathjax',
'color',
'classlink',
'requirements',
'requirements-static',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["../common/_templates"]
templates_path = ['../common/_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"
source_suffix = '.rst'
# The master toctree document.
master_doc = "index"
master_doc = 'index'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -83,17 +82,17 @@ master_doc = "index"
# The full version, including alpha/beta/rc tags.
release = "v" + _pyproject["tool"]["poetry"]["version"]
# The short X.Y version.
version = re.match(r"(v\d+\.\d+)", release)[0]
version = re.match(r'(v\d+\.\d+)', release)[0]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
language = None
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "xcode"
pygments_style = 'xcode'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
@@ -101,10 +100,10 @@ todo_include_todos = True
# Figure numbering
numfig = True
numfig_format = {
"figure": "Figure %s",
"table": "Table %s",
"code-block": "Listing %s",
"section": "Section %s",
'figure': 'Figure %s',
'table': 'Table %s',
'code-block': 'Listing %s',
'section': 'Section %s'
}
# Find cross-reference errors
@@ -112,49 +111,59 @@ nitpicky = True
# https://stackoverflow.com/a/30624034/1976323
nitpick_ignore = [
("py:class", "bool"),
("py:class", "bytearray"),
("py:class", "bytes"),
("py:class", "callable"),
("py:class", "dict"),
("py:class", "float"),
("py:class", "int"),
("py:class", "iter"),
("py:class", "list"),
("py:class", "object"),
("py:class", "str"),
("py:class", "tuple"),
("py:exc", "OSError"),
("py:exc", "RuntimeError"),
("py:exc", "TypeError"),
("py:exc", "ValueError"),
('py:class', 'bool'),
('py:class', 'bytearray'),
('py:class', 'bytes'),
('py:class', 'callable'),
('py:class', 'dict'),
('py:class', 'float'),
('py:class', 'int'),
('py:class', 'iter'),
('py:class', 'list'),
('py:class', 'object'),
('py:class', 'str'),
('py:class', 'tuple'),
('py:exc', 'OSError'),
('py:exc', 'RuntimeError'),
('py:exc', 'TypeError'),
('py:exc', 'ValueError'),
]
# not sure why, but this is needed for typing.IO in uselect
nitpick_ignore.append(("py:obj", "typing.IO"))
nitpick_ignore.append(('py:class', 'IO'))
# Workaround until change below is released.
# https://github.com/sphinx-doc/sphinx/commit/86091934db5ec593b4b0c982b7f08f3231ef995b
nitpick_ignore.extend([
('py:class', '0'),
('py:class', '1'),
('py:class', '2'),
('py:class', '3'),
('py:class', 'big'),
('py:class', 'little'),
])
# -- Autodoc options ------------------------------------------------------
autodoc_member_order = "bysource"
autodoc_member_order = 'bysource'
autodoc_default_options = {
"members": True,
"undoc-members": True,
'members': True,
'undoc-members': True,
}
autoclass_content = "both" # This ensures init arguments are not ignored
autoclass_content = 'both' # This ensures init arguments are not ignored
add_module_names = False # Hide module name
# -- Options for HTML output ----------------------------------------------
if ON_RTD:
html_theme = "default"
html_theme = 'default'
else:
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_context = {
"disclaimer": _DISCLAIMER,
'disclaimer': _DISCLAIMER,
}
# The theme to use for HTML and HTML Help pages. See the documentation for
@@ -167,14 +176,14 @@ html_context = {
# documentation.
#
html_theme_options = {
"style_external_links": True,
"logo_only": True,
'style_external_links': True,
'logo_only': True,
}
# 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 = ["../common/_static"]
html_static_path = ['../common/_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
@@ -182,9 +191,9 @@ html_static_path = ["../common/_static"]
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
"**": [
"relations.html", # needs 'show_related': True theme option to display
"searchbox.html",
'**': [
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
]
}
@@ -194,7 +203,7 @@ html_scaled_image_link = False
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "Pybricksdoc"
htmlhelp_basename = 'Pybricksdoc'
# -- Options for LaTeX output ---------------------------------------------
@@ -203,12 +212,14 @@ 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": r"""
'preamble': r'''
\usepackage{CJKutf8}
\makeatletter
\fancypagestyle{normal}{
@@ -228,46 +239,54 @@ latex_elements = {
\renewcommand{\footrulewidth}{0.4pt}
}
\makeatother
"""
% {
"disclaimer": " ".join((_DISCLAIMER, "©", copyright)),
''' % {
'disclaimer': ' '.join((_DISCLAIMER, '©', copyright)),
},
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
"extraclassoptions": "openany,oneside",
"releasename": "Version",
'extraclassoptions': 'openany,oneside',
'releasename': 'Version',
}
# 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, "".join([project, "-v", version, ".tex"]), _TITLE, author, "manual"),
(master_doc, ''.join([project, '-v', version, '.tex']), _TITLE,
author, 'manual'),
]
# -- Content control -----------------------------------------------------
exclude_patterns = [
"ev3devices.rst",
"hubs/ev3brick.rst",
"iodevices/analogsensor.rst",
"iodevices/dcmotor.rst",
"iodevices/ev3devsensor.rst",
"iodevices/i2cdevice.rst",
"iodevices/lumpdevice.rst",
"iodevices/uartdevice.rst",
"media.rst",
"messaging.rst",
"nxtdevices.rst",
"tools/datalog.rst",
'ev3devices.rst',
'hubs/ev3brick.rst',
'hubs/primehub.rst',
'geometry.rst',
'iodevices/analogsensor.rst',
'iodevices/dcmotor.rst',
'iodevices/ev3devsensor.rst',
'iodevices/i2cdevice.rst',
'iodevices/lumpdevice.rst',
'iodevices/lwp3device.rst',
'iodevices/uartdevice.rst',
'media.rst',
'messaging.rst',
'nxtdevices.rst',
'tools/datalog.rst'
]
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "pybricks", "Pybricks Documentation", [author], 1)]
man_pages = [
(master_doc, 'pybricks', 'Pybricks Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
@@ -276,96 +295,33 @@ man_pages = [(master_doc, "pybricks", "Pybricks Documentation", [author], 1)]
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"Pybricks",
"Pybricks Documentation",
author,
"Pybricks",
"One line description of project.",
"Miscellaneous",
),
(master_doc, 'Pybricks', 'Pybricks Documentation',
author, 'Pybricks', 'One line description of project.',
'Miscellaneous'),
]
# -- .. availability:: directive
class AvailabilityDirective(Directive):
has_content = True
option_spec = {
"movehub": flag,
"cityhub": flag,
"technichub": flag,
"ev3dev-stretch": flag,
'movehub': flag,
'cityhub': flag,
'technichub': flag,
'ev3dev-stretch': flag,
}
def run(self):
if not self.options:
raise self.error("Must specify at least one platform.")
raise self.error('Must specify at least one platform.')
# TODO: make links to platform pages
return [
nodes.emphasis(text="Availability: "),
nodes.Text(", ".join(self.options)),
]
def on_missing_reference(
app: Sphinx, env: BuildEnvironment, node: pending_xref, contnode: nodes.Element
) -> nodes.Element:
# The Number type alias is on the Signals and Units page instead of on the
# pybricks.parameters page so normal resolution doesn't work
if node["reftype"] == "class" and node["reftarget"] == "Number":
return make_refnode(
app.builder, node["refdoc"], "signaltypes", "numbers", contnode
)
# References with special characters can't exist, so we have to supress
# warnings when Sphinx tries to cross reference units like deg/s. For
# consistency, we also treat units without special characters this way.
for unit in [
"deg",
"deg/s",
"deg/s²",
"mm",
"mm/s",
"mm/s²",
"%",
"mV",
"mA",
"ms",
"mNm",
"Hz",
"°C",
"J",
"Ω",
"N",
]:
# If they match on raw source, we are dealing with argument types.
if unit == contnode.rawsource:
# Return as-is to suppress missing cross reference warning. We
# could make this more fancy by returning an xref node that links
# to the signals page.
return contnode
# Return types are denoted as "int: deg"
try:
# Try to unpack the node.
ret_type, ret_unit = str(contnode).split(": ")
except ValueError:
# Not a valid format, so skip.
continue
# If it's a match, we could format the node so it looks a bit nicer.
# For now just keep the colon notation as is.
if unit == ret_unit:
return nodes.Text(f"{ret_type}: {ret_unit}")
return [nodes.emphasis(text='Availability: '),
nodes.Text(', '.join(self.options))]
def setup(app: Sphinx):
app.add_directive("availability", AvailabilityDirective)
app.connect("missing-reference", on_missing_reference)
app.add_directive('availability', AvailabilityDirective)
# -- Python domain hacks ---------------------------------------------------
+11 -13
View File
@@ -13,23 +13,21 @@ class PybricksClasslinkDirective(Directive):
link = name if len(self.arguments) == 1 else self.arguments[1]
html = (
'<a href="{0}.html">'.format(link.lower())
+ '<dl class="py class">'
+ "<dt>"
+ '<em class="property">class </em>'
+ '<code class="sig-name descname">'
+ name
+ "</code>"
+ "</dt>"
+ "<dd></dd>"
+ "</dl>"
+ "</a>"
'<a href="{0}.html">'.format(link.lower()) +
'<dl class="py class">' +
'<dt>' +
'<em class="property">class </em>' +
'<code class="sig-name descname">' + name + '</code>' +
'</dt>' +
'<dd></dd>' +
'</dl>' +
'</a>'
)
# Return the node
node = nodes.raw("", html, format="html")
node = nodes.raw('', html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain("py", "pybricks-classlink", PybricksClasslinkDirective)
app.add_directive_to_domain('py', 'pybricks-classlink', PybricksClasslinkDirective)
+9 -8
View File
@@ -16,27 +16,28 @@ class PybricksColorDirective(Directive):
color = getattr(Color, name)
# Convert HSV to RGB
r, g, b = hsv_to_rgb(color.h / 360, color.s / 100, color.v / 100)
r, g, b = hsv_to_rgb(color.h/360, color.s/100, color.v/100)
# Convert RGB to HEX
rgbhex = "#{0:02x}{1:02x}{2:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
rgbhex = '#{0:02x}{1:02x}{2:02x}'.format(
round(r*255),
round(g*255),
round(b*255)
)
# Render a small block of the given color
css = "background-color: {0}; color: {0}; width: 50px;".format(rgbhex)
if name == "WHITE":
css += (
"border-style: solid; border-width: 0.5px;" + "border-color: #666666;"
)
css += "border-style: solid; border-width: 0.5px;" + \
"border-color: #666666;"
html = '<div id="test" style="{0}">_</div>'.format(css)
# Return the node
node = nodes.raw("", html, format="html")
node = nodes.raw('', html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain("py", "pybricks-color", PybricksColorDirective)
app.add_directive_to_domain('py', 'pybricks-color', PybricksColorDirective)
+25 -27
View File
@@ -10,10 +10,10 @@ FEATURES_SMALL = set()
# Medium feature set.
FEATURES_MEDIUM = FEATURES_SMALL | {
"pybricks-geometry",
"pybricks-iodevices",
"stm32-extra",
"stm32-float",
'pybricks-geometry',
'pybricks-iodevices',
'stm32-extra',
'stm32-float',
}
# Large feature set.
@@ -21,12 +21,11 @@ FEATURES_LARGE = FEATURES_MEDIUM | set()
# Features per hub.
HUB_FEATURES = {
"movehub": {"movehub"} | FEATURES_SMALL,
"cityhub": {"cityhub"} | FEATURES_MEDIUM,
"technichub": {"technichub"} | FEATURES_MEDIUM,
"primehub": {"primehub", "inventorhub"} | FEATURES_LARGE,
"inventorhub": {"primehub", "inventorhub"} | FEATURES_LARGE,
"essentialhub": {"essentialhub"} | FEATURES_LARGE,
'movehub': {'movehub'} | FEATURES_SMALL,
'cityhub': {'cityhub'} | FEATURES_MEDIUM,
'technichub': {'technichub'} | FEATURES_MEDIUM,
'primehub': {'primehub', 'inventorhub'} | FEATURES_LARGE,
'inventorhub': {'primehub', 'inventorhub'} | FEATURES_LARGE,
}
@@ -41,15 +40,15 @@ class PybricksRequirementsStaticDirective(Directive):
# CC BY-SA 4.0 via https://stackoverflow.com/a/63728208
env = self.state.document.settings.env
destdir = path.join(env.app.builder.outdir, "_images")
destdir = path.join(env.app.builder.outdir, '_images')
if not path.exists(destdir):
makedirs(destdir)
for hub in HUB_FEATURES:
for compat in ("true", "false"):
uri = "compat_{0}_{1}_label.png".format(hub, compat)
src_uri = path.join(env.app.builder.srcdir, "images", uri)
build_uri = path.join(env.app.builder.outdir, "_images", uri)
uri = 'compat_{0}_{1}_label.png'.format(hub, compat)
src_uri = path.join(env.app.builder.srcdir, 'images', uri)
build_uri = path.join(env.app.builder.outdir, '_images', uri)
copyfile(src_uri, build_uri)
# Get requirements from sphinx-directive.
@@ -68,14 +67,13 @@ class PybricksRequirementsStaticDirective(Directive):
depth_path = "../" * depth
# Table row with hub images.
compat_row = "".join(
[
hub_cell.format(
depth_path, hub, "true" if requirements <= features else "false"
)
for hub, features in HUB_FEATURES.items()
]
)
compat_row = "".join([
hub_cell.format(
depth_path,
hub,
"true" if requirements <= features else "false")
for hub, features in HUB_FEATURES.items()
])
# Generate full table.
html = """
@@ -88,16 +86,16 @@ class PybricksRequirementsStaticDirective(Directive):
</tbody>
</table>
</div>
""".format(
compat_row
)
""".format(compat_row)
# Return the node.
node = nodes.raw("", html, format="html")
node = nodes.raw('', html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain(
"py", "pybricks-requirements-static", PybricksRequirementsStaticDirective
'py',
'pybricks-requirements-static',
PybricksRequirementsStaticDirective
)
+14 -14
View File
@@ -29,25 +29,25 @@ from sphinx.util.osutil import copyfile
from sphinx.util import logging
CSS_FILE = "requirements.css"
JS_FILE = "requirements.js"
CSS_FILE = 'requirements.css'
JS_FILE = 'requirements.js'
class PybricksRequirementsDirective(Directive):
has_content = True
option_spec = {"header": directives.unchanged}
option_spec = {'header': directives.unchanged}
required_arguments = 0
optional_arguments = 10
def run(self):
node = nodes.container()
node["classes"].append("toggle-content")
node['classes'].append('toggle-content')
par = nodes.container()
par["classes"].append("toggle-header")
par['classes'].append('toggle-header')
content = ".. pybricks-requirements-static:: " + " ".join(self.arguments)
content = '.. pybricks-requirements-static:: ' + " ".join(self.arguments)
self.state.nested_parse(StringList([content]), self.content_offset, node)
@@ -60,20 +60,20 @@ def add_assets(app):
def copy_assets(app, exception):
if app.builder.name not in ["html", "readthedocs"] or exception:
if app.builder.name not in ['html', 'readthedocs'] or exception:
return
logger = logging.getLogger(__name__)
logger.info("Copying requirements stylesheet/javascript... ", nonl=True)
dest = os.path.join(app.builder.outdir, "_static", CSS_FILE)
logger.info('Copying requirements stylesheet/javascript... ', nonl=True)
dest = os.path.join(app.builder.outdir, '_static', CSS_FILE)
source = os.path.join(os.path.abspath(os.path.dirname(__file__)), CSS_FILE)
copyfile(source, dest)
dest = os.path.join(app.builder.outdir, "_static", JS_FILE)
dest = os.path.join(app.builder.outdir, '_static', JS_FILE)
source = os.path.join(os.path.abspath(os.path.dirname(__file__)), JS_FILE)
copyfile(source, dest)
logger.info("done")
logger.info('done')
def setup(app):
app.add_directive("pybricks-requirements", PybricksRequirementsDirective)
app.connect("builder-inited", add_assets)
app.connect("build-finished", copy_assets)
app.add_directive('pybricks-requirements', PybricksRequirementsDirective)
app.connect('builder-inited', add_assets)
app.connect('build-finished', copy_assets)
-31
View File
@@ -1,31 +0,0 @@
"""This directive hides the builtin directives
* versionchanged
* versionadded
* deprecated
when building documentation with the 'ide' tag.
"""
from docutils import nodes
from docutils.parsers.rst import Directive
class PybricksVersionDirective(Directive):
has_content = True
def run(self):
html = ""
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
if "ide" in app.tags.tags:
app.add_directive_to_domain(
"py", "deprecated", PybricksVersionDirective, override=True
)
app.add_directive_to_domain(
"py", "versionadded", PybricksVersionDirective, override=True
)
app.add_directive_to_domain(
"py", "versionchanged", PybricksVersionDirective, override=True
)
+22 -29
View File
@@ -4,54 +4,47 @@
# Pybricks documentation build configuration file
#
import os
import sys
# General information about the project.
project = "pybricks"
copyright = "2018-2021 The Pybricks Authors"
author = ""
project = 'pybricks'
copyright = '2018-2021 The Pybricks Authors'
author = ''
_TITLE = "Pybricks Modules and Examples"
_DISCLAIMER = "LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are\
_TITLE = 'Pybricks Modules and Examples'
_DISCLAIMER = 'LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are\
trademarks and/or copyrights of the LEGO Group of companies \
which does not sponsor, authorize or endorse this site."
which does not sponsor, authorize or endorse this site.'
html_favicon = "../common/images/favicon.ico"
html_logo = "../common/images/pybricks-logo-rtd.png"
latex_logo = "../common/images/pybricks-logo-large.png"
html_favicon = '../common/images/favicon.ico'
html_logo = '../common/images/pybricks-logo-rtd.png'
latex_logo = '../common/images/pybricks-logo-large.png'
# Build main docs for RTD by default.
# Since tags cannot be passed via the TAG make variable on read the docs,
# add it manually.
if os.environ.get("READTHEDOCS", None) == "True":
tags.add("main") # noqa F821
if os.environ.get('READTHEDOCS', None) == 'True':
tags.add('main') # noqa F821
# HACK: this allows Number type alias to be imported by Sphinx
os.environ["SPHINX_BUILD"] = "True"
# Addtional configuration of the IDE docs
if "ide" in tags.tags: # noqa F821
_DISCLAIMER = ""
if 'ide' in tags.tags: # noqa F821
_DISCLAIMER = ''
html_show_copyright = False
html_show_sphinx = False
html_css_files = ["css/ide.css"]
html_js_files = ["js/ide.js"]
html_css_files = ['css/ide.css']
html_js_files = ['js/ide.js']
imgmath_image_format = "svg"
imgmath_image_format = 'svg'
imgmath_use_preview = True # requires Sphinx v3
imgmath_latex_preamble = r"""
imgmath_latex_preamble = r'''
\usepackage{newtxsf}
"""
'''
exec(open(os.path.abspath("../common/conf.py")).read())
# Addtional configuration of the IDE docs
if "ide" in tags.tags: # noqa F821
if 'ide' in tags.tags: # noqa F821
extensions.remove("sphinx.ext.mathjax") # noqa F821
extensions.append("sphinx.ext.imgmath") # noqa F821
html_theme_options["prev_next_buttons_location"] = None # noqa F821
# Build hub specific example scripts.
sys.path.append(os.path.abspath("../../examples/pup/hub_common"))
import make_examples # noqa F401, E402
extensions.remove('sphinx.ext.mathjax') # noqa F821
extensions.append('sphinx.ext.imgmath') # noqa F821
html_theme_options['prev_next_buttons_location'] = None # noqa F821
+4 -29
View File
@@ -44,42 +44,17 @@ Motors
.. automethod:: pybricks.ev3devices.Motor.run_target
.. automethod:: pybricks.ev3devices.Motor.track_target
.. automethod:: pybricks.ev3devices.Motor.run_until_stalled
.. automethod:: pybricks.ev3devices.Motor.dc
.. rubric:: Motor status
.. rubric:: Advanced motion control
.. attribute:: control.scale
.. automethod:: pybricks.ev3devices.Motor.track_target
Number of degrees that the motor turns to complete one degree at the
output of the gear train. This is the gear ratio determined from the
``gears`` argument when initializing the motor.
.. autoattribute:: pybricks.ev3devices.Motor.control
:annotation:
.. automethod:: pybricks.ev3devices.Motor.control.done
.. automethod:: pybricks.ev3devices.Motor.control.stalled
.. automethod:: pybricks.ev3devices.Motor.control.load
.. rubric:: Motor settings
You can only change these settings while the controller is stopped. For
example, you can change them at the start of your program. Alternatively,
first call :meth:`stop() <pybricks.ev3devices.Motor.stop>`, and then change
the settings.
.. automethod:: pybricks.ev3devices.Motor.settings
.. automethod:: pybricks.ev3devices.Motor.control.limits
.. automethod:: pybricks.ev3devices.Motor.control.pid
.. automethod:: pybricks.ev3devices.Motor.control.target_tolerances
.. automethod:: pybricks.ev3devices.Motor.control.stall_tolerances
Touch Sensor
^^^^^^^^^^^^
+6 -6
View File
@@ -44,25 +44,25 @@ Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_off_cityhub.py
../../../examples/pup/hub_cityhub/light_off.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_hsv_cityhub.py
../../../examples/pup/hub_cityhub/light_hsv.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_common/build/light_blink_cityhub.py
../../../examples/pup/hub_cityhub/light_blink.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_animate_cityhub.py
../../../examples/pup/hub_cityhub/light_animate.py
Button and system examples
----------------------------------
@@ -71,10 +71,10 @@ Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/button_single_cityhub.py
../../../examples/pup/hub_cityhub/button_single.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/system_shutdown_cityhub.py
../../../examples/pup/hub_cityhub/system_shutdown.py
-146
View File
@@ -1,146 +0,0 @@
.. pybricks-requirements:: essentialhub
Essential Hub
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. figure:: ../../main/images/essentialhub.png
:height: 15 em
.. note:: Pybricks support for this hub is in beta.
Check the `installation instructions`_ to try it out.
The following functions may change before the final release.
.. _installation instructions: https://pybricks.com/install/
.. autoclass:: pybricks.hubs.EssentialHub
:no-members:
.. rubric:: Using the hub status light
.. automethod:: pybricks.hubs::EssentialHub.light.on
.. automethod:: pybricks.hubs::EssentialHub.light.off
.. automethod:: pybricks.hubs::EssentialHub.light.blink
.. automethod:: pybricks.hubs::EssentialHub.light.animate
.. rubric:: Using the button
.. automethod:: pybricks.hubs::EssentialHub.button.pressed
.. rubric:: Using the IMU
.. automethod:: pybricks.hubs::EssentialHub.imu.up
.. automethod:: pybricks.hubs::EssentialHub.imu.tilt
.. automethod:: pybricks.hubs::EssentialHub.imu.acceleration
.. automethod:: pybricks.hubs::EssentialHub.imu.angular_velocity
.. automethod:: pybricks.hubs::EssentialHub.imu.heading
.. automethod:: pybricks.hubs::EssentialHub.imu.reset_heading
.. rubric:: Using the battery
.. automethod:: pybricks.hubs::EssentialHub.battery.voltage
.. automethod:: pybricks.hubs::EssentialHub.battery.current
.. rubric:: Getting the charger status
.. automethod:: pybricks.hubs::EssentialHub.charger.connected
.. automethod:: pybricks.hubs::EssentialHub.charger.current
.. automethod:: pybricks.hubs::EssentialHub.charger.status
.. rubric:: System control
.. automethod:: pybricks.hubs::EssentialHub.system.set_stop_button
.. automethod:: pybricks.hubs::EssentialHub.system.name
.. automethod:: pybricks.hubs::EssentialHub.system.shutdown
.. automethod:: pybricks.hubs::EssentialHub.system.reset_reason
Status light examples
---------------------
Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_off_essentialhub.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_hsv_essentialhub.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_common/build/light_blink_essentialhub.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_animate_essentialhub.py
IMU examples
---------------
Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_up_essentialhub.py
Reading the tilt value
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_essentialhub.py
Using a custom hub orientation
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_blast_essentialhub.py
Reading acceleration and angular velocity vectors
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_vector_essentialhub.py
Reading acceleration and angular velocity on one axis
*****************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_scalar_essentialhub.py
System examples
----------------------------------
Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/button_single_essentialhub.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/system_shutdown_essentialhub.py
-4
View File
@@ -38,18 +38,14 @@ MINDSTORMS EV3 Brick
.. automethod:: pybricks.hubs::EV3Brick.screen.clear
.. automethod:: pybricks.hubs::EV3Brick.screen.draw_text
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.print
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.set_font
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.load_image
.. automethod:: pybricks.hubs::EV3Brick.screen.draw_image
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.draw_pixel
-20
View File
@@ -12,8 +12,6 @@
movehub
cityhub
technichub
primehub
essentialhub
.. pybricks-classlink:: MoveHub
@@ -32,21 +30,3 @@
.. figure:: ../../main/images/technichub.png
:height: 10 em
:target: technichub.html
.. pybricks-classlink:: PrimeHub
.. figure:: ../../main/images/primehub.png
:height: 10 em
:target: primehub.html
.. pybricks-classlink:: InventorHub PrimeHub
.. figure:: ../../main/images/inventorhub.png
:height: 10 em
:target: primehub.html
.. pybricks-classlink:: EssentialHub
.. figure:: ../../main/images/essentialhub.png
:height: 10 em
:target: essentialhub.html
+5 -9
View File
@@ -27,10 +27,6 @@ Move Hub
.. automethod:: pybricks.hubs::MoveHub.imu.acceleration
.. versionchanged:: 3.2
Changed acceleration units from m/s² to mm/s².
.. rubric:: Using the battery
.. automethod:: pybricks.hubs::MoveHub.battery.voltage
@@ -56,13 +52,13 @@ Turning the light on and off
******************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_off_movehub.py
../../../examples/pup/hub_movehub/light_off.py
Making the light blink
******************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_blink_movehub.py
../../../examples/pup/hub_movehub/light_blink.py
IMU examples
---------------
@@ -71,7 +67,7 @@ Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_up_movehub.py
../../../examples/pup/hub_movehub/imu_up.py
Reading acceleration
**************************************************
@@ -86,10 +82,10 @@ Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/button_single_movehub.py
../../../examples/pup/hub_movehub/button_single.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/system_shutdown_movehub.py
../../../examples/pup/hub_movehub/system_shutdown.py
+12 -30
View File
@@ -6,11 +6,6 @@ Prime Hub / Inventor Hub
.. figure:: ../../main/images/primeinventorhub.png
:height: 15 em
.. note:: Pybricks support for these hubs is in beta.
Check the `installation instructions`_ to try it out.
The following functions may change before the final release.
.. class:: InventorHub
This class is the same as the ``PrimeHub`` class, shown below. Both classes
@@ -78,8 +73,6 @@ Prime Hub / Inventor Hub
.. rubric:: Using the speaker
.. automethod:: pybricks.hubs::PrimeHub.speaker.volume
.. automethod:: pybricks.hubs::PrimeHub.speaker.beep
.. automethod:: pybricks.hubs::PrimeHub.speaker.play_notes
@@ -90,14 +83,6 @@ Prime Hub / Inventor Hub
.. automethod:: pybricks.hubs::PrimeHub.battery.current
.. rubric:: Getting the charger status
.. automethod:: pybricks.hubs::PrimeHub.charger.connected
.. automethod:: pybricks.hubs::PrimeHub.charger.current
.. automethod:: pybricks.hubs::PrimeHub.charger.status
.. rubric:: System control
.. automethod:: pybricks.hubs::PrimeHub.system.set_stop_button
@@ -109,8 +94,8 @@ Prime Hub / Inventor Hub
.. automethod:: pybricks.hubs::PrimeHub.system.reset_reason
.. note:: The examples below use the ``PrimeHub`` class. The examples work fine
on both hubs because they are the identical. If you prefer, you can
change this to ``InventorHub``.
on both hubs because they are the identical. If you prefer, you can
change this to ``InventorHub``.
Status light examples
---------------------
@@ -119,25 +104,25 @@ Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_off_primehub.py
../../../examples/pup/hub_primehub/light_off.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_hsv_primehub.py
../../../examples/pup/hub_primehub/light_hsv.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_common/build/light_blink_primehub.py
../../../examples/pup/hub_primehub/light_blink.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_animate_primehub.py
../../../examples/pup/hub_primehub/light_animate.py
Matrix display examples
-----------------------
@@ -209,32 +194,32 @@ Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_up_primehub.py
../../../examples/pup/hub_primehub/imu_up.py
Reading the tilt value
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_primehub.py
../../../examples/pup/hub_primehub/imu_tilt.py
Using a custom hub orientation
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_blast_primehub.py
../../../examples/pup/hub_primehub/imu_tilt_blast.py
Reading acceleration and angular velocity vectors
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_vector_primehub.py
../../../examples/pup/hub_primehub/imu_read_vector.py
Reading acceleration and angular velocity on one axis
*****************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_scalar_primehub.py
../../../examples/pup/hub_primehub/imu_read_scalar.py
System examples
----------------------------------
@@ -249,7 +234,4 @@ Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/system_shutdown_primehub.py
.. _installation instructions: https://pybricks.com/install/
../../../examples/pup/hub_primehub/system_shutdown.py
+9 -56
View File
@@ -6,8 +6,9 @@ Technic Hub
.. figure:: ../../main/images/technichub.png
:height: 15 em
.. autoclass:: pybricks.hubs.TechnicHub
:no-members:
.. class:: TechnicHub
LEGO® Technic Hub.
.. rubric:: Using the hub status light
@@ -19,20 +20,6 @@ Technic Hub
.. automethod:: pybricks.hubs::TechnicHub.light.animate
.. rubric:: Using the IMU
.. automethod:: pybricks.hubs::TechnicHub.imu.up
.. automethod:: pybricks.hubs::TechnicHub.imu.tilt
.. automethod:: pybricks.hubs::TechnicHub.imu.acceleration
.. automethod:: pybricks.hubs::TechnicHub.imu.angular_velocity
.. automethod:: pybricks.hubs::TechnicHub.imu.heading
.. automethod:: pybricks.hubs::TechnicHub.imu.reset_heading
.. rubric:: Using the battery
.. automethod:: pybricks.hubs::TechnicHub.battery.voltage
@@ -58,59 +45,25 @@ Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_off_technichub.py
../../../examples/pup/hub_technichub/light_off.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_hsv_technichub.py
../../../examples/pup/hub_technichub/light_hsv.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_common/build/light_blink_technichub.py
../../../examples/pup/hub_technichub/light_blink.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_animate_technichub.py
IMU examples
---------------
Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_up_technichub.py
Reading the tilt value
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_technichub.py
Using a custom hub orientation
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_blast_technichub.py
Reading acceleration and angular velocity vectors
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_vector_technichub.py
Reading acceleration and angular velocity on one axis
*****************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_scalar_technichub.py
../../../examples/pup/hub_technichub/light_animate.py
Button and system examples
----------------------------------
@@ -119,10 +72,10 @@ Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/button_single_technichub.py
../../../examples/pup/hub_technichub/button_single.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/system_shutdown_technichub.py
../../../examples/pup/hub_technichub/system_shutdown.py
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

+3 -14
View File
@@ -28,8 +28,8 @@ Pybricks Documentation
.. list-table::
* - **Technic, City, and BOOST Move Hubs**
- **SPIKE Essential/Prime, and MINDSTORMS Inventor Hubs**
* - **Technic Hub, City Hub, BOOST Move Hub**
- **SPIKE Prime Hub / MINDSTORMS Inventor Hub**
* - .. figure:: ../main/images/powereduphubs.png
:target: https://pybricks.com/install/technic-boost-city/
@@ -49,16 +49,6 @@ Pybricks Documentation
.. only:: ide
.. note::
**You are using a new beta version of Pybricks!**
This is great for trying the very latest features, but some things
might not work.
If in doubt, use the `latest stable release`_. Please report any
issues via our `support page`_. Thanks!
To begin, install the Pybricks firmware on your hub. Check
`pybricks.com/install`_ to learn how.
@@ -67,7 +57,7 @@ Pybricks Documentation
.. rubric:: Programmable hubs
.. figure:: ../main/images/hubsoverview.png
.. figure:: ../main/images/powereduphubs.png
:width: 100 %
:target: hubs/index.html
@@ -110,7 +100,6 @@ Pybricks Documentation
parameters/index
tools/index
robotics
geometry
signaltypes
.. toctree::
+3 -3
View File
@@ -9,12 +9,12 @@ EV3 DC Motor
.. figure:: ../../main/images/rcxmotor.png
:width: 40 %
.. autoclass:: pybricks.iodevices.DCMotor
.. autoclass:: pybricks._common.DCMotor
:noindex:
:no-members:
.. automethod:: pybricks.iodevices.DCMotor.dc
.. automethod:: pybricks._common.DCMotor.dc
:noindex:
.. automethod:: pybricks.iodevices.DCMotor.stop
.. automethod:: pybricks._common.DCMotor.stop
:noindex:
-7
View File
@@ -10,7 +10,6 @@
:hidden:
pupdevice
lwp3device
This module has classes for generic input/output devices.
@@ -19,9 +18,3 @@ This module has classes for generic input/output devices.
.. figure:: ../../main/images/sensor_pup.png
:width: 70 %
:target: pupdevice.html
.. pybricks-classlink:: LWP3Device
.. figure:: ../../main/images/powereduphubs.png
:width: 70 %
:target: lwp3device.html
+15 -1
View File
@@ -36,12 +36,26 @@ Basic types
.. pybricks-requirements::
..
_comment: The int class is defined manually because otherwise the classmethod is hidden, see https://github.com/pybricks/pybricks-api/issues/86
.. autoclass:: ubuiltins.int
:no-members:
.. automethod:: ubuiltins.int.to_bytes
.. automethod:: ubuiltins.int.from_bytes
.. classmethod:: from_bytes(bytes: Union[bytes, bytearray], byteorder: Literal["little", "big"]) -> int
Returns the integer represented by the given bytes.
:param bytes: The bytes to convert.
:param byteorder: Determines the byte order used to represent the
integer. If byteorder is ``"big"``, the most significant byte is at
the beginning of the byte sequence. If byteorder is ``"little"``,
the most significant byte is at the end of the byte sequence.
:returns: The integer represented by the bytes.
.. pybricks-requirements::
-6
View File
@@ -45,12 +45,6 @@ NXT Color Sensor
.. automethod:: pybricks.nxtdevices.ColorSensor.rgb
.. rubric:: Advanced color sensing
.. automethod:: pybricks.nxtdevices.ColorSensor.hsv
.. automethod:: pybricks.nxtdevices.ColorSensor.detectable_colors
.. rubric:: Built-in light
This sensor has a built-in light. You can make it red, green, blue, or turn
-20
View File
@@ -26,26 +26,6 @@ Side
.. autoattribute:: pybricks.parameters.Side.RIGHT
:annotation:
Screens or light matrices have only four sides. For those,
``TOP`` is treated the same as ``FRONT``, and ``BOTTOM`` is treated the
same as ``BACK``. The diagrams below define the sides for relevant devices.
**Prime Hub**
.. figure:: ../../main/images/orientation_primehub_label.png
:height: 17 em
**Inventor Hub**
.. figure:: ../../main/images/orientation_inventorhub_label.png
:height: 17 em
**Essential Hub**
.. figure:: ../../main/images/orientation_essentialhub_label.png
:height: 17 em
**Move Hub**
.. figure:: ../../main/images/orientation_movehub_label.png
-6
View File
@@ -82,9 +82,3 @@ Blinking the built-in lights
.. literalinclude::
../../../examples/pup/sensor_color/lights_blink.py
Turning off the lights when the program ends
**********************************************
.. literalinclude::
../../../examples/pup/sensor_color/cleanup.py
-6
View File
@@ -122,12 +122,6 @@ Resetting the measured angle
.. literalinclude::
../../../examples/pup/motor/motor_reset_angle.py
Getting the absolute angle
*******************************************************
.. literalinclude::
../../../examples/pup/motor/motor_absolute.py
Movement examples
-----------------------
+13 -10
View File
@@ -4,12 +4,6 @@ Signals and Units
Many commands allow you to specify arguments in terms of well-known physical
quantities. This page gives an overview of each quantity and its unit.
Numbers
~~~~~~~
.. autodata:: pybricks.parameters.Number
:noindex:
Time
~~~~~~
@@ -62,12 +56,12 @@ use the following table to convert between commonly used units.
.. _acceleration:
rotational acceleration: deg/s²
rotational acceleration: deg/s/s
--------------------------------
Rotational acceleration, or *angular acceleration* describes how fast the
rotational speed changes. This is expressed as the change of the number of
degrees per second, during one second (deg/s²). This is also commonly written
degrees per second, during one second (deg/s/s). This is also commonly written
as :math:`deg/s^2`.
For example, you can adjust the rotational acceleration setting of a ``Motor``
@@ -120,17 +114,26 @@ For example, the speed of a robotic vehicle is expressed in mm/s.
.. _linacceleration:
linear acceleration: mm/s²
linear acceleration: mm/s/s
--------------------------------
Linear acceleration describes how fast the speed changes. This is expressed as
the change of the millimeters per second, during one second (mm/s²).
the change of the millimeters per second, during one second (deg/s/s).
This is also commonly written as :math:`mm/s^2`.
For example, you can adjust the acceleration setting of a
:class:`DriveBase <.robotics.DriveBase>` to change how
smoothly or how quickly it reaches the constant speed set point.
.. _linacceleration_m:
linear acceleration: m/s/s
--------------------------------
As above, but expressed in meters per second squared: :math:`m/s^2`.
This is a more practical unit for large values such as those given by an
accelerometer.
Approximate and relative units
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+5 -5
View File
@@ -9,17 +9,17 @@
from pybricks.messaging import BluetoothMailboxClient, TextMailbox
# This is the name of the remote EV3 or PC we are connecting to.
SERVER = "ev3dev"
SERVER = 'ev3dev'
client = BluetoothMailboxClient()
mbox = TextMailbox("greeting", client)
mbox = TextMailbox('greeting', client)
print("establishing connection...")
print('establishing connection...')
client.connect(SERVER)
print("connected!")
print('connected!')
# In this program, the client sends the first message and then waits for the
# server to reply.
mbox.send("hello!")
mbox.send('hello!')
mbox.wait()
print(mbox.read())
+5 -5
View File
@@ -17,17 +17,17 @@ from pybricks.messaging import BluetoothMailboxClient, TextMailbox
# visible on the EV3. You can skip pairing if you already know the EV3 address.
# This is the address of the server EV3 we are connecting to.
SERVER = "CC:78:AB:D8:4E:F6"
SERVER = 'CC:78:AB:D8:4E:F6'
client = BluetoothMailboxClient()
mbox = TextMailbox("greeting", client)
mbox = TextMailbox('greeting', client)
print("establishing connection...")
print('establishing connection...')
client.connect(SERVER)
print("connected!")
print('connected!')
# In this program, the client sends the first message and then waits for the
# server to reply.
mbox.send("hello!")
mbox.send('hello!')
mbox.wait()
print(mbox.read())
@@ -18,17 +18,17 @@ BDADDR_ANY = ""
def str2ba(string, ba):
"""Convert string to Bluetooth address"""
for i, v in enumerate(string.split(":")):
ba.b[5 - i] = int(v, 16)
for i, v in enumerate(string.split(':')):
ba.b[5-i] = int(v, 16)
def ba2str(ba):
"""Convert Bluetooth address to string"""
string = []
for b in ba.b:
string.append("{:02X}".format(b))
string.append('{:02X}'.format(b))
string.reverse()
return ":".join(string).upper()
return ':'.join(string).upper()
class RFCOMMServer:
@@ -37,7 +37,6 @@ class RFCOMMServer:
This is based on the ``socketserver.SocketServer`` class in the Python
standard library.
"""
request_queue_size = 1
def __init__(self, server_address, RequestHandlerClass):
@@ -89,7 +88,6 @@ class StreamRequestHandler:
This is based on ``socketserver.StreamRequestHandler`` from the Python
standard library.
"""
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
@@ -115,7 +113,6 @@ class ThreadingRFCOMMServer(ThreadingMixIn, RFCOMMServer):
"""Version of :class:`RFCOMMServer` that handles connections in a new
thread.
"""
pass
+19 -33
View File
@@ -5,12 +5,8 @@ from _thread import allocate_lock
from errno import ECONNRESET
from struct import pack, unpack
from .bluetooth import (
BDADDR_ANY,
ThreadingRFCOMMServer,
ThreadingRFCOMMClient,
StreamRequestHandler,
)
from .bluetooth import (BDADDR_ANY, ThreadingRFCOMMServer,
ThreadingRFCOMMClient, StreamRequestHandler)
def resolve(brick):
@@ -103,7 +99,7 @@ class LogicMailbox(Mailbox):
"""
def encode(self, value):
return b"\x01" if value else b"\x00"
return b'\x01' if value else b'\x00'
def decode(self, payload):
return bool(payload[0])
@@ -117,10 +113,10 @@ class NumericMailbox(Mailbox):
"""
def encode(self, value):
return pack("<f", value)
return pack('<f', value)
def decode(self, payload):
return unpack("<f", payload)[0]
return unpack('<f', payload)[0]
class TextMailbox(Mailbox):
@@ -131,10 +127,10 @@ class TextMailbox(Mailbox):
"""
def encode(self, value):
return ("{}\0".format(value)).encode("utf-8")
return ('{}\0'.format(value)).encode('utf-8')
def decode(self, payload):
return payload.decode().strip("\0")
return payload.decode().strip('\0')
# EV3 standard firmware is hard-coded to use channel 1
@@ -159,16 +155,16 @@ class MailboxHandler(StreamRequestHandler):
if ex.args[0] == ECONNRESET:
break
raise
(size,) = unpack("<H", buf)
size, = unpack('<H', buf)
buf = self.rfile.recv(size)
msg_count, cmd_type, cmd, name_size = unpack("<HBBB", buf[0:5])
msg_count, cmd_type, cmd, name_size = unpack('<HBBB', buf[0:5])
if cmd_type != SYSTEM_COMMAND_NO_REPLY:
raise ValueError("Bad message type")
raise ValueError('Bad message type')
if cmd != WRITEMAILBOX:
raise ValueError("Bad command")
mbox = buf[5 : 5 + name_size].decode().strip("\0")
(data_size,) = unpack("<H", buf[5 + name_size : 7 + name_size])
data = buf[7 + name_size : 7 + name_size + data_size]
raise ValueError('Bad command')
mbox = buf[5:5+name_size].decode().strip('\0')
data_size, = unpack('<H', buf[5+name_size:7+name_size])
data = buf[7+name_size:7+name_size+data_size]
with self.server._lock:
self.server._mailboxes[mbox] = data
@@ -220,18 +216,9 @@ class MailboxHandlerMixIn:
mbox_len = len(mbox) + 1
payload_len = len(payload)
send_len = 7 + mbox_len + payload_len
fmt = "<HHBBB{}sH{}s".format(mbox_len, payload_len)
data = pack(
fmt,
send_len,
1,
SYSTEM_COMMAND_NO_REPLY,
WRITEMAILBOX,
mbox_len,
mbox.encode("utf-8"),
payload_len,
payload,
)
fmt = '<HHBBB{}sH{}s'.format(mbox_len, payload_len)
data = pack(fmt, send_len, 1, SYSTEM_COMMAND_NO_REPLY, WRITEMAILBOX,
mbox_len, mbox.encode('utf-8'), payload_len, payload)
with self._lock:
if brick is None:
for client in self._clients.values():
@@ -268,8 +255,7 @@ class BluetoothMailboxServer(MailboxHandlerMixIn, ThreadingRFCOMMServer):
"""
super().__init__()
super(ThreadingRFCOMMServer, self).__init__(
(BDADDR_ANY, EV3_RFCOMM_CHANNEL), MailboxHandler
)
(BDADDR_ANY, EV3_RFCOMM_CHANNEL), MailboxHandler)
def wait_for_connection(self, count=1):
"""Waits for a :class:`BluetoothMailboxClient` on a remote device to
@@ -340,7 +326,7 @@ class BluetoothMailboxClient(MailboxHandlerMixIn):
raise ValueError('no paired devices matching "{}"'.format(brick))
client = MailboxRFCOMMClient(self, addr)
if self._clients.setdefault(addr, client) is not client:
raise ValueError("connection with this address already exists")
raise ValueError('connection with this address already exists')
try:
client.handle_request()
except Exception:
@@ -1,9 +1,15 @@
from uctypes import addressof, sizeof, struct
from usocket import socket, SOCK_STREAM
from _thread import start_new_thread
from pybricks.bluetooth import str2ba, sockaddr_rc, AF_BLUETOOTH, BTPROTO_RFCOMM
from pybricks.bluetooth import (
str2ba,
sockaddr_rc,
AF_BLUETOOTH,
BTPROTO_RFCOMM
)
from pybricks.tools import wait, StopWatch
@@ -19,7 +25,7 @@ def get_bluetooth_rfcomm_socket(address, channel):
return sock
class SpikePrimeStreamReader:
class SpikePrimeStreamReader():
def __init__(self, address):
try:
@@ -50,8 +56,8 @@ class SpikePrimeStreamReader:
break
try:
data = eval(raw)
if data["m"] == 0:
self._values = data["p"]
if data['m'] == 0:
self._values = data['p']
except (SyntaxError, KeyError):
pass
@@ -59,8 +65,8 @@ class SpikePrimeStreamReader:
return self._values
def device(self, port):
if "A" <= port <= "F":
return self.values()[ord(port) - ord("A")][1]
if 'A' <= port <= 'F':
return self.values()[ord(port)-ord('A')][1]
else:
raise ValueError
+1 -1
View File
@@ -9,7 +9,7 @@ ev3 = EV3Brick()
ev3.speaker.beep()
# Create the connection. See README.md to find the address for your SPIKE hub.
spike = SpikePrimeStreamReader("F4:84:4C:AA:C8:A4")
spike = SpikePrimeStreamReader('F4:84:4C:AA:C8:A4')
# Now you can simply read values!
for i in range(100):
+2 -2
View File
@@ -12,7 +12,7 @@ ev3 = EV3Brick()
ev3.speaker.beep()
# Create the connection. See README.md to find the address for your SPIKE hub.
spike = SpikePrimeStreamReader("F4:84:4C:AA:C8:A4")
spike = SpikePrimeStreamReader('F4:84:4C:AA:C8:A4')
# Initialize the motors and drive base
left_motor = Motor(Port.B)
@@ -24,5 +24,5 @@ while True:
yaw, pitch, roll = spike.orientation()
# Set speed and turn rate based on orientation
robot.drive(-pitch * 6, roll * 2)
robot.drive(-pitch*6, roll*2)
wait(20)
+4 -4
View File
@@ -9,15 +9,15 @@
from pybricks.messaging import BluetoothMailboxServer, TextMailbox
server = BluetoothMailboxServer()
mbox = TextMailbox("greeting", server)
mbox = TextMailbox('greeting', server)
# The server must be started before the client!
print("waiting for connection...")
print('waiting for connection...')
server.wait_for_connection()
print("connected!")
print('connected!')
# In this program, the server waits for the client to send the first message
# and then sends a reply.
mbox.wait()
print(mbox.read())
mbox.send("hello to you!")
mbox.send('hello to you!')
+1 -1
View File
@@ -8,7 +8,7 @@ def wait_for_button(ev3):
"""
# Show a picture of the buttons on the screen.
ev3.screen.load_image("buttons.png")
ev3.screen.load_image('buttons.png')
# Tip: add text or icons to the image to help you
# remember what each button will do in your program.
+1 -1
View File
@@ -8,7 +8,7 @@ from pybricks.tools import DataLog, StopWatch, wait
# log_2020_02_13_10_07_44_431260.csv
# * You can optionally specify the titles of your data columns. For example,
# if you want to record the motor angles at a given time, you could do:
data = DataLog("time", "angle")
data = DataLog('time', 'angle')
# Initialize a motor and make it move
wheel = Motor(Port.B)
+4 -4
View File
@@ -3,13 +3,13 @@ from pybricks.parameters import Color
from pybricks.tools import DataLog
# Create a data log file called my_file.txt
data = DataLog("time", "angle", name="my_file", timestamp=False, extension="txt")
data = DataLog('time', 'angle', name='my_file', timestamp=False, extension='txt')
# The log method uses the print() method to add a line of text.
# So, you can do much more than saving numbers. For example:
data.log("Temperature", 25)
data.log("Sunday", "Monday", "Tuesday")
data.log({"Kiwi": Color.GREEN}, {"Banana": Color.YELLOW})
data.log('Temperature', 25)
data.log('Sunday', 'Monday', 'Tuesday')
data.log({'Kiwi': Color.GREEN}, {'Banana': Color.YELLOW})
# You can upload the file to your computer, but you can also print the data:
print(data)
+4 -4
View File
@@ -13,22 +13,22 @@ class MySensor(Ev3devSensor):
super().__init__(port)
# Get the sysfs path.
self.path = "/sys/class/lego-sensor/sensor" + str(self.sensor_index)
self.path = '/sys/class/lego-sensor/sensor' + str(self.sensor_index)
def get_modes(self):
"""Get a list of mode strings so we don't have to look them up."""
# The path of the modes file.
modes_path = self.path + "/modes"
modes_path = self.path + '/modes'
# Open the modes file.
with open(modes_path, "r") as m:
with open(modes_path, 'r') as m:
# Read the contents.
contents = m.read()
# Strip the newline symbol, and split at every space symbol.
return contents.strip().split(" ")
return contents.strip().split(' ')
# Initialize the sensor
+2 -2
View File
@@ -10,10 +10,10 @@ sensor = Ev3devSensor(Port.S3)
while True:
# Read the raw RGB values
r, g, b = sensor.read("RGB-RAW")
r, g, b = sensor.read('RGB-RAW')
# Print results
print("R: {0}\t G: {1}\t B: {2}".format(r, g, b))
print('R: {0}\t G: {1}\t B: {2}'.format(r, g, b))
# Wait
wait(200)
+3 -3
View File
@@ -10,7 +10,7 @@ ev3 = EV3Brick()
device = I2CDevice(Port.S2, 0xD2 >> 1)
# Recommended for reading
(result,) = device.read(reg=0x0F, length=1)
result, = device.read(reg=0x0F, length=1)
# Read 1 byte from no particular register:
device.read(reg=None, length=1)
@@ -23,10 +23,10 @@ device.read(reg=None, length=0)
# can choose to skip the register or data as follows:
# Recommended for writing:
device.write(reg=0x22, data=b"\x08")
device.write(reg=0x22, data=b'\x08')
# Write 1 byte to no particular register:
device.write(reg=None, data=b"\x08")
device.write(reg=None, data=b'\x08')
# Write 0 bytes to a particular register:
device.write(reg=0x08, data=None)
+2 -3
View File
@@ -21,7 +21,7 @@ in_file = open(infile_path, "rb")
# Define the format the event data will be read.
# https://docs.python.org/3/library/struct.html#format-characters
FORMAT = "llHHi"
FORMAT = 'llHHi'
EVENT_SIZE = struct.calcsize(FORMAT)
event = in_file.read(EVENT_SIZE)
@@ -30,11 +30,10 @@ event = in_file.read(EVENT_SIZE)
# numbers (-100 to 100)
def scale(val, src, dst):
result = float(val - src[0]) / (src[1] - src[0])
result = (float(val - src[0]) / (src[1] - src[0]))
result = result * (dst[1] - dst[0]) + dst[0]
return result
# Create a loop to react to events
# This loop reacte to all main PS4 button and stick events. I have left out
# buttons like share and options, but can easily be added in by referring
+1 -1
View File
@@ -7,7 +7,7 @@ from pybricks.tools import wait
class RCXTouchSensor(AnalogSensor):
def pressed(self):
return self.resistance() < 50 * 1000
return self.resistance() < 50*1000
ev3 = EV3Brick()
+13 -41
View File
@@ -15,24 +15,12 @@ ev3 = EV3Brick()
# SPLIT SCREEN ################################################################
# Make a sub-image for the left half of the screen
left = Image(
ev3.screen,
sub=True,
x1=0,
y1=0,
x2=ev3.screen.width // 2 - 1,
y2=ev3.screen.height - 1,
)
left = Image(ev3.screen, sub=True, x1=0, y1=0,
x2=ev3.screen.width // 2 - 1, y2=ev3.screen.height - 1)
# Make a sub-image for the right half of the screen
right = Image(
ev3.screen,
sub=True,
x1=ev3.screen.width // 2,
y1=0,
x2=ev3.screen.width - 1,
y2=ev3.screen.height - 1,
)
right = Image(ev3.screen, sub=True, x1=ev3.screen.width // 2, y1=0,
x2=ev3.screen.width - 1, y2=ev3.screen.height - 1)
# Use a monospaced font so that text is vertically aligned when we print
right.set_font(Font(size=8, monospace=True))
@@ -65,7 +53,7 @@ for t in range(200):
# Print every 10th value on right side
if t % 10 == 0:
right.print("{:10.2f}{:10.2f}".format(x1, y1))
right.print('{:10.2f}{:10.2f}'.format(x1, y1))
wait(100)
@@ -76,8 +64,8 @@ for t in range(200):
buf = Image(ev3.screen)
# Load images from file
bg = Image("background.png")
sprite = Image("sprite.png")
bg = Image('background.png')
sprite = Image('sprite.png')
# Number of cells in each sprite animation
NUM_CELLS = 8
@@ -87,28 +75,12 @@ CELL_WIDTH, CELL_HEIGHT = 75, 100
# Get sub-images for each individual cell
# This is more efficient that loading individual images
walk_right = [
Image(
sprite,
sub=True,
x1=x * CELL_WIDTH,
y1=0,
x2=(x + 1) * CELL_WIDTH - 1,
y2=CELL_HEIGHT - 1,
)
for x in range(NUM_CELLS)
]
walk_left = [
Image(
sprite,
sub=True,
x1=x * CELL_WIDTH,
y1=CELL_HEIGHT,
x2=(x + 1) * CELL_WIDTH - 1,
y2=2 * CELL_HEIGHT - 1,
)
for x in range(NUM_CELLS)
]
walk_right = [Image(sprite, sub=True, x1=x * CELL_WIDTH, y1=0,
x2=(x + 1) * CELL_WIDTH - 1, y2=CELL_HEIGHT - 1)
for x in range(NUM_CELLS)]
walk_left = [Image(sprite, sub=True, x1=x * CELL_WIDTH, y1=CELL_HEIGHT,
x2=(x + 1) * CELL_WIDTH - 1, y2=2 * CELL_HEIGHT - 1)
for x in range(NUM_CELLS)]
# Walk from left to right
+5 -5
View File
@@ -8,7 +8,7 @@ from pybricks.media.ev3dev import Font
# load them once at the beginning of the program like this:
tiny_font = Font(size=6)
big_font = Font(size=24, bold=True)
chinese_font = Font(size=24, lang="zh-cn")
chinese_font = Font(size=24, lang='zh-cn')
# Initialize the EV3
@@ -16,19 +16,19 @@ ev3 = EV3Brick()
# Say hello
ev3.screen.print("Hello!")
ev3.screen.print('Hello!')
# Say tiny hello
ev3.screen.set_font(tiny_font)
ev3.screen.print("hello")
ev3.screen.print('hello')
# Say big hello
ev3.screen.set_font(big_font)
ev3.screen.print("HELLO")
ev3.screen.print('HELLO')
# Say Chinese hello
ev3.screen.set_font(chinese_font)
ev3.screen.print("你好")
ev3.screen.print('你好')
# Wait some time to look at the screen
wait(5000)
+6 -20
View File
@@ -26,23 +26,9 @@ wait(1000)
# PLAY NOTES ##################################################################
# Twinkle, Twinkle Little Star
A = [
"C4/4",
"C4/4",
"G4/4",
"G4/4",
"A4/4",
"A4/4",
"G4/2",
"F4/4",
"F4/4",
"E4/4",
"E4/4",
"D4/4",
"D4/4",
"C4/2",
]
B = ["G4/4", "G4/4", "F4/4", "F4/4", "E4/4", "E4/4", "D4/2"] * 2
A = ['C4/4', 'C4/4', 'G4/4', 'G4/4', 'A4/4', 'A4/4', 'G4/2',
'F4/4', 'F4/4', 'E4/4', 'E4/4', 'D4/4', 'D4/4', 'C4/2']
B = ['G4/4', 'G4/4', 'F4/4', 'F4/4', 'E4/4', 'E4/4', 'D4/2'] * 2
TWINKLE = A + B + A
ev3.speaker.play_notes(TWINKLE)
@@ -60,10 +46,10 @@ wait(1000)
# TEXT TO SPEECH ##############################################################
# Say something in English
ev3.speaker.say("I am am E V 3. Pleased to meet you.")
ev3.speaker.say('I am am E V 3. Pleased to meet you.')
# Say something in Danish + female
ev3.speaker.set_speech_options(voice="da+f5")
ev3.speaker.say("Leg godt!")
ev3.speaker.set_speech_options(voice='da+f5')
ev3.speaker.say('Leg godt!')
wait(1000)
+1 -1
View File
@@ -11,7 +11,7 @@ ev3 = EV3Brick()
ser = UARTDevice(Port.S2, baudrate=115200)
# Write some data
ser.write(b"\r\nHello, world!\r\n")
ser.write(b'\r\nHello, world!\r\n')
# Play a sound while we wait for some data
for i in range(3):
@@ -10,8 +10,8 @@ def convert_raw_to_temperature(voltage):
# Convert the raw voltage to the NTC resistance
# according to the Vernier Adapter EV3 block.
counts = voltage / 5000 * 4096
ntc = 15000 * (counts) / (4130 - counts)
counts = voltage/5000*4096
ntc = 15000*(counts)/(4130-counts)
# Handle log(0) safely: make sure that ntc value is positive.
if ntc <= 0:
@@ -21,7 +21,7 @@ def convert_raw_to_temperature(voltage):
K0 = 1.02119e-3
K1 = 2.22468e-4
K2 = 1.33342e-7
return 1 / (K0 + K1 * log(ntc) + K2 * log(ntc) ** 3)
return 1/(K0 + K1*log(ntc) + K2*log(ntc)**3)
# Initialize the adapter on port 1
@@ -1,10 +1,9 @@
# ThisHub = MoveHub CityHub TechnicHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import CityHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = ThisHub()
hub = CityHub()
# Disable the stop button.
hub.system.set_stop_button(None)
@@ -1,11 +1,10 @@
# ThisHub = CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
from umath import sin, pi
# Initialize the hub.
hub = ThisHub()
hub = CityHub()
# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
@@ -13,11 +12,12 @@ hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
wait(10000)
# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
wait(10000)
# Cycle through a rainbow of colors.
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
wait(10000)
@@ -1,10 +1,9 @@
# ThisHub = MoveHub CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = ThisHub()
hub = CityHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
@@ -1,10 +1,9 @@
# ThisHub = CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = ThisHub()
hub = CityHub()
# Show the color at 30% brightness.
hub.light.on(Color.RED * 0.3)
@@ -1,10 +1,9 @@
# ThisHub = MoveHub CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = ThisHub()
hub = CityHub()
# Turn the light on and off 5 times.
for i in range(5):
@@ -1,9 +1,8 @@
# ThisHub = MoveHub CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import CityHub
from pybricks.tools import wait
# Initialize the hub.
hub = ThisHub()
hub = CityHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
-39
View File
@@ -1,39 +0,0 @@
#!/usr/bin/env python3
"""Generates hub-specific examples from common template script."""
import pathlib
# Make build directory.
dir_path = pathlib.Path(__file__).parent
build_path = dir_path / "build"
build_path.mkdir(exist_ok=True)
# Get list of scripts to be parsed.
file_paths = [f for f in dir_path.glob("*.py") if f.stem != "make_examples"]
# Go through all template scripts
for file_path in file_paths:
with open(file_path) as template:
# First line contains hub info
hubs = template.readline().strip().split()[3:]
print("Converting", template.name, "to", hubs)
for hub in hubs:
# Path to hub-specific output script.
gen_path = build_path / (file_path.stem + "_" + hub.lower() + ".py")
# Reset source script and skip over header.
template.seek(0)
template.readline()
# Open destination script:
with open(gen_path, "w") as dest_file:
# Read script line by line.
for line in template.readlines():
# Replace hub name if present.
dest_file.writelines(line.replace("ThisHub", hub))
+25
View File
@@ -0,0 +1,25 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = MoveHub()
# Disable the stop button.
hub.system.set_stop_button(None)
# Check the button for 5 seconds.
watch = StopWatch()
while watch.time() < 5000:
# Set light to green if pressed, else red.
if hub.button.pressed():
hub.light.on(Color.GREEN)
else:
hub.light.on(Color.RED)
# Enable the stop button again.
hub.system.set_stop_button(Button.CENTER)
# Now you can press the stop button as usual.
wait(5000)
@@ -1,10 +1,9 @@
# ThisHub = TechnicHub PrimeHub MoveHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import MoveHub
from pybricks.parameters import Color, Side
from pybricks.tools import wait
# Initialize the hub.
hub = ThisHub()
hub = MoveHub()
# Define colors for each side in a dictionary.
SIDE_COLORS = {
+16
View File
@@ -0,0 +1,16 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = MoveHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
wait(10000)
# Keep blinking green slowly and then quickly.
hub.light.blink(Color.GREEN, [500, 500, 50, 900])
wait(10000)
+15
View File
@@ -0,0 +1,15 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = MoveHub()
# Turn the light on and off 5 times.
for i in range(5):
hub.light.on(Color.RED)
wait(1000)
hub.light.off()
wait(500)
@@ -0,0 +1,12 @@
from pybricks.hubs import MoveHub
from pybricks.tools import wait
# Initialize the hub.
hub = MoveHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
wait(100)
# Shut the hub down.
hub.system.shutdown()
+1 -1
View File
@@ -12,7 +12,7 @@ hub.light.off()
brightness = list(range(0, 100, 4)) + list(range(100, 0, -4))
# Create an animation of the heart icon with changing brightness.
hub.display.animate([Icon.HEART * i / 100 for i in brightness], 30)
hub.display.animate([Icon.HEART * i/100 for i in brightness], 30)
# The animation repeats in the background. Here we just wait.
while True:
@@ -12,15 +12,15 @@ while True:
# Start with random left brow: up or down.
if randint(0, 100) < 70:
brows = Icon.EYE_LEFT_BROW * 0.5
brows = Icon.EYE_LEFT_BROW*0.5
else:
brows = Icon.EYE_LEFT_BROW_UP * 0.5
brows = Icon.EYE_LEFT_BROW_UP*0.5
# Add random right brow: up or down.
if randint(0, 100) < 70:
brows += Icon.EYE_RIGHT_BROW * 0.5
brows += Icon.EYE_RIGHT_BROW*0.5
else:
brows += Icon.EYE_RIGHT_BROW_UP * 0.5
brows += Icon.EYE_RIGHT_BROW_UP*0.5
for i in range(3):
# Display eyes open plus the random brows.
@@ -28,7 +28,5 @@ while True:
wait(2000)
# Display eyes blinked plus the random brows.
hub.display.image(
Icon.EYE_LEFT_BLINK * 0.7 + Icon.EYE_RIGHT_BLINK * 0.7 + brows
)
hub.display.image(Icon.EYE_LEFT_BLINK*0.7 + Icon.EYE_RIGHT_BLINK*0.7 + brows)
wait(200)
+7 -9
View File
@@ -6,15 +6,13 @@ from pybricks.geometry import Matrix
hub = PrimeHub()
# Make a square that is bright on the outside and faint in the middle.
SQUARE = Matrix(
[
[100, 100, 100, 100, 100],
[100, 50, 50, 50, 100],
[100, 50, 0, 50, 100],
[100, 50, 50, 50, 100],
[100, 100, 100, 100, 100],
]
)
SQUARE = Matrix([
[100, 100, 100, 100, 100],
[100, 50, 50, 50, 100],
[100, 50, 0, 50, 100],
[100, 50, 50, 50, 100],
[100, 100, 100, 100, 100],
])
# Display the square.
hub.display.image(SQUARE)
+2 -2
View File
@@ -5,8 +5,8 @@ from pybricks.tools import wait
hub = PrimeHub()
# Display the letter A for two seconds.
hub.display.char("A")
hub.display.char('A')
wait(2000)
# Display text, one letter at a time.
hub.display.text("Hello, world!")
hub.display.text('Hello, world!')
@@ -1,10 +1,9 @@
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub.
hub = ThisHub()
hub = PrimeHub()
# Get the acceleration or angular_velocity along a single axis.
# If you need only one value, this is more memory efficient.
@@ -1,12 +1,11 @@
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
# Initialize the hub.
hub = ThisHub()
hub = PrimeHub()
# Get the acceleration vector in g's.
print(hub.imu.acceleration() / 9810)
# Get the acceleration vector.
print(hub.imu.acceleration())
# Get the angular velocity vector.
print(hub.imu.angular_velocity())
@@ -1,9 +1,8 @@
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
# Initialize the hub.
hub = ThisHub()
hub = PrimeHub()
while True:
# Read the tilt values.
@@ -1,12 +1,11 @@
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub. In this case, specify that the hub is mounted with the
# top side facing forward and the front side facing to the right.
# For example, this is how the hub is mounted in BLAST in the 51515 set.
hub = ThisHub(top_side=Axis.X, front_side=-Axis.Y)
hub = PrimeHub(top_side=Axis.X, front_side=-Axis.Y)
while True:
# Read the tilt values. Now, the values are 0 when BLAST stands upright.
+29
View File
@@ -0,0 +1,29 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color, Side
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Define colors for each side in a dictionary.
SIDE_COLORS = {
Side.TOP: Color.RED,
Side.BOTTOM: Color.BLUE,
Side.LEFT: Color.GREEN,
Side.RIGHT: Color.YELLOW,
Side.FRONT: Color.MAGENTA,
Side.BACK: Color.BLACK,
}
# Keep updating the color based on detected up side.
while True:
# Check which side of the hub is up.
up_side = hub.imu.up()
# Change the color based on the side.
hub.light.on(SIDE_COLORS[up_side])
# Also print the result.
print(up_side)
wait(50)
@@ -0,0 +1,23 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
from umath import sin, pi
# Initialize the hub.
hub = PrimeHub()
# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
wait(10000)
# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
wait(10000)
# Cycle through a rainbow of colors.
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
wait(10000)
+16
View File
@@ -0,0 +1,16 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = PrimeHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
wait(10000)
# Keep blinking green slowly and then quickly.
hub.light.blink(Color.GREEN, [500, 500, 50, 900])
wait(10000)
+21
View File
@@ -0,0 +1,21 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Show the color at 30% brightness.
hub.light.on(Color.RED * 0.3)
wait(2000)
# Use your own custom color.
hub.light.on(Color(h=30, s=100, v=50))
wait(2000)
# Go through all the colors.
for hue in range(360):
hub.light.on(Color(hue))
wait(10)
+15
View File
@@ -0,0 +1,15 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Turn the light on and off 5 times.
for i in range(5):
hub.light.on(Color.RED)
wait(1000)
hub.light.off()
wait(500)
@@ -0,0 +1,12 @@
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
wait(100)
# Shut the hub down.
hub.system.shutdown()
+26
View File
@@ -0,0 +1,26 @@
# ExampleHub = MoveHub CityHub TechnicHub
from pybricks.hubs import ExampleHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = ExampleHub()
# Disable the stop button.
hub.system.set_stop_button(None)
# Check the button for 5 seconds.
watch = StopWatch()
while watch.time() < 5000:
# Set light to green if pressed, else red.
if hub.button.pressed():
hub.light.on(Color.GREEN)
else:
hub.light.on(Color.RED)
# Enable the stop button again.
hub.system.set_stop_button(Button.CENTER)
# Now you can press the stop button as usual.
wait(5000)
@@ -0,0 +1,21 @@
# ExampleHub = TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub.
hub = ExampleHub()
# Get the acceleration or angular_velocity along a single axis.
# If you need only one value, this is more memory efficient.
while True:
# Read the forward acceleration.
forward_acceleration = hub.imu.acceleration(Axis.X)
# Read the yaw rate.
yaw_rate = hub.imu.angular_velocity(Axis.Z)
# Print the yaw rate.
print(yaw_rate)
wait(100)
@@ -0,0 +1,15 @@
# ExampleHub = TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
# Get the acceleration vector.
print(hub.imu.acceleration())
# Get the angular velocity vector.
print(hub.imu.angular_velocity())
# Wait so we can see what we printed
wait(5000)
+14
View File
@@ -0,0 +1,14 @@
# ExampleHub = TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
while True:
# Read the tilt values.
pitch, roll = hub.imu.tilt()
# Print the result.
print(pitch, roll)
wait(200)
+18
View File
@@ -0,0 +1,18 @@
# ExampleHub = TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub. In this case, specify that the hub is mounted with the
# top side facing forward and the front side facing to the right.
# For example, this is how the hub is mounted in BLAST in the 51515 set.
hub = ExampleHub(top_side=Axis.X, front_side=-Axis.Y)
while True:
# Read the tilt values. Now, the values are 0 when BLAST stands upright.
# Leaning forward gives positive pitch. Leaning right gives positive roll.
pitch, roll = hub.imu.tilt()
# Print the result.
print(pitch, roll)
wait(200)
+30
View File
@@ -0,0 +1,30 @@
# ExampleHub = TechnicHub PrimeHub MoveHub
from pybricks.hubs import ExampleHub
from pybricks.parameters import Color, Side
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
# Define colors for each side in a dictionary.
SIDE_COLORS = {
Side.TOP: Color.RED,
Side.BOTTOM: Color.BLUE,
Side.LEFT: Color.GREEN,
Side.RIGHT: Color.YELLOW,
Side.FRONT: Color.MAGENTA,
Side.BACK: Color.BLACK,
}
# Keep updating the color based on detected up side.
while True:
# Check which side of the hub is up.
up_side = hub.imu.up()
# Change the color based on the side.
hub.light.on(SIDE_COLORS[up_side])
# Also print the result.
print(up_side)
wait(50)
+24
View File
@@ -0,0 +1,24 @@
# ExampleHub = CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.parameters import Color
from pybricks.tools import wait
from umath import sin, pi
# Initialize the hub.
hub = ExampleHub()
# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
wait(10000)
# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
wait(10000)
# Cycle through a rainbow of colors.
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
wait(10000)
+17
View File
@@ -0,0 +1,17 @@
# ExampleHub = MoveHub CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = ExampleHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
wait(10000)
# Keep blinking green slowly and then quickly.
hub.light.blink(Color.GREEN, [500, 500, 50, 900])
wait(10000)
+22
View File
@@ -0,0 +1,22 @@
# ExampleHub = CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
# Show the color at 30% brightness.
hub.light.on(Color.RED * 0.3)
wait(2000)
# Use your own custom color.
hub.light.on(Color(h=30, s=100, v=50))
wait(2000)
# Go through all the colors.
for hue in range(360):
hub.light.on(Color(hue))
wait(10)
+16
View File
@@ -0,0 +1,16 @@
# ExampleHub = MoveHub CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
# Turn the light on and off 5 times.
for i in range(5):
hub.light.on(Color.RED)
wait(1000)
hub.light.off()
wait(500)
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Replaces all instances of ExampleHub in template with actual hub names."""
import os
# Get list of scripts to be parsed
script_names = [f for f in os.listdir('.') if f != 'make_shared_examples.py']
# Go through all template scripts
for script in (open(f, 'r') for f in script_names):
# First line contains hub info
hubs = script.readline().strip().split()[3:]
print("Converting", script.name, "for", hubs)
for hub in hubs:
# Determine path to the hub
hub_path = os.path.join('..', 'hub_' + hub.lower())
# Reset source script
script.seek(0)
script.readline()
# Open destination script:
with open(os.path.join(hub_path, script.name), 'w') as dest_file:
# Read script line by line
for line in script.readlines():
# Replace hub name if present
dest_file.writelines(line.replace('ExampleHub', hub))
@@ -0,0 +1,13 @@
# ExampleHub = MoveHub CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
wait(100)
# Shut the hub down.
hub.system.shutdown()
@@ -0,0 +1,25 @@
from pybricks.hubs import TechnicHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = TechnicHub()
# Disable the stop button.
hub.system.set_stop_button(None)
# Check the button for 5 seconds.
watch = StopWatch()
while watch.time() < 5000:
# Set light to green if pressed, else red.
if hub.button.pressed():
hub.light.on(Color.GREEN)
else:
hub.light.on(Color.RED)
# Enable the stop button again.
hub.system.set_stop_button(Button.CENTER)
# Now you can press the stop button as usual.
wait(5000)
@@ -0,0 +1,20 @@
from pybricks.hubs import TechnicHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub.
hub = TechnicHub()
# Get the acceleration or angular_velocity along a single axis.
# If you need only one value, this is more memory efficient.
while True:
# Read the forward acceleration.
forward_acceleration = hub.imu.acceleration(Axis.X)
# Read the yaw rate.
yaw_rate = hub.imu.angular_velocity(Axis.Z)
# Print the yaw rate.
print(yaw_rate)
wait(100)
@@ -0,0 +1,14 @@
from pybricks.hubs import TechnicHub
from pybricks.tools import wait
# Initialize the hub.
hub = TechnicHub()
# Get the acceleration vector.
print(hub.imu.acceleration())
# Get the angular velocity vector.
print(hub.imu.angular_velocity())
# Wait so we can see what we printed
wait(5000)
+13
View File
@@ -0,0 +1,13 @@
from pybricks.hubs import TechnicHub
from pybricks.tools import wait
# Initialize the hub.
hub = TechnicHub()
while True:
# Read the tilt values.
pitch, roll = hub.imu.tilt()
# Print the result.
print(pitch, roll)
wait(200)

Some files were not shown because too many files have changed in this diff Show More