[
  {
    "path": ".codespellrc",
    "content": "# See: https://github.com/codespell-project/codespell#using-a-config-file\n[codespell]\n# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here:\nignore-words-list = ,\ncheck-filenames =\ncheck-hidden =\nskip = ./.git\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# See: https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#about-the-dependabotyml-file\nversion: 2\n\nupdates:\n  # Configure check for outdated GitHub Actions actions in workflows.\n  # See: https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-dependabot\n  - package-ecosystem: github-actions\n    directory: / # Check the repository's workflows under /.github/workflows/\n    schedule:\n      interval: daily\n    labels:\n      - \"topic: infrastructure\"\n"
  },
  {
    "path": ".github/workflows/check-arduino.yml",
    "content": "name: Check Arduino\n\n# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows\non:\n  push:\n  pull_request:\n  schedule:\n    # Run every Tuesday at 8 AM UTC to catch breakage caused by new rules added to Arduino Lint.\n    - cron: \"0 8 * * TUE\"\n  workflow_dispatch:\n  repository_dispatch:\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Arduino Lint\n        uses: arduino/arduino-lint-action@v2\n        with:\n          compliance: specification\n          library-manager: update\n          # Always use this setting for official repositories. Remove for 3rd party projects.\n          official: true\n          project-type: library\n"
  },
  {
    "path": ".github/workflows/compile-examples.yml",
    "content": "name: Compile Examples\n\n# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows\non:\n  push:\n    paths:\n      - \".github/workflows/compile-examples.yml\"\n      - \"examples/**\"\n      - \"src/**\"\n  pull_request:\n    paths:\n      - \".github/workflows/compile-examples.yml\"\n      - \"examples/**\"\n      - \"src/**\"\n  schedule:\n    # Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms).\n    - cron: \"0 8 * * TUE\"\n  workflow_dispatch:\n  repository_dispatch:\n\njobs:\n  build:\n    name: ${{ matrix.board.fqbn }}\n    runs-on: ubuntu-latest\n\n    env:\n      SKETCHES_REPORTS_PATH: sketches-reports\n\n    strategy:\n      fail-fast: false\n\n      matrix:\n        board:\n          - fqbn: arduino:avr:nano\n            platforms: |\n              - name: arduino:avr\n            artifact-name-suffix: arduino-avr-nano\n          - fqbn: arduino:avr:mega\n            platforms: |\n              - name: arduino:avr\n            artifact-name-suffix: arduino-avr-mega\n          - fqbn: arduino:avr:leonardo\n            platforms: |\n              - name: arduino:avr\n            artifact-name-suffix: arduino-avr-leonardo\n          - fqbn: arduino:megaavr:nona4809\n            platforms: |\n              - name: arduino:megaavr\n            artifact-name-suffix: arduino-megaavr-nona4809\n          - fqbn: arduino:sam:arduino_due_x_dbg\n            platforms: |\n              - name: arduino:sam\n            artifact-name-suffix: arduino-sam-arduino_due_x_dbg\n          - fqbn: arduino:samd:mkrzero\n            platforms: |\n              - name: arduino:samd\n            artifact-name-suffix: arduino-samd-mkrzero\n          - fqbn: arduino:mbed_portenta:envie_m7:target_core=cm4\n            platforms: |\n              - name: arduino:mbed_portenta\n            artifact-name-suffix: arduino-mbed_portenta-envie_m7-target_core-cm4\n          - fqbn: arduino:mbed_portenta:envie_m7\n            platforms: |\n              - name: arduino:mbed_portenta\n            artifact-name-suffix: arduino-mbed_portenta-envie_m7\n          - fqbn: arduino:mbed_nano:nano33ble\n            platforms: |\n              - name: arduino:mbed_nano\n            artifact-name-suffix: arduino-mbed_nano-nano33ble\n          - fqbn: arduino:mbed_nano:nanorp2040connect\n            platforms: |\n              - name: arduino:mbed_nano\n            artifact-name-suffix: arduino-mbed_nano-nanorp2040connect\n          - fqbn: arduino:esp32:nano_nora\n            platforms: |\n              - name: arduino:esp32\n            artifact-name-suffix: arduino-esp32-nano_nora\n          - fqbn: arduino:zephyr:unoq\n            platforms: |\n              - name: arduino:zephyr\n            artifact-name-suffix: arduino-zephyr-unoq\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Compile examples\n        uses: arduino/compile-sketches@v1\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n          fqbn: ${{ matrix.board.fqbn }}\n          platforms: ${{ matrix.board.platforms }}\n          libraries: |\n            # Install the library from the local path.\n            - source-path: ./\n            # Additional library dependencies can be listed here.\n            # See: https://github.com/arduino/compile-sketches#libraries\n          sketch-paths: |\n            - examples\n          enable-deltas-report: true\n          sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }}\n\n      - name: Save sketches report as workflow artifact\n        uses: actions/upload-artifact@v7\n        with:\n          if-no-files-found: error\n          path: ${{ env.SKETCHES_REPORTS_PATH }}\n          name: sketches-report-${{ matrix.board.artifact-name-suffix }}\n"
  },
  {
    "path": ".github/workflows/report-size-deltas.yml",
    "content": "name: Report Size Deltas\n\n# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows\non:\n  push:\n    paths:\n      - \".github/workflows/report-size-deltas.yml\"\n  schedule:\n    # Run at the minimum interval allowed by GitHub Actions.\n    # Note: GitHub Actions periodically has outages which result in workflow failures.\n    # In this event, the workflows will start passing again once the service recovers.\n    - cron: \"*/5 * * * *\"\n  workflow_dispatch:\n  repository_dispatch:\n\njobs:\n  report:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Comment size deltas reports to PRs\n        uses: arduino/report-size-deltas@v1\n        with:\n          # Regex matching the names of the workflow artifacts created by the \"Compile Examples\" workflow\n          sketches-reports-source: ^sketches-report-.+\n"
  },
  {
    "path": ".github/workflows/spell-check.yml",
    "content": "name: Spell Check\n\n# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows\non:\n  push:\n  pull_request:\n  schedule:\n    # Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates.\n    - cron: \"0 8 * * TUE\"\n  workflow_dispatch:\n  repository_dispatch:\n\njobs:\n  spellcheck:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Spell check\n        uses: codespell-project/actions-codespell@master\n"
  },
  {
    "path": ".github/workflows/sync-labels.yml",
    "content": "# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md\nname: Sync Labels\n\n# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows\non:\n  push:\n    paths:\n      - \".github/workflows/sync-labels.ya?ml\"\n      - \".github/label-configuration-files/*.ya?ml\"\n  pull_request:\n    paths:\n      - \".github/workflows/sync-labels.ya?ml\"\n      - \".github/label-configuration-files/*.ya?ml\"\n  schedule:\n    # Run daily at 8 AM UTC to sync with changes to shared label configurations.\n    - cron: \"0 8 * * *\"\n  workflow_dispatch:\n  repository_dispatch:\n\nenv:\n  CONFIGURATIONS_FOLDER: .github/label-configuration-files\n  CONFIGURATIONS_ARTIFACT: label-configuration-files\n\njobs:\n  check:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Download JSON schema for labels configuration file\n        id: download-schema\n        uses: carlosperate/download-file-action@v2\n        with:\n          file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json\n          location: ${{ runner.temp }}/label-configuration-schema\n\n      - name: Install JSON schema validator\n        run: |\n          sudo npm install \\\n            --global \\\n            ajv-cli \\\n            ajv-formats\n\n      - name: Validate local labels configuration\n        run: |\n          # See: https://github.com/ajv-validator/ajv-cli#readme\n          ajv validate \\\n            --all-errors \\\n            -c ajv-formats \\\n            -s \"${{ steps.download-schema.outputs.file-path }}\" \\\n            -d \"${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}\"\n\n  download:\n    needs: check\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        filename:\n          # Filenames of the shared configurations to apply to the repository in addition to the local configuration.\n          # https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels\n          - universal.yml\n\n    steps:\n      - name: Download\n        uses: carlosperate/download-file-action@v2\n        with:\n          file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }}\n\n      - name: Pass configuration files to next job via workflow artifact\n        uses: actions/upload-artifact@v7\n        with:\n          path: |\n            *.yaml\n            *.yml\n          if-no-files-found: error\n          name: ${{ env.CONFIGURATIONS_ARTIFACT }}\n\n  sync:\n    needs: download\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Set environment variables\n        run: |\n          # See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable\n          echo \"MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml\" >> \"$GITHUB_ENV\"\n\n      - name: Determine whether to dry run\n        id: dry-run\n        if: >\n          github.event_name == 'pull_request' ||\n          (\n            (\n              github.event_name == 'push' ||\n              github.event_name == 'workflow_dispatch'\n            ) &&\n            github.ref != format('refs/heads/{0}', github.event.repository.default_branch)\n          )\n        run: |\n          # Use of this flag in the github-label-sync command will cause it to only check the validity of the\n          # configuration.\n          echo \"::set-output name=flag::--dry-run\"\n\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Download configuration files artifact\n        uses: actions/download-artifact@v8\n        with:\n          name: ${{ env.CONFIGURATIONS_ARTIFACT }}\n          path: ${{ env.CONFIGURATIONS_FOLDER }}\n\n      - name: Remove unneeded artifact\n        uses: geekyeggo/delete-artifact@v6\n        with:\n          name: ${{ env.CONFIGURATIONS_ARTIFACT }}\n\n      - name: Merge label configuration files\n        run: |\n          # Merge all configuration files\n          shopt -s extglob\n          cat \"${{ env.CONFIGURATIONS_FOLDER }}\"/*.@(yml|yaml) > \"${{ env.MERGED_CONFIGURATION_PATH }}\"\n\n      - name: Install github-label-sync\n        run: sudo npm install --global github-label-sync\n\n      - name: Sync labels\n        env:\n          GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        run: |\n          # See: https://github.com/Financial-Times/github-label-sync\n          github-label-sync \\\n            --labels \"${{ env.MERGED_CONFIGURATION_PATH }}\" \\\n            ${{ steps.dry-run.outputs.flag }} \\\n            ${{ github.repository }}\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "                  GNU LESSER GENERAL PUBLIC LICENSE\n                       Version 2.1, February 1999\n\n Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n[This is the first released version of the Lesser GPL.  It also counts\n as the successor of the GNU Library Public License, version 2, hence\n the version number 2.1.]\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicenses are intended to guarantee your freedom to share and change\nfree software--to make sure the software is free for all its users.\n\n  This license, the Lesser General Public License, applies to some\nspecially designated software packages--typically libraries--of the\nFree Software Foundation and other authors who decide to use it.  You\ncan use it too, but we suggest you first think carefully about whether\nthis license or the ordinary General Public License is the better\nstrategy to use in any particular case, based on the explanations below.\n\n  When we speak of free software, we are referring to freedom of use,\nnot price.  Our General Public Licenses are designed to make sure that\nyou have the freedom to distribute copies of free software (and charge\nfor this service if you wish); that you receive source code or can get\nit if you want it; that you can change the software and use pieces of\nit in new free programs; and that you are informed that you can do\nthese things.\n\n  To protect your rights, we need to make restrictions that forbid\ndistributors to deny you these rights or to ask you to surrender these\nrights.  These restrictions translate to certain responsibilities for\nyou if you distribute copies of the library or if you modify it.\n\n  For example, if you distribute copies of the library, whether gratis\nor for a fee, you must give the recipients all the rights that we gave\nyou.  You must make sure that they, too, receive or can get the source\ncode.  If you link other code with the library, you must provide\ncomplete object files to the recipients, so that they can relink them\nwith the library after making changes to the library and recompiling\nit.  And you must show them these terms so they know their rights.\n\n  We protect your rights with a two-step method: (1) we copyright the\nlibrary, and (2) we offer you this license, which gives you legal\npermission to copy, distribute and/or modify the library.\n\n  To protect each distributor, we want to make it very clear that\nthere is no warranty for the free library.  Also, if the library is\nmodified by someone else and passed on, the recipients should know\nthat what they have is not the original version, so that the original\nauthor's reputation will not be affected by problems that might be\nintroduced by others.\n\n  Finally, software patents pose a constant threat to the existence of\nany free program.  We wish to make sure that a company cannot\neffectively restrict the users of a free program by obtaining a\nrestrictive license from a patent holder.  Therefore, we insist that\nany patent license obtained for a version of the library must be\nconsistent with the full freedom of use specified in this license.\n\n  Most GNU software, including some libraries, is covered by the\nordinary GNU General Public License.  This license, the GNU Lesser\nGeneral Public License, applies to certain designated libraries, and\nis quite different from the ordinary General Public License.  We use\nthis license for certain libraries in order to permit linking those\nlibraries into non-free programs.\n\n  When a program is linked with a library, whether statically or using\na shared library, the combination of the two is legally speaking a\ncombined work, a derivative of the original library.  The ordinary\nGeneral Public License therefore permits such linking only if the\nentire combination fits its criteria of freedom.  The Lesser General\nPublic License permits more lax criteria for linking other code with\nthe library.\n\n  We call this license the \"Lesser\" General Public License because it\ndoes Less to protect the user's freedom than the ordinary General\nPublic License.  It also provides other free software developers Less\nof an advantage over competing non-free programs.  These disadvantages\nare the reason we use the ordinary General Public License for many\nlibraries.  However, the Lesser license provides advantages in certain\nspecial circumstances.\n\n  For example, on rare occasions, there may be a special need to\nencourage the widest possible use of a certain library, so that it becomes\na de-facto standard.  To achieve this, non-free programs must be\nallowed to use the library.  A more frequent case is that a free\nlibrary does the same job as widely used non-free libraries.  In this\ncase, there is little to gain by limiting the free library to free\nsoftware only, so we use the Lesser General Public License.\n\n  In other cases, permission to use a particular library in non-free\nprograms enables a greater number of people to use a large body of\nfree software.  For example, permission to use the GNU C Library in\nnon-free programs enables many more people to use the whole GNU\noperating system, as well as its variant, the GNU/Linux operating\nsystem.\n\n  Although the Lesser General Public License is Less protective of the\nusers' freedom, it does ensure that the user of a program that is\nlinked with the Library has the freedom and the wherewithal to run\nthat program using a modified version of the Library.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.  Pay close attention to the difference between a\n\"work based on the library\" and a \"work that uses the library\".  The\nformer contains code derived from the library, whereas the latter must\nbe combined with the library in order to run.\n\n                  GNU LESSER GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License Agreement applies to any software library or other\nprogram which contains a notice placed by the copyright holder or\nother authorized party saying it may be distributed under the terms of\nthis Lesser General Public License (also called \"this License\").\nEach licensee is addressed as \"you\".\n\n  A \"library\" means a collection of software functions and/or data\nprepared so as to be conveniently linked with application programs\n(which use some of those functions and data) to form executables.\n\n  The \"Library\", below, refers to any such software library or work\nwhich has been distributed under these terms.  A \"work based on the\nLibrary\" means either the Library or any derivative work under\ncopyright law: that is to say, a work containing the Library or a\nportion of it, either verbatim or with modifications and/or translated\nstraightforwardly into another language.  (Hereinafter, translation is\nincluded without limitation in the term \"modification\".)\n\n  \"Source code\" for a work means the preferred form of the work for\nmaking modifications to it.  For a library, complete source code means\nall the source code for all modules it contains, plus any associated\ninterface definition files, plus the scripts used to control compilation\nand installation of the library.\n\n  Activities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning a program using the Library is not restricted, and output from\nsuch a program is covered only if its contents constitute a work based\non the Library (independent of the use of the Library in a tool for\nwriting it).  Whether that is true depends on what the Library does\nand what the program that uses the Library does.\n\n  1. You may copy and distribute verbatim copies of the Library's\ncomplete source code as you receive it, in any medium, provided that\nyou conspicuously and appropriately publish on each copy an\nappropriate copyright notice and disclaimer of warranty; keep intact\nall the notices that refer to this License and to the absence of any\nwarranty; and distribute a copy of this License along with the\nLibrary.\n\n  You may charge a fee for the physical act of transferring a copy,\nand you may at your option offer warranty protection in exchange for a\nfee.\n\n  2. You may modify your copy or copies of the Library or any portion\nof it, thus forming a work based on the Library, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) The modified work must itself be a software library.\n\n    b) You must cause the files modified to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    c) You must cause the whole of the work to be licensed at no\n    charge to all third parties under the terms of this License.\n\n    d) If a facility in the modified Library refers to a function or a\n    table of data to be supplied by an application program that uses\n    the facility, other than as an argument passed when the facility\n    is invoked, then you must make a good faith effort to ensure that,\n    in the event an application does not supply such function or\n    table, the facility still operates, and performs whatever part of\n    its purpose remains meaningful.\n\n    (For example, a function in a library to compute square roots has\n    a purpose that is entirely well-defined independent of the\n    application.  Therefore, Subsection 2d requires that any\n    application-supplied function or table used by this function must\n    be optional: if the application does not supply it, the square\n    root function must still compute square roots.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Library,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Library, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote\nit.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Library.\n\nIn addition, mere aggregation of another work not based on the Library\nwith the Library (or with a work based on the Library) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may opt to apply the terms of the ordinary GNU General Public\nLicense instead of this License to a given copy of the Library.  To do\nthis, you must alter all the notices that refer to this License, so\nthat they refer to the ordinary GNU General Public License, version 2,\ninstead of to this License.  (If a newer version than version 2 of the\nordinary GNU General Public License has appeared, then you can specify\nthat version instead if you wish.)  Do not make any other change in\nthese notices.\n\n  Once this change is made in a given copy, it is irreversible for\nthat copy, so the ordinary GNU General Public License applies to all\nsubsequent copies and derivative works made from that copy.\n\n  This option is useful when you wish to copy part of the code of\nthe Library into a program that is not a library.\n\n  4. You may copy and distribute the Library (or a portion or\nderivative of it, under Section 2) in object code or executable form\nunder the terms of Sections 1 and 2 above provided that you accompany\nit with the complete corresponding machine-readable source code, which\nmust be distributed under the terms of Sections 1 and 2 above on a\nmedium customarily used for software interchange.\n\n  If distribution of object code is made by offering access to copy\nfrom a designated place, then offering equivalent access to copy the\nsource code from the same place satisfies the requirement to\ndistribute the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  5. A program that contains no derivative of any portion of the\nLibrary, but is designed to work with the Library by being compiled or\nlinked with it, is called a \"work that uses the Library\".  Such a\nwork, in isolation, is not a derivative work of the Library, and\ntherefore falls outside the scope of this License.\n\n  However, linking a \"work that uses the Library\" with the Library\ncreates an executable that is a derivative of the Library (because it\ncontains portions of the Library), rather than a \"work that uses the\nlibrary\".  The executable is therefore covered by this License.\nSection 6 states terms for distribution of such executables.\n\n  When a \"work that uses the Library\" uses material from a header file\nthat is part of the Library, the object code for the work may be a\nderivative work of the Library even though the source code is not.\nWhether this is true is especially significant if the work can be\nlinked without the Library, or if the work is itself a library.  The\nthreshold for this to be true is not precisely defined by law.\n\n  If such an object file uses only numerical parameters, data\nstructure layouts and accessors, and small macros and small inline\nfunctions (ten lines or less in length), then the use of the object\nfile is unrestricted, regardless of whether it is legally a derivative\nwork.  (Executables containing this object code plus portions of the\nLibrary will still fall under Section 6.)\n\n  Otherwise, if the work is a derivative of the Library, you may\ndistribute the object code for the work under the terms of Section 6.\nAny executables containing that work also fall under Section 6,\nwhether or not they are linked directly with the Library itself.\n\n  6. As an exception to the Sections above, you may also combine or\nlink a \"work that uses the Library\" with the Library to produce a\nwork containing portions of the Library, and distribute that work\nunder terms of your choice, provided that the terms permit\nmodification of the work for the customer's own use and reverse\nengineering for debugging such modifications.\n\n  You must give prominent notice with each copy of the work that the\nLibrary is used in it and that the Library and its use are covered by\nthis License.  You must supply a copy of this License.  If the work\nduring execution displays copyright notices, you must include the\ncopyright notice for the Library among them, as well as a reference\ndirecting the user to the copy of this License.  Also, you must do one\nof these things:\n\n    a) Accompany the work with the complete corresponding\n    machine-readable source code for the Library including whatever\n    changes were used in the work (which must be distributed under\n    Sections 1 and 2 above); and, if the work is an executable linked\n    with the Library, with the complete machine-readable \"work that\n    uses the Library\", as object code and/or source code, so that the\n    user can modify the Library and then relink to produce a modified\n    executable containing the modified Library.  (It is understood\n    that the user who changes the contents of definitions files in the\n    Library will not necessarily be able to recompile the application\n    to use the modified definitions.)\n\n    b) Use a suitable shared library mechanism for linking with the\n    Library.  A suitable mechanism is one that (1) uses at run time a\n    copy of the library already present on the user's computer system,\n    rather than copying library functions into the executable, and (2)\n    will operate properly with a modified version of the library, if\n    the user installs one, as long as the modified version is\n    interface-compatible with the version that the work was made with.\n\n    c) Accompany the work with a written offer, valid for at\n    least three years, to give the same user the materials\n    specified in Subsection 6a, above, for a charge no more\n    than the cost of performing this distribution.\n\n    d) If distribution of the work is made by offering access to copy\n    from a designated place, offer equivalent access to copy the above\n    specified materials from the same place.\n\n    e) Verify that the user has already received a copy of these\n    materials or that you have already sent this user a copy.\n\n  For an executable, the required form of the \"work that uses the\nLibrary\" must include any data and utility programs needed for\nreproducing the executable from it.  However, as a special exception,\nthe materials to be distributed need not include anything that is\nnormally distributed (in either source or binary form) with the major\ncomponents (compiler, kernel, and so on) of the operating system on\nwhich the executable runs, unless that component itself accompanies\nthe executable.\n\n  It may happen that this requirement contradicts the license\nrestrictions of other proprietary libraries that do not normally\naccompany the operating system.  Such a contradiction means you cannot\nuse both them and the Library together in an executable that you\ndistribute.\n\n  7. You may place library facilities that are a work based on the\nLibrary side-by-side in a single library together with other library\nfacilities not covered by this License, and distribute such a combined\nlibrary, provided that the separate distribution of the work based on\nthe Library and of the other library facilities is otherwise\npermitted, and provided that you do these two things:\n\n    a) Accompany the combined library with a copy of the same work\n    based on the Library, uncombined with any other library\n    facilities.  This must be distributed under the terms of the\n    Sections above.\n\n    b) Give prominent notice with the combined library of the fact\n    that part of it is a work based on the Library, and explaining\n    where to find the accompanying uncombined form of the same work.\n\n  8. You may not copy, modify, sublicense, link with, or distribute\nthe Library except as expressly provided under this License.  Any\nattempt otherwise to copy, modify, sublicense, link with, or\ndistribute the Library is void, and will automatically terminate your\nrights under this License.  However, parties who have received copies,\nor rights, from you under this License will not have their licenses\nterminated so long as such parties remain in full compliance.\n\n  9. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Library or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Library (or any work based on the\nLibrary), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Library or works based on it.\n\n  10. Each time you redistribute the Library (or any work based on the\nLibrary), the recipient automatically receives a license from the\noriginal licensor to copy, distribute, link with or modify the Library\nsubject to these terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties with\nthis License.\n\n  11. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Library at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Library by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Library.\n\nIf any portion of this section is held invalid or unenforceable under any\nparticular circumstance, the balance of the section is intended to apply,\nand the section as a whole is intended to apply in other circumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  12. If the distribution and/or use of the Library is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Library under this License may add\nan explicit geographical distribution limitation excluding those countries,\nso that distribution is permitted only in or among countries not thus\nexcluded.  In such case, this License incorporates the limitation as if\nwritten in the body of this License.\n\n  13. The Free Software Foundation may publish revised and/or new\nversions of the Lesser General Public License from time to time.\nSuch new versions will be similar in spirit to the present version,\nbut may differ in detail to address new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Library\nspecifies a version number of this License which applies to it and\n\"any later version\", you have the option of following the terms and\nconditions either of that version or of any later version published by\nthe Free Software Foundation.  If the Library does not specify a\nlicense version number, you may choose any version ever published by\nthe Free Software Foundation.\n\n  14. If you wish to incorporate parts of the Library into other free\nprograms whose distribution conditions are incompatible with these,\nwrite to the author to ask for permission.  For software which is\ncopyrighted by the Free Software Foundation, write to the Free\nSoftware Foundation; we sometimes make exceptions for this.  Our\ndecision will be guided by the two goals of preserving the free status\nof all derivatives of our free software and of promoting the sharing\nand reuse of software generally.\n\n                            NO WARRANTY\n\n  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\nWARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\nEXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\nOTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\nKIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\nLIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\nTHE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\nWRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\nAND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\nFOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\nCONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\nLIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\nRENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\nFAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\nSUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n           How to Apply These Terms to Your New Libraries\n\n  If you develop a new library, and you want it to be of the greatest\npossible use to the public, we recommend making it free software that\neveryone can redistribute and change.  You can do so by permitting\nredistribution under these terms (or, alternatively, under the terms of the\nordinary General Public License).\n\n  To apply these terms, attach the following notices to the library.  It is\nsafest to attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least the\n\"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the library's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301\n    USA\n\nAlso add information on how to contact you by electronic and paper mail.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the library, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the\n  library `Frob' (a library for tweaking knobs) written by James Random\n  Hacker.\n\n  <signature of Ty Coon>, 1 April 1990\n  Ty Coon, President of Vice\n\nThat's all there is to it!\n"
  },
  {
    "path": "README.adoc",
    "content": ":repository-owner: arduino-libraries\n:repository-name: Servo\n\n= {repository-name} Library for Arduino =\n\nimage:https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml/badge.svg[\"Check Arduino status\", link=\"https://github.com/{repository-owner}/{repository-name}/actions/workflows/check-arduino.yml\"]\nimage:https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml/badge.svg[\"Compile Examples status\", link=\"https://github.com/{repository-owner}/{repository-name}/actions/workflows/compile-examples.yml\"]\nimage:https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml/badge.svg[\"Spell Check status\", link=\"https://github.com/{repository-owner}/{repository-name}/actions/workflows/spell-check.yml\"]\n\nThis library allows an Arduino board to control RC (hobby) servo motors.\n\nFor more information about this library please visit us at\nhttps://www.arduino.cc/reference/en/libraries/servo/\n"
  },
  {
    "path": "docs/api.md",
    "content": "# Servo library\n\n## Methods\n\n### `attach()`\n\nAttach the Servo variable to a pin. Note that in Arduino IDE 0016 and earlier, the Servo library supports servos on only two pins: 9 and 10.\n\n#### Syntax\n\n```\nservo.attach(pin)\nservo.attach(pin, min, max)\n```\n\n#### Parameters\n\n* _servo_: a variable of type `Servo`\n* _pin_: the number of the pin that the servo is attached to\n* _min_ (optional): the pulse width, in microseconds, corresponding to the minimum (0 degree) angle on the servo (defaults to 544)\n* _max_ (optional): the pulse width, in microseconds, corresponding to the maximum (180 degree) angle on the servo (defaults to 2400)\n\n#### Example\n\n```\n#include <Servo.h>\n\nServo myservo;\n\nvoid setup()\n{\n  myservo.attach(9);\n}\n\nvoid loop() {}\n```\n\n#### See also\n\n* [attached()](#attached)\n* [detach()](#detach)\n\n### `write()`\n\nWrites a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).\n\n#### Syntax\n\n```\nservo.write(angle)\n```\n\n#### Parameters\n\n* _servo_: a variable of type Servo\n* _angle_: the value to write to the servo, from 0 to 180\n\n#### Example\n\n````\n#include <Servo.h>\n\nServo myservo;\n\nvoid setup()\n{\n  myservo.attach(9);\n  myservo.write(90);  // set servo to mid-point\n}\n\nvoid loop() {}\n````\n#### See also\n\n* [attach()](#attach)\n* [read()](#read)\n\n### `writeMicroseconds()`\n\nWrites a value in microseconds (us) to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft. On standard servos a parameter value of 1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the middle.\n\nNote that some manufactures do not follow this standard very closely so that servos often respond to values between 700 and 2300. Feel free to increase these endpoints until the servo no longer continues to increase its range. Note however that attempting to drive a servo past its endpoints (often indicated by a growling sound) is a high-current state, and should be avoided.\n\nContinuous-rotation servos will respond to the writeMicrosecond function in an manner analogous to the write function.\n\n#### Syntax\n\n````\nservo.writeMicroseconds(us)\n````\n\n#### Parameters\n\n* _servo_: a variable of type Servo\n* _us_: the value of the parameter in microseconds (int)\n\n#### Example\n\n````\n#include <Servo.h>\n\nServo myservo;\n\nvoid setup()\n{\n  myservo.attach(9);\n  myservo.writeMicroseconds(1500);  // set servo to mid-point\n}\n\nvoid loop() {}\n````\n\n#### See also\n\n* [attach()](#attach)\n* [read()](#read)\n\n\n### `read()`\n\nRead the current setpoint of the servo (the angle passed to the last call to [write()](#write)).\n\nNote that the servo has no way of reporting its current physical orientation. This method returns the angle to which the sketch program has requested the servo to move, regardless of whether the servo has already reached that angle.\n\n#### Syntax\n\n````\nservo.read()\n````\n\n#### Parameters\n\n* _servo_: a variable of type `Servo`\n\n#### Returns\n\nThe setpoint of the servo, as an angle from 0 to 180 degrees.\n\n#### See also\n\n* [write()](#write)\n\n### `attached()`\n\nCheck whether the Servo variable is attached to a pin.\n\n#### Syntax\n\n```\nservo.attached()\n```\n\n#### Parameters\n\n* _servo_: a variable of type `Servo`\n\n#### Returns\n\n`true` if the servo is attached to pin; `false` otherwise.\n\n#### See also\n\n* [attach()](#attach)\n* [detach()](#detach)\n\n### `detach()`\n\nDetach the Servo variable from its pin. If all Servo variables are detached, then pins 9 and 10 can be used for PWM output with [analogWrite()](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/).\n\n#### Syntax\n\n```\nservo.detach()\n```\n\n#### Parameters\n\n* _servo_: a variable of type `Servo`\n\n#### See also\n\n* [attach()](#attach)\n* [attached()](#attached)\n"
  },
  {
    "path": "docs/readme.md",
    "content": "# Servo library\n\n\nThis library allows an Arduino board to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds.\n\nThe Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables `analogWrite()` (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.\n\nTo use this library:\n\n```\n#include <Servo.h>\n```\n\n## Circuit\n\nServo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to a digital pin on the Arduino board. Note that servos draw considerable power, so if you need to drive more than one or two, you'll probably need to power them from a separate supply (i.e. not the 5V pin on your Arduino). Be sure to connect the grounds of the Arduino and external power supply together.\n\n## Examples\n\n* [Knob](https://www.arduino.cc/en/Tutorial/Knob): control the shaft of a servo motor by turning a potentiometer\n* [Sweep](https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep): sweeps the shaft of a servo motor back and forth\n"
  },
  {
    "path": "examples/Knob/Knob.ino",
    "content": "/*\n Controlling a servo position using a potentiometer (variable resistor)\n by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>\n\n modified on 8 Nov 2013\n by Scott Fitzgerald\n http://www.arduino.cc/en/Tutorial/Knob\n*/\n\n#include <Servo.h>\n\nServo myservo;  // create Servo object to control a servo\n\nint potpin = A0;  // analog pin used to connect the potentiometer\nint val;    // variable to read the value from the analog pin\n\nvoid setup() {\n  myservo.attach(9);  // attaches the servo on pin 9 to the Servo object\n}\n\nvoid loop() {\n  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)\n  val = map(val, 0, 1023, 0, 180);     // scale it for use with the servo (value between 0 and 180)\n  myservo.write(val);                  // sets the servo position according to the scaled value\n  delay(15);                           // waits for the servo to get there\n}\n"
  },
  {
    "path": "examples/Knob/readme.md",
    "content": "# Knob\n\nControl the position of an RC (hobby) [servo motor](http://en.wikipedia.org/wiki/Servo_motor#RC_servos) with your Arduino and a potentiometer.\n\nThis example makes use of the Arduino `Servo` library.\n\n## Hardware Required\n\n* an Arduino board\n* Servo motor\n* 10k ohm potentiometer\n* hook-up wires\n\n## Circuit\n\nServo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the board. The signal pin is typically yellow or orange and should be connected to pin 9 on the board.\n\nThe potentiometer should be wired so that its two outer pins are connected to power (5V) and ground, and its middle pin is connected to analog input 0 on the board.\n\n![](images/knob_BB.png)\n\n(Images developed using Fritzing. For more circuit examples, see the [Fritzing project page](http://fritzing.org/projects/))\n\n## Schematic\n\n![](images/knob_schem.png)\n\n## See also\n\n* [attach()](/docs/api.md#attach)\n* [write()](/docs/api.md#write)\n* [map()](https://www.arduino.cc/en/Reference/Map)\n* [analogRead()](https://www.arduino.cc/en/Reference/AnalogRead)\n* [Servo library reference](/docs/readme.md)\n* [Sweep](../Sweep) - Sweep the shaft of a servo motor back and forth\n"
  },
  {
    "path": "examples/Sweep/Sweep.ino",
    "content": "/* Sweep\n by BARRAGAN <http://barraganstudio.com>\n This example code is in the public domain.\n\n modified 8 Nov 2013\n by Scott Fitzgerald\n https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep\n*/\n\n#include <Servo.h>\n\nServo myservo;  // create Servo object to control a servo\n// twelve Servo objects can be created on most boards\n\nint pos = 0;    // variable to store the servo position\n\nvoid setup() {\n  myservo.attach(9);  // attaches the servo on pin 9 to the Servo object\n}\n\nvoid loop() {\n  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees\n    // in steps of 1 degree\n    myservo.write(pos);              // tell servo to go to position in variable 'pos'\n    delay(15);                       // waits 15 ms for the servo to reach the position\n  }\n  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees\n    myservo.write(pos);              // tell servo to go to position in variable 'pos'\n    delay(15);                       // waits 15 ms for the servo to reach the position\n  }\n}\n"
  },
  {
    "path": "examples/Sweep/readme.md",
    "content": "# Sweep\n\nSweeps the shaft of an RC [servo motor](http://en.wikipedia.org/wiki/Servo_motor#RC_servos) back and forth across 180 degrees.\n\n## Hardware Required\n\n* Arduino Board\n* Servo Motor\n* Hook-up wires\n\n## Circuit\n\nServo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the board. The signal pin is typically yellow, orange or white and should be connected to pin 9 on the board.\n\n![](images/sweep_bb.png)\n\n(Images developed using Fritzing. For more circuit examples, see the [Fritzing project page](http://fritzing.org/projects/))\n\n## Schematic\n\n![](images/sweep_schem.png)\n\n## See also\n\n* [attach()](/docs/api.md#attach)\n* [write()](/docs/api.md#write)\n* [map()](https://www.arduino.cc/en/Reference/Map)\n* [Servo library reference](/docs/readme.md)\n* [Knob](../Knob) - Control the position of a servo with a potentiometer\n"
  },
  {
    "path": "keywords.txt",
    "content": "#######################################\n# Syntax Coloring Map Servo\n#######################################\n\n#######################################\n# Datatypes (KEYWORD1)\n#######################################\n\nServo\tKEYWORD1\tServo\n\n#######################################\n# Methods and Functions (KEYWORD2)\n#######################################\nattach\tKEYWORD2\ndetach\tKEYWORD2\nwrite\tKEYWORD2\nread\tKEYWORD2\nattached\tKEYWORD2\nwriteMicroseconds\tKEYWORD2\nreadMicroseconds\tKEYWORD2\n\n#######################################\n# Constants (LITERAL1)\n#######################################\n"
  },
  {
    "path": "library.properties",
    "content": "name=Servo\nversion=1.3.0\nauthor=Michael Margolis, Arduino\nmaintainer=Arduino <info@arduino.cc>\nsentence=Allows Arduino boards to control a variety of servo motors.\nparagraph=This library can control a great number of servos.<br />It makes careful use of timers: the library can control 12 servos using only 1 timer.<br />On the Arduino Due you can control up to 60 servos.\ncategory=Device Control\nurl=https://www.arduino.cc/reference/en/libraries/servo/\narchitectures=avr,megaavr,sam,samd,nrf52,stm32f4,mbed,mbed_nano,mbed_portenta,mbed_rp2040,renesas,renesas_portenta,renesas_uno,zephyr\n"
  },
  {
    "path": "src/Servo.h",
    "content": "/*\n  Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers - Version 2\n  Copyright (c) 2009 Michael Margolis. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n*/\n\n/*\n  A servo is activated by creating an instance of the Servo class passing\n  the desired pin to the attach() method.\n  The servos are pulsed in the background using the value most recently\n  written using the write() method.\n\n  Note that analogWrite of PWM on pins associated with the timer are\n  disabled when the first servo is attached.\n  Timers are seized as needed in groups of 12 servos - 24 servos use two\n  timers, 48 servos will use four.\n  The sequence used to seize timers is defined in timers.h\n\n  The methods are:\n\n    Servo - Class for manipulating servo motors connected to Arduino pins.\n\n    attach(pin ) - Attaches a servo motor to an I/O pin.\n    attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds\n    default min is 544, max is 2400\n\n    write()     - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds)\n    writeMicroseconds() - Sets the servo pulse width in microseconds\n    read()      - Gets the last written servo pulse width as an angle between 0 and 180.\n    readMicroseconds()   - Gets the last written servo pulse width in microseconds. (was read_us() in first release)\n    attached()  - Returns true if there is a servo attached.\n    detach()    - Stops an attached servos from pulsing its I/O pin.\n */\n\n#ifndef Servo_h\n#define Servo_h\n\n#include <inttypes.h>\n\n/*\n * Defines for 16 bit timers used with Servo library\n *\n * If _useTimerX is defined then TimerX is a 16 bit timer on the current board\n * timer16_Sequence_t enumerates the sequence that the timers should be allocated\n * _Nbr_16timers indicates how many 16 bit timers are available.\n */\n\n// Architecture specific include\n#if defined(ARDUINO_ARCH_AVR)\n#include \"avr/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_SAM)\n#include \"sam/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_SAMD)\n#include \"samd/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_STM32F4)\n#include \"stm32f4/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_NRF52)\n#include \"nrf52/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_MEGAAVR)\n#include \"megaavr/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_MBED)\n#include \"mbed/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_RENESAS)\n#include \"renesas/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_XMC)\n#include \"xmc/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_ESP32)\n#include \"esp32/ServoTimers.h\"\n#elif defined(ARDUINO_ARCH_ZEPHYR)\n#include \"zephyr/ServoTimers.h\"\n#else\n#error \"This library only supports boards with an AVR, SAM, SAMD, NRF52, STM32F4, Renesas, XMC, ESP32 or Zephyr core.\"\n#endif\n\n#define Servo_VERSION           2     // software version of this library\n\n#define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo\n#define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo\n#define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached\n#define REFRESH_INTERVAL    20000     // minimum time to refresh servos in microseconds\n\n#define SERVOS_PER_TIMER       12     // the maximum number of servos controlled by one timer\n#define MAX_SERVOS   (_Nbr_16timers  * SERVOS_PER_TIMER)\n\n#define INVALID_SERVO         255     // flag indicating an invalid servo index\n\n#if !defined(ARDUINO_ARCH_STM32F4) && !defined(ARDUINO_ARCH_XMC)\n\ntypedef struct  {\n  uint8_t nbr        :6 ;             // a pin number from 0 to 63\n  uint8_t isActive   :1 ;             // true if this channel is enabled, pin not pulsed if false\n} ServoPin_t   ;\n\ntypedef struct {\n  ServoPin_t Pin;\n  volatile unsigned int ticks;\n} servo_t;\n\nclass Servo\n{\npublic:\n  Servo();\n  uint8_t attach(int pin);           // attach the given pin to the next free channel, sets pinMode, returns channel number or INVALID_SERVO if failure\n  uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes.\n  void detach();\n  void write(int value);             // if value is < 200 it's treated as an angle, otherwise as pulse width in microseconds\n  void writeMicroseconds(int value); // Write pulse width in microseconds\n  int read();                        // returns current pulse width as an angle between 0 and 180 degrees\n  int readMicroseconds();            // returns current pulse width in microseconds for this servo (was read_us() in first release)\n  bool attached();                   // return true if this servo is attached, otherwise false\nprivate:\n   uint8_t servoIndex;               // index into the channel data for this servo\n   int8_t min;                       // minimum is this value times 4 added to MIN_PULSE_WIDTH\n   int8_t max;                       // maximum is this value times 4 added to MAX_PULSE_WIDTH\n};\n\n#endif\n#endif\n"
  },
  {
    "path": "src/avr/Servo.cpp",
    "content": "/*\n Servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers - Version 2\n Copyright (c) 2009 Michael Margolis.  All right reserved.\n\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n */\n\n#if defined(ARDUINO_ARCH_AVR)\n\n#include <avr/interrupt.h>\n#include <Arduino.h>\n\n#include \"Servo.h\"\n\n#define usToTicks(_us)    (( clockCyclesPerMicrosecond()* _us) / 8)     // converts microseconds to ticks (assumes prescaler of 8)  // 12 Aug 2009\n#define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds\n\n\n#define TRIM_DURATION       2                               // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009\n\n//#define NBR_TIMERS        (MAX_SERVOS / SERVOS_PER_TIMER)\n\nstatic servo_t servos[MAX_SERVOS];                          // static array of servo structures\nstatic volatile int8_t Channel[_Nbr_16timers ];             // counter for the servo being pulsed for each timer (or -1 if refresh interval)\n\nuint8_t ServoCount = 0;                                     // the total number of attached servos\n\n\n// convenience macros\n#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo\n#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER)       // returns the index of the servo on this timer\n#define SERVO_INDEX(_timer,_channel)  ((_timer*SERVOS_PER_TIMER) + _channel)     // macro to access servo index by timer and channel\n#define SERVO(_timer,_channel)  (servos[SERVO_INDEX(_timer,_channel)])            // macro to access servo class by timer and channel\n\n#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4)  // minimum value in us for this servo\n#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4)  // maximum value in us for this servo\n\n/************ static functions common to all instances ***********************/\n\nstatic inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t *TCNTn, volatile uint16_t* OCRnA)\n{\n  if( Channel[timer] < 0 )\n    *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer\n  else{\n    if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true )\n      digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,LOW); // pulse this channel low if activated\n  }\n\n  Channel[timer]++;    // increment to the next channel\n  if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) {\n    *OCRnA = *TCNTn + SERVO(timer,Channel[timer]).ticks;\n    if(SERVO(timer,Channel[timer]).Pin.isActive == true)     // check if activated\n      digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // it's an active channel so pulse it high\n  }\n  else {\n    // finished all channels so wait for the refresh period to expire before starting over\n    if( ((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL) )  // allow a few ticks to ensure the next OCR1A not missed\n      *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL);\n    else\n      *OCRnA = *TCNTn + 4;  // at least REFRESH_INTERVAL has elapsed\n    Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel\n  }\n}\n\n#ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform\n// Interrupt handlers for Arduino\n#if defined(_useTimer1)\nSIGNAL (TIMER1_COMPA_vect)\n{\n  handle_interrupts(_timer1, &TCNT1, &OCR1A);\n}\n#endif\n\n#if defined(_useTimer3)\nSIGNAL (TIMER3_COMPA_vect)\n{\n  handle_interrupts(_timer3, &TCNT3, &OCR3A);\n}\n#endif\n\n#if defined(_useTimer4)\nSIGNAL (TIMER4_COMPA_vect)\n{\n  handle_interrupts(_timer4, &TCNT4, &OCR4A);\n}\n#endif\n\n#if defined(_useTimer5)\nSIGNAL (TIMER5_COMPA_vect)\n{\n  handle_interrupts(_timer5, &TCNT5, &OCR5A);\n}\n#endif\n\n#elif defined WIRING\n// Interrupt handlers for Wiring\n#if defined(_useTimer1)\nvoid Timer1Service()\n{\n  handle_interrupts(_timer1, &TCNT1, &OCR1A);\n}\n#endif\n#if defined(_useTimer3)\nvoid Timer3Service()\n{\n  handle_interrupts(_timer3, &TCNT3, &OCR3A);\n}\n#endif\n#endif\n\n\nstatic void initISR(timer16_Sequence_t timer)\n{\n#if defined (_useTimer1)\n  if(timer == _timer1) {\n    TCCR1A = 0;             // normal counting mode\n    TCCR1B = _BV(CS11);     // set prescaler of 8\n    TCNT1 = 0;              // clear the timer count\n#if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__)\n    TIFR |= _BV(OCF1A);      // clear any pending interrupts\n    TIMSK |=  _BV(OCIE1A) ;  // enable the output compare interrupt\n#else\n    // here if not ATmega8 or ATmega128\n    TIFR1 |= _BV(OCF1A);     // clear any pending interrupts\n    TIMSK1 |=  _BV(OCIE1A) ; // enable the output compare interrupt\n#endif\n#if defined(WIRING)\n    timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service);\n#endif\n  }\n#endif\n\n#if defined (_useTimer3)\n  if(timer == _timer3) {\n    TCCR3A = 0;             // normal counting mode\n    TCCR3B = _BV(CS31);     // set prescaler of 8\n    TCNT3 = 0;              // clear the timer count\n#if defined(__AVR_ATmega128__)\n    TIFR |= _BV(OCF3A);     // clear any pending interrupts\n\tETIMSK |= _BV(OCIE3A);  // enable the output compare interrupt\n#else\n    TIFR3 = _BV(OCF3A);     // clear any pending interrupts\n    TIMSK3 =  _BV(OCIE3A) ; // enable the output compare interrupt\n#endif\n#if defined(WIRING)\n    timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service);  // for Wiring platform only\n#endif\n  }\n#endif\n\n#if defined (_useTimer4)\n  if(timer == _timer4) {\n    TCCR4A = 0;             // normal counting mode\n    TCCR4B = _BV(CS41);     // set prescaler of 8\n    TCNT4 = 0;              // clear the timer count\n    TIFR4 = _BV(OCF4A);     // clear any pending interrupts\n    TIMSK4 =  _BV(OCIE4A) ; // enable the output compare interrupt\n  }\n#endif\n\n#if defined (_useTimer5)\n  if(timer == _timer5) {\n    TCCR5A = 0;             // normal counting mode\n    TCCR5B = _BV(CS51);     // set prescaler of 8\n    TCNT5 = 0;              // clear the timer count\n    TIFR5 = _BV(OCF5A);     // clear any pending interrupts\n    TIMSK5 =  _BV(OCIE5A) ; // enable the output compare interrupt\n  }\n#endif\n}\n\nstatic void finISR(timer16_Sequence_t timer)\n{\n    //disable use of the given timer\n#if defined WIRING   // Wiring\n  if(timer == _timer1) {\n    #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__)\n    TIMSK1 &=  ~_BV(OCIE1A) ;  // disable timer 1 output compare interrupt\n    #else\n    TIMSK &=  ~_BV(OCIE1A) ;  // disable timer 1 output compare interrupt\n    #endif\n    timerDetach(TIMER1OUTCOMPAREA_INT);\n  }\n  else if(timer == _timer3) {\n    #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__)\n    TIMSK3 &= ~_BV(OCIE3A);    // disable the timer3 output compare A interrupt\n    #else\n    ETIMSK &= ~_BV(OCIE3A);    // disable the timer3 output compare A interrupt\n    #endif\n    timerDetach(TIMER3OUTCOMPAREA_INT);\n  }\n#else\n  //For Arduino - in future: call here to a currently undefined function to reset the timer\n  (void) timer;  // squash \"unused parameter 'timer' [-Wunused-parameter]\" warning\n#endif\n}\n\nstatic boolean isTimerActive(timer16_Sequence_t timer)\n{\n  // returns true if any servo is active on this timer\n  for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) {\n    if(SERVO(timer,channel).Pin.isActive == true)\n      return true;\n  }\n  return false;\n}\n\n\n/****************** end of static functions ******************************/\n\nServo::Servo()\n{\n  if( ServoCount < MAX_SERVOS) {\n    this->servoIndex = ServoCount++;                    // assign a servo index to this instance\n\tservos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);   // store default values  - 12 Aug 2009\n  }\n  else\n    this->servoIndex = INVALID_SERVO ;  // too many servos\n}\n\nuint8_t Servo::attach(int pin)\n{\n  return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  if(this->servoIndex < MAX_SERVOS ) {\n    pinMode( pin, OUTPUT) ;                                   // set servo pin to output\n    servos[this->servoIndex].Pin.nbr = pin;\n    // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128\n    this->min  = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us\n    this->max  = (MAX_PULSE_WIDTH - max)/4;\n    // initialize the timer if it has not already been initialized\n    timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);\n    if(isTimerActive(timer) == false)\n      initISR(timer);\n    servos[this->servoIndex].Pin.isActive = true;  // this must be set after the check for isTimerActive\n  }\n  return this->servoIndex ;\n}\n\nvoid Servo::detach()\n{\n  servos[this->servoIndex].Pin.isActive = false;\n  timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);\n  if(isTimerActive(timer) == false) {\n    finISR(timer);\n  }\n}\n\nvoid Servo::write(int value)\n{\n  if(value < MIN_PULSE_WIDTH)\n  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)\n    if(value < 0) value = 0;\n    if(value > 180) value = 180;\n    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());\n  }\n  this->writeMicroseconds(value);\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n  // calculate and store the values for the given channel\n  byte channel = this->servoIndex;\n  if( (channel < MAX_SERVOS) )   // ensure channel is valid\n  {\n    if( value < SERVO_MIN() )          // ensure pulse width is valid\n      value = SERVO_MIN();\n    else if( value > SERVO_MAX() )\n      value = SERVO_MAX();\n\n    value = value - TRIM_DURATION;\n    value = usToTicks(value);  // convert to ticks after compensating for interrupt overhead - 12 Aug 2009\n\n    uint8_t oldSREG = SREG;\n    cli();\n    servos[channel].ticks = value;\n    SREG = oldSREG;\n  }\n}\n\nint Servo::read() // return the value as degrees\n{\n  return  map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n  unsigned int pulsewidth;\n  if( this->servoIndex != INVALID_SERVO )\n    pulsewidth = ticksToUs(servos[this->servoIndex].ticks)  + TRIM_DURATION ;   // 12 aug 2009\n  else\n    pulsewidth  = 0;\n\n  return pulsewidth;\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex].Pin.isActive ;\n}\n\n#endif // ARDUINO_ARCH_AVR\n"
  },
  {
    "path": "src/avr/ServoTimers.h",
    "content": "/*\n  Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers - Version 2\n  Copyright (c) 2009 Michael Margolis.  All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n*/\n\n/*\n * Defines for 16 bit timers used with Servo library\n *\n * If _useTimerX is defined then TimerX is a 16 bit timer on the current board\n * timer16_Sequence_t enumerates the sequence that the timers should be allocated\n * _Nbr_16timers indicates how many 16 bit timers are available.\n */\n\n/**\n * AVR Only definitions\n * --------------------\n */\n\n// Say which 16 bit timers can be used and in what order\n#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)\n#define _useTimer5\n#define _useTimer1\n#define _useTimer3\n#define _useTimer4\ntypedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t;\n\n#elif defined(__AVR_ATmega32U4__)\n#define _useTimer1\ntypedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t;\n\n#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)\n#define _useTimer3\n#define _useTimer1\ntypedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t;\n\n#elif defined(__AVR_ATmega128__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega2561__)\n#define _useTimer3\n#define _useTimer1\ntypedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t;\n\n#else  // everything else\n#define _useTimer1\ntypedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t;\n#endif\n"
  },
  {
    "path": "src/esp32/Servo.cpp",
    "content": "#if defined(ARDUINO_ARCH_ESP32)\n\n#include <Arduino.h>\n#include <Servo.h>\n\n#if defined __has_include\n#  if __has_include (\"pinDefinitions.h\")\n#    include \"pinDefinitions.h\"\n#  endif\n#endif\n\n/*\n * This group/channel/timmer mapping is for information only;\n * the details are handled by lower-level code\n *\n * LEDC Chan to Group/Channel/Timer Mapping\n ** ledc: 0  => Group: 0, Channel: 0, Timer: 0\n ** ledc: 1  => Group: 0, Channel: 1, Timer: 0\n ** ledc: 2  => Group: 0, Channel: 2, Timer: 1\n ** ledc: 3  => Group: 0, Channel: 3, Timer: 1\n ** ledc: 4  => Group: 0, Channel: 4, Timer: 2\n ** ledc: 5  => Group: 0, Channel: 5, Timer: 2\n ** ledc: 6  => Group: 0, Channel: 6, Timer: 3\n ** ledc: 7  => Group: 0, Channel: 7, Timer: 3\n ** ledc: 8  => Group: 1, Channel: 0, Timer: 0\n ** ledc: 9  => Group: 1, Channel: 1, Timer: 0\n ** ledc: 10 => Group: 1, Channel: 2, Timer: 1\n ** ledc: 11 => Group: 1, Channel: 3, Timer: 1\n ** ledc: 12 => Group: 1, Channel: 4, Timer: 2\n ** ledc: 13 => Group: 1, Channel: 5, Timer: 2\n ** ledc: 14 => Group: 1, Channel: 6, Timer: 3\n ** ledc: 15 => Group: 1, Channel: 7, Timer: 3\n */\n\nclass ServoImpl {\n  uint8_t pin;\n\npublic:\n    ServoImpl(const uint8_t _pin, const uint8_t _channel) : pin(_pin) {\n      // Setup timer\n      ledcSetup(_channel, (1000000 / REFRESH_INTERVAL), LEDC_MAX_BIT_WIDTH);\n\n      // Attach timer to a LED pin\n      ledcAttachPin(pin, _channel);\n    }\n\n    ~ServoImpl() {\n      ledcDetachPin(pin);\n    }\n\n    void set(const uint8_t _channel, const uint32_t duration_us) {\n      ledcWrite(_channel, LEDC_US_TO_TICKS(duration_us));\n    }\n\n    uint32_t get(const uint8_t _channel) const {\n      return LEDC_TICKS_TO_US(ledcRead(_channel));\n    }\n};\n\nstatic ServoImpl* servos[MAX_PWM_SERVOS] = {nullptr};      // static array of servo structures\nuint8_t ServoCount = 0;                                    // the total number of attached servos\n\n#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min)   // minimum value in us for this servo\n#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max)   // maximum value in us for this servo\n\nServo::Servo()\n{\n  if (ServoCount < MAX_PWM_SERVOS) {\n    this->servoIndex = ServoCount++;\n  } else {\n    this->servoIndex = INVALID_SERVO;  // too many servos\n  }\n}\n\nuint8_t Servo::attach(int pin)\n{\n  return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  servos[this->servoIndex] = new ServoImpl(pin, this->servoIndex);\n\n  this->min  = (MIN_PULSE_WIDTH - min);\n  this->max  = (MAX_PULSE_WIDTH - max);\n  return this->servoIndex;\n}\n\nvoid Servo::detach()\n{\n  delete servos[this->servoIndex];\n  servos[this->servoIndex] = NULL;\n}\n\nvoid Servo::write(int value)\n{\n  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)\n  if (value < MIN_PULSE_WIDTH)\n  {\n    if (value < 0)\n      value = 0;\n    else if (value > 180)\n      value = 180;\n\n    value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());\n  }\n  writeMicroseconds(value);\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n  if (!servos[this->servoIndex]) {\n    return;\n  }\n  // calculate and store the values for the given channel\n  byte channel = this->servoIndex;\n  if( (channel < MAX_PWM_SERVOS) )   // ensure channel is valid\n  {\n    if (value < SERVO_MIN())          // ensure pulse width is valid\n      value = SERVO_MIN();\n    else if (value > SERVO_MAX())\n      value = SERVO_MAX();\n\n    servos[this->servoIndex]->set(this->servoIndex, value);\n  }\n}\n\nint Servo::read() // return the value as degrees\n{\n  return map(readMicroseconds(), SERVO_MIN(), SERVO_MAX(), 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n  if (!servos[this->servoIndex]) {\n    return 0;\n  }\n  return servos[this->servoIndex]->get(this->servoIndex);\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex] != NULL;\n}\n\n#endif\n"
  },
  {
    "path": "src/esp32/ServoTimers.h",
    "content": "#define MAX_PWM_SERVOS             16\n\n#define LEDC_MAX_BIT_WIDTH      SOC_LEDC_TIMER_BIT_WIDE_NUM\n\nconstexpr uint32_t BIT_RESOLUTION = (1 << LEDC_MAX_BIT_WIDTH) - 1;\n\n#define LEDC_US_TO_TICKS(us)    static_cast<uint32_t>((us * BIT_RESOLUTION) / REFRESH_INTERVAL)\n#define LEDC_TICKS_TO_US(ticks) static_cast<uint32_t>((ticks * REFRESH_INTERVAL) / BIT_RESOLUTION)"
  },
  {
    "path": "src/mbed/Servo.cpp",
    "content": "#if defined(ARDUINO_ARCH_MBED)\n\n#include <Arduino.h>\n#include <Servo.h>\n#include <mbed.h>\n\n#if defined __has_include\n#  if __has_include (\"pinDefinitions.h\")\n#    include \"pinDefinitions.h\"\n#  endif\n#endif\n\nclass ServoImpl {\n    mbed::DigitalOut   *pin;\n    mbed::Timeout      timeout;  // calls a callback once when a timeout expires\n    mbed::Ticker       ticker;   // calls a callback repeatedly with a timeout\n\npublic:\n    ServoImpl(PinName _pin) {\n      pin = new mbed::DigitalOut(_pin);\n    }\n\n    ~ServoImpl() {\n        ticker.detach();\n        timeout.detach();\n        delete pin;\n    }\n\n    void start(uint32_t duration_us) {\n      duration = duration_us;\n      ticker.attach(mbed::callback(this, &ServoImpl::call), 0.02f);\n    }\n\n    void call() {\n        timeout.attach(mbed::callback(this, &ServoImpl::toggle), duration / 1e6);\n        toggle();\n    }\n\n    void toggle() {\n      *pin = !*pin;\n    }\n\n    int32_t           duration = -1;\n};\n\nstatic ServoImpl* servos[MAX_SERVOS];                      // static array of servo structures\nuint8_t ServoCount = 0;                                    // the total number of attached servos\n\n#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min)   // minimum value in us for this servo\n#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max)   // maximum value in us for this servo\n\n#define TRIM_DURATION   15                           //callback overhead (35 us) -> 15 us if toggle() is called after starting the timeout\n\nServo::Servo()\n{\n  if (ServoCount < MAX_SERVOS) {\n    this->servoIndex = ServoCount++;\n  } else {\n    this->servoIndex = INVALID_SERVO;  // too many servos\n  }\n}\n\nuint8_t Servo::attach(int pin)\n{\n  return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  pinMode(pin, OUTPUT);                                   // set servo pin to output\n  servos[this->servoIndex] = new ServoImpl(digitalPinToPinName(pin));\n\n  this->min  = (MIN_PULSE_WIDTH - min);\n  this->max  = (MAX_PULSE_WIDTH - max);\n  return this->servoIndex;\n}\n\nvoid Servo::detach()\n{\n  delete servos[this->servoIndex];\n  servos[this->servoIndex] = NULL;\n}\n\nvoid Servo::write(int value)\n{\n  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)\n  if (value < MIN_PULSE_WIDTH)\n  {\n    if (value < 0)\n      value = 0;\n    else if (value > 180)\n      value = 180;\n\n    value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());\n  }\n  writeMicroseconds(value);\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n  if (!servos[this->servoIndex]) {\n    return;\n  }\n  // calculate and store the values for the given channel\n  byte channel = this->servoIndex;\n  if( (channel < MAX_SERVOS) )   // ensure channel is valid\n  {\n    if (value < SERVO_MIN())          // ensure pulse width is valid\n      value = SERVO_MIN();\n    else if (value > SERVO_MAX())\n      value = SERVO_MAX();\n\n    value = value - TRIM_DURATION;\n    if (servos[this->servoIndex]->duration == -1) {\n      servos[this->servoIndex]->start(value);\n    }\n    servos[this->servoIndex]->duration = value;\n  }\n}\n\nint Servo::read() // return the value as degrees\n{\n  return map(readMicroseconds(), SERVO_MIN(), SERVO_MAX(), 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n  if (!servos[this->servoIndex]) {\n    return 0;\n  }\n  return servos[this->servoIndex]->duration;\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex] != NULL;\n}\n\n#endif\n"
  },
  {
    "path": "src/mbed/ServoTimers.h",
    "content": "#define _Nbr_16timers 32\n"
  },
  {
    "path": "src/megaavr/Servo.cpp",
    "content": "#if defined(ARDUINO_ARCH_MEGAAVR)\n\n#include <Arduino.h>\n#include <Servo.h>\n\n#define usToTicks(_us)    ((clockCyclesPerMicrosecond() / 16 * _us) / 4)                 // converts microseconds to ticks\n#define ticksToUs(_ticks) (((unsigned) _ticks * 16) / (clockCyclesPerMicrosecond() / 4))   // converts from ticks back to microseconds\n\n#define TRIM_DURATION  5                                   // compensation ticks to trim adjust for digitalWrite delays\n\nstatic servo_t servos[MAX_SERVOS];                         // static array of servo structures\n\nuint8_t ServoCount = 0;                                    // the total number of attached servos\n\nstatic volatile int8_t currentServoIndex[_Nbr_16timers];   // index for the servo being pulsed for each timer (or -1 if refresh interval)\n\n// convenience macros\n#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER))   // returns the timer controlling this servo\n#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER)                       // returns the index of the servo on this timer\n#define SERVO_INDEX(_timer,_channel)  ((_timer*SERVOS_PER_TIMER) + _channel)                     // macro to access servo index by timer and channel\n#define SERVO(_timer,_channel)  (servos[SERVO_INDEX(_timer,_channel)])                           // macro to access servo class by timer and channel\n\n#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4)   // minimum value in us for this servo\n#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4)   // maximum value in us for this servo\n\n#undef REFRESH_INTERVAL\n#define REFRESH_INTERVAL 16000\n\nvoid ServoHandler(int timer)\n{\n    if (currentServoIndex[timer] < 0) {\n        // Write compare register\n        _timer->CCMP = 0;\n    } else {\n        if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) {\n            digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, LOW);   // pulse this channel low if activated\n        }\n    }\n\n    // Select the next servo controlled by this timer\n    currentServoIndex[timer]++;\n\n    if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && currentServoIndex[timer] < SERVOS_PER_TIMER) {\n        if (SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) {   // check if activated\n            digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, HIGH);   // it's an active channel so pulse it high\n        }\n\n        // Get the counter value\n        uint16_t tcCounterValue =  0; //_timer->CCMP;\n        _timer->CCMP = (uint16_t) (tcCounterValue + SERVO(timer, currentServoIndex[timer]).ticks);\n    }\n    else {\n        // finished all channels so wait for the refresh period to expire before starting over\n\n        // Get the counter value\n        uint16_t tcCounterValue = _timer->CCMP;\n\n        if (tcCounterValue + 4UL < usToTicks(REFRESH_INTERVAL)) {   // allow a few ticks to ensure the next OCR1A not missed\n            _timer->CCMP = (uint16_t) usToTicks(REFRESH_INTERVAL);\n        }\n        else {\n            _timer->CCMP = (uint16_t) (tcCounterValue + 4UL);   // at least REFRESH_INTERVAL has elapsed\n        }\n\n        currentServoIndex[timer] = -1;   // this will get incremented at the end of the refresh period to start again at the first channel\n    }\n\n    /* Clear flag */\n    _timer->INTFLAGS = TCB_CAPT_bm;\n}\n\n#if defined USE_TIMERB0\nISR(TCB0_INT_vect)\n#elif defined USE_TIMERB1\nISR(TCB1_INT_vect)\n#elif defined USE_TIMERB2\nISR(TCB2_INT_vect)\n#endif\n{\n  ServoHandler(0);\n}\n\nstatic void initISR(timer16_Sequence_t timer)\n{\n  //TCA0.SINGLE.CTRLA = (TCA_SINGLE_CLKSEL_DIV16_gc) | (TCA_SINGLE_ENABLE_bm);\n\n  _timer->CTRLA = TCB_CLKSEL_CLKTCA_gc;\n  // Timer to Periodic interrupt mode\n  // This write will also disable any active PWM outputs\n  _timer->CTRLB = TCB_CNTMODE_INT_gc;\n  // Enable interrupt\n  _timer->INTCTRL = TCB_CAPTEI_bm;\n  // Enable timer\n  _timer->CTRLA |= TCB_ENABLE_bm;\n}\n\nstatic void finISR(timer16_Sequence_t timer)\n{\n  // Disable interrupt\n  _timer->INTCTRL = 0;\n}\n\nstatic boolean isTimerActive(timer16_Sequence_t timer)\n{\n  // returns true if any servo is active on this timer\n  for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) {\n    if(SERVO(timer,channel).Pin.isActive == true)\n      return true;\n  }\n  return false;\n}\n\n/****************** end of static functions ******************************/\n\nServo::Servo()\n{\n  if (ServoCount < MAX_SERVOS) {\n    this->servoIndex = ServoCount++;                    // assign a servo index to this instance\n    servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);   // store default values\n  } else {\n    this->servoIndex = INVALID_SERVO;  // too many servos\n  }\n}\n\nuint8_t Servo::attach(int pin)\n{\n  return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  timer16_Sequence_t timer;\n\n  if (this->servoIndex < MAX_SERVOS) {\n    pinMode(pin, OUTPUT);                                   // set servo pin to output\n    servos[this->servoIndex].Pin.nbr = pin;\n    // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128\n    this->min  = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us\n    this->max  = (MAX_PULSE_WIDTH - max)/4;\n    // initialize the timer if it has not already been initialized\n    timer = SERVO_INDEX_TO_TIMER(servoIndex);\n    if (isTimerActive(timer) == false) {\n      initISR(timer);\n    }\n    servos[this->servoIndex].Pin.isActive = true;  // this must be set after the check for isTimerActive\n  }\n  return this->servoIndex;\n}\n\nvoid Servo::detach()\n{\n  timer16_Sequence_t timer;\n\n  servos[this->servoIndex].Pin.isActive = false;\n  timer = SERVO_INDEX_TO_TIMER(servoIndex);\n  if(isTimerActive(timer) == false) {\n    finISR(timer);\n  }\n}\n\nvoid Servo::write(int value)\n{\n  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)\n  if (value < MIN_PULSE_WIDTH)\n  {\n    if (value < 0)\n      value = 0;\n    else if (value > 180)\n      value = 180;\n\n    value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());\n  }\n  writeMicroseconds(value);\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n  // calculate and store the values for the given channel\n  byte channel = this->servoIndex;\n  if( (channel < MAX_SERVOS) )   // ensure channel is valid\n  {\n    if (value < SERVO_MIN())          // ensure pulse width is valid\n      value = SERVO_MIN();\n    else if (value > SERVO_MAX())\n      value = SERVO_MAX();\n\n    value = value - TRIM_DURATION;\n    value = usToTicks(value);  // convert to ticks after compensating for interrupt overhead\n    servos[channel].ticks = value;\n  }\n}\n\nint Servo::read() // return the value as degrees\n{\n  return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n  unsigned int pulsewidth;\n  if (this->servoIndex != INVALID_SERVO)\n    pulsewidth = ticksToUs(servos[this->servoIndex].ticks)  + TRIM_DURATION;\n  else\n    pulsewidth  = 0;\n\n  return pulsewidth;\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex].Pin.isActive;\n}\n\n#endif\n"
  },
  {
    "path": "src/megaavr/ServoTimers.h",
    "content": "/*\n  Copyright (c) 2018 Arduino LLC. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n/*\n * Defines for 16 bit timers used with Servo library\n *\n */\n\n#ifndef __SERVO_TIMERS_H__\n#define __SERVO_TIMERS_H__\n\n#include <avr/io.h>\n\n//#define USE_TIMERB1        // interferes with PWM on pin 3\n#define USE_TIMERB2        // interferes with PWM on pin 11\n//#define USE_TIMERB0        // interferes with PWM on pin 6\n\n#if !defined(USE_TIMERB1) && !defined(USE_TIMERB2) && !defined(USE_TIMERB0)\n    # error \"No timers allowed for Servo\"\n    /* Please uncomment a timer above and rebuild */\n#endif\n\nstatic volatile TCB_t* _timer =\n#if defined(USE_TIMERB0)\n&TCB0;\n#endif\n#if defined(USE_TIMERB1)\n&TCB1;\n#endif\n#if defined(USE_TIMERB2)\n&TCB2;\n#endif\n\ntypedef enum {\n    timer0,\n    _Nbr_16timers } timer16_Sequence_t;\n\n\n#endif  /* __SERVO_TIMERS_H__ */\n"
  },
  {
    "path": "src/nrf52/Servo.cpp",
    "content": "/*\n  Copyright (c) 2016 Arduino. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n#if defined(ARDUINO_ARCH_NRF52)\n\n#include <Arduino.h>\n#include <Servo.h>\n\n\nstatic servo_t servos[MAX_SERVOS];                          // static array of servo structures\n\nuint8_t ServoCount = 0;                                     // the total number of attached servos\n\n\n\nuint32_t group_pins[3][NRF_PWM_CHANNEL_COUNT]={{NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}, {NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}, {NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}};\nstatic uint16_t seq_values[3][NRF_PWM_CHANNEL_COUNT]={{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};\n\nServo::Servo()\n{\n  if (ServoCount < MAX_SERVOS) {\n    this->servoIndex = ServoCount++;                    // assign a servo index to this instance\n  } else {\n    this->servoIndex = INVALID_SERVO;  \t\t\t\t\t// too many servos\n  }\n\n}\n\nuint8_t Servo::attach(int pin)\n{\n\n\treturn this->attach(pin, 0, 2500);\n}\n\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  int servo_min, servo_max;\n  if (this->servoIndex < MAX_SERVOS) {\n    pinMode(pin, OUTPUT);                                   // set servo pin to output\n    servos[this->servoIndex].Pin.nbr = pin;\n\n\tif(min < servo_min) min = servo_min;\n\tif (max > servo_max) max = servo_max;\n\tthis->min  = min;\n    this->max  = max;\n\n\tservos[this->servoIndex].Pin.isActive = true;\n\n  }\n  return this->servoIndex;\n}\n\nvoid Servo::detach()\n{\n\tservos[this->servoIndex].Pin.isActive = false;\n}\n\n\nvoid Servo::write(int value)\n{\n\tif (value < 0)\n\t\tvalue = 0;\n\telse if (value > 180)\n\t\tvalue = 180;\n\tvalue = map(value, 0, 180, MIN_PULSE, MAX_PULSE);\n\n\twriteMicroseconds(value);\n}\n\n\nvoid Servo::writeMicroseconds(int value)\n{\n\tuint8_t channel, instance;\n\tuint8_t pin = servos[this->servoIndex].Pin.nbr;\n\t//instance of PWM module is MSB - look at VWariant.h\n\tinstance=(g_APinDescription[pin].ulPWMChannel & 0xF0)/16;\n\t//index of PWM channel is LSB - look at VWariant.h\n\tchannel=g_APinDescription[pin].ulPWMChannel & 0x0F;\n\tgroup_pins[instance][channel]=g_APinDescription[pin].ulPin;\n\tNRF_PWM_Type * PWMInstance = instance == 0 ? NRF_PWM0 : (instance == 1 ? NRF_PWM1 : NRF_PWM2);\n\t//configure PWM instance and enable it\n\tseq_values[instance][channel]= value | 0x8000;\n\tnrf_pwm_sequence_t const seq={\n\t\t\t\t\t\t\t\tseq_values[instance],\n\t\t\t\t\t\t\t\tNRF_PWM_VALUES_LENGTH(seq_values),\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t0\n    };\n\tnrf_pwm_pins_set(PWMInstance, group_pins[instance]);\n\tnrf_pwm_enable(PWMInstance);\n\tnrf_pwm_configure(PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, 2500);\t// 20ms - 50Hz\n\tnrf_pwm_decoder_set(PWMInstance, NRF_PWM_LOAD_INDIVIDUAL, NRF_PWM_STEP_AUTO);\n\tnrf_pwm_sequence_set(PWMInstance, 0, &seq);\n\tnrf_pwm_loop_set(PWMInstance, 0UL);\n\tnrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_SEQSTART0);\n}\n\nint Servo::read() // return the value as degrees\n{\n\treturn map(readMicroseconds(), MIN_PULSE, MAX_PULSE, 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n\tuint8_t channel, instance;\n\tuint8_t pin=servos[this->servoIndex].Pin.nbr;\n\tinstance=(g_APinDescription[pin].ulPWMChannel & 0xF0)/16;\n\tchannel=g_APinDescription[pin].ulPWMChannel & 0x0F;\n\t// remove the 16th bit we added before\n\treturn seq_values[instance][channel] & 0x7FFF;\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex].Pin.isActive;\n}\n\n#endif // ARDUINO_ARCH_NRF52\n"
  },
  {
    "path": "src/nrf52/ServoTimers.h",
    "content": "/*\n  Copyright (c) 2016 Arduino. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n/*\n * nRF52 doesn't use timer, but PWM. This file includes definitions to keep\n * compatibility with the Servo library standards.\n */\n\n#ifndef __SERVO_TIMERS_H__\n#define __SERVO_TIMERS_H__\n\n/**\n * nRF52 only definitions\n * ---------------------\n */\n\n#define MIN_PULSE 55\n#define MAX_PULSE 284\n\n// define one timer in order to have MAX_SERVOS = 12\ntypedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t;\n\n#endif   // __SERVO_TIMERS_H__\n"
  },
  {
    "path": "src/renesas/Servo.cpp",
    "content": "/* The MIT License (MIT)\n *\n * Copyright (c) 2022 Arduino SA\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#if defined(ARDUINO_ARCH_RENESAS)\n\n#include \"Arduino.h\"\n#include \"Servo.h\"\n#include \"ServoTimers.h\"\n#include \"math.h\"\n#include \"FspTimer.h\"\n\n#define SERVO_MAX_SERVOS            (_Nbr_16timers  * SERVOS_PER_TIMER)\n#define SERVO_INVALID_INDEX         (255)\n// Lower the timer ticks for finer resolution.\n#define SERVO_US_PER_CYCLE          (20000)\n#define SERVO_IO_PORT_ADDR(pn)      &((R_PORT0 + ((uint32_t) (R_PORT1 - R_PORT0) * (pn)))->PCNTR3)\n#define SERVO_MIN_CYCLE_OFF_US      50\n\n// Internal Servo struct to keep track of RA configuration.\ntypedef struct {\n    // Servo period in microseconds.\n    uint32_t period_us;\n    // Store min/max pulse width here, because min/max in\n    // Servo class are not wide enough for the pulse width.\n    uint32_t period_min;\n    uint32_t period_max;\n    // Period period_count in timer ticks.\n    uint32_t period_ticks;\n    // Internal FSP GPIO port/pin control bits.\n    volatile uint32_t *io_port;\n    uint32_t io_mask;\n} ra_servo_t;\n\n// Keep track of the total number of servos attached.\nstatic size_t n_servos=0;\nstatic ra_servo_t ra_servos[SERVO_MAX_SERVOS];\n\nstatic FspTimer servo_timer;\nstatic bool servo_timer_started = false;\nvoid servo_timer_callback(timer_callback_args_t *args);\n\nstatic uint32_t servo_ticks_per_cycle = 0;\nstatic uint32_t min_servo_cycle_low = 0;\nstatic uint32_t active_servos_mask = 0;\nstatic uint32_t active_servos_mask_refresh = 0;\n\n\nstatic uint32_t us_to_ticks(uint32_t time_us) {\n    return ((float) servo_ticks_per_cycle / (float) SERVO_US_PER_CYCLE) * time_us;\n}\n\nstatic int servo_timer_config(uint32_t period_us)\n{\n    static bool configured = false;\n    if (configured == false) {\n        // Configure and enable the servo timer.\n        uint8_t type = 0;\n        int8_t channel = FspTimer::get_available_timer(type);\n        if (channel != -1) {\n            servo_timer.begin(TIMER_MODE_PERIODIC, type, channel,\n                    1000000.0f/period_us, 50.0f, servo_timer_callback, nullptr);\n            servo_timer.set_period_buffer(false);  // disable period buffering\n            servo_timer.setup_overflow_irq(10);\n            servo_timer.open();\n            servo_timer.stop();\n            // Read the timer's period count.\n            servo_ticks_per_cycle = servo_timer.get_period_raw();\n            min_servo_cycle_low = us_to_ticks(SERVO_MIN_CYCLE_OFF_US);\n\n            configured = true;\n        }\n    }\n    return configured ? 0 : -1;\n}\n\nstatic int servo_timer_start()\n{\n    // Start the timer if it's not started\n    if (servo_timer_started == false &&\n            servo_timer.start() == false) {\n        return -1;\n    }\n    servo_timer_started = true;\n    return 0;\n}\n\nstatic int servo_timer_stop()\n{\n    // Start the timer if it's not started\n    if (servo_timer_started == true &&\n            servo_timer.stop() == false) {\n        return -1;\n    }\n    servo_timer_started = false;\n    return 0;\n}\n\ninline static void servo_timer_set_period(uint32_t period) {\n    servo_timer.set_period(period);\n}\n\nvoid servo_timer_callback(timer_callback_args_t *args)\n{\n    (void)args; // remove warning\n    static uint8_t channel = SERVO_MAX_SERVOS;\n    static uint8_t channel_pin_set_high = 0xff;\n    static uint32_t ticks_accum = 0;\n\n    // See if we need to set a servo back low\n    if (channel_pin_set_high != 0xff) {\n        *ra_servos[channel_pin_set_high].io_port = ra_servos[channel_pin_set_high].io_mask << 16;\n    }\n\n    // Find the next servo to set high\n    while (active_servos_mask_refresh) {\n        channel = __builtin_ctz(active_servos_mask_refresh);\n        if (ra_servos[channel].period_us) {\n            *ra_servos[channel].io_port = ra_servos[channel].io_mask;\n            servo_timer_set_period(ra_servos[channel].period_ticks);\n            channel_pin_set_high = channel;\n            ticks_accum += ra_servos[channel].period_ticks;\n            active_servos_mask_refresh &= ~(1 << channel);\n            return;\n        }\n        active_servos_mask_refresh &= ~(1 << channel);\n    }\n    // Finished processing all servos, now delay to start of next pass.\n    ticks_accum += min_servo_cycle_low;\n    uint32_t time_to_next_cycle;\n    if (servo_ticks_per_cycle > ticks_accum) {\n        time_to_next_cycle = servo_ticks_per_cycle - ticks_accum;\n    } else {\n        time_to_next_cycle = min_servo_cycle_low;\n    }\n    ticks_accum = 0;\n    servo_timer_set_period(time_to_next_cycle);\n    channel_pin_set_high = 0xff;\n    active_servos_mask_refresh = active_servos_mask;\n}\n\nServo::Servo()\n{\n    servoIndex = SERVO_INVALID_INDEX;\n}\n\nuint8_t Servo::attach(int pin)\n{\n    return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nbool Servo::attached()\n{\n    return (servoIndex != SERVO_INVALID_INDEX);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n    //assert(pin < NUM_DIGITAL_PINS); ?\n    if (n_servos == SERVO_MAX_SERVOS) {\n        return 0;\n    }\n\n    // Configure the servo timer.\n    if (servo_timer_config(SERVO_US_PER_CYCLE) != 0) {\n        return 0;\n    }\n\n    // Try to find a free servo slot.\n    ra_servo_t *servo = NULL;\n    bsp_io_port_pin_t io_pin = g_pin_cfg[pin].pin;\n    for (size_t i=0; i<SERVO_MAX_SERVOS; i++) {\n        servo = &ra_servos[i];\n        if (servo->period_us == 0) {\n            n_servos++;\n            servoIndex = i;\n            servo->period_min = min;\n            servo->period_max = max;\n            servo->io_mask = (1U << (io_pin & 0xFF));\n            servo->io_port = SERVO_IO_PORT_ADDR(((io_pin >> 8U) & 0xFF));\n            active_servos_mask |= (1 << i);  // update mask of servos that are active.\n            writeMicroseconds(DEFAULT_PULSE_WIDTH);\n            break;\n        }\n    }\n\n    if (servoIndex == SERVO_INVALID_INDEX) {\n        return 0;\n    }\n\n    // Configure GPIO pin for the servo.\n    R_IOPORT_PinCfg(&g_ioport_ctrl, io_pin,\n            IOPORT_CFG_PORT_DIRECTION_OUTPUT | IOPORT_CFG_PORT_OUTPUT_HIGH);\n\n    // Start the timer if it's not started.\n    if (servo_timer_start() != 0) {\n        return 0;\n    }\n    return 1;\n}\n\nvoid Servo::detach()\n{\n    if (servoIndex != SERVO_INVALID_INDEX) {\n        ra_servo_t *servo = &ra_servos[servoIndex];\n        servo_timer_stop();\n        servo->period_us = 0;\n        active_servos_mask &= ~(1 << servoIndex);  // update mask of servos that are active.\n        servoIndex = SERVO_INVALID_INDEX;\n        if (--n_servos) {\n            servo_timer_start();\n        }\n\n    }\n}\n\nvoid Servo::write(int angle)\n{\n    if (servoIndex != SERVO_INVALID_INDEX) {\n        ra_servo_t *servo = &ra_servos[servoIndex];\n        angle = constrain(angle, 0, 180);\n        writeMicroseconds(map(angle, 0, 180, servo->period_min, servo->period_max));\n    }\n}\n\nint Servo::read()\n{\n    if (servoIndex != SERVO_INVALID_INDEX) {\n        ra_servo_t *servo = &ra_servos[servoIndex];\n        return map(servo->period_us, servo->period_min, servo->period_max, 0, 180);\n    }\n    return 0;\n}\n\nvoid Servo::writeMicroseconds(int us)\n{\n    if (servoIndex != SERVO_INVALID_INDEX) {\n        ra_servo_t *servo = &ra_servos[servoIndex];\n        servo->period_us = constrain(us, servo->period_min, servo->period_max);\n        servo->period_ticks = us_to_ticks(servo->period_us);\n    }\n}\n\nint Servo::readMicroseconds()\n{\n    if (servoIndex != SERVO_INVALID_INDEX) {\n        ra_servo_t *servo = &ra_servos[servoIndex];\n        return servo->period_us;\n    }\n    return 0;\n}\n#endif  // defined(ARDUINO_ARCH_RENESAS)\n"
  },
  {
    "path": "src/renesas/ServoTimers.h",
    "content": "#define _Nbr_16timers 1\n"
  },
  {
    "path": "src/sam/Servo.cpp",
    "content": "/*\n  Copyright (c) 2013 Arduino LLC. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n#if defined(ARDUINO_ARCH_SAM)\n\n#include <Arduino.h>\n#include <Servo.h>\n\n#define usToTicks(_us)    (( clockCyclesPerMicrosecond() * _us) / 32)     // converts microseconds to ticks\n#define ticksToUs(_ticks) (( (unsigned)_ticks * 32)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds\n\n#define TRIM_DURATION       2                               // compensation ticks to trim adjust for digitalWrite delays\n\nstatic servo_t servos[MAX_SERVOS];                          // static array of servo structures\n\nuint8_t ServoCount = 0;                                     // the total number of attached servos\n\nstatic volatile int8_t Channel[_Nbr_16timers ];             // counter for the servo being pulsed for each timer (or -1 if refresh interval)\n\n// convenience macros\n#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo\n#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER)       // returns the index of the servo on this timer\n#define SERVO_INDEX(_timer,_channel)  ((_timer*SERVOS_PER_TIMER) + _channel)     // macro to access servo index by timer and channel\n#define SERVO(_timer,_channel)  (servos[SERVO_INDEX(_timer,_channel)])            // macro to access servo class by timer and channel\n\n#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4)  // minimum value in us for this servo\n#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4)  // maximum value in us for this servo\n\n/************ static functions common to all instances ***********************/\n\n//------------------------------------------------------------------------------\n/// Interrupt handler for the TC0 channel 1.\n//------------------------------------------------------------------------------\nvoid Servo_Handler(timer16_Sequence_t timer, Tc *pTc, uint8_t channel);\n#if defined (_useTimer1)\nvoid HANDLER_FOR_TIMER1(void) {\n    Servo_Handler(_timer1, TC_FOR_TIMER1, CHANNEL_FOR_TIMER1);\n}\n#endif\n#if defined (_useTimer2)\nvoid HANDLER_FOR_TIMER2(void) {\n    Servo_Handler(_timer2, TC_FOR_TIMER2, CHANNEL_FOR_TIMER2);\n}\n#endif\n#if defined (_useTimer3)\nvoid HANDLER_FOR_TIMER3(void) {\n    Servo_Handler(_timer3, TC_FOR_TIMER3, CHANNEL_FOR_TIMER3);\n}\n#endif\n#if defined (_useTimer4)\nvoid HANDLER_FOR_TIMER4(void) {\n    Servo_Handler(_timer4, TC_FOR_TIMER4, CHANNEL_FOR_TIMER4);\n}\n#endif\n#if defined (_useTimer5)\nvoid HANDLER_FOR_TIMER5(void) {\n    Servo_Handler(_timer5, TC_FOR_TIMER5, CHANNEL_FOR_TIMER5);\n}\n#endif\n\nvoid Servo_Handler(timer16_Sequence_t timer, Tc *tc, uint8_t channel)\n{\n    // clear interrupt\n    tc->TC_CHANNEL[channel].TC_SR;\n    if (Channel[timer] < 0) {\n        tc->TC_CHANNEL[channel].TC_CCR |= TC_CCR_SWTRG; // channel set to -1 indicated that refresh interval completed so reset the timer\n    } else {\n        if (SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true) {\n            digitalWrite(SERVO(timer,Channel[timer]).Pin.nbr, LOW); // pulse this channel low if activated\n        }\n    }\n\n    Channel[timer]++;    // increment to the next channel\n    if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) {\n        tc->TC_CHANNEL[channel].TC_RA = tc->TC_CHANNEL[channel].TC_CV + SERVO(timer,Channel[timer]).ticks;\n        if(SERVO(timer,Channel[timer]).Pin.isActive == true) {    // check if activated\n            digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // it's an active channel so pulse it high\n        }\n    }\n    else {\n        // finished all channels so wait for the refresh period to expire before starting over\n        if( (tc->TC_CHANNEL[channel].TC_CV) + 4 < usToTicks(REFRESH_INTERVAL) ) { // allow a few ticks to ensure the next OCR1A not missed\n            tc->TC_CHANNEL[channel].TC_RA = (unsigned int)usToTicks(REFRESH_INTERVAL);\n        }\n        else {\n            tc->TC_CHANNEL[channel].TC_RA = tc->TC_CHANNEL[channel].TC_CV + 4;  // at least REFRESH_INTERVAL has elapsed\n        }\n        Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel\n    }\n}\n\nstatic void _initISR(Tc *tc, uint32_t channel, uint32_t id, IRQn_Type irqn)\n{\n    pmc_enable_periph_clk(id);\n    TC_Configure(tc, channel,\n   TC_CMR_TCCLKS_TIMER_CLOCK3 | // MCK/32\n            TC_CMR_WAVE |                // Waveform mode\n            TC_CMR_WAVSEL_UP_RC );       // Counter running up and reset when equals to RC\n\n    /* 84 MHz, MCK/32, for 1.5 ms: 3937 */\n    TC_SetRA(tc, channel, 2625); // 1ms\n\n    /* Configure and enable interrupt */\n    NVIC_EnableIRQ(irqn);\n    // TC_IER_CPAS: RA Compare\n    tc->TC_CHANNEL[channel].TC_IER = TC_IER_CPAS;\n\n    // Enables the timer clock and performs a software reset to start the counting\n    TC_Start(tc, channel);\n}\n\nstatic void initISR(timer16_Sequence_t timer)\n{\n#if defined (_useTimer1)\n    if (timer == _timer1)\n        _initISR(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, ID_TC_FOR_TIMER1, IRQn_FOR_TIMER1);\n#endif\n#if defined (_useTimer2)\n    if (timer == _timer2)\n        _initISR(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, ID_TC_FOR_TIMER2, IRQn_FOR_TIMER2);\n#endif\n#if defined (_useTimer3)\n    if (timer == _timer3)\n        _initISR(TC_FOR_TIMER3, CHANNEL_FOR_TIMER3, ID_TC_FOR_TIMER3, IRQn_FOR_TIMER3);\n#endif\n#if defined (_useTimer4)\n    if (timer == _timer4)\n        _initISR(TC_FOR_TIMER4, CHANNEL_FOR_TIMER4, ID_TC_FOR_TIMER4, IRQn_FOR_TIMER4);\n#endif\n#if defined (_useTimer5)\n    if (timer == _timer5)\n        _initISR(TC_FOR_TIMER5, CHANNEL_FOR_TIMER5, ID_TC_FOR_TIMER5, IRQn_FOR_TIMER5);\n#endif\n}\n\nstatic void finISR(timer16_Sequence_t timer)\n{\n#if defined (_useTimer1)\n    TC_Stop(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1);\n#endif\n#if defined (_useTimer2)\n    TC_Stop(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2);\n#endif\n#if defined (_useTimer3)\n    TC_Stop(TC_FOR_TIMER3, CHANNEL_FOR_TIMER3);\n#endif\n#if defined (_useTimer4)\n    TC_Stop(TC_FOR_TIMER4, CHANNEL_FOR_TIMER4);\n#endif\n#if defined (_useTimer5)\n    TC_Stop(TC_FOR_TIMER5, CHANNEL_FOR_TIMER5);\n#endif\n}\n\n\nstatic boolean isTimerActive(timer16_Sequence_t timer)\n{\n  // returns true if any servo is active on this timer\n  for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) {\n    if(SERVO(timer,channel).Pin.isActive == true)\n      return true;\n  }\n  return false;\n}\n\n/****************** end of static functions ******************************/\n\nServo::Servo()\n{\n  if (ServoCount < MAX_SERVOS) {\n    this->servoIndex = ServoCount++;                    // assign a servo index to this instance\n    servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);   // store default values\n  } else {\n    this->servoIndex = INVALID_SERVO;  // too many servos\n  }\n}\n\nuint8_t Servo::attach(int pin)\n{\n  return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  timer16_Sequence_t timer;\n\n  if (this->servoIndex < MAX_SERVOS) {\n    pinMode(pin, OUTPUT);                                   // set servo pin to output\n    servos[this->servoIndex].Pin.nbr = pin;\n    // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128\n    this->min  = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us\n    this->max  = (MAX_PULSE_WIDTH - max)/4;\n    // initialize the timer if it has not already been initialized\n    timer = SERVO_INDEX_TO_TIMER(servoIndex);\n    if (isTimerActive(timer) == false) {\n      initISR(timer);\n    }\n    servos[this->servoIndex].Pin.isActive = true;  // this must be set after the check for isTimerActive\n  }\n  return this->servoIndex;\n}\n\nvoid Servo::detach()\n{\n  timer16_Sequence_t timer;\n\n  servos[this->servoIndex].Pin.isActive = false;\n  timer = SERVO_INDEX_TO_TIMER(servoIndex);\n  if(isTimerActive(timer) == false) {\n    finISR(timer);\n  }\n}\n\nvoid Servo::write(int value)\n{\n  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)\n  if (value < MIN_PULSE_WIDTH)\n  {\n    if (value < 0)\n      value = 0;\n    else if (value > 180)\n      value = 180;\n\n    value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());\n  }\n  writeMicroseconds(value);\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n  // calculate and store the values for the given channel\n  byte channel = this->servoIndex;\n  if( (channel < MAX_SERVOS) )   // ensure channel is valid\n  {\n    if (value < SERVO_MIN())          // ensure pulse width is valid\n      value = SERVO_MIN();\n    else if (value > SERVO_MAX())\n      value = SERVO_MAX();\n\n    value = value - TRIM_DURATION;\n    value = usToTicks(value);  // convert to ticks after compensating for interrupt overhead\n    servos[channel].ticks = value;\n  }\n}\n\nint Servo::read() // return the value as degrees\n{\n  return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n  unsigned int pulsewidth;\n  if (this->servoIndex != INVALID_SERVO)\n    pulsewidth = ticksToUs(servos[this->servoIndex].ticks)  + TRIM_DURATION;\n  else\n    pulsewidth  = 0;\n\n  return pulsewidth;\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex].Pin.isActive;\n}\n\n#endif // ARDUINO_ARCH_SAM\n"
  },
  {
    "path": "src/sam/ServoTimers.h",
    "content": "/*\n  Copyright (c) 2013 Arduino LLC. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n/*\n * Defines for 16 bit timers used with Servo library\n *\n * If _useTimerX is defined then TimerX is a 16 bit timer on the current board\n * timer16_Sequence_t enumerates the sequence that the timers should be allocated\n * _Nbr_16timers indicates how many 16 bit timers are available.\n */\n\n/**\n * SAM Only definitions\n * --------------------\n */\n\n// For SAM3X:\n#define _useTimer1\n#define _useTimer2\n#define _useTimer3\n#define _useTimer4\n#define _useTimer5\n\n/*\n  TC0, chan 0 => TC0_Handler\n  TC0, chan 1 => TC1_Handler\n  TC0, chan 2 => TC2_Handler\n  TC1, chan 0 => TC3_Handler\n  TC1, chan 1 => TC4_Handler\n  TC1, chan 2 => TC5_Handler\n  TC2, chan 0 => TC6_Handler\n  TC2, chan 1 => TC7_Handler\n  TC2, chan 2 => TC8_Handler\n */\n\n#if defined (_useTimer1)\n#define TC_FOR_TIMER1       TC1\n#define CHANNEL_FOR_TIMER1  0\n#define ID_TC_FOR_TIMER1    ID_TC3\n#define IRQn_FOR_TIMER1     TC3_IRQn\n#define HANDLER_FOR_TIMER1  TC3_Handler\n#endif\n#if defined (_useTimer2)\n#define TC_FOR_TIMER2       TC1\n#define CHANNEL_FOR_TIMER2  1\n#define ID_TC_FOR_TIMER2    ID_TC4\n#define IRQn_FOR_TIMER2     TC4_IRQn\n#define HANDLER_FOR_TIMER2  TC4_Handler\n#endif\n#if defined (_useTimer3)\n#define TC_FOR_TIMER3       TC1\n#define CHANNEL_FOR_TIMER3  2\n#define ID_TC_FOR_TIMER3    ID_TC5\n#define IRQn_FOR_TIMER3     TC5_IRQn\n#define HANDLER_FOR_TIMER3  TC5_Handler\n#endif\n#if defined (_useTimer4)\n#define TC_FOR_TIMER4       TC0\n#define CHANNEL_FOR_TIMER4  2\n#define ID_TC_FOR_TIMER4    ID_TC2\n#define IRQn_FOR_TIMER4     TC2_IRQn\n#define HANDLER_FOR_TIMER4  TC2_Handler\n#endif\n#if defined (_useTimer5)\n#define TC_FOR_TIMER5       TC0\n#define CHANNEL_FOR_TIMER5  0\n#define ID_TC_FOR_TIMER5    ID_TC0\n#define IRQn_FOR_TIMER5     TC0_IRQn\n#define HANDLER_FOR_TIMER5  TC0_Handler\n#endif\n\ntypedef enum { _timer1, _timer2, _timer3, _timer4, _timer5, _Nbr_16timers } timer16_Sequence_t ;\n"
  },
  {
    "path": "src/samd/Servo.cpp",
    "content": "/*\n  Copyright (c) 2015 Arduino LLC. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n#if defined(ARDUINO_ARCH_SAMD)\n\n#include <Arduino.h>\n#include <Servo.h>\n\n#define usToTicks(_us)    ((clockCyclesPerMicrosecond() * _us) / 16)                 // converts microseconds to ticks\n#define ticksToUs(_ticks) (((unsigned) _ticks * 16) / clockCyclesPerMicrosecond())   // converts from ticks back to microseconds\n\n#define TRIM_DURATION  5                                   // compensation ticks to trim adjust for digitalWrite delays\n\nstatic servo_t servos[MAX_SERVOS];                         // static array of servo structures\n\nuint8_t ServoCount = 0;                                    // the total number of attached servos\n\nstatic volatile int8_t currentServoIndex[_Nbr_16timers];   // index for the servo being pulsed for each timer (or -1 if refresh interval)\n\n// convenience macros\n#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER))   // returns the timer controlling this servo\n#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER)                       // returns the index of the servo on this timer\n#define SERVO_INDEX(_timer,_channel)  ((_timer*SERVOS_PER_TIMER) + _channel)                     // macro to access servo index by timer and channel\n#define SERVO(_timer,_channel)  (servos[SERVO_INDEX(_timer,_channel)])                           // macro to access servo class by timer and channel\n\n#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4)   // minimum value in us for this servo\n#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4)   // maximum value in us for this servo\n\n#define WAIT_TC16_REGS_SYNC(x) while(x->COUNT16.STATUS.bit.SYNCBUSY);\n\n/************ static functions common to all instances ***********************/\n\nvoid Servo_Handler(timer16_Sequence_t timer, Tc *pTc, uint8_t channel, uint8_t intFlag);\n#if defined (_useTimer1)\nvoid HANDLER_FOR_TIMER1(void) {\n    Servo_Handler(_timer1, TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, INTFLAG_BIT_FOR_TIMER_1);\n}\n#endif\n#if defined (_useTimer2)\nvoid HANDLER_FOR_TIMER2(void) {\n    Servo_Handler(_timer2, TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, INTFLAG_BIT_FOR_TIMER_2);\n}\n#endif\n\nvoid Servo_Handler(timer16_Sequence_t timer, Tc *tc, uint8_t channel, uint8_t intFlag)\n{\n    if (currentServoIndex[timer] < 0) {\n        tc->COUNT16.COUNT.reg = (uint16_t) 0;\n        WAIT_TC16_REGS_SYNC(tc)\n    } else {\n        if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) {\n            digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, LOW);   // pulse this channel low if activated\n        }\n    }\n\n    // Select the next servo controlled by this timer\n    currentServoIndex[timer]++;\n\n    if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && currentServoIndex[timer] < SERVOS_PER_TIMER) {\n        if (SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) {   // check if activated\n            digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, HIGH);   // it's an active channel so pulse it high\n        }\n\n        // Get the counter value\n        uint16_t tcCounterValue = tc->COUNT16.COUNT.reg;\n        WAIT_TC16_REGS_SYNC(tc)\n\n        tc->COUNT16.CC[channel].reg = (uint16_t) (tcCounterValue + SERVO(timer, currentServoIndex[timer]).ticks);\n        WAIT_TC16_REGS_SYNC(tc)\n    }\n    else {\n        // finished all channels so wait for the refresh period to expire before starting over\n\n        // Get the counter value\n        uint16_t tcCounterValue = tc->COUNT16.COUNT.reg;\n        WAIT_TC16_REGS_SYNC(tc)\n\n        if (tcCounterValue + 4UL < usToTicks(REFRESH_INTERVAL)) {   // allow a few ticks to ensure the next OCR1A not missed\n            tc->COUNT16.CC[channel].reg = (uint16_t) usToTicks(REFRESH_INTERVAL);\n        }\n        else {\n            tc->COUNT16.CC[channel].reg = (uint16_t) (tcCounterValue + 4UL);   // at least REFRESH_INTERVAL has elapsed\n        }\n        WAIT_TC16_REGS_SYNC(tc)\n\n        currentServoIndex[timer] = -1;   // this will get incremented at the end of the refresh period to start again at the first channel\n    }\n\n    // Clear the interrupt\n    tc->COUNT16.INTFLAG.reg = intFlag;\n}\n\nstatic inline void resetTC (Tc* TCx)\n{\n    // Disable TCx\n    TCx->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE;\n    WAIT_TC16_REGS_SYNC(TCx)\n\n    // Reset TCx\n    TCx->COUNT16.CTRLA.reg = TC_CTRLA_SWRST;\n    WAIT_TC16_REGS_SYNC(TCx)\n    while (TCx->COUNT16.CTRLA.bit.SWRST);\n}\n\nstatic void _initISR(Tc *tc, uint8_t channel, uint32_t id, IRQn_Type irqn, uint8_t gcmForTimer, uint8_t intEnableBit)\n{\n    // Enable GCLK for timer 1 (timer counter input clock)\n    GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(gcmForTimer));\n    while (GCLK->STATUS.bit.SYNCBUSY);\n\n    // Reset the timer\n    // TODO this is not the right thing to do if more than one channel per timer is used by the Servo library\n    resetTC(tc);\n\n    // Set timer counter mode to 16 bits\n    tc->COUNT16.CTRLA.reg |= TC_CTRLA_MODE_COUNT16;\n\n    // Set timer counter mode as normal PWM\n    tc->COUNT16.CTRLA.reg |= TC_CTRLA_WAVEGEN_NPWM;\n\n    // Set the prescaler factor to GCLK_TC/16. At nominal 48 MHz GCLK_TC this is 3000 ticks per millisecond\n    tc->COUNT16.CTRLA.reg |= TC_CTRLA_PRESCALER_DIV16;\n\n    // Count up\n    tc->COUNT16.CTRLBCLR.bit.DIR = 1;\n    WAIT_TC16_REGS_SYNC(tc)\n\n    // First interrupt request after 1 ms\n    tc->COUNT16.CC[channel].reg = (uint16_t) usToTicks(1000UL);\n    WAIT_TC16_REGS_SYNC(tc)\n\n    // Configure interrupt request\n    // TODO this should be changed if more than one channel per timer is used by the Servo library\n    NVIC_DisableIRQ(irqn);\n    NVIC_ClearPendingIRQ(irqn);\n    NVIC_SetPriority(irqn, 0);\n    NVIC_EnableIRQ(irqn);\n\n    // Enable the match channel interrupt request\n    tc->COUNT16.INTENSET.reg = intEnableBit;\n\n    // Enable the timer and start it\n    tc->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE;\n    WAIT_TC16_REGS_SYNC(tc)\n}\n\nstatic void initISR(timer16_Sequence_t timer)\n{\n#if defined (_useTimer1)\n    if (timer == _timer1)\n        _initISR(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, ID_TC_FOR_TIMER1, IRQn_FOR_TIMER1, GCM_FOR_TIMER_1, INTENSET_BIT_FOR_TIMER_1);\n#endif\n#if defined (_useTimer2)\n    if (timer == _timer2)\n        _initISR(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, ID_TC_FOR_TIMER2, IRQn_FOR_TIMER2, GCM_FOR_TIMER_2, INTENSET_BIT_FOR_TIMER_2);\n#endif\n}\n\nstatic void finISR(timer16_Sequence_t timer)\n{\n#if defined (_useTimer1)\n    // Disable the match channel interrupt request\n    TC_FOR_TIMER1->COUNT16.INTENCLR.reg = INTENCLR_BIT_FOR_TIMER_1;\n#endif\n#if defined (_useTimer2)\n    // Disable the match channel interrupt request\n    TC_FOR_TIMER2->COUNT16.INTENCLR.reg = INTENCLR_BIT_FOR_TIMER_2;\n#endif\n}\n\nstatic boolean isTimerActive(timer16_Sequence_t timer)\n{\n  // returns true if any servo is active on this timer\n  for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) {\n    if(SERVO(timer,channel).Pin.isActive == true)\n      return true;\n  }\n  return false;\n}\n\n/****************** end of static functions ******************************/\n\nServo::Servo()\n{\n  if (ServoCount < MAX_SERVOS) {\n    this->servoIndex = ServoCount++;                    // assign a servo index to this instance\n    servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);   // store default values\n  } else {\n    this->servoIndex = INVALID_SERVO;  // too many servos\n  }\n}\n\nuint8_t Servo::attach(int pin)\n{\n  return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);\n}\n\nuint8_t Servo::attach(int pin, int min, int max)\n{\n  timer16_Sequence_t timer;\n\n  if (this->servoIndex < MAX_SERVOS) {\n    pinMode(pin, OUTPUT);                                   // set servo pin to output\n    servos[this->servoIndex].Pin.nbr = pin;\n    // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128\n    this->min  = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us\n    this->max  = (MAX_PULSE_WIDTH - max)/4;\n    // initialize the timer if it has not already been initialized\n    timer = SERVO_INDEX_TO_TIMER(servoIndex);\n    if (isTimerActive(timer) == false) {\n      initISR(timer);\n    }\n    servos[this->servoIndex].Pin.isActive = true;  // this must be set after the check for isTimerActive\n  }\n  return this->servoIndex;\n}\n\nvoid Servo::detach()\n{\n  timer16_Sequence_t timer;\n\n  servos[this->servoIndex].Pin.isActive = false;\n  timer = SERVO_INDEX_TO_TIMER(servoIndex);\n  if(isTimerActive(timer) == false) {\n    finISR(timer);\n  }\n}\n\nvoid Servo::write(int value)\n{\n  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)\n  if (value < MIN_PULSE_WIDTH)\n  {\n    if (value < 0)\n      value = 0;\n    else if (value > 180)\n      value = 180;\n\n    value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX());\n  }\n  writeMicroseconds(value);\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n  // calculate and store the values for the given channel\n  byte channel = this->servoIndex;\n  if( (channel < MAX_SERVOS) )   // ensure channel is valid\n  {\n    if (value < SERVO_MIN())          // ensure pulse width is valid\n      value = SERVO_MIN();\n    else if (value > SERVO_MAX())\n      value = SERVO_MAX();\n\n    value = value - TRIM_DURATION;\n    value = usToTicks(value);  // convert to ticks after compensating for interrupt overhead\n    servos[channel].ticks = value;\n  }\n}\n\nint Servo::read() // return the value as degrees\n{\n  return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180);\n}\n\nint Servo::readMicroseconds()\n{\n  unsigned int pulsewidth;\n  if (this->servoIndex != INVALID_SERVO)\n    pulsewidth = ticksToUs(servos[this->servoIndex].ticks)  + TRIM_DURATION;\n  else\n    pulsewidth  = 0;\n\n  return pulsewidth;\n}\n\nbool Servo::attached()\n{\n  return servos[this->servoIndex].Pin.isActive;\n}\n\n#endif // ARDUINO_ARCH_SAMD\n"
  },
  {
    "path": "src/samd/ServoTimers.h",
    "content": "/*\n  Copyright (c) 2015 Arduino LLC. All right reserved.\n\n  This library is free software; you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public\n  License as published by the Free Software Foundation; either\n  version 2.1 of the License, or (at your option) any later version.\n\n  This library is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this library; if not, write to the Free Software\n  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*/\n\n/*\n * Defines for 16 bit timers used with Servo library\n *\n * If _useTimerX is defined then TimerX is a 16 bit timer on the current board\n * timer16_Sequence_t enumerates the sequence that the timers should be allocated\n * _Nbr_16timers indicates how many 16 bit timers are available.\n */\n\n#ifndef __SERVO_TIMERS_H__\n#define __SERVO_TIMERS_H__\n\n/**\n * SAMD Only definitions\n * ---------------------\n */\n\n// For SAMD:\n#define _useTimer1\n//#define _useTimer2   // <- TODO do not activate until the code in Servo.cpp has been changed in order\n                       //         to manage more than one channel per timer on the SAMD architecture\n\n#if defined (_useTimer1)\n#define TC_FOR_TIMER1             TC4\n#define CHANNEL_FOR_TIMER1        0\n#define INTENSET_BIT_FOR_TIMER_1  TC_INTENSET_MC0\n#define INTENCLR_BIT_FOR_TIMER_1  TC_INTENCLR_MC0\n#define INTFLAG_BIT_FOR_TIMER_1   TC_INTFLAG_MC0\n#define ID_TC_FOR_TIMER1          ID_TC4\n#define IRQn_FOR_TIMER1           TC4_IRQn\n#define HANDLER_FOR_TIMER1        TC4_Handler\n#define GCM_FOR_TIMER_1           GCM_TC4_TC5\n#endif\n#if defined (_useTimer2)\n#define TC_FOR_TIMER2             TC4\n#define CHANNEL_FOR_TIMER2        1\n#define INTENSET_BIT_FOR_TIMER_2  TC_INTENSET_MC1\n#define INTENCLR_BIT_FOR_TIMER_2  TC_INTENCLR_MC1\n#define ID_TC_FOR_TIMER2          ID_TC4\n#define IRQn_FOR_TIMER2           TC4_IRQn\n#define HANDLER_FOR_TIMER2        TC4_Handler\n#define GCM_FOR_TIMER_2           GCM_TC4_TC5\n#endif\n\ntypedef enum {\n#if defined (_useTimer1)\n    _timer1,\n#endif\n#if defined (_useTimer2)\n    _timer2,\n#endif\n    _Nbr_16timers } timer16_Sequence_t;\n\n#endif   // __SERVO_TIMERS_H__\n"
  },
  {
    "path": "src/stm32f4/Servo.cpp",
    "content": "/******************************************************************************\n * The MIT License\n *\n * Copyright (c) 2010, LeafLabs, LLC.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *****************************************************************************/\n\n#if defined(ARDUINO_ARCH_STM32F4)\n\n#include \"ServoTimers.h\"\n\n#include \"boards.h\"\n#include \"io.h\"\n#include \"pwm.h\"\n#include \"math.h\"\n\n// 20 millisecond period config. For a 1-based prescaler,\n//\n//    (prescaler * overflow / CYC_MSEC) msec = 1 timer cycle = 20 msec\n// => prescaler * overflow = 20 * CYC_MSEC\n//\n// This picks the smallest prescaler that allows an overflow < 2^16.\n#define MAX_OVERFLOW    ((1 << 16) - 1)\n#define CYC_MSEC        (1000 * CYCLES_PER_MICROSECOND)\n#define TAU_MSEC        20\n#define TAU_USEC        (TAU_MSEC * 1000)\n#define TAU_CYC         (TAU_MSEC * CYC_MSEC)\n#define SERVO_PRESCALER (TAU_CYC / MAX_OVERFLOW + 1)\n#define SERVO_OVERFLOW  ((uint16)round((double)TAU_CYC / SERVO_PRESCALER))\n\n// Unit conversions\n#define US_TO_COMPARE(us) ((uint16)map((us), 0, TAU_USEC, 0, SERVO_OVERFLOW))\n#define COMPARE_TO_US(c)  ((uint32)map((c), 0, SERVO_OVERFLOW, 0, TAU_USEC))\n#define ANGLE_TO_US(a)    ((uint16)(map((a), this->minAngle, this->maxAngle, \\\n                                        this->minPW, this->maxPW)))\n#define US_TO_ANGLE(us)   ((int16)(map((us), this->minPW, this->maxPW,  \\\n                                       this->minAngle, this->maxAngle)))\n\nServo::Servo() {\n    this->resetFields();\n}\n\nbool Servo::attach(uint8 pin, uint16 minPW, uint16 maxPW, int16 minAngle, int16 maxAngle)\n{\n    // SerialUSB.begin(115200);\n    // SerialUSB.println(MAX_OVERFLOW);\n\n\n    timer_dev *tdev = PIN_MAP[pin].timer_device;\n\n    analogWriteResolution(16);\n\n    int prescaler = 6;\n    int overflow = 65400;\n    int minPW_correction = 300;\n    int maxPW_correction = 300;\n\n    pinMode(pin, OUTPUT);\n\n\n    if (tdev == NULL) {\n        // don't reset any fields or ASSERT(0), to keep driving any\n        // previously attach()ed servo.\n        return false;\n    }\n\n    if ( (tdev == TIMER1) || (tdev == TIMER8) || (tdev == TIMER10) || (tdev == TIMER11))\n    {\n        prescaler = 54;\n        overflow = 65400;\n        minPW_correction = 40;\n        maxPW_correction = 50;\n    }\n\n    if ( (tdev == TIMER2) || (tdev == TIMER3) || (tdev == TIMER4) || (tdev == TIMER5) )\n    {\n        prescaler = 6;\n        overflow = 64285;\n        minPW_correction = 370;\n        maxPW_correction = 350;\n    }\n\n    if ( (tdev == TIMER6) || (tdev == TIMER7) )\n    {\n        prescaler = 6;\n        overflow = 65400;\n        minPW_correction = 0;\n        maxPW_correction = 0;\n    }\n\n    if ( (tdev == TIMER9) || (tdev == TIMER12) || (tdev == TIMER13) || (tdev == TIMER14) )\n    {\n        prescaler = 6;\n        overflow = 65400;\n        minPW_correction = 30;\n        maxPW_correction = 0;\n    }\n\n    if (this->attached()) {\n        this->detach();\n    }\n\n    this->pin = pin;\n    this->minPW = (minPW + minPW_correction);\n    this->maxPW = (maxPW + maxPW_correction);\n    this->minAngle = minAngle;\n    this->maxAngle = maxAngle;\n\n    timer_pause(tdev);\n    timer_set_prescaler(tdev, prescaler); // prescaler is 1-based\n    timer_set_reload(tdev, overflow);\n    timer_generate_update(tdev);\n    timer_resume(tdev);\n\n    return true;\n}\n\nbool Servo::detach() {\n    if (!this->attached()) {\n        return false;\n    }\n\n    timer_dev *tdev = PIN_MAP[this->pin].timer_device;\n    uint8 tchan = PIN_MAP[this->pin].timer_channel;\n    timer_set_mode(tdev, tchan, TIMER_DISABLED);\n\n    this->resetFields();\n\n    return true;\n}\n\nvoid Servo::write(int degrees) {\n    degrees = constrain(degrees, this->minAngle, this->maxAngle);\n    this->writeMicroseconds(ANGLE_TO_US(degrees));\n}\n\nint Servo::read() const {\n    int a = US_TO_ANGLE(this->readMicroseconds());\n    // map() round-trips in a weird way we mostly correct for here;\n    // the round-trip is still sometimes off-by-one for write(1) and\n    // write(179).\n    return a == this->minAngle || a == this->maxAngle ? a : a + 1;\n}\n\nvoid Servo::writeMicroseconds(uint16 pulseWidth) {\n    if (!this->attached()) {\n        ASSERT(0);\n        return;\n    }\n    pulseWidth = constrain(pulseWidth, this->minPW, this->maxPW);\n    analogWrite(this->pin, US_TO_COMPARE(pulseWidth));\n}\n\nuint16 Servo::readMicroseconds() const {\n    if (!this->attached()) {\n        ASSERT(0);\n        return 0;\n    }\n\n    stm32_pin_info pin_info = PIN_MAP[this->pin];\n    uint16 compare = timer_get_compare(pin_info.timer_device,\n                                       pin_info.timer_channel);\n\n    return COMPARE_TO_US(compare);\n}\n\nvoid Servo::resetFields(void) {\n    this->pin = NOT_ATTACHED;\n    this->minAngle = MIN_ANGLE;\n    this->maxAngle = MAX_ANGLE;\n    this->minPW = MIN_PULSE_WIDTH;\n    this->maxPW = MAX_PULSE_WIDTH;\n}\n\n#endif\n"
  },
  {
    "path": "src/stm32f4/ServoTimers.h",
    "content": "/******************************************************************************\n * The MIT License\n *\n * Copyright (c) 2010, LeafLabs, LLC.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *****************************************************************************/\n\n /*\n * Arduino srl - www.arduino.org\n * 2017 Feb 23: Edited by Francesco Alessi (alfran) - francesco@arduino.org\n */\n#ifndef _SERVO_H_\n#define _SERVO_H_\n\n#include \"types.h\"\n#include \"timer.h\"\n\n#include \"wiring.h\"             /* hack for IDE compile */\n\n/*\n * Note on Arduino compatibility:\n *\n * In the Arduino implementation, PWM is done \"by hand\" in the sense\n * that timer channels are hijacked in groups and an ISR is set which\n * toggles Servo::attach()ed pins using digitalWrite().\n *\n * While this scheme allows any pin to drive a servo, it chews up\n * cycles and complicates the programmer's notion of when a particular\n * timer channel will be in use.\n *\n * This implementation only allows Servo instances to attach() to pins\n * that already have a timer channel associated with them, and just\n * uses analogWrite() to drive the wave.\n *\n * This introduces an incompatibility: while the Arduino\n * implementation of attach() returns the affected channel on success\n * and 0 on failure, this one returns true on success and false on\n * failure.\n *\n * RC Servos expect a pulse every 20 ms. Since periods are set for\n * entire timers, rather than individual channels, attach()ing a Servo\n * to a pin can interfere with other pins associated with the same\n * timer. As always, your board's pin map is your friend.\n */\n\n// Pin number of unattached pins\n#define NOT_ATTACHED                    (-1)\n\n#define _Nbr_16timers 14 // Number of STM32F469 Timers\n#define SERVOS_PER_TIMER 4 // Number of timer channels\n\n\n// Default min/max pulse widths (in microseconds) and angles (in\n// degrees). Values chosen for Arduino compatibility. These values\n// are part of the public API; DO NOT CHANGE THEM.\n#define MIN_ANGLE               0\n#define MAX_ANGLE             180\n\n#define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo\n#define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo\n\n/** Class for interfacing with RC servomotors. */\nclass Servo {\npublic:\n    /**\n     * @brief Construct a new Servo instance.\n     *\n     * The new instance will not be attached to any pin.\n     */\n    Servo();\n\n    /**\n     * @brief Associate this instance with a servomotor whose input is\n     *        connected to pin.\n     *\n     * If this instance is already attached to a pin, it will be\n     * detached before being attached to the new pin. This function\n     * doesn't detach any interrupt attached with the pin's timer\n     * channel.\n     *\n     * @param pin Pin connected to the servo pulse wave input. This\n     *            pin must be capable of PWM output.\n     *\n     * @param minPulseWidth Minimum pulse width to write to pin, in\n     *                      microseconds. This will be associated\n     *                      with a minAngle degree angle. Defaults to\n     *                      SERVO_DEFAULT_MIN_PW = 544.\n     *\n     * @param maxPulseWidth Maximum pulse width to write to pin, in\n     *                      microseconds. This will be associated\n     *                      with a maxAngle degree angle. Defaults to\n     *                      SERVO_DEFAULT_MAX_PW = 2400.\n     *\n     * @param minAngle Target angle (in degrees) associated with\n     *                 minPulseWidth. Defaults to\n     *                 SERVO_DEFAULT_MIN_ANGLE = 0.\n     *\n     * @param maxAngle Target angle (in degrees) associated with\n     *                 maxPulseWidth. Defaults to\n     *                 SERVO_DEFAULT_MAX_ANGLE = 180.\n     *\n     * @sideeffect May set pinMode(pin, PWM).\n     *\n     * @return true if successful, false when pin doesn't support PWM.\n     */\n\n    bool attach(uint8 pin,\n                uint16 minPulseWidth=MIN_PULSE_WIDTH,\n                uint16 maxPulseWidth=MAX_PULSE_WIDTH,\n                int16 minAngle=MIN_ANGLE,\n                int16 maxAngle=MAX_ANGLE);\n    /**\n     * @brief Stop driving the servo pulse train.\n     *\n     * If not currently attached to a motor, this function has no effect.\n     *\n     * @return true if this call did anything, false otherwise.\n     */\n    bool detach();\n\n    /**\n     * @brief Set the servomotor target angle.\n     *\n     * @param angle Target angle, in degrees. If the target angle is\n     *              outside the range specified at attach() time, it\n     *              will be clamped to lie in that range.\n     *\n     * @see Servo::attach()\n     */\n    void write(int angle);\n\n    /**\n     * @brief Set the pulse width, in microseconds.\n     *\n     * @param pulseWidth Pulse width to send to the servomotor, in\n     *                   microseconds. If outside of the range\n     *                   specified at attach() time, it is clamped to\n     *                   lie in that range.\n     *\n     * @see Servo::attach()\n     */\n    void writeMicroseconds(uint16 pulseWidth);\n\n    /**\n     * Get the servomotor's target angle, in degrees. This will\n     * lie inside the range specified at attach() time.\n     *\n     * @see Servo::attach()\n     */\n    int read() const;\n\n    /**\n     * Get the current pulse width, in microseconds. This will\n     * lie within the range specified at attach() time.\n     *\n     * @see Servo::attach()\n     */\n    uint16 readMicroseconds() const;\n\n\n    /**\n     * @brief Check if this instance is attached to a servo.\n     * @return true if this instance is attached to a servo, false otherwise.\n     * @see Servo::attachedPin()\n     */\n    bool attached() const { return this->pin != NOT_ATTACHED; }\n\n    /**\n     * @brief Get the pin this instance is attached to.\n     * @return Pin number if currently attached to a pin, NOT_ATTACHED\n     *         otherwise.\n     * @see Servo::attach()\n     */\n    int attachedPin() const { return this->pin; }\n\nprivate:\n    int16 pin;\n    uint16 minPW;\n    uint16 maxPW;\n    int16 minAngle;\n    int16 maxAngle;\n\n    void resetFields(void);\n};\n\n\n\n#endif  /* _SERVO_H_ */\n"
  },
  {
    "path": "src/xmc/Servo.cpp",
    "content": "/******************************************************************************\n * The MIT License\n *\n * Copyright (c) 2010, LeafLabs, LLC.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *****************************************************************************/\n\n#if defined(ARDUINO_ARCH_XMC)\n\n#include \"ServoTimers.h\"\n\n       uint8_t _ServoCount = 1;                                  // internal counter to check if max numbers of servos is reached\nstatic uint8_t _allowed[MAX_PWM_SERVOS] = ALLOWED_PINS;          // internal array to check allowed pwm pins\nstatic uint8_t _servos[MAX_PWM_SERVOS];                          // static array of used servo pins for checking\n\n\n/**\n * @brief None blocking wait loop.\n *\n * @param uS microseconds to wait\n */\nstatic void _delayUs(unsigned long uS)\n{\n    unsigned long time_now = micros();\n    while (micros() < time_now + uS)\n        ;\n}\n\n\nServo::Servo()\n{\n    if (_ServoCount <= MAX_PWM_SERVOS )\n    {\n        this->servoIndex = _ServoCount++;\n\n        this->_minAngle = MIN_ANGLE;\n        this->_maxAngle = MAX_ANGLE;\n        this->_minPW = MIN_PULSE_WIDTH;\n        this->_maxPW = MAX_PULSE_WIDTH;\n        this->_pin = 0;\n        this->_isActive = false;\n        this->_pwm = 0;\n        this->_deg = 0.0;\n    }else{\n        this->servoIndex = INVALID_SERVO;\n    }\n}\n\nuint8_t Servo::attach(uint8_t pin, uint16_t min, uint16_t max)\n{\n    if (this->servoIndex <= MAX_PWM_SERVOS )\n    {\n        // validate selected pin\n        bool pin_allowed = false;\n        for( int i = 0; i < MAX_PWM_SERVOS; i++)\n        {\n            // check if pin already in use\n            if ( _servos[i] == pin)\n                return INVALID_SERVO;\n\n            // check if selected pin has a pwm unit on the used XMC board\n            if ( _allowed[i] == pin)\n                pin_allowed = true;\n        }\n        // return if pin is not found in allowed pin list\n        if ( !pin_allowed )\n            return INVALID_SERVO;\n\n        // Set min/max values according the input and check for absolute limits\n        if (min < MIN_PULSE_CHECK)\n        {\n            this->_minAngle = constrain(min,MIN_ANGLE,MAX_ANGLE);\n            this->_minPW = MIN_PULSE_WIDTH;\n        } else {\n            this->_minAngle = MIN_ANGLE;  //TODO has to calculated\n            this->_minPW = constrain(min,MIN_PULSE_WIDTH,MAX_PULSE_WIDTH);\n        }\n\n        if (max < MIN_PULSE_CHECK)\n        {\n            this->_maxAngle = constrain(max,MIN_ANGLE,MAX_ANGLE);\n            this->_maxPW = 2 * MAX_PULSE_WIDTH;\n        } else {\n            this->_maxAngle = MAX_ANGLE;  //TODO has to calculated\n            this->_maxPW = constrain(max,MIN_PULSE_WIDTH,MAX_PULSE_WIDTH);\n        }\n\n        this->_pin      = pin;\n        this->_isActive = true;\n\n        setAnalogWriteFrequency(this->_pin, REFRESH_FREQUENCY);\n        analogWriteResolution(ADC_RESOLUTION);\n\n    }\n\n    return this->servoIndex;\n}\n\n\nvoid Servo::detach()\n{\n    this->servoIndex = _ServoCount--;\n\n    this->_minAngle = MIN_ANGLE;\n    this->_maxAngle = MAX_ANGLE;\n    this->_minPW = MIN_PULSE_WIDTH;\n    this->_maxPW = MAX_PULSE_WIDTH;\n\n    this->_pin = 0;\n    this->_isActive = false;\n    this->_pwm = 0;\n    this->_deg = 0.0;\n}\n\nvoid Servo::write(int value)\n{\n    if (value < MIN_PULSE_CHECK)\n    {\n        // angle must be inside the boundaries\n        double angle = constrain(value, this->_minAngle, this->_maxAngle);\n        double dutyCycle = ( 0.5 + ( angle / MAX_ANGLE ) * 2.0 ) * DUTYCYCLE_STEPS;\n\n        this->_deg = angle;\n        this->_pwm = uint16_t(dutyCycle);\n\n        analogWrite(this->_pin, uint16_t(dutyCycle));\n        _delayUs(50);\n    } else {\n        writeMicroseconds(value);\n    }\n}\n\nvoid Servo::writeMicroseconds(int value)\n{\n    // value must be inside the boundaries\n    double pw = constrain(value,this->_minPW, this->_maxPW);\n    double dutyCycle = map(pw, MIN_PULSE_WIDTH,MAX_PULSE_WIDTH, 0.5 * DUTYCYCLE_STEPS, 2.5 * DUTYCYCLE_STEPS);\n\n    this->_deg = ( dutyCycle - DUTYCYCLE_STEPS * 0.5 ) * MAX_ANGLE / ( 2 * DUTYCYCLE_STEPS );\n    this->_pwm = uint16_t(dutyCycle);\n\n    analogWrite(this->_pin, uint16_t(dutyCycle));\n    _delayUs(50);\n}\n\n#endif\n"
  },
  {
    "path": "src/xmc/ServoTimers.h",
    "content": "/******************************************************************************\n * The MIT License\n *\n * Copyright (c) 2010, LeafLabs, LLC.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *****************************************************************************/\n\n/*\n * @copyright Copyright (c) 2019-2020 Infineon Technologies AG\n */\n#ifndef _SERVO_H_\n#define _SERVO_H_\n\n#include <Arduino.h>\n#include \"wiring_analog.h\"\n\n/*\n * Note on Arduino compatibility:\n *\n * In the Arduino implementation, PWM is done \"by hand\" in the sense\n * that timer channels are hijacked in groups and an ISR is set which\n * toggles Servo::attach()ed pins using digitalWrite().\n *\n * While this scheme allows any pin to drive a servo, it chews up\n * cycles and complicates the programmer's notion of when a particular\n * timer channel will be in use.\n *\n * This implementation only allows Servo instances to attach() to pins\n * that already have PWM unit associated with them, which drives the wave.\n *\n * While the Arduino implementation of attach() returns the affected channel,\n * this one returns the index number of the servo or an INVALID_SERVO = 255 in\n * case of an error.\n * The attach will check if a pin is already in use and if a pin has a PWM unit on\n * the selected XMC board, otherwise it returns an INVALID_SERVO.\n * This error handling is different than the original one from Arduino.\n *\n * Depending on the XMC type the number of possible PWM channels vary from 4 to 23\n * and may change with future version of the XMC series.\n */\n\n// Define the MAX_PWM_SERVOS number per XMC type and the allowed PWM pins on the selected XMC board\n#if defined(XMC1100_XMC2GO)\n#define MAX_PWM_SERVOS             4\n#define ALLOWED_PINS               {1, 2, 3, 8,}\n#elif defined(XMC1100_Boot_Kit)\n#define MAX_PWM_SERVOS             6\n#define ALLOWED_PINS               { 3,4,6,9,10,11 }\n#elif defined(XMC1300_Boot_Kit)\n#define MAX_PWM_SERVOS             4\n#define ALLOWED_PINS               { 26,31,32,33 }\n#elif defined(XMC1400_Arduino_Kit)\n#define MAX_PWM_SERVOS             6\n#define ALLOWED_PINS               { 3,4,6,9,10,11 }\n#elif defined(XMC4200_Platform2GO)\n#define MAX_PWM_SERVOS             7\n#define ALLOWED_PINS               { 3,5,6,9,22,23,24 }\n#elif defined(XMC4400_Platform2GO)\n#define MAX_PWM_SERVOS             15\n#define ALLOWED_PINS               { 3,5,6,9,10,14,25,26,27,28,29,30,45,48,67 }\n#elif defined(XMC4700_Relax_Kit)\n#define MAX_PWM_SERVOS             23\n#define ALLOWED_PINS               { 3,5,6,9,10,11,34,36,37,51,61,62,66,70,76,77,79,80,81,88,89,93,94 }\n#else\n#error \"Not a supported XMC Board\"\n#endif\n\n#define MIN_ANGLE               0                               // the minimal angle in degree\n#define MAX_ANGLE               180                             // the maximal angle in degree\n#define MIN_PULSE_WIDTH         544                             // the shortest pulse sent to a servo in microseconds\n#define MAX_PULSE_WIDTH         2400                            // the longest pulse sent to a servo in microseconds\n\n#define MIN_PULSE_CHECK         500                             // border with below = angle and above = pulse width\n#define REFRESH_FREQUENCY       50u                             // the refresh frequency on analog pins\n#define REFRESH_TIME            20.0                            // the PWM refresh frequency for the servo motor\n#define DUTYCYCLE_STEPS         65536.0 / REFRESH_TIME          // the number of duty cycle steps during one refresh period\n#define ADC_RESOLUTION          16                              // the resolution of the adc during analog write\n\n#define INVALID_SERVO           255                             // flag indicating an invalid servo index\n\n/** Class for interfacing with RC servomotors. */\nclass Servo\n{\npublic:\n    /**\n     * @brief Construct a new Servo instance.\n     *\n     * The new instance will not be attached to any pin, but only PWM capable pins will run.\n     * see pin list above.\n     */\n    Servo();\n\n    /**\n     * @brief Associate this instance with a servomotor whose input is\n     *        connected to pin.\n     *\n     * If this instance is already attached to a pin, it will be\n     * detached before being attached to the new pin.\n     * If the pin is not allowed for running PWM or the max number of\n     * PWM channels on the XMC board is reached it will return\n     * with an INVALID_SERVO, otherwise with the servoIndex number.\n     *\n     * @param pin Pin connected to the servo pulse wave input. This\n     *            pin must be capable of PWM output.\n     *\n     * @param min If this value is below MIN_PULSE_CHECK it will be associated\n     *            with an angle in degree. Otherwise it will be the minimum\n     *            pulse width.\n     *            min as an angle must be between MIN_ANGLE < angle < MAX_ANGLE\n     *            with default as MIN_ANGLE\n     *            min as a pulse width must be between MIN_PULSE_WIDTH < pwm < MAX_PULSE_WIDTH\n     *            with a default as MIN_PULSE_WIDTH\n     *\n     * @param max If this value is below MIN_PULSE_CHECK it will be associated\n     *            with an angle in degree. Otherwise it will be the maximum\n     *            pulse width.\n     *            max as an angle must be between MIN_ANGLE < angle < MAX_ANGLE\n     *            with default as MAX_ANGLE\n     *            max as a pulse width must be between MIN_PULSE_WIDTH < pwm < MAX_PULSE_WIDTH\n     *            with a default as MAX_PULSE_WIDTH\n     *\n     * @return servoIndex number or INVALID_SERVO = 255 in case of an error\n     */\n    uint8_t attach(uint8_t pin, uint16_t min = MIN_ANGLE, uint16_t max = MAX_ANGLE);\n\n\n    /**\n     * @brief Stop driving the servo pulse train.\n     *\n     * If not currently attached to a motor, this function has no effect.\n     *\n     * @return true if this call did anything, false otherwise.\n     */\n    void detach();\n\n    /**\n     * @brief Set the servomotor target angle by recalculating the duty cycle\n     *        for XMC PWM settings.\n     *\n     * @param value Target angle, in degrees. If the target angle is\n     *              outside the range specified at attach(), it\n     *              will be clamped to lie in that range.\n     *\n     * @see Servo::attach()\n     */\n    void write(int value);\n\n    /**\n     * @brief Set the pulse width, in microseconds by recalculating it for the\n     *        XMC PWM settings. It also calculates the angle from the pwm value.\n     *\n     * @param value Pulse width to send to the servomotor, in\n     *              microseconds. If outside of the range\n     *              specified at attach() time, it is clamped to\n     *              lie in that range.\n     *\n     * @see Servo::attach()\n     */\n    void writeMicroseconds(int value);\n\n    /**\n     * returns the current value in degree as an angle between 0 and 189 degrees\n     *\n     * @see Servo::attach()\n     */\n    int read() const { return uint16_t(this->_deg); }\n\n    /**\n     * returns the current pwm value in microseconds.\n     *\n     * @see Servo::attach()\n     */\n    int readMicroseconds() const { return uint16_t(this->_pwm); }\n\n    /**\n     * @brief Check if this instance is attached to a servo.\n     * @return true if this instance is attached to a servo, false otherwise.\n     * @see Servo::attachedPin()\n     */\n    bool attached() const { return this->_isActive; }\n\nprivate:\n    uint16_t _minPW;                        // the initial minPulseWidth, if not set than MIN_PULSE_WIDTH\n    uint16_t _maxPW;                        // the initial maxPulseWidth, if not set than MAX_PULSE_WIDTH\n    int16_t  _minAngle;                     // the initial minAngle, if not set than MIN_ANGLE\n    int16_t  _maxAngle;                     // the initial maxAngle, if not set than MAX_ANGLE\n    int16_t  _pin;                          // attached arduino pin number\n    double   _deg;                          // actual angle in degree\n    double   _pwm;                          // actual pwm signal in microseconds\n    uint8_t  _isActive;                     // true if this pin is active, otherwise false\n\n    uint8_t  servoIndex;                    // the actual number of Servos attached to this library\n\n\n};\n\n#endif /* _SERVO_H_ */\n"
  },
  {
    "path": "src/zephyr/Servo.cpp",
    "content": "#if defined(ARDUINO_ARCH_ZEPHYR)\n\n#include <zephyr/kernel.h>\n#include <zephyr/drivers/gpio.h>\n#include <zephyr/device.h>\n#include <zephyr/drivers/counter.h>\n\n#include <Arduino.h>\n#include <Servo.h>\n\n\ntypedef struct {\n    uint8_t pin;\n    uint32_t position_tick;\n    uint32_t timer_index;\n    uint32_t min;\n    uint32_t max;\n} servoTimer_t;\n\nclass ServoTimerHandler{\n\n  inline static uint32_t timer_servo;\n  inline static uint32_t servo_timing_period;\n  bool timer_is_started;\n\n  inline static servoTimer_t * servos[MAX_ZEPHYR_SERVOS] = {nullptr};\n  uint8_t servoCount;\n\n  public:\n    ServoTimerHandler(){\n      timer_is_started = false;\n      timer_servo = 0;\n      servoCount = 0;\n    }\n\n    int initTimer(){\n      if (!timer_is_started){\n        const struct device *const counter_dev = DEVICE_DT_GET(TIMER);\n        counter_start(counter_dev);\n        struct counter_top_cfg top_cfg;\n        top_cfg.ticks = counter_us_to_ticks(counter_dev, servo_timer_base_us_tick);\n        top_cfg.callback = this->servo_timer_update; \n        top_cfg.user_data = &top_cfg;\n        top_cfg.flags = 0;\n\n        int err = counter_set_top_value(counter_dev, &top_cfg);\n        if (err){\n          return 0;\n        }\n        else{\n          timer_is_started = true;\n          return 1;\n        }\n      }\n      return -1;\n    }\n\n    static void servo_timer_update(const struct device *counter_dev, void *user_data){\n      for (uint8_t i = 0; i < MAX_ZEPHYR_SERVOS; i++){\n        if (servos[i]!=nullptr){\n          if (timer_servo>servos[i]->position_tick){\n            digitalWrite(servos[i]->pin, LOW);\n          }\n          else{\n            digitalWrite(servos[i]->pin, HIGH);\n          }\n        }\n      }\n      if (timer_servo>servo_timer_end_tick){\n        timer_servo = 0;\n      }\n      timer_servo++;\n    }\n    \n    int addServo(servoTimer_t * s){\n      if (servoCount<MAX_ZEPHYR_SERVOS){\n        for (uint8_t i = 0; i<MAX_ZEPHYR_SERVOS; i++){\n          if (servos[i]!=nullptr && servos[i]->pin==s->pin){\n            return i;\n          }\n      }\n      for (uint8_t i = 0; i<MAX_ZEPHYR_SERVOS; i++){\n        if (servos[i]==nullptr){\n          servos[i]=s;\n          servoCount++;\n          return i;\n        }\n      }\n      }\n      else{\n        return -1;\n      }\n      return -2;\n    }\n\n    int removeServo(int index){\n      if (index<MAX_ZEPHYR_SERVOS){\n        delete servos[index];\n        servos[index]=nullptr;\n        servoCount--;\n        return index;\n      }\n      else{\n        return -1;\n      }\n    }\n\n    void writeMicroseconds(int index, int value){\n      if (servos[index]!=nullptr){\n        servos[index]->position_tick = value/servo_timer_base_us_tick;\n      }\n    }\n\n    uint32_t getMin(int index){\n      if (servos[index]!=nullptr){\n        return servos[index]->min;\n      }\n      return MIN_PULSE_WIDTH;\n    }\n\n    uint32_t getMax(int index){\n      if (servos[index]!=nullptr){\n        return servos[index]->max;\n      }\n      return MAX_PULSE_WIDTH;\n    }\n\n    uint32_t readMicroseconds(int index){\n      if (servos[index]!=nullptr){\n        return servos[index]->position_tick*servo_timer_base_us_tick;\n      }\n      return 0;\n    }\n};\n\nstatic ServoTimerHandler servo_handle;\n\n\nServo::Servo(){\n  servo_handle.initTimer();\n  servoIndex = 255;\n}\n\nuint8_t Servo::attach(int pin){\n  return this->attach(pin, MIN_PULSE_WIDTH , MAX_PULSE_WIDTH );\n}\n\nuint8_t Servo::attach(int pin, int min, int max){\n  pinMode(pin, OUTPUT);\n  servoTimer_t * tmp_servo = new servoTimer_t();\n  tmp_servo->pin = pin;\n  tmp_servo->min = min;\n  tmp_servo->max = max;\n  servoIndex = servo_handle.addServo(tmp_servo);\n  this->min = servo_handle.getMin(servoIndex)/4;\n  this->max = servo_handle.getMax(servoIndex)/4;\n  return 0;\n}\n\n\nvoid Servo::detach(){\n  servo_handle.removeServo(servoIndex);\n  servoIndex = 255;\n}\n\nvoid Servo::write(int value){\n  servo_handle.writeMicroseconds(servoIndex, map(value, 0, 180, servo_handle.getMin(servoIndex), servo_handle.getMax(servoIndex)));\n}\n\nvoid Servo::writeMicroseconds(int value){\n  servo_handle.writeMicroseconds(servoIndex, value);\n}\n\nint Servo::read(){\n  return map(servo_handle.readMicroseconds(servoIndex), servo_handle.getMin(servoIndex), servo_handle.getMax(servoIndex), 0, 180);\n}\n\nint Servo::readMicroseconds(){\n  return servo_handle.readMicroseconds(servoIndex);\n}\n\nbool Servo::attached(){\n  if (servoIndex==255){\n    return false;\n  }\n  else{\n    return true;\n  }\n}\n\n#endif"
  },
  {
    "path": "src/zephyr/ServoTimers.h",
    "content": "#define MAX_ZEPHYR_SERVOS 16\n\n#define TIMER DT_NODELABEL(counter_servo)\n\nconst uint32_t servo_timer_base_us_tick = 4; \nconst uint32_t servo_timer_end_tick = 20000/servo_timer_base_us_tick;\n"
  }
]