├── LICENSE ├── README.md ├── examples ├── Acceleration │ └── Acceleration.ino ├── Basic │ └── Basic.ino ├── ClassMethodLambdaCallback │ └── ClassMethodLambdaCallback.ino ├── CommonCallbackHandler │ └── CommonCallbackHandler.ino ├── DisableEncoderButton │ └── DisableEncoderButton.ino ├── LongPressExample │ └── LongPressExample.ino └── MultiButton │ └── MultiButton.ino ├── images ├── button.jpg ├── encoder-button.jpg └── mpg.jpg ├── keywords.txt ├── library.json ├── library.properties └── src ├── EncoderButton.cpp └── EncoderButton.h /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 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 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EncoderButton 2 | 3 | > **The new version of EncoderButton can now be found in the [InputEvents library](https://github.com/Stutchbury/InputEvents).** 4 | 5 | 6 | A comprehensive Rotary Encoder & Button library that makes working with rotary encoders (with or without a button) and individual buttons very efficient. 7 | 8 | * Read the position & encoder increment for pressed and non-pressed actions. 9 | * Rate limit the encoder events without losing steps (eg for easy acceleration or to reduce events sent over Serial). 10 | * Multi-click events (single, double, triple - however many you want). 11 | * Optional long press repeat. 12 | * Many other events are fired (see below). 13 | 14 | It is effectively an event wrapper for Paul Stoffregen's [Encoder library](https://www.pjrc.com/teensy/td_libs_Encoder.html) & Thomas Fredericks' [Bounce2 library](https://github.com/thomasfredericks/Bounce2) and inspired by Lennart Hennigs [Button2 library](https://github.com/LennartHennigs/Button2) 15 | 16 | Huge thanks to all of the above - I am standing on the shoulders of giants. 17 | 18 | Use any or all combinations of these: 19 | 20 | ![encoder button](images/encoder-button.jpg) and/or ![MPG encoder](images/mpg.jpg) and/or ![momentary button](images/button.jpg) 21 | 22 | 23 | 24 | ## INSTALLATION & DOWNLOAD 25 | Install via the Arduino Library Manager or download from [github](https://github.com/Stutchbury/EncoderButton). 26 | 27 | ## BASIC USAGE 28 | 29 | ### INSTANTIATE 30 | 31 | ```cpp 32 | #include 33 | EncoderButton eb1(, , ); 34 | 35 | // Create one or more callback functions 36 | void onEb1Encoder(EncoderButton& eb) { 37 | Serial.print("eb1 incremented by: "); 38 | Serial.println(eb.increment()); 39 | Serial.print("eb1 position is: "); 40 | Serial.println(eb.position()); 41 | } 42 | ``` 43 | 44 | ### SETUP 45 | 46 | ```cpp 47 | // Link event to function defined above 48 | eb1.setEncoderHandler(onEb1Encoder); 49 | ``` 50 | ### LOOP 51 | 52 | ```cpp 53 | // Call 'update' for every EncoderButton 54 | eb1.update(); 55 | ``` 56 | 57 | ## Constructors 58 | 59 | Construct a rotary encoder with a button 60 | ```cpp 61 | EncoderButton(byte encoderPin1, byte encoderPin2, byte switchPin); 62 | ``` 63 | Construct a rotary encoder without a button 64 | ```cpp 65 | EncoderButton(byte encoderPin1, byte encoderPin2); 66 | ``` 67 | Construct a button only 68 | ```cpp 69 | EncoderButton(byte switchPin); 70 | ``` 71 | 72 | ## Loop method 73 | 74 | There is only one method to be called from loop but it must be called for each defined ```EncoderButton```. 75 | 76 | **```void update()```** reads the position of the encoder and updates the state of the button. This will fire the appropriate handlers. 77 | 78 | ## Setup methods 79 | 80 | Normally called from within ```setup()``` but can be updated at runtime. 81 | 82 | ### Setting button callback handlers 83 | 84 | Each of these methods (optionally) sets the function to be called on the event being fired. 85 | 86 | They all take a single argument of your function name (except ```setLongPressHandler``` which takes and optional ```bool``` to repeatedly fire or not). 87 | 88 | For an ESP8288/32 or Teensy you can also pass a class method - see ```ClassMethodLambdaCallback.ino``` in the examples. 89 | 90 | **```setChangedHandler```** fires when button state changes: 91 | Rarely used - try 'pressed', 'released' or 'clicked' first. 92 | 93 | **```setPressedHandler```** fires after button is pressed down: 94 | 95 | **```setReleasedHandler```** fires after button is released: 96 | Note: if the encoder is turned while pressed, then 97 | the 'encoder released' callback is fired instead. 98 | 99 | **```setClickHandler```** fires after button is clicked (when pressed duration is less than setLongClickDuration() (default 750ms) 100 | Note: the number of multi clicks can be read from EncoderButton.clickCount() in the callback so you are not limited to double or triple clicks - any number can be actioned. 101 | If double or triple click callbacks are set, this will not be fired for those events. 102 | 103 | **```setDoubleClickHandler```** fires after button is double clicked 104 | Determined by ```setMultiClickInterval()``` (default 250ms) 105 | Syntactic sugar for click handler + clickCount == 2 106 | 107 | **```setTripleClickHandler```** fires when button is triple clicked 108 | Syntactic sugar for click handler + clickCount == 3 109 | 110 | **```setLongClickHandler```** fires *after* button is long clicked (ie when pressed duration is greater than ```setLongClickDuration(ms)``` (default 750ms) 111 | See also long press handler 112 | 113 | **```setLongPressHandler```** fired *while* button is long pressed. 114 | By default, this fires once but can fire every ```setLongClickDuration()``` by passing 'true' as a second argument to ```setLongPressHandler()``` or by setting ```setLongPressRepeat()``` to true. 115 | Use ```longPressCount()``` in callback to read the number of times fired. 116 | 117 | 118 | ### Setting encoder callback handlers 119 | 120 | As per buttons, each of these methods (optionally) sets the function to be called on the event being fired. They all take a single argument of your function name. 121 | 122 | **```setEncoderHandler```** fires when the encoder is turned. By default is fired once per 'click' but can fire full quadrature encoding if ```useQuadPrecision()``` is set to 'true' 123 | 124 | **```setEncoderPressedHandler```** fires when the encoder is turned while pressed. 125 | 126 | **```setEncoderReleasedHandler```** fires after encoder is released *and turned* (if not turned the button 'released' handler is fired). 127 | 128 | 129 | **```setIdleHandler```** fires after the encoder or button has been idle for ```setIdleTimeout(ms)``` (default 10 seconds). 130 | 131 | ### Button settings 132 | 133 | **```setDebounceInterval(unsigned int intervalMs)```** - default is set in the Bounce2 library (currently 10ms) 134 | 135 | **```setMultiClickInterval(unsigned int intervalMs)```** - set the interval (in ms) between double, triple or multi clicks. 136 | 137 | **```setLongClickDuration(unsigned int longDurationMs)```** - set the ms that defines a long click. 138 | Long pressed callback will be fired at this interval if repeat is set to true via the ```setLongPressHandler()``` second argument or ```setLongPressRepeat()```. 139 | 140 | **```setLongPressRepeat(bool repeat=false)```** - choose whether to repeat the long press callback (default is 'false'). 141 | 142 | ### Encoder settings 143 | 144 | **```setRateLimit(long ms)```** Encoder callbacks are normally fired on every loop() but for MPG style encoders this can fire a huge number of events (that may for example, swamp a serial connection). 145 | The encoder interupts will still be called but this setting will limit the call back firing to every set ms - read the ```EncoderButton.increment()``` for lossless counting of encoder. 146 | This is also how you can easily implement acceleration - simply set an appropriate rate limit and then multiply ```increment() * increment()``` in your callback function. 147 | Set to zero (default) for no rate limit. 148 | 149 | **```useQuadPrecision(bool prec)```** Quadrature encoders have four states for each 'click' of the rotary switch. By default we only fire once per click. 150 | Set this to 'true' if you want four events per click. 151 | Affects both pressed+turning and no-pressed-turning. 152 | 153 | **```resetPosition(long pos = 0)```** Reset the counted position of the encoder. 154 | 155 | **```resetPressedPosition(long pos = 0)```** Reset the counted pressed position of the encoder. 156 | 157 | ### Setting idle timeout 158 | 159 | **```setIdleTimeout(unsigned int timeoutMs)```** Set the idle timeout in ms (default 10000) 160 | 161 | ### Setting id or user state 162 | 163 | **```setUserId(unsigned int identifier)```** Set a user defined value to identify this button. Does not have to be unique (defaults to 0). Useful when multiple buttons call the same handler. 164 | 165 | **```setUserState(unsigned int state)```** Set a user defined state for this button. Eg enum for ON, OFF, INACTIVE etc. Not used by the library. 166 | 167 | ### Read button state 168 | 169 | From within your callback function. 170 | 171 | **```buttonState()```** Directly get the current button state from Bounce2. 172 | 173 | **```unsigned long currentDuration()```** Directly get the duration of the button current state from Bounce2. 174 | 175 | **```unsigned long previousDuration()```** Directly get the duration of the button previous state from Bounce2. 176 | 177 | **```unsigned char clickCount()```** The number of multi-clicks that have been fired in the clicked event. 178 | 179 | **```uint8_t longPressCount()```** The number of times the long press handler has been fired in the button pressed event 180 | 181 | ### Read encoder state 182 | 183 | From within your callback function 184 | 185 | **```int16_t increment()```** Returns a positive (CW) or negative (CCW) integer. Is normally 1 or -1 but if your loop() has lots of processing, your Arduino is slow or you ```setRateLimit()``` this will return the actual number of increments made by the encoder since the last encoder handler event. 186 | 187 | **```long position()```** The current position of the encoder. Can be reset by ```resetPosition()```. 188 | 189 | **```long pressedPosition()```** The current position of the encoder when pressed. Can be reset by ```resetPressedPosition()```. 190 | 191 | ### Timeout 192 | **```unsigned long msSinceLastEvent()```** Returns the number of ms since any event was fired for this encoder/button. 193 | 194 | ### Getting user id or user state 195 | 196 | **```unsigned int userId()```** Return the user defined value that identifies this button. May not be unique. 197 | 198 | **```unsigned int userState()```** Returns the user defined state for this button. 199 | 200 | ### Enabling/disabling the EncoderButton 201 | 202 | **```void enable(bool=true)```** Disabling the EncoderButton will prevent all events firing and also stop incrementing the encoder position. Pass ```true``` to enable (default) or ```false``` to disable. 203 | 204 | **```bool enabled()```** Returns ```true``` if enabled or ```false``` if disabled. -------------------------------------------------------------------------------- /examples/Acceleration/Acceleration.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * Example of using the EncoderButton library to accelerate. 3 | */ 4 | #include 5 | 6 | /** 7 | * Instatiate an EncoderButton. 8 | * For Arduino Uno, the hardware interrupts are pins 2 & 3 9 | * For Teensy, you can use any digital pin. 10 | */ 11 | EncoderButton eb1(2, 3); //Two args means encoder only but will work for an encoder with a button too. 12 | 13 | int myValue = 0; 14 | 15 | 16 | /** 17 | * A function to handle the 'encoder' event 18 | */ 19 | void onEb1Encoder(EncoderButton& eb) { 20 | myValue += eb.increment()*abs(eb.increment()); 21 | Serial.print("eb1 incremented by: "); 22 | Serial.print(eb.increment()); 23 | Serial.print(" accelerated to: "); 24 | Serial.print(eb.increment()*abs(eb.increment())); 25 | Serial.print(" myValue is now: "); 26 | Serial.println(myValue); 27 | } 28 | 29 | void setup() { 30 | // put your setup code here, to run once: 31 | Serial.begin(9600); 32 | delay(500); 33 | Serial.println("EncoderButton Acceleration Example"); 34 | 35 | //Link the event(s) to your function 36 | eb1.setEncoderHandler(onEb1Encoder); 37 | //Set the rate limit on your encoder. 38 | eb1.setRateLimit(200); 39 | //If set to 200 milliseconds, the increment() will be > 1 if the encoder rotation clicks more than 5 time/second 40 | } 41 | 42 | void loop() { 43 | // put your main code here, to run repeatedly: 44 | // You must call update() for every defined EncoderButton. 45 | // This will update the state of the encoder & button and 46 | // fire the appropriate events. 47 | eb1.update(); 48 | } 49 | -------------------------------------------------------------------------------- /examples/Basic/Basic.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * A basic example of using the EncoderButton library. 3 | */ 4 | #include 5 | 6 | /** 7 | * Instatiate an EncoderButton. 8 | * For Arduino Uno, the hardware interrupts are pins 2 & 3 9 | * For Teensy, you can use any digital pin. 10 | * Probably better to pick a more meaningful name than 'eb1'... 11 | * Encoder+button: 12 | * EncoderButton(byte encoderPin1, byte encoderPin2, byte switchPin); 13 | * Encoder only: 14 | * EncoderButton(byte encoderPin1, byte encoderPin2); 15 | * Button only: 16 | * EncoderButton(byte switchPin); 17 | */ 18 | EncoderButton eb1(2, 3, 4); 19 | 20 | 21 | /** 22 | * A function to handle the 'clicked' event 23 | * Can be called anything but requires EncoderButton& 24 | * as its only parameter. 25 | * I tend to prefix with 'on' and suffix with the 26 | * event type. 27 | */ 28 | void onEb1Clicked(EncoderButton& eb) { 29 | Serial.print("eb1 clickCount: "); 30 | Serial.println(eb.clickCount()); 31 | } 32 | 33 | /** 34 | * A function to handle the 'encoder' event 35 | */ 36 | void onEb1Encoder(EncoderButton& eb) { 37 | Serial.print("eb1 incremented by: "); 38 | Serial.println(eb.increment()); 39 | Serial.print("eb1 position is: "); 40 | Serial.println(eb.position()); 41 | } 42 | 43 | void setup() { 44 | // put your setup code here, to run once: 45 | Serial.begin(9600); 46 | delay(500); 47 | Serial.println("EncoderButton Basic Example"); 48 | 49 | //Link the event(s) to your function 50 | eb1.setClickHandler(onEb1Clicked); 51 | eb1.setEncoderHandler(onEb1Encoder); 52 | } 53 | 54 | void loop() { 55 | // put your main code here, to run repeatedly: 56 | // You must call update() for every defined EncoderButton. 57 | // This will update the state of the encoder & button and 58 | // fire the appropriat events. 59 | eb1.update(); 60 | } 61 | -------------------------------------------------------------------------------- /examples/ClassMethodLambdaCallback/ClassMethodLambdaCallback.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * Example using the EncoderButton library with a class method 3 | * as a the callback function. 4 | * **NOTE** Only available for ESP8266/32 and Teensy 5 | */ 6 | #include 7 | 8 | /** 9 | * Instatiate an EncoderButton. 10 | * For Teensy, you can use any digital pin. 11 | */ 12 | EncoderButton eb1(6,7,8); 13 | 14 | /** 15 | * A noddy class for this example 16 | */ 17 | class Foo { 18 | 19 | public: 20 | /** 21 | * A class method to handle the 'clicked' event 22 | * Can be called anything but requires EncoderButton& 23 | * as its only parameter. 24 | * 25 | */ 26 | void onEb1Clicked(EncoderButton& eb) { 27 | Serial.print("eb1 clickCount: "); 28 | Serial.println(eb.clickCount()); 29 | } 30 | 31 | /** 32 | * A class method to handle the 'encoder' event 33 | */ 34 | void onEb1Encoder(EncoderButton& eb) { 35 | Serial.print("eb1 incremented by: "); 36 | Serial.println(eb.increment()); 37 | Serial.print("eb1 position is: "); 38 | Serial.println(eb.position()); 39 | } 40 | 41 | }; 42 | 43 | /** 44 | * Instantiate the class 45 | */ 46 | Foo foo; 47 | 48 | 49 | void setup() { 50 | // put your setup code here, to run once: 51 | Serial.begin(9600); 52 | delay(500); 53 | Serial.println("EncoderButton Class Method Callback Example"); 54 | 55 | //Link the event(s) to your class method 56 | //Not quite as simple as a static function 57 | eb1.setClickHandler([&](EncoderButton &btn) { 58 | foo.onEb1Clicked(btn); 59 | }); 60 | 61 | // And the encoder event 62 | eb1.setEncoderHandler([&](EncoderButton &btn) { 63 | foo.onEb1Encoder(btn); 64 | }); 65 | 66 | } 67 | 68 | void loop() { 69 | // put your main code here, to run repeatedly: 70 | // You must call update() for every defined EncoderButton. 71 | // This will update the state of the encoder & button and 72 | // fire the appropriate events. 73 | eb1.update(); 74 | } 75 | -------------------------------------------------------------------------------- /examples/CommonCallbackHandler/CommonCallbackHandler.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * An example of using a common callback for an event in the EncoderButton library 3 | * Can be used for multi-function buttons (ie button actions are changed at runtime). 4 | * 5 | * **NOTE** 6 | * I am using buttons as this works well on all devices but the same principle applies to 7 | * encoders (multiple encoders work well on Teensies, not so much on UNOs. 8 | * See https://www.pjrc.com/teensy/td_libs_Encoder.html for why. 9 | * 10 | * Also note: I am using an array to store the button (or encoder) instances but this is 11 | * not required. 12 | * 13 | */ 14 | #include 15 | 16 | /** 17 | * Instatiate multiple EncoderButtons. We're using just buttons here but the same applies 18 | * to encoders or encoders+buttons. 19 | */ 20 | EncoderButton buttonRow[5] = { EncoderButton(28), EncoderButton(27), EncoderButton(26), EncoderButton(25), EncoderButton(24) }; 21 | 22 | 23 | /** 24 | * A common function to handle the 'clicked' event of all buttons. 25 | */ 26 | void onButtonRowClicked(EncoderButton& eb) { 27 | Serial.print("button "); 28 | Serial.print(eb.userId()); 29 | Serial.print(" clickCount: "); 30 | Serial.println(eb.clickCount()); 31 | } 32 | 33 | 34 | void setup() { 35 | // put your setup code here, to run once: 36 | Serial.begin(9600); 37 | delay(500); 38 | Serial.println("EncoderButton common callback handler example"); 39 | 40 | //Loop through the array of encoder buttons. 41 | for ( uint8_t b=0; b<5; b++ ) { 42 | // Give each button a userId - this defaults to 0 so 43 | // must be set if you want to identify a button in the callback. 44 | buttonRow[b].setUserId(b); 45 | // Set all buttons in the button row to use the same handler 46 | buttonRow[b].setClickHandler(onButtonRowClicked); 47 | } 48 | } 49 | 50 | void loop() { 51 | //Update all buttons/encoders 52 | for ( uint8_t b=0; b<5; b++ ) { 53 | buttonRow[b].update(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /examples/DisableEncoderButton/DisableEncoderButton.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * A basic example of enabling or disabling an EncoderButton. 3 | */ 4 | #include 5 | 6 | /** 7 | * Instantiate an EncoderButton. 8 | * For Arduino Uno, the hardware interrupts are pins 2 & 3 9 | * For Teensy, you can use any digital pin. 10 | * 11 | * I've set this us as an encoder only because I'm using the 12 | * button to toggle enable/disable. 13 | */ 14 | EncoderButton eb1(2, 3); 15 | 16 | 17 | /** 18 | * Instantiate the button to enable or disable the encoder above 19 | */ 20 | EncoderButton sw1(4); 21 | 22 | 23 | /** 24 | * A function to handle the 'clicked' event 25 | * Can be called anything but requires EncoderButton& 26 | * as its only parameter. 27 | * I tend to prefix with 'on' and suffix with the 28 | * event type. 29 | */ 30 | void onSw1Clicked(EncoderButton& eb) { 31 | //Toggle enable for the encoder eb1 32 | //Note: this is not the EncoderButton 'eb' passed to the function. 33 | eb1.enabled() ? eb1.enable(false) : eb1.enable(); 34 | } 35 | 36 | /** 37 | * A function to handle the 'encoder' event 38 | */ 39 | void onEb1Encoder(EncoderButton& eb) { 40 | //To show the increment is not changed while disabled. 41 | Serial.print("eb1 incremented by: "); 42 | Serial.println(eb.increment()); 43 | Serial.print("eb1 position is: "); 44 | Serial.println(eb.position()); 45 | } 46 | 47 | void setup() { 48 | // put your setup code here, to run once: 49 | Serial.begin(9600); 50 | delay(500); 51 | Serial.println("EncoderButton Enable/Disable Example"); 52 | 53 | //Link the event(s) to your function 54 | sw1.setClickHandler(onSw1Clicked); 55 | eb1.setEncoderHandler(onEb1Encoder); 56 | } 57 | 58 | void loop() { 59 | // put your main code here, to run repeatedly: 60 | // You must call update() for every defined EncoderButton. 61 | // This will update the state of the encoder & button and 62 | // fire the appropriate events. 63 | sw1.update(); 64 | eb1.update(); 65 | } 66 | -------------------------------------------------------------------------------- /examples/LongPressExample/LongPressExample.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * Example of using the EncoderButton long press repeat. 3 | */ 4 | #include 5 | 6 | /** 7 | * Instatiate an EncoderButton. 8 | * For Arduino Uno, the hardware interrupts are pins 2 & 3 9 | * For Teensy, you can use any digital pin. 10 | */ 11 | EncoderButton button1(4); //Single arg means button only but will work the same with the button on an encoder 12 | 13 | 14 | /** 15 | * A function to handle the 'clicked' event 16 | * Can be called anything but requires EncoderButton& 17 | * as its only parameter. 18 | * I tend to prefix with 'on' and suffix with the 19 | * event type. 20 | */ 21 | void onButton1LongPress(EncoderButton& eb) { 22 | Serial.print("button1 longPressCount: "); 23 | Serial.println(eb.longPressCount()); 24 | } 25 | 26 | void setup() { 27 | // put your setup code here, to run once: 28 | Serial.begin(9600); 29 | delay(500); 30 | Serial.println("EncoderButton Long Press Repeat Example"); 31 | 32 | //Link the event(s) to your function 33 | button1.setLongPressHandler(onButton1LongPress, true); //Second arg means repeat the long click 34 | } 35 | 36 | void loop() { 37 | // put your main code here, to run repeatedly: 38 | // You must call update() for every defined EncoderButton. 39 | // This will update the state of the encoder & button and 40 | // fire the appropriat events. 41 | button1.update(); 42 | } 43 | -------------------------------------------------------------------------------- /examples/MultiButton/MultiButton.ino: -------------------------------------------------------------------------------- 1 | /** 2 | * This example demostrates how to create multiple encoders or buttons. 3 | * 4 | * ** NOTE ** 5 | * This example uses a single encoder and multiple buttons because UNOs and other Arduinos 6 | * with limited hardware interrupts will struggle to perform well (read: reliably) with 7 | * multiple encoders. 8 | * ** Teensys will handle multiple encoders without any issues *** (they have hardware 9 | * interupts on all digital pins). 10 | * See https://www.pjrc.com/teensy/td_libs_Encoder.html for details. 11 | * 12 | */ 13 | #include 14 | 15 | /** 16 | * Instatiate an EncoderButton. 17 | * For Arduino Uno, the hardware interrupts are pins 2 & 3 18 | * For Teensy, you can use any digital pin. 19 | */ 20 | EncoderButton firstEncoderButton(2, 3, 4); 21 | EncoderButton secondButton(14); //The first button is on the encoder! 22 | //. . . 23 | EncoderButton nthButton(15); 24 | 25 | 26 | /** 27 | * A function to handle the first encoder 'encoder' event 28 | */ 29 | void onFirstEncoder(EncoderButton& eb) { 30 | Serial.print("first encoder incremented by: "); 31 | Serial.println(eb.increment()); 32 | Serial.print("first encoder position is: "); 33 | Serial.println(eb.position()); 34 | } 35 | 36 | /** 37 | * A function to handle the first encoder 'clicked' event 38 | */ 39 | void onFirstButtonClicked(EncoderButton& eb) { 40 | Serial.print("First button clickCount: "); 41 | Serial.println(eb.clickCount()); 42 | } 43 | 44 | 45 | /** 46 | * A function to handle the second button 'clicked' event 47 | */ 48 | void onSecondButtonClicked(EncoderButton& eb) { 49 | Serial.print("Second button clickCount: "); 50 | Serial.println(eb.clickCount()); 51 | } 52 | 53 | /** 54 | * A function to handle the second button 'clicked' event 55 | */ 56 | void onNthButtonClicked(EncoderButton& eb) { 57 | Serial.print("Nth button clickCount: "); 58 | Serial.println(eb.clickCount()); 59 | } 60 | 61 | void setup() { 62 | // put your setup code here, to run once: 63 | Serial.begin(9600); 64 | delay(500); 65 | Serial.println("EncoderButton multiple encoder/button example"); 66 | 67 | //Link the event(s) to your function 68 | firstEncoderButton.setEncoderHandler(onFirstEncoder); 69 | firstEncoderButton.setClickHandler(onFirstButtonClicked); 70 | secondButton.setClickHandler(onSecondButtonClicked); 71 | nthButton.setClickHandler(onNthButtonClicked); 72 | 73 | 74 | 75 | } 76 | 77 | void loop() { 78 | // put your main code here, to run repeatedly: 79 | // You must call update() for every defined EncoderButton. 80 | firstEncoderButton.update(); 81 | secondButton.update(); 82 | nthButton.update(); 83 | } 84 | -------------------------------------------------------------------------------- /images/button.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stutchbury/EncoderButton/654f02d330eae00e382473acfa7feb2c6e1b3442/images/button.jpg -------------------------------------------------------------------------------- /images/encoder-button.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stutchbury/EncoderButton/654f02d330eae00e382473acfa7feb2c6e1b3442/images/encoder-button.jpg -------------------------------------------------------------------------------- /images/mpg.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stutchbury/EncoderButton/654f02d330eae00e382473acfa7feb2c6e1b3442/images/mpg.jpg -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | EncoderButton KEYWORD1 4 | CallbackFunction KEYWORD1 5 | 6 | update KEYWORD2 7 | 8 | setChangedHandler KEYWORD2 9 | setPressedHandler KEYWORD2 10 | setReleasedHandler KEYWORD2 11 | setClickHandler KEYWORD2 12 | setDoubleClickHandler KEYWORD2 13 | setTripleClickHandler KEYWORD2 14 | setLongClickHandler KEYWORD2 15 | setLongPressHandler KEYWORD2 16 | 17 | setEncoderHandler KEYWORD2 18 | setEncoderPressedHandler KEYWORD2 19 | setEncoderReleasedHandler KEYWORD2 20 | 21 | setIdleHandler KEYWORD2 22 | 23 | setUserId KEYWORD2 24 | setUserState KEYWORD2 25 | 26 | setDebounceInterval KEYWORD2 27 | setMultiClickInterval KEYWORD2 28 | setLongClickDuration KEYWORD2 29 | setLongPressRepeat KEYWORD2 30 | 31 | setRateLimit KEYWORD2 32 | useQuadPrecision KEYWORD2 33 | resetPosition KEYWORD2 34 | resetPressedPosition KEYWORD2 35 | setIdleTimeout KEYWORD2 36 | 37 | buttonState KEYWORD2 38 | currentDuration KEYWORD2 39 | previousDuration KEYWORD2 40 | clickCount KEYWORD2 41 | longPressCount KEYWORD2 42 | 43 | increment KEYWORD2 44 | position KEYWORD2 45 | pressedPosition KEYWORD2 46 | 47 | msSinceLastEvent KEYWORD2 48 | 49 | userId KEYWORD2 50 | userState KEYWORD2 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "EncoderButton", 3 | "version": "1.0.6", 4 | "description": "Lossless event based rotary encoder+button library for Arduino and Teensy", 5 | "keywords": "encoder, button, momentary, event, debounce", 6 | "repository": 7 | { 8 | "type": "git", 9 | "url": "https://github.com/Stutchbury/EncoderButton.git" 10 | }, 11 | "authors": 12 | [ 13 | { 14 | "name": "Philip Fletcher", 15 | "email": "philip.fletcher@stutchbury.com", 16 | "url": "https://stutchbury.com", 17 | "maintainer": true 18 | } 19 | ], 20 | "license": "GPL-2.0", 21 | "homepage": "https://github.com/Stutchbury/EncoderButton/", 22 | "dependencies": { 23 | "thomasfredericks/Bounce2": "2.71", 24 | "paulstoffregen/Encoder": "1.4.2" 25 | }, 26 | "frameworks": "Arduino", 27 | "platforms": "*" 28 | } -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=EncoderButton 2 | version=1.0.6 3 | author=Philip Fletcher 4 | maintainer=Philip Fletcher 5 | sentence=Lossless event based rotary encoder & button library 6 | paragraph=A comprehensive library that makes working with rotary encoders (with or without a button) and individual buttons very efficient. Read the position & encoder increment for pressed and non-pressed actions. Rate limit the encoder events without losing steps (eg easy acceleration or reduce events sent over Serial). Multi-click events (1-n). Long press repeat. Many other events can be handled. 7 | category=Signal Input/Output 8 | includes=EncoderButton.h 9 | depends=Encoder, Bounce2 10 | url=https://github.com/Stutchbury/EncoderButton 11 | architectures=* 12 | -------------------------------------------------------------------------------- /src/EncoderButton.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * GPLv2 Licence https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt 4 | * 5 | * Copyright (c) 2022 Philip Fletcher 6 | * 7 | */ 8 | 9 | #include "EncoderButton.h" 10 | 11 | 12 | EncoderButton::EncoderButton(byte encoderPin1, byte encoderPin2, byte switchPin ) 13 | : encoder(new Encoder(encoderPin1, encoderPin2)), bounce(new Bounce()) { 14 | haveEncoder = true; 15 | haveButton = true; 16 | // Top tip From PJRC's Encoder - without this delay the 17 | // long-press doesn't fire on first press. 18 | // allow time for a passive R-C filter to charge 19 | // through the pullup resistors, before reading 20 | // the initial state 21 | pinMode(switchPin, INPUT_PULLUP); //Set pullup first 22 | delayMicroseconds(2000); //Delay 23 | bounce->attach(switchPin, INPUT_PULLUP); //then attach button 24 | } 25 | 26 | EncoderButton::EncoderButton(byte encoderPin1, byte encoderPin2 ) 27 | : encoder(new Encoder(encoderPin1, encoderPin2)) { 28 | haveEncoder = true; 29 | } 30 | 31 | EncoderButton::EncoderButton(byte switchPin ) 32 | : bounce(new Bounce()) { 33 | haveButton = true; 34 | pinMode(switchPin, INPUT_PULLUP); //Set pullup first 35 | delayMicroseconds(2000); //Delay 36 | bounce->attach(switchPin, INPUT_PULLUP); //then attach button 37 | } 38 | 39 | void EncoderButton::update() { 40 | if ( _enabled ) { 41 | //button update (fires pressed/released callbacks) 42 | if ( haveButton && bounce->update() ) { 43 | lastEventMs = millis(); 44 | idleFlagged = false; 45 | if (changed_cb != NULL) changed_cb (*this); 46 | _buttonState = bounce->read(); 47 | if ( bounce->fell() ) { 48 | previousState = HIGH; 49 | if (pressed_cb != NULL) pressed_cb (*this); 50 | } else if (bounce->rose() ) { 51 | if ( encodingPressed ) { 52 | encodingPressed = false; 53 | prevClickCount = 0; 54 | clickCounter = 0; 55 | if (encoder_released_cb != NULL) encoder_released_cb (*this); 56 | } else { 57 | if ( previousState == HIGH ) { 58 | clickFired = false; 59 | clickCounter++; 60 | } 61 | if (released_cb != NULL) released_cb (*this); 62 | } 63 | previousState = LOW; 64 | } 65 | } 66 | //encoder udate (fires encoder rotation callbacks) 67 | if ( haveEncoder && millis() > (rateLimitCounter + rateLimit) ) { 68 | long newPosition = floor(encoder->read()/positionDivider); 69 | if (newPosition != encoderPosition) { 70 | encoderIncrement = (newPosition - encoderPosition); 71 | encoderPosition = newPosition; 72 | idleFlagged = false; 73 | lastEventMs = millis(); 74 | if ( _buttonState == HIGH ) { 75 | currentPosition += encoderIncrement; 76 | if (encoder_cb != NULL) encoder_cb (*this); 77 | } else { 78 | encodingPressed = true; 79 | currentPressedPosition += encoderIncrement; 80 | if (encoder_pressed_cb != NULL) encoder_pressed_cb (*this); 81 | } 82 | } 83 | rateLimitCounter = millis(); 84 | } 85 | //fire long press callbacks 86 | if (haveButton && !encodingPressed && LOW == bounce->read() ) { 87 | if ( bounce->currentDuration() > (longClickDuration * (longPressCounter+1)) ) { 88 | lastEventMs = millis(); 89 | if ( (repeatLongPress || longPressCounter == 0 ) && long_press_cb != NULL) { 90 | long_press_cb (*this); 91 | } 92 | longPressCounter++; 93 | } 94 | } 95 | //fire button click callbacks 96 | if ( haveButton && !clickFired && _buttonState == HIGH && bounce->currentDuration() > multiClickInterval ) { 97 | clickFired = true; 98 | if ( bounce->previousDuration() > longClickDuration ) { 99 | clickCounter = 0; 100 | prevClickCount = 1; 101 | longPressCounter = 0; 102 | if (long_click_cb != NULL) long_click_cb (*this); 103 | } else { 104 | prevClickCount = clickCounter; 105 | if (clickCounter == 3 && triple_click_cb != NULL) { 106 | triple_click_cb (*this); 107 | } else if ( clickCounter == 2 && double_click_cb != NULL) { 108 | double_click_cb (*this); 109 | } else { 110 | if (click_cb != NULL) click_cb (*this); 111 | } 112 | clickCounter = 0; 113 | } 114 | } 115 | //fire idle timeout callback 116 | if ( !idleFlagged && idle_cb != NULL && msSinceLastEvent() > idleTimeout ) { 117 | idleFlagged = true; 118 | idle_cb (*this); 119 | } 120 | } 121 | } 122 | 123 | void EncoderButton::setChangedHandler(CallbackFunction f) { changed_cb = f; } 124 | 125 | void EncoderButton::setPressedHandler(CallbackFunction f) { pressed_cb = f; } 126 | 127 | void EncoderButton::setReleasedHandler(CallbackFunction f) { released_cb = f; } 128 | 129 | void EncoderButton::setClickHandler(CallbackFunction f) { click_cb = f; } 130 | 131 | void EncoderButton::setLongClickHandler(CallbackFunction f) { long_click_cb = f; } 132 | 133 | void EncoderButton::setDoubleClickHandler(CallbackFunction f) { double_click_cb = f; } 134 | 135 | void EncoderButton::setTripleClickHandler(CallbackFunction f) { triple_click_cb = f; } 136 | 137 | void EncoderButton::setLongPressHandler(CallbackFunction f, bool repeat /*=false*/) { 138 | long_press_cb = f; 139 | repeatLongPress = repeat; 140 | } 141 | 142 | void EncoderButton::setEncoderHandler(CallbackFunction f) { encoder_cb = f; } 143 | 144 | void EncoderButton::setEncoderPressedHandler(CallbackFunction f) { encoder_pressed_cb = f; } 145 | 146 | void EncoderButton::setEncoderReleasedHandler(CallbackFunction f) { encoder_released_cb = f; } 147 | 148 | void EncoderButton::setIdleHandler(CallbackFunction f) { idle_cb = f; } 149 | 150 | void EncoderButton::setDebounceInterval(unsigned int intervalMs) { bounce->interval(intervalMs); } 151 | 152 | void EncoderButton::setMultiClickInterval(unsigned int intervalMs) { multiClickInterval = intervalMs; } 153 | 154 | void EncoderButton::setLongClickDuration(unsigned int longDurationMs) { longClickDuration = longDurationMs; } 155 | 156 | void EncoderButton::setLongPressRepeat(bool repeat /*=false*/) { repeatLongPress = repeat; } 157 | 158 | void EncoderButton::setRateLimit(long ms) { rateLimit = ms; } 159 | 160 | void EncoderButton::useQuadPrecision(bool prec) { positionDivider = (prec?1:4); } 161 | 162 | void EncoderButton::resetPosition(long pos) { 163 | encoder->readAndReset(); 164 | encoderPosition = 0; 165 | currentPosition = pos; 166 | } 167 | 168 | void EncoderButton::resetPressedPosition(long pos) { 169 | encoder->readAndReset(); 170 | encoderPosition = 0; 171 | currentPressedPosition = pos; 172 | } 173 | 174 | void EncoderButton::setIdleTimeout(unsigned int timeoutMs) { idleTimeout = timeoutMs; } 175 | 176 | void EncoderButton::setUserId(unsigned int identifier) { _userId = identifier; } 177 | 178 | void EncoderButton::setUserState(unsigned int s) { _userState = s; } 179 | 180 | bool EncoderButton::buttonState() { return bounce->read(); } 181 | 182 | unsigned char EncoderButton::clickCount() { return prevClickCount; } 183 | 184 | unsigned long EncoderButton::currentDuration() { return bounce->currentDuration(); } 185 | 186 | unsigned long EncoderButton::previousDuration() { return bounce->previousDuration(); } 187 | 188 | uint8_t EncoderButton::longPressCount() { return longPressCounter+1; } 189 | 190 | bool EncoderButton::isPressed() { return buttonState() == LOW; } 191 | 192 | int16_t EncoderButton::increment() { return encoderIncrement; } 193 | 194 | long EncoderButton::position() { return currentPosition; } 195 | 196 | long EncoderButton::pressedPosition() { return currentPressedPosition; } 197 | 198 | unsigned long EncoderButton::msSinceLastEvent() { return millis() - lastEventMs; } 199 | 200 | unsigned int EncoderButton::userId() { return _userId; } 201 | 202 | unsigned int EncoderButton::userState() { return _userState; } 203 | 204 | bool EncoderButton::enabled() { return _enabled; } 205 | 206 | void EncoderButton::enable(bool e) { 207 | _enabled = e; 208 | if ( e == true ) { 209 | //Reset the encoder so we don't trigger an event 210 | encoder->write(encoderPosition*positionDivider); 211 | } 212 | } 213 | 214 | 215 | -------------------------------------------------------------------------------- /src/EncoderButton.h: -------------------------------------------------------------------------------- 1 | /** 2 | * A lossless event based rotary encoder button wrapper for 3 | * Paul Stoffregen's Encoder library 4 | * https://www.pjrc.com/teensy/td_libs_Encoder.html 5 | * and Thomas Fredericks' Bounce2 library 6 | * https://github.com/thomasfredericks/Bounce2 7 | * and inspired by Lennart Hennigs Button2 8 | * https://github.com/LennartHennigs/Button2 9 | * 10 | * Written for Teensy but tested on Arduino Uno and others. 11 | * 12 | * It is important, but not essential, to use hardware interrupt pins (any 13 | * pin on a Teensy, but only pins 2 & 3 on an UNO). The library will work on software 14 | * interrupts but may not avoid loss of steps. 15 | * Do not use setRateLimit() with software interrupts. 16 | * See https://www.pjrc.com/teensy/td_libs_Encoder.html 17 | * for more details. 18 | * 19 | * Works with Encoder+button, Encoder alone or just a Button. 20 | * 21 | * Encoder can fire rotation callbacks when pressed or not and optionally 22 | * in quadrature mode. Default is once per click (ie once per four encoder positions). 23 | * 24 | * Button events are fired for both the encoder button and/or a standalone 25 | * momentary switch. 26 | * 27 | * GPLv2 Licence https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt 28 | * 29 | * Copyright (c) 2022 Philip Fletcher 30 | * 31 | */ 32 | 33 | #ifndef EncoderButton_h 34 | #define EncoderButton_h 35 | 36 | #include "Arduino.h" 37 | 38 | //Standing on the shoulders of giants 39 | // http://www.pjrc.com/teensy/td_libs_Encoder.html 40 | #ifndef Encoder_h 41 | #include 42 | #endif 43 | 44 | #ifndef Bounce2_h 45 | #include 46 | #endif 47 | 48 | #if defined(ARDUINO_ARCH_ESP32) || defined(ESP8266) || defined(CORE_TEENSY) 49 | #include 50 | #endif 51 | 52 | class EncoderButton { 53 | 54 | protected: 55 | 56 | #if defined(ARDUINO_ARCH_ESP32) || defined(ESP8266) || defined(CORE_TEENSY) 57 | typedef std::function CallbackFunction; 58 | #else 59 | typedef void (*CallbackFunction)(EncoderButton &); 60 | #endif 61 | 62 | public: 63 | /** 64 | * Construct a rotary encoder with a button 65 | */ 66 | EncoderButton(byte encoderPin1, byte encoderPin2, byte switchPin); 67 | 68 | /** 69 | * Construct a rotary encoder without a button 70 | */ 71 | EncoderButton(byte encoderPin1, byte encoderPin2); 72 | 73 | /** 74 | * Construct a button only 75 | */ 76 | EncoderButton(byte switchPin); 77 | 78 | 79 | /** 80 | * Read the position of the encoder and update the state of the button. 81 | * Call from loop() for each defined EncoderButton 82 | */ 83 | void update(); 84 | 85 | /** *************************************************** 86 | * set button callback handlers 87 | */ 88 | /** 89 | * Fires when button state changes 90 | */ 91 | void setChangedHandler(CallbackFunction f); 92 | 93 | /** 94 | * Fires after button is pressed down 95 | */ 96 | void setPressedHandler(CallbackFunction f); 97 | 98 | /** 99 | * Fires after button is released. 100 | * Note: if the encoder is turned while pressed, then 101 | * the 'encoder released' callback is fired instead. 102 | */ 103 | void setReleasedHandler(CallbackFunction f); 104 | 105 | /** 106 | * Fires after button is clicked (when pressed duration 107 | * is less than setLongClickDuration() (default 750ms) 108 | * Note: the number of multi clicks can be read from 109 | * EncoderButton.clickCount() in the callback so you are not 110 | * limited to double or triple clicks - any number can be actioned. 111 | * If double or triple click callbacks are set, this will not be 112 | * fired for those events. 113 | */ 114 | void setClickHandler(CallbackFunction f); 115 | 116 | /** 117 | * Fires after button is double clicked 118 | * Determined by setMultiClickInterval() (default 250ms) 119 | * Syntactic sugar for click handler + clickCount == 2 120 | */ 121 | void setDoubleClickHandler(CallbackFunction f); 122 | 123 | /** 124 | * Fires when button is triple clicked 125 | * Syntactic sugar for click handler + clickCount == 3 126 | */ 127 | void setTripleClickHandler(CallbackFunction f); 128 | 129 | /** 130 | * Fires after button is long clicked (when pressed duration 131 | * is greater than setLongClickDuration(ms) (default 750ms) 132 | * See also long press handler 133 | */ 134 | void setLongClickHandler(CallbackFunction f); 135 | 136 | /** 137 | * Fired *while* button is long pressed. By default, this fires 138 | * once but can fire every setLongClickDuration by passing 'true' 139 | * as a second argument. 140 | * Use longPressCount() in callback to read the number of times fired 141 | */ 142 | void setLongPressHandler(CallbackFunction f, bool repeat=false); 143 | 144 | /** *************************************************** 145 | * set encoder callback handlers 146 | */ 147 | 148 | /** 149 | * Fired when the encoder is turned. By default is fired once 150 | * per 'click' but can fire full quadrature encoding if 151 | * useQuadPrecision(bool) is set to 'true' 152 | */ 153 | void setEncoderHandler(CallbackFunction f); 154 | 155 | /** 156 | * Fired when the encoder is turned while pressed 157 | */ 158 | void setEncoderPressedHandler(CallbackFunction f); 159 | 160 | /** 161 | * Fired after encoder is released *and turned* (if not turned 162 | * the button 'releaded' handler is fired) 163 | */ 164 | void setEncoderReleasedHandler(CallbackFunction f); 165 | 166 | /** *************************************** 167 | * Fired after the encoder or button has been idle for 168 | * setIdleTimeout(ms) (default 10 seconds) 169 | */ 170 | void setIdleHandler(CallbackFunction f); 171 | 172 | 173 | /** *************************************** 174 | * button setup 175 | */ 176 | 177 | /** 178 | * Default is set in the Bounce2 library (currently 10ms) 179 | */ 180 | void setDebounceInterval(unsigned int intervalMs); 181 | 182 | /** 183 | * Set the interval in ms between double, triple or 184 | * multi clicks 185 | */ 186 | void setMultiClickInterval(unsigned int intervalMs); 187 | 188 | /** 189 | * Set the ms that defines a lonf click. Long pressed callback 190 | * will be fired at this interval if repeat is set to true via the 191 | * setLongPressHandler() 192 | */ 193 | void setLongClickDuration(unsigned int longDurationMs); 194 | 195 | /** 196 | * Choose whether to repeat the long press callback 197 | * (default is 'false') 198 | */ 199 | void setLongPressRepeat(bool repeat=false); 200 | 201 | /** *************************************** 202 | * encoder setup 203 | */ 204 | 205 | /** 206 | * Encoder callbacks are normally fired on every loop() but for MPG 207 | * style encoders this can fire a huge number of events (that may 208 | * swamp a serial connection). 209 | * The encoder interupts will sitll be called but this will limit 210 | * the call back firing to every set ms - read the 211 | * EncoderButton.increment() for lossless counting of encoder. 212 | * Set to zero (default) for no rate limit. 213 | */ 214 | void setRateLimit(long ms); 215 | 216 | /** 217 | * Quadrature encoders have four states for each 'click' of the 218 | * rotary switch. By default we only fire once per click. 219 | * Set this to 'true' if you want four events per click. 220 | * Affects pressed+turning too. 221 | */ 222 | void useQuadPrecision(bool prec); 223 | 224 | /** 225 | * Reset the counted position of the encoder. 226 | */ 227 | void resetPosition(long pos = 0); 228 | 229 | /** 230 | * Reset the counted pressed position of the encoder. 231 | */ 232 | void resetPressedPosition(long pos = 0); 233 | 234 | /** 235 | * Set the idle timeout in ms (default 10000) 236 | */ 237 | void setIdleTimeout(unsigned int timeoutMs); 238 | 239 | /** 240 | * Set the button identifier (not unique, defaults to 0) 241 | * Useful when multiple buttons call the same handler. 242 | */ 243 | void setUserId(unsigned int id); 244 | 245 | /** 246 | * Set the user state. Slight function creep but useful. 247 | * For use by implementor, ignored by library 248 | * eg ON, OFF, INACTIVE etc 249 | */ 250 | void setUserState(unsigned int s); 251 | 252 | 253 | /** *************************************** 254 | * button state 255 | */ 256 | 257 | /** 258 | * Directly get the current button state from Bounce2 259 | */ 260 | bool buttonState(); 261 | 262 | /** 263 | * Directly get the duration of the button current state from Bounce2 264 | */ 265 | unsigned long currentDuration(); 266 | 267 | /** 268 | * Directly get the duration of the button previous state from Bounce2 269 | */ 270 | unsigned long previousDuration(); 271 | 272 | /** 273 | * The number of multi-clicks that have been fired in the clicked event 274 | */ 275 | unsigned char clickCount(); 276 | 277 | 278 | /** 279 | * The number of times the long press handler has been fired in the 280 | * button pressed event 281 | */ 282 | uint8_t longPressCount(); 283 | 284 | /** 285 | * Returns true if pressed 286 | */ 287 | bool isPressed(); 288 | 289 | 290 | /** *************************************** 291 | * encoder state 292 | */ 293 | 294 | /** 295 | * Returns a positive (CW) or negative (CCW) integer. Is normally 1 or -1 but if your 296 | * loop() has lots of processing, your Arduino is slow or you setRateLimit() 297 | * this will report the actual number of increments made by the encoder since 298 | * the last encoder handler event. 299 | */ 300 | int16_t increment(); 301 | 302 | /** 303 | * The current position of the encoder. Can be reset by resetPosition() 304 | */ 305 | long position(); 306 | 307 | /** 308 | * The current position of the encoder when pressed. Can be reset by resetPressedPosition() 309 | */ 310 | long pressedPosition(); 311 | 312 | 313 | /** *************************************** 314 | * Returns the number of ms since any event was fired for this encoder/button 315 | */ 316 | unsigned long msSinceLastEvent(); 317 | 318 | /** 319 | * Get the button identifier (not unique, defaults to 0) 320 | */ 321 | unsigned int userId(); 322 | 323 | /** 324 | * Get the user state. 325 | */ 326 | unsigned int userState(); 327 | 328 | /** 329 | * Returns true if enabled 330 | */ 331 | bool enabled(); 332 | 333 | /** 334 | * Set enabled to true of false 335 | * This will enable/disable all event callbacks. 336 | * When disabled the encoder positions will not be updated. 337 | */ 338 | void enable(bool e=true); 339 | 340 | protected: 341 | 342 | CallbackFunction changed_cb = NULL; 343 | CallbackFunction pressed_cb = NULL; 344 | CallbackFunction released_cb = NULL; 345 | CallbackFunction click_cb = NULL; 346 | CallbackFunction long_click_cb = NULL; 347 | CallbackFunction double_click_cb = NULL; 348 | CallbackFunction triple_click_cb = NULL; 349 | CallbackFunction long_press_cb = NULL; 350 | //Encoder 351 | CallbackFunction encoder_cb = NULL; 352 | CallbackFunction encoder_pressed_cb = NULL; 353 | CallbackFunction encoder_released_cb = NULL; 354 | //Common 355 | CallbackFunction idle_cb = NULL; 356 | 357 | 358 | private: 359 | Encoder* encoder; 360 | Bounce* bounce; 361 | boolean haveButton = false; 362 | boolean haveEncoder = false; 363 | uint8_t positionDivider = 4; 364 | int32_t encoderPosition = 0; 365 | int32_t currentPosition = 0; 366 | int32_t currentPressedPosition = 0; 367 | int encoderIncrement = 0; 368 | bool encodingPressed = false; 369 | unsigned char _buttonState = HIGH; 370 | unsigned int multiClickInterval = 250; 371 | unsigned int longClickDuration = 750; 372 | bool clickFired = true; 373 | unsigned char clickCounter = 0; 374 | unsigned int longPressCounter = 0; 375 | unsigned long lastEventMs = millis(); 376 | unsigned long idleTimeout = 10000; 377 | bool idleFlagged = false; 378 | bool previousState = LOW; 379 | unsigned char prevClickCount = 0; 380 | bool repeatLongPress = false; 381 | 382 | unsigned int rateLimit = 0; 383 | unsigned long rateLimitCounter = 0; 384 | 385 | unsigned int _userId = 0; 386 | unsigned int _userState = 0; 387 | bool _enabled = true; 388 | 389 | 390 | 391 | }; 392 | 393 | #endif 394 | 395 | 396 | --------------------------------------------------------------------------------