├── .gitignore ├── .vscode └── extensions.json ├── LICENSE ├── README.md ├── board └── raspberry-mstrens.json ├── expresslrs_relay.png ├── include ├── README └── pico │ └── config_autogen.h ├── lib └── README ├── openTx_ELRS direct 4 MHz, 20 M Samples [19].logicdata ├── platformio.ini ├── src ├── config_basic.h ├── crc.cpp ├── crc.h ├── crsf.cpp ├── crsf.h ├── crsf_1pin.cpp ├── crsf_uart_tx_rx.pio ├── crsf_uart_tx_rx.pio.h ├── crsf_uart_tx_rx2.pio ├── main.cpp ├── sbus.cpp ├── sbus.h ├── sport.cpp ├── sport.h ├── sport_uart_tx_rx.pio ├── sport_uart_tx_rx.pio.h ├── tools.cpp ├── tools.h └── uart_tx_rx.pio.h ├── test └── README └── uf2 └── APPLICATION.uf2 /.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "platformio.platformio-ide" 6 | ], 7 | "unwantedRecommendations": [ 8 | "ms-vscode.cpptools-extension-pack" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/] 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | {one line to give the program's name and a brief idea of what it does.} 636 | Copyright (C) {year} {name of author} 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see [http://www.gnu.org/licenses/]. 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | {project} Copyright (C) {year} {fullname} 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | [http://www.gnu.org/licenses/]. 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | [http://www.gnu.org/philosophy/why-not-lgpl.html]. 676 | 677 | 678 | 679 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExpressLRS Relay 2 | A common trope for long-range pilots in the search for great performance and longer flights is to put the TX modules up in a pole or to use antenna trackers in order to increase the range by making the signals go over obstacles easier or by using high-gain antennas that has to point to the aircraft to be effective. Commercial systems like the Dragonlink, allow you to do that by providing standard SBUS and Mavilink protocols which can be retransmitted wirelessly to the radio using a wireless usually by a regular RC receiver and/or wifi-fi, Bluetooth allowing the user to stay out of the sun, use larger monitors for FPV, etc. 3 | The technology used in the ExpressLRS TX modules gives us an enormous range and excellent penetration but, due to the characteristics of the protocol (CRFS), the TX module has to be physically attached to the radio, negating the benefits expressed above. 4 | The objective of this project is to close this gap by creating a bidirectional converter for the CRFS protocol used in ExpressLSR and TBS Crossfire. 5 | Using two cheap microcontroller boards, the relay will convert the CRFS protocol used to SBUS+SPORT and back allowing the mounting of the ExpresssLRS TX into a pole or tracker, greatly extending its range and mobility. 6 | Currently, only RP2040-zero (and potentially Raspberry Pi Pico) is supported but other platforms with 3 serial ports can be used and may be supported in the future. 7 | ![](https://github.com/mstrens/expressLRS_relay/blob/master/expresslrs_relay.png?raw=true) 8 | ### Important: at this point the code is not ready for flying, only bench tests have being done! 9 | ### The authors can't take responsibility, personal or otherwise, by the use of this software. It is provided "as is". 10 | This software is licenced under the GPLv3. Please check the LICENSE file for more information but, in short: 11 | #### GPL v3 Requirements 12 | ° Include a copy of the full license text 13 | 14 | ° State all significant changes made to the original software 15 | 16 | ° Make available the original source code when you distribute any binaries based on the licensed work 17 | 18 | ° Include a copy of the original copyright notice 19 | 20 | ° In addition, GPL v3 states that anyone who includes the code as part of a consumer device has to include any installation information necessary to update and reinstall the software. 21 | #### The GPL v3 license permits users of the code to: 22 | ° Use the code for commercial purposes: Like GPL v2, GPL v3 imposes no conditions on the internal use of the software. 23 | 24 | ° Change the code: Users can change or rework the code, but if they distribute these changes/modifications in binary form, they’re also required to release these updates in source code form under the GPL v3 license. 25 | 26 | ° Distribute copies or modifications of the code: As long as these modifications are also released under the GPL v3 license, they can be distributed to others. 27 | 28 | ° Place warranty: Distributors of the original code can offer their own warranty on the licensed software. 29 | -------------------------------------------------------------------------------- /board/raspberry-mstrens.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "WizIO - Raspberry Pi Pico ( mstrens )", 3 | "url": "https://github.com", 4 | "vendor": "Raspberry Pi", 5 | "frameworks": [ "baremetal", "arduino" ], 6 | 7 | "build": { 8 | "core" : "RP2040", 9 | "variant" : "raspberry-pi-pico", 10 | "f_cpu" : "133000000L", 11 | "mcu" : "RP2040" 12 | }, 13 | 14 | "debug": { 15 | "openocd_target" : "rp2040.cfg", 16 | "svd_path" : "rp2040.svd" 17 | }, 18 | 19 | "upload": { 20 | "maximum_ram_size" : 262144, 21 | "maximum_size" : 2097152, 22 | "require_upload_port": true, 23 | "native_usb": true, 24 | "use_1200bps_touch": true, 25 | "wait_for_upload_port": false, 26 | "protocol": "picotool" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /expresslrs_relay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mstrens/expressLRS_relay/2a2561740dff4a22fb28fcef03236871c1247b25/expresslrs_relay.png -------------------------------------------------------------------------------- /include/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project header files. 3 | 4 | A header file is a file containing C declarations and macro definitions 5 | to be shared between several project source files. You request the use of a 6 | header file in your project source file (C, C++, etc) located in `src` folder 7 | by including it, with the C preprocessing directive `#include'. 8 | 9 | ```src/main.c 10 | 11 | #include "header.h" 12 | 13 | int main (void) 14 | { 15 | ... 16 | } 17 | ``` 18 | 19 | Including a header file produces the same results as copying the header file 20 | into each source file that needs it. Such copying would be time-consuming 21 | and error-prone. With a header file, the related declarations appear 22 | in only one place. If they need to be changed, they can be changed in one 23 | place, and programs that include the header file will automatically use the 24 | new version when next recompiled. The header file eliminates the labor of 25 | finding and changing all the copies as well as the risk that a failure to 26 | find one copy will result in inconsistencies within a program. 27 | 28 | In C, the usual convention is to give header files names that end with `.h'. 29 | It is most portable to use only letters, digits, dashes, and underscores in 30 | header file names, and at most one dot. 31 | 32 | Read more about using header files in official GCC documentation: 33 | 34 | * Include Syntax 35 | * Include Operation 36 | * Once-Only Headers 37 | * Computed Includes 38 | 39 | https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html 40 | -------------------------------------------------------------------------------- /include/pico/config_autogen.h: -------------------------------------------------------------------------------- 1 | 2 | /* SELECT BOARD */ 3 | #include "boards/pico.h" 4 | 5 | 6 | -------------------------------------------------------------------------------- /lib/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project specific (private) libraries. 3 | PlatformIO will compile them to static libraries and link into executable file. 4 | 5 | The source code of each library should be placed in a an own separate directory 6 | ("lib/your_library_name/[here are source files]"). 7 | 8 | For example, see a structure of the following two libraries `Foo` and `Bar`: 9 | 10 | |--lib 11 | | | 12 | | |--Bar 13 | | | |--docs 14 | | | |--examples 15 | | | |--src 16 | | | |- Bar.c 17 | | | |- Bar.h 18 | | | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html 19 | | | 20 | | |--Foo 21 | | | |- Foo.c 22 | | | |- Foo.h 23 | | | 24 | | |- README --> THIS FILE 25 | | 26 | |- platformio.ini 27 | |--src 28 | |- main.c 29 | 30 | and a contents of `src/main.c`: 31 | ``` 32 | #include 33 | #include 34 | 35 | int main (void) 36 | { 37 | ... 38 | } 39 | 40 | ``` 41 | 42 | PlatformIO Library Dependency Finder will find automatically dependent 43 | libraries scanning project source files. 44 | 45 | More information about PlatformIO Library Dependency Finder 46 | - https://docs.platformio.org/page/librarymanager/ldf.html 47 | -------------------------------------------------------------------------------- /openTx_ELRS direct 4 MHz, 20 M Samples [19].logicdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mstrens/expressLRS_relay/2a2561740dff4a22fb28fcef03236871c1247b25/openTx_ELRS direct 4 MHz, 20 M Samples [19].logicdata -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [env:raspberry-mstrens] 12 | platform = wizio-pico 13 | board = raspberry-mstrens 14 | framework = baremetal 15 | 16 | board_build.pio = 17 | src/sport_uart_tx_rx.pio src/crsf_uart_tx_rx.pio 18 | 19 | ;monitor_port = COM5 20 | monitor_speed = 115200 21 | 22 | build_flags = -D LIB_PICO_STDIO_USB 23 | -D PICO_XOSC_STARTUP_DELAY_MULTIPLIER=64 24 | ;build_flags = -D LIB_PICO_STDIO_UART ; if Serial is not used 25 | ;build_flags = -D LIB_PICO_STDIO_SEMIHOSTING 26 | 27 | ;lib_deps = 28 | -------------------------------------------------------------------------------- /src/config_basic.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/crc.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | #include 18 | 19 | GENERIC_CRC8::GENERIC_CRC8(uint8_t poly) 20 | { 21 | uint8_t crc; 22 | 23 | for (uint16_t i = 0; i < crclen; i++) 24 | { 25 | crc = i; 26 | for (uint8_t j = 0; j < 8; j++) 27 | { 28 | crc = (crc << 1) ^ ((crc & 0x80) ? poly : 0); 29 | } 30 | crc8tab[i] = crc & 0xFF; 31 | } 32 | } 33 | 34 | uint8_t GENERIC_CRC8::calc(const uint8_t data) 35 | { 36 | return crc8tab[data]; 37 | } 38 | 39 | uint8_t GENERIC_CRC8::calc(const uint8_t *data, uint8_t len, uint8_t crc) 40 | { 41 | while (len--) 42 | { 43 | crc = crc8tab[crc ^ *data++]; 44 | } 45 | return crc; 46 | } 47 | 48 | GENERIC_CRC14::GENERIC_CRC14(uint16_t poly) 49 | { 50 | uint16_t crc; 51 | for (uint16_t i = 0; i < crclen; i++) 52 | { 53 | crc = i << (14 - 8); 54 | for (uint8_t j = 0; j < 8; j++) 55 | { 56 | crc = (crc << 1) ^ ((crc & 0x2000) ? poly : 0); 57 | } 58 | crc14tab[i] = crc; 59 | } 60 | } 61 | 62 | uint16_t GENERIC_CRC14::calc(uint8_t *data, uint8_t len, uint16_t crc) 63 | { 64 | while (len--) 65 | { 66 | crc = (crc << 8) ^ crc14tab[((crc >> 6) ^ (uint16_t) *data++) & 0x00FF]; 67 | } 68 | return crc & 0x3FFF; 69 | } 70 | 71 | uint16_t GENERIC_CRC14::calc(volatile uint8_t *data, uint8_t len, uint16_t crc) 72 | { 73 | while (len--) 74 | { 75 | crc = (crc << 8) ^ crc14tab[((crc >> 6) ^ (uint16_t) *data++) & 0x00FF]; 76 | } 77 | return crc & 0x3FFF; 78 | } 79 | 80 | 81 | // CRC8 implementation with polynom = x^8+x^7+x^6+x^4+x^2+1 (0xD5) 82 | const unsigned char crc8tab[256] = { 83 | 0x00, 0xD5, 0x7F, 0xAA, 0xFE, 0x2B, 0x81, 0x54, 84 | 0x29, 0xFC, 0x56, 0x83, 0xD7, 0x02, 0xA8, 0x7D, 85 | 0x52, 0x87, 0x2D, 0xF8, 0xAC, 0x79, 0xD3, 0x06, 86 | 0x7B, 0xAE, 0x04, 0xD1, 0x85, 0x50, 0xFA, 0x2F, 87 | 0xA4, 0x71, 0xDB, 0x0E, 0x5A, 0x8F, 0x25, 0xF0, 88 | 0x8D, 0x58, 0xF2, 0x27, 0x73, 0xA6, 0x0C, 0xD9, 89 | 0xF6, 0x23, 0x89, 0x5C, 0x08, 0xDD, 0x77, 0xA2, 90 | 0xDF, 0x0A, 0xA0, 0x75, 0x21, 0xF4, 0x5E, 0x8B, 91 | 0x9D, 0x48, 0xE2, 0x37, 0x63, 0xB6, 0x1C, 0xC9, 92 | 0xB4, 0x61, 0xCB, 0x1E, 0x4A, 0x9F, 0x35, 0xE0, 93 | 0xCF, 0x1A, 0xB0, 0x65, 0x31, 0xE4, 0x4E, 0x9B, 94 | 0xE6, 0x33, 0x99, 0x4C, 0x18, 0xCD, 0x67, 0xB2, 95 | 0x39, 0xEC, 0x46, 0x93, 0xC7, 0x12, 0xB8, 0x6D, 96 | 0x10, 0xC5, 0x6F, 0xBA, 0xEE, 0x3B, 0x91, 0x44, 97 | 0x6B, 0xBE, 0x14, 0xC1, 0x95, 0x40, 0xEA, 0x3F, 98 | 0x42, 0x97, 0x3D, 0xE8, 0xBC, 0x69, 0xC3, 0x16, 99 | 0xEF, 0x3A, 0x90, 0x45, 0x11, 0xC4, 0x6E, 0xBB, 100 | 0xC6, 0x13, 0xB9, 0x6C, 0x38, 0xED, 0x47, 0x92, 101 | 0xBD, 0x68, 0xC2, 0x17, 0x43, 0x96, 0x3C, 0xE9, 102 | 0x94, 0x41, 0xEB, 0x3E, 0x6A, 0xBF, 0x15, 0xC0, 103 | 0x4B, 0x9E, 0x34, 0xE1, 0xB5, 0x60, 0xCA, 0x1F, 104 | 0x62, 0xB7, 0x1D, 0xC8, 0x9C, 0x49, 0xE3, 0x36, 105 | 0x19, 0xCC, 0x66, 0xB3, 0xE7, 0x32, 0x98, 0x4D, 106 | 0x30, 0xE5, 0x4F, 0x9A, 0xCE, 0x1B, 0xB1, 0x64, 107 | 0x72, 0xA7, 0x0D, 0xD8, 0x8C, 0x59, 0xF3, 0x26, 108 | 0x5B, 0x8E, 0x24, 0xF1, 0xA5, 0x70, 0xDA, 0x0F, 109 | 0x20, 0xF5, 0x5F, 0x8A, 0xDE, 0x0B, 0xA1, 0x74, 110 | 0x09, 0xDC, 0x76, 0xA3, 0xF7, 0x22, 0x88, 0x5D, 111 | 0xD6, 0x03, 0xA9, 0x7C, 0x28, 0xFD, 0x57, 0x82, 112 | 0xFF, 0x2A, 0x80, 0x55, 0x01, 0xD4, 0x7E, 0xAB, 113 | 0x84, 0x51, 0xFB, 0x2E, 0x7A, 0xAF, 0x05, 0xD0, 114 | 0xAD, 0x78, 0xD2, 0x07, 0x53, 0x86, 0x2C, 0xF9 115 | }; 116 | 117 | uint8_t crc8(const uint8_t * ptr, uint32_t len) 118 | { 119 | uint8_t crc = 0; 120 | for (uint32_t i=0; i 19 | //#include "targets.h" 20 | 21 | #define crclen 256 22 | #define CRSF_CRC_POLY 0xd5 23 | 24 | class GENERIC_CRC8 25 | { 26 | private: 27 | uint8_t crc8tab[crclen]; 28 | uint8_t crcpoly; 29 | 30 | public: 31 | GENERIC_CRC8(uint8_t poly); 32 | uint8_t calc(const uint8_t data); 33 | uint8_t calc(const uint8_t *data, uint8_t len, uint8_t crc = 0); 34 | }; 35 | 36 | class GENERIC_CRC14 37 | { 38 | private: 39 | uint16_t crc14tab[crclen]; 40 | uint16_t crcpoly; 41 | 42 | public: 43 | GENERIC_CRC14(uint16_t poly); 44 | uint16_t calc(uint8_t *data, uint8_t len, uint16_t crc); 45 | uint16_t calc(volatile uint8_t *data, uint8_t len, uint16_t crc); 46 | }; 47 | 48 | uint8_t crc8(const uint8_t * ptr, uint32_t len); 49 | uint8_t command_crc8(const uint8_t * ptr, uint32_t len); 50 | -------------------------------------------------------------------------------- /src/crsf.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | //#include 18 | #include "hardware/pio.h" 19 | #include "hardware/dma.h" 20 | //#include "hardware/irq.h" 21 | //#include "uart_tx.pio.h" 22 | #include "pico/util/queue.h" 23 | #include "crsf_uart_tx_rx.pio.h" 24 | #include "crsf.h" 25 | #include "config_basic.h" 26 | #include "crc.h" 27 | #include "sport.h" 28 | #include "stdio.h" // used by printf 29 | #include "tools.h" 30 | 31 | //#define DEBUG_WITH_FIXED_RC_FRAME 32 | //#define DEBUG_RECEIVED_FRAME // print the content of valid received frames 33 | 34 | 35 | 36 | #define CRSF_PIO_PIN_TX 7 // pin being used by the UART pio for ELRS 37 | #define CRSF_PIO_PIN_RX 8 // pin being used by the UART pio for ELRS 38 | 39 | // When we look at the data exchanged with openTX with a logic analyser, it seems that: 40 | // openTX send a frame with Rc channel once every 4msec (24 bytes at 400000 bauds = 24*25micro sec) 41 | // the eLRS module sent some frame back about 40/45 usec later with an adress = EA 42 | // When the RX has no telemetry, there are at least 2 types of frame to openTx 43 | // one has a length = 0X0D and a type = 3A; it is sent every 0.2msec 44 | // the other has a length = 0X0C and a type = 0C (= link statistic); it is sent once every 0.32 sec 45 | // I expect that there are some others type (gps, vario, ...) 46 | // Still at least when ELRS TX was configured with 500 frames/sec, the connection occurs only when the frames where generates every 2msec instead of 4msec 47 | // Probably this is related to the frame rate selected in ELRS TX 48 | 49 | queue_t crsfRxQueue ; // queue to get the telemetry data from crsf (from an irq handler) 50 | 51 | 52 | //// This is the same as the default UART baud rate on Pico 53 | const uint32_t CRSF_SERIAL_BAUD = 400000; 54 | 55 | // one pio with 2 state machine is used to manage the inverted hal duplex uart for crsf 56 | PIO crsfPio = pio1; 57 | uint crsfSmRx = 1; // to get the telemetry from crsf 58 | uint crsfSmTx = 0; // to send the channels to crsf 59 | uint crsfOffsetTx ; 60 | uint crsfOffsetRx ; 61 | 62 | // dma channel is used to send Sport telemetry without blocking 63 | int crsf_dma_chan; 64 | dma_channel_config crsfDmaConfig; 65 | 66 | uint8_t crsfTxBuffer[50]; // buffer to be used by dma to send the RC channels 67 | uint8_t crsfTxBufferLength; 68 | 69 | 70 | uint32_t restoreCrsfPioToReceiveMillis = 0; // when 0, the pio is normally in receive mode, 71 | // otherwise, it is the timestamp when pio transmit has to be restore to receive mode 72 | 73 | //#define CRSF_RC_FRAME_INTERVAL 4 // msec replaced by an interval in micro sec 74 | #define CRSF_RC_FRAME_INTERVAL_MICROS 4000 // microsec 75 | #define CRSF_IRQ_TXFIFO_EMPTY PIO1_IRQ_1 // irq when txfifo is empty 76 | #define CRSF_IRQ_RX_RECEIVED PIO1_IRQ_0 // irq when a byte is received 77 | 78 | uint32_t crsfRcFrameIntervalMicros = CRSF_RC_FRAME_INTERVAL_MICROS ; 79 | 80 | volatile CRSF_MODE crsfMode = RECEIVING; 81 | 82 | crsf_tlm_state tlmState; // store the state of handling receiving tlm bytes 83 | 84 | #define FRAME_TYPES_MAX 5 85 | uint32_t crsfFrameNextMillis[FRAME_TYPES_MAX] = {0} ; 86 | uint8_t crsf_last_frame_idx = 0 ; 87 | 88 | voltageFrameStruct voltageFrame; 89 | varioFrameStruct varioFrame; 90 | attitudeFrameStruct attitudeFrame; 91 | gpsFrameStruct gpsFrame; 92 | 93 | //uint8_t CRSFTlmFrame[50]; 94 | //uint8_t CRSFTlmFrameLength; 95 | 96 | rcFrameStruct crsfRcFrame ; 97 | bool crsfRcFrameReady = false; 98 | 99 | bool oneFrameFromElrsReceived = false; // become true when a valid frame is received from ELRS 100 | 101 | GENERIC_CRC8 crsf_crc(CRSF_CRC_POLY); 102 | 103 | #define TEST_PIN 3 104 | 105 | void setupCRSF(){ 106 | //Serial1.begin(SERIAL_BAUD_CRSF); 107 | // configure the queue to get the telemetry data from crsf in the irq handle 108 | queue_init (&crsfRxQueue, sizeof(uint8_t), 250); 109 | 110 | // set up the DMA but do not yet start it to send rc data to crsf 111 | // Configure a channel to write the same byte (8 bits) repeatedly to PIO1 112 | // SM0's TX FIFO, paced by the data request signal from that peripheral. 113 | crsf_dma_chan = dma_claim_unused_channel(true); 114 | crsfDmaConfig = dma_channel_get_default_config(crsf_dma_chan); 115 | channel_config_set_read_increment(&crsfDmaConfig, true); 116 | channel_config_set_write_increment(&crsfDmaConfig, false); 117 | channel_config_set_dreq(&crsfDmaConfig, DREQ_PIO1_TX0); // use state machine 0 on PIO1 118 | channel_config_set_transfer_data_size(&crsfDmaConfig, DMA_SIZE_8); 119 | dma_channel_configure( 120 | crsf_dma_chan, 121 | &crsfDmaConfig, 122 | &pio1_hw->txf[0], // Write address (only need to set this once) 123 | &crsfTxBuffer[0], // we use always the same buffer 124 | 0 , // do not yet provide the number of bytes (DMA cycles) 125 | false // Don't start yet 126 | ); 127 | // Set up the state machine for transmit and start it (but dma is not yet started) 128 | crsfOffsetTx = pio_add_program(crsfPio, &crsf_uart_tx_program); 129 | crsf_uart_tx_program_init(crsfPio, crsfSmTx, crsfOffsetTx, CRSF_PIO_PIN_TX, CRSF_SERIAL_BAUD , true); // we use the same pin and baud rate for tx and rx, true means that UART is inverted 130 | 131 | // Set up an irq on pio to handle when Tx fifo is empty. We use PIO1_IRQ_1 for this 132 | //irq_set_exclusive_handler( CRSF_IRQ_TXFIFO_EMPTY , crsfPioTxEmptyHandlerIrq) ; 133 | //irq_set_enabled (CRSF_IRQ_TXFIFO_EMPTY , false) ; 134 | 135 | // set an irq on pio to handle a received byte 136 | irq_set_exclusive_handler( CRSF_IRQ_RX_RECEIVED , crsfPioRxHandlerIrq) ; 137 | irq_set_enabled (CRSF_IRQ_RX_RECEIVED , false) ; 138 | 139 | // Set up the state machine we're going to use to receive them. the sm is started 140 | crsfOffsetRx = pio_add_program(crsfPio, &crsf_uart_rx_program); 141 | crsf_uart_rx_program_init(crsfPio, crsfSmRx, crsfOffsetRx, CRSF_PIO_PIN_RX, CRSF_SERIAL_BAUD , true); 142 | 143 | irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 144 | 145 | } 146 | 147 | void crsfPioRxHandlerIrq(){ // when a byte is received on the CRSF, read the pio CRSF fifo and push the data to a queue (to be processed in the main loop) 148 | irq_clear (CRSF_IRQ_RX_RECEIVED ); // clear the irq flag 149 | while ( ! pio_sm_is_rx_fifo_empty (crsfPio ,crsfSmRx)){ // when some data have been received 150 | uint8_t c = pio_sm_get (crsfPio , crsfSmRx) >> 24; // read the data 151 | queue_try_add (&crsfRxQueue, &c); // push to the queue 152 | 153 | //sportRxMillis = millis(); // save the timestamp. 154 | } 155 | } 156 | 157 | // when crsf state machine fires the IRQ because TXFIFO is empty 158 | // - clear the IRQ flag for TXFIFO and disabled it 159 | // - clear the IRQ flag for receiving 160 | // _ clear the Rx queue 161 | // - enable the receiving IRQ 162 | // - switch PIO receiving mode 163 | // - set state to receiving mode 164 | /*void crsfPioTxEmptyHandlerIrq(){ 165 | //printf("in irq\n"); 166 | pio_interrupt_clear(crsfPio, 0); // clear the irq flag in the pio that was set when Txfifo is empty 167 | irq_set_enabled (CRSF_IRQ_TXFIFO_EMPTY , false) ; // disable the IRQ to handle when TXFIFO is empty 168 | irq_clear (CRSF_IRQ_TXFIFO_EMPTY ); // clear the irq flag in NVIC 169 | irq_clear (CRSF_IRQ_RX_RECEIVED ); // clear the irq flag for receiving 170 | clearCrsfRxQueue(); // clear the queue and reset the process state 171 | irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 172 | crsf_uart_tx_program_stop(crsfPio ,crsfSmTx , CRSF_PIO_PIN); 173 | crsf_uart_rx_program_restart(crsfPio ,crsfSmTx , CRSF_PIO_PIN , true); // false = no invert 174 | crsfMode = RECEIVING ; 175 | } 176 | */ 177 | /* 178 | int64_t alarm_callback_switchToReceiveMode(alarm_id_t id, void *user_data) { 179 | irq_clear (CRSF_IRQ_RX_RECEIVED ); // clear the irq flag for receiving 180 | clearCrsfRxQueue(); // clear the queue and reset the process state 181 | //irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 182 | crsf_uart_tx_program_stop(crsfPio ,crsfSmTx , CRSF_PIO_PIN); 183 | crsf_uart_rx_program_restart(crsfPio ,crsfSmRx , CRSF_PIO_PIN , true); // true = invert 184 | irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 185 | 186 | crsfMode = RECEIVING ; 187 | return 0; // return 0 to avoid that the callback is called automatically in the future; we use a new add at each time. 188 | } 189 | */ 190 | 191 | //#ifdef DEBUG_WITH_FIXED_RC_FRAME 192 | uint8_t testBuffer[]={ 0xEE , 0x18, 0x16, 0xF2, 0x83, 0x1E, 0xFC, 0x00, 0x08, 0x3E , 0XF0, 0X81, 193 | 0X0F, 0x7C , 0xE0, 0x03, 0x1F, 0XF8, 0xC0, 0x07, 0x3E, 0XF0, 0X81, 0x0F, 0x7C, 0X63}; 194 | uint8_t testBufferLength = 0x1A; 195 | //#endif 196 | 197 | #define MODULE_ADDRESS 0xEE 198 | 199 | void sendCrsfRcFrame(void){ // called by main loop : 200 | // when crsf state is receiving mode , if last transmit is more than x msec and if Rc channels are available, 201 | // - process once more the Rx queue 202 | // - clear the Rx queue from crsf (just to be sure because all bytes should have been processed) 203 | // - fill the TX buffer with RC channels , 204 | // - switch the pio to transmit mode, 205 | // - start the dma to send the RC channel 206 | // - set state to transmit and save the timestamp. 207 | // - clear the irq on PIO1_IRQ1 and enable it (it is fired by the PIO when txfifo becomes emtpty) 208 | // when crsf state machine fires the IRQ because TXFIFO is empty, it call crsfPioTxEmptyHandlerIrq() 209 | // - clear the IRQ flag for TXFIFO and disabled it 210 | // - clear the IRQ flag for receiving 211 | // _ clear the Rx queue 212 | // - enable the receiving IRQ 213 | // - switch PIO receiving mode 214 | // - set state to receiving mode 215 | // when a character is received in PIO, it fires an irq that is handled in crsfPioRxHandlerIrq() 216 | // - the irq push the data to a queue 217 | // The main loop read the queue and process the received data in handleTlmIn() 218 | static uint32_t lastRcFrameSendMillis = 0; 219 | static uint32_t lastRcFrameSendMicros = 0; 220 | static bool waitFirstFrameFromElrs = true; 221 | ////if ( (crsfMode == RECEIVING) && ( (millis() - lastRcFrameSendMillis ) > CRSF_RC_FRAME_INTERVAL ) && ( crsfRcFrameReady) ) { 222 | //if ( ( (millis() - lastRcFrameSendMillis ) >= CRSF_RC_FRAME_INTERVAL ) && ( crsfRcFrameReady) ) { 223 | //if ( ( (millis() - lastRcFrameSendMillis ) >= CRSF_RC_FRAME_INTERVAL ) ) { 224 | if ( ( (micros() - lastRcFrameSendMicros ) >= crsfRcFrameIntervalMicros ) ) { 225 | if (waitFirstFrameFromElrs && oneFrameFromElrsReceived){ 226 | waitFirstFrameFromElrs = false; 227 | createRadioModelIdFrame(); 228 | } else { 229 | createRcChannelsFrame(); 230 | } 231 | dma_channel_set_read_addr (crsf_dma_chan, &crsfTxBuffer[0], false); 232 | dma_channel_set_trans_count (crsf_dma_chan, crsfTxBufferLength, true) ; // start the dma 233 | // add_alarm_in_us( (crsfTxBufferLength *24)+40 , alarm_callback_switchToReceiveMode , NULL , false); // 400000 baud = 2.5 usec/bit = 25 usec/byte 234 | crsfMode = SENDING ; 235 | lastRcFrameSendMillis = millis(); 236 | lastRcFrameSendMicros = micros(); 237 | } 238 | } 239 | 240 | 241 | void clearCrsfRxQueue(){ 242 | uint8_t data; 243 | while ( !queue_is_empty(&crsfRxQueue)) queue_try_remove (&crsfRxQueue, &data); // clear the queue 244 | tlmState = CRSF_TLM_NOT_RECEIVING; // reset the state of processing data 245 | } 246 | 247 | 248 | void fillCrsfTxBuffer(uint8_t c){ 249 | crsfTxBuffer[crsfTxBufferLength++] = c; 250 | } 251 | 252 | void fillCrsfTxBuffer(uint8_t * bufferFrom , uint8_t length){ 253 | uint8_t count = 0; 254 | while (count < length){ 255 | crsfTxBuffer[crsfTxBufferLength] = bufferFrom[count++]; 256 | crsfTxBufferLength++; 257 | } 258 | } 259 | 260 | void createRcChannelsFrame(){ 261 | crsfTxBufferLength = 0; 262 | fillCrsfTxBuffer(MODULE_ADDRESS); 263 | fillCrsfTxBuffer(CRSF_FRAME_RC_PAYLOAD_SIZE + 2); 264 | fillCrsfTxBuffer(CRSF_FRAMETYPE_RC_CHANNELS); 265 | #ifdef DEBUG_WITH_FIXED_RC_FRAME 266 | fillCrsfTxBuffer( &testBuffer[3] , CRSF_FRAME_RC_PAYLOAD_SIZE ); // payload size include type and CRC 267 | #else 268 | fillCrsfTxBuffer( ( (uint8_t *) &crsfRcFrame) + 3 , CRSF_FRAME_RC_PAYLOAD_SIZE ); 269 | #endif 270 | fillCrsfTxBuffer(crsf_crc.calc(&crsfTxBuffer[2], CRSF_FRAME_RC_PAYLOAD_SIZE + 1)); // crc includes frame type and so is 1 byte more than the payload 271 | } 272 | 273 | #define MODEL_ID 0 274 | void createRadioModelIdFrame(){ 275 | crsfTxBufferLength = 0; 276 | fillCrsfTxBuffer(CRSF_ADDRESS_FLIGHT_CONTROLLER); 277 | fillCrsfTxBuffer(8); // size of payload 278 | fillCrsfTxBuffer(CRSF_FRAMETYPE_COMMAND); 279 | fillCrsfTxBuffer(CRSF_ADDRESS_CRSF_TRANSMITTER) ; 280 | fillCrsfTxBuffer(CRSF_ADDRESS_RADIO_TRANSMITTER) ; 281 | fillCrsfTxBuffer(SUBCOMMAND_CRSF); 282 | fillCrsfTxBuffer(COMMAND_MODEL_SELECT_ID) ; 283 | fillCrsfTxBuffer(MODEL_ID); // sequence of the model ID (in range 0...63) 284 | fillCrsfTxBuffer(command_crc8(&crsfTxBuffer[2], 6)); 285 | fillCrsfTxBuffer(crc8(&crsfTxBuffer[2], 7)); 286 | } 287 | 288 | /* 289 | void sendCRSFRcFrame(){ 290 | static uint32_t lastRcFrameSendMillis ; 291 | if ( ( (millis() - lastRcFrameSendMillis ) > CRSF_RC_FRAME_INTERVAL ) && ( CRSFRcFrameReady) ) { 292 | //Serial1.write(MODULE_ADDRESS); 293 | //Serial1.write(CRSF_FRAME_RC_PAYLOAD_SIZE + 2); 294 | //Serial1.write(CRSF_FRAMETYPE_RC_CHANNELS); 295 | //Serial1.write(& CRSFRcFrame[3], CRSF_FRAME_RC_PAYLOAD_SIZE); 296 | //Serial1.write(crsf_crc.calc(&CRSFRcFrame[2], 22)); 297 | crsfTxBufferLength = 0; 298 | fillCrsfBuffer(MODULE_ADDRESS); 299 | fillCrsfBuffer(CRSF_FRAME_RC_PAYLOAD_SIZE + 2); 300 | fillCrsfBuffer(CRSF_FRAMETYPE_RC_CHANNELS); 301 | fillCrsfBuffer(&CRSFRcFrame[3], CRSF_FRAME_RC_PAYLOAD_SIZE); 302 | fillCrsfBuffer(crsf_crc.calc(&crsfTXBuffer[2], 22)); 303 | } 304 | } 305 | */ 306 | 307 | // read the rx queue and process each byte (= tlm data) 308 | // when a frame has been totally received, check it, and store the tlm data in separated fields (to be sent later by sport process) 309 | void handleTlmIn(){ 310 | //static uint8_t tlmBuffer[50]; 311 | static uint8_t tlmCounter; 312 | static uint8_t tlmLength ; // Length in the second byte of the message (is equal to the payload+2 because type and crc are included) 313 | static uint8_t tlmType; 314 | uint8_t c; 315 | while(! queue_is_empty(&crsfRxQueue)) { 316 | queue_try_remove (&crsfRxQueue,&c); 317 | //printf("%x\n", c); 318 | switch (tlmState) { 319 | case CRSF_TLM_NOT_RECEIVING : 320 | if (c == CRSF_ADDRESS_TLM) { 321 | tlmCounter=0; 322 | tlmFrame.tlmBuffer[tlmCounter++] = c; 323 | tlmState = CRSF_TLM_RECEIVING_SIZE; 324 | } 325 | break; 326 | case CRSF_TLM_RECEIVING_SIZE : 327 | tlmFrame.tlmBuffer[tlmCounter++] = c; 328 | tlmLength = c; 329 | tlmState = CRSF_TLM_RECEIVING_TYPE; 330 | break; 331 | case CRSF_TLM_RECEIVING_TYPE : 332 | if ( ( ( c == CRSF_FRAMETYPE_GPS) && (tlmLength == (CRSF_FRAME_GPS_PAYLOAD_SIZE+2) ) ) 333 | || ( ( c == CRSF_FRAMETYPE_VARIO) && (tlmLength == (CRSF_FRAME_VARIO_PAYLOAD_SIZE+2) ) ) 334 | || ( ( c == CRSF_FRAMETYPE_BATTERY_SENSOR) && (tlmLength == (CRSF_FRAME_BATTERY_SENSOR_PAYLOAD_SIZE+2) ) ) 335 | || ( ( c == CRSF_FRAMETYPE_ATTITUDE) && (tlmLength == (CRSF_FRAME_ATTITUDE_PAYLOAD_SIZE+2) ) ) 336 | || ( ( c == CRSF_FRAMETYPE_LINK_STATISTICS) && (tlmLength == (CRSF_FRAME_LINK_STATISTICS_PAYLOAD_SIZE+2) ) ) 337 | || ( ( c == CRSF_FRAMETYPE_RADIO_ID ) && (tlmLength == (CRSF_FRAME_OPENTX_SYNC_PAYLOAD_SIZE+2) ) ) ){ 338 | tlmType = c; 339 | tlmState = CRSF_TLM_RECEIVING_PAYLOAD; 340 | tlmFrame.tlmBuffer[tlmCounter++] = c; 341 | } else { 342 | tlmState = CRSF_TLM_NOT_RECEIVING; 343 | } 344 | break; 345 | case CRSF_TLM_RECEIVING_PAYLOAD : 346 | tlmFrame.tlmBuffer[tlmCounter++] = c; 347 | if (tlmCounter > tlmLength ) { // e.g. if tlmLength = 3, CRC is at idx 4 (because there is an adress in pos 0) 348 | tlmState = CRSF_TLM_RECEIVING_CRC; 349 | } 350 | break; 351 | case CRSF_TLM_RECEIVING_CRC : 352 | if ( c != crsf_crc.calc(&tlmFrame.tlmBuffer[2], tlmLength - 1)) { 353 | tlmState = CRSF_TLM_NOT_RECEIVING; 354 | } else { // we received a full telemetry packet; we can save it. 355 | storeTlmFrame(); 356 | //printf("frame received\n"); 357 | } 358 | break; 359 | 360 | } 361 | } 362 | } 363 | 364 | extern field fields[SPORT_TYPES_MAX]; 365 | 366 | void storeTlmFrame(){ 367 | #ifdef DEBUG_RECEIVED_FRAME 368 | for (uint8_t i = 0 ; i<(tlmFrame.tlmBuffer[1] +1); i++){ 369 | printf(" %X ",tlmFrame.tlmBuffer[i] ); 370 | } 371 | printf("\n"); 372 | #endif 373 | int32_t temp; 374 | oneFrameFromElrsReceived = true ; 375 | switch (tlmFrame.tlmBuffer[2]) { // byte 2 = type 376 | case CRSF_FRAMETYPE_GPS: 377 | temp = tlmFrame.gpsFrame.longitude; // degree with 7 decimals 378 | fields[LONGITUDE].value = (( ((((uint32_t)( temp < 0 ? -temp : temp)) /10 ) * 6 ) / 10 ) & 0x3FFFFFFF) | 0x80000000; 379 | if(temp < 0) fields[LONGITUDE].value |= 0x40000000; 380 | fields[LONGITUDE].available = true ; 381 | temp = tlmFrame.gpsFrame.latitude; 382 | fields[LATITUDE].value = (( ((((uint32_t)( temp < 0 ? -temp : temp)) /10 ) * 6 ) / 10 ) & 0x3FFFFFFF) ; 383 | if(temp < 0) fields[LATITUDE].value |= 0x40000000; 384 | fields[LATITUDE].available = true ; 385 | fields[GROUNDSPEED].value = tlmFrame.gpsFrame.groundspeed; //( km/h / 10 ) 386 | fields[GROUNDSPEED].available = true; 387 | fields[HEADING].value = tlmFrame.gpsFrame.heading; //( degree / 100 ) 388 | fields[HEADING].available = true; 389 | fields[ALTITUDE].value = tlmFrame.gpsFrame.altitude; 390 | fields[ALTITUDE].available = true; 391 | fields[NUMSAT].value = tlmFrame.gpsFrame.numSat; 392 | fields[NUMSAT].available = true; 393 | break; 394 | case CRSF_FRAMETYPE_VARIO: 395 | fields[VSPEED].value = tlmFrame.varioFrame.vSpeed; 396 | fields[VSPEED].available = true; 397 | break; 398 | case CRSF_FRAMETYPE_BATTERY_SENSOR: 399 | fields[MVOLT].value = tlmFrame.voltageFrame.mVolt; 400 | fields[MVOLT].available = true; 401 | fields[CURRENT].value = tlmFrame.voltageFrame.current; 402 | fields[CURRENT].available = true; 403 | fields[CAPACITY].value = tlmFrame.voltageFrame.capacity; 404 | fields[CAPACITY].available = true; 405 | fields[REMAIN].value = tlmFrame.voltageFrame.remain; 406 | fields[REMAIN].available = true; 407 | break; 408 | case CRSF_FRAMETYPE_ATTITUDE: 409 | fields[PITCH].value = tlmFrame.attitudeFrame.pitch; 410 | fields[PITCH].available = true; 411 | fields[ROLL].value = tlmFrame.attitudeFrame.roll; 412 | fields[ROLL].available = true; 413 | fields[YAW].value = tlmFrame.attitudeFrame.yaw; 414 | fields[YAW].available = true; 415 | break; 416 | case CRSF_FRAMETYPE_LINK_STATISTICS: 417 | fields[UPLINK_RSSI_1].value = tlmFrame.linkstatisticsFrame.uplink_RSSI_1; 418 | fields[UPLINK_RSSI_1].available = true; 419 | fields[UPLINK_RSSI_2].value = tlmFrame.linkstatisticsFrame.uplink_RSSI_2; 420 | fields[UPLINK_RSSI_2].available = true; 421 | fields[UPLINK_LINK_QUALITY].value = tlmFrame.linkstatisticsFrame.uplink_Link_quality; 422 | fields[UPLINK_LINK_QUALITY].available = true; 423 | fields[UPLINK_SNR].value = tlmFrame.linkstatisticsFrame.uplink_SNR; 424 | fields[UPLINK_SNR].available = true; 425 | fields[ACTIVE_ANTENNA].value = tlmFrame.linkstatisticsFrame.active_antenna; 426 | fields[ACTIVE_ANTENNA].available = true; 427 | fields[RF_MODE].value = tlmFrame.linkstatisticsFrame.rf_Mode; 428 | fields[RF_MODE].available = true; 429 | fields[UPLINK_TX_POWER].value = tlmFrame.linkstatisticsFrame.uplink_TX_Power; 430 | fields[UPLINK_TX_POWER].available = true; 431 | fields[DOWNLINK_RSSI].value = tlmFrame.linkstatisticsFrame.downlink_RSSI; 432 | fields[DOWNLINK_RSSI].available = true; 433 | fields[DOWNLINK_LINK_QUALITY].value = tlmFrame.linkstatisticsFrame.downlink_Link_quality; 434 | fields[DOWNLINK_LINK_QUALITY].available = true; 435 | fields[DOWNLINK_SNR].value = tlmFrame.linkstatisticsFrame.downlink_SNR; 436 | fields[DOWNLINK_SNR].available = true; 437 | //printf(" Rf mode %x", tlmFrame.linkstatisticsFrame.rf_Mode); 438 | break; 439 | case CRSF_FRAMETYPE_RADIO_ID: 440 | int rate ; 441 | int offset; 442 | if ( ( tlmFrame.opentxSyncFrame.dest_addr == 0xEA ) && (tlmFrame.opentxSyncFrame.synchrType == 0x10) ) { 443 | rate = swap_int32(tlmFrame.opentxSyncFrame.rate) / 10 ; // save rate in usec 444 | offset = swap_int32(tlmFrame.opentxSyncFrame.offset) / 10 ;// save offset in usec 445 | } 446 | printf( "tlm="); 447 | for ( uint8_t i = 0; i < (0X0D+2) ; i++){ 448 | printf("%X ",tlmFrame.tlmBuffer[i]); 449 | } 450 | printf("rate=%i offset=%i\n", rate , offset ); 451 | break; 452 | } 453 | } 454 | 455 | -------------------------------------------------------------------------------- /src/crsf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | #define CRSF_ADDRESS_CRSF_RECEIVER 0xEC // address of the receiver (used for telemetry) 22 | #define CRSF_ADDRESS_FLIGHT_CONTROLLER 0xC8 // address of the flight controller 23 | #define CRSF_ADDRESS_CRSF_TRANSMITTER 0xEE // address of the crsf transmitter 24 | #define CRSF_ADDRESS_RADIO_TRANSMITTER 0xEA // address of the sender 25 | 26 | #define SUBCOMMAND_CRSF 0x10 // subcommand to send the radio model id 27 | 28 | #define COMMAND_MODEL_SELECT_ID 0x05 // sub command to identify the radio model id 29 | 30 | typedef enum 31 | 32 | { 33 | CRSF_FRAMETYPE_GPS = 0x02, 34 | CRSF_FRAMETYPE_VARIO = 0x07, 35 | CRSF_FRAMETYPE_BATTERY_SENSOR = 0x08, 36 | CRSF_FRAMETYPE_LINK_STATISTICS = 0x14, 37 | CRSF_FRAMETYPE_OPENTX_SYNC = 0x10, 38 | CRSF_FRAMETYPE_RADIO_ID = 0x3A, 39 | CRSF_FRAMETYPE_RC_CHANNELS = 0x16, 40 | CRSF_FRAMETYPE_ATTITUDE = 0x1E, 41 | CRSF_FRAMETYPE_FLIGHT_MODE = 0x21, 42 | // Extended Header Frames, range: 0x28 to 0x96 43 | CRSF_FRAMETYPE_DEVICE_PING = 0x28, 44 | CRSF_FRAMETYPE_DEVICE_INFO = 0x29, 45 | CRSF_FRAMETYPE_PARAMETER_SETTINGS_ENTRY = 0x2B, 46 | CRSF_FRAMETYPE_PARAMETER_READ = 0x2C, 47 | CRSF_FRAMETYPE_PARAMETER_WRITE = 0x2D, 48 | 49 | //CRSF_FRAMETYPE_ELRS_STATUS = 0x2E, ELRS good/bad packet count and status flags 50 | 51 | CRSF_FRAMETYPE_COMMAND = 0x32, 52 | // KISS frames 53 | CRSF_FRAMETYPE_KISS_REQ = 0x78, 54 | CRSF_FRAMETYPE_KISS_RESP = 0x79, 55 | // MSP commands 56 | CRSF_FRAMETYPE_MSP_REQ = 0x7A, // response request using msp sequence as command 57 | CRSF_FRAMETYPE_MSP_RESP = 0x7B, // reply with 58 byte chunked binary 58 | CRSF_FRAMETYPE_MSP_WRITE = 0x7C, // write with 8 byte chunked binary (OpenTX outbound telemetry buffer limit) 59 | // Ardupilot frames 60 | CRSF_FRAMETYPE_ARDUPILOT_RESP = 0x80, 61 | } crsf_frame_type_e; 62 | 63 | 64 | #define CRSF_FRAME_RC_PAYLOAD_SIZE 22 65 | #define CRSF_FRAME_GPS_PAYLOAD_SIZE 15 66 | #define CRSF_FRAME_VARIO_PAYLOAD_SIZE 2 67 | #define CRSF_FRAME_BATTERY_SENSOR_PAYLOAD_SIZE 8 68 | #define CRSF_FRAME_ATTITUDE_PAYLOAD_SIZE 6 69 | #define CRSF_FRAME_FLIGHT_MODE_PAYLOAD_SIZE 8 // to change? 70 | #define CRSF_FRAME_LINK_STATISTICS_PAYLOAD_SIZE 10 71 | #define CRSF_FRAME_OPENTX_SYNC_PAYLOAD_SIZE 11 // 72 | 73 | #define CRSF_ADDRESS_TLM 0xEA // this value has been seen using the logic analyser = radio transmitter 74 | 75 | // telemetry synchronisation sent from ELRS to the radio transmitter contains 76 | // EA 0D 3A EA ?? 10 xx xx xx xx yy yy yy yy cc ; xx = 32 bits for rate us*10 ; yy idem but offset 77 | 78 | 79 | enum CRSF_MODE { 80 | RECEIVING = 0, 81 | SENDING 82 | }; 83 | 84 | typedef enum 85 | { 86 | CRSF_FRAMEIDX_GPS = 0x00, 87 | CRSF_FRAMEIDX_VARIO = 0x01, 88 | CRSF_FRAMEIDX_BATTERY_SENSOR = 0x02, 89 | CRSF_FRAMEIDX_ATTITUDE = 0x03, 90 | CRSF_FRAMEIDX_FLIGHT_MODE = 0x04, 91 | } crsf_frame_idx_e; 92 | 93 | typedef enum { 94 | CRSF_TLM_NOT_RECEIVING = 0x00, 95 | CRSF_TLM_RECEIVING_SIZE , 96 | CRSF_TLM_RECEIVING_TYPE , 97 | CRSF_TLM_RECEIVING_PAYLOAD , 98 | CRSF_TLM_RECEIVING_CRC, 99 | } crsf_tlm_state; 100 | 101 | struct gpsFrameStruct 102 | { 103 | uint8_t device_addr; // should be 0xEC (=receiver) 104 | uint8_t frame_size; // counts size after this byte, so it must be the payload size + 2 (type and crc) 105 | uint8_t type; // from crsf_frame_type_e 106 | int32_t latitude; //( degree / 10`000`000 ) 107 | int32_t longitude; // (degree / 10`000`000 ) 108 | uint16_t groundspeed; // ( km/h / 10 ) 109 | uint16_t heading; //( degree / 100 ) 110 | uint16_t altitude; //( meter ­1000m offset ) 111 | uint8_t numSat; //( counter ) 112 | uint8_t crc; 113 | } __attribute__((packed)) ; 114 | 115 | struct voltageFrameStruct 116 | { 117 | uint8_t device_addr; // should be 0xEC (=receiver) 118 | uint8_t frame_size; // counts size after this byte, so it must be the payload size + 2 (type and crc) 119 | uint8_t type; // from crsf_frame_type_e 120 | uint16_t mVolt ; 121 | uint16_t current ; 122 | uint32_t capacity : 24; // there is only one uint32 (splitted in 24 and 8) 123 | uint32_t remain : 8 ; 124 | uint8_t crc; 125 | } __attribute__((packed)) ; 126 | 127 | struct varioFrameStruct 128 | { 129 | uint8_t device_addr; // should be 0xEC (=receiver) 130 | uint8_t frame_size; // counts size after this byte, so it must be the payload size + 2 (type and crc) 131 | uint8_t type; // from crsf_frame_type_e 132 | int16_t vSpeed ; // in 0.1 m/sec 133 | uint8_t crc; 134 | } __attribute__((packed)) ; 135 | 136 | 137 | struct attitudeFrameStruct 138 | { 139 | uint8_t device_addr; // should be 0xEC (=receiver) 140 | uint8_t frame_size; // counts size after this byte, so it must be the payload size + 2 (type and crc) 141 | uint8_t type; // from crsf_frame_type_e 142 | int16_t pitch; //( rad/1000 ) 143 | int16_t roll; // (rad / 1000 ) 144 | int16_t yaw; // ( rad / 1000 ) 145 | uint8_t crc; 146 | } __attribute__((packed)) ; 147 | 148 | struct opentxSyncFrameStruct 149 | { 150 | uint8_t device_addr; // should be 0xEA (=receiver) 151 | uint8_t frame_size; // = 0x0D 152 | uint8_t type; // = 0x3A 153 | uint8_t dest_addr; // = 0xEA 154 | uint8_t orig_addr; // = ?? 155 | uint8_t synchrType; // = 0x10 156 | int32_t rate; // rate in 1/10 of usec 157 | int32_t offset; // offset in 1/10 of usec 158 | uint8_t crc; 159 | } __attribute__((packed)) ; 160 | 161 | 162 | /* 163 | * 0x14 Link statistics 164 | * Payload: 165 | * 166 | * uint8_t Uplink RSSI Ant. 1 ( dBm * -1 ) 167 | * uint8_t Uplink RSSI Ant. 2 ( dBm * -1 ) 168 | * uint8_t Uplink Package success rate / Link quality ( % ) 169 | * int8_t Uplink SNR ( db ) 170 | * uint8_t Diversity active antenna ( enum ant. 1 = 0, ant. 2 ) 171 | * uint8_t RF Mode ( enum 4fps = 0 , 50fps, 150hz) 172 | * uint8_t Uplink TX Power ( enum 0mW = 0, 10mW, 25 mW, 100 mW, 500 mW, 1000 mW, 2000mW ) 173 | * uint8_t Downlink RSSI ( dBm * -1 ) 174 | * uint8_t Downlink package success rate / Link quality ( % ) 175 | * int8_t Downlink SNR ( db ) 176 | * Uplink is the connection from the ground to the UAV and downlink the opposite direction. 177 | */ 178 | 179 | struct linkstatisticsFrameStruct 180 | { 181 | uint8_t device_addr; // should be 0xEC (=receiver) 182 | uint8_t frame_size; // counts size after this byte, so it must be the payload size + 2 (type and crc) 183 | uint8_t type; // from crsf_frame_type_e 184 | uint8_t uplink_RSSI_1; 185 | uint8_t uplink_RSSI_2; 186 | uint8_t uplink_Link_quality; 187 | int8_t uplink_SNR; 188 | uint8_t active_antenna; 189 | uint8_t rf_Mode; 190 | uint8_t uplink_TX_Power; 191 | uint8_t downlink_RSSI; 192 | uint8_t downlink_Link_quality; 193 | int8_t downlink_SNR; 194 | uint8_t crc; 195 | }__attribute__((packed)) ; 196 | 197 | 198 | union { 199 | gpsFrameStruct gpsFrame; 200 | voltageFrameStruct voltageFrame; 201 | varioFrameStruct varioFrame; 202 | attitudeFrameStruct attitudeFrame; 203 | linkstatisticsFrameStruct linkstatisticsFrame; 204 | opentxSyncFrameStruct opentxSyncFrame; 205 | uint8_t tlmBuffer[50]; 206 | } tlmFrame ; 207 | 208 | struct rcFrameStruct 209 | { 210 | uint8_t device_addr; // should be 0xEC (=receiver) 211 | uint8_t frame_size; // counts size after this byte, so it must be the payload size + 2 (type and crc) 212 | uint8_t type; // from crsf_frame_type_e 213 | uint8_t rcChannels[22]; // 16 channels * 11 bits = 176 bits = 214 | uint8_t crc; 215 | } __attribute__((packed)) ; 216 | 217 | //void setup_DMA_PIO(); 218 | void setupCRSF(); 219 | void sendCrsfRcFrame(); 220 | void handleTlmIn(); 221 | void storeTlmFrame(); 222 | void crsfPioRxHandlerIrq(); 223 | //void processCrsfRxQueue(); 224 | //void fillCrsfBufferWithRcChannels(); 225 | void fillCrsfTxBuffer(uint8_t c); 226 | void fillCrsfTxBuffer(uint8_t * bufferFrom , uint8_t length); 227 | void createRcChannelsFrame(); 228 | void createRadioModelIdFrame(); 229 | 230 | void crsfPioTxEmptyHandlerIrq(); 231 | void clearCrsfRxQueue(); 232 | 233 | 234 | -------------------------------------------------------------------------------- /src/crsf_1pin.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | /* 18 | //#include 19 | #include "hardware/pio.h" 20 | #include "hardware/dma.h" 21 | //#include "hardware/irq.h" 22 | //#include "uart_tx.pio.h" 23 | #include "pico/util/queue.h" 24 | #include "crsf_uart_tx_rx.pio.h" 25 | #include "crsf.h" 26 | #include "config_basic.h" 27 | #include "crc.h" 28 | #include "sport.h" 29 | #include "stdio.h" // used by printf 30 | #include "tools.h" 31 | 32 | //#define DEBUG_WITH_FIXED_RC_FRAME 33 | //#define DEBUG_RECEIVED_FRAME // print the content of valid received frames 34 | 35 | 36 | 37 | #define CRSF_PIO_PIN 7 // pin being used by the UART pio for ELRS 38 | 39 | // When we look at the data exchanged with openTX with a logic analyser, it seems that: 40 | // openTX send a frame with Rc channel once every 4msec (24 bytes at 400000 bauds = 24*25micro sec) 41 | // the eLRS module sent some frame back about 40/45 usec later with an adress = EA 42 | // When the RX has no telemetry, there are at least 2 types of frame to openTx 43 | // one has a length = 0X0D and a type = 3A; it is sent every 0.2msec 44 | // the other has a length = 0X0C and a type = 0C (= link statistic); it is sent once every 0.32 sec 45 | // I expect that there are some others type (gps, vario, ...) 46 | // Still at least when ELRS TX was configured with 500 frames/sec, the connection occurs only when the frames where generates every 2msec instead of 4msec 47 | // Probably this is related to the frame rate selected in ELRS TX 48 | 49 | queue_t crsfRxQueue ; // queue to get the telemetry data from crsf (from an irq handler) 50 | 51 | 52 | //// This is the same as the default UART baud rate on Pico 53 | const uint32_t CRSF_SERIAL_BAUD = 400000; 54 | 55 | // one pio with 2 state machine is used to manage the inverted hal duplex uart for crsf 56 | PIO crsfPio = pio1; 57 | uint crsfSmRx = 1; // to get the telemetry from crsf 58 | uint crsfSmTx = 0; // to send the channels to crsf 59 | uint crsfOffsetTx ; 60 | uint crsfOffsetRx ; 61 | 62 | // dma channel is used to send Sport telemetry without blocking 63 | int crsf_dma_chan; 64 | dma_channel_config crsfDmaConfig; 65 | 66 | uint8_t crsfTxBuffer[50]; // buffer to be used by dma to send the RC channels 67 | uint8_t crsfTxBufferLength; 68 | 69 | 70 | uint32_t restoreCrsfPioToReceiveMillis = 0; // when 0, the pio is normally in receive mode, 71 | // otherwise, it is the timestamp when pio transmit has to be restore to receive mode 72 | 73 | //#define CRSF_RC_FRAME_INTERVAL 4 // msec replaced by an interval in micro sec 74 | #define CRSF_RC_FRAME_INTERVAL_MICROS 4000 // microsec 75 | #define CRSF_IRQ_TXFIFO_EMPTY PIO1_IRQ_1 // irq when txfifo is empty 76 | #define CRSF_IRQ_RX_RECEIVED PIO1_IRQ_0 // irq when a byte is received 77 | 78 | 79 | volatile CRSF_MODE crsfMode = RECEIVING; 80 | 81 | crsf_tlm_state tlmState; // store the state of handling receiving tlm bytes 82 | 83 | #define FRAME_TYPES_MAX 5 84 | uint32_t crsfFrameNextMillis[FRAME_TYPES_MAX] = {0} ; 85 | uint8_t crsf_last_frame_idx = 0 ; 86 | 87 | voltageFrameStruct voltageFrame; 88 | varioFrameStruct varioFrame; 89 | attitudeFrameStruct attitudeFrame; 90 | gpsFrameStruct gpsFrame; 91 | 92 | //uint8_t CRSFTlmFrame[50]; 93 | //uint8_t CRSFTlmFrameLength; 94 | 95 | rcFrameStruct crsfRcFrame ; 96 | bool crsfRcFrameReady = false; 97 | 98 | GENERIC_CRC8 crsf_crc(CRSF_CRC_POLY); 99 | 100 | #define TEST_PIN 3 101 | 102 | void setupCRSF(){ 103 | //Serial1.begin(SERIAL_BAUD_CRSF); 104 | // configure the queue to get the telemetry data from crsf in the irq handle 105 | queue_init (&crsfRxQueue, sizeof(uint8_t), 250); 106 | 107 | // set up the DMA but do not yet start it to send rc data to crsf 108 | // Configure a channel to write the same byte (8 bits) repeatedly to PIO1 109 | // SM0's TX FIFO, paced by the data request signal from that peripheral. 110 | crsf_dma_chan = dma_claim_unused_channel(true); 111 | crsfDmaConfig = dma_channel_get_default_config(crsf_dma_chan); 112 | channel_config_set_read_increment(&crsfDmaConfig, true); 113 | channel_config_set_write_increment(&crsfDmaConfig, false); 114 | channel_config_set_dreq(&crsfDmaConfig, DREQ_PIO1_TX0); // use state machine 0 on PIO1 115 | channel_config_set_transfer_data_size(&crsfDmaConfig, DMA_SIZE_8); 116 | dma_channel_configure( 117 | crsf_dma_chan, 118 | &crsfDmaConfig, 119 | &pio1_hw->txf[0], // Write address (only need to set this once) 120 | &crsfTxBuffer[0], // we use always the same buffer 121 | 0 , // do not yet provide the number of bytes (DMA cycles) 122 | false // Don't start yet 123 | ); 124 | // Set up the state machine for transmit but do not yet start it 125 | crsfOffsetTx = pio_add_program(crsfPio, &crsf_uart_tx_program); 126 | crsf_uart_tx_program_init(crsfPio, crsfSmTx, crsfOffsetTx, CRSF_PIO_PIN, CRSF_SERIAL_BAUD , true); // we use the same pin and baud rate for tx and rx, true means that UART is inverted 127 | 128 | // Set up an irq on pio to handle when Tx fifo is empty. We use PIO1_IRQ_1 for this 129 | //irq_set_exclusive_handler( CRSF_IRQ_TXFIFO_EMPTY , crsfPioTxEmptyHandlerIrq) ; 130 | //irq_set_enabled (CRSF_IRQ_TXFIFO_EMPTY , false) ; 131 | 132 | // set an irq on pio to handle a received byte 133 | irq_set_exclusive_handler( CRSF_IRQ_RX_RECEIVED , crsfPioRxHandlerIrq) ; 134 | irq_set_enabled (CRSF_IRQ_RX_RECEIVED , false) ; 135 | 136 | // Set up the state machine we're going to use to receive them. 137 | crsfOffsetRx = pio_add_program(crsfPio, &crsf_uart_rx_program); 138 | crsf_uart_rx_program_init(crsfPio, crsfSmRx, crsfOffsetRx, CRSF_PIO_PIN, CRSF_SERIAL_BAUD , true); 139 | } 140 | 141 | void crsfPioRxHandlerIrq(){ // when a byte is received on the CRSF, read the pio CRSF fifo and push the data to a queue (to be processed in the main loop) 142 | irq_clear (CRSF_IRQ_RX_RECEIVED ); // clear the irq flag 143 | while ( ! pio_sm_is_rx_fifo_empty (crsfPio ,crsfSmRx)){ // when some data have been received 144 | uint8_t c = pio_sm_get (crsfPio , crsfSmRx) >> 24; // read the data 145 | queue_try_add (&crsfRxQueue, &c); // push to the queue 146 | 147 | //sportRxMillis = millis(); // save the timestamp. 148 | } 149 | } 150 | 151 | // when crsf state machine fires the IRQ because TXFIFO is empty 152 | // - clear the IRQ flag for TXFIFO and disabled it 153 | // - clear the IRQ flag for receiving 154 | // _ clear the Rx queue 155 | // - enable the receiving IRQ 156 | // - switch PIO receiving mode 157 | // - set state to receiving mode 158 | //*void crsfPioTxEmptyHandlerIrq(){ 159 | // //printf("in irq\n"); 160 | // pio_interrupt_clear(crsfPio, 0); // clear the irq flag in the pio that was set when Txfifo is empty 161 | // irq_set_enabled (CRSF_IRQ_TXFIFO_EMPTY , false) ; // disable the IRQ to handle when TXFIFO is empty 162 | // irq_clear (CRSF_IRQ_TXFIFO_EMPTY ); // clear the irq flag in NVIC 163 | // irq_clear (CRSF_IRQ_RX_RECEIVED ); // clear the irq flag for receiving 164 | // clearCrsfRxQueue(); // clear the queue and reset the process state 165 | // irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 166 | // crsf_uart_tx_program_stop(crsfPio ,crsfSmTx , CRSF_PIO_PIN); 167 | // crsf_uart_rx_program_restart(crsfPio ,crsfSmTx , CRSF_PIO_PIN , true); // false = no invert 168 | // crsfMode = RECEIVING ; 169 | //} 170 | 171 | int64_t alarm_callback_switchToReceiveMode(alarm_id_t id, void *user_data) { 172 | irq_clear (CRSF_IRQ_RX_RECEIVED ); // clear the irq flag for receiving 173 | clearCrsfRxQueue(); // clear the queue and reset the process state 174 | //irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 175 | crsf_uart_tx_program_stop(crsfPio ,crsfSmTx , CRSF_PIO_PIN); 176 | crsf_uart_rx_program_restart(crsfPio ,crsfSmRx , CRSF_PIO_PIN , true); // true = invert 177 | irq_set_enabled (CRSF_IRQ_RX_RECEIVED , true) ; // enable the IRQ to handle the received charaters 178 | 179 | crsfMode = RECEIVING ; 180 | return 0; // return 0 to avoid that the callback is called automatically in the future; we use a new add at each time. 181 | } 182 | 183 | 184 | //#ifdef DEBUG_WITH_FIXED_RC_FRAME 185 | uint8_t testBuffer[]={ 0xEE , 0x18, 0x16, 0xF2, 0x83, 0x1E, 0xFC, 0x00, 0x08, 0x3E , 0XF0, 0X81, 186 | 0X0F, 0x7C , 0xE0, 0x03, 0x1F, 0XF8, 0xC0, 0x07, 0x3E, 0XF0, 0X81, 0x0F, 0x7C, 0X63}; 187 | uint8_t testBufferLength = 0x1A; 188 | //#endif 189 | 190 | #define MODULE_ADDRESS 0xEE 191 | 192 | void sendCrsfRcFrame(void){ // called by main loop : 193 | // when crsf state is receiving mode , if last transmit is more than x msec and if Rc channels are available, 194 | // - process once more the Rx queue 195 | // - clear the Rx queue from crsf (just to be sure because all bytes should have been processed) 196 | // - fill the TX buffer with RC channels , 197 | // - switch the pio to transmit mode, 198 | // - start the dma to send the RC channel 199 | // - set state to transmit and save the timestamp. 200 | // - clear the irq on PIO1_IRQ1 and enable it (it is fired by the PIO when txfifo becomes emtpty) 201 | // when crsf state machine fires the IRQ because TXFIFO is empty, it call crsfPioTxEmptyHandlerIrq() 202 | // - clear the IRQ flag for TXFIFO and disabled it 203 | // - clear the IRQ flag for receiving 204 | // _ clear the Rx queue 205 | // - enable the receiving IRQ 206 | // - switch PIO receiving mode 207 | // - set state to receiving mode 208 | // when a character is received in PIO, it fires an irq that is handled in crsfPioRxHandlerIrq() 209 | // - the irq push the data to a queue 210 | // The main loop read the queue and process the received data in handleTlmIn() 211 | static uint32_t lastRcFrameSendMillis = 0; 212 | static uint32_t lastRcFrameSendMicros = 0; 213 | ////if ( (crsfMode == RECEIVING) && ( (millis() - lastRcFrameSendMillis ) > CRSF_RC_FRAME_INTERVAL ) && ( crsfRcFrameReady) ) { 214 | //if ( ( (millis() - lastRcFrameSendMillis ) >= CRSF_RC_FRAME_INTERVAL ) && ( crsfRcFrameReady) ) { 215 | //if ( ( (millis() - lastRcFrameSendMillis ) >= CRSF_RC_FRAME_INTERVAL ) ) { 216 | if ( ( (micros() - lastRcFrameSendMicros ) >= CRSF_RC_FRAME_INTERVAL_MICROS ) ) { 217 | 218 | //if (crsfMode == RECEIVING ) printf("receiving\n"); 219 | handleTlmIn(); // try to process one more time just to be sure 220 | clearCrsfRxQueue(); // clear the receiving queue 221 | crsfTxBufferLength = 0; 222 | fillCrsfTxBuffer(MODULE_ADDRESS); 223 | fillCrsfTxBuffer(CRSF_FRAME_RC_PAYLOAD_SIZE + 2); 224 | fillCrsfTxBuffer(CRSF_FRAMETYPE_RC_CHANNELS); 225 | #ifdef DEBUG_WITH_FIXED_RC_FRAME 226 | fillCrsfTxBuffer( &testBuffer[3] , CRSF_FRAME_RC_PAYLOAD_SIZE ); // payload size include type and CRC 227 | #else 228 | fillCrsfTxBuffer( ( (uint8_t *) &crsfRcFrame) + 3 , CRSF_FRAME_RC_PAYLOAD_SIZE ); 229 | #endif 230 | fillCrsfTxBuffer(crsf_crc.calc(&crsfTxBuffer[2], CRSF_FRAME_RC_PAYLOAD_SIZE + 1)); // crc includes frame type and so is 1 byte more than the payload 231 | //float rc1 = (crsfTxBuffer[3] | (crsfTxBuffer[4] <<8 )) & 0x7FF; 232 | //printf("rc1 = %f\n", rc1/2); 233 | //printHexBuffer( &crsfTxBuffer[0] , crsfTxBufferLength); 234 | crsf_uart_rx_program_stop(crsfPio, crsfSmRx, CRSF_PIO_PIN); 235 | crsf_uart_tx_program_start(crsfPio, crsfSmTx, CRSF_PIO_PIN , true ); // true because we invert the UART signal 236 | dma_channel_set_read_addr (crsf_dma_chan, &crsfTxBuffer[0], false); 237 | dma_channel_set_trans_count (crsf_dma_chan, crsfTxBufferLength, true) ; // start the dma 238 | add_alarm_in_us( (crsfTxBufferLength *24)+40 , alarm_callback_switchToReceiveMode , NULL , false); // 400000 baud = 2.5 usec/bit = 25 usec/byte 239 | crsfMode = SENDING ; 240 | lastRcFrameSendMillis = millis(); 241 | lastRcFrameSendMicros = micros(); 242 | //irq_clear (CRSF_IRQ_TXFIFO_EMPTY ); // clear the irq flag for TX 243 | //irq_set_enabled (CRSF_IRQ_TXFIFO_EMPTY , true) ; // enable the IRQ to handle when TXFIFO is empty 244 | } 245 | } 246 | 247 | 248 | void clearCrsfRxQueue(){ 249 | uint8_t data; 250 | while ( !queue_is_empty(&crsfRxQueue)) queue_try_remove (&crsfRxQueue, &data); // clear the queue 251 | tlmState = CRSF_TLM_NOT_RECEIVING; // reset the state of processing data 252 | } 253 | 254 | 255 | void fillCrsfTxBuffer(uint8_t c){ 256 | crsfTxBuffer[crsfTxBufferLength++] = c; 257 | } 258 | 259 | void fillCrsfTxBuffer(uint8_t * bufferFrom , uint8_t length){ 260 | uint8_t count = 0; 261 | while (count < length){ 262 | crsfTxBuffer[crsfTxBufferLength] = bufferFrom[count++]; 263 | crsfTxBufferLength++; 264 | } 265 | } 266 | 267 | 268 | //void sendCRSFRcFrame(){ 269 | // static uint32_t lastRcFrameSendMillis ; 270 | // if ( ( (millis() - lastRcFrameSendMillis ) > CRSF_RC_FRAME_INTERVAL ) && ( CRSFRcFrameReady) ) { 271 | // //Serial1.write(MODULE_ADDRESS); 272 | // //Serial1.write(CRSF_FRAME_RC_PAYLOAD_SIZE + 2); 273 | // //Serial1.write(CRSF_FRAMETYPE_RC_CHANNELS); 274 | // //Serial1.write(& CRSFRcFrame[3], CRSF_FRAME_RC_PAYLOAD_SIZE); 275 | // //Serial1.write(crsf_crc.calc(&CRSFRcFrame[2], 22)); 276 | // crsfTxBufferLength = 0; 277 | // fillCrsfBuffer(MODULE_ADDRESS); 278 | // fillCrsfBuffer(CRSF_FRAME_RC_PAYLOAD_SIZE + 2); 279 | // fillCrsfBuffer(CRSF_FRAMETYPE_RC_CHANNELS); 280 | // fillCrsfBuffer(&CRSFRcFrame[3], CRSF_FRAME_RC_PAYLOAD_SIZE); 281 | // fillCrsfBuffer(crsf_crc.calc(&crsfTXBuffer[2], 22)); 282 | // } 283 | //} 284 | 285 | 286 | // read the rx queue and process each byte (= tlm data) 287 | // when a frame has been totally received, check it, and store the tlm data in separated fields (to be sent later by sport process) 288 | void handleTlmIn(){ 289 | //static uint8_t tlmBuffer[50]; 290 | static uint8_t tlmCounter; 291 | static uint8_t tlmLength ; // Length in the second byte of the message (is equal to the payload+2 because type and crc are included) 292 | static uint8_t tlmType; 293 | uint8_t c; 294 | while(! queue_is_empty(&crsfRxQueue)) { 295 | queue_try_remove (&crsfRxQueue,&c); 296 | switch (tlmState) { 297 | case CRSF_TLM_NOT_RECEIVING : 298 | if (c == CRSF_ADDRESS_TLM) { 299 | tlmCounter=0; 300 | tlmFrame.tlmBuffer[tlmCounter++] = c; 301 | tlmState = CRSF_TLM_RECEIVING_SIZE; 302 | } 303 | break; 304 | case CRSF_TLM_RECEIVING_SIZE : 305 | tlmFrame.tlmBuffer[tlmCounter++] = c; 306 | tlmLength = c; 307 | tlmState = CRSF_TLM_RECEIVING_TYPE; 308 | break; 309 | case CRSF_TLM_RECEIVING_TYPE : 310 | if ( ( ( c == CRSF_FRAMETYPE_GPS) && (tlmLength == (CRSF_FRAME_GPS_PAYLOAD_SIZE+2) ) ) 311 | || ( ( c == CRSF_FRAMETYPE_VARIO) && (tlmLength == (CRSF_FRAME_VARIO_PAYLOAD_SIZE+2) ) ) 312 | || ( ( c == CRSF_FRAMETYPE_BATTERY_SENSOR) && (tlmLength == (CRSF_FRAME_BATTERY_SENSOR_PAYLOAD_SIZE+2) ) ) 313 | || ( ( c == CRSF_FRAMETYPE_ATTITUDE) && (tlmLength == (CRSF_FRAME_ATTITUDE_PAYLOAD_SIZE+2) ) ) 314 | || ( ( c == CRSF_FRAMETYPE_LINK_STATISTICS) && (tlmLength == (CRSF_FRAME_LINK_STATISTICS_PAYLOAD_SIZE+2) ) ) ){ 315 | 316 | tlmType = c; 317 | tlmState = CRSF_TLM_RECEIVING_PAYLOAD; 318 | tlmFrame.tlmBuffer[tlmCounter++] = c; 319 | } else { 320 | tlmState = CRSF_TLM_NOT_RECEIVING; 321 | } 322 | break; 323 | case CRSF_TLM_RECEIVING_PAYLOAD : 324 | tlmFrame.tlmBuffer[tlmCounter++] = c; 325 | if (tlmCounter > tlmLength ) { // e.g. if tlmLength = 3, CRC is at idx 4 (because there is an adress in pos 0) 326 | tlmState = CRSF_TLM_RECEIVING_CRC; 327 | } 328 | break; 329 | case CRSF_TLM_RECEIVING_CRC : 330 | if ( c != crsf_crc.calc(&tlmFrame.tlmBuffer[2], tlmLength - 1)) { 331 | tlmState = CRSF_TLM_NOT_RECEIVING; 332 | } else { // we received a full telemetry packet; we can save it. 333 | storeTlmFrame(); 334 | //printf("frame received\n"); 335 | } 336 | break; 337 | 338 | } 339 | } 340 | } 341 | 342 | extern field fields[SPORT_TYPES_MAX]; 343 | 344 | void storeTlmFrame(){ 345 | #ifdef DEBUG_RECEIVED_FRAME 346 | for (uint8_t i = 0 ; i<(tlmFrame.tlmBuffer[1] +1); i++){ 347 | printf(" %X ",tlmFrame.tlmBuffer[i] ); 348 | } 349 | printf("\n"); 350 | #endif 351 | int32_t temp; 352 | switch (tlmFrame.tlmBuffer[2]) { // byte 2 = type 353 | case CRSF_FRAMETYPE_GPS: 354 | temp = tlmFrame.gpsFrame.longitude; // degree with 7 decimals 355 | fields[LONGITUDE].value = (( ((((uint32_t)( temp < 0 ? -temp : temp)) /10 ) * 6 ) / 10 ) & 0x3FFFFFFF) | 0x80000000; 356 | if(temp < 0) fields[LONGITUDE].value |= 0x40000000; 357 | fields[LONGITUDE].available = true ; 358 | temp = tlmFrame.gpsFrame.latitude; 359 | fields[LATITUDE].value = (( ((((uint32_t)( temp < 0 ? -temp : temp)) /10 ) * 6 ) / 10 ) & 0x3FFFFFFF) ; 360 | if(temp < 0) fields[LATITUDE].value |= 0x40000000; 361 | fields[LATITUDE].available = true ; 362 | fields[GROUNDSPEED].value = tlmFrame.gpsFrame.groundspeed; //( km/h / 10 ) 363 | fields[GROUNDSPEED].available = true; 364 | fields[HEADING].value = tlmFrame.gpsFrame.heading; //( degree / 100 ) 365 | fields[HEADING].available = true; 366 | fields[ALTITUDE].value = tlmFrame.gpsFrame.altitude; 367 | fields[ALTITUDE].available = true; 368 | fields[NUMSAT].value = tlmFrame.gpsFrame.numSat; 369 | fields[NUMSAT].available = true; 370 | break; 371 | case CRSF_FRAMETYPE_VARIO: 372 | fields[VSPEED].value = tlmFrame.varioFrame.vSpeed; 373 | fields[VSPEED].available = true; 374 | break; 375 | case CRSF_FRAMETYPE_BATTERY_SENSOR: 376 | fields[MVOLT].value = tlmFrame.voltageFrame.mVolt; 377 | fields[MVOLT].available = true; 378 | fields[CURRENT].value = tlmFrame.voltageFrame.current; 379 | fields[CURRENT].available = true; 380 | fields[CAPACITY].value = tlmFrame.voltageFrame.capacity; 381 | fields[CAPACITY].available = true; 382 | fields[REMAIN].value = tlmFrame.voltageFrame.remain; 383 | fields[REMAIN].available = true; 384 | break; 385 | case CRSF_FRAMETYPE_ATTITUDE: 386 | fields[PITCH].value = tlmFrame.attitudeFrame.pitch; 387 | fields[PITCH].available = true; 388 | fields[ROLL].value = tlmFrame.attitudeFrame.roll; 389 | fields[ROLL].available = true; 390 | fields[YAW].value = tlmFrame.attitudeFrame.yaw; 391 | fields[YAW].available = true; 392 | break; 393 | case CRSF_FRAMETYPE_LINK_STATISTICS: 394 | fields[UPLINK_RSSI_1].value = tlmFrame.linkstatisticsFrame.uplink_RSSI_1; 395 | fields[UPLINK_RSSI_1].available = true; 396 | fields[UPLINK_RSSI_2].value = tlmFrame.linkstatisticsFrame.uplink_RSSI_2; 397 | fields[UPLINK_RSSI_2].available = true; 398 | fields[UPLINK_LINK_QUALITY].value = tlmFrame.linkstatisticsFrame.uplink_Link_quality; 399 | fields[UPLINK_LINK_QUALITY].available = true; 400 | fields[UPLINK_SNR].value = tlmFrame.linkstatisticsFrame.uplink_SNR; 401 | fields[UPLINK_SNR].available = true; 402 | fields[ACTIVE_ANTENNA].value = tlmFrame.linkstatisticsFrame.active_antenna; 403 | fields[ACTIVE_ANTENNA].available = true; 404 | fields[RF_MODE].value = tlmFrame.linkstatisticsFrame.rf_Mode; 405 | fields[RF_MODE].available = true; 406 | fields[UPLINK_TX_POWER].value = tlmFrame.linkstatisticsFrame.uplink_TX_Power; 407 | fields[UPLINK_TX_POWER].available = true; 408 | fields[DOWNLINK_RSSI].value = tlmFrame.linkstatisticsFrame.downlink_RSSI; 409 | fields[DOWNLINK_RSSI].available = true; 410 | fields[DOWNLINK_LINK_QUALITY].value = tlmFrame.linkstatisticsFrame.downlink_Link_quality; 411 | fields[DOWNLINK_LINK_QUALITY].available = true; 412 | fields[DOWNLINK_SNR].value = tlmFrame.linkstatisticsFrame.downlink_SNR; 413 | fields[DOWNLINK_SNR].available = true; 414 | //printf(" Rf mode %x", tlmFrame.linkstatisticsFrame.rf_Mode); 415 | break; 416 | } 417 | } 418 | 419 | */ -------------------------------------------------------------------------------- /src/crsf_uart_tx_rx.pio: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | .program crsf_uart_tx 18 | .side_set 1 opt 19 | 20 | ; An 8n1 UART transmit program. 21 | ; OUT pin 0 and side-set pin 0 are both mapped to UART TX pin. 22 | 23 | pull side 1 [7] ; Assert stop bit, or stall with line in idle state 24 | set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks 25 | bitloop: ; This loop will run 8 times (8n1 UART) 26 | out pins, 1 ; Shift 1 bit from OSR to the first OUT pin 27 | jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. 28 | 29 | 30 | 31 | 32 | 33 | ; pull side 1 [7] ; Assert stop bit, or stall with line in idle state 34 | ; set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks 35 | ;bitloop: ; This loop will run 8 times (8n1 UART) 36 | ; out pins, 1 ; Shift 1 bit from OSR to the first OUT pin 37 | ; jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. 38 | ; set x , 7 side 1 ; preload bit counter 39 | ; mov y , !STATUS [4] ; Assert stop bit and y becomes all 1 when TX fifo is less than 0 (value defined in setup) 40 | ; jmp !y setirq ; When fifo is empty do a special process (irq) 41 | ; pull [2] ; get next byte from fifo 42 | ; jmp bitloop side 0 [7] ; assert start bit for 8 clocks 43 | ;setirq: 44 | ; irq 0 ; when fifo is empty, fire an irq 45 | 46 | % c-sdk { 47 | #include "hardware/clocks.h" 48 | #include "stdio.h" // used by printf 49 | 50 | #define DEBUG_TIMING_CRSF // let check when pio switch from receiving to sending mode. 51 | #define TEST_PIN 3 52 | 53 | // here the code from elrs for Tx 54 | static inline void crsf_uart_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud, bool invert) { 55 | // Tell PIO to initially drive output-high on the selected pin, then map PIO 56 | // onto that pin with the IO muxes. 57 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 58 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 59 | pio_gpio_init(pio, pin_tx); 60 | if ( invert ) { 61 | gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from 62 | gpio_pull_down(pin_tx); // changed by MS 63 | } else { 64 | gpio_pull_up(pin_tx); // changed by MS 65 | } 66 | pio_sm_config c = crsf_uart_tx_program_get_default_config(offset); 67 | 68 | // OUT shifts to right, no autopull 69 | sm_config_set_out_shift(&c, true, false, 32); 70 | 71 | // We are mapping both OUT and side-set to the same pin, because sometimes 72 | // we need to assert user data onto the pin (with OUT) and sometimes 73 | // assert constant values (start/stop bit) 74 | sm_config_set_out_pins(&c, pin_tx, 1); 75 | sm_config_set_sideset_pins(&c, pin_tx); 76 | 77 | // We only need TX, so get an 8-deep FIFO! 78 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); 79 | 80 | // we use a move y , !STATUS instruction to know when the TXFIFO is empty, so we have to set it up in the configured 81 | //sm_config_set_mov_status (&c, STATUS_TX_LESSTHAN , 1 ) ; // when TX fifo is less than 0(n), y will become all-ones, otherwise all-zeroes 82 | 83 | // SM transmits 1 bit per 8 execution cycles. 84 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 85 | sm_config_set_clkdiv(&c, div); 86 | 87 | pio_sm_init(pio, sm, offset, &c); 88 | //pio_set_irq1_source_enabled(pio , pis_interrupt0 , true) ; // enable an interrupt0 on line IRQ1 when pio fire it because fifo is empty 89 | pio_sm_set_enabled(pio, sm, true); 90 | #ifdef DEBUG_TIMING_CRSF 91 | // set test pin to check when pio mode change from sending to receiving 92 | gpio_init(TEST_PIN); 93 | gpio_set_dir(TEST_PIN, GPIO_OUT); // set pin as output 94 | #endif 95 | } 96 | /* 97 | static inline void crsf_uart_tx_program_stop(PIO pio, uint sm, uint pin_tx) { 98 | pio_sm_set_enabled(pio, sm, false); // disabled 99 | pio_sm_set_pindirs_with_mask(pio, sm, 0u , 1u << pin_tx); // put pin Tx as input 100 | // normally other parameters are already configured by init 101 | 102 | } 103 | 104 | 105 | static inline void crsf_uart_tx_program_start(PIO pio, uint sm, uint pin_tx , bool invert ) { 106 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin TX on high level 107 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin Tx as output 108 | if (invert) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 109 | // normally other parameters are already configured by init 110 | pio_sm_restart (pio, sm); // to test if we need an enable after this 111 | pio_sm_set_enabled(pio, sm, true); 112 | #ifdef DEBUG_TIMING_CRSF 113 | gpio_put(TEST_PIN, 1); 114 | #endif 115 | } 116 | */ 117 | 118 | /* 119 | 120 | static inline void uart_tx_program_putc(PIO pio, uint sm, char c) { 121 | pio_sm_put_blocking(pio, sm, (uint32_t)c); 122 | } 123 | 124 | static inline void uart_tx_program_puts(PIO pio, uint sm, const char *s) { 125 | while (*s) 126 | uart_tx_program_putc(pio, sm, *s++); 127 | } 128 | */ 129 | 130 | %} 131 | 132 | 133 | .program crsf_uart_rx 134 | 135 | ; Slightly more fleshed-out 8n1 UART receiver which handles framing errors and 136 | ; break conditions more gracefully. 137 | ; IN pin 0 and JMP pin are both mapped to the GPIO used as UART RX. 138 | 139 | start: 140 | wait 0 pin 0 ; Stall until start bit is asserted 141 | set x, 7 [10] ; Preload bit counter, then delay until halfway through 142 | bitloop: ; the first data bit (12 cycles incl wait, set). 143 | in pins, 1 ; Shift data bit into ISR 144 | jmp x-- bitloop [6] ; Loop 8 times, each loop iteration is 8 cycles 145 | jmp pin good_stop ; Check stop bit (should be high) 146 | 147 | irq 4 rel ; Either a framing error or a break. Set a sticky flag, 148 | wait 1 pin 0 ; and wait for line to return to idle state. 149 | jmp start ; Don't push data if we didn't see good framing. 150 | 151 | good_stop: ; No delay before returning to start; a little slack is 152 | push ; important in case the TX clock is slightly too fast. 153 | 154 | 155 | % c-sdk { 156 | #include "hardware/gpio.h" 157 | #include "hardware/clocks.h" 158 | static inline void crsf_uart_rx_program_init(PIO pio, uint sm, uint offset, uint pin_rx, uint baud , bool invert) { 159 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // was in Tx program but is normally not required for Rx 160 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 161 | //pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, false); // remove by ms 162 | pio_gpio_init(pio, pin_rx); 163 | if (invert) { 164 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 165 | gpio_pull_down(pin_rx); // changed by MS 166 | } else { 167 | gpio_pull_up(pin_rx); // changed by MS 168 | } 169 | pio_sm_config c = crsf_uart_rx_program_get_default_config(offset); 170 | sm_config_set_in_pins(&c, pin_rx); // for WAIT, IN 171 | sm_config_set_jmp_pin(&c, pin_rx); // for JMP 172 | // Shift to right, autopush disabled 173 | sm_config_set_in_shift(&c, true, false, 32); 174 | // Deeper FIFO as we're not doing any TX 175 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 176 | // SM transmits 1 bit per 8 execution cycles. 177 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 178 | sm_config_set_clkdiv(&c, div); 179 | 180 | pio_sm_init(pio, sm, offset, &c); 181 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); // added by ms to get an irq int0 from pio 182 | pio_sm_set_enabled(pio, sm, true); 183 | } 184 | 185 | /* 186 | static inline void crsf_uart_rx_program_stop(PIO pio, uint sm, uint pin_rx) { 187 | pio_sm_set_enabled(pio, sm, false); // disable sm. 188 | } 189 | 190 | static inline void crsf_uart_rx_program_restart(PIO pio, uint sm, uint pin_rx , bool invert) { 191 | pio_sm_set_pindirs_with_mask(pio, sm, 0u , 1u << pin_rx); // set pin as input 192 | if (invert) { 193 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 194 | gpio_pull_down(pin_rx); // changed by MS 195 | } else { 196 | gpio_pull_up(pin_rx); // changed by MS 197 | } 198 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); 199 | pio_sm_restart (pio, sm); // to test if we need an enable after this 200 | pio_sm_set_enabled(pio, sm, true); 201 | #ifdef DEBUG_TIMING_CRSF 202 | gpio_put(TEST_PIN, 0); 203 | #endif 204 | } 205 | */ 206 | /* 207 | static inline char crsf_uart_rx_program_getc(PIO pio, uint sm) { 208 | // 8-bit read from the uppermost byte of the FIFO, as data is left-justified 209 | io_rw_8 *rxfifo_shift = (io_rw_8*)&pio->rxf[sm] + 3; 210 | while (pio_sm_is_rx_fifo_empty(pio, sm)) 211 | tight_loop_contents(); 212 | return (char)*rxfifo_shift; 213 | } 214 | */ 215 | %} 216 | 217 | -------------------------------------------------------------------------------- /src/crsf_uart_tx_rx.pio.h: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------- // 2 | // This file is autogenerated by pioasm; do not edit! // 3 | // -------------------------------------------------- // 4 | 5 | #if !PICO_NO_HARDWARE 6 | #include "hardware/pio.h" 7 | #endif 8 | 9 | // ------------ // 10 | // crsf_uart_tx // 11 | // ------------ // 12 | 13 | #define crsf_uart_tx_wrap_target 0 14 | #define crsf_uart_tx_wrap 3 15 | 16 | static const uint16_t crsf_uart_tx_program_instructions[] = { 17 | // .wrap_target 18 | 0x9fa0, // 0: pull block side 1 [7] 19 | 0xf727, // 1: set x, 7 side 0 [7] 20 | 0x6001, // 2: out pins, 1 21 | 0x0642, // 3: jmp x--, 2 [6] 22 | // .wrap 23 | }; 24 | 25 | #if !PICO_NO_HARDWARE 26 | static const struct pio_program crsf_uart_tx_program = { 27 | .instructions = crsf_uart_tx_program_instructions, 28 | .length = 4, 29 | .origin = -1, 30 | }; 31 | 32 | static inline pio_sm_config crsf_uart_tx_program_get_default_config(uint offset) { 33 | pio_sm_config c = pio_get_default_sm_config(); 34 | sm_config_set_wrap(&c, offset + crsf_uart_tx_wrap_target, offset + crsf_uart_tx_wrap); 35 | sm_config_set_sideset(&c, 2, true, false); 36 | return c; 37 | } 38 | 39 | #include "hardware/clocks.h" 40 | #include "stdio.h" // used by printf 41 | #define DEBUG_TIMING_CRSF // let check when pio switch from receiving to sending mode. 42 | #define TEST_PIN 3 43 | // here the code from elrs for Tx 44 | static inline void crsf_uart_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud, bool invert) { 45 | // Tell PIO to initially drive output-high on the selected pin, then map PIO 46 | // onto that pin with the IO muxes. 47 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 48 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 49 | pio_gpio_init(pio, pin_tx); 50 | if ( invert ) { 51 | gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 52 | gpio_pull_down(pin_tx); // changed by MS 53 | } else { 54 | gpio_pull_up(pin_tx); // changed by MS 55 | } 56 | pio_sm_config c = crsf_uart_tx_program_get_default_config(offset); 57 | // OUT shifts to right, no autopull 58 | sm_config_set_out_shift(&c, true, false, 32); 59 | // We are mapping both OUT and side-set to the same pin, because sometimes 60 | // we need to assert user data onto the pin (with OUT) and sometimes 61 | // assert constant values (start/stop bit) 62 | sm_config_set_out_pins(&c, pin_tx, 1); 63 | sm_config_set_sideset_pins(&c, pin_tx); 64 | // We only need TX, so get an 8-deep FIFO! 65 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); 66 | // we use a move y , !STATUS instruction to know when the TXFIFO is empty, so we have to set it up in the configured 67 | //sm_config_set_mov_status (&c, STATUS_TX_LESSTHAN , 1 ) ; // when TX fifo is less than 0(n), y will become all-ones, otherwise all-zeroes 68 | // SM transmits 1 bit per 8 execution cycles. 69 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 70 | sm_config_set_clkdiv(&c, div); 71 | pio_sm_init(pio, sm, offset, &c); 72 | //pio_set_irq1_source_enabled(pio , pis_interrupt0 , true) ; // enable an interrupt0 on line IRQ1 when pio fire it because fifo is empty 73 | pio_sm_set_enabled(pio, sm, true); 74 | #ifdef DEBUG_TIMING_CRSF 75 | // set test pin to check when pio mode change from sending to receiving 76 | gpio_init(TEST_PIN); 77 | gpio_set_dir(TEST_PIN, GPIO_OUT); // set pin as output 78 | #endif 79 | } 80 | /* 81 | static inline void crsf_uart_tx_program_stop(PIO pio, uint sm, uint pin_tx) { 82 | pio_sm_set_enabled(pio, sm, false); // disabled 83 | pio_sm_set_pindirs_with_mask(pio, sm, 0u , 1u << pin_tx); // put pin Tx as input 84 | // normally other parameters are already configured by init 85 | } 86 | static inline void crsf_uart_tx_program_start(PIO pio, uint sm, uint pin_tx , bool invert ) { 87 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin TX on high level 88 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin Tx as output 89 | if (invert) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 90 | // normally other parameters are already configured by init 91 | pio_sm_restart (pio, sm); // to test if we need an enable after this 92 | pio_sm_set_enabled(pio, sm, true); 93 | #ifdef DEBUG_TIMING_CRSF 94 | gpio_put(TEST_PIN, 1); 95 | #endif 96 | } 97 | */ 98 | /* 99 | static inline void uart_tx_program_putc(PIO pio, uint sm, char c) { 100 | pio_sm_put_blocking(pio, sm, (uint32_t)c); 101 | } 102 | static inline void uart_tx_program_puts(PIO pio, uint sm, const char *s) { 103 | while (*s) 104 | uart_tx_program_putc(pio, sm, *s++); 105 | } 106 | */ 107 | 108 | #endif 109 | 110 | // ------------ // 111 | // crsf_uart_rx // 112 | // ------------ // 113 | 114 | #define crsf_uart_rx_wrap_target 0 115 | #define crsf_uart_rx_wrap 8 116 | 117 | static const uint16_t crsf_uart_rx_program_instructions[] = { 118 | // .wrap_target 119 | 0x2020, // 0: wait 0 pin, 0 120 | 0xea27, // 1: set x, 7 [10] 121 | 0x4001, // 2: in pins, 1 122 | 0x0642, // 3: jmp x--, 2 [6] 123 | 0x00c8, // 4: jmp pin, 8 124 | 0xc014, // 5: irq nowait 4 rel 125 | 0x20a0, // 6: wait 1 pin, 0 126 | 0x0000, // 7: jmp 0 127 | 0x8020, // 8: push block 128 | // .wrap 129 | }; 130 | 131 | #if !PICO_NO_HARDWARE 132 | static const struct pio_program crsf_uart_rx_program = { 133 | .instructions = crsf_uart_rx_program_instructions, 134 | .length = 9, 135 | .origin = -1, 136 | }; 137 | 138 | static inline pio_sm_config crsf_uart_rx_program_get_default_config(uint offset) { 139 | pio_sm_config c = pio_get_default_sm_config(); 140 | sm_config_set_wrap(&c, offset + crsf_uart_rx_wrap_target, offset + crsf_uart_rx_wrap); 141 | return c; 142 | } 143 | 144 | #include "hardware/gpio.h" 145 | #include "hardware/clocks.h" 146 | static inline void crsf_uart_rx_program_init(PIO pio, uint sm, uint offset, uint pin_rx, uint baud , bool invert) { 147 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // was in Tx program but is normally not required for Rx 148 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 149 | //pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, false); // remove by ms 150 | pio_gpio_init(pio, pin_rx); 151 | if (invert) { 152 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 153 | gpio_pull_down(pin_rx); // changed by MS 154 | } else { 155 | gpio_pull_up(pin_rx); // changed by MS 156 | } 157 | pio_sm_config c = crsf_uart_rx_program_get_default_config(offset); 158 | sm_config_set_in_pins(&c, pin_rx); // for WAIT, IN 159 | sm_config_set_jmp_pin(&c, pin_rx); // for JMP 160 | // Shift to right, autopush disabled 161 | sm_config_set_in_shift(&c, true, false, 32); 162 | // Deeper FIFO as we're not doing any TX 163 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 164 | // SM transmits 1 bit per 8 execution cycles. 165 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 166 | sm_config_set_clkdiv(&c, div); 167 | pio_sm_init(pio, sm, offset, &c); 168 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); // added by ms to get an irq int0 from pio 169 | pio_sm_set_enabled(pio, sm, true); 170 | } 171 | /* 172 | static inline void crsf_uart_rx_program_stop(PIO pio, uint sm, uint pin_rx) { 173 | pio_sm_set_enabled(pio, sm, false); // disable sm. 174 | } 175 | static inline void crsf_uart_rx_program_restart(PIO pio, uint sm, uint pin_rx , bool invert) { 176 | pio_sm_set_pindirs_with_mask(pio, sm, 0u , 1u << pin_rx); // set pin as input 177 | if (invert) { 178 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 179 | gpio_pull_down(pin_rx); // changed by MS 180 | } else { 181 | gpio_pull_up(pin_rx); // changed by MS 182 | } 183 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); 184 | pio_sm_restart (pio, sm); // to test if we need an enable after this 185 | pio_sm_set_enabled(pio, sm, true); 186 | #ifdef DEBUG_TIMING_CRSF 187 | gpio_put(TEST_PIN, 0); 188 | #endif 189 | } 190 | */ 191 | /* 192 | static inline char crsf_uart_rx_program_getc(PIO pio, uint sm) { 193 | // 8-bit read from the uppermost byte of the FIFO, as data is left-justified 194 | io_rw_8 *rxfifo_shift = (io_rw_8*)&pio->rxf[sm] + 3; 195 | while (pio_sm_is_rx_fifo_empty(pio, sm)) 196 | tight_loop_contents(); 197 | return (char)*rxfifo_shift; 198 | } 199 | */ 200 | 201 | #endif 202 | 203 | -------------------------------------------------------------------------------- /src/crsf_uart_tx_rx2.pio: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | .program crsf_uart_tx 18 | .side_set 1 opt 19 | 20 | ; An 8n1 UART transmit program. 21 | ; OUT pin 0 and side-set pin 0 are both mapped to UART TX pin. 22 | 23 | pull side 1 [7] ; Assert stop bit, or stall with line in idle state 24 | set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks 25 | bitloop: ; This loop will run 8 times (8n1 UART) 26 | out pins, 1 ; Shift 1 bit from OSR to the first OUT pin 27 | jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. 28 | 29 | 30 | 31 | 32 | 33 | ; pull side 1 [7] ; Assert stop bit, or stall with line in idle state 34 | ; set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks 35 | ;bitloop: ; This loop will run 8 times (8n1 UART) 36 | ; out pins, 1 ; Shift 1 bit from OSR to the first OUT pin 37 | ; jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. 38 | ; set x , 7 side 1 ; preload bit counter 39 | ; mov y , !STATUS [4] ; Assert stop bit and y becomes all 1 when TX fifo is less than 0 (value defined in setup) 40 | ; jmp !y setirq ; When fifo is empty do a special process (irq) 41 | ; pull [2] ; get next byte from fifo 42 | ; jmp bitloop side 0 [7] ; assert start bit for 8 clocks 43 | ;setirq: 44 | ; irq 0 ; when fifo is empty, fire an irq 45 | 46 | % c-sdk { 47 | #include "hardware/clocks.h" 48 | #include "stdio.h" // used by printf 49 | 50 | #define DEBUG_TIMING_CRSF // let check when pio switch from receiving to sending mode. 51 | #define TEST_PIN 3 52 | 53 | // here the code from elrs for Tx 54 | static inline void crsf_uart_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud, bool invert) { 55 | // Tell PIO to initially drive output-high on the selected pin, then map PIO 56 | // onto that pin with the IO muxes. 57 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 58 | //pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 59 | pio_gpio_init(pio, pin_tx); 60 | if ( invert ) { 61 | gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 62 | gpio_pull_down(pin_tx); // changed by MS 63 | } else { 64 | gpio_pull_up(pin_tx); // changed by MS 65 | } 66 | pio_sm_config c = crsf_uart_tx_program_get_default_config(offset); 67 | 68 | // OUT shifts to right, no autopull 69 | sm_config_set_out_shift(&c, true, false, 32); 70 | 71 | // We are mapping both OUT and side-set to the same pin, because sometimes 72 | // we need to assert user data onto the pin (with OUT) and sometimes 73 | // assert constant values (start/stop bit) 74 | sm_config_set_out_pins(&c, pin_tx, 1); 75 | sm_config_set_sideset_pins(&c, pin_tx); 76 | 77 | // We only need TX, so get an 8-deep FIFO! 78 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); 79 | 80 | // we use a move y , !STATUS instruction to know when the TXFIFO is empty, so we have to set it up in the configured 81 | sm_config_set_mov_status (&c, STATUS_TX_LESSTHAN , 1 ) ; // when TX fifo is less than 0(n), y will become all-ones, otherwise all-zeroes 82 | 83 | // SM transmits 1 bit per 8 execution cycles. 84 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 85 | sm_config_set_clkdiv(&c, div); 86 | 87 | pio_sm_init(pio, sm, offset, &c); 88 | pio_set_irq1_source_enabled(pio , pis_interrupt0 , true) ; // enable an interrupt0 on line IRQ1 when pio fire it because fifo is empty 89 | // pio_sm_set_enabled(pio, sm, true); // sm will be enable only on request 90 | #ifdef DEBUG_TIMING_CRSF 91 | // set test pin to check when pio mode change from sending to receiving 92 | gpio_init(TEST_PIN); 93 | gpio_set_dir(TEST_PIN, GPIO_OUT); // set pin as output 94 | #endif 95 | } 96 | 97 | static inline void crsf_uart_tx_program_stop(PIO pio, uint sm, uint pin_tx) { 98 | pio_sm_set_enabled(pio, sm, false); // disabled 99 | pio_sm_set_pindirs_with_mask(pio, sm, 0u , 1u << pin_tx); // put pin Tx as input 100 | // normally other parameters are already configured by init 101 | 102 | } 103 | 104 | 105 | static inline void crsf_uart_tx_program_start(PIO pio, uint sm, uint pin_tx , bool invert ) { 106 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin TX on high level 107 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin Tx as output 108 | if (invert) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 109 | // normally other parameters are already configured by init 110 | pio_sm_restart (pio, sm); // to test if we need an enable after this 111 | pio_sm_set_enabled(pio, sm, true); 112 | #ifdef DEBUG_TIMING_CRSF 113 | gpio_put(TEST_PIN, 1); 114 | #endif 115 | } 116 | 117 | /* 118 | 119 | static inline void uart_tx_program_putc(PIO pio, uint sm, char c) { 120 | pio_sm_put_blocking(pio, sm, (uint32_t)c); 121 | } 122 | 123 | static inline void uart_tx_program_puts(PIO pio, uint sm, const char *s) { 124 | while (*s) 125 | uart_tx_program_putc(pio, sm, *s++); 126 | } 127 | */ 128 | 129 | %} 130 | 131 | 132 | .program crsf_uart_rx 133 | 134 | ; Slightly more fleshed-out 8n1 UART receiver which handles framing errors and 135 | ; break conditions more gracefully. 136 | ; IN pin 0 and JMP pin are both mapped to the GPIO used as UART RX. 137 | 138 | start: 139 | wait 0 pin 0 ; Stall until start bit is asserted 140 | set x, 7 [10] ; Preload bit counter, then delay until halfway through 141 | bitloop: ; the first data bit (12 cycles incl wait, set). 142 | in pins, 1 ; Shift data bit into ISR 143 | jmp x-- bitloop [6] ; Loop 8 times, each loop iteration is 8 cycles 144 | jmp pin good_stop ; Check stop bit (should be high) 145 | 146 | irq 4 rel ; Either a framing error or a break. Set a sticky flag, 147 | wait 1 pin 0 ; and wait for line to return to idle state. 148 | jmp start ; Don't push data if we didn't see good framing. 149 | 150 | good_stop: ; No delay before returning to start; a little slack is 151 | push ; important in case the TX clock is slightly too fast. 152 | 153 | 154 | % c-sdk { 155 | #include "hardware/gpio.h" 156 | #include "hardware/clocks.h" 157 | static inline void crsf_uart_rx_program_init(PIO pio, uint sm, uint offset, uint pin_rx, uint baud , bool invert) { 158 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // was in Tx program but is normally not required for Rx 159 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 160 | //pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, false); // remove by ms 161 | pio_gpio_init(pio, pin_rx); 162 | if (invert) { 163 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 164 | gpio_pull_down(pin_rx); // changed by MS 165 | } else { 166 | gpio_pull_up(pin_rx); // changed by MS 167 | } 168 | pio_sm_config c = crsf_uart_rx_program_get_default_config(offset); 169 | sm_config_set_in_pins(&c, pin_rx); // for WAIT, IN 170 | sm_config_set_jmp_pin(&c, pin_rx); // for JMP 171 | // Shift to right, autopush disabled 172 | sm_config_set_in_shift(&c, true, false, 32); 173 | // Deeper FIFO as we're not doing any TX 174 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 175 | // SM transmits 1 bit per 8 execution cycles. 176 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 177 | sm_config_set_clkdiv(&c, div); 178 | 179 | pio_sm_init(pio, sm, offset, &c); 180 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); // added by ms to get an irq int0 from pio 181 | //pio_sm_set_enabled(pio, sm, true); 182 | } 183 | static inline void crsf_uart_rx_program_stop(PIO pio, uint sm, uint pin_rx) { 184 | pio_sm_set_enabled(pio, sm, false); // disable sm. 185 | } 186 | 187 | static inline void crsf_uart_rx_program_restart(PIO pio, uint sm, uint pin_rx , bool invert) { 188 | pio_sm_set_pindirs_with_mask(pio, sm, 0u , 1u << pin_rx); // set pin as input 189 | if (invert) { 190 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 191 | gpio_pull_down(pin_rx); // changed by MS 192 | } else { 193 | gpio_pull_up(pin_rx); // changed by MS 194 | } 195 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); 196 | pio_sm_restart (pio, sm); // to test if we need an enable after this 197 | pio_sm_set_enabled(pio, sm, true); 198 | #ifdef DEBUG_TIMING_CRSF 199 | gpio_put(TEST_PIN, 0); 200 | #endif 201 | } 202 | /* 203 | static inline char crsf_uart_rx_program_getc(PIO pio, uint sm) { 204 | // 8-bit read from the uppermost byte of the FIFO, as data is left-justified 205 | io_rw_8 *rxfifo_shift = (io_rw_8*)&pio->rxf[sm] + 3; 206 | while (pio_sm_is_rx_fifo_empty(pio, sm)) 207 | tight_loop_contents(); 208 | return (char)*rxfifo_shift; 209 | } 210 | */ 211 | %} 212 | 213 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | //#include 18 | #include "pico/stdlib.h" 19 | #include "pico/util/queue.h" 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include "hardware/watchdog.h" 25 | #include 26 | #include 27 | 28 | // to do : in crsf.cpp, handle the synchronisation frame from ELRS (decode it and change interval based on rate and offset) 29 | 30 | // CRSF uses PIO1 with 2 pins. pin 7 for TX and pin 8 for RX; 31 | // still ELRS module uses half duplex UART with only one pin (the lowest in the JR bay which is normally used for Sport) 32 | // So, pin 8 (RX) from RP2040 has to be connected to the lowest pin (Sport) from ELRS Tx module 33 | // and pin 7 (TX) from RP2040 has to be connected to pin 8 from RP2040 via a resistor (a value of 1K ohm should be ok) 34 | // SBUS uses pin 1 UART0 RX = Serial 35 | // SPORT (TX and RX) uses PIO0 and pin 5; for safety, insert a 1K resistor in serie on the wire to Frsky Sport 36 | // the pinout of the ELRS Tx module is the folowing: 37 | // - upper pin = ???? not used 38 | // - second upper pin = ???? not used 39 | // - battery VCC (5V-10V) 40 | // - gnd 41 | // - CRSF signal (is usually used by frsky for sport signal) 42 | // 43 | // The firmware reads the Sbus signal and save the 16 channels values 44 | // At regular interval (2 or 4ms as defined in the set up; not Sbus related), 45 | // it sent a CRSF RC channels frame with the last received Sbus value 46 | // If the ELRS Tx module is binded with the ELRS Rx module, 47 | // it get back a telemetry frame just after sending some RC channels (delay between is about 40usec) 48 | // There are 5 types of telemetry frames being decoded by the firmware 49 | // When valid, the telemetry data of each frame are stored in memory 50 | // At regular interval the Frsky receiver sent a pulling code to ask if some device has telemetry data to transmit. 51 | // When the device ID of the module is polled, the firmware sent on Sport bus a frame with one data (Id and value) 52 | // On each request, the firmware tries to send a different data if the delay from the previous one (of the same type) exceed some delay 53 | // The delay's of each type of data can be set up in order to manage priority in some way. 54 | 55 | 56 | void setup() { 57 | stdio_init_all(); 58 | uint16_t counter = 100; 59 | //if ( watchdog_caused_reboot() ) counter = 0; // avoid the UDC wait time when reboot is caused by the watchdog 60 | while ( (!tud_cdc_connected()) && (counter--)) { sleep_ms(100); } 61 | 62 | printf("started\n"); 63 | // setup UART for Sbus (100 kbaud, 8E2)...) (inverted) 64 | setupSbus(); 65 | 66 | // setup crsf uart for CRSF at 400000 baud; use pio1, 2 sm (one for tx and one for rx), dma for sending , irq and queue for reading) 67 | // the relay is master of crsf uart; it sent rc frame once every 4ms (or 2ms) and between 2 frames, it read the telemetry on the same pin 68 | setupCRSF(); 69 | 70 | // setup Sport uart (using pio0, 2 sm, dma, irq, queue) 71 | // FRSKY is master; it sent a code for polling the different devices once pet 11 msec; only one device can reply 72 | setupSport(); 73 | watchdog_enable(500, 1); // require an update once every 500 msec; othsewise, it forces a reboot 74 | } 75 | 76 | void loop() { 77 | //- use hardware uart0 to read the Sbus; get the data from a queue and store the data in a sbus buffer 78 | //- pio1 (2 state machines) is used for half duplex uart to communicate with CRSF 79 | // at regular interval convert the Sbus buffer into a CRSF frame , switch pio in sending mode and send using a DMA 80 | // When pio TXFIFO becomes empty, it call an IRQ that switch the UART in receiving mode. 81 | // An IRQ send each received character from ELRS to a queue 82 | // The queue is read in main loop and handle the process the char 83 | // Discard the data when it is not a valid telemetry frame; 84 | // When valid, store each receive data in a array (value and flag available) 85 | //- Sport uart (pio0) is inverted half duplex and is normally in receive mode. 86 | // When a byte is received and fit the device ID, look for the next telemetry field to be sent 87 | // If any, make a sport frame, put the pio (sport UART) in transmit mode, put the telemetry frame on DMA a dma channel 88 | // after some timelaps, put the pio back in receive mode; this could be changed to use an interrupt like for CRSF. 89 | watchdog_update(); 90 | handleSbusIn(); 91 | sendCrsfRcFrame(); 92 | handleTlmIn(); 93 | handleSportRxTx(); 94 | } 95 | 96 | 97 | int main(){ 98 | setup(); 99 | while(1) loop(); 100 | } 101 | -------------------------------------------------------------------------------- /src/sbus.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | //#include "arduino.h" 18 | 19 | #include "pico/stdlib.h" 20 | #include "stdio.h" // used by printf 21 | #include "hardware/uart.h" 22 | #include "hardware/irq.h" 23 | #include "pico/util/queue.h" 24 | #include 25 | #include "crsf.h" 26 | #include "tools.h" 27 | #include // used by memcpy 28 | 29 | #define SBUS_UART_ID uart0 30 | #define SBUS_TX_PIN 0 31 | #define SBUS_RX_PIN 1 32 | #define SBUS_BAUDRATE 100000 33 | queue_t sbusQueue ; 34 | 35 | enum SBUS_STATE{ 36 | NO_SBUS_FRAME = 0, 37 | RECEIVING_SBUS 38 | }; 39 | 40 | uint8_t runningSbusFrame[24]; 41 | extern rcFrameStruct crsfRcFrame ; // buffer used by crsf.cpp to fill the RC frame sent to ELRS 42 | extern bool crsfRcFrameReady ; // says that a buffer is ready 43 | 44 | // RX interrupt handler 45 | void on_sbus_uart_rx() { 46 | while (uart_is_readable(SBUS_UART_ID)) { 47 | uint8_t ch = uart_getc(SBUS_UART_ID); 48 | int count = queue_get_level( &sbusQueue ); 49 | //printf(" level = %i\n", count); 50 | //printf( "val = %X\n", ch); // printf in interrupt generates error but can be tested for debugging if some char are received 51 | if (!queue_try_add ( &sbusQueue , &ch)) printf("queue try add error\n"); 52 | //printf("%x\n", ch); 53 | } 54 | } 55 | 56 | 57 | void setupSbus(){ 58 | queue_init(&sbusQueue , 1 ,256) ;// queue for sbus uart with 256 elements of 1 59 | 60 | uart_init(SBUS_UART_ID, SBUS_BAUDRATE); // setup UART at 100000 baud 61 | uart_set_hw_flow(SBUS_UART_ID, false, false);// Set UART flow control CTS/RTS, we don't want these, so turn them off 62 | uart_set_fifo_enabled(SBUS_UART_ID, false); // Turn on FIFO's 63 | uart_set_format (SBUS_UART_ID, 8, 2 ,UART_PARITY_EVEN ) ; 64 | 65 | gpio_set_function(SBUS_TX_PIN , GPIO_FUNC_UART); // Set the GPIO pin mux to the UART 66 | gpio_set_function(SBUS_RX_PIN , GPIO_FUNC_UART); 67 | gpio_set_inover(SBUS_RX_PIN , GPIO_OVERRIDE_INVERT); 68 | // And set up and enable the interrupt handlers 69 | irq_set_exclusive_handler(UART0_IRQ, on_sbus_uart_rx); 70 | irq_set_enabled(UART0_IRQ, true); 71 | // Now enable the UART to send interrupts - RX only 72 | uart_set_irq_enables(SBUS_UART_ID, true, false); 73 | uint8_t dummy; 74 | while (! queue_is_empty (&sbusQueue)) queue_try_remove ( &sbusQueue , &dummy ) ; 75 | } // end setup sbus 76 | 77 | void handleSbusIn(){ 78 | static SBUS_STATE sbusState = NO_SBUS_FRAME ; 79 | static uint8_t sbusCounter = 0; 80 | static uint32_t lastSbusMillis = 0; 81 | uint8_t c; 82 | while (! queue_is_empty (&sbusQueue) ){ 83 | if ( (millis() - lastSbusMillis ) > 2 ){ 84 | sbusState = NO_SBUS_FRAME ; 85 | } 86 | lastSbusMillis = millis(); 87 | queue_try_remove ( &sbusQueue , &c); 88 | //printf(" %X",c); 89 | switch (sbusState) { 90 | case NO_SBUS_FRAME : 91 | if (c == 0x0F) { 92 | sbusCounter = 1; 93 | sbusState = RECEIVING_SBUS ; 94 | } 95 | break; 96 | case RECEIVING_SBUS : 97 | runningSbusFrame[sbusCounter++] = c; 98 | if (sbusCounter == 24 ) { 99 | if ( (c != 0x00) && (c != 0x04) && (c != 0x14) && (c != 0x24) && (c != 0x34) ) { 100 | sbusState = NO_SBUS_FRAME; 101 | } else { 102 | storeSbusFrame(); 103 | sbusState = NO_SBUS_FRAME; 104 | } 105 | } 106 | break; 107 | } 108 | } 109 | } 110 | 111 | 112 | void storeSbusFrame(){ 113 | memcpy( ( (uint8_t *) &crsfRcFrame) + 3, &runningSbusFrame[1], 22); 114 | crsfRcFrameReady = true; 115 | //float rc1 = ((runningSbusFrame[1] |runningSbusFrame[2]<<8) & 0x07FF); 116 | //printf("rc1 = %f\n", rc1/2); 117 | //printf("sbus received\n"); 118 | } 119 | -------------------------------------------------------------------------------- /src/sbus.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | #pragma once 18 | 19 | 20 | void setupSbus(); 21 | void storeSbusFrame(); 22 | void handleSbusIn(); 23 | -------------------------------------------------------------------------------- /src/sport.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | //#include 18 | #include 19 | 20 | #include "pico/stdlib.h" 21 | //#include "pico/multicore.h" 22 | #include "hardware/pio.h" 23 | //#include "hardware/uart.h" 24 | #include "sport_uart_tx_rx.pio.h" 25 | #include "pico/util/queue.h" 26 | #include "hardware/dma.h" 27 | #include "sport.h" 28 | 29 | // to do: 30 | // if we can reply to several device id, we should keep a table with the last field index used for this deviceid 31 | // when we get a polling for one device id, we should use this table to search from this last field index 32 | 33 | 34 | // one pio and 2 state machines are used to manage the sport in halfduplex 35 | // one state machine (sm) handle the TX and the second the RX 36 | // to receive data, the sm is initialised and use an IRQ handler when rx fifo is not empty 37 | // in irq, this byte is store in a Rx queue 38 | // This queue is read in main loop 39 | // When a byte is received after a 7E, then we stop the sm that receive (it means frsky made a polling) 40 | // We fill a buffer with the data 41 | // We set up a dma to transfer the data to the TX fifo of the Tx state machine 42 | // We also set up a timestamp to stop after some msec the Tx state machine and start again the Rx one 43 | 44 | 45 | #define SPORT_PIO_RX_PIN 5 // pin being used by the UART pio 46 | #define SPORTSYNCREQUEST 0x7E 47 | #define SPORTDEVICEID 0xE4 48 | 49 | queue_t sportRxQueue ; 50 | 51 | // one pio with 2 state machine is used to manage the inverted hal duplex uart for Sport 52 | PIO sportPio = pio0; 53 | uint sportSmRx = 1; // to get the request from sport 54 | uint sportSmTx = 0; // to send the telemetry to sport 55 | uint sportOffsetTx ; 56 | uint sportOffsetRx ; 57 | 58 | // dma channel is used to send Sport telemetry without blocking 59 | int sport_dma_chan; 60 | dma_channel_config sportDmaConfig; 61 | 62 | uint8_t sportTxBuffer[50]; 63 | 64 | uint32_t restoreSportPioToReceiveMillis = 0; // when 0, the pio is normally in receive mode, 65 | // otherwise, it is the timestamp when pio transmit has to be restore to receive mode 66 | 67 | 68 | field fields[SPORT_TYPES_MAX]; // list of all telemetry fields and parameters used by Sport 69 | 70 | 71 | void setupSport() { 72 | // list of fileds being used 73 | //latitude , longitude , groundspeed , heading , altitude , numSat 74 | //mVolt , current , capacity , remain 75 | //vSpeed, pitch , roll , yaw 76 | //uplink_RSSI_1 , uplink_RSSI_2 , uplink_Link_quality , uplink_SNR , active_antenna , rf_Mode , 77 | //uplink_TX_Power , downlink_RSSI , downlink_Link_quality , downlink_SNR 78 | 79 | uint16_t listFieldsID[] = {GPS_LONG_LATI_FIRST_ID , GPS_LONG_LATI_FIRST_ID ,GPS_SPEED_FIRST_ID, GPS_COURS_FIRST_ID , ALT_FIRST_ID, T1_FIRST_ID ,\ 80 | VFAS_FIRST_ID , CURR_FIRST_ID , T2_FIRST_ID , FUEL_FIRST_ID ,\ 81 | VARIO_FIRST_ID, ACCX_FIRST_ID , ACCY_FIRST_ID , ACCZ_FIRST_ID ,\ 82 | UPLINK_RSSI_1_ID , UPLINK_RSSI_2_ID , UPLINK_LINK_QUALITY_ID , UPLINK_SNR_ID , ACTIVE_ANTENNA_ID, RF_MODE_ID ,\ 83 | UPLINK_TX_POWER_ID , DOWNLINK_RSSI_ID , DOWNLINK_LINK_QUALITY_ID , DOWNLINK_SNR_ID} ; 84 | uint8_t listdeviceID[] = {DATA_ID_GPS, DATA_ID_GPS, DATA_ID_GPS, DATA_ID_GPS, DATA_ID_VARIO , DATA_ID_RPM ,\ 85 | DATA_ID_FAS , DATA_ID_FAS , DATA_ID_RPM , DATA_ID_FAS ,\ 86 | DATA_ID_VARIO , DATA_ID_ACC , DATA_ID_ACC , DATA_ID_ACC ,\ 87 | DATA_ID_RPM , DATA_ID_RPM , DATA_ID_RPM , DATA_ID_RPM , DATA_ID_RPM , DATA_ID_RPM,\ 88 | DATA_ID_RPM , DATA_ID_RPM , DATA_ID_RPM , DATA_ID_RPM}; 89 | uint16_t listInterval[] = { 500, 500 , 500 , 500 , 500 ,500,\ 90 | 500 , 500 , 500 , 500,\ 91 | 300 , 300 , 300 , 300,\ 92 | 500 , 500 , 500 , 500 , 500, 500,\ 93 | 500 , 500 , 500 , 500}; 94 | for (uint8_t i = 0 ; itxf[0], // Write address (only need to set this once) 118 | &sportTxBuffer[0], // we use always the same buffer 119 | 0 , // do not yet provide the number of bytes (DMA cycles) 120 | false // Don't start yet 121 | ); 122 | // Set up the state machine for transmit but do not yet start it (it starts only when a request from receiver is received) 123 | sportOffsetTx = pio_add_program(sportPio, &sport_uart_tx_program); 124 | sport_uart_tx_program_init(sportPio, sportSmTx, sportOffsetTx, SPORT_PIO_RX_PIN, 57600 , true); // we use the same pin and baud rate for tx and rx, true means thet UART is inverted 125 | 126 | // set an irq on pio to handle a received byte 127 | irq_set_exclusive_handler( PIO0_IRQ_0 , sportPioRxHandlerIrq) ; 128 | irq_set_enabled (PIO0_IRQ_0 , true) ; 129 | 130 | // Set up the state machine we're going to use to receive them. 131 | sportOffsetRx = pio_add_program(sportPio, &sport_uart_rx_program); 132 | sport_uart_rx_program_init(sportPio, sportSmRx, sportOffsetRx, SPORT_PIO_RX_PIN, 57600 , true); 133 | } 134 | 135 | 136 | void sportPioRxHandlerIrq(){ // when a byte is received on the Sport, read the pio Sport fifo and push the data to a queue (to be processed in the main loop) 137 | // clear the irq flag 138 | irq_clear (PIO0_IRQ_0 ); 139 | while ( ! pio_sm_is_rx_fifo_empty (sportPio ,sportSmRx)){ // when some data have been received 140 | uint8_t c = pio_sm_get (sportPio , sportSmRx) >> 24; // read the data 141 | queue_try_add (&sportRxQueue, &c); // push to the queue 142 | //sportRxMillis = millis(); // save the timestamp. 143 | } 144 | } 145 | 146 | 147 | //void processNextSportRxByte( uint8_t c){ 148 | // static uint8_t previous = 0; 149 | // printf(" %X",c); 150 | // if ( ( previous == SPORTSYNCREQUEST) && (c == SPORTDEVICEID) ) sendNextSportFrame(); 151 | // previous = c; 152 | //} 153 | 154 | void handleSportRxTx(void){ // main loop : restore receiving mode , wait for tlm request, prepare frame, start pio and dma to transmit it 155 | static uint8_t previous = 0; 156 | uint8_t data; 157 | if ( restoreSportPioToReceiveMillis) { // put sm back in recive mode after some delay 158 | if (millis() > restoreSportPioToReceiveMillis){ 159 | sport_uart_tx_program_stop(sportPio, sportSmTx, SPORT_PIO_RX_PIN ); 160 | sport_uart_rx_program_restart(sportPio, sportSmRx, SPORT_PIO_RX_PIN, true); // true = inverted 161 | restoreSportPioToReceiveMillis = 0 ; 162 | } 163 | } else { // when we are in receive mode 164 | if (! queue_is_empty(&sportRxQueue)) { 165 | queue_try_remove (&sportRxQueue,&data); 166 | if ( ( previous == SPORTSYNCREQUEST) && (data == SPORTDEVICEID) ) sendNextSportFrame(data); 167 | // we could use several device id ti increase the telemetry rate 168 | //if ( ( previous == SPORTSYNCREQUEST) && ( (data == DATA_ID_GPS) || 169 | //(data == DATA_ID_VARIO) || (data == DATA_ID_RPM) || (data == DATA_ID_FAS) || (data == DATA_ID_ACC) ) ) sendNextSportFrame(data); 170 | previous = data; 171 | } 172 | } 173 | } 174 | 175 | 176 | void sendNextSportFrame(uint8_t data_id){ // search for the next data to be sent for this device ID 177 | static uint8_t last_sport_idx = 0 ; 178 | if ( dma_channel_is_busy(sport_dma_chan) )return ; // skip if the DMA is still sending data 179 | uint32_t _millis = millis(); 180 | for (uint8_t i = 0 ; i< SPORT_TYPES_MAX ; i++ ){ 181 | last_sport_idx++; 182 | if (last_sport_idx >= SPORT_TYPES_MAX) last_sport_idx = 0 ; 183 | if ( (_millis >= fields[last_sport_idx].nextMillis) && (fields[last_sport_idx].available) ) { 184 | sendOneSport(last_sport_idx); 185 | fields[last_sport_idx].available = false; // flag as sent 186 | fields[last_sport_idx].nextMillis = millis() + fields[last_sport_idx].interval; 187 | break; 188 | } 189 | } 190 | } 191 | 192 | void sendOneSport(uint8_t idx){ // fill one frame and send it 193 | // the frame contains 1 byte = type, 2 bytes = value id, 4 byte( or more) for value, 1 byte CRC 194 | uint8_t counter = 0; 195 | uint8_t value[4] = { 0, 1, 2, 3}; 196 | uint16_t crc ; 197 | uint8_t tempBuffer[10]; 198 | tempBuffer[counter++] = 0X10 ; // type of packet : data 199 | tempBuffer[counter++] = fields[idx].fieldId ; // 0x0110 = Id for vario data 200 | tempBuffer[counter++] = fields[idx].fieldId >> 8 ; // 0x0110 = Id for vario data 201 | tempBuffer[counter++] = fields[idx].value >> 0 ; // value 202 | tempBuffer[counter++] = fields[idx].value >> 8 ; 203 | tempBuffer[counter++] = fields[idx].value >> 16 ; 204 | tempBuffer[counter++] = fields[idx].value >> 24; // value 205 | 206 | crc = tempBuffer[0] ; 207 | for (uint8_t i = 1; i<=6;i++){ 208 | crc += tempBuffer[i]; //0-1FF 209 | crc += crc >> 8 ; //0-100 210 | crc &= 0x00ff ; 211 | } 212 | tempBuffer[counter] = 0xFF-crc ; // CRC in buffer 213 | // copy and convert bytes 214 | // Byte in frame has value 0x7E is changed into 2 bytes: 0x7D 0x5E 215 | // Byte in frame has value 0x7D is changed into 2 bytes: 0x7D 0x5D 216 | uint8_t sportLength = 0; 217 | for (uint8_t i = 0 ; i<=7 ; i++){ 218 | if (tempBuffer[i] == 0x7E) { 219 | sportTxBuffer[sportLength++] = 0x7D; 220 | sportTxBuffer[sportLength++] = 0x5E; 221 | } else if (tempBuffer[i] == 0x7D) { 222 | sportTxBuffer[sportLength++] = 0x7D; 223 | sportTxBuffer[sportLength++] = 0x5D; 224 | } else { 225 | sportTxBuffer[sportLength++]= tempBuffer[i]; 226 | } 227 | } 228 | sleep_us(100) ; 229 | sport_uart_rx_program_stop(sportPio, sportSmRx, SPORT_PIO_RX_PIN); // stop receiving 230 | sport_uart_tx_program_start(sportPio, sportSmTx, SPORT_PIO_RX_PIN, true); // prepare to transmit 231 | // start the DMA channel with the data to transmit 232 | dma_channel_set_read_addr (sport_dma_chan, &sportTxBuffer[0], false); 233 | dma_channel_set_trans_count (sport_dma_chan, sportLength, true) ; 234 | // we need a way to set the pio back in receive mode when all bytes are sent 235 | // this will be done in the main loop after some ms (here 6ms) 236 | restoreSportPioToReceiveMillis = millis() + 6; 237 | } 238 | 239 | -------------------------------------------------------------------------------- /src/sport.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include "Arduino.h" 20 | 21 | #define SPORT_TYPES_MAX 24 22 | struct field { 23 | int32_t value; 24 | bool available; 25 | uint32_t nextMillis; 26 | uint16_t interval; // msec 27 | uint8_t deviceId; 28 | uint16_t fieldId; 29 | } ; 30 | 31 | 32 | // default SPORT_SENSOR_ID 33 | #define DATA_ID_VARIO 0x00 // = sensor 0 used for Alt and Vspeed 34 | #define DATA_ID_FLVSS 0xA1 // 1 35 | #define DATA_ID_FAS 0x22 // 2 36 | #define DATA_ID_GPS 0x83 // 3 used for all GPS data 37 | #define DATA_ID_RPM 0xE4 // 4 38 | #define DATA_ID_ACC 0x67 // 7 39 | //list of 28 device ID codes is (in sequence) 40 | // 0x00,0xA1,0x22,0x83,0xE4,0x45,0xC6,0x67,0x48,0xE9,0x6A,0xCB,0xAC,0x0D,0x8E,0x2F,0xD0,0x71,0xF2,0x53,0x34,0x95,0x16,0xB7,0x98,0x39,0xBA,0x1B 41 | 42 | 43 | // FrSky new DATA IDs (2 bytes) (copied from openTX telemetry/frsky_sport.cpp on 11 jul 2014) // those values are not used directly but bits 4 up to 11 are stored in an array in oXs_out_frsky.cpp 44 | #define ALT_FIRST_ID 0x0100 45 | #define ALT_LAST_ID 0x010f 46 | #define VARIO_FIRST_ID 0x0110 47 | #define VARIO_LAST_ID 0x011f 48 | #define CURR_FIRST_ID 0x0200 49 | #define CURR_LAST_ID 0x020f 50 | #define VFAS_FIRST_ID 0x0210 51 | #define VFAS_LAST_ID 0x021f 52 | #define CELLS_FIRST_ID 0x0300 53 | #define CELLS_SECOND_ID 0x0301 54 | #define CELLS_THIRD_ID 0x0302 55 | #define CELLS_LAST_ID 0x030f 56 | #define T1_FIRST_ID 0x0400 57 | #define T1_LAST_ID 0x040f 58 | #define T2_FIRST_ID 0x0410 59 | #define T2_LAST_ID 0x041f 60 | #define RPM_FIRST_ID 0x0500 61 | #define RPM_LAST_ID 0x050f 62 | #define FUEL_FIRST_ID 0x0600 63 | #define FUEL_LAST_ID 0x060f 64 | #define ACCX_FIRST_ID 0x0700 65 | #define ACCX_LAST_ID 0x070f 66 | #define ACCY_FIRST_ID 0x0710 67 | #define ACCY_LAST_ID 0x071f 68 | #define ACCZ_FIRST_ID 0x0720 69 | #define ACCZ_LAST_ID 0x072f 70 | #define GPS_LONG_LATI_FIRST_ID 0x0800 71 | #define GPS_LONG_LATI_LAST_ID 0x080f 72 | #define GPS_ALT_FIRST_ID 0x0820 73 | #define GPS_ALT_LAST_ID 0x082f 74 | #define GPS_SPEED_FIRST_ID 0x0830 75 | #define GPS_SPEED_LAST_ID 0x083f 76 | #define GPS_COURS_FIRST_ID 0x0840 77 | #define GPS_COURS_LAST_ID 0x084f 78 | #define GPS_TIME_DATE_FIRST_ID 0x0850 79 | #define GPS_TIME_DATE_LAST_ID 0x085f 80 | #define A3_FIRST_ID 0x0900 81 | #define A3_LAST_ID 0x090f 82 | #define A4_FIRST_ID 0x0910 83 | #define A4_LAST_ID 0x091f 84 | #define AIR_SPEED_FIRST_ID 0x0a00 85 | #define AIR_SPEED_LAST_ID 0x0a0f 86 | #define RSSI_ID 0xf101 // please do not use this code because it is already used by the receiver 87 | #define ADC1_ID 0xf102 // please do not use this code because it is already used by the receiver 88 | #define ADC2_ID 0xf103 89 | #define BATT_ID 0xf104 90 | #define SWR_ID 0xf105 // please do not use this code because it is already used by the receiver 91 | #define UPLINK_RSSI_1_ID 0x0c00 // to check if this range is valid 92 | #define UPLINK_RSSI_2_ID 0x0c01 93 | #define UPLINK_LINK_QUALITY_ID 0x0c02 94 | #define UPLINK_SNR_ID 0x0c03 95 | #define ACTIVE_ANTENNA_ID 0x0c04 96 | #define RF_MODE_ID 0x0c05 97 | #define UPLINK_TX_POWER_ID 0x0c06 98 | #define DOWNLINK_RSSI_ID 0x0c07 99 | #define DOWNLINK_LINK_QUALITY_ID 0x0c08 100 | #define DOWNLINK_SNR_ID 0x0c09 101 | 102 | 103 | 104 | enum fieldIdx { 105 | LATITUDE =0, 106 | LONGITUDE, 107 | GROUNDSPEED , 108 | HEADING, 109 | ALTITUDE , 110 | NUMSAT , 111 | MVOLT, 112 | CURRENT, 113 | CAPACITY, 114 | REMAIN, 115 | VSPEED, 116 | PITCH, 117 | ROLL, 118 | YAW , 119 | UPLINK_RSSI_1 , UPLINK_RSSI_2 , UPLINK_LINK_QUALITY , UPLINK_SNR , ACTIVE_ANTENNA, RF_MODE , 120 | UPLINK_TX_POWER , DOWNLINK_RSSI , DOWNLINK_LINK_QUALITY , DOWNLINK_SNR 121 | }; 122 | 123 | void setupSport(void); 124 | 125 | void sportPioRxHandlerIrq() ; // when a byte is received on the Sport, read the pio Sport fifo and push the data to a queue (to be processed in the main loop) 126 | 127 | void handleSportRxTx(void); 128 | void sendNextSportFrame(uint8_t data_id) ; // search for the next data to be sent 129 | void sendOneSport(uint8_t idx); 130 | 131 | -------------------------------------------------------------------------------- /src/sport_uart_tx_rx.pio: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | .program sport_uart_tx 18 | .side_set 1 opt 19 | 20 | ; An 8n1 UART transmit program. 21 | ; OUT pin 0 and side-set pin 0 are both mapped to UART TX pin. 22 | 23 | pull side 1 [7] ; Assert stop bit, or stall with line in idle state 24 | set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks 25 | bitloop: ; This loop will run 8 times (8n1 UART) 26 | out pins, 1 ; Shift 1 bit from OSR to the first OUT pin 27 | jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. 28 | 29 | 30 | % c-sdk { 31 | #include "hardware/clocks.h" 32 | // here the code from elrsoXs for Tx 33 | static inline void sport_uart_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud, bool invert) { 34 | // Tell PIO to initially drive output-high on the selected pin, then map PIO 35 | // onto that pin with the IO muxes. 36 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 37 | //pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 38 | pio_gpio_init(pio, pin_tx); 39 | if ( invert ) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 40 | pio_sm_config c = sport_uart_tx_program_get_default_config(offset); 41 | 42 | // OUT shifts to right, no autopull 43 | sm_config_set_out_shift(&c, true, false, 32); 44 | 45 | // We are mapping both OUT and side-set to the same pin, because sometimes 46 | // we need to assert user data onto the pin (with OUT) and sometimes 47 | // assert constant values (start/stop bit) 48 | sm_config_set_out_pins(&c, pin_tx, 1); 49 | sm_config_set_sideset_pins(&c, pin_tx); 50 | 51 | // We only need TX, so get an 8-deep FIFO! 52 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); 53 | 54 | // SM transmits 1 bit per 8 execution cycles. 55 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 56 | sm_config_set_clkdiv(&c, div); 57 | 58 | pio_sm_init(pio, sm, offset, &c); 59 | // pio_sm_set_enabled(pio, sm, true); // sm will be enable only on request 60 | } 61 | 62 | static inline void sport_uart_tx_program_stop(PIO pio, uint sm, uint pin_tx) { 63 | pio_sm_set_enabled(pio, sm, false); // disabled 64 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_tx); // put pin Tx as input 65 | // normally other parameters are already configured by init 66 | 67 | } 68 | 69 | 70 | static inline void sport_uart_tx_program_start(PIO pio, uint sm, uint pin_tx , bool invert ) { 71 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin TX on high level 72 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin Tx as output 73 | if (invert) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 74 | // normally other parameters are already configured by init 75 | pio_sm_restart (pio, sm); // to test if we need an enable after this 76 | pio_sm_set_enabled(pio, sm, true); 77 | } 78 | 79 | 80 | 81 | static inline void sport_uart_tx_program_putc(PIO pio, uint sm, char c) { 82 | pio_sm_put_blocking(pio, sm, (uint32_t)c); 83 | } 84 | 85 | static inline void sport_uart_tx_program_puts(PIO pio, uint sm, const char *s) { 86 | while (*s) 87 | sport_uart_tx_program_putc(pio, sm, *s++); 88 | } 89 | 90 | %} 91 | 92 | 93 | .program sport_uart_rx 94 | 95 | ; Slightly more fleshed-out 8n1 UART receiver which handles framing errors and 96 | ; break conditions more gracefully. 97 | ; IN pin 0 and JMP pin are both mapped to the GPIO used as UART RX. 98 | 99 | start: 100 | wait 0 pin 0 ; Stall until start bit is asserted 101 | set x, 7 [10] ; Preload bit counter, then delay until halfway through 102 | bitloop: ; the first data bit (12 cycles incl wait, set). 103 | in pins, 1 ; Shift data bit into ISR 104 | jmp x-- bitloop [6] ; Loop 8 times, each loop iteration is 8 cycles 105 | jmp pin good_stop ; Check stop bit (should be high) 106 | 107 | irq 4 rel ; Either a framing error or a break. Set a sticky flag, 108 | wait 1 pin 0 ; and wait for line to return to idle state. 109 | jmp start ; Don't push data if we didn't see good framing. 110 | 111 | good_stop: ; No delay before returning to start; a little slack is 112 | push ; important in case the TX clock is slightly too fast. 113 | 114 | 115 | % c-sdk { 116 | #include "hardware/gpio.h" 117 | #include "hardware/clocks.h" 118 | static inline void sport_uart_rx_program_init(PIO pio, uint sm, uint offset, uint pin_rx, uint baud , bool invert) { 119 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // was in Tx program but is normally not required for Rx 120 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 121 | //pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, false); // remove by ms 122 | pio_gpio_init(pio, pin_rx); 123 | if (invert) { 124 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 125 | gpio_pull_down(pin_rx); // changed by MS 126 | } else { 127 | gpio_pull_up(pin_rx); // changed by MS 128 | } 129 | pio_sm_config c = sport_uart_rx_program_get_default_config(offset); 130 | sm_config_set_in_pins(&c, pin_rx); // for WAIT, IN 131 | sm_config_set_jmp_pin(&c, pin_rx); // for JMP 132 | // Shift to right, autopush disabled 133 | sm_config_set_in_shift(&c, true, false, 32); 134 | // Deeper FIFO as we're not doing any TX 135 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 136 | // SM transmits 1 bit per 8 execution cycles. 137 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 138 | sm_config_set_clkdiv(&c, div); 139 | 140 | pio_sm_init(pio, sm, offset, &c); 141 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); // added by ms to get an irq int0 from pio 142 | pio_sm_set_enabled(pio, sm, true); 143 | } 144 | static inline void sport_uart_rx_program_stop(PIO pio, uint sm, uint pin_rx) { 145 | pio_sm_set_enabled(pio, sm, false); // disable sm. 146 | } 147 | 148 | static inline void sport_uart_rx_program_restart(PIO pio, uint sm, uint pin_rx , bool invert) { 149 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 150 | if (invert) { 151 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 152 | gpio_pull_down(pin_rx); // changed by MS 153 | } else { 154 | gpio_pull_up(pin_rx); // changed by MS 155 | } 156 | pio_sm_restart (pio, sm); // to test if we need an enable after this 157 | pio_sm_set_enabled(pio, sm, true); 158 | } 159 | /* 160 | static inline char sport_uart_rx_program_getc(PIO pio, uint sm) { 161 | // 8-bit read from the uppermost byte of the FIFO, as data is left-justified 162 | io_rw_8 *rxfifo_shift = (io_rw_8*)&pio->rxf[sm] + 3; 163 | while (pio_sm_is_rx_fifo_empty(pio, sm)) 164 | tight_loop_contents(); 165 | return (char)*rxfifo_shift; 166 | } 167 | */ 168 | %} 169 | 170 | -------------------------------------------------------------------------------- /src/sport_uart_tx_rx.pio.h: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------- // 2 | // This file is autogenerated by pioasm; do not edit! // 3 | // -------------------------------------------------- // 4 | 5 | #if !PICO_NO_HARDWARE 6 | #include "hardware/pio.h" 7 | #endif 8 | 9 | // ------------- // 10 | // sport_uart_tx // 11 | // ------------- // 12 | 13 | #define sport_uart_tx_wrap_target 0 14 | #define sport_uart_tx_wrap 3 15 | 16 | static const uint16_t sport_uart_tx_program_instructions[] = { 17 | // .wrap_target 18 | 0x9fa0, // 0: pull block side 1 [7] 19 | 0xf727, // 1: set x, 7 side 0 [7] 20 | 0x6001, // 2: out pins, 1 21 | 0x0642, // 3: jmp x--, 2 [6] 22 | // .wrap 23 | }; 24 | 25 | #if !PICO_NO_HARDWARE 26 | static const struct pio_program sport_uart_tx_program = { 27 | .instructions = sport_uart_tx_program_instructions, 28 | .length = 4, 29 | .origin = -1, 30 | }; 31 | 32 | static inline pio_sm_config sport_uart_tx_program_get_default_config(uint offset) { 33 | pio_sm_config c = pio_get_default_sm_config(); 34 | sm_config_set_wrap(&c, offset + sport_uart_tx_wrap_target, offset + sport_uart_tx_wrap); 35 | sm_config_set_sideset(&c, 2, true, false); 36 | return c; 37 | } 38 | 39 | #include "hardware/clocks.h" 40 | // here the code from elrsoXs for Tx 41 | static inline void sport_uart_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud, bool invert) { 42 | // Tell PIO to initially drive output-high on the selected pin, then map PIO 43 | // onto that pin with the IO muxes. 44 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 45 | //pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 46 | pio_gpio_init(pio, pin_tx); 47 | if ( invert ) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 48 | pio_sm_config c = sport_uart_tx_program_get_default_config(offset); 49 | // OUT shifts to right, no autopull 50 | sm_config_set_out_shift(&c, true, false, 32); 51 | // We are mapping both OUT and side-set to the same pin, because sometimes 52 | // we need to assert user data onto the pin (with OUT) and sometimes 53 | // assert constant values (start/stop bit) 54 | sm_config_set_out_pins(&c, pin_tx, 1); 55 | sm_config_set_sideset_pins(&c, pin_tx); 56 | // We only need TX, so get an 8-deep FIFO! 57 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); 58 | // SM transmits 1 bit per 8 execution cycles. 59 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 60 | sm_config_set_clkdiv(&c, div); 61 | pio_sm_init(pio, sm, offset, &c); 62 | // pio_sm_set_enabled(pio, sm, true); // sm will be enable only on request 63 | } 64 | static inline void sport_uart_tx_program_stop(PIO pio, uint sm, uint pin_tx) { 65 | pio_sm_set_enabled(pio, sm, false); // disabled 66 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_tx); // put pin Tx as input 67 | // normally other parameters are already configured by init 68 | } 69 | static inline void sport_uart_tx_program_start(PIO pio, uint sm, uint pin_tx , bool invert ) { 70 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin TX on high level 71 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin Tx as output 72 | if (invert) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 73 | // normally other parameters are already configured by init 74 | pio_sm_restart (pio, sm); // to test if we need an enable after this 75 | pio_sm_set_enabled(pio, sm, true); 76 | } 77 | static inline void sport_uart_tx_program_putc(PIO pio, uint sm, char c) { 78 | pio_sm_put_blocking(pio, sm, (uint32_t)c); 79 | } 80 | static inline void sport_uart_tx_program_puts(PIO pio, uint sm, const char *s) { 81 | while (*s) 82 | sport_uart_tx_program_putc(pio, sm, *s++); 83 | } 84 | 85 | #endif 86 | 87 | // ------------- // 88 | // sport_uart_rx // 89 | // ------------- // 90 | 91 | #define sport_uart_rx_wrap_target 0 92 | #define sport_uart_rx_wrap 8 93 | 94 | static const uint16_t sport_uart_rx_program_instructions[] = { 95 | // .wrap_target 96 | 0x2020, // 0: wait 0 pin, 0 97 | 0xea27, // 1: set x, 7 [10] 98 | 0x4001, // 2: in pins, 1 99 | 0x0642, // 3: jmp x--, 2 [6] 100 | 0x00c8, // 4: jmp pin, 8 101 | 0xc014, // 5: irq nowait 4 rel 102 | 0x20a0, // 6: wait 1 pin, 0 103 | 0x0000, // 7: jmp 0 104 | 0x8020, // 8: push block 105 | // .wrap 106 | }; 107 | 108 | #if !PICO_NO_HARDWARE 109 | static const struct pio_program sport_uart_rx_program = { 110 | .instructions = sport_uart_rx_program_instructions, 111 | .length = 9, 112 | .origin = -1, 113 | }; 114 | 115 | static inline pio_sm_config sport_uart_rx_program_get_default_config(uint offset) { 116 | pio_sm_config c = pio_get_default_sm_config(); 117 | sm_config_set_wrap(&c, offset + sport_uart_rx_wrap_target, offset + sport_uart_rx_wrap); 118 | return c; 119 | } 120 | 121 | #include "hardware/gpio.h" 122 | #include "hardware/clocks.h" 123 | static inline void sport_uart_rx_program_init(PIO pio, uint sm, uint offset, uint pin_rx, uint baud , bool invert) { 124 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // was in Tx program but is normally not required for Rx 125 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 126 | //pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, false); // remove by ms 127 | pio_gpio_init(pio, pin_rx); 128 | if (invert) { 129 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 130 | gpio_pull_down(pin_rx); // changed by MS 131 | } else { 132 | gpio_pull_up(pin_rx); // changed by MS 133 | } 134 | pio_sm_config c = sport_uart_rx_program_get_default_config(offset); 135 | sm_config_set_in_pins(&c, pin_rx); // for WAIT, IN 136 | sm_config_set_jmp_pin(&c, pin_rx); // for JMP 137 | // Shift to right, autopush disabled 138 | sm_config_set_in_shift(&c, true, false, 32); 139 | // Deeper FIFO as we're not doing any TX 140 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 141 | // SM transmits 1 bit per 8 execution cycles. 142 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 143 | sm_config_set_clkdiv(&c, div); 144 | pio_sm_init(pio, sm, offset, &c); 145 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); // added by ms to get an irq int0 from pio 146 | pio_sm_set_enabled(pio, sm, true); 147 | } 148 | static inline void sport_uart_rx_program_stop(PIO pio, uint sm, uint pin_rx) { 149 | pio_sm_set_enabled(pio, sm, false); // disable sm. 150 | } 151 | static inline void sport_uart_rx_program_restart(PIO pio, uint sm, uint pin_rx , bool invert) { 152 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 153 | if (invert) { 154 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 155 | gpio_pull_down(pin_rx); // changed by MS 156 | } else { 157 | gpio_pull_up(pin_rx); // changed by MS 158 | } 159 | pio_sm_restart (pio, sm); // to test if we need an enable after this 160 | pio_sm_set_enabled(pio, sm, true); 161 | } 162 | /* 163 | static inline char sport_uart_rx_program_getc(PIO pio, uint sm) { 164 | // 8-bit read from the uppermost byte of the FIFO, as data is left-justified 165 | io_rw_8 *rxfifo_shift = (io_rw_8*)&pio->rxf[sm] + 3; 166 | while (pio_sm_is_rx_fifo_empty(pio, sm)) 167 | tight_loop_contents(); 168 | return (char)*rxfifo_shift; 169 | } 170 | */ 171 | 172 | #endif 173 | 174 | -------------------------------------------------------------------------------- /src/tools.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | #include "tools.h" 18 | #include "pico/stdlib.h" 19 | #include "stdio.h" // used by printf 20 | 21 | 22 | uint32_t millis(){ 23 | return to_ms_since_boot( get_absolute_time()); 24 | } 25 | 26 | uint32_t micros() { 27 | return to_us_since_boot(get_absolute_time ()); 28 | } 29 | 30 | void printHexBuffer(uint8_t * buffer , uint8_t bufferLength){ 31 | for ( uint8_t i = 0 ; i < bufferLength ; i++){ 32 | printf(" %x ", buffer[i]); 33 | } 34 | printf("\n"); 35 | } 36 | 37 | 38 | //! Byte swap unsigned short 39 | uint16_t swap_uint16( uint16_t val ) 40 | { 41 | return (val << 8) | (val >> 8 ); 42 | } 43 | 44 | //! Byte swap short 45 | int16_t swap_int16( int16_t val ) 46 | { 47 | return (val << 8) | ((val >> 8) & 0xFF); 48 | } 49 | 50 | //! Byte swap unsigned int 51 | uint32_t swap_uint32( uint32_t val ) 52 | { 53 | val = ((val << 8) & 0xFF00FF00 ) | ((val >> 8) & 0xFF00FF ); 54 | return (val << 16) | (val >> 16); 55 | } 56 | 57 | //! Byte swap int 58 | int32_t swap_int32( int32_t val ) 59 | { 60 | val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF ); 61 | return (val << 16) | ((val >> 16) & 0xFFFF); 62 | } -------------------------------------------------------------------------------- /src/tools.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) ExpressLRS_relay 3 | * 4 | * 5 | * License GPLv3: http://www.gnu.org/licenses/gpl-3.0.html 6 | * 7 | * This program is free software; you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License version 2 as 9 | * published by the Free Software Foundation. 10 | * 11 | * This program 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 14 | * GNU General Public License for more details. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include "pico/stdlib.h" 20 | //#include "stdio.h" 21 | 22 | 23 | uint32_t millis() ; 24 | 25 | uint32_t micros(); 26 | 27 | void printHexBuffer(uint8_t * buffer , uint8_t bufferLength); 28 | 29 | 30 | //! Byte swap unsigned short 31 | uint16_t swap_uint16( uint16_t val ); 32 | 33 | 34 | //! Byte swap short 35 | int16_t swap_int16( int16_t val ) ; 36 | 37 | //! Byte swap unsigned int 38 | uint32_t swap_uint32( uint32_t val ); 39 | 40 | //! Byte swap int 41 | int32_t swap_int32( int32_t val ); 42 | -------------------------------------------------------------------------------- /src/uart_tx_rx.pio.h: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------- // 2 | // This file is autogenerated by pioasm; do not edit! // 3 | // -------------------------------------------------- // 4 | 5 | #if !PICO_NO_HARDWARE 6 | #include "hardware/pio.h" 7 | #endif 8 | 9 | // ------- // 10 | // uart_tx // 11 | // ------- // 12 | 13 | #define uart_tx_wrap_target 0 14 | #define uart_tx_wrap 3 15 | 16 | static const uint16_t uart_tx_program_instructions[] = { 17 | // .wrap_target 18 | 0x9fa0, // 0: pull block side 1 [7] 19 | 0xf727, // 1: set x, 7 side 0 [7] 20 | 0x6001, // 2: out pins, 1 21 | 0x0642, // 3: jmp x--, 2 [6] 22 | // .wrap 23 | }; 24 | 25 | #if !PICO_NO_HARDWARE 26 | static const struct pio_program uart_tx_program = { 27 | .instructions = uart_tx_program_instructions, 28 | .length = 4, 29 | .origin = -1, 30 | }; 31 | 32 | static inline pio_sm_config uart_tx_program_get_default_config(uint offset) { 33 | pio_sm_config c = pio_get_default_sm_config(); 34 | sm_config_set_wrap(&c, offset + uart_tx_wrap_target, offset + uart_tx_wrap); 35 | sm_config_set_sideset(&c, 2, true, false); 36 | return c; 37 | } 38 | 39 | #include "hardware/clocks.h" 40 | // here the code from elrsoXs for Tx 41 | static inline void uart_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud, bool invert) { 42 | // Tell PIO to initially drive output-high on the selected pin, then map PIO 43 | // onto that pin with the IO muxes. 44 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 45 | //pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); 46 | pio_gpio_init(pio, pin_tx); 47 | if ( invert ) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 48 | pio_sm_config c = uart_tx_program_get_default_config(offset); 49 | // OUT shifts to right, no autopull 50 | sm_config_set_out_shift(&c, true, false, 32); 51 | // We are mapping both OUT and side-set to the same pin, because sometimes 52 | // we need to assert user data onto the pin (with OUT) and sometimes 53 | // assert constant values (start/stop bit) 54 | sm_config_set_out_pins(&c, pin_tx, 1); 55 | sm_config_set_sideset_pins(&c, pin_tx); 56 | // We only need TX, so get an 8-deep FIFO! 57 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); 58 | // SM transmits 1 bit per 8 execution cycles. 59 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 60 | sm_config_set_clkdiv(&c, div); 61 | pio_sm_init(pio, sm, offset, &c); 62 | // pio_sm_set_enabled(pio, sm, true); // sm will be enable only on request 63 | } 64 | static inline void uart_tx_program_stop(PIO pio, uint sm, uint pin_tx) { 65 | pio_sm_set_enabled(pio, sm, false); // disabled 66 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_tx); // put pin Tx as input 67 | // normally other parameters are already configured by init 68 | } 69 | static inline void uart_tx_program_start(PIO pio, uint sm, uint pin_tx , bool invert ) { 70 | pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin TX on high level 71 | pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // put pin Tx as output 72 | if (invert) gpio_set_outover(pin_tx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 73 | // normally other parameters are already configured by init 74 | pio_sm_restart (pio, sm); // to test if we need an enable after this 75 | pio_sm_set_enabled(pio, sm, true); 76 | } 77 | static inline void uart_tx_program_putc(PIO pio, uint sm, char c) { 78 | pio_sm_put_blocking(pio, sm, (uint32_t)c); 79 | } 80 | static inline void uart_tx_program_puts(PIO pio, uint sm, const char *s) { 81 | while (*s) 82 | uart_tx_program_putc(pio, sm, *s++); 83 | } 84 | 85 | #endif 86 | 87 | // ------- // 88 | // uart_rx // 89 | // ------- // 90 | 91 | #define uart_rx_wrap_target 0 92 | #define uart_rx_wrap 8 93 | 94 | static const uint16_t uart_rx_program_instructions[] = { 95 | // .wrap_target 96 | 0x2020, // 0: wait 0 pin, 0 97 | 0xea27, // 1: set x, 7 [10] 98 | 0x4001, // 2: in pins, 1 99 | 0x0642, // 3: jmp x--, 2 [6] 100 | 0x00c8, // 4: jmp pin, 8 101 | 0xc014, // 5: irq nowait 4 rel 102 | 0x20a0, // 6: wait 1 pin, 0 103 | 0x0000, // 7: jmp 0 104 | 0x8020, // 8: push block 105 | // .wrap 106 | }; 107 | 108 | #if !PICO_NO_HARDWARE 109 | static const struct pio_program uart_rx_program = { 110 | .instructions = uart_rx_program_instructions, 111 | .length = 9, 112 | .origin = -1, 113 | }; 114 | 115 | static inline pio_sm_config uart_rx_program_get_default_config(uint offset) { 116 | pio_sm_config c = pio_get_default_sm_config(); 117 | sm_config_set_wrap(&c, offset + uart_rx_wrap_target, offset + uart_rx_wrap); 118 | return c; 119 | } 120 | 121 | #include "hardware/gpio.h" 122 | #include "hardware/clocks.h" 123 | static inline void uart_rx_program_init(PIO pio, uint sm, uint offset, uint pin_rx, uint baud , bool invert) { 124 | //pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx); // was in Tx program but is normally not required for Rx 125 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 126 | //pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, false); // remove by ms 127 | pio_gpio_init(pio, pin_rx); 128 | if (invert) { 129 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 130 | gpio_pull_down(pin_rx); // changed by MS 131 | } else { 132 | gpio_pull_up(pin_rx); // changed by MS 133 | } 134 | pio_sm_config c = uart_rx_program_get_default_config(offset); 135 | sm_config_set_in_pins(&c, pin_rx); // for WAIT, IN 136 | sm_config_set_jmp_pin(&c, pin_rx); // for JMP 137 | // Shift to right, autopush disabled 138 | sm_config_set_in_shift(&c, true, false, 32); 139 | // Deeper FIFO as we're not doing any TX 140 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 141 | // SM transmits 1 bit per 8 execution cycles. 142 | float div = (float)clock_get_hz(clk_sys) / (8 * baud); 143 | sm_config_set_clkdiv(&c, div); 144 | pio_sm_init(pio, sm, offset, &c); 145 | pio_set_irq0_source_enabled(pio , pis_sm1_rx_fifo_not_empty , true ); // added by ms to get an irq int0 from pio 146 | pio_sm_set_enabled(pio, sm, true); 147 | } 148 | static inline void uart_rx_program_stop(PIO pio, uint sm, uint pin_rx) { 149 | pio_sm_set_enabled(pio, sm, false); // disable sm. 150 | } 151 | static inline void uart_rx_program_restart(PIO pio, uint sm, uint pin_rx , bool invert) { 152 | pio_sm_set_pindirs_with_mask(pio, sm, 0 , 1u << pin_rx); // set pin as input 153 | if (invert) { 154 | gpio_set_inover(pin_rx, GPIO_OVERRIDE_INVERT) ; // added by ms to manage inverted UART from Sport 155 | gpio_pull_down(pin_rx); // changed by MS 156 | } else { 157 | gpio_pull_up(pin_rx); // changed by MS 158 | } 159 | pio_sm_restart (pio, sm); // to test if we need an enable after this 160 | pio_sm_set_enabled(pio, sm, true); 161 | } 162 | /* 163 | static inline char uart_rx_program_getc(PIO pio, uint sm) { 164 | // 8-bit read from the uppermost byte of the FIFO, as data is left-justified 165 | io_rw_8 *rxfifo_shift = (io_rw_8*)&pio->rxf[sm] + 3; 166 | while (pio_sm_is_rx_fifo_empty(pio, sm)) 167 | tight_loop_contents(); 168 | return (char)*rxfifo_shift; 169 | } 170 | */ 171 | 172 | #endif 173 | 174 | -------------------------------------------------------------------------------- /test/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for PlatformIO Unit Testing and project tests. 3 | 4 | Unit Testing is a software testing method by which individual units of 5 | source code, sets of one or more MCU program modules together with associated 6 | control data, usage procedures, and operating procedures, are tested to 7 | determine whether they are fit for use. Unit testing finds problems early 8 | in the development cycle. 9 | 10 | More information about PlatformIO Unit Testing: 11 | - https://docs.platformio.org/page/plus/unit-testing.html 12 | -------------------------------------------------------------------------------- /uf2/APPLICATION.uf2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mstrens/expressLRS_relay/2a2561740dff4a22fb28fcef03236871c1247b25/uf2/APPLICATION.uf2 --------------------------------------------------------------------------------