docs: self host docs

Move doc hosting from readthedocs to espressif servers

Update CI, Sphinx configs and add IDF Sphinx theme
This commit is contained in:
Marius Vikhammer 2021-07-30 19:13:08 +08:00 committed by Krzysztof Budzynski
parent ee3e817a93
commit 38b0870fab
25 changed files with 2348 additions and 949 deletions

View File

@ -49,8 +49,10 @@ variables:
CI_AUTO_TEST_SCRIPT_REPO_URL: "https://gitlab-ci-token:${BOT_TOKEN}@${CI_SERVER_HOST}:${CI_SERVER_PORT}/qa/auto_test_script.git"
CI_AUTO_TEST_SCRIPT_REPO_BRANCH: "ci/v3.1"
# Versioned esp-idf-doc env image to use for all document building jobs
ESP_IDF_DOC_ENV_IMAGE: "$CI_DOCKER_REGISTRY/esp-idf-doc-env:v5"
# Versioned esp-idf-doc env image to use for all document building jobs
ESP_IDF_DOC_ENV_IMAGE: "$CI_DOCKER_REGISTRY/esp-idf-doc-env:v7"
# before each job, we need to check if this job is filtered by bot stage/job filter
.apply_bot_filter: &apply_bot_filter
@ -284,25 +286,18 @@ build_examples_cmake:
- mkdir -p ${LOG_PATH}
- ${IDF_PATH}/tools/ci/build_examples_cmake.sh
build_docs:
.build_docs_template: &build_docs_template
stage: build
image: $CI_DOCKER_REGISTRY/esp32-ci-env$BOT_DOCKER_IMAGE_TAG
image: $ESP_IDF_DOC_ENV_IMAGE
tags:
- build_docs
artifacts:
when: always
paths:
# English version of documentation
- docs/en/doxygen-warning-log.txt
- docs/en/sphinx-warning-log.txt
- docs/en/sphinx-warning-log-sanitized.txt
- docs/en/_build/html
- docs/sphinx-err-*
# Chinese version of documentation
- docs/zh_CN/doxygen-warning-log.txt
- docs/zh_CN/sphinx-warning-log.txt
- docs/zh_CN/sphinx-warning-log-sanitized.txt
- docs/zh_CN/_build/html
- docs/*/*.txt
- docs/_build/*/html/*
- docs/_build/*/latex/*
expire_in: 4 days
only:
variables:
@ -310,17 +305,32 @@ build_docs:
- $BOT_LABEL_BUILD
- $BOT_LABEL_BUILD_DOCS
- $BOT_LABEL_REGULAR_TEST
dependencies: []
script:
# Active python 3.6.10 env as this is where Sphinx is installed
- source /opt/pyenv/activate && pyenv global 3.6.10
# Setup a build dir with both languages to simplify deployment
- cd docs
- mkdir -p _build/$DOCLANG
- ./check_lang_folder_sync.sh
- cd en
- cd $DOCLANG
- make gh-linkcheck
- make html
- ../check_doc_warnings.sh
- cd ../zh_CN
- make gh-linkcheck
- make html
- make latexpdf LATEXMKOPTS="--f --interaction=nonstopmode --quiet --outdir=build"
- ../check_doc_warnings.sh
- mv -f _build/* ../_build/$DOCLANG
build_docs_en:
extends: .build_docs_template
variables:
DOCLANG: "en"
build_docs_zh_CN:
extends: .build_docs_template
variables:
DOCLANG: "zh_CN"
.check_job_template: &check_job_template
stage: check
@ -614,45 +624,67 @@ push_to_github:
- git remote add github git@github.com:espressif/esp-idf.git
- tools/ci/push_to_github.sh
deploy_docs:
.deploy_docs_template:
extends: .before_script_lesser
stage: deploy
image: $CI_DOCKER_REGISTRY/esp32-ci-env$BOT_DOCKER_IMAGE_TAG
image: $ESP_IDF_DOC_ENV_IMAGE
tags:
- deploy
- shiny
dependencies:
- build_docs_en
- build_docs_zh_CN
variables:
DOCS_BUILD_DIR: "${IDF_PATH}/docs/_build/"
PYTHONUNBUFFERED: 1
script:
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- echo -n $DOCS_DEPLOY_PRIVATEKEY > ~/.ssh/id_rsa_base64
- base64 --decode --ignore-garbage ~/.ssh/id_rsa_base64 > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- echo -e "Host $DOCS_DEPLOY_SERVER\n\tStrictHostKeyChecking no\n\tUser $DOCS_DEPLOY_SERVER_USER\n" >> ~/.ssh/config
- export GIT_VER=$(git describe --always)
- ${IDF_PATH}/tools/ci/multirun_with_pyenv.sh -p 3.6.10 ${IDF_PATH}/tools/ci/deploy_docs.py
# deploys docs to CI_DOCKER_REGISTRY webserver, for internal review
deploy_docs_preview:
extends: .deploy_docs_template
only:
refs:
- master
- /^release\/v/
- /^v\d+\.\d+(\.\d+)?($|-)/
- triggers
variables:
- $BOT_TRIGGER_WITH_LABEL == null
- $BOT_LABEL_BUILD_DOCS
dependencies:
- build_docs
<<: *before_script_lesser
script:
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- echo -n $DOCS_DEPLOY_KEY > ~/.ssh/id_rsa_base64
- base64 --decode --ignore-garbage ~/.ssh/id_rsa_base64 > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- echo -e "Host $DOCS_SERVER\n\tStrictHostKeyChecking no\n\tUser $DOCS_SERVER_USER\n" >> ~/.ssh/config
- export GIT_VER=$(git describe --always)
- cd docs/en/_build/
- mv html $GIT_VER
- tar czvf $GIT_VER.tar.gz $GIT_VER
- scp $GIT_VER.tar.gz $DOCS_SERVER:$DOCS_PATH/en
- ssh $DOCS_SERVER -x "cd $DOCS_PATH/en && tar xzvf $GIT_VER.tar.gz && rm -f latest && ln -s $GIT_VER latest"
- cd ../../zh_CN/_build/
- mv html $GIT_VER
- tar czvf $GIT_VER.tar.gz $GIT_VER
- scp $GIT_VER.tar.gz $DOCS_SERVER:$DOCS_PATH/zh_CN
- ssh $DOCS_SERVER -x "cd $DOCS_PATH/zh_CN && tar xzvf $GIT_VER.tar.gz && rm -f latest && ln -s $GIT_VER latest"
# add link to preview doc
- echo "[document preview][en] $CI_DOCKER_REGISTRY/docs/esp-idf/en/${GIT_VER}/index.html"
- echo "[document preview][zh_CN] $CI_DOCKER_REGISTRY/docs/esp-idf/zh_CN/${GIT_VER}/index.html"
variables:
TYPE: "preview"
# older branches use DOCS_DEPLOY_KEY, DOCS_SERVER, DOCS_SERVER_USER, DOCS_PATH for preview server so we keep these names for 'preview'
DOCS_DEPLOY_PRIVATEKEY: "$DOCS_DEPLOY_KEY"
DOCS_DEPLOY_SERVER: "$DOCS_SERVER"
DOCS_DEPLOY_SERVER_USER: "$DOCS_SERVER_USER"
DOCS_DEPLOY_PATH: "$DOCS_PATH"
DOCS_DEPLOY_URL_BASE: "https://$CI_DOCKER_REGISTRY/docs/esp-idf"
# deploy docs to production webserver
deploy_docs_production:
extends: .deploy_docs_template
only:
refs:
# The DOCS_PROD_* variables used by this job are "Protected" so these branches must all be marked "Protected" in Gitlab settings
- master
- /^release\/v/
- /^v\d+\.\d+(\.\d+)?($|-)/
variables:
- $BOT_TRIGGER_WITH_LABEL == null
variables:
TYPE: "preview"
DOCS_DEPLOY_PRIVATEKEY: "$DOCS_PROD_DEPLOY_KEY"
DOCS_DEPLOY_SERVER: "$DOCS_PROD_SERVER"
DOCS_DEPLOY_SERVER_USER: "$DOCS_PROD_SERVER_USER"
DOCS_DEPLOY_PATH: "$DOCS_PROD_PATH"
DOCS_DEPLOY_URL_BASE: "https://docs.espressif.com/projects/esp-idf"
check_doc_links:
stage: host_test

View File

@ -1,7 +1,5 @@
# Espressif IoT Development Framework
[![Documentation Status](https://readthedocs.com/projects/espressif-esp-idf/badge/?version=latest)](https://docs.espressif.com/projects/esp-idf/en/latest/?badge=latest)
ESP-IDF is the official development framework for the [ESP32](https://espressif.com/en/products/hardware/esp32/overview) chip.
# Developing With ESP-IDF

View File

@ -167,6 +167,7 @@ MACRO_EXPANSION = YES
EXPAND_ONLY_PREDEF = YES
PREDEFINED = \
__attribute__(x)= \
_Static_assert()= \
IRAM_ATTR= \
configSUPPORT_DYNAMIC_ALLOCATION=1 \
configSUPPORT_STATIC_ALLOCATION=1 \

785
docs/_static/espressif2.pdf vendored Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -19,16 +19,21 @@ from __future__ import unicode_literals
import sys
import os
import subprocess
from sanitize_version import sanitize_version
from get_github_rev import get_github_rev
# Note: If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute
from local_util import run_cmd_get_output, copy_if_modified
from local_util import copy_if_modified
# build_docs on the CI server sometimes fails under Python3. This is a workaround:
sys.setrecursionlimit(3500)
config_dir = os.path.abspath(os.path.dirname(__file__))
try:
builddir = os.environ['BUILDDIR']
except KeyError:
@ -142,6 +147,7 @@ suppress_warnings = ['image.nonlocal_uri']
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['breathe',
'sphinx_idf_theme',
'link-roles',
'sphinxcontrib.blockdiag',
'sphinxcontrib.seqdiag',
@ -150,6 +156,7 @@ extensions = ['breathe',
'sphinxcontrib.rackdiag',
'sphinxcontrib.packetdiag',
'html_redirects',
'latex_builder',
]
# Set up font for blockdiag, nwdiag, rackdiag and packetdiag
@ -192,16 +199,14 @@ master_doc = 'index'
# built documents.
#
# Readthedocs largely ignores 'version' and 'release', and displays one of
# 'latest', tag name, or branch name, depending on the build type.
# Still, this is useful for non-RTD builds.
# This is supposed to be "the short X.Y version", but it's the only version
# This is the full exact version, canonical git version description
# visible when you open index.html.
# Display full version to make things less confusing.
version = run_cmd_get_output('git describe')
# The full version, including alpha/beta/rc tags.
# If needed, nearest tag is returned by 'git describe --abbrev=0'.
release = version
version = subprocess.check_output(['git', 'describe']).strip().decode('utf-8')
# The 'release' version is the same as version for non-CI builds, but for CI
# builds on a branch then it's replaced with the branch name
release = sanitize_version(version)
print('Version: {0} Release: {1}'.format(version, release))
# There are two options for replacing |today|: either, you set today to some
@ -232,6 +237,13 @@ exclude_patterns = ['_build','README.md']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Extra options required by sphinx_idf_theme
project_slug = 'esp-idf'
versions_url = 'https://dl.espressif.com/dl/esp-idf/idf_versions.js'
languages = ['en', 'zh_CN']
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
@ -257,7 +269,15 @@ html_redirect_pages = [('api-reference/ethernet/index', 'api-reference/network/i
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
html_theme = 'sphinx_idf_theme'
# context used by sphinx_idf_theme
html_context = {
"display_github": True, # Add 'Edit on Github' link instead of 'View page source'
"github_user": "espressif",
"github_repo": "esp-idf",
"github_version": get_github_rev(),
}
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
@ -340,28 +360,41 @@ htmlhelp_basename = 'ReadtheDocsTemplatedoc'
# -- 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_template_dir = os.path.join(config_dir, 'latex_templates')
# 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 = [
('index', 'ReadtheDocsTemplate.tex', u'Read the Docs Template Documentation',
u'Read the Docs', 'manual'),
]
preamble = ''
with open(os.path.join(latex_template_dir, 'preamble.tex')) as f:
preamble = f.read()
titlepage = ''
with open(os.path.join(latex_template_dir, 'titlepage.tex')) as f:
titlepage = f.read()
latex_elements = {
'papersize': 'a4paper',
# Latex figure (float) alignment
'figure_align':'htbp',
'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
'fncychap': '\\usepackage[Sonny]{fncychap}',
'preamble': preamble,
'maketitle': titlepage,
}
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# The name of an image file (relative to this directory) to place at the bottom of
# the title page.
latex_logo = "../_static/espressif2.pdf"
latex_engine = 'xelatex'
latex_use_xindy = False
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
@ -422,3 +455,24 @@ texinfo_documents = [
def setup(app):
app.add_stylesheet('theme_overrides.css')
generate_version_specific_includes(app)
# Not all config variables are set when setup is called
app.connect('config-inited', setup_config_values)
app.connect('config-inited', setup_html_context)
def setup_config_values(app, config):
# Sets up global config values needed by other extensions
idf_target_title_dict = {
'esp32': 'ESP32',
}
app.add_config_value('idf_target_title_dict', idf_target_title_dict, 'env')
pdf_name = "esp-idf-{}-{}-{}".format(app.config.language, app.config.version, "esp32")
app.add_config_value('pdf_file', pdf_name, 'env')
def setup_html_context(app, config):
# Setup path for 'edit on github'-link
app.config.html_context['conf_py_path'] = "/docs/{}/".format(app.config.language)

View File

@ -16,7 +16,7 @@ except ImportError:
# General information about the project.
project = u'ESP-IDF Programming Guide'
copyright = u'2016 - 2020, Espressif Systems (Shanghai) CO., LTD'
copyright = u'2016 - 2021, Espressif Systems (Shanghai) CO., LTD'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@ -82,14 +82,14 @@ If you have different board, move to sections below.
Step 1. Set up Toolchain
========================
The quickest way to start development with ESP32 is by installing a prebuilt toolchain. Pick up your OS below and follow provided instructions.
The quickest way to start development with ESP32 is by installing a prebuilt toolchain. Pick up your OS below and follow provided instructions.
.. toctree::
:hidden:
Windows <windows-setup>
Linux <linux-setup>
MacOS <macos-setup>
Linux <linux-setup>
MacOS <macos-setup>
+-------------------+-------------------+-------------------+
| |windows-logo| | |linux-logo| | |macos-logo| |
@ -298,12 +298,12 @@ This command will compile the application and all the ESP-IDF components, genera
-- Building empty aws_iot component due to configuration
-- Component names: ...
-- Component paths: ...
... (more lines of build system output)
[527/527] Generating hello-world.bin
esptool.py v2.3.1
Project build complete. To flash, run this command:
../../../components/esptool_py/esptool/esptool.py -p (PORT) -b 921600 write_flash --flash_mode dio --flash_size detect --flash_freq 40m 0x10000 build/hello-world.bin build 0x1000 build/bootloader/bootloader.bin 0x8000 build/partition_table/partition-table.bin
or run 'idf.py -p PORT flash'
@ -352,7 +352,7 @@ This step will flash the binaries that you just built to your ESP32 board.
Compressed 136672 bytes to 67544...
Wrote 136672 bytes (67544 compressed) at 0x00010000 in 1.9 seconds (effective 567.5 kbit/s)...
Hash of data verified.
Leaving...
Hard resetting via RTS pin...
@ -393,14 +393,13 @@ Several lines below, after start up and diagnostic log, you should see "Hello wo
To exit the monitor use shortcut ``Ctrl+]``.
.. note::
If instead of the messages above, you see a random garbage similar to what is shown below, or monitor fails shortly after upload, your board is likely using 26MHz crystal, while the ESP-IDF assumes default of 40MHz. Exit the monitor, go back to the :ref:`menuconfig <get-started-configure>`, change :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` to 26MHz, then :ref:`build and flash <get-started-build-flash>` the application again. This is found under ``make menuconfig`` under Component config --> ESP32-specific --> Main XTAL frequency.
If instead of the messages above, you see a random garbage similar to::
.. figure:: ../../_static/get-started-garbled-output.png
:align: center
:alt: Garbled output
:figclass: align-center
e<><65><EFBFBD>)(Xn@<40>y.!<21><>(<28>PW+)<29><>Hn9a؅/9<>!<21>t5<74><35>P<EFBFBD>~<7E>k<EFBFBD><6B>e<EFBFBD>ea<65>5<EFBFBD>jA
~zY<7A><59>Y(1<>,1<15><> e<><65><EFBFBD>)(Xn@<40>y.!Dr<44>zY(<28>jpi<70>|<7C>+z5Ymvp
or monitor fails shortly after upload, your board is likely using 26MHz crystal. Most development board designs use 40MHz and the ESP-IDF uses this default value. Exit the monitor, go back to the :ref:`menuconfig <get-started-configure-cmake>`, change :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` to 26MHz, then :ref:`build and flash <get-started-flash-cmake>` the application again. This is found under ``idf.py menuconfig`` under Component config --> ESP32-specific --> Main XTAL frequency.
.. note::

View File

@ -1,376 +1,375 @@
***********
Get Started
***********
:link_to_translation:`zh_CN:[中文]`
This document is intended to help users set up the software environment for development of applications using hardware based on the Espressif ESP32. Through a simple example we would like to illustrate how to use ESP-IDF (Espressif IoT Development Framework), including the menu based configuration, compiling the ESP-IDF and firmware download to ESP32 boards.
.. include:: /_build/inc/version-note.inc
Introduction
============
ESP32 integrates Wi-Fi (2.4 GHz band) and Bluetooth 4.2 solutions on a single chip, along with dual high performance cores, Ultra Low Power co-processor and several peripherals. Powered by 40 nm technology, ESP32 provides a robust, highly integrated platform to meet the continuous demands for efficient power usage, compact design, security, high performance, and reliability.
Espressif provides the basic hardware and software resources that help application developers to build their ideas around the ESP32 series hardware. The software development framework by Espressif is intended for rapidly developing Internet-of-Things (IoT) applications, with Wi-Fi, Bluetooth, power management and several other system features.
What You Need
=============
To develop applications for ESP32 you need:
* **PC** loaded with either Windows, Linux or Mac operating system
* **Toolchain** to build the **Application** for ESP32
* **ESP-IDF** that essentially contains API for ESP32 and scripts to operate the **Toolchain**
* A text editor to write programs (**Projects**) in C, e.g. `Eclipse <https://www.eclipse.org/>`_
* The **ESP32** board itself and a **USB cable** to connect it to the **PC**
.. figure:: ../../_static/what-you-need.png
:align: center
:alt: Development of applications for ESP32
:figclass: align-center
Development of applications for ESP32
Preparation of development environment consists of three steps:
1. Setup of **Toolchain**
2. Getting of **ESP-IDF** from GitHub
3. Installation and configuration of **Eclipse**
You may skip the last step, if you prefer to use different editor.
Having environment set up, you are ready to start the most interesting part - the application development. This process may be summarized in four steps:
1. Configuration of a **Project** and writing the code
2. Compilation of the **Project** and linking it to build an **Application**
3. Flashing (uploading) of the **Application** to **ESP32**
4. Monitoring / debugging of the **Application**
See instructions below that will walk you through these steps.
Guides
======
If you have one of ESP32 development boards listed below, click on provided links to get you up and running.
.. toctree::
:maxdepth: 1
ESP32 DevKitC <get-started-devkitc>
ESP-WROVER-KIT <get-started-wrover-kit>
ESP32-PICO-KIT <get-started-pico-kit>
If you have different board, move to sections below.
.. _get-started-setup-toolchain:
Setup Toolchain
===============
The quickest way to start development with ESP32 is by installing a prebuilt toolchain. Pick up your OS below and follow provided instructions.
.. toctree::
:hidden:
Windows <windows-setup>
Linux <linux-setup>
MacOS <macos-setup>
+-------------------+-------------------+-------------------+
| |windows-logo| | |linux-logo| | |macos-logo| |
+-------------------+-------------------+-------------------+
| `Windows`_ | `Linux`_ | `Mac OS`_ |
+-------------------+-------------------+-------------------+
.. |windows-logo| image:: ../../_static/windows-logo.png
:target: ../get-started/windows-setup.html
.. |linux-logo| image:: ../../_static/linux-logo.png
:target: ../get-started/linux-setup.html
.. |macos-logo| image:: ../../_static/macos-logo.png
:target: ../get-started/macos-setup.html
.. _Windows: ../get-started/windows-setup.html
.. _Linux: ../get-started/linux-setup.html
.. _Mac OS: ../get-started/macos-setup.html
.. note::
We are using ``~/esp`` directory to install the prebuilt toolchain, ESP-IDF and sample applications. You can use different directory, but need to adjust respective commands.
Depending on your experience and preferences, instead of using a prebuilt toolchain, you may want to customize your environment. To set up the system your own way go to section :ref:`get-started-customized-setup`.
Once you are done with setting up the toolchain then go to section :ref:`get-started-get-esp-idf`.
.. _get-started-get-esp-idf:
Get ESP-IDF
===========
.. highlight:: bash
Besides the toolchain (that contains programs to compile and build the application), you also need ESP32 specific API / libraries. They are provided by Espressif in `ESP-IDF repository <https://github.com/espressif/esp-idf>`_.
To obtain a local copy: open terminal, navigate to the directory you want to put ESP-IDF, and clone the repository using ``git clone`` command:
.. include:: /_build/inc/git-clone-bash.inc
ESP-IDF will be downloaded into ``~/esp/esp-idf``.
Consult :doc:`/versions` for information about which version of ESP-IDF to use in a given situation.
.. include:: /_build/inc/git-clone-notes.inc
.. note::
Do not miss the ``--recursive`` option. If you have already cloned ESP-IDF without this option, run another command to get all the submodules::
cd esp-idf
git submodule update --init --recursive
.. _get-started-setup-path:
Setup Path to ESP-IDF
=====================
The toolchain programs access ESP-IDF using ``IDF_PATH`` environment variable. This variable should be set up on your PC, otherwise projects will not build. Setting may be done manually, each time PC is restarted. Another option is to set up it permanently by defining ``IDF_PATH`` in user profile. To do so, follow instructions specific to :ref:`Windows <add-idf_path-to-profile-windows>` , :ref:`Linux and MacOS <add-idf_path-to-profile-linux-macos>` in section :doc:`add-idf_path-to-profile`.
.. _get-started-get-packages:
Install the Required Python Packages
====================================
Python packages required by ESP-IDF are located in the ``$IDF_PATH/requirements.txt`` file. You can install them by running::
python -m pip install --user -r $IDF_PATH/requirements.txt
.. note::
Please invoke that version of the Python interpreter which you will be using with ESP-IDF. The version of the
interpreter can be checked by running command ``python --version`` and depending on the result, you might want to
use ``python2``, ``python2.7`` or similar instead of ``python``, e.g.::
python2.7 -m pip install --user -r $IDF_PATH/requirements.txt
.. _get-started-start-project:
Start a Project
===============
Now you are ready to prepare your application for ESP32. To start off quickly, we will use :example:`get-started/hello_world` project from :idf:`examples` directory in IDF.
Copy :example:`get-started/hello_world` to ``~/esp`` directory::
cd ~/esp
cp -r $IDF_PATH/examples/get-started/hello_world .
You can also find a range of example projects under the :idf:`examples` directory in ESP-IDF. These example project directories can be copied in the same way as presented above, to begin your own projects.
.. important::
The esp-idf build system does not support spaces in paths to esp-idf or to projects.
.. _get-started-connect:
Connect
=======
You are almost there. To be able to proceed further, connect ESP32 board to PC, check under what serial port the board is visible and verify if serial communication works. If you are not sure how to do it, check instructions in section :doc:`establish-serial-connection`. Note the port number, as it will be required in the next step.
.. _get-started-configure:
Configure
=========
Being in terminal window, go to directory of ``hello_world`` application by typing ``cd ~/esp/hello_world``. Then start project configuration utility ``menuconfig``::
cd ~/esp/hello_world
make menuconfig
If previous steps have been done correctly, the following menu will be displayed:
.. figure:: ../../_static/project-configuration.png
:align: center
:alt: Project configuration - Home window
:figclass: align-center
Project configuration - Home window
In the menu, navigate to ``Serial flasher config`` > ``Default serial port`` to configure the serial port, where project will be loaded to. Confirm selection by pressing enter, save configuration by selecting ``< Save >`` and then exit application by selecting ``< Exit >``.
.. note::
On Windows, serial ports have names like COM1. On MacOS, they start with ``/dev/cu.``. On Linux, they start with ``/dev/tty``.
(See :doc:`establish-serial-connection` for full details.)
Here are couple of tips on navigation and use of ``menuconfig``:
* Use up & down arrow keys to navigate the menu.
* Use Enter key to go into a submenu, Escape key to go out or to exit.
* Type ``?`` to see a help screen. Enter key exits the help screen.
* Use Space key, or ``Y`` and ``N`` keys to enable (Yes) and disable (No) configuration items with checkboxes "``[*]``"
* Pressing ``?`` while highlighting a configuration item displays help about that item.
* Type ``/`` to search the configuration items.
.. note::
If you are **Arch Linux** user, navigate to ``SDK tool configuration`` and change the name of ``Python 2 interpreter`` from ``python`` to ``python2``.
.. attention::
When using ESP32-DevKitC board with ESP32-SOLO-1 module, enable single core mode (:ref:`CONFIG_FREERTOS_UNICORE`) in menuconfig before flashing example applications.
.. _get-started-build-flash:
Build and Flash
===============
Now you can build and flash the application. Run::
make flash
This will compile the application and all the ESP-IDF components, generate bootloader, partition table, and application binaries, and flash these binaries to your ESP32 board.
.. highlight:: none
::
esptool.py v2.0-beta2
Flashing binaries to serial port /dev/ttyUSB0 (app at offset 0x10000)...
esptool.py v2.0-beta2
Connecting........___
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Attaching SPI flash...
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0220
Compressed 11616 bytes to 6695...
Wrote 11616 bytes (6695 compressed) at 0x00001000 in 0.1 seconds (effective 920.5 kbit/s)...
Hash of data verified.
Compressed 408096 bytes to 171625...
Wrote 408096 bytes (171625 compressed) at 0x00010000 in 3.9 seconds (effective 847.3 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 82...
Wrote 3072 bytes (82 compressed) at 0x00008000 in 0.0 seconds (effective 8297.4 kbit/s)...
Hash of data verified.
Leaving...
Hard resetting...
If there are no issues, at the end of build process, you should see messages describing progress of loading process. Finally, the end module will be reset and "hello_world" application will start.
If you'd like to use the Eclipse IDE instead of running ``make``, check out the :doc:`Eclipse guide <eclipse-setup>`.
.. _get-started-build-monitor:
Monitor
=======
To see if "hello_world" application is indeed running, type ``make monitor``. This command is launching :doc:`IDF Monitor <idf-monitor>` application::
$ make monitor
MONITOR
--- idf_monitor on /dev/ttyUSB0 115200 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57
...
Several lines below, after start up and diagnostic log, you should see "Hello world!" printed out by the application. ::
...
Hello world!
Restarting in 10 seconds...
I (211) cpu_start: Starting scheduler on APP CPU.
Restarting in 9 seconds...
Restarting in 8 seconds...
Restarting in 7 seconds...
To exit the monitor use shortcut ``Ctrl+]``.
.. note::
If instead of the messages above, you see a random garbage similar to::
e<><65><EFBFBD>)(Xn@<40>y.!<21><>(<28>PW+)<29><>Hn9a؅/9<>!<21>t5<74><35>P<EFBFBD>~<7E>k<EFBFBD><6B>e<EFBFBD>ea<65>5<EFBFBD>jA
~zY<7A><59>Y(1<>,1<15><> e<><65><EFBFBD>)(Xn@<40>y.!Dr<44>zY(<28>jpi<70>|<7C>+z5Ymvp
or monitor fails shortly after upload, your board is likely using 26MHz crystal, while the ESP-IDF assumes default of 40MHz. Exit the monitor, go back to the :ref:`menuconfig <get-started-configure>`, change :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` to 26MHz, then :ref:`build and flash <get-started-build-flash>` the application again. This is found under ``make menuconfig`` under Component config --> ESP32-specific --> Main XTAL frequency.
To execute ``make flash`` and ``make monitor`` in one go, type ``make flash monitor``. Check section :doc:`IDF Monitor <idf-monitor>` for handy shortcuts and more details on using this application.
That's all what you need to get started with ESP32!
Now you are ready to try some other :idf:`examples`, or go right to developing your own applications.
Environment Variables
=====================
Some environment variables can be specified whilst calling ``make`` allowing users to **override arguments without needing to reconfigure them using** ``make menuconfig``.
+-----------------+--------------------------------------------------------------+
| Variables | Description & Usage |
+=================+==============================================================+
| ``ESPPORT`` | Overrides the serial port used in ``flash`` and ``monitor``. |
| | |
| | Examples: ``make flash ESPPORT=/dev/ttyUSB1``, |
| | ``make monitor ESPPORT=COM1`` |
+-----------------+--------------------------------------------------------------+
| ``ESPBAUD`` | Overrides the serial baud rate when flashing the ESP32. |
| | |
| | Example: ``make flash ESPBAUD=9600`` |
+-----------------+--------------------------------------------------------------+
| ``MONITORBAUD`` | Overrides the serial baud rate used when monitoring. |
| | |
| | Example: ``make monitor MONITORBAUD=9600`` |
+-----------------+--------------------------------------------------------------+
.. note::
Users can export environment variables (e.g. ``export ESPPORT=/dev/ttyUSB1``).
All subsequent calls of ``make`` within the same terminal session will use
the exported value given that the variable is not simultaneously overridden.
Updating ESP-IDF
================
After some time of using ESP-IDF, you may want to update it to take advantage of new features or bug fixes. The simplest way to do so is by deleting existing ``esp-idf`` folder and cloning it again, exactly as when doing initial installation described in sections :ref:`get-started-get-esp-idf`.
If downloading to a new path, remember to :doc:`add-idf_path-to-profile` so that the toolchain scripts know where to find the ESP-IDF in its release specific location.
Another solution is to update only what has changed. :ref:`The update procedure depends on the version of ESP-IDF you are using <updating>`.
Related Documents
=================
.. toctree::
:maxdepth: 1
add-idf_path-to-profile
establish-serial-connection
make-project
eclipse-setup
idf-monitor
toolchain-setup-scratch
.. _Stable version: https://docs.espressif.com/projects/esp-idf/en/stable/
.. _Releases page: https://github.com/espressif/esp-idf/releases
***********
Get Started
***********
:link_to_translation:`zh_CN:[中文]`
This document is intended to help users set up the software environment for development of applications using hardware based on the Espressif ESP32. Through a simple example we would like to illustrate how to use ESP-IDF (Espressif IoT Development Framework), including the menu based configuration, compiling the ESP-IDF and firmware download to ESP32 boards.
.. include:: /_build/inc/version-note.inc
Introduction
============
ESP32 integrates Wi-Fi (2.4 GHz band) and Bluetooth 4.2 solutions on a single chip, along with dual high performance cores, Ultra Low Power co-processor and several peripherals. Powered by 40 nm technology, ESP32 provides a robust, highly integrated platform to meet the continuous demands for efficient power usage, compact design, security, high performance, and reliability.
Espressif provides the basic hardware and software resources that help application developers to build their ideas around the ESP32 series hardware. The software development framework by Espressif is intended for rapidly developing Internet-of-Things (IoT) applications, with Wi-Fi, Bluetooth, power management and several other system features.
What You Need
=============
To develop applications for ESP32 you need:
* **PC** loaded with either Windows, Linux or Mac operating system
* **Toolchain** to build the **Application** for ESP32
* **ESP-IDF** that essentially contains API for ESP32 and scripts to operate the **Toolchain**
* A text editor to write programs (**Projects**) in C, e.g. `Eclipse <https://www.eclipse.org/>`_
* The **ESP32** board itself and a **USB cable** to connect it to the **PC**
.. figure:: ../../_static/what-you-need.png
:align: center
:alt: Development of applications for ESP32
:figclass: align-center
Development of applications for ESP32
Preparation of development environment consists of three steps:
1. Setup of **Toolchain**
2. Getting of **ESP-IDF** from GitHub
3. Installation and configuration of **Eclipse**
You may skip the last step, if you prefer to use different editor.
Having environment set up, you are ready to start the most interesting part - the application development. This process may be summarized in four steps:
1. Configuration of a **Project** and writing the code
2. Compilation of the **Project** and linking it to build an **Application**
3. Flashing (uploading) of the **Application** to **ESP32**
4. Monitoring / debugging of the **Application**
See instructions below that will walk you through these steps.
Guides
======
If you have one of ESP32 development boards listed below, click on provided links to get you up and running.
.. toctree::
:maxdepth: 1
ESP32 DevKitC <get-started-devkitc>
ESP-WROVER-KIT <get-started-wrover-kit>
ESP32-PICO-KIT <get-started-pico-kit>
If you have different board, move to sections below.
.. _get-started-setup-toolchain:
Setup Toolchain
===============
The quickest way to start development with ESP32 is by installing a prebuilt toolchain. Pick up your OS below and follow provided instructions.
.. toctree::
:hidden:
Windows <windows-setup>
Linux <linux-setup>
MacOS <macos-setup>
+-------------------+-------------------+-------------------+
| |windows-logo| | |linux-logo| | |macos-logo| |
+-------------------+-------------------+-------------------+
| `Windows`_ | `Linux`_ | `Mac OS`_ |
+-------------------+-------------------+-------------------+
.. |windows-logo| image:: ../../_static/windows-logo.png
:target: ../get-started/windows-setup.html
.. |linux-logo| image:: ../../_static/linux-logo.png
:target: ../get-started/linux-setup.html
.. |macos-logo| image:: ../../_static/macos-logo.png
:target: ../get-started/macos-setup.html
.. _Windows: ../get-started/windows-setup.html
.. _Linux: ../get-started/linux-setup.html
.. _Mac OS: ../get-started/macos-setup.html
.. note::
We are using ``~/esp`` directory to install the prebuilt toolchain, ESP-IDF and sample applications. You can use different directory, but need to adjust respective commands.
Depending on your experience and preferences, instead of using a prebuilt toolchain, you may want to customize your environment. To set up the system your own way go to section :ref:`get-started-customized-setup`.
Once you are done with setting up the toolchain then go to section :ref:`get-started-get-esp-idf`.
.. _get-started-get-esp-idf:
Get ESP-IDF
===========
.. highlight:: bash
Besides the toolchain (that contains programs to compile and build the application), you also need ESP32 specific API / libraries. They are provided by Espressif in `ESP-IDF repository <https://github.com/espressif/esp-idf>`_.
To obtain a local copy: open terminal, navigate to the directory you want to put ESP-IDF, and clone the repository using ``git clone`` command:
.. include:: /_build/inc/git-clone-bash.inc
ESP-IDF will be downloaded into ``~/esp/esp-idf``.
Consult :doc:`/versions` for information about which version of ESP-IDF to use in a given situation.
.. include:: /_build/inc/git-clone-notes.inc
.. note::
Do not miss the ``--recursive`` option. If you have already cloned ESP-IDF without this option, run another command to get all the submodules::
cd esp-idf
git submodule update --init --recursive
.. _get-started-setup-path:
Setup Path to ESP-IDF
=====================
The toolchain programs access ESP-IDF using ``IDF_PATH`` environment variable. This variable should be set up on your PC, otherwise projects will not build. Setting may be done manually, each time PC is restarted. Another option is to set up it permanently by defining ``IDF_PATH`` in user profile. To do so, follow instructions specific to :ref:`Windows <add-idf_path-to-profile-windows>` , :ref:`Linux and MacOS <add-idf_path-to-profile-linux-macos>` in section :doc:`add-idf_path-to-profile`.
.. _get-started-get-packages:
Install the Required Python Packages
====================================
Python packages required by ESP-IDF are located in the ``$IDF_PATH/requirements.txt`` file. You can install them by running::
python -m pip install --user -r $IDF_PATH/requirements.txt
.. note::
Please invoke that version of the Python interpreter which you will be using with ESP-IDF. The version of the
interpreter can be checked by running command ``python --version`` and depending on the result, you might want to
use ``python2``, ``python2.7`` or similar instead of ``python``, e.g.::
python2.7 -m pip install --user -r $IDF_PATH/requirements.txt
.. _get-started-start-project:
Start a Project
===============
Now you are ready to prepare your application for ESP32. To start off quickly, we will use :example:`get-started/hello_world` project from :idf:`examples` directory in IDF.
Copy :example:`get-started/hello_world` to ``~/esp`` directory::
cd ~/esp
cp -r $IDF_PATH/examples/get-started/hello_world .
You can also find a range of example projects under the :idf:`examples` directory in ESP-IDF. These example project directories can be copied in the same way as presented above, to begin your own projects.
.. important::
The esp-idf build system does not support spaces in paths to esp-idf or to projects.
.. _get-started-connect:
Connect
=======
You are almost there. To be able to proceed further, connect ESP32 board to PC, check under what serial port the board is visible and verify if serial communication works. If you are not sure how to do it, check instructions in section :doc:`establish-serial-connection`. Note the port number, as it will be required in the next step.
.. _get-started-configure:
Configure
=========
Being in terminal window, go to directory of ``hello_world`` application by typing ``cd ~/esp/hello_world``. Then start project configuration utility ``menuconfig``::
cd ~/esp/hello_world
make menuconfig
If previous steps have been done correctly, the following menu will be displayed:
.. figure:: ../../_static/project-configuration.png
:align: center
:alt: Project configuration - Home window
:figclass: align-center
Project configuration - Home window
In the menu, navigate to ``Serial flasher config`` > ``Default serial port`` to configure the serial port, where project will be loaded to. Confirm selection by pressing enter, save configuration by selecting ``< Save >`` and then exit application by selecting ``< Exit >``.
.. note::
On Windows, serial ports have names like COM1. On MacOS, they start with ``/dev/cu.``. On Linux, they start with ``/dev/tty``.
(See :doc:`establish-serial-connection` for full details.)
Here are couple of tips on navigation and use of ``menuconfig``:
* Use up & down arrow keys to navigate the menu.
* Use Enter key to go into a submenu, Escape key to go out or to exit.
* Type ``?`` to see a help screen. Enter key exits the help screen.
* Use Space key, or ``Y`` and ``N`` keys to enable (Yes) and disable (No) configuration items with checkboxes "``[*]``"
* Pressing ``?`` while highlighting a configuration item displays help about that item.
* Type ``/`` to search the configuration items.
.. note::
If you are **Arch Linux** user, navigate to ``SDK tool configuration`` and change the name of ``Python 2 interpreter`` from ``python`` to ``python2``.
.. attention::
When using ESP32-DevKitC board with ESP32-SOLO-1 module, enable single core mode (:ref:`CONFIG_FREERTOS_UNICORE`) in menuconfig before flashing example applications.
.. _get-started-build-flash:
Build and Flash
===============
Now you can build and flash the application. Run::
make flash
This will compile the application and all the ESP-IDF components, generate bootloader, partition table, and application binaries, and flash these binaries to your ESP32 board.
.. highlight:: none
::
esptool.py v2.0-beta2
Flashing binaries to serial port /dev/ttyUSB0 (app at offset 0x10000)...
esptool.py v2.0-beta2
Connecting........___
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 921600
Changed.
Attaching SPI flash...
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0220
Compressed 11616 bytes to 6695...
Wrote 11616 bytes (6695 compressed) at 0x00001000 in 0.1 seconds (effective 920.5 kbit/s)...
Hash of data verified.
Compressed 408096 bytes to 171625...
Wrote 408096 bytes (171625 compressed) at 0x00010000 in 3.9 seconds (effective 847.3 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 82...
Wrote 3072 bytes (82 compressed) at 0x00008000 in 0.0 seconds (effective 8297.4 kbit/s)...
Hash of data verified.
Leaving...
Hard resetting...
If there are no issues, at the end of build process, you should see messages describing progress of loading process. Finally, the end module will be reset and "hello_world" application will start.
If you'd like to use the Eclipse IDE instead of running ``make``, check out the :doc:`Eclipse guide <eclipse-setup>`.
.. _get-started-build-monitor:
Monitor
=======
To see if "hello_world" application is indeed running, type ``make monitor``. This command is launching :doc:`IDF Monitor <idf-monitor>` application::
$ make monitor
MONITOR
--- idf_monitor on /dev/ttyUSB0 115200 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57
...
Several lines below, after start up and diagnostic log, you should see "Hello world!" printed out by the application. ::
...
Hello world!
Restarting in 10 seconds...
I (211) cpu_start: Starting scheduler on APP CPU.
Restarting in 9 seconds...
Restarting in 8 seconds...
Restarting in 7 seconds...
To exit the monitor use shortcut ``Ctrl+]``.
If instead of the messages above, you see a random garbage similar to what is shown below, or monitor fails shortly after upload, your board is likely using 26MHz crystal, while the ESP-IDF assumes default of 40MHz. Exit the monitor, go back to the :ref:`menuconfig <get-started-configure>`, change :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` to 26MHz, then :ref:`build and flash <get-started-build-flash>` the application again. This is found under ``make menuconfig`` under Component config --> ESP32-specific --> Main XTAL frequency.
.. figure:: ../../_static/get-started-garbled-output.png
:align: center
:alt: Garbled output
:figclass: align-center
To execute ``make flash`` and ``make monitor`` in one go, type ``make flash monitor``. Check section :doc:`IDF Monitor <idf-monitor>` for handy shortcuts and more details on using this application.
That's all what you need to get started with ESP32!
Now you are ready to try some other :idf:`examples`, or go right to developing your own applications.
Environment Variables
=====================
Some environment variables can be specified whilst calling ``make`` allowing users to **override arguments without needing to reconfigure them using** ``make menuconfig``.
+-----------------+--------------------------------------------------------------+
| Variables | Description & Usage |
+=================+==============================================================+
| ``ESPPORT`` | Overrides the serial port used in ``flash`` and ``monitor``. |
| | |
| | Examples: ``make flash ESPPORT=/dev/ttyUSB1``, |
| | ``make monitor ESPPORT=COM1`` |
+-----------------+--------------------------------------------------------------+
| ``ESPBAUD`` | Overrides the serial baud rate when flashing the ESP32. |
| | |
| | Example: ``make flash ESPBAUD=9600`` |
+-----------------+--------------------------------------------------------------+
| ``MONITORBAUD`` | Overrides the serial baud rate used when monitoring. |
| | |
| | Example: ``make monitor MONITORBAUD=9600`` |
+-----------------+--------------------------------------------------------------+
.. note::
Users can export environment variables (e.g. ``export ESPPORT=/dev/ttyUSB1``).
All subsequent calls of ``make`` within the same terminal session will use
the exported value given that the variable is not simultaneously overridden.
Updating ESP-IDF
================
After some time of using ESP-IDF, you may want to update it to take advantage of new features or bug fixes. The simplest way to do so is by deleting existing ``esp-idf`` folder and cloning it again, exactly as when doing initial installation described in sections :ref:`get-started-get-esp-idf`.
If downloading to a new path, remember to :doc:`add-idf_path-to-profile` so that the toolchain scripts know where to find the ESP-IDF in its release specific location.
Another solution is to update only what has changed. :ref:`The update procedure depends on the version of ESP-IDF you are using <updating>`.
Related Documents
=================
.. toctree::
:maxdepth: 1
add-idf_path-to-profile
establish-serial-connection
make-project
eclipse-setup
idf-monitor
toolchain-setup-scratch
.. _Stable version: https://docs.espressif.com/projects/esp-idf/en/stable/
.. _Releases page: https://github.com/espressif/esp-idf/releases

View File

@ -189,34 +189,29 @@ def write_version_note(template, out_dir, version, ver_type, is_stable):
def get_version():
"""
Returns a tuple of (name of branch/tag, type branch/tag, is_stable)
Returns a tuple of (name of branch/tag/commit-id, type branch/tag/commit, is_stable)
"""
# Trust what RTD says our version is, if it is set
version = os.environ.get("READTHEDOCS_VERSION", None)
if version == "latest":
return ("master", "branch", False)
# Otherwise, use git to look for a tag
# Use git to look for a tag
try:
tag = subprocess.check_output(["git", "describe", "--exact-match"]).strip()
tag = subprocess.check_output(["git", "describe", "--exact-match"]).strip().decode('utf-8')
is_stable = re.match(r"v[0-9\.]+$", tag) is not None
return (tag, "tag", is_stable)
except subprocess.CalledProcessError:
pass
# No tag, look for a branch
refs = subprocess.check_output(["git", "for-each-ref", "--points-at", "HEAD", "--format", "%(refname)"])
print("refs:\n%s" % refs)
refs = refs.split(b"\n")
# Note: this looks for branches in 'origin' because GitLab CI doesn't check out a local branch
branches = [r.replace(b"refs/remotes/origin/",b"").strip() for r in refs if r.startswith(b"refs/remotes/origin/")]
if len(branches) == 0:
# last resort, return the commit (may happen on Gitlab CI sometimes, unclear why)
return (subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).strip(), "commit", False)
if "master" in branches:
return ("master", "branch", False)
else:
return (branches[0], "branch", False) # take whatever the first branch is
# No tag, look at branch name from CI, this will give the correct branch name even if the ref for the branch we
# merge into has moved forward before the pipeline runs
branch = os.environ.get("CI_COMMIT_REF_NAME", None)
if branch is not None:
return (branch, "branch", False)
# Try to find the branch name even if docs are built locally
branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).strip().decode('utf-8')
if branch != "HEAD":
return (branch, "branch", False)
# As a last resort we return commit SHA-1, should never happen in CI/docs that should be published
return (subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).strip().decode('utf-8'), "commit", False)
if __name__ == "__main__":

15
docs/get_github_rev.py Normal file
View File

@ -0,0 +1,15 @@
import subprocess
# Get revision used for constructing github URLs
def get_github_rev():
path = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode('utf-8')
try:
tag = subprocess.check_output(['git', 'describe', '--exact-match']).strip().decode('utf-8')
except subprocess.CalledProcessError:
tag = None
print('Git commit ID: ', path)
if tag:
print('Git tag: ', tag)
return tag
return path

55
docs/latex_builder.py Normal file
View File

@ -0,0 +1,55 @@
from sphinx.builders.latex import LaTeXBuilder
import os
# Overrides the default Sphinx latex build
class IdfLatexBuilder(LaTeXBuilder):
def __init__(self, app):
# Sets up the latex_documents config value, done here instead of conf.py since it depends on the runtime value 'idf_target'
self.init_latex_documents(app)
super().__init__(app)
def init_latex_documents(self, app):
file_name = app.config.pdf_file + '.tex'
if app.config.language == 'zh_CN':
latex_documents = [('index', file_name, u'ESP-IDF 编程指南', u'乐鑫信息科技', 'manual')]
else:
# Default to english naming
latex_documents = [('index', file_name, u'ESP-IDF Programming Guide', u'Espressif Systems', 'manual')]
app.config.latex_documents = latex_documents
def prepare_latex_macros(self, package_path, config):
PACKAGE_NAME = "espidf.sty"
latex_package = ''
with open(package_path, 'r') as template:
latex_package = template.read()
idf_target_title = "ESP32"
latex_package = latex_package.replace('<idf_target_title>', idf_target_title)
# Release name for the PDF front page, remove '_' as this is used for subscript in Latex
idf_release_name = "Release {}".format(config.version.replace('_', '-'))
latex_package = latex_package.replace('<idf_release_name>', idf_release_name)
with open(os.path.join(self.outdir, PACKAGE_NAME), 'w') as package_file:
package_file.write(latex_package)
def finish(self):
super().finish()
TEMPLATE_PATH = "../latex_templates/espidf.sty"
self.prepare_latex_macros(os.path.join(self.confdir,TEMPLATE_PATH), self.config)
def setup(app):
app.add_builder(IdfLatexBuilder, override=True)
return {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': '0.1'}

View File

@ -0,0 +1,7 @@
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\ProvidesPackage{espidf}[2020/03/25 v0.1.0 LaTeX package (ESP-IDF markup)]
\newcommand{\idfTarget}{<idf_target_title>}
\newcommand{\idfReleaseName}{<idf_release_name>}
\endinput

View File

@ -0,0 +1,129 @@
% package with esp-idf specific macros
\usepackage{espidf}
\setcounter{secnumdepth}{2}
\setcounter{tocdepth}{2}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{graphicx}
%%% reduce spaces for Table of contents, figures and tables
%%% it is used "\addtocontents{toc}{\vskip -1.2cm}" etc. in the document
\usepackage[notlot,nottoc,notlof]{}
\usepackage{color}
\usepackage{transparent}
\usepackage{eso-pic}
\usepackage{lipsum}
%%% Needed for displaying Chinese in English documentation
\usepackage{xeCJK}
\usepackage{footnotebackref} %%link at the footnote to go to the place of footnote in the text
%% spacing between line
\usepackage{setspace}
\singlespacing
\definecolor{myred}{RGB}{229, 32, 26}
\definecolor{mygrayy}{RGB}{127, 127, 127}
\definecolor{myblack}{RGB}{64, 64, 64}
%%%%%%%%%%% datetime
\usepackage{datetime}
\newdateformat{MonthYearFormat}{%
\monthname[\THEMONTH], \THEYEAR}
%% RO, LE will not work for 'oneside' layout.
%% Change oneside to twoside in document class
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
% Header and footer
\makeatletter
\fancypagestyle{normal}{
\fancyhf{}
\fancyhead[L]{\nouppercase{\leftmark}}
\fancyfoot[C]{\py@HeaderFamily\thepage \\ \href{https://www.espressif.com/en/company/documents/documentation_feedback?docId=4287&sections=&version=\idfReleaseName}{Submit Document Feedback}}
\fancyfoot[L]{Espressif Systems}
\fancyfoot[R]{\idfReleaseName}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}
}
\makeatother
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0.5pt}
% Define a spacing for section, subsection and subsubsection
% http://tex.stackexchange.com/questions/108684/spacing-before-and-after-section-titles
\titlespacing*{\section}{0pt}{6pt plus 0pt minus 0pt}{6pt plus 0pt minus 0pt}
\titlespacing*{\subsection}{0pt}{18pt plus 64pt minus 0pt}{0pt}
\titlespacing*{\subsubsection}{0pt}{12pt plus 0pt minus 0pt}{0pt}
\titlespacing*{\paragraph} {0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}
\titlespacing*{\subparagraph} {0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}
% Define the colors of table of contents
% This is helpful to understand http://tex.stackexchange.com/questions/110253/what-the-first-argument-for-lsubsection-actually-is
\definecolor{LochmaraColor}{HTML}{1020A0}
% Hyperlinks
\hypersetup{
colorlinks = true,
allcolors = {LochmaraColor},
}
\RequirePackage{tocbibind} %%% comment this to remove page number for following
\addto\captionsenglish{\renewcommand{\contentsname}{Table of contents}}
\addto\captionsenglish{\renewcommand{\listfigurename}{List of figures}}
\addto\captionsenglish{\renewcommand{\listtablename}{List of tables}}
% \addto\captionsenglish{\renewcommand{\chaptername}{Chapter}}
%%reduce spacing for itemize
\usepackage{enumitem}
\setlist{nosep}
%%%%%%%%%%% Quote Styles at the top of chapter
\usepackage{epigraph}
\setlength{\epigraphwidth}{0.8\columnwidth}
\newcommand{\chapterquote}[2]{\epigraphhead[60]{\epigraph{\textit{#1}}{\textbf {\textit{--#2}}}}}
%%%%%%%%%%% Quote for all places except Chapter
\newcommand{\sectionquote}[2]{{\quote{\textit{``#1''}}{\textbf {\textit{--#2}}}}}
% Insert 22pt white space before roc title. \titlespacing at line 65 changes it by -22 later on.
\renewcommand*\contentsname{\hspace{0pt}Contents}
% Define section, subsection and subsubsection font size and color
\usepackage{sectsty}
\definecolor{AllportsColor}{HTML}{A02010}
\allsectionsfont{\color{AllportsColor}}
\usepackage{titlesec}
\titleformat{\section}
{\color{AllportsColor}\LARGE\bfseries}{\thesection.}{1em}{}
\titleformat{\subsection}
{\color{AllportsColor}\Large\bfseries}{\thesubsection.}{1em}{}
\titleformat{\subsubsection}
{\color{AllportsColor}\large\bfseries}{\thesubsubsection.}{1em}{}
\titleformat{\paragraph}
{\color{AllportsColor}\large\bfseries}{\theparagraph}{1em}{}
\titleformat{\subparagraph}
{\normalfont\normalsize\bfseries}{\thesubparagraph}{1em}{}
\titleformat{\subsubparagraph}
{\normalfont\normalsize\bfseries}{\thesubsubparagraph}{1em}{}

View File

@ -0,0 +1,39 @@
\makeatletter
\newgeometry{left=0cm,right=0cm,bottom=2cm}
\cfoot{www.espressif.com}
\renewcommand{\headrulewidth}{0pt}
{\color{myred}\rule{30pt}{2.1cm}}
\hspace{0.2cm}
\begin{minipage}[b]{18cm}
{\fontsize{36pt}{48pt}\textbf{\idfTarget}}\\
{\fontsize{28pt}{18pt}\textbf{\color{mygrayy}\@title}}
\end{minipage}
\hspace{\stretch{1}}
\vspace{48em}
\begin{flushright}
\setlength\parindent{8em}
\begin{minipage}[b]{2cm}
\sphinxlogo
\end{minipage}
\hspace{0.2cm}
\rule{3pt}{1.9cm}
\hspace{0.2cm}
\begin{minipage}[b]{7cm}
{\large{\idfReleaseName}}\smallskip\newline
{\large{\@author}}\smallskip\newline
{\large{\@date}}\smallskip
\end{minipage}
{\color{myred}\rule{30pt}{1.9cm}}
\end{flushright}
\restoregeometry
\makeatother

View File

@ -6,6 +6,7 @@ import re
import os
from docutils import nodes
from local_util import run_cmd_get_output
from sphinx.transforms.post_transforms import SphinxPostTransform
def get_github_rev():
@ -34,17 +35,42 @@ def setup(app):
app.add_role('example_raw', autolink('{}/raw/{}/examples/%s'.format(baseurl, rev)))
# link to the current documentation file in specific language version
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if on_rtd:
# provide RTD specific commit identification to be included in the link
tag_rev = 'latest'
if (run_cmd_get_output('git rev-parse --short HEAD') != rev):
tag_rev = rev
else:
# if not on the RTD then provide generic identification
tag_rev = run_cmd_get_output('git describe --always')
app.add_role('link_to_translation', link_to_translation)
app.add_node(translation_link)
app.add_post_transform(TranslationLinkNodeTransform)
app.add_role('link_to_translation', crosslink('%s../../%s/{}/%s.html'.format(tag_rev)))
class translation_link(nodes.Element):
"""Node for "link_to_translation" role."""
# Linking to translation is done at the "writing" stage to avoid issues with the info being cached between builders
def link_to_translation(name, rawtext, text, lineno, inliner, options={}, content=[]):
node = translation_link()
node['expr'] = (rawtext, text, options)
return [node], []
class TranslationLinkNodeTransform(SphinxPostTransform):
# Transform needs to happen early to ensure the new reference node is also transformed
default_priority = 0
def run(self, **kwargs):
# Only output relative links if building HTML
for node in self.document.traverse(translation_link):
if 'html' in self.app.builder.name:
rawtext, text, options = node['expr']
(language, link_text) = text.split(':')
env = self.document.settings.env
docname = env.docname
doc_path = env.doc2path(docname, None, None)
return_path = '../' * doc_path.count('/') # path back to the root from 'docname'
# then take off 2 more paths for language/release/ and build the new URL
url = '{}.html'.format(os.path.join(return_path, '../..', language, env.config.release, docname))
node.replace_self(nodes.reference(rawtext, link_text, refuri=url, **options))
else:
node.replace_self([])
def autolink(pattern):

View File

@ -1,16 +1,14 @@
# This is a list of python packages used to generate documentation. This file is used with pip:
# pip install --user -r requirements.txt
#
sphinx>=1.8.4
breathe==4.11.1
sphinx-rtd-theme
sphinxcontrib-blockdiag>=1.5.5, <2.0.0
sphinxcontrib-seqdiag>=0.8.5, <2.0.0
sphinxcontrib-actdiag>=0.8.5, <2.0.0
sphinxcontrib-nwdiag>=0.9.5, <2.0.0
blockdiag>=1.5.4, <2.0.0
seqdiag>=0.9.6, <2.0.0
actdiag>=0.5.4, <2.0.0
nwdiag>=1.0.4, <2.0.0
sphinx==2.3.1
breathe==4.14.1
sphinxcontrib-blockdiag==2.0.0
sphinxcontrib-seqdiag==2.0.0
sphinxcontrib-actdiag==2.0.0
sphinxcontrib-nwdiag==2.0.0
sphinxcontrib-wavedrom==2.0.0
nwdiag==2.0.0
recommonmark
future>=0.16.0 # for ../tools/gen_esp_err_to_name.py
sphinx_idf_theme==0.2

43
docs/sanitize_version.py Normal file
View File

@ -0,0 +1,43 @@
# Tiny Python module to sanitize a Git version into something that can be used in a URL
#
# (this is used in multiple places: conf_common.py and in tools/ci/docs_deploy
#
# Copyright 2020 Espressif Systems (Shanghai) PTE LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
def sanitize_version(original_version):
""" Given a version (probably output from 'git describe --always' or similar), return
a URL-safe sanitized version. (this is used as 'release' config variable when building
the docs.)
Will override the original version with the Gitlab CI CI_COMMIT_REF_NAME environment variable if
this is present.
Also follows the RTD-ism that master branch is named 'latest'
"""
try:
version = os.environ['CI_COMMIT_REF_NAME']
except KeyError:
version = original_version
if version == "master":
return "latest"
version = version.replace('/', '-')
return version

View File

@ -32,7 +32,7 @@ C 文件可以包含多个测试用例。测试文件的名字要以 “test”
来声明主函数的区域, ``unity_platform.c`` 会自动调用
``UNITY_BEGIN()``\ 然后运行测试用例,最后调用 ``UNITY_END()``\ 。
``test`` 子目录需要包含 ref`组件 CMakeLists.txt <component-directories-cmake>`因为他们本身就是一种组件。ESP-IDF 使用了
``test`` 子目录需要包含 ref`组件 CMakeLists.txt <component-directories-cmake>`因为他们本身就是一种组件。ESP-IDF 使用了
``unity`` 测试框架,需要将其指定为组件的依赖项。通常,组件
ref`需要手动指定待编译的源文件 <cmake-file-globbing>`;但是,对于测试组件来说,这个要求被放宽了,仅仅是建议使用 “COMPONENT_SRCDIRS”。
@ -103,14 +103,14 @@ DUT 进行写入和运行测试。
DUT1master终端
.. code:: bash
.. code::
Waiting for signal: [output high level]!
Please press "Enter" key once any board send this signal.
DUT2slave终端
.. code:: bash
.. code::
Send signal: [output high level]!
@ -179,7 +179,7 @@ DUT2slave终端
当单元测试应用程序空闲时,输入回车键,它会打印出测试菜单,其中包含所有的测试项目。
.. code:: bash
.. code::
Here's the test menu, pick your combo:
(1) "esp_ota_begin() verifies arguments" [ota]
@ -226,7 +226,7 @@ DUT2slave终端
一旦选择了多设备测试用例,它会打印一个子菜单:
.. code:: bash
.. code::
Running gpio master/slave test example...
gpio master/slave test example
@ -237,7 +237,7 @@ DUT2slave终端
与多设备测试用例相似,多阶段测试用例也会打印子菜单:
.. code:: bash
.. code::
Running reset reason check for deepsleep...
reset reason check for deepsleep

View File

@ -17,7 +17,7 @@ C 文件可以包含多个测试用例。测试文件的名字要以 “test”
测试用例需要通过 C 文件中特定的函数来添加,如下所示:
.. code:: c
.. code-block:: c
TEST_CASE("test name", "[module name]"
{
@ -187,7 +187,7 @@ DUT2 终端::
当单元测试应用程序空闲时,输入回车键,它会打印出测试菜单,其中包含所有的测试项目。
.. code:: bash
.. code::
Here's the test menu, pick your combo:
(1) "esp_ota_begin() verifies arguments" [ota]
@ -234,7 +234,7 @@ DUT2 终端::
一旦选择了多设备测试用例,它会打印一个子菜单:
.. code:: bash
.. code::
Running gpio master/slave test example...
gpio master/slave test example
@ -245,7 +245,7 @@ DUT2 终端::
与多设备测试用例相似,多阶段测试用例也会打印子菜单:
.. code:: bash
.. code::
Running reset reason check for deepsleep...
reset reason check for deepsleep

View File

@ -16,7 +16,7 @@ except ImportError:
# General information about the project.
project = u'ESP-IDF 编程指南'
copyright = u'2016 - 2020 乐鑫信息科技(上海)股份有限公司'
copyright = u'2016 - 2021 乐鑫信息科技(上海)股份有限公司'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@ -1,421 +1,421 @@
********************************
快速入门 (CMake)
********************************
:link_to_translation:`en:[英文]`
.. include:: ../cmake-warning.rst
.. include:: ../cmake-pending-features.rst
本文档旨在指导用户创建 ESP32 的软件环境。本文将通过一个简单的例子,说明 ESP-IDF (Espressif IoT Development Framework) 的使用方法,包括配置、编译、下载固件到开发板等步骤。
.. include:: /_build/inc/version-note.inc
概述
============
ESP32 是一套 Wi-Fi (2.4 GHz) 和蓝牙 (4.2) 双模解决方案,集成了高性能的 CPU 内核、超低功耗协处理器和丰富的外设。ESP32 采用 40 nm 工艺制成,具有最佳的功耗性能、射频性能、稳定性、通用性和可靠性,适用于各种应用和不同功耗需求。
乐鑫为用户提供完整的软、硬件资源,支持 ESP32 设备的开发。我们的软件开发环境 ESP-IDF 能够帮助用户快速开发物联网 (IoT) 应用,满足用户对于 Wi-Fi、蓝牙、低功耗等性能的需求。
准备工作
====================
开发 ESP32 应用程序需要准备:
* **电脑**:安装 Windows、Linux 或者 Mac 操作系统
* **工具链**:用于编译 ESP32 代码
* **编译工具**:用于编译 ESP32 完整**应用程序**的 CMake 和 Ninja
* **ESP-IDF**:包含 ESP32 API 和用于操作 **工具链** 的脚本
* **文本编辑器**:编写 C 语言程序,例如 `Eclipse <https://www.eclipse.org/>`_
* **ESP32 开发板** 和将其连接到 **电脑** 的 **USB 线**
.. figure:: ../../_static/what-you-need-cmake.png
:align: center
:alt: Development of applications for ESP32
:figclass: align-center
开发应用程序
开发环境的准备工作包括以下两部分:
1. 设置 **工具链**
2. 从 GitHub 上获取 **ESP-IDF**
开发环境设置完成后,遵循以下步骤创建 ESP-IDF 应用程序:
1. 配置**工程** 并编写代码
2. 编译**工程** 并链接成一个**应用程序**
3. 通过 USB/串口连接,烧录(上传)预编译的**应用程序****ESP32**
4. 通过 USB/串口,监视/调试**应用程序**输出
.. The label below is placeholder to link a new section "Installation Step by Step"
.. _get-started-step-by-step-cmake:
开发板指南
========================
如果你有下列任一 ESP32 开发板,请点击对应的链接进行硬件设置:
.. toctree::
:maxdepth: 1
ESP32 DevKitC <get-started-devkitc>
ESP-WROVER-KIT <get-started-wrover-kit>
ESP32-PICO-KIT <get-started-pico-kit>
如果你使用其它开发板,请查看下面的内容。
.. _get-started-setup-toolchain-cmake:
设置工具链
======================
用 ESP32 进行开发最快的方法是安装预编译的工具链。请根据你的操作系,点击对应的链接,并按照链接中的指导进行安装。
.. toctree::
:hidden:
Windows <windows-setup>
Linux <linux-setup>
MacOS <macos-setup>
+-------------------+-------------------+-------------------+
| |windows-logo| | |linux-logo| | |macos-logo| |
+-------------------+-------------------+-------------------+
| `Windows`_ | `Linux`_ | `Mac OS`_ |
+-------------------+-------------------+-------------------+
.. |windows-logo| image:: ../../_static/windows-logo.png
:target: ../get-started-cmake/windows-setup.html
.. |linux-logo| image:: ../../_static/linux-logo.png
:target: ../get-started-cmake/linux-setup.html
.. |macos-logo| image:: ../../_static/macos-logo.png
:target: ../get-started-cmake/macos-setup.html
.. _Windows: ../get-started-cmake/windows-setup.html
.. _Linux: ../get-started-cmake/linux-setup.html
.. _Mac OS: ../get-started-cmake/macos-setup.html
.. note::
我们使用用户名主目录下的 ``esp`` 子目录Linux 和 MacOS 为 ``~/esp``Windows 为 ``%userprofile%\esp``)来进行一切有关 ESP-IDF 的安装操作。你也可以使用其他目录,但是需要注意调整相应的指令。
你可以安装预编译的工具链或者自定义你的环境,这完全取决于个人经验和偏好。如果你要自定义环境,请参考 :ref:`get-started-customized-setup-cmake`
工具链设置完成后,继续阅读 :ref:`get-started-get-esp-idf-cmake` 一节。
.. _get-started-get-esp-idf-cmake:
获取 ESP-IDF
==================
工具链(包括用于编译和构建应用程序的程序)安装完成后,你还需要 ESP32 相关的 API/库。你可在乐鑫提供的 `ESP-IDF 仓库 <https://github.com/espressif/esp-idf>`_ 中获取 API/库本地副本。打开终端,切换到你要存放 ESP-IDF 的目录,然后使用 ``git clone`` 命令克隆远程仓库。
Linux 和 MacOS
~~~~~~~~~~~~~~~~~~~~~~~~~~~
获取本地副本:打开终端,切换到你要存放 ESP-IDF 的工作目录,使用 ``git clone`` 命令克隆远程仓库:
.. include:: /_build/inc/git-clone-bash.inc
ESP-IDF 将会被下载到 ``~/esp/esp-idf`` 目录下。
有关在给定情况下使用哪个 ESP-IDF 版本的信息,请参阅 :doc:`/versions`
Windows Command Prompt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /_build/inc/git-clone-windows.inc
ESP-IDF 将会被下载到用户的 ``esp\esp-idf`` 目录下。
有关在给定情况下使用哪个 ESP-IDF 版本的信息,请参阅 :doc:`/versions`
.. include:: /_build/inc/git-clone-notes.inc
.. highlight:: bash
.. note::
注意这里有个 ``--recursive`` 选项。如果你克隆 ESP-IDF 时没有带这个选项,你还需要运行额外的命令来获取子模块::
cd esp-idf
git submodule update --init
.. _get-started-setup-path-cmake:
设置环境变量
===========================
ESP-IDF 的正常运行需要设置两个环境变量:
- ``IDF_PATH`` 应设置为 ESP-IDF 根目录的路径。
- ``PATH`` 应包括同一 ``IDF_PATH`` 目录下的 ``tools`` 目录路径。
你需在你的电脑中设置这两个变量,否则工程将不能编译。
你可以在每次 PC 重启时手动设置,你也可以在用户配置中进行永久设置,具体请参照 :doc:`add-idf_path-to-profile` 小节中的 :ref:`Windows <add-paths-to-profile-windows-cmake>`:ref:`Linux 和 MacOS <add-idf_path-to-profile-linux-macos-cmake>` 相关指导进行操作。
.. _get-started-start-project-cmake:
创建一个工程
======================
现在可以开始创建 ESP32 应用程序了。为了快速开始,我们这里以 IDF 的 :idf:`examples` 目录下的 :example:`get-started/hello_world` 工程为例进行说明。
:example:`get-started/hello_world` 拷贝到 ``~/esp`` 目录:
Linux 和 MacOS
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
cd ~/esp
cp -r $IDF_PATH/examples/get-started/hello_world .
Windows Command Prompt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: batch
cd %userprofile%\esp
xcopy /e /i %IDF_PATH%\examples\get-started\hello_world hello_world
ESP-IDF 的 :idf:`examples` 目录下有一系列示例工程,都可以按照上面的方法进行创建。
你也可以在原有位置创建示例,无需事先拷贝这些示例。
.. important::
esp-idf 构建系统不支持在路径中存在空格。
.. _get-started-connect-cmake:
连接
=======
还有几个步骤就完成了。在继续后续操作前,先将 ESP32 开发板连接到 PC然后检查串口号看看它能否正常通信。如果你不知道如何操作请查看 :doc:`establish-serial-connection` 中的相关指导。请注意一下端口号,我们在下一步中会用到。
.. _get-started-configure-cmake:
配置
=========
进入 ``hello_world`` 应用程序副本目录,运行 ``menuconfig`` 工程配置工具:
Linux 和 MacOS
~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
cd ~/esp/hello_world
idf.py menuconfig
Windows Command Prompt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: batch
cd %userprofile%\esp\hello_world
idf.py menuconfig
.. note:: 如果你收到未发现 ``idf.py`` 的报错信息,查看是否如上 :ref:`get-started-setup-path-cmake` 所述将 ``tools`` 目录添加到你的路径中。如果 ``tools`` 目录中没有 ``idf.py``,查看 :ref:`get-started-get-esp-idf-cmake` 中 CMake 预览所处的分支是否正确。
.. note:: 对于 Windows 用户而言Python 2.7 安装器会尝试配置 Windows关联扩展名为 ``.py`` 的 Python 2 文件。如果单独安装的程序(如 Visual Studio Python 工具)关联到其他 Python 版本,``idf.py`` 可能无法运行(而仅是在 Visual Studio 中打开此文件)。你可以每次运行 ``C:\Python27\python idf.py`` 或更改 Windows 中有关``.py`` 文件的关联设置。
.. note:: 对于 Linux 用户而言,如果默认为 Python 3.x 版本,你需要运行 ``python2 idf.py``
如果之前的步骤都正确,则会显示下面的菜单:
.. figure:: ../../_static/project-configuration.png
:align: center
:alt: Project configuration - Home window
:figclass: align-center
工程配置 - 主窗口
下面是一些使用 ``menuconfig`` 的小技巧:
* 使用 up & down 组合键在菜单中上下移动
* 使用 Enter 键进入一个子菜单Escape 键进入上一层菜单或退出整个菜单
* 输入 ``?`` 查看帮助信息Enter 键退出帮助屏幕
* 使用空格键或 ``Y`` 和 ``N`` 键来使能 (Yes) 和禁止 (No) 带有复选框 "``[*]``" 的配置项
* 当光标在某个配置项上面高亮时,输入 ``?`` 可以直接查看该项的帮助信息
* 输入 ``/`` 搜索配置项
.. attention::
如果 ESP32-DevKitC 板载的是 ESP32-SOLO-1 模组,请务必在烧写示例程序之前在 menuconfig 中使能单核模式(:ref:`CONFIG_FREERTOS_UNICORE`)。
.. _get-started-build-cmake:
创建一个工程
==========================
.. highlight:: bash
现在可以编译工程了,执行指令::
idf.py build
这条命令会编译应用程序和所有的 ESP-IDF 组件,生成 bootloader、区分表和应用程序 bin 文件。
.. code-block:: none
$ idf.py build
Running cmake in directory /path/to/hello_world/build
Executing "cmake -G Ninja --warn-uninitialized /path/to/hello_world"...
Warn about uninitialized values.
-- Found Git: /usr/bin/git (found version "2.17.0")
-- Building empty aws_iot component due to configuration
-- Component names: ...
-- Component paths: ...
... (more lines of build system output)
[527/527] Generating hello-world.bin
esptool.py v2.3.1
Project build complete. To flash, run this command:
../../../components/esptool_py/esptool/esptool.py -p (PORT) -b 921600 write_flash --flash_mode dio --flash_size detect --flash_freq 40m 0x10000 build/hello-world.bin build 0x1000 build/bootloader/bootloader.bin 0x8000 build/partition_table/partition-table.bin
or run 'idf.py -p PORT flash'
如果没有任何报错,将会生成 bin 文件,至此编译完成。
.. _get-started-flash-cmake:
烧录到设备
==========================
现在可以将应用程序烧录到 ESP32 板子上,执行指令::
idf.py -p PORT flash
将端口改为 ESP32 板子的串口名称。Windows 平台的端口名称类似 ``COM1``,而 MacOS 则以 ``/dev/cu.`` 开头Linux 则是 ``/dev/tty``。详情请参照 :doc:`establish-serial-connection`
该步骤旨在将此前编译的 bin 文件烧录到 ESP32 板子上。
.. note:: 无需在 ``idf.py flash`` 之前运行 ``idf.py build``,烧录这一步会按照烧录前编写的要求(如有)自动编写工程。
.. code-block:: none
Running esptool.py in directory [...]/esp/hello_world
Executing "python [...]/esp-idf/components/esptool_py/esptool/esptool.py -b 460800 write_flash @flash_project_args"...
esptool.py -b 460800 write_flash --flash_mode dio --flash_size detect --flash_freq 40m 0x1000 bootloader/bootloader.bin 0x8000 partition_table/partition-table.bin 0x10000 hello-world.bin
esptool.py v2.3.1
Connecting....
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0220
Compressed 22992 bytes to 13019...
Wrote 22992 bytes (13019 compressed) at 0x00001000 in 0.3 seconds (effective 558.9 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 82...
Wrote 3072 bytes (82 compressed) at 0x00008000 in 0.0 seconds (effective 5789.3 kbit/s)...
Hash of data verified.
Compressed 136672 bytes to 67544...
Wrote 136672 bytes (67544 compressed) at 0x00010000 in 1.9 seconds (effective 567.5 kbit/s)...
Hash of data verified.
Leaving...
Hard resetting via RTS pin...
如果没有任何问题,在烧录的最后阶段,板子将会复位,应用程序 "hello_world" 开始运行。
.. (目前暂不支持)如果你想使用 Eclipse IDE 而不是运行 ``idf.py``,请参考 :doc:`Eclipse guide <eclipse-setup>`。
.. _get-started-build-monitor-cmake:
监视器
================
如果要查看 "hello_world" 程序是否真的在运行,输入命令 ``idf.py -p PORT monitor``。这个命令会启动 :doc:`IDF Monitor <idf-monitor>` 程序::
$ idf.py -p /dev/ttyUSB0 monitor
Running idf_monitor in directory [...]/esp/hello_world/build
Executing "python [...]/esp-idf/tools/idf_monitor.py -b 115200 [...]/esp/hello_world/build/hello-world.elf"...
--- idf_monitor on /dev/ttyUSB0 115200 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57
...
在启动消息和诊断消息后,你就能看到 "Hello world!" 程序所打印的消息:
.. code-block:: none
...
Hello world!
Restarting in 10 seconds...
I (211) cpu_start: Starting scheduler on APP CPU.
Restarting in 9 seconds...
Restarting in 8 seconds...
Restarting in 7 seconds...
要退出监视器,请使用快捷键 ``Ctrl+]``
.. note::
如果串口打印的不是上面显示的消息而是类似下面的乱码::
e<><65><EFBFBD>)(Xn@<40>y.!<21><>(<28>PW+)<29><>Hn9a؅/9<>!<21>t5<74><35>P<EFBFBD>~<7E>k<EFBFBD><6B>e<EFBFBD>ea<65>5<EFBFBD>jA
~zY<7A><59>Y(1<>,1<15><> e<><65><EFBFBD>)(Xn@<40>y.!Dr<44>zY(<28>jpi<70>|<7C>+z5Ymvp
或者监视器程序启动失败,那么可能你的开发板用的是 26 MHz 晶振,而大多数开发板用的是 40 MHz 晶振,并且 ESP-IDF 默认的也是这一数值。请退出监视器,回到 :ref:`menuconfig <get-started-configure-cmake>`,将 :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` 改为 26 MHz然后再次 :ref:`编写和烧录 <get-started-flash-cmake>` 程序。请在 ``idf.py menuconfig`` 的 Component config --> ESP32-specific --> Main XTAL frequency 中配置。
.. note::
你可以将编写、烧录和监视整合到一步当中,如下所示::
idf.py -p PORT flash monitor
有关监视器使用的快捷键和其他详情,请参阅 :doc:`IDF Monitor <idf-monitor>`
有关 ``idf.py`` 的全部命令和选项,请参阅 :ref:`idf.py`
你已完成 ESP32 的入门!
现在你可以尝试其他的示例工程 :idf:`examples`,或者直接开发自己的应用程序。
更新 ESP-IDF
=============
使用 ESP-IDF 一段时间后,您可能想通过升级来获取新的功能或者修复 bug最简单的升级方式就是删除已有的 ``esp-idf`` 文件夹然后重新克隆一个,即重复 :ref:`get-started-get-esp-idf` 里的操作。
然后 :doc:`添加 IDF 到工作路径 <add-idf_path-to-profile>`,这样工具链脚本就能够知道这一版本的 ESP-IDF 的具体位置。
另外一种方法是只更新有改动的部分。:ref:`更新步骤取决于现在用的ESP-IDF版本 <updating>`
相关文档
=================
.. toctree::
:maxdepth: 1
add-idf_path-to-profile
establish-serial-connection
eclipse-setup
idf-monitor
toolchain-setup-scratch
.. _Stable version: https://docs.espressif.com/projects/esp-idf/en/stable/
.. _Releases page: https://github.com/espressif/esp-idf/releases
********************************
快速入门 (CMake)
********************************
:link_to_translation:`en:[英文]`
.. include:: ../cmake-warning.rst
.. include:: ../cmake-pending-features.rst
本文档旨在指导用户创建 ESP32 的软件环境。本文将通过一个简单的例子,说明 ESP-IDF (Espressif IoT Development Framework) 的使用方法,包括配置、编译、下载固件到开发板等步骤。
.. include:: /_build/inc/version-note.inc
概述
============
ESP32 是一套 Wi-Fi (2.4 GHz) 和蓝牙 (4.2) 双模解决方案,集成了高性能的 CPU 内核、超低功耗协处理器和丰富的外设。ESP32 采用 40 nm 工艺制成,具有最佳的功耗性能、射频性能、稳定性、通用性和可靠性,适用于各种应用和不同功耗需求。
乐鑫为用户提供完整的软、硬件资源,支持 ESP32 设备的开发。我们的软件开发环境 ESP-IDF 能够帮助用户快速开发物联网 (IoT) 应用,满足用户对于 Wi-Fi、蓝牙、低功耗等性能的需求。
准备工作
====================
开发 ESP32 应用程序需要准备:
* **电脑**:安装 Windows、Linux 或者 Mac 操作系统
* **工具链**:用于编译 ESP32 代码
* **编译工具**:用于编译 ESP32 完整**应用程序**的 CMake 和 Ninja
* **ESP-IDF**:包含 ESP32 API 和用于操作 **工具链** 的脚本
* **文本编辑器**:编写 C 语言程序,例如 `Eclipse <https://www.eclipse.org/>`_
* **ESP32 开发板** 和将其连接到 **电脑** 的 **USB 线**
.. figure:: ../../_static/what-you-need-cmake.png
:align: center
:alt: Development of applications for ESP32
:figclass: align-center
开发应用程序
开发环境的准备工作包括以下两部分:
1. 设置 **工具链**
2. 从 GitHub 上获取 **ESP-IDF**
开发环境设置完成后,遵循以下步骤创建 ESP-IDF 应用程序:
1. 配置**工程** 并编写代码
2. 编译**工程** 并链接成一个**应用程序**
3. 通过 USB/串口连接,烧录(上传)预编译的**应用程序****ESP32**
4. 通过 USB/串口,监视/调试**应用程序**输出
.. The label below is placeholder to link a new section "Installation Step by Step"
.. _get-started-step-by-step-cmake:
开发板指南
========================
如果你有下列任一 ESP32 开发板,请点击对应的链接进行硬件设置:
.. toctree::
:maxdepth: 1
ESP32 DevKitC <get-started-devkitc>
ESP-WROVER-KIT <get-started-wrover-kit>
ESP32-PICO-KIT <get-started-pico-kit>
如果你使用其它开发板,请查看下面的内容。
.. _get-started-setup-toolchain-cmake:
设置工具链
======================
用 ESP32 进行开发最快的方法是安装预编译的工具链。请根据你的操作系,点击对应的链接,并按照链接中的指导进行安装。
.. toctree::
:hidden:
Windows <windows-setup>
Linux <linux-setup>
MacOS <macos-setup>
+-------------------+-------------------+-------------------+
| |windows-logo| | |linux-logo| | |macos-logo| |
+-------------------+-------------------+-------------------+
| `Windows`_ | `Linux`_ | `Mac OS`_ |
+-------------------+-------------------+-------------------+
.. |windows-logo| image:: ../../_static/windows-logo.png
:target: ../get-started-cmake/windows-setup.html
.. |linux-logo| image:: ../../_static/linux-logo.png
:target: ../get-started-cmake/linux-setup.html
.. |macos-logo| image:: ../../_static/macos-logo.png
:target: ../get-started-cmake/macos-setup.html
.. _Windows: ../get-started-cmake/windows-setup.html
.. _Linux: ../get-started-cmake/linux-setup.html
.. _Mac OS: ../get-started-cmake/macos-setup.html
.. note::
我们使用用户名主目录下的 ``esp`` 子目录Linux 和 MacOS 为 ``~/esp``Windows 为 ``%userprofile%\esp``)来进行一切有关 ESP-IDF 的安装操作。你也可以使用其他目录,但是需要注意调整相应的指令。
你可以安装预编译的工具链或者自定义你的环境,这完全取决于个人经验和偏好。如果你要自定义环境,请参考 :ref:`get-started-customized-setup-cmake`
工具链设置完成后,继续阅读 :ref:`get-started-get-esp-idf-cmake` 一节。
.. _get-started-get-esp-idf-cmake:
获取 ESP-IDF
==================
工具链(包括用于编译和构建应用程序的程序)安装完成后,你还需要 ESP32 相关的 API/库。你可在乐鑫提供的 `ESP-IDF 仓库 <https://github.com/espressif/esp-idf>`_ 中获取 API/库本地副本。打开终端,切换到你要存放 ESP-IDF 的目录,然后使用 ``git clone`` 命令克隆远程仓库。
Linux 和 MacOS
~~~~~~~~~~~~~~~~~~~~~~~~~~~
获取本地副本:打开终端,切换到你要存放 ESP-IDF 的工作目录,使用 ``git clone`` 命令克隆远程仓库:
.. include:: /_build/inc/git-clone-bash.inc
ESP-IDF 将会被下载到 ``~/esp/esp-idf`` 目录下。
有关在给定情况下使用哪个 ESP-IDF 版本的信息,请参阅 :doc:`/versions`
Windows Command Prompt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /_build/inc/git-clone-windows.inc
ESP-IDF 将会被下载到用户的 ``esp\esp-idf`` 目录下。
有关在给定情况下使用哪个 ESP-IDF 版本的信息,请参阅 :doc:`/versions`
.. include:: /_build/inc/git-clone-notes.inc
.. highlight:: bash
.. note::
注意这里有个 ``--recursive`` 选项。如果你克隆 ESP-IDF 时没有带这个选项,你还需要运行额外的命令来获取子模块::
cd esp-idf
git submodule update --init
.. _get-started-setup-path-cmake:
设置环境变量
===========================
ESP-IDF 的正常运行需要设置两个环境变量:
- ``IDF_PATH`` 应设置为 ESP-IDF 根目录的路径。
- ``PATH`` 应包括同一 ``IDF_PATH`` 目录下的 ``tools`` 目录路径。
你需在你的电脑中设置这两个变量,否则工程将不能编译。
你可以在每次 PC 重启时手动设置,你也可以在用户配置中进行永久设置,具体请参照 :doc:`add-idf_path-to-profile` 小节中的 :ref:`Windows <add-paths-to-profile-windows-cmake>`:ref:`Linux 和 MacOS <add-idf_path-to-profile-linux-macos-cmake>` 相关指导进行操作。
.. _get-started-start-project-cmake:
创建一个工程
======================
现在可以开始创建 ESP32 应用程序了。为了快速开始,我们这里以 IDF 的 :idf:`examples` 目录下的 :example:`get-started/hello_world` 工程为例进行说明。
:example:`get-started/hello_world` 拷贝到 ``~/esp`` 目录:
Linux 和 MacOS
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
cd ~/esp
cp -r $IDF_PATH/examples/get-started/hello_world .
Windows Command Prompt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: batch
cd %userprofile%\esp
xcopy /e /i %IDF_PATH%\examples\get-started\hello_world hello_world
ESP-IDF 的 :idf:`examples` 目录下有一系列示例工程,都可以按照上面的方法进行创建。
你也可以在原有位置创建示例,无需事先拷贝这些示例。
.. important::
esp-idf 构建系统不支持在路径中存在空格。
.. _get-started-connect-cmake:
连接
=======
还有几个步骤就完成了。在继续后续操作前,先将 ESP32 开发板连接到 PC然后检查串口号看看它能否正常通信。如果你不知道如何操作请查看 :doc:`establish-serial-connection` 中的相关指导。请注意一下端口号,我们在下一步中会用到。
.. _get-started-configure-cmake:
配置
=========
进入 ``hello_world`` 应用程序副本目录,运行 ``menuconfig`` 工程配置工具:
Linux 和 MacOS
~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
cd ~/esp/hello_world
idf.py menuconfig
Windows Command Prompt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: batch
cd %userprofile%\esp\hello_world
idf.py menuconfig
.. note:: 如果你收到未发现 ``idf.py`` 的报错信息,查看是否如上 :ref:`get-started-setup-path-cmake` 所述将 ``tools`` 目录添加到你的路径中。如果 ``tools`` 目录中没有 ``idf.py``,查看 :ref:`get-started-get-esp-idf-cmake` 中 CMake 预览所处的分支是否正确。
.. note:: 对于 Windows 用户而言Python 2.7 安装器会尝试配置 Windows关联扩展名为 ``.py`` 的 Python 2 文件。如果单独安装的程序(如 Visual Studio Python 工具)关联到其他 Python 版本,``idf.py`` 可能无法运行(而仅是在 Visual Studio 中打开此文件)。你可以每次运行 ``C:\Python27\python idf.py`` 或更改 Windows 中有关``.py`` 文件的关联设置。
.. note:: 对于 Linux 用户而言,如果默认为 Python 3.x 版本,你需要运行 ``python2 idf.py``
如果之前的步骤都正确,则会显示下面的菜单:
.. figure:: ../../_static/project-configuration.png
:align: center
:alt: Project configuration - Home window
:figclass: align-center
工程配置 - 主窗口
下面是一些使用 ``menuconfig`` 的小技巧:
* 使用 up & down 组合键在菜单中上下移动
* 使用 Enter 键进入一个子菜单Escape 键进入上一层菜单或退出整个菜单
* 输入 ``?`` 查看帮助信息Enter 键退出帮助屏幕
* 使用空格键或 ``Y`` 和 ``N`` 键来使能 (Yes) 和禁止 (No) 带有复选框 "``[*]``" 的配置项
* 当光标在某个配置项上面高亮时,输入 ``?`` 可以直接查看该项的帮助信息
* 输入 ``/`` 搜索配置项
.. attention::
如果 ESP32-DevKitC 板载的是 ESP32-SOLO-1 模组,请务必在烧写示例程序之前在 menuconfig 中使能单核模式(:ref:`CONFIG_FREERTOS_UNICORE`)。
.. _get-started-build-cmake:
创建一个工程
==========================
.. highlight:: bash
现在可以编译工程了,执行指令::
idf.py build
这条命令会编译应用程序和所有的 ESP-IDF 组件,生成 bootloader、区分表和应用程序 bin 文件。
.. code-block:: none
$ idf.py build
Running cmake in directory /path/to/hello_world/build
Executing "cmake -G Ninja --warn-uninitialized /path/to/hello_world"...
Warn about uninitialized values.
-- Found Git: /usr/bin/git (found version "2.17.0")
-- Building empty aws_iot component due to configuration
-- Component names: ...
-- Component paths: ...
... (more lines of build system output)
[527/527] Generating hello-world.bin
esptool.py v2.3.1
Project build complete. To flash, run this command:
../../../components/esptool_py/esptool/esptool.py -p (PORT) -b 921600 write_flash --flash_mode dio --flash_size detect --flash_freq 40m 0x10000 build/hello-world.bin build 0x1000 build/bootloader/bootloader.bin 0x8000 build/partition_table/partition-table.bin
or run 'idf.py -p PORT flash'
如果没有任何报错,将会生成 bin 文件,至此编译完成。
.. _get-started-flash-cmake:
烧录到设备
==========================
现在可以将应用程序烧录到 ESP32 板子上,执行指令::
idf.py -p PORT flash
将端口改为 ESP32 板子的串口名称。Windows 平台的端口名称类似 ``COM1``,而 MacOS 则以 ``/dev/cu.`` 开头Linux 则是 ``/dev/tty``。详情请参照 :doc:`establish-serial-connection`
该步骤旨在将此前编译的 bin 文件烧录到 ESP32 板子上。
.. note:: 无需在 ``idf.py flash`` 之前运行 ``idf.py build``,烧录这一步会按照烧录前编写的要求(如有)自动编写工程。
.. code-block:: none
Running esptool.py in directory [...]/esp/hello_world
Executing "python [...]/esp-idf/components/esptool_py/esptool/esptool.py -b 460800 write_flash @flash_project_args"...
esptool.py -b 460800 write_flash --flash_mode dio --flash_size detect --flash_freq 40m 0x1000 bootloader/bootloader.bin 0x8000 partition_table/partition-table.bin 0x10000 hello-world.bin
esptool.py v2.3.1
Connecting....
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0220
Compressed 22992 bytes to 13019...
Wrote 22992 bytes (13019 compressed) at 0x00001000 in 0.3 seconds (effective 558.9 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 82...
Wrote 3072 bytes (82 compressed) at 0x00008000 in 0.0 seconds (effective 5789.3 kbit/s)...
Hash of data verified.
Compressed 136672 bytes to 67544...
Wrote 136672 bytes (67544 compressed) at 0x00010000 in 1.9 seconds (effective 567.5 kbit/s)...
Hash of data verified.
Leaving...
Hard resetting via RTS pin...
如果没有任何问题,在烧录的最后阶段,板子将会复位,应用程序 "hello_world" 开始运行。
.. (目前暂不支持)如果你想使用 Eclipse IDE 而不是运行 ``idf.py``,请参考 :doc:`Eclipse guide <eclipse-setup>`。
.. _get-started-build-monitor-cmake:
监视器
================
如果要查看 "hello_world" 程序是否真的在运行,输入命令 ``idf.py -p PORT monitor``。这个命令会启动 :doc:`IDF Monitor <idf-monitor>` 程序::
$ idf.py -p /dev/ttyUSB0 monitor
Running idf_monitor in directory [...]/esp/hello_world/build
Executing "python [...]/esp-idf/tools/idf_monitor.py -b 115200 [...]/esp/hello_world/build/hello-world.elf"...
--- idf_monitor on /dev/ttyUSB0 115200 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57
...
在启动消息和诊断消息后,你就能看到 "Hello world!" 程序所打印的消息:
.. code-block:: none
...
Hello world!
Restarting in 10 seconds...
I (211) cpu_start: Starting scheduler on APP CPU.
Restarting in 9 seconds...
Restarting in 8 seconds...
Restarting in 7 seconds...
要退出监视器,请使用快捷键 ``Ctrl+]``
如果串口打印的不是上面显示的消息而是类似下面的乱码:
.. figure:: ../../_static/get-started-garbled-output.png
:align: center
:alt: Garbled output
:figclass: align-center
或者监视器程序启动失败,那么可能你的开发板用的是 26 MHz 晶振,而 ESP-IDF 默认的是 40 MHz 晶振。请退出监视器,回到 :ref:`配置 <get-started-configure>`,将 :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` 改为 26 MHz然后再次 :ref:`编译和烧写 <get-started-build-flash>`。请在 ``make menuconfig`` 的 Component config --> ESP32-specific --> Main XTAL frequency 中配置。
.. note::
你可以将编写、烧录和监视整合到一步当中,如下所示::
idf.py -p PORT flash monitor
有关监视器使用的快捷键和其他详情,请参阅 :doc:`IDF Monitor <idf-monitor>`
有关 ``idf.py`` 的全部命令和选项,请参阅 :ref:`idf.py`
你已完成 ESP32 的入门!
现在你可以尝试其他的示例工程 :idf:`examples`,或者直接开发自己的应用程序。
更新 ESP-IDF
=============
使用 ESP-IDF 一段时间后,您可能想通过升级来获取新的功能或者修复 bug最简单的升级方式就是删除已有的 ``esp-idf`` 文件夹然后重新克隆一个,即重复 :ref:`get-started-get-esp-idf` 里的操作。
然后 :doc:`添加 IDF 到工作路径 <add-idf_path-to-profile>`,这样工具链脚本就能够知道这一版本的 ESP-IDF 的具体位置。
另外一种方法是只更新有改动的部分。:ref:`更新步骤取决于现在用的ESP-IDF版本 <updating>`
相关文档
=================
.. toctree::
:maxdepth: 1
add-idf_path-to-profile
establish-serial-connection
eclipse-setup
idf-monitor
toolchain-setup-scratch
.. _Stable version: https://docs.espressif.com/projects/esp-idf/en/stable/
.. _Releases page: https://github.com/espressif/esp-idf/releases

View File

@ -294,14 +294,14 @@ ESP-IDF 的 :idf:`examples` 目录下有一系列示例工程,都可以按照
要退出监视器,请使用快捷键 ``Ctrl+]``
.. note::
如果串口打印的不是上面显示的消息而是类似下面的乱码:
如果串口打印的不是上面显示的消息而是类似下面的乱码: ::
.. figure:: ../../_static/get-started-garbled-output.png
:align: center
:alt: Garbled output
:figclass: align-center
e<><65><EFBFBD>)(Xn@<40>y.!<21><>(<28>PW+)<29><>Hn9a؅/9<>!<21>t5<74><35>P<EFBFBD>~<7E>k<EFBFBD><6B>e<EFBFBD>ea<65>5<EFBFBD>jA
~zY<7A><59>Y(1<>,1<15><> e<><65><EFBFBD>)(Xn@<40>y.!Dr<44>zY(<28>jpi<70>|<7C>+z5Ymvp
或者监视器程序启动失败,那么可能你的开发板用的是 26 MHz 晶振,而 ESP-IDF 默认的是 40 MHz 晶振。请退出监视器,回到 :ref:`配置 <get-started-configure>`,将 :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` 改为 26 MHz然后再次 :ref:`编译和烧写 <get-started-build-flash>`。请在 ``make menuconfig`` 的 Component config --> ESP32-specific --> Main XTAL frequency 中配置。
或者监视器程序启动失败,那么可能你的开发板用的是 26 MHz 晶振,而 ESP-IDF 默认的是 40 MHz 晶振。请退出监视器,回到 :ref:`配置 <get-started-configure>`,将 :ref:`CONFIG_ESP32_XTAL_FREQ_SEL` 改为 26 MHz然后再次 :ref:`编译和烧写 <get-started-build-flash>`。请在 ``make menuconfig`` 的 Component config --> ESP32-specific --> Main XTAL frequency 中配置。
要一次性执行 ``make flash````make monitor``,输入 ``make flash monitor``。参考文档 :doc:`IDF Monitor <idf-monitor>` 里的快捷键和更多内容。

223
tools/ci/deploy_docs.py Executable file
View File

@ -0,0 +1,223 @@
#!/usr/bin/env python3
#
# CI script to deploy docs to a webserver. Not useful outside of CI environment
#
#
# Copyright 2020 Espressif Systems (Shanghai) PTE LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import glob
import os
import os.path
import re
import stat
import sys
import subprocess
import tarfile
import packaging.version
def env(variable, default=None):
""" Shortcut to return the expanded version of an environment variable """
return os.path.expandvars(os.environ.get(variable, default) if default else os.environ[variable])
# import sanitize_version from the docs directory, shared with here
sys.path.append(os.path.join(env("IDF_PATH"), "docs"))
from sanitize_version import sanitize_version # noqa
def main():
# if you get KeyErrors on the following lines, it's probably because you're not running in Gitlab CI
git_ver = env("GIT_VER") # output of git describe --always
ci_ver = env("CI_COMMIT_REF_NAME", git_ver) # branch or tag we're building for (used for 'release' & URL)
version = sanitize_version(ci_ver)
print("Git version: {}".format(git_ver))
print("CI Version: {}".format(ci_ver))
print("Deployment version: {}".format(version))
if not version:
raise RuntimeError("A version is needed to deploy")
build_dir = env("DOCS_BUILD_DIR") # top-level local build dir, where docs have already been built
if not build_dir:
raise RuntimeError("Valid DOCS_BUILD_DIR is needed to deploy")
url_base = env("DOCS_DEPLOY_URL_BASE") # base for HTTP URLs, used to print the URL to the log after deploying
docs_server = env("DOCS_DEPLOY_SERVER") # ssh server to deploy to
docs_user = env("DOCS_DEPLOY_SERVER_USER")
docs_path = env("DOCS_DEPLOY_PATH") # filesystem path on DOCS_SERVER
if not docs_server:
raise RuntimeError("Valid DOCS_DEPLOY_SERVER is needed to deploy")
if not docs_user:
raise RuntimeError("Valid DOCS_DEPLOY_SERVER_USER is needed to deploy")
docs_server = "{}@{}".format(docs_user, docs_server)
if not docs_path:
raise RuntimeError("Valid DOCS_DEPLOY_PATH is needed to deploy")
print("DOCS_DEPLOY_SERVER {} DOCS_DEPLOY_PATH {}".format(docs_server, docs_path))
tarball_path, version_urls = build_doc_tarball(version, git_ver, build_dir)
deploy(version, tarball_path, docs_path, docs_server)
print("Docs URLs:")
doc_deploy_type = os.getenv('TYPE')
for vurl in version_urls:
language, _, = vurl.split('/')
tag = '{}'.format(language)
url = "{}/{}/index.html".format(url_base, vurl) # (index.html needed for the preview server)
url = re.sub(r"([^:])//", r"\1/", url) # get rid of any // that isn't in the https:// part
print('[document {}][{}] {}'.format(doc_deploy_type, tag, url))
# note: it would be neater to use symlinks for stable, but because of the directory order
# (language first) it's kind of a pain to do on a remote server, so we just repeat the
# process but call the version 'stable' this time
if is_stable_version(version):
print("Deploying again as stable version...")
tarball_path, version_urls = build_doc_tarball("stable", git_ver, build_dir)
deploy("stable", tarball_path, docs_path, docs_server)
def deploy(version, tarball_path, docs_path, docs_server):
def run_ssh(commands):
""" Log into docs_server and run a sequence of commands using ssh """
print("Running ssh: {}".format(commands))
subprocess.run(["ssh", "-o", "BatchMode=yes", docs_server, "-x", " && ".join(commands)], check=True)
# copy the version tarball to the server
run_ssh(["mkdir -p {}".format(docs_path)])
print("Running scp {} to {}".format(tarball_path, "{}:{}".format(docs_server, docs_path)))
subprocess.run(["scp", "-B", tarball_path, "{}:{}".format(docs_server, docs_path)], check=True)
tarball_name = os.path.basename(tarball_path)
run_ssh(["cd {}".format(docs_path),
"rm -rf ./*/{}".format(version), # remove any pre-existing docs matching this version
"tar -zxvf {}".format(tarball_name), # untar the archive with the new docs
"rm {}".format(tarball_name)])
# Note: deleting and then extracting the archive is a bit awkward for updating stable/latest/etc
# as the version will be invalid for a window of time. Better to do it atomically, but this is
# another thing made much more complex by the directory structure putting language before version...
def build_doc_tarball(version, git_ver, build_dir):
""" Make a tar.gz archive of the docs, in the directory structure used to deploy as
the given version """
version_paths = []
tarball_path = "{}/{}.tar.gz".format(build_dir, version)
# find all the 'html/' directories under build_dir
html_dirs = glob.glob("{}/**/html/".format(build_dir), recursive=True)
print("Found %d html directories" % len(html_dirs))
pdfs = glob.glob("{}/**/latex/build/*.pdf".format(build_dir), recursive=True)
print("Found %d PDFs in latex directories" % len(pdfs))
# add symlink for stable and latest and adds them to PDF blob
symlinks = create_and_add_symlinks(version, git_ver, pdfs)
def not_sources_dir(ti):
""" Filter the _sources directories out of the tarballs """
if ti.name.endswith("/_sources"):
return None
ti.mode |= stat.S_IWGRP # make everything group-writeable
return ti
try:
os.remove(tarball_path)
except OSError:
pass
with tarfile.open(tarball_path, "w:gz") as tarball:
for html_dir in html_dirs:
# html_dir has the form '<ignored>/<language>/html/'
language_dirname = os.path.dirname(os.path.dirname(html_dir))
language = os.path.basename(language_dirname)
# when deploying, we want the top-level directory layout 'language/version'
archive_path = "{}/{}".format(language, version)
print("Archiving '{}' as '{}'...".format(html_dir, archive_path))
tarball.add(html_dir, archive_path, filter=not_sources_dir)
version_paths.append(archive_path)
for pdf_path in pdfs:
# pdf_path has the form '<ignored>/<language>/<target>/latex/build'
latex_dirname = os.path.dirname(pdf_path)
pdf_filename = os.path.basename(pdf_path)
language_dirname = os.path.dirname(os.path.dirname(latex_dirname))
language = os.path.basename(language_dirname)
# when deploying, we want the layout 'language/version/pdf'
archive_path = "{}/{}/{}".format(language, version, pdf_filename)
print("Archiving '{}' as '{}'...".format(pdf_path, archive_path))
tarball.add(pdf_path, archive_path)
for symlink in symlinks:
os.unlink(symlink)
return (os.path.abspath(tarball_path), version_paths)
def create_and_add_symlinks(version, git_ver, pdfs):
""" Create symbolic links for PDFs for 'latest' and 'stable' releases """
symlinks = []
if 'stable' in version or 'latest' in version:
for pdf_path in pdfs:
symlink_path = pdf_path.replace(git_ver, version)
os.symlink(pdf_path, symlink_path)
symlinks.append(symlink_path)
pdfs.extend(symlinks)
print("Found %d PDFs in latex directories after adding symlink" % len(pdfs))
return symlinks
def is_stable_version(version):
""" Heuristic for whether this is the latest stable release """
if not version.startswith("v"):
return False # branch name
if "-" in version:
return False # prerelease tag
git_out = subprocess.check_output(["git", "tag", "-l"]).decode("utf-8")
versions = [v.strip() for v in git_out.split("\n")]
versions = [v for v in versions if re.match(r"^v[\d\.]+$", v)] # include vX.Y.Z only
versions = [packaging.version.parse(v) for v in versions]
max_version = max(versions)
if max_version.public != version[1:]:
print("Stable version is v{}. This version is {}.".format(max_version.public, version))
return False
else:
print("This version {} is the stable version".format(version))
return True
if __name__ == "__main__":
main()

View File

@ -24,6 +24,7 @@ tools/ci/check_idf_version.sh
tools/ci/check-executable.sh
tools/ci/check-line-endings.sh
tools/ci/checkout_project_ref.py
tools/ci/deploy_docs.py
tools/ci/envsubst.py
tools/ci/mirror-submodule-update.sh
tools/ci/push_to_github.sh