├── .DS_Store ├── EspSoftwareSerial ├── LICENSE ├── README.md ├── examples │ ├── bitpattern │ │ └── bitpattern.ino │ ├── circular_queue_mp_test │ │ └── mp_queue_test.cpp │ ├── loopback │ │ └── loopback.ino │ ├── onewiretest │ │ └── onewiretest.ino │ ├── onreceive │ │ └── onreceive.ino │ ├── repeater │ │ └── repeater.ino │ └── swsertest │ │ └── swsertest.ino ├── keywords.txt ├── library.json ├── library.properties └── src │ ├── SoftwareSerial.cpp │ ├── SoftwareSerial.h │ └── circular_queue │ ├── Delegate.h │ ├── MultiDelegate.h │ ├── circular_queue.h │ ├── circular_queue_mp.h │ └── ghostl.h ├── LICENSE ├── README.md ├── fox.ino └── morsemelody.ino /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c0ldbru/fox/1372326b63d19cc765448027943f62d07a0b963a/.DS_Store -------------------------------------------------------------------------------- /EspSoftwareSerial/LICENSE: -------------------------------------------------------------------------------- 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 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! -------------------------------------------------------------------------------- /EspSoftwareSerial/README.md: -------------------------------------------------------------------------------- 1 | # EspSoftwareSerial 2 | 3 | ## Implementation of the Arduino software serial library for the ESP8266 / ESP32 family 4 | 5 | This fork implements interrupt service routine best practice. 6 | In the receive interrupt, instead of blocking for whole bytes 7 | at a time - voiding any near-realtime behavior of the CPU - only level 8 | change and timestamp are recorded. The more time consuming phase 9 | detection and byte assembly are done in the main code. 10 | 11 | Except at high bitrates, depending on other ongoing activity, 12 | interrupts in particular, this software serial adapter 13 | supports full duplex receive and send. At high bitrates (115200bps) 14 | send bit timing can be improved at the expense of blocking concurrent 15 | full duplex receives, with the 16 | `EspSoftwareSerial::UART::enableIntTx(false)` function call. 17 | 18 | The same functionality is given as the corresponding AVR library but 19 | several instances can be active at the same time. Speed up to 115200 baud 20 | is supported. Besides a constructor compatible to the AVR SoftwareSerial class, 21 | and updated constructor that takes no arguments exists, instead the `begin()` 22 | function can handle the pin assignments and logic inversion. 23 | It also has optional input buffer capacity arguments for byte buffer and ISR bit buffer. 24 | This way, it is a better drop-in replacement for the hardware serial APIs on the ESP MCUs. 25 | 26 | Please note that due to the fact that the ESPs always have other activities 27 | ongoing, there will be some inexactness in interrupt timings. This may 28 | lead to inevitable, but few, bit errors when having heavy data traffic 29 | at high baud rates. 30 | 31 | This library supports ESP8266, ESP32, ESP32-S2 and ESP32-C3 devices. 32 | 33 | ## Resource optimization 34 | 35 | The memory footprint can be optimized to just fit the amount of expected 36 | incoming asynchronous data. 37 | For this, the `EspSoftwareSerial::UART` constructor provides two arguments. First, the 38 | octet buffer capacity for assembled received octets can be set. Read calls are 39 | satisfied from this buffer, freeing it in return. 40 | Second, the signal edge detection buffer of 32bit fields can be resized. 41 | One octet may require up to to 10 fields, but fewer may be needed, 42 | depending on the bit pattern. Any read or write calls check this buffer 43 | to assemble received octets, thus promoting completed octets to the octet 44 | buffer, freeing fields in the edge detection buffer. 45 | 46 | Look at the swsertest.ino example. There, on reset, ASCII characters ' ' to 'z' 47 | are sent. This happens not as a block write, but in a single write call per 48 | character. As the example uses a local loopback wire, every outgoing bit is 49 | immediately received back. Therefore, any single write call causes up to 50 | 10 fields - depending on the exact bit pattern - to be occupied in the signal 51 | edge detection buffer. In turn, as explained before, each single write call 52 | also causes received bit assembly to be performed, promoting these bits from 53 | the signal edge detection buffer to the octet buffer as soon as possible. 54 | Explaining by way of contrast, if during a a single write call, perhaps because 55 | of using block writing, more than a single octet is received, there will be a 56 | need for more than 10 fields in the signal edge detection buffer. 57 | The necessary capacity of the octet buffer only depends on the amount of incoming 58 | data until the next read call. 59 | 60 | For the swsertest.ino example, this results in the following optimized 61 | constructor arguments to spend only the minimum RAM on buffers required: 62 | 63 | The octet buffer capacity (`bufCapacity`) is 95 (93 characters net plus two tolerance). 64 | The signal edge detection buffer capacity (`isrBufCapacity`) is 11, as each 65 | single octet can have up to 11 bits on the wire, 66 | which are immediately received during the write, and each 67 | write call causes the signal edge detection to promote the previously sent and 68 | received bits to the octet buffer. 69 | 70 | In a more generalized scenario, calculate the bits (use message size in octets 71 | times 10) that may be asynchronously received to determine the value for 72 | `isrBufCapacity` in the constructor. Also use the number of received octets 73 | that must be buffered for reading as the value of `bufCapacity`. 74 | The more frequently your code calls write or read functions, the greater the 75 | chances are that you can reduce the `isrBufCapacity` footprint without losing data, 76 | and each time you call read to fetch from the octet buffer, you reduce the 77 | need for space there. 78 | 79 | ## EspSoftwareSerial::Config and parity 80 | The configuration of the data stream is done via a `EspSoftwareSerial::Config` 81 | argument to `begin()`. Word lengths can be set to between 5 and 8 bits, parity 82 | can be N(one), O(dd) or E(ven) and 1 or 2 stop bits can be used. The default is 83 | `SWSERIAL_8N1` using 8 bits, no parity and 1 stop bit but any combination can 84 | be used, e.g. `SWSERIAL_7E2`. If using EVEN or ODD parity, any parity errors 85 | can be detected with the `readParity()` and `parityEven()` or `parityOdd()` 86 | functions respectively. Note that the result of `readParity()` always applies 87 | to the preceding `read()` or `peek()` call, and is undefined if they report 88 | no data or an error. 89 | 90 | To allow flexible 9-bit and data/addressing protocols, the additional parity 91 | modes MARK and SPACE are also available. Furthermore, the parity mode can be 92 | individually set in each call to `write()`. 93 | 94 | This allows a simple implementation of protocols where the parity bit is used to 95 | distinguish between data and addresses/commands ("9-bit" protocols). First set 96 | up EspSoftwareSerial::UART with parity mode SPACE, e.g. `SWSERIAL_8S1`. This will add a 97 | parity bit to every byte sent, setting it to logical zero (SPACE parity). 98 | 99 | To detect incoming bytes with the parity bit set (MARK parity), use the 100 | `readParity()` function. To send a byte with the parity bit set, just add 101 | `MARK` as the second argument when writing, e.g. `write(ch, SWSERIAL_PARITY_MARK)`. 102 | 103 | ## Checking for correct pin selection / configuration 104 | In general, most pins on the ESP8266 and ESP32 devices can be used by EspSoftwareSerial, 105 | however each device has a number of pins that have special functions or require careful 106 | handling to prevent undesirable situations, for example they are connected to the 107 | on-board SPI flash memory or they are used to determine boot and programming modes 108 | after powerup or brownouts. These pins are not able to be configured by this library. 109 | 110 | The exact list for each device can be found in the 111 | [ESP32 data sheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf) 112 | in sections 2.2 (Pin Descriptions) and 2.4 (Strapping pins). There is a discussion 113 | dedicated to the use of GPIO12 in this 114 | [note about GPIO12](https://github.com/espressif/esp-idf/tree/release/v3.2/examples/storage/sd_card#note-about-gpio12). 115 | Refer to the `isValidPin()`, `isValidRxPin()` and `isValidTxPin()` 116 | functions in the `EspSoftwareSerial::GpioCapabilities` class for the GPIO restrictions 117 | enforced by this library by default. 118 | 119 | The easiest and safest method is to test the object returned at runtime, to see if 120 | it is valid. For example: 121 | 122 | ``` 123 | #include 124 | 125 | #define MYPORT_TX 12 126 | #define MYPORT_RX 13 127 | 128 | EspSoftwareSerial::UART myPort; 129 | 130 | [...] 131 | 132 | Serial.begin(115200); // Standard hardware serial port 133 | 134 | myPort.begin(38400, SWSERIAL_8N1, MYPORT_RX, MYPORT_TX, false); 135 | if (!myPort) { // If the object did not initialize, then its configuration is invalid 136 | Serial.println("Invalid EspSoftwareSerial pin configuration, check config"); 137 | while (1) { // Don't continue with invalid configuration 138 | delay (1000); 139 | } 140 | } 141 | 142 | [...] 143 | ``` 144 | 145 | ## Using and updating EspSoftwareSerial in the esp8266com/esp8266 Arduino build environment 146 | 147 | EspSoftwareSerial is both part of the BSP download for ESP8266 in Arduino, 148 | and it is set up as a Git submodule in the esp8266 source tree, 149 | specifically in `.../esp8266/libraries/SoftwareSerial` when using a Github 150 | repository clone in your Arduino sketchbook hardware directory. 151 | This supersedes any version of EspSoftwareSerial installed for instance via 152 | the Arduino library manager, it is not required to install EspSoftwareSerial 153 | for the ESP8266 separately at all, but doing so has ill effect. 154 | 155 | The responsible maintainer of the esp8266 repository has kindly shared the 156 | following command line instructions to use, if one wishes to manually 157 | update EspSoftwareSerial to a newer release than pulled in via the ESP8266 Arduino BSP: 158 | 159 | To update esp8266/arduino EspSoftwareSerial submodule to lastest master: 160 | 161 | Clean it (optional): 162 | ```shell 163 | $ rm -rf libraries/SoftwareSerial 164 | $ git submodule update --init 165 | ``` 166 | Now update it: 167 | ```shell 168 | $ cd libraries/SoftwareSerial 169 | $ git checkout master 170 | $ git pull 171 | ``` 172 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/bitpattern/bitpattern.ino: -------------------------------------------------------------------------------- 1 | #include "SoftwareSerial.h" 2 | 3 | #ifndef D5 4 | #if defined(ESP8266) 5 | #define D8 (15) 6 | #define D5 (14) 7 | #define D7 (13) 8 | #define D6 (12) 9 | #define RX (3) 10 | #define TX (1) 11 | #elif defined(ESP32) 12 | #define D8 (5) 13 | #define D5 (18) 14 | #define D7 (23) 15 | #define D6 (19) 16 | #define RX (3) 17 | #define TX (1) 18 | #endif 19 | #endif 20 | 21 | EspSoftwareSerial::UART swSer; 22 | #ifdef ESP8266 23 | auto logSer = EspSoftwareSerial::UART(-1, TX); 24 | auto hwSer = Serial; 25 | #else 26 | auto logSer = Serial; 27 | auto hwSer = Serial1; 28 | #endif 29 | 30 | constexpr uint32_t TESTBPS = 115200; 31 | 32 | void setup() { 33 | delay(2000); 34 | #ifdef ESP8266 35 | hwSer.begin(TESTBPS, ::SERIAL_8N1); 36 | hwSer.swap(); 37 | #else 38 | hwSer.begin(TESTBPS, ::SERIAL_8N1, D6, D5); 39 | #endif 40 | logSer.begin(115200); 41 | logSer.println(PSTR("\nOne Wire Half Duplex Bitpattern and Datarate Test")); 42 | swSer.begin(TESTBPS, EspSoftwareSerial::SWSERIAL_8N1, D6, D5); 43 | swSer.enableIntTx(true); 44 | logSer.println(PSTR("Tx on swSer")); 45 | } 46 | 47 | uint8_t val = 0xff; 48 | 49 | void loop() { 50 | swSer.write((uint8_t)0x00); 51 | swSer.write(val); 52 | swSer.write(val); 53 | auto start = ESP.getCycleCount(); 54 | int rxCnt = 0; 55 | while (ESP.getCycleCount() - start < ESP.getCpuFreqMHz() * 1000000 / 10) { 56 | if (hwSer.available()) { 57 | auto rxVal = hwSer.read(); 58 | if ((!rxCnt && rxVal) || (rxCnt && rxVal != val)) { 59 | logSer.printf(PSTR("Rx bit error: tx = 0x%02x, rx = 0x%02x\n"), val, rxVal); 60 | } 61 | ++rxCnt; 62 | } 63 | } 64 | if (rxCnt != 3) { 65 | logSer.printf(PSTR("Rx cnt error, tx = 0x%02x\n"), val); 66 | } 67 | ++val; 68 | if (!val) { 69 | logSer.println("Starting over"); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/circular_queue_mp_test/mp_queue_test.cpp: -------------------------------------------------------------------------------- 1 | // circular_mp_test.cpp : This file contains the 'main' function. Program execution begins and ends there. 2 | // 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "circular_queue/circular_queue_mp.h" 9 | 10 | struct qitem 11 | { 12 | // produer id 13 | int id; 14 | // monotonic increasing value 15 | int val = 0; 16 | }; 17 | 18 | constexpr int TOTALMESSAGESTARGET = 60000000; 19 | // reserve one thread as consumer 20 | const auto THREADS = std::thread::hardware_concurrency() / 2 - 1; 21 | const int MESSAGES = TOTALMESSAGESTARGET / THREADS; 22 | circular_queue threads(THREADS); 23 | circular_queue_mp queue(threads.capacity()* MESSAGES / 10); 24 | std::vector checks(threads.capacity()); 25 | 26 | int main() 27 | { 28 | using namespace std::chrono_literals; 29 | std::cerr << "Utilizing " << THREADS << " producer threads" << std::endl; 30 | for (int i = 0; i < threads.capacity(); ++i) 31 | { 32 | threads.push(std::thread([i]() { 33 | for (int c = 0; c < MESSAGES;) 34 | { 35 | // simulate some load 36 | auto start = std::chrono::system_clock::now(); 37 | while (std::chrono::system_clock::now() - start < 1us); 38 | if (queue.push({ i, c })) 39 | { 40 | ++c; 41 | } 42 | else 43 | { 44 | //std::cerr << "queue full" << std::endl; 45 | //std::this_thread::sleep_for(10us); 46 | } 47 | //if (0 == c % 10000) std::this_thread::sleep_for(10us); 48 | } 49 | })); 50 | } 51 | for (int o = 0; o < threads.available() * MESSAGES; ++o) 52 | { 53 | auto now = std::chrono::system_clock::now(); 54 | while (!queue.available()) 55 | { 56 | auto starvedFor = std::chrono::system_clock::now() - now; 57 | if (starvedFor > 20s) std::cerr << "queue starved for > 20s" << std::endl; 58 | //std::this_thread::sleep_for(20ms); 59 | } 60 | auto item = queue.pop(); 61 | if (checks[item.id] != item.val) 62 | { 63 | std::cerr << "item mismatch" << std::endl; 64 | } 65 | checks[item.id] = item.val + 1; 66 | if (0 == item.val % 1000) std::this_thread::sleep_for(100us); 67 | } 68 | while (threads.available()) 69 | { 70 | auto thread = threads.pop(); 71 | thread.join(); 72 | } 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/loopback/loopback.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // On ESP8266: 4 | // Local EspSoftwareSerial loopback, connect D5 (rx) and D6 (tx). 5 | // For local hardware loopback, connect D5 to D8 (tx), D6 to D7 (rx). 6 | // For hardware send/sink, connect D7 (rx) and D8 (tx). 7 | // Hint: The logger is run at 9600bps such that enableIntTx(true) can remain unchanged. Blocking 8 | // interrupts severely impacts the ability of the EspSoftwareSerial devices to operate concurrently 9 | // and/or in duplex mode. 10 | // Operating in software serial full duplex mode, runs at 19200bps and few errors (~2.5%). 11 | // Operating in software serial half duplex mode (both loopback and repeater), 12 | // runs at 57600bps with nearly no errors. 13 | // Operating loopback in full duplex, and repeater in half duplex, runs at 38400bps with nearly no errors. 14 | // On ESP32: 15 | // For EspSoftwareSerial or hardware send/sink, connect D5 (rx) and D6 (tx). 16 | // Hardware Serial2 defaults to D4 (rx), D3 (tx). 17 | // For local hardware loopback, connect D5 (rx) to D3 (tx), D6 (tx) to D4 (rx). 18 | 19 | #ifndef D5 20 | #if defined(ESP8266) 21 | #define D8 (15) 22 | #define D5 (14) 23 | #define D7 (13) 24 | #define D6 (12) 25 | #define RX (3) 26 | #define TX (1) 27 | #elif defined(ESP32) 28 | #define D8 (5) 29 | #define D5 (18) 30 | #define D7 (23) 31 | #define D6 (19) 32 | #define RX (3) 33 | #define TX (1) 34 | #endif 35 | #endif 36 | 37 | // Pick only one of HWLOOPBACK, HWSOURCESWSINK, or HWSOURCESINK 38 | //#define HWLOOPBACK 1 39 | //#define HWSOURCESWSINK 1 40 | //#define HWSOURCESINK 1 41 | #define HALFDUPLEX 1 42 | 43 | #ifdef ESP32 44 | constexpr int IUTBITRATE = 19200; 45 | #else 46 | constexpr int IUTBITRATE = 19200; 47 | #endif 48 | 49 | #if defined(ESP8266) 50 | constexpr EspSoftwareSerial::Config swSerialConfig = EspSoftwareSerial::SWSERIAL_8E1; 51 | constexpr SerialConfig hwSerialConfig = ::SERIAL_8E1; 52 | #elif defined(ESP32) 53 | constexpr EspSoftwareSerial::Config swSerialConfig = EspSoftwareSerial::SWSERIAL_8E1; 54 | constexpr uint32_t hwSerialConfig = ::SERIAL_8E1; 55 | #else 56 | constexpr unsigned swSerialConfig = 3; 57 | #endif 58 | constexpr bool invert = false; 59 | 60 | constexpr int BLOCKSIZE = 16; // use fractions of 256 61 | 62 | unsigned long start; 63 | const char effTxTxt[] PROGMEM = "eff. tx: "; 64 | const char effRxTxt[] PROGMEM = "eff. rx: "; 65 | int txCount; 66 | int rxCount; 67 | int expected; 68 | int rxErrors; 69 | int rxParityErrors; 70 | constexpr int ReportInterval = IUTBITRATE / 8; 71 | 72 | #if defined(ESP8266) 73 | #if defined(HWLOOPBACK) || defined(HWSOURCESWSINK) 74 | HardwareSerial& hwSerial(Serial); 75 | EspSoftwareSerial::UART serialIUT; 76 | EspSoftwareSerial::UART logger; 77 | #elif defined(HWSOURCESINK) 78 | HardwareSerial& serialIUT(Serial); 79 | EspSoftwareSerial::UART logger; 80 | #else 81 | EspSoftwareSerial::UART serialIUT; 82 | HardwareSerial& logger(Serial); 83 | #endif 84 | #elif defined(ESP32) 85 | #if defined(HWLOOPBACK) || defined (HWSOURCESWSINK) 86 | HardwareSerial& hwSerial(Serial2); 87 | EspSoftwareSerial::UART serialIUT; 88 | #elif defined(HWSOURCESINK) 89 | HardwareSerial& serialIUT(Serial2); 90 | #else 91 | EspSoftwareSerial::UART serialIUT; 92 | #endif 93 | HardwareSerial& logger(Serial); 94 | #else 95 | EspSoftwareSerial::UART serialIUT(14, 12); 96 | HardwareSerial& logger(Serial); 97 | #endif 98 | 99 | void setup() { 100 | #if defined(ESP8266) 101 | #if defined(HWLOOPBACK) || defined(HWSOURCESINK) || defined(HWSOURCESWSINK) 102 | Serial.begin(IUTBITRATE, hwSerialConfig, ::SERIAL_FULL, 1, invert); 103 | Serial.swap(); 104 | Serial.setRxBufferSize(2 * BLOCKSIZE); 105 | logger.begin(9600, EspSoftwareSerial::SWSERIAL_8N1, -1, TX); 106 | #else 107 | logger.begin(9600); 108 | #endif 109 | #if !defined(HWSOURCESINK) 110 | serialIUT.begin(IUTBITRATE, swSerialConfig, D5, D6, invert, 2 * BLOCKSIZE); 111 | #ifdef HALFDUPLEX 112 | serialIUT.enableIntTx(false); 113 | #endif 114 | #endif 115 | #elif defined(ESP32) 116 | #if defined(HWLOOPBACK) || defined(HWSOURCESWSINK) 117 | Serial2.begin(IUTBITRATE, hwSerialConfig, D4, D3, invert); 118 | Serial2.setRxBufferSize(2 * BLOCKSIZE); 119 | #elif defined(HWSOURCESINK) 120 | serialIUT.begin(IUTBITRATE, hwSerialConfig, D5, D6, invert); 121 | serialIUT.setRxBufferSize(2 * BLOCKSIZE); 122 | #endif 123 | #if !defined(HWSOURCESINK) 124 | serialIUT.begin(IUTBITRATE, swSerialConfig, D5, D6, invert, 2 * BLOCKSIZE); 125 | #ifdef HALFDUPLEX 126 | serialIUT.enableIntTx(false); 127 | #endif 128 | #endif 129 | logger.begin(9600); 130 | #else 131 | #if !defined(HWSOURCESINK) 132 | serialIUT.begin(IUTBITRATE); 133 | #endif 134 | logger.begin(9600); 135 | #endif 136 | 137 | logger.println(PSTR("Loopback example for EspEspSoftwareSerial")); 138 | 139 | start = micros(); 140 | txCount = 0; 141 | rxCount = 0; 142 | rxErrors = 0; 143 | rxParityErrors = 0; 144 | expected = -1; 145 | } 146 | 147 | unsigned char c = 0; 148 | 149 | void loop() { 150 | #ifdef HALFDUPLEX 151 | char block[BLOCKSIZE]; 152 | #endif 153 | char inBuf[BLOCKSIZE]; 154 | for (int i = 0; i < BLOCKSIZE; ++i) { 155 | #ifndef HALFDUPLEX 156 | #ifdef HWSOURCESWSINK 157 | hwSerial.write(c); 158 | #else 159 | serialIUT.write(c); 160 | #endif 161 | #ifdef HWLOOPBACK 162 | int avail = hwSerial.available(); 163 | while ((0 == (i % 8)) && avail > 0) { 164 | int inCnt = hwSerial.read(inBuf, min(avail, min(BLOCKSIZE, hwSerial.availableForWrite()))); 165 | hwSerial.write(inBuf, inCnt); 166 | avail -= inCnt; 167 | } 168 | #endif 169 | #else 170 | block[i] = c; 171 | #endif 172 | c = (c + 1) % 256; 173 | ++txCount; 174 | } 175 | #ifdef HALFDUPLEX 176 | #ifdef HWSOURCESWSINK 177 | hwSerial.write(block, BLOCKSIZE); 178 | #else 179 | serialIUT.write(block, BLOCKSIZE); 180 | #endif 181 | #endif 182 | #ifdef HWSOURCESINK 183 | #if defined(ESP8266) 184 | if (serialIUT.hasOverrun()) { logger.println(PSTR("serialIUT.overrun")); } 185 | #endif 186 | #else 187 | if (serialIUT.overflow()) { logger.println(PSTR("serialIUT.overflow")); } 188 | #endif 189 | 190 | int inCnt; 191 | uint32_t deadlineStart; 192 | 193 | #ifdef HWLOOPBACK 194 | // starting deadline for the first bytes to become readable 195 | deadlineStart = ESP.getCycleCount(); 196 | inCnt = 0; 197 | while ((ESP.getCycleCount() - deadlineStart) < (1000000UL * 12 * BLOCKSIZE) / IUTBITRATE * 24 * ESP.getCpuFreqMHz()) { 198 | int avail = hwSerial.available(); 199 | inCnt += hwSerial.read(&inBuf[inCnt], min(avail, min(BLOCKSIZE - inCnt, hwSerial.availableForWrite()))); 200 | if (inCnt >= BLOCKSIZE) { break; } 201 | // wait for more outstanding bytes to trickle in 202 | if (avail) deadlineStart = ESP.getCycleCount(); 203 | } 204 | hwSerial.write(inBuf, inCnt); 205 | #endif 206 | 207 | // starting deadline for the first bytes to come in 208 | deadlineStart = ESP.getCycleCount(); 209 | inCnt = 0; 210 | while ((ESP.getCycleCount() - deadlineStart) < (1000000UL * 12 * BLOCKSIZE) / IUTBITRATE * 8 * ESP.getCpuFreqMHz()) { 211 | int avail; 212 | if (0 != (swSerialConfig & 070)) 213 | avail = serialIUT.available(); 214 | else 215 | avail = serialIUT.read(inBuf, BLOCKSIZE); 216 | for (int i = 0; i < avail; ++i) 217 | { 218 | unsigned char r; 219 | if (0 != (swSerialConfig & 070)) 220 | r = serialIUT.read(); 221 | else 222 | r = inBuf[i]; 223 | if (expected == -1) { expected = r; } 224 | else { 225 | expected = (expected + 1) % (1UL << (5 + swSerialConfig % 4)); 226 | } 227 | if (r != expected) { 228 | ++rxErrors; 229 | expected = -1; 230 | } 231 | #ifndef HWSOURCESINK 232 | if (serialIUT.readParity() != (static_cast(swSerialConfig & 010) ? serialIUT.parityOdd(r) : serialIUT.parityEven(r))) 233 | { 234 | ++rxParityErrors; 235 | } 236 | #elif defined(ESP8266) 237 | // current ESP8266 API does not flag parity errors separately 238 | if (serialIUT.hasRxError()) 239 | { 240 | ++rxParityErrors; 241 | } 242 | #endif 243 | ++rxCount; 244 | ++inCnt; 245 | } 246 | 247 | if (inCnt >= BLOCKSIZE) { break; } 248 | // wait for more outstanding bytes to trickle in 249 | if (avail) deadlineStart = ESP.getCycleCount(); 250 | } 251 | 252 | const uint32_t interval = micros() - start; 253 | if (txCount >= ReportInterval && interval) { 254 | uint8_t wordBits = (5 + swSerialConfig % 4) + static_cast(swSerialConfig & 070) + 1 + ((swSerialConfig & 0300) ? 1 : 0); 255 | logger.println(String(PSTR("tx/rx: ")) + txCount + PSTR("/") + rxCount); 256 | const long txCps = txCount * (1000000.0 / interval); 257 | const long rxCps = rxCount * (1000000.0 / interval); 258 | logger.print(String(FPSTR(effTxTxt)) + wordBits * txCps + PSTR("bps, ") 259 | + effRxTxt + wordBits * rxCps + PSTR("bps, ") 260 | + rxErrors + PSTR(" errors (") + 100.0 * rxErrors / (!rxErrors ? 1 : rxCount) + PSTR("%)")); 261 | if (0 != (swSerialConfig & 070)) 262 | { 263 | logger.print(PSTR(" (")); logger.print(rxParityErrors); logger.println(PSTR(" parity errors)")); 264 | } 265 | else 266 | { 267 | logger.println(); 268 | } 269 | txCount = 0; 270 | rxCount = 0; 271 | rxErrors = 0; 272 | rxParityErrors = 0; 273 | expected = -1; 274 | // resync 275 | delay(1000UL * 12 * BLOCKSIZE / IUTBITRATE * 16); 276 | serialIUT.flush(); 277 | start = micros(); 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/onewiretest/onewiretest.ino: -------------------------------------------------------------------------------- 1 | #include "SoftwareSerial.h" 2 | 3 | #ifndef D5 4 | #if defined(ESP8266) 5 | #define D5 (14) 6 | #define D6 (12) 7 | #elif defined(ESP32) 8 | #define D5 (18) 9 | #define D6 (19) 10 | #endif 11 | #endif 12 | 13 | EspSoftwareSerial::UART swSer1; 14 | EspSoftwareSerial::UART swSer2; 15 | 16 | void checkSwSerial(EspSoftwareSerial::UART* ss) { 17 | byte ch; 18 | while (!Serial.available()); 19 | ss->enableTx(true); 20 | while (Serial.available()) { 21 | ch = Serial.read(); 22 | ss->write(ch); 23 | } 24 | ss->enableTx(false); 25 | // wait 1 second for the reply from EspSoftwareSerial if any 26 | delay(1000); 27 | if (ss->available()) { 28 | Serial.print(PSTR("\nResult:")); 29 | while (ss->available()) { 30 | ch = (byte)ss->read(); 31 | Serial.print(ch < 0x10 ? PSTR(" 0") : PSTR(" ")); 32 | Serial.print(ch, HEX); 33 | } 34 | Serial.println(); 35 | } 36 | } 37 | 38 | void setup() { 39 | delay(2000); 40 | Serial.begin(115200); 41 | Serial.println(PSTR("\nOne Wire Half Duplex Serial Tester")); 42 | swSer1.begin(115200, EspSoftwareSerial::SWSERIAL_8N1, D6, D6, false, 256); 43 | // high speed half duplex, turn off interrupts during tx 44 | swSer1.enableIntTx(false); 45 | swSer2.begin(115200, EspSoftwareSerial::SWSERIAL_8N1, D5, D5, false, 256); 46 | // high speed half duplex, turn off interrupts during tx 47 | swSer2.enableIntTx(false); 48 | } 49 | 50 | void loop() { 51 | Serial.println(PSTR("\n\nTesting on swSer1")); 52 | Serial.print(PSTR("Enter something to send using swSer1.")); 53 | checkSwSerial(&swSer1); 54 | 55 | Serial.println(PSTR("\n\nTesting on swSer2")); 56 | Serial.print(PSTR("Enter something to send using swSer2.")); 57 | checkSwSerial(&swSer2); 58 | 59 | } 60 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/onreceive/onreceive.ino: -------------------------------------------------------------------------------- 1 | // On ESP8266: 2 | // Runs up to 115200bps at 80MHz, 250000bps at 160MHz, with nearly zero errors. 3 | // This example is currently not ported to ESP32, which is based on FreeRTOS. 4 | 5 | #include 6 | 7 | #ifndef D5 8 | #define D8 (15) 9 | #define D5 (14) 10 | #define D7 (13) 11 | #define D6 (12) 12 | #define RX (3) 13 | #define TX (1) 14 | #endif 15 | 16 | #define BAUD_RATE 115200 17 | #define MAX_FRAMEBITS (1 + 8 + 1 + 2) 18 | 19 | EspSoftwareSerial::UART testSerial; 20 | 21 | // Becomes set from ISR / IRQ callback function. 22 | std::atomic rxPending(false); 23 | 24 | void IRAM_ATTR receiveHandler() { 25 | rxPending.store(true); 26 | esp_schedule(); 27 | } 28 | 29 | void setup() { 30 | Serial.begin(115200); 31 | Serial.setDebugOutput(false); 32 | Serial.swap(); 33 | testSerial.begin(BAUD_RATE, EspSoftwareSerial::SWSERIAL_8N1, RX, TX); 34 | // Only half duplex this way, but reliable TX timings for high bps 35 | testSerial.enableIntTx(false); 36 | testSerial.onReceive(receiveHandler); 37 | 38 | testSerial.println(PSTR("\nSoftware serial onReceive() event test started")); 39 | 40 | for (char ch = ' '; ch <= 'z'; ch++) { 41 | testSerial.write(ch); 42 | } 43 | testSerial.println(); 44 | } 45 | 46 | void loop() { 47 | #ifdef ESP8266 48 | bool isRxPending = rxPending.load(); 49 | if (isRxPending) { 50 | rxPending.store(false); 51 | } 52 | #else 53 | bool isRxPending = m_isrOverflow.exchange(false); 54 | #endif 55 | auto avail = testSerial.available(); 56 | if (isRxPending && !avail) { 57 | // event fired on start bit, wait until first stop bit of longest frame 58 | delayMicroseconds(1 + MAX_FRAMEBITS * 1000000 / BAUD_RATE); 59 | avail = testSerial.available(); 60 | } 61 | if (!avail) { 62 | // On development board, idle power draw at USB: 63 | // with yield() 77mA, 385mW (160MHz: 82mA, 410mW) 64 | // with esp_suspend() 20mA, 100mW (at 160MHz, too) 65 | //yield(); 66 | esp_suspend(); 67 | return; 68 | } 69 | // try to force to half-duplex 70 | decltype(avail) prev_avail; 71 | do { 72 | delayMicroseconds(1 + MAX_FRAMEBITS * 1000000 / BAUD_RATE); 73 | prev_avail = avail; 74 | } while (prev_avail != (avail = testSerial.available())); 75 | while (avail > 0) { 76 | testSerial.write(testSerial.read()); 77 | avail = testSerial.available(); 78 | } 79 | testSerial.println(); 80 | } 81 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/repeater/repeater.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // On ESP8266: 4 | // EspSoftwareSerial loopback for remote source (loopback.ino), or hardware loopback. 5 | // Connect source D5 (rx) to local D8 (tx), source D6 (tx) to local D7 (rx). 6 | // Hint: The logger is run at 9600bps such that enableIntTx(true) can remain unchanged. Blocking 7 | // interrupts severely impacts the ability of the EspSoftwareSerial devices to operate concurrently 8 | // and/or in duplex mode. 9 | // On ESP32: 10 | // For software or hardware loopback, connect source rx to local D8 (tx), source tx to local D7 (rx). 11 | 12 | #ifndef D5 13 | #if defined(ESP8266) 14 | #define D8 (15) 15 | #define D5 (14) 16 | #define D7 (13) 17 | #define D6 (12) 18 | #define RX (3) 19 | #define TX (1) 20 | #elif defined(ESP32) 21 | #define D8 (5) 22 | #define D5 (18) 23 | #define D7 (23) 24 | #define D6 (19) 25 | #define RX (3) 26 | #define TX (1) 27 | #endif 28 | #endif 29 | 30 | #define HWLOOPBACK 1 31 | #define HALFDUPLEX 1 32 | 33 | #ifdef ESP32 34 | constexpr int IUTBITRATE = 19200; 35 | #else 36 | constexpr int IUTBITRATE = 19200; 37 | #endif 38 | 39 | #if defined(ESP8266) 40 | constexpr EspSoftwareSerial::Config swSerialConfig = EspSoftwareSerial::SWSERIAL_8E1; 41 | constexpr SerialConfig hwSerialConfig = ::SERIAL_8E1; 42 | #elif defined(ESP32) 43 | constexpr EspSoftwareSerial::Config swSerialConfig = EspSoftwareSerial::SWSERIAL_8E1; 44 | constexpr uint32_t hwSerialConfig = ::SERIAL_8E1; 45 | #else 46 | constexpr unsigned swSerialConfig = 3; 47 | #endif 48 | constexpr bool invert = false; 49 | 50 | constexpr int BLOCKSIZE = 16; // use fractions of 256 51 | 52 | unsigned long start; 53 | const char bitRateTxt[] PROGMEM = "Effective data rate: "; 54 | int rxCount; 55 | int seqErrors; 56 | int parityErrors; 57 | int expected; 58 | constexpr int ReportInterval = IUTBITRATE / 8; 59 | 60 | #if defined(ESP8266) 61 | #if defined(HWLOOPBACK) 62 | HardwareSerial& repeater(Serial); 63 | EspSoftwareSerial::UART logger; 64 | #else 65 | EspSoftwareSerial::UART repeater; 66 | HardwareSerial& logger(Serial); 67 | #endif 68 | #elif defined(ESP32) 69 | #if defined(HWLOOPBACK) 70 | HardwareSerial& repeater(Serial2); 71 | #else 72 | EspSoftwareSerial::UART repeater; 73 | #endif 74 | HardwareSerial& logger(Serial); 75 | #else 76 | EspSoftwareSerial::UART repeater(14, 12); 77 | HardwareSerial& logger(Serial); 78 | #endif 79 | 80 | void setup() { 81 | #if defined(ESP8266) 82 | #if defined(HWLOOPBACK) 83 | repeater.begin(IUTBITRATE, hwSerialConfig, ::SERIAL_FULL, 1, invert); 84 | repeater.swap(); 85 | repeater.setRxBufferSize(2 * BLOCKSIZE); 86 | logger.begin(9600, EspSoftwareSerial::SWSERIAL_8N1, -1, TX); 87 | #else 88 | repeater.begin(IUTBITRATE, swSerialConfig, D7, D8, invert, 4 * BLOCKSIZE); 89 | #ifdef HALFDUPLEX 90 | repeater.enableIntTx(false); 91 | #endif 92 | logger.begin(9600); 93 | #endif 94 | #elif defined(ESP32) 95 | #if defined(HWLOOPBACK) 96 | repeater.begin(IUTBITRATE, hwSerialConfig, D7, D8, invert); 97 | repeater.setRxBufferSize(2 * BLOCKSIZE); 98 | #else 99 | repeater.begin(IUTBITRATE, swSerialConfig, D7, D8, invert, 4 * BLOCKSIZE); 100 | #ifdef HALFDUPLEX 101 | repeater.enableIntTx(false); 102 | #endif 103 | #endif 104 | logger.begin(9600); 105 | #else 106 | repeater.begin(IUTBITRATE); 107 | logger.begin(9600); 108 | #endif 109 | 110 | logger.println(PSTR("Repeater example for EspEspSoftwareSerial")); 111 | start = micros(); 112 | rxCount = 0; 113 | seqErrors = 0; 114 | parityErrors = 0; 115 | expected = -1; 116 | } 117 | 118 | void loop() { 119 | #ifdef HWLOOPBACK 120 | #if defined(ESP8266) 121 | if (repeater.hasOverrun()) { logger.println(PSTR("repeater.overrun")); } 122 | #endif 123 | #else 124 | if (repeater.overflow()) { logger.println(PSTR("repeater.overflow")); } 125 | #endif 126 | 127 | #ifdef HALFDUPLEX 128 | char block[BLOCKSIZE]; 129 | #endif 130 | // starting deadline for the first bytes to come in 131 | uint32_t deadlineStart = ESP.getCycleCount(); 132 | int inCnt = 0; 133 | while ((ESP.getCycleCount() - deadlineStart) < (1000000UL * 12 * BLOCKSIZE) / IUTBITRATE * 24 * ESP.getCpuFreqMHz()) { 134 | int avail = repeater.available(); 135 | for (int i = 0; i < avail; ++i) 136 | { 137 | int r = repeater.read(); 138 | if (r == -1) { logger.println(PSTR("read() == -1")); } 139 | if (expected == -1) { expected = r; } 140 | else { 141 | expected = (expected + 1) % (1UL << (5 + swSerialConfig % 4)); 142 | } 143 | if (r != expected) { 144 | ++seqErrors; 145 | expected = -1; 146 | } 147 | #ifndef HWLOOPBACK 148 | if (repeater.readParity() != (static_cast(swSerialConfig & 010) ? repeater.parityOdd(r) : repeater.parityEven(r))) 149 | { 150 | ++parityErrors; 151 | } 152 | #elif defined(ESP8266) 153 | // current ESP8266 API does not flag parity errors separately 154 | if (repeater.hasRxError()) 155 | { 156 | ++parityErrors; 157 | } 158 | #endif 159 | ++rxCount; 160 | #ifdef HALFDUPLEX 161 | block[inCnt] = r; 162 | #else 163 | repeater.write(r); 164 | #endif 165 | if (++inCnt >= BLOCKSIZE) { break; } 166 | } 167 | if (inCnt >= BLOCKSIZE) { break; } 168 | // wait for more outstanding bytes to trickle in 169 | if (avail) deadlineStart = ESP.getCycleCount(); 170 | } 171 | 172 | #ifdef HALFDUPLEX 173 | repeater.write(block, inCnt); 174 | #endif 175 | 176 | if (rxCount >= ReportInterval) { 177 | auto end = micros(); 178 | unsigned long interval = end - start; 179 | long cps = rxCount * (1000000.0 / interval); 180 | long seqErrorsps = seqErrors * (1000000.0 / interval); 181 | logger.print(String(FPSTR(bitRateTxt)) + 10 * cps + PSTR("bps, ") 182 | + seqErrorsps + PSTR("cps seq. errors (") + 100.0 * seqErrors / rxCount + PSTR("%)")); 183 | #ifndef HWLOOPBACK 184 | if (0 != (swSerialConfig & 070)) 185 | { 186 | logger.print(PSTR(" (")); logger.print(parityErrors); logger.println(PSTR(" parity errors)")); 187 | } 188 | else 189 | #endif 190 | { 191 | logger.println(); 192 | } 193 | start = end; 194 | rxCount = 0; 195 | seqErrors = 0; 196 | parityErrors = 0; 197 | expected = -1; 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /EspSoftwareSerial/examples/swsertest/swsertest.ino: -------------------------------------------------------------------------------- 1 | // On ESP8266: 2 | // At 80MHz runs up 57600bps, and at 160MHz CPU frequency up to 115200bps with only negligible errors. 3 | // Connect pin 13 to 15. 4 | // For verification and as a example for how to use SW serial on the USB to PC connection, 5 | // which allows the use of HW Serial on GPIO13 and GPIO15 instead, #define SWAPSERIAL below. 6 | // Notice how the bitrates are also swapped then between RX/TX and GPIO13/GPIO15. 7 | // Builtin debug output etc. must be stopped on HW Serial in this case, as it would interfere with the 8 | // external communication on GPIO13/GPIO15. 9 | 10 | #include 11 | 12 | #ifndef D5 13 | #if defined(ESP8266) 14 | #define D8 (15) 15 | #define D5 (14) 16 | #define D7 (13) 17 | #define D6 (12) 18 | #define RX (3) 19 | #define TX (1) 20 | #elif defined(ESP32) 21 | #define D8 (5) 22 | #define D5 (18) 23 | #define D7 (23) 24 | #define D6 (19) 25 | #define RX (3) 26 | #define TX (1) 27 | #endif 28 | #endif 29 | 30 | #ifdef ESP32 31 | #define BAUD_RATE 57600 32 | #else 33 | #define BAUD_RATE 57600 34 | #endif 35 | 36 | #undef SWAPSERIAL 37 | 38 | #ifndef SWAPSERIAL 39 | auto& usbSerial = Serial; 40 | EspSoftwareSerial::UART testSerial; 41 | #else 42 | EspSoftwareSerial::UART usbSerial; 43 | auto& testSerial = Serial; 44 | #endif 45 | 46 | void setup() { 47 | #ifndef SWAPSERIAL 48 | usbSerial.begin(115200); 49 | // Important: the buffer size optimizations here, in particular the isrBufSize (11) that is only sufficiently 50 | // large to hold a single word (up to start - 8 data - parity - stop), are on the basis that any char written 51 | // to the loopback EspSoftwareSerial adapter gets read before another write is performed. 52 | // Block writes with a size greater than 1 would usually fail. Do not copy this into your own project without 53 | // reading the documentation. 54 | testSerial.begin(BAUD_RATE, EspSoftwareSerial::SWSERIAL_8N1, D7, D8, false, 95, 11); 55 | #else 56 | testSerial.begin(115200); 57 | testSerial.setDebugOutput(false); 58 | testSerial.swap(); 59 | usbSerial.begin(BAUD_RATE, EspSoftwareSerial::SWSERIAL_8N1, RX, TX, false, 95); 60 | #endif 61 | 62 | usbSerial.println(PSTR("\nSoftware serial test started")); 63 | 64 | for (char ch = ' '; ch <= 'z'; ch++) { 65 | testSerial.write(ch); 66 | } 67 | testSerial.println(); 68 | } 69 | 70 | void loop() { 71 | while (testSerial.available() > 0) { 72 | usbSerial.write(testSerial.read()); 73 | yield(); 74 | } 75 | while (usbSerial.available() > 0) { 76 | testSerial.write(usbSerial.read()); 77 | yield(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /EspSoftwareSerial/keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map for EspSoftwareSerial 3 | # (esp8266) 4 | ####################################### 5 | 6 | ####################################### 7 | # Datatypes (KEYWORD1) 8 | ####################################### 9 | 10 | EspSoftwareSerial KEYWORD1 11 | SoftwareSerial KEYWORD1 12 | 13 | ####################################### 14 | # Methods and Functions (KEYWORD2) 15 | ####################################### 16 | 17 | begin KEYWORD2 18 | baudRate KEYWORD2 19 | setTransmitEnablePin KEYWORD2 20 | enableIntTx KEYWORD2 21 | overflow KEYWORD2 22 | available KEYWORD2 23 | peek KEYWORD2 24 | read KEYWORD2 25 | flush KEYWORD2 26 | write KEYWORD2 27 | enableRx KEYWORD2 28 | enableTx KEYWORD2 29 | listen KEYWORD2 30 | end KEYWORD2 31 | isListening KEYWORD2 32 | stopListening KEYWORD2 33 | onReceive KEYWORD2 34 | 35 | ####################################### 36 | # Constants (LITERAL1) 37 | ####################################### 38 | 39 | SW_SERIAL_UNUSED_PIN LITERAL1 40 | SWSERIAL_5N1 LITERAL1 41 | SWSERIAL_6N1 LITERAL1 42 | SWSERIAL_7N1 LITERAL1 43 | SWSERIAL_8N1 LITERAL1 44 | -------------------------------------------------------------------------------- /EspSoftwareSerial/library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "EspSoftwareSerial", 3 | "version": "8.1.0", 4 | "description": "Implementation of the Arduino software serial for ESP8266/ESP32.", 5 | "keywords": [ 6 | "serial", "io", "softwareserial" 7 | ], 8 | "repository": 9 | { 10 | "type": "git", 11 | "url": "https://github.com/plerup/espsoftwareserial" 12 | }, 13 | "authors": [ 14 | { 15 | "name": "Dirk Kaar" 16 | }, 17 | { 18 | "name": "Peter Lerup" 19 | } 20 | ], 21 | "license": "LGPL-2.1+", 22 | "frameworks": "arduino", 23 | "platforms": [ 24 | "espressif8266", "espressif32" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /EspSoftwareSerial/library.properties: -------------------------------------------------------------------------------- 1 | name=EspSoftwareSerial 2 | version=8.1.0 3 | author=Dirk Kaar, Peter Lerup 4 | maintainer=Dirk Kaar 5 | sentence=Implementation of the Arduino software serial for ESP8266/ESP32. 6 | paragraph= 7 | category=Signal Input/Output 8 | url=https://github.com/plerup/espsoftwareserial/ 9 | architectures=esp8266,esp32 10 | -------------------------------------------------------------------------------- /EspSoftwareSerial/src/SoftwareSerial.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | SoftwareSerial.cpp - Implementation of the Arduino software serial for ESP8266/ESP32. 4 | Copyright (c) 2015-2016 Peter Lerup. All rights reserved. 5 | Copyright (c) 2018-2019 Dirk O. Kaar. All rights reserved. 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | 21 | */ 22 | 23 | #include "SoftwareSerial.h" 24 | #include 25 | 26 | using namespace EspSoftwareSerial; 27 | 28 | #ifndef ESP32 29 | uint32_t UARTBase::m_savedPS = 0; 30 | #else 31 | portMUX_TYPE UARTBase::m_interruptsMux = portMUX_INITIALIZER_UNLOCKED; 32 | #endif 33 | 34 | ALWAYS_INLINE_ATTR inline void IRAM_ATTR UARTBase::disableInterrupts() 35 | { 36 | #ifndef ESP32 37 | m_savedPS = xt_rsil(15); 38 | #else 39 | taskENTER_CRITICAL(&m_interruptsMux); 40 | #endif 41 | } 42 | 43 | ALWAYS_INLINE_ATTR inline void IRAM_ATTR UARTBase::restoreInterrupts() 44 | { 45 | #ifndef ESP32 46 | xt_wsr_ps(m_savedPS); 47 | #else 48 | taskEXIT_CRITICAL(&m_interruptsMux); 49 | #endif 50 | } 51 | 52 | constexpr uint8_t BYTE_ALL_BITS_SET = ~static_cast(0); 53 | 54 | UARTBase::UARTBase() { 55 | } 56 | 57 | UARTBase::UARTBase(int8_t rxPin, int8_t txPin, bool invert) 58 | { 59 | m_rxPin = rxPin; 60 | m_txPin = txPin; 61 | m_invert = invert; 62 | } 63 | 64 | UARTBase::~UARTBase() { 65 | end(); 66 | } 67 | 68 | void UARTBase::setRxGPIOPinMode() { 69 | if (m_rxValid) { 70 | pinMode(m_rxPin, m_rxGPIOHasPullUp && m_rxGPIOPullUpEnabled ? INPUT_PULLUP : INPUT); 71 | } 72 | } 73 | 74 | void UARTBase::setTxGPIOPinMode() { 75 | if (m_txValid) { 76 | pinMode(m_txPin, m_txGPIOOpenDrain ? OUTPUT_OPEN_DRAIN : OUTPUT); 77 | } 78 | } 79 | 80 | void UARTBase::begin(uint32_t baud, Config config, 81 | int8_t rxPin, int8_t txPin, 82 | bool invert) { 83 | if (-1 != rxPin) m_rxPin = rxPin; 84 | if (-1 != txPin) m_txPin = txPin; 85 | m_oneWire = (m_rxPin == m_txPin); 86 | m_invert = invert; 87 | m_dataBits = 5 + (config & 07); 88 | m_parityMode = static_cast(config & 070); 89 | m_stopBits = 1 + ((config & 0300) ? 1 : 0); 90 | m_pduBits = m_dataBits + static_cast(m_parityMode) + m_stopBits; 91 | m_bitTicks = (microsToTicks(1000000UL) + baud / 2) / baud; 92 | m_intTxEnabled = true; 93 | } 94 | 95 | void UARTBase::beginRx(bool hasPullUp, int bufCapacity, int isrBufCapacity) { 96 | m_rxGPIOHasPullUp = hasPullUp; 97 | m_rxReg = portInputRegister(digitalPinToPort(m_rxPin)); 98 | m_rxBitMask = digitalPinToBitMask(m_rxPin); 99 | m_buffer.reset(new circular_queue((bufCapacity > 0) ? bufCapacity : 64)); 100 | if (m_parityMode) 101 | { 102 | m_parityBuffer.reset(new circular_queue((m_buffer->capacity() + 7) / 8)); 103 | m_parityInPos = m_parityOutPos = 1; 104 | } 105 | m_isrBuffer.reset(new circular_queue((isrBufCapacity > 0) ? 106 | isrBufCapacity : m_buffer->capacity() * (2 + m_dataBits + static_cast(m_parityMode)))); 107 | if (m_buffer && (!m_parityMode || m_parityBuffer) && m_isrBuffer) { 108 | m_rxValid = true; 109 | setRxGPIOPinMode(); 110 | } 111 | } 112 | 113 | void UARTBase::beginTx() { 114 | #if !defined(ESP8266) 115 | m_txReg = portOutputRegister(digitalPinToPort(m_txPin)); 116 | #endif 117 | m_txBitMask = digitalPinToBitMask(m_txPin); 118 | m_txValid = true; 119 | if (!m_oneWire) { 120 | setTxGPIOPinMode(); 121 | digitalWrite(m_txPin, !m_invert); 122 | } 123 | } 124 | 125 | void UARTBase::end() 126 | { 127 | enableRx(false); 128 | m_txValid = false; 129 | if (m_buffer) { 130 | m_buffer.reset(); 131 | } 132 | m_parityBuffer.reset(); 133 | if (m_isrBuffer) { 134 | m_isrBuffer.reset(); 135 | } 136 | } 137 | 138 | uint32_t UARTBase::baudRate() { 139 | return 1000000UL / ticksToMicros(m_bitTicks); 140 | } 141 | 142 | void UARTBase::setTransmitEnablePin(int8_t txEnablePin) { 143 | if (-1 != txEnablePin) { 144 | m_txEnableValid = true; 145 | m_txEnablePin = txEnablePin; 146 | pinMode(m_txEnablePin, OUTPUT); 147 | digitalWrite(m_txEnablePin, LOW); 148 | } 149 | else { 150 | m_txEnableValid = false; 151 | } 152 | } 153 | 154 | void UARTBase::enableIntTx(bool on) { 155 | m_intTxEnabled = on; 156 | } 157 | 158 | void UARTBase::enableRxGPIOPullUp(bool on) { 159 | m_rxGPIOPullUpEnabled = on; 160 | setRxGPIOPinMode(); 161 | } 162 | 163 | void UARTBase::enableTxGPIOOpenDrain(bool on) { 164 | m_txGPIOOpenDrain = on; 165 | setTxGPIOPinMode(); 166 | } 167 | 168 | void UARTBase::enableTx(bool on) { 169 | if (m_txValid && m_oneWire) { 170 | if (on) { 171 | enableRx(false); 172 | setTxGPIOPinMode(); 173 | digitalWrite(m_txPin, !m_invert); 174 | } 175 | else { 176 | setRxGPIOPinMode(); 177 | enableRx(true); 178 | } 179 | } 180 | } 181 | 182 | void UARTBase::enableRx(bool on) { 183 | if (m_rxValid && on != m_rxEnabled) { 184 | if (on) { 185 | m_rxLastBit = m_pduBits - 1; 186 | // Init to stop bit level and current tick 187 | m_isrLastTick = (microsToTicks(micros()) | 1) ^ m_invert; 188 | if (m_bitTicks >= microsToTicks(1000000UL / 74880UL)) 189 | attachInterruptArg(digitalPinToInterrupt(m_rxPin), reinterpret_cast(rxBitISR), this, CHANGE); 190 | else 191 | attachInterruptArg(digitalPinToInterrupt(m_rxPin), reinterpret_cast(rxBitSyncISR), this, m_invert ? RISING : FALLING); 192 | } 193 | else { 194 | detachInterrupt(digitalPinToInterrupt(m_rxPin)); 195 | } 196 | m_rxEnabled = on; 197 | } 198 | } 199 | 200 | int UARTBase::read() { 201 | if (!m_rxValid) { return -1; } 202 | if (!m_buffer->available()) { 203 | rxBits(); 204 | if (!m_buffer->available()) { return -1; } 205 | } 206 | auto val = m_buffer->pop(); 207 | if (m_parityBuffer) 208 | { 209 | m_lastReadParity = m_parityBuffer->peek() & m_parityOutPos; 210 | m_parityOutPos <<= 1; 211 | if (!m_parityOutPos) 212 | { 213 | m_parityOutPos = 1; 214 | m_parityBuffer->pop(); 215 | } 216 | } 217 | return val; 218 | } 219 | 220 | int UARTBase::read(uint8_t* buffer, size_t size) { 221 | if (!m_rxValid) { return 0; } 222 | int avail; 223 | if (0 == (avail = m_buffer->pop_n(buffer, size))) { 224 | rxBits(); 225 | avail = m_buffer->pop_n(buffer, size); 226 | } 227 | if (!avail) return 0; 228 | if (m_parityBuffer) { 229 | uint32_t parityBits = avail; 230 | while (m_parityOutPos >>= 1) ++parityBits; 231 | m_parityOutPos = (1 << (parityBits % 8)); 232 | m_parityBuffer->pop_n(nullptr, parityBits / 8); 233 | } 234 | return avail; 235 | } 236 | 237 | size_t UARTBase::readBytes(uint8_t* buffer, size_t size) { 238 | if (!m_rxValid || !size) { return 0; } 239 | size_t count = 0; 240 | auto start = millis(); 241 | do { 242 | auto readCnt = read(&buffer[count], size - count); 243 | count += readCnt; 244 | if (count >= size) break; 245 | if (readCnt) { 246 | start = millis(); 247 | } 248 | else { 249 | optimistic_yield(1000UL); 250 | } 251 | } while (millis() - start < _timeout); 252 | return count; 253 | } 254 | 255 | int UARTBase::available() { 256 | if (!m_rxValid) { return 0; } 257 | rxBits(); 258 | int avail = m_buffer->available(); 259 | if (!avail) { 260 | optimistic_yield(10000UL); 261 | } 262 | return avail; 263 | } 264 | 265 | void UARTBase::lazyDelay() { 266 | // Reenable interrupts while delaying to avoid other tasks piling up 267 | if (!m_intTxEnabled) { restoreInterrupts(); } 268 | const auto expired = microsToTicks(micros()) - m_periodStart; 269 | const int32_t remaining = m_periodDuration - expired; 270 | const uint32_t ms = remaining > 0 ? ticksToMicros(remaining) / 1000UL : 0; 271 | if (ms > 0) 272 | { 273 | delay(ms); 274 | } 275 | else 276 | { 277 | optimistic_yield(10000UL); 278 | } 279 | // Assure that below-ms part of delays are not elided 280 | preciseDelay(); 281 | // Disable interrupts again if applicable 282 | if (!m_intTxEnabled) { disableInterrupts(); } 283 | } 284 | 285 | void IRAM_ATTR UARTBase::preciseDelay() { 286 | uint32_t ticks; 287 | do { 288 | ticks = microsToTicks(micros()); 289 | } while ((ticks - m_periodStart) < m_periodDuration); 290 | m_periodDuration = 0; 291 | m_periodStart = ticks; 292 | } 293 | 294 | void IRAM_ATTR UARTBase::writePeriod( 295 | uint32_t dutyCycle, uint32_t offCycle, bool withStopBit) { 296 | preciseDelay(); 297 | if (dutyCycle) 298 | { 299 | #if defined(ESP8266) 300 | if (16 == m_txPin) { 301 | GP16O = 1; 302 | } 303 | else { 304 | GPOS = m_txBitMask; 305 | } 306 | #else 307 | *m_txReg = *m_txReg | m_txBitMask; 308 | #endif 309 | m_periodDuration += dutyCycle; 310 | if (offCycle || (withStopBit && !m_invert)) { 311 | if (!withStopBit || m_invert) { 312 | preciseDelay(); 313 | } 314 | else { 315 | lazyDelay(); 316 | } 317 | } 318 | } 319 | if (offCycle) 320 | { 321 | #if defined(ESP8266) 322 | if (16 == m_txPin) { 323 | GP16O = 0; 324 | } 325 | else { 326 | GPOC = m_txBitMask; 327 | } 328 | #else 329 | *m_txReg = *m_txReg & ~m_txBitMask; 330 | #endif 331 | m_periodDuration += offCycle; 332 | if (withStopBit && m_invert) lazyDelay(); 333 | } 334 | } 335 | 336 | size_t UARTBase::write(uint8_t byte) { 337 | return write(&byte, 1); 338 | } 339 | 340 | size_t UARTBase::write(uint8_t byte, Parity parity) { 341 | return write(&byte, 1, parity); 342 | } 343 | 344 | size_t UARTBase::write(const uint8_t* buffer, size_t size) { 345 | return write(buffer, size, m_parityMode); 346 | } 347 | 348 | size_t IRAM_ATTR UARTBase::write(const uint8_t* buffer, size_t size, Parity parity) { 349 | if (m_rxValid) { rxBits(); } 350 | if (!m_txValid) { return -1; } 351 | 352 | if (m_txEnableValid) { 353 | digitalWrite(m_txEnablePin, HIGH); 354 | } 355 | // Stop bit: if inverted, LOW, otherwise HIGH 356 | bool b = !m_invert; 357 | uint32_t dutyCycle = 0; 358 | uint32_t offCycle = 0; 359 | if (!m_intTxEnabled) { 360 | // Disable interrupts in order to get a clean transmit timing 361 | disableInterrupts(); 362 | } 363 | const uint32_t dataMask = ((1UL << m_dataBits) - 1); 364 | bool withStopBit = true; 365 | m_periodDuration = 0; 366 | m_periodStart = microsToTicks(micros()); 367 | for (size_t cnt = 0; cnt < size; ++cnt) { 368 | uint8_t byte = pgm_read_byte(buffer + cnt) & dataMask; 369 | // push LSB start-data-parity-stop bit pattern into uint32_t 370 | // Stop bits: HIGH 371 | uint32_t word = ~0UL; 372 | // inverted parity bit, performance tweak for xor all-bits-set word 373 | if (parity && m_parityMode) 374 | { 375 | uint32_t parityBit; 376 | switch (parity) 377 | { 378 | case PARITY_EVEN: 379 | // from inverted, so use odd parity 380 | parityBit = byte; 381 | parityBit ^= parityBit >> 4; 382 | parityBit &= 0xf; 383 | parityBit = (0x9669 >> parityBit) & 1; 384 | break; 385 | case PARITY_ODD: 386 | // from inverted, so use even parity 387 | parityBit = byte; 388 | parityBit ^= parityBit >> 4; 389 | parityBit &= 0xf; 390 | parityBit = (0x6996 >> parityBit) & 1; 391 | break; 392 | case PARITY_MARK: 393 | parityBit = 0; 394 | break; 395 | case PARITY_SPACE: 396 | // suppresses warning parityBit uninitialized 397 | default: 398 | parityBit = 1; 399 | break; 400 | } 401 | word ^= parityBit; 402 | } 403 | word <<= m_dataBits; 404 | word |= byte; 405 | // Start bit: LOW 406 | word <<= 1; 407 | if (m_invert) word = ~word; 408 | for (int i = 0; i <= m_pduBits; ++i) { 409 | bool pb = b; 410 | b = word & (1UL << i); 411 | if (!pb && b) { 412 | writePeriod(dutyCycle, offCycle, withStopBit); 413 | withStopBit = false; 414 | dutyCycle = offCycle = 0; 415 | } 416 | if (b) { 417 | dutyCycle += m_bitTicks; 418 | } 419 | else { 420 | offCycle += m_bitTicks; 421 | } 422 | } 423 | withStopBit = true; 424 | } 425 | writePeriod(dutyCycle, offCycle, true); 426 | if (!m_intTxEnabled) { 427 | // restore the interrupt state if applicable 428 | restoreInterrupts(); 429 | } 430 | if (m_txEnableValid) { 431 | digitalWrite(m_txEnablePin, LOW); 432 | } 433 | return size; 434 | } 435 | 436 | void UARTBase::flush() { 437 | if (!m_rxValid) { return; } 438 | m_buffer->flush(); 439 | if (m_parityBuffer) 440 | { 441 | m_parityInPos = m_parityOutPos = 1; 442 | m_parityBuffer->flush(); 443 | } 444 | } 445 | 446 | bool UARTBase::overflow() { 447 | bool res = m_overflow; 448 | m_overflow = false; 449 | return res; 450 | } 451 | 452 | int UARTBase::peek() { 453 | if (!m_rxValid) { return -1; } 454 | if (!m_buffer->available()) { 455 | rxBits(); 456 | if (!m_buffer->available()) return -1; 457 | } 458 | auto val = m_buffer->peek(); 459 | if (m_parityBuffer) m_lastReadParity = m_parityBuffer->peek() & m_parityOutPos; 460 | return val; 461 | } 462 | 463 | void UARTBase::rxBits() { 464 | #ifdef ESP8266 465 | if (m_isrOverflow.load()) { 466 | m_overflow = true; 467 | m_isrOverflow.store(false); 468 | } 469 | #else 470 | if (m_isrOverflow.exchange(false)) { 471 | m_overflow = true; 472 | } 473 | #endif 474 | 475 | m_isrBuffer->for_each(m_isrBufferForEachDel); 476 | 477 | // A stop bit can go undetected if leading data bits are at same level 478 | // and there was also no next start bit yet, so one word may be pending. 479 | // Check that there was no new ISR data received in the meantime, inserting an 480 | // extraneous stop level bit out of sequence breaks rx. 481 | if (m_rxLastBit < m_pduBits - 1) { 482 | const uint32_t detectionTicks = (m_pduBits - 1 - m_rxLastBit) * m_bitTicks; 483 | if (!m_isrBuffer->available() && microsToTicks(micros()) - m_isrLastTick > detectionTicks) { 484 | // Produce faux stop bit level, prevents start bit maldetection 485 | // tick's LSB is repurposed for the level bit 486 | rxBits(((m_isrLastTick + detectionTicks) | 1) ^ m_invert); 487 | } 488 | } 489 | } 490 | 491 | void UARTBase::rxBits(const uint32_t isrTick) { 492 | const bool level = (m_isrLastTick & 1) ^ m_invert; 493 | 494 | // error introduced by edge value in LSB of isrTick is negligible 495 | uint32_t ticks = isrTick - m_isrLastTick; 496 | m_isrLastTick = isrTick; 497 | 498 | uint32_t bits = ticks / m_bitTicks; 499 | if (ticks % m_bitTicks > (m_bitTicks >> 1)) ++bits; 500 | while (bits > 0) { 501 | // start bit detection 502 | if (m_rxLastBit >= (m_pduBits - 1)) { 503 | // leading edge of start bit? 504 | if (level) break; 505 | m_rxLastBit = -1; 506 | --bits; 507 | continue; 508 | } 509 | // data bits 510 | if (m_rxLastBit < (m_dataBits - 1)) { 511 | uint8_t dataBits = min(bits, static_cast(m_dataBits - 1 - m_rxLastBit)); 512 | m_rxLastBit += dataBits; 513 | bits -= dataBits; 514 | m_rxCurByte >>= dataBits; 515 | if (level) { m_rxCurByte |= (BYTE_ALL_BITS_SET << (8 - dataBits)); } 516 | continue; 517 | } 518 | // parity bit 519 | if (m_parityMode && m_rxLastBit == (m_dataBits - 1)) { 520 | ++m_rxLastBit; 521 | --bits; 522 | m_rxCurParity = level; 523 | continue; 524 | } 525 | // stop bits 526 | // Store the received value in the buffer unless we have an overflow 527 | // if not high stop bit level, discard word 528 | if (bits >= static_cast(m_pduBits - 1 - m_rxLastBit) && level) { 529 | m_rxCurByte >>= (sizeof(uint8_t) * 8 - m_dataBits); 530 | if (!m_buffer->push(m_rxCurByte)) { 531 | m_overflow = true; 532 | } 533 | else { 534 | if (m_parityBuffer) 535 | { 536 | if (m_rxCurParity) { 537 | m_parityBuffer->pushpeek() |= m_parityInPos; 538 | } 539 | else { 540 | m_parityBuffer->pushpeek() &= ~m_parityInPos; 541 | } 542 | m_parityInPos <<= 1; 543 | if (!m_parityInPos) 544 | { 545 | m_parityBuffer->push(); 546 | m_parityInPos = 1; 547 | } 548 | } 549 | } 550 | } 551 | m_rxLastBit = m_pduBits - 1; 552 | // reset to 0 is important for masked bit logic 553 | m_rxCurByte = 0; 554 | m_rxCurParity = false; 555 | break; 556 | } 557 | } 558 | 559 | void IRAM_ATTR UARTBase::rxBitISR(UARTBase* self) { 560 | const bool level = *self->m_rxReg & self->m_rxBitMask; 561 | const uint32_t curTick = microsToTicks(micros()); 562 | const bool empty = !self->m_isrBuffer->available(); 563 | 564 | // Store level and tick in the buffer unless we have an overflow 565 | // tick's LSB is repurposed for the level bit 566 | if (!self->m_isrBuffer->push((curTick | 1U) ^ !level)) self->m_isrOverflow.store(true); 567 | // Trigger rx callback only when receiver is starved 568 | if (empty) self->m_rxHandler(); 569 | } 570 | 571 | void IRAM_ATTR UARTBase::rxBitSyncISR(UARTBase* self) { 572 | bool level = self->m_invert; 573 | const uint32_t start = microsToTicks(micros()); 574 | uint32_t wait = self->m_bitTicks; 575 | const bool empty = !self->m_isrBuffer->available(); 576 | 577 | // Store level and tick in the buffer unless we have an overflow 578 | // tick's LSB is repurposed for the level bit 579 | if (!self->m_isrBuffer->push(((start + wait) | 1U) ^ !level)) self->m_isrOverflow.store(true); 580 | 581 | for (uint32_t i = 0; i < self->m_pduBits; ++i) { 582 | while (microsToTicks(micros()) - start < wait) {}; 583 | wait += self->m_bitTicks; 584 | 585 | // Store level and tick in the buffer unless we have an overflow 586 | // tick's LSB is repurposed for the level bit 587 | if (static_cast(*self->m_rxReg & self->m_rxBitMask) != level) 588 | { 589 | if (!self->m_isrBuffer->push(((start + wait) | 1U) ^ level)) self->m_isrOverflow.store(true); 590 | level = !level; 591 | } 592 | } 593 | // Trigger rx callback only when receiver is starved 594 | if (empty) self->m_rxHandler(); 595 | } 596 | 597 | void UARTBase::onReceive(const Delegate& handler) { 598 | disableInterrupts(); 599 | m_rxHandler = handler; 600 | restoreInterrupts(); 601 | } 602 | 603 | void UARTBase::onReceive(Delegate&& handler) { 604 | disableInterrupts(); 605 | m_rxHandler = std::move(handler); 606 | restoreInterrupts(); 607 | } 608 | 609 | #if __GNUC__ < 12 610 | // The template member functions below must be in IRAM, but due to a bug GCC doesn't currently 611 | // honor the attribute. Instead, it is possible to do explicit specialization and adorn 612 | // these with the IRAM attribute: 613 | // Delegate<>::operator (), circular_queue<>::available, 614 | // circular_queue<>::available_for_push, circular_queue<>::push_peek, circular_queue<>::push 615 | 616 | template void IRAM_ATTR delegate::detail::DelegateImpl::operator()() const; 617 | template size_t IRAM_ATTR circular_queue::available() const; 618 | template bool IRAM_ATTR circular_queue::push(uint32_t&&); 619 | template bool IRAM_ATTR circular_queue::push(const uint32_t&); 620 | #endif // __GNUC__ < 12 621 | 622 | -------------------------------------------------------------------------------- /EspSoftwareSerial/src/SoftwareSerial.h: -------------------------------------------------------------------------------- 1 | /* 2 | SoftwareSerial.h - Implementation of the Arduino software serial for ESP8266/ESP32. 3 | Copyright (c) 2015-2016 Peter Lerup. All rights reserved. 4 | Copyright (c) 2018-2019 Dirk O. Kaar. All rights reserved. 5 | 6 | This library is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU Lesser General Public 8 | License as published by the Free Software Foundation; either 9 | version 2.1 of the License, or (at your option) any later version. 10 | 11 | This library is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | Lesser General Public License for more details. 15 | 16 | You should have received a copy of the GNU Lesser General Public 17 | License along with this library; if not, write to the Free Software 18 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | 20 | */ 21 | 22 | #ifndef __SoftwareSerial_h 23 | #define __SoftwareSerial_h 24 | 25 | #include "circular_queue/circular_queue.h" 26 | #include 27 | 28 | namespace EspSoftwareSerial { 29 | 30 | // Interface definition for template argument of BasicUART 31 | class IGpioCapabilities { 32 | public: 33 | static constexpr bool isValidPin(int8_t pin); 34 | static constexpr bool isValidInputPin(int8_t pin); 35 | static constexpr bool isValidOutputPin(int8_t pin); 36 | // result is only defined for a valid Rx pin 37 | static constexpr bool hasPullUp(int8_t pin); 38 | }; 39 | 40 | class GpioCapabilities : private IGpioCapabilities { 41 | public: 42 | static constexpr bool isValidPin(int8_t pin) { 43 | #if defined(ESP8266) 44 | return (pin >= 0 && pin <= 16) && !isFlashInterfacePin(pin); 45 | #elif defined(ESP32) 46 | // Remove the strapping pins as defined in the datasheets, they affect bootup and other critical operations 47 | // Remmove the flash memory pins on related devices, since using these causes memory access issues. 48 | #ifdef CONFIG_IDF_TARGET_ESP32 49 | // Datasheet https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf, 50 | // Pinout https://docs.espressif.com/projects/esp-idf/en/latest/esp32/_images/esp32-devkitC-v4-pinout.jpg 51 | return (pin == 1) || (pin >= 3 && pin <= 5) || 52 | (pin >= 12 && pin <= 15) || 53 | (!psramFound() && pin >= 16 && pin <= 17) || 54 | (pin >= 18 && pin <= 19) || 55 | (pin >= 21 && pin <= 23) || (pin >= 25 && pin <= 27) || (pin >= 32 && pin <= 39); 56 | #elif CONFIG_IDF_TARGET_ESP32S2 57 | // Datasheet https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf, 58 | // Pinout https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/_images/esp32-s2_saola1-pinout.jpg 59 | return (pin >= 1 && pin <= 21) || (pin >= 33 && pin <= 44); 60 | #elif CONFIG_IDF_TARGET_ESP32C3 61 | // Datasheet https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf, 62 | // Pinout https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/_images/esp32-c3-devkitm-1-v1-pinout.jpg 63 | return (pin >= 0 && pin <= 1) || (pin >= 3 && pin <= 7) || (pin >= 18 && pin <= 21); 64 | #else 65 | return pin >= 0; 66 | #endif 67 | #else 68 | return pin >= 0; 69 | #endif 70 | } 71 | 72 | static constexpr bool isValidInputPin(int8_t pin) { 73 | return isValidPin(pin) 74 | #if defined(ESP8266) 75 | && (pin != 16) 76 | #endif 77 | ; 78 | } 79 | 80 | static constexpr bool isValidOutputPin(int8_t pin) { 81 | return isValidPin(pin) 82 | #if defined(ESP32) 83 | #ifdef CONFIG_IDF_TARGET_ESP32 84 | && (pin < 34) 85 | #elif CONFIG_IDF_TARGET_ESP32S2 86 | && (pin <= 45) 87 | #elif CONFIG_IDF_TARGET_ESP32C3 88 | // no restrictions 89 | #endif 90 | #endif 91 | ; 92 | } 93 | 94 | // result is only defined for a valid Rx pin 95 | static constexpr bool hasPullUp(int8_t pin) { 96 | #if defined(ESP32) 97 | return !(pin >= 34 && pin <= 39); 98 | #else 99 | (void)pin; 100 | return true; 101 | #endif 102 | } 103 | }; 104 | 105 | enum Parity : uint8_t { 106 | PARITY_NONE = 000, 107 | PARITY_EVEN = 020, 108 | PARITY_ODD = 030, 109 | PARITY_MARK = 040, 110 | PARITY_SPACE = 070, 111 | }; 112 | 113 | enum Config { 114 | SWSERIAL_5N1 = PARITY_NONE, 115 | SWSERIAL_6N1, 116 | SWSERIAL_7N1, 117 | SWSERIAL_8N1, 118 | SWSERIAL_5E1 = PARITY_EVEN, 119 | SWSERIAL_6E1, 120 | SWSERIAL_7E1, 121 | SWSERIAL_8E1, 122 | SWSERIAL_5O1 = PARITY_ODD, 123 | SWSERIAL_6O1, 124 | SWSERIAL_7O1, 125 | SWSERIAL_8O1, 126 | SWSERIAL_5M1 = PARITY_MARK, 127 | SWSERIAL_6M1, 128 | SWSERIAL_7M1, 129 | SWSERIAL_8M1, 130 | SWSERIAL_5S1 = PARITY_SPACE, 131 | SWSERIAL_6S1, 132 | SWSERIAL_7S1, 133 | SWSERIAL_8S1, 134 | SWSERIAL_5N2 = 0200 | PARITY_NONE, 135 | SWSERIAL_6N2, 136 | SWSERIAL_7N2, 137 | SWSERIAL_8N2, 138 | SWSERIAL_5E2 = 0200 | PARITY_EVEN, 139 | SWSERIAL_6E2, 140 | SWSERIAL_7E2, 141 | SWSERIAL_8E2, 142 | SWSERIAL_5O2 = 0200 | PARITY_ODD, 143 | SWSERIAL_6O2, 144 | SWSERIAL_7O2, 145 | SWSERIAL_8O2, 146 | SWSERIAL_5M2 = 0200 | PARITY_MARK, 147 | SWSERIAL_6M2, 148 | SWSERIAL_7M2, 149 | SWSERIAL_8M2, 150 | SWSERIAL_5S2 = 0200 | PARITY_SPACE, 151 | SWSERIAL_6S2, 152 | SWSERIAL_7S2, 153 | SWSERIAL_8S2, 154 | }; 155 | 156 | /// This class is compatible with the corresponding AVR one, however, 157 | /// the constructor takes no arguments, for compatibility with the 158 | /// HardwareSerial class. 159 | /// Instead, the begin() function handles pin assignments and logic inversion. 160 | /// It also has optional input buffer capacity arguments for byte buffer and ISR bit buffer. 161 | /// Bitrates up to at least 115200 can be used. 162 | class UARTBase : public Stream { 163 | public: 164 | UARTBase(); 165 | /// Ctor to set defaults for pins. 166 | /// @param rxPin the GPIO pin used for RX 167 | /// @param txPin -1 for onewire protocol, GPIO pin used for twowire TX 168 | UARTBase(int8_t rxPin, int8_t txPin = -1, bool invert = false); 169 | UARTBase(const UARTBase&) = delete; 170 | UARTBase& operator= (const UARTBase&) = delete; 171 | virtual ~UARTBase(); 172 | /// Configure the UARTBase object for use. 173 | /// @param baud the TX/RX bitrate 174 | /// @param config sets databits, parity, and stop bit count 175 | /// @param rxPin -1 or default: either no RX pin, or keeps the rxPin set in the ctor 176 | /// @param txPin -1 or default: either no TX pin (onewire), or keeps the txPin set in the ctor 177 | /// @param invert true: uses invert line level logic 178 | /// @param bufCapacity the capacity for the received bytes buffer 179 | /// @param isrBufCapacity 0: derived from bufCapacity. The capacity of the internal asynchronous 180 | /// bit receive buffer, a suggested size is bufCapacity times the sum of 181 | /// start, data, parity and stop bit count. 182 | void begin(uint32_t baud, Config config, 183 | int8_t rxPin, int8_t txPin, bool invert); 184 | 185 | uint32_t baudRate(); 186 | /// Transmit control pin. 187 | void setTransmitEnablePin(int8_t txEnablePin); 188 | /// Enable (default) or disable interrupts during tx. 189 | void enableIntTx(bool on); 190 | /// Enable (default) or disable internal rx GPIO pull-up. 191 | void enableRxGPIOPullUp(bool on); 192 | /// Enable or disable (default) tx GPIO output mode. 193 | void enableTxGPIOOpenDrain(bool on); 194 | 195 | bool overflow(); 196 | 197 | int available() override; 198 | #if defined(ESP8266) 199 | int availableForWrite() override { 200 | #else 201 | int availableForWrite() { 202 | #endif 203 | if (!m_txValid) return 0; 204 | return 1; 205 | } 206 | int peek() override; 207 | int read() override; 208 | /// @returns The verbatim parity bit associated with the last successful read() or peek() call 209 | bool readParity() 210 | { 211 | return m_lastReadParity; 212 | } 213 | /// @returns The calculated bit for even parity of the parameter byte 214 | static bool parityEven(uint8_t byte) { 215 | byte ^= byte >> 4; 216 | byte &= 0xf; 217 | return (0x6996 >> byte) & 1; 218 | } 219 | /// @returns The calculated bit for odd parity of the parameter byte 220 | static bool parityOdd(uint8_t byte) { 221 | byte ^= byte >> 4; 222 | byte &= 0xf; 223 | return (0x9669 >> byte) & 1; 224 | } 225 | /// The read(buffer, size) functions are non-blocking, the same as readBytes but without timeout 226 | int read(uint8_t* buffer, size_t size) 227 | #if defined(ESP8266) 228 | override 229 | #endif 230 | ; 231 | /// The read(buffer, size) functions are non-blocking, the same as readBytes but without timeout 232 | int read(char* buffer, size_t size) { 233 | return read(reinterpret_cast(buffer), size); 234 | } 235 | /// @returns The number of bytes read into buffer, up to size. Times out if the limit set through 236 | /// Stream::setTimeout() is reached. 237 | size_t readBytes(uint8_t* buffer, size_t size) override; 238 | /// @returns The number of bytes read into buffer, up to size. Times out if the limit set through 239 | /// Stream::setTimeout() is reached. 240 | size_t readBytes(char* buffer, size_t size) override { 241 | return readBytes(reinterpret_cast(buffer), size); 242 | } 243 | void flush() override; 244 | size_t write(uint8_t byte) override; 245 | size_t write(uint8_t byte, Parity parity); 246 | size_t write(const uint8_t* buffer, size_t size) override; 247 | size_t write(const char* buffer, size_t size) { 248 | return write(reinterpret_cast(buffer), size); 249 | } 250 | size_t write(const uint8_t* buffer, size_t size, Parity parity); 251 | size_t write(const char* buffer, size_t size, Parity parity) { 252 | return write(reinterpret_cast(buffer), size, parity); 253 | } 254 | operator bool() const { 255 | return (-1 == m_rxPin || m_rxValid) && (-1 == m_txPin || m_txValid) && !(-1 == m_rxPin && m_oneWire); 256 | } 257 | 258 | /// Disable or enable interrupts on the rx pin. 259 | void enableRx(bool on); 260 | /// One wire control. 261 | void enableTx(bool on); 262 | 263 | // AVR compatibility methods. 264 | bool listen() { enableRx(true); return true; } 265 | void end(); 266 | bool isListening() { return m_rxEnabled; } 267 | bool stopListening() { enableRx(false); return true; } 268 | 269 | /// onReceive sets a callback that will be called in interrupt context 270 | /// when data is received. 271 | /// More precisely, the callback is triggered when UARTBase detects 272 | /// a new reception, which may not yet have completed on invocation. 273 | /// Reading - never from this interrupt context - should therefore be 274 | /// delayed at least for the duration of one incoming word. 275 | void onReceive(const Delegate& handler); 276 | /// onReceive sets a callback that will be called in interrupt context 277 | /// when data is received. 278 | /// More precisely, the callback is triggered when UARTBase detects 279 | /// a new reception, which may not yet have completed on invocation. 280 | /// Reading - never from this interrupt context - should therefore be 281 | /// delayed at least for the duration of one incoming word. 282 | void onReceive(Delegate&& handler); 283 | 284 | [[deprecated("function removed; semantics of onReceive() changed; check the header file.")]] 285 | void perform_work(); 286 | 287 | using Print::write; 288 | 289 | protected: 290 | void beginRx(bool hasPullUp, int bufCapacity, int isrBufCapacity); 291 | void beginTx(); 292 | // Member variables 293 | int8_t m_rxPin = -1; 294 | int8_t m_txPin = -1; 295 | bool m_invert = false; 296 | 297 | private: 298 | // It's legal to exceed the deadline, for instance, 299 | // by enabling interrupts. 300 | void lazyDelay(); 301 | // Synchronous precise delay 302 | void preciseDelay(); 303 | // If withStopBit is set, either cycle contains a stop bit. 304 | // If dutyCycle == 0, the level is not forced to HIGH. 305 | // If offCycle == 0, the level remains unchanged from dutyCycle. 306 | void writePeriod( 307 | uint32_t dutyCycle, uint32_t offCycle, bool withStopBit); 308 | // safely set the pin mode for the Rx GPIO pin 309 | void setRxGPIOPinMode(); 310 | // safely set the pin mode for the Tx GPIO pin 311 | void setTxGPIOPinMode(); 312 | /* check m_rxValid that calling is safe */ 313 | void rxBits(); 314 | void rxBits(const uint32_t isrTick); 315 | static void disableInterrupts(); 316 | static void restoreInterrupts(); 317 | 318 | static void rxBitISR(UARTBase* self); 319 | static void rxBitSyncISR(UARTBase* self); 320 | 321 | static inline uint32_t IRAM_ATTR microsToTicks(uint32_t micros) ALWAYS_INLINE_ATTR { 322 | return micros << 1; 323 | } 324 | static inline uint32_t ticksToMicros(uint32_t ticks) ALWAYS_INLINE_ATTR { 325 | return ticks >> 1; 326 | } 327 | 328 | // Member variables 329 | volatile uint32_t* m_rxReg; 330 | uint32_t m_rxBitMask; 331 | #if !defined(ESP8266) 332 | volatile uint32_t* m_txReg; 333 | #endif 334 | uint32_t m_txBitMask; 335 | int8_t m_txEnablePin = -1; 336 | uint8_t m_dataBits; 337 | bool m_oneWire; 338 | bool m_rxValid = false; 339 | bool m_rxEnabled = false; 340 | bool m_txValid = false; 341 | bool m_txEnableValid = false; 342 | /// PDU bits include data, parity and stop bits; the start bit is not counted. 343 | uint8_t m_pduBits; 344 | bool m_intTxEnabled; 345 | bool m_rxGPIOHasPullUp = false; 346 | bool m_rxGPIOPullUpEnabled = true; 347 | bool m_txGPIOOpenDrain = false; 348 | Parity m_parityMode; 349 | uint8_t m_stopBits; 350 | bool m_lastReadParity; 351 | bool m_overflow = false; 352 | uint32_t m_bitTicks; 353 | uint8_t m_parityInPos; 354 | uint8_t m_parityOutPos; 355 | int8_t m_rxLastBit; // 0 thru (m_pduBits - m_stopBits - 1): data/parity bits. -1: start bit. (m_pduBits - 1): stop bit. 356 | uint8_t m_rxCurByte = 0; 357 | std::unique_ptr > m_buffer; 358 | std::unique_ptr > m_parityBuffer; 359 | uint32_t m_periodStart; 360 | uint32_t m_periodDuration; 361 | #ifndef ESP32 362 | static uint32_t m_savedPS; 363 | #else 364 | static portMUX_TYPE m_interruptsMux; 365 | #endif 366 | // the ISR stores the relative bit times in the buffer. The inversion corrected level is used as sign bit (2's complement): 367 | // 1 = positive including 0, 0 = negative. 368 | std::unique_ptr > m_isrBuffer; 369 | const Delegate m_isrBufferForEachDel { [](UARTBase* self, uint32_t&& isrTick) { self->rxBits(isrTick); }, this }; 370 | std::atomic m_isrOverflow { false }; 371 | uint32_t m_isrLastTick; 372 | bool m_rxCurParity = false; 373 | Delegate m_rxHandler; 374 | }; 375 | 376 | template< class GpioCapabilities > class BasicUART : public UARTBase { 377 | static_assert(std::is_base_of::value, 378 | "template argument is not derived from IGpioCapabilities"); 379 | public: 380 | BasicUART() : UARTBase() { 381 | } 382 | /// Ctor to set defaults for pins. 383 | /// @param rxPin the GPIO pin used for RX 384 | /// @param txPin -1 for onewire protocol, GPIO pin used for twowire TX 385 | BasicUART(int8_t rxPin, int8_t txPin = -1, bool invert = false) : 386 | UARTBase(rxPin, txPin, invert) { 387 | } 388 | 389 | /// Configure the BasicUART object for use. 390 | /// @param baud the TX/RX bitrate 391 | /// @param config sets databits, parity, and stop bit count 392 | /// @param rxPin -1 or default: either no RX pin, or keeps the rxPin set in the ctor 393 | /// @param txPin -1 or default: either no TX pin (onewire), or keeps the txPin set in the ctor 394 | /// @param invert true: uses invert line level logic 395 | /// @param bufCapacity the capacity for the received bytes buffer 396 | /// @param isrBufCapacity 0: derived from bufCapacity. The capacity of the internal asynchronous 397 | /// bit receive buffer, a suggested size is bufCapacity times the sum of 398 | /// start, data, parity and stop bit count. 399 | void begin(uint32_t baud, Config config, 400 | int8_t rxPin, int8_t txPin, bool invert, 401 | int bufCapacity = 64, int isrBufCapacity = 0) { 402 | UARTBase::begin(baud, config, rxPin, txPin, invert); 403 | if (GpioCapabilities::isValidInputPin(rxPin)) { 404 | beginRx(GpioCapabilities:: hasPullUp(rxPin), bufCapacity, isrBufCapacity); 405 | } 406 | if (GpioCapabilities::isValidOutputPin(txPin)) { 407 | beginTx(); 408 | } 409 | enableRx(true); 410 | } 411 | void begin(uint32_t baud, Config config, 412 | int8_t rxPin, int8_t txPin) { 413 | begin(baud, config, rxPin, txPin, m_invert); 414 | } 415 | void begin(uint32_t baud, Config config, 416 | int8_t rxPin) { 417 | begin(baud, config, rxPin, m_txPin, m_invert); 418 | } 419 | void begin(uint32_t baud, Config config = SWSERIAL_8N1) { 420 | begin(baud, config, m_rxPin, m_txPin, m_invert); 421 | } 422 | void setTransmitEnablePin(int8_t txEnablePin) { 423 | UARTBase::setTransmitEnablePin( 424 | GpioCapabilities::isValidOutputPin(txEnablePin) ? txEnablePin : -1); 425 | } 426 | }; 427 | 428 | using UART = BasicUART< GpioCapabilities >; 429 | 430 | }; // namespace EspSoftwareSerial 431 | 432 | using SoftwareSerial = EspSoftwareSerial::UART; 433 | using namespace EspSoftwareSerial; 434 | 435 | #if __GNUC__ < 12 436 | // The template member functions below must be in IRAM, but due to a bug GCC doesn't currently 437 | // honor the attribute. Instead, it is possible to do explicit specialization and adorn 438 | // these with the IRAM attribute: 439 | // Delegate<>::operator (), circular_queue<>::available, 440 | // circular_queue<>::available_for_push, circular_queue<>::push_peek, circular_queue<>::push 441 | 442 | extern template void delegate::detail::DelegateImpl::operator()() const; 443 | extern template size_t circular_queue::available() const; 444 | extern template bool circular_queue::push(uint32_t&&); 445 | extern template bool circular_queue::push(const uint32_t&); 446 | #endif // __GNUC__ < 12 447 | 448 | #endif // __SoftwareSerial_h 449 | 450 | -------------------------------------------------------------------------------- /EspSoftwareSerial/src/circular_queue/MultiDelegate.h: -------------------------------------------------------------------------------- 1 | /* 2 | MultiDelegate.h - A queue or event multiplexer based on the efficient Delegate 3 | class 4 | Copyright (c) 2019-2020 Dirk O. Kaar. All rights reserved. 5 | 6 | This library is free software; you can redistribute it and/or 7 | modify it under the terms of the GNU Lesser General Public 8 | License as published by the Free Software Foundation; either 9 | version 2.1 of the License, or (at your option) any later version. 10 | 11 | This library is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | Lesser General Public License for more details. 15 | 16 | You should have received a copy of the GNU Lesser General Public 17 | License along with this library; if not, write to the Free Software 18 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 19 | */ 20 | 21 | #ifndef __MULTIDELEGATE_H 22 | #define __MULTIDELEGATE_H 23 | 24 | #include 25 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 26 | #include 27 | #else 28 | #include "circular_queue/ghostl.h" 29 | #endif 30 | 31 | #if defined(ESP8266) 32 | #include 33 | using esp8266::InterruptLock; 34 | #elif defined(ARDUINO) 35 | class InterruptLock { 36 | public: 37 | InterruptLock() { 38 | noInterrupts(); 39 | } 40 | ~InterruptLock() { 41 | interrupts(); 42 | } 43 | }; 44 | #else 45 | #include 46 | #endif 47 | 48 | namespace 49 | { 50 | 51 | template< typename Delegate, typename R, bool ISQUEUE = false, typename... P> 52 | struct CallP 53 | { 54 | static R execute(Delegate& del, P... args) 55 | { 56 | return del(std::forward(args...)); 57 | } 58 | }; 59 | 60 | template< typename Delegate, bool ISQUEUE, typename... P> 61 | struct CallP 62 | { 63 | static bool execute(Delegate& del, P... args) 64 | { 65 | del(std::forward(args...)); 66 | return true; 67 | } 68 | }; 69 | 70 | template< typename Delegate, typename R, bool ISQUEUE = false> 71 | struct Call 72 | { 73 | static R execute(Delegate& del) 74 | { 75 | return del(); 76 | } 77 | }; 78 | 79 | template< typename Delegate, bool ISQUEUE> 80 | struct Call 81 | { 82 | static bool execute(Delegate& del) 83 | { 84 | del(); 85 | return true; 86 | } 87 | }; 88 | 89 | } 90 | 91 | namespace delegate 92 | { 93 | namespace detail 94 | { 95 | 96 | template< typename Delegate, typename R, bool ISQUEUE = false, size_t QUEUE_CAPACITY = 32, typename... P> 97 | class MultiDelegatePImpl 98 | { 99 | public: 100 | MultiDelegatePImpl() = default; 101 | ~MultiDelegatePImpl() 102 | { 103 | *this = nullptr; 104 | } 105 | 106 | MultiDelegatePImpl(const MultiDelegatePImpl&) = delete; 107 | MultiDelegatePImpl& operator=(const MultiDelegatePImpl&) = delete; 108 | 109 | MultiDelegatePImpl(MultiDelegatePImpl&& md) 110 | { 111 | first = md.first; 112 | last = md.last; 113 | unused = md.unused; 114 | nodeCount = md.nodeCount; 115 | md.first = nullptr; 116 | md.last = nullptr; 117 | md.unused = nullptr; 118 | md.nodeCount = 0; 119 | } 120 | 121 | MultiDelegatePImpl(const Delegate& del) 122 | { 123 | add(del); 124 | } 125 | 126 | MultiDelegatePImpl(Delegate&& del) 127 | { 128 | add(std::move(del)); 129 | } 130 | 131 | MultiDelegatePImpl& operator=(MultiDelegatePImpl&& md) 132 | { 133 | first = md.first; 134 | last = md.last; 135 | unused = md.unused; 136 | nodeCount = md.nodeCount; 137 | md.first = nullptr; 138 | md.last = nullptr; 139 | md.unused = nullptr; 140 | md.nodeCount = 0; 141 | return *this; 142 | } 143 | 144 | MultiDelegatePImpl& operator=(std::nullptr_t) 145 | { 146 | if (last) 147 | last->mNext = unused; 148 | if (first) 149 | unused = first; 150 | while (unused) 151 | { 152 | auto to_delete = unused; 153 | unused = unused->mNext; 154 | delete(to_delete); 155 | } 156 | return *this; 157 | } 158 | 159 | MultiDelegatePImpl& operator+=(const Delegate& del) 160 | { 161 | add(del); 162 | return *this; 163 | } 164 | 165 | MultiDelegatePImpl& operator+=(Delegate&& del) 166 | { 167 | add(std::move(del)); 168 | return *this; 169 | } 170 | 171 | protected: 172 | struct Node_t 173 | { 174 | ~Node_t() 175 | { 176 | mDelegate = nullptr; // special overload in Delegate 177 | } 178 | Node_t* mNext = nullptr; 179 | Delegate mDelegate; 180 | }; 181 | 182 | Node_t* first = nullptr; 183 | Node_t* last = nullptr; 184 | Node_t* unused = nullptr; 185 | size_t nodeCount = 0; 186 | 187 | // Returns a pointer to an unused Node_t, 188 | // or if none are available allocates a new one, 189 | // or nullptr if limit is reached 190 | Node_t* IRAM_ATTR get_node_unsafe() 191 | { 192 | Node_t* result = nullptr; 193 | // try to get an item from unused items list 194 | if (unused) 195 | { 196 | result = unused; 197 | unused = unused->mNext; 198 | } 199 | // if no unused items, and count not too high, allocate a new one 200 | else if (nodeCount < QUEUE_CAPACITY) 201 | { 202 | #if defined(ESP8266) || defined(ESP32) 203 | result = new (std::nothrow) Node_t; 204 | #else 205 | result = new Node_t; 206 | #endif 207 | if (result) 208 | ++nodeCount; 209 | } 210 | return result; 211 | } 212 | 213 | void recycle_node_unsafe(Node_t* node) 214 | { 215 | node->mDelegate = nullptr; // special overload in Delegate 216 | node->mNext = unused; 217 | unused = node; 218 | } 219 | 220 | #ifndef ARDUINO 221 | std::mutex mutex_unused; 222 | #endif 223 | public: 224 | class iterator : public std::iterator 225 | { 226 | public: 227 | Node_t* current = nullptr; 228 | Node_t* prev = nullptr; 229 | const Node_t* stop = nullptr; 230 | 231 | iterator(MultiDelegatePImpl& md) : current(md.first), stop(md.last) {} 232 | iterator() = default; 233 | iterator(const iterator&) = default; 234 | iterator& operator=(const iterator&) = default; 235 | iterator& operator=(iterator&&) = default; 236 | operator bool() const 237 | { 238 | return current && stop; 239 | } 240 | bool operator==(const iterator& rhs) const 241 | { 242 | return current == rhs.current; 243 | } 244 | bool operator!=(const iterator& rhs) const 245 | { 246 | return !operator==(rhs); 247 | } 248 | Delegate& operator*() const 249 | { 250 | return current->mDelegate; 251 | } 252 | Delegate* operator->() const 253 | { 254 | return ¤t->mDelegate; 255 | } 256 | iterator& operator++() // prefix 257 | { 258 | if (current && stop != current) 259 | { 260 | prev = current; 261 | current = current->mNext; 262 | } 263 | else 264 | current = nullptr; // end 265 | return *this; 266 | } 267 | iterator& operator++(int) // postfix 268 | { 269 | iterator tmp(*this); 270 | operator++(); 271 | return tmp; 272 | } 273 | }; 274 | 275 | iterator begin() 276 | { 277 | return iterator(*this); 278 | } 279 | iterator end() const 280 | { 281 | return iterator(); 282 | } 283 | 284 | const Delegate* add(const Delegate& del) 285 | { 286 | return add(Delegate(del)); 287 | } 288 | 289 | const Delegate* add(Delegate&& del) 290 | { 291 | if (!del) 292 | return nullptr; 293 | 294 | #ifdef ARDUINO 295 | InterruptLock lockAllInterruptsInThisScope; 296 | #else 297 | std::lock_guard lock(mutex_unused); 298 | #endif 299 | 300 | Node_t* item = ISQUEUE ? get_node_unsafe() : 301 | #if defined(ESP8266) || defined(ESP32) 302 | new (std::nothrow) Node_t; 303 | #else 304 | new Node_t; 305 | #endif 306 | if (!item) 307 | return nullptr; 308 | 309 | item->mDelegate = std::move(del); 310 | item->mNext = nullptr; 311 | 312 | if (last) 313 | last->mNext = item; 314 | else 315 | first = item; 316 | last = item; 317 | 318 | return &item->mDelegate; 319 | } 320 | 321 | iterator erase(iterator it) 322 | { 323 | if (!it) 324 | return end(); 325 | #ifdef ARDUINO 326 | InterruptLock lockAllInterruptsInThisScope; 327 | #else 328 | std::lock_guard lock(mutex_unused); 329 | #endif 330 | auto to_recycle = it.current; 331 | 332 | if (last == it.current) 333 | last = it.prev; 334 | it.current = it.current->mNext; 335 | if (it.prev) 336 | { 337 | it.prev->mNext = it.current; 338 | } 339 | else 340 | { 341 | first = it.current; 342 | } 343 | if (ISQUEUE) 344 | recycle_node_unsafe(to_recycle); 345 | else 346 | delete to_recycle; 347 | return it; 348 | } 349 | 350 | bool erase(const Delegate* const del) 351 | { 352 | auto it = begin(); 353 | while (it) 354 | { 355 | if (del == &(*it)) 356 | { 357 | erase(it); 358 | return true; 359 | } 360 | ++it; 361 | } 362 | return false; 363 | } 364 | 365 | operator bool() const 366 | { 367 | return first; 368 | } 369 | 370 | R operator()(P... args) 371 | { 372 | auto it = begin(); 373 | if (!it) 374 | return {}; 375 | 376 | static std::atomic fence(false); 377 | // prevent recursive calls 378 | #if defined(ARDUINO) && !defined(ESP32) 379 | if (fence.load()) return {}; 380 | fence.store(true); 381 | #else 382 | if (fence.exchange(true)) return {}; 383 | #endif 384 | 385 | R result; 386 | do 387 | { 388 | result = CallP::execute(*it, args...); 389 | if (result && ISQUEUE) 390 | it = erase(it); 391 | else 392 | ++it; 393 | #if defined(ESP8266) || defined(ESP32) 394 | // running callbacks might last too long for watchdog etc. 395 | optimistic_yield(10000); 396 | #endif 397 | } while (it); 398 | 399 | fence.store(false); 400 | return result; 401 | } 402 | }; 403 | 404 | template< typename Delegate, typename R = void, bool ISQUEUE = false, size_t QUEUE_CAPACITY = 32> 405 | class MultiDelegateImpl : public MultiDelegatePImpl 406 | { 407 | public: 408 | using MultiDelegatePImpl::MultiDelegatePImpl; 409 | 410 | R operator()() 411 | { 412 | auto it = this->begin(); 413 | if (!it) 414 | return {}; 415 | 416 | static std::atomic fence(false); 417 | // prevent recursive calls 418 | #if defined(ARDUINO) && !defined(ESP32) 419 | if (fence.load()) return {}; 420 | fence.store(true); 421 | #else 422 | if (fence.exchange(true)) return {}; 423 | #endif 424 | 425 | R result; 426 | do 427 | { 428 | result = Call::execute(*it); 429 | if (result && ISQUEUE) 430 | it = this->erase(it); 431 | else 432 | ++it; 433 | #if defined(ESP8266) || defined(ESP32) 434 | // running callbacks might last too long for watchdog etc. 435 | optimistic_yield(10000); 436 | #endif 437 | } while (it); 438 | 439 | fence.store(false); 440 | return result; 441 | } 442 | }; 443 | 444 | template< typename Delegate, typename R, bool ISQUEUE, size_t QUEUE_CAPACITY, typename... P> class MultiDelegate; 445 | 446 | template< typename Delegate, typename R, bool ISQUEUE, size_t QUEUE_CAPACITY, typename... P> 447 | class MultiDelegate : public MultiDelegatePImpl 448 | { 449 | public: 450 | using MultiDelegatePImpl::MultiDelegatePImpl; 451 | }; 452 | 453 | template< typename Delegate, typename R, bool ISQUEUE, size_t QUEUE_CAPACITY> 454 | class MultiDelegate : public MultiDelegateImpl 455 | { 456 | public: 457 | using MultiDelegateImpl::MultiDelegateImpl; 458 | }; 459 | 460 | template< typename Delegate, bool ISQUEUE, size_t QUEUE_CAPACITY, typename... P> 461 | class MultiDelegate : public MultiDelegatePImpl 462 | { 463 | public: 464 | using MultiDelegatePImpl::MultiDelegatePImpl; 465 | 466 | void operator()(P... args) 467 | { 468 | auto it = this->begin(); 469 | if (!it) 470 | return; 471 | 472 | static std::atomic fence(false); 473 | // prevent recursive calls 474 | #if defined(ARDUINO) && !defined(ESP32) 475 | if (fence.load()) return; 476 | fence.store(true); 477 | #else 478 | if (fence.exchange(true)) return; 479 | #endif 480 | 481 | do 482 | { 483 | CallP::execute(*it, args...); 484 | if (ISQUEUE) 485 | it = this->erase(it); 486 | else 487 | ++it; 488 | #if defined(ESP8266) || defined(ESP32) 489 | // running callbacks might last too long for watchdog etc. 490 | optimistic_yield(10000); 491 | #endif 492 | } while (it); 493 | 494 | fence.store(false); 495 | } 496 | }; 497 | 498 | template< typename Delegate, bool ISQUEUE, size_t QUEUE_CAPACITY> 499 | class MultiDelegate : public MultiDelegateImpl 500 | { 501 | public: 502 | using MultiDelegateImpl::MultiDelegateImpl; 503 | 504 | void operator()() 505 | { 506 | auto it = this->begin(); 507 | if (!it) 508 | return; 509 | 510 | static std::atomic fence(false); 511 | // prevent recursive calls 512 | #if defined(ARDUINO) && !defined(ESP32) 513 | if (fence.load()) return; 514 | fence.store(true); 515 | #else 516 | if (fence.exchange(true)) return; 517 | #endif 518 | 519 | do 520 | { 521 | Call::execute(*it); 522 | if (ISQUEUE) 523 | it = this->erase(it); 524 | else 525 | ++it; 526 | #if defined(ESP8266) || defined(ESP32) 527 | // running callbacks might last too long for watchdog etc. 528 | optimistic_yield(10000); 529 | #endif 530 | } while (it); 531 | 532 | fence.store(false); 533 | } 534 | }; 535 | 536 | } 537 | 538 | } 539 | 540 | /** 541 | The MultiDelegate class template can be specialized to either a queue or an event multiplexer. 542 | It is designed to be used with Delegate, the efficient runtime wrapper for C function ptr and C++ std::function. 543 | @tparam Delegate specifies the concrete type that MultiDelegate bases the queue or event multiplexer on. 544 | @tparam ISQUEUE modifies the generated MultiDelegate class in subtle ways. In queue mode (ISQUEUE == true), 545 | the value of QUEUE_CAPACITY enforces the maximum number of simultaneous items the queue can contain. 546 | This is exploited to minimize the use of new and delete by reusing already allocated items, thus 547 | reducing heap fragmentation. In event multiplexer mode (ISQUEUE = false), new and delete are 548 | used for allocation of the event handler items. 549 | If the result type of the function call operator of Delegate is void, calling a MultiDelegate queue 550 | removes each item after calling it; a Multidelegate event multiplexer keeps event handlers until 551 | explicitly removed. 552 | If the result type of the function call operator of Delegate is non-void, in a MultiDelegate queue 553 | the type-conversion to bool of that result determines if the item is immediately removed or kept 554 | after each call: if true is returned, the item is removed. A Multidelegate event multiplexer keeps event 555 | handlers until they are explicitly removed. 556 | @tparam QUEUE_CAPACITY is only used if ISQUEUE == true. Then, it sets the maximum capacity that the queue dynamically 557 | allocates from the heap. Unused items are not returned to the heap, but are managed by the MultiDelegate 558 | instance during its own lifetime for efficiency. 559 | */ 560 | template< typename Delegate, bool ISQUEUE = false, size_t QUEUE_CAPACITY = 32> 561 | class MultiDelegate : public delegate::detail::MultiDelegate 562 | { 563 | public: 564 | using delegate::detail::MultiDelegate::MultiDelegate; 565 | }; 566 | 567 | #endif // __MULTIDELEGATE_H 568 | -------------------------------------------------------------------------------- /EspSoftwareSerial/src/circular_queue/circular_queue.h: -------------------------------------------------------------------------------- 1 | /* 2 | circular_queue.h - Implementation of a lock-free circular queue for EspSoftwareSerial. 3 | Copyright (c) 2019 Dirk O. Kaar. All rights 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 | #ifndef __circular_queue_h 21 | #define __circular_queue_h 22 | 23 | #ifdef ARDUINO 24 | #include 25 | #endif 26 | 27 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 28 | #include 29 | #include 30 | #include 31 | #include "Delegate.h" 32 | using std::min; 33 | #else 34 | #include "ghostl.h" 35 | #endif 36 | 37 | #if !defined(ESP32) && !defined(ESP8266) 38 | #define IRAM_ATTR 39 | #endif 40 | 41 | #if defined(__GNUC__) 42 | #undef ALWAYS_INLINE_ATTR 43 | #define ALWAYS_INLINE_ATTR __attribute__((always_inline)) 44 | #else 45 | #define ALWAYS_INLINE_ATTR 46 | #endif 47 | 48 | /*! 49 | @brief Instance class for a single-producer, single-consumer circular queue / ring buffer (FIFO). 50 | This implementation is lock-free between producer and consumer for the available(), peek(), 51 | pop(), and push() type functions. 52 | */ 53 | template< typename T, typename ForEachArg = void > 54 | class circular_queue 55 | { 56 | public: 57 | /*! 58 | @brief Constructs a valid, but zero-capacity dummy queue. 59 | */ 60 | circular_queue() : m_bufSize(1) 61 | { 62 | m_inPos.store(0); 63 | m_outPos.store(0); 64 | } 65 | /*! 66 | @brief Constructs a queue of the given maximum capacity. 67 | */ 68 | circular_queue(const size_t capacity) : m_bufSize(capacity + 1), m_buffer(new T[m_bufSize]) 69 | { 70 | m_inPos.store(0); 71 | m_outPos.store(0); 72 | } 73 | circular_queue(circular_queue&& cq) : 74 | m_bufSize(cq.m_bufSize), m_buffer(cq.m_buffer), m_inPos(cq.m_inPos.load()), m_outPos(cq.m_outPos.load()) 75 | {} 76 | ~circular_queue() 77 | { 78 | m_buffer.reset(); 79 | } 80 | circular_queue(const circular_queue&) = delete; 81 | circular_queue& operator=(circular_queue&& cq) 82 | { 83 | m_bufSize = cq.m_bufSize; 84 | m_buffer = cq.m_buffer; 85 | m_inPos.store(cq.m_inPos.load()); 86 | m_outPos.store(cq.m_outPos.load()); 87 | } 88 | circular_queue& operator=(const circular_queue&) = delete; 89 | 90 | /*! 91 | @brief Get the numer of elements the queue can hold at most. 92 | */ 93 | size_t capacity() const 94 | { 95 | return m_bufSize - 1; 96 | } 97 | 98 | /*! 99 | @brief Resize the queue. The available elements in the queue are preserved. 100 | This is not lock-free and concurrent producer or consumer access 101 | will lead to corruption. 102 | @return True if the new capacity could accommodate the present elements in 103 | the queue, otherwise nothing is done and false is returned. 104 | */ 105 | bool capacity(const size_t cap); 106 | 107 | /*! 108 | @brief Discard all data in the queue. 109 | */ 110 | void flush() 111 | { 112 | m_outPos.store(m_inPos.load()); 113 | } 114 | 115 | /*! 116 | @brief Get a snapshot number of elements that can be retrieved by pop. 117 | */ 118 | size_t IRAM_ATTR available() const 119 | { 120 | int avail = static_cast(m_inPos.load() - m_outPos.load()); 121 | if (avail < 0) avail += m_bufSize; 122 | return avail; 123 | } 124 | 125 | /*! 126 | @brief Get the remaining free elementes for pushing. 127 | */ 128 | size_t IRAM_ATTR available_for_push() const 129 | { 130 | int avail = static_cast(m_outPos.load() - m_inPos.load()) - 1; 131 | if (avail < 0) avail += m_bufSize; 132 | return avail; 133 | } 134 | 135 | /*! 136 | @brief Peek at the next element pop will return without removing it from the queue. 137 | @return An rvalue copy of the next element that can be popped. If the queue is empty, 138 | return an rvalue copy of the element that is pending the next push. 139 | */ 140 | T peek() const 141 | { 142 | const auto outPos = m_outPos.load(std::memory_order_relaxed); 143 | std::atomic_thread_fence(std::memory_order_acquire); 144 | return m_buffer[outPos]; 145 | } 146 | 147 | /*! 148 | @brief Peek at the next pending input value. 149 | @return A reference to the next element that can be pushed. 150 | */ 151 | T& IRAM_ATTR pushpeek() 152 | { 153 | const auto inPos = m_inPos.load(std::memory_order_relaxed); 154 | std::atomic_thread_fence(std::memory_order_acquire); 155 | return m_buffer[inPos]; 156 | } 157 | 158 | /*! 159 | @brief Release the next pending input value, accessible by pushpeek(), into the queue. 160 | @return true if the queue accepted the value, false if the queue 161 | was full. 162 | */ 163 | bool IRAM_ATTR push() 164 | { 165 | const auto inPos = m_inPos.load(std::memory_order_acquire); 166 | const size_t next = (inPos + 1) % m_bufSize; 167 | if (next == m_outPos.load(std::memory_order_relaxed)) { 168 | return false; 169 | } 170 | std::atomic_thread_fence(std::memory_order_release); 171 | m_inPos.store(next, std::memory_order_release); 172 | return true; 173 | } 174 | 175 | /*! 176 | @brief Move the rvalue parameter into the queue. 177 | @return true if the queue accepted the value, false if the queue 178 | was full. 179 | */ 180 | bool IRAM_ATTR push(T&& val) 181 | { 182 | const auto inPos = m_inPos.load(std::memory_order_acquire); 183 | const size_t next = (inPos + 1) % m_bufSize; 184 | if (next == m_outPos.load(std::memory_order_relaxed)) { 185 | return false; 186 | } 187 | m_buffer[inPos] = std::move(val); 188 | std::atomic_thread_fence(std::memory_order_release); 189 | m_inPos.store(next, std::memory_order_release); 190 | return true; 191 | } 192 | 193 | /*! 194 | @brief Push a copy of the parameter into the queue. 195 | @return true if the queue accepted the value, false if the queue 196 | was full. 197 | */ 198 | inline bool IRAM_ATTR push(const T& val) ALWAYS_INLINE_ATTR 199 | { 200 | T v(val); 201 | return push(std::move(v)); 202 | } 203 | 204 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 205 | /*! 206 | @brief Push copies of multiple elements from a buffer into the queue, 207 | in order, beginning at buffer's head. 208 | @return The number of elements actually copied into the queue, counted 209 | from the buffer head. 210 | */ 211 | size_t push_n(const T* buffer, size_t size); 212 | #endif 213 | 214 | /*! 215 | @brief Pop the next available element from the queue. 216 | @return An rvalue copy of the popped element, or a default 217 | value of type T if the queue is empty. 218 | */ 219 | T pop(); 220 | 221 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 222 | /*! 223 | @brief Pop multiple elements in ordered sequence from the queue to a buffer. 224 | If buffer is nullptr, simply discards up to size elements from the queue. 225 | @return The number of elements actually popped from the queue to 226 | buffer. 227 | */ 228 | size_t pop_n(T* buffer, size_t size); 229 | #endif 230 | 231 | /*! 232 | @brief Iterate over and remove each available element from queue, 233 | calling back fun with an rvalue reference of every single element. 234 | */ 235 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 236 | void for_each(const Delegate& fun); 237 | #else 238 | void for_each(Delegate fun); 239 | #endif 240 | 241 | /*! 242 | @brief In reverse order, iterate over, pop and optionally requeue each available element from the queue, 243 | calling back fun with a reference of every single element. 244 | Requeuing is dependent on the return boolean of the callback function. If it 245 | returns true, the requeue occurs. 246 | */ 247 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 248 | bool for_each_rev_requeue(const Delegate& fun); 249 | #else 250 | bool for_each_rev_requeue(Delegate fun); 251 | #endif 252 | 253 | protected: 254 | size_t m_bufSize; 255 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 256 | std::unique_ptr m_buffer; 257 | #else 258 | std::unique_ptr m_buffer; 259 | #endif 260 | std::atomic m_inPos; 261 | std::atomic m_outPos; 262 | }; 263 | 264 | template< typename T, typename ForEachArg > 265 | bool circular_queue::capacity(const size_t cap) 266 | { 267 | if (cap + 1 == m_bufSize) return true; 268 | else if (available() > cap) return false; 269 | std::unique_ptr buffer(new T[cap + 1]); 270 | const auto available = pop_n(buffer, cap); 271 | m_buffer.reset(buffer); 272 | m_bufSize = cap + 1; 273 | m_inPos.store(available, std::memory_order_relaxed); 274 | m_outPos.store(0, std::memory_order_relaxed); 275 | return true; 276 | } 277 | 278 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 279 | template< typename T, typename ForEachArg > 280 | size_t circular_queue::push_n(const T* buffer, size_t size) 281 | { 282 | const auto inPos = m_inPos.load(std::memory_order_acquire); 283 | const auto outPos = m_outPos.load(std::memory_order_relaxed); 284 | 285 | size_t blockSize = (outPos > inPos) ? outPos - 1 - inPos : (outPos == 0) ? m_bufSize - 1 - inPos : m_bufSize - inPos; 286 | blockSize = min(size, blockSize); 287 | if (!blockSize) return 0; 288 | int next = (inPos + blockSize) % m_bufSize; 289 | 290 | auto dest = m_buffer.get() + inPos; 291 | std::copy_n(std::make_move_iterator(buffer), blockSize, dest); 292 | size = min(size - blockSize, outPos > 1 ? static_cast(outPos - next - 1) : 0); 293 | next += size; 294 | dest = m_buffer.get(); 295 | std::copy_n(std::make_move_iterator(buffer + blockSize), size, dest); 296 | 297 | std::atomic_thread_fence(std::memory_order_release); 298 | m_inPos.store(next, std::memory_order_release); 299 | return blockSize + size; 300 | } 301 | #endif 302 | 303 | template< typename T, typename ForEachArg > 304 | T circular_queue::pop() 305 | { 306 | const auto outPos = m_outPos.load(std::memory_order_acquire); 307 | if (m_inPos.load(std::memory_order_relaxed) == outPos) return {}; 308 | 309 | std::atomic_thread_fence(std::memory_order_acquire); 310 | 311 | auto val = std::move(m_buffer[outPos]); 312 | 313 | m_outPos.store((outPos + 1) % m_bufSize, std::memory_order_release); 314 | return val; 315 | } 316 | 317 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 318 | template< typename T, typename ForEachArg > 319 | size_t circular_queue::pop_n(T* buffer, size_t size) { 320 | size_t avail = size = min(size, available()); 321 | if (!avail) return 0; 322 | const auto outPos = m_outPos.load(std::memory_order_acquire); 323 | size_t n = min(avail, static_cast(m_bufSize - outPos)); 324 | 325 | std::atomic_thread_fence(std::memory_order_acquire); 326 | 327 | if (buffer) { 328 | buffer = std::copy_n(std::make_move_iterator(m_buffer.get() + outPos), n, buffer); 329 | avail -= n; 330 | std::copy_n(std::make_move_iterator(m_buffer.get()), avail, buffer); 331 | } 332 | 333 | m_outPos.store((outPos + size) % m_bufSize, std::memory_order_release); 334 | return size; 335 | } 336 | #endif 337 | 338 | template< typename T, typename ForEachArg > 339 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 340 | void circular_queue::for_each(const Delegate& fun) 341 | #else 342 | void circular_queue::for_each(Delegate fun) 343 | #endif 344 | { 345 | auto outPos = m_outPos.load(std::memory_order_acquire); 346 | const auto inPos = m_inPos.load(std::memory_order_relaxed); 347 | std::atomic_thread_fence(std::memory_order_acquire); 348 | while (outPos != inPos) 349 | { 350 | fun(std::move(m_buffer[outPos])); 351 | outPos = (outPos + 1) % m_bufSize; 352 | m_outPos.store(outPos, std::memory_order_release); 353 | } 354 | } 355 | 356 | template< typename T, typename ForEachArg > 357 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 358 | bool circular_queue::for_each_rev_requeue(const Delegate& fun) 359 | #else 360 | bool circular_queue::for_each_rev_requeue(Delegate fun) 361 | #endif 362 | { 363 | auto inPos0 = circular_queue::m_inPos.load(std::memory_order_acquire); 364 | auto outPos = circular_queue::m_outPos.load(std::memory_order_relaxed); 365 | if (outPos == inPos0) return false; 366 | auto pos = inPos0; 367 | auto outPos1 = inPos0; 368 | const auto posDecr = circular_queue::m_bufSize - 1; 369 | std::atomic_thread_fence(std::memory_order_acquire); 370 | do { 371 | pos = (pos + posDecr) % circular_queue::m_bufSize; 372 | T&& val = std::move(circular_queue::m_buffer[pos]); 373 | if (fun(val)) 374 | { 375 | outPos1 = (outPos1 + posDecr) % circular_queue::m_bufSize; 376 | if (outPos1 != pos) circular_queue::m_buffer[outPos1] = std::move(val); 377 | } 378 | } while (pos != outPos); 379 | std::atomic_thread_fence(std::memory_order_release); 380 | circular_queue::m_outPos.store(outPos1, std::memory_order_release); 381 | return true; 382 | } 383 | 384 | #endif // __circular_queue_h 385 | -------------------------------------------------------------------------------- /EspSoftwareSerial/src/circular_queue/circular_queue_mp.h: -------------------------------------------------------------------------------- 1 | /* 2 | circular_queue_mp.h - Implementation of a lock-free circular queue for EspSoftwareSerial. 3 | Copyright (c) 2019 Dirk O. Kaar. All rights 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 | #ifndef __circular_queue_mp_h 21 | #define __circular_queue_mp_h 22 | 23 | #include "circular_queue.h" 24 | 25 | #if defined(ESP8266) 26 | #include 27 | using esp8266::InterruptLock; 28 | #endif 29 | 30 | /*! 31 | @brief Instance class for a multi-producer, single-consumer circular queue / ring buffer (FIFO). 32 | This implementation is lock-free between producers and consumer for the available(), peek(), 33 | pop(), and push() type functions. 34 | */ 35 | template< typename T, typename ForEachArg = void > 36 | class circular_queue_mp : protected circular_queue 37 | { 38 | public: 39 | circular_queue_mp() : circular_queue() 40 | { 41 | m_inPos_mp.store(0); 42 | m_concurrent_mp.store(0); 43 | } 44 | circular_queue_mp(const size_t capacity) : circular_queue(capacity) 45 | { 46 | m_inPos_mp.store(0); 47 | m_concurrent_mp.store(0); 48 | } 49 | circular_queue_mp(circular_queue_mp&& cq) : circular_queue(std::move(cq)) 50 | { 51 | m_inPos_mp.store(cq.m_inPos_mp.load()); 52 | m_concurrent_mp.store(cq.m_concurrent_mp.load()); 53 | } 54 | circular_queue_mp& operator=(circular_queue_mp&& cq) 55 | { 56 | circular_queue::operator=(std::move(cq)); 57 | m_inPos_mp.store(cq.m_inPos_mp.load()); 58 | m_concurrent_mp.store(cq.m_concurrent_mp.load()); 59 | } 60 | circular_queue_mp& operator=(const circular_queue_mp&) = delete; 61 | 62 | using circular_queue::capacity; 63 | using circular_queue::flush; 64 | using circular_queue::peek; 65 | using circular_queue::pop; 66 | using circular_queue::pop_n; 67 | using circular_queue::for_each; 68 | using circular_queue::for_each_rev_requeue; 69 | 70 | T& pushpeek() = delete; 71 | bool push() = delete; 72 | 73 | inline size_t IRAM_ATTR available() const ALWAYS_INLINE_ATTR 74 | { 75 | return circular_queue::available(); 76 | } 77 | inline size_t IRAM_ATTR available_for_push() const ALWAYS_INLINE_ATTR 78 | { 79 | return circular_queue::available_for_push(); 80 | } 81 | 82 | /*! 83 | @brief Resize the queue. The available elements in the queue are preserved. 84 | This is not lock-free and concurrent producer or consumer access 85 | will lead to corruption. 86 | @return True if the new capacity could accommodate the present elements in 87 | the queue, otherwise nothing is done and false is returned. 88 | */ 89 | bool capacity(const size_t cap); 90 | 91 | /*! 92 | @brief Move the rvalue parameter into the queue, guarded 93 | for multiple concurrent producers. 94 | @return true if the queue accepted the value, false if the queue 95 | was full. 96 | */ 97 | bool push(T&& val); 98 | 99 | /*! 100 | @brief Push a copy of the parameter into the queue, guarded 101 | for multiple concurrent producers. 102 | @return true if the queue accepted the value, false if the queue 103 | was full. 104 | */ 105 | inline bool IRAM_ATTR push(const T& val) ALWAYS_INLINE_ATTR 106 | { 107 | T v(val); 108 | return push(std::move(v)); 109 | } 110 | 111 | /*! 112 | @brief Push copies of multiple elements from a buffer into the queue, 113 | in order, beginning at buffer's head. This is safe for 114 | multiple producers. 115 | @return The number of elements actually copied into the queue, counted 116 | from the buffer head. 117 | */ 118 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 119 | size_t push_n(const T* buffer, size_t size); 120 | #endif 121 | 122 | protected: 123 | std::atomic m_inPos_mp; 124 | std::atomic m_concurrent_mp; 125 | }; 126 | 127 | template< typename T, typename ForEachArg > 128 | bool circular_queue_mp::capacity(const size_t cap) 129 | { 130 | if (cap + 1 == circular_queue::m_bufSize) return true; 131 | else if (!circular_queue::capacity(cap)) return false; 132 | m_inPos_mp.store(circular_queue::m_inPos.load(std::memory_order_relaxed), 133 | std::memory_order_relaxed); 134 | m_concurrent_mp.store(0, std::memory_order_relaxed); 135 | return true; 136 | } 137 | 138 | template< typename T, typename ForEachArg > 139 | bool IRAM_ATTR circular_queue_mp::push(T&& val) 140 | { 141 | size_t inPos_mp; 142 | size_t next; 143 | #if !defined(ESP32) && defined(ARDUINO) 144 | class InterruptLock { 145 | public: 146 | InterruptLock() { 147 | noInterrupts(); 148 | } 149 | ~InterruptLock() { 150 | interrupts(); 151 | } 152 | }; 153 | { 154 | InterruptLock lock; 155 | #else 156 | ++m_concurrent_mp; 157 | do 158 | { 159 | #endif 160 | inPos_mp = m_inPos_mp.load(std::memory_order_relaxed); 161 | next = (inPos_mp + 1) % circular_queue::m_bufSize; 162 | if (next == circular_queue::m_outPos.load(std::memory_order_relaxed)) { 163 | #if !defined(ESP32) && defined(ARDUINO) 164 | return false; 165 | } 166 | m_inPos_mp.store(next, std::memory_order_relaxed); 167 | m_concurrent_mp.store(m_concurrent_mp.load(std::memory_order_relaxed) + 1, 168 | std::memory_order_relaxed); 169 | std::atomic_thread_fence(std::memory_order_release); 170 | } 171 | #else 172 | int concurrent_mp; 173 | do 174 | { 175 | inPos_mp = m_inPos_mp.load(); 176 | concurrent_mp = m_concurrent_mp.load(); 177 | if (1 == concurrent_mp) 178 | { 179 | circular_queue::m_inPos.store(inPos_mp, std::memory_order_release); 180 | } 181 | } 182 | while (!m_concurrent_mp.compare_exchange_weak(concurrent_mp, concurrent_mp - 1)); 183 | return false; 184 | } 185 | } 186 | while (!m_inPos_mp.compare_exchange_weak(inPos_mp, next)); 187 | #endif 188 | 189 | circular_queue::m_buffer[inPos_mp] = std::move(val); 190 | 191 | std::atomic_thread_fence(std::memory_order_release); 192 | 193 | #if !defined(ESP32) && defined(ARDUINO) 194 | { 195 | InterruptLock lock; 196 | if (1 == m_concurrent_mp.load(std::memory_order_relaxed)) 197 | { 198 | inPos_mp = m_inPos_mp.load(std::memory_order_relaxed); 199 | circular_queue::m_inPos.store(inPos_mp, std::memory_order_relaxed); 200 | } 201 | m_concurrent_mp.store(m_concurrent_mp.load(std::memory_order_relaxed) - 1, 202 | std::memory_order_relaxed); 203 | std::atomic_thread_fence(std::memory_order_release); 204 | } 205 | #else 206 | int concurrent_mp; 207 | do 208 | { 209 | inPos_mp = m_inPos_mp.load(); 210 | concurrent_mp = m_concurrent_mp.load(); 211 | if (1 == concurrent_mp) 212 | { 213 | circular_queue::m_inPos.store(inPos_mp, std::memory_order_release); 214 | } 215 | } 216 | while (!m_concurrent_mp.compare_exchange_weak(concurrent_mp, concurrent_mp - 1)); 217 | #endif 218 | 219 | return true; 220 | } 221 | 222 | #if defined(ESP8266) || defined(ESP32) || !defined(ARDUINO) 223 | template< typename T, typename ForEachArg > 224 | size_t circular_queue_mp::push_n(const T* buffer, size_t size) 225 | { 226 | const auto outPos = circular_queue::m_outPos.load(std::memory_order_relaxed); 227 | size_t inPos_mp; 228 | size_t next; 229 | size_t blockSize; 230 | #if !defined(ESP32) && defined(ARDUINO) 231 | { 232 | InterruptLock lock; 233 | #else 234 | ++m_concurrent_mp; 235 | do 236 | { 237 | #endif 238 | inPos_mp = m_inPos_mp.load(std::memory_order_relaxed); 239 | blockSize = (outPos > inPos_mp) ? outPos - 1 - inPos_mp : (outPos == 0) ? circular_queue::m_bufSize - 1 - inPos_mp : circular_queue::m_bufSize - inPos_mp; 240 | blockSize = min(size, blockSize); 241 | if (!blockSize) 242 | { 243 | #if !defined(ESP32) && defined(ARDUINO) 244 | return 0; 245 | } 246 | next = (inPos_mp + blockSize) % circular_queue::m_bufSize; 247 | m_inPos_mp.store(next, std::memory_order_relaxed); 248 | m_concurrent_mp.store(m_concurrent_mp.load(std::memory_order_relaxed) + 1, 249 | std::memory_order_relaxed); 250 | std::atomic_thread_fence(std::memory_order_release); 251 | } 252 | #else 253 | int concurrent_mp = m_concurrent_mp.load(); 254 | do 255 | { 256 | inPos_mp = m_inPos_mp.load(); 257 | concurrent_mp = m_concurrent_mp.load(); 258 | if (1 == concurrent_mp) 259 | { 260 | circular_queue::m_inPos.store(inPos_mp, std::memory_order_release); 261 | } 262 | } 263 | while (!m_concurrent_mp.compare_exchange_weak(concurrent_mp, concurrent_mp - 1)); 264 | return false; 265 | } 266 | } 267 | while (!m_inPos_mp.compare_exchange_weak(inPos_mp, next)); 268 | #endif 269 | 270 | auto dest = circular_queue::m_buffer.get() + inPos_mp; 271 | std::copy_n(std::make_move_iterator(buffer), blockSize, dest); 272 | size = min(size - blockSize, outPos > 1 ? static_cast(outPos - next - 1) : 0); 273 | next += size; 274 | dest = circular_queue::m_buffer.get(); 275 | std::copy_n(std::make_move_iterator(buffer + blockSize), size, dest); 276 | 277 | std::atomic_thread_fence(std::memory_order_release); 278 | 279 | #if !defined(ESP32) && defined(ARDUINO) 280 | { 281 | InterruptLock lock; 282 | if (1 == m_concurrent_mp.load(std::memory_order_relaxed)) 283 | { 284 | inPos_mp = m_inPos_mp.load(std::memory_order_relaxed); 285 | circular_queue::m_inPos.store(inPos_mp, std::memory_order_relaxed); 286 | } 287 | m_concurrent_mp.store(m_concurrent_mp.load(std::memory_order_relaxed) - 1, 288 | std::memory_order_relaxed); 289 | std::atomic_thread_fence(std::memory_order_release); 290 | } 291 | #else 292 | int concurrent_mp; 293 | do 294 | { 295 | inPos_mp = m_inPos_mp.load(); 296 | concurrent_mp = m_concurrent_mp.load(); 297 | if (1 == concurrent_mp) 298 | { 299 | circular_queue::m_inPos.store(inPos_mp, std::memory_order_release); 300 | } 301 | } 302 | while (!m_concurrent_mp.compare_exchange_weak(concurrent_mp, concurrent_mp - 1)); 303 | #endif 304 | 305 | return blockSize + size; 306 | } 307 | 308 | #endif 309 | 310 | #endif // __circular_queue_mp_h 311 | -------------------------------------------------------------------------------- /EspSoftwareSerial/src/circular_queue/ghostl.h: -------------------------------------------------------------------------------- 1 | /* 2 | ghostl.h - Implementation of a bare-bones, mostly no-op, C++ STL shell 3 | that allows building some Arduino ESP8266/ESP32 4 | libraries on Aruduino AVR. 5 | Copyright (c) 2019 Dirk O. Kaar. All rights reserved. 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | */ 21 | 22 | #ifndef __ghostl_h 23 | #define __ghostl_h 24 | 25 | #if defined(ARDUINO_ARCH_SAMD) 26 | #include 27 | #endif 28 | 29 | using size_t = decltype(sizeof(char)); 30 | 31 | namespace std 32 | { 33 | #if !defined(ARDUINO_ARCH_SAMD) 34 | typedef enum memory_order { 35 | memory_order_relaxed, 36 | memory_order_acquire, 37 | memory_order_release, 38 | memory_order_seq_cst 39 | } memory_order; 40 | template< typename T > class atomic { 41 | private: 42 | T value; 43 | public: 44 | atomic() {} 45 | atomic(T desired) { value = desired; } 46 | void store(T desired, std::memory_order = std::memory_order_seq_cst) volatile noexcept { value = desired; } 47 | T load(std::memory_order = std::memory_order_seq_cst) const volatile noexcept { return value; } 48 | }; 49 | inline void atomic_thread_fence(std::memory_order order) noexcept {} 50 | template< typename T > T&& move(T& t) noexcept { return static_cast(t); } 51 | #endif 52 | 53 | template< typename T, size_t long N > struct array 54 | { 55 | T _M_elems[N]; 56 | decltype(sizeof(0)) size() const { return N; } 57 | T& operator[](decltype(sizeof(0)) i) { return _M_elems[i]; } 58 | const T& operator[](decltype(sizeof(0)) i) const { return _M_elems[i]; } 59 | }; 60 | 61 | template< typename T > class unique_ptr 62 | { 63 | public: 64 | using pointer = T*; 65 | unique_ptr() noexcept : ptr(nullptr) {} 66 | unique_ptr(pointer p) : ptr(p) {} 67 | pointer operator->() const noexcept { return ptr; } 68 | T& operator[](decltype(sizeof(0)) i) const { return ptr[i]; } 69 | void reset(pointer p = pointer()) noexcept 70 | { 71 | delete ptr; 72 | ptr = p; 73 | } 74 | T& operator*() const { return *ptr; } 75 | private: 76 | pointer ptr; 77 | }; 78 | 79 | template< typename T > using function = T*; 80 | using nullptr_t = decltype(nullptr); 81 | 82 | template 83 | struct identity { 84 | typedef T type; 85 | }; 86 | 87 | template 88 | inline T&& forward(typename identity::type& t) noexcept 89 | { 90 | return static_cast::type&&>(t); 91 | } 92 | } 93 | 94 | #endif // __ghostl_h 95 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rot13labs fox 2 | 3 | Much of this code was copied from / inspired by Yet Another Foxbox (YAFB) by Gregory Stoike (KN4CK) which can be found here: https://github.com/N8HR/YAFB. It has been stripped down and adapted for use on a Seeed Studio XIAO ESP32C3 and a NiceRF SA868. 4 | 5 | All credit for this project goes to Gregory Stoike; I just made his work simple enough for my own simple foxes. 6 | 7 | To update the firmware with a new frequency, delay, callsign, etc. simply open fox.ino in the arduino IDE and make the changes you want, then hold down the 'B' button on the XIAO controller while you plug it in. This puts the fox into boot-selector mode which prepares it to recieve a new firmware. hit upload on the Arduino IDE and once its done, hit the 'R' button on the XIAO controller to restart the fox with the new firmware. 8 | 9 | Holding 'B' while restarting the fox can also be used to halt transmissions while charging the fox via USB-C 10 | 11 | ## Hardware 12 | 13 | The hardware for this fox is (purposely) super simplistic. I wanted something that was minimal to make but could be expanded out by myself or others to do more than just the basic functionality of a fox. 14 | 15 | The seed XIAO fit this bill perfectly; it has a battery controller built in to manage the LiPo, reducing the need for more components, and offers wifi and bluetooth for future expandability. 16 | 17 | LEDs were added to the radio power and transmit pins for easy troubleshooting. 18 | 19 | The full circuit looks like this: 20 | 21 | rot13labs fox circuit diagram 22 | 23 | ## Firmware 24 | 25 | Right now this project is basically just a hodge-podge of others code brought together by a bit of my own. 26 | 27 | I tried to comment as liberally as possible because im hoping others can use this code to help their own SA868 projects. It's an awesome chip and deserves a lot more of a community than it currently has. 28 | 29 | ## Libraries 30 | 31 | In order to build this you will need softwareserial.h. This can be found in the EspSoftwareSerial library contained in this repo. Simply move or copy the EspSoftwareSerial directory into the arduino libraries directory on your machine (~/Documents/Arduino/libraries/EspSoftwareSerial on MacOS) 32 | 33 | ## Contact 34 | 35 | If you found one of my foxes at a con and want help updating the firmware, or are just looking to build one of your own, please feel free to reach out to me on twitter! 36 | @c0ldbru 37 | 38 | -------------------------------------------------------------------------------- /fox.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Much of this code was copied from / inspired by Yet Another Foxbox 3 | * (YAFB) by Gregory Stoike (KN4CK) which can be found here: 4 | * https://github.com/N8HR/YAFB. It has been stripped down and adapted 5 | * for use on a Seeed Studio XIAO ESP32C3 and a NiceRF SA868. All credit 6 | * for this project goes to Gregory Stoike; I just made his work simple 7 | * enough for my own simple foxes. 8 | * 9 | * This project is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This project is distributed in the hope that it will be useful, but 15 | * WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | * General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this. If not, see . 21 | */ 22 | 23 | #include // ESP software serial for SA868 connection 24 | 25 | String callmessage = "Fox Hunt"; // your callsign goes here 26 | String morse = ""; // leave this blank for now; it will be filled in during setup 27 | float frequency = 146.565; // 146.565 is the normal TX frequency for foxes 28 | int delayms = 30000; // delay between transmissions in milliseconds 29 | int initial_delay = 1000; // delay before transmissions start in milliseconds 30 | byte bandwidth = 1; // Bandwidth, 0=12.5k, 1=25K 31 | byte squelch = 1; // Squelch 0-8, 0 is listen/open 32 | byte volume = 5; // Volume 1-8 33 | 34 | #define PTT_Pin 5 // GPIO05 | D3 on XIAO 35 | #define PD_Pin 6 // GPIO06 | D4 on XIAO 36 | #define HL_Pin 7 // GPIO07 | D5 on XIAO 37 | #define rx 20 // GPIO20 | D7 on XIAO 38 | #define tx 21 // GPIO21 | D6 on XIAO 39 | 40 | SoftwareSerial ESerial(rx, tx); 41 | 42 | void setup(){ 43 | ESerial.begin(9600); 44 | delay(initial_delay); 45 | 46 | morse = createMorse(callmessage); 47 | 48 | pinMode(PTT_Pin, OUTPUT); 49 | pinMode(PD_Pin, OUTPUT); 50 | pinMode(HL_Pin, OUTPUT); 51 | digitalWrite(PTT_Pin, HIGH); // LOW is TX, High is RX 52 | digitalWrite(PD_Pin, HIGH); // LOW is power down mode, HIGH to power up 53 | digitalWrite(HL_Pin, LOW); // LOW for low power, HIGH is for high power -- HIGH seems to cause issues. 54 | delay(3000); 55 | moduleInit(); 56 | moduleSetFreq(frequency); 57 | moduleSetVol(volume); 58 | } 59 | 60 | void loop(){ 61 | digitalWrite(PTT_Pin, LOW); // Put the SA868 in TX mode 62 | 63 | delay(750); 64 | playMelody(); 65 | delay(750); 66 | playMorse(); 67 | 68 | digitalWrite(PTT_Pin, HIGH); // Put the SA868 in RX mode 69 | delay(delayms); // wait 30 seconds to allow cooldown of SA868 70 | } 71 | 72 | void moduleInit(){ 73 | ESerial.print("AT+DMOCONNECT\r\n"); 74 | delay(500); 75 | }; 76 | 77 | void moduleSetFreq(float freq){ 78 | String toSend=""; 79 | toSend+="AT+DMOSETGROUP=1,"; 80 | toSend+=String(freq,4); 81 | toSend+=","; 82 | toSend+=String(freq,4); 83 | toSend+=","; 84 | toSend+="0000,"; 85 | toSend+="3,"; 86 | toSend+="0000"; 87 | toSend+="\r\n"; 88 | ESerial.print(toSend); 89 | delay(100); 90 | }; 91 | 92 | void moduleSetVol(uint8_t vol){ 93 | String toSend=""; 94 | if(vol>8) vol=8; 95 | toSend+="AT+DMOSETVOLUME="; 96 | toSend+=(String)vol; 97 | toSend+="\r\n"; 98 | ESerial.print(toSend); 99 | delay(100); 100 | }; 101 | -------------------------------------------------------------------------------- /morsemelody.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Much of this code was copied from / inspired by Yet Another Foxbox 3 | * (YAFB) by Gregory Stoike (KN4CK) which can be found here: 4 | * https://github.com/N8HR/YAFB. It has been stripped down and adapted 5 | * for use on a Seeed Studio XIAO ESP32C3 and a NiceRF SA868. All credit 6 | * for this project goes to Gregory Stoike; I just made his work simple 7 | * enough for my own simple foxes. 8 | * 9 | * This project is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation, either version 3 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This project is distributed in the hope that it will be useful, but 15 | * WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | * General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this. If not, see . 21 | */ 22 | 23 | #define Sound_Pin 3 // GPIO03 | D1 on XIAO 24 | 25 | // ledc is used to create different tones 26 | int ledc_freq = 2000; 27 | int ledc_channel = 0; 28 | int ledc_resolution = 8; 29 | 30 | // Notes and Frequencies 31 | #define REST 0 32 | #define NOTE_B0 31 33 | #define NOTE_C1 33 34 | #define NOTE_CS1 35 35 | #define NOTE_D1 37 36 | #define NOTE_DS1 39 37 | #define NOTE_E1 41 38 | #define NOTE_F1 44 39 | #define NOTE_FS1 46 40 | #define NOTE_G1 49 41 | #define NOTE_GS1 52 42 | #define NOTE_A1 55 43 | #define NOTE_AS1 58 44 | #define NOTE_B1 62 45 | #define NOTE_C2 65 46 | #define NOTE_CS2 69 47 | #define NOTE_D2 73 48 | #define NOTE_DS2 78 49 | #define NOTE_E2 82 50 | #define NOTE_F2 87 51 | #define NOTE_FS2 93 52 | #define NOTE_G2 98 53 | #define NOTE_GS2 104 54 | #define NOTE_A2 110 55 | #define NOTE_AS2 117 56 | #define NOTE_B2 123 57 | #define NOTE_C3 131 58 | #define NOTE_CS3 139 59 | #define NOTE_D3 147 60 | #define NOTE_DS3 156 61 | #define NOTE_E3 165 62 | #define NOTE_F3 175 63 | #define NOTE_FS3 185 64 | #define NOTE_G3 196 65 | #define NOTE_GS3 208 66 | #define NOTE_A3 220 67 | #define NOTE_AS3 233 68 | #define NOTE_B3 247 69 | #define NOTE_C4 262 70 | #define NOTE_CS4 277 71 | #define NOTE_D4 294 72 | #define NOTE_DS4 311 73 | #define NOTE_E4 330 74 | #define NOTE_F4 349 75 | #define NOTE_FS4 370 76 | #define NOTE_G4 392 77 | #define NOTE_GS4 415 78 | #define NOTE_A4 440 79 | #define NOTE_AS4 466 80 | #define NOTE_B4 494 81 | #define NOTE_C5 523 82 | #define NOTE_CS5 554 83 | #define NOTE_D5 587 84 | #define NOTE_DS5 622 85 | #define NOTE_E5 659 86 | #define NOTE_F5 698 87 | #define NOTE_FS5 740 88 | #define NOTE_G5 784 89 | #define NOTE_GS5 831 90 | #define NOTE_A5 880 91 | #define NOTE_AS5 932 92 | #define NOTE_B5 988 93 | #define NOTE_C6 1047 94 | #define NOTE_CS6 1109 95 | #define NOTE_D6 1175 96 | #define NOTE_DS6 1245 97 | #define NOTE_E6 1319 98 | #define NOTE_F6 1397 99 | #define NOTE_FS6 1480 100 | #define NOTE_G6 1568 101 | #define NOTE_GS6 1661 102 | #define NOTE_A6 1760 103 | #define NOTE_AS6 1865 104 | #define NOTE_B6 1976 105 | #define NOTE_C7 2093 106 | #define NOTE_CS7 2217 107 | #define NOTE_D7 2349 108 | #define NOTE_DS7 2489 109 | #define NOTE_E7 2637 110 | #define NOTE_F7 2794 111 | #define NOTE_FS7 2960 112 | #define NOTE_G7 3136 113 | #define NOTE_GS7 3322 114 | #define NOTE_A7 3520 115 | #define NOTE_AS7 3729 116 | #define NOTE_B7 3951 117 | #define NOTE_C8 4186 118 | #define NOTE_CS8 4435 119 | #define NOTE_D8 4699 120 | #define NOTE_DS8 4978 121 | 122 | 123 | /****************************************************************************** 124 | * Morse and Audio Playing Functions 125 | * 126 | * playMelody 127 | * Plays a small melody 128 | * 129 | * playMorse 130 | * Plays 'callsign' in morse code 131 | * 132 | * createMorse 133 | * Converts 'callmessage' into a morse code language 134 | ******************************************************************************/ 135 | 136 | /****************************************************************************** 137 | * The playMelody fuction was adpated from: 138 | * https://github.com/robsoncouto/arduino-songs 139 | * 140 | * From https://github.com/robsoncouto/arduino-songs/blob/master/README.md 141 | * Commit 8fb1283 on Feb 13, 2019 142 | * 143 | * Copyright 144 | * 145 | * Every sketch here has been written by myself, although based on 146 | * scores I found online or books I own. These scores are linked in 147 | * each file when possible. You can use the sketches for anything, 148 | * I only kindly ask that you give credit if you use these codes on 149 | * a tutorial, video, example, etc. 150 | ******************************************************************************/ 151 | 152 | void playMelody() 153 | { 154 | // Change this to make the song slower or faster 155 | int tempo = 140; 156 | 157 | // Notes of the moledy followed by the duration 158 | // A 4 means a quarter note, 8 an eighteenth , 16 sixteenth, so on 159 | // Negative numbers are used to represent dotted notes, 160 | // so -4 means a dotted quarter note, that is, a quarter plus an eighteenth!! 161 | int melody[] = 162 | { 163 | NOTE_A4,16, NOTE_B4,16, NOTE_D5,16, NOTE_B4,16, NOTE_FS5,-8, NOTE_FS5,-8, NOTE_E5,-4, 164 | NOTE_A4,16, NOTE_B4,16, NOTE_D5,16, NOTE_B4,16, NOTE_E5,-8, NOTE_E5,-8, NOTE_D5,-8, 165 | NOTE_CS5,16, NOTE_B4,-8, NOTE_A4,16, NOTE_B4,16, NOTE_D5,16, NOTE_B4,16, 166 | NOTE_D5,4, NOTE_E5,8, NOTE_CS5,-8, NOTE_B4,16, NOTE_A4,8, NOTE_A4,8, NOTE_A4,8, 167 | NOTE_E5,4, NOTE_D5,2, NOTE_A4,16, NOTE_B4,16, NOTE_D5,16, NOTE_B4,16, 168 | NOTE_FS5,-8, NOTE_FS5,-8, NOTE_E5,-4, NOTE_A4,16, NOTE_B4,16, NOTE_D5,16, NOTE_B4,16, 169 | NOTE_A5,4, NOTE_CS5,8, NOTE_D5,-8, NOTE_CS5,16, NOTE_B4,8, NOTE_A4,16, NOTE_B4,16, NOTE_D5,16, NOTE_B4,16, 170 | NOTE_D5,4, NOTE_E5,8, NOTE_CS5,-8, NOTE_B4,16, NOTE_A4,4, NOTE_A4,8, NOTE_E5,4, NOTE_D5,2, REST,4, 171 | }; 172 | 173 | // sizeof gives the number of bytes, each int value is composed of two bytes (16 bits) 174 | // There are two values per note (pitch and duration), so for each note there are four bytes 175 | int notes = sizeof(melody) / sizeof(melody[0]) / 2; 176 | 177 | // This calculates the duration of a whole note in ms (60s/tempo)*4 beats 178 | int wholenote = (60000 * 4) / tempo; 179 | 180 | int divider = 0, noteDuration = 0; 181 | 182 | // Iterate over the notes of the melody. 183 | // Remember, the array is twice the number of notes (notes + durations) 184 | for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) 185 | { 186 | // calculates the duration of each note 187 | divider = melody[thisNote + 1]; 188 | if (divider > 0) { 189 | // Regular note, just proceed 190 | noteDuration = (wholenote) / divider; 191 | } else if (divider < 0) { 192 | // Dotted notes are represented with negative durations 193 | noteDuration = (wholenote) / abs(divider); 194 | noteDuration *= 1.5; // increases the duration in half for dotted notes 195 | } 196 | 197 | // we only play the note for 90% of the duration, leaving 10% as a pause 198 | tone(Sound_Pin, melody[thisNote], noteDuration * 0.9); 199 | 200 | // Wait for the specief duration before playing the next note. 201 | delay(noteDuration); 202 | 203 | // stop the waveform generation before the next note. 204 | noTone(Sound_Pin); 205 | } 206 | } 207 | 208 | /****************************************************************************** 209 | * Morse Generating Function 210 | * 211 | * Input: Yet Another Foxbox 212 | * Output: -.-- . - / .- -. --- - .... . .-. / ..-. --- -..- -... --- -..- 213 | ******************************************************************************/ 214 | 215 | String createMorse(String toconvert) 216 | { 217 | struct dict 218 | { 219 | char character; 220 | char morse[8]; 221 | }; 222 | 223 | dict morseLookup[54] = 224 | { 225 | { 'a', ".-" }, 226 | { 'b', "-..." }, 227 | { 'c', "-.-." }, 228 | { 'd', "-.." }, 229 | { 'e', "." }, 230 | { 'f', "..-." }, 231 | { 'g', "--." }, 232 | { 'h', "...." }, 233 | { 'i', ".." }, 234 | { 'j', ".---" }, 235 | { 'k', "-.-" }, 236 | { 'l', ".-.." }, 237 | { 'm', "--" }, 238 | { 'n', "-." }, 239 | { 'o', "---" }, 240 | { 'p', ".--." }, 241 | { 'q', "--.-" }, 242 | { 'r', ".-." }, 243 | { 's', "..." }, 244 | { 't', "-" }, 245 | { 'u', "..-" }, 246 | { 'v', "...-" }, 247 | { 'w', ".--" }, 248 | { 'x', "-..-" }, 249 | { 'y', "-.--" }, 250 | { 'z', "--.." }, 251 | { '0', "-----" }, 252 | { '1', ".----" }, 253 | { '2', "..---" }, 254 | { '3', "...--" }, 255 | { '4', "....-" }, 256 | { '5', "....." }, 257 | { '6', "-...." }, 258 | { '7', "--..." }, 259 | { '8', "---.." }, 260 | { '9', "----." }, 261 | { '.', ".-.-.-" }, 262 | { ',', "--..--" }, 263 | { '\?', "..--.." }, 264 | { '\'', ".----." }, 265 | { '!', "-.-.--" }, 266 | { '/', "-..-." }, 267 | { '(', "-.--." }, 268 | { ')', "-.--.-" }, 269 | { '&', ".-..." }, 270 | { ':', "---..." }, 271 | { ';', "-.-.-." }, 272 | { '=', "-...-" }, 273 | { '+', ".-.-." }, 274 | { '-', "-....-" }, 275 | { '_', "..--.-" }, 276 | { '\"', ".-..-." }, 277 | { '$', "...-..-" }, 278 | { '@', ".--.-." }, 279 | }; 280 | 281 | morse = ""; 282 | toconvert.toLowerCase(); 283 | 284 | for (int messagei = 0; messagei < toconvert.length(); messagei++) 285 | { 286 | for (int structi = 0; structi < sizeof(morseLookup)/sizeof(dict); structi++) 287 | { 288 | if (isSpace(toconvert.charAt(messagei))) 289 | { 290 | morse.concat("/ "); 291 | break; 292 | } 293 | else if (toconvert.charAt(messagei) == morseLookup[structi].character) 294 | { 295 | morse.concat(morseLookup[structi].morse); 296 | morse.concat(" "); 297 | } 298 | } 299 | } 300 | 301 | return morse; 302 | } 303 | 304 | 305 | /****************************************************************************** 306 | * Morse Playing Function 307 | ******************************************************************************/ 308 | 309 | void playMorse() 310 | { 311 | /* 312 | * short mark, dot or "dit" (.): "dot duration" is one time unit long 313 | * longer mark, dash or "dah" (-): three time units long 314 | * inter-element gap between the dots and dashes within a character: one dot duration or one unit long 315 | * short gap (between letters): three time units long 316 | * medium gap (between words): seven time units long 317 | */ 318 | 319 | int wpm = 13; 320 | int morsetone = 800; 321 | 322 | int wpmduration = (60000) / (wpm*50); 323 | 324 | ledcSetup(ledc_channel, ledc_freq, ledc_resolution); 325 | ledcAttachPin(Sound_Pin, ledc_channel); 326 | 327 | // convertedmessage 328 | Serial.println("Playing morse start"); 329 | for (int i = 0; i < morse.length(); i++) 330 | { 331 | // only have . - / SPACE 332 | switch (morse.charAt(i)) 333 | { 334 | case '.': 335 | ledcWriteTone(ledc_channel, morsetone * 10); 336 | delay(1 * wpmduration); 337 | ledcWriteTone(ledc_channel, 0); 338 | delay(1 * wpmduration); 339 | break; 340 | case '-': 341 | ledcWriteTone(ledc_channel, morsetone * 10); 342 | delay(3 * wpmduration); 343 | ledcWriteTone(ledc_channel, 0); 344 | delay(1 * wpmduration); 345 | break; 346 | case ' ': 347 | delay(2 * wpmduration); 348 | break; 349 | case '/': 350 | delay(6 * wpmduration); 351 | break; 352 | } 353 | } 354 | 355 | Serial.println("Playing morse end"); 356 | ledcDetachPin(Sound_Pin); 357 | } 358 | --------------------------------------------------------------------------------