├── GPSDO_breadboarda.jpg ├── LICENSE ├── OLEDv002i_expl.jpg ├── README.md ├── docs ├── DAC_resolution_discussion.txt ├── STM32 GPSDO - BOM.pdf ├── STM32_16bit_PWM_DAC.txt ├── USB_serial_output.txt ├── pictures │ ├── CTI_OCXO_bottom.jpg │ ├── CTI_OCXO_top.jpg │ ├── CTI_datasheet1.jpg │ └── ocxo_datasheet2.png ├── tab_delim_fields.txt └── utc_pps.txt ├── extra ├── BT_HC06_config.ino ├── GPS_Checker_With_Display_Mod.ino ├── eeprom_emulation_test_1a.ino ├── fptest_01.ino └── lcd_test_1a.ino ├── schematics └── GPSDO-KiCad.pdf └── software ├── GPSDO.ino ├── GPSDO_V006c ├── GPSDO_V006c.ino ├── GPSDO_algorithms.cpp └── GPSDO_algorithms.h └── WARNING.txt /GPSDO_breadboarda.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/GPSDO_breadboarda.jpg -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /OLEDv002i_expl.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/OLEDv002i_expl.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # An STM32 GPSDO 2 | Designing, assembling, programming and testing an ultra-low-cost GPS-disciplined oven controlled crystal oscillator / lab clock based on an STM32 32-bit ARM microcontroller 3 | 4 | Keywords: STM32, GPS, GPSDO, crystal oscillator, frequency standard, atomic clock 5 | 6 | André Balsa, April 2021 7 | 8 | The Project 9 | =========== 10 | 11 | I decided to build my own version of a 10MHz GPSDO with the following features: 12 | - Very low cost i.e. < 30 euros ($35), short and easily purchased BOM. 13 | - Acceptable performance (+/- 1ppb) "out of the box", can be fine tuned over time. 14 | - Uses an STM32F411CEU6 "Black Pill" microcontroller module, programmed in C/C++ using the Arduino IDE (STM32duino). 15 | - Requires only a 5V @ 1A power supply, supplied through a USB C cable. 16 | - Compact and portable. 17 | - Optionally battery powered (allows taking it outdoors for optimal satellite signal reception). 18 | - An optional suite of environmental sensors (temperature, humidity, air pressure, voltages, OCXO current/power consumption). 19 | - An optional Bluetooth serial interface for wireless communication with a PC. 20 | - Extensive logging of various operating parameters to allow further software tuning. 21 | - An optional small OLED displaying room temperature, UTC time, uptime, operating status, measured frequency. 22 | 23 | The first breadboard prototype: 24 | 25 | 26 | In normal operation this is displayed on the small OLED: 27 | 28 | -------------------------------------------------------------------------------- /docs/DAC_resolution_discussion.txt: -------------------------------------------------------------------------------- 1 | A quick discussion of noise, DAC resolution and OCXO frequency control 2 | ====================================================================== 3 | 4 | The STM32 GPSDO can use either an inexpensive 12-bit I2C DAC (MCP4725) module, or a couple of rc filters on one of the PWM pins of the STM32 MCU, to generate Vctl - the voltage used to control the frequency of the OCXO over a narrow range of 10MHz +/- a few Hz. The exact OCXO frequency provided by varying Vctl over a 0V - 4.4V range depends on the OCXO used as well as a number of different factors, but roughly speaking the precision of the OCXO frequency relative to a precise 10MHz is directly proportional to the precision with which we can set Vctl. 5 | 6 | That's for the theory. In practice, we have to contend with a ton of noise, specially on a circuit implemented on a breadboard and with voltage supplies coming from a laptop USB port or a cheap power brick. 7 | So from experience, I have determined that a 12-bit DAC used to control Vctl was good enough to control the OCXO frequency down to +/- 0.01Hz or 10E-9 or 1ppb which was my initial precision target for the STM32 GPSDO. 8 | 9 | Back to the theory, the GPS receiver when locked with a good fix provides a 1PPS with a maximum jitter of roughly 100ns - which also happens to be the period of our 10MHz OCXO. So a single OCXO frequency measurement sample timed by the 1PPS pulse from the GPS receiver has a maximum error of exactly 1Hz (again theoretically speaking). However the error from the 1PPS jitter "cancels out" over sequential measurements, so the maximum error over 10 sequential measurements (10 seconds) is 0.1Hz, over 100 sequential measurements (100 seconds) is 0.01Hz, etc. 10 | 11 | So in theory if we measure the OCXO frequency based on the 1PPS pulse over 1000 seconds (1000 sequential measurements), the maximum measurement error should be < 0.001Hz, or 10E-10 or 0.1ppb. That's exactly an order of magnitude better than what our 12-bit DAC is capable of. 12 | 13 | Using a 16-bit DAC provided by a PWM signal 14 | =========================================== 15 | 16 | The above reasoning led me to test a 16-bit DAC built by connecting a pair of rc filters to the PWM output of the STM32 MCU. Because the STM32 timers are 16-bit timers, we can with four lines of C obtain a 2kHz 16-bit PWM signal from the MCU, which is converted to a DC value (plus a ton of noise) and hence provides us with a 16-bit DAC, which we can use to control the OCXO Vctl. That's 16x more resolution than our 12-bit DAC can provide, at least in theory. 17 | 18 | So, in practice do we get an OCXO frequency control with a precision of 0.001Hz to match our 1000s maximum measurement error with such a setup? 19 | 20 | The anecdotal data I have collected so far seems to indicate that yes, we do. The STM32 GPSDO when calibrated and with an uptime of 10 hours or more often reports a stable frequency of 10000000.000Hz +/- 0.001Hz (see below). 21 | 22 | Of course I would need an even better clock to confirm to which degree these readings are correct, and I don't have access to such expensive equipment right now. 23 | 24 | Can we do even better? 25 | ====================== 26 | 27 | The question here is whether we could use a measurement period of 10,000 seconds and target a precision of 10E-11 or 0.01ppb for our STM32 GPSDO breadboard prototype, by either "dithering" the 16-bit PWM signal or mixing two 16-bit PWM signals with different amplitudes to increase the resolution of our software-based DAC by another 4 bits or so. 28 | 29 | To me, that's a moot point, for various reasons. 30 | 31 | As already mentioned, my initial precision target for the STM32 GPSDO project was 10E-9 (1ppb) and that was achieved with the 12-bit DAC. An order of magnitude better precision (10E-10) was also achieved apparently, by using a software based 16-bit DAC and 1000s measurement periods. 32 | 33 | For a DIY home project following the time-proven K.I.S.S. principle, costing less than $40 and assembled on a breadboard, these are more than good enough results. 34 | 35 | An anecdotal data point 36 | ======================= 37 | 38 | This is what the STM32 GPSDO reports either on USB serial or Bluetooth serial (but not both), once per second: 39 | 40 | Wait for GPS fix max. 1 second 41 | 42 | $GNGSA,A,3,31,25,12,18,02,29,20,,,,,,2.23,1.37,1.76*1E 43 | $GNGSA1,,86,49,215,*6B 44 | $GNGLL,4833.64512,N,00746.91322,E,092423.00,A,A*7F 45 | $GNRMC,092424.00,A,4833.64512,N,00746.91323,E,0.040,,070621,,,A*66 46 | $GNGGA,092424.00,4833.64512,N,00746.91323,E,1,06,1.88,147.8,M,47.3,M,,*41 47 | 48 | 49 | Fix time 884mS 50 | Uptime: 000d 12:41:36 51 | New GPS Fix: 52 | Lat: 48.560753 Lon: 7.781887 Alt: 147.8m 53 | Sats: 6 HDOP: 1.88 54 | UTC Time: 09:24:24 Date: 7/6/2021 55 | 56 | Voltages: 57 | Vctl: 1.97 DAC: 2402 58 | VctlPWM: 1.78 PWM: 35546 59 | Vcc: 5.06 60 | Vdd: 3.29 61 | 62 | Frequency measurements using 64-bit counter: 63 | 64-bit Counter: 435387151170 64 | Frequency: 9999999 Hz 65 | 10s Frequency Avg: 9999999.9 Hz 66 | 100s Frequency Avg: 9999999.99 Hz 67 | 1,000s Frequency Avg: 9999999.999 Hz 68 | 10,000s Frequency Avg: 0.0000 Hz 69 | 70 | BMP280 Temperature = 25.3 *C 71 | Pressure = 1021.0 hPa 72 | Approx altitude = 48.9 m 73 | AHT10 Temperature: 22.15 *C 74 | Humidity: 77.75% rH 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/STM32 GPSDO - BOM.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/docs/STM32 GPSDO - BOM.pdf -------------------------------------------------------------------------------- /docs/STM32_16bit_PWM_DAC.txt: -------------------------------------------------------------------------------- 1 | Notes on using a software 16-bit PWM DAC instead of an external 12-bit I2C DAC 2 | ============================================================================== 3 | 4 | To generate Vctl, the analog voltage that control the OCXO frequency, the STM32 GPSDO 5 | uses either a $0.50 MCP4725 I2C 12-bit DAC module or a pair of rc filters (2 x r=20k, 6 | 2 x c=10uF) connected to a 16-bit, 2kHz PWM output pin on the STM32F411CEU6. 7 | 8 | Only 4 lines of C are required to generate this 2kHz PWM signal: 9 | // generate a test 2kHz square wave on PB9 PWM pin, using Timer 4 channel 4 10 | // PB9 is Timer 4 Channel 4 from Arduino_Core_STM32/variants/STM32F4xx/F411C(C-E)(U-Y)/PeripheralPins_BLACKPILL_F411CE.c 11 | analogWrite(PB9, 127); // configures PB9 as PWM output pin at default frequency (1kHz) and resolution (8 bits), 50% duty cycle 12 | analogWriteFrequency(2000); // default PWM frequency is 1kHz, change it to 2kHz 13 | analogWriteResolution(16); // set PWM resolution to 16 bits, default is 8 bits 14 | analogWrite(PB9, 32767); // 32767 for 16 bits -> 50% duty cycle so a square wave 15 | 16 | Initially I was worried that the software 16-bit PWM DAC would not provide a clean Vctl to 17 | precisely control the OCXO frequency, but after extensive testing I now believe it is a better 18 | solution than the external MCP4725 12-bit I2C DAC module. 19 | 20 | With the MCP4725 12-bit DAC the STM32 GPSDO stabilizes the OCXO frequency within +/- 1ppb 21 | (that is +/- 0.01Hz). 22 | But with the 16-bit PWM software DAC, the STM32 GPSDO manages to stabilize the OCXO frequency 23 | within +/- 0.1ppb (a stable and accurate 10MHz +/- 0.001Hz), which is an order of magnitude 24 | better and rather good performance considering the cost and simplicity of the hardware. 25 | -------------------------------------------------------------------------------- /docs/USB_serial_output.txt: -------------------------------------------------------------------------------- 1 | Wait GPS Fix 5 seconds 2 | 3 | 4 | Fix time 797mS 5 | Uptime 000d 00:01:45 6 | New GPS Fix Lat,48.~~~~~~,Lon,7.~~~~~~,Alt,181.1m,Sats,6,HDOP,3.82,Time,16:26:56,Date,17/5/2021 7 | 8 | Vctl: 1.88 DAC: 2382 9 | Vcc: 4.94 10 | Vdd: 3.29 11 | OCXO voltage: 4.97V 12 | OCXO current: 149mA 13 | 14 | Counter: 1032571013 Frequency: 10000000 Hz 15 | 10s Frequency Avg: 10000000.0 Hz 16 | 100s Frequency Avg: 10000000.02 Hz 17 | BMP280 Temperature = 19.4 *C 18 | Pressure = 1010.0 hPa 19 | Approx altitude = 140.9 m 20 | AHT10 Temperature: 19.59 *C 21 | Humidity: 68.37% rH 22 | 23 | -------------------------------------------------------------------------------- /docs/pictures/CTI_OCXO_bottom.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/docs/pictures/CTI_OCXO_bottom.jpg -------------------------------------------------------------------------------- /docs/pictures/CTI_OCXO_top.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/docs/pictures/CTI_OCXO_top.jpg -------------------------------------------------------------------------------- /docs/pictures/CTI_datasheet1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/docs/pictures/CTI_datasheet1.jpg -------------------------------------------------------------------------------- /docs/pictures/ocxo_datasheet2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/docs/pictures/ocxo_datasheet2.png -------------------------------------------------------------------------------- /docs/tab_delim_fields.txt: -------------------------------------------------------------------------------- 1 | STM32 GPSDO reporting tab delimited fields 2 | 3 | Line no. (0 if no position fix, increments by one each second if position fix) 4 | timestamp (UTC) 5 | uptime (days hours mins secs) 6 | 64-bit count 7 | frequency (Hz) 8 | 10s freq. avg. (one decimal) (Hz) 9 | 100s freq. avg. (two decimals) (Hz) 10 | 1,000s freq. avg. (three decimals) (Hz) 11 | 10,000s freq. avg. (four decimals) (Hz) 12 | no. of sats 13 | HDOP (meters) 14 | PWM (16-bit, 1-65535) 15 | PWM adc mov. avg. (V) 16 | Vcc adc mov. avg. (5.0V nominal) 17 | Vdd adc mov. avg. (3.3V nominal) 18 | BMP280 Temp. (C) 19 | BMP280 Atm. Pressure (hPa) 20 | AHT20 Temp. (C) 21 | AHT20 Humidity (%) 22 | INA219 OCXO Voltage (5.05V nominal) 23 | INA219 OCXO Current (mA, 2A maximum) 24 | TIC (10-bit, 1024ns max) 25 | 26 | When a value is not available, field contains "0". 27 | -------------------------------------------------------------------------------- /docs/utc_pps.txt: -------------------------------------------------------------------------------- 1 | Achieving a UTC-synchronized PPS using a picDIV, Lars' 1ns resolution TIC and the STM32 GPSDO 2 | ============================================================================================= 3 | 4 | By André Derrick Balsa, March 2022 - v0.2 5 | 6 | The following documentation is part of the STM32 GPSDO documentation and covered by the same GPL V3 license. 7 | 8 | Introduction 9 | ------------ 10 | 11 | The purpose of this short paper is to examine the hardware and method/algorithm to obtain a UTC synchronized PPS (pulse per second) (within x nanoseconds, where x would be preferably < 50), given some very simple hardware, namely: 12 | 13 | - A picDIV (see http://www.leapsecond.com/pic/picdiv.htm), which is a PIC MCU programmed to divide by 10,000,000. The picDIV is an invention by Tom Van Baak. 14 | 15 | - An extremely simple 1ns resolution TIC design by Lars Walenius, slightly modified. The original 1ns resolution TIC circuit and explanations by Lars Walenius can be found here: https://github.com/AndrewBCN/Lars-DIY-GPSDO 16 | 17 | - An STM32 GPSDO: a very simple FLL-based GPS disciplined oscillator that uses a readily available STM32F411 ARM development board, designed and programmed by the author. See https://github.com/AndrewBCN/STM32-GPSDO 18 | 19 | Why a UTC-synchronized PPS? 20 | --------------------------- 21 | 22 | The question immediately arises when one has a very precise clock in a lab, computing center or other facility on how to get it synchronized to a global network of very precise ("atomic") clocks. It is not very useful to have a clock accurate to within 1µs per year if that same clock is off by a few ms or even tens of seconds from UTC. 23 | 24 | A portable UTC-synchronized PPS generator is probably one of the simplest ways to synchronize a precision clock with UTC. 25 | 26 | Another possible use for a portable UTC-synchronized PPS generator would be to periodically measure the accuracy of a clock that is not permanently connected to a network of other precision clocks. 27 | 28 | How it works - the picDIV 29 | ------------------------- 30 | 31 | The picDIV is used to generate the UTC-synchronized PPS signal. 32 | 33 | Here is the pinout of the picDIV (from Tom Van Baak's source code documentation): 34 | 35 | ---__--- 36 | 5V (Vdd) +++++|1 8|===== Ground (Vss) 37 | 10 MHz clock in ---->|2 pD 7|----> 1PPS out (100 us) 38 | 1PPS (10 ms) out <----|3 11 6|----> 1 Hz out (50%) 39 | Arm o--->|4 5|<+--- Sync 40 | -------- 41 | Notes: 42 | 43 | o External pull-up required on Arm input (pin4/GP3). 44 | + Sync input (pin5/GP2) has internal WPU. 45 | Output frequency accuracy is the same as clock input accuracy. 46 | Output drive current is 25 mA maximum per pin. 47 | Coded for Microchip 12F675 but any '609 '615 '629 '635 '675 '683 works. 48 | 49 | The 10MHz clock input is driven by the 10MHz OCXO in the STM32 GPSDO circuit. The rising edge of either of the PPS outputs (pins 3 and 7) is almost synchronous with the rising edge of the 10MHz clock input (there is the small and fixed propagation delay of the picDIV). So either of the PPS outputs (pins 3 and 7) can be used as our UTC-synchronized PPS. 50 | 51 | But how exactly do we synchronize the picDIV output with UTC? This is where Lars' 1ns resolution TIC and the STM32 MCU come into play. Notice the "Arm" and "Sync" inputs in the picDIV? The "Arm" input is connected to one of the GPIO pins of the STM32 MCU, and the "Sync" input is connected to the 1PPS from the GPS module. 52 | 53 | How it works - Lars' 1ns resolution TIC 54 | --------------------------------------- 55 | 56 | TIC stands for Time Interval Counter, in other words it's a circuit that measures very small time intervals, in this case we will be measuring a 1µs maximum time interval with a (theoretical) resolution of 1ns. 57 | 58 | Essentially Lars' TIC is a "black box" with two digital inputs and one analog output. The two digital inputs are wired to the GPS module 1PPS output and the picDIV 1PPS (100µs) output. The analog output is connected to one of the 12-bit ADC channels of our STM32 MCU. 59 | 60 | The analog output varies almost linearly between 0 and a maximum voltage (e.g. 3.3V) proportional to the phase difference between the rising edges of the two digital inputs. If the two digital inputs are perfectly in phase, the analog output is zero. If the phase difference is 500ns, the output voltage should be the maximum voltage divided by 2 (e.g. 1.65V), and if the phase difference is >= 1000ns (1µs) the output voltage should be the maximum (e.g. 3.3V). 61 | 62 | The theoretical resolution of Lars' TIC in his original circuit is approximately 1ns, and since we are using a 2-bit higher resolution ADC in the STM32, we could claim a 250ps resolution, but in practice, because of noise, jitter, non-linearities, temperature effects and other factors, the actual resolution is on the order of 25~30ns. Since we are aiming for 50ns synchronization, this is quite acceptable. 63 | 64 | How it works - the STM32 MCU "closes the loop" 65 | ---------------------------------------------- 66 | 67 | In the STM32 GPSDO, the STM32F411 MCU generates a 16-bit PWM voltage Vctl that is connected to the frequency control pin of the OCXO. In normal GPSDO operation, Vctl is the final step in closing the Frequency Locked Loop (FLL) that keeps the OCXO frequency at an exact 10MHz +/-1ppb or better. 68 | 69 | However, we can also use Vctl to "close the loop" and adjust the phase of our picDIV 1PPS output. This is done in four steps: 70 | 1. First, we must arm and synchronize the picDIV. To do that, the picDIV "Arm" pin is pulled low by the MCU for one second, and the next PPS pulse rising edge from the GPS module will synchronize the picDIV PPS output within 1µs. 71 | 2. Second, we do the fine syncing: once per second, we measure the analog output of the TIC and if the measured voltage is larger than some preset floor (e.g 50mV), we slightly bump the frequency of the OCXO. This has the effect of progressively decreasing the phase difference / time interval measured by our TIC. 72 | 3. Third, once we reach a measured time interval under 50ns, we can dial down Vctl again. 73 | 4. Fourth and last, we periodically measure the TIC output and apply our feedback to Vctl if needed. 74 | 75 | The net effect of this algorithm is to synchronize the 1PPS from the picDIV with the 1PPS from the GPS module (which is itself within a few ns of GPS/UTC time) within a predetermined window, which we have set arbitrarily at 50ns. 76 | 77 | Conclusion 78 | __________ 79 | 80 | We have described above how to combine a PLL loop to control phase and an FLL loop to control frequency, both implemented using inexpensive and readily available hardware. This hybrid FLL/PLL control method gives us a stable and accurate 10MHz signal and a UTC-synchronized 1PPS signal within reasonable margins. 81 | -------------------------------------------------------------------------------- /extra/BT_HC06_config.ino: -------------------------------------------------------------------------------- 1 | // Very short program just used to configure HC-06 Bluetooth modules 2 | // for name and baud rate, using AT commands 3 | HardwareSerial Serial2(PA3, PA2); // Serial to Bluetooth module 4 | 5 | 6 | void setup() { 7 | // put your setup code here, to run once: 8 | Serial1.begin(9600); // serial to GPS module 9 | Serial2.begin(115200); // serial to Bluetooth module 10 | 11 | Serial.begin(115200); // USB serial 12 | 13 | Serial.print(F("Check HC-06 module version, set baud rate to 115200 and rename to GPSDO1")); 14 | Serial.println(); 15 | // check module version 16 | Serial2.println("AT+VERSION"); // module should answer with HC06 version 17 | delay(1500); 18 | if (Serial2.available()) Serial.println("Response="+Serial2.readString()); 19 | // change BT module name 20 | Serial2.println("AT+NAMEGPSDO1"); // change 1 to 2 or 3 or etc 21 | delay(1500); 22 | if (Serial2.available()) Serial.println("Response="+Serial2.readString()); 23 | // Change BT module baud rate (default is 9600) 24 | // Serial2.println("AT+BAUD8"); // 8=115200 25 | // delay(1500); 26 | // if (Serial2.available()) Serial.println("Response="+Serial2.readString()); 27 | } 28 | 29 | void loop() { 30 | // put your main code here, to run repeatedly: 31 | Serial.println("Done setting HC06, turn off development board now"); 32 | delay(5000); 33 | } 34 | -------------------------------------------------------------------------------- /extra/GPS_Checker_With_Display_Mod.ino: -------------------------------------------------------------------------------- 1 | /******************************************************************************************************* 2 | GPS Checker for u-Blox Neo-M8 receiver 3 | Original code by Stuart Robinson 4 | UBX command sending based on code by Brad Burleson 5 | Repurposed and refactored by André Balsa, June 2021 6 | 7 | This program is supplied as is, it is up to the user of the program to decide if the program is 8 | suitable for the intended purpose and free from errors. 9 | *******************************************************************************************************/ 10 | 11 | // GPS Checker with I2C SSD1306 display, Hardware Serial on STM32 MCU, u-Blox Neo-M8 GPS receiver 12 | 13 | /******************************************************************************************************* 14 | Program Operation - This program is a portable GPS checker with display option. It uses an SSD1306 or 15 | SH1106 128x64 I2C OLED display. It reads the GPS for 5 seconds and copies the characters from the GPS 16 | to the serial monitor, this is an example printout from a working GPS that has just been powered on: 17 | 18 | Wait GPS Fix 5 seconds 19 | 20 | $GNGSA,A,3,32,08,14,,,,,,,,,,1.98,1.06,1.67*17 21 | $GNGSA,A,3,88,81,87,,,,,,,,,,1.98,1.06,1.67*1D 22 | $GPGSV,4,1,14,01,85,030,,03,61,253,19,04,16,188,,08,18,173,19*70 23 | $GPGSV,4,2,14,14,13,269,12,17,35,309,,19,13,321,14,21,67,115,*71 24 | $GPGSV,4,3,14,22,86,009,,28,17,287,,31,07,104,,32,24,046,27*7D 25 | $GPGSV,4,4,14,36,30,150,,49,34,184,*79 26 | $GLGSV,3,1,09,65,69,045,22,66,43,213,,72,22,039,,73,07,012,*6B 27 | $GLGSV,3,2,09,80,05,326,,81,52,322,13,82,04,320,,87,27,139,24*60 28 | $GLGSV,3,3,09,88,70,136,30*5C 29 | $GNGLL,4833.64651,N,00746.91564,E,171944.00,A,A*7F 30 | $GNRMC,171945.00,A,4833.64644,N,00746.91603,E,1.298,,060621,,,A*60 31 | $GNVTG,,T,,M,1.298,N,2.403,K,A*3A 32 | $GNGGA,171945.00,4833.64644,N,00746.91603,E,1,05,1.17,139.2,M,47.3,M,,*46 33 | 34 | 35 | Fix time 918mS 36 | New GPS Fix Lat,48.560776,Lon,7.781934,Alt,139.2m,Sats,5,HDOP,1.17,Time,17:19:45,Date,6/6/2021 37 | 38 | The printout is from a u-Blox Neo M8 receiver. The data from the GPS is also fed into 39 | the TinyGPS++ library and if there is no fix a message is printed on the serial monitor. 40 | 41 | During setup the GPS receiver is reconfigured in stationary mode and with a higher baud rate. 42 | When the program detects that the GPS has a fix, it prints the Latitude, Longitude, Altitude, Number 43 | of satellites in use, the HDOP value, time and date to the serial monitor. If the I2C OLED display is 44 | attached that is updated as well. Display is assumed to be on I2C address 0x3C. 45 | 46 | Serial monitor baud rate is set at 115200. 47 | *******************************************************************************************************/ 48 | 49 | #define Program_Version "V0.03" 50 | 51 | #include //get library here > http://arduiniana.org/libraries/tinygpsplus/ 52 | TinyGPSPlus gps; //create the TinyGPS++ object 53 | 54 | #include // I2C 55 | 56 | #include //get library here > https://github.com/olikraus/u8g2 57 | U8X8_SSD1306_128X64_NONAME_HW_I2C disp(U8X8_PIN_NONE); //use this line for standard 0.96" SSD1306 58 | 59 | float GPSLat; //Latitude from GPS 60 | float GPSLon; //Longitude from GPS 61 | float GPSAlt; //Altitude from GPS 62 | uint8_t GPSSats; //number of GPS satellites in use 63 | uint32_t GPSHdop; //HDOP from GPS 64 | uint8_t hours, mins, secs, day, month; 65 | uint16_t year; 66 | uint32_t startGetFixmS; 67 | uint32_t endFixmS; 68 | 69 | void loop() 70 | { 71 | if (gpsWaitFix(5)) // wait 5 seconds for fix 72 | { 73 | Serial.println(); 74 | Serial.println(); 75 | Serial.print(F("Fix time ")); 76 | Serial.print(endFixmS - startGetFixmS); 77 | Serial.println(F("mS")); 78 | 79 | GPSLat = gps.location.lat(); 80 | GPSLon = gps.location.lng(); 81 | GPSAlt = gps.altitude.meters(); 82 | GPSSats = gps.satellites.value(); 83 | GPSHdop = gps.hdop.value(); 84 | 85 | hours = gps.time.hour(); 86 | mins = gps.time.minute(); 87 | secs = gps.time.second(); 88 | day = gps.date.day(); 89 | month = gps.date.month(); 90 | year = gps.date.year(); 91 | 92 | printGPSfix(); 93 | displayscreen1(); 94 | startGetFixmS = millis(); //have a fix, next thing that happens is checking for a fix, so restart timer 95 | } 96 | else 97 | { 98 | disp.clearLine(0); 99 | disp.setCursor(0, 0); 100 | disp.print(F("No GPS Fix ")); 101 | disp.print( (millis() - startGetFixmS) / 1000 ); 102 | Serial.println(); 103 | Serial.println(); 104 | Serial.print(F("Timeout - No GPS Fix ")); 105 | Serial.print( (millis() - startGetFixmS) / 1000 ); 106 | Serial.println(F("s")); 107 | } 108 | } 109 | 110 | 111 | bool gpsWaitFix(uint16_t waitSecs) 112 | { 113 | //waits a specified number of seconds for a fix, returns true for good fix 114 | 115 | uint32_t endwaitmS; 116 | uint8_t GPSchar; 117 | 118 | Serial.print(F("Wait GPS Fix ")); 119 | Serial.print(waitSecs); 120 | Serial.println(F(" seconds")); 121 | 122 | endwaitmS = millis() + (waitSecs * 1000); 123 | 124 | while (millis() < endwaitmS) 125 | { 126 | if (Serial1.available() > 0) 127 | { 128 | GPSchar = Serial1.read(); 129 | gps.encode(GPSchar); 130 | Serial.write(GPSchar); 131 | } 132 | 133 | if (gps.location.isUpdated() && gps.altitude.isUpdated() && gps.date.isUpdated()) 134 | { 135 | endFixmS = millis(); //record the time when we got a GPS fix 136 | return true; 137 | } 138 | } 139 | 140 | return false; 141 | } 142 | 143 | 144 | void printGPSfix() 145 | { 146 | float tempfloat; 147 | 148 | Serial.print(F("New GPS Fix ")); 149 | 150 | tempfloat = ( (float) GPSHdop / 100); 151 | 152 | Serial.print(F("Lat,")); 153 | Serial.print(GPSLat, 6); 154 | Serial.print(F(",Lon,")); 155 | Serial.print(GPSLon, 6); 156 | Serial.print(F(",Alt,")); 157 | Serial.print(GPSAlt, 1); 158 | Serial.print(F("m,Sats,")); 159 | Serial.print(GPSSats); 160 | Serial.print(F(",HDOP,")); 161 | Serial.print(tempfloat, 2); 162 | Serial.print(F(",Time,")); 163 | 164 | if (hours < 10) 165 | { 166 | Serial.print(F("0")); 167 | } 168 | 169 | Serial.print(hours); 170 | Serial.print(F(":")); 171 | 172 | if (mins < 10) 173 | { 174 | Serial.print(F("0")); 175 | } 176 | 177 | Serial.print(mins); 178 | Serial.print(F(":")); 179 | 180 | if (secs < 10) 181 | { 182 | Serial.print(F("0")); 183 | } 184 | 185 | Serial.print(secs); 186 | Serial.print(F(",Date,")); 187 | 188 | Serial.print(day); 189 | Serial.print(F("/")); 190 | Serial.print(month); 191 | Serial.print(F("/")); 192 | Serial.print(year); 193 | 194 | Serial.println(); 195 | Serial.println(); 196 | } 197 | 198 | 199 | void displayscreen1() 200 | { 201 | //show GPS data on display 202 | float tempfloat; 203 | tempfloat = ( (float) GPSHdop / 100); 204 | 205 | disp.clearLine(0); 206 | disp.clearLine(1); 207 | disp.setCursor(0, 1); 208 | disp.print(GPSLat, 6); 209 | disp.clearLine(2); 210 | disp.setCursor(0, 2); 211 | disp.print(GPSLon, 6); 212 | disp.clearLine(3); 213 | disp.setCursor(0, 3); 214 | disp.print(GPSAlt); 215 | disp.print(F("m")); 216 | disp.clearLine(4); 217 | disp.setCursor(0, 4); 218 | disp.print(F("Sats ")); 219 | disp.print(GPSSats); 220 | disp.clearLine(5); 221 | disp.setCursor(0, 5); 222 | disp.print(F("HDOP ")); 223 | disp.print(tempfloat); 224 | 225 | disp.clearLine(6); 226 | disp.setCursor(0, 6); 227 | 228 | if (hours < 10) 229 | { 230 | disp.print(F("0")); 231 | } 232 | 233 | disp.print(hours); 234 | disp.print(F(":")); 235 | 236 | if (mins < 10) 237 | { 238 | disp.print(F("0")); 239 | } 240 | 241 | disp.print(mins); 242 | disp.print(F(":")); 243 | 244 | if (secs < 10) 245 | { 246 | disp.print(F("0")); 247 | } 248 | 249 | disp.print(secs); 250 | disp.print(F(" ")); 251 | 252 | disp.clearLine(7); 253 | disp.setCursor(0, 7); 254 | 255 | disp.print(day); 256 | disp.print(F("/")); 257 | disp.print(month); 258 | disp.print(F("/")); 259 | disp.print(year); 260 | } 261 | 262 | void setup() 263 | { 264 | 265 | Serial1.begin(9600); // serial to GPS module 266 | Serial.begin(115200); // USB serial 267 | // Reconfigure the GPS receiver 268 | // first send the $PUBX configuration commands 269 | delay(5000); // give everything a moment to stabilize 270 | Serial.println("GPS checker program started"); 271 | Serial.println("Sending $PUBX commands to GPS"); 272 | Serial1.print("$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n"); // disable all VTG messages (useless since we are stationary) 273 | Serial1.print("$PUBX,41,1,0003,0003,38400,0*24\r\n"); // set GPS baud rate to 38400 in/out protocols NMEA+UBX 274 | Serial1.flush(); // empty the buffer 275 | delay(100); // give it a moment 276 | Serial1.end(); // close serial port 277 | Serial1.begin(38400); // re-open at new rate 278 | delay(5000); 279 | // second, send the proprietary UBX configuration commands 280 | Serial.println("Now sending UBX commands to GPS"); 281 | ubxconfig(); 282 | 283 | Serial.println(); 284 | Serial.print(F(__TIME__)); 285 | Serial.print(F(" ")); 286 | Serial.println(F(__DATE__)); 287 | Serial.println(F(Program_Version)); 288 | Serial.println(); 289 | 290 | disp.begin(); 291 | disp.setFont(u8x8_font_chroma48medium8_r); 292 | disp.clear(); 293 | disp.setCursor(0, 0); 294 | disp.print(F("Display Ready")); 295 | 296 | Serial.println(F("29_GPS_Checker_Display Starting")); 297 | Serial.println(); 298 | 299 | startGetFixmS = millis(); 300 | } 301 | 302 | void ubxconfig() // based on code by Brad Burleson 303 | { 304 | // send UBX commands to set optimal configuration for GPSDO use 305 | // we are going to change a single parameter from default by 306 | // setting the navigation mode to "stationary" 307 | 308 | bool gps_set_success = false; // flag setting GPS configuration success 309 | 310 | // This UBX command sets stationary mode and confirms it 311 | Serial.println("Setting u-Blox M8 receiver navigation mode to stationary: "); 312 | uint8_t setNav[] = { 313 | 0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x53}; 314 | while(!gps_set_success) 315 | { 316 | sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t)); 317 | Serial.println(); 318 | Serial.println("UBX command sent, waiting for UBX ACK... "); 319 | gps_set_success=getUBX_ACK(setNav); 320 | if (gps_set_success) 321 | Serial.println("Success: UBX ACK received! "); 322 | else 323 | Serial.println("Oops, something went wrong here... "); 324 | } 325 | } 326 | 327 | // Send a byte array of UBX protocol to the GPS 328 | void sendUBX(uint8_t *MSG, uint8_t len) { 329 | for(int i=0; i 9) { 366 | // All packets in order! 367 | Serial.println(" (SUCCESS!)"); 368 | return true; 369 | } 370 | 371 | // Timeout if no valid response in 3 seconds 372 | if (millis() - startTime > 3000) { 373 | Serial.println(" (FAILED!)"); 374 | return false; 375 | } 376 | 377 | // Make sure data is available to read 378 | if (Serial1.available()) { 379 | b = Serial1.read(); 380 | 381 | // Check that bytes arrive in sequence as per expected ACK packet 382 | if (b == ackPacket[ackByteID]) { 383 | ackByteID++; 384 | Serial.print(b, HEX); 385 | } 386 | else { 387 | ackByteID = 0; // Reset and look again, invalid order 388 | } 389 | 390 | } 391 | } 392 | } 393 | -------------------------------------------------------------------------------- /extra/eeprom_emulation_test_1a.ino: -------------------------------------------------------------------------------- 1 | // eeprom_emulation_test_1a 2 | // by André Derrick Balsa (AndrewBCN) 3 | // April 2022 4 | // GPLV3 5 | // Testing STM32duino EEPROM emulation library (emulates EEPROM in Flash) 6 | 7 | #if !defined(STM32_CORE_VERSION) || (STM32_CORE_VERSION < 0x02020000) 8 | #error "Due to API changes, this sketch is compatible with STM32_CORE_VERSION >= 0x02020000 (2.2.0 or later)" 9 | #endif 10 | 11 | // Increase HardwareSerial (UART) TX and RX buffer sizes from default 64 characters to 256. 12 | // The main worry here is that we could miss some characters from the u-blox GPS module if 13 | // the processor is busy doing something else (e.g. updating the display, reading a sensor, etc) 14 | // specially since we increase the GPS baud rate from 9600 to 38400. 15 | 16 | #define SERIAL_TX_BUFFER_SIZE 256 // Warning: > 256 could cause problems, see comments in STM32 HardwareSerial library 17 | #define SERIAL_RX_BUFFER_SIZE 256 18 | 19 | #define GPSDO_GEN_2kHz_PB5 // generate 2kHz square wave test signal on pin PB5 using Timer 3 20 | #define GPSDO_EEPROM // enable STM32 buffered EEPROM emulation library 21 | 22 | #ifdef GPSDO_GEN_2kHz_PB5 23 | #define Test2kHzOutputPin PB5 // digital output pin used to output a test 2kHz square wave 24 | #endif // GEN_2kHz_PB5 25 | 26 | // EEPROM emulation in flash 27 | #ifdef GPSDO_EEPROM 28 | #include // Buffered EEPROM emulation library 29 | #define DATA_LENGTH E2END 30 | const uint32_t eepromsize = DATA_LENGTH; 31 | #endif // EEPROM 32 | 33 | char signature[6] = "STM32"; 34 | bool sigalreadywritten = true; 35 | 36 | // LEDs 37 | // Blue onboard LED blinks to indicate ISR is working 38 | #define blueledpin PC13 // Blue onboard LED is on PC13 on STM32F411CEU6 Black Pill 39 | 40 | // Uptime data 41 | volatile uint8_t uphours = 0; 42 | volatile uint8_t upminutes = 0; 43 | volatile uint8_t upseconds = 0; 44 | volatile uint16_t updays = 0; 45 | volatile bool halfsecond = false; 46 | char uptimestr[9] = "00:00:00"; // uptime string 47 | char updaysstr[5] = "000d"; // updays string 48 | 49 | // Interrupt Service Routine for the 2Hz timer 50 | void Timer_ISR_2Hz(void) { // WARNING! Do not attempt I2C communication inside the ISR 51 | 52 | // Toggle pin. 2hz toogle --> 1Hz pulse, perfect 50% duty cycle 53 | digitalWrite(blueledpin, !digitalRead(blueledpin)); 54 | 55 | halfsecond = !halfsecond; // true @ 1Hz 56 | 57 | // Uptime clock - in days, hours, minutes, seconds 58 | if (halfsecond) 59 | { 60 | if (++upseconds > 59) 61 | { 62 | upseconds = 0; 63 | if (++upminutes > 59) 64 | { 65 | upminutes = 0; 66 | if (++uphours > 23) 67 | { 68 | uphours = 0; 69 | ++updays; 70 | } 71 | } 72 | } 73 | } 74 | } // end of 2Hz ISR 75 | 76 | void uptimetostrings() { 77 | // translate uptime variables to strings 78 | uptimestr[0] = '0' + uphours / 10; 79 | uptimestr[1] = '0' + uphours % 10; 80 | uptimestr[3] = '0' + upminutes / 10; 81 | uptimestr[4] = '0' + upminutes % 10; 82 | uptimestr[6] = '0' + upseconds / 10; 83 | uptimestr[7] = '0' + upseconds % 10; 84 | 85 | if (updays > 99) { // 100 days or more 86 | updaysstr[0] = '0' + updays / 100; 87 | updaysstr[1] = '0' + (updays % 100) / 10; 88 | updaysstr[2] = '0' + (updays % 100) % 10; 89 | } 90 | else { // less than 100 days 91 | updaysstr[0] = '0'; 92 | updaysstr[1] = '0' + updays / 10; 93 | updaysstr[2] = '0' + updays % 10; 94 | } 95 | } 96 | 97 | void setup() { 98 | // Wait 1 second for things to stabilize 99 | delay(1000); 100 | 101 | // setup USB serial 102 | Serial.begin(9600); 103 | Serial.println(F("EEPROM library test")); 104 | 105 | // configure blueledpin in output mode 106 | pinMode(blueledpin, OUTPUT); 107 | 108 | // setup 2kHz test signal on PB5 if configured, uses Timer 3 109 | #ifdef GPSDO_GEN_2kHz_PB5 // note this uses Timer 3 Channel 2 110 | analogWrite(Test2kHzOutputPin, 127); // configures PB5 as PWM output pin at default frequency and resolution 111 | analogWriteFrequency(2000); // default PWM frequency is 1kHz, change it to 2kHz 112 | analogWriteResolution(16); // default PWM resolution is 8 bits, change it to 16 bits 113 | analogWrite(Test2kHzOutputPin, 32767); // 32767 for 16 bits -> 50% duty cycle so a square wave 114 | #endif // GEN_2kHz_PB5 115 | 116 | // setup 2Hz timer and interrupt, uses Timer 9 117 | HardwareTimer *tim2Hz = new HardwareTimer(TIM9); 118 | tim2Hz->setOverflow(2, HERTZ_FORMAT); // 2 Hz 119 | tim2Hz->attachInterrupt(Timer_ISR_2Hz); 120 | tim2Hz->resume(); 121 | 122 | delay(1000); 123 | 124 | } // setup done 125 | 126 | void loop() { 127 | // print something once per second to USB serial (Arduino monitor) 128 | uint32_t i = 0; 129 | 130 | uptimetostrings(); // get updaysstr and uptimestr 131 | Serial.print(F("Uptime: ")); 132 | Serial.print(updaysstr); 133 | Serial.print(F(" ")); 134 | Serial.println(uptimestr); 135 | 136 | delay(1000); 137 | 138 | for (i = 0; i < 6; i++) { 139 | Serial.print(signature[i]); 140 | } 141 | Serial.println(); 142 | 143 | eeprom_buffer_fill(); // fill the buffer with contents of Flash emulating EEPROM 144 | 145 | Serial.print(F("EEPROM size: ")); 146 | Serial.println(eepromsize); 147 | 148 | sigalreadywritten = true; 149 | for (i = 0; i < 6; i++) { 150 | if (eeprom_buffered_read_byte(i) != signature[i]) sigalreadywritten = false; 151 | Serial.println(eeprom_buffered_read_byte(i)); 152 | delay(500); 153 | } 154 | 155 | uint32_t writetime = millis(); 156 | 157 | if (sigalreadywritten) { 158 | Serial.println(F("Signature already written, skipping EEPROM buffer flush")); 159 | } 160 | else { 161 | for (i = 0; i < 6; i++) { 162 | eeprom_buffered_write_byte(i, signature[i]); // write signature to buffer 163 | } 164 | eeprom_buffer_flush(); // and flush buffer 165 | } 166 | 167 | Serial.print(F("Write time: ")); // printout how long it took to flush the buffer 168 | Serial.print(millis() - writetime); 169 | Serial.println(F("ms")); 170 | } 171 | -------------------------------------------------------------------------------- /extra/fptest_01.ino: -------------------------------------------------------------------------------- 1 | /* Floating point math test on the STM32F411CEU6 2 | * The following code tests for rounding errors / weird floating point math 3 | * that could potentiallycause wrong results in the actual STM32 GPSDO code. 4 | * The code below is very similar to the actual code used to calculate 5 | * floating point frequency averages from the data in the ring buffers. 6 | * So, do I need to worry? 7 | * Here are the results printed to serial monitor: 8 | Floating point on STM32, precision test 9 | One decimal test 10 | 10000000.3 11 | Two decimals test 12 | 10000000.23 13 | Three decimals test 14 | 10000000.123 15 | Four decimals test 16 | 10000000.1234 17 | ... (repeated every 5 s) 18 | * 19 | * Conclusion: no, I don't need to worry! :) 20 | */ 21 | 22 | // Some global variables 23 | double dbten=0, dbhun=0, dbtho=0, dbtth=0; 24 | 25 | void setup() { 26 | Serial.begin(115200); // results are printed on the serial monitor 27 | } 28 | 29 | void loop() { 30 | Serial.println(F("Floating point on STM32, precision test")); 31 | 32 | // One decimal 33 | uint64_t x1 = 200000123; 34 | uint64_t x2 = 100000120; 35 | dbten = double(x1 - x2) / 10.0; 36 | Serial.println(F("One decimal test")); 37 | Serial.println(dbten, 1); 38 | 39 | // Two decimals 40 | uint64_t y1 = 2000000123; 41 | uint64_t y2 = 1000000100; 42 | dbhun = double(y1 - y2) / 100.00; 43 | Serial.println(F("Two decimals test")); 44 | Serial.println(dbhun, 2); 45 | 46 | // Three decimals 47 | uint64_t z1 = 20000000123; 48 | uint64_t z2 = 10000000000; 49 | dbtho = double(z1 - z2) / 1000.000; 50 | Serial.println(F("Three decimals test")); 51 | Serial.println(dbtho, 3); 52 | 53 | // Four decimals 54 | uint64_t w1 = 200000001234; 55 | uint64_t w2 = 100000000000; 56 | dbtth = double(w1 - w2) / 10000.0000; 57 | Serial.println(F("Four decimals test")); 58 | Serial.println(dbtth, 4); 59 | 60 | delay(5000); 61 | } 62 | -------------------------------------------------------------------------------- /extra/lcd_test_1a.ino: -------------------------------------------------------------------------------- 1 | // lcd_test_1a 2 | // by André Derrick Balsa (AndrewBCN) 3 | // March 2022 4 | // GPLV3 5 | // Testing the LCD display with the STM32F401CCU6 6 | // Also test SPI bus and I2C bus and various sensors 7 | 8 | #if !defined(STM32_CORE_VERSION) || (STM32_CORE_VERSION < 0x02020000) 9 | #error "Due to API changes, this sketch is compatible with STM32_CORE_VERSION >= 0x02020000 (2.2.0 or later)" 10 | #endif 11 | 12 | // Increase HardwareSerial (UART) TX and RX buffer sizes from default 64 characters to 256. 13 | // The main worry here is that we could miss some characters from the u-blox GPS module if 14 | // the processor is busy doing something else (e.g. updating the display, reading a sensor, etc) 15 | // specially since we increase the GPS baud rate from 9600 to 38400. 16 | 17 | #define SERIAL_TX_BUFFER_SIZE 256 // Warning: > 256 could cause problems, see comments in STM32 HardwareSerial library 18 | #define SERIAL_RX_BUFFER_SIZE 256 19 | 20 | #define GPSDO_GEN_2kHz_PB5 // generate 2kHz square wave test signal on pin PB5 using Timer 3 21 | #define GPSDO_INA219 // INA 219 current sensor 22 | 23 | #ifdef GPSDO_GEN_2kHz_PB5 24 | #define Test2kHzOutputPin PB5 // digital output pin used to output a test 2kHz square wave 25 | #endif // GEN_2kHz_PB5 26 | 27 | #ifdef GPSDO_INA219 28 | #include 29 | Adafruit_INA219 ina219; 30 | #endif // INA219 31 | 32 | #define VctlPWMOutputPin PB9 // digital output pin used to output a PWM value, TIM4 ch4 33 | // Two cascaded RC filters transform the PWM into an analog DC value 34 | 35 | #include // Hardware I2C library on STM32 36 | // Uses PB6 (SCL1) and PB7 (SDA1) on Black Pill for I2C1 37 | #include // Hardware SPI library on STM32 38 | // Uses PA5, PA6, PA7 on Black Pill for SPI1 39 | // AHT20 - I2C 40 | #include // Adafruit AHTX0 library for AHT20 I2C temperature and humidity sensor 41 | Adafruit_AHTX0 aht20; // create object aht20 42 | 43 | // BMP280 - I2C 44 | #include 45 | Adafruit_BMP280 bmp280; // hardware I2C 46 | Adafruit_Sensor *bmp_temp = bmp280.getTemperatureSensor(); 47 | Adafruit_Sensor *bmp_pressure = bmp280.getPressureSensor(); 48 | 49 | // TFT LCD ST7789 - SPI 50 | #include // need this adapted for STM32F4xx/F411C: https://github.com/fpistm/Adafruit-GFX-Library/tree/Fix_pin_type 51 | #include 52 | //#include 53 | 54 | #define TFT_DC PB12 // note this pin assigment conflicts with the original GPSDO schematic 55 | #define TFT_CS PB13 // in reality, not connected, CS not used on 1.3" TFT ST7789 display 56 | #define TFT_RST PB15 // also uses pins PA5, PA6, PA7 for MOSI MISO and SCLK 57 | 58 | Adafruit_ST7789 disp = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST); 59 | 60 | // LEDs 61 | // Blue onboard LED blinks to indicate ISR is working 62 | #define blueledpin PC13 // Blue onboard LED is on PC13 on STM32F411CEU6 Black Pill 63 | // Yellow extra LED is off, on or blinking to indicate some GPSDO status 64 | #define yellowledpin PB8 // Yellow LED on PB8 65 | volatile int yellow_led_state = 2; // global variable 0=off 1=on 2=1Hz blink 66 | 67 | // Uptime data 68 | volatile uint8_t uphours = 0; 69 | volatile uint8_t upminutes = 0; 70 | volatile uint8_t upseconds = 0; 71 | volatile uint16_t updays = 0; 72 | volatile bool halfsecond = false; 73 | char uptimestr[9] = "00:00:00"; // uptime string 74 | char updaysstr[5] = "000d"; // updays string 75 | 76 | 77 | // Interrupt Service Routine for the 2Hz timer 78 | void Timer_ISR_2Hz(void) { // WARNING! Do not attempt I2C communication inside the ISR 79 | 80 | // Toggle pin. 2hz toogle --> 1Hz pulse, perfect 50% duty cycle 81 | digitalWrite(blueledpin, !digitalRead(blueledpin)); 82 | 83 | halfsecond = !halfsecond; // true @ 1Hz 84 | 85 | switch (yellow_led_state) 86 | { 87 | case 0: 88 | // turn off led 89 | digitalWrite(yellowledpin, LOW); 90 | break; 91 | case 1: 92 | // turn on led 93 | digitalWrite(yellowledpin, HIGH); 94 | break; 95 | case 2: 96 | // blink led 97 | digitalWrite(yellowledpin, !digitalRead(yellowledpin)); 98 | break; 99 | default: 100 | // default is to turn off led 101 | digitalWrite(yellowledpin, LOW); 102 | break; 103 | } 104 | 105 | // Uptime clock - in days, hours, minutes, seconds 106 | if (halfsecond) 107 | { 108 | if (++upseconds > 59) 109 | { 110 | upseconds = 0; 111 | if (++upminutes > 59) 112 | { 113 | upminutes = 0; 114 | if (++uphours > 23) 115 | { 116 | uphours = 0; 117 | ++updays; 118 | } 119 | } 120 | } 121 | } 122 | } // end of 2Hz ISR 123 | 124 | void uptimetostrings() { 125 | // translate uptime variables to strings 126 | uptimestr[0] = '0' + uphours / 10; 127 | uptimestr[1] = '0' + uphours % 10; 128 | uptimestr[3] = '0' + upminutes / 10; 129 | uptimestr[4] = '0' + upminutes % 10; 130 | uptimestr[6] = '0' + upseconds / 10; 131 | uptimestr[7] = '0' + upseconds % 10; 132 | 133 | if (updays > 99) { // 100 days or more 134 | updaysstr[0] = '0' + updays / 100; 135 | updaysstr[1] = '0' + (updays % 100) / 10; 136 | updaysstr[2] = '0' + (updays % 100) % 10; 137 | } 138 | else { // less than 100 days 139 | updaysstr[0] = '0'; 140 | updaysstr[1] = '0' + updays / 10; 141 | updaysstr[2] = '0' + updays % 10; 142 | } 143 | } 144 | 145 | void setup() { 146 | // Wait 1 second for things to stabilize 147 | delay(1000); 148 | 149 | // setup USB serial 150 | Serial.begin(9600); 151 | Serial.println(F("LCD display test")); 152 | 153 | // configure blueledpin in output mode 154 | pinMode(blueledpin, OUTPUT); 155 | 156 | // configure yellow_led_pin in output mode 157 | pinMode(yellowledpin, OUTPUT); 158 | 159 | // setup 2kHz test signal on PB5 if configured, uses Timer 3 160 | #ifdef GPSDO_GEN_2kHz_PB5 // note this uses Timer 3 Channel 2 161 | analogWrite(Test2kHzOutputPin, 127); // configures PB5 as PWM output pin at default frequency and resolution 162 | analogWriteFrequency(2000); // default PWM frequency is 1kHz, change it to 2kHz 163 | analogWriteResolution(16); // default PWM resolution is 8 bits, change it to 16 bits 164 | analogWrite(Test2kHzOutputPin, 32767); // 32767 for 16 bits -> 50% duty cycle so a square wave 165 | #endif // GEN_2kHz_PB5 166 | 167 | // setup Vctl PWM DAC, output approximately 1.65V for testing purposes 168 | // we generate a 2kHz square wave on PB9 PWM pin, using Timer 4 channel 4 169 | // PB9 is Timer 4 Channel 4 from Arduino_Core_STM32/variants/STM32F4xx/F411C(C-E)(U-Y)/PeripheralPins_BLACKPILL_F411CE.c 170 | analogWrite(VctlPWMOutputPin, 127); // configures PB9 as PWM output pin at default frequency and resolution 171 | analogWriteFrequency(2000); // default PWM frequency is 1kHz, change it to 2kHz 172 | analogWriteResolution(16); // set PWM resolution to 16 bits (the maximum for the STM32F411CEU6) 173 | analogWrite(VctlPWMOutputPin, 32767); // 32767 for 16 bits -> 50% duty cycle so a square wave 174 | 175 | // setup 2Hz timer and interrupt, uses Timer 9 176 | HardwareTimer *tim2Hz = new HardwareTimer(TIM9); 177 | tim2Hz->setOverflow(2, HERTZ_FORMAT); // 2 Hz 178 | tim2Hz->attachInterrupt(Timer_ISR_2Hz); 179 | tim2Hz->resume(); 180 | 181 | // setup sensors and LCD display 182 | // AHT20, BMP280, INA219, ST7789 240x240 TFT LCD 183 | 184 | Serial.println(F("Testing for presence of AHT20 Sensor on I2C bus")); 185 | if (!aht20.begin()) { 186 | Serial.println(F("Could not find AHT20 sensor, check wiring")); 187 | while (1) delay(10); 188 | } 189 | else Serial.println(F("AHT20 sensor found!")); 190 | 191 | Serial.println(F("Testing for presence of BMP280 Sensor on I2C bus")); 192 | if (!bmp280.begin(0x76,0x58)) { 193 | Serial.println(F("Could not find BMP280 sensor, check wiring")); 194 | while (1) delay(10); 195 | } 196 | else Serial.println(F("BMP280 sensor found!")); 197 | 198 | // Default settings from datasheet 199 | bmp280.setSampling(Adafruit_BMP280::MODE_NORMAL, // Operating Mode 200 | Adafruit_BMP280::SAMPLING_X2, // Temp. oversampling 201 | Adafruit_BMP280::SAMPLING_X16, // Pressure oversampling 202 | Adafruit_BMP280::FILTER_X16, // Filtering 203 | Adafruit_BMP280::STANDBY_MS_500); // Standby time 204 | 205 | // Initialize the INA219. 206 | // By default the initialization will use the largest range (32V, 2A). However 207 | // you can call a setCalibration function to change this range (see comments). 208 | if (! ina219.begin()) { 209 | Serial.println(F("Could not find INA219 sensor, check wiring")); 210 | while (1) { delay(10); } 211 | } 212 | else Serial.println(F("INA219 sensor found!")); 213 | // To use a slightly lower 32V, 1A range (higher precision on amps): 214 | //ina219.setCalibration_32V_1A(); 215 | // Or to use a lower 16V, 400mA range (higher precision on volts and amps): 216 | //ina219.setCalibration_16V_400mA(); 217 | ina219.setCalibration_32V_1A(); 218 | 219 | // Setup 240x240 LCD SPI ST7789 display 220 | disp.init(240, 240, SPI_MODE3); // 1.3" 240x240 TFT LCD 221 | delay(500); 222 | disp.fillScreen(ST77XX_BLACK); 223 | disp.setTextColor(ST77XX_YELLOW, ST77XX_BLACK); // 224 | disp.setRotation(2); // 0..3 max, here we use 180° = landscape 225 | disp.setFont(); 226 | disp.setTextSize(3); 227 | disp.setCursor(0, 30); 228 | disp.print(F("Testing...")); 229 | disp.setTextSize(2); 230 | disp.setCursor(0, 60); 231 | disp.setTextColor(ST77XX_GREEN, ST77XX_BLACK); 232 | disp.print(F(" Smaller text - ")); 233 | disp.setTextColor(ST77XX_WHITE, ST77XX_BLACK); 234 | disp.print(F("123")); 235 | disp.setCursor(0, 80); 236 | disp.setTextColor(ST77XX_RED, ST77XX_BLACK); 237 | disp.print(F("Different colors.")); 238 | disp.setTextSize(3); 239 | disp.setTextColor(ST77XX_CYAN, ST77XX_BLACK); 240 | disp.setCursor(0, 120); 241 | disp.print(F("STM32 GPSDO")); 242 | disp.setTextSize(2); 243 | disp.setTextColor(ST77XX_MAGENTA, ST77XX_BLACK); 244 | disp.setCursor(0, 150); 245 | disp.print(F(" Version v0.99z")); 246 | disp.setTextColor(ST77XX_BLUE, ST77XX_BLACK); 247 | disp.setCursor(0, 180); 248 | disp.print(F(" ... not really!")); 249 | } // setup done 250 | 251 | void loop() { 252 | // print something once per second to USB serial (Arduino monitor) 253 | 254 | uptimetostrings(); // get updaysstr and uptimestr 255 | Serial.print(F("Uptime: ")); 256 | Serial.print(updaysstr); 257 | Serial.print(F(" ")); 258 | Serial.println(uptimestr); 259 | 260 | Serial.println(); 261 | 262 | sensors_event_t temp_event, pressure_event; 263 | bmp_temp->getEvent(&temp_event); 264 | bmp_pressure->getEvent(&pressure_event); 265 | 266 | Serial.println(F("BMP280 Sensor Readings")); 267 | Serial.print(F("Temperature = ")); 268 | Serial.print(temp_event.temperature); 269 | Serial.println(F(" *C")); 270 | 271 | Serial.print(F("Pressure = ")); 272 | Serial.print(pressure_event.pressure); 273 | Serial.println(F(" hPa")); 274 | 275 | Serial.println(); 276 | 277 | Serial.println(F("AHT20 Sensor Readings")); 278 | sensors_event_t humidity, temp; 279 | aht20.getEvent(&humidity, &temp); // populate temp and humidity objects with fresh data 280 | Serial.print(F("Temperature = ")); 281 | Serial.print(temp.temperature); 282 | Serial.println(F(" *C")); 283 | 284 | Serial.print(F("Humidity = ")); 285 | Serial.print(humidity.relative_humidity); 286 | Serial.println(F("% rH")); 287 | 288 | Serial.println(); 289 | 290 | // Read INA 219 current voltage sensor 291 | float shuntvoltage = 0; 292 | float busvoltage = 0; 293 | float current_mA = 0; 294 | float loadvoltage = 0; 295 | float power_mW = 0; 296 | 297 | shuntvoltage = ina219.getShuntVoltage_mV(); 298 | busvoltage = ina219.getBusVoltage_V(); 299 | current_mA = ina219.getCurrent_mA(); 300 | power_mW = ina219.getPower_mW(); 301 | loadvoltage = busvoltage + (shuntvoltage / 1000); 302 | 303 | Serial.print("Bus Voltage: "); Serial.print(busvoltage); Serial.println(" V"); 304 | Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV"); 305 | Serial.print("Load Voltage: "); Serial.print(loadvoltage); Serial.println(" V"); 306 | Serial.print("Current: "); Serial.print(current_mA); Serial.println(" mA"); 307 | Serial.print("Power: "); Serial.print(power_mW); Serial.println(" mW"); 308 | 309 | Serial.println(""); 310 | 311 | delay(2000); 312 | } 313 | -------------------------------------------------------------------------------- /schematics/GPSDO-KiCad.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AndrewBCN/STM32-GPSDO/a3102458f531ff3edabe53704ac7ce54c3f06c72/schematics/GPSDO-KiCad.pdf -------------------------------------------------------------------------------- /software/GPSDO.ino: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************** 2 | STM32 GPSDO v0.05j by André Balsa, March 2022 3 | GPLV3 license 4 | GitHub collaborators: iannezsp (Angelo Iannello) 5 | Reuses small bits of the excellent GPS checker code Arduino sketch by Stuart Robinson - 05/04/20 6 | From version 0.03 includes a command parser, so the GPSDO can receive commands from the USB serial or 7 | Bluetooth serial interfaces and execute various callback functions. 8 | From version 0.04 includes an auto-calibration function, enabled by default at power on. The 9 | calibration process can also be launched at any time by sending the "C" command. 10 | The very first calibration after power on includes an OCXO warmup delay, usually 300 seconds. 11 | Version 0.04f implements a GPS receiver "tunnel mode" where the MCU simply relays the information 12 | when the "T" command is received. 13 | This should make it possible to connect the STM32 GPSDO to a laptop/PC running u-center. 14 | Note that tunnel mode is exited automatically after a configurable timeout. There is no other way to 15 | exit tunnel mode. 16 | - Initial ST7735 SPI LCD display support code contributed by Badwater-Frank. 17 | 18 | This program is supplied as is, it is up to the user of the program to decide if the program is 19 | suitable for the intended purpose and free from errors. 20 | **********************************************************************************************************/ 21 | 22 | // GPSDO with STM32 MCU, optional OLED/LCD display, various sensors, DFLL in software, optional Bluetooth 23 | 24 | /********************************************************************************************************** 25 | This Arduino with STM32 Core package sketch implements a GPSDO with display options. It uses an SSD1306 26 | 128x64 I2C OLED display or SPI LCD. It reads the GPS for 1 or 5 seconds and copies the half-dozen or so 27 | default NMEA sentences from the GPS to either the USB serial or Bluetooth serial ports (but not both) 28 | if verbose mode is enabled. That is followed by various sensors data and the FLL and OCXO data. 29 | This is an example printout from a working GPSDO running firmware version v0.04e: 30 | 31 | Wait for GPS fix max. 1 second 32 | 33 | $GNGSA,A,3,27,10,23,26,18,15,,,,,,,2.30,1.91,1.28*13 34 | $GNGSA,A9,76,38,268,,77,23,327,,84,05,085,,85,57,052,23*61 35 | $GLGSV,3,3,09,86,53,308,*5F 36 | $GNGLL,4833.66284,N,00746.88237,E,134626.00,A,A*72 37 | $GNRMC,134627.00,A,4833.66358,N,00746.88039,E,2.527,,050621,,,A*64 38 | $GNGGA,134627.00,4833.66358,N,00746.88039,E,1,07,1.91,137.7,M,47.3,M,,*46 39 | 40 | Fix time 889mS 41 | Uptime: 000d 00:28:44 42 | New GPS Fix: 43 | Lat: 48.561058 Lon: 7.781340 Alt: 137.7m 44 | Sats: 7 HDOP: 1.91 45 | UTC Time: 13:46:27 Date: 5/6/2021 46 | 47 | Voltages: 48 | Vctl: 1.97 DAC: 2404 49 | VctlPWM: 1.81 PWM: 35751 50 | Vcc: 5.02 51 | Vdd: 3.29 52 | 53 | Frequency measurements using 64-bit counter: 54 | 64-bit Counter: 17215439735 55 | Frequency: 10000000 Hz 56 | 10s Frequency Avg: 10000000.0 Hz 57 | 100s Frequency Avg: 9999999.99 Hz 58 | 1,000s Frequency Avg: 9999999.997 Hz 59 | 10,000s Frequency Avg: 0.0000 Hz 60 | 61 | BMP280 Temperature = 26.6 *C 62 | Pressure = 1020.0 hPa 63 | Approx altitude = 57.3 m 64 | AHT10 Temperature: 23.57 *C 65 | Humidity: 76.48% rH 66 | 67 | When the program detects that the GPS has a fix, it prints the information above to the USB serial 68 | xor the Bluetooth serial (if the Bluetooth serial port is defined in the preprocessor directives). 69 | If the I2C OLED display is attached that is updated as well. 70 | 71 | The USB serial port is set at 115200 baud, the Bluetooth serial port at 57600 baud, and the GPS 72 | serial port is set initially at 9600 baud then reconfigured at 38400 baud. 73 | **********************************************************************************************************/ 74 | /* Libraries required to compile, depending on configured options: 75 | - TinyGPS++ 76 | - U8g2/u8x8 graphics library, see https://github.com/olikraus/u8g2 77 | - Adafruit AHTX0 78 | - Adafruit BMP280 79 | - movingAvg library, on STM32 architecture needs a simple patch to avoid warning during compilation 80 | - Color LCD support requires the installation of the Adafruit ST7735 and ST7789 LCD library 81 | and the Adafruit GFX library. 82 | - TM1637 LED clock module requires the TM1637 library, see https://github.com/avishorp/TM1637 83 | 84 | For commands parsing, uses SerialCommands library found here: 85 | https://github.com/ppedro74/Arduino-SerialCommands 86 | 87 | And also requires the installation of support for the STM32 MCUs by installing the STM32duino 88 | package (STM32 Core version 2.2.0 or later). 89 | **********************************************************************************************************/ 90 | /* Commands implemented: 91 | - V : returns program name, version and author 92 | - F : flush ring buffers 93 | - C : calibrate OCXO 94 | - dp/up 1/10 : adjust Vctl down/up PWM fine/coarse, example dp1 means decrease PWM by 1. 95 | - SP : set PWM to value between 1 and 65535 96 | - RD/RH : toggle between tab Delimited and Human readable GPSDO status reporting 97 | 98 | /* Commands to be implemented: 99 | - L0 to L9 : select log levels 100 | - L0 : silence mode 101 | - L1 : fix only mode 102 | - L7 : fix and full status mode, no NMEA (default) 103 | - L8 : NMEA stream from GPS module only mode 104 | - L9 : NMEA + full status 105 | 106 | /********************************************************************************************************** 107 | Program Operation - This program is a GPSDO with optional OLED display. It uses a small SSD1306 108 | 128x64 I2C OLED display. At startup the program starts checking the data coming from the GPS for a 109 | valid fix. It reads the GPS NMEA stream for 1/5 seconds and if there is no fix, prints a message on the 110 | Arduino IDE serial monitor and updates the seconds without a fix on the display. During this time the 111 | NMEA stream coming from the GPS is copied to the serial monitor also. The DFLL is active as soon as 112 | the GPS starts providing a 1PPS pulse. The 10MHz OCXO is controlled by a voltage generated by either 113 | the 16-bit PWM ; this voltage (Vctl) is adjusted once every 429 seconds. 114 | **********************************************************************************************************/ 115 | 116 | // Version v0.04i and later: Erik Kaashoek has suggested a 10s sampling rate for the 64-bit counter, to save RAM. 117 | // This is work in progress, see the changes in Timer2_Capture_ISR. 118 | 119 | // Version v0.05j and later: reporting on USB serial / Bluetooth serial can be toggled between human readable and tabulated data. 120 | 121 | // 1. picDIV synchronization control. 122 | // 2. Refactor the entire program to make it easier to understand and maintain. 123 | // 3. Implement support for the STM32F401CCU6 Black Pill. 124 | // 4. Frequency / period meter implementation. 125 | // 5. Improve layout of ST7789 display. 126 | 127 | #define Program_Name "GPSDO" 128 | #define Program_Version "v0.05j" 129 | #define Author_Name "André Balsa" 130 | 131 | // Debug options 132 | // ------------- 133 | #define FastBootMode // reduce various delays during boot 134 | #define TunnelModeTesting // reduce tunnel mode timeout 135 | 136 | // Hardware options 137 | // ---------------- 138 | // #define GPSDO_STM32F401 // use an STM32F401 Black Pill instead of STM32F411 (reduced RAM) 139 | // IMPORTANT! Don't forget to select the correct board in the Tools->Board menu in the arduino IDE 140 | #define GPSDO_OLED // SSD1306 128x64 I2C OLED display 141 | // #define GPSDO_LCD_ST7735 // ST7735 160x128 SPI LCD display 142 | #define GPSDO_LCD_ST7789 // ST7789 240x240 SPI LCD display (testing) 143 | #define GPSDO_PWM_DAC // STM32 16-bit PWM DAC, requires two rc filters (2xr=20k, 2xc=10uF) - note this will become the default 144 | #define GPSDO_AHT10 // AHT10 or AHT20 (recommended) I2C temperature and humidity sensor 145 | #define GPSDO_GEN_2kHz_PB5 // generate 2kHz square wave test signal on pin PB5 using Timer 3 146 | // #define GPSDO_BMP280_SPI // SPI atmospheric pressure, temperature and altitude sensor 147 | #define GPSDO_BMP280_I2C // I2C atmospheric pressure, temperature and altitude sensor 148 | #define GPSDO_INA219 // INA219 I2C current and voltage sensor 149 | // #define GPSDO_BLUETOOTH // Bluetooth serial (HC-06 module) 150 | #define GPSDO_VCC // Vcc (nominal 5V) ; reading Vcc requires 1:2 voltage divider to PA0 151 | #define GPSDO_VDD // Vdd (nominal 3.3V) reads VREF internal ADC channel 152 | #define GPSDO_CALIBRATION // auto-calibration is enabled 153 | #define GPSDO_UBX_CONFIG // optimize u-blox GPS receiver configuration 154 | #define GPSDO_VERBOSE_NMEA // GPS module NMEA stream echoed to USB serial xor Bluetooth serial 155 | // #define GPSDO_PICDIV // generate a 1.2s synchronization pulse for the picDIV 156 | #define GPSDO_TM1637 // TM1637 4-digit LED module 157 | // #define GPSDO_TIC // read TIC 12-bit value on PA1 (ADC channel 1), then discharge capacitor using PB2 158 | #define GPSDO_EEPROM // enable STM32 buffered EEPROM emulation library 159 | 160 | // Includes 161 | // -------- 162 | #if !defined(STM32_CORE_VERSION) || (STM32_CORE_VERSION < 0x02020000) 163 | #error "Due to API changes, this sketch is compatible with STM32_CORE_VERSION >= 0x02020000 (2.2.0 or later)" 164 | #endif 165 | 166 | // Increase HardwareSerial (UART) TX and RX buffer sizes from default 64 characters to 256. 167 | // The main worry here is that we could miss some characters from the u-blox GPS module if 168 | // the processor is busy doing something else (e.g. updating the display, reading a sensor, etc) 169 | // specially since we increase the GPS baud rate from 9600 to 38400. 170 | 171 | #define SERIAL_TX_BUFFER_SIZE 256 // Warning: > 256 could cause problems, see comments in STM32 HardwareSerial library 172 | #define SERIAL_RX_BUFFER_SIZE 256 173 | 174 | bool report_tab_delimited = false; // true for tab delimited reporting, false for human-readable reporting 175 | uint64_t report_line_no = 0; // line number for tab delimited reporting, 0 if no GPS fix 176 | 177 | const uint16_t waitFixTime = 1; // Maximum time in seconds waiting for a fix before reporting no fix / yes fix 178 | // Tested values 1 second and 5 seconds, 1s recommended 179 | 180 | #include // https://github.com/JChristensen/movingAvg , needs simple patch 181 | // to avoid warning message during compilation 182 | 183 | #ifdef GPSDO_PICDIV 184 | #define picDIVsyncPin PB3 // digital output pin used to generate a 1.2s synchronization pulse for the picDIV 185 | #endif // PICDIV 186 | 187 | #ifdef GPSDO_GEN_2kHz_PB5 188 | #define Test2kHzOutputPin PB5 // digital output pin used to output a test 2kHz square wave 189 | #endif // GEN_2kHz_PB5 190 | 191 | // HC-06 Bluetooth module 192 | #ifdef GPSDO_BLUETOOTH 193 | // UART RX TX 194 | HardwareSerial Serial2(PA3, PA2); // Serial connection to HC-06 Bluetooth module 195 | #define BT_BAUD 57600 // Bluetooth baud rate 196 | #endif // BLUETOOTH 197 | 198 | // EEPROM emulation in flash 199 | #ifdef GPSDO_EEPROM 200 | #include // Buffered EEPROM emulation library 201 | #endif // EEPROM 202 | 203 | #include // Commands parser library 204 | char serial_command_buffer_[32]; // buffer for commands library 205 | // The following line determines which serial port we'll listen to 206 | // "\n" means only newline needed to accept command 207 | #ifdef GPSDO_BLUETOOTH 208 | SerialCommands serial_commands_(&Serial2, serial_command_buffer_, sizeof(serial_command_buffer_), "\n", " "); 209 | #else 210 | SerialCommands serial_commands_(&Serial, serial_command_buffer_, sizeof(serial_command_buffer_), "\n", " "); 211 | #endif // BLUETOOTH 212 | 213 | #include // get library here > http://arduiniana.org/libraries/tinygpsplus/ 214 | TinyGPSPlus gps; // create the TinyGPS++ object 215 | 216 | #include // Hardware I2C library on STM32 217 | 218 | // AHT10 / AHT20 temperature humidity sensor // Uses PB6 (SCL1) and PB7 (SDA1) on Black Pill for I2C1 219 | #ifdef GPSDO_AHT10 220 | #include // Adafruit AHTX0 library 221 | Adafruit_AHTX0 aht; // create object aht 222 | #endif // AHT10 223 | 224 | // INA219 current voltage sensor 225 | #ifdef GPSDO_INA219 226 | #include 227 | Adafruit_INA219 ina219; 228 | float ina219volt=0.0, ina219curr=0.0; 229 | #endif // INA219 230 | 231 | // TM1637 4-digit LED module 232 | #ifdef GPSDO_TM1637 233 | #include // get library here > https://github.com/avishorp/TM1637 234 | // Module connection pins (Digital Pins) 235 | #define CLK PA8 // interface to TM1637 requires two GPIO pins 236 | #define DIO PB4 237 | TM1637Display tm1637(CLK, DIO); // create tm1637 object 238 | const uint8_t mid_dashes[] = { 239 | SEG_G, // - 240 | SEG_G, // - 241 | SEG_G, // - 242 | SEG_G // - 243 | }; 244 | const uint8_t low_oooo_s[] = { 245 | SEG_C | SEG_D | SEG_E | SEG_G, // o 246 | SEG_C | SEG_D | SEG_E | SEG_G, // o 247 | SEG_C | SEG_D | SEG_E | SEG_G, // o 248 | SEG_C | SEG_D | SEG_E | SEG_G // o 249 | }; 250 | #endif // TM1637 251 | 252 | // OLED 0.96 SSD1306 128x64 253 | #ifdef GPSDO_OLED 254 | #include // get library here > https://github.com/olikraus/u8g2 255 | U8X8_SSD1306_128X64_NONAME_HW_I2C disp(U8X8_PIN_NONE); // use this line for standard 0.96" SSD1306 256 | #endif // OLED 257 | 258 | // LCD 1.8" ST7735 160x128 (tested by Badwater-Frank) 259 | #ifdef GPSDO_LCD_ST7735 260 | #include // need this adapted for STM32F4xx/F411C: https://github.com/fpistm/Adafruit-GFX-Library/tree/Fix_pin_type 261 | #include 262 | //#include 263 | #include 264 | #define TFT_DC PA1 // note this pin assigment conflicts with the original schematic 265 | #define TFT_CS PA2 266 | #define TFT_RST PA3 267 | // For 1.44" and 1.8" TFT with ST7735 use: 268 | Adafruit_ST7735 disp = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); 269 | #endif // LCD_ST7735 270 | 271 | // LCD 1.3" ST7789 240x240 (Testing) 272 | #ifdef GPSDO_LCD_ST7789 273 | #include // need this adapted for STM32F4xx/F411C: https://github.com/fpistm/Adafruit-GFX-Library/tree/Fix_pin_type 274 | #include 275 | #include 276 | #define TFT_DC PB12 // note pin assigment that does not conflict with other interfaces 277 | #define TFT_CS PB13 // in reality, CS not connected, CS not used on 1.3" TFT ST7789 display 278 | #define TFT_RST PB15 // also uses pins PA5, PA6, PA7 for MOSI MISO and SCLK 279 | // For 1.3" LCD with ST7789 280 | Adafruit_ST7789 disp_st7789 = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST); 281 | bool must_clear_disp_st7789 = false; // flag is set when display has to be cleared 282 | 283 | // include the following GFX library fonts 284 | #include // tiny, but readable in white 285 | #include // medium size, readable 286 | #endif // LCD_ST7789 287 | 288 | // PWM 16-bit DAC 289 | const uint16_t default_PWM_output = 35585; // "ideal" 16-bit PWM value, varies with OCXO, RC network, and time and temperature 290 | // 35585 for a second NDK ENE3311B 291 | uint16_t adjusted_PWM_output; // we adjust this value to "close the loop" of the DFLL when using the PWM 292 | volatile bool must_adjust_DAC = false; // true when there is enough data to adjust Vctl 293 | char trendstr[5] = " ___"; // PWM trend string, set in the adjustVctlPWM() function 294 | 295 | #define VctlPWMOutputPin PB9 // digital output pin used to output a PWM value, TIM4 ch4 296 | // Two cascaded RC filters transform the PWM into an analog DC value 297 | #define VctlPWMInputPin PB1 // ADC pin to read Vctl from filtered PWM 298 | volatile int pwmVctl = 0; // variable used to store PWM Vctl read by ADC pin PB1 299 | 300 | // VCC - 5V 301 | #ifdef GPSDO_VCC 302 | #define VccDiv2InputPin PA0 // Vcc/2 using resistor divider connects to PA0 303 | int adcVcc = 0; 304 | #endif // VCC 305 | 306 | // VDD - 3.3V 307 | #ifdef GPSDO_VDD 308 | int adcVdd = 0; // Vdd is read internally as Vref 309 | #endif // VDD 310 | 311 | // movingAvg objects for the voltages measured by MCU ADC 312 | // all averages over 10 samples (10 seconds in principle) 313 | #ifdef GPSDO_VDD 314 | movingAvg avg_adcVdd(10); 315 | int16_t avgVdd = 0; 316 | #endif // VDD 317 | 318 | #ifdef GPSDO_VCC 319 | movingAvg avg_adcVcc(10); 320 | int16_t avgVcc = 0; 321 | #endif // VCC 322 | 323 | movingAvg avg_pwmVctl(10); 324 | int16_t avgpwmVctl = 0; 325 | 326 | // BMP280 atmospheric pressure and temperature sensor 327 | #ifdef GPSDO_BMP280_SPI 328 | // BMP280 - SPI 329 | #include 330 | #include 331 | #define BMP280_CS (PA4) // SPI1 uses PA4, PA5, PA6, PA7 332 | Adafruit_BMP280 bmp(BMP280_CS); // hardware SPI, use PA4 as Chip Select 333 | #endif // BMP280_SPI 334 | 335 | #ifdef GPSDO_BMP280_I2C 336 | // BMP280 - I2C 337 | #include 338 | Adafruit_BMP280 bmp; // hardware I2C 339 | #endif // BMP280_I2C 340 | 341 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 342 | const uint16_t PressureOffset = 1860; // that offset must be calculated for your sensor and location 343 | float bmp280temp=0.0, bmp280pres=0.0, bmp280alti=0.0; // read sensor, save here 344 | #endif // BMP280 345 | 346 | // LEDs 347 | // Blue onboard LED blinks to indicate ISR is working 348 | #define blueledpin PC13 // Blue onboard LED is on PC13 on STM32F411CEU6 Black Pill 349 | // Yellow extra LED is off, on or blinking to indicate some GPSDO status 350 | #define yellowledpin PB8 // Yellow LED on PB8 351 | volatile int yellow_led_state = 2; // global variable 0=off 1=on 2=1Hz blink 352 | 353 | // GPS data 354 | float GPSLat; // Latitude from GPS 355 | float GPSLon; // Longitude from GPS 356 | float GPSAlt; // Altitude from GPS 357 | uint8_t GPSSats; // number of GPS satellites in use 358 | uint32_t GPSHdop; // HDOP from GPS 359 | uint8_t hours, mins, secs, day, month; 360 | uint16_t year; 361 | uint32_t startGetFixmS; 362 | uint32_t endFixmS; 363 | 364 | // Uptime data 365 | volatile uint8_t uphours = 0; 366 | volatile uint8_t upminutes = 0; 367 | volatile uint8_t upseconds = 0; 368 | volatile uint16_t updays = 0; 369 | volatile bool halfsecond = false; 370 | char uptimestr[9] = "00:00:00"; // uptime string 371 | char updaysstr[5] = "000d"; // updays string 372 | 373 | // OCXO frequency measurement 374 | 375 | // special 10s sampling rate data structures (work in progress) 376 | volatile uint16_t esamplingfactor = 10; // sample 64-bit counter every 10 seconds 377 | volatile uint16_t esamplingcounter = 0; // counter from 0 to esamplingfactor 378 | volatile bool esamplingflag = false; 379 | 380 | volatile uint64_t circbuf_esten64[11]; // 10+1 x10 seconds circular buffer, so 100 seconds 381 | volatile uint32_t cbihes_newest = 0; // newest/oldest index 382 | volatile bool cbHes_full = false; // flag set when buffer has filled up 383 | volatile double avgesample = 0; // 100 seconds average with 10s sampling rate 384 | 385 | // other OCXO frequency measurement data structures 386 | const uint32_t basefreq=10000000; // OCXO nominal frequency in Hz 387 | volatile uint32_t lsfcount=0, previousfcount=0, calcfreqint=basefreq; 388 | 389 | // Frequency check boundaries 390 | const uint32_t lowerfcount = 9999500; 391 | const uint32_t upperfcount = 10000500; 392 | 393 | /* Moving average frequency variables 394 | Basically we store the counter captures for 10 and 100 seconds. 395 | When the buffers are full, the average frequency is quite simply 396 | the difference between the oldest and newest data divided by the size 397 | of the buffer. 398 | Each second, when the buffers are full, we overwrite the oldest data 399 | with the newest data and calculate each average frequency. 400 | */ 401 | volatile uint64_t fcount64=0, prevfcount64=0, calcfreq64=basefreq; 402 | // ATTENTION! must declare 64-bit, not 32-bit variable, because of shift 403 | volatile uint64_t tim2overflowcounter = 0; // testing, counts the number of times TIM2 overflows 404 | volatile bool overflowflag = false; // flag set by the overflow ISR, reset by the 2Hz ISR 405 | volatile bool captureflag = false; // flag set by the capture ISR, reset by the 2Hz ISR 406 | volatile bool overflowErrorFlag = false; // flag set if there was an overflow processing error 407 | 408 | volatile uint64_t circbuf_ten64[11]; // 10+1 seconds circular buffer 409 | volatile uint64_t circbuf_hun64[101]; // 100+1 seconds circular buffer 410 | volatile uint64_t circbuf_tho64[1001]; // 1,000+1 seconds circular buffer 411 | #ifndef GPSDO_STM32F401 412 | volatile uint64_t circbuf_tth64[10001]; // 10,000 + 1 seconds circular buffer 413 | #else // STM32F401 has less RAM 414 | volatile uint64_t circbuf_fth64[5001]; // 5,000 + 1 seconds circular buffer 415 | #endif // GPSDO_STM32F401 416 | 417 | volatile uint32_t cbiten_newest=0; // index to oldest, newest data 418 | volatile uint32_t cbihun_newest=0; 419 | volatile uint32_t cbitho_newest=0; 420 | volatile uint32_t cbitth_newest=0; 421 | 422 | volatile bool cbTen_full=false, cbHun_full=false, cbTho_full=false, cbTth_full=false; // flag when buffer full 423 | volatile double avgften=0, avgfhun=0, avgftho=0, avgftth=0; // average frequency calculated once the buffer is full 424 | volatile bool flush_ring_buffers_flag = true; // indicates ring buffers should be flushed 425 | 426 | // Miscellaneous data structures 427 | 428 | // picDIV support 429 | #ifdef GPSDO_PICDIV 430 | #define VphaseInputPin PB1 // ADC pin to read Vphase from 1ns-resolution TIC 431 | volatile bool force_armpicDIV_flag = true; // indicates picDIV must be armed waiting to sync on next PPS from GPS module 432 | #endif // PICDIV 433 | 434 | volatile bool force_calibration_flag = true; // indicates GPSDO should start calibration sequence 435 | 436 | volatile bool ocxo_needs_warming = true; // indicates OCXO needs to warm up a few minutes after power on 437 | 438 | #ifdef FastBootMode 439 | const uint16_t ocxo_warmup_time = 15; // ocxo warmup time in seconds; 15s for testing 440 | const uint16_t ocxo_calib_time = 15; // 15s fast calibration countdown time (for each calibration step) 441 | #else 442 | const uint16_t ocxo_warmup_time = 300; // ocxo warmup time in seconds; 300s or 600s normal use 443 | const uint16_t ocxo_calib_time = 60; // 60s normal calibration countdown time (for each calibration step) 444 | #endif // FastBootMode 445 | 446 | volatile bool tunnel_mode_flag = false; // the GPSDO relays the information directly to and from the GPS module to the USB serial 447 | #ifdef TunnelModeTesting 448 | const uint16_t tunnelSecs = 15; // tunnel mode timeout in seconds; 15s for testing, 300s or 600s normal use 449 | #else 450 | const uint16_t tunnelSecs = 300; // tunnel mode timeout in seconds; 15s for testing, 300s or 600s normal use 451 | #endif // TunnelModeTesting 452 | 453 | // Miscellaneous functions 454 | 455 | // SerialCommands callback functions 456 | // This is the default handler, and gets called when no other command matches. 457 | void cmd_unrecognized(SerialCommands* sender, const char* cmd) 458 | { 459 | sender->GetSerial()->print("Unrecognized command ["); 460 | sender->GetSerial()->print(cmd); 461 | sender->GetSerial()->println("]"); 462 | } 463 | 464 | // called for V (version) command 465 | void cmd_version(SerialCommands* sender) 466 | { 467 | sender->GetSerial()->print(Program_Name); 468 | sender->GetSerial()->print(" - "); 469 | sender->GetSerial()->print(Program_Version); 470 | sender->GetSerial()->print(" by "); 471 | sender->GetSerial()->println(Author_Name); 472 | } 473 | 474 | // called for RD (Report tab Delimited format) command 475 | void cmd_repdel(SerialCommands* sender) 476 | { 477 | report_tab_delimited = true; // set switch 478 | sender->GetSerial()->println("Switching to reporting in Tab Delimited Format"); 479 | } 480 | 481 | // called for RH (Report Human readable format) command 482 | void cmd_rephum(SerialCommands* sender) 483 | { 484 | report_tab_delimited = false; // reset switch 485 | report_line_no = 0; // reset line counter 486 | sender->GetSerial()->println("Switching to reporting in Human Readable Format"); 487 | } 488 | 489 | // called for F (flush ring buffers) command 490 | void cmd_flush(SerialCommands* sender) 491 | { 492 | flush_ring_buffers_flag = true; // ring buffers will be flushed inside interrupt routine 493 | sender->GetSerial()->println("Ring buffers flushed"); 494 | } 495 | 496 | // called for C (calibration) command 497 | void cmd_calibrate(SerialCommands* sender) 498 | { 499 | force_calibration_flag = true; // starts auto-calibration sequence 500 | sender->GetSerial()->println("Auto-calibration sequence started"); 501 | } 502 | 503 | // called for T (tunnel) command 504 | void cmd_tunnel(SerialCommands* sender) 505 | { 506 | tunnel_mode_flag = true; // switches GPSDO operation to tunnel mode 507 | sender->GetSerial()->println("Switching to USB Serial <-> GPS tunnel mode"); 508 | } 509 | 510 | // called for SP (set PWM) command 511 | void cmd_setPWM(SerialCommands* sender) 512 | { 513 | int32_t pwm; 514 | char* pwm_str = sender->Next(); 515 | if (pwm_str == NULL) // check if a value was specified 516 | { 517 | sender->GetSerial()->println("No PWM value specified, using default"); 518 | pwm = default_PWM_output; 519 | adjusted_PWM_output = pwm; 520 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 521 | } 522 | else // check the value that was specified 523 | { 524 | pwm = atoi(pwm_str); // note atoi() returns zero if it cannot convert the string to a valid integer 525 | if ((pwm >= 1) && (pwm <= 65535)) // check if the value specified is positive 16-bit integer 526 | { 527 | sender->GetSerial()->print("Setting PWM value "); // if yes, set the value 528 | sender->GetSerial()->println(pwm); 529 | adjusted_PWM_output = pwm; 530 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 531 | } 532 | else // incorrect value specified, print error message 533 | { 534 | sender->GetSerial()->println("PWM value must be positive integer between 1 and 65535, leaving unchanged"); 535 | } 536 | } 537 | } 538 | 539 | // PWM direct control commands (up/down) 540 | // ------------------------------------- 541 | // called for up1 (increase PWM 1 bit) command 542 | void cmd_up1(SerialCommands* sender) 543 | { 544 | adjusted_PWM_output = adjusted_PWM_output + 1; 545 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 546 | sender->GetSerial()->println("increased PWM 1 bit"); 547 | } 548 | // called for up10 (increase PWM 10 bits) command 549 | void cmd_up10(SerialCommands* sender) 550 | { 551 | adjusted_PWM_output = adjusted_PWM_output + 10; 552 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 553 | sender->GetSerial()->println("increased PWM 10 bits"); 554 | } 555 | // called for dp1 (decrease PWM 1 bit) command 556 | void cmd_dp1(SerialCommands* sender) 557 | { 558 | adjusted_PWM_output = adjusted_PWM_output - 1; 559 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 560 | sender->GetSerial()->println("decreased PWM 1 bit"); 561 | } 562 | // called for dp10 (decrease PWM 10 bits) command 563 | void cmd_dp10(SerialCommands* sender) 564 | { 565 | adjusted_PWM_output = adjusted_PWM_output - 10; 566 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 567 | sender->GetSerial()->println("decreased PWM 10 bits"); 568 | } 569 | 570 | #ifdef GPSDO_EEPROM 571 | // add callback functions for PS and PR commands to Store PWM and Recall PWM value in Flash (emulating EEPROM) 572 | // warning! limited number of writes allowed 573 | #endif // EEPROM 574 | 575 | // SerialCommand commands 576 | // Note: Commands are case sensitive 577 | SerialCommand cmd_version_("V", cmd_version); // print program name and version 578 | SerialCommand cmd_flush_("F", cmd_flush); // flush ring buffers 579 | SerialCommand cmd_calibrate_("C", cmd_calibrate); // force calibration 580 | SerialCommand cmd_tunnel_("T", cmd_tunnel); // activate tunnel mode 581 | SerialCommand cmd_rephum_("RH", cmd_rephum); // activate humand readable reporting 582 | SerialCommand cmd_repdel_("RD", cmd_repdel); // activate tab delimited reporting 583 | SerialCommand cmd_setPWM_("SP", cmd_setPWM); // note this command takes a 16-bit PWM value (1 to 65535) as an argument 584 | // 16-bit PWM commands 585 | SerialCommand cmd_up1_("up1", cmd_up1); 586 | SerialCommand cmd_up10_("up10", cmd_up10); 587 | SerialCommand cmd_dp1_("dp1", cmd_dp1); 588 | SerialCommand cmd_dp10_("dp10", cmd_dp10); 589 | 590 | #ifdef GPSDO_EEPROM 591 | // add PS and PR commands to Store PWM and Recall PWM value in Flash (emulating EEPROM) 592 | // warning! limited number of writes allowed 593 | #endif // EEPROM 594 | 595 | // loglevel 596 | uint8_t loglevel = 7; // see commands comments for log level definitions, default is 7 597 | // note log levels are not implemented yet 598 | 599 | // Interrupt service routines 600 | 601 | // Interrupt Service Routine for TIM2 counter overflow / wraparound 602 | void Timer2_Overflow_ISR(void) 603 | { 604 | overflowflag = true; 605 | } 606 | 607 | // Interrupt Service Routine for TIM2 counter capture 608 | void Timer2_Capture_ISR(void) 609 | { 610 | captureflag = true; 611 | } 612 | 613 | // Interrupt Service Routine for the 2Hz timer 614 | void Timer_ISR_2Hz(void) // WARNING! Do not attempt I2C communication inside the ISR 615 | 616 | { // Toggle pin. 2hz toogle --> 1Hz pulse, perfect 50% duty cycle 617 | digitalWrite(blueledpin, !digitalRead(blueledpin)); 618 | 619 | halfsecond = !halfsecond; // true @ 1Hz 620 | 621 | // read TIM2->CCR3 once per second (when captureflag is set) and if it has changed, calculate OCXO frequency 622 | 623 | if (captureflag) { 624 | lsfcount = TIM2->CCR3; // read TIM2->CCR3 625 | captureflag = false; // clear capture flag 626 | if (flush_ring_buffers_flag) 627 | { 628 | flushringbuffers(); // flush ring buffers after a sat fix loss 629 | } 630 | else // check if the frequency counter has been updated and process accordingly 631 | { 632 | // there are two possible cases 633 | // 1. lsfcount is the same as last time -> there is nothing to do, or 634 | // 2. lsfcount is NOT the same as last time -> process 635 | if (lsfcount != previousfcount) 636 | { 637 | // again we must consider two cases 638 | // 1. lsfcount < previousfcount -> a wraparound has occurred, process 639 | // 2. lsfcount > previous fcount -> no wraparound processing required 640 | if (lsfcount < previousfcount) 641 | { 642 | must_adjust_DAC = true; // set flag, once every wraparound / every 429s 643 | // check wraparound flag, it should be set, if so clear it, otherwise raise error flag 644 | tim2overflowcounter++; 645 | if (overflowflag) overflowflag=false; else overflowErrorFlag = true; 646 | } 647 | fcount64 = (tim2overflowcounter << 32) + lsfcount; // hehe now we have a 64-bit counter 648 | if (fcount64 > prevfcount64) { // if we have a new count - that happens once per second 649 | if (((fcount64 - prevfcount64) > lowerfcount) && ((fcount64 - prevfcount64) < upperfcount)) { // if we have a valid fcount, otherwise it's discarded 650 | logfcount64(); // save fcount in the 64-bit ring buffers 651 | calcfreq64 = fcount64 - prevfcount64; // the difference is exactly the OCXO frequency in Hz 652 | } 653 | prevfcount64 = fcount64; 654 | } 655 | } 656 | previousfcount = lsfcount; // this happens whether it has changed or not 657 | } 658 | } 659 | 660 | switch (yellow_led_state) 661 | { 662 | case 0: 663 | // turn off led 664 | digitalWrite(yellowledpin, LOW); 665 | break; 666 | case 1: 667 | // turn on led 668 | digitalWrite(yellowledpin, HIGH); 669 | break; 670 | case 2: 671 | // blink led 672 | digitalWrite(yellowledpin, !digitalRead(yellowledpin)); 673 | break; 674 | default: 675 | // default is to turn off led 676 | digitalWrite(yellowledpin, LOW); 677 | break; 678 | } 679 | 680 | // Uptime clock - in days, hours, minutes, seconds 681 | if (halfsecond) 682 | { 683 | if (++upseconds > 59) 684 | { 685 | upseconds = 0; 686 | if (++upminutes > 59) 687 | { 688 | upminutes = 0; 689 | if (++uphours > 23) 690 | { 691 | uphours = 0; 692 | ++updays; 693 | } 694 | } 695 | } 696 | } 697 | } 698 | 699 | void logfcount64() // called once per second from ISR to update all the ring buffers 700 | { 701 | // 10 seconds buffer 702 | circbuf_ten64[cbiten_newest]=fcount64; 703 | cbiten_newest++; 704 | if (cbiten_newest > 10) { 705 | cbTen_full=true; // this only needs to happen once, when the buffer fills up for the first time 706 | cbiten_newest = 0; // (wrap around) 707 | } 708 | // 100 seconds buffer 709 | circbuf_hun64[cbihun_newest]=fcount64; 710 | cbihun_newest++; 711 | if (cbihun_newest > 100) { 712 | cbHun_full=true; // this only needs to happen once, when the buffer fills up for the first time 713 | cbihun_newest = 0; // (wrap around) 714 | } 715 | // 1000 seconds buffer 716 | circbuf_tho64[cbitho_newest]=fcount64; 717 | cbitho_newest++; 718 | if (cbitho_newest > 1000) { 719 | cbTho_full=true; // this only needs to happen once, when the buffer fills up for the first time 720 | cbitho_newest = 0; // (wrap around) 721 | } 722 | // 10000 seconds buffer (2 hr 46 min 40 sec) 723 | circbuf_tth64[cbitth_newest]=fcount64; 724 | cbitth_newest++; 725 | if (cbitth_newest > 10000) { 726 | cbTth_full=true; // this only needs to happen once, when the buffer fills up for the first time 727 | cbitth_newest = 0; // (wrap around) 728 | } 729 | 730 | calcavg(); // always recalculate averages after logging fcount (if the respective buffers are full) 731 | } 732 | 733 | void calcavg() { 734 | // Calculate the OCXO frequency to 1, 2, 3 or 4 decimal places only when the respective buffers are full 735 | // Try to understand the algorithm for the 10s ring buffer first, the others work exactly the same 736 | 737 | uint64_t latfcount64, oldfcount64; // latest fcount, oldest fcount stored in ring buffer 738 | 739 | if (cbTen_full) { // we want (latest fcount - oldest fcount) / 10 740 | // latest fcount is always circbuf_ten64[cbiten_newest-1] 741 | // except when cbiten_newest is zero 742 | // oldest fcount is always circbuf_ten64[cbiten_newest] when buffer is full 743 | if (cbiten_newest == 0) latfcount64 = circbuf_ten64[10]; 744 | else latfcount64 = circbuf_ten64[cbiten_newest-1]; 745 | oldfcount64 = circbuf_ten64[cbiten_newest]; 746 | // now that we have latfcount64 and oldfcount64 we can calculate the average frequency 747 | avgften = double(latfcount64 - oldfcount64)/10.0; 748 | } 749 | if (cbHun_full) { // we want (latest fcount - oldest fcount) / 100 750 | 751 | // latest fcount is always circbuf_hun[cbihun_newest-1] 752 | // except when cbihun_newest is zero 753 | // oldest fcount is always circbuf_hun[cbihun_newest] when buffer is full 754 | 755 | if (cbihun_newest == 0) latfcount64 = circbuf_hun64[100]; 756 | else latfcount64 = circbuf_hun64[cbihun_newest-1]; 757 | oldfcount64 = circbuf_hun64[cbihun_newest]; 758 | 759 | avgfhun = double(latfcount64 - oldfcount64)/100.0; 760 | } 761 | if (cbTho_full) { // we want (latest fcount - oldest fcount) / 1000 762 | 763 | // latest fcount is always circbuf_tho[cbitho_newest-1] 764 | // except when cbitho_newest is zero 765 | // oldest fcount is always circbuf_tho[cbitho_newest] when buffer is full 766 | 767 | if (cbitho_newest == 0) latfcount64 = circbuf_tho64[1000]; 768 | else latfcount64 = circbuf_tho64[cbitho_newest-1]; 769 | oldfcount64 = circbuf_tho64[cbitho_newest]; 770 | 771 | avgftho = double(latfcount64 - oldfcount64)/1000.0; 772 | // oldest fcount is always circbuf_ten[cbiten_newest-2] 773 | // except when cbiten_newest is <2 (zero or 1) 774 | } 775 | if (cbTth_full) { // we want (latest fcount - oldest fcount) / 10000 776 | 777 | // latest fcount is always circbuf_tth[cbitth_newest-1] 778 | // except when cbitth_newest is zero 779 | // oldest fcount is always circbuf_tth[cbitth_newest] when buffer is full 780 | 781 | if (cbitth_newest == 0) latfcount64 = circbuf_tth64[10000]; 782 | else latfcount64 = circbuf_tth64[cbitth_newest-1]; 783 | oldfcount64 = circbuf_tth64[cbitth_newest]; 784 | 785 | avgftth = double(latfcount64 - oldfcount64)/10000.0; 786 | // oldest fcount is always circbuf_ten[cbiten_newest-2] 787 | // except when cbiten_newest is <2 (zero or 1) 788 | } 789 | } 790 | 791 | void flushringbuffers(void) { 792 | cbTen_full = false; 793 | cbHun_full = false; 794 | cbTho_full = false; 795 | cbTth_full = false; 796 | cbiten_newest = 0; 797 | cbihun_newest = 0; 798 | cbitho_newest = 0; 799 | cbitth_newest = 0; 800 | avgften = 0; 801 | avgfhun = 0; 802 | avgftho = 0; 803 | avgftth = 0; 804 | prevfcount64 = 0; 805 | previousfcount = 0; 806 | flush_ring_buffers_flag = false; // clear flag 807 | } 808 | 809 | void pinModeAF(int ulPin, uint32_t Alternate) 810 | { 811 | int pn = digitalPinToPinName(ulPin); 812 | 813 | if (STM_PIN(pn) < 8) { 814 | LL_GPIO_SetAFPin_0_7( get_GPIO_Port(STM_PORT(pn)), STM_LL_GPIO_PIN(pn), Alternate); 815 | } else { 816 | LL_GPIO_SetAFPin_8_15(get_GPIO_Port(STM_PORT(pn)), STM_LL_GPIO_PIN(pn), Alternate); 817 | } 818 | 819 | LL_GPIO_SetPinMode(get_GPIO_Port(STM_PORT(pn)), STM_LL_GPIO_PIN(pn), LL_GPIO_MODE_ALTERNATE); 820 | } 821 | 822 | #ifdef GPSDO_UBX_CONFIG 823 | void ubxconfig() // based on code by Brad Burleson 824 | { 825 | // send UBX commands to set optimal configuration for GPSDO use 826 | // we are going to change a single parameter from default by 827 | // setting the navigation mode to "stationary" 828 | 829 | bool gps_set_success = false; // flag setting GPS configuration success 830 | 831 | // This UBX command sets stationary mode and confirms it 832 | Serial.println("Setting u-Blox M8 receiver navigation mode to stationary: "); 833 | uint8_t setNav[] = { 834 | 0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x53}; 835 | while(!gps_set_success) 836 | { 837 | sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t)); 838 | Serial.println(); 839 | Serial.println("UBX command sent, waiting for UBX ACK... "); 840 | gps_set_success=getUBX_ACK(setNav); 841 | if (gps_set_success) 842 | Serial.println("Success: UBX ACK received! "); 843 | else 844 | Serial.println("Oops, something went wrong here... "); 845 | } 846 | } 847 | 848 | // Send a byte array of UBX protocol to the GPS 849 | void sendUBX(uint8_t *MSG, uint8_t len) { 850 | for(int i=0; i 9) { 887 | // All packets in order! 888 | Serial.println(" (SUCCESS!)"); 889 | return true; 890 | } 891 | 892 | // Timeout if no valid response in 3 seconds 893 | if (millis() - startTime > 3000) { 894 | Serial.println(" (FAILED!)"); 895 | return false; 896 | } 897 | 898 | // Make sure data is available to read 899 | if (Serial1.available()) { 900 | b = Serial1.read(); 901 | 902 | // Check that bytes arrive in sequence as per expected ACK packet 903 | if (b == ackPacket[ackByteID]) { 904 | ackByteID++; 905 | Serial.print(b, HEX); 906 | } 907 | else { 908 | ackByteID = 0; // Reset and look again, invalid order 909 | } 910 | 911 | } 912 | } 913 | } 914 | #endif // UBX_CONFIG 915 | 916 | // --------------------------------------------------------------------------------------------- 917 | // GPSDO tunnel mode (GPS serial is relayed to Bluetooth serial or USB serial) 918 | // --------------------------------------------------------------------------------------------- 919 | void tunnelgps() 920 | // GPSDO tunnel mode operation 921 | { 922 | #ifdef GPSDO_BLUETOOTH // print entering tunnel mode message to either 923 | Serial2.println(); // Bluetooth serial xor USB serial 924 | Serial2.print(F("Entering tunnel mode...")); 925 | Serial2.println(); 926 | #else 927 | Serial.println(); 928 | Serial.print(F("Entering tunnel mode...")); 929 | Serial.println(); 930 | #endif // BLUETOOTH 931 | 932 | // tunnel mode operation starts here 933 | uint32_t endtunnelmS = millis() + (tunnelSecs * 1000); 934 | uint8_t GPSchar; 935 | uint8_t PCchar; 936 | while (millis() < endtunnelmS) 937 | { 938 | if (Serial1.available() > 0) 939 | { 940 | GPSchar = Serial1.read(); 941 | #ifdef GPSDO_BLUETOOTH 942 | Serial2.write(GPSchar); // echo GPS NMEA serial stream to Bluetooth serial 943 | #else 944 | Serial.write(GPSchar); // echo GPS NMEA serial stream to USB serial 945 | #endif // BLUETOOTH 946 | } 947 | #ifdef GPSDO_BLUETOOTH 948 | if (Serial2.available() > 0) 949 | #else 950 | if (Serial.available() > 0) 951 | #endif // BLUETOOTH 952 | { 953 | #ifdef GPSDO_BLUETOOTH 954 | PCchar = Serial2.read(); 955 | #else 956 | PCchar = Serial.read(); 957 | #endif // BLUETOOTH 958 | Serial1.write(PCchar); // echo USB serial stream to GPS serial 959 | } 960 | } 961 | // tunnel mode operation ends here 962 | 963 | #ifdef GPSDO_BLUETOOTH // print exiting tunnel mode message to either 964 | Serial2.println(); // Bluetooth serial xor USB serial 965 | Serial2.print(F("Tunnel mode exited.")); 966 | Serial2.println(); 967 | #else 968 | Serial.println(); 969 | Serial.print(F("Tunnel mode exited.")); 970 | Serial.println(); 971 | #endif // BLUETOOTH 972 | 973 | tunnel_mode_flag = false; // reset flag, exit tunnel mode 974 | } // end of tunnel mode routine 975 | 976 | // --------------------------------------------------------------------------------------------- 977 | // OCXO warmup delay routine (only needed during a GPSDO "cold start") 978 | // --------------------------------------------------------------------------------------------- 979 | void doocxowarmup() 980 | { 981 | // Spend a few seconds/minutes here just waiting for the OCXO to warmup 982 | // show countdown timer on OLED or LCD display 983 | // and report on either USB serial or Bluetooth serial 984 | // Note: during OCXO warmup the GPSDO does not accept any commands 985 | uint16_t countdown = ocxo_warmup_time; 986 | while (countdown) { 987 | 988 | #ifdef GPSDO_OLED 989 | disp.clear(); // display warmup message on OLED 990 | disp.setCursor(0, 0); 991 | disp.print(F(Program_Name)); 992 | disp.print(F(" - ")); 993 | disp.print(F(Program_Version)); 994 | disp.setCursor(0, 2); 995 | disp.print(F("OCXO warming up")); 996 | disp.setCursor(0, 3); 997 | disp.print(F("Please wait")); 998 | disp.setCursor(5, 4); 999 | disp.print(countdown); 1000 | disp.print(F("s")); 1001 | #endif // OLED 1002 | 1003 | #ifdef GPSDO_LCD_ST7735 1004 | disp.fillScreen(ST7735_BLACK); // display warmup message on LCD ST7735 1005 | disp.setCursor(0, 0); 1006 | disp.print(F(Program_Name)); 1007 | disp.print(F(" - ")); 1008 | disp.print(F(Program_Version)); 1009 | disp.setCursor(0, 16); 1010 | disp.print(F("OCXO warming up")); 1011 | disp.setCursor(0, 24); 1012 | disp.print(F("Please wait")); 1013 | disp.setCursor(0, 32); 1014 | disp.print(countdown); 1015 | disp.print(F("s")); 1016 | #endif // LCD_ST7735 1017 | 1018 | #ifdef GPSDO_LCD_ST7789 1019 | // display OCXO warmup message on ST7789 LCD 1020 | disp_st7789.fillScreen(ST77XX_BLACK); // clear display 1021 | // Display program name and version 1022 | disp_st7789.setTextSize(1); 1023 | disp_st7789.setFont(&FreeMonoBold12pt7b); 1024 | disp_st7789.setTextColor(ST77XX_YELLOW); 1025 | disp_st7789.setCursor(0, 16); 1026 | disp_st7789.print(F("STM32 ")); 1027 | disp_st7789.print(F(Program_Name)); 1028 | disp_st7789.setTextSize(1); 1029 | disp_st7789.setFont(&FreeMono9pt7b); 1030 | disp_st7789.setTextColor(ST77XX_CYAN); 1031 | disp_st7789.setCursor(168, 11); 1032 | disp_st7789.print(F(Program_Version)); 1033 | // display OCXO warming up and countdown 1034 | disp_st7789.setCursor(0, 36); 1035 | disp_st7789.setTextColor(ST77XX_WHITE); 1036 | disp_st7789.print(F("OCXO warming up")); 1037 | disp_st7789.setCursor(0, 50); 1038 | disp_st7789.print(F("Please wait")); 1039 | disp_st7789.setCursor(0, 64); 1040 | disp_st7789.print(countdown); 1041 | disp_st7789.print(F("s")); 1042 | 1043 | must_clear_disp_st7789 = true; 1044 | 1045 | #endif // LCD_ST7789 1046 | 1047 | #ifdef GPSDO_BLUETOOTH // print warmup countdown message to either 1048 | Serial2.println(); // Bluetooth serial xor USB serial 1049 | Serial2.print(F("OCXO Warming up, ")); 1050 | Serial2.print(countdown); 1051 | Serial2.println(F("s remaining")); 1052 | #else 1053 | Serial.println(); 1054 | Serial.print(F("OCXO Warming up, ")); 1055 | Serial.print(countdown); 1056 | Serial.println(F("s remaining")); 1057 | #endif // BLUETOOTH 1058 | 1059 | // do nothing for 1s 1060 | delay(1000); 1061 | countdown--; 1062 | } 1063 | ocxo_needs_warming = false; // reset flag, next "hot" calibration skips ocxo warmup 1064 | } // end of OCXO warmup routine 1065 | 1066 | // --------------------------------------------------------------------------------------------- 1067 | // GPSDO calibration routine 1068 | // --------------------------------------------------------------------------------------------- 1069 | void docalibration() 1070 | // OCXO Vctl calibration: find an approximate value for Vctl 1071 | { 1072 | yellow_led_state = 2; // blink yellow LED (handled by 2Hz ISR) 1073 | 1074 | if (ocxo_needs_warming) doocxowarmup(); 1075 | 1076 | // Note: during calibration the GPSDO does not accept any commands 1077 | #ifdef GPSDO_BLUETOOTH // print calibration started message to either 1078 | Serial2.println(); // Bluetooth serial xor USB serial 1079 | Serial2.print(F("Calibrating...")); 1080 | Serial2.println(); 1081 | #else 1082 | Serial.println(); 1083 | Serial.print(F("Calibrating...")); 1084 | Serial.println(); 1085 | #endif // BLUETOOTH 1086 | 1087 | #ifdef GPSDO_OLED 1088 | disp.clear(); // display calibrating message on OLED 1089 | disp.setCursor(0, 0); 1090 | disp.print(F(Program_Name)); 1091 | disp.print(F(" - ")); 1092 | disp.print(F(Program_Version)); 1093 | disp.setCursor(0, 2); 1094 | disp.print(F("Calibrating...")); 1095 | disp.setCursor(0, 3); 1096 | disp.print(F("Please wait")); 1097 | #endif // OLED 1098 | 1099 | #ifdef GPSDO_LCD_ST7735 1100 | disp.fillScreen(ST7735_BLACK); // display calibrating message on LCD ST7735 1101 | disp.setCursor(0, 0); 1102 | disp.print(F(Program_Name)); 1103 | disp.print(F(" - ")); 1104 | disp.print(F(Program_Version)); 1105 | disp.setCursor(0, 16); 1106 | disp.print(F("Calibrating...")); 1107 | disp.setCursor(0, 24); 1108 | disp.print(F("Please wait")); 1109 | #endif // LCD_ST7735 1110 | 1111 | #ifdef GPSDO_LCD_ST7789 1112 | // display calibrating message on LCD ST7789 1113 | 1114 | disp_st7789.fillScreen(ST77XX_BLACK); // clear display 1115 | 1116 | // display program name and version 1117 | disp_st7789.setTextSize(1); 1118 | disp_st7789.setFont(&FreeMonoBold12pt7b); 1119 | disp_st7789.setTextColor(ST77XX_YELLOW); 1120 | disp_st7789.setCursor(0, 16); 1121 | disp_st7789.print(F("STM32 ")); 1122 | disp_st7789.print(F(Program_Name)); 1123 | disp_st7789.setTextSize(1); 1124 | disp_st7789.setFont(&FreeMono9pt7b); 1125 | disp_st7789.setTextColor(ST77XX_CYAN); 1126 | disp_st7789.setCursor(168, 11); 1127 | disp_st7789.print(F(Program_Version)); 1128 | 1129 | // display calibrating message 1130 | disp_st7789.setCursor(0, 36); 1131 | disp_st7789.setTextColor(ST77XX_WHITE); 1132 | disp_st7789.print(F("Calibrating...")); 1133 | disp_st7789.setCursor(0, 50); 1134 | disp_st7789.print(F("Please wait")); 1135 | 1136 | must_clear_disp_st7789 = true; 1137 | 1138 | #endif // LCD_ST7789 1139 | 1140 | /* The calibration algorithm 1141 | * The objective of the calibration is to find the approximate Vctl to obtain 1142 | * 10MHz +/- 0.1Hz. 1143 | * 1144 | * we can use either a PID algorithm or a simple linear interpolation algorithm 1145 | * 1146 | * The following describes a simple linear interpolation algorithm 1147 | * 1148 | * We first output 1.5V for the DAC or PWM, wait 30 seconds and note the 10s frequency average. 1149 | * Next we output 2.5V for the DAC or PWM, wait 30 seconds and note the 10s frequency average. 1150 | * Now we calculate the Vctl for 10MHz +/- 0.1Hz using linear interpolation between the two points. 1151 | */ 1152 | // for 12-bit DAC 1153 | // 1.5V for DAC = 4096 x (1.5 / 3.3) = 1862 results in frequency f1 = 10MHz + e1 1154 | // 2.5V for DAC = 4096 x (2.5 / 3.3) = 3103 results in frequency f2 = 10MHz + e2 1155 | // for 16-bit PWM 1156 | // 1.5V for PWM = 65536 x (1.5 / 3.2) = 30720 results in frequency f1 = 10MHz + e1 1157 | // 2.5V for PWM = 65536 x (2.5 / 3.2) = 51200 results in frequency f2 = 10MHz + e2 1158 | // where f2 > f1 (most OCXOs have positive slope). 1159 | 1160 | double f1, f2, e1, e2; 1161 | 1162 | // make sure we have a fix and data 1163 | while (!cbTen_full) delay(1000); // note there is a small chance that we lose PPS during calibration 1164 | // resulting in completely wrong calibration value 1165 | 1166 | // measure frequency for Vctl=1.5V 1167 | Serial.println(F("Measure frequency for Vctl=1.5V")); 1168 | Serial.print(F("Set PWM Vctl to 1.5V, wait ")); Serial.print(ocxo_calib_time); Serial.println(F("s")); 1169 | analogWrite(VctlPWMOutputPin, 30720); 1170 | 1171 | uint16_t calib_countdown = ocxo_calib_time; // note there are two possible values depending on FastBootMode setting 1172 | while (calib_countdown > 0) 1173 | { 1174 | calib_countdown--; 1175 | Serial.print(calib_countdown); Serial.print(F("s ")); 1176 | delay(1000); 1177 | } 1178 | 1179 | Serial.println(); 1180 | Serial.print(F("f1 (average frequency for Vctl=1.5V): ")); 1181 | f1 = avgften; 1182 | Serial.print(f1,1); 1183 | Serial.println(F(" Hz")); 1184 | Serial.println(); 1185 | 1186 | // make sure we have a fix and data again 1187 | while (!cbTen_full) delay(1000); 1188 | 1189 | // measure frequency for Vctl=2.5V 1190 | Serial.println(F("Measure frequency for Vctl=2.5V")); 1191 | Serial.println(F("Set PWM Vctl to 2.5V, wait ")); Serial.print(ocxo_calib_time); Serial.println(F("s")); 1192 | analogWrite(VctlPWMOutputPin, 51200); 1193 | 1194 | calib_countdown = ocxo_calib_time; // no need to declare variable again 1195 | while (calib_countdown > 0) 1196 | { 1197 | calib_countdown--; 1198 | Serial.print(calib_countdown); Serial.print(F("s ")); 1199 | delay(1000); 1200 | } 1201 | 1202 | Serial.println(); 1203 | Serial.print(F("f2 (average frequency for 2.5V Vctl): ")); 1204 | f2 = avgften; 1205 | Serial.print(f2,1); 1206 | Serial.println(F(" Hz")); 1207 | Serial.println(); 1208 | 1209 | // slope s is (f2-f1) / (51200-30720) for PWM 1210 | // So F=10MHz +/- 0.1Hz for PWM = 30720 - (e1 / s) 1211 | // set Vctl 1212 | // adjusted_PWM_output = formula 1213 | adjusted_PWM_output = 30720 - ((f1 - 10000000.0) / ((f2 - f1) / 20480)); 1214 | Serial.print(F("Calculated PWM: ")); 1215 | Serial.println(adjusted_PWM_output); 1216 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 1217 | // calibration done 1218 | 1219 | #ifdef GPSDO_BLUETOOTH // print calibration finished message to either 1220 | Serial2.println(); // Bluetooth serial xor USB serial 1221 | Serial2.print(F("Calibration done.")); 1222 | Serial2.println(); 1223 | #else 1224 | Serial.println(); 1225 | Serial.print(F("Calibration done.")); 1226 | Serial.println(); 1227 | #endif // BLUETOOTH 1228 | 1229 | #ifdef GPSDO_OLED 1230 | disp.clear(); // clear display and show program name and version again 1231 | disp.setCursor(0, 0); 1232 | disp.print(F(Program_Name)); 1233 | disp.print(F(" - ")); 1234 | disp.print(F(Program_Version)); 1235 | #endif // OLED 1236 | 1237 | #ifdef GPSDO_LCD_ST7735 1238 | disp.fillScreen(ST7735_BLACK); 1239 | #endif // LCD_ST7735 1240 | 1241 | #ifdef GPSDO_LCD_ST7789 1242 | disp_st7789.fillScreen(ST77XX_BLACK); 1243 | #endif // LCD_ST7789 1244 | 1245 | yellow_led_state = 0; // turn off yellow LED (handled by 2Hz ISR) 1246 | force_calibration_flag = false; // reset flag, calibration done 1247 | } // end of GPSDO calibration routine 1248 | 1249 | // --------------------------------------------------------------------------------------------- 1250 | // Adjust Vctl PWM routine 1251 | // --------------------------------------------------------------------------------------------- 1252 | #ifdef GPSDO_PWM_DAC 1253 | void adjustVctlPWM() 1254 | // This should reach a stable PWM output value / a stable 10000000.00 frequency 1255 | // after an hour or so, and 10000000.000 after eight hours or so 1256 | { 1257 | // check first if we have the data, then do ultrafine and veryfine frequency 1258 | // adjustment, when we are very close 1259 | // ultimately the objective is 10000000.000 over the last 1000s (16min40s) 1260 | if ((cbTho_full) && (avgftho >= 9999999.990) && (avgftho <= 10000000.010)) { 1261 | 1262 | // decrease frequency; 1000s based 1263 | if (avgftho >= 10000000.001) { 1264 | if (avgftho >= 10000000.005) { 1265 | // decrease PWM by 5 bits = very fine 1266 | adjusted_PWM_output = adjusted_PWM_output - 5; 1267 | strcpy(trendstr, " vf-"); 1268 | } 1269 | else { 1270 | // decrease PWM by one bit = ultrafine 1271 | adjusted_PWM_output = adjusted_PWM_output - 1; 1272 | strcpy(trendstr, " uf-"); 1273 | } 1274 | } 1275 | // or increase frequency; 1000s based 1276 | else if (avgftho <= 9999999.999) { 1277 | if (avgftho <= 9999999.995) { 1278 | // increase PWM by 5 bits = very fine 1279 | adjusted_PWM_output = adjusted_PWM_output + 5; 1280 | strcpy(trendstr, " vf+"); 1281 | } 1282 | else { 1283 | // increase PWM by one bit = ultrafine 1284 | adjusted_PWM_output = adjusted_PWM_output + 1; 1285 | strcpy(trendstr, " uf+"); 1286 | } 1287 | } 1288 | } 1289 | ///// next check the 100s values in second place because we are too far off 1290 | // decrease frequency; 100s based 1291 | else if (avgfhun >= 10000000.01) { 1292 | if (avgfhun >= 10000000.10) { 1293 | // decrease PWM by 100 bits = coarse 1294 | adjusted_PWM_output = adjusted_PWM_output - 100; 1295 | strcpy(trendstr, " c- "); 1296 | } 1297 | else { 1298 | // decrease PWM by ten bits = fine 1299 | adjusted_PWM_output = adjusted_PWM_output - 10; 1300 | strcpy(trendstr, " f- "); 1301 | } 1302 | } 1303 | // or increase frequency; 100s based 1304 | else if (avgfhun <= 9999999.99) { 1305 | if (avgfhun <= 9999999.90) { 1306 | // increase PWM by 100 bits = coarse 1307 | adjusted_PWM_output = adjusted_PWM_output + 100; 1308 | strcpy(trendstr, " c+ "); 1309 | } 1310 | else { 1311 | // increase PWM by ten bits = fine 1312 | adjusted_PWM_output = adjusted_PWM_output + 10; 1313 | strcpy(trendstr, " f+ "); 1314 | } 1315 | } 1316 | else { // here we keep setting, because it is exact 10000000.000MHz 1317 | strcpy(trendstr, " hit"); 1318 | } 1319 | // write the computed value to PWM 1320 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); 1321 | must_adjust_DAC = false; // clear flag and we are done 1322 | } // end adjustVctlPWM 1323 | #endif // GPSDO_PWM_DAC 1324 | 1325 | bool gpsWaitFix(uint16_t waitSecs) 1326 | { 1327 | // waits a specified number of seconds for a fix, 1328 | // returns true as soon as fix available or false on timeout 1329 | 1330 | uint32_t endwaitmS; 1331 | uint8_t GPSchar; 1332 | 1333 | if (!report_tab_delimited) { 1334 | #ifdef GPSDO_BLUETOOTH 1335 | Serial2.println(); 1336 | //Serial2.print(F("Wait for GPS fix max. ")); 1337 | //Serial2.print(waitSecs); 1338 | //if (waitSecs > 1) Serial2.println(F(" seconds")); else Serial2.println(F(" second")); 1339 | #else 1340 | Serial.println(); 1341 | //Serial.print(F("Wait for GPS fix max. ")); 1342 | //Serial.print(waitSecs); 1343 | //if (waitSecs > 1) Serial.println(F(" seconds")); else Serial.println(F(" second")); 1344 | #endif // Bluetooth 1345 | } 1346 | 1347 | endwaitmS = millis() + (waitSecs * 1000); 1348 | 1349 | while (millis() < endwaitmS) 1350 | { 1351 | if (Serial1.available() > 0) 1352 | { 1353 | GPSchar = Serial1.read(); 1354 | gps.encode(GPSchar); 1355 | if (!report_tab_delimited) { 1356 | #ifdef GPSDO_VERBOSE_NMEA 1357 | #ifdef GPSDO_BLUETOOTH 1358 | Serial2.write(GPSchar); // echo NMEA stream to Bluetooth serial 1359 | #else 1360 | Serial.write(GPSchar); // echo NMEA stream to USB serial 1361 | #endif // Bluetooth 1362 | #endif // VERBOSE_NMEA 1363 | } 1364 | } 1365 | 1366 | if (gps.location.isUpdated() && gps.altitude.isUpdated() && gps.date.isUpdated()) 1367 | { 1368 | endFixmS = millis(); //record the time when we got a GPS fix 1369 | return true; 1370 | } 1371 | } 1372 | return false; 1373 | } 1374 | 1375 | void printGPSDOtab(Stream &Serialx) { // tab delimited fields suitable for spreadsheet import 1376 | 1377 | /* 1378 | * STM32 GPSDO reporting tab delimited fields 1379 | * if any field is not available (e.g. sensor not configured), print "0" 1380 | 1381 | * Line no. (0 if no position fix, increments by one each second if position fix) 1382 | * timestamp (UTC) 1383 | * uptime (days hours mins secs) 1384 | * 64-bit counter 1385 | * frequency (Hz) 1386 | * 10s freq. avg. (one decimal) (Hz) 1387 | * 100s freq. avg. (two decimals) (Hz) 1388 | * 1,000s freq. avg. (three decimals) (Hz) 1389 | * 10,000s freq. avg. (four decimals) (Hz) 1390 | * no. of sats 1391 | * HDOP (meters) 1392 | * PWM (16-bit, 1-65535) 1393 | * PWM adc mov. avg. (V) 1394 | * Vcc adc mov. avg. (5.0V nominal) 1395 | * Vdd adc mov. avg. (3.3V nominal) 1396 | * BMP280 Temp. (C) 1397 | * BMP280 Atm. Pressure (hPa) 1398 | * AHT20 Temp. (C) 1399 | * AHT20 Humidity (%) 1400 | * INA219 OCXO Voltage (5.05V nominal) 1401 | * INA219 OCXO Current (mA, 2A maximum) 1402 | * TIC (10-bit, 1024ns max) 1403 | 1404 | * When a value is not available, field contains "0". 1405 | */ 1406 | 1407 | report_line_no++; // increment line number, first line is 1 1408 | 1409 | Serialx.print(report_line_no); // line number 1410 | Serialx.print("\t"); // tab 1411 | 1412 | Serialx.print(day); // date dd/mm/yyyy 1413 | Serialx.print(F("/")); 1414 | Serialx.print(month); 1415 | Serialx.print(F("/")); 1416 | Serialx.print(year); 1417 | Serialx.print(F(" ")); // 1418 | 1419 | if (hours < 10) { // time hh:mm:ss 1420 | Serialx.print(F("0")); 1421 | } 1422 | Serialx.print(hours); 1423 | Serialx.print(F(":")); 1424 | if (mins < 10) { 1425 | Serialx.print(F("0")); 1426 | } 1427 | Serialx.print(mins); 1428 | Serialx.print(F(":")); 1429 | if (secs < 10) { 1430 | Serialx.print(F("0")); 1431 | } 1432 | Serialx.print(secs); 1433 | Serialx.print("\t"); // tab 1434 | 1435 | Serialx.print(updaysstr); // uptime 000d hh:mm:ss 1436 | Serialx.print(F(" ")); // 1437 | Serialx.print(uptimestr); 1438 | Serialx.print("\t"); // tab 1439 | 1440 | Serialx.print(fcount64); // 64-bit counter 1441 | Serialx.print("\t"); // tab 1442 | 1443 | Serialx.print(calcfreq64); // frequency 1444 | Serialx.print("\t"); // tab 1445 | Serialx.print(avgften,1); // avg. 10s 1446 | Serialx.print("\t"); // tab 1447 | Serialx.print(avgfhun,2); // avg. 100s 1448 | Serialx.print("\t"); // tab 1449 | Serialx.print(avgftho,3); // avg. 1,000s 1450 | Serialx.print("\t"); // tab 1451 | Serialx.print(avgftth,4); // avg. 10,000s 1452 | Serialx.print("\t"); // tab 1453 | 1454 | Serialx.print(GPSSats); // sats 1455 | Serialx.print("\t"); // tab 1456 | 1457 | float tempfloat; // HDOP 1458 | tempfloat = ( (float) GPSHdop / 100); 1459 | Serialx.print(tempfloat, 2); 1460 | Serialx.print("\t"); // tab 1461 | 1462 | Serialx.print(adjusted_PWM_output); // PWM 1463 | Serialx.print("\t"); // tab 1464 | 1465 | float Vctlp = (float(avgpwmVctl)/4096) * 3.3; // PWM Vctl 1466 | Serialx.print(Vctlp); 1467 | Serialx.print("\t"); // tab 1468 | 1469 | #ifdef GPSDO_VCC 1470 | // Vcc/2 is provided on pin PA0 1471 | float Vcc = (float(avgVcc)/4096) * 3.3 * 2.0; 1472 | Serialx.print(Vcc); 1473 | #else 1474 | Serialx.print("0"); 1475 | #endif // VCC 1476 | Serialx.print("\t"); // tab 1477 | 1478 | #ifdef GPSDO_VDD 1479 | // internal sensor Vref 1480 | float Vdd = (1.21 * 4096) / float(avgVdd); // from STM32F411CEU6 datasheet 1481 | // Vdd = Vref on Black Pill 1482 | Serialx.print(Vdd); 1483 | #else 1484 | Serialx.print("0"); 1485 | #endif // VDD 1486 | Serialx.print("\t"); // tab 1487 | 1488 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 1489 | // BMP280 measurements 1490 | Serialx.print(bmp280temp, 1); 1491 | Serialx.print("\t"); 1492 | Serialx.print((bmp280pres+PressureOffset)/100, 1); 1493 | #else 1494 | Serialx.print("0"); 1495 | Serialx.print("\t"); 1496 | Serialx.print("0"); 1497 | #endif // BMP280_SPI 1498 | Serialx.print("\t"); // tab 1499 | 1500 | #ifdef GPSDO_AHT10 1501 | // AHT10/AHT20 measurements 1502 | sensors_event_t humidity, temp; 1503 | aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data 1504 | Serialx.print(temp.temperature); 1505 | Serialx.print("\t"); 1506 | Serialx.print(humidity.relative_humidity); 1507 | #else 1508 | Serialx.print("0"); 1509 | Serialx.print("\t"); 1510 | Serialx.print("0"); 1511 | #endif // AHT10 1512 | Serialx.print("\t"); // tab 1513 | 1514 | #ifdef GPSDO_INA219 1515 | // current sensor for the OCXO 1516 | Serialx.print(ina219volt, 2); 1517 | Serialx.print("\t"); 1518 | Serialx.print(ina219curr, 0); 1519 | #else 1520 | Serialx.print("0"); 1521 | Serialx.print("\t"); 1522 | Serialx.print("0"); 1523 | #endif // INA219 1524 | Serialx.print("\t"); // tab 1525 | 1526 | #ifdef GPSDO_TIC 1527 | // Phase difference in ns, WIP 1528 | #else 1529 | Serialx.print("0"); 1530 | #endif // INA219 1531 | 1532 | Serialx.println(); // end of line 1533 | 1534 | } // end of printGPSDOtab - tab delimited data output 1535 | 1536 | void printGPSDOstats(Stream &Serialx) { // human readable output 1537 | 1538 | float tempfloat; 1539 | 1540 | Serialx.print(F("Uptime: ")); 1541 | Serialx.print(updaysstr); 1542 | Serialx.print(F(" ")); 1543 | Serialx.println(uptimestr); 1544 | 1545 | Serialx.println(F("New GPS Fix: ")); 1546 | 1547 | tempfloat = ( (float) GPSHdop / 100); 1548 | 1549 | Serialx.print(F("Lat: ")); 1550 | Serialx.print(GPSLat, 6); 1551 | Serialx.print(F(" Lon: ")); 1552 | Serialx.print(GPSLon, 6); 1553 | Serialx.print(F(" Alt: ")); 1554 | Serialx.print(GPSAlt, 1); 1555 | Serialx.println(F("m")); 1556 | Serialx.print(F("Sats: ")); 1557 | Serialx.print(GPSSats); 1558 | Serialx.print(F(" HDOP: ")); 1559 | Serialx.println(tempfloat, 2); 1560 | Serialx.print(F("UTC Time: ")); 1561 | 1562 | if (hours < 10) { 1563 | Serialx.print(F("0")); 1564 | } 1565 | Serialx.print(hours); 1566 | Serialx.print(F(":")); 1567 | if (mins < 10) { 1568 | Serialx.print(F("0")); 1569 | } 1570 | Serialx.print(mins); 1571 | Serialx.print(F(":")); 1572 | if (secs < 10) { 1573 | Serialx.print(F("0")); 1574 | } 1575 | Serialx.print(secs); 1576 | 1577 | Serialx.print(F(" Date: ")); 1578 | 1579 | Serialx.print(day); 1580 | Serialx.print(F("/")); 1581 | Serialx.print(month); 1582 | Serialx.print(F("/")); 1583 | Serialx.println(year); 1584 | 1585 | Serialx.println(); 1586 | Serialx.println(F("Voltages: ")); 1587 | 1588 | float Vctlp = (float(avgpwmVctl)/4096) * 3.3; 1589 | Serialx.print("VctlPWM: "); 1590 | Serialx.print(Vctlp); 1591 | Serialx.print(" PWM: "); 1592 | Serialx.println(adjusted_PWM_output); 1593 | 1594 | #ifdef GPSDO_VCC 1595 | // Vcc/2 is provided on pin PA0 1596 | float Vcc = (float(avgVcc)/4096) * 3.3 * 2.0; 1597 | Serialx.print("Vcc: "); 1598 | Serialx.println(Vcc); 1599 | #endif // VCC 1600 | 1601 | #ifdef GPSDO_VDD 1602 | // internal sensor Vref 1603 | float Vdd = (1.21 * 4096) / float(avgVdd); // from STM32F411CEU6 datasheet 1604 | Serialx.print("Vdd: "); // Vdd = Vref on Black Pill 1605 | Serialx.println(Vdd); 1606 | #endif // VDD 1607 | 1608 | #ifdef GPSDO_INA219 1609 | // current sensor for the OCXO 1610 | Serialx.print(F("OCXO voltage: ")); 1611 | Serialx.print(ina219volt, 2); 1612 | Serialx.println(F("V")); 1613 | Serialx.print(F("OCXO current: ")); 1614 | Serialx.print(ina219curr, 0); 1615 | Serialx.println(F("mA")); 1616 | #endif // INA219 1617 | 1618 | // OCXO frequency measurements 1619 | Serialx.println(); 1620 | Serialx.println(F("Frequency measurements using 64-bit counter:")); 1621 | // temporarily added to check proper 16-bit PWM operation 1622 | // Serialx.print(F("TIM4 ARR: ")); // should in principle be 48000-1, because 96MHz / 2kHz = 48000 1623 | // Serialx.println(TIM4->ARR); // and yes, verified 1624 | // Serialx.print(F("TIM4 ch4 CCR: ")); // in principle, the PWM value x 48000/65536 1625 | // Serialx.println(TIM4->CCR4); // and also yes, verified 1626 | // end of temp code 1627 | // if (overflowErrorFlag) Serialx.println(F("ERROR: overflow ")); 1628 | // Serialx.print(F("Most Significant 32 bits (OverflowCounter): ")); 1629 | // Serialx.println(tim2overflowcounter); 1630 | // Serialx.print(F("Least Significant 32 bits (TIM2->CCR3): ")); 1631 | // Serialx.println(lsfcount); 1632 | Serialx.print(F("64-bit Counter: ")); 1633 | Serialx.println(fcount64); 1634 | Serialx.print(F("Frequency: ")); 1635 | Serialx.print(calcfreq64); 1636 | Serialx.println(F(" Hz")); 1637 | Serialx.print("10s Frequency Avg: "); 1638 | Serialx.print(avgften,1); 1639 | Serialx.println(F(" Hz")); 1640 | Serialx.print("100s Frequency Avg: "); 1641 | Serialx.print(avgfhun,2); 1642 | Serialx.println(F(" Hz")); 1643 | Serialx.print("1,000s Frequency Avg: "); 1644 | Serialx.print(avgftho,3); 1645 | Serialx.println(F(" Hz")); 1646 | Serialx.print("10,000s Frequency Avg: "); 1647 | Serialx.print(avgftth,4); 1648 | Serialx.println(F(" Hz")); 1649 | 1650 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 1651 | // BMP280 measurements 1652 | Serialx.println(); 1653 | Serialx.print(F("BMP280 Temperature = ")); 1654 | Serialx.print(bmp280temp, 1); 1655 | Serialx.println(" *C"); 1656 | Serialx.print(F("Pressure = ")); 1657 | Serialx.print((bmp280pres+PressureOffset)/100, 1); 1658 | Serialx.println(" hPa"); 1659 | Serialx.print(F("Approx altitude = ")); 1660 | Serialx.print(bmp280alti, 1); /* Adjusted to local forecast! */ 1661 | Serialx.println(" m"); 1662 | #endif // BMP280_SPI 1663 | 1664 | #ifdef GPSDO_AHT10 1665 | // AHT10 measurements 1666 | sensors_event_t humidity, temp; 1667 | aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data 1668 | Serialx.print("AHT10 Temperature: "); 1669 | Serialx.print(temp.temperature); 1670 | Serialx.println(" *C"); 1671 | Serialx.print("Humidity: "); 1672 | Serialx.print(humidity.relative_humidity); 1673 | Serialx.println("% rH"); 1674 | #endif // AHT10 1675 | 1676 | Serialx.println(); 1677 | } 1678 | 1679 | #ifdef GPSDO_OLED 1680 | void displayscreen_OLED() // show GPSDO data on OLED display 1681 | { 1682 | float tempfloat; 1683 | 1684 | // OCXO frequency 1685 | disp.setCursor(0, 1); 1686 | disp.print(F("F ")); 1687 | // display 1s, 10s or 100s value depending on whether data is available 1688 | if (cbTen_full) { 1689 | if (cbHun_full) { // if we have data over 100 seconds 1690 | if (avgfhun < 10000000) { 1691 | disp.setCursor(2, 1); disp.print(" "); 1692 | } 1693 | else disp.setCursor(2, 1); 1694 | disp.print(avgfhun, 2); // to 2 decimal places 1695 | disp.print("Hz "); 1696 | } 1697 | else { // nope, only 10 seconds 1698 | if (avgften < 10000000) { 1699 | disp.setCursor(2, 1); disp.print(" "); 1700 | } 1701 | else disp.setCursor(2, 1); 1702 | disp.print(avgften, 1); // to 1 decimal place 1703 | disp.print("Hz "); 1704 | } 1705 | } 1706 | else { // we don't have any averages 1707 | calcfreqint = calcfreq64; // convert to 32-bit integer 1708 | if (calcfreqint < 10000000) { 1709 | disp.setCursor(2, 1); disp.print(" "); 1710 | } 1711 | else disp.setCursor(2, 1); 1712 | disp.print(calcfreqint); // integer 1713 | disp.print("Hz "); 1714 | } 1715 | 1716 | // Latitude 1717 | //disp.clearLine(2); 1718 | disp.setCursor(0, 2); 1719 | disp.print(GPSLat, 6); 1720 | // Longitude 1721 | //disp.clearLine(3); 1722 | disp.setCursor(0, 3); 1723 | disp.print(GPSLon, 6); 1724 | // Altitude and Satellites 1725 | //disp.clearLine(4); 1726 | disp.setCursor(0, 4); 1727 | disp.print(GPSAlt); 1728 | disp.print(F("m ")); 1729 | disp.setCursor(9, 4); 1730 | disp.print(F("Sats ")); 1731 | disp.print(GPSSats); 1732 | if (GPSSats < 10) disp.print(F(" ")); // clear possible digit when sats >= 10 1733 | // HDOP 1734 | //disp.clearLine(5); 1735 | disp.setCursor(0, 5); 1736 | // choose HDOP or uptime 1737 | //disp.print(F("HDOP ")); 1738 | //tempfloat = ((float) GPSHdop / 100); 1739 | //disp.print(tempfloat); 1740 | disp.print(F("Up ")); 1741 | disp.print(updaysstr); 1742 | disp.print(F(" ")); 1743 | disp.print(uptimestr); 1744 | 1745 | // Time 1746 | //disp.clearLine(6); 1747 | disp.setCursor(0, 6); 1748 | 1749 | if (hours < 10) 1750 | { 1751 | disp.print(F("0")); 1752 | } 1753 | 1754 | disp.print(hours); 1755 | disp.print(F(":")); 1756 | 1757 | if (mins < 10) 1758 | { 1759 | disp.print(F("0")); 1760 | } 1761 | 1762 | disp.print(mins); 1763 | disp.print(F(":")); 1764 | 1765 | if (secs < 10) 1766 | { 1767 | disp.print(F("0")); 1768 | } 1769 | 1770 | disp.print(secs); 1771 | disp.print(F(" ")); 1772 | 1773 | // Date 1774 | //disp.clearLine(7); 1775 | disp.setCursor(0, 7); 1776 | 1777 | disp.print(day); 1778 | disp.print(F("/")); 1779 | disp.print(month); 1780 | disp.print(F("/")); 1781 | disp.print(year); 1782 | 1783 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 1784 | // BMP280 temperature 1785 | disp.setCursor(10, 6); 1786 | disp.print(bmp280temp, 1); 1787 | disp.print(F("C")); 1788 | #endif // BMP280_SPI 1789 | 1790 | #ifdef GPSDO_VCC 1791 | disp.setCursor(11, 2); 1792 | // Vcc/2 is provided on pin PA0 1793 | float Vcc = (float(avgVcc)/4096) * 3.3 * 2.0; 1794 | disp.print(Vcc); 1795 | disp.print(F("V")); 1796 | #endif // VCC 1797 | 1798 | #ifdef GPSDO_VDD 1799 | // internal sensor Vref 1800 | disp.setCursor(11, 3); 1801 | float Vdd = (1.21 * 4096) / float(avgVdd); // from STM32F411CEU6 datasheet 1802 | disp.print(Vdd); // Vdd = Vref on Black Pill 1803 | disp.print(F("V")); 1804 | #endif // VDD 1805 | 1806 | disp.setCursor(11, 7); // display PWM/DAC value 1807 | #ifdef GPSDO_PWM_DAC 1808 | disp.print(adjusted_PWM_output); 1809 | #else 1810 | disp.print(adjusted_DAC_output); 1811 | #endif // PWM_DAC 1812 | } 1813 | #endif // OLED 1814 | 1815 | #ifdef GPSDO_LCD_ST7735 1816 | void displayscreen_LCD_ST7735() // show GPSDO data on LCD ST7735 display 1817 | // we use font1 8x6 pix and font2 16x12 pix 1818 | { 1819 | float tempfloat; 1820 | 1821 | // Latitude 1822 | disp.setCursor(0, 40); 1823 | disp.print(F("Lat: ")); 1824 | disp.print(GPSLat, 6); 1825 | // Longitude 1826 | disp.setCursor(0, 48); 1827 | disp.print(F("Lon: ")); 1828 | disp.print(GPSLon, 6); 1829 | // Altitude 1830 | disp.setCursor(0, 56); 1831 | disp.print(F("Alt: ")); 1832 | disp.print(GPSAlt); 1833 | disp.print(F("m ")); 1834 | //Satellites 1835 | disp.setCursor(90, 40); 1836 | disp.print(F("Sats: ")); 1837 | disp.print(GPSSats); 1838 | if (GPSSats < 10) disp.print(F(" ")); // clear possible digit when sats >= 10 1839 | // HDOP 1840 | disp.setCursor(0, 64); 1841 | // choose HDOP or uptime 1842 | //disp.print(F("HDOP ")); 1843 | //tempfloat = ((float) GPSHdop / 100); 1844 | //disp.print(tempfloat); 1845 | disp.print(F("UpT: ")); 1846 | disp.print(updaysstr); 1847 | //disp.print(F(" ")); 1848 | disp.setCursor(30, 72); 1849 | disp.print(uptimestr); 1850 | 1851 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 1852 | // BMP280 temperature 1853 | disp.setCursor(90, 64); 1854 | disp.print(F(" ")); 1855 | disp.print((char)247); 1856 | //disp.print((char)9); 1857 | disp.print(F("C: ")); 1858 | disp.print(bmp280temp, 1); 1859 | // BMP280 pressure 1860 | disp.setCursor(90, 72); 1861 | disp.print(F("hPa: ")); 1862 | disp.print(((bmp280pres+PressureOffset)/100), 1); 1863 | #endif // BMP280_SPI 1864 | 1865 | #ifdef GPSDO_VCC 1866 | disp.setCursor(90, 48); 1867 | // Vcc/2 is provided on pin PA0 1868 | float Vcc = (float(avgVcc)/4096) * 3.3 * 2.0; 1869 | disp.print(F("5V0: ")); 1870 | disp.print(Vcc); 1871 | disp.print(F("V")); 1872 | #endif // VCC 1873 | 1874 | #ifdef GPSDO_VDD 1875 | // internal sensor Vref 1876 | disp.setCursor(90, 56); 1877 | float Vdd = (1.21 * 4096) / float(avgVdd); // from STM32F411CEU6 datasheet 1878 | disp.print(F("3V3: ")); 1879 | disp.print(Vdd); // Vdd = Vref on Black Pill 1880 | disp.print(F("V")); 1881 | #endif // VDD 1882 | 1883 | disp.setCursor(0, 80); // display PWM/DAC value 1884 | #ifdef GPSDO_PWM_DAC 1885 | disp.print(F("PWM: ")); 1886 | disp.print(adjusted_PWM_output); 1887 | disp.print(F(trendstr)); 1888 | #endif // PWM_DAC 1889 | 1890 | // display vref value 1891 | disp.setCursor(90, 80); // display vref value 1892 | float Vctlp = (float(avgpwmVctl)/4096) * 3.3; 1893 | disp.print(F("Vctl: ")); 1894 | disp.print(Vctlp); 1895 | disp.print(F("V")); 1896 | 1897 | // Display Headline and Version 1898 | disp.setTextColor(ST7735_YELLOW, ST7735_BLACK); 1899 | disp.setTextSize(2); 1900 | disp.setCursor(0, 0); 1901 | disp.print(F(" ")); 1902 | disp.print(F(Program_Name)); 1903 | // 1904 | disp.setTextSize(1); 1905 | disp.setCursor(115, 5); 1906 | disp.setTextColor(ST7735_BLUE, ST7735_BLACK); 1907 | disp.print(F(Program_Version)); 1908 | disp.setTextSize(2); 1909 | 1910 | // OCXO frequency 1911 | disp.setCursor(0, 19); 1912 | disp.setTextColor(ST7735_YELLOW, ST7735_BLACK); 1913 | 1914 | // display 1s, 10s or 100s value depending on whether data is available 1915 | if (cbTen_full) { 1916 | if (cbTho_full) { // if we have data over 1000 seconds 1917 | if (avgftho < 10000000) { 1918 | disp.print(" "); 1919 | } 1920 | disp.print(avgftho, 3); // to 3 decimal places 1921 | } 1922 | else if (cbHun_full) { 1923 | if (avgfhun < 10000000) { 1924 | disp.print(" "); 1925 | } 1926 | disp.print(avgfhun, 2); // to 2 decimal places 1927 | disp.print(" "); 1928 | } 1929 | 1930 | else { // nope, only 10 seconds 1931 | if (avgften < 10000000) { 1932 | disp.print(" "); 1933 | } 1934 | disp.print(avgften, 1); // to 1 decimal place 1935 | disp.print(" "); 1936 | } 1937 | } 1938 | else { // we don't have any averages and print integer value 1939 | calcfreqint = calcfreq64; // convert to 32-bit integer 1940 | if (calcfreqint < 10000000) { 1941 | disp.print(" "); 1942 | } 1943 | disp.print(calcfreqint); // integer 1944 | disp.print(" "); // these are used for more exact dispaly 1945 | } 1946 | // due to limited space small character unit 1947 | disp.setTextSize(1); 1948 | disp.setCursor(144, 19); 1949 | // due to some unknown issue in printing the freq digits/unit we clear the section of the display first 1950 | disp.fillRect(144, 19, 15, 20, ST7735_BLACK); 1951 | disp.print("Hz"); 1952 | 1953 | // clock and date 1954 | disp.setTextSize(2); 1955 | disp.setTextColor(ST7735_RED, ST7735_BLACK); 1956 | // Date 1957 | disp.setCursor(2, 94); 1958 | //disp.print(F("Date: ")); 1959 | disp.print(day); 1960 | disp.print(F(".")); 1961 | disp.print(month); 1962 | disp.print(F(".")); 1963 | disp.print(year); 1964 | 1965 | // Time 1966 | disp.setTextColor(ST7735_GREEN, ST7735_BLACK); 1967 | disp.setCursor(2, 113); 1968 | 1969 | if (hours < 10) 1970 | { 1971 | disp.print(F("0")); 1972 | } 1973 | 1974 | disp.print(hours); 1975 | disp.print(F(":")); 1976 | 1977 | if (mins < 10) 1978 | { 1979 | disp.print(F("0")); 1980 | } 1981 | 1982 | disp.print(mins); 1983 | disp.print(F(":")); 1984 | 1985 | if (secs < 10) 1986 | { 1987 | disp.print(F("0")); 1988 | } 1989 | 1990 | disp.print(secs); 1991 | disp.setTextColor(ST7735_WHITE, ST7735_BLACK); 1992 | disp.print(F(" UTC")); 1993 | 1994 | // reset all font stuff for normal display 1995 | disp.setTextSize(1); 1996 | disp.setTextColor(ST7735_WHITE, ST7735_BLACK); 1997 | 1998 | } 1999 | #endif // LCD_ST7735 2000 | 2001 | #ifdef GPSDO_LCD_ST7789 2002 | void displayscreen_LCD_ST7789() { // show GPSDO data on LCD ST7789 display 2003 | // we use Mono fonts and built-in fonts 2004 | float tempfloat; 2005 | 2006 | // check if we have to clear the display 2007 | if (must_clear_disp_st7789) { 2008 | disp_st7789.fillScreen(ST77XX_BLACK); // clear display 2009 | must_clear_disp_st7789 = false; // reset flag 2010 | } 2011 | disp_st7789.fillScreen(ST77XX_BLACK); // clear display 2012 | // Display program name and version 2013 | disp_st7789.setTextSize(1); 2014 | disp_st7789.setFont(&FreeMonoBold12pt7b); 2015 | disp_st7789.setTextColor(ST77XX_YELLOW); 2016 | disp_st7789.setCursor(0, 16); 2017 | disp_st7789.print(F("STM32 ")); 2018 | disp_st7789.print(F(Program_Name)); 2019 | disp_st7789.setFont(&FreeMono9pt7b); 2020 | disp_st7789.setTextColor(ST77XX_CYAN); 2021 | disp_st7789.setCursor(168, 11); 2022 | disp_st7789.print(F(Program_Version)); 2023 | 2024 | // Latitude 2025 | disp_st7789.setTextColor(ST77XX_WHITE); 2026 | disp_st7789.setCursor(2, 60); 2027 | disp_st7789.print(F("Lat: ")); 2028 | // disp_st7789.print(GPSLat, 6); 2029 | disp_st7789.print("12.345678 "); // test to see if there is a problem with printing strings vs floats 2030 | // Longitude 2031 | disp_st7789.setCursor(2, 74); 2032 | disp_st7789.print(F("Lon: ")); 2033 | disp_st7789.print(GPSLon, 6); 2034 | // Altitude 2035 | disp_st7789.setCursor(2, 88); 2036 | disp_st7789.print(F("Alt: ")); 2037 | disp_st7789.print(GPSAlt, 1); 2038 | disp_st7789.print(F("m ")); 2039 | //Satellites 2040 | disp_st7789.setCursor(140, 88); 2041 | disp_st7789.print(F("Sats: ")); 2042 | disp_st7789.print(GPSSats); 2043 | if (GPSSats < 10) disp_st7789.print(F(" ")); // clear possible digit when sats >= 10 2044 | // HDOP 2045 | disp_st7789.setCursor(2, 102); 2046 | disp_st7789.print(F("HDOP: ")); 2047 | tempfloat = ((float) GPSHdop / 100); 2048 | disp_st7789.print(tempfloat, 1); 2049 | disp_st7789.setCursor(2, 116); 2050 | disp_st7789.print(F("UpT: ")); 2051 | disp_st7789.print(updaysstr); 2052 | disp_st7789.setCursor(140, 116); 2053 | disp_st7789.print(uptimestr); 2054 | 2055 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 2056 | // BMP280 temperature 2057 | disp_st7789.setCursor(2, 130); 2058 | disp_st7789.print(F(" ")); 2059 | //disp_st7789.print((char)247); 2060 | //disp_st7789.print((char)9); 2061 | disp_st7789.print(F("*C: ")); 2062 | disp_st7789.print(bmp280temp, 1); 2063 | // BMP280 pressure 2064 | disp_st7789.setCursor(2, 144); 2065 | disp_st7789.print(F("hPa: ")); 2066 | disp_st7789.print(((bmp280pres+PressureOffset)/100), 1); 2067 | #endif // BMP280_SPI 2068 | 2069 | #ifdef GPSDO_VCC 2070 | disp_st7789.setCursor(2, 160); 2071 | // Vcc/2 is provided on pin PA0 2072 | float Vcc = (float(avgVcc)/4096) * 3.3 * 2.0; 2073 | disp_st7789.print(F("5V0: ")); 2074 | disp_st7789.print(Vcc, 2); 2075 | disp_st7789.print(F("V")); 2076 | #endif // VCC 2077 | 2078 | #ifdef GPSDO_VDD 2079 | // internal sensor Vref 2080 | disp_st7789.setCursor(2, 174); 2081 | float Vdd = (1.21 * 4096) / float(avgVdd); // from STM32F411CEU6 datasheet 2082 | disp_st7789.print(F("3V3: ")); 2083 | disp_st7789.print(Vdd, 2); // Vdd = Vref on Black Pill 2084 | disp_st7789.print(F("V")); 2085 | #endif // VDD 2086 | /* 2087 | disp_st7789.setCursor(0, 80); // display PWM/DAC value 2088 | #ifdef GPSDO_PWM_DAC 2089 | disp_st7789.print(F("PWM: ")); 2090 | disp_st7789.print(adjusted_PWM_output); 2091 | disp_st7789.print(F(trendstr)); 2092 | #endif // PWM_DAC 2093 | 2094 | // display Vctl value 2095 | disp_st7789.setCursor(90, 80); // display Vctl value 2096 | float Vctlp = (float(avgpwmVctl)/4096) * 3.3; 2097 | disp_st7789.print(F("Vctl: ")); 2098 | disp_st7789.print(Vctlp); 2099 | disp_st7789.print(F("V")); 2100 | */ 2101 | // OCXO frequency 2102 | disp_st7789.setFont(); // reset font to built-in 2103 | disp_st7789.setTextSize(2); 2104 | disp_st7789.setCursor(10, 24); 2105 | disp_st7789.setTextColor(ST77XX_RED, ST77XX_BLACK); 2106 | 2107 | // display 1s, 10s or 100s value depending on whether data is available 2108 | if (cbTen_full) { 2109 | if (cbTho_full) { // if we have data over 1000 seconds 2110 | if (avgftho < 10000000) { 2111 | disp_st7789.print(" "); 2112 | } 2113 | disp_st7789.print(avgftho, 3); // to 3 decimal places 2114 | } 2115 | else if (cbHun_full) { 2116 | if (avgfhun < 10000000) { 2117 | disp_st7789.print(" "); 2118 | } 2119 | disp_st7789.print(avgfhun, 2); // to 2 decimal places 2120 | disp_st7789.print(" "); 2121 | } 2122 | 2123 | else { // nope, only 10 seconds 2124 | if (avgften < 10000000) { 2125 | disp_st7789.print(" "); 2126 | } 2127 | disp_st7789.print(avgften, 1); // to 1 decimal place 2128 | disp_st7789.print(" "); 2129 | } 2130 | } 2131 | else { // we don't have any averages and print integer value 2132 | calcfreqint = calcfreq64; // convert to 32-bit integer 2133 | if (calcfreqint < 10000000) { 2134 | disp_st7789.print(" "); 2135 | } 2136 | disp_st7789.print(calcfreqint); // integer 2137 | disp_st7789.print(" "); // these are used for more exact display 2138 | } 2139 | // due to limited space small character unit 2140 | // disp_st7789.setTextSize(1); 2141 | // disp_st7789.setCursor(168, 20); 2142 | // due to some unknown issue in printing the freq digits/unit we clear the section of the display first 2143 | // disp_st7789.fillRect(144, 19, 15, 20, ST77XX_BLACK); 2144 | disp_st7789.print(" Hz"); 2145 | 2146 | // clock and date 2147 | disp_st7789.setTextSize(2); 2148 | disp_st7789.setTextColor(ST77XX_MAGENTA, ST77XX_BLACK); 2149 | // Date 2150 | disp_st7789.setCursor(2, 188); 2151 | //disp_st7789.print(F("Date: ")); 2152 | disp_st7789.print(day); 2153 | disp_st7789.print(F(".")); 2154 | disp_st7789.print(month); 2155 | disp_st7789.print(F(".")); 2156 | disp_st7789.print(year); 2157 | 2158 | // Time 2159 | disp_st7789.setTextColor(ST77XX_GREEN, ST77XX_BLACK); 2160 | disp_st7789.setCursor(2, 208); 2161 | 2162 | if (hours < 10) { 2163 | disp_st7789.print(F("0")); 2164 | } 2165 | disp_st7789.print(hours); 2166 | disp_st7789.print(F(":")); 2167 | 2168 | if (mins < 10) { 2169 | disp_st7789.print(F("0")); 2170 | } 2171 | disp_st7789.print(mins); 2172 | disp_st7789.print(F(":")); 2173 | 2174 | if (secs < 10) { 2175 | disp_st7789.print(F("0")); 2176 | } 2177 | disp_st7789.print(secs); 2178 | 2179 | disp_st7789.setTextColor(ST77XX_WHITE, ST77XX_BLACK); 2180 | disp_st7789.print(F(" UTC")); 2181 | 2182 | // reset all font stuff for normal display 2183 | // disp_st7789.setFont(); 2184 | // disp_st7789.setTextSize(1); 2185 | // disp_st7789.setTextColor(ST77XX_WHITE, ST77XX_BLACK); 2186 | } 2187 | #endif // LCD_ST7789 2188 | 2189 | #ifdef GPSDO_TM1637 2190 | void displaytime_TM1637() { 2191 | int LEDtime = (hours * 100) + mins; 2192 | // Show UTC or local time on TM1637 4-digit LED display and blink colon at 1Hz 2193 | if ((secs%2) == 0) tm1637.showNumberDecEx(LEDtime, 0b11100000, true); 2194 | else tm1637.showNumberDec(LEDtime, true); 2195 | } 2196 | #endif // TM1637 2197 | 2198 | void uptimetostrings() { 2199 | // translate uptime variables to strings 2200 | uptimestr[0] = '0' + uphours / 10; 2201 | uptimestr[1] = '0' + uphours % 10; 2202 | uptimestr[3] = '0' + upminutes / 10; 2203 | uptimestr[4] = '0' + upminutes % 10; 2204 | uptimestr[6] = '0' + upseconds / 10; 2205 | uptimestr[7] = '0' + upseconds % 10; 2206 | 2207 | if (updays > 99) { // 100 days or more 2208 | updaysstr[0] = '0' + updays / 100; 2209 | updaysstr[1] = '0' + (updays % 100) / 10; 2210 | updaysstr[2] = '0' + (updays % 100) % 10; 2211 | } 2212 | else { // less than 100 days 2213 | updaysstr[0] = '0'; 2214 | updaysstr[1] = '0' + updays / 10; 2215 | updaysstr[2] = '0' + updays % 10; 2216 | } 2217 | } // end of uptimetostrings() 2218 | 2219 | 2220 | // --------------------------------------------------------------------------------------------- 2221 | // setup routine, prepares the hardware for normal operation 2222 | // --------------------------------------------------------------------------------------------- 2223 | void setup() 2224 | { 2225 | // Wait 1 second for things to stabilize 2226 | delay(1000); 2227 | 2228 | // setup 2kHz test signal on PB5, can be tested with an oscilloscope 2229 | #ifdef GPSDO_GEN_2kHz_PB5 // note this uses Timer 3 Channel 2 2230 | analogWrite(Test2kHzOutputPin, 127); // configures PB5 as PWM output pin at default frequency and resolution 2231 | analogWriteFrequency(2000); // default PWM frequency is 1kHz, change it to 2kHz 2232 | analogWriteResolution(16); // default PWM resolution is 8 bits, change it to 16 bits 2233 | analogWrite(Test2kHzOutputPin, 32767); // 32767 for 16 bits -> 50% duty cycle so a square wave 2234 | #endif // GEN_2kHz_PB5 2235 | 2236 | // configure blueledpin in output mode 2237 | pinMode(blueledpin, OUTPUT); // blinking blue LED indicates interrupts are working 2238 | 2239 | // configure yellow_led_pin in output mode 2240 | pinMode(yellowledpin, OUTPUT); // yellow LED is used to indicate status of the GPSDO 2241 | 2242 | // Setup 2Hz Timer and its interrupt service routine 2243 | HardwareTimer *tim2Hz = new HardwareTimer(TIM9); 2244 | tim2Hz->setOverflow(2, HERTZ_FORMAT); // 2 Hz 2245 | tim2Hz->attachInterrupt(Timer_ISR_2Hz); 2246 | tim2Hz->resume(); 2247 | 2248 | // Setup UART (serial) interfaces 2249 | Serial.begin(115200); // USB serial 2250 | Serial1.begin(9600); // Hardware serial 1 to GPS module 2251 | #ifdef GPSDO_BLUETOOTH 2252 | // HC-06 module baud rate factory setting is 9600, 2253 | // IMPORTANT! Use separate program to set baud rate to 57600 2254 | Serial2.begin(BT_BAUD); // Hardware serial 2 to Bluetooth module 2255 | #endif // BLUETOOTH 2256 | 2257 | Serial.println(); 2258 | Serial.println(F(Program_Name)); 2259 | Serial.println(F(Program_Version)); 2260 | Serial.println(); 2261 | Serial.println(F("2Hz interrupt configured")); 2262 | Serial.println(F("Serial interfaces configured")); 2263 | 2264 | // setup commands parser 2265 | serial_commands_.SetDefaultHandler(cmd_unrecognized); 2266 | serial_commands_.AddCommand(&cmd_version_); 2267 | serial_commands_.AddCommand(&cmd_flush_); 2268 | serial_commands_.AddCommand(&cmd_calibrate_); 2269 | serial_commands_.AddCommand(&cmd_tunnel_); 2270 | serial_commands_.AddCommand(&cmd_setPWM_); 2271 | serial_commands_.AddCommand(&cmd_rephum_); 2272 | serial_commands_.AddCommand(&cmd_repdel_); 2273 | 2274 | serial_commands_.AddCommand(&cmd_up1_); 2275 | serial_commands_.AddCommand(&cmd_up10_); 2276 | serial_commands_.AddCommand(&cmd_dp1_); 2277 | serial_commands_.AddCommand(&cmd_dp10_); 2278 | 2279 | #ifdef GPSDO_EEPROM 2280 | // register the commands to Store PWM and Recall PWM 2281 | #endif // EEPROM 2282 | 2283 | Serial.println(F("Commands parser configured")); 2284 | 2285 | #ifdef GPSDO_LCD_ST7735 2286 | // Setup LCD SPI ST7735 display 2287 | disp.initR(INITR_BLACKTAB); // 1.8" LCD 2288 | delay(500); 2289 | disp.fillScreen(ST7735_BLACK); 2290 | disp.setTextColor(ST7735_YELLOW, ST7735_BLACK); // 2291 | disp.setRotation(1); // 0..3 max, here we use 90° = landscape 2292 | disp.setFont(); 2293 | disp.setTextSize(3); 2294 | // splash screen 2295 | disp.setCursor(40, 30); 2296 | disp.print(F(Program_Name)); 2297 | disp.setTextSize(1); 2298 | disp.setCursor(60, 65); 2299 | //disp.print(F(" - ")); 2300 | disp.setTextColor(ST7735_WHITE, ST7735_BLACK); 2301 | disp.print(F(Program_Version)); 2302 | disp.setTextColor(ST7735_WHITE, ST7735_BLACK); 2303 | disp.setTextSize(1); 2304 | 2305 | Serial.println(F("ST7735 LCD display configured")); 2306 | #endif // LCD_ST7735 2307 | 2308 | // Setup LCD SPI ST7789 display 2309 | #ifdef GPSDO_LCD_ST7789 2310 | disp_st7789.init(240, 240, SPI_MODE3); // 1.3" 240x240 TFT LCD 2311 | delay(100); 2312 | disp_st7789.fillScreen(ST77XX_BLACK); 2313 | disp_st7789.setRotation(2); // 0..3 max, 1 = 90° = landscape 2314 | // Display program name and version 2315 | disp_st7789.setTextSize(1); 2316 | disp_st7789.setFont(&FreeMonoBold12pt7b); 2317 | disp_st7789.setTextColor(ST77XX_YELLOW); 2318 | disp_st7789.setCursor(0, 16); 2319 | disp_st7789.print(F("STM32 ")); 2320 | disp_st7789.print(F(Program_Name)); // program name 2321 | disp_st7789.setFont(&FreeMono9pt7b); 2322 | disp_st7789.setTextColor(ST77XX_CYAN); 2323 | disp_st7789.setCursor(168, 11); 2324 | disp_st7789.print(F(Program_Version)); // program version 2325 | 2326 | Serial.println(F("ST7789 LCD display configured")); 2327 | #endif // LCD_ST7789 2328 | 2329 | // Setup TM1637 4-digit LED module 2330 | #ifdef GPSDO_TM1637 2331 | // Set the display brightness (0-7): 2332 | tm1637.setBrightness(5); 2333 | // Clear the display: 2334 | tm1637.clear(); 2335 | tm1637.setSegments(mid_dashes); 2336 | 2337 | Serial.println(F("TM1637 4-digit LED clock display configured")); 2338 | #endif // TM1637 2339 | 2340 | #ifdef GPSDO_UBX_CONFIG 2341 | // Reconfigure the GPS receiver 2342 | // first send the $PUBX configuration commands 2343 | delay(3000); // give everything a moment to stabilize 2344 | Serial.println("GPS checker program started"); 2345 | Serial.println("Sending $PUBX commands to GPS"); 2346 | // first send the $PUBG configuration commands 2347 | Serial1.print("$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n"); // disable all VTG messages (useless since we are stationary) 2348 | Serial1.print("$PUBX,41,1,0003,0003,38400,0*24\r\n"); // set GPS baud rate to 38400 in/out protocols NMEA+UBX 2349 | Serial1.flush(); // empty the buffer 2350 | delay(100); // give it a moment 2351 | Serial1.end(); // close serial port 2352 | Serial1.begin(38400); // re-open at new rate 2353 | delay(3000); 2354 | // second, send the proprietary UBX configuration commands 2355 | Serial.println("Now sending UBX commands to GPS"); 2356 | ubxconfig(); 2357 | 2358 | Serial.println(F("u-blox GPS module configured")); 2359 | #endif // UBX_CONFIG 2360 | 2361 | // Setup AHT10 / AHT20 temperature and humidity sensor module 2362 | #ifdef GPSDO_AHT10 // same code for AHT20 2363 | Serial.println(F("Testing for presence of AHT10 or AHT20 Sensor on I2C bus")); 2364 | if (!aht.begin()) { 2365 | Serial.println(F("Could not find AHT10 or AHT20 sensor, check wiring")); 2366 | while (1) delay(10); 2367 | } 2368 | else Serial.println(F("AHTX0 sensor configured")); 2369 | #endif // AHT10 - Note this seems to initialize the I2C bus interface 2370 | 2371 | // Setup OLED I2C display 2372 | #ifdef GPSDO_OLED 2373 | // Note that u8x8 library initializes I2C hardware interface 2374 | // disp.setBusClock(400000L); // try to avoid display locking up 2375 | disp.begin(); 2376 | disp.setFont(u8x8_font_chroma48medium8_r); 2377 | disp.clear(); 2378 | disp.setCursor(0, 0); 2379 | disp.print(F(Program_Name)); 2380 | disp.print(F(" - ")); 2381 | disp.print(F(Program_Version)); 2382 | 2383 | Serial.println(F("OLED display configured")); 2384 | #endif // OLED 2385 | 2386 | // Setup INA219 current sensor module 2387 | #ifdef GPSDO_INA219 2388 | // By default the initialization will use the largest range (32V, 2A). However 2389 | // you can call a setCalibration function to change this range (see comments). 2390 | if (! ina219.begin()) { 2391 | Serial.println(F("Could not find INA219 sensor, check wiring")); 2392 | while (1) { delay(10); } 2393 | } 2394 | else Serial.println(F("INA219 sensor configured")); 2395 | // To use a slightly lower 32V, 1A range (higher precision on amps): 2396 | //ina219.setCalibration_32V_1A(); 2397 | // Or to use a lower 16V, 400mA range (higher precision on volts and amps): 2398 | //ina219.setCalibration_16V_400mA(); 2399 | ina219.setCalibration_32V_1A(); 2400 | #endif // INA219 2401 | 2402 | analogReadResolution(12); // make sure we read 12 bit values when we read from any ADC analog channel 2403 | 2404 | // generate a 2kHz square wave on PB9 PWM pin, using Timer 4 channel 4 2405 | // PB9 is Timer 4 Channel 4 from Arduino_Core_STM32/variants/STM32F4xx/F411C(C-E)(U-Y)/PeripheralPins_BLACKPILL_F411CE.c 2406 | analogWrite(VctlPWMOutputPin, 127); // configures PB9 as PWM output pin at default frequency and resolution 2407 | analogWriteFrequency(2000); // default PWM frequency is 1kHz, change it to 2kHz 2408 | analogWriteResolution(16); // set PWM resolution to 16 bits (the maximum for the STM32F411CEU6) 2409 | adjusted_PWM_output = default_PWM_output; // initial PWM value 2410 | analogWrite(VctlPWMOutputPin, adjusted_PWM_output); // 32767 for 16 bits -> 50% duty cycle so a square wave 2411 | Serial.println(F("16-bit PWM DAC configured")); 2412 | 2413 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 2414 | // Initialize BMP280 2415 | Serial.println(F("Testing for presence of BMP280 Sensor on I2C bus")); 2416 | #ifdef GPSDO_BMP280_I2C // BMP280 on I2C bus requires specifying address 2417 | if (!bmp.begin(0x76,0x58)) { 2418 | #else 2419 | if (!bmp.begin()) { 2420 | #endif 2421 | Serial.println(F("Could not find BMP280 sensor, check wiring")); 2422 | while (1) delay(10); 2423 | } 2424 | else Serial.println(F("BMP280 sensor configured")); 2425 | 2426 | // Default settings from datasheet 2427 | bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, // Operating Mode 2428 | Adafruit_BMP280::SAMPLING_X2, // Temp. oversampling 2429 | Adafruit_BMP280::SAMPLING_X16, // Pressure oversampling 2430 | Adafruit_BMP280::FILTER_X16, // Filtering 2431 | Adafruit_BMP280::STANDBY_MS_500); // Standby time 2432 | 2433 | #endif // BMP280_SPI or BMP280_I2C 2434 | 2435 | // Setup and start Timer 2 which measures OCXO frequency 2436 | // setup pin used as ETR (10MHz external clock from OCXO) 2437 | pinMode(PA15, INPUT_PULLUP); // setup PA15 as input pin 2438 | pinModeAF(PA15, GPIO_AF1_TIM2); // setup PA15 as TIM2 channel 1 / ETR 2439 | 2440 | // setup Timer 2 in input capture mode, active input channel 3 2441 | // to latch counter value on rising edge 2442 | 2443 | // Instantiate HardwareTimer object. Thanks to 'new' instantiation, HardwareTimer is not destructed when setup() function is finished. 2444 | HardwareTimer *FreqMeasTim = new HardwareTimer(TIM2); 2445 | 2446 | // Configure rising edge detection to measure frequency 2447 | FreqMeasTim->setMode(3, TIMER_INPUT_CAPTURE_RISING, PB10); 2448 | 2449 | // Configure 32-bit auto-reload register (ARR) with maximum possible value 2450 | TIM2->ARR = 0xffffffff; // count to 2^32, then wraparound (approximately every 429 seconds) 2451 | 2452 | // Configure the ISR for the timer overflow interrupt 2453 | FreqMeasTim->attachInterrupt(Timer2_Overflow_ISR); 2454 | 2455 | // Configure the ISR for the 1PPS capture 2456 | FreqMeasTim->attachInterrupt(3, Timer2_Capture_ISR); 2457 | 2458 | // select external clock source mode 2 by writing ECE=1 in the TIM2_SMCR register 2459 | TIM2->SMCR |= TIM_SMCR_ECE; // 0x4000 2460 | 2461 | // start the timer 2462 | FreqMeasTim->resume(); 2463 | 2464 | // Initialize movingAvg objects (note this allocates space on heap) and immediately read 1st value 2465 | #ifdef GPSDO_VDD 2466 | avg_adcVdd.begin(); 2467 | adcVdd = analogRead(AVREF); 2468 | avgVdd = avg_adcVdd.reading(adcVdd); 2469 | # endif // VDD 2470 | 2471 | #ifdef GPSDO_VCC 2472 | avg_adcVcc.begin(); 2473 | adcVcc = analogRead(VccDiv2InputPin); 2474 | avgVcc = avg_adcVcc.reading(adcVcc); 2475 | # endif // VCC 2476 | 2477 | avg_pwmVctl.begin(); 2478 | pwmVctl = analogRead(VctlPWMInputPin); 2479 | avgpwmVctl = avg_pwmVctl.reading(pwmVctl); 2480 | 2481 | startGetFixmS = millis(); 2482 | 2483 | Serial.println(); 2484 | Serial.println(F("GPSDO Starting")); 2485 | Serial.println(); 2486 | 2487 | #ifdef GPSDO_EEPROM 2488 | // detect signature and if available, retrieve 16-bit PWM value 2489 | #endif // EEPROM 2490 | 2491 | } // end of setup() 2492 | 2493 | 2494 | // --------------------------------------------------------------------------------------------- 2495 | // loop routine: this is the main loop 2496 | // --------------------------------------------------------------------------------------------- 2497 | void loop() 2498 | { 2499 | serial_commands_.ReadSerial(); // process any command from either USB serial (usually 2500 | // the Arduino monitor) xor Bluetooth serial (e.g. a smartphone) 2501 | if (force_calibration_flag) docalibration(); else 2502 | 2503 | if (tunnel_mode_flag) tunnelgps(); else 2504 | 2505 | if (gpsWaitFix(waitFixTime)) // wait up to waitFixTime seconds for fix, returns true if we have a fix 2506 | { 2507 | // if we have a GPS fix (implies we have a stable 1PPS pulse from the GPS) 2508 | 2509 | if (!report_tab_delimited) { // only report fix time when in human readable output format mode 2510 | #ifdef GPSDO_BLUETOOTH 2511 | Serial2.println(); 2512 | Serial2.println(); 2513 | Serial2.print(F("Fix time ")); 2514 | Serial2.print(endFixmS - startGetFixmS); 2515 | Serial2.println(F("mS")); 2516 | #else 2517 | Serial.println(); 2518 | Serial.println(); 2519 | Serial.print(F("Fix time ")); 2520 | Serial.print(endFixmS - startGetFixmS); 2521 | Serial.println(F("mS")); 2522 | #endif // BLUETOOTH 2523 | } // !report_tab_delimited 2524 | 2525 | GPSLat = gps.location.lat(); 2526 | GPSLon = gps.location.lng(); 2527 | GPSAlt = gps.altitude.meters(); 2528 | GPSSats = gps.satellites.value(); 2529 | GPSHdop = gps.hdop.value(); 2530 | 2531 | hours = gps.time.hour(); 2532 | mins = gps.time.minute(); 2533 | secs = gps.time.second(); 2534 | day = gps.date.day(); 2535 | month = gps.date.month(); 2536 | year = gps.date.year(); 2537 | 2538 | 2539 | if (must_adjust_DAC && cbHun_full) // in principle just once every 429 seconds, and only if we have valid data 2540 | { 2541 | // use different algorithms for 12-bit I2C DAC and STM32 16-bit PWM DAC 2542 | #ifdef GPSDO_PWM_DAC 2543 | adjustVctlPWM(); 2544 | #endif // PWM_DAC 2545 | } 2546 | 2547 | pwmVctl = analogRead(VctlPWMInputPin); // read the filtered Vctl voltage output by the PWM 2548 | avgpwmVctl = avg_pwmVctl.reading(pwmVctl); // average it 2549 | 2550 | #ifdef GPSDO_VCC 2551 | adcVcc = analogRead(VccDiv2InputPin); // read Vcc 2552 | avgVcc = avg_adcVcc.reading(adcVcc); // average it 2553 | # endif // VCC 2554 | 2555 | #ifdef GPSDO_VDD 2556 | adcVdd = analogRead(AVREF); // Vdd is read internally as Vref 2557 | avgVdd = avg_adcVdd.reading(adcVdd); // average it 2558 | #endif // VDD 2559 | 2560 | #if (defined (GPSDO_BMP280_SPI) || defined (GPSDO_BMP280_I2C)) 2561 | bmp280temp = bmp.readTemperature(); // read bmp280 sensor, save values 2562 | bmp280pres = bmp.readPressure(); 2563 | bmp280alti = bmp.readAltitude(); 2564 | #endif // BMP280_SPI or BMP280_SPI 2565 | 2566 | #ifdef GPSDO_INA219 2567 | ina219volt = ina219.getBusVoltage_V(); // read ina219 sensor, save values 2568 | ina219curr = ina219.getCurrent_mA(); 2569 | #endif // INA219 2570 | 2571 | uptimetostrings(); // get updaysstr and uptimestr 2572 | 2573 | yellow_led_state = 0; // turn off yellow LED 2574 | 2575 | if (report_tab_delimited) { // check what to print and where 2576 | #ifdef GPSDO_BLUETOOTH 2577 | printGPSDOtab(Serial2); // print tabulated data to Bluetooth Serial 2578 | #else // xor 2579 | printGPSDOtab(Serial); // print tabulated data to USB Serial 2580 | #endif // BLUETOOTH 2581 | } 2582 | else { 2583 | #ifdef GPSDO_BLUETOOTH 2584 | printGPSDOstats(Serial2); // print stats to Bluetooth Serial 2585 | #else // xor 2586 | printGPSDOstats(Serial); // print stats to USB Serial 2587 | #endif // BLUETOOTH 2588 | } // end if (report_tab_delimited) 2589 | 2590 | #ifdef GPSDO_OLED // show stats on various displays 2591 | displayscreen_OLED(); 2592 | #endif // OLED 2593 | 2594 | #ifdef GPSDO_LCD_ST7735 2595 | displayscreen_LCD_ST7735(); 2596 | #endif // LCD_ST7735 2597 | 2598 | #ifdef GPSDO_LCD_ST7789 2599 | displayscreen_LCD_ST7789(); 2600 | #endif // LCD_ST7789 2601 | 2602 | #ifdef GPSDO_TM1637 2603 | displaytime_TM1637(); 2604 | #endif // TM1637 2605 | 2606 | startGetFixmS = millis(); // have a fix, next thing that happens is checking for a fix, so restart timer 2607 | } 2608 | else // no GPS fix could be acquired for the last 1/2/5 seconds (see settings) 2609 | { 2610 | // we don't have a GPS fix, so we consider that we don't have a stable 1PPS 2611 | yellow_led_state = 1; // turn on yellow LED to show something is not right 2612 | 2613 | #ifdef GPSDO_OLED 2614 | disp.clear(); // display no fix message on OLED 2615 | disp.setCursor(0, 0); 2616 | disp.print(F(Program_Name)); 2617 | disp.print(F(" - ")); 2618 | disp.print(F(Program_Version)); 2619 | disp.setCursor(0, 1); 2620 | disp.print(F("Wait fix ")); 2621 | disp.print( (millis() - startGetFixmS) / 1000 ); 2622 | disp.print(F("s")); 2623 | #endif // OLED 2624 | 2625 | #ifdef GPSDO_LCD_ST7735 2626 | disp.fillScreen(ST7735_BLACK); // display no fix message on ST7735 LCD 2627 | disp.setCursor(0, 0); 2628 | disp.print(F(Program_Name)); 2629 | disp.print(F(" - ")); 2630 | disp.print(F(Program_Version)); 2631 | disp.setCursor(0, 8); 2632 | disp.print(F("Wait fix ")); 2633 | disp.print( (millis() - startGetFixmS) / 1000 ); 2634 | disp.print(F("s")); 2635 | #endif // LCD_ST7735 2636 | 2637 | #ifdef GPSDO_LCD_ST7789 2638 | // display no fix message on ST7789 LCD 2639 | disp_st7789.fillScreen(ST77XX_BLACK); // clear display 2640 | // Display program name and version 2641 | disp_st7789.setTextSize(1); 2642 | disp_st7789.setFont(&FreeMonoBold12pt7b); 2643 | disp_st7789.setTextColor(ST77XX_YELLOW); 2644 | disp_st7789.setCursor(0, 16); 2645 | disp_st7789.print(F("STM32 ")); 2646 | disp_st7789.print(F(Program_Name)); 2647 | disp_st7789.setFont(&FreeMono9pt7b); 2648 | disp_st7789.setTextColor(ST77XX_CYAN); 2649 | disp_st7789.setCursor(168, 11); 2650 | disp_st7789.print(F(Program_Version)); 2651 | // display wait fix message and seconds count 2652 | disp_st7789.setCursor(0, 36); 2653 | disp_st7789.setTextColor(ST77XX_WHITE); 2654 | disp_st7789.print(F(" Wait fix ")); 2655 | disp_st7789.print( (millis() - startGetFixmS) / 1000 ); 2656 | disp_st7789.print(F("s")); 2657 | 2658 | must_clear_disp_st7789 = true; 2659 | #endif // LCD_ST7789 2660 | 2661 | #ifdef GPSDO_TM1637 2662 | tm1637.setSegments(low_oooo_s); 2663 | #endif // TM1637 2664 | 2665 | if (report_tab_delimited) { // check what to print and where 2666 | #ifdef GPSDO_BLUETOOTH // print 0 message to either 2667 | Serial2.println(F("0")); 2668 | #else 2669 | Serial.println(F("0")); 2670 | #endif // BLUETOOTH 2671 | report_line_no = 0; // we restart linecount every time we lose GPS position fix (PPS) 2672 | } 2673 | else { 2674 | #ifdef GPSDO_BLUETOOTH // print no fix message to either 2675 | Serial2.println(); // Bluetooth serial or USB serial 2676 | Serial2.print(F("Waiting for GPS Fix ")); 2677 | Serial2.print( (millis() - startGetFixmS) / 1000 ); 2678 | Serial2.println(F("s")); 2679 | #else 2680 | Serial.println(); 2681 | Serial.print(F("Waiting for GPS Fix ")); 2682 | Serial.print( (millis() - startGetFixmS) / 1000 ); 2683 | Serial.println(F("s")); 2684 | #endif // BLUETOOTH 2685 | } 2686 | 2687 | // no fix or fix lost, we must flush the ring buffers, 2688 | // so raise flush_ring_buffers_flag 2689 | flush_ring_buffers_flag = true; 2690 | } 2691 | 2692 | } // end of loop() 2693 | -------------------------------------------------------------------------------- /software/GPSDO_V006c/GPSDO_algorithms.cpp: -------------------------------------------------------------------------------- 1 | /* STM32 GPSDO Control Loop Algorithms 2 | * 3 | */ 4 | 5 | #include "GPSDO_algorithms.h" 6 | // --------------------------------------------------------------------------------------------- 7 | // Control loop algorithm selector 8 | // --------------------------------------------------------------------------------------------- 9 | uint16_t adjustVctlPWM(uint16_t previous_PWM_output, uint32_t timer, uint8_t algorithm_no) { 10 | uint16_t return_PWM_output = previous_PWM_output; 11 | 12 | switch(algorithm_no) { 13 | case 0: 14 | return_PWM_output = primitive_ctl_loop(previous_PWM_output, timer); 15 | break; 16 | 17 | case 1: 18 | return_PWM_output = forced_drift_Vctl(previous_PWM_output, timer); 19 | break; 20 | 21 | case 2: 22 | return_PWM_output = random_walk_Vctl(previous_PWM_output, timer); 23 | break; 24 | 25 | // add new control algorithms here and below, and in header file 26 | 27 | default: 28 | return_PWM_output = primitive_ctl_loop(previous_PWM_output, timer); 29 | } 30 | return (return_PWM_output); 31 | } 32 | // --------------------------------------------------------------------------------------------- 33 | // Very primitive Adjust Vctl PWM routine 34 | // --------------------------------------------------------------------------------------------- 35 | uint16_t primitive_ctl_loop(uint16_t adjusted_PWM_output, uint32_t lclppscount) { 36 | // This should reach a stable PWM output value / a stable 10000000.00 frequency 37 | // after an hour or so, and 10000000.000 after eight hours or so 38 | 39 | uint16_t new_PWM_output = adjusted_PWM_output; 40 | const uint32_t update_periodicity = 429; // only calculate new value every 429s 41 | 42 | if ((lclppscount % update_periodicity) == 0) { 43 | // check first if we have the data, then do ultrafine and very fine frequency 44 | // adjustment, when we are very close 45 | // ultimately the objective is 10000000.000 over the last 1000s (16min40s) 46 | if ((cotho_full) && (oavgftho >= 9999999.990) && (oavgftho <= 10000000.010)) { 47 | 48 | // decrease frequency; 1000s based 49 | if (oavgftho >= 10000000.001) { 50 | if (oavgftho >= 10000000.005) { 51 | // decrease PWM by 5 bits = very fine 52 | new_PWM_output = adjusted_PWM_output - 5; 53 | strcpy(trendstr, " vf-"); 54 | } 55 | else { 56 | // decrease PWM by one bit = ultrafine 57 | new_PWM_output = adjusted_PWM_output - 1; 58 | strcpy(trendstr, " uf-"); 59 | } 60 | } 61 | // or increase frequency; 1000s based 62 | else if (oavgftho <= 9999999.999) { 63 | if (oavgftho <= 9999999.995) { 64 | // increase PWM by 5 bits = very fine 65 | new_PWM_output = adjusted_PWM_output + 5; 66 | strcpy(trendstr, " vf+"); 67 | } 68 | else { 69 | // increase PWM by one bit = ultrafine 70 | new_PWM_output = adjusted_PWM_output + 1; 71 | strcpy(trendstr, " uf+"); 72 | } 73 | } 74 | } 75 | ///// next check the 100s values in second place because we are too far off 76 | // decrease frequency; 100s based 77 | else if (oavgfhun >= 10000000.01) { 78 | if (oavgfhun >= 10000000.10) { 79 | // decrease PWM by 100 bits = coarse 80 | new_PWM_output = adjusted_PWM_output - 100; 81 | strcpy(trendstr, " c- "); 82 | } 83 | else { 84 | // decrease PWM by ten bits = fine 85 | new_PWM_output = adjusted_PWM_output - 10; 86 | strcpy(trendstr, " f- "); 87 | } 88 | } 89 | // or increase frequency; 100s based 90 | else if (oavgfhun <= 9999999.99) { 91 | if (oavgfhun <= 9999999.90) { 92 | // increase PWM by 100 bits = coarse 93 | new_PWM_output = adjusted_PWM_output + 100; 94 | strcpy(trendstr, " c+ "); 95 | } 96 | else { 97 | // increase PWM by ten bits = fine 98 | new_PWM_output = adjusted_PWM_output + 10; 99 | strcpy(trendstr, " f+ "); 100 | } 101 | } 102 | else { 103 | // here we keep PWM DAC setting, because measured frequency is exactly 10000000.000MHz 104 | strcpy(trendstr, " hit"); 105 | } 106 | } 107 | return(new_PWM_output); // return newly computed value for PWM DAC 108 | } // end adjustVctlPWM 109 | 110 | // --------------------------------------------------------------------------------------------- 111 | // Forced drift : increases PWM DAC by 1 bit every 1000 seconds 112 | // --------------------------------------------------------------------------------------------- 113 | uint16_t forced_drift_Vctl(uint16_t adjusted_PWM_output, uint32_t lclppscount) { 114 | 115 | uint16_t new_PWM_output = adjusted_PWM_output; 116 | const uint32_t update_periodicity = 1000; // only calculate new value every 1000s 117 | 118 | if ((lclppscount % update_periodicity) == 0) { 119 | new_PWM_output = adjusted_PWM_output + 1; 120 | } 121 | return(new_PWM_output); // return newly computed value for PWM DAC 122 | } // end forced_drift 123 | 124 | // --------------------------------------------------------------------------------------------- 125 | // Random walk : adds -1, 0, +1 with equal probabilities to PWM DAC every 5 seconds 126 | // --------------------------------------------------------------------------------------------- 127 | uint16_t random_walk_Vctl(uint16_t adjusted_PWM_output, uint32_t lclppscount) { 128 | 129 | uint16_t new_PWM_output = adjusted_PWM_output; 130 | const uint32_t update_periodicity = 5; // only calculate new value every 5s 131 | 132 | if ((lclppscount % update_periodicity) == 0) { 133 | new_PWM_output = adjusted_PWM_output + random(-1,2); 134 | } 135 | return(new_PWM_output); // return newly computed value for PWM DAC 136 | } // end random_walk 137 | -------------------------------------------------------------------------------- /software/GPSDO_V006c/GPSDO_algorithms.h: -------------------------------------------------------------------------------- 1 | #ifndef GPSDO_ALGORITHMS_H 2 | #define GPSDO_ALGORITHMS_H 3 | #include 4 | // algorithm selector function 5 | uint16_t adjustVctlPWM(uint16_t previous_PWM_output, uint32_t timer, uint8_t algorithm_no); 6 | // up to 10 different control loop algorithms, in order from 0 to 9 7 | // 0 - primitive, very simple control loop 8 | uint16_t primitive_ctl_loop(uint16_t adjusted_PWM_output, uint32_t lclppscount); 9 | // 1 - not a control loop, we force the OCXO to drift slowly and regularly 10 | uint16_t forced_drift_Vctl(uint16_t adjusted_PWM_output, uint32_t lclppscount); 11 | // 2 - not a control loop, we force the OCXO to "jitter" randomly 12 | uint16_t random_walk_Vctl(uint16_t adjusted_PWM_output, uint32_t lclppscount); 13 | // 3 - FLL PID control loop, coefficients set manually 14 | // 4 - PLL PI (not PID) control loop, coefficients set manually (similar to Lars') 15 | // 5 - PLL PID control loop, coefficients set manually 16 | // 6 - FLL PID control loop, genetic algorithm used to find near-optimal coefficients 17 | // 7 - PLL PID control loop, genetic algorithm used to find near-optimal coefficients 18 | // 8 - FLL + PLL "hybrid" PID control loop, weights and coefficients set manually 19 | // 9 - Neural network MLP driven control loop 20 | 21 | // global variables from main program 22 | extern char trendstr[5]; 23 | extern volatile bool cotho_full; 24 | extern volatile double oavgftho; 25 | extern volatile double oavgfhun; 26 | #endif 27 | -------------------------------------------------------------------------------- /software/WARNING.txt: -------------------------------------------------------------------------------- 1 | WARNING!!! ALPHA QUALITY firmware could cause your GPSDO 2 | and even your computer to suddenly burst into flames!!! 3 | 4 | ================= TRY AT YOUR OWN RISK ================= --------------------------------------------------------------------------------