├── .codespellrc ├── .github ├── dependabot.yml └── workflows │ ├── check-arduino.yml │ ├── compile-examples.yml │ ├── report-size-deltas.yml │ ├── spell-check.yml │ └── sync-labels.yml ├── LICENSE.txt ├── README.adoc ├── docs ├── api.md └── readme.md ├── examples ├── Knob │ ├── Knob.ino │ ├── images │ │ ├── knob_BB.png │ │ └── knob_schem.png │ └── readme.md └── Sweep │ ├── Sweep.ino │ ├── images │ ├── sweep_bb.png │ └── sweep_schem.png │ └── readme.md ├── keywords.txt ├── library.properties └── src ├── Servo.h ├── avr ├── Servo.cpp └── ServoTimers.h ├── mbed ├── Servo.cpp └── ServoTimers.h ├── megaavr ├── Servo.cpp └── ServoTimers.h ├── nrf52 ├── Servo.cpp └── ServoTimers.h ├── renesas ├── Servo.cpp └── ServoTimers.h ├── sam ├── Servo.cpp └── ServoTimers.h ├── samd ├── Servo.cpp └── ServoTimers.h ├── stm32f4 ├── Servo.cpp └── ServoTimers.h └── xmc ├── Servo.cpp └── ServoTimers.h /.codespellrc: -------------------------------------------------------------------------------- 1 | # See: https://github.com/codespell-project/codespell#using-a-config-file 2 | [codespell] 3 | # In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here: 4 | ignore-words-list = , 5 | check-filenames = 6 | check-hidden = 7 | skip = ./.git 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # See: https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#about-the-dependabotyml-file 2 | version: 2 3 | 4 | updates: 5 | # Configure check for outdated GitHub Actions actions in workflows. 6 | # See: https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-dependabot 7 | - package-ecosystem: github-actions 8 | directory: / # Check the repository's workflows under /.github/workflows/ 9 | schedule: 10 | interval: daily 11 | labels: 12 | - "topic: infrastructure" 13 | -------------------------------------------------------------------------------- /.github/workflows/check-arduino.yml: -------------------------------------------------------------------------------- 1 | name: Check Arduino 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | pull_request: 7 | schedule: 8 | # Run every Tuesday at 8 AM UTC to catch breakage caused by new rules added to Arduino Lint. 9 | - cron: "0 8 * * TUE" 10 | workflow_dispatch: 11 | repository_dispatch: 12 | 13 | jobs: 14 | lint: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | 21 | - name: Arduino Lint 22 | uses: arduino/arduino-lint-action@v2 23 | with: 24 | compliance: specification 25 | library-manager: update 26 | # Always use this setting for official repositories. Remove for 3rd party projects. 27 | official: true 28 | project-type: library 29 | -------------------------------------------------------------------------------- /.github/workflows/compile-examples.yml: -------------------------------------------------------------------------------- 1 | name: Compile Examples 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | paths: 7 | - ".github/workflows/compile-examples.yml" 8 | - "examples/**" 9 | - "src/**" 10 | pull_request: 11 | paths: 12 | - ".github/workflows/compile-examples.yml" 13 | - "examples/**" 14 | - "src/**" 15 | schedule: 16 | # Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms). 17 | - cron: "0 8 * * TUE" 18 | workflow_dispatch: 19 | repository_dispatch: 20 | 21 | jobs: 22 | build: 23 | name: ${{ matrix.board.fqbn }} 24 | runs-on: ubuntu-latest 25 | 26 | env: 27 | SKETCHES_REPORTS_PATH: sketches-reports 28 | 29 | strategy: 30 | fail-fast: false 31 | 32 | matrix: 33 | board: 34 | - fqbn: arduino:avr:nano 35 | platforms: | 36 | - name: arduino:avr 37 | artifact-name-suffix: arduino-avr-nano 38 | - fqbn: arduino:avr:mega 39 | platforms: | 40 | - name: arduino:avr 41 | artifact-name-suffix: arduino-avr-mega 42 | - fqbn: arduino:avr:leonardo 43 | platforms: | 44 | - name: arduino:avr 45 | artifact-name-suffix: arduino-avr-leonardo 46 | - fqbn: arduino:megaavr:nona4809 47 | platforms: | 48 | - name: arduino:megaavr 49 | artifact-name-suffix: arduino-megaavr-nona4809 50 | - fqbn: arduino:sam:arduino_due_x_dbg 51 | platforms: | 52 | - name: arduino:sam 53 | artifact-name-suffix: arduino-sam-arduino_due_x_dbg 54 | - fqbn: arduino:samd:mkrzero 55 | platforms: | 56 | - name: arduino:samd 57 | artifact-name-suffix: arduino-samd-mkrzero 58 | - fqbn: arduino:mbed_portenta:envie_m7:target_core=cm4 59 | platforms: | 60 | - name: arduino:mbed_portenta 61 | artifact-name-suffix: arduino-mbed_portenta-envie_m7-target_core-cm4 62 | - fqbn: arduino:mbed_portenta:envie_m7 63 | platforms: | 64 | - name: arduino:mbed_portenta 65 | artifact-name-suffix: arduino-mbed_portenta-envie_m7 66 | - fqbn: arduino:mbed_nano:nano33ble 67 | platforms: | 68 | - name: arduino:mbed_nano 69 | artifact-name-suffix: arduino-mbed_nano-nano33ble 70 | - fqbn: arduino:mbed_nano:nanorp2040connect 71 | platforms: | 72 | - name: arduino:mbed_nano 73 | artifact-name-suffix: arduino-mbed_nano-nanorp2040connect 74 | 75 | steps: 76 | - name: Checkout repository 77 | uses: actions/checkout@v4 78 | 79 | - name: Compile examples 80 | uses: arduino/compile-sketches@v1 81 | with: 82 | github-token: ${{ secrets.GITHUB_TOKEN }} 83 | fqbn: ${{ matrix.board.fqbn }} 84 | platforms: ${{ matrix.board.platforms }} 85 | libraries: | 86 | # Install the library from the local path. 87 | - source-path: ./ 88 | # Additional library dependencies can be listed here. 89 | # See: https://github.com/arduino/compile-sketches#libraries 90 | sketch-paths: | 91 | - examples 92 | enable-deltas-report: true 93 | sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }} 94 | 95 | - name: Save sketches report as workflow artifact 96 | uses: actions/upload-artifact@v4 97 | with: 98 | if-no-files-found: error 99 | path: ${{ env.SKETCHES_REPORTS_PATH }} 100 | name: sketches-report-${{ matrix.board.artifact-name-suffix }} 101 | -------------------------------------------------------------------------------- /.github/workflows/report-size-deltas.yml: -------------------------------------------------------------------------------- 1 | name: Report Size Deltas 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | paths: 7 | - ".github/workflows/report-size-deltas.yml" 8 | schedule: 9 | # Run at the minimum interval allowed by GitHub Actions. 10 | # Note: GitHub Actions periodically has outages which result in workflow failures. 11 | # In this event, the workflows will start passing again once the service recovers. 12 | - cron: "*/5 * * * *" 13 | workflow_dispatch: 14 | repository_dispatch: 15 | 16 | jobs: 17 | report: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Comment size deltas reports to PRs 21 | uses: arduino/report-size-deltas@v1 22 | with: 23 | # Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow 24 | sketches-reports-source: ^sketches-report-.+ 25 | -------------------------------------------------------------------------------- /.github/workflows/spell-check.yml: -------------------------------------------------------------------------------- 1 | name: Spell Check 2 | 3 | # See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows 4 | on: 5 | push: 6 | pull_request: 7 | schedule: 8 | # Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates. 9 | - cron: "0 8 * * TUE" 10 | workflow_dispatch: 11 | repository_dispatch: 12 | 13 | jobs: 14 | spellcheck: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | 21 | - name: Spell check 22 | uses: codespell-project/actions-codespell@master 23 | -------------------------------------------------------------------------------- /.github/workflows/sync-labels.yml: -------------------------------------------------------------------------------- 1 | # Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md 2 | name: Sync Labels 3 | 4 | # See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows 5 | on: 6 | push: 7 | paths: 8 | - ".github/workflows/sync-labels.ya?ml" 9 | - ".github/label-configuration-files/*.ya?ml" 10 | pull_request: 11 | paths: 12 | - ".github/workflows/sync-labels.ya?ml" 13 | - ".github/label-configuration-files/*.ya?ml" 14 | schedule: 15 | # Run daily at 8 AM UTC to sync with changes to shared label configurations. 16 | - cron: "0 8 * * *" 17 | workflow_dispatch: 18 | repository_dispatch: 19 | 20 | env: 21 | CONFIGURATIONS_FOLDER: .github/label-configuration-files 22 | CONFIGURATIONS_ARTIFACT: label-configuration-files 23 | 24 | jobs: 25 | check: 26 | runs-on: ubuntu-latest 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v4 31 | 32 | - name: Download JSON schema for labels configuration file 33 | id: download-schema 34 | uses: carlosperate/download-file-action@v2 35 | with: 36 | file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json 37 | location: ${{ runner.temp }}/label-configuration-schema 38 | 39 | - name: Install JSON schema validator 40 | run: | 41 | sudo npm install \ 42 | --global \ 43 | ajv-cli \ 44 | ajv-formats 45 | 46 | - name: Validate local labels configuration 47 | run: | 48 | # See: https://github.com/ajv-validator/ajv-cli#readme 49 | ajv validate \ 50 | --all-errors \ 51 | -c ajv-formats \ 52 | -s "${{ steps.download-schema.outputs.file-path }}" \ 53 | -d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}" 54 | 55 | download: 56 | needs: check 57 | runs-on: ubuntu-latest 58 | 59 | strategy: 60 | matrix: 61 | filename: 62 | # Filenames of the shared configurations to apply to the repository in addition to the local configuration. 63 | # https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels 64 | - universal.yml 65 | 66 | steps: 67 | - name: Download 68 | uses: carlosperate/download-file-action@v2 69 | with: 70 | file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }} 71 | 72 | - name: Pass configuration files to next job via workflow artifact 73 | uses: actions/upload-artifact@v4 74 | with: 75 | path: | 76 | *.yaml 77 | *.yml 78 | if-no-files-found: error 79 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 80 | 81 | sync: 82 | needs: download 83 | runs-on: ubuntu-latest 84 | 85 | steps: 86 | - name: Set environment variables 87 | run: | 88 | # See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable 89 | echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV" 90 | 91 | - name: Determine whether to dry run 92 | id: dry-run 93 | if: > 94 | github.event_name == 'pull_request' || 95 | ( 96 | ( 97 | github.event_name == 'push' || 98 | github.event_name == 'workflow_dispatch' 99 | ) && 100 | github.ref != format('refs/heads/{0}', github.event.repository.default_branch) 101 | ) 102 | run: | 103 | # Use of this flag in the github-label-sync command will cause it to only check the validity of the 104 | # configuration. 105 | echo "::set-output name=flag::--dry-run" 106 | 107 | - name: Checkout repository 108 | uses: actions/checkout@v4 109 | 110 | - name: Download configuration files artifact 111 | uses: actions/download-artifact@v4 112 | with: 113 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 114 | path: ${{ env.CONFIGURATIONS_FOLDER }} 115 | 116 | - name: Remove unneeded artifact 117 | uses: geekyeggo/delete-artifact@v5 118 | with: 119 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 120 | 121 | - name: Merge label configuration files 122 | run: | 123 | # Merge all configuration files 124 | shopt -s extglob 125 | cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}" 126 | 127 | - name: Install github-label-sync 128 | run: sudo npm install --global github-label-sync 129 | 130 | - name: Sync labels 131 | env: 132 | GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }} 133 | run: | 134 | # See: https://github.com/Financial-Times/github-label-sync 135 | github-label-sync \ 136 | --labels "${{ env.MERGED_CONFIGURATION_PATH }}" \ 137 | ${{ steps.dry-run.outputs.flag }} \ 138 | ${{ github.repository }} 139 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | :repository-owner: arduino-libraries 2 | :repository-name: Servo 3 | 4 | = {repository-name} Library for Arduino = 5 | 6 | image: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"] 7 | image: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"] 8 | image: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"] 9 | 10 | This library allows an Arduino board to control RC (hobby) servo motors. 11 | 12 | For more information about this library please visit us at 13 | https://www.arduino.cc/reference/en/libraries/servo/ 14 | -------------------------------------------------------------------------------- /docs/api.md: -------------------------------------------------------------------------------- 1 | # Servo library 2 | 3 | ## Methods 4 | 5 | ### `attach()` 6 | 7 | Attach 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. 8 | 9 | #### Syntax 10 | 11 | ``` 12 | servo.attach(pin) 13 | servo.attach(pin, min, max) 14 | ``` 15 | 16 | #### Parameters 17 | 18 | * _servo_: a variable of type `Servo` 19 | * _pin_: the number of the pin that the servo is attached to 20 | * _min_ (optional): the pulse width, in microseconds, corresponding to the minimum (0 degree) angle on the servo (defaults to 544) 21 | * _max_ (optional): the pulse width, in microseconds, corresponding to the maximum (180 degree) angle on the servo (defaults to 2400) 22 | 23 | #### Example 24 | 25 | ``` 26 | #include 27 | 28 | Servo myservo; 29 | 30 | void setup() 31 | { 32 | myservo.attach(9); 33 | } 34 | 35 | void loop() {} 36 | ``` 37 | 38 | #### See also 39 | 40 | * [attached()](#attached) 41 | * [detach()](#detach) 42 | 43 | ### `write()` 44 | 45 | Writes 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). 46 | 47 | #### Syntax 48 | 49 | ``` 50 | servo.write(angle) 51 | ``` 52 | 53 | #### Parameters 54 | 55 | * _servo_: a variable of type Servo 56 | * _angle_: the value to write to the servo, from 0 to 180 57 | 58 | #### Example 59 | 60 | ```` 61 | #include 62 | 63 | Servo myservo; 64 | 65 | void setup() 66 | { 67 | myservo.attach(9); 68 | myservo.write(90); // set servo to mid-point 69 | } 70 | 71 | void loop() {} 72 | ```` 73 | #### See also 74 | 75 | * [attach()](#attach) 76 | * [read()](#read) 77 | 78 | ### `writeMicroseconds()` 79 | 80 | Writes 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. 81 | 82 | Note 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. 83 | 84 | Continuous-rotation servos will respond to the writeMicrosecond function in an manner analogous to the write function. 85 | 86 | #### Syntax 87 | 88 | ```` 89 | servo.writeMicroseconds(us) 90 | ```` 91 | 92 | #### Parameters 93 | 94 | * _servo_: a variable of type Servo 95 | * _us_: the value of the parameter in microseconds (int) 96 | 97 | #### Example 98 | 99 | ```` 100 | #include 101 | 102 | Servo myservo; 103 | 104 | void setup() 105 | { 106 | myservo.attach(9); 107 | myservo.writeMicroseconds(1500); // set servo to mid-point 108 | } 109 | 110 | void loop() {} 111 | ```` 112 | 113 | #### See also 114 | 115 | * [attach()](#attach) 116 | * [read()](#read) 117 | 118 | 119 | ### `read()` 120 | 121 | Read the current setpoint of the servo (the angle passed to the last call to [write()](#write)). 122 | 123 | Note 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. 124 | 125 | #### Syntax 126 | 127 | ```` 128 | servo.read() 129 | ```` 130 | 131 | #### Parameters 132 | 133 | * _servo_: a variable of type `Servo` 134 | 135 | #### Returns 136 | 137 | The setpoint of the servo, as an angle from 0 to 180 degrees. 138 | 139 | #### See also 140 | 141 | * [write()](#write) 142 | 143 | ### `attached()` 144 | 145 | Check whether the Servo variable is attached to a pin. 146 | 147 | #### Syntax 148 | 149 | ``` 150 | servo.attached() 151 | ``` 152 | 153 | #### Parameters 154 | 155 | * _servo_: a variable of type `Servo` 156 | 157 | #### Returns 158 | 159 | `true` if the servo is attached to pin; `false` otherwise. 160 | 161 | #### See also 162 | 163 | * [attach()](#attach) 164 | * [detach()](#detach) 165 | 166 | ### `detach()` 167 | 168 | Detach 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/). 169 | 170 | #### Syntax 171 | 172 | ``` 173 | servo.detach() 174 | ``` 175 | 176 | #### Parameters 177 | 178 | * _servo_: a variable of type `Servo` 179 | 180 | #### See also 181 | 182 | * [attach()](#attach) 183 | * [attached()](#attached) 184 | -------------------------------------------------------------------------------- /docs/readme.md: -------------------------------------------------------------------------------- 1 | # Servo library 2 | 3 | 4 | This 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. 5 | 6 | The 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. 7 | 8 | To use this library: 9 | 10 | ``` 11 | #include 12 | ``` 13 | 14 | ## Circuit 15 | 16 | Servo 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. 17 | 18 | ## Examples 19 | 20 | * [Knob](https://www.arduino.cc/en/Tutorial/Knob): control the shaft of a servo motor by turning a potentiometer 21 | * [Sweep](https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep): sweeps the shaft of a servo motor back and forth 22 | -------------------------------------------------------------------------------- /examples/Knob/Knob.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Controlling a servo position using a potentiometer (variable resistor) 3 | by Michal Rinott 4 | 5 | modified on 8 Nov 2013 6 | by Scott Fitzgerald 7 | http://www.arduino.cc/en/Tutorial/Knob 8 | */ 9 | 10 | #include 11 | 12 | Servo myservo; // create Servo object to control a servo 13 | 14 | int potpin = A0; // analog pin used to connect the potentiometer 15 | int val; // variable to read the value from the analog pin 16 | 17 | void setup() { 18 | myservo.attach(9); // attaches the servo on pin 9 to the Servo object 19 | } 20 | 21 | void loop() { 22 | val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) 23 | val = map(val, 0, 1023, 0, 180); // scale it for use with the servo (value between 0 and 180) 24 | myservo.write(val); // sets the servo position according to the scaled value 25 | delay(15); // waits for the servo to get there 26 | } 27 | -------------------------------------------------------------------------------- /examples/Knob/images/knob_BB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/Servo/aeef55f192c502dbd8e2e7f7710eb307663bb4ee/examples/Knob/images/knob_BB.png -------------------------------------------------------------------------------- /examples/Knob/images/knob_schem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/Servo/aeef55f192c502dbd8e2e7f7710eb307663bb4ee/examples/Knob/images/knob_schem.png -------------------------------------------------------------------------------- /examples/Knob/readme.md: -------------------------------------------------------------------------------- 1 | # Knob 2 | 3 | Control the position of an RC (hobby) [servo motor](http://en.wikipedia.org/wiki/Servo_motor#RC_servos) with your Arduino and a potentiometer. 4 | 5 | This example makes use of the Arduino `Servo` library. 6 | 7 | ## Hardware Required 8 | 9 | * an Arduino board 10 | * Servo motor 11 | * 10k ohm potentiometer 12 | * hook-up wires 13 | 14 | ## Circuit 15 | 16 | Servo 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. 17 | 18 | The 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. 19 | 20 | ![](images/knob_BB.png) 21 | 22 | (Images developed using Fritzing. For more circuit examples, see the [Fritzing project page](http://fritzing.org/projects/)) 23 | 24 | ## Schematic 25 | 26 | ![](images/knob_schem.png) 27 | 28 | ## See also 29 | 30 | * [attach()](/docs/api.md#attach) 31 | * [write()](/docs/api.md#write) 32 | * [map()](https://www.arduino.cc/en/Reference/Map) 33 | * [analogRead()](https://www.arduino.cc/en/Reference/AnalogRead) 34 | * [Servo library reference](/docs/readme.md) 35 | * [Sweep](../Sweep) - Sweep the shaft of a servo motor back and forth 36 | -------------------------------------------------------------------------------- /examples/Sweep/Sweep.ino: -------------------------------------------------------------------------------- 1 | /* Sweep 2 | by BARRAGAN 3 | This example code is in the public domain. 4 | 5 | modified 8 Nov 2013 6 | by Scott Fitzgerald 7 | https://www.arduino.cc/en/Tutorial/LibraryExamples/Sweep 8 | */ 9 | 10 | #include 11 | 12 | Servo myservo; // create Servo object to control a servo 13 | // twelve Servo objects can be created on most boards 14 | 15 | int pos = 0; // variable to store the servo position 16 | 17 | void setup() { 18 | myservo.attach(9); // attaches the servo on pin 9 to the Servo object 19 | } 20 | 21 | void loop() { 22 | for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees 23 | // in steps of 1 degree 24 | myservo.write(pos); // tell servo to go to position in variable 'pos' 25 | delay(15); // waits 15 ms for the servo to reach the position 26 | } 27 | for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees 28 | myservo.write(pos); // tell servo to go to position in variable 'pos' 29 | delay(15); // waits 15 ms for the servo to reach the position 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/Sweep/images/sweep_bb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/Servo/aeef55f192c502dbd8e2e7f7710eb307663bb4ee/examples/Sweep/images/sweep_bb.png -------------------------------------------------------------------------------- /examples/Sweep/images/sweep_schem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/Servo/aeef55f192c502dbd8e2e7f7710eb307663bb4ee/examples/Sweep/images/sweep_schem.png -------------------------------------------------------------------------------- /examples/Sweep/readme.md: -------------------------------------------------------------------------------- 1 | # Sweep 2 | 3 | Sweeps the shaft of an RC [servo motor](http://en.wikipedia.org/wiki/Servo_motor#RC_servos) back and forth across 180 degrees. 4 | 5 | ## Hardware Required 6 | 7 | * Arduino Board 8 | * Servo Motor 9 | * Hook-up wires 10 | 11 | ## Circuit 12 | 13 | Servo 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. 14 | 15 | ![](images/sweep_bb.png) 16 | 17 | (Images developed using Fritzing. For more circuit examples, see the [Fritzing project page](http://fritzing.org/projects/)) 18 | 19 | ## Schematic 20 | 21 | ![](images/sweep_schem.png) 22 | 23 | ## See also 24 | 25 | * [attach()](/docs/api.md#attach) 26 | * [write()](/docs/api.md#write) 27 | * [map()](https://www.arduino.cc/en/Reference/Map) 28 | * [Servo library reference](/docs/readme.md) 29 | * [Knob](../Knob) - Control the position of a servo with a potentiometer 30 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map Servo 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | 9 | Servo KEYWORD1 Servo 10 | 11 | ####################################### 12 | # Methods and Functions (KEYWORD2) 13 | ####################################### 14 | attach KEYWORD2 15 | detach KEYWORD2 16 | write KEYWORD2 17 | read KEYWORD2 18 | attached KEYWORD2 19 | writeMicroseconds KEYWORD2 20 | readMicroseconds KEYWORD2 21 | 22 | ####################################### 23 | # Constants (LITERAL1) 24 | ####################################### 25 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=Servo 2 | version=1.2.2 3 | author=Michael Margolis, Arduino 4 | maintainer=Arduino 5 | sentence=Allows Arduino boards to control a variety of servo motors. 6 | paragraph=This library can control a great number of servos.
It makes careful use of timers: the library can control 12 servos using only 1 timer.
On the Arduino Due you can control up to 60 servos. 7 | category=Device Control 8 | url=https://www.arduino.cc/reference/en/libraries/servo/ 9 | architectures=avr,megaavr,sam,samd,nrf52,stm32f4,mbed,mbed_nano,mbed_portenta,mbed_rp2040,renesas,renesas_portenta,renesas_uno 10 | -------------------------------------------------------------------------------- /src/Servo.h: -------------------------------------------------------------------------------- 1 | /* 2 | Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers - Version 2 3 | Copyright (c) 2009 Michael Margolis. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | /* 21 | A servo is activated by creating an instance of the Servo class passing 22 | the desired pin to the attach() method. 23 | The servos are pulsed in the background using the value most recently 24 | written using the write() method. 25 | 26 | Note that analogWrite of PWM on pins associated with the timer are 27 | disabled when the first servo is attached. 28 | Timers are seized as needed in groups of 12 servos - 24 servos use two 29 | timers, 48 servos will use four. 30 | The sequence used to seize timers is defined in timers.h 31 | 32 | The methods are: 33 | 34 | Servo - Class for manipulating servo motors connected to Arduino pins. 35 | 36 | attach(pin ) - Attaches a servo motor to an I/O pin. 37 | attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds 38 | default min is 544, max is 2400 39 | 40 | write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) 41 | writeMicroseconds() - Sets the servo pulse width in microseconds 42 | read() - Gets the last written servo pulse width as an angle between 0 and 180. 43 | readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) 44 | attached() - Returns true if there is a servo attached. 45 | detach() - Stops an attached servos from pulsing its I/O pin. 46 | */ 47 | 48 | #ifndef Servo_h 49 | #define Servo_h 50 | 51 | #include 52 | 53 | /* 54 | * Defines for 16 bit timers used with Servo library 55 | * 56 | * If _useTimerX is defined then TimerX is a 16 bit timer on the current board 57 | * timer16_Sequence_t enumerates the sequence that the timers should be allocated 58 | * _Nbr_16timers indicates how many 16 bit timers are available. 59 | */ 60 | 61 | // Architecture specific include 62 | #if defined(ARDUINO_ARCH_AVR) 63 | #include "avr/ServoTimers.h" 64 | #elif defined(ARDUINO_ARCH_SAM) 65 | #include "sam/ServoTimers.h" 66 | #elif defined(ARDUINO_ARCH_SAMD) 67 | #include "samd/ServoTimers.h" 68 | #elif defined(ARDUINO_ARCH_STM32F4) 69 | #include "stm32f4/ServoTimers.h" 70 | #elif defined(ARDUINO_ARCH_NRF52) 71 | #include "nrf52/ServoTimers.h" 72 | #elif defined(ARDUINO_ARCH_MEGAAVR) 73 | #include "megaavr/ServoTimers.h" 74 | #elif defined(ARDUINO_ARCH_MBED) 75 | #include "mbed/ServoTimers.h" 76 | #elif defined(ARDUINO_ARCH_RENESAS) 77 | #include "renesas/ServoTimers.h" 78 | #elif defined(ARDUINO_ARCH_XMC) 79 | #include "xmc/ServoTimers.h" 80 | #else 81 | #error "This library only supports boards with an AVR, SAM, SAMD, NRF52, STM32F4, Renesas or XMC processor." 82 | #endif 83 | 84 | #define Servo_VERSION 2 // software version of this library 85 | 86 | #define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo 87 | #define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo 88 | #define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached 89 | #define REFRESH_INTERVAL 20000 // minimum time to refresh servos in microseconds 90 | 91 | #define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer 92 | #define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER) 93 | 94 | #define INVALID_SERVO 255 // flag indicating an invalid servo index 95 | 96 | #if !defined(ARDUINO_ARCH_STM32F4) && !defined(ARDUINO_ARCH_XMC) 97 | 98 | typedef struct { 99 | uint8_t nbr :6 ; // a pin number from 0 to 63 100 | uint8_t isActive :1 ; // true if this channel is enabled, pin not pulsed if false 101 | } ServoPin_t ; 102 | 103 | typedef struct { 104 | ServoPin_t Pin; 105 | volatile unsigned int ticks; 106 | } servo_t; 107 | 108 | class Servo 109 | { 110 | public: 111 | Servo(); 112 | uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or INVALID_SERVO if failure 113 | uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. 114 | void detach(); 115 | void write(int value); // if value is < 200 it's treated as an angle, otherwise as pulse width in microseconds 116 | void writeMicroseconds(int value); // Write pulse width in microseconds 117 | int read(); // returns current pulse width as an angle between 0 and 180 degrees 118 | int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release) 119 | bool attached(); // return true if this servo is attached, otherwise false 120 | private: 121 | uint8_t servoIndex; // index into the channel data for this servo 122 | int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH 123 | int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH 124 | }; 125 | 126 | #endif 127 | #endif 128 | -------------------------------------------------------------------------------- /src/avr/Servo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers - Version 2 3 | Copyright (c) 2009 Michael Margolis. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #if defined(ARDUINO_ARCH_AVR) 21 | 22 | #include 23 | #include 24 | 25 | #include "Servo.h" 26 | 27 | #define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8) // converts microseconds to ticks (assumes prescaler of 8) // 12 Aug 2009 28 | #define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds 29 | 30 | 31 | #define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009 32 | 33 | //#define NBR_TIMERS (MAX_SERVOS / SERVOS_PER_TIMER) 34 | 35 | static servo_t servos[MAX_SERVOS]; // static array of servo structures 36 | static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval) 37 | 38 | uint8_t ServoCount = 0; // the total number of attached servos 39 | 40 | 41 | // convenience macros 42 | #define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo 43 | #define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer 44 | #define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel 45 | #define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel 46 | 47 | #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo 48 | #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo 49 | 50 | /************ static functions common to all instances ***********************/ 51 | 52 | static inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t *TCNTn, volatile uint16_t* OCRnA) 53 | { 54 | if( Channel[timer] < 0 ) 55 | *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer 56 | else{ 57 | if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true ) 58 | digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,LOW); // pulse this channel low if activated 59 | } 60 | 61 | Channel[timer]++; // increment to the next channel 62 | if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) { 63 | *OCRnA = *TCNTn + SERVO(timer,Channel[timer]).ticks; 64 | if(SERVO(timer,Channel[timer]).Pin.isActive == true) // check if activated 65 | digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // it's an active channel so pulse it high 66 | } 67 | else { 68 | // finished all channels so wait for the refresh period to expire before starting over 69 | if( ((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL) ) // allow a few ticks to ensure the next OCR1A not missed 70 | *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL); 71 | else 72 | *OCRnA = *TCNTn + 4; // at least REFRESH_INTERVAL has elapsed 73 | Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel 74 | } 75 | } 76 | 77 | #ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform 78 | // Interrupt handlers for Arduino 79 | #if defined(_useTimer1) 80 | SIGNAL (TIMER1_COMPA_vect) 81 | { 82 | handle_interrupts(_timer1, &TCNT1, &OCR1A); 83 | } 84 | #endif 85 | 86 | #if defined(_useTimer3) 87 | SIGNAL (TIMER3_COMPA_vect) 88 | { 89 | handle_interrupts(_timer3, &TCNT3, &OCR3A); 90 | } 91 | #endif 92 | 93 | #if defined(_useTimer4) 94 | SIGNAL (TIMER4_COMPA_vect) 95 | { 96 | handle_interrupts(_timer4, &TCNT4, &OCR4A); 97 | } 98 | #endif 99 | 100 | #if defined(_useTimer5) 101 | SIGNAL (TIMER5_COMPA_vect) 102 | { 103 | handle_interrupts(_timer5, &TCNT5, &OCR5A); 104 | } 105 | #endif 106 | 107 | #elif defined WIRING 108 | // Interrupt handlers for Wiring 109 | #if defined(_useTimer1) 110 | void Timer1Service() 111 | { 112 | handle_interrupts(_timer1, &TCNT1, &OCR1A); 113 | } 114 | #endif 115 | #if defined(_useTimer3) 116 | void Timer3Service() 117 | { 118 | handle_interrupts(_timer3, &TCNT3, &OCR3A); 119 | } 120 | #endif 121 | #endif 122 | 123 | 124 | static void initISR(timer16_Sequence_t timer) 125 | { 126 | #if defined (_useTimer1) 127 | if(timer == _timer1) { 128 | TCCR1A = 0; // normal counting mode 129 | TCCR1B = _BV(CS11); // set prescaler of 8 130 | TCNT1 = 0; // clear the timer count 131 | #if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__) 132 | TIFR |= _BV(OCF1A); // clear any pending interrupts 133 | TIMSK |= _BV(OCIE1A) ; // enable the output compare interrupt 134 | #else 135 | // here if not ATmega8 or ATmega128 136 | TIFR1 |= _BV(OCF1A); // clear any pending interrupts 137 | TIMSK1 |= _BV(OCIE1A) ; // enable the output compare interrupt 138 | #endif 139 | #if defined(WIRING) 140 | timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service); 141 | #endif 142 | } 143 | #endif 144 | 145 | #if defined (_useTimer3) 146 | if(timer == _timer3) { 147 | TCCR3A = 0; // normal counting mode 148 | TCCR3B = _BV(CS31); // set prescaler of 8 149 | TCNT3 = 0; // clear the timer count 150 | #if defined(__AVR_ATmega128__) 151 | TIFR |= _BV(OCF3A); // clear any pending interrupts 152 | ETIMSK |= _BV(OCIE3A); // enable the output compare interrupt 153 | #else 154 | TIFR3 = _BV(OCF3A); // clear any pending interrupts 155 | TIMSK3 = _BV(OCIE3A) ; // enable the output compare interrupt 156 | #endif 157 | #if defined(WIRING) 158 | timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service); // for Wiring platform only 159 | #endif 160 | } 161 | #endif 162 | 163 | #if defined (_useTimer4) 164 | if(timer == _timer4) { 165 | TCCR4A = 0; // normal counting mode 166 | TCCR4B = _BV(CS41); // set prescaler of 8 167 | TCNT4 = 0; // clear the timer count 168 | TIFR4 = _BV(OCF4A); // clear any pending interrupts 169 | TIMSK4 = _BV(OCIE4A) ; // enable the output compare interrupt 170 | } 171 | #endif 172 | 173 | #if defined (_useTimer5) 174 | if(timer == _timer5) { 175 | TCCR5A = 0; // normal counting mode 176 | TCCR5B = _BV(CS51); // set prescaler of 8 177 | TCNT5 = 0; // clear the timer count 178 | TIFR5 = _BV(OCF5A); // clear any pending interrupts 179 | TIMSK5 = _BV(OCIE5A) ; // enable the output compare interrupt 180 | } 181 | #endif 182 | } 183 | 184 | static void finISR(timer16_Sequence_t timer) 185 | { 186 | //disable use of the given timer 187 | #if defined WIRING // Wiring 188 | if(timer == _timer1) { 189 | #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) 190 | TIMSK1 &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt 191 | #else 192 | TIMSK &= ~_BV(OCIE1A) ; // disable timer 1 output compare interrupt 193 | #endif 194 | timerDetach(TIMER1OUTCOMPAREA_INT); 195 | } 196 | else if(timer == _timer3) { 197 | #if defined(__AVR_ATmega1281__)||defined(__AVR_ATmega2561__) 198 | TIMSK3 &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt 199 | #else 200 | ETIMSK &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt 201 | #endif 202 | timerDetach(TIMER3OUTCOMPAREA_INT); 203 | } 204 | #else 205 | //For Arduino - in future: call here to a currently undefined function to reset the timer 206 | (void) timer; // squash "unused parameter 'timer' [-Wunused-parameter]" warning 207 | #endif 208 | } 209 | 210 | static boolean isTimerActive(timer16_Sequence_t timer) 211 | { 212 | // returns true if any servo is active on this timer 213 | for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { 214 | if(SERVO(timer,channel).Pin.isActive == true) 215 | return true; 216 | } 217 | return false; 218 | } 219 | 220 | 221 | /****************** end of static functions ******************************/ 222 | 223 | Servo::Servo() 224 | { 225 | if( ServoCount < MAX_SERVOS) { 226 | this->servoIndex = ServoCount++; // assign a servo index to this instance 227 | servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009 228 | } 229 | else 230 | this->servoIndex = INVALID_SERVO ; // too many servos 231 | } 232 | 233 | uint8_t Servo::attach(int pin) 234 | { 235 | return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); 236 | } 237 | 238 | uint8_t Servo::attach(int pin, int min, int max) 239 | { 240 | if(this->servoIndex < MAX_SERVOS ) { 241 | pinMode( pin, OUTPUT) ; // set servo pin to output 242 | servos[this->servoIndex].Pin.nbr = pin; 243 | // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 244 | this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us 245 | this->max = (MAX_PULSE_WIDTH - max)/4; 246 | // initialize the timer if it has not already been initialized 247 | timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); 248 | if(isTimerActive(timer) == false) 249 | initISR(timer); 250 | servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive 251 | } 252 | return this->servoIndex ; 253 | } 254 | 255 | void Servo::detach() 256 | { 257 | servos[this->servoIndex].Pin.isActive = false; 258 | timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); 259 | if(isTimerActive(timer) == false) { 260 | finISR(timer); 261 | } 262 | } 263 | 264 | void Servo::write(int value) 265 | { 266 | if(value < MIN_PULSE_WIDTH) 267 | { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) 268 | if(value < 0) value = 0; 269 | if(value > 180) value = 180; 270 | value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); 271 | } 272 | this->writeMicroseconds(value); 273 | } 274 | 275 | void Servo::writeMicroseconds(int value) 276 | { 277 | // calculate and store the values for the given channel 278 | byte channel = this->servoIndex; 279 | if( (channel < MAX_SERVOS) ) // ensure channel is valid 280 | { 281 | if( value < SERVO_MIN() ) // ensure pulse width is valid 282 | value = SERVO_MIN(); 283 | else if( value > SERVO_MAX() ) 284 | value = SERVO_MAX(); 285 | 286 | value = value - TRIM_DURATION; 287 | value = usToTicks(value); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009 288 | 289 | uint8_t oldSREG = SREG; 290 | cli(); 291 | servos[channel].ticks = value; 292 | SREG = oldSREG; 293 | } 294 | } 295 | 296 | int Servo::read() // return the value as degrees 297 | { 298 | return map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); 299 | } 300 | 301 | int Servo::readMicroseconds() 302 | { 303 | unsigned int pulsewidth; 304 | if( this->servoIndex != INVALID_SERVO ) 305 | pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION ; // 12 aug 2009 306 | else 307 | pulsewidth = 0; 308 | 309 | return pulsewidth; 310 | } 311 | 312 | bool Servo::attached() 313 | { 314 | return servos[this->servoIndex].Pin.isActive ; 315 | } 316 | 317 | #endif // ARDUINO_ARCH_AVR 318 | -------------------------------------------------------------------------------- /src/avr/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers - Version 2 3 | Copyright (c) 2009 Michael Margolis. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | /* 21 | * Defines for 16 bit timers used with Servo library 22 | * 23 | * If _useTimerX is defined then TimerX is a 16 bit timer on the current board 24 | * timer16_Sequence_t enumerates the sequence that the timers should be allocated 25 | * _Nbr_16timers indicates how many 16 bit timers are available. 26 | */ 27 | 28 | /** 29 | * AVR Only definitions 30 | * -------------------- 31 | */ 32 | 33 | // Say which 16 bit timers can be used and in what order 34 | #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) 35 | #define _useTimer5 36 | #define _useTimer1 37 | #define _useTimer3 38 | #define _useTimer4 39 | typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t; 40 | 41 | #elif defined(__AVR_ATmega32U4__) 42 | #define _useTimer1 43 | typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; 44 | 45 | #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) 46 | #define _useTimer3 47 | #define _useTimer1 48 | typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; 49 | 50 | #elif defined(__AVR_ATmega128__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega2561__) 51 | #define _useTimer3 52 | #define _useTimer1 53 | typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t; 54 | 55 | #else // everything else 56 | #define _useTimer1 57 | typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; 58 | #endif 59 | -------------------------------------------------------------------------------- /src/mbed/Servo.cpp: -------------------------------------------------------------------------------- 1 | #if defined(ARDUINO_ARCH_MBED) 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #if defined __has_include 8 | # if __has_include ("pinDefinitions.h") 9 | # include "pinDefinitions.h" 10 | # endif 11 | #endif 12 | 13 | class ServoImpl { 14 | mbed::DigitalOut *pin; 15 | mbed::Timeout timeout; // calls a callback once when a timeout expires 16 | mbed::Ticker ticker; // calls a callback repeatedly with a timeout 17 | 18 | public: 19 | ServoImpl(PinName _pin) { 20 | pin = new mbed::DigitalOut(_pin); 21 | } 22 | 23 | ~ServoImpl() { 24 | ticker.detach(); 25 | timeout.detach(); 26 | delete pin; 27 | } 28 | 29 | void start(uint32_t duration_us) { 30 | duration = duration_us; 31 | ticker.attach(mbed::callback(this, &ServoImpl::call), 0.02f); 32 | } 33 | 34 | void call() { 35 | timeout.attach(mbed::callback(this, &ServoImpl::toggle), duration / 1e6); 36 | toggle(); 37 | } 38 | 39 | void toggle() { 40 | *pin = !*pin; 41 | } 42 | 43 | int32_t duration = -1; 44 | }; 45 | 46 | static ServoImpl* servos[MAX_SERVOS]; // static array of servo structures 47 | uint8_t ServoCount = 0; // the total number of attached servos 48 | 49 | #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min) // minimum value in us for this servo 50 | #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max) // maximum value in us for this servo 51 | 52 | #define TRIM_DURATION 15 //callback overhead (35 us) -> 15 us if toggle() is called after starting the timeout 53 | 54 | Servo::Servo() 55 | { 56 | if (ServoCount < MAX_SERVOS) { 57 | this->servoIndex = ServoCount++; 58 | } else { 59 | this->servoIndex = INVALID_SERVO; // too many servos 60 | } 61 | } 62 | 63 | uint8_t Servo::attach(int pin) 64 | { 65 | return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); 66 | } 67 | 68 | uint8_t Servo::attach(int pin, int min, int max) 69 | { 70 | pinMode(pin, OUTPUT); // set servo pin to output 71 | servos[this->servoIndex] = new ServoImpl(digitalPinToPinName(pin)); 72 | 73 | this->min = (MIN_PULSE_WIDTH - min); 74 | this->max = (MAX_PULSE_WIDTH - max); 75 | return this->servoIndex; 76 | } 77 | 78 | void Servo::detach() 79 | { 80 | delete servos[this->servoIndex]; 81 | servos[this->servoIndex] = NULL; 82 | } 83 | 84 | void Servo::write(int value) 85 | { 86 | // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) 87 | if (value < MIN_PULSE_WIDTH) 88 | { 89 | if (value < 0) 90 | value = 0; 91 | else if (value > 180) 92 | value = 180; 93 | 94 | value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); 95 | } 96 | writeMicroseconds(value); 97 | } 98 | 99 | void Servo::writeMicroseconds(int value) 100 | { 101 | if (!servos[this->servoIndex]) { 102 | return; 103 | } 104 | // calculate and store the values for the given channel 105 | byte channel = this->servoIndex; 106 | if( (channel < MAX_SERVOS) ) // ensure channel is valid 107 | { 108 | if (value < SERVO_MIN()) // ensure pulse width is valid 109 | value = SERVO_MIN(); 110 | else if (value > SERVO_MAX()) 111 | value = SERVO_MAX(); 112 | 113 | value = value - TRIM_DURATION; 114 | if (servos[this->servoIndex]->duration == -1) { 115 | servos[this->servoIndex]->start(value); 116 | } 117 | servos[this->servoIndex]->duration = value; 118 | } 119 | } 120 | 121 | int Servo::read() // return the value as degrees 122 | { 123 | return map(readMicroseconds(), SERVO_MIN(), SERVO_MAX(), 0, 180); 124 | } 125 | 126 | int Servo::readMicroseconds() 127 | { 128 | if (!servos[this->servoIndex]) { 129 | return 0; 130 | } 131 | return servos[this->servoIndex]->duration; 132 | } 133 | 134 | bool Servo::attached() 135 | { 136 | return servos[this->servoIndex] != NULL; 137 | } 138 | 139 | #endif 140 | -------------------------------------------------------------------------------- /src/mbed/ServoTimers.h: -------------------------------------------------------------------------------- 1 | #define _Nbr_16timers 32 2 | -------------------------------------------------------------------------------- /src/megaavr/Servo.cpp: -------------------------------------------------------------------------------- 1 | #if defined(ARDUINO_ARCH_MEGAAVR) 2 | 3 | #include 4 | #include 5 | 6 | #define usToTicks(_us) ((clockCyclesPerMicrosecond() / 16 * _us) / 4) // converts microseconds to ticks 7 | #define ticksToUs(_ticks) (((unsigned) _ticks * 16) / (clockCyclesPerMicrosecond() / 4)) // converts from ticks back to microseconds 8 | 9 | #define TRIM_DURATION 5 // compensation ticks to trim adjust for digitalWrite delays 10 | 11 | static servo_t servos[MAX_SERVOS]; // static array of servo structures 12 | 13 | uint8_t ServoCount = 0; // the total number of attached servos 14 | 15 | static volatile int8_t currentServoIndex[_Nbr_16timers]; // index for the servo being pulsed for each timer (or -1 if refresh interval) 16 | 17 | // convenience macros 18 | #define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo 19 | #define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer 20 | #define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel 21 | #define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel 22 | 23 | #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo 24 | #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo 25 | 26 | #undef REFRESH_INTERVAL 27 | #define REFRESH_INTERVAL 16000 28 | 29 | void ServoHandler(int timer) 30 | { 31 | if (currentServoIndex[timer] < 0) { 32 | // Write compare register 33 | _timer->CCMP = 0; 34 | } else { 35 | if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { 36 | digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, LOW); // pulse this channel low if activated 37 | } 38 | } 39 | 40 | // Select the next servo controlled by this timer 41 | currentServoIndex[timer]++; 42 | 43 | if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && currentServoIndex[timer] < SERVOS_PER_TIMER) { 44 | if (SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { // check if activated 45 | digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, HIGH); // it's an active channel so pulse it high 46 | } 47 | 48 | // Get the counter value 49 | uint16_t tcCounterValue = 0; //_timer->CCMP; 50 | _timer->CCMP = (uint16_t) (tcCounterValue + SERVO(timer, currentServoIndex[timer]).ticks); 51 | } 52 | else { 53 | // finished all channels so wait for the refresh period to expire before starting over 54 | 55 | // Get the counter value 56 | uint16_t tcCounterValue = _timer->CCMP; 57 | 58 | if (tcCounterValue + 4UL < usToTicks(REFRESH_INTERVAL)) { // allow a few ticks to ensure the next OCR1A not missed 59 | _timer->CCMP = (uint16_t) usToTicks(REFRESH_INTERVAL); 60 | } 61 | else { 62 | _timer->CCMP = (uint16_t) (tcCounterValue + 4UL); // at least REFRESH_INTERVAL has elapsed 63 | } 64 | 65 | currentServoIndex[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel 66 | } 67 | 68 | /* Clear flag */ 69 | _timer->INTFLAGS = TCB_CAPT_bm; 70 | } 71 | 72 | #if defined USE_TIMERB0 73 | ISR(TCB0_INT_vect) 74 | #elif defined USE_TIMERB1 75 | ISR(TCB1_INT_vect) 76 | #elif defined USE_TIMERB2 77 | ISR(TCB2_INT_vect) 78 | #endif 79 | { 80 | ServoHandler(0); 81 | } 82 | 83 | static void initISR(timer16_Sequence_t timer) 84 | { 85 | //TCA0.SINGLE.CTRLA = (TCA_SINGLE_CLKSEL_DIV16_gc) | (TCA_SINGLE_ENABLE_bm); 86 | 87 | _timer->CTRLA = TCB_CLKSEL_CLKTCA_gc; 88 | // Timer to Periodic interrupt mode 89 | // This write will also disable any active PWM outputs 90 | _timer->CTRLB = TCB_CNTMODE_INT_gc; 91 | // Enable interrupt 92 | _timer->INTCTRL = TCB_CAPTEI_bm; 93 | // Enable timer 94 | _timer->CTRLA |= TCB_ENABLE_bm; 95 | } 96 | 97 | static void finISR(timer16_Sequence_t timer) 98 | { 99 | // Disable interrupt 100 | _timer->INTCTRL = 0; 101 | } 102 | 103 | static boolean isTimerActive(timer16_Sequence_t timer) 104 | { 105 | // returns true if any servo is active on this timer 106 | for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { 107 | if(SERVO(timer,channel).Pin.isActive == true) 108 | return true; 109 | } 110 | return false; 111 | } 112 | 113 | /****************** end of static functions ******************************/ 114 | 115 | Servo::Servo() 116 | { 117 | if (ServoCount < MAX_SERVOS) { 118 | this->servoIndex = ServoCount++; // assign a servo index to this instance 119 | servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values 120 | } else { 121 | this->servoIndex = INVALID_SERVO; // too many servos 122 | } 123 | } 124 | 125 | uint8_t Servo::attach(int pin) 126 | { 127 | return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); 128 | } 129 | 130 | uint8_t Servo::attach(int pin, int min, int max) 131 | { 132 | timer16_Sequence_t timer; 133 | 134 | if (this->servoIndex < MAX_SERVOS) { 135 | pinMode(pin, OUTPUT); // set servo pin to output 136 | servos[this->servoIndex].Pin.nbr = pin; 137 | // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 138 | this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us 139 | this->max = (MAX_PULSE_WIDTH - max)/4; 140 | // initialize the timer if it has not already been initialized 141 | timer = SERVO_INDEX_TO_TIMER(servoIndex); 142 | if (isTimerActive(timer) == false) { 143 | initISR(timer); 144 | } 145 | servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive 146 | } 147 | return this->servoIndex; 148 | } 149 | 150 | void Servo::detach() 151 | { 152 | timer16_Sequence_t timer; 153 | 154 | servos[this->servoIndex].Pin.isActive = false; 155 | timer = SERVO_INDEX_TO_TIMER(servoIndex); 156 | if(isTimerActive(timer) == false) { 157 | finISR(timer); 158 | } 159 | } 160 | 161 | void Servo::write(int value) 162 | { 163 | // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) 164 | if (value < MIN_PULSE_WIDTH) 165 | { 166 | if (value < 0) 167 | value = 0; 168 | else if (value > 180) 169 | value = 180; 170 | 171 | value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); 172 | } 173 | writeMicroseconds(value); 174 | } 175 | 176 | void Servo::writeMicroseconds(int value) 177 | { 178 | // calculate and store the values for the given channel 179 | byte channel = this->servoIndex; 180 | if( (channel < MAX_SERVOS) ) // ensure channel is valid 181 | { 182 | if (value < SERVO_MIN()) // ensure pulse width is valid 183 | value = SERVO_MIN(); 184 | else if (value > SERVO_MAX()) 185 | value = SERVO_MAX(); 186 | 187 | value = value - TRIM_DURATION; 188 | value = usToTicks(value); // convert to ticks after compensating for interrupt overhead 189 | servos[channel].ticks = value; 190 | } 191 | } 192 | 193 | int Servo::read() // return the value as degrees 194 | { 195 | return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); 196 | } 197 | 198 | int Servo::readMicroseconds() 199 | { 200 | unsigned int pulsewidth; 201 | if (this->servoIndex != INVALID_SERVO) 202 | pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; 203 | else 204 | pulsewidth = 0; 205 | 206 | return pulsewidth; 207 | } 208 | 209 | bool Servo::attached() 210 | { 211 | return servos[this->servoIndex].Pin.isActive; 212 | } 213 | 214 | #endif 215 | -------------------------------------------------------------------------------- /src/megaavr/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2018 Arduino LLC. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | /* 20 | * Defines for 16 bit timers used with Servo library 21 | * 22 | */ 23 | 24 | #ifndef __SERVO_TIMERS_H__ 25 | #define __SERVO_TIMERS_H__ 26 | 27 | #include 28 | 29 | //#define USE_TIMERB1 // interferes with PWM on pin 3 30 | #define USE_TIMERB2 // interferes with PWM on pin 11 31 | //#define USE_TIMERB0 // interferes with PWM on pin 6 32 | 33 | #if !defined(USE_TIMERB1) && !defined(USE_TIMERB2) && !defined(USE_TIMERB0) 34 | # error "No timers allowed for Servo" 35 | /* Please uncomment a timer above and rebuild */ 36 | #endif 37 | 38 | static volatile TCB_t* _timer = 39 | #if defined(USE_TIMERB0) 40 | &TCB0; 41 | #endif 42 | #if defined(USE_TIMERB1) 43 | &TCB1; 44 | #endif 45 | #if defined(USE_TIMERB2) 46 | &TCB2; 47 | #endif 48 | 49 | typedef enum { 50 | timer0, 51 | _Nbr_16timers } timer16_Sequence_t; 52 | 53 | 54 | #endif /* __SERVO_TIMERS_H__ */ 55 | -------------------------------------------------------------------------------- /src/nrf52/Servo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Arduino. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | #if defined(ARDUINO_ARCH_NRF52) 20 | 21 | #include 22 | #include 23 | 24 | 25 | static servo_t servos[MAX_SERVOS]; // static array of servo structures 26 | 27 | uint8_t ServoCount = 0; // the total number of attached servos 28 | 29 | 30 | 31 | uint32_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}}; 32 | static uint16_t seq_values[3][NRF_PWM_CHANNEL_COUNT]={{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; 33 | 34 | Servo::Servo() 35 | { 36 | if (ServoCount < MAX_SERVOS) { 37 | this->servoIndex = ServoCount++; // assign a servo index to this instance 38 | } else { 39 | this->servoIndex = INVALID_SERVO; // too many servos 40 | } 41 | 42 | } 43 | 44 | uint8_t Servo::attach(int pin) 45 | { 46 | 47 | return this->attach(pin, 0, 2500); 48 | } 49 | 50 | 51 | uint8_t Servo::attach(int pin, int min, int max) 52 | { 53 | int servo_min, servo_max; 54 | if (this->servoIndex < MAX_SERVOS) { 55 | pinMode(pin, OUTPUT); // set servo pin to output 56 | servos[this->servoIndex].Pin.nbr = pin; 57 | 58 | if(min < servo_min) min = servo_min; 59 | if (max > servo_max) max = servo_max; 60 | this->min = min; 61 | this->max = max; 62 | 63 | servos[this->servoIndex].Pin.isActive = true; 64 | 65 | } 66 | return this->servoIndex; 67 | } 68 | 69 | void Servo::detach() 70 | { 71 | servos[this->servoIndex].Pin.isActive = false; 72 | } 73 | 74 | 75 | void Servo::write(int value) 76 | { 77 | if (value < 0) 78 | value = 0; 79 | else if (value > 180) 80 | value = 180; 81 | value = map(value, 0, 180, MIN_PULSE, MAX_PULSE); 82 | 83 | writeMicroseconds(value); 84 | } 85 | 86 | 87 | void Servo::writeMicroseconds(int value) 88 | { 89 | uint8_t channel, instance; 90 | uint8_t pin = servos[this->servoIndex].Pin.nbr; 91 | //instance of PWM module is MSB - look at VWariant.h 92 | instance=(g_APinDescription[pin].ulPWMChannel & 0xF0)/16; 93 | //index of PWM channel is LSB - look at VWariant.h 94 | channel=g_APinDescription[pin].ulPWMChannel & 0x0F; 95 | group_pins[instance][channel]=g_APinDescription[pin].ulPin; 96 | NRF_PWM_Type * PWMInstance = instance == 0 ? NRF_PWM0 : (instance == 1 ? NRF_PWM1 : NRF_PWM2); 97 | //configure PWM instance and enable it 98 | seq_values[instance][channel]= value | 0x8000; 99 | nrf_pwm_sequence_t const seq={ 100 | seq_values[instance], 101 | NRF_PWM_VALUES_LENGTH(seq_values), 102 | 0, 103 | 0 104 | }; 105 | nrf_pwm_pins_set(PWMInstance, group_pins[instance]); 106 | nrf_pwm_enable(PWMInstance); 107 | nrf_pwm_configure(PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, 2500); // 20ms - 50Hz 108 | nrf_pwm_decoder_set(PWMInstance, NRF_PWM_LOAD_INDIVIDUAL, NRF_PWM_STEP_AUTO); 109 | nrf_pwm_sequence_set(PWMInstance, 0, &seq); 110 | nrf_pwm_loop_set(PWMInstance, 0UL); 111 | nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_SEQSTART0); 112 | } 113 | 114 | int Servo::read() // return the value as degrees 115 | { 116 | return map(readMicroseconds(), MIN_PULSE, MAX_PULSE, 0, 180); 117 | } 118 | 119 | int Servo::readMicroseconds() 120 | { 121 | uint8_t channel, instance; 122 | uint8_t pin=servos[this->servoIndex].Pin.nbr; 123 | instance=(g_APinDescription[pin].ulPWMChannel & 0xF0)/16; 124 | channel=g_APinDescription[pin].ulPWMChannel & 0x0F; 125 | // remove the 16th bit we added before 126 | return seq_values[instance][channel] & 0x7FFF; 127 | } 128 | 129 | bool Servo::attached() 130 | { 131 | return servos[this->servoIndex].Pin.isActive; 132 | } 133 | 134 | #endif // ARDUINO_ARCH_NRF52 135 | -------------------------------------------------------------------------------- /src/nrf52/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Arduino. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | /* 20 | * nRF52 doesn't use timer, but PWM. This file includes definitions to keep 21 | * compatibility with the Servo library standards. 22 | */ 23 | 24 | #ifndef __SERVO_TIMERS_H__ 25 | #define __SERVO_TIMERS_H__ 26 | 27 | /** 28 | * nRF52 only definitions 29 | * --------------------- 30 | */ 31 | 32 | #define MIN_PULSE 55 33 | #define MAX_PULSE 284 34 | 35 | // define one timer in order to have MAX_SERVOS = 12 36 | typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t; 37 | 38 | #endif // __SERVO_TIMERS_H__ 39 | -------------------------------------------------------------------------------- /src/renesas/Servo.cpp: -------------------------------------------------------------------------------- 1 | /* The MIT License (MIT) 2 | * 3 | * Copyright (c) 2022 Arduino SA 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is 10 | * furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in 13 | * all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | * THE SOFTWARE. 22 | */ 23 | #if defined(ARDUINO_ARCH_RENESAS) 24 | 25 | #include "Arduino.h" 26 | #include "Servo.h" 27 | #include "ServoTimers.h" 28 | #include "math.h" 29 | #include "FspTimer.h" 30 | 31 | #define SERVO_MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER) 32 | #define SERVO_INVALID_INDEX (255) 33 | // Lower the timer ticks for finer resolution. 34 | #define SERVO_US_PER_CYCLE (20000) 35 | #define SERVO_IO_PORT_ADDR(pn) &((R_PORT0 + ((uint32_t) (R_PORT1 - R_PORT0) * (pn)))->PCNTR3) 36 | #define SERVO_MIN_CYCLE_OFF_US 50 37 | 38 | // Internal Servo struct to keep track of RA configuration. 39 | typedef struct { 40 | // Servo period in microseconds. 41 | uint32_t period_us; 42 | // Store min/max pulse width here, because min/max in 43 | // Servo class are not wide enough for the pulse width. 44 | uint32_t period_min; 45 | uint32_t period_max; 46 | // Period period_count in timer ticks. 47 | uint32_t period_ticks; 48 | // Internal FSP GPIO port/pin control bits. 49 | volatile uint32_t *io_port; 50 | uint32_t io_mask; 51 | } ra_servo_t; 52 | 53 | // Keep track of the total number of servos attached. 54 | static size_t n_servos=0; 55 | static ra_servo_t ra_servos[SERVO_MAX_SERVOS]; 56 | 57 | static FspTimer servo_timer; 58 | static bool servo_timer_started = false; 59 | void servo_timer_callback(timer_callback_args_t *args); 60 | 61 | static uint32_t servo_ticks_per_cycle = 0; 62 | static uint32_t min_servo_cycle_low = 0; 63 | static uint32_t active_servos_mask = 0; 64 | static uint32_t active_servos_mask_refresh = 0; 65 | 66 | 67 | static uint32_t us_to_ticks(uint32_t time_us) { 68 | return ((float) servo_ticks_per_cycle / (float) SERVO_US_PER_CYCLE) * time_us; 69 | } 70 | 71 | static int servo_timer_config(uint32_t period_us) 72 | { 73 | static bool configured = false; 74 | if (configured == false) { 75 | // Configure and enable the servo timer. 76 | uint8_t type = 0; 77 | int8_t channel = FspTimer::get_available_timer(type); 78 | if (channel != -1) { 79 | servo_timer.begin(TIMER_MODE_PERIODIC, type, channel, 80 | 1000000.0f/period_us, 50.0f, servo_timer_callback, nullptr); 81 | servo_timer.set_period_buffer(false); // disable period buffering 82 | servo_timer.setup_overflow_irq(10); 83 | servo_timer.open(); 84 | servo_timer.stop(); 85 | // Read the timer's period count. 86 | servo_ticks_per_cycle = servo_timer.get_period_raw(); 87 | min_servo_cycle_low = us_to_ticks(SERVO_MIN_CYCLE_OFF_US); 88 | 89 | configured = true; 90 | } 91 | } 92 | return configured ? 0 : -1; 93 | } 94 | 95 | static int servo_timer_start() 96 | { 97 | // Start the timer if it's not started 98 | if (servo_timer_started == false && 99 | servo_timer.start() == false) { 100 | return -1; 101 | } 102 | servo_timer_started = true; 103 | return 0; 104 | } 105 | 106 | static int servo_timer_stop() 107 | { 108 | // Start the timer if it's not started 109 | if (servo_timer_started == true && 110 | servo_timer.stop() == false) { 111 | return -1; 112 | } 113 | servo_timer_started = false; 114 | return 0; 115 | } 116 | 117 | inline static void servo_timer_set_period(uint32_t period) { 118 | servo_timer.set_period(period); 119 | } 120 | 121 | void servo_timer_callback(timer_callback_args_t *args) 122 | { 123 | (void)args; // remove warning 124 | static uint8_t channel = SERVO_MAX_SERVOS; 125 | static uint8_t channel_pin_set_high = 0xff; 126 | static uint32_t ticks_accum = 0; 127 | 128 | // See if we need to set a servo back low 129 | if (channel_pin_set_high != 0xff) { 130 | *ra_servos[channel_pin_set_high].io_port = ra_servos[channel_pin_set_high].io_mask << 16; 131 | } 132 | 133 | // Find the next servo to set high 134 | while (active_servos_mask_refresh) { 135 | channel = __builtin_ctz(active_servos_mask_refresh); 136 | if (ra_servos[channel].period_us) { 137 | *ra_servos[channel].io_port = ra_servos[channel].io_mask; 138 | servo_timer_set_period(ra_servos[channel].period_ticks); 139 | channel_pin_set_high = channel; 140 | ticks_accum += ra_servos[channel].period_ticks; 141 | active_servos_mask_refresh &= ~(1 << channel); 142 | return; 143 | } 144 | active_servos_mask_refresh &= ~(1 << channel); 145 | } 146 | // Finished processing all servos, now delay to start of next pass. 147 | ticks_accum += min_servo_cycle_low; 148 | uint32_t time_to_next_cycle; 149 | if (servo_ticks_per_cycle > ticks_accum) { 150 | time_to_next_cycle = servo_ticks_per_cycle - ticks_accum; 151 | } else { 152 | time_to_next_cycle = min_servo_cycle_low; 153 | } 154 | ticks_accum = 0; 155 | servo_timer_set_period(time_to_next_cycle); 156 | channel_pin_set_high = 0xff; 157 | active_servos_mask_refresh = active_servos_mask; 158 | } 159 | 160 | Servo::Servo() 161 | { 162 | servoIndex = SERVO_INVALID_INDEX; 163 | } 164 | 165 | uint8_t Servo::attach(int pin) 166 | { 167 | return attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); 168 | } 169 | 170 | bool Servo::attached() 171 | { 172 | return (servoIndex != SERVO_INVALID_INDEX); 173 | } 174 | 175 | uint8_t Servo::attach(int pin, int min, int max) 176 | { 177 | //assert(pin < NUM_DIGITAL_PINS); ? 178 | if (n_servos == SERVO_MAX_SERVOS) { 179 | return 0; 180 | } 181 | 182 | // Configure the servo timer. 183 | if (servo_timer_config(SERVO_US_PER_CYCLE) != 0) { 184 | return 0; 185 | } 186 | 187 | // Try to find a free servo slot. 188 | ra_servo_t *servo = NULL; 189 | bsp_io_port_pin_t io_pin = g_pin_cfg[pin].pin; 190 | for (size_t i=0; iperiod_us == 0) { 193 | n_servos++; 194 | servoIndex = i; 195 | servo->period_min = min; 196 | servo->period_max = max; 197 | servo->io_mask = (1U << (io_pin & 0xFF)); 198 | servo->io_port = SERVO_IO_PORT_ADDR(((io_pin >> 8U) & 0xFF)); 199 | active_servos_mask |= (1 << i); // update mask of servos that are active. 200 | writeMicroseconds(DEFAULT_PULSE_WIDTH); 201 | break; 202 | } 203 | } 204 | 205 | if (servoIndex == SERVO_INVALID_INDEX) { 206 | return 0; 207 | } 208 | 209 | // Configure GPIO pin for the servo. 210 | R_IOPORT_PinCfg(&g_ioport_ctrl, io_pin, 211 | IOPORT_CFG_PORT_DIRECTION_OUTPUT | IOPORT_CFG_PORT_OUTPUT_HIGH); 212 | 213 | // Start the timer if it's not started. 214 | if (servo_timer_start() != 0) { 215 | return 0; 216 | } 217 | return 1; 218 | } 219 | 220 | void Servo::detach() 221 | { 222 | if (servoIndex != SERVO_INVALID_INDEX) { 223 | ra_servo_t *servo = &ra_servos[servoIndex]; 224 | servo_timer_stop(); 225 | servo->period_us = 0; 226 | active_servos_mask &= ~(1 << servoIndex); // update mask of servos that are active. 227 | servoIndex = SERVO_INVALID_INDEX; 228 | if (--n_servos) { 229 | servo_timer_start(); 230 | } 231 | 232 | } 233 | } 234 | 235 | void Servo::write(int angle) 236 | { 237 | if (servoIndex != SERVO_INVALID_INDEX) { 238 | ra_servo_t *servo = &ra_servos[servoIndex]; 239 | angle = constrain(angle, 0, 180); 240 | writeMicroseconds(map(angle, 0, 180, servo->period_min, servo->period_max)); 241 | } 242 | } 243 | 244 | int Servo::read() 245 | { 246 | if (servoIndex != SERVO_INVALID_INDEX) { 247 | ra_servo_t *servo = &ra_servos[servoIndex]; 248 | return map(servo->period_us, servo->period_min, servo->period_max, 0, 180); 249 | } 250 | return 0; 251 | } 252 | 253 | void Servo::writeMicroseconds(int us) 254 | { 255 | if (servoIndex != SERVO_INVALID_INDEX) { 256 | ra_servo_t *servo = &ra_servos[servoIndex]; 257 | servo->period_us = constrain(us, servo->period_min, servo->period_max); 258 | servo->period_ticks = us_to_ticks(servo->period_us); 259 | } 260 | } 261 | 262 | int Servo::readMicroseconds() 263 | { 264 | if (servoIndex != SERVO_INVALID_INDEX) { 265 | ra_servo_t *servo = &ra_servos[servoIndex]; 266 | return servo->period_us; 267 | } 268 | return 0; 269 | } 270 | #endif // defined(ARDUINO_ARCH_RENESAS) 271 | -------------------------------------------------------------------------------- /src/renesas/ServoTimers.h: -------------------------------------------------------------------------------- 1 | #define _Nbr_16timers 1 2 | -------------------------------------------------------------------------------- /src/sam/Servo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2013 Arduino LLC. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | #if defined(ARDUINO_ARCH_SAM) 20 | 21 | #include 22 | #include 23 | 24 | #define usToTicks(_us) (( clockCyclesPerMicrosecond() * _us) / 32) // converts microseconds to ticks 25 | #define ticksToUs(_ticks) (( (unsigned)_ticks * 32)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds 26 | 27 | #define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays 28 | 29 | static servo_t servos[MAX_SERVOS]; // static array of servo structures 30 | 31 | uint8_t ServoCount = 0; // the total number of attached servos 32 | 33 | static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval) 34 | 35 | // convenience macros 36 | #define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo 37 | #define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer 38 | #define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel 39 | #define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel 40 | 41 | #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo 42 | #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo 43 | 44 | /************ static functions common to all instances ***********************/ 45 | 46 | //------------------------------------------------------------------------------ 47 | /// Interrupt handler for the TC0 channel 1. 48 | //------------------------------------------------------------------------------ 49 | void Servo_Handler(timer16_Sequence_t timer, Tc *pTc, uint8_t channel); 50 | #if defined (_useTimer1) 51 | void HANDLER_FOR_TIMER1(void) { 52 | Servo_Handler(_timer1, TC_FOR_TIMER1, CHANNEL_FOR_TIMER1); 53 | } 54 | #endif 55 | #if defined (_useTimer2) 56 | void HANDLER_FOR_TIMER2(void) { 57 | Servo_Handler(_timer2, TC_FOR_TIMER2, CHANNEL_FOR_TIMER2); 58 | } 59 | #endif 60 | #if defined (_useTimer3) 61 | void HANDLER_FOR_TIMER3(void) { 62 | Servo_Handler(_timer3, TC_FOR_TIMER3, CHANNEL_FOR_TIMER3); 63 | } 64 | #endif 65 | #if defined (_useTimer4) 66 | void HANDLER_FOR_TIMER4(void) { 67 | Servo_Handler(_timer4, TC_FOR_TIMER4, CHANNEL_FOR_TIMER4); 68 | } 69 | #endif 70 | #if defined (_useTimer5) 71 | void HANDLER_FOR_TIMER5(void) { 72 | Servo_Handler(_timer5, TC_FOR_TIMER5, CHANNEL_FOR_TIMER5); 73 | } 74 | #endif 75 | 76 | void Servo_Handler(timer16_Sequence_t timer, Tc *tc, uint8_t channel) 77 | { 78 | // clear interrupt 79 | tc->TC_CHANNEL[channel].TC_SR; 80 | if (Channel[timer] < 0) { 81 | tc->TC_CHANNEL[channel].TC_CCR |= TC_CCR_SWTRG; // channel set to -1 indicated that refresh interval completed so reset the timer 82 | } else { 83 | if (SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive == true) { 84 | digitalWrite(SERVO(timer,Channel[timer]).Pin.nbr, LOW); // pulse this channel low if activated 85 | } 86 | } 87 | 88 | Channel[timer]++; // increment to the next channel 89 | if( SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) { 90 | tc->TC_CHANNEL[channel].TC_RA = tc->TC_CHANNEL[channel].TC_CV + SERVO(timer,Channel[timer]).ticks; 91 | if(SERVO(timer,Channel[timer]).Pin.isActive == true) { // check if activated 92 | digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // it's an active channel so pulse it high 93 | } 94 | } 95 | else { 96 | // finished all channels so wait for the refresh period to expire before starting over 97 | if( (tc->TC_CHANNEL[channel].TC_CV) + 4 < usToTicks(REFRESH_INTERVAL) ) { // allow a few ticks to ensure the next OCR1A not missed 98 | tc->TC_CHANNEL[channel].TC_RA = (unsigned int)usToTicks(REFRESH_INTERVAL); 99 | } 100 | else { 101 | tc->TC_CHANNEL[channel].TC_RA = tc->TC_CHANNEL[channel].TC_CV + 4; // at least REFRESH_INTERVAL has elapsed 102 | } 103 | Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel 104 | } 105 | } 106 | 107 | static void _initISR(Tc *tc, uint32_t channel, uint32_t id, IRQn_Type irqn) 108 | { 109 | pmc_enable_periph_clk(id); 110 | TC_Configure(tc, channel, 111 | TC_CMR_TCCLKS_TIMER_CLOCK3 | // MCK/32 112 | TC_CMR_WAVE | // Waveform mode 113 | TC_CMR_WAVSEL_UP_RC ); // Counter running up and reset when equals to RC 114 | 115 | /* 84 MHz, MCK/32, for 1.5 ms: 3937 */ 116 | TC_SetRA(tc, channel, 2625); // 1ms 117 | 118 | /* Configure and enable interrupt */ 119 | NVIC_EnableIRQ(irqn); 120 | // TC_IER_CPAS: RA Compare 121 | tc->TC_CHANNEL[channel].TC_IER = TC_IER_CPAS; 122 | 123 | // Enables the timer clock and performs a software reset to start the counting 124 | TC_Start(tc, channel); 125 | } 126 | 127 | static void initISR(timer16_Sequence_t timer) 128 | { 129 | #if defined (_useTimer1) 130 | if (timer == _timer1) 131 | _initISR(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, ID_TC_FOR_TIMER1, IRQn_FOR_TIMER1); 132 | #endif 133 | #if defined (_useTimer2) 134 | if (timer == _timer2) 135 | _initISR(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, ID_TC_FOR_TIMER2, IRQn_FOR_TIMER2); 136 | #endif 137 | #if defined (_useTimer3) 138 | if (timer == _timer3) 139 | _initISR(TC_FOR_TIMER3, CHANNEL_FOR_TIMER3, ID_TC_FOR_TIMER3, IRQn_FOR_TIMER3); 140 | #endif 141 | #if defined (_useTimer4) 142 | if (timer == _timer4) 143 | _initISR(TC_FOR_TIMER4, CHANNEL_FOR_TIMER4, ID_TC_FOR_TIMER4, IRQn_FOR_TIMER4); 144 | #endif 145 | #if defined (_useTimer5) 146 | if (timer == _timer5) 147 | _initISR(TC_FOR_TIMER5, CHANNEL_FOR_TIMER5, ID_TC_FOR_TIMER5, IRQn_FOR_TIMER5); 148 | #endif 149 | } 150 | 151 | static void finISR(timer16_Sequence_t timer) 152 | { 153 | #if defined (_useTimer1) 154 | TC_Stop(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1); 155 | #endif 156 | #if defined (_useTimer2) 157 | TC_Stop(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2); 158 | #endif 159 | #if defined (_useTimer3) 160 | TC_Stop(TC_FOR_TIMER3, CHANNEL_FOR_TIMER3); 161 | #endif 162 | #if defined (_useTimer4) 163 | TC_Stop(TC_FOR_TIMER4, CHANNEL_FOR_TIMER4); 164 | #endif 165 | #if defined (_useTimer5) 166 | TC_Stop(TC_FOR_TIMER5, CHANNEL_FOR_TIMER5); 167 | #endif 168 | } 169 | 170 | 171 | static boolean isTimerActive(timer16_Sequence_t timer) 172 | { 173 | // returns true if any servo is active on this timer 174 | for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { 175 | if(SERVO(timer,channel).Pin.isActive == true) 176 | return true; 177 | } 178 | return false; 179 | } 180 | 181 | /****************** end of static functions ******************************/ 182 | 183 | Servo::Servo() 184 | { 185 | if (ServoCount < MAX_SERVOS) { 186 | this->servoIndex = ServoCount++; // assign a servo index to this instance 187 | servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values 188 | } else { 189 | this->servoIndex = INVALID_SERVO; // too many servos 190 | } 191 | } 192 | 193 | uint8_t Servo::attach(int pin) 194 | { 195 | return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); 196 | } 197 | 198 | uint8_t Servo::attach(int pin, int min, int max) 199 | { 200 | timer16_Sequence_t timer; 201 | 202 | if (this->servoIndex < MAX_SERVOS) { 203 | pinMode(pin, OUTPUT); // set servo pin to output 204 | servos[this->servoIndex].Pin.nbr = pin; 205 | // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 206 | this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us 207 | this->max = (MAX_PULSE_WIDTH - max)/4; 208 | // initialize the timer if it has not already been initialized 209 | timer = SERVO_INDEX_TO_TIMER(servoIndex); 210 | if (isTimerActive(timer) == false) { 211 | initISR(timer); 212 | } 213 | servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive 214 | } 215 | return this->servoIndex; 216 | } 217 | 218 | void Servo::detach() 219 | { 220 | timer16_Sequence_t timer; 221 | 222 | servos[this->servoIndex].Pin.isActive = false; 223 | timer = SERVO_INDEX_TO_TIMER(servoIndex); 224 | if(isTimerActive(timer) == false) { 225 | finISR(timer); 226 | } 227 | } 228 | 229 | void Servo::write(int value) 230 | { 231 | // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) 232 | if (value < MIN_PULSE_WIDTH) 233 | { 234 | if (value < 0) 235 | value = 0; 236 | else if (value > 180) 237 | value = 180; 238 | 239 | value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); 240 | } 241 | writeMicroseconds(value); 242 | } 243 | 244 | void Servo::writeMicroseconds(int value) 245 | { 246 | // calculate and store the values for the given channel 247 | byte channel = this->servoIndex; 248 | if( (channel < MAX_SERVOS) ) // ensure channel is valid 249 | { 250 | if (value < SERVO_MIN()) // ensure pulse width is valid 251 | value = SERVO_MIN(); 252 | else if (value > SERVO_MAX()) 253 | value = SERVO_MAX(); 254 | 255 | value = value - TRIM_DURATION; 256 | value = usToTicks(value); // convert to ticks after compensating for interrupt overhead 257 | servos[channel].ticks = value; 258 | } 259 | } 260 | 261 | int Servo::read() // return the value as degrees 262 | { 263 | return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); 264 | } 265 | 266 | int Servo::readMicroseconds() 267 | { 268 | unsigned int pulsewidth; 269 | if (this->servoIndex != INVALID_SERVO) 270 | pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; 271 | else 272 | pulsewidth = 0; 273 | 274 | return pulsewidth; 275 | } 276 | 277 | bool Servo::attached() 278 | { 279 | return servos[this->servoIndex].Pin.isActive; 280 | } 281 | 282 | #endif // ARDUINO_ARCH_SAM 283 | -------------------------------------------------------------------------------- /src/sam/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2013 Arduino LLC. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | /* 20 | * Defines for 16 bit timers used with Servo library 21 | * 22 | * If _useTimerX is defined then TimerX is a 16 bit timer on the current board 23 | * timer16_Sequence_t enumerates the sequence that the timers should be allocated 24 | * _Nbr_16timers indicates how many 16 bit timers are available. 25 | */ 26 | 27 | /** 28 | * SAM Only definitions 29 | * -------------------- 30 | */ 31 | 32 | // For SAM3X: 33 | #define _useTimer1 34 | #define _useTimer2 35 | #define _useTimer3 36 | #define _useTimer4 37 | #define _useTimer5 38 | 39 | /* 40 | TC0, chan 0 => TC0_Handler 41 | TC0, chan 1 => TC1_Handler 42 | TC0, chan 2 => TC2_Handler 43 | TC1, chan 0 => TC3_Handler 44 | TC1, chan 1 => TC4_Handler 45 | TC1, chan 2 => TC5_Handler 46 | TC2, chan 0 => TC6_Handler 47 | TC2, chan 1 => TC7_Handler 48 | TC2, chan 2 => TC8_Handler 49 | */ 50 | 51 | #if defined (_useTimer1) 52 | #define TC_FOR_TIMER1 TC1 53 | #define CHANNEL_FOR_TIMER1 0 54 | #define ID_TC_FOR_TIMER1 ID_TC3 55 | #define IRQn_FOR_TIMER1 TC3_IRQn 56 | #define HANDLER_FOR_TIMER1 TC3_Handler 57 | #endif 58 | #if defined (_useTimer2) 59 | #define TC_FOR_TIMER2 TC1 60 | #define CHANNEL_FOR_TIMER2 1 61 | #define ID_TC_FOR_TIMER2 ID_TC4 62 | #define IRQn_FOR_TIMER2 TC4_IRQn 63 | #define HANDLER_FOR_TIMER2 TC4_Handler 64 | #endif 65 | #if defined (_useTimer3) 66 | #define TC_FOR_TIMER3 TC1 67 | #define CHANNEL_FOR_TIMER3 2 68 | #define ID_TC_FOR_TIMER3 ID_TC5 69 | #define IRQn_FOR_TIMER3 TC5_IRQn 70 | #define HANDLER_FOR_TIMER3 TC5_Handler 71 | #endif 72 | #if defined (_useTimer4) 73 | #define TC_FOR_TIMER4 TC0 74 | #define CHANNEL_FOR_TIMER4 2 75 | #define ID_TC_FOR_TIMER4 ID_TC2 76 | #define IRQn_FOR_TIMER4 TC2_IRQn 77 | #define HANDLER_FOR_TIMER4 TC2_Handler 78 | #endif 79 | #if defined (_useTimer5) 80 | #define TC_FOR_TIMER5 TC0 81 | #define CHANNEL_FOR_TIMER5 0 82 | #define ID_TC_FOR_TIMER5 ID_TC0 83 | #define IRQn_FOR_TIMER5 TC0_IRQn 84 | #define HANDLER_FOR_TIMER5 TC0_Handler 85 | #endif 86 | 87 | typedef enum { _timer1, _timer2, _timer3, _timer4, _timer5, _Nbr_16timers } timer16_Sequence_t ; 88 | -------------------------------------------------------------------------------- /src/samd/Servo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2015 Arduino LLC. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | #if defined(ARDUINO_ARCH_SAMD) 20 | 21 | #include 22 | #include 23 | 24 | #define usToTicks(_us) ((clockCyclesPerMicrosecond() * _us) / 16) // converts microseconds to ticks 25 | #define ticksToUs(_ticks) (((unsigned) _ticks * 16) / clockCyclesPerMicrosecond()) // converts from ticks back to microseconds 26 | 27 | #define TRIM_DURATION 5 // compensation ticks to trim adjust for digitalWrite delays 28 | 29 | static servo_t servos[MAX_SERVOS]; // static array of servo structures 30 | 31 | uint8_t ServoCount = 0; // the total number of attached servos 32 | 33 | static volatile int8_t currentServoIndex[_Nbr_16timers]; // index for the servo being pulsed for each timer (or -1 if refresh interval) 34 | 35 | // convenience macros 36 | #define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo 37 | #define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer 38 | #define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel 39 | #define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel 40 | 41 | #define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in us for this servo 42 | #define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in us for this servo 43 | 44 | #define WAIT_TC16_REGS_SYNC(x) while(x->COUNT16.STATUS.bit.SYNCBUSY); 45 | 46 | /************ static functions common to all instances ***********************/ 47 | 48 | void Servo_Handler(timer16_Sequence_t timer, Tc *pTc, uint8_t channel, uint8_t intFlag); 49 | #if defined (_useTimer1) 50 | void HANDLER_FOR_TIMER1(void) { 51 | Servo_Handler(_timer1, TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, INTFLAG_BIT_FOR_TIMER_1); 52 | } 53 | #endif 54 | #if defined (_useTimer2) 55 | void HANDLER_FOR_TIMER2(void) { 56 | Servo_Handler(_timer2, TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, INTFLAG_BIT_FOR_TIMER_2); 57 | } 58 | #endif 59 | 60 | void Servo_Handler(timer16_Sequence_t timer, Tc *tc, uint8_t channel, uint8_t intFlag) 61 | { 62 | if (currentServoIndex[timer] < 0) { 63 | tc->COUNT16.COUNT.reg = (uint16_t) 0; 64 | WAIT_TC16_REGS_SYNC(tc) 65 | } else { 66 | if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { 67 | digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, LOW); // pulse this channel low if activated 68 | } 69 | } 70 | 71 | // Select the next servo controlled by this timer 72 | currentServoIndex[timer]++; 73 | 74 | if (SERVO_INDEX(timer, currentServoIndex[timer]) < ServoCount && currentServoIndex[timer] < SERVOS_PER_TIMER) { 75 | if (SERVO(timer, currentServoIndex[timer]).Pin.isActive == true) { // check if activated 76 | digitalWrite(SERVO(timer, currentServoIndex[timer]).Pin.nbr, HIGH); // it's an active channel so pulse it high 77 | } 78 | 79 | // Get the counter value 80 | uint16_t tcCounterValue = tc->COUNT16.COUNT.reg; 81 | WAIT_TC16_REGS_SYNC(tc) 82 | 83 | tc->COUNT16.CC[channel].reg = (uint16_t) (tcCounterValue + SERVO(timer, currentServoIndex[timer]).ticks); 84 | WAIT_TC16_REGS_SYNC(tc) 85 | } 86 | else { 87 | // finished all channels so wait for the refresh period to expire before starting over 88 | 89 | // Get the counter value 90 | uint16_t tcCounterValue = tc->COUNT16.COUNT.reg; 91 | WAIT_TC16_REGS_SYNC(tc) 92 | 93 | if (tcCounterValue + 4UL < usToTicks(REFRESH_INTERVAL)) { // allow a few ticks to ensure the next OCR1A not missed 94 | tc->COUNT16.CC[channel].reg = (uint16_t) usToTicks(REFRESH_INTERVAL); 95 | } 96 | else { 97 | tc->COUNT16.CC[channel].reg = (uint16_t) (tcCounterValue + 4UL); // at least REFRESH_INTERVAL has elapsed 98 | } 99 | WAIT_TC16_REGS_SYNC(tc) 100 | 101 | currentServoIndex[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel 102 | } 103 | 104 | // Clear the interrupt 105 | tc->COUNT16.INTFLAG.reg = intFlag; 106 | } 107 | 108 | static inline void resetTC (Tc* TCx) 109 | { 110 | // Disable TCx 111 | TCx->COUNT16.CTRLA.reg &= ~TC_CTRLA_ENABLE; 112 | WAIT_TC16_REGS_SYNC(TCx) 113 | 114 | // Reset TCx 115 | TCx->COUNT16.CTRLA.reg = TC_CTRLA_SWRST; 116 | WAIT_TC16_REGS_SYNC(TCx) 117 | while (TCx->COUNT16.CTRLA.bit.SWRST); 118 | } 119 | 120 | static void _initISR(Tc *tc, uint8_t channel, uint32_t id, IRQn_Type irqn, uint8_t gcmForTimer, uint8_t intEnableBit) 121 | { 122 | // Enable GCLK for timer 1 (timer counter input clock) 123 | GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(gcmForTimer)); 124 | while (GCLK->STATUS.bit.SYNCBUSY); 125 | 126 | // Reset the timer 127 | // TODO this is not the right thing to do if more than one channel per timer is used by the Servo library 128 | resetTC(tc); 129 | 130 | // Set timer counter mode to 16 bits 131 | tc->COUNT16.CTRLA.reg |= TC_CTRLA_MODE_COUNT16; 132 | 133 | // Set timer counter mode as normal PWM 134 | tc->COUNT16.CTRLA.reg |= TC_CTRLA_WAVEGEN_NPWM; 135 | 136 | // Set the prescaler factor to GCLK_TC/16. At nominal 48 MHz GCLK_TC this is 3000 ticks per millisecond 137 | tc->COUNT16.CTRLA.reg |= TC_CTRLA_PRESCALER_DIV16; 138 | 139 | // Count up 140 | tc->COUNT16.CTRLBCLR.bit.DIR = 1; 141 | WAIT_TC16_REGS_SYNC(tc) 142 | 143 | // First interrupt request after 1 ms 144 | tc->COUNT16.CC[channel].reg = (uint16_t) usToTicks(1000UL); 145 | WAIT_TC16_REGS_SYNC(tc) 146 | 147 | // Configure interrupt request 148 | // TODO this should be changed if more than one channel per timer is used by the Servo library 149 | NVIC_DisableIRQ(irqn); 150 | NVIC_ClearPendingIRQ(irqn); 151 | NVIC_SetPriority(irqn, 0); 152 | NVIC_EnableIRQ(irqn); 153 | 154 | // Enable the match channel interrupt request 155 | tc->COUNT16.INTENSET.reg = intEnableBit; 156 | 157 | // Enable the timer and start it 158 | tc->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE; 159 | WAIT_TC16_REGS_SYNC(tc) 160 | } 161 | 162 | static void initISR(timer16_Sequence_t timer) 163 | { 164 | #if defined (_useTimer1) 165 | if (timer == _timer1) 166 | _initISR(TC_FOR_TIMER1, CHANNEL_FOR_TIMER1, ID_TC_FOR_TIMER1, IRQn_FOR_TIMER1, GCM_FOR_TIMER_1, INTENSET_BIT_FOR_TIMER_1); 167 | #endif 168 | #if defined (_useTimer2) 169 | if (timer == _timer2) 170 | _initISR(TC_FOR_TIMER2, CHANNEL_FOR_TIMER2, ID_TC_FOR_TIMER2, IRQn_FOR_TIMER2, GCM_FOR_TIMER_2, INTENSET_BIT_FOR_TIMER_2); 171 | #endif 172 | } 173 | 174 | static void finISR(timer16_Sequence_t timer) 175 | { 176 | #if defined (_useTimer1) 177 | // Disable the match channel interrupt request 178 | TC_FOR_TIMER1->COUNT16.INTENCLR.reg = INTENCLR_BIT_FOR_TIMER_1; 179 | #endif 180 | #if defined (_useTimer2) 181 | // Disable the match channel interrupt request 182 | TC_FOR_TIMER2->COUNT16.INTENCLR.reg = INTENCLR_BIT_FOR_TIMER_2; 183 | #endif 184 | } 185 | 186 | static boolean isTimerActive(timer16_Sequence_t timer) 187 | { 188 | // returns true if any servo is active on this timer 189 | for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { 190 | if(SERVO(timer,channel).Pin.isActive == true) 191 | return true; 192 | } 193 | return false; 194 | } 195 | 196 | /****************** end of static functions ******************************/ 197 | 198 | Servo::Servo() 199 | { 200 | if (ServoCount < MAX_SERVOS) { 201 | this->servoIndex = ServoCount++; // assign a servo index to this instance 202 | servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values 203 | } else { 204 | this->servoIndex = INVALID_SERVO; // too many servos 205 | } 206 | } 207 | 208 | uint8_t Servo::attach(int pin) 209 | { 210 | return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); 211 | } 212 | 213 | uint8_t Servo::attach(int pin, int min, int max) 214 | { 215 | timer16_Sequence_t timer; 216 | 217 | if (this->servoIndex < MAX_SERVOS) { 218 | pinMode(pin, OUTPUT); // set servo pin to output 219 | servos[this->servoIndex].Pin.nbr = pin; 220 | // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 221 | this->min = (MIN_PULSE_WIDTH - min)/4; //resolution of min/max is 4 us 222 | this->max = (MAX_PULSE_WIDTH - max)/4; 223 | // initialize the timer if it has not already been initialized 224 | timer = SERVO_INDEX_TO_TIMER(servoIndex); 225 | if (isTimerActive(timer) == false) { 226 | initISR(timer); 227 | } 228 | servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive 229 | } 230 | return this->servoIndex; 231 | } 232 | 233 | void Servo::detach() 234 | { 235 | timer16_Sequence_t timer; 236 | 237 | servos[this->servoIndex].Pin.isActive = false; 238 | timer = SERVO_INDEX_TO_TIMER(servoIndex); 239 | if(isTimerActive(timer) == false) { 240 | finISR(timer); 241 | } 242 | } 243 | 244 | void Servo::write(int value) 245 | { 246 | // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) 247 | if (value < MIN_PULSE_WIDTH) 248 | { 249 | if (value < 0) 250 | value = 0; 251 | else if (value > 180) 252 | value = 180; 253 | 254 | value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); 255 | } 256 | writeMicroseconds(value); 257 | } 258 | 259 | void Servo::writeMicroseconds(int value) 260 | { 261 | // calculate and store the values for the given channel 262 | byte channel = this->servoIndex; 263 | if( (channel < MAX_SERVOS) ) // ensure channel is valid 264 | { 265 | if (value < SERVO_MIN()) // ensure pulse width is valid 266 | value = SERVO_MIN(); 267 | else if (value > SERVO_MAX()) 268 | value = SERVO_MAX(); 269 | 270 | value = value - TRIM_DURATION; 271 | value = usToTicks(value); // convert to ticks after compensating for interrupt overhead 272 | servos[channel].ticks = value; 273 | } 274 | } 275 | 276 | int Servo::read() // return the value as degrees 277 | { 278 | return map(readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); 279 | } 280 | 281 | int Servo::readMicroseconds() 282 | { 283 | unsigned int pulsewidth; 284 | if (this->servoIndex != INVALID_SERVO) 285 | pulsewidth = ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; 286 | else 287 | pulsewidth = 0; 288 | 289 | return pulsewidth; 290 | } 291 | 292 | bool Servo::attached() 293 | { 294 | return servos[this->servoIndex].Pin.isActive; 295 | } 296 | 297 | #endif // ARDUINO_ARCH_SAMD 298 | -------------------------------------------------------------------------------- /src/samd/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2015 Arduino LLC. All right reserved. 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | /* 20 | * Defines for 16 bit timers used with Servo library 21 | * 22 | * If _useTimerX is defined then TimerX is a 16 bit timer on the current board 23 | * timer16_Sequence_t enumerates the sequence that the timers should be allocated 24 | * _Nbr_16timers indicates how many 16 bit timers are available. 25 | */ 26 | 27 | #ifndef __SERVO_TIMERS_H__ 28 | #define __SERVO_TIMERS_H__ 29 | 30 | /** 31 | * SAMD Only definitions 32 | * --------------------- 33 | */ 34 | 35 | // For SAMD: 36 | #define _useTimer1 37 | //#define _useTimer2 // <- TODO do not activate until the code in Servo.cpp has been changed in order 38 | // to manage more than one channel per timer on the SAMD architecture 39 | 40 | #if defined (_useTimer1) 41 | #define TC_FOR_TIMER1 TC4 42 | #define CHANNEL_FOR_TIMER1 0 43 | #define INTENSET_BIT_FOR_TIMER_1 TC_INTENSET_MC0 44 | #define INTENCLR_BIT_FOR_TIMER_1 TC_INTENCLR_MC0 45 | #define INTFLAG_BIT_FOR_TIMER_1 TC_INTFLAG_MC0 46 | #define ID_TC_FOR_TIMER1 ID_TC4 47 | #define IRQn_FOR_TIMER1 TC4_IRQn 48 | #define HANDLER_FOR_TIMER1 TC4_Handler 49 | #define GCM_FOR_TIMER_1 GCM_TC4_TC5 50 | #endif 51 | #if defined (_useTimer2) 52 | #define TC_FOR_TIMER2 TC4 53 | #define CHANNEL_FOR_TIMER2 1 54 | #define INTENSET_BIT_FOR_TIMER_2 TC_INTENSET_MC1 55 | #define INTENCLR_BIT_FOR_TIMER_2 TC_INTENCLR_MC1 56 | #define ID_TC_FOR_TIMER2 ID_TC4 57 | #define IRQn_FOR_TIMER2 TC4_IRQn 58 | #define HANDLER_FOR_TIMER2 TC4_Handler 59 | #define GCM_FOR_TIMER_2 GCM_TC4_TC5 60 | #endif 61 | 62 | typedef enum { 63 | #if defined (_useTimer1) 64 | _timer1, 65 | #endif 66 | #if defined (_useTimer2) 67 | _timer2, 68 | #endif 69 | _Nbr_16timers } timer16_Sequence_t; 70 | 71 | #endif // __SERVO_TIMERS_H__ 72 | -------------------------------------------------------------------------------- /src/stm32f4/Servo.cpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * The MIT License 3 | * 4 | * Copyright (c) 2010, LeafLabs, LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person 7 | * obtaining a copy of this software and associated documentation 8 | * files (the "Software"), to deal in the Software without 9 | * restriction, including without limitation the rights to use, copy, 10 | * modify, merge, publish, distribute, sublicense, and/or sell copies 11 | * of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be 15 | * included in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 21 | * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 22 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | *****************************************************************************/ 26 | 27 | #if defined(ARDUINO_ARCH_STM32F4) 28 | 29 | #include "ServoTimers.h" 30 | 31 | #include "boards.h" 32 | #include "io.h" 33 | #include "pwm.h" 34 | #include "math.h" 35 | 36 | // 20 millisecond period config. For a 1-based prescaler, 37 | // 38 | // (prescaler * overflow / CYC_MSEC) msec = 1 timer cycle = 20 msec 39 | // => prescaler * overflow = 20 * CYC_MSEC 40 | // 41 | // This picks the smallest prescaler that allows an overflow < 2^16. 42 | #define MAX_OVERFLOW ((1 << 16) - 1) 43 | #define CYC_MSEC (1000 * CYCLES_PER_MICROSECOND) 44 | #define TAU_MSEC 20 45 | #define TAU_USEC (TAU_MSEC * 1000) 46 | #define TAU_CYC (TAU_MSEC * CYC_MSEC) 47 | #define SERVO_PRESCALER (TAU_CYC / MAX_OVERFLOW + 1) 48 | #define SERVO_OVERFLOW ((uint16)round((double)TAU_CYC / SERVO_PRESCALER)) 49 | 50 | // Unit conversions 51 | #define US_TO_COMPARE(us) ((uint16)map((us), 0, TAU_USEC, 0, SERVO_OVERFLOW)) 52 | #define COMPARE_TO_US(c) ((uint32)map((c), 0, SERVO_OVERFLOW, 0, TAU_USEC)) 53 | #define ANGLE_TO_US(a) ((uint16)(map((a), this->minAngle, this->maxAngle, \ 54 | this->minPW, this->maxPW))) 55 | #define US_TO_ANGLE(us) ((int16)(map((us), this->minPW, this->maxPW, \ 56 | this->minAngle, this->maxAngle))) 57 | 58 | Servo::Servo() { 59 | this->resetFields(); 60 | } 61 | 62 | bool Servo::attach(uint8 pin, uint16 minPW, uint16 maxPW, int16 minAngle, int16 maxAngle) 63 | { 64 | // SerialUSB.begin(115200); 65 | // SerialUSB.println(MAX_OVERFLOW); 66 | 67 | 68 | timer_dev *tdev = PIN_MAP[pin].timer_device; 69 | 70 | analogWriteResolution(16); 71 | 72 | int prescaler = 6; 73 | int overflow = 65400; 74 | int minPW_correction = 300; 75 | int maxPW_correction = 300; 76 | 77 | pinMode(pin, OUTPUT); 78 | 79 | 80 | if (tdev == NULL) { 81 | // don't reset any fields or ASSERT(0), to keep driving any 82 | // previously attach()ed servo. 83 | return false; 84 | } 85 | 86 | if ( (tdev == TIMER1) || (tdev == TIMER8) || (tdev == TIMER10) || (tdev == TIMER11)) 87 | { 88 | prescaler = 54; 89 | overflow = 65400; 90 | minPW_correction = 40; 91 | maxPW_correction = 50; 92 | } 93 | 94 | if ( (tdev == TIMER2) || (tdev == TIMER3) || (tdev == TIMER4) || (tdev == TIMER5) ) 95 | { 96 | prescaler = 6; 97 | overflow = 64285; 98 | minPW_correction = 370; 99 | maxPW_correction = 350; 100 | } 101 | 102 | if ( (tdev == TIMER6) || (tdev == TIMER7) ) 103 | { 104 | prescaler = 6; 105 | overflow = 65400; 106 | minPW_correction = 0; 107 | maxPW_correction = 0; 108 | } 109 | 110 | if ( (tdev == TIMER9) || (tdev == TIMER12) || (tdev == TIMER13) || (tdev == TIMER14) ) 111 | { 112 | prescaler = 6; 113 | overflow = 65400; 114 | minPW_correction = 30; 115 | maxPW_correction = 0; 116 | } 117 | 118 | if (this->attached()) { 119 | this->detach(); 120 | } 121 | 122 | this->pin = pin; 123 | this->minPW = (minPW + minPW_correction); 124 | this->maxPW = (maxPW + maxPW_correction); 125 | this->minAngle = minAngle; 126 | this->maxAngle = maxAngle; 127 | 128 | timer_pause(tdev); 129 | timer_set_prescaler(tdev, prescaler); // prescaler is 1-based 130 | timer_set_reload(tdev, overflow); 131 | timer_generate_update(tdev); 132 | timer_resume(tdev); 133 | 134 | return true; 135 | } 136 | 137 | bool Servo::detach() { 138 | if (!this->attached()) { 139 | return false; 140 | } 141 | 142 | timer_dev *tdev = PIN_MAP[this->pin].timer_device; 143 | uint8 tchan = PIN_MAP[this->pin].timer_channel; 144 | timer_set_mode(tdev, tchan, TIMER_DISABLED); 145 | 146 | this->resetFields(); 147 | 148 | return true; 149 | } 150 | 151 | void Servo::write(int degrees) { 152 | degrees = constrain(degrees, this->minAngle, this->maxAngle); 153 | this->writeMicroseconds(ANGLE_TO_US(degrees)); 154 | } 155 | 156 | int Servo::read() const { 157 | int a = US_TO_ANGLE(this->readMicroseconds()); 158 | // map() round-trips in a weird way we mostly correct for here; 159 | // the round-trip is still sometimes off-by-one for write(1) and 160 | // write(179). 161 | return a == this->minAngle || a == this->maxAngle ? a : a + 1; 162 | } 163 | 164 | void Servo::writeMicroseconds(uint16 pulseWidth) { 165 | if (!this->attached()) { 166 | ASSERT(0); 167 | return; 168 | } 169 | pulseWidth = constrain(pulseWidth, this->minPW, this->maxPW); 170 | analogWrite(this->pin, US_TO_COMPARE(pulseWidth)); 171 | } 172 | 173 | uint16 Servo::readMicroseconds() const { 174 | if (!this->attached()) { 175 | ASSERT(0); 176 | return 0; 177 | } 178 | 179 | stm32_pin_info pin_info = PIN_MAP[this->pin]; 180 | uint16 compare = timer_get_compare(pin_info.timer_device, 181 | pin_info.timer_channel); 182 | 183 | return COMPARE_TO_US(compare); 184 | } 185 | 186 | void Servo::resetFields(void) { 187 | this->pin = NOT_ATTACHED; 188 | this->minAngle = MIN_ANGLE; 189 | this->maxAngle = MAX_ANGLE; 190 | this->minPW = MIN_PULSE_WIDTH; 191 | this->maxPW = MAX_PULSE_WIDTH; 192 | } 193 | 194 | #endif 195 | -------------------------------------------------------------------------------- /src/stm32f4/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * The MIT License 3 | * 4 | * Copyright (c) 2010, LeafLabs, LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person 7 | * obtaining a copy of this software and associated documentation 8 | * files (the "Software"), to deal in the Software without 9 | * restriction, including without limitation the rights to use, copy, 10 | * modify, merge, publish, distribute, sublicense, and/or sell copies 11 | * of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be 15 | * included in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 21 | * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 22 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | *****************************************************************************/ 26 | 27 | /* 28 | * Arduino srl - www.arduino.org 29 | * 2017 Feb 23: Edited by Francesco Alessi (alfran) - francesco@arduino.org 30 | */ 31 | #ifndef _SERVO_H_ 32 | #define _SERVO_H_ 33 | 34 | #include "types.h" 35 | #include "timer.h" 36 | 37 | #include "wiring.h" /* hack for IDE compile */ 38 | 39 | /* 40 | * Note on Arduino compatibility: 41 | * 42 | * In the Arduino implementation, PWM is done "by hand" in the sense 43 | * that timer channels are hijacked in groups and an ISR is set which 44 | * toggles Servo::attach()ed pins using digitalWrite(). 45 | * 46 | * While this scheme allows any pin to drive a servo, it chews up 47 | * cycles and complicates the programmer's notion of when a particular 48 | * timer channel will be in use. 49 | * 50 | * This implementation only allows Servo instances to attach() to pins 51 | * that already have a timer channel associated with them, and just 52 | * uses analogWrite() to drive the wave. 53 | * 54 | * This introduces an incompatibility: while the Arduino 55 | * implementation of attach() returns the affected channel on success 56 | * and 0 on failure, this one returns true on success and false on 57 | * failure. 58 | * 59 | * RC Servos expect a pulse every 20 ms. Since periods are set for 60 | * entire timers, rather than individual channels, attach()ing a Servo 61 | * to a pin can interfere with other pins associated with the same 62 | * timer. As always, your board's pin map is your friend. 63 | */ 64 | 65 | // Pin number of unattached pins 66 | #define NOT_ATTACHED (-1) 67 | 68 | #define _Nbr_16timers 14 // Number of STM32F469 Timers 69 | #define SERVOS_PER_TIMER 4 // Number of timer channels 70 | 71 | 72 | // Default min/max pulse widths (in microseconds) and angles (in 73 | // degrees). Values chosen for Arduino compatibility. These values 74 | // are part of the public API; DO NOT CHANGE THEM. 75 | #define MIN_ANGLE 0 76 | #define MAX_ANGLE 180 77 | 78 | #define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo 79 | #define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo 80 | 81 | /** Class for interfacing with RC servomotors. */ 82 | class Servo { 83 | public: 84 | /** 85 | * @brief Construct a new Servo instance. 86 | * 87 | * The new instance will not be attached to any pin. 88 | */ 89 | Servo(); 90 | 91 | /** 92 | * @brief Associate this instance with a servomotor whose input is 93 | * connected to pin. 94 | * 95 | * If this instance is already attached to a pin, it will be 96 | * detached before being attached to the new pin. This function 97 | * doesn't detach any interrupt attached with the pin's timer 98 | * channel. 99 | * 100 | * @param pin Pin connected to the servo pulse wave input. This 101 | * pin must be capable of PWM output. 102 | * 103 | * @param minPulseWidth Minimum pulse width to write to pin, in 104 | * microseconds. This will be associated 105 | * with a minAngle degree angle. Defaults to 106 | * SERVO_DEFAULT_MIN_PW = 544. 107 | * 108 | * @param maxPulseWidth Maximum pulse width to write to pin, in 109 | * microseconds. This will be associated 110 | * with a maxAngle degree angle. Defaults to 111 | * SERVO_DEFAULT_MAX_PW = 2400. 112 | * 113 | * @param minAngle Target angle (in degrees) associated with 114 | * minPulseWidth. Defaults to 115 | * SERVO_DEFAULT_MIN_ANGLE = 0. 116 | * 117 | * @param maxAngle Target angle (in degrees) associated with 118 | * maxPulseWidth. Defaults to 119 | * SERVO_DEFAULT_MAX_ANGLE = 180. 120 | * 121 | * @sideeffect May set pinMode(pin, PWM). 122 | * 123 | * @return true if successful, false when pin doesn't support PWM. 124 | */ 125 | 126 | bool attach(uint8 pin, 127 | uint16 minPulseWidth=MIN_PULSE_WIDTH, 128 | uint16 maxPulseWidth=MAX_PULSE_WIDTH, 129 | int16 minAngle=MIN_ANGLE, 130 | int16 maxAngle=MAX_ANGLE); 131 | /** 132 | * @brief Stop driving the servo pulse train. 133 | * 134 | * If not currently attached to a motor, this function has no effect. 135 | * 136 | * @return true if this call did anything, false otherwise. 137 | */ 138 | bool detach(); 139 | 140 | /** 141 | * @brief Set the servomotor target angle. 142 | * 143 | * @param angle Target angle, in degrees. If the target angle is 144 | * outside the range specified at attach() time, it 145 | * will be clamped to lie in that range. 146 | * 147 | * @see Servo::attach() 148 | */ 149 | void write(int angle); 150 | 151 | /** 152 | * @brief Set the pulse width, in microseconds. 153 | * 154 | * @param pulseWidth Pulse width to send to the servomotor, in 155 | * microseconds. If outside of the range 156 | * specified at attach() time, it is clamped to 157 | * lie in that range. 158 | * 159 | * @see Servo::attach() 160 | */ 161 | void writeMicroseconds(uint16 pulseWidth); 162 | 163 | /** 164 | * Get the servomotor's target angle, in degrees. This will 165 | * lie inside the range specified at attach() time. 166 | * 167 | * @see Servo::attach() 168 | */ 169 | int read() const; 170 | 171 | /** 172 | * Get the current pulse width, in microseconds. This will 173 | * lie within the range specified at attach() time. 174 | * 175 | * @see Servo::attach() 176 | */ 177 | uint16 readMicroseconds() const; 178 | 179 | 180 | /** 181 | * @brief Check if this instance is attached to a servo. 182 | * @return true if this instance is attached to a servo, false otherwise. 183 | * @see Servo::attachedPin() 184 | */ 185 | bool attached() const { return this->pin != NOT_ATTACHED; } 186 | 187 | /** 188 | * @brief Get the pin this instance is attached to. 189 | * @return Pin number if currently attached to a pin, NOT_ATTACHED 190 | * otherwise. 191 | * @see Servo::attach() 192 | */ 193 | int attachedPin() const { return this->pin; } 194 | 195 | private: 196 | int16 pin; 197 | uint16 minPW; 198 | uint16 maxPW; 199 | int16 minAngle; 200 | int16 maxAngle; 201 | 202 | void resetFields(void); 203 | }; 204 | 205 | 206 | 207 | #endif /* _SERVO_H_ */ 208 | -------------------------------------------------------------------------------- /src/xmc/Servo.cpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * The MIT License 3 | * 4 | * Copyright (c) 2010, LeafLabs, LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person 7 | * obtaining a copy of this software and associated documentation 8 | * files (the "Software"), to deal in the Software without 9 | * restriction, including without limitation the rights to use, copy, 10 | * modify, merge, publish, distribute, sublicense, and/or sell copies 11 | * of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be 15 | * included in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 21 | * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 22 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | *****************************************************************************/ 26 | 27 | #if defined(ARDUINO_ARCH_XMC) 28 | 29 | #include "ServoTimers.h" 30 | 31 | uint8_t _ServoCount = 1; // internal counter to check if max numbers of servos is reached 32 | static uint8_t _allowed[MAX_PWM_SERVOS] = ALLOWED_PINS; // internal array to check allowed pwm pins 33 | static uint8_t _servos[MAX_PWM_SERVOS]; // static array of used servo pins for checking 34 | 35 | 36 | /** 37 | * @brief None blocking wait loop. 38 | * 39 | * @param uS microseconds to wait 40 | */ 41 | static void _delayUs(unsigned long uS) 42 | { 43 | unsigned long time_now = micros(); 44 | while (micros() < time_now + uS) 45 | ; 46 | } 47 | 48 | 49 | Servo::Servo() 50 | { 51 | if (_ServoCount <= MAX_PWM_SERVOS ) 52 | { 53 | this->servoIndex = _ServoCount++; 54 | 55 | this->_minAngle = MIN_ANGLE; 56 | this->_maxAngle = MAX_ANGLE; 57 | this->_minPW = MIN_PULSE_WIDTH; 58 | this->_maxPW = MAX_PULSE_WIDTH; 59 | this->_pin = 0; 60 | this->_isActive = false; 61 | this->_pwm = 0; 62 | this->_deg = 0.0; 63 | }else{ 64 | this->servoIndex = INVALID_SERVO; 65 | } 66 | } 67 | 68 | uint8_t Servo::attach(uint8_t pin, uint16_t min, uint16_t max) 69 | { 70 | if (this->servoIndex <= MAX_PWM_SERVOS ) 71 | { 72 | // validate selected pin 73 | bool pin_allowed = false; 74 | for( int i = 0; i < MAX_PWM_SERVOS; i++) 75 | { 76 | // check if pin already in use 77 | if ( _servos[i] == pin) 78 | return INVALID_SERVO; 79 | 80 | // check if selected pin has a pwm unit on the used XMC board 81 | if ( _allowed[i] == pin) 82 | pin_allowed = true; 83 | } 84 | // return if pin is not found in allowed pin list 85 | if ( !pin_allowed ) 86 | return INVALID_SERVO; 87 | 88 | // Set min/max values according the input and check for absolute limits 89 | if (min < MIN_PULSE_CHECK) 90 | { 91 | this->_minAngle = constrain(min,MIN_ANGLE,MAX_ANGLE); 92 | this->_minPW = MIN_PULSE_WIDTH; 93 | } else { 94 | this->_minAngle = MIN_ANGLE; //TODO has to calculated 95 | this->_minPW = constrain(min,MIN_PULSE_WIDTH,MAX_PULSE_WIDTH); 96 | } 97 | 98 | if (max < MIN_PULSE_CHECK) 99 | { 100 | this->_maxAngle = constrain(max,MIN_ANGLE,MAX_ANGLE); 101 | this->_maxPW = 2 * MAX_PULSE_WIDTH; 102 | } else { 103 | this->_maxAngle = MAX_ANGLE; //TODO has to calculated 104 | this->_maxPW = constrain(max,MIN_PULSE_WIDTH,MAX_PULSE_WIDTH); 105 | } 106 | 107 | this->_pin = pin; 108 | this->_isActive = true; 109 | 110 | setAnalogWriteFrequency(this->_pin, REFRESH_FREQUENCY); 111 | analogWriteResolution(ADC_RESOLUTION); 112 | 113 | } 114 | 115 | return this->servoIndex; 116 | } 117 | 118 | 119 | void Servo::detach() 120 | { 121 | this->servoIndex = _ServoCount--; 122 | 123 | this->_minAngle = MIN_ANGLE; 124 | this->_maxAngle = MAX_ANGLE; 125 | this->_minPW = MIN_PULSE_WIDTH; 126 | this->_maxPW = MAX_PULSE_WIDTH; 127 | 128 | this->_pin = 0; 129 | this->_isActive = false; 130 | this->_pwm = 0; 131 | this->_deg = 0.0; 132 | } 133 | 134 | void Servo::write(int value) 135 | { 136 | if (value < MIN_PULSE_CHECK) 137 | { 138 | // angle must be inside the boundaries 139 | double angle = constrain(value, this->_minAngle, this->_maxAngle); 140 | double dutyCycle = ( 0.5 + ( angle / MAX_ANGLE ) * 2.0 ) * DUTYCYCLE_STEPS; 141 | 142 | this->_deg = angle; 143 | this->_pwm = uint16_t(dutyCycle); 144 | 145 | analogWrite(this->_pin, uint16_t(dutyCycle)); 146 | _delayUs(50); 147 | } else { 148 | writeMicroseconds(value); 149 | } 150 | } 151 | 152 | void Servo::writeMicroseconds(int value) 153 | { 154 | // value must be inside the boundaries 155 | double pw = constrain(value,this->_minPW, this->_maxPW); 156 | double dutyCycle = map(pw, MIN_PULSE_WIDTH,MAX_PULSE_WIDTH, 0.5 * DUTYCYCLE_STEPS, 2.5 * DUTYCYCLE_STEPS); 157 | 158 | this->_deg = ( dutyCycle - DUTYCYCLE_STEPS * 0.5 ) * MAX_ANGLE / ( 2 * DUTYCYCLE_STEPS ); 159 | this->_pwm = uint16_t(dutyCycle); 160 | 161 | analogWrite(this->_pin, uint16_t(dutyCycle)); 162 | _delayUs(50); 163 | } 164 | 165 | #endif 166 | -------------------------------------------------------------------------------- /src/xmc/ServoTimers.h: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * The MIT License 3 | * 4 | * Copyright (c) 2010, LeafLabs, LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person 7 | * obtaining a copy of this software and associated documentation 8 | * files (the "Software"), to deal in the Software without 9 | * restriction, including without limitation the rights to use, copy, 10 | * modify, merge, publish, distribute, sublicense, and/or sell copies 11 | * of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be 15 | * included in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 21 | * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 22 | * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 23 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | *****************************************************************************/ 26 | 27 | /* 28 | * @copyright Copyright (c) 2019-2020 Infineon Technologies AG 29 | */ 30 | #ifndef _SERVO_H_ 31 | #define _SERVO_H_ 32 | 33 | #include 34 | #include "wiring_analog.h" 35 | 36 | /* 37 | * Note on Arduino compatibility: 38 | * 39 | * In the Arduino implementation, PWM is done "by hand" in the sense 40 | * that timer channels are hijacked in groups and an ISR is set which 41 | * toggles Servo::attach()ed pins using digitalWrite(). 42 | * 43 | * While this scheme allows any pin to drive a servo, it chews up 44 | * cycles and complicates the programmer's notion of when a particular 45 | * timer channel will be in use. 46 | * 47 | * This implementation only allows Servo instances to attach() to pins 48 | * that already have PWM unit associated with them, which drives the wave. 49 | * 50 | * While the Arduino implementation of attach() returns the affected channel, 51 | * this one returns the index number of the servo or an INVALID_SERVO = 255 in 52 | * case of an error. 53 | * The attach will check if a pin is already in use and if a pin has a PWM unit on 54 | * the selected XMC board, otherwise it returns an INVALID_SERVO. 55 | * This error handling is different than the original one from Arduino. 56 | * 57 | * Depending on the XMC type the number of possible PWM channels vary from 4 to 23 58 | * and may change with future version of the XMC series. 59 | */ 60 | 61 | // Define the MAX_PWM_SERVOS number per XMC type and the allowed PWM pins on the selected XMC board 62 | #if defined(XMC1100_XMC2GO) 63 | #define MAX_PWM_SERVOS 4 64 | #define ALLOWED_PINS {1, 2, 3, 8,} 65 | #elif defined(XMC1100_Boot_Kit) 66 | #define MAX_PWM_SERVOS 6 67 | #define ALLOWED_PINS { 3,4,6,9,10,11 } 68 | #elif defined(XMC1300_Boot_Kit) 69 | #define MAX_PWM_SERVOS 4 70 | #define ALLOWED_PINS { 26,31,32,33 } 71 | #elif defined(XMC1400_Arduino_Kit) 72 | #define MAX_PWM_SERVOS 6 73 | #define ALLOWED_PINS { 3,4,6,9,10,11 } 74 | #elif defined(XMC4200_Platform2GO) 75 | #define MAX_PWM_SERVOS 7 76 | #define ALLOWED_PINS { 3,5,6,9,22,23,24 } 77 | #elif defined(XMC4400_Platform2GO) 78 | #define MAX_PWM_SERVOS 15 79 | #define ALLOWED_PINS { 3,5,6,9,10,14,25,26,27,28,29,30,45,48,67 } 80 | #elif defined(XMC4700_Relax_Kit) 81 | #define MAX_PWM_SERVOS 23 82 | #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 } 83 | #else 84 | #error "Not a supported XMC Board" 85 | #endif 86 | 87 | #define MIN_ANGLE 0 // the minimal angle in degree 88 | #define MAX_ANGLE 180 // the maximal angle in degree 89 | #define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo in microseconds 90 | #define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo in microseconds 91 | 92 | #define MIN_PULSE_CHECK 500 // border with below = angle and above = pulse width 93 | #define REFRESH_FREQUENCY 50u // the refresh frequency on analog pins 94 | #define REFRESH_TIME 20.0 // the PWM refresh frequency for the servo motor 95 | #define DUTYCYCLE_STEPS 65536.0 / REFRESH_TIME // the number of duty cycle steps during one refresh period 96 | #define ADC_RESOLUTION 16 // the resolution of the adc during analog write 97 | 98 | #define INVALID_SERVO 255 // flag indicating an invalid servo index 99 | 100 | /** Class for interfacing with RC servomotors. */ 101 | class Servo 102 | { 103 | public: 104 | /** 105 | * @brief Construct a new Servo instance. 106 | * 107 | * The new instance will not be attached to any pin, but only PWM capable pins will run. 108 | * see pin list above. 109 | */ 110 | Servo(); 111 | 112 | /** 113 | * @brief Associate this instance with a servomotor whose input is 114 | * connected to pin. 115 | * 116 | * If this instance is already attached to a pin, it will be 117 | * detached before being attached to the new pin. 118 | * If the pin is not allowed for running PWM or the max number of 119 | * PWM channels on the XMC board is reached it will return 120 | * with an INVALID_SERVO, otherwise with the servoIndex number. 121 | * 122 | * @param pin Pin connected to the servo pulse wave input. This 123 | * pin must be capable of PWM output. 124 | * 125 | * @param min If this value is below MIN_PULSE_CHECK it will be associated 126 | * with an angle in degree. Otherwise it will be the minimum 127 | * pulse width. 128 | * min as an angle must be between MIN_ANGLE < angle < MAX_ANGLE 129 | * with default as MIN_ANGLE 130 | * min as a pulse width must be between MIN_PULSE_WIDTH < pwm < MAX_PULSE_WIDTH 131 | * with a default as MIN_PULSE_WIDTH 132 | * 133 | * @param max If this value is below MIN_PULSE_CHECK it will be associated 134 | * with an angle in degree. Otherwise it will be the maximum 135 | * pulse width. 136 | * max as an angle must be between MIN_ANGLE < angle < MAX_ANGLE 137 | * with default as MAX_ANGLE 138 | * max as a pulse width must be between MIN_PULSE_WIDTH < pwm < MAX_PULSE_WIDTH 139 | * with a default as MAX_PULSE_WIDTH 140 | * 141 | * @return servoIndex number or INVALID_SERVO = 255 in case of an error 142 | */ 143 | uint8_t attach(uint8_t pin, uint16_t min = MIN_ANGLE, uint16_t max = MAX_ANGLE); 144 | 145 | 146 | /** 147 | * @brief Stop driving the servo pulse train. 148 | * 149 | * If not currently attached to a motor, this function has no effect. 150 | * 151 | * @return true if this call did anything, false otherwise. 152 | */ 153 | void detach(); 154 | 155 | /** 156 | * @brief Set the servomotor target angle by recalculating the duty cycle 157 | * for XMC PWM settings. 158 | * 159 | * @param value Target angle, in degrees. If the target angle is 160 | * outside the range specified at attach(), it 161 | * will be clamped to lie in that range. 162 | * 163 | * @see Servo::attach() 164 | */ 165 | void write(int value); 166 | 167 | /** 168 | * @brief Set the pulse width, in microseconds by recalculating it for the 169 | * XMC PWM settings. It also calculates the angle from the pwm value. 170 | * 171 | * @param value Pulse width to send to the servomotor, in 172 | * microseconds. If outside of the range 173 | * specified at attach() time, it is clamped to 174 | * lie in that range. 175 | * 176 | * @see Servo::attach() 177 | */ 178 | void writeMicroseconds(int value); 179 | 180 | /** 181 | * returns the current value in degree as an angle between 0 and 189 degrees 182 | * 183 | * @see Servo::attach() 184 | */ 185 | int read() const { return uint16_t(this->_deg); } 186 | 187 | /** 188 | * returns the current pwm value in microseconds. 189 | * 190 | * @see Servo::attach() 191 | */ 192 | int readMicroseconds() const { return uint16_t(this->_pwm); } 193 | 194 | /** 195 | * @brief Check if this instance is attached to a servo. 196 | * @return true if this instance is attached to a servo, false otherwise. 197 | * @see Servo::attachedPin() 198 | */ 199 | bool attached() const { return this->_isActive; } 200 | 201 | private: 202 | uint16_t _minPW; // the initial minPulseWidth, if not set than MIN_PULSE_WIDTH 203 | uint16_t _maxPW; // the initial maxPulseWidth, if not set than MAX_PULSE_WIDTH 204 | int16_t _minAngle; // the initial minAngle, if not set than MIN_ANGLE 205 | int16_t _maxAngle; // the initial maxAngle, if not set than MAX_ANGLE 206 | int16_t _pin; // attached arduino pin number 207 | double _deg; // actual angle in degree 208 | double _pwm; // actual pwm signal in microseconds 209 | uint8_t _isActive; // true if this pin is active, otherwise false 210 | 211 | uint8_t servoIndex; // the actual number of Servos attached to this library 212 | 213 | 214 | }; 215 | 216 | #endif /* _SERVO_H_ */ 217 | --------------------------------------------------------------------------------