[
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Build ESCape32\non: workflow_dispatch\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v2\n    - run: |\n        sudo apt update\n        sudo apt install -y cmake\n        sudo apt install -y gcc-arm-none-eabi\n        sudo apt install -y binutils-arm-none-eabi\n        sudo apt install -y libnewlib-arm-none-eabi\n        git clone https://github.com/libopencm3/libopencm3.git\n        make -C libopencm3 TARGETS='stm32/f0 stm32/g0 stm32/g4 stm32/l4'\n        cmake -B build -D LIBOPENCM3_DIR=libopencm3\n        cd build\n        make\n    - uses: actions/upload-artifact@v4\n      with:\n        name: escape32-build\n        path: build/**/*.bin\n        retention-days: 7\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.15)\nset(CMAKE_SYSTEM_NAME Generic)\nset(CMAKE_C_COMPILER arm-none-eabi-gcc)\nset(CMAKE_C_COMPILER_WORKS 1)\nset(CMAKE_C_FLAGS \"-Os -g\")\nset(CMAKE_C_FLAGS_DEBUG \"-Og\")\nproject(ESCape32 C)\nif(UNIX AND NOT CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) # Use 'CMAKE_INSTALL_PREFIX' as alternative system root\n\tset(CMAKE_PREFIX_PATH ${CMAKE_INSTALL_PREFIX})\n\tinclude(GNUInstallDirs)\n\tinclude_directories(${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR})\n\tlink_directories(${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR})\nendif()\nif(LIBOPENCM3_DIR)\n\tinclude_directories(${LIBOPENCM3_DIR}/include)\n\tlink_directories(${LIBOPENCM3_DIR}/lib)\nendif()\nadd_compile_options(-ffreestanding -ffunction-sections -fdata-sections -fsingle-precision-constant\n\t-Wall -Wextra -Wpedantic -Wundef -Wshadow -Wredundant-decls -Wstrict-prototypes -Wmissing-prototypes\n\t-Wno-variadic-macros -Wno-unused-result -Wno-unused-parameter -Wno-unused-label)\nadd_link_options(-nostartfiles -Wl,--gc-sections)\n\nfunction(add_target name mcu)\n\tinclude(mcu/${mcu}/config.cmake)\n\tfile(READ src/main.c main_c)\n\tstring(REGEX MATCH \"REVISION [0-9]+\" rev1 ${main_c})\n\tstring(REGEX MATCH \"REVPATCH [0-9]+\" rev2 ${main_c})\n\tstring(REGEX REPLACE \"[^0-9]+\" \"-rev\" rev1 ${rev1})\n\tif (rev2)\n\t\tstring(REGEX REPLACE \"[^0-9]+\" \".\" rev2 ${rev2})\n\tendif()\n\tset(elf ${name}${rev1}${rev2}.elf)\n\tset(bin ${name}${rev1}${rev2}.bin)\n\tset(hex ${name}${rev1}${rev2}.hex)\n\tfile(GLOB srcs src/*.c mcu/${mcu}/*.c)\n\tadd_executable(${elf} ${srcs})\n\ttarget_include_directories(${elf} PRIVATE src mcu/${mcu})\n\ttarget_compile_options(${elf} PRIVATE ${opts})\n\ttarget_compile_definitions(${elf} PRIVATE ${mcu} ${name} ${defs} TARGET_NAME=\"${name}\" ${ARGN})\n\ttarget_link_options(${elf} PRIVATE -T${CMAKE_CURRENT_SOURCE_DIR}/mcu/${mcu}/config.ld -T${CMAKE_CURRENT_SOURCE_DIR}/mcu/common.ld ${opts})\n\ttarget_link_libraries(${elf} c_nano gcc nosys ${libs})\n\tadd_custom_command(\n\t\tOUTPUT ${bin} ${hex}\n\t\tCOMMAND arm-none-eabi-objcopy -O binary ${elf} ${bin}\n\t\tCOMMAND arm-none-eabi-objcopy -O ihex ${elf} ${hex}\n\t\tDEPENDS ${elf}\n\t)\n\tadd_custom_target(${name} ALL DEPENDS ${hex})\n\tadd_custom_target(flash-${name} COMMAND st-flash --reset --connect-under-reset --format ihex write ${hex} DEPENDS ${hex})\nendfunction()\n\nadd_subdirectory(boot)\n\nadd_target(AART1 AT32F421 DEAD_TIME=0 COMP_MAP=123 ARM=0 VOLUME=0 INPUT_MODE=1 ANALOG_CHAN=6 ANALOG_MIN=270 ANALOG_MAX=1440 DUTY_MIN=100 DUTY_SPUP=25 FULL_DUTY IO_RXTX)\nadd_target(AIRBOT1 AT32F421 DEAD_TIME=66 COMP_MAP=321 SENS_MAP=0xA3A6 VOLT_MUL=738 CURR_MUL=30 LED_MAP=0xAFB3B4)\nadd_target(AIRBOT2 STM32F051 DEAD_TIME=26 COMP_MAP=321 SENS_MAP=0xA3 VOLT_MUL=738 IO_PA2)\nadd_target(EMAX1 STM32F051 DEAD_TIME=26 COMP_MAP=123 IO_PA2)\nadd_target(ESCAPE1 STM32G071 DEAD_TIME=35 COMP_MAP=123 HALL_MAP=0xAFB35 SENS_MAP=0xA6A5A4 VOLT_MUL=1100 CURR_MUL=30 BEC_MAP=0xCEF LED_WS2812 LED_STAT IO_PA2)\nadd_target(ESCAPE2 STM32G071 DEAD_TIME=35 COMP_MAP=123 SENS_MAP=0xA6 VOLT_MUL=1100 BEC_MAP=0xADE IO_PA2)\nadd_target(ESCAPE3 AT32F421 DEAD_TIME=66 COMP_MAP=123 SENS_MAP=0xA6 VOLT_MUL=1100 BEC_MAP=0xADE)\nadd_target(ESCAPE4 STM32G071 DEAD_TIME=35 COMP_MAP=123 HALL_MAP=0xB358 SENS_MAP=0xA6A5A4 VOLT_MUL=1100 CURR_MUL=30 BEC_MAP=0xCEF LED_MAP=0xF2AF LED1_INV LED_STAT IO_PA2)\nadd_target(ESCAPE5 STM32G071 DEAD_TIME=35 COMP_MAP=123 SENS_MAP=0xA6 VOLT_MUL=1100 BEC_MAP=0xA45 LED_WS2812 LED_STAT IO_PA2)\nadd_target(FLYCOLOR1 STM32F051 DEAD_TIME=26 COMP_MAP=123 SENS_MAP=0xA6 VOLT_MUL=1100 LED_MAP=0xB5B4B3 IO_PA2)\nadd_target(FLYCOLOR2 STM32G071 DEAD_TIME=35 COMP_MAP=123 SENS_MAP=0xA6 VOLT_MUL=1100 LED_MAP=0xB8 LED_STAT)\nadd_target(FLYCOLOR3 STM32G071 DEAD_TIME=50 COMP_MAP=123 SENS_MAP=0xA6A4 VOLT_MUL=2100 CURR_MUL=30)\nadd_target(FLYINGRC1 AT32F421 DEAD_TIME=66 COMP_MAP=123)\nadd_target(FREELYRC1 AT32F421 DEAD_TIME=66 COMP_MAP=123 SENS_MAP=0xA3 VOLT_MUL=1100 LED_WS2812 LED_STAT)\nadd_target(GEPRC1 AT32F421 DEAD_TIME=66 COMP_MAP=123 SENS_MAP=0xA3 VOLT_MUL=1100)\nadd_target(HAKRC1 STM32F051 DEAD_TIME=26 COMP_MAP=213 SENS_MAP=0xA3 VOLT_MUL=1100 LED_MAP=0xAFB5B3 LED_INV LED_OD)\nadd_target(HAKRC2 AT32F421 DEAD_TIME=66 COMP_MAP=213 SENS_MAP=0xA3 VOLT_MUL=1100 LED_MAP=0xAFB5B3 LED_INV LED_OD)\nadd_target(HAKRC3 STM32G071 DEAD_TIME=35 COMP_MAP=132 SENS_MAP=0xA1A5 VOLT_MUL=1100 CURR_MUL=20 LED_WS2812 LED_STAT)\nadd_target(HGLRC1 STM32F051 DEAD_TIME=26 COMP_MAP=123 SENS_MAP=0xA6 VOLT_MUL=2100 IO_PA2)\nadd_target(HHOBBIES1 GD32E230 DEAD_TIME=40 COMP_MAP=321 SENS_MAP=0xA6 VOLT_MUL=1100 LED_MAP=0xAF LED_INV LED_STAT)\nadd_target(HOBBYWING1 STM32F051 DEAD_TIME=40 COMP_MAP=123 IO_PA2)\nadd_target(HOBBYWING2 AT32F421 DEAD_TIME=96 COMP_MAP=123)\nadd_target(HOLYBRO1 GD32F350 DEAD_TIME=57 COMP_MAP=321 SENS_MAP=0xA6A0 VOLT_MUL=1290 CURR_MUL=50 USE_COMP2)\nadd_target(IFLIGHT1 STM32F051 DEAD_TIME=26 COMP_MAP=321 SENS_MAP=0xA3A6 VOLT_MUL=1100 CURR_MUL=60 LED_MAP=0xB8B5B3 LED_INV)\nadd_target(IFLIGHT2 STM32G071 DEAD_TIME=35 COMP_MAP=213 SENS_MAP=0xA5A4 VOLT_MUL=1100 CURR_MUL=20 LED_WS2812 IO_PA6)\nadd_target(IFLIGHT3 STM32G071 DEAD_TIME=35 COMP_MAP=132 SENS_MAP=0xA0 VOLT_MUL=1100 LED_WS2812)\nadd_target(IFLIGHT4 STM32G071 DEAD_TIME=35 COMP_MAP=213 SENS_MAP=0xA5 VOLT_MUL=1100 LED_WS2812 IO_PA6)\nadd_target(LUMENIER1 GD32F350 DEAD_TIME=57 COMP_MAP=321 SENS_MAP=0xA3 VOLT_MUL=1100)\nadd_target(LYI1 AT32F421 DEAD_TIME=66 COMP_MAP=321 SENS_MAP=0xA3 VOLT_MUL=1100)\nadd_target(NEUTRON1 AT32F421 DEAD_TIME=66 COMP_MAP=321)\nadd_target(NEUTRON2 AT32F421 DEAD_TIME=66 COMP_MAP=321 INVERTED_HIGH)\nadd_target(NEUTRON3 STM32L431 DEAD_TIME=44 COMP_MAP=123 SENS_MAP=0xA6A3 VOLT_MUL=2100 CURR_MUL=125 USE_COMP2 USE_OPAMP)\nadd_target(ODDITYRC1 AT32F421 DEAD_TIME=66 COMP_MAP=123 SENS_MAP=0xA3BF VOLT_MUL=1100 CURR_MUL=40)\nadd_target(PHOTONDRIVE1 STM32G431 DEAD_TIME=155 COMP_MAP=132 SENS_MAP=0xBFA6 VOLT_MUL=2236 CURR_MUL=63 TEMP_ADC2 TEMP_CHAN=14 TEMP_FUNC=NTC10K3455UP10K LED_WS2812 LED_STAT USE_PB1 USE_HSE=8 DUTY_SPUP=5 DUTY_RATE=20 PROT_TEMP=100)\nadd_target(RHINO1 STM32F051 DEAD_TIME=26 COMP_MAP=321 SENS_MAP=0xA6 VOLT_MUL=1100)\nadd_target(SEQURE1 STM32G071 DEAD_TIME=35 COMP_MAP=123 SENS_MAP=0xA6A4 VOLT_MUL=2100 CURR_MUL=30 BEC_MAP=0xCEF BEC_MIN=1 LED_WS2812 LED_STAT)\nadd_target(SEQURE2 STM32G071 DEAD_TIME=50 COMP_MAP=123 SENS_MAP=0xA6A4 VOLT_MUL=2100 CURR_MUL=87 BEC_MAP=0xCEF BEC_MIN=1 LED_WS2812 LED_STAT ERPM_PIN=5)\nadd_target(SKYSTARS1 GD32E230 DEAD_TIME=40 COMP_MAP=321 SENS_MAP=0xA3 VOLT_MUL=1100 LED_MAP=0xB5B3AF)\nadd_target(TMOTOR1 STM32F051 DEAD_TIME=26 COMP_MAP=132 IO_PA2)\nadd_target(TMOTOR2 STM32F051 DEAD_TIME=26 COMP_MAP=321)\nadd_target(TMOTOR3 STM32G071 DEAD_TIME=35 COMP_MAP=231 IO_PA6)\nadd_target(TMOTOR4 STM32G071 DEAD_TIME=35 COMP_MAP=123)\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "ESCape32\n========\n\nFirmware for 32-bit BLDC motor electronic speed controllers that aims for simplicity. It is designed to deliver smooth and efficient motor drive, fast transitions from a complete stop to full throttle, robust direction reversals, and maximum hardware support.\n\n\nFeatures\n--------\n\n+ Servo PWM, Oneshot125, automatic throttle calibration\n+ DSHOT 300/600/1200, bidirectional DSHOT, extended telemetry\n+ Analog/serial/iBUS/SBUS/SBUS2/CRSF input mode\n+ KISS/iBUS/S.Port/CRSF telemetry\n+ DSHOT 3D mode, turtle mode, beacon, LED, programming\n+ Sine startup mode, brushed mode, hybrid mode (sensored/sensorless)\n+ Proportional brake, adjustable drag brake\n+ Temperature/voltage/current/stall protection\n+ Variable PWM frequency, active freewheeling\n+ Customizable startup music/sounds\n\n\nInstallation\n------------\n\nThe list of compatible ESCs can be found [here](https://github.com/neoxic/ESCape32/wiki/Targets).\n\nThe latest release can be downloaded [here](https://github.com/neoxic/ESCape32/releases).\n\nVisit the [ESCape32 Wiki](https://github.com/neoxic/ESCape32/wiki) for more information.\n\n\nDependencies\n------------\n\n+ cmake\n+ arm-none-eabi-gcc\n+ arm-none-eabi-binutils\n+ arm-none-eabi-newlib\n+ libopencm3\n+ stlink\n\n\nBuilding from source\n--------------------\n\nUse `LIBOPENCM3_DIR` to specify a path to LibOpenCM3 if it is not in the system root:\n\n```\ngit clone https://github.com/libopencm3/libopencm3.git\nmake -C libopencm3 TARGETS='stm32/f0 stm32/g0 stm32/g4 stm32/l4'\ncmake -B build -D LIBOPENCM3_DIR=libopencm3\n```\n\nUse `CMAKE_INSTALL_PREFIX` to specify an alternative system root:\n\n```\ncmake -B build -D CMAKE_INSTALL_PREFIX=~/local\n```\n\nTo build all targets, run:\n\n```\ncmake -B build\ncd build\nmake\n```\n\nTo flash a particular target using an ST-LINK programmer, run:\n\n```\nmake flash-<target>\n```\n\n\nBuilding on GitHub\n------------------\n\n+ Fork the repository.\n+ Go to _Actions_.\n+ Run the _Build ESCape32_ workflow.\n"
  },
  {
    "path": "boot/CMakeLists.txt",
    "content": "add_target(BOOT1_PA2 STM32F0 IO_PA2)\nadd_target(BOOT1_PB4 STM32F0)\nadd_target(BOOT2_PA2 STM32G0 IO_PA2)\nadd_target(BOOT2_PA6 STM32G0 IO_PA6)\nadd_target(BOOT2_PB4 STM32G0)\nadd_target(BOOT3_PA2 STM32F0 AT32F4 IO_PA2)\nadd_target(BOOT3_PA2_FE STM32F0 AT32F4 IO_PA2 IO_RXTX FAST_EXIT)\nadd_target(BOOT4_PA2 STM32G4)\n"
  },
  {
    "path": "boot/mcu/STM32F0/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nvoid init(void) {\n\tRCC_AHBENR = RCC_AHBENR_CRCEN | RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;\n\tRCC_APB2ENR = RCC_APB2ENR_TIM1EN;\n\n\tFLASH_ACR = FLASH_ACR_LATENCY_1WS | FLASH_ACR_PRFTEN;\n\tRCC_CFGR = RCC_CFGR_PLLMUL_MUL12;\n\tRCC_CR |= RCC_CR_PLLON;\n\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\tRCC_CFGR |= RCC_CFGR_SW_PLL;\n\n\tGPIOA_MODER = 0xebffffff;\n\tGPIOB_MODER = 0xffffffff;\n#ifdef IO_PA2\n\tRCC_APB1ENR |= RCC_APB1ENR_USART2EN;\n\tGPIOA_AFRL |= 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (USART2_TX)\n#else\n\tRCC_APB1ENR |= RCC_APB1ENR_TIM3EN;\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_PUPDR |= 0x100; // B4 (pull-up)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n#endif\n}\n"
  },
  {
    "path": "boot/mcu/STM32F0/config.cmake",
    "content": "set(opts -mcpu=cortex-m0 -mthumb)\nset(libs opencm3_stm32f0)\n"
  },
  {
    "path": "boot/mcu/STM32F0/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 48000000\n#define PAGE_SIZE 1024\n"
  },
  {
    "path": "boot/mcu/STM32F0/config.ld",
    "content": "MEMORY {\n\trom (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 4K\n}\n"
  },
  {
    "path": "boot/mcu/STM32G0/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nvoid init(void) {\n\tRCC_IOPENR = 0x3; // GPIOAEN=1, GPIOBEN=1\n\tRCC_AHBENR = RCC_AHBENR_FLASHEN | RCC_AHBENR_CRCEN;\n\tRCC_APBENR2 = RCC_APBENR2_TIM1EN;\n\n\tFLASH_ACR = FLASH_ACR_LATENCY_2WS | FLASH_ACR_PRFTEN | FLASH_ACR_ICEN | FLASH_ACR_DBG_SWEN;\n\tRCC_PLLCFGR = RCC_PLLCFGR_PLLSRC_HSI16 | 8 << RCC_PLLCFGR_PLLN_SHIFT | RCC_PLLCFGR_PLLREN | 1 << RCC_PLLCFGR_PLLR_SHIFT;\n\tRCC_CR |= RCC_CR_PLLON;\n\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\tRCC_CFGR = RCC_CFGR_SW_PLLRCLK;\n\n#ifdef IO_PA2\n\tRCC_APBENR1 |= RCC_APBENR1_USART2EN;\n\tGPIOA_AFRL |= 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (USART2_TX)\n#else\n\tRCC_APBENR1 |= RCC_APBENR1_TIM3EN;\n#ifdef IO_PA6\n\tGPIOA_AFRL |= 0x1000000; // A6 (TIM3_CH1)\n\tGPIOA_PUPDR |= 0x1000; // A6 (pull-up)\n\tGPIOA_MODER &= ~0x1000; // A6 (TIM3_CH1)\n#else\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_PUPDR |= 0x100; // B4 (pull-up)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n#endif\n#endif\n}\n"
  },
  {
    "path": "boot/mcu/STM32G0/config.cmake",
    "content": "set(opts -mcpu=cortex-m0plus -mthumb)\nset(libs opencm3_stm32g0)\n"
  },
  {
    "path": "boot/mcu/STM32G0/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 64000000\n#define PAGE_SIZE 2048\n"
  },
  {
    "path": "boot/mcu/STM32G0/config.ld",
    "content": "MEMORY {\n\trom (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 4K\n}\n"
  },
  {
    "path": "boot/mcu/STM32G4/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nvoid init(void) {\n\tRCC_AHB1ENR = RCC_AHB1ENR_FLASHEN | RCC_AHB1ENR_CRCEN;\n\tRCC_AHB2ENR = RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN;\n\tRCC_APB1ENR1 = RCC_APB1ENR1_USART2EN;\n\tRCC_APB2ENR = RCC_APB2ENR_TIM1EN;\n\n\tFLASH_ACR = 4 | FLASH_ACR_PRFTEN | FLASH_ACR_ICEN | FLASH_ACR_DCEN | FLASH_ACR_DBG_SWEN; // LATENCY=4\n\tRCC_PLLCFGR = RCC_PLLCFGR_PLLSRC_HSI16 | 10 << RCC_PLLCFGR_PLLN_SHIFT | RCC_PLLCFGR_PLLREN;\n\tRCC_CR |= RCC_CR_HSION | RCC_CR_PLLON;\n\twhile (!(RCC_CR & (RCC_CR_HSIRDY | RCC_CR_PLLRDY)));\n\tRCC_CFGR = RCC_CFGR_SWx_PLL;\n\n\tGPIOA_AFRL = 0x00000700; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH = 0x70000000; // A15 (USART2_RX)\n#endif\n\tGPIOA_PUPDR = 0x24000010; // A2 (pull-up)\n\tGPIOB_PUPDR = 0x00000000;\n\tGPIOA_MODER = 0xebffffef; // A2 (USART2_TX)\n\tGPIOB_MODER = 0xffffffff;\n}\n"
  },
  {
    "path": "boot/mcu/STM32G4/config.cmake",
    "content": "set(opts -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16)\nset(libs opencm3_stm32g4)\n"
  },
  {
    "path": "boot/mcu/STM32G4/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 80000000\n#define PAGE_SIZE 2048\n#define IO_PA2\n"
  },
  {
    "path": "boot/mcu/STM32G4/config.ld",
    "content": "MEMORY {\n\trom (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 4K\n}\n"
  },
  {
    "path": "boot/mcu/common.ld",
    "content": "_rom = ORIGIN(rom);\n_rom_end = ORIGIN(rom) + LENGTH(rom);\n_ram_end = ORIGIN(ram) + LENGTH(ram);\n\nINCLUDE cortex-m-generic.ld\n"
  },
  {
    "path": "boot/src/common.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#include <libopencm3/cm3/scb.h>\n#include <libopencm3/stm32/rcc.h>\n#include <libopencm3/stm32/gpio.h>\n#include <libopencm3/stm32/timer.h>\n#ifdef AT32F4\n#include <libopencm3/cm3/common.h>\n#include <libopencm3/stm32/f1/usart.h>\n#else\n#include <libopencm3/stm32/usart.h>\n#endif\n#include <libopencm3/stm32/flash.h>\n#include <libopencm3/stm32/crc.h>\n#include <libopencm3/stm32/dbgmcu.h>\n#include \"config.h\"\n\n#define CLK_CNT(rate) ((CLK + ((rate) >> 1)) / (rate))\n\n#ifdef IO_PA2\n#define IO_PIN 1\n#elif defined IO_PA6\n#define IO_PIN 2\n#define TIM3_IDR (GPIOA_IDR & 0x40) // A6\n#else\n#define IO_PIN 3\n#define TIM3_IDR (GPIOB_IDR & 0x10) // B4\n#endif\n\nextern char _rom[], _rom_end[], _ram_end[]; // Linker exports\n\nvoid init(void);\nvoid initio(void);\n\nint recvbuf(char *buf, int len);\nvoid sendbuf(const char *buf, int len);\nint recvval(void);\nvoid sendval(int val);\nint recvdata(char *buf);\nvoid senddata(const char *buf, int len);\n\nuint32_t crc32(const char *buf, int len);\nint write(char *dst, const char *src, int len) __attribute__((__long_call__));\nvoid update(char *dst, const char *src, int len) __attribute__((__long_call__));\nvoid setwrp(int type);\n"
  },
  {
    "path": "boot/src/io.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#ifdef AT32F4\n#define USART2_TDR USART2_DR\n#define USART2_RDR USART2_DR\n#define USART2_ISR USART2_SR\n#define USART_ISR_RXNE USART_SR_RXNE\n#define USART_ISR_TXE USART_SR_TXE\n#define USART_ISR_TC USART_SR_TC\n#define USART_ISR_FE USART_SR_FE\n#define USART_ISR_NF USART_SR_NE\n#endif\n\nvoid initio(void) {\n#ifdef IO_PA2\n#ifdef IO_RXTX\n\tGPIOA_PUPDR |= 0x80000000; // A15 (pull-down)\n\tGPIOA_MODER &= ~0x40000000; // A15 (USART2_RX)\n\tTIM1_ARR = CLK_CNT(20000) - 1;\n\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM1_CR1 & TIM_CR1_CEN) { // Wait for 50us high level on A15\n\t\tif (!(GPIOA_IDR & 0x8000)) { // A15 low\n\t\t\tUSART2_CR3 = USART_CR3_HDSEL;\n\t\t\tbreak;\n\t\t}\n\t}\n#else\n\tUSART2_CR3 = USART_CR3_HDSEL;\n#endif\n\tUSART2_BRR = CLK_CNT(38400);\n\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;\n#else\n\tTIM3_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2 | TIM_CCMR1_CC2S_IN_TI1 | TIM_CCMR1_IC2F_CK_INT_N_8;\n\tTIM3_SMCR = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\tTIM3_CCER = TIM_CCER_CC2E | TIM_CCER_CC2P; // IC2 on falling edge on TI1\n\tTIM3_ARR = CLK_CNT(38400) - 1; // Bit time\n\tTIM3_CCR1 = CLK_CNT(76800); // Half-bit time\n\tTIM3_EGR = TIM_EGR_UG;\n\tTIM3_CR1 = TIM_CR1_CEN;\n#endif\n\tTIM1_PSC = CLK_CNT(10000) - 1; // 0.1ms resolution\n\tTIM1_ARR = 4999; // 500ms I/O timeout\n\tTIM1_CR1 = TIM_CR1_URS;\n\tTIM1_EGR = TIM_EGR_UG;\n\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_URS;\n}\n\n#ifdef IO_PA2\nint recvbuf(char *buf, int len) {\n\tTIM1_EGR = TIM_EGR_UG;\n\tTIM1_SR = ~TIM_SR_UIF;\n\tfor (int i = 0; i < len; ++i) {\n\t\twhile (!(USART2_ISR & USART_ISR_RXNE)) {\n\t\t\tif (TIM1_SR & TIM_SR_UIF) return 0; // Timeout\n\t\t}\n\t\tif (USART2_ISR & (USART_ISR_FE | USART_ISR_NF)) { // Data error\n#ifdef AT32F4\n\t\t\tUSART2_DR; // Clear flags\n#else\n\t\t\tUSART2_ICR = USART_ICR_FECF | USART_ICR_NCF;\n#endif\n\t\t\treturn 0;\n\t\t}\n\t\tbuf[i] = USART2_RDR; // Clear RXNE\n\t\tTIM1_EGR = TIM_EGR_UG;\n\t}\n\treturn 1;\n}\n\nvoid sendbuf(const char *buf, int len) {\n\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE;\n\tfor (int i = 0; i < len; ++i) {\n\t\twhile (!(USART2_ISR & USART_ISR_TXE));\n\t\tUSART2_TDR = buf[i]; // Clear TXE+TC\n\t}\n\twhile (!(USART2_ISR & USART_ISR_TC));\n\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;\n}\n#else\nint recvbuf(char *buf, int len) {\n\tTIM1_EGR = TIM_EGR_UG;\n\tTIM1_SR = ~TIM_SR_UIF;\n\tint n = 10, b = 0;\n\tfor (;;) {\n\t\tint sr = TIM3_SR;\n\t\tif (sr & TIM_SR_CC1IF) { // Half-bit time\n\t\t\tTIM3_SR = ~TIM_SR_CC1IF;\n\t\t\tif (n == 10) continue;\n\t\t\tint p = TIM3_IDR; // Signal level\n\t\t\tif (!n++) { // Start bit\n\t\t\t\tif (p) return 0; // Data error\n\t\t\t\tb = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (n < 10) { // Data bit\n\t\t\t\tb >>= 1;\n\t\t\t\tif (p) b |= 0x80;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!p) return 0; // Data error\n\t\t\t*buf++ = b;\n\t\t\tif (!--len) return 1;\n\t\t\tTIM1_EGR = TIM_EGR_UG;\n\t\t}\n\t\tif (sr & TIM_SR_CC2IF) { // Falling edge\n\t\t\tTIM3_SR = ~TIM_SR_CC2IF;\n\t\t\tif (n == 10) n = 0;\n\t\t}\n\t\tif (TIM1_SR & TIM_SR_UIF) return 0; // Timeout\n\t}\n}\n\nvoid sendbuf(const char *buf, int len) {\n\tTIM3_SMCR = 0;\n\tTIM3_CCR1 = 0; // Preload high level\n\tTIM3_EGR = TIM_EGR_UG; // Update registers and trigger UEV\n\tTIM3_CCER = TIM_CCER_CC1E; // Enable output\n\tint n = 0, b = 0;\n\tfor (;;) {\n\t\tif (!(TIM3_SR & TIM_SR_UIF)) continue;\n\t\tTIM3_SR = ~TIM_SR_UIF;\n\t\tif (!len) break;\n\t\tint p = -1;\n\t\tif (!n++) b = *buf++; // Start bit\n\t\telse if (n < 10) { // Data bit\n\t\t\tif (b & 1) p = 0;\n\t\t\tb >>= 1;\n\t\t} else { // Stop bit\n\t\t\tn = 0;\n\t\t\tp = 0;\n\t\t\t--len;\n\t\t}\n\t\tTIM3_CCR1 = p;\n\t}\n\tTIM3_SMCR = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\tTIM3_CCER = TIM_CCER_CC2E | TIM_CCER_CC2P; // IC2 on falling edge on TI1\n\tTIM3_CCR1 = CLK_CNT(76800); // Half-bit time\n\tTIM3_EGR = TIM_EGR_UG;\n}\n#endif\n\nint recvval(void) {\n\tchar buf[2];\n\treturn recvbuf(buf, 2) && (buf[0] ^ buf[1]) == 0xff ? buf[0] : -1;\n}\n\nvoid sendval(int val) {\n\tchar buf[2] = {val, ~val};\n\tsendbuf(buf, 2);\n}\n\nint recvdata(char *buf) {\n\tint cnt = recvval();\n\tif (cnt == -1) return -1;\n\tint len = (cnt + 1) << 2;\n\tuint32_t crc;\n\treturn recvbuf(buf, len) && recvbuf((char *)&crc, 4) && crc32(buf, len) == crc ? len : -1;\n}\n\nvoid senddata(const char *buf, int len) {\n\tuint32_t crc = crc32(buf, len);\n\tsendval((len >> 2) - 1);\n\tsendbuf(buf, len);\n\tsendbuf((char *)&crc, 4);\n}\n"
  },
  {
    "path": "boot/src/main.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#define REVISION 4\n\n#define CMD_PROBE  0\n#define CMD_INFO   1\n#define CMD_READ   2\n#define CMD_WRITE  3\n#define CMD_UPDATE 4\n#define CMD_SETWRP 5\n\n#define RES_OK    0\n#define RES_ERROR 1\n\nvoid main(void) {\n\tinit();\n\tinitio();\n\tif (RCC_CSR & (RCC_CSR_SFTRSTF | RCC_CSR_OBLRSTF)) { // Reboot\n\t\tRCC_CSR = RCC_CSR_RMVF; // Clear reset flags\n\t\tsendval(RES_OK); // ACK after reboot\n\t}\n#ifdef FAST_EXIT\n\telse goto done;\n#endif\n\tfor (;;) {\n\t\tswitch (recvval()) {\n\t\t\tcase CMD_PROBE: // Probe bootloader\n\t\t\t\tsendval(RES_OK);\n\t\t\t\tbreak;\n\t\t\tcase CMD_INFO: { // Get info\n\t\t\t\tint mcu = DBGMCU_IDCODE;\n\t\t\t\tchar buf[32] = {REVISION, IO_PIN, mcu, mcu >> 8, mcu >> 16, mcu >> 24};\n\t\t\t\tsenddata(buf, sizeof buf);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CMD_READ: { // Read block\n\t\t\t\tint num = recvval();\n\t\t\t\tif (num == -1) goto done;\n\t\t\t\tint cnt = recvval();\n\t\t\t\tif (cnt == -1) goto done;\n\t\t\t\tsenddata(_rom_end + (num << 10), (cnt + 1) << 2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CMD_WRITE: { // Write block\n\t\t\t\tint num = recvval();\n\t\t\t\tif (num == -1) goto done;\n\t\t\t\tchar buf[1024];\n\t\t\t\tint len = recvdata(buf);\n\t\t\t\tif (len == -1) goto done;\n\t\t\t\tsendval(write(_rom_end + (num << 10), buf, len) ? RES_OK : RES_ERROR);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CMD_UPDATE: { // Update bootloader\n\t\t\t\tchar *buf = _ram_end; // Use upper SRAM as buffer\n\t\t\t\tint pos = 0;\n\t\t\t\tfor (int i = 0, n = (_rom_end - _rom) >> 10; i < n; ++i) {\n\t\t\t\t\tint len = recvdata(buf + pos);\n\t\t\t\t\tif (len == -1) goto done;\n\t\t\t\t\tsendval(RES_OK);\n\t\t\t\t\tpos += len;\n\t\t\t\t\tif (len < 1024) break; // Last block\n\t\t\t\t}\n\t\t\t\tupdate(_rom, buf, pos);\n\t\t\t\tsendval(RES_ERROR);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CMD_SETWRP: // Set write protection\n\t\t\t\tswitch (recvval()) {\n\t\t\t\t\tcase 0x33: // Off\n\t\t\t\t\t\tsetwrp(0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x44: // Bootloader\n\t\t\t\t\t\tsetwrp(1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x55: // Full\n\t\t\t\t\t\tsetwrp(2);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsendval(RES_ERROR);\n\t\t\t\tbreak;\n\t\t\tdefault: // Pass control to application\n\t\t\tdone:\n\t\t\t\tif (*(uint16_t *)_rom_end != 0x32ea) break;\n\t\t\t\t__asm__(\"msr msp, %0\" :: \"g\" (*(uint32_t *)(_rom_end + PAGE_SIZE))); // Initialize stack pointer\n\t\t\t\t(*(void (**)(void))(_rom_end + PAGE_SIZE + 4))(); // Jump to application\n\t\t\t\tfor (;;); // Never return\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "boot/src/util.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#ifndef FLASH_CR_STRT\n#define FLASH_CR_STRT FLASH_CR_START\n#endif\n\nuint32_t crc32(const char *buf, int len) {\n\tuint32_t *val = (uint32_t *)buf;\n\tlen >>= 2;\n\tCRC_CR = CRC_CR_RESET | CRC_CR_REV_IN_WORD | CRC_CR_REV_OUT;\n\twhile (len--) CRC_DR = *val++;\n\treturn ~CRC_DR;\n}\n\n__attribute__((__section__(\".ramtext\")))\nint write(char *dst, const char *src, int len) {\n\tFLASH_KEYR = FLASH_KEYR_KEY1;\n\tFLASH_KEYR = FLASH_KEYR_KEY2;\n\tFLASH_SR = -1; // Clear errors\n\tFLASH_CR = FLASH_CR_PER;\n\tuint32_t addr = ((uint32_t)dst + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);\n\tuint32_t last = ((uint32_t)dst + len - 1) & ~(PAGE_SIZE - 1);\n\twhile (addr <= last) { // Erase pages\n\t\tMMIO32(addr); // Invalid address triggers a hard fault\n#ifdef STM32F0\n\t\tFLASH_AR = addr;\n\t\tFLASH_CR = FLASH_CR_PER | FLASH_CR_STRT;\n#else\n\t\tFLASH_CR = FLASH_CR_PER | FLASH_CR_STRT | ((addr - (uint32_t)_rom) / PAGE_SIZE) << FLASH_CR_PNB_SHIFT;\n#endif\n\t\twhile (FLASH_SR & FLASH_SR_BSY);\n\t\taddr += PAGE_SIZE;\n\t}\n\tFLASH_CR = FLASH_CR_PG;\n#ifdef STM32F0\n\tfor (int pos = 0; pos < len; pos += 2) { // Write half-words\n\t\t*(uint16_t *)(dst + pos) = *(uint16_t *)(src + pos);\n\t\twhile (FLASH_SR & FLASH_SR_BSY);\n\t}\n#else\n\tfor (int pos = 0; pos < len; pos += 8) { // Write double words\n\t\t*(uint32_t *)(dst + pos) = *(uint32_t *)(src + pos);\n\t\t*(uint32_t *)(dst + pos + 4) = *(uint32_t *)(src + pos + 4);\n\t\twhile (FLASH_SR & FLASH_SR_BSY);\n\t}\n#endif\n\tFLASH_CR = FLASH_CR_LOCK;\n#ifdef STM32F0\n\tif (FLASH_SR & (FLASH_SR_PGERR | FLASH_SR_WRPRTERR)) return 0;\n#else\n\tif (FLASH_SR & (FLASH_SR_PROGERR | FLASH_SR_WRPERR)) return 0;\n#endif\n\tfor (int pos = 0; pos < len; pos += 4) { // Check written data\n\t\tif (*(uint32_t *)(dst + pos) != *(uint32_t *)(src + pos)) return 0;\n\t}\n\treturn 1;\n}\n\n__attribute__((__section__(\".ramtext\")))\nvoid update(char *dst, const char *src, int len) {\n\tif (!write(dst, src, len)) return;\n\tSCB_AIRCR = SCB_AIRCR_VECTKEY | SCB_AIRCR_SYSRESETREQ;\n\tfor (;;); // Never return\n}\n\nvoid setwrp(int type) { // 0 - off, 1 - bootloader, 2 - full\n\tFLASH_KEYR = FLASH_KEYR_KEY1;\n\tFLASH_KEYR = FLASH_KEYR_KEY2;\n\tFLASH_OPTKEYR = FLASH_OPTKEYR_KEY1;\n\tFLASH_OPTKEYR = FLASH_OPTKEYR_KEY2;\n\tFLASH_SR = -1; // Clear errors\n#ifdef STM32F0\n\tchar opts[6] = {FLASH_OPTION_BYTE_0, FLASH_OPTION_BYTE_1, FLASH_OPTION_BYTE_2, FLASH_OPTION_BYTE_3, 0xff, 0xff};\n\tif (type == 1) opts[4] = ~((1 << ((_rom_end - _rom + 4095) >> 12)) - 1);\n\telse if (type == 2) opts[4] = opts[5] = 0;\n\tFLASH_CR = FLASH_CR_OPTWRE | FLASH_CR_OPTER;\n\tFLASH_CR = FLASH_CR_OPTWRE | FLASH_CR_OPTER | FLASH_CR_STRT;\n\twhile (FLASH_SR & FLASH_SR_BSY);\n\tFLASH_CR = FLASH_CR_OPTWRE | FLASH_CR_OPTPG;\n\tfor (int i = 0; i < 6; ++i) {\n\t\tFLASH_OPTION_BYTE(i) = opts[i];\n\t\twhile (FLASH_SR & FLASH_SR_BSY);\n\t}\n\tif (FLASH_SR & (FLASH_SR_PGERR | FLASH_SR_WRPRTERR)) return;\n#else\n\tFLASH_WRP1AR =\n\t\ttype == 1 ? (((_rom_end - _rom + 2047) >> 11) - 1) << 16:\n\t\ttype == 2 ? 0xff0000 : 0xff;\n\tFLASH_CR = FLASH_CR_OPTSTRT;\n\twhile (FLASH_SR & FLASH_SR_BSY);\n\tif (FLASH_SR & (FLASH_SR_PROGERR | FLASH_SR_WRPERR)) return;\n#endif\n#ifdef AT32F4\n\tSCB_AIRCR = SCB_AIRCR_VECTKEY | SCB_AIRCR_SYSRESETREQ;\n#else\n\tFLASH_CR = FLASH_CR_OBL_LAUNCH;\n#endif\n\tfor (;;); // Never return\n}\n"
  },
  {
    "path": "mcu/AT32F421/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/cm3/common.h>\n#include <libopencm3/stm32/f1/adc.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA3 // A3 (volt)\n#define SENS_CHAN 0x3\n#elif SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0x6\n#elif SENS_MAP == 0xA3A6 // A3 (volt), A6 (curr)\n#define SENS_CHAN 0x66\n#elif SENS_MAP == 0xA3BF // A3 (volt), B15 (curr)\n#define SENS_CHAN 0x6e\n#elif SENS_MAP == 0xA6A3 // A6 (volt), A3 (curr)\n#define SENS_CHAN 0xc3\n#elif SENS_MAP == 0xB2A6A3 // B2 (temp), A6 (volt), A3 (curr)\n#define SENS_CHAN 0x28c3\n#endif\n\n#ifndef ANALOG_CHAN\n#define ANALOG_CHAN 0x2 // ADC_IN2 (A2)\n#endif\n\n#ifndef TEMP_CHAN\n#define TEMP_CHAN 0x10 // ADC_IN16 (temp)\n#define TEMP_FUNC(x) ((((x) - 1280) * 3800 >> 12) + 100)\n#endif\n\n#define ADC1_BASE ADC_BASE\n#define COMP_CSR MMIO32(SYSCFG_COMP_BASE + 0x1c)\n\nstatic char len, ain;\nstatic uint16_t buf[6];\n#ifdef LED_WS2812\nstatic uint16_t led[5];\n#endif\n\nvoid init(void) {\n\tRCC_APB2RSTR = -1;\n\tRCC_APB1RSTR = -1;\n\tRCC_APB2RSTR = 0;\n\tRCC_APB1RSTR = 0;\n\tRCC_AHBENR = RCC_AHBENR_DMAEN | RCC_AHBENR_SRAMEN | RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;\n\tRCC_APB2ENR = RCC_APB2ENR_SYSCFGCOMPEN | RCC_APB2ENR_ADCEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_USART1EN;\n\tRCC_APB1ENR = RCC_APB1ENR_TIM3EN | RCC_APB1ENR_TIM6EN | RCC_APB1ENR_WWDGEN;\n\tSCB_VTOR = (uint32_t)_rom; // Set vector table address\n\n\tRCC_CFGR &= ~RCC_CFGR_SW_PLL;\n\twhile (RCC_CFGR & RCC_CFGR_SWS_PLL);\n\tRCC_CR &= ~RCC_CR_PLLON;\n\twhile (RCC_CR & RCC_CR_PLLRDY);\n\tFLASH_ACR = 0x13; // LATENCY=3WS, PFTEN\n\tRCC_CFGR = 0x2034c000; // ADCDIV=011 (PCLK/8), PLLMUL=011101 (x30)\n\tRCC_CR |= RCC_CR_PLLON;\n\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\tRCC_CFGR |= RCC_CFGR_SW_PLL;\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRL = 0x20000000; // A7 (TIM1_CH1N)\n\tGPIOA_AFRH = 0x00000222; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x00000022; // B0 (TIM1_CH2N), B1 (TIM1_CH3N)\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeabfff; // A7 (TIM1_CH1N), A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffeffa; // B0 (TIM1_CH2N), B1 (TIM1_CH3N), B6 (USART1_TX)\n#ifndef ANALOG\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM15EN;\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM15_IRQ, 0x40);\n#ifdef IO_AUX\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM16EN;\n\tGPIOB_AFRH |= 0x2; // B8 (TIM16_CH1)\n\tGPIOB_PUPDR |= 0x10000; // B8 (pull-up)\n\tGPIOB_MODER &= ~0x10000; // B8 (TIM16_CH1)\n\tnvic_set_priority(NVIC_TIM16_IRQ, 0x40);\n#endif\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x80); // ADC, WS2812\n\tnvic_set_priority(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ, 0x80); // USART1_TX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ, 0x40); // TIM15 or USART2_RX\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_UP_TRG_COM_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_CC_IRQ);\n\tnvic_enable_irq(NVIC_TIM3_IRQ);\n\tnvic_enable_irq(NVIC_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_TIM16_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ);\n\n\tTIM1_DIER = TIM_DIER_CC1IE; // ADC trigger\n\tTIM1_SMCR = TIM_SMCR_TS_ITR2; // TRGI=TIM3\n\tTIM3_CR2 = TIM_CR2_MMS_COMPARE_OC3REF; // TRGO=OC3REF\n\tTIM3_CCMR1 = TIM_CCMR1_CC1S_IN_TI1;\n\tTIM3_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM2; // Inverted PWM on OC3\n\tTIM3_CCER = TIM_CCER_CC1E; // IC1 on rising edge on TI1 (COMP_OUT)\n\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE;\n\tTIM6_ARR = CLK_MHZ * 3 - 1;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 3us (RM 18.4.2.1)\n\tADC1_CR2 |= ADC_CR2_CAL;\n\twhile (ADC1_CR2 & ADC_CR2_CAL);\n\tADC1_CR1 = ADC_CR1_SCAN;\n\tADC1_SMPR1 = -1; // Sampling time ~16us @ PCLK/8=15Mhz\n\tADC1_SMPR2 = -1;\n\tADC1_SQR3 = SENS_CHAN;\n\tlen = SENS_CNT;\n\tif (IO_ANALOG) {\n\t\tADC1_SQR3 |= ANALOG_CHAN << (len++ * 5);\n\t\tain = 1;\n\t}\n\tADC1_SQR3 |= (TEMP_CHAN | 0x220) << (len * 5); // ADC_IN17 (vref)\n\tlen += 2;\n\tADC1_SQR1 = (len - 1) << ADC_SQR1_L_LSB;\n#ifndef LED_WS2812\n\tDMA1_CPAR(1) = (uint32_t)&ADC1_DR;\n\tDMA1_CMAR(1) = (uint32_t)buf;\n#endif\n}\n\n#ifdef LED_WS2812\nvoid initled(void) {\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM17EN;\n\tGPIOB_AFRL |= 0x20000000; // B7 (TIM17_CH1N)\n\tGPIOB_MODER &= ~0x4000; // B7 (TIM17_CH1N)\n}\n\nvoid ledctl(int x) {\n\tstatic int y = -1;\n\tif (DMA1_CCR(1) & DMA_CCR_EN) { // DMA channel is shared with ADC\n\t\ty = x;\n\t\treturn;\n\t}\n\tif (x < 0 && (x = y) < 0) return;\n\tled[0] = x & 2 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Green\n\tled[1] = x & 1 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Red\n\tled[2] = x & 4 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Blue\n\tled[3] = 0;\n\tled[4] = 0;\n\tDMA1_CPAR(1) = (uint32_t)&TIM17_CCR1;\n\tDMA1_CMAR(1) = (uint32_t)led;\n\tDMA1_CNDTR(1) = 5;\n\tDMA1_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tTIM17_BDTR = TIM_BDTR_MOE;\n\tTIM17_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1;\n\tTIM17_CCER = TIM_CCER_CC1NE;\n\tTIM17_DIER = TIM_DIER_CC1DE;\n\tTIM17_CR2 = TIM_CR2_CCDS; // CC1 DMA request on UEV\n\tTIM17_ARR = CLK_CNT(800000) - 1;\n\tTIM17_RCR = 7;\n\tTIM17_EGR = TIM_EGR_UG;\n\tTIM17_CR1 = TIM_CR1_CEN;\n\ty = -1;\n}\n#endif\n\nvoid hsictl(int x) {\n\tint cr = RCC_CR;\n\tint tv = (cr & 0xfc) >> 2; // 6 bits\n\tRCC_CR = (cr & ~0xfc) | clamp(tv + x, 0, 0x3f) << 2;\n}\n\nvoid compctl(int x) {\n\tint cr = 0;\n\tswitch (x & 3) {\n\t\tcase COMP_IN1:\n\t\t\tcr = 0x418e1; // A1>A0\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tcr = 0x418c1; // A1>A4\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tcr = 0x418d1; // A1>A5\n\t\t\tbreak;\n\t}\n\tif (x & 4) cr |= 0x8000; // Change polarity\n\tCOMP_CSR = cr;\n}\n\nvoid io_serial(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tRCC_APB1ENR |= RCC_APB1ENR_USART2EN;\n\tGPIOA_AFRL |= 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n}\n\nvoid io_analog(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n\nvoid adctrig(void) {\n\tif (DMA1_CCR(1) & DMA_CCR_EN) return;\n#ifdef LED_WS2812\n\tDMA1_CPAR(1) = (uint32_t)&ADC1_DR;\n\tDMA1_CMAR(1) = (uint32_t)buf;\n#endif\n\tDMA1_CNDTR(1) = len;\n\tDMA1_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_DMA | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL_SWSTART;\n}\n\nvoid tim1_cc_isr(void) {\n\tTIM1_SR = ~TIM_SR_CC1IF;\n\tif (!(ADC1_CR2 & ADC_CR2_DMA)) return;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_DMA | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL_SWSTART | ADC_CR2_SWSTART;\n}\n\nvoid dma1_channel1_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(1);\n#ifdef LED_WS2812\n\tif (DMA1_CCR(1) & DMA_CCR_DIR) {\n\t\tDMA1_CCR(1) = 0;\n\t\tRCC_APB2RSTR = RCC_APB2RSTR_TIM17RST; // Errata 1.5.1\n\t\tRCC_APB2RSTR = 0;\n\t\treturn;\n\t}\n#endif\n\tDMA1_CCR(1) = 0;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE;\n#ifdef LED_WS2812\n\tledctl(-1);\n#endif\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n\tif (ain) a = buf[i++];\n\tint r = 4914000 / buf[i + 1];\n\tadcdata(TEMP_FUNC(buf[i] * r >> 12), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n"
  },
  {
    "path": "mcu/AT32F421/config.cmake",
    "content": "set(opts -mcpu=cortex-m4 -mthumb)\nset(libs opencm3_stm32f0)\nset(defs STM32F0 AT32F4)\n"
  },
  {
    "path": "mcu/AT32F421/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 120000000\n#define IO_PA2\n\n#define IFTIM TIM3\n#define IFTIM_XRES 0\n#define IFTIM_ICFL 128\n#define IFTIM_ICMR TIM3_CCMR1\n#define IFTIM_ICM1 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_16_N_8)\n#define IFTIM_ICM2 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8)\n#define IFTIM_ICM3 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_4_N_8)\n#define IFTIM_ICIE TIM_DIER_CC1IE\n#define IFTIM_ICR TIM3_CCR1\n#define IFTIM_OCR TIM3_CCR3\n#define iftim_isr tim3_isr\n\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define IOTIM_DMA 5\n#define iotim_isr tim15_isr\n#define iodma_isr dma1_channel4_7_dma2_channel3_5_isr\n\n#define IOTIM2 TIM16\n#define iotim2_isr tim16_isr\n\n#define USART1_RX_DMA 3\n#define USART1_TX_DMA 2\n#define usart1_tx_dma_isr dma1_channel2_3_dma2_channel1_2_isr\n\n#define USART2_RX_DMA 5\n#define USART2_TX_DMA 4\n\n#define tim1_com_isr tim1_brk_up_trg_com_isr\n"
  },
  {
    "path": "mcu/AT32F421/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 1K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 64K - LENGTH(boot) - LENGTH(cfg)\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 8K\n}\n"
  },
  {
    "path": "mcu/AT32F421/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t400, 407, 414, 421, 428, 435, 442, 449, 456, 463, 469, 476, 483, 490, 497,\n\t504, 510, 517, 524, 530, 537, 543, 550, 556, 563, 569, 575, 582, 588, 594,\n\t600, 606, 612, 618, 624, 629, 635, 641, 646, 652, 657, 662, 668, 673, 678,\n\t683, 688, 693, 697, 702, 706, 711, 715, 719, 724, 728, 732, 735, 739, 743,\n\t746, 750, 753, 756, 760, 763, 765, 768, 771, 773, 776, 778, 780, 783, 785,\n\t786, 788, 790, 791, 793, 794, 795, 796, 797, 798, 798, 799, 799, 800, 800,\n\t800, 800, 800, 799, 799, 798, 798, 797, 796, 795, 794, 793, 791, 790, 788,\n\t786, 785, 783, 780, 778, 776, 773, 771, 768, 765, 763, 760, 756, 753, 750,\n\t746, 743, 739, 735, 732, 728, 724, 719, 715, 711, 706, 702, 697, 693, 688,\n\t683, 678, 673, 668, 662, 657, 652, 646, 641, 635, 629, 624, 618, 612, 606,\n\t600, 594, 588, 582, 575, 569, 563, 556, 550, 543, 537, 530, 524, 517, 510,\n\t504, 497, 490, 483, 476, 469, 463, 456, 449, 442, 435, 428, 421, 414, 407,\n\t400, 393, 386, 379, 372, 365, 358, 351, 344, 337, 331, 324, 317, 310, 303,\n\t296, 290, 283, 276, 270, 263, 257, 250, 244, 237, 231, 225, 218, 212, 206,\n\t200, 194, 188, 182, 176, 171, 165, 159, 154, 148, 143, 138, 132, 127, 122,\n\t117, 112, 107, 103,  98,  94,  89,  85,  81,  76,  72,  68,  65,  61,  57,\n\t 54,  50,  47,  44,  40,  37,  35,  32,  29,  27,  24,  22,  20,  17,  15,\n\t 14,  12,  10,   9,   7,   6,   5,   4,   3,   2,   2,   1,   1,   0,   0,\n\t  0,   0,   0,   1,   1,   2,   2,   3,   4,   5,   6,   7,   9,  10,  12,\n\t 14,  15,  17,  20,  22,  24,  27,  29,  32,  35,  37,  40,  44,  47,  50,\n\t 54,  57,  61,  65,  68,  72,  76,  81,  85,  89,  94,  98, 103, 107, 112,\n\t117, 122, 127, 132, 138, 143, 148, 154, 159, 165, 171, 176, 182, 188, 194,\n\t200, 206, 212, 218, 225, 231, 237, 244, 250, 257, 263, 270, 276, 283, 290,\n\t296, 303, 310, 317, 324, 331, 337, 344, 351, 358, 365, 372, 379, 386, 393,\n};\n"
  },
  {
    "path": "mcu/GD32E230/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/cm3/common.h>\n#include <libopencm3/stm32/f1/adc.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA3 // A3 (volt)\n#define SENS_CHAN 0x3\n#elif SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0x6\n#elif SENS_MAP == 0xA6A3 // A6 (volt), A3 (curr)\n#define SENS_CHAN 0xc3\n#endif\n\n#ifndef ANALOG_CHAN\n#define ANALOG_CHAN 0x2 // ADC_IN2 (A2)\n#endif\n\n#ifndef TEMP_CHAN\n#define TEMP_CHAN 0x10 // ADC_IN16 (temp)\n#define TEMP_FUNC(x) (((1450 - (x)) * 3800 >> 12) + 100)\n#endif\n\n#define ADC1_BASE ADC_BASE\n#define COMP_CSR MMIO32(SYSCFG_COMP_BASE + 0x1c)\n\nstatic char len, ain;\nstatic uint16_t buf[6];\n\nvoid init(void) {\n\tRCC_APB2RSTR = -1;\n\tRCC_APB1RSTR = -1;\n\tRCC_APB2RSTR = 0;\n\tRCC_APB1RSTR = 0;\n\tRCC_AHBENR = RCC_AHBENR_DMAEN | RCC_AHBENR_SRAMEN | RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;\n\tRCC_APB2ENR = RCC_APB2ENR_SYSCFGCOMPEN | RCC_APB2ENR_ADCEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_USART1EN;\n\tRCC_APB1ENR = RCC_APB1ENR_TIM3EN | RCC_APB1ENR_TIM6EN | RCC_APB1ENR_WWDGEN;\n\tSCB_VTOR = (uint32_t)_rom; // Set vector table address\n\n\tRCC_CFGR &= ~RCC_CFGR_SW_PLL;\n\twhile (RCC_CFGR & RCC_CFGR_SWS_PLL);\n\tRCC_CR &= ~RCC_CR_PLLON;\n\twhile (RCC_CR & RCC_CR_PLLRDY);\n\tFLASH_ACR = 0x12; // LATENCY=2WS, PFTEN\n\tRCC_CFGR = 0x8040000; // PLLMUL=10001 (x18)\n\tRCC_CR |= RCC_CR_PLLON;\n\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\tRCC_CFGR |= RCC_CFGR_SW_PLL;\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRL = 0x20000000; // A7 (TIM1_CH1N)\n\tGPIOA_AFRH = 0x00000222; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x00000022; // B0 (TIM1_CH2N), B1 (TIM1_CH3N)\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeabfff; // A7 (TIM1_CH1N), A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffeffa; // B0 (TIM1_CH2N), B1 (TIM1_CH3N), B6 (USART1_TX)\n#ifndef ANALOG\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM15EN;\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM15_IRQ, 0x40);\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x80); // ADC\n\tnvic_set_priority(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ, 0x80); // USART1_TX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ, 0x40); // TIM15 or USART2_RX\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_UP_TRG_COM_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_CC_IRQ);\n\tnvic_enable_irq(NVIC_TIM3_IRQ);\n\tnvic_enable_irq(NVIC_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ);\n\n\tTIM1_DIER = TIM_DIER_CC1IE; // ADC trigger\n\tTIM1_SMCR = TIM_SMCR_TS_ITR2; // TRGI=TIM3\n\tTIM3_CR2 = TIM_CR2_MMS_COMPARE_OC3REF; // TRGO=OC3REF\n\tTIM3_CCMR1 = TIM_CCMR1_CC1S_IN_TI1;\n\tTIM3_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM2; // Inverted PWM on OC3\n\tTIM3_CCER = TIM_CCER_CC1E; // IC1 on rising edge on TI1 (COMP_OUT)\n\n\tRCC_CR2 |= RCC_CR2_HSI14ON; // Enable IRC28M\n\twhile (!(RCC_CR2 & RCC_CR2_HSI14RDY));\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE;\n\tTIM6_ARR = CLK_MHZ - 1;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 1us (RM 10.4.1)\n\tADC1_CR2 |= ADC_CR2_CAL;\n\twhile (ADC1_CR2 & ADC_CR2_CAL);\n\tADC1_CR1 = ADC_CR1_SCAN;\n\tADC1_SMPR1 = -1; // Sampling time ~17us @ IRC28M/2=14Mhz\n\tADC1_SMPR2 = -1;\n\tADC1_SQR3 = SENS_CHAN;\n\tlen = SENS_CNT;\n\tif (IO_ANALOG) {\n\t\tADC1_SQR3 |= ANALOG_CHAN << (len++ * 5);\n\t\tain = 1;\n\t}\n\tADC1_SQR3 |= (TEMP_CHAN | 0x220) << (len * 5); // ADC_IN17 (vref)\n\tlen += 2;\n\tADC1_SQR1 = (len - 1) << ADC_SQR1_L_LSB;\n\tDMA1_CPAR(1) = (uint32_t)&ADC1_DR;\n\tDMA1_CMAR(1) = (uint32_t)buf;\n}\n\nvoid compctl(int x) {\n\tint cr = 0;\n\tswitch (x & 3) {\n\t\tcase COMP_IN1:\n\t\t\tcr = 0x61; // A1>A0\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tcr = 0x41; // A1>A4\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tcr = 0x51; // A1>A5\n\t\t\tbreak;\n\t}\n\tif (x & 4) cr |= 0x800; // Change polarity\n\tCOMP_CSR = cr;\n}\n\nvoid io_serial(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tRCC_APB1ENR |= RCC_APB1ENR_USART2EN;\n\tGPIOA_AFRL |= 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n}\n\nvoid io_analog(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n\nvoid adctrig(void) {\n\tif (DMA1_CCR(1) & DMA_CCR_EN) return;\n\tDMA1_CNDTR(1) = len;\n\tDMA1_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_DMA | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL_SWSTART;\n}\n\nvoid tim1_brk_up_trg_com_isr(void) {\n\tint sr = TIM1_SR;\n\tif (sr & TIM_SR_UIF) {\n\t\tTIM1_SR = ~TIM_SR_UIF;\n\t\tif (TIM1_CCR4) COMP_CSR &= ~0x700; // COMP_OUT off\n\t}\n\tif (sr & TIM_SR_COMIF) tim1_com_isr();\n}\n\nvoid tim1_cc_isr(void) {\n\tint sr = TIM1_SR;\n\tif (sr & TIM_SR_CC4IF) {\n\t\tTIM1_SR = ~TIM_SR_CC4IF;\n\t\tCOMP_CSR |= 0x600; // COMP_OUT=TIM3_IC1\n\t}\n\tif (!(sr & TIM_SR_CC1IF)) return;\n\tTIM1_SR = ~TIM_SR_CC1IF;\n\tif (!(ADC1_CR2 & ADC_CR2_DMA)) return;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_DMA | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL_SWSTART | ADC_CR2_SWSTART;\n}\n\nvoid dma1_channel1_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(1);\n\tDMA1_CCR(1) = 0;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE;\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n\tif (ain) a = buf[i++];\n\tint r = 4914000 / buf[i + 1];\n\tadcdata(TEMP_FUNC(buf[i] * r >> 12), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n"
  },
  {
    "path": "mcu/GD32E230/config.cmake",
    "content": "set(opts -mcpu=cortex-m23 -mthumb)\nset(libs opencm3_stm32f0)\nset(defs STM32F0)\n"
  },
  {
    "path": "mcu/GD32E230/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 72000000\n#define SW_BLANKING\n#define IO_PA2\n\n#define IFTIM TIM3\n#define IFTIM_XRES 0\n#define IFTIM_ICFL 64\n#define IFTIM_ICMR TIM3_CCMR1\n#define IFTIM_ICM1 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8)\n#define IFTIM_ICM2 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_4_N_8)\n#define IFTIM_ICM3 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_2_N_8)\n#define IFTIM_ICIE TIM_DIER_CC1IE\n#define IFTIM_ICR TIM3_CCR1\n#define IFTIM_OCR TIM3_CCR3\n#define iftim_isr tim3_isr\n\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define IOTIM_DMA 5\n#define iotim_isr tim15_isr\n#define iodma_isr dma1_channel4_7_dma2_channel3_5_isr\n\n#define USART1_RX_DMA 3\n#define USART1_TX_DMA 2\n#define usart1_tx_dma_isr dma1_channel2_3_dma2_channel1_2_isr\n\n#define USART2_RX_DMA 5\n#define USART2_TX_DMA 4\n\nvoid tim1_com_isr(void);\n"
  },
  {
    "path": "mcu/GD32E230/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 1K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 64K - LENGTH(boot) - LENGTH(cfg)\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 8K\n}\n"
  },
  {
    "path": "mcu/GD32E230/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t240, 244, 248, 253, 257, 261, 265, 269, 273, 278, 282, 286, 290, 294, 298,\n\t302, 306, 310, 314, 318, 322, 326, 330, 334, 338, 341, 345, 349, 353, 356,\n\t360, 364, 367, 371, 374, 378, 381, 384, 388, 391, 394, 397, 401, 404, 407,\n\t410, 413, 416, 418, 421, 424, 427, 429, 432, 434, 437, 439, 441, 444, 446,\n\t448, 450, 452, 454, 456, 458, 459, 461, 463, 464, 466, 467, 468, 470, 471,\n\t472, 473, 474, 475, 476, 476, 477, 478, 478, 479, 479, 479, 480, 480, 480,\n\t480, 480, 480, 480, 479, 479, 479, 478, 478, 477, 476, 476, 475, 474, 473,\n\t472, 471, 470, 468, 467, 466, 464, 463, 461, 459, 458, 456, 454, 452, 450,\n\t448, 446, 444, 441, 439, 437, 434, 432, 429, 427, 424, 421, 418, 416, 413,\n\t410, 407, 404, 401, 397, 394, 391, 388, 384, 381, 378, 374, 371, 367, 364,\n\t360, 356, 353, 349, 345, 341, 338, 334, 330, 326, 322, 318, 314, 310, 306,\n\t302, 298, 294, 290, 286, 282, 278, 273, 269, 265, 261, 257, 253, 248, 244,\n\t240, 236, 232, 227, 223, 219, 215, 211, 207, 202, 198, 194, 190, 186, 182,\n\t178, 174, 170, 166, 162, 158, 154, 150, 146, 142, 139, 135, 131, 127, 124,\n\t120, 116, 113, 109, 106, 102,  99,  96,  92,  89,  86,  83,  79,  76,  73,\n\t 70,  67,  64,  62,  59,  56,  53,  51,  48,  46,  43,  41,  39,  36,  34,\n\t 32,  30,  28,  26,  24,  22,  21,  19,  17,  16,  14,  13,  12,  10,   9,\n\t  8,   7,   6,   5,   4,   4,   3,   2,   2,   1,   1,   1,   0,   0,   0,\n\t  0,   0,   0,   0,   1,   1,   1,   2,   2,   3,   4,   4,   5,   6,   7,\n\t  8,   9,  10,  12,  13,  14,  16,  17,  19,  21,  22,  24,  26,  28,  30,\n\t 32,  34,  36,  39,  41,  43,  46,  48,  51,  53,  56,  59,  62,  64,  67,\n\t 70,  73,  76,  79,  83,  86,  89,  92,  96,  99, 102, 106, 109, 113, 116,\n\t120, 124, 127, 131, 135, 139, 142, 146, 150, 154, 158, 162, 166, 170, 174,\n\t178, 182, 186, 190, 194, 198, 202, 207, 211, 215, 219, 223, 227, 232, 236,\n};\n"
  },
  {
    "path": "mcu/GD32F350/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/cm3/common.h>\n#include <libopencm3/stm32/f1/adc.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA3 // A3 (volt)\n#define SENS_CHAN 0x3\n#elif SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0x6\n#elif SENS_MAP == 0xA6A0 // A6 (volt), A0 (curr)\n#define SENS_CHAN 0xc0\n#elif SENS_MAP == 0xA6A3 // A6 (volt), A3 (curr)\n#define SENS_CHAN 0xc3\n#endif\n\n#ifndef ANALOG_CHAN\n#define ANALOG_CHAN 0x2 // ADC_IN2 (A2)\n#endif\n\n#ifndef TEMP_CHAN\n#define TEMP_CHAN 0x10 // ADC_IN16 (temp)\n#define TEMP_FUNC(x) (((1440 - (x)) * 2000 >> 11) + 100)\n#endif\n\n#define ADC1_BASE ADC_BASE\n#define COMP_CSR MMIO32(SYSCFG_COMP_BASE + 0x1c)\n#ifdef USE_COMP2\n#define COMP_SHIFT 16\n#else\n#define COMP_SHIFT 0\n#endif\n\nstatic char len, ain;\nstatic uint16_t buf[6];\n\nvoid init(void) {\n\tRCC_APB2RSTR = -1;\n\tRCC_APB1RSTR = -1;\n\tRCC_APB2RSTR = 0;\n\tRCC_APB1RSTR = 0;\n\tRCC_AHBENR = RCC_AHBENR_DMAEN | RCC_AHBENR_SRAMEN | RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;\n\tRCC_APB2ENR = RCC_APB2ENR_SYSCFGCOMPEN | RCC_APB2ENR_ADCEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_USART1EN;\n\tRCC_APB1ENR = RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM6EN | RCC_APB1ENR_WWDGEN;\n\tSCB_VTOR = (uint32_t)_rom; // Set vector table address\n\n\tRCC_CFGR &= ~RCC_CFGR_SW_PLL;\n\twhile (RCC_CFGR & RCC_CFGR_SWS_PLL);\n\tRCC_CR &= ~RCC_CR_PLLON;\n\twhile (RCC_CR & RCC_CR_PLLRDY);\n\tRCC_CFGR = 0x8240000; // PLLMUL=11001 (x26)\n\tRCC_CR |= RCC_CR_PLLON;\n\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\tRCC_CFGR |= RCC_CFGR_SW_PLL;\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRL = 0x20000000; // A7 (TIM1_CH1N)\n\tGPIOA_AFRH = 0x00000222; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x00000022; // B0 (TIM1_CH2N), B1 (TIM1_CH3N)\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeabfff; // A7 (TIM1_CH1N), A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffeffa; // B0 (TIM1_CH2N), B1 (TIM1_CH3N), B6 (USART1_TX)\n#ifdef HALL_MAP\n\tRCC_APB1ENR |= RCC_APB1ENR_TIM3EN;\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n#endif\n#ifndef ANALOG\n#ifdef IO_PA2\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM15EN;\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM15_IRQ, 0x40);\n#else\n\tRCC_APB1ENR |= RCC_APB1ENR_TIM3EN;\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_PUPDR |= 0x100; // B4 (pull-up)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n\tnvic_set_priority(NVIC_TIM3_IRQ, 0x40);\n#endif\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x80); // ADC\n\tnvic_set_priority(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ, 0x80); // USART1_TX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ, 0x40); // TIM3 or TIM15 or USART2_RX\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_UP_TRG_COM_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_CC_IRQ);\n\tnvic_enable_irq(NVIC_TIM2_IRQ);\n\tnvic_enable_irq(NVIC_TIM3_IRQ);\n\tnvic_enable_irq(NVIC_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ);\n\n\tTIM1_DIER = TIM_DIER_CC1IE; // ADC trigger\n\tTIM1_SMCR = TIM_SMCR_TS_ITR1; // TRGI=TIM2\n\tTIM2_CR2 = TIM_CR2_MMS_COMPARE_OC1REF; // TRGO=OC1REF\n\tTIM2_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2; // Inverted PWM on OC1\n\tTIM2_CCMR2 = TIM_CCMR2_CC4S_IN_TI4;\n\tTIM2_CCER = TIM_CCER_CC4E; // IC4 on rising edge on TI4 (COMP_OUT)\n\n\tRCC_CR2 |= RCC_CR2_HSI14ON; // Enable IRC28M\n\twhile (!(RCC_CR2 & RCC_CR2_HSI14RDY));\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE;\n\tTIM6_ARR = CLK_MHZ - 1;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 1us (RM 11.4.1)\n\tADC1_CR2 |= ADC_CR2_CAL;\n\twhile (ADC1_CR2 & ADC_CR2_CAL);\n\tADC1_CR1 = ADC_CR1_SCAN;\n\tADC1_SMPR1 = -1; // Sampling time ~17us @ IRC28M/2=14Mhz\n\tADC1_SMPR2 = -1;\n\tADC1_SQR3 = SENS_CHAN;\n\tlen = SENS_CNT;\n\tif (IO_ANALOG) {\n\t\tADC1_SQR3 |= ANALOG_CHAN << (len++ * 5);\n\t\tain = 1;\n\t}\n\tADC1_SQR3 |= (TEMP_CHAN | 0x220) << (len * 5); // ADC_IN17 (vref)\n\tlen += 2;\n\tADC1_SQR1 = (len - 1) << ADC_SQR1_L_LSB;\n\tDMA1_CPAR(1) = (uint32_t)&ADC1_DR;\n\tDMA1_CMAR(1) = (uint32_t)buf;\n}\n\nvoid compctl(int x) {\n\tint cr = 0;\n\tswitch (x & 3) {\n\t\tcase COMP_IN1:\n\t\t\tcr = 0x61; // A1>A0\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tcr = 0x41; // A1>A4\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tcr = 0x51; // A1>A5\n\t\t\tbreak;\n\t}\n\tif (x & 4) cr |= 0x800; // Change polarity\n\tCOMP_CSR = cr << COMP_SHIFT;\n}\n\nvoid io_serial(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tRCC_APB1ENR |= RCC_APB1ENR_USART2EN;\n\tGPIOA_AFRL |= 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n}\n\nvoid io_analog(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n\nvoid adctrig(void) {\n\tif (DMA1_CCR(1) & DMA_CCR_EN) return;\n\tDMA1_CNDTR(1) = len;\n\tDMA1_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_DMA | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL_SWSTART;\n}\n\nvoid tim1_brk_up_trg_com_isr(void) {\n\tint sr = TIM1_SR;\n\tif (sr & TIM_SR_UIF) {\n\t\tTIM1_SR = ~TIM_SR_UIF;\n\t\tif (TIM1_CCR4) COMP_CSR &= ~(0x700 << COMP_SHIFT); // COMP_OUT off\n\t}\n\tif (sr & TIM_SR_COMIF) tim1_com_isr();\n}\n\nvoid tim1_cc_isr(void) {\n\tint sr = TIM1_SR;\n\tif (sr & TIM_SR_CC4IF) {\n\t\tTIM1_SR = ~TIM_SR_CC4IF;\n\t\tCOMP_CSR |= 0x400 << COMP_SHIFT; // COMP_OUT=TIM2_IC4\n\t}\n\tif (!(sr & TIM_SR_CC1IF)) return;\n\tTIM1_SR = ~TIM_SR_CC1IF;\n\tif (!(ADC1_CR2 & ADC_CR2_DMA)) return;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_DMA | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL_SWSTART | ADC_CR2_SWSTART;\n}\n\nvoid dma1_channel1_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(1);\n\tDMA1_CCR(1) = 0;\n\tADC1_CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE;\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n\tif (ain) a = buf[i++];\n\tint r = 4914000 / buf[i + 1];\n\tadcdata(TEMP_FUNC(buf[i] * r >> 12), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n"
  },
  {
    "path": "mcu/GD32F350/config.cmake",
    "content": "set(opts -mcpu=cortex-m4 -mthumb)\nset(libs opencm3_stm32f0)\nset(defs STM32F0)\n"
  },
  {
    "path": "mcu/GD32F350/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 104000000\n#define SW_BLANKING\n\n#define IFTIM TIM2\n#define IFTIM_XRES 2\n#define IFTIM_ICFL 128\n#define IFTIM_ICMR TIM2_CCMR2\n#define IFTIM_ICM1 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_16_N_8)\n#define IFTIM_ICM2 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_8_N_8)\n#define IFTIM_ICM3 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_4_N_8)\n#define IFTIM_ICIE TIM_DIER_CC4IE\n#define IFTIM_ICR TIM2_CCR4\n#define IFTIM_OCR TIM2_CCR1\n#define iftim_isr tim2_isr\n\n#ifdef IO_PA2\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define IOTIM_DMA 5\n#define iotim_isr tim15_isr\n#else\n#define IOTIM TIM3\n#define IOTIM_IDR (GPIOB_IDR & 0x10) // B4\n#define IOTIM_DMA 4\n#define iotim_isr tim3_isr\n#endif\n#define iodma_isr dma1_channel4_7_dma2_channel3_5_isr\n\n#define USART1_RX_DMA 3\n#define USART1_TX_DMA 2\n#define usart1_tx_dma_isr dma1_channel2_3_dma2_channel1_2_isr\n\n#define USART2_RX_DMA 5\n#define USART2_TX_DMA 4\n\nvoid tim1_com_isr(void);\n"
  },
  {
    "path": "mcu/GD32F350/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 1K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 64K - LENGTH(boot) - LENGTH(cfg)\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 8K\n}\n"
  },
  {
    "path": "mcu/GD32F350/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t347, 353, 359, 365, 371, 377, 383, 389, 395, 401, 407, 413, 419, 424, 430,\n\t436, 442, 448, 454, 459, 465, 471, 476, 482, 487, 493, 498, 504, 509, 514,\n\t520, 525, 530, 535, 540, 545, 550, 555, 560, 565, 569, 574, 578, 583, 587,\n\t592, 596, 600, 604, 608, 612, 616, 620, 623, 627, 630, 634, 637, 640, 644,\n\t647, 650, 652, 655, 658, 661, 663, 665, 668, 670, 672, 674, 676, 678, 680,\n\t681, 683, 684, 685, 687, 688, 689, 690, 690, 691, 692, 692, 693, 693, 693,\n\t693, 693, 693, 693, 692, 692, 691, 690, 690, 689, 688, 687, 685, 684, 683,\n\t681, 680, 678, 676, 674, 672, 670, 668, 665, 663, 661, 658, 655, 652, 650,\n\t647, 644, 640, 637, 634, 630, 627, 623, 620, 616, 612, 608, 604, 600, 596,\n\t592, 587, 583, 578, 574, 569, 565, 560, 555, 550, 545, 540, 535, 530, 525,\n\t520, 514, 509, 504, 498, 493, 487, 482, 476, 471, 465, 459, 454, 448, 442,\n\t436, 430, 424, 419, 413, 407, 401, 395, 389, 383, 377, 371, 365, 359, 353,\n\t347, 340, 334, 328, 322, 316, 310, 304, 298, 292, 286, 280, 274, 269, 263,\n\t257, 251, 245, 239, 234, 228, 222, 217, 211, 206, 200, 195, 189, 184, 179,\n\t173, 168, 163, 158, 153, 148, 143, 138, 133, 128, 124, 119, 115, 110, 106,\n\t101,  97,  93,  89,  85,  81,  77,  73,  70,  66,  63,  59,  56,  53,  49,\n\t 46,  43,  41,  38,  35,  32,  30,  28,  25,  23,  21,  19,  17,  15,  13,\n\t 12,  10,   9,   8,   6,   5,   4,   3,   3,   2,   1,   1,   0,   0,   0,\n\t  0,   0,   0,   0,   1,   1,   2,   3,   3,   4,   5,   6,   8,   9,  10,\n\t 12,  13,  15,  17,  19,  21,  23,  25,  28,  30,  32,  35,  38,  41,  43,\n\t 46,  49,  53,  56,  59,  63,  66,  70,  73,  77,  81,  85,  89,  93,  97,\n\t101, 106, 110, 115, 119, 124, 128, 133, 138, 143, 148, 153, 158, 163, 168,\n\t173, 179, 184, 189, 195, 200, 206, 211, 217, 222, 228, 234, 239, 245, 251,\n\t257, 263, 269, 274, 280, 286, 292, 298, 304, 310, 316, 322, 328, 334, 340,\n};\n"
  },
  {
    "path": "mcu/STM32F051/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/stm32/adc.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA3 // A3 (volt)\n#define SENS_CHAN 0x8\n#elif SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0x40\n#elif SENS_MAP == 0xA3A6 // A3 (volt), A6 (curr)\n#define SENS_CHAN 0x48\n#define SENS_SWAP\n#elif SENS_MAP == 0xA6A3 // A6 (volt), A3 (curr)\n#define SENS_CHAN 0x48\n#endif\n\n#ifndef ANALOG_CHAN\n#define ANALOG_CHAN 0x2 // ADC_IN2 (A2)\n#endif\n\n#ifdef TEMP_CHAN\n#define TEMP_SHIFT 12\n#else\n#define TEMP_SHIFT 0\n#define TEMP_CHAN 0x10000 // ADC_IN16 (temp)\n#define TEMP_FUNC(x) (((x) / 3300 - ST_TSENSE_CAL1_30C) * 320 / (ST_TSENSE_CAL2_110C - ST_TSENSE_CAL1_30C) + 120)\n#endif\n\n#define COMP_CSR MMIO32(SYSCFG_COMP_BASE + 0x1c)\n#ifdef USE_COMP2\n#define COMP_SHIFT 16\n#else\n#define COMP_SHIFT 0\n#endif\n\nstatic char len, ain;\nstatic uint16_t buf[6];\n\nvoid init(void) {\n\tRCC_APB2RSTR = -1;\n\tRCC_APB1RSTR = -1;\n\tRCC_APB2RSTR = 0;\n\tRCC_APB1RSTR = 0;\n\tRCC_AHBENR = RCC_AHBENR_DMAEN | RCC_AHBENR_SRAMEN | RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;\n\tRCC_APB2ENR = RCC_APB2ENR_SYSCFGCOMPEN | RCC_APB2ENR_ADCEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_USART1EN;\n\tRCC_APB1ENR = RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM6EN | RCC_APB1ENR_WWDGEN;\n\tSYSCFG_CFGR1 = SYSCFG_CFGR1_MEM_MODE_SRAM; // Map SRAM at 0x00000000\n\tmemcpy(_vec, _rom, _ram - _vec); // Copy vector table to SRAM\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRL = 0x20000000; // A7 (TIM1_CH1N)\n\tGPIOA_AFRH = 0x00000222; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x00000022; // B0 (TIM1_CH2N), B1 (TIM1_CH3N)\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeabfff; // A7 (TIM1_CH1N), A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffeffa; // B0 (TIM1_CH2N), B1 (TIM1_CH3N), B6 (USART1_TX)\n#ifdef HALL_MAP\n\tRCC_APB1ENR |= RCC_APB1ENR_TIM3EN;\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n#endif\n#ifndef ANALOG\n#ifdef IO_PA2\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM15EN;\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM15_IRQ, 0x40);\n#else\n\tRCC_APB1ENR |= RCC_APB1ENR_TIM3EN;\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_PUPDR |= 0x100; // B4 (pull-up)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n\tnvic_set_priority(NVIC_TIM3_IRQ, 0x40);\n#endif\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x80); // ADC\n\tnvic_set_priority(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ, 0x80); // USART1_TX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ, 0x40); // TIM3 or TIM15 or USART2_RX\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_UP_TRG_COM_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_CC_IRQ);\n\tnvic_enable_irq(NVIC_TIM2_IRQ);\n\tnvic_enable_irq(NVIC_TIM3_IRQ);\n\tnvic_enable_irq(NVIC_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL2_3_DMA2_CHANNEL1_2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL4_7_DMA2_CHANNEL3_5_IRQ);\n\n\tTIM1_SMCR = TIM_SMCR_TS_ITR1; // TRGI=TIM2\n\tTIM2_CR2 = TIM_CR2_MMS_COMPARE_OC1REF; // TRGO=OC1REF\n\tTIM2_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2; // Inverted PWM on OC1\n\tTIM2_CCMR2 = TIM_CCMR2_CC4S_IN_TI4;\n\tTIM2_CCER = TIM_CCER_CC4E; // IC4 on rising edge on TI4 (COMP_OUT)\n\n\tADC1_CR = ADC_CR_ADCAL;\n\twhile (ADC1_CR & ADC_CR_ADCAL);\n\twhile (ADC1_CR = ADC_CR_ADEN, !(ADC1_ISR & ADC_ISR_ADRDY)); // Keep powering on until ready (Errata 2.5.3)\n\tADC1_CFGR1 = ADC_CFGR1_DMAEN | ADC_CFGR1_EXTEN_RISING_EDGE;\n\tADC1_SMPR = ADC_SMPR_SMP_239DOT5; // Sampling time ~17us @ HSI14\n\tADC1_CCR = ADC_CCR_VREFEN | ADC_CCR_TSEN;\n\tADC1_CHSELR = SENS_CHAN | TEMP_CHAN | 0x20000; // ADC_IN17 (vref)\n\tlen = SENS_CNT + 2;\n\tif (IO_ANALOG) {\n\t\tADC1_CHSELR |= 1 << ANALOG_CHAN;\n\t\t++len;\n\t\tain = 1;\n\t}\n\tDMA1_CPAR(1) = (uint32_t)&ADC1_DR;\n\tDMA1_CMAR(1) = (uint32_t)buf;\n}\n\nvoid compctl(int x) {\n\tint cr = 0;\n\tswitch (x & 3) {\n\t\tcase COMP_IN1:\n\t\t\tcr = 0x61; // A1>A0\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tcr = 0x41; // A1>A4\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tcr = 0x51; // A1>A5\n\t\t\tbreak;\n\t}\n\tif (x & 4) cr |= 0x800; // Change polarity\n\tCOMP_CSR = cr << COMP_SHIFT;\n}\n\nvoid io_serial(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tRCC_APB1ENR |= RCC_APB1ENR_USART2EN;\n\tGPIOA_AFRL |= 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n}\n\nvoid io_analog(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n\nvoid adctrig(void) {\n\tif (DMA1_CCR(1) & DMA_CCR_EN) return;\n\tDMA1_CNDTR(1) = len;\n\tDMA1_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC1_CR = ADC_CR_ADSTART;\n}\n\nvoid tim1_brk_up_trg_com_isr(void) {\n\tint sr = TIM1_SR;\n\tif (sr & TIM_SR_UIF) {\n\t\tTIM1_SR = ~TIM_SR_UIF;\n\t\tif (TIM1_CCR4) COMP_CSR &= ~(0x700 << COMP_SHIFT); // COMP_OUT off\n\t}\n\tif (sr & TIM_SR_COMIF) tim1_com_isr();\n}\n\nvoid tim1_cc_isr(void) {\n\tTIM1_SR = ~TIM_SR_CC4IF;\n\tCOMP_CSR |= 0x400 << COMP_SHIFT; // COMP_OUT=TIM2_IC4\n}\n\nvoid dma1_channel1_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(1);\n\tDMA1_CCR(1) = 0;\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#ifndef ANALOG_LAST\n\tif (ain) a = buf[i++];\n#endif\n#ifdef SENS_SWAP\n\tv = buf[i++];\n\tc = buf[i++];\n#else\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n#ifdef ANALOG_LAST\n\tif (ain) a = buf[i++];\n#endif\n\tint r = ST_VREFINT_CAL * 3300 / buf[i + 1];\n\tadcdata(TEMP_FUNC(buf[i] * r >> TEMP_SHIFT), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n"
  },
  {
    "path": "mcu/STM32F051/config.cmake",
    "content": "set(opts -mcpu=cortex-m0 -mthumb)\nset(libs opencm3_stm32f0)\nset(defs STM32F0)\n"
  },
  {
    "path": "mcu/STM32F051/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 48000000\n#define SW_BLANKING\n\n#define IFTIM TIM2\n#define IFTIM_XRES 2\n#define IFTIM_ICFL 64\n#define IFTIM_ICMR TIM2_CCMR2\n#define IFTIM_ICM1 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_8_N_8)\n#define IFTIM_ICM2 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_4_N_8)\n#define IFTIM_ICM3 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_2_N_8)\n#define IFTIM_ICIE TIM_DIER_CC4IE\n#define IFTIM_ICR TIM2_CCR4\n#define IFTIM_OCR TIM2_CCR1\n#define iftim_isr tim2_isr\n\n#ifdef IO_PA2\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define IOTIM_DMA 5\n#define iotim_isr tim15_isr\n#else\n#define IOTIM TIM3\n#define IOTIM_IDR (GPIOB_IDR & 0x10) // B4\n#define IOTIM_DMA 4\n#define iotim_isr tim3_isr\n#endif\n#define iodma_isr dma1_channel4_7_dma2_channel3_5_isr\n\n#define USART1_RX_DMA 3\n#define USART1_TX_DMA 2\n#define usart1_tx_dma_isr dma1_channel2_3_dma2_channel1_2_isr\n\n#define USART2_RX_DMA 5\n#define USART2_TX_DMA 4\n\nvoid tim1_com_isr(void);\n"
  },
  {
    "path": "mcu/STM32F051/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 1K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 32K - LENGTH(boot) - LENGTH(cfg)\n\tvec (rx) : ORIGIN = 0x20000000, LENGTH = 192\n\tram (rwx) : ORIGIN = ORIGIN(vec) + LENGTH(vec), LENGTH = 8K - LENGTH(vec)\n}\n\n_vec = ORIGIN(vec);\n"
  },
  {
    "path": "mcu/STM32F051/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t160, 163, 166, 168, 171, 174, 177, 179, 182, 185, 188, 191, 193, 196, 199,\n\t201, 204, 207, 209, 212, 215, 217, 220, 223, 225, 228, 230, 233, 235, 238,\n\t240, 242, 245, 247, 249, 252, 254, 256, 259, 261, 263, 265, 267, 269, 271,\n\t273, 275, 277, 279, 281, 283, 284, 286, 288, 289, 291, 293, 294, 296, 297,\n\t299, 300, 301, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314,\n\t315, 315, 316, 317, 317, 318, 318, 318, 319, 319, 319, 320, 320, 320, 320,\n\t320, 320, 320, 320, 320, 319, 319, 319, 318, 318, 318, 317, 317, 316, 315,\n\t315, 314, 313, 312, 311, 310, 309, 308, 307, 306, 305, 304, 303, 301, 300,\n\t299, 297, 296, 294, 293, 291, 289, 288, 286, 284, 283, 281, 279, 277, 275,\n\t273, 271, 269, 267, 265, 263, 261, 259, 256, 254, 252, 249, 247, 245, 242,\n\t240, 238, 235, 233, 230, 228, 225, 223, 220, 217, 215, 212, 209, 207, 204,\n\t201, 199, 196, 193, 191, 188, 185, 182, 179, 177, 174, 171, 168, 166, 163,\n\t160, 157, 154, 152, 149, 146, 143, 141, 138, 135, 132, 129, 127, 124, 121,\n\t119, 116, 113, 111, 108, 105, 103, 100,  97,  95,  92,  90,  87,  85,  82,\n\t 80,  78,  75,  73,  71,  68,  66,  64,  61,  59,  57,  55,  53,  51,  49,\n\t 47,  45,  43,  41,  39,  37,  36,  34,  32,  31,  29,  27,  26,  24,  23,\n\t 21,  20,  19,  17,  16,  15,  14,  13,  12,  11,  10,   9,   8,   7,   6,\n\t  5,   5,   4,   3,   3,   2,   2,   2,   1,   1,   1,   0,   0,   0,   0,\n\t  0,   0,   0,   0,   0,   1,   1,   1,   2,   2,   2,   3,   3,   4,   5,\n\t  5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,  19,  20,\n\t 21,  23,  24,  26,  27,  29,  31,  32,  34,  36,  37,  39,  41,  43,  45,\n\t 47,  49,  51,  53,  55,  57,  59,  61,  64,  66,  68,  71,  73,  75,  78,\n\t 80,  82,  85,  87,  90,  92,  95,  97, 100, 103, 105, 108, 111, 113, 116,\n\t119, 121, 124, 127, 129, 132, 135, 138, 141, 143, 146, 149, 152, 154, 157,\n};\n"
  },
  {
    "path": "mcu/STM32G071/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/stm32/dmamux.h>\n#include <libopencm3/stm32/adc.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA0 // A0 (volt)\n#define SENS_CHAN 0x0\n#elif SENS_MAP == 0xA5 // A5 (volt)\n#define SENS_CHAN 0x5\n#elif SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0x6\n#elif SENS_MAP == 0xA1A5 // A1 (volt), A5 (curr)\n#define SENS_CHAN 0x15\n#elif SENS_MAP == 0xA5A4 // A5 (volt), A4 (curr)\n#define SENS_CHAN 0x54\n#elif SENS_MAP == 0xA6A4 // A6 (volt), A4 (curr)\n#define SENS_CHAN 0x64\n#elif SENS_MAP == 0xA6A5A4 // A6 (temp), A5 (volt), A4 (curr)\n#define SENS_CHAN 0x654\n#endif\n\n#ifndef ANALOG_CHAN\n#ifdef IO_PA6\n#define ANALOG_CHAN 0x6 // ADC_IN6 (A6)\n#else\n#define ANALOG_CHAN 0x2 // ADC_IN2 (A2)\n#endif\n#endif\n\n#ifdef TEMP_CHAN\n#define TEMP_SHIFT 12\n#else\n#define TEMP_SHIFT 0\n#define TEMP_CHAN 0xc // ADC_IN12 (temp)\n#define TEMP_FUNC(x) (((x) / 3000 - ST_TSENSE_CAL1_30C) * 400 / (ST_TSENSE_CAL2_130C - ST_TSENSE_CAL1_30C) + 120)\n#endif\n\n#define COMP1_CSR MMIO32(COMP_BASE + 0x0)\n#define COMP2_CSR MMIO32(COMP_BASE + 0x4)\n\nstatic char len, ain;\nstatic uint16_t buf[6];\n#ifdef LED_WS2812\nstatic uint16_t led[5];\n#endif\n\nvoid init(void) {\n\tRCC_AHBRSTR = -1;\n\tRCC_APBRSTR1 = -1;\n\tRCC_APBRSTR2 = -1;\n\tRCC_AHBRSTR = 0;\n\tRCC_APBRSTR1 = 0;\n\tRCC_APBRSTR2 = 0;\n\tRCC_IOPENR = 0x27; // GPIOAEN=1, GPIOBEN=1, GPIOCEN=1, GPIOFEN=1\n\tRCC_AHBENR = RCC_AHBENR_DMAEN | RCC_AHBENR_FLASHEN;\n\tRCC_APBENR1 = RCC_APBENR1_TIM2EN | RCC_APBENR1_TIM6EN | RCC_APBENR1_WWDGEN;\n\tRCC_APBENR2 = RCC_APBENR2_SYSCFGEN | RCC_APBENR2_TIM1EN | RCC_APBENR2_USART1EN | RCC_APBENR2_ADCEN;\n\tSYSCFG_CFGR1 = SYSCFG_CFGR1_PA11_RMP | SYSCFG_CFGR1_PA12_RMP | SYSCFG_CFGR1_UCPD1_STROBE; // A11->A9, A12->A10, disable internal pull-downs on A8/B15\n\tSCB_VTOR = (uint32_t)_rom; // Set vector table address\n\n#ifdef USE_HSE\n\tif (!cfg.throt_cal) {\n\t\tTIM6_PSC = CLK_MHZ - 1; // 1us resolution\n\t\tTIM6_ARR = 9999;\n\t\tTIM6_EGR = TIM_EGR_UG;\n\t\tTIM6_SR = ~TIM_SR_UIF;\n\t\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\t\tRCC_CR |= RCC_CR_HSEON;\n\t\twhile (!(RCC_CR & RCC_CR_HSERDY)) {\n\t\t\tif (!(TIM6_CR1 & TIM_CR1_CEN)) { // Timeout 10ms\n\t\t\t\tRCC_CR &= ~RCC_CR_HSEON;\n\t\t\t\tgoto skip;\n\t\t\t}\n\t\t}\n\t\tRCC_CFGR = RCC_CFGR_SW_HSE;\n\t\twhile ((RCC_CFGR & RCC_CFGR_SWS_MASK << RCC_CFGR_SWS_SHIFT) != RCC_CFGR_SWS_HSE << RCC_CFGR_SWS_SHIFT);\n\t\tRCC_CR &= ~RCC_CR_PLLON;\n\t\twhile (RCC_CR & RCC_CR_PLLRDY);\n\t\tRCC_PLLCFGR = RCC_PLLCFGR_PLLSRC_HSE | (128 / USE_HSE) << RCC_PLLCFGR_PLLN_SHIFT | RCC_PLLCFGR_PLLREN | 1 << RCC_PLLCFGR_PLLR_SHIFT;\n\t\tRCC_CR |= RCC_CR_PLLON;\n\t\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\t\tRCC_CFGR = RCC_CFGR_SW_PLLRCLK;\n\t}\nskip:\n#endif\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRL = 0x20000000; // A7 (TIM1_CH1N)\n\tGPIOA_AFRH = 0x00000222; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x00000002; // B0 (TIM1_CH2N)\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeabfff; // A7 (TIM1_CH1N), A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffeffe; // B0 (TIM1_CH2N), B6 (USART1_TX)\n#ifdef IO_PA6 // N version\n\tGPIOB_AFRH |= 0x20000000; // B15 (TIM1_CH3N)\n\tGPIOB_MODER &= ~0x40000000; // B15 (TIM1_CH3N)\n#else\n\tGPIOB_AFRL |= 0x20; // B1 (TIM1_CH3N)\n\tGPIOB_MODER &= ~0x4; // B1 (TIM1_CH3N)\n#endif\n#ifdef HALL_MAP\n\tRCC_APBENR1 |= RCC_APBENR1_TIM3EN;\n\tGPIOC_AFRL |= 0x1000000; // C6 (TIM3_CH1)\n\tGPIOC_MODER &= ~0x1000; // C6 (TIM3_CH1)\n#endif\n#ifndef ANALOG\n#ifdef IO_PA2\n\tRCC_APBENR2 |= RCC_APBENR2_TIM15EN;\n\tGPIOA_AFRL |= 0x500; // A2 (TIM15_CH1)\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM15_IRQ, 0x40);\n#else\n\tRCC_APBENR1 |= RCC_APBENR1_TIM3EN;\n#ifdef IO_PA6\n\tGPIOA_AFRL |= 0x1000000; // A6 (TIM3_CH1)\n\tGPIOA_PUPDR |= 0x1000; // A6 (pull-up)\n\tGPIOA_MODER &= ~0x1000; // A6 (TIM3_CH1)\n#else\n\tGPIOB_AFRL |= 0x10000; // B4 (TIM3_CH1)\n\tGPIOB_PUPDR |= 0x100; // B4 (pull-up)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n#endif\n\tnvic_set_priority(NVIC_TIM34_IRQ, 0x40);\n#endif\n#ifndef IO_AUX\n#elif IO_AUX == 0xB8\n\tRCC_APBENR2 |= RCC_APBENR2_TIM16EN;\n\tGPIOB_AFRH |= 0x2; // B8 (TIM16_CH1)\n\tGPIOB_PUPDR |= 0x10000; // B8 (pull-up)\n\tGPIOB_MODER &= ~0x10000; // B8 (TIM16_CH1)\n\tnvic_set_priority(NVIC_TIM16_FDCAN_IT0_IRQ, 0x40);\n#elif IO_AUX == 0xB9\n\tRCC_APBENR2 |= RCC_APBENR2_TIM17EN;\n\tGPIOB_AFRH |= 0x20; // B9 (TIM17_CH1)\n\tGPIOB_PUPDR |= 0x40000; // B9 (pull-up)\n\tGPIOB_MODER &= ~0x40000; // B9 (TIM17_CH1)\n\tnvic_set_priority(NVIC_TIM17_FDCAN_IT1_IRQ, 0x40);\n#else\n\tRCC_APBENR1 |= RCC_APBENR1_TIM3EN;\n\tGPIOC_AFRL |= 0x1000000; // C6 (TIM3_CH1)\n\tGPIOC_PUPDR |= 0x1000; // C6 (pull-up)\n\tGPIOC_MODER &= ~0x1000; // C6 (TIM3_CH1)\n\tnvic_set_priority(NVIC_TIM34_IRQ, 0x40);\n#endif\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_LPUART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x40); // TIM3 or TIM15 or USART2_RX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL2_3_IRQ, 0x80); // USART1_TX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL4_7_DMAMUX_IRQ, 0x80); // ADC, WS2812\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_UP_TRG_COM_IRQ);\n\tnvic_enable_irq(NVIC_TIM2_IRQ);\n\tnvic_enable_irq(NVIC_TIM34_IRQ);\n\tnvic_enable_irq(NVIC_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_TIM16_FDCAN_IT0_IRQ);\n\tnvic_enable_irq(NVIC_TIM17_FDCAN_IT1_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_LPUART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL2_3_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL4_7_DMAMUX_IRQ);\n\n#ifdef IO_PA2\n\tDMAMUX1_CxCR(1) = DMAMUX_CxCR_DMAREQ_ID_TIM15_CH1;\n#else\n\tDMAMUX1_CxCR(1) = DMAMUX_CxCR_DMAREQ_ID_TIM3_CH1;\n#endif\n\tDMAMUX1_CxCR(2) = DMAMUX_CxCR_DMAREQ_ID_USART1_RX;\n\tDMAMUX1_CxCR(3) = DMAMUX_CxCR_DMAREQ_ID_USART1_TX;\n\tDMAMUX1_CxCR(4) = DMAMUX_CxCR_DMAREQ_ID_ADC;\n\n\tTIM1_SMCR = TIM_SMCR_TS_ITR1; // TRGI=TIM2\n\tTIM2_CR2 = TIM_CR2_MMS_COMPARE_OC3REF; // TRGO=OC3REF\n\tTIM2_CCMR1 = TIM_CCMR1_CC2S_IN_TI2;\n\tTIM2_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM2; // Inverted PWM on OC3\n\tTIM2_CCER = TIM_CCER_CC2E; // IC2 on rising edge on TI2 (COMP2_OUT)\n#if defined IO_PA2 || defined IO_PA6\n\tTIM2_CCMR1 |= TIM_CCMR1_CC1S_IN_TI1;\n\tTIM2_CCER |= TIM_CCER_CC1E; // IC1 on rising edge on TI1 (COMP1_OUT)\n#endif\n\n\tADC_CFGR2(ADC1) = ADC_CFGR2_LFTRIG | ADC_CFGR2_CKMODE_PCLK_DIV4 << ADC_CFGR2_CKMODE_SHIFT;\n\tADC_CCR(ADC1) = ADC_CCR_VREFEN | ADC_CCR_TSEN;\n\tADC_CR(ADC1) = ADC_CR_ADVREGEN;\n\tTIM6_PSC = 0;\n\tTIM6_ARR = CLK_KHZ / 50 - 1;\n\tTIM6_EGR = TIM_EGR_UG;\n\tTIM6_SR = ~TIM_SR_UIF;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 20us (RM 15.3.2)\n\tADC_CR(ADC1) = ADC_CR_ADVREGEN | ADC_CR_ADCAL;\n\twhile (ADC_CR(ADC1) & ADC_CR_ADCAL);\n\tADC_CR(ADC1) = ADC_CR_ADEN | ADC_CR_ADVREGEN;\n\twhile (!(ADC_ISR(ADC1) & ADC_ISR_ADRDY));\n\tADC_CFGR1(ADC1) = ADC_CFGR1_DMAEN | ADC_CFGR1_EXTEN_RISING_EDGE | ADC_CFGR1_CHSELRMOD;\n\tADC_SMPR1(ADC1) = ADC_SMPR_SMPx_160DOT5CYC; // Sampling time ~10us @ PCLK/4=16Mhz\n\tADC_CHSELR(ADC1) = SENS_CHAN;\n\tlen = SENS_CNT;\n\tif (IO_ANALOG) {\n\t\tADC_CHSELR(ADC1) |= ANALOG_CHAN << (len++ << 2);\n\t\tain = 1;\n\t}\n\tADC_CHSELR(ADC1) |= (TEMP_CHAN | 0xfd0) << (len << 2); // ADC_IN13 (vref)\n\tlen += 2;\n\twhile (!(ADC_ISR(ADC1) & ADC_ISR_CCRDY));\n\tDMA1_CPAR(4) = (uint32_t)&ADC_DR(ADC1);\n\tDMA1_CMAR(4) = (uint32_t)buf;\n}\n\n#ifdef LED_WS2812\nvoid initled(void) {\n\tRCC_APBENR2 |= RCC_APBENR2_TIM16EN;\n\tGPIOB_AFRH |= 0x2; // B8 (TIM16_CH1)\n\tGPIOB_MODER &= ~0x10000; // B8 (TIM16_CH1)\n\tTIM16_BDTR = TIM_BDTR_MOE;\n\tTIM16_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1;\n\tTIM16_CCER = TIM_CCER_CC1E;\n\tTIM16_CR2 = TIM_CR2_CCDS; // CC1 DMA request on UEV\n\tTIM16_ARR = CLK_CNT(800000) - 1;\n\tTIM16_RCR = 7;\n\tDMAMUX1_CxCR(6) = DMAMUX_CxCR_DMAREQ_ID_TIM16_CH1;\n\tDMA1_CPAR(6) = (uint32_t)&TIM16_CCR1;\n\tDMA1_CMAR(6) = (uint32_t)led;\n}\n\nvoid ledctl(int x) {\n\tif (DMA1_CCR(6) & DMA_CCR_EN) return;\n\tled[0] = x & 2 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Green\n\tled[1] = x & 1 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Red\n\tled[2] = x & 4 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Blue\n\tled[3] = 0;\n\tled[4] = 0;\n\tDMA1_CNDTR(6) = 5;\n\tDMA1_CCR(6) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tTIM16_DIER = TIM_DIER_CC1DE;\n\tTIM16_EGR = TIM_EGR_UG;\n\tTIM16_CR1 = TIM_CR1_CEN;\n}\n#endif\n\nvoid hsictl(int x) {\n\tint cr = RCC_ICSCR;\n\tint tv = (cr & 0x7f00) >> 8; // 7 bits\n\tRCC_ICSCR = (cr & ~0x7f00) | clamp(tv + x, 0, 0x7f) << 8;\n}\n\nvoid compctl(int x) {\n\tint id = 0;\n\tint cr = 0;\n\tswitch (x & 3) {\n#ifdef IO_PA2\n\t\tcase COMP_IN1:\n\t\t\tid = 1;\n\t\t\tcr = 0x108281; // A0>A1\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tid = 2;\n\t\t\tcr = 0x108271; // B7>A3\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tid = 2;\n\t\t\tcr = 0x108071; // B7>B4\n\t\t\tbreak;\n#else\n\t\tcase COMP_IN1:\n\t\t\tid = 2;\n\t\t\tcr = 0x100281; // A3>A2\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n#ifdef IO_PA6 // N version\n\t\t\tid = 1;\n\t\t\tcr = 0x100281; // A1>A0\n#else\n\t\t\tid = 2;\n\t\t\tcr = 0x100261; // A3>B3\n#endif\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tid = 2;\n\t\t\tcr = 0x100271; // A3>B7\n\t\t\tbreak;\n#endif\n\t}\n\tif (x & 4) cr ^= 0x8000; // Change polarity\n\tswitch (id) {\n\t\tcase 0:\n\t\t\tCOMP1_CSR = 0;\n\t\t\tCOMP2_CSR = 0;\n\t\t\tTIM2_TISEL = 0;\n\t\t\tbreak;\n#if defined IO_PA2 || defined IO_PA6\n\t\tcase 1:\n\t\t\tCOMP1_CSR = cr;\n\t\t\tTIM2_TISEL = 0x1; // TI1=COMP1_OUT\n\t\t\tbreak;\n#endif\n\t\tcase 2:\n\t\t\tCOMP2_CSR = cr;\n\t\t\tTIM2_TISEL = 0x100; // TI2=COMP2_OUT\n\t\t\tbreak;\n\t}\n}\n\nvoid io_serial(void) {\n\tRCC_APBRSTR2 = RCC_APBRSTR2_TIM15RST;\n\tRCC_APBRSTR2 = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tRCC_APBENR1 |= RCC_APBENR1_USART2EN;\n\tGPIOA_AFRL = (GPIOA_AFRL & ~0xf00) | 0x100; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x10000000; // A15 (USART2_RX)\n#endif\n\tDMAMUX1_CxCR(1) = DMAMUX_CxCR_DMAREQ_ID_USART2_RX;\n\tDMAMUX1_CxCR(5) = DMAMUX_CxCR_DMAREQ_ID_USART2_TX;\n}\n\n#ifdef IO_PA6\nvoid io_analog(void) {\n\tRCC_APBRSTR1 = RCC_APBRSTR1_TIM3RST;\n\tRCC_APBRSTR1 = 0;\n\tnvic_clear_pending_irq(NVIC_TIM34_IRQ);\n\tGPIOA_PUPDR &= ~0x3000; // A6 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x3000; // A6 (analog)\n}\n#else\nvoid io_analog(void) {\n\tRCC_APBRSTR2 = RCC_APBRSTR2_TIM15RST;\n\tRCC_APBRSTR2 = 0;\n\tnvic_clear_pending_irq(NVIC_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n#endif\n\nvoid adctrig(void) {\n\tif (DMA1_CCR(4) & DMA_CCR_EN) return;\n\tDMA1_CNDTR(4) = len;\n\tDMA1_CCR(4) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC_CR(ADC1) = ADC_CR_ADSTART | ADC_CR_ADVREGEN;\n}\n\nvoid dma1_channel4_7_dmamux_isr(void) {\n#ifdef LED_WS2812\n\tif (DMA1_ISR & DMA_ISR_TCIF(6)) {\n\t\tDMA1_IFCR = DMA_IFCR_CTCIF(6);\n\t\tDMA1_CCR(6) = 0;\n\t\tTIM16_DIER = 0;\n\t\tTIM16_CR1 = 0;\n\t\treturn;\n\t}\n#endif\n\tDMA1_IFCR = DMA_IFCR_CTCIF(4);\n\tDMA1_CCR(4) = 0;\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n\tif (ain) a = buf[i++];\n\tint r = ST_VREFINT_CAL * 3000 / buf[i + 1];\n\tadcdata(TEMP_FUNC(buf[i] * r >> TEMP_SHIFT), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n"
  },
  {
    "path": "mcu/STM32G071/config.cmake",
    "content": "set(opts -mcpu=cortex-m0plus -mthumb)\nset(libs opencm3_stm32g0)\nset(defs STM32G0)\n"
  },
  {
    "path": "mcu/STM32G071/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 64000000\n\n#define IFTIM TIM2\n#define IFTIM_XRES 2\n#define IFTIM_ICFL 64\n#define IFTIM_ICMR TIM2_CCMR1\n#if defined IO_PA2 || defined IO_PA6\n#define IFTIM_ICM1 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8 | TIM_CCMR1_CC2S_IN_TI2 | TIM_CCMR1_IC2F_DTF_DIV_8_N_8)\n#define IFTIM_ICM2 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_4_N_8 | TIM_CCMR1_CC2S_IN_TI2 | TIM_CCMR1_IC2F_DTF_DIV_4_N_8)\n#define IFTIM_ICM3 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_2_N_8 | TIM_CCMR1_CC2S_IN_TI2 | TIM_CCMR1_IC2F_DTF_DIV_2_N_8)\n#define IFTIM_ICIE (TIM_DIER_CC1IE | TIM_DIER_CC2IE)\n#define IFTIM_ICR (sr & TIM_SR_CC1IF ? TIM2_CCR1 : TIM2_CCR2)\n#else\n#define IFTIM_ICM1 (TIM_CCMR1_CC2S_IN_TI2 | TIM_CCMR1_IC2F_DTF_DIV_8_N_8)\n#define IFTIM_ICM2 (TIM_CCMR1_CC2S_IN_TI2 | TIM_CCMR1_IC2F_DTF_DIV_4_N_8)\n#define IFTIM_ICM3 (TIM_CCMR1_CC2S_IN_TI2 | TIM_CCMR1_IC2F_DTF_DIV_2_N_8)\n#define IFTIM_ICIE TIM_DIER_CC2IE\n#define IFTIM_ICR TIM2_CCR2\n#endif\n#define IFTIM_OCR TIM2_CCR3\n#define iftim_isr tim2_isr\n\n#ifdef IO_PA2\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define iotim_isr tim15_isr\n#else\n#define IOTIM TIM3\n#ifdef IO_PA6\n#define IOTIM_IDR (GPIOA_IDR & 0x40) // A6\n#else\n#define IOTIM_IDR (GPIOB_IDR & 0x10) // B4\n#endif\n#define iotim_isr tim3_isr\n#endif\n#define IOTIM_DMA 1\n#define iodma_isr dma1_channel1_isr\n\n#ifndef IO_AUX\n#elif IO_AUX == 0xB8\n#define IOTIM2 TIM16\n#define iotim2_isr tim16_fdcan_it0_isr\n#elif IO_AUX == 0xB9\n#define IOTIM2 TIM17\n#define iotim2_isr tim17_fdcan_it1_isr\n#else\n#define IOTIM2 TIM3\n#define iotim2_isr tim34_isr\n#endif\n\n#define USART1_RX_DMA 2\n#define USART1_TX_DMA 3\n#define usart1_tx_dma_isr dma1_channel2_3_isr\n\n#define USART2_RX_DMA 1\n#define USART2_TX_DMA 5\n#define usart2_isr usart2_lpuart2_isr\n\n#define tim1_com_isr tim1_brk_up_trg_com_isr\n#define tim3_isr tim34_isr\n"
  },
  {
    "path": "mcu/STM32G071/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 2K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 64K - LENGTH(boot) - LENGTH(cfg)\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 8K\n}\n"
  },
  {
    "path": "mcu/STM32G071/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t213, 217, 220, 224, 228, 232, 235, 239, 243, 246, 250, 254, 257, 261, 265,\n\t268, 272, 275, 279, 282, 286, 289, 293, 296, 300, 303, 306, 310, 313, 316,\n\t320, 323, 326, 329, 332, 335, 338, 341, 344, 347, 350, 353, 356, 358, 361,\n\t364, 366, 369, 371, 374, 376, 379, 381, 383, 385, 387, 390, 392, 394, 396,\n\t397, 399, 401, 403, 404, 406, 408, 409, 410, 412, 413, 414, 416, 417, 418,\n\t419, 420, 421, 421, 422, 423, 423, 424, 424, 425, 425, 425, 426, 426, 426,\n\t426, 426, 426, 426, 425, 425, 425, 424, 424, 423, 423, 422, 421, 421, 420,\n\t419, 418, 417, 416, 414, 413, 412, 410, 409, 408, 406, 404, 403, 401, 399,\n\t397, 396, 394, 392, 390, 387, 385, 383, 381, 379, 376, 374, 371, 369, 366,\n\t364, 361, 358, 356, 353, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323,\n\t320, 316, 313, 310, 306, 303, 300, 296, 293, 289, 286, 282, 279, 275, 272,\n\t268, 265, 261, 257, 254, 250, 246, 243, 239, 235, 232, 228, 224, 220, 217,\n\t213, 209, 206, 202, 198, 194, 191, 187, 183, 180, 176, 172, 169, 165, 161,\n\t158, 154, 151, 147, 144, 140, 137, 133, 130, 126, 123, 120, 116, 113, 110,\n\t106, 103, 100,  97,  94,  91,  88,  85,  82,  79,  76,  73,  70,  68,  65,\n\t 62,  60,  57,  55,  52,  50,  47,  45,  43,  41,  39,  36,  34,  32,  30,\n\t 29,  27,  25,  23,  22,  20,  18,  17,  16,  14,  13,  12,  10,   9,   8,\n\t  7,   6,   5,   5,   4,   3,   3,   2,   2,   1,   1,   1,   0,   0,   0,\n\t  0,   0,   0,   0,   1,   1,   1,   2,   2,   3,   3,   4,   5,   5,   6,\n\t  7,   8,   9,  10,  12,  13,  14,  16,  17,  18,  20,  22,  23,  25,  27,\n\t 29,  30,  32,  34,  36,  39,  41,  43,  45,  47,  50,  52,  55,  57,  60,\n\t 62,  65,  68,  70,  73,  76,  79,  82,  85,  88,  91,  94,  97, 100, 103,\n\t106, 110, 113, 116, 120, 123, 126, 130, 133, 137, 140, 144, 147, 151, 154,\n\t158, 161, 165, 169, 172, 176, 180, 183, 187, 191, 194, 198, 202, 206, 209,\n};\n"
  },
  {
    "path": "mcu/STM32G431/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/stm32/dmamux.h>\n#include <libopencm3/stm32/adc.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0x3\n#elif SENS_MAP == 0xA6F1 // A6 (volt), F1 (curr)\n#define SENS_CHAN 0xca\n#elif SENS_MAP == 0xBFA6 // B15 (volt), A6 (curr)\n#define SENS_CHAN 0x3c3\n#elif SENS_MAP == 0xB2A6A7 // B2 (temp), A6 (volt), A7 (curr)\n#define SENS_CHAN 0xc0c4\n#endif\n\n#ifdef TEMP_CHAN\n#define TEMP_SHIFT 12\n#else\n#define TEMP_SHIFT 0\n#define TEMP_CHAN 0x10 // ADC1_IN16 (temp)\n#define TEMP_FUNC(x) (((x) / 3000 - ST_TSENSE_CAL1_30C) * 400 / (ST_TSENSE_CAL2_130C - ST_TSENSE_CAL1_30C) + 120)\n#endif\n\n#define COMP1_CSR MMIO32(COMP_BASE + 0x0)\n#define COMP2_CSR MMIO32(COMP_BASE + 0x4)\n#define TIM1_CCMR3 MMIO32(TIM1_BASE + 0x50)\n#define TIM2_TISEL MMIO32(TIM2_BASE + 0x5c)\n\nstatic char len1, len2, ain;\nstatic uint16_t buf[6];\n#ifdef LED_WS2812\nstatic uint16_t led[5];\n#endif\n\nvoid init(void) {\n\tRCC_AHB1RSTR = -1;\n\tRCC_AHB2RSTR = -1;\n\tRCC_AHB3RSTR = -1;\n\tRCC_APB1RSTR1 = -1;\n\tRCC_APB1RSTR2 = -1;\n\tRCC_APB2RSTR = -1;\n\tRCC_AHB1RSTR = 0;\n\tRCC_AHB2RSTR = 0;\n\tRCC_AHB3RSTR = 0;\n\tRCC_APB1RSTR1 = 0;\n\tRCC_APB1RSTR2 = 0;\n\tRCC_APB2RSTR = 0;\n\tRCC_AHB1ENR = RCC_AHB1ENR_DMA1EN | RCC_AHB1ENR_DMA2EN | RCC_AHB1ENR_DMAMUX1EN | RCC_AHB1ENR_FLASHEN;\n\tRCC_AHB2ENR = RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN | RCC_AHB2ENR_GPIOCEN | RCC_AHB2ENR_GPIOFEN | RCC_AHB2ENR_ADC12EN;\n\tRCC_APB1ENR1 = RCC_APB1ENR1_TIM2EN | RCC_APB1ENR1_TIM6EN | RCC_APB1ENR1_WWDGEN | RCC_APB1ENR1_PWREN;\n\tRCC_APB2ENR = RCC_APB2ENR_SYSCFGEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_USART1EN;\n\tPWR_CR3 = PWR_CR3_UCPD1_DBDIS; // Disable internal pull-downs on B4/B6\n\tSCB_VTOR = (uint32_t)_rom; // Set vector table address\n\n\tRCC_CFGR = RCC_CFGR_SWx_HSI16;\n\twhile ((RCC_CFGR & RCC_CFGR_SWS_MASK << RCC_CFGR_SWS_SHIFT) != RCC_CFGR_SWx_HSI16 << RCC_CFGR_SWS_SHIFT);\n\tRCC_CR &= ~RCC_CR_PLLON;\n\twhile (RCC_CR & RCC_CR_PLLRDY);\n#ifdef USE_HSE\n\tif (!cfg.throt_cal) {\n\t\tTIM6_PSC = 15; // 1us resolution @ HSI16\n\t\tTIM6_ARR = 9999;\n\t\tTIM6_EGR = TIM_EGR_UG;\n\t\tTIM6_SR = ~TIM_SR_UIF;\n\t\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\t\tRCC_CR |= RCC_CR_HSEON;\n\t\twhile (!(RCC_CR & RCC_CR_HSERDY)) {\n\t\t\tif (!(TIM6_CR1 & TIM_CR1_CEN)) { // Timeout 10ms\n\t\t\t\tRCC_CR &= ~RCC_CR_HSEON;\n\t\t\t\tgoto skip;\n\t\t\t}\n\t\t}\n\t\tRCC_PLLCFGR = RCC_PLLCFGR_PLLSRC_HSE | (336 / USE_HSE) << RCC_PLLCFGR_PLLN_SHIFT | RCC_PLLCFGR_PLLREN;\n\t} else\nskip:\n#endif\n\tRCC_PLLCFGR = RCC_PLLCFGR_PLLSRC_HSI16 | 21 << RCC_PLLCFGR_PLLN_SHIFT | RCC_PLLCFGR_PLLREN;\n\tRCC_CR |= RCC_CR_PLLON;\n\twhile (!(RCC_CR & RCC_CR_PLLRDY));\n\tRCC_CFGR = RCC_CFGR_SWx_PLL | RCC_CFGR_HPRE_DIV2 << RCC_CFGR_HPRE_SHIFT;\n\tPWR_CR5 = 0; // R1MODE=0 (boost mode)\n\tTIM6_PSC = 0;\n\tTIM6_ARR = CLK_MHZ / 2 - 1;\n\tTIM6_EGR = TIM_EGR_UG;\n\tTIM6_SR = ~TIM_SR_UIF;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Ensure 1us HCLK/2 transition period (RM 7.2.7)\n\tRCC_CFGR = RCC_CFGR_SWx_PLL;\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRH = 0x00000666; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x07000000; // B6 (USART1_TX)\n\tGPIOA_PUPDR = 0x24000000;\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeaffff; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffefff; // B6 (USART1_TX)\n#ifdef USE_XOR\n\tGPIOB_AFRH |= 0x46600000; // B13 (TIM1_CH1N), B14 (TIM1_CH2N), B15 (TIM1_CH3N)\n\tGPIOB_MODER &= ~0x54000000; // B13 (TIM1_CH1N), B14 (TIM1_CH2N), B15 (TIM1_CH3N)\n#else\n\tGPIOA_AFRL |= 0x60000000; // A7 (TIM1_CH1N)\n\tGPIOB_AFRL |= 0x6; // B0 (TIM1_CH2N)\n\tGPIOA_MODER &= ~0x4000; // A7 (TIM1_CH1N)\n\tGPIOB_MODER &= ~0x1; // B0 (TIM1_CH2N)\n#ifdef USE_PB1\n\tGPIOB_AFRL |= 0x60; // B1 (TIM1_CH3N)\n\tGPIOB_MODER &= ~0x4; // B1 (TIM1_CH3N)\n#else\n\tGPIOF_AFRL |= 0x6; // F0 (TIM1_CH3N)\n\tGPIOF_MODER &= ~0x1; // F0 (TIM1_CH3N)\n#endif\n#endif\n#ifdef HALL_MAP\n\tRCC_APB1ENR1 |= RCC_APB1ENR1_TIM3EN;\n#ifdef USE_XOR\n\tGPIOB_AFRL |= 0x220002; // B0 (TIM3_CH3), B4 (TIM3_CH1), B5 (TIM3_CH2)\n\tGPIOB_PUPDR |= 0x501; // B0,B4,B5 (pull-up)\n\tGPIOB_MODER &= ~0x501; // B0 (TIM3_CH3), B4 (TIM3_CH1), B5 (TIM3_CH2)\n#else\n\tGPIOB_AFRL |= 0x20000; // B4 (TIM3_CH1)\n\tGPIOB_MODER &= ~0x100; // B4 (TIM3_CH1)\n#endif\n#endif\n#ifndef ANALOG\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM15EN;\n\tGPIOA_AFRL |= 0x900; // A2 (TIM15_CH1)\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM1_BRK_TIM15_IRQ, 0x40);\n#ifdef IO_AUX\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM8EN;\n\tGPIOA_AFRH |= 0x20000000; // A15 (TIM8_CH1)\n\tGPIOA_PUPDR |= 0x40000000; // A15 (pull-up)\n\tGPIOA_MODER &= ~0x40000000; // A15 (TIM8_CH1)\n\tnvic_set_priority(NVIC_TIM8_CC_IRQ, 0x40);\n#endif\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x40); // TIM15 or USART2_RX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL3_IRQ, 0x80); // USART1_TX\n\tnvic_set_priority(NVIC_DMA1_CHANNEL4_IRQ, 0x80); // ADC1\n\tnvic_set_priority(NVIC_DMA1_CHANNEL5_IRQ, 0x80); // ADC2\n\tnvic_set_priority(NVIC_DMA2_CHANNEL1_IRQ, 0x80); // WS2812\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_TRG_TIM17_IRQ);\n\tnvic_enable_irq(NVIC_TIM2_IRQ);\n\tnvic_enable_irq(NVIC_TIM3_IRQ);\n\tnvic_enable_irq(NVIC_TIM8_CC_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL3_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL4_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL5_IRQ);\n\tnvic_enable_irq(NVIC_DMA2_CHANNEL1_IRQ);\n\n\tDMAMUX1_CxCR(1) = DMAMUX_CxCR_DMAREQ_ID_TIM15_CH1;\n\tDMAMUX1_CxCR(2) = DMAMUX_CxCR_DMAREQ_ID_UART1_RX;\n\tDMAMUX1_CxCR(3) = DMAMUX_CxCR_DMAREQ_ID_UART1_TX;\n\tDMAMUX1_CxCR(4) = DMAMUX_CxCR_DMAREQ_ID_ADC1;\n\tDMAMUX1_CxCR(5) = DMAMUX_CxCR_DMAREQ_ID_ADC2;\n\n\tTIM1_CCMR3 = 0x68; // OC5PE=1, OC5M=PWM1\n\tTIM1_SMCR = TIM_SMCR_TS_ITR1; // TRGI=TIM2\n\tTIM2_CR2 = TIM_CR2_MMS_COMPARE_OC3REF; // TRGO=OC3REF\n\tTIM2_CCMR1 = TIM_CCMR1_CC1S_IN_TI1;\n\tTIM2_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM2; // Inverted PWM on OC3\n\tTIM2_CCER = TIM_CCER_CC1E; // IC1 on rising edge on TI1 (COMPx_OUT)\n\n\tADC_CCR(ADC1) = ADC_CCR_VREFEN | ADC_CCR_TSEN | ADC_CCR_CKMODE_DIV4;\n\tADC_CR(ADC1) = 0; // DEEPPWD=0\n\tADC_CR(ADC2) = 0; // DEEPPWD=0\n\tADC_CR(ADC1) = ADC_CR_ADVREGEN;\n\tADC_CR(ADC2) = ADC_CR_ADVREGEN;\n\tTIM6_ARR = CLK_KHZ / 50 - 1;\n\tTIM6_SR = ~TIM_SR_UIF;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 20us (RM 21.4.6)\n\tADC_CR(ADC1) = ADC_CR_ADVREGEN | ADC_CR_ADCAL;\n\tADC_CR(ADC2) = ADC_CR_ADVREGEN | ADC_CR_ADCAL;\n\twhile (ADC_CR(ADC1) & ADC_CR_ADCAL);\n\twhile (ADC_CR(ADC2) & ADC_CR_ADCAL);\n\twhile (ADC_CR(ADC1) = ADC_CR_ADEN | ADC_CR_ADVREGEN, !(ADC_ISR(ADC1) & ADC_ISR_ADRDY)); // Keep powering on until ready (RM 21.4.9)\n\twhile (ADC_CR(ADC2) = ADC_CR_ADEN | ADC_CR_ADVREGEN, !(ADC_ISR(ADC2) & ADC_ISR_ADRDY));\n\tADC_CFGR1(ADC1) = ADC_CFGR1_DMAEN | ADC12_CFGR1_EXTSEL_TIM1_TRGO | ADC_CFGR1_EXTEN_RISING_EDGE;\n\tADC_CFGR1(ADC2) = ADC_CFGR1_DMAEN | ADC12_CFGR1_EXTSEL_TIM1_TRGO | ADC_CFGR1_EXTEN_RISING_EDGE;\n\tADC_SMPR1(ADC1) = -1; // Sampling time ~15us @ HCLK/4=42Mhz\n\tADC_SMPR1(ADC2) = -1;\n\tADC_SMPR2(ADC1) = -1;\n\tADC_SMPR2(ADC2) = -1;\n\tuint64_t seq1 = 0;\n\tuint64_t seq2 = SENS_CHAN;\n\tlen1 = 0;\n\tlen2 = SENS_CNT;\n\tif (IO_ANALOG) {\n#ifdef ANALOG_CHAN\n#ifdef ANALOG_ADC2\n\t\tseq2 |= ANALOG_CHAN << (len2++ * 6);\n#else\n\t\tseq1 = ANALOG_CHAN;\n\t\tlen1 = 1;\n#endif\n#else\n\t\tseq1 = 0x3; // ADC1_IN3 (A2)\n\t\tlen1 = 1;\n#endif\n\t\tain = 1;\n\t}\n#ifdef TEMP_ADC2\n\tseq2 |= TEMP_CHAN << (len2++ * 6);\n#else\n\tseq1 |= TEMP_CHAN << (len1++ * 6);\n#endif\n\tseq1 |= 0x12 << (len1++ * 6); // ADC1_IN18 (vref)\n\tADC_SQR1(ADC1) = seq1 << 6 | (len1 - 1);\n\tADC_SQR1(ADC2) = seq2 << 6 | (len2 - 1);\n\tADC_SQR2(ADC1) = seq1 >> 24;\n\tADC_SQR2(ADC2) = seq2 >> 24;\n\tDMA1_CPAR(4) = (uint32_t)&ADC_DR(ADC1);\n\tDMA1_CMAR(4) = (uint32_t)(buf + len2);\n\tDMA1_CPAR(5) = (uint32_t)&ADC_DR(ADC2);\n\tDMA1_CMAR(5) = (uint32_t)buf;\n}\n\n#ifdef LED_WS2812\nvoid initled(void) {\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM16EN;\n\tGPIOB_AFRH |= 0x1; // B8 (TIM16_CH1)\n\tGPIOB_MODER &= ~0x10000; // B8 (TIM16_CH1)\n\tTIM16_BDTR = TIM_BDTR_MOE;\n\tTIM16_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1;\n\tTIM16_CCER = TIM_CCER_CC1E;\n\tTIM16_CR2 = TIM_CR2_CCDS; // CC1 DMA request on UEV\n\tTIM16_ARR = CLK_CNT(800000) - 1;\n\tTIM16_RCR = 7;\n\tDMAMUX1_CxCR(9) = DMAMUX_CxCR_DMAREQ_ID_TIM16_CH1;\n\tDMA2_CPAR(1) = (uint32_t)&TIM16_CCR1;\n\tDMA2_CMAR(1) = (uint32_t)led;\n}\n\nvoid ledctl(int x) {\n\tif (DMA2_CCR(1) & DMA_CCR_EN) return;\n\tled[0] = x & 2 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Green\n\tled[1] = x & 1 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Red\n\tled[2] = x & 4 ? CLK_CNT(1250000) : CLK_CNT(2500000); // Blue\n\tled[3] = 0;\n\tled[4] = 0;\n\tDMA2_CNDTR(1) = 5;\n\tDMA2_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tTIM16_DIER = TIM_DIER_CC1DE;\n\tTIM16_EGR = TIM_EGR_UG;\n\tTIM16_CR1 = TIM_CR1_CEN;\n}\n#endif\n\nvoid hsictl(int x) {\n\tint cr = RCC_ICSCR;\n\tint tv = (cr & 0x7f000000) >> 24; // 7 bits\n\tRCC_ICSCR = (cr & ~0x7f000000) | clamp(tv + x, 0, 0x7f) << 24;\n}\n\nvoid compctl(int x) {\n\tint id = 0;\n\tint cr = 0;\n\tswitch (x & 3) {\n\t\tcase COMP_IN1:\n\t\t\tid = 1;\n\t\t\tcr = 0x80071; // A1>A0\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tid = 1;\n\t\t\tcr = 0x80061; // A1>A4\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tid = 2;\n\t\t\tcr = 0x80161; // A3>A5\n\t\t\tbreak;\n\t}\n\tif (x & 4) cr |= 0x8000; // Change polarity\n\tswitch (id) {\n\t\tcase 0:\n\t\t\tCOMP1_CSR = 0;\n\t\t\tCOMP2_CSR = 0;\n\t\t\tTIM2_TISEL = 0;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tCOMP1_CSR = cr;\n\t\t\tTIM2_TISEL = 0x1; // TI1=COMP1_OUT\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tCOMP2_CSR = cr;\n\t\t\tTIM2_TISEL = 0x2; // TI1=COMP2_OUT\n\t\t\tbreak;\n\t}\n}\n\nvoid io_serial(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM1_BRK_TIM15_IRQ);\n\tRCC_APB1ENR1 |= RCC_APB1ENR1_USART2EN;\n\tGPIOA_AFRL = (GPIOA_AFRL & ~0xf00) | 0x700; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x70000000; // A15 (USART2_RX)\n#endif\n\tDMAMUX1_CxCR(1) = DMAMUX_CxCR_DMAREQ_ID_UART2_RX;\n\tDMAMUX1_CxCR(6) = DMAMUX_CxCR_DMAREQ_ID_UART2_TX;\n}\n\nvoid io_analog(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM1_BRK_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n\nvoid adctrig(void) {\n\tif ((DMA1_CCR(4) & DMA_CCR_EN) || (DMA1_CCR(5) & DMA_CCR_EN)) return;\n\tDMA1_CNDTR(4) = len1;\n\tDMA1_CCR(4) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC_CR(ADC1) = ADC_CR_ADSTART | ADC_CR_ADVREGEN;\n\tif (!len2) return;\n\tDMA1_CNDTR(5) = len2;\n\tDMA1_CCR(5) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC_CR(ADC2) = ADC_CR_ADSTART | ADC_CR_ADVREGEN;\n}\n\nstatic void adcdma(void) {\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n#if !defined ANALOG_ADC2 && defined TEMP_ADC2\n\tint t = buf[i++];\n\tif (ain) a = buf[i++];\n#else\n\tif (ain) a = buf[i++];\n\tint t = buf[i++];\n#endif\n\tint r = ST_VREFINT_CAL * 3000 / buf[i];\n\tadcdata(TEMP_FUNC(t * r >> TEMP_SHIFT), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n\nvoid dma1_channel4_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(4);\n\tDMA1_CCR(4) = 0;\n\tif (DMA1_CCR(5) & DMA_CCR_EN) return;\n\tadcdma();\n}\n\nvoid dma1_channel5_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(5);\n\tDMA1_CCR(5) = 0;\n\tif (DMA1_CCR(4) & DMA_CCR_EN) return;\n\tadcdma();\n}\n\n#ifdef LED_WS2812\nvoid dma2_channel1_isr(void) {\n\tDMA2_IFCR = DMA_IFCR_CTCIF(1);\n\tDMA2_CCR(1) = 0;\n\tTIM16_DIER = 0;\n\tTIM16_CR1 = 0;\n}\n#endif\n"
  },
  {
    "path": "mcu/STM32G431/config.cmake",
    "content": "set(opts -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16)\nset(libs opencm3_stm32g4)\nset(defs STM32G4)\n"
  },
  {
    "path": "mcu/STM32G431/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 168000000\n#define IO_PA2\n\n#define IFTIM TIM2\n#define IFTIM_XRES 2\n#define IFTIM_ICFL 256\n#define IFTIM_ICMR TIM2_CCMR1\n#define IFTIM_ICM1 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_32_N_8)\n#define IFTIM_ICM2 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_16_N_8)\n#define IFTIM_ICM3 (TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8)\n#define IFTIM_ICIE TIM_DIER_CC1IE\n#define IFTIM_ICR TIM2_CCR1\n#define IFTIM_OCR TIM2_CCR3\n#define iftim_isr tim2_isr\n\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define IOTIM_DMA 1\n#define iotim_isr tim1_brk_tim15_isr\n#define iodma_isr dma1_channel1_isr\n\n#define IOTIM2 TIM8\n#define iotim2_isr tim8_cc_isr\n\n#define USART1_RX_DMA 2\n#define USART1_TX_DMA 3\n#define usart1_tx_dma_isr dma1_channel3_isr\n\n#define USART2_RX_DMA 1\n#define USART2_TX_DMA 6\n\n#define tim1_com_isr tim1_trg_tim17_isr\n\n#define TIM1_CCR5 MMIO32(TIM1_BASE + 0x48)\n#define TIM_CCER_CC5E 0x10000\n"
  },
  {
    "path": "mcu/STM32G431/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 2K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 64K - LENGTH(boot) - LENGTH(cfg)\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 8K\n}\n"
  },
  {
    "path": "mcu/STM32G431/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t 560,  570,  580,  589,  599,  609,  619,  628,  638,  648,  657,  667,  676,  686,  695,\n\t 705,  714,  724,  733,  742,  752,  761,  770,  779,  788,  797,  805,  814,  823,  831,\n\t 840,  848,  857,  865,  873,  881,  889,  897,  905,  912,  920,  927,  935,  942,  949,\n\t 956,  963,  970,  976,  983,  989,  995, 1001, 1007, 1013, 1019, 1024, 1030, 1035, 1040,\n\t1045, 1050, 1054, 1059, 1063, 1068, 1072, 1075, 1079, 1083, 1086, 1089, 1093, 1096, 1098,\n\t1101, 1103, 1106, 1108, 1110, 1111, 1113, 1115, 1116, 1117, 1118, 1119, 1119, 1120, 1120,\n\t1120, 1120, 1120, 1119, 1119, 1118, 1117, 1116, 1115, 1113, 1111, 1110, 1108, 1106, 1103,\n\t1101, 1098, 1096, 1093, 1089, 1086, 1083, 1079, 1075, 1072, 1068, 1063, 1059, 1054, 1050,\n\t1045, 1040, 1035, 1030, 1024, 1019, 1013, 1007, 1001,  995,  989,  983,  976,  970,  963,\n\t 956,  949,  942,  935,  927,  920,  912,  905,  897,  889,  881,  873,  865,  857,  848,\n\t 840,  831,  823,  814,  805,  797,  788,  779,  770,  761,  752,  742,  733,  724,  714,\n\t 705,  695,  686,  676,  667,  657,  648,  638,  628,  619,  609,  599,  589,  580,  570,\n\t 560,  550,  540,  531,  521,  511,  501,  492,  482,  472,  463,  453,  444,  434,  425,\n\t 415,  406,  396,  387,  378,  368,  359,  350,  341,  332,  323,  315,  306,  297,  289,\n\t 280,  272,  263,  255,  247,  239,  231,  223,  215,  208,  200,  193,  185,  178,  171,\n\t 164,  157,  150,  144,  137,  131,  125,  119,  113,  107,  101,   96,   90,   85,   80,\n\t  75,   70,   66,   61,   57,   52,   48,   45,   41,   37,   34,   31,   27,   24,   22,\n\t  19,   17,   14,   12,   10,    9,    7,    5,    4,    3,    2,    1,    1,    0,    0,\n\t   0,    0,    0,    1,    1,    2,    3,    4,    5,    7,    9,   10,   12,   14,   17,\n\t  19,   22,   24,   27,   31,   34,   37,   41,   45,   48,   52,   57,   61,   66,   70,\n\t  75,   80,   85,   90,   96,  101,  107,  113,  119,  125,  131,  137,  144,  150,  157,\n\t 164,  171,  178,  185,  193,  200,  208,  215,  223,  231,  239,  247,  255,  263,  272,\n\t 280,  289,  297,  306,  315,  323,  332,  341,  350,  359,  368,  378,  387,  396,  406,\n\t 415,  425,  434,  444,  453,  463,  472,  482,  492,  501,  511,  521,  531,  540,  550,\n};\n"
  },
  {
    "path": "mcu/STM32L431/config.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <libopencm3/stm32/adc.h>\n#include <libopencm3/stm32/g4/opamp.h>\n#include \"common.h\"\n\n#if SENS_MAP == 0xA6 // A6 (volt)\n#define SENS_CHAN 0xb\n#elif SENS_MAP == 0xA6A3 // A6 (volt), A3 (curr)\n#define SENS_CHAN 0x2c8\n#endif\n\n#ifndef ANALOG_CHAN\n#define ANALOG_CHAN 0x7 // ADC_IN7 (A2)\n#endif\n\n#ifdef TEMP_CHAN\n#define TEMP_SHIFT 12\n#else\n#define TEMP_SHIFT 0\n#define TEMP_CHAN 0x11 // ADC_IN17 (temp)\n#define TEMP_FUNC(x) (((x) / 3000 - ST_TSENSE_CAL1_30C) * 400 / (ST_TSENSE_CAL2_110C - ST_TSENSE_CAL1_30C) + 120)\n#endif\n\n#ifdef USE_COMP2\n#define COMP_CSR MMIO32(COMP_BASE + 0x4)\n#else\n#define COMP_CSR MMIO32(COMP_BASE + 0x0)\n#define TIM1_CCMR3 MMIO32(TIM1_BASE + 0x54)\n#endif\n#define TIM2_OR1 MMIO32(TIM2_BASE + 0x50)\n\nstatic char len, ain;\nstatic uint16_t buf[6];\n\nvoid init(void) {\n\tRCC_AHB1RSTR = -1;\n\tRCC_AHB2RSTR = -1;\n\tRCC_AHB3RSTR = -1;\n\tRCC_APB1RSTR1 = -1;\n\tRCC_APB1RSTR2 = -1;\n\tRCC_APB2RSTR = -1;\n\tRCC_AHB1RSTR = 0;\n\tRCC_AHB2RSTR = 0;\n\tRCC_AHB3RSTR = 0;\n\tRCC_APB1RSTR1 = 0;\n\tRCC_APB1RSTR2 = 0;\n\tRCC_APB2RSTR = 0;\n\tRCC_AHB1ENR = RCC_AHB1ENR_DMA1EN | RCC_AHB1ENR_DMA2EN | RCC_AHB1ENR_FLASHEN;\n\tRCC_AHB2ENR = RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN | RCC_AHB2ENR_GPIOCEN | RCC_AHB2ENR_ADCEN;\n\tRCC_APB1ENR1 = RCC_APB1ENR1_TIM2EN | RCC_APB1ENR1_TIM6EN | 0x800; // WWDGEN=1\n\tRCC_APB2ENR = RCC_APB2ENR_SYSCFGEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_USART1EN;\n\tSCB_VTOR = (uint32_t)_rom; // Set vector table address\n\n\t// Default GPIO state - analog input\n\tGPIOA_AFRL = 0x10000000; // A7 (TIM1_CH1N)\n\tGPIOA_AFRH = 0x00000111; // A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_AFRL = 0x07000011; // B0 (TIM1_CH2N), B1 (TIM1_CH3N), B6 (USART1_TX)\n\tGPIOA_PUPDR = 0x24000000;\n\tGPIOB_PUPDR = 0x00001000; // B6 (pull-up)\n\tGPIOA_MODER = 0xebeabfff; // A7 (TIM1_CH1N), A8 (TIM1_CH1), A9 (TIM1_CH2), A10 (TIM1_CH3)\n\tGPIOB_MODER = 0xffffeffa; // B0 (TIM1_CH2N), B1 (TIM1_CH3N), B6 (USART1_TX)\n#ifndef ANALOG\n\tRCC_APB2ENR |= RCC_APB2ENR_TIM15EN;\n\tGPIOA_AFRL |= 0xe00; // A2 (TIM15_CH1)\n\tGPIOA_PUPDR |= 0x10; // A2 (pull-up)\n\tGPIOA_MODER &= ~0x10; // A2 (TIM15_CH1)\n\tnvic_set_priority(NVIC_TIM1_BRK_TIM15_IRQ, 0x40);\n#endif\n\tnvic_set_priority(NVIC_USART1_IRQ, 0x80);\n\tnvic_set_priority(NVIC_USART2_IRQ, 0x40);\n\tnvic_set_priority(NVIC_DMA1_CHANNEL1_IRQ, 0x80); // ADC\n\tnvic_set_priority(NVIC_DMA1_CHANNEL5_IRQ, 0x40); // TIM15\n\tnvic_set_priority(NVIC_DMA1_CHANNEL6_IRQ, 0x40); // USART2_RX\n\tnvic_set_priority(NVIC_DMA2_CHANNEL6_IRQ, 0x80); // USART1_TX\n\n\tnvic_enable_irq(NVIC_TIM1_BRK_TIM15_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_UP_TIM16_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_TRG_COM_TIM17_IRQ);\n\tnvic_enable_irq(NVIC_TIM1_CC_IRQ);\n\tnvic_enable_irq(NVIC_TIM2_IRQ);\n\tnvic_enable_irq(NVIC_USART1_IRQ);\n\tnvic_enable_irq(NVIC_USART2_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL1_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL5_IRQ);\n\tnvic_enable_irq(NVIC_DMA1_CHANNEL6_IRQ);\n\tnvic_enable_irq(NVIC_DMA2_CHANNEL6_IRQ);\n\n\tDMA1_CSELR = 0x2270000; // C5S=TIM15, C6S=USART2_RX, C7S=USART2_TX\n\tDMA2_CSELR = 0x2200000; // C6S=USART1_TX, C7S=USART1_RX\n#ifndef USE_COMP2\n\tTIM1_CCMR3 = 0x68; // OC5PE=1, OC5M=PWM1\n\tTIM2_OR1 = 0x4; // TI4=COMP1_OUT\n#elif defined USE_OPAMP\n\tRCC_APB1ENR1 |= RCC_APB1ENR1_OPAMPEN;\n\tOPAMP1_CSR = 0x39; // OPAEN=1, OPAMODE=PGA, PGA_GAIN=16\n#endif\n\tTIM1_SMCR = TIM_SMCR_TS_ITR1; // TRGI=TIM2\n\tTIM2_CR2 = TIM_CR2_MMS_COMPARE_OC1REF; // TRGO=OC1REF\n\tTIM2_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2; // Inverted PWM on OC1\n\tTIM2_CCMR2 = TIM_CCMR2_CC4S_IN_TI4;\n\tTIM2_CCER = TIM_CCER_CC4E; // IC4 on rising edge on TI4 (COMPx_OUT)\n\n\tADC_CCR(ADC1) = ADC_CCR_VREFEN | ADC_CCR_TSEN | 0x20000; // CKMODE=HCLK/2\n\tADC_CR(ADC1) = 0; // DEEPPWD=0\n\tADC_CR(ADC1) = ADC_CR_ADVREGEN;\n\tTIM6_ARR = CLK_KHZ / 50 - 1;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 20us (RM 16.4.6)\n\tADC_CR(ADC1) = ADC_CR_ADVREGEN | ADC_CR_ADCAL;\n\twhile (ADC_CR(ADC1) & ADC_CR_ADCAL);\n\twhile (ADC_CR(ADC1) = ADC_CR_ADEN | ADC_CR_ADVREGEN, !(ADC_ISR(ADC1) & ADC_ISR_ADRDY)); // Keep powering on until ready (RM 16.4.9)\n\tADC_CFGR1(ADC1) = ADC_CFGR1_DMAEN | ADC_CFGR1_EXTSEL_VAL(9) | ADC_CFGR1_EXTEN_RISING_EDGE; // EXTSEL=TIM1_TRGO\n\tADC_SMPR1(ADC1) = -1; // Sampling time ~16us @ HCLK/2=40Mhz\n\tADC_SMPR2(ADC1) = -1;\n\tuint64_t seq = SENS_CHAN;\n\tlen = SENS_CNT;\n\tif (IO_ANALOG) {\n\t\tseq |= ANALOG_CHAN << (len++ * 6);\n\t\tain = 1;\n\t}\n\tseq |= TEMP_CHAN << (len * 6); // ADC_IN0 (vref)\n\tlen += 2;\n\tADC_SQR1(ADC1) = seq << 6 | (len - 1);\n\tADC_SQR2(ADC1) = seq >> 24;\n\tDMA1_CPAR(1) = (uint32_t)&ADC_DR(ADC1);\n\tDMA1_CMAR(1) = (uint32_t)buf;\n}\n\nvoid hsictl(int x) {\n\tint cr = RCC_ICSCR;\n\tint tv = (cr & 0x7f000000) >> 24; // 7 bits\n\tRCC_ICSCR = (cr & ~0x7f000000) | ((tv + x) & 0x7f) << 24;\n}\n\nvoid compctl(int x) {\n\tint cr = 0;\n\tswitch (x & 3) {\n#ifdef USE_COMP2\n\t\tcase COMP_IN1:\n\t\t\tcr = 0x4000071; // B4>A4\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tcr = 0x6000071; // B4>A5\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tcr = 0x71; // B4>B7\n\t\t\tbreak;\n#else\n\t\tcase COMP_IN1:\n\t\t\tcr = 0x2000071; // A1>A0\n\t\t\tbreak;\n\t\tcase COMP_IN2:\n\t\t\tcr = 0x4000071; // A1>A4\n\t\t\tbreak;\n\t\tcase COMP_IN3:\n\t\t\tcr = 0x6000071; // A1>A5\n\t\t\tbreak;\n#endif\n\t}\n\tif (x & 4) cr |= 0x8000; // Change polarity\n\tCOMP_CSR = cr;\n}\n\nvoid io_serial(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM1_BRK_TIM15_IRQ);\n\tRCC_APB1ENR1 |= RCC_APB1ENR1_USART2EN;\n\tGPIOA_AFRL = (GPIOA_AFRL & ~0xf00) | 0x700; // A2 (USART2_TX)\n#ifdef IO_RXTX\n\tGPIOA_AFRH |= 0x30000000; // A15 (USART2_RX)\n#endif\n}\n\nvoid io_analog(void) {\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tnvic_clear_pending_irq(NVIC_TIM1_BRK_TIM15_IRQ);\n\tGPIOA_PUPDR &= ~0x30; // A2 (no pull-up/pull-down)\n\tGPIOA_MODER |= 0x30; // A2 (analog)\n}\n\nvoid adctrig(void) {\n\tif (DMA1_CCR(1) & DMA_CCR_EN) return;\n\tDMA1_CNDTR(1) = len;\n\tDMA1_CCR(1) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tADC_CR(ADC1) = ADC_CR_ADSTART | ADC_CR_ADVREGEN;\n}\n\n#ifdef USE_COMP2\nvoid tim1_up_tim16_isr(void) {\n\tTIM1_SR = ~TIM_SR_UIF;\n\tif (TIM1_CCR4) TIM2_OR1 = 0;\n}\n\nvoid tim1_cc_isr(void) {\n\tTIM1_SR = ~TIM_SR_CC4IF;\n\tTIM2_OR1 = 0x8; // TI4=COMP2_OUT\n}\n#endif\n\nvoid dma1_channel6_isr(void) {\n\tdma1_channel5_isr();\n}\n\nvoid dma1_channel1_isr(void) {\n\tDMA1_IFCR = DMA_IFCR_CTCIF(1);\n\tDMA1_CCR(1) = 0;\n\tint i = 0, u = 0, v = 0, c = 0, a = 0;\n#if SENS_CNT >= 2\n\tc = buf[i++];\n#endif\n#if SENS_CNT >= 1\n\tv = buf[i++];\n#endif\n#if SENS_CNT >= 3\n\tu = buf[i++];\n#endif\n\tif (ain) a = buf[i++];\n\tint r = ST_VREFINT_CAL * 3000 / buf[i + 1];\n\tadcdata(TEMP_FUNC(buf[i] * r >> TEMP_SHIFT), u * r >> 12, v * r >> 12, c * r >> 12, a * r >> 12);\n}\n"
  },
  {
    "path": "mcu/STM32L431/config.cmake",
    "content": "set(opts -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16)\nset(libs opencm3_stm32l4)\nset(defs STM32L4)\n"
  },
  {
    "path": "mcu/STM32L431/config.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#define CLK 80000000\n#define IO_PA2\n\n#define IFTIM TIM2\n#define IFTIM_XRES 2\n#define IFTIM_ICFL 128\n#define IFTIM_ICMR TIM2_CCMR2\n#define IFTIM_ICM1 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_16_N_8)\n#define IFTIM_ICM2 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_8_N_8)\n#define IFTIM_ICM3 (TIM_CCMR2_CC4S_IN_TI4 | TIM_CCMR2_IC4F_DTF_DIV_4_N_8)\n#define IFTIM_ICIE TIM_DIER_CC4IE\n#define IFTIM_ICR TIM2_CCR4\n#define IFTIM_OCR TIM2_CCR1\n#define iftim_isr tim2_isr\n\n#define IOTIM TIM15\n#define IOTIM_IDR (GPIOA_IDR & 0x4) // A2\n#define IOTIM_DMA 5\n#define iotim_isr tim1_brk_tim15_isr\n#define iodma_isr dma1_channel5_isr\n\n#define USART1_DMA_BASE DMA2_BASE\n#define USART1_RX_DMA 7\n#define USART1_TX_DMA 6\n#define usart1_tx_dma_isr dma2_channel6_isr\n\n#define USART2_RX_DMA 6\n#define USART2_TX_DMA 7\n\n#define tim1_com_isr tim1_trg_com_tim17_isr\n\n#ifdef USE_COMP2\n#define SW_BLANKING\n#else\n#define TIM1_CCR5 MMIO32(TIM1_BASE + 0x58)\n#define TIM_CCER_CC5E 0x10000\n#endif\n"
  },
  {
    "path": "mcu/STM32L431/config.ld",
    "content": "MEMORY {\n\tboot (rx) : ORIGIN = 0x8000000, LENGTH = 4K\n\tcfg (rx) : ORIGIN = ORIGIN(boot) + LENGTH(boot), LENGTH = 2K\n\trom (rx) : ORIGIN = ORIGIN(cfg) + LENGTH(cfg), LENGTH = 64K - LENGTH(boot) - LENGTH(cfg)\n\tram (rwx) : ORIGIN = 0x20000000, LENGTH = 8K\n}\n"
  },
  {
    "path": "mcu/STM32L431/preset.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\nconst uint16_t sinedata[] = {\n\t267, 271, 276, 280, 285, 290, 294, 299, 304, 308, 313, 317, 322, 326, 331,\n\t335, 340, 344, 349, 353, 358, 362, 366, 371, 375, 379, 383, 387, 392, 396,\n\t400, 404, 408, 412, 416, 419, 423, 427, 431, 434, 438, 441, 445, 448, 452,\n\t455, 458, 461, 465, 468, 471, 474, 477, 479, 482, 485, 487, 490, 493, 495,\n\t497, 500, 502, 504, 506, 508, 510, 512, 514, 515, 517, 518, 520, 521, 523,\n\t524, 525, 526, 527, 528, 529, 530, 530, 531, 532, 532, 532, 533, 533, 533,\n\t533, 533, 533, 533, 532, 532, 532, 531, 530, 530, 529, 528, 527, 526, 525,\n\t524, 523, 521, 520, 518, 517, 515, 514, 512, 510, 508, 506, 504, 502, 500,\n\t497, 495, 493, 490, 487, 485, 482, 479, 477, 474, 471, 468, 465, 461, 458,\n\t455, 452, 448, 445, 441, 438, 434, 431, 427, 423, 419, 416, 412, 408, 404,\n\t400, 396, 392, 387, 383, 379, 375, 371, 366, 362, 358, 353, 349, 344, 340,\n\t335, 331, 326, 322, 317, 313, 308, 304, 299, 294, 290, 285, 280, 276, 271,\n\t267, 262, 257, 253, 248, 243, 239, 234, 229, 225, 220, 216, 211, 207, 202,\n\t198, 193, 189, 184, 180, 175, 171, 167, 162, 158, 154, 150, 146, 141, 137,\n\t133, 129, 125, 121, 117, 114, 110, 106, 102,  99,  95,  92,  88,  85,  81,\n\t 78,  75,  72,  68,  65,  62,  59,  56,  54,  51,  48,  46,  43,  40,  38,\n\t 36,  33,  31,  29,  27,  25,  23,  21,  19,  18,  16,  15,  13,  12,  10,\n\t  9,   8,   7,   6,   5,   4,   3,   3,   2,   1,   1,   1,   0,   0,   0,\n\t  0,   0,   0,   0,   1,   1,   1,   2,   3,   3,   4,   5,   6,   7,   8,\n\t  9,  10,  12,  13,  15,  16,  18,  19,  21,  23,  25,  27,  29,  31,  33,\n\t 36,  38,  40,  43,  46,  48,  51,  54,  56,  59,  62,  65,  68,  72,  75,\n\t 78,  81,  85,  88,  92,  95,  99, 102, 106, 110, 114, 117, 121, 125, 129,\n\t133, 137, 141, 146, 150, 154, 158, 162, 167, 171, 175, 180, 184, 189, 193,\n\t198, 202, 207, 211, 216, 220, 225, 229, 234, 239, 243, 248, 253, 257, 262,\n};\n"
  },
  {
    "path": "mcu/common.ld",
    "content": "SECTIONS {\n\t.cfg : {\n\t\t_cfg_start = .;\n\t\t*(.cfg)\n\t\t. = ALIGN(8);\n\t\t_cfg_end = .;\n\t} >ram AT >cfg\n}\n\n_boot = ORIGIN(boot);\n_cfg = ORIGIN(cfg);\n_rom = ORIGIN(rom);\n_ram = ORIGIN(ram);\n_eod = LOADADDR(.data) + SIZEOF(.data);\n\nINCLUDE cortex-m-generic.ld\n"
  },
  {
    "path": "src/cli.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#define CFG_MAP(XX) \\\n\tXX( 0, val, arm) \\\n\tXX( 1, val, damp) \\\n\tXX( 2, val, revdir) \\\n\tXX( 3, val, brushed) \\\n\tXX( 4, val, timing) \\\n\tXX( 5, val, sine_range) \\\n\tXX( 6, val, sine_power) \\\n\tXX( 7, val, freq_min) \\\n\tXX( 8, val, freq_max) \\\n\tXX( 9, val, duty_min) \\\n\tXX(10, val, duty_max) \\\n\tXX(11, val, duty_spup) \\\n\tXX(12, val, duty_ramp) \\\n\tXX(13, val, duty_rate) \\\n\tXX(14, val, duty_drag) \\\n\tXX(15, val, duty_lock) \\\n\tXX(16, val, throt_mode) \\\n\tXX(17, val, throt_rev) \\\n\tXX(18, val, throt_brk) \\\n\tXX(19, val, throt_set) \\\n\tXX(20, val, throt_ztc) \\\n\tXX(21, val, throt_cal) \\\n\tXX(22, val, throt_min) \\\n\tXX(23, val, throt_mid) \\\n\tXX(24, val, throt_max) \\\n\tXX(25, val, analog_min) \\\n\tXX(26, val, analog_max) \\\n\tXX(27, val, input_mode) \\\n\tXX(28, val, input_ch1) \\\n\tXX(29, val, input_ch2) \\\n\tXX(30, val, telem_mode) \\\n\tXX(31, val, telem_phid) \\\n\tXX(32, val, telem_poles) \\\n\tXX(33, val, prot_stall) \\\n\tXX(34, val, prot_temp) \\\n\tXX(35, val, prot_sens) \\\n\tXX(36, val, prot_volt) \\\n\tXX(37, val, prot_cells) \\\n\tXX(38, val, prot_curr) \\\n\tXX(39, val, prot_park) \\\n\tXX(40, str, music) \\\n\tXX(41, val, volume) \\\n\tXX(42, val, beacon) \\\n\tXX(43, val, bec) \\\n\tXX(44, val, led) \\\n\nstatic int beep = -1;\n\nstatic int split(char *str, char **vec, int len, const char *sep) {\n\tint idx = 0;\n\tfor (char *val; (val = strsep(&str, sep));) {\n\t\tif (!*val) continue;\n\t\tvec[idx++] = val;\n\t\tif (idx == len) break;\n\t}\n\treturn idx;\n}\n\nstatic int getidx(const char *str, const char *const vec[]) {\n\tint idx = 0;\n\tconst char *const *pos = vec;\n\tfor (const char *val; (val = *pos++) && strcasecmp(val, str); ++idx);\n\treturn idx;\n}\n\nstatic int getval(const char *str, int *val) {\n\tchar *end;\n\tint res = strtol(str, &end, 10);\n\tif (*end) return 0;\n\t*val = res;\n\treturn 1;\n}\n\nstatic void appendstr(char **pos, const char *str) {\n\t*pos = stpcpy(*pos, str);\n}\n\nstatic void appendval(char **pos, int val) {\n\tchar buf[12];\n\tappendstr(pos, itoa(val, buf, 10));\n}\n\nstatic void appenddec(char **pos, int val) {\n\tchar buf[12];\n\tappendstr(pos, itoa(val / 100, buf, 10));\n\tappendstr(pos, \".\");\n\tfor (int i = strlen(itoa(val % 100, buf, 10)); i < 2; ++i) appendstr(pos, \"0\");\n\tappendstr(pos, buf);\n}\n\n#define appendpair(pos, type, key) \\\n\tappendstr(pos, #key); \\\n\tappendstr(pos, \": \"); \\\n\tappend##type(pos, cfg.key); \\\n\tappendstr(pos, \"\\n\"); \\\n\n#define setstr(str, key) strlcpy(cfg.key, str, sizeof cfg.key)\n#define setval(str, key) \\\n\tif (!getval(str, &val)) goto error; \\\n\tcfg.key = val; \\\n\n#define setbeepstr(str)\n\nstatic int setbeepval(int val) {\n\tif (beep < 0 || val < 0) return val;\n\tbeep = beepval = val;\n\treturn val;\n}\n\nint execcmd(char *str) {\n\tstatic const char *const cmds[] = {\"help\", \"info\", \"show\", \"get\", \"set\", \"save\", \"reset\", \"play\", \"throt\", \"beep\", 0};\n\tstatic const char *const keys[] = {\n#define XX(idx, type, key) #key,\nCFG_MAP(XX)\n#undef XX\n\t0};\n\tchar *args[10];\n\tint narg = split(str, args, 10, \" \\t\\r\\n\");\n\tif (!narg) return 0;\n\tint val;\n\tchar *pos = str;\n\tswitch (getidx(args[0], cmds)) {\n\t\tcase 0: // 'help'\n\t\t\tappendstr(&pos,\n\t\t\t\t\"Usage:\\n\"\n\t\t\t\t\"info\\n\"\n\t\t\t\t\"show\\n\"\n\t\t\t\t\"get <param>\\n\"\n\t\t\t\t\"set <param> <value>\\n\"\n\t\t\t\t\"save\\n\"\n\t\t\t\t\"reset\\n\"\n\t\t\t\t\"play <music> [<volume>]\\n\"\n\t\t\t\t\"throt <value>\\n\"\n\t\t\t\t\"beep\\n\"\n\t\t\t);\n\t\t\tbreak;\n\t\tcase 1: // 'info'\n\t\t\tif (narg != 1) goto error;\n\t\t\tappendstr(&pos, \"ESCape32 rev\");\n\t\t\tappendval(&pos, setbeepval(cfg.revision));\n\t\t\tappendstr(&pos, \".\");\n\t\t\tappendval(&pos, cfg.revpatch);\n\t\t\tappendstr(&pos, \" [\");\n\t\t\tappendstr(&pos, cfg.name);\n\t\t\tappendstr(&pos, \"]\\nTemp: \");\n\t\t\tappendval(&pos, temp1);\n\t\t\tif (temp2) {\n\t\t\t\tappendstr(&pos, \"C, ext \");\n\t\t\t\tappendval(&pos, temp2);\n\t\t\t}\n\t\t\tappendstr(&pos, \"C\\nVolt: \");\n\t\t\tappenddec(&pos, volt);\n\t\t\tappendstr(&pos, \"V\\nCurr: \");\n\t\t\tappenddec(&pos, curr);\n\t\t\tappendstr(&pos, \"A\\nCsum: \");\n\t\t\tappendval(&pos, csum);\n\t\t\tappendstr(&pos, \"mAh\\nERPM: \");\n\t\t\tappendval(&pos, erpm);\n\t\t\tappendstr(&pos, \"\\n\");\n\t\t\tbreak;\n\t\tcase 2: // 'show'\n\t\t\tif (narg != 1) goto error;\n#define XX(idx, type, key) \\\n\t\t\tappendpair(&pos, type, key);\nCFG_MAP(XX)\n#undef XX\n\t\t\tbreak;\n\t\tcase 3: // 'get <param>'\n\t\t\tif (narg != 2) goto error;\n\t\t\tswitch (getidx(args[1], keys)) {\n#define XX(idx, type, key) \\\n\t\t\t\tcase idx: \\\n\t\t\t\t\tappendpair(&pos, type, key); \\\n\t\t\t\t\tsetbeep##type(cfg.key); \\\n\t\t\t\t\tbreak;\nCFG_MAP(XX)\n#undef XX\n\t\t\t\tdefault:\n\t\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4: // 'set <param> <value>'\n\t\t\tif (narg != 3) goto error;\n\t\t\tswitch (getidx(args[1], keys)) {\n#define XX(idx, type, key) \\\n\t\t\t\tcase idx: \\\n\t\t\t\t\tset##type(args[2], key); \\\n\t\t\t\t\tcheckcfg(); \\\n\t\t\t\t\tappendpair(&pos, type, key); \\\n\t\t\t\t\tsetbeep##type(cfg.key); \\\n\t\t\t\t\tbreak;\nCFG_MAP(XX)\n#undef XX\n\t\t\t\tdefault:\n\t\t\t\t\tgoto error;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 5: // 'save'\n\t\t\tif (narg != 1 || !setbeepval(savecfg())) goto error;\n\t\t\tbreak;\n\t\tcase 6: // 'reset'\n\t\t\tif (narg != 1 || !setbeepval(resetcfg())) goto error;\n\t\t\tbreak;\n\t\tcase 7: // 'play <music> [<volume>]'\n\t\t\tif (narg < 2 || narg > 3) goto error;\n\t\t\tval = cfg.volume;\n\t\t\tif (narg == 3 && (!getval(args[2], &val) || val < 1 || val > 100)) goto error;\n\t\t\tif (!playmusic(args[1], val)) goto error;\n\t\t\tbreak;\n\t\tcase 8: // 'throt <value>'\n\t\t\tif (narg != 2 || !getval(args[1], &val) || val < -2000 || val > 2000) goto error;\n\t\t\tthrot = val;\n\t\t\tanalog = 0;\n\t\t\tbreak;\n\t\tcase 9: // 'beep'\n\t\t\tif (narg != 1) goto error;\n\t\t\tif (beep < 0) beep = 0;\n\t\t\tbeepval = beep;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto error;\n\t}\n\tappendstr(&pos, \"OK\\n\");\n\treturn pos - str;\nerror:\n\tappendstr(&pos, \"ERROR\\n\");\n\treturn pos - str;\n}\n"
  },
  {
    "path": "src/common.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#include <stdlib.h>\n#include <string.h>\n#include <libopencmsis/core_cm3.h>\n#include <libopencm3/stm32/syscfg.h>\n#include <libopencm3/stm32/rcc.h>\n#include <libopencm3/stm32/gpio.h>\n#include <libopencm3/stm32/timer.h>\n#ifdef AT32F4\n#include <libopencm3/cm3/common.h>\n#include <libopencm3/stm32/f1/usart.h>\n#else\n#include <libopencm3/stm32/usart.h>\n#endif\n#include <libopencm3/stm32/dma.h>\n#include <libopencm3/stm32/flash.h>\n#include <libopencm3/stm32/iwdg.h>\n#include <libopencm3/stm32/wwdg.h>\n#include \"config.h\"\n#include \"defs.h\"\n\n#define CLK_CNT(rate) ((CLK + ((rate) >> 1)) / (rate))\n#define CLK_KHZ (CLK / 1000)\n#define CLK_MHZ (CLK / 1000000)\n\n#ifdef ANALOG\n#define IO_ANALOG (cfg.throt_set < 100)\n#elif defined IO_PA2 || defined IO_PA6 || defined ANALOG_CHAN\n#define IO_ANALOG (cfg.input_mode == 1)\n#else\n#define IO_ANALOG 0\n#endif\n\n#define GPIO(port, name) _GPIO(port, name)\n#define _GPIO(port, name) __GPIO(port, name)\n#define __GPIO(port, name) GPIO##port##_##name\n\ntypedef struct {\n\tconst uint16_t id;\n\tconst char revision;\n\tconst char revpatch;\n\tconst char name[15];\n\tconst char _null;\n\tchar arm;\n\tchar damp;\n\tchar revdir;\n\tchar brushed;\n\tchar timing;\n\tchar sine_range;\n\tchar sine_power;\n\tchar freq_min;\n\tchar freq_max;\n\tchar duty_min;\n\tchar duty_max;\n\tchar duty_spup;\n\tchar duty_ramp;\n\tchar duty_rate;\n\tchar duty_drag;\n\tchar duty_lock;\n\tchar throt_mode;\n\tchar throt_rev;\n\tchar throt_brk;\n\tchar throt_set;\n\tchar throt_ztc;\n\tchar throt_cal;\n\tuint16_t throt_min;\n\tuint16_t throt_mid;\n\tuint16_t throt_max;\n\tuint16_t analog_min;\n\tuint16_t analog_max;\n\tchar input_mode;\n\tchar input_ch1;\n\tchar input_ch2;\n\tchar telem_mode;\n\tchar telem_phid;\n\tchar telem_poles;\n\tuint16_t prot_stall;\n\tchar prot_temp;\n\tchar prot_sens;\n\tchar prot_volt;\n\tchar prot_cells;\n\tuint16_t prot_curr;\n\tchar prot_park;\n\tchar music[256];\n\tchar volume;\n\tchar beacon;\n\tchar bec;\n\tchar led;\n} Cfg;\n\ntypedef struct {\n\tint Kp, Ki, Kd, Li, i, x;\n} PID;\n\ntypedef void (*Func)(void);\n\nextern char _boot[], _cfg[], _cfg_start[], _cfg_end[], _rom[], _ram[], _eod[], _vec[]; // Linker exports\nextern const uint16_t sinedata[];\nextern const Cfg cfgdata;\nextern Cfg cfg;\nextern int throt, brake, ertm, erpm, temp1, temp2, volt, curr, csum, dshotval, beepval;\nextern char analog, telreq, telmode, flipdir, beacon, dshotext, auxup;\n\nvoid init(void);\nvoid initio(void);\nvoid initgpio(void);\nvoid initled(void);\nvoid inittelem(void);\nint hallcode(void);\nvoid ledctl(int x);\nvoid hsictl(int x);\nvoid compctl(int x);\nvoid io_serial(void);\nvoid io_analog(void);\nvoid adctrig(void);\nvoid adcdata(int t, int u, int v, int c, int a);\nvoid delay(int ms, Func f);\nvoid kisstelem(void);\nvoid autotelem(void);\nint execcmd(char *str);\nchar crc8(const char *buf, int len);\nchar crc8dvbs2(const char *buf, int len);\nint scale(int x, int a1, int a2, int b1, int b2);\nint smooth(int *s, int x, int n);\nvoid initpid(PID *pid, int x);\nint calcpid(PID *pid, int x, int y);\nvoid checkcfg(void);\nint savecfg(void);\nint resetcfg(void);\nvoid resetcom(void);\nint playmusic(const char *str, int vol);\nvoid playsound(const char *buf, int vol);\n\nstatic inline int min(int a, int b) {return a < b ? a : b;}\nstatic inline int max(int a, int b) {return a > b ? a : b;}\nstatic inline int clamp(int x, int a, int b) {return min(max(x, a), b);}\n\n// Temperature sensors\n\nstatic inline int NTC10K3455LO2K(int x) {\n\treturn (x < 2338 ? (x - 1650) * 46 + 74841 : (x - 2640) * 83 + 132044) >> 8;\n}\n\nstatic inline int NTC10K3455UP2K(int x) {\n\treturn (x > 961 ? (x - 1650) * -46 + 74841 : (x - 660) * -83 + 132044) >> 8;\n}\n\nstatic inline int NTC10K3455LO10K(int x) {\n\treturn (x < 2762 ? (x - 1650) * 36 + 25600 : (x - 3036) * 151 + 107130) >> 8;\n}\n\nstatic inline int NTC10K3455UP10K(int x) {\n\treturn (x > 537 ? (x - 1650) * -36 + 25600 : (x - 264) * -151 + 107130) >> 8;\n}\n"
  },
  {
    "path": "src/defs.h",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#if DEAD_TIME < 128\n#define TIM_DTG DEAD_TIME\n#elif DEAD_TIME < 256\n#define TIM_DTG (((DEAD_TIME - 128) >> 1) | 0x80)\n#elif DEAD_TIME < 512\n#define TIM_DTG (((DEAD_TIME - 256) >> 3) | 0xc0)\n#elif DEAD_TIME < 1024\n#define TIM_DTG (((DEAD_TIME - 512) >> 4) | 0xe0)\n#endif\n\n#if COMP_MAP == 123\n#define COMP_IN1 1\n#define COMP_IN2 2\n#define COMP_IN3 3\n#elif COMP_MAP == 231\n#define COMP_IN1 2\n#define COMP_IN2 3\n#define COMP_IN3 1\n#elif COMP_MAP == 312\n#define COMP_IN1 3\n#define COMP_IN2 1\n#define COMP_IN3 2\n#elif COMP_MAP == 132\n#define COMP_IN1 1\n#define COMP_IN2 3\n#define COMP_IN3 2\n#elif COMP_MAP == 321\n#define COMP_IN1 3\n#define COMP_IN2 2\n#define COMP_IN3 1\n#elif COMP_MAP == 213\n#define COMP_IN1 2\n#define COMP_IN2 1\n#define COMP_IN3 3\n#endif\n\n#ifndef SENS_MAP\n#define SENS_MAP 0\n#define SENS_CNT 0\n#define SENS_CHAN 0\n#elif SENS_MAP <= 0xff\n#define SENS_CNT 1\n#elif SENS_MAP <= 0xffff\n#define SENS_CNT 2\n#elif SENS_MAP <= 0xffffff\n#define SENS_CNT 3\n#endif\n\n#ifndef LED_MAP\n#ifdef LED_WS2812\n#define LED_CNT 3\n#else\n#define LED_CNT 0\n#endif\n#elif LED_MAP <= 0xff\n#define LED_CNT 1\n#elif LED_MAP <= 0xffff\n#define LED_CNT 2\n#elif LED_MAP <= 0xffffff\n#define LED_CNT 3\n#elif LED_MAP <= 0xffffffff\n#define LED_CNT 4\n#endif\n\n#ifndef TEMP_SENS\n#define TEMP_SENS NTC10K3455UP2K\n#endif\n#ifndef VOLT_MUL\n#define VOLT_MUL 0 // %\n#endif\n#ifndef CURR_MUL\n#define CURR_MUL 0 // mA/mV\n#endif\n#ifndef SERIAL_BR\n#define SERIAL_BR 460800\n#endif\n#ifndef ERPM_PORT\n#define ERPM_PORT B\n#endif\n#ifndef PARK_PORT\n#define PARK_PORT B\n#endif\n#ifndef BEC_MIN\n#define BEC_MIN 0\n#endif\n#ifndef BEC_MAX\n#define BEC_MAX (BEC_MIN + 3)\n#endif\n\n// Default settings\n\n#ifndef ARM\n#define ARM 1\n#endif\n#ifndef DAMP\n#define DAMP 1\n#endif\n#ifndef REVDIR\n#define REVDIR 0\n#endif\n#ifndef BRUSHED\n#define BRUSHED 0\n#endif\n#ifndef TIMING\n#define TIMING 16\n#endif\n#ifndef SINE_RANGE\n#define SINE_RANGE 0\n#endif\n#ifndef SINE_POWER\n#define SINE_POWER 8\n#endif\n#ifndef FREQ_MIN\n#define FREQ_MIN 24\n#endif\n#ifndef FREQ_MAX\n#define FREQ_MAX 48\n#endif\n#ifndef DUTY_MIN\n#define DUTY_MIN 1\n#endif\n#ifndef DUTY_MAX\n#define DUTY_MAX 100\n#endif\n#ifndef DUTY_SPUP\n#define DUTY_SPUP 15\n#endif\n#ifndef DUTY_RAMP\n#define DUTY_RAMP 0\n#endif\n#ifndef DUTY_RATE\n#define DUTY_RATE 30\n#endif\n#ifndef DUTY_DRAG\n#define DUTY_DRAG 0\n#endif\n#ifndef DUTY_LOCK\n#define DUTY_LOCK 0\n#endif\n#ifndef THROT_MODE\n#define THROT_MODE 0\n#endif\n#ifndef THROT_ZTC\n#define THROT_ZTC 0\n#endif\n#ifndef THROT_REV\n#define THROT_REV 0\n#endif\n#ifndef THROT_BRK\n#define THROT_BRK 100\n#endif\n#ifndef THROT_SET\n#define THROT_SET 0\n#endif\n#ifndef THROT_CAL\n#ifdef USE_HSE\n#define THROT_CAL 0\n#else\n#define THROT_CAL 1\n#endif\n#endif\n#ifndef THROT_MIN\n#define THROT_MIN 1000\n#endif\n#ifndef THROT_MID\n#define THROT_MID 1500\n#endif\n#ifndef THROT_MAX\n#define THROT_MAX 2000\n#endif\n#ifndef ANALOG_MIN\n#define ANALOG_MIN 100\n#endif\n#ifndef ANALOG_MAX\n#define ANALOG_MAX 3200\n#endif\n#ifndef INPUT_MODE\n#define INPUT_MODE 0\n#endif\n#ifndef INPUT_CH1\n#define INPUT_CH1 0\n#endif\n#ifndef INPUT_CH2\n#define INPUT_CH2 0\n#endif\n#ifndef TELEM_MODE\n#define TELEM_MODE 0\n#endif\n#ifndef TELEM_PHID\n#define TELEM_PHID 0\n#endif\n#ifndef TELEM_POLES\n#define TELEM_POLES 14\n#endif\n#ifndef PROT_STALL\n#define PROT_STALL 0\n#endif\n#ifndef PROT_TEMP\n#define PROT_TEMP 0\n#endif\n#ifndef PROT_SENS\n#define PROT_SENS 0\n#endif\n#ifndef PROT_VOLT\n#define PROT_VOLT 0\n#endif\n#ifndef PROT_CELLS\n#define PROT_CELLS 0\n#endif\n#ifndef PROT_CURR\n#define PROT_CURR 0\n#endif\n#ifndef PROT_PARK\n#define PROT_PARK 0\n#endif\n#ifndef MUSIC\n#define MUSIC \"dfa#\"\n#endif\n#ifndef VOLUME\n#define VOLUME 25\n#endif\n#ifndef BEACON\n#define BEACON 50\n#endif\n#ifndef BEC\n#define BEC 0\n#endif\n#ifndef LED\n#define LED 0\n#endif\n"
  },
  {
    "path": "src/io.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#ifdef AT32F4\n#define USART2_TDR USART2_DR\n#define USART2_RDR USART2_DR\n#define USART2_ISR USART2_SR\n#define USART_CR1_M0 USART_CR1_M\n#define USART_ISR_FE USART_SR_FE\n#define USART_ISR_NF USART_SR_NE\n#endif\n\nstatic void entryirq(void);\nstatic void calibirq(void);\nstatic void servoirq(void);\nstatic void dshotirq(void);\nstatic void dshotdma(void);\nstatic void cliirq(void);\n#ifdef IO_PA2\nstatic void serialirq(void);\nstatic void serialdma(void);\nstatic void ibusdma(void);\nstatic void sbusdma(void);\nstatic void crsfirq(void);\nstatic char rxlen;\n#endif\nstatic Func ioirq, iodma;\nstatic char dshotinv, iobuf[1024];\nstatic uint16_t dshotarr1, dshotarr2, dshotbuf1[32], dshotbuf2[23] = {-1, -1, 0, -1, 0, -1, -1, 0, -1, 0, -1, -1, 0, -1, 0, -1, 0, -1, -1, -1};\n\nstatic void setthrot(int x) {\n\tif (x < 0) return;\n\tthrot = cfg.throt_mode ?\n\t\tx < cfg.throt_mid - 50 ? scale(x, cfg.throt_min, cfg.throt_mid - 50, -2000, 0):\n\t\tx > cfg.throt_mid + 50 ? scale(x, cfg.throt_mid + 50, cfg.throt_max, 0, 2000): 0:\n\t\tx > cfg.throt_min + 50 ? scale(x, cfg.throt_min + 50, cfg.throt_max, 0, 2000): 0;\n}\n\n#if defined IO_PA2 || defined IO_AUX\nstatic void setbrake(int x) {\n\tif (x < 0) return;\n\tbrake = scale(x, 1100, 1900, 0, cfg.duty_drag);\n\tauxup = 0;\n}\n#endif\n\n#ifdef IO_AUX\nvoid iotim2_isr(void) {\n#if IOTIM2 == TIM16 || IOTIM2 == TIM17\n\tstatic uint16_t t1;\n\tuint16_t t2 = TIM_CCR1(IOTIM2);\n\tuint16_t er = TIM_CCER(IOTIM2);\n\tTIM_CCER(IOTIM2) = er ^ TIM_CCER_CC1P;\n\tif (!(er & TIM_CCER_CC1P)) { // Rising edge\n\t\tt1 = t2;\n\t\treturn;\n\t}\n\tint x = t2 - t1;\n#else\n\tint x = TIM_CCR2(IOTIM2);\n#endif\n\tif (x < 800 || x > 2200) return; // Invalid signal\n\tsetbrake(x);\n}\n#endif\n\nvoid initio(void) {\n\tioirq = entryirq;\n\tTIM_BDTR(IOTIM) = TIM_BDTR_MOE;\n\tTIM_CCMR1(IOTIM) = TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_CK_INT_N_8;\n\tTIM_SMCR(IOTIM) = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1FP1; // Reset on rising edge on TI1\n\tTIM_CCER(IOTIM) = TIM_CCER_CC1E; // IC1 on rising edge on TI1\n\tTIM_DIER(IOTIM) = TIM_DIER_UIE | TIM_DIER_CC1IE;\n\tTIM_PSC(IOTIM) = CLK_MHZ - 1; // 1us resolution\n\tTIM_ARR(IOTIM) = -1;\n\tTIM_CR1(IOTIM) = TIM_CR1_URS;\n\tTIM_EGR(IOTIM) = TIM_EGR_UG;\n\tTIM_CR1(IOTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n#ifdef IO_AUX\n#if IOTIM2 == TIM16 || IOTIM2 == TIM17\n\tTIM_CCMR1(IOTIM2) = TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8;\n\tTIM_CCER(IOTIM2) = TIM_CCER_CC1E; // IC1 on rising edge on TI1\n\tTIM_DIER(IOTIM2) = TIM_DIER_CC1IE;\n#else\n\tTIM_CCMR1(IOTIM2) = TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8 | TIM_CCMR1_CC2S_IN_TI1 | TIM_CCMR1_IC2F_DTF_DIV_8_N_8;\n\tTIM_SMCR(IOTIM2) = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1FP1; // Reset on rising edge on TI1\n\tTIM_CCER(IOTIM2) = TIM_CCER_CC2E | TIM_CCER_CC2P; // IC2 on falling edge on TI1\n\tTIM_DIER(IOTIM2) = TIM_DIER_CC2IE;\n#endif\n\tTIM_PSC(IOTIM2) = CLK_MHZ - 1; // 1us resolution\n\tTIM_ARR(IOTIM2) = -1;\n\tTIM_EGR(IOTIM2) = TIM_EGR_UG;\n\tTIM_CR1(IOTIM2) = TIM_CR1_CEN;\n#endif\n}\n\nstatic void entryirq(void) {\n\tstatic int n, c, d;\n\tif (TIM_SR(IOTIM) & TIM_SR_UIF) { // Timeout ~66ms\n\t\tTIM_SR(IOTIM) = ~TIM_SR_UIF;\n\t\tif (!IOTIM_IDR) { // Low level\n\t\t\tif (IO_ANALOG) goto analog;\n\t\t\tn = 0;\n\t\t\treturn;\n\t\t}\n\t\tif (++c < 16) return; // Wait for ~1s before entering CLI\n\t\tioirq = cliirq;\n#ifdef IO_PA2\n\t\tio_serial();\n#ifdef IO_RXTX\n\t\tGPIOA_PUPDR |= 0x80000000; // A15 (pull-down)\n\t\tGPIOA_MODER &= ~0x40000000; // A15 (USART2_RX)\n\t\tTIM15_ARR = CLK_CNT(20000) - 1;\n\t\tTIM15_EGR = TIM_EGR_UG;\n\t\tTIM15_SR = ~TIM_SR_UIF;\n\t\tTIM15_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\t\twhile (TIM15_CR1 & TIM_CR1_CEN) { // Wait for 50us high level on A15\n\t\t\tif (!(GPIOA_IDR & 0x8000)) { // A15 low\n\t\t\t\tUSART2_CR3 = USART_CR3_HDSEL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n#else\n\t\tUSART2_CR3 = USART_CR3_HDSEL;\n#endif\n\t\tUSART2_BRR = CLK_CNT(38400);\n\t\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_RXNEIE;\n#else\n\t\tTIM3_CCER = 0;\n\t\tTIM3_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2 | TIM_CCMR1_CC2S_IN_TI1 | TIM_CCMR1_IC2F_CK_INT_N_8;\n\t\tTIM3_SMCR = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\t\tTIM3_CCER = TIM_CCER_CC2E | TIM_CCER_CC2P; // IC2 on falling edge on TI1\n\t\tTIM3_SR = ~TIM_SR_CC2IF;\n\t\tTIM3_DIER = TIM_DIER_CC2IE;\n\t\tTIM3_PSC = 0;\n\t\tTIM3_ARR = CLK_CNT(38400) - 1; // Bit time\n\t\tTIM3_CCR1 = CLK_CNT(76800); // Half-bit time\n\t\tTIM3_EGR = TIM_EGR_UG;\n\t\tTIM3_CR1 = TIM_CR1_CEN;\n#endif\n\t\treturn;\n\t}\n\tint t = TIM_CCR1(IOTIM); // Time between two rising edges\n\tif (IO_ANALOG) {\n\tanalog:\n#ifndef ANALOG_CHAN\n\t\tio_analog();\n\t\tanalog = 1;\n#endif\n\t\treturn;\n\t}\n\tif (!n++) return; // First capture is always invalid\n\tIWDG_KR = IWDG_KR_START;\n#ifdef IO_PA2\n\tif (cfg.input_mode >= 2) {\n\t\tioirq = serialirq;\n\t\tio_serial();\n\t\tswitch (cfg.input_mode) {\n\t\t\tcase 2: // Serial\n\t\t\t\tiodma = serialdma;\n\t\t\t\trxlen = 4;\n\t\t\t\tUSART2_BRR = CLK_CNT(SERIAL_BR);\n\t\t\t\tbreak;\n\t\t\tcase 3: // iBUS\n\t\t\t\tiodma = ibusdma;\n\t\t\t\trxlen = 32;\n\t\t\t\tUSART2_BRR = CLK_CNT(115200);\n\t\t\t\tbreak;\n\t\t\tcase 4: // SBUS/SBUS2\n\t\t\t\tiodma = sbusdma;\n\t\t\t\trxlen = 25;\n\t\t\t\tUSART2_BRR = CLK_CNT(100000);\n\t\t\t\tUSART2_CR1 = USART_CR1_PCE | USART_CR1_M0;\n\t\t\t\tUSART2_CR2 = USART_CR2_STOPBITS_2;\n#ifndef AT32F4\n\t\t\t\tUSART2_CR2 |= USART_CR2_RXINV | USART_CR2_TXINV;\n\t\t\t\tGPIOA_PUPDR = (GPIOA_PUPDR & ~0x30) | 0x20; // A2 (pull-down)\n#endif\n\t\t\t\tTIM15_PSC = CLK_MHZ / 8 - 1; // 125ns resolution\n\t\t\t\tTIM15_ARR = -1;\n\t\t\t\tTIM15_EGR = TIM_EGR_UG;\n\t\t\t\tTIM15_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE;\n\t\t\t\tbreak;\n\t\t\tcase 5: // CRSF\n\t\t\t\tioirq = crsfirq;\n\t\t\t\tUSART2_BRR = CLK_CNT(416666);\n\t\t\t\tbreak;\n\t\t}\n\t\tUSART2_CR3 = USART_CR3_HDSEL;\n\t\tUSART2_CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_IDLEIE;\n\t\tDMA1_CPAR(USART2_RX_DMA) = (uint32_t)&USART2_RDR;\n\t\tDMA1_CMAR(USART2_RX_DMA) = (uint32_t)iobuf;\n\t\tDMA1_CPAR(USART2_TX_DMA) = (uint32_t)&USART2_TDR;\n\t\tDMA1_CMAR(USART2_TX_DMA) = (uint32_t)iobuf;\n\t\treturn;\n\t}\n#endif\n\tif (TIM_PSC(IOTIM)) {\n\t\tif (t > 2000) { // Servo/Oneshot125\n\t\t\tioirq = calibirq;\n\t\t\tTIM_DIER(IOTIM) = TIM_DIER_CC1IE;\n\t\t\tTIM_CR1(IOTIM) = TIM_CR1_CEN;\n\t\t\tcalibirq();\n\t\t\treturn;\n\t\t}\n\t\tTIM_PSC(IOTIM) = TIM_PSC(IOTIM) == CLK_MHZ - 1 ? CLK_MHZ / 8 - 1 : 0;\n\t\tTIM_EGR(IOTIM) = TIM_EGR_UG;\n\t\tn = 0;\n\t\treturn;\n\t}\n\tint m = 2;\n\twhile (t >= CLK_CNT(800000)) t >>= 1, --m;\n\tif (d != m) {\n\t\td = m;\n\t\tn = 1;\n\t\treturn;\n\t}\n\tif (m < 0 || n < 4) return;\n\tioirq = dshotirq;\n\tiodma = dshotdma;\n\tdshotarr1 = CLK_CNT(150000 << m) - 1;\n\tdshotarr2 = CLK_CNT(375000 << m) - 1;\n\tTIM_CCER(IOTIM) = 0;\n\tTIM_CCMR1(IOTIM) = TIM_CCMR1_CC1S_IN_TRC | TIM_CCMR1_IC1F_CK_INT_N_8;\n\tTIM_SMCR(IOTIM) = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\tTIM_DIER(IOTIM) = TIM_DIER_UIE;\n\tTIM_ARR(IOTIM) = dshotarr1; // Frame reset timeout\n\tTIM_EGR(IOTIM) = TIM_EGR_UG;\n\tDMA1_CPAR(IOTIM_DMA) = (uint32_t)&TIM_CCR1(IOTIM);\n\tDMA1_CMAR(IOTIM_DMA) = (uint32_t)dshotbuf1;\n}\n\nstatic void calibirq(void) {\n\tstatic int n, q, x, y;\n\tint p = TIM_CCR1(IOTIM); // Pulse period\n\tif (cfg.throt_cal && // 50/100/125/200/250/333/500Hz 11/22ms servo PWM within 8% margin\n\t\t((p < 22880 && p > 21120) || (p < 20800 && p > 19200) || (p < 11440 && p > 10560) || (p < 10400 && p > 9600) || (p < 8320 && p > 7680) ||\n\t\t(p < 5200 && p > 4800) || (p < 4160 && p > 3840) || (p < 3120 && p > 2880) || (p < 2080 && p > 1920))) {\n\t\tIWDG_KR = IWDG_KR_RESET;\n\t\tq += p - ((p + 500) / 1000) * 1000; // Cumulative error\n\t\tif (++n & 3) return;\n\t\tif (q > x) { // Slow down\n\t\t\ty = -q;\n\t\t\tq = 0;\n\t\t\thsictl(-1);\n\t\t\treturn;\n\t\t}\n\t\tif (q < y) { // Speed up\n\t\t\tx = -q;\n\t\t\tq = 0;\n\t\t\thsictl(1);\n\t\t\treturn;\n\t\t}\n\t}\n\tioirq = servoirq;\n\tTIM_CCMR1(IOTIM) = TIM_CCMR1_CC1S_IN_TI1 | TIM_CCMR1_IC1F_DTF_DIV_8_N_8 | TIM_CCMR1_CC2S_IN_TI1 | TIM_CCMR1_IC2F_DTF_DIV_8_N_8;\n\tTIM_CCER(IOTIM) = TIM_CCER_CC2E | TIM_CCER_CC2P; // IC2 on falling edge on TI1\n\tTIM_SR(IOTIM) = ~TIM_SR_CC2IF;\n\tTIM_DIER(IOTIM) = TIM_DIER_CC2IE;\n}\n\nstatic void servoirq(void) {\n\tint x = TIM_CCR2(IOTIM);\n\tif (x >= 28 && x <= 32) { // Telemetry request\n\t\tIWDG_KR = IWDG_KR_RESET;\n\t\ttelreq = 1;\n\t\treturn;\n\t}\n\tif (x < 800 || x > 2200) return; // Invalid signal\n\tIWDG_KR = IWDG_KR_RESET;\n\tsetthrot(x);\n}\n\nstatic void dshotirq(void) {\n\tif (!(TIM_DIER(IOTIM) & TIM_DIER_UIE) || !(TIM_SR(IOTIM) & TIM_SR_UIF)) return; // Fall through exactly once\n\tTIM_SR(IOTIM) = ~TIM_SR_UIF;\n\tif (!TIM_CCER(IOTIM)) { // Detect DSHOT polarity\n\t\tTIM_CCER(IOTIM) = TIM_CCER_CC1E; // IC1 on any edge on TI1\n\t\tdshotinv = IOTIM_IDR; // Inactive level\n\t}\n\tDMA1_CNDTR(IOTIM_DMA) = 32;\n\tDMA1_CCR(IOTIM_DMA) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_CIRC | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tTIM_ARR(IOTIM) = -1;\n\tTIM_EGR(IOTIM) = TIM_EGR_UG;\n\tTIM_CR1(IOTIM) = TIM_CR1_CEN | TIM_CR1_ARPE;\n\tTIM_DIER(IOTIM) = TIM_DIER_CC1DE;\n}\n\nstatic void dshotreset(void) {\n#ifdef AT32F4 // Errata 1.5.1\n\tRCC_APB2RSTR = RCC_APB2RSTR_TIM15RST;\n\tRCC_APB2RSTR = 0;\n\tTIM15_BDTR = TIM_BDTR_MOE;\n\tTIM15_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE;\n#else\n\tTIM_CCER(IOTIM) = 0;\n\tTIM_DIER(IOTIM) = 0;\n\tTIM_CR2(IOTIM) = 0;\n#endif\n\tDMA1_CCR(IOTIM_DMA) = 0;\n\tDMA1_CMAR(IOTIM_DMA) = (uint32_t)dshotbuf1;\n\tDMA1_CNDTR(IOTIM_DMA) = 32;\n\tDMA1_CCR(IOTIM_DMA) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_CIRC | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\tTIM_ARR(IOTIM) = -1;\n\tTIM_EGR(IOTIM) = TIM_EGR_UG;\n\tTIM_CCMR1(IOTIM) = TIM_CCMR1_CC1S_IN_TRC | TIM_CCMR1_IC1F_CK_INT_N_8;\n\tTIM_SMCR(IOTIM) = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\tTIM_CCER(IOTIM) = TIM_CCER_CC1E; // IC1 on any edge on TI1\n\tTIM_DIER(IOTIM) = TIM_DIER_CC1DE;\n}\n\nstatic void dshotresync(void) {\n\tif (dshotinv) dshotreset();\n\tDMA1_CCR(IOTIM_DMA) = 0;\n\tTIM_CR1(IOTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n\tTIM_ARR(IOTIM) = dshotarr1; // Frame reset timeout\n\tTIM_EGR(IOTIM) = TIM_EGR_UG;\n\tTIM_SR(IOTIM) = ~TIM_SR_UIF;\n\tTIM_DIER(IOTIM) = TIM_DIER_UIE;\n}\n\nstatic int dshotcrc(int x, int inv) {\n\tint a = x;\n\tfor (int b = x; b >>= 4; a ^= b);\n\tif (inv) a = ~a;\n\treturn a & 0xf;\n}\n\nstatic void dshotdma(void) {\n\tstatic const char gcr[] = {0x19, 0x1b, 0x12, 0x13, 0x1d, 0x15, 0x16, 0x17, 0x1a, 0x09, 0x0a, 0x0b, 0x1e, 0x0d, 0x0e, 0x0f};\n\tstatic int cmd, cnt, rep;\n\tif (DMA1_CCR(IOTIM_DMA) & DMA_CCR_DIR) {\n\t\tdshotreset();\n\t\tif (!dshotval) {\n\t\t\tint a = ertm ? min(ertm, 65408) : 65408;\n\t\t\tint b = 0;\n\t\t\twhile (a > 511) a >>= 1, ++b;\n\t\t\tdshotval = a | b << 9;\n\t\t}\n\t\tint a = dshotval << 4 | dshotcrc(dshotval, 1);\n\t\tint b = 0;\n\t\tfor (int i = 0, j = 0; i < 16; i += 4, j += 5) b |= gcr[a >> i & 0xf] << j;\n\t\tfor (int p = -1, i = 19; i >= 0; --i) {\n\t\t\tif (b >> i & 1) p = ~p;\n\t\t\tdshotbuf2[20 - i] = p;\n\t\t}\n\t\tif (!rep || !--rep) dshotval = 0;\n\t\treturn;\n\t}\n\tif (dshotinv) { // Bidirectional DSHOT\n\t\tTIM_CCER(IOTIM) = 0;\n\t\tTIM_SMCR(IOTIM) = 0;\n\t\tTIM_CCMR1(IOTIM) = 0; // Disable OC before enabling PWM to force OC1REF update (RM: OC1M, note #2)\n\t\tTIM_CCMR1(IOTIM) = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2;\n\t\tTIM_CR2(IOTIM) = TIM_CR2_CCDS; // CC1 DMA request on UEV using the same DMA channel\n\t\tDMA1_CCR(IOTIM_DMA) = 0;\n\t\tDMA1_CMAR(IOTIM_DMA) = (uint32_t)dshotbuf2;\n\t\tDMA1_CNDTR(IOTIM_DMA) = 23;\n\t\tDMA1_CCR(IOTIM_DMA) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_16BIT | DMA_CCR_MSIZE_16BIT;\n\t\tTIM_CCR1(IOTIM) = 0; // Preload high level\n\t\t__disable_irq();\n\t\tTIM_ARR(IOTIM) = max(CLK_CNT(33333) - TIM_CNT(IOTIM) - 1, 19); // 30us output delay\n\t\tTIM_EGR(IOTIM) = TIM_EGR_UG; // Update registers and trigger DMA to preload the first bit\n\t\tTIM_EGR(IOTIM); // Ensure UEV has happened\n\t\tTIM_ARR(IOTIM) = dshotarr2; // Preload bit time\n\t\tTIM_CCER(IOTIM) = TIM_CCER_CC1E; // Enable output\n\t\t__enable_irq();\n\t}\n\tint x = 0;\n\tint y = dshotarr1 + 1; // Two bit time\n\tint z = y >> 2; // Half-bit time\n\tfor (int i = 0; i < 32; i += 2) {\n\t\tif (i && dshotbuf1[i] >= y) { // Invalid pulse timing\n\t\t\tdshotresync();\n\t\t\treturn;\n\t\t}\n\t\tx <<= 1;\n\t\tif (dshotbuf1[i + 1] >= z) x |= 1;\n\t}\n\tif (dshotcrc(x, dshotinv)) { // Invalid checksum\n\t\tdshotresync();\n\t\treturn;\n\t}\n\tIWDG_KR = IWDG_KR_RESET;\n\tint tlm = x & 0x10;\n\tx >>= 5;\n\tif (!x || x > 47) {\n\t\tif (tlm) telreq = 1; // Telemetry request\n\t\tthrot = x ? cfg.throt_mode ? (x > 1047 ? x - 1047 : 47 - x) << 1 : x - 47 : 0;\n\t\tcmd = 0;\n\t\treturn;\n\t}\n\tif (!tlm || ertm) return; // Telemetry bit must be set, motor must be stopped\n\tif (cmd != x) {\n\t\tcmd = x;\n\t\tcnt = 0;\n\t}\n\tif (cnt < 10) ++cnt;\n\tswitch (cmd) {\n\t\tcase 1: // DSHOT_CMD_BEACON1\n\t\tcase 2: // DSHOT_CMD_BEACON2\n\t\tcase 3: // DSHOT_CMD_BEACON3\n\t\tcase 4: // DSHOT_CMD_BEACON4\n\t\tcase 5: // DSHOT_CMD_BEACON5\n\t\t\tbeacon = cmd;\n\t\t\tbreak;\n\t\tcase 7: // DSHOT_CMD_SPIN_DIRECTION_1\n\t\t\tif (cnt != 6) break;\n\t\t\tcfg.revdir = 0;\n\t\t\tbreak;\n\t\tcase 8: // DSHOT_CMD_SPIN_DIRECTION_2\n\t\t\tif (cnt != 6) break;\n\t\t\tcfg.revdir = 1;\n\t\t\tbreak;\n\t\tcase 9: // DSHOT_CMD_3D_MODE_OFF\n\t\t\tif (cnt != 6) break;\n\t\t\tcfg.throt_mode = 0;\n\t\t\tbreak;\n\t\tcase 10: // DSHOT_CMD_3D_MODE_ON\n\t\t\tif (cnt != 6) break;\n\t\t\tcfg.throt_mode = 1;\n\t\t\tbreak;\n\t\tcase 12: // DSHOT_CMD_SAVE_SETTINGS\n\t\t\tif (cnt != 6) break;\n\t\t\tbeepval = savecfg();\n\t\t\tbreak;\n\t\tcase 13: // DSHOT_CMD_EXTENDED_TELEMETRY_ENABLE\n\t\t\tif (cnt != 6) break;\n\t\t\tdshotext = 1;\n\t\t\tdshotval = 0xe00;\n\t\t\trep = 10;\n\t\t\tbreak;\n\t\tcase 14: // DSHOT_CMD_EXTENDED_TELEMETRY_DISABLE\n\t\t\tif (cnt != 6) break;\n\t\t\tdshotext = 0;\n\t\t\tdshotval = 0xeff;\n\t\t\trep = 10;\n\t\t\tbreak;\n\t\tcase 20: // DSHOT_CMD_SPIN_DIRECTION_NORMAL\n\t\t\tif (cnt != 6) break;\n\t\t\tflipdir = 0;\n\t\t\tbreak;\n\t\tcase 21: // DSHOT_CMD_SPIN_DIRECTION_REVERSED\n\t\t\tif (cnt != 6) break;\n\t\t\tflipdir = 1;\n\t\t\tbreak;\n#if LED_CNT >= 1\n\t\tcase 22: // DSHOT_CMD_LED0_ON\n\t\t\tcfg.led |= 1;\n\t\t\tbreak;\n\t\tcase 26: // DSHOT_CMD_LED0_OFF\n\t\t\tcfg.led &= ~1;\n\t\t\tbreak;\n#endif\n#if LED_CNT >= 2\n\t\tcase 23: // DSHOT_CMD_LED1_ON\n\t\t\tcfg.led |= 2;\n\t\t\tbreak;\n\t\tcase 27: // DSHOT_CMD_LED1_OFF\n\t\t\tcfg.led &= ~2;\n\t\t\tbreak;\n#endif\n#if LED_CNT >= 3\n\t\tcase 24: // DSHOT_CMD_LED2_ON\n\t\t\tcfg.led |= 4;\n\t\t\tbreak;\n\t\tcase 28: // DSHOT_CMD_LED2_OFF\n\t\t\tcfg.led &= ~4;\n\t\t\tbreak;\n#endif\n#if LED_CNT >= 4\n\t\tcase 25: // DSHOT_CMD_LED3_ON\n\t\t\tcfg.led |= 8;\n\t\t\tbreak;\n\t\tcase 29: // DSHOT_CMD_LED3_OFF\n\t\t\tcfg.led &= ~8;\n\t\t\tbreak;\n#endif\n\t\tcase 40: // Select motor timing\n\t\t\tif (cnt != 6) break;\n\t\t\tif ((x = (cfg.timing >> 1) + 1) > 15 || x < 8) x = 8;\n\t\t\tcfg.timing = x << 1;\n\t\t\tbeepval = x - 7;\n\t\t\tbreak;\n\t\tcase 41: // Select PWM frequency\n\t\t\tif (cnt != 6) break;\n\t\t\tif ((x = (cfg.freq_min >> 2) + 1) > 12 || x < 6) x = 6;\n\t\t\tcfg.freq_min = x << 2;\n\t\t\tcfg.freq_max = x << 3;\n\t\t\tbeepval = x - 5;\n\t\t\tbreak;\n\t\tcase 42: // Select maximum duty cycle ramp\n\t\t\tif (cnt != 6) break;\n\t\t\tif ((x = cfg.duty_ramp / 10 + 1) > 10) x = 0;\n\t\t\tcfg.duty_ramp = x * 10;\n\t\t\tbeepval = x;\n\t\t\tbreak;\n\t\tcase 43: // Select duty cycle slew rate\n\t\t\tif (cnt != 6) break;\n\t\t\tif ((x = cfg.duty_rate / 10 + 1) > 10) x = 1;\n\t\t\tcfg.duty_rate = x * 10;\n\t\t\tbeepval = x;\n\t\t\tbreak;\n\t\tcase 47: // Reset settings\n\t\t\tif (cnt != 6) break;\n\t\t\tbeepval = resetcfg();\n\t\t\tbreak;\n\t}\n}\n\nvoid iotim_isr(void) {\n\tioirq();\n}\n\nvoid iodma_isr(void) {\n#ifdef IO_PA2\n\tDMA1_IFCR = DMA_IFCR_CTCIF(IOTIM_DMA) | DMA_IFCR_CTCIF(USART2_RX_DMA);\n#else\n\tDMA1_IFCR = DMA_IFCR_CTCIF(IOTIM_DMA);\n#endif\n\tiodma();\n}\n\n#ifdef IO_PA2\nvoid usart2_isr(void) {\n\tioirq();\n}\n\nstatic int getchan(const char *buf, int n) {\n\tif (n < 0) return -1;\n\tint i = (n * 11) >> 3;\n\tint a = (n * 3) & 7;\n\tint b = ((n + 1) * 3) & 7;\n\tint x = a < b ?\n\t\tbuf[i] >> a | (buf[i + 1] & ((1 << b) - 1)) << (8 - a):\n\t\tbuf[i] >> a | buf[i + 1] << (8 - a) | (buf[i + 2] & ((1 << b) - 1)) << (16 - a);\n\treturn (x * 5 >> 3) + 880;\n}\n\nstatic void serialresync(void) {\n#ifdef AT32F4\n\tUSART2_SR, USART2_DR; // Clear flags\n#else\n\tUSART2_ICR = USART_ICR_IDLECF;\n#endif\n\tUSART2_CR1 |= USART_CR1_IDLEIE;\n\tUSART2_CR3 = USART_CR3_HDSEL;\n\tDMA1_CCR(USART2_RX_DMA) = 0;\n}\n\nstatic void serialirq(void) {\n\tif (USART2_CR1 & USART_CR1_TCIE) {\n\t\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;\n\t\treturn;\n\t}\n#ifdef AT32F4\n\tUSART2_SR, USART2_DR; // Clear flags\n#else\n\tUSART2_RQR = USART_RQR_RXFRQ; // Clear RXNE\n\tUSART2_ICR = USART_ICR_IDLECF | USART_ICR_ORECF;\n#endif\n\tUSART2_CR1 &= ~USART_CR1_IDLEIE;\n\tUSART2_CR3 = USART_CR3_HDSEL | USART_CR3_DMAT | USART_CR3_DMAR;\n\tDMA1_CNDTR(USART2_RX_DMA) = rxlen;\n\tDMA1_CCR(USART2_RX_DMA) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_CIRC | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n}\n\nstatic int serialresp(int x) {\n\tiobuf[0] = x;\n\tiobuf[1] = x >> 8;\n\tiobuf[2] = crc8(iobuf, 2);\n\treturn 3;\n}\n\nstatic int serialreq(char a, int x) {\n\tswitch (a & 0xf) {\n\t\tcase 0x1: // Throttle\n\t\t\tif (x & 0x8000) x -= 0x10000; // Propagate sign\n\t\t\tif (x < -2000 || x > 2000) break;\n\t\t\tthrot = x;\n\t\t\tbreak;\n\t\tcase 0x2: // Reversed motor direction\n\t\t\tflipdir = !!x;\n\t\t\tbreak;\n\t\tcase 0x3: // Drag brake adjustment\n\t\t\tbrake = min(x, 100) * cfg.duty_drag * 41 >> 12;\n\t\t\tauxup = 0;\n\t\t\tbreak;\n#if LED_CNT > 0\n\t\tcase 0x4: // LED\n\t\t\tcfg.led = x & ((1 << LED_CNT) - 1);\n\t\t\tbreak;\n#endif\n\t}\n\tswitch (a >> 4) {\n\t\tcase 0x8: // Combined telemetry\n\t\t\tiobuf[0] = temp1;\n\t\t\tiobuf[1] = temp2;\n\t\t\tiobuf[2] = volt;\n\t\t\tiobuf[3] = volt >> 8;\n\t\t\tiobuf[4] = curr;\n\t\t\tiobuf[5] = curr >> 8;\n\t\t\tiobuf[6] = csum;\n\t\t\tiobuf[7] = csum >> 8;\n\t\t\tiobuf[8] = x = min(ertm, 0xffff);\n\t\t\tiobuf[9] = x >> 8;\n\t\t\tiobuf[10] = crc8(iobuf, 10);\n\t\t\treturn 11;\n\t\tcase 0x9: return serialresp(min(ertm, 0xffff)); // Electrical revolution time (us)\n\t\tcase 0xa: return serialresp(temp1); // ESC temperature (C)\n\t\tcase 0xb: return serialresp(temp2); // Motor temperature (C)\n\t\tcase 0xc: return serialresp(volt); // Voltage (V/100)\n\t\tcase 0xd: return serialresp(curr); // Current (A/100)\n\t\tcase 0xe: return serialresp(csum); // Consumption (mAh)\n\t}\n\treturn 0;\n}\n\nstatic void serialdma(void) {\n\tif (crc8(iobuf, 4)) { // Invalid checksum\n\t\tserialresync();\n\t\treturn;\n\t}\n\tIWDG_KR = IWDG_KR_RESET;\n\tint len = serialreq(iobuf[0], iobuf[1] | iobuf[2] << 8);\n\tif (!len) return;\n#ifdef AT32F4\n\tUSART2_SR = ~USART_SR_TC;\n#else\n\tUSART2_ICR = USART_ICR_TCCF;\n#endif\n\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_TCIE;\n\tDMA1_CCR(USART2_TX_DMA) = 0;\n\tDMA1_CNDTR(USART2_TX_DMA) = len;\n\tDMA1_CCR(USART2_TX_DMA) = DMA_CCR_EN | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n}\n\nstatic void ibusdma(void) {\n\tif (iobuf[0] != 0x20 || iobuf[1] != 0x40) { // Invalid frame\n\t\tserialresync();\n\t\treturn;\n\t}\n\tint n1 = cfg.input_ch1;\n\tint n2 = cfg.input_ch2;\n\tint x1 = -1;\n\tint x2 = -1;\n\tint u = 0xff9f;\n\tfor (int i = 1;; ++i) {\n\t\tint j = i << 1;\n\t\tchar a = iobuf[j];\n\t\tchar b = iobuf[j + 1];\n\t\tint v = a | b << 8;\n\t\tif (i == 15) {\n\t\t\tif (u == v) break;\n\t\t\tserialresync(); // Invalid checksum\n\t\t\treturn;\n\t\t}\n\t\tu -= a + b;\n\t\tif (i == n1) x1 = v & 0xfff;\n\t\telse if (i == n2) x2 = v & 0xfff;\n\t}\n\tIWDG_KR = IWDG_KR_RESET;\n\tsetthrot(x1);\n\tsetbrake(x2);\n}\n\nstatic void sbusrx(void) {\n\tTIM15_SR = ~TIM_SR_UIF;\n\tTIM15_DIER = 0;\n\tTIM15_ARR = -1;\n\tTIM15_EGR = TIM_EGR_UG;\n\tUSART2_CR1 = USART_CR1_PCE | USART_CR1_M0 | USART_CR1_UE | USART_CR1_TE | USART_CR1_RE;\n\tioirq = serialirq;\n}\n\nstatic void sbustx(void) {\n\tstatic const char slot[] = {\n\t\t0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, // 2..7\n\t\t0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, // 10..15\n\t\t0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, // 18..23\n\t\t0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, // 26..31\n\t};\n\tstatic int n;\n\tint a = 0, b = 0;\n\tTIM15_SR = ~TIM_SR_UIF;\n\tswitch (n) {\n\t\tcase 0: // SBS-01T (ESC temperature)\n\t\t\ta = temp1 + 100;\n\t\t\tb = a >> 8 | 0x80;\n\t\t\tbreak;\n\t\tcase 1: // SBS-01T (motor temperature)\n\t\t\ta = temp2 + 100;\n\t\t\tb = a >> 8 | 0x80;\n\t\t\tbreak;\n\t\tcase 2: // SBS-01C (current)\n\t\t\tb = curr;\n\t\t\ta = b >> 8 | 0x40;\n\t\t\tbreak;\n\t\tcase 3: // SBS-01C (voltage)\n\t\t\tb = volt;\n\t\t\ta = b >> 8;\n\t\t\tbreak;\n\t\tcase 4: // SBS-01C (consumption)\n\t\t\tb = csum;\n\t\t\ta = b >> 8;\n\t\t\tbreak;\n\t\tcase 5: // SBS-01R (RPM)\n\t\t\ta = min(erpm / (cfg.telem_poles * 3), 0xffff);\n\t\t\tb = a >> 8;\n\t\t\tbreak;\n\t}\n\tiobuf[0] = slot[n + (cfg.telem_phid - 1) * 6];\n\tiobuf[1] = a;\n\tiobuf[2] = b;\n\tDMA1_CCR(USART2_TX_DMA) = 0;\n\tDMA1_CNDTR(USART2_TX_DMA) = 3;\n\tDMA1_CCR(USART2_TX_DMA) = DMA_CCR_EN | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n\tif (++n < 6) return;\n\tioirq = sbusrx;\n\tn = 0;\n}\n\nstatic void sbusdma(void) {\n\tif (iobuf[0] != 0x0f) { // Invalid frame\n\t\tserialresync();\n\t\treturn;\n\t}\n\tTIM15_EGR = TIM_EGR_UG;\n\tIWDG_KR = IWDG_KR_RESET;\n\tsetthrot(getchan(iobuf + 1, cfg.input_ch1 - 1));\n\tsetbrake(getchan(iobuf + 1, cfg.input_ch2 - 1));\n\tint a = iobuf[24];\n\tif ((a & 0xf) != 0x4) return; // No telemetry\n\tif (telmode == 2 || telmode == 3 || a >> 4 != cfg.telem_phid - 1) { // Disable RX for 7280us (2000+660*8)\n\t\tioirq = sbusrx;\n\t\t__disable_irq();\n\t\tTIM15_ARR = 58239 - TIM15_CNT;\n\t\tTIM15_EGR = TIM_EGR_UG;\n\t\t__enable_irq();\n\t} else { // Delay TX for 3980us (2000+660*3)\n\t\tioirq = sbustx;\n\t\t__disable_irq();\n\t\tTIM15_ARR = 31839 - TIM15_CNT;\n\t\tTIM15_EGR = TIM_EGR_UG;\n\t\tTIM15_EGR; // Ensure UEV has happened\n\t\tTIM15_ARR = 5279; // Preload slot interval\n\t\t__enable_irq();\n\t}\n\tTIM15_SR = ~TIM_SR_UIF;\n\tTIM15_DIER = TIM_DIER_UIE;\n\tUSART2_CR1 = USART_CR1_PCE | USART_CR1_M0 | USART_CR1_UE | USART_CR1_TE;\n}\n\nstatic void crsfirq(void) {\n#ifdef AT32F4\n\tUSART2_SR, USART2_DR; // Clear flags\n#else\n\tUSART2_RQR = USART_RQR_RXFRQ; // Clear RXNE\n\tUSART2_ICR = USART_ICR_IDLECF | USART_ICR_ORECF;\n#endif\n\tint len = 64 - DMA1_CNDTR(USART2_RX_DMA);\n\tUSART2_CR3 = USART_CR3_HDSEL | USART_CR3_DMAT | USART_CR3_DMAR;\n\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_IDLEIE;\n\tDMA1_CCR(USART2_RX_DMA) = 0;\n\tDMA1_CNDTR(USART2_RX_DMA) = 64;\n\tDMA1_CCR(USART2_RX_DMA) = DMA_CCR_EN | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n\tif (len != 26 || iobuf[1] != 0x18 || iobuf[2] != 0x16 || crc8dvbs2(iobuf + 2, 24)) return; // Invalid frame\n\tIWDG_KR = IWDG_KR_RESET;\n\tsetthrot(getchan(iobuf + 3, cfg.input_ch1 - 1));\n\tsetbrake(getchan(iobuf + 3, cfg.input_ch2 - 1));\n}\n\nstatic void cliirq(void) {\n\tstatic int i, j;\n\tint cr = USART2_CR1;\n\tif (cr & USART_CR1_TXEIE) {\n\t\tUSART2_TDR = iobuf[i++]; // Clear TXE+TC\n\t\tif (i < j) return;\n\t\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_TCIE;\n\t\ti = 0;\n\t\tj = 0;\n\t\treturn;\n\t}\n\tif (cr & USART_CR1_TCIE) {\n\t\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_RXNEIE;\n\t\treturn;\n\t}\n\tif (USART2_ISR & (USART_ISR_FE | USART_ISR_NF) || i == sizeof iobuf - 1) WWDG_CR = WWDG_CR_WDGA; // Data error\n\tchar b = USART2_RDR; // Clear RXNE\n\tif (b == '\\b' || b == 0x7f) { // Backspace\n\t\tif (i) --i;\n\t\treturn;\n\t}\n\tiobuf[i++] = b;\n\tif (i == 2 && iobuf[0] == 0x00 && iobuf[1] == 0xff) scb_reset_system(); // Reboot into bootloader\n\tif (b != '\\n') return;\n\tiobuf[i] = '\\0';\n\ti = 0;\n\tif (!(j = execcmd(iobuf))) return;\n\tUSART2_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_TXEIE;\n}\n#else\nstatic void cliirq(void) {\n\tstatic int i, j, n, b;\n\tswitch (TIM3_DIER) {\n\t\tcase TIM_DIER_UIE: // Output\n\t\t\tTIM3_SR = ~TIM_SR_UIF;\n\t\t\tif (i < j) {\n\t\t\t\tint p = -1;\n\t\t\t\tif (!n++) b = iobuf[i]; // Start bit\n\t\t\t\telse if (n < 10) { // Data bit\n\t\t\t\t\tif (b & 1) p = 0;\n\t\t\t\t\tb >>= 1;\n\t\t\t\t} else { // Stop bit\n\t\t\t\t\tif (++i == j) { // End of data\n\t\t\t\t\t\ti = 0;\n\t\t\t\t\t\tj = 0;\n\t\t\t\t\t}\n\t\t\t\t\tn = 0;\n\t\t\t\t\tp = 0;\n\t\t\t\t}\n\t\t\t\tTIM3_CCR1 = p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tTIM3_SMCR = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\t\t\tTIM3_CCER = TIM_CCER_CC2E | TIM_CCER_CC2P; // IC2 on falling edge on TI1\n\t\t\tTIM3_SR = ~TIM_SR_CC2IF;\n\t\t\tTIM3_DIER = TIM_DIER_CC2IE;\n\t\t\tTIM3_CCR1 = CLK_CNT(76800); // Half-bit time\n\t\t\tTIM3_EGR = TIM_EGR_UG;\n\t\t\tbreak;\n\t\tcase TIM_DIER_CC1IE: // Half-bit time\n\t\t\tTIM3_SR = ~TIM_SR_CC1IF;\n\t\t\tint p = IOTIM_IDR; // Signal level\n\t\t\tif (!n++) { // Start bit\n\t\t\t\tif (p) WWDG_CR = WWDG_CR_WDGA; // Data error\n\t\t\t\tb = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (n < 10) { // Data bit\n\t\t\t\tb >>= 1;\n\t\t\t\tif (p) b |= 0x80;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!p || i == sizeof iobuf - 1) WWDG_CR = WWDG_CR_WDGA; // Data error\n\t\t\tTIM3_SR = ~TIM_SR_CC2IF;\n\t\t\tTIM3_DIER = TIM_DIER_CC2IE;\n\t\t\tn = 0;\n\t\t\tif (b == '\\b' || b == 0x7f) { // Backspace\n\t\t\t\tif (i) --i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tiobuf[i++] = b;\n\t\t\tif (i == 2 && iobuf[0] == 0x00 && iobuf[1] == 0xff) scb_reset_system(); // Reboot into bootloader\n\t\t\tif (b != '\\n') break;\n\t\t\tiobuf[i] = '\\0';\n\t\t\ti = 0;\n\t\t\tif (!(j = execcmd(iobuf))) break;\n\t\t\tTIM3_SMCR = 0;\n\t\t\tTIM3_CCR1 = 0; // Preload high level\n\t\t\tTIM3_EGR = TIM_EGR_UG; // Update registers and trigger UEV\n\t\t\tTIM3_CCER = TIM_CCER_CC1E; // Enable output\n\t\t\tTIM3_DIER = TIM_DIER_UIE;\n\t\t\tbreak;\n\t\tcase TIM_DIER_CC2IE: // Falling edge\n\t\t\tTIM3_SR = ~(TIM_SR_CC1IF | TIM_SR_CC2IF);\n\t\t\tTIM3_DIER = TIM_DIER_CC1IE;\n\t\t\tbreak;\n\t}\n}\n#endif\n"
  },
  {
    "path": "src/main.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#define REVISION 15\n#define REVPATCH 0\n\nconst Cfg cfgdata = {\n\t.id = 0x32ea,\n\t.revision = REVISION,\n\t.revpatch = REVPATCH,\n\t.name = TARGET_NAME,\n\t.arm = ARM,                 // Wait for 250ms zero throttle on startup\n\t.damp = DAMP,               // Complementary PWM (active freewheeling)\n\t.revdir = REVDIR,           // Reversed motor direction\n\t.brushed = BRUSHED,         // Brushed mode\n\t.timing = TIMING,           // Motor timing (15/16 deg) [1..31]\n\t.sine_range = SINE_RANGE,   // Sine startup range (%) [0 - off, 5..25]\n\t.sine_power = SINE_POWER,   // Sine startup power (%) [1..15]\n\t.freq_min = FREQ_MIN,       // Minimum PWM frequency (kHz) [16..48]\n\t.freq_max = FREQ_MAX,       // Maximum PWM frequency (kHz) [16..96]\n\t.duty_min = DUTY_MIN,       // Minimum duty cycle (%) [1..100]\n\t.duty_max = DUTY_MAX,       // Maximum duty cycle (%) [1..100]\n\t.duty_spup = DUTY_SPUP,     // Maximum duty cycle during spin-up (%) [1..25]\n\t.duty_ramp = DUTY_RAMP,     // Maximum duty cycle ramp (kERPM) [0..100]\n\t.duty_rate = DUTY_RATE,     // Duty cycle slew rate (0.1%/ms) [1..100]\n\t.duty_drag = DUTY_DRAG,     // Drag brake power (%) [0..100]\n\t.duty_lock = DUTY_LOCK,     // Active drag brake (0 - off, 1 - soft, 2 - hard)\n\t.throt_mode = THROT_MODE,   // Throttle mode (0 - forward, 1 - forward/reverse, 2 - forward/brake/reverse, 3 - forward/brake)\n\t.throt_rev = THROT_REV,     // Maximum reverse throttle (0 - 100%, 1 - 75%, 2 - 50%, 3 - 25%)\n\t.throt_brk = THROT_BRK,     // Maximum brake power (%) [0..100]\n\t.throt_set = THROT_SET,     // Preset throttle (%) [0..100]\n\t.throt_ztc = THROT_ZTC,     // Zero-throttle coasting\n\t.throt_cal = THROT_CAL,     // Automatic throttle calibration\n\t.throt_min = THROT_MIN,     // Minimum throttle setpoint (us)\n\t.throt_mid = THROT_MID,     // Middle throttle setpoint (us)\n\t.throt_max = THROT_MAX,     // Maximum throttle setpoint (us)\n\t.analog_min = ANALOG_MIN,   // Minimum analog throttle setpoint (mV)\n\t.analog_max = ANALOG_MAX,   // Maximum analog throttle setpoint (mV)\n\t.input_mode = INPUT_MODE,   // Input mode (0 - servo/Oneshot125/DSHOT, 1 - analog, 2 - serial, 3 - iBUS, 4 - SBUS/SBUS2, 5 - CRSF)\n\t.input_ch1 = INPUT_CH1,     // Throttle channel [0 - off, 1..14 - iBUS, 1..16 - SBUS/SBUS2/CRSF]\n\t.input_ch2 = INPUT_CH2,     // Auxiliary channel [0 - off, 1..14 - iBUS, 1..16 - SBUS/SBUS2/CRSF]\n\t.telem_mode = TELEM_MODE,   // Telemetry mode (0 - KISS, 1 - KISS auto, 2 - iBUS, 3 - S.Port, 4 - CRSF)\n\t.telem_phid = TELEM_PHID,   // Telemetry physical ID [0 - off, 1..2 - iBUS, 1..28 - S.Port, 1..4 - SBUS2]\n\t.telem_poles = TELEM_POLES, // Number of motor poles for RPM telemetry [2..100]\n\t.prot_stall = PROT_STALL,   // Stall protection (ERPM) [0 - off, 1800..3200]\n\t.prot_temp = PROT_TEMP,     // Temperature threshold (C) [0 - off, 60..140]\n\t.prot_sens = PROT_SENS,     // Temperature sensor (0 - ESC, 1 - motor, 2 - both)\n\t.prot_volt = PROT_VOLT,     // Low voltage cutoff per battery cell (V/10) [0 - off, 28..38]\n\t.prot_cells = PROT_CELLS,   // Number of battery cells [0 - auto, 1..24]\n\t.prot_curr = PROT_CURR,     // Maximum current (A) [0..500]\n\t.prot_park = PROT_PARK,     // Parking speed [0..4]\n\t.music = MUSIC,             // Startup music\n\t.volume = VOLUME,           // Sound volume (%) [0..100]\n\t.beacon = BEACON,           // Beacon volume (%) [0..100]\n\t.bec = BEC,                 // BEC voltage control (0 - 5.5V, 1 - 6.5V, 2 - 7.4V, 3 - 8.4V, 4 - 12V)\n\t.led = LED,                 // LED on/off bits [0..15]\n};\n\n__attribute__((__section__(\".cfg\")))\nCfg cfg = cfgdata;\n\nint throt, brake, ertm, erpm, temp1, temp2, volt, curr, csum, dshotval, beepval = -1;\nchar analog, telreq, telmode, flipdir, beacon, dshotext, auxup;\n\nstatic int oldstep, step, sine, sync, ival, cutback, led;\nstatic char prep, fast, lock, tick, ready, reverse;\nstatic uint32_t tickms, tickmsv;\nstatic volatile char tickmsf;\n#ifndef HALL_MAP\nstatic const int hall;\n#else\nstatic int hall;\n\nstatic int getcode(void) {\n\tint x = -1;\n\tfor (int i = 0, j = 0; j < 4; ++j) {\n\t\tint y = hallcode();\n\t\tif (x == y) continue;\n\t\tif (++i == 20) hard_fault_handler(); // Unstable signal\n\t\tx = y;\n\t\tj = 0;\n\t}\n\treturn x;\n}\n#endif\n\n/*\n6-step commutation sequence:\n #  +|-  COMP  MASK  BEMF\n 1  C|B   101   110   101\n 2  A|B   011   011   001\n 3  A|C   110   101   011\n 4  B|C   001   110   010\n 5  B|A   111   011   110\n 6  C|A   010   101   100\n*/\n\nstatic void nextstep(void) {\n\tif (sine) { // Sine startup\n\t\tTIM_ARR(IFTIM) = IFTIM_OCR = sine;\n\t\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\t\tif (!prep && step) step = step * 60 - 59; // Switch over from 6-step\n\t\tif (reverse) {\n\t\t\tif (--step < 1) step = 360;\n\t\t} else {\n\t\t\tif (++step > 360) step = 1;\n\t\t}\n\t\tint a = step - 1;\n\t\tint b = a < 120 ? a + 240 : a - 120;\n\t\tint c = a < 240 ? a + 120 : a - 240;\n\t\tint p = min(cfg.sine_power << 3, 120 - cutback); // 50% cutback at 15C above prot_temp\n\t\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_UDIS;\n\t\tTIM1_ARR = CLK_KHZ / 24 - 1;\n\t\tTIM1_CCR1 = DEAD_TIME + (sinedata[a] * p >> 7);\n\t\tTIM1_CCR2 = DEAD_TIME + (sinedata[b] * p >> 7);\n\t\tTIM1_CCR3 = DEAD_TIME + (sinedata[c] * p >> 7);\n\t\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE;\n#ifdef ERPM_PIN\n\t\tif (step == 1) GPIO(ERPM_PORT, BSRR) = 1 << (ERPM_PIN + 16);\n\t\telse if (step == 181) GPIO(ERPM_PORT, BSRR) = 1 << ERPM_PIN;\n#endif\n\t\tif (prep) return;\n\t\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2M_PWM1;\n\t\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM1;\n#ifdef PWM_ENABLE\n\t\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NP | TIM_CCER_CC2E | TIM_CCER_CC2NP | TIM_CCER_CC3E | TIM_CCER_CC3NP;\n#else\n\t\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NE | TIM_CCER_CC2E | TIM_CCER_CC2NE | TIM_CCER_CC3E | TIM_CCER_CC3NE;\n#endif\n#ifdef INVERTED_HIGH\n\t\ter |= TIM_CCER_CC1P | TIM_CCER_CC2P | TIM_CCER_CC3P;\n#endif\n\t\tTIM1_CCER = er;\n\t\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n\t\tTIM_DIER(IFTIM) = 0;\n\t\tcompctl(0);\n\t\tsync = 0;\n\t\tprep = 1;\n\t\treturn;\n\t}\n#ifdef HALL_MAP\n\tstatic const char map[][2] = {{2, 4}, {4, 6}, {3, 5}, {6, 2}, {1, 3}, {5, 1}}; // Hall sensor code mapping\n\tif (hall > 4000) {\n\t\tint code = getcode();\n\t\tif (code < 1 || code > 6) hard_fault_handler(); // Invalid Hall sensor code\n\t\tstep = map[code - 1][!!reverse];\n\t} else\n#endif\n\tif (reverse) {\n\t\tif (--step < 1) step = 6;\n\t} else {\n\t\tif (++step > 6) step = 1;\n\t}\n\tstatic const uint16_t seq[] = {0x175, 0xd9, 0x1ab, 0x72, 0x1de, 0xac}; // Commutation sequence\n\tstatic int pcc, val, cnt, buf[6];\n\tint x = seq[step - 1];\n\tint m = x >> 3; // Energized phase mask\n\tint p = x & m; // Positive phase\n\tint n = ~x & m; // Negative phase\n\tint cc = m >> 3 ^ reverse << 2; // Floating phase\n\tint m1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC2PE;\n#ifdef TIM1_CCR5\n\tint m2 = TIM_CCMR2_OC3PE;\n\tint er = TIM_CCER_CC5E;\n#else\n\tint m2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC4PE | TIM_CCMR2_OC4M_PWM1;\n\tint er = TIM_CCER_CC4E;\n#endif\n\tif (cfg.throt_ztc && !throt) p = n = 0; // Zero-throttle coasting\n\tif (p & 1) {\n\t\tm1 |= TIM_CCMR1_OC1M_PWM1;\n#ifdef PWM_ENABLE\n\t\ter |= TIM_CCER_CC1E;\n#else\n\t\ter |= cfg.damp ? TIM_CCER_CC1E | TIM_CCER_CC1NE : TIM_CCER_CC1E;\n#endif\n\t} else if (n & 1) {\n#ifdef PWM_ENABLE\n\t\tm1 |= TIM_CCMR1_OC1M_FORCE_LOW;\n#else\n\t\tm1 |= TIM_CCMR1_OC1M_FORCE_HIGH;\n#endif\n\t\ter |= TIM_CCER_CC1NE;\n\t} else {\n#ifdef PWM_ENABLE\n\t\tm1 |= TIM_CCMR1_OC1M_FORCE_HIGH;\n#else\n\t\tm1 |= TIM_CCMR1_OC1M_FORCE_LOW;\n#endif\n\t\ter |= TIM_CCER_CC1NE;\n\t}\n\tif (p & 2) {\n\t\tm1 |= TIM_CCMR1_OC2M_PWM1;\n#ifdef PWM_ENABLE\n\t\ter |= TIM_CCER_CC2E;\n#else\n\t\ter |= cfg.damp ? TIM_CCER_CC2E | TIM_CCER_CC2NE : TIM_CCER_CC2E;\n#endif\n\t} else if (n & 2) {\n#ifdef PWM_ENABLE\n\t\tm1 |= TIM_CCMR1_OC2M_FORCE_LOW;\n#else\n\t\tm1 |= TIM_CCMR1_OC2M_FORCE_HIGH;\n#endif\n\t\ter |= TIM_CCER_CC2NE;\n\t} else {\n#ifdef PWM_ENABLE\n\t\tm1 |= TIM_CCMR1_OC2M_FORCE_HIGH;\n#else\n\t\tm1 |= TIM_CCMR1_OC2M_FORCE_LOW;\n#endif\n\t\ter |= TIM_CCER_CC2NE;\n\t}\n\tif (p & 4) {\n\t\tm2 |= TIM_CCMR2_OC3M_PWM1;\n#ifdef PWM_ENABLE\n\t\ter |= TIM_CCER_CC3E;\n#else\n\t\ter |= cfg.damp ? TIM_CCER_CC3E | TIM_CCER_CC3NE : TIM_CCER_CC3E;\n#endif\n\t} else if (n & 4) {\n#ifdef PWM_ENABLE\n\t\tm2 |= TIM_CCMR2_OC3M_FORCE_LOW;\n#else\n\t\tm2 |= TIM_CCMR2_OC3M_FORCE_HIGH;\n#endif\n\t\ter |= TIM_CCER_CC3NE;\n\t} else {\n#ifdef PWM_ENABLE\n\t\tm2 |= TIM_CCMR2_OC3M_FORCE_HIGH;\n#else\n\t\tm2 |= TIM_CCMR2_OC3M_FORCE_LOW;\n#endif\n\t\ter |= TIM_CCER_CC3NE;\n\t}\n#ifdef PWM_ENABLE\n\ter |= TIM_CCER_CC1NP | TIM_CCER_CC2NP | TIM_CCER_CC3NP;\n#endif\n#ifdef INVERTED_HIGH\n\ter |= TIM_CCER_CC1P | TIM_CCER_CC2P | TIM_CCER_CC3P;\n#endif\n\tTIM1_CCMR1 = m1;\n\tTIM1_CCMR2 = m2;\n\tTIM1_CCER = er;\n\tcompctl(pcc);\n\tpcc = cc;\n\tif (ival > 1000 << IFTIM_XRES) {\n\t\tval = 1000 << IFTIM_XRES;\n\t\tcnt = 0;\n\t} else if (++cnt == 6) {\n\t\tif (abs(val - ival) > ival >> 1) { // Probably desync\n\t\t\tsync = 0;\n\t\t\tfast = 0;\n\t\t\tival = 5000 << IFTIM_XRES;\n\t\t\tertm = 100000000;\n\t\t}\n\t\tval = ival;\n\t\tcnt = 0;\n\t}\n\tif (ertm < 100) { // 600K+ ERPM\n#ifdef TIM1_CCR5\n\t\tTIM1_CCR5 = 0;\n#else\n\t\tTIM1_CCR4 = 0;\n#endif\n\t\tIFTIM_ICMR = IFTIM_ICM3;\n\t\tTIM_CR1(IFTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n\t} else if (ertm < 200) { // 300K+ ERPM\n#ifdef TIM1_CCR5\n\t\tTIM1_CCR5 = 0;\n#else\n\t\tTIM1_CCR4 = 0;\n#endif\n\t\tIFTIM_ICMR = IFTIM_ICM2;\n\t\tTIM_CR1(IFTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n\t} else if (ertm < 1000) { // 60K+ ERPM\n#ifdef TIM1_CCR5\n\t\tTIM1_CCR5 = 0;\n#else\n\t\tTIM1_CCR4 = 0;\n#endif\n\t\tIFTIM_ICMR = IFTIM_ICM1;\n\t\tTIM_CR1(IFTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n\t} else if (ertm < 2000) { // 30K+ ERPM\n#ifdef TIM1_CCR5\n\t\tTIM1_CCR5 = 0;\n#else\n\t\tTIM1_CCR4 = 0;\n#endif\n\t\tIFTIM_ICMR = IFTIM_ICM1;\n\t\tTIM_CR1(IFTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS | TIM_CR1_CKD_CK_INT_MUL_2;\n\t} else { // Minimum PWM frequency\n#ifdef TIM1_CCR5\n\t\tTIM1_CCR5 = IFTIM_ICFL << 2;\n#else\n\t\tTIM1_CCR4 = IFTIM_ICFL << 2;\n#endif\n\t\tIFTIM_ICMR = IFTIM_ICM1;\n\t\tTIM_CR1(IFTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS | TIM_CR1_CKD_CK_INT_MUL_4;\n\t}\n\tTIM_SR(IFTIM) = 0; // Clear BEMF events before enabling interrupts\n\tTIM_DIER(IFTIM) = TIM_DIER_UIE | IFTIM_ICIE;\n\tbuf[step - 1] = hall > 4000 ? hall << IFTIM_XRES : ival;\n\tif (sync < 6) return;\n\tertm = (buf[0] + buf[1] + buf[2] + buf[3] + buf[4] + buf[5]) >> (IFTIM_XRES + 1); // Electrical revolution time (us)\n#ifdef ERPM_PIN\n\tif (step == 1) GPIO(ERPM_PORT, BSRR) = 1 << (ERPM_PIN + 16);\n\telse if (step == 4) GPIO(ERPM_PORT, BSRR) = 1 << ERPM_PIN;\n#endif\n}\n\nstatic void laststep(void) {\n\tresetcom();\n\tif (sine && prep) { // Switch over to 6-step\n\t\tstep = (step + 29) / 60 + 1;\n\t\tif (step > 6) step = 1;\n\t}\n\tsine = 0;\n\tprep = 0;\n\tif (lock) nextstep();\n\telse {\n#ifdef PWM_ENABLE\n\t\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM2 | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2M_PWM2;\n\t\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM2;\n#else\n\t\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2PE | TIM_CCMR1_OC2M_PWM1;\n\t\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM1;\n#endif\n\t}\n\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n\tcompctl(0);\n\toldstep = step;\n\tstep = 0;\n}\n\nvoid tim1_com_isr(void) {\n\tif (!(TIM1_DIER & TIM_DIER_COMIE)) return;\n#if !defined STM32G4 && !defined AT32F4\n\tint m1 = TIM1_CCMR1;\n\tint m2 = TIM1_CCMR2;\n#ifdef PWM_ENABLE\n\tif ((m1 & TIM_CCMR1_OC1M_MASK) == TIM_CCMR1_OC1M_FORCE_HIGH) m1 &= ~TIM_CCMR1_OC1M_MASK;\n\tif ((m1 & TIM_CCMR1_OC2M_MASK) == TIM_CCMR1_OC2M_FORCE_HIGH) m1 &= ~TIM_CCMR1_OC2M_MASK;\n\tif ((m2 & TIM_CCMR2_OC3M_MASK) == TIM_CCMR2_OC3M_FORCE_HIGH) m2 &= ~TIM_CCMR2_OC3M_MASK;\n#else\n\tif ((m1 & TIM_CCMR1_OC1M_MASK) == TIM_CCMR1_OC1M_FORCE_LOW) m1 &= ~TIM_CCMR1_OC1M_MASK;\n\tif ((m1 & TIM_CCMR1_OC2M_MASK) == TIM_CCMR1_OC2M_FORCE_LOW) m1 &= ~TIM_CCMR1_OC2M_MASK;\n\tif ((m2 & TIM_CCMR2_OC3M_MASK) == TIM_CCMR2_OC3M_FORCE_LOW) m2 &= ~TIM_CCMR2_OC3M_MASK;\n#endif\n\tTIM1_CCMR1 = m1;\n\tTIM1_CCMR2 = m2;\n\tTIM1_EGR = TIM_EGR_COMG;\n#endif\n\tTIM1_SR = ~TIM_SR_COMIF;\n\tnextstep();\n}\n\nvoid iftim_isr(void) { // BEMF zero-crossing\n\tint er = TIM_DIER(IFTIM);\n\tint sr = TIM_SR(IFTIM);\n\tif ((er & TIM_DIER_UIE) && (sr & TIM_SR_UIF)) { // Timeout\n\t\tTIM_SR(IFTIM) = ~TIM_SR_UIF;\n\t\tTIM_DIER(IFTIM) = 0;\n\t\tsync = 0;\n\t\tfast = 0;\n\t\tival = 10000 << IFTIM_XRES;\n\t\tertm = 100000000;\n\t\treturn;\n\t}\n\tif (!(er & IFTIM_ICIE)) return;\n\tint t = IFTIM_ICR; // Time since last zero-crossing\n\tif (t < ival >> 1) return;\n\tint u = ival * 3;\n\tfast = (t < u >> 2 || t > u >> 1) && ertm < 2000; // Fast acceleration/deceleration\n\tival = (t + u) >> 2; // Commutation interval\n\tIFTIM_OCR = max((ival - (ival * cfg.timing >> 5)) >> 1, 1); // Commutation delay\n\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\tTIM_DIER(IFTIM) = 0;\n\tif (sync < 6) ++sync;\n}\n\n#ifdef HALL_MAP\nvoid tim3_isr(void) { // Any change on Hall sensor inputs\n\tif (TIM3_SR & TIM_SR_UIF) { // Timeout\n\t\tTIM3_SR = ~TIM_SR_UIF;\n\t\thall = 0x10000;\n\t\tif (sine || !step) return;\n\t\tsync = 0;\n\t\tfast = 0;\n\t\tival = 10000 << IFTIM_XRES;\n\t\tertm = 100000000;\n\t\treturn;\n\t}\n\thall = (TIM3_CCR1 + hall * 3) >> 2;\n\tif (hall < 5000 || sine || !step) return;\n\tival = hall << IFTIM_XRES;\n\tTIM1_EGR = TIM_EGR_COMG;\n\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\tTIM_DIER(IFTIM) = 0;\n\tif (sync < 6) ++sync;\n}\n#endif\n\nvoid adcdata(int t, int u, int v, int c, int a) {\n\tstatic int z = 3300, i, q, st = -1, su = -1, sv = -1, sc = -1, sa = -1;\n\tif ((c -= z) >= 0) ready = 1;\n\telse {\n\t\tif (!ready) z += c >> 1;\n\t\tc = 0;\n\t}\n\ttemp1 = max((t = smooth(&st, t, 10)) >> 2, 0); // C\n\ttemp2 = hall || cfg.prot_sens ? max((u = smooth(&su, TEMP_SENS(u), 10)) >> 2, 0) : 0; // C\n\tvolt = smooth(&sv, v * VOLT_MUL * 131 >> 17, 7); // V/100\n\tcurr = smooth(&sc, c * CURR_MUL * 205 >> 11, 4); // A/100\n\ti += curr; // Current integral\n\tif (!(tickms & 0x3ff)) {\n\t\tcsum = (q += i >> 10) * 91 >> 15; // mAh\n\t\ti = 0;\n\t}\n\tif (cfg.prot_temp) { // Temperature protection\n\t\tint x = -(cfg.prot_temp << 2);\n\t\tswitch (cfg.prot_sens) {\n\t\t\tcase 0:\n\t\t\t\tx += t;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tx += u;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tx += max(t, u);\n\t\t\t\tbreak;\n\t\t}\n\t\tcutback = clamp(x, 0, 60);\n\t}\n\tif (!analog) return;\n\tthrot = scale(smooth(&sa, a, 5), cfg.analog_min, cfg.analog_max, cfg.throt_set * 20, 2000);\n}\n\nvoid sys_tick_handler(void) {\n\tSCB_ICSR = SCB_ICSR_PENDSVSET; // Continue with low priority\n\tSCB_SCR = 0; // Resume main loop\n\tif (++tick & 15) return; // 16kHz -> 1kHz\n\tif (++tickms == tickmsv) tickmsf = 0;\n}\n\nvoid delay(int ms, Func f) {\n\t__disable_irq();\n\ttickmsv = tickms + ms;\n\ttickmsf = 1;\n\t__enable_irq();\n\twhile (tickmsf) f();\n}\n\nvoid pend_sv_handler(void) {\n\tstatic int a = -1;\n\tif (telreq && !telmode) { // Telemetry request\n\t\tkisstelem();\n\t\ttelreq = 0;\n\t}\n\tif (tick & 15) return; // 16kHz -> 1kHz\n\tadctrig();\n\tif (!(tickms & 31)) autotelem(); // Telemetry every 32ms\n\tint b = cfg.led ? cfg.led : led;\n\tif (a != b) ledctl(a = b); // Update LED\n}\n\nvoid hard_fault_handler(void) {\n\tledctl(1); // Indicate error\n\tTIM1_EGR = TIM_EGR_BG;\n\tTIM6_PSC = CLK_KHZ / 10 - 1; // 0.1ms resolution\n\tTIM6_ARR = 9999;\n\tTIM6_EGR = TIM_EGR_UG;\n\tTIM6_SR = ~TIM_SR_UIF;\n\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_OPM;\n\twhile (TIM6_CR1 & TIM_CR1_CEN); // Wait for 1s\n\tWWDG_CR = WWDG_CR_WDGA; // Trigger watchdog reset\n\tfor (;;); // Never return\n}\n\nstatic void delayf(void) {\n\tTIM6_EGR = TIM_EGR_UG; // Reset arming timeout\n}\n\nstatic void beep(void) {\n\tstatic const char *const beacons[] = {\"EG\", \"FA\", \"GB\", \"AB#\", \"aDGE\"};\n\tstatic const char *const values[] = {\"c6\", \"C2\", \"D2C2\", \"E2D2C2\", \"F#2E2D2C2\", \"G#A#G#A#G#2\", \"G#A#G#A#F#2G#2\", \"G#A#G#A#E2F#2G#2\", \"G#A#G#A#D2E2F#2G#2\", \"G#A#G#A#C2D2E2F#2G#2\", 0};\n\tif (beacon) {\n\t\tplaymusic(beacons[beacon - 1], cfg.beacon);\n\t\tbeacon = 0;\n\t}\n\tif (beepval < 0) return;\n\tint i[10], n = 0, x = beepval, vol = max(cfg.volume, 25);\n\twhile (i[n++] = x % 10, x /= 10);\n\twhile (n--) {\n\t\tif (x++) delay(500, delayf);\n\t\tplaymusic(values[i[n]], vol);\n\t}\n\tbeepval = -1;\n}\n\n#ifdef PARK_PIN\nstatic char park1;\nstatic uint16_t park2, park3;\n\nstatic int park(void) {\n\tif (!--park3) return 0;\n\tif (park1 == 3 || ++park2 < 800) return 1;\n\tint x = -1;\n\tfor (int i = 0, j = 0; j < 4; ++j) {\n\t\tint y = GPIO(PARK_PORT, IDR) & (1 << PARK_PIN);\n\t\tif (x == y) continue;\n\t\tif (++i == 20) return 0; // Unstable signal\n\t\tx = y;\n\t\tj = 0;\n\t}\n\tswitch (park1) {\n\t\tcase 0:\n\t\t\tif (!x) return 1;\n\t\t\tpark1 = 1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tif (x) return 1;\n\t\t\tpark1 = 2;\n\t\t\tpark3 = -1;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif (!x) return 1;\n\t\t\tpark1 = 3;\n\t\t\tpark3 = (0xffff - park3) >> 1;\n\t\t\treverse = !reverse;\n\t\t\tbreak;\n\t}\n\tpark2 = 0;\n\treturn 1;\n}\n#endif\n\nvoid main(void) {\n\tmemcpy(_cfg_start, _cfg, _cfg_end - _cfg_start); // Copy configuration to SRAM\n\tcheckcfg();\n\tconst int brushed = cfg.brushed;\n\tthrot = cfg.throt_set * 20;\n\tbrake = cfg.duty_drag;\n\tlock = cfg.duty_lock;\n\ttelmode = cfg.telem_mode;\n#if defined ANALOG || defined ANALOG_CHAN\n\tanalog = IO_ANALOG;\n#endif\n\tinit();\n\tinitgpio();\n\tinitled();\n\tinittelem();\n#ifndef ANALOG\n\tinitio();\n#endif\n\tTIM1_BDTR = TIM_DTG | TIM_BDTR_OSSR | TIM_BDTR_MOE;\n\tTIM1_ARR = CLK_KHZ / 24 - 1;\n\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE;\n#ifdef STM32G0\n\tTIM1_CR2 = TIM_CR2_CCPC | TIM_CR2_CCUS | TIM_CR2_MMS_COMPARE_PULSE << 16; // TRGO2=OC1\n#else\n\tTIM1_CR2 = TIM_CR2_CCPC | TIM_CR2_CCUS | TIM_CR2_MMS_COMPARE_PULSE; // TRGO=OC1\n#endif\n\tTIM_PSC(IFTIM) = (CLK_MHZ >> (IFTIM_XRES + 1)) - 1; // 125/250/500ns resolution\n\tTIM_ARR(IFTIM) = 0;\n\tTIM_CR1(IFTIM) = TIM_CR1_URS;\n\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\tTIM_CR1(IFTIM) = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n#ifdef HALL_MAP\n\tif (!brushed && getcode() != 7) { // Hybrid mode\n\t\tTIM3_CCMR1 = TIM_CCMR1_CC1S_IN_TRC | TIM_CCMR1_IC1F_DTF_DIV_8_N_8;\n\t\tTIM3_SMCR = TIM_SMCR_SMS_RM | TIM_SMCR_TS_TI1F_ED; // Reset on any edge on TI1\n\t\tTIM3_CCER = TIM_CCER_CC1E; // IC1 on any edge on TI1\n\t\tTIM3_DIER = TIM_DIER_UIE | TIM_DIER_CC1IE;\n\t\tTIM3_PSC = CLK_MHZ / 2 - 1; // 500ns resolution\n\t\tTIM3_ARR = -1;\n\t\tTIM3_CR1 = TIM_CR1_URS;\n#ifdef USE_XOR\n\t\tTIM3_CR2 = TIM_CR2_TI1S;\n#endif\n\t\tTIM3_EGR = TIM_EGR_UG;\n\t\tTIM3_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_URS;\n\t\thall = 0x10000;\n\t}\n#endif\n\tnvic_set_priority(NVIC_PENDSV_IRQ, 0x80);\n\tSTK_RVR = CLK_KHZ / 16 - 1; // 16kHz\n\tSTK_CVR = 0;\n\tSTK_CSR = STK_CSR_ENABLE | STK_CSR_TICKINT | STK_CSR_CLKSOURCE_AHB;\n#ifndef ANALOG\n\tint cells = cfg.prot_cells;\n#if SENS_CNT > 0\n\twhile (!ready) __WFI(); // Wait for sensors\n\tif (!cells) cells = (volt + 439) / 440; // Assume maximum 4.4V per battery cell\n#endif\n\tint csr = RCC_CSR;\n\tRCC_CSR = RCC_CSR_RMVF; // Clear reset flags\n\tif (!(csr & (RCC_CSR_IWDGRSTF | RCC_CSR_WWDGRSTF))) { // Power-on\n\t\tconst char *str = cfg.music;\n\t\tif (str[0] == '~') playsound(_eod, clamp(atoi(str + 1), 0, 100));\n\t\telse playmusic(str, cfg.volume);\n\t\tif (cfg.prot_volt) { // Report the number of battery cells\n\t\t\tbeepval = cells;\n\t\t\tdelay(250, delayf);\n\t\t\tbeep();\n\t\t}\n\t}\n\tif (cfg.arm || (csr & RCC_CSR_WWDGRSTF)) { // Arming required\n\trearm:\n\t\tTIM6_PSC = CLK_KHZ / 10 - 1; // 0.1ms resolution\n\t\tTIM6_ARR = 2499; // 250ms\n\t\tTIM6_CR1 = TIM_CR1_URS;\n\t\tTIM6_EGR = TIM_EGR_UG;\n\t\tTIM6_CR1 = TIM_CR1_CEN | TIM_CR1_URS;\n\t\tTIM6_SR = ~TIM_SR_UIF;\n\t\tthrot = 1;\n\t\twhile (!(TIM6_SR & TIM_SR_UIF)) { // Wait for 250ms zero throttle\n\t\t\t__WFI();\n\t\t\tbeep();\n\t\t\tif (!throt) continue;\n\t\t\tTIM6_EGR = TIM_EGR_UG;\n\t\t}\n\t\tthrot = 0;\n\t\tTIM6_CR1 = 0;\n\t\tplaymusic(hall ? \"G_GC\" : \"GC\", cfg.volume);\n\t}\n#endif\n\tlaststep();\n\tPID bpid = {.Kp = 50, .Ki = 0, .Kd = 1000}; // Stall protection\n\tPID cpid = {.Kp = 80, .Ki = 0, .Kd = 600}; // Overcurrent protection\n\tfor (int curduty = 0, running = 0, braking = 2, cutoff = 0, boost = 0, choke = 0, n = 0;;) {\n\t\tint ccr, arr = CLK_KHZ / cfg.freq_min;\n\t\tint input = cutoff == 3000 ? 0 : throt;\n\t\tint range = cfg.sine_range * 20;\n\t\tint delta = range ? 10 : 0;\n\t\tint newduty = 0;\n\t\tif (!running) curduty = 0;\n\t\tif (!input) { // Neutral\n\t\t\tif (braking == 1) braking = 2; // Reverse after braking\n\t\t\tif (lock != cfg.duty_lock && !brushed) { // Switch brake mode\n\t\t\t\tlock = cfg.duty_lock;\n\t\t\t\tif (!running) laststep();\n\t\t\t}\n\t\t\tif (sync < 6 || erpm < 800 || lock == 2) { // Drag brake\n#ifdef PARK_PIN\n\t\t\t\tif (cfg.prot_park && running && park()) { // Parking\n\t\t\t\t\tsine = (1000 << IFTIM_XRES) / cfg.prot_park;\n\t\t\t\t\tertm = 100000000;\n\t\t\t\t\terpm = 0;\n\t\t\t\t\tgoto skipduty;\n\t\t\t\t}\n#endif\n\t\t\t\tcurduty = lock ? min(brake, 100 - cutback) : brake * 20; // 60% cutback at 15C above prot_temp\n\t\t\t\trunning = 0;\n\t\t\t\tgoto setduty;\n\t\t\t}\n\t\t\tboost = 0; // Coasting\n\t\t\tgoto calcduty;\n\t\t}\n#ifdef PARK_PIN\n\t\tpark1 = 0;\n\t\tpark2 = 0;\n\t\tpark3 = -1;\n#endif\n\t\tif (input < 0) { // Reverse\n\t\t\tif ((cfg.throt_mode == 2 && braking != 2) || cfg.throt_mode == 3) { // Proportional brake\n\t\t\t\tcurduty = scale(input, -2000, 0, cfg.throt_brk * 20, brake * 20);\n\t\t\t\trunning = 0;\n\t\t\t\tbraking = 1;\n\t\t\t\tgoto setduty;\n\t\t\t}\n\t\t\tinput = input * (cfg.throt_rev - 4) >> 2;\n\t\t\treverse = !cfg.revdir ^ flipdir;\n\t\t\trunning = 1;\n\t\t} else { // Forward\n\t\t\treverse = cfg.revdir ^ flipdir;\n\t\t\trunning = 1;\n\t\t\tbraking = 0;\n\t\t}\n\t\tif (range + (sine ? delta : -delta) < input) newduty = scale(input, range + delta, 2000, cfg.duty_min * 20, cfg.duty_max * 20);\n\t\telse sine = scale(input, 0, range - delta, 1000 << IFTIM_XRES, cfg.prot_stall ? (333333 << IFTIM_XRES) / cfg.prot_stall : 145 << IFTIM_XRES);\n\t\tif (sine) { // Sine startup\n\t\t\tif (!newduty) {\n\t\t\t\tif (!ertm) goto skipduty;\n\t\t\t\tertm = sine * (180 >> IFTIM_XRES);\n\t\t\t\terpm = 60000000 / ertm;\n\t\t\t\tgoto skipduty;\n\t\t\t}\n\t\t\t__disable_irq();\n\t\t\tif (prep) { // Switch over to 6-step\n\t\t\t\tint a = step - 1;\n\t\t\t\tint b = a / 60;\n\t\t\t\tint c = b * 60;\n\t\t\t\tIFTIM_OCR = sine * (reverse ? (void)(++b == 6 && (b = 0)), a - c + 1 : c - a + 60); // Commutation delay\n\t\t\t\tTIM_ARR(IFTIM) = (1 << (IFTIM_XRES + 16)) - 1;\n\t\t\t\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\t\t\t\tstep = b + 1;\n\t\t\t}\n\t\t\tsine = 0;\n\t\t\tprep = 0;\n\t\t\tsync = 0;\n\t\t\tfast = 0;\n\t\t\tival = 10000 << IFTIM_XRES;\n\t\t\tnextstep();\n\t\t\t__enable_irq();\n\t\t\tinitpid(&bpid, 10000 << IFTIM_XRES);\n\t\t\tcurduty = 0;\n\t\t\tboost = 0;\n\t\t}\n\tcalcduty:\n\t\tif (brushed && step != reverse + 1) step = 0; // Change brushed direction\n\t\tif ((newduty += boost - choke) < 0) newduty = 0;\n\t\tif (ertm) { // Variable PWM frequency\n\t\t\tarr = scale(ertm, 1000, 2000, CLK_KHZ / cfg.freq_max, arr); // 30..60 kERPM\n\t\t\terpm = 60000000 / ertm;\n\t\t}\n\t\tint maxduty = min(scale(erpm, 0, cfg.duty_ramp * 1000, cfg.duty_spup * 20, 2000), 2000 - cutback * 25); // 75% cutback at 15C above prot_temp\n\t\tif (newduty > maxduty) newduty = maxduty;\n\t\tint a = fast ? 0 : cfg.duty_rate;\n\t\tint b = a >> 3;\n\t\tif (n < (a & 7)) ++b;\n\t\tif (++n == 8) n = 0;\n\t\tif (curduty > newduty ? sync < 6 || (curduty -= b) < newduty : (curduty += b) > newduty) curduty = newduty; // Duty cycle slew rate limiting\n\tsetduty:\n#ifdef FULL_DUTY // Allow 100% duty cycle\n\t\tccr = scale(curduty, 0, 2000, lock || (running && cfg.damp) ? DEAD_TIME : 0, arr--);\n#else\n\t\tccr = scale(curduty, 0, 2000, lock || (running && cfg.damp) ? DEAD_TIME : 0, brushed ? arr - (CLK_MHZ * 3 >> 1) : arr);\n#endif\n\t\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_UDIS;\n\t\tTIM1_ARR = arr;\n\t\tTIM1_CCR1 = ccr;\n\t\tTIM1_CCR2 = ccr;\n\t\tTIM1_CCR3 = ccr;\n\t\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE;\n\tskipduty:\n\t\tif (running && !step) { // Start motor\n\t\t\tif (brushed) {\n\t\t\t\tint m1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC2PE;\n\t\t\t\tint m2 = TIM_CCMR2_OC3PE;\n#ifdef PWM_ENABLE\n\t\t\t\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NP | TIM_CCER_CC2E | TIM_CCER_CC2NP | TIM_CCER_CC3E | TIM_CCER_CC3NP;\n\t\t\t\tif (reverse) {\n\t\t\t\t\tm1 |= TIM_CCMR1_OC1M_FORCE_LOW | TIM_CCMR1_OC2M_PWM1;\n\t\t\t\t\tm2 |= TIM_CCMR2_OC3M_FORCE_LOW;\n\t\t\t\t} else {\n\t\t\t\t\tm1 |= TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2M_FORCE_LOW;\n\t\t\t\t\tm2 |= TIM_CCMR2_OC3M_PWM1;\n\t\t\t\t}\n#else\n\t\t\t\tint er = 0;\n\t\t\t\tif (reverse) {\n\t\t\t\t\tm1 |= TIM_CCMR1_OC1M_FORCE_HIGH | TIM_CCMR1_OC2M_PWM1;\n\t\t\t\t\tm2 |= TIM_CCMR2_OC3M_FORCE_HIGH;\n\t\t\t\t\ter |= TIM_CCER_CC1NE | TIM_CCER_CC2E | TIM_CCER_CC3NE;\n\t\t\t\t\tif (cfg.damp) er |= TIM_CCER_CC2NE;\n\t\t\t\t} else {\n\t\t\t\t\tm1 |= TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2M_FORCE_HIGH;\n\t\t\t\t\tm2 |= TIM_CCMR2_OC3M_PWM1;\n\t\t\t\t\ter |= TIM_CCER_CC1E | TIM_CCER_CC2NE | TIM_CCER_CC3E;\n\t\t\t\t\tif (cfg.damp) er |= TIM_CCER_CC1NE | TIM_CCER_CC3NE;\n\t\t\t\t}\n#endif\n#ifdef INVERTED_HIGH\n\t\t\t\ter |= TIM_CCER_CC1P | TIM_CCER_CC2P | TIM_CCER_CC3P;\n#endif\n\t\t\t\tTIM1_CCMR1 = m1;\n\t\t\t\tTIM1_CCMR2 = m2;\n\t\t\t\tTIM1_CCER = er;\n\t\t\t\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n\t\t\t\tstep = reverse + 1;\n\t\t\t\tertm = 600; // 100K ERPM (freq_min/duty_spup/duty_ramp have no effect)\n\t\t\t\tgoto tick;\n\t\t\t}\n\t\t\t__disable_irq();\n\t\t\tstep = oldstep;\n\t\t\tival = 10000 << IFTIM_XRES;\n\t\t\tertm = 100000000;\n\t\t\tnextstep();\n\t\t\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n#ifdef SW_BLANKING\n\t\t\tTIM1_DIER |= TIM_DIER_COMIE | TIM_DIER_UIE | TIM_DIER_CC4IE;\n#else\n\t\t\tTIM1_DIER |= TIM_DIER_COMIE;\n#endif\n\t\t\tTIM_ARR(IFTIM) = IFTIM_OCR = (1 << (IFTIM_XRES + 16)) - 1;\n\t\t\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\t\t\t__enable_irq();\n\t\t\tinitpid(&bpid, 10000 << IFTIM_XRES);\n\t\t\tboost = 0;\n\t\t} else if (!running && step) { // Stop motor\n\t\t\t__disable_irq();\n#ifdef SW_BLANKING\n\t\t\tTIM1_DIER &= ~(TIM_DIER_COMIE | TIM_DIER_UIE | TIM_DIER_CC4IE);\n#else\n\t\t\tTIM1_DIER &= ~TIM_DIER_COMIE;\n#endif\n\t\t\tTIM_DIER(IFTIM) = 0;\n\t\t\tTIM_ARR(IFTIM) = 0;\n\t\t\tTIM_EGR(IFTIM) = TIM_EGR_UG;\n\t\t\tlaststep();\n\t\t\tsync = 0;\n\t\t\tfast = 0;\n\t\t\tertm = 0;\n\t\t\terpm = 0;\n\t\t\t__enable_irq();\n\t\t}\n\ttick:\n\t\tSCB_SCR = SCB_SCR_SLEEPONEXIT; // Suspend main loop\n\t\t__WFI();\n\t\tif (tick & 15) continue; // 16kHz -> 1kHz\n#ifndef ANALOG\n\t\tif (++auxup == 100) { // Restore brake after 100ms timeout\n\t\t\tbrake = cfg.duty_drag;\n\t\t\tauxup = 0;\n\t\t}\n\t\tif (cutoff < 3000) cutoff = volt < cfg.prot_volt * cells * 10 ? cutoff + 1 : 0;\n\t\telse if (!running) goto rearm; // Low voltage cutoff after 3s\n#endif\n\t\tboost = cfg.prot_stall ? clamp(boost + (calcpid(&bpid, hall > 4000 ? hall : ival >> IFTIM_XRES, 20000000 / cfg.prot_stall - 800) >> 16), 0, 160) : 0; // Up to 8%\n\t\tchoke = cfg.prot_curr ? clamp(choke + (calcpid(&cpid, curr, cfg.prot_curr * 100) >> 10), 0, 2000) : 0;\n\t\tbeep();\n#ifdef LED_STAT\n\t\tint x = 0;\n\t\tif (running) {\n\t\t\tif ((tickms << (throt < 0) & 0x1ff) < (sine ? 0x180 : 0x100)) x = LED_CNT >= 2 ? 2 : 1;\n\t\t} else if (curduty) {\n\t\t\tif ((tickms & (lock ? 0x2ff : 0x3ff)) < 0x40) x = LED_CNT >= 3 ? 4 : LED_CNT;\n\t\t}\n\t\tif (cutback || cutoff || choke) x |= 1;\n\t\tled = x;\n#endif\n\t}\n}\n"
  },
  {
    "path": "src/telem.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#ifndef USART1_DMA_BASE\n#define USART1_DMA_BASE DMA1_BASE\n#endif\n\n#ifdef AT32F4\n#define USART1_TDR USART1_DR\n#define USART1_RDR USART1_DR\n#endif\n\nstatic int ibusfunc(int len);\nstatic int sportfunc(int len);\nstatic int (*iofunc)(int len);\nstatic char iobuf[16];\n\nvoid inittelem(void) {\n\tUSART1_BRR = CLK_CNT(115200);\n\tswitch (telmode) {\n\t\tcase 2: // iBUS\n\t\t\tiofunc = ibusfunc;\n#ifndef AT32F4\n\t\t\tUSART1_RTOR = 12; // TX delay ~100us\n\t\t\tUSART1_CR2 = USART_CR2_RTOEN;\n#endif\n\t\t\tbreak;\n\t\tcase 3: // S.Port\n\t\t\tiofunc = sportfunc;\n\t\t\tUSART1_BRR = CLK_CNT(57600);\n#ifndef AT32F4\n\t\t\tUSART1_RTOR = 26; // TX delay ~450us\n\t\t\tUSART1_CR2 = USART_CR2_RTOEN | USART_CR2_RXINV | USART_CR2_TXINV;\n\t\t\tGPIOB_PUPDR = (GPIOB_PUPDR & ~0x3000) | 0x2000; // B6 (pull-down)\n#endif\n\t\t\tbreak;\n\t\tcase 4: // CRSF\n\t\t\tUSART1_BRR = CLK_CNT(416666);\n\t\t\tbreak;\n\t}\n\tif (iofunc) {\n\t\tUSART1_CR3 = USART_CR3_HDSEL | USART_CR3_DMAT | USART_CR3_DMAR;\n\t\tUSART1_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_IDLEIE;\n\t} else {\n\t\tUSART1_CR3 = USART_CR3_HDSEL | USART_CR3_DMAT;\n\t\tUSART1_CR1 = USART_CR1_UE | USART_CR1_TE;\n\t}\n\tDMA_CPAR(USART1_DMA_BASE, USART1_RX_DMA) = (uint32_t)&USART1_RDR;\n\tDMA_CMAR(USART1_DMA_BASE, USART1_RX_DMA) = (uint32_t)iobuf;\n\tDMA_CPAR(USART1_DMA_BASE, USART1_TX_DMA) = (uint32_t)&USART1_TDR;\n\tDMA_CMAR(USART1_DMA_BASE, USART1_TX_DMA) = (uint32_t)iobuf;\n}\n\nvoid usart1_isr(void) {\n\tint cr = USART1_CR1;\n\tif (cr & USART_CR1_TCIE) goto reading;\n#ifdef AT32F4\n\tUSART1_SR, USART1_DR; // Clear flags\n#else\n\tUSART1_RQR = USART_RQR_RXFRQ; // Clear RXNE\n\tUSART1_ICR = USART_ICR_IDLECF | USART_ICR_ORECF | USART_ICR_RTOCF;\n#endif\n\tint len = iofunc(sizeof iobuf - DMA_CNDTR(USART1_DMA_BASE, USART1_RX_DMA));\n\tif (len) {\n#ifdef AT32F4\n\t\tUSART1_SR = ~USART_SR_TC;\n#else\n\t\tUSART1_ICR = USART_ICR_TCCF;\n#endif\n\t\tUSART1_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_TCIE;\n\t\tDMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) = 0;\n\t\tDMA_CNDTR(USART1_DMA_BASE, USART1_TX_DMA) = len;\n\t\tDMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) = DMA_CCR_EN | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n\t\treturn;\n\t}\nreading:\n#ifdef AT32F4\n\tUSART1_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_IDLEIE;\n#else\n\tUSART1_CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_RTOIE;\n#endif\n\tDMA_CCR(USART1_DMA_BASE, USART1_RX_DMA) = 0;\n\tDMA_CNDTR(USART1_DMA_BASE, USART1_RX_DMA) = sizeof iobuf;\n\tDMA_CCR(USART1_DMA_BASE, USART1_RX_DMA) = DMA_CCR_EN | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n}\n\nvoid usart1_tx_dma_isr(void) {\n\tDMA_IFCR(USART1_DMA_BASE) = DMA_IFCR_CTCIF(USART1_TX_DMA);\n\tDMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) = 0;\n}\n\nstatic int ibusresp(char a, int x) {\n\tchar b = x, c = x >> 8;\n\tint u = 0xfff9 - a - b - c;\n\tiobuf[0] = 6;\n\tiobuf[1] = a;\n\tiobuf[2] = b;\n\tiobuf[3] = c;\n\tiobuf[4] = u;\n\tiobuf[5] = u >> 8;\n\treturn 6;\n}\n\nstatic int ibusfunc(int len) {\n\tstatic const uint16_t type[] = {0x201, 0x201, 0x203, 0x205, 0x206, 0x202};\n\tif (len != 4 || iobuf[0] != 4) return 0; // Invalid frame\n\tchar a = iobuf[1];\n\tif (a + (iobuf[2] | iobuf[3] << 8) != 0xfffb) return 0; // Invalid checksum\n\tint n = (a & 0xf) - (cfg.telem_phid - 1) * 6 - 1;\n\tif (n < 0 || n > 5) return 0;\n\tswitch (a >> 4) {\n\t\tcase 0x8: return 4; // Probe\n\t\tcase 0x9: return ibusresp(a, type[n]); // Type\n\t\tcase 0xa: // Value\n\t\t\tswitch (n) {\n\t\t\t\tcase 0: return ibusresp(a, (temp1 + 40) * 10);\n\t\t\t\tcase 1: return ibusresp(a, (temp2 + 40) * 10);\n\t\t\t\tcase 2: return ibusresp(a, volt);\n\t\t\t\tcase 3: return ibusresp(a, curr);\n\t\t\t\tcase 4: return ibusresp(a, csum);\n\t\t\t\tcase 5: return ibusresp(a, min(erpm / (cfg.telem_poles >> 1), 0xffff));\n\t\t\t}\n\t}\n\treturn 0;\n}\n\nstatic void sportbyte(int *crc, int *pos, char b) {\n\t*crc += b;\n\t*crc += *crc >> 8;\n\t*crc &= 0xff;\n\tif (b == 0x7d || b == 0x7e) { // Byte stuffing\n\t\tb &= ~0x20;\n\t\tiobuf[(*pos)++] = 0x7d;\n\t}\n\tiobuf[(*pos)++] = b;\n}\n\nstatic int sportresp(int t, int v) {\n\tint crc = 0, pos = 0;\n\tsportbyte(&crc, &pos, 0x10);\n\tsportbyte(&crc, &pos, t);\n\tsportbyte(&crc, &pos, t >> 8);\n\tsportbyte(&crc, &pos, v);\n\tsportbyte(&crc, &pos, v >> 8);\n\tsportbyte(&crc, &pos, v >> 16);\n\tsportbyte(&crc, &pos, v >> 24);\n\tsportbyte(&crc, &pos, 0xff - crc);\n\treturn pos;\n}\n\nstatic int sportfunc(int len) {\n\tstatic const uint16_t type[] = {0xb70, 0x400, 0x210, 0x200, 0xb30, 0x500};\n\tstatic int n;\n\tif (len != 2 || iobuf[0] != 0x7e) return 0; // Invalid frame\n\tif ((iobuf[1] & 0x1f) != cfg.telem_phid - 1) return 0;\n\tif (n == 6) n = 0;\n\tint t = type[n];\n\tswitch (n++) {\n\t\tcase 0: return sportresp(t, temp1);\n\t\tcase 1: return sportresp(t, temp2);\n\t\tcase 2: return sportresp(t, volt);\n\t\tcase 3: return sportresp(t, curr * 205 >> 11);\n\t\tcase 4: return sportresp(t, csum);\n\t\tcase 5: return sportresp(t, erpm / (cfg.telem_poles >> 1));\n\t}\n\treturn 0;\n}\n\nvoid kisstelem(void) {\n\tif (DMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) & DMA_CCR_EN) return;\n\tint r = erpm * 41 >> 12;\n\tiobuf[0] = temp1;\n\tiobuf[1] = volt >> 8;\n\tiobuf[2] = volt;\n\tiobuf[3] = curr >> 8;\n\tiobuf[4] = curr;\n\tiobuf[5] = csum >> 8;\n\tiobuf[6] = csum;\n\tiobuf[7] = r >> 8;\n\tiobuf[8] = r;\n\tiobuf[9] = crc8(iobuf, 9);\n\tDMA_CNDTR(USART1_DMA_BASE, USART1_TX_DMA) = 10;\n\tDMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n}\n\nstatic void crsftelem(void) {\n\tstatic int n;\n\tint a, b, len = 0;\n\tif (DMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) & DMA_CCR_EN) return;\n\tiobuf[0] = 0xc8;\n\tswitch (n++) {\n\t\tcase 0: // Temperature\n\t\t\ta = temp1 * 10;\n\t\t\tb = temp2 * 10;\n\t\t\tiobuf[1] = 0x07;\n\t\t\tiobuf[2] = 0x0d;\n\t\t\tiobuf[3] = 0;\n\t\t\tiobuf[4] = a >> 8;\n\t\t\tiobuf[5] = a;\n\t\t\tiobuf[6] = b >> 8;\n\t\t\tiobuf[7] = b;\n\t\t\tiobuf[8] = crc8dvbs2(iobuf + 2, 6);\n\t\t\tlen = 9;\n\t\t\tbreak;\n\t\tcase 1: // Battery\n\t\t\ta = volt * 205 >> 11;\n\t\t\tb = curr * 205 >> 11;\n\t\t\tiobuf[1] = 0x0a;\n\t\t\tiobuf[2] = 0x08;\n\t\t\tiobuf[3] = a >> 8;\n\t\t\tiobuf[4] = a;\n\t\t\tiobuf[5] = b >> 8;\n\t\t\tiobuf[6] = b;\n\t\t\tiobuf[7] = csum >> 16;\n\t\t\tiobuf[8] = csum >> 8;\n\t\t\tiobuf[9] = csum;\n\t\t\tiobuf[10] = 0;\n\t\t\tiobuf[11] = crc8dvbs2(iobuf + 2, 9);\n\t\t\tlen = 12;\n\t\t\tbreak;\n\t\tcase 2: // RPM\n\t\t\ta = erpm / (cfg.telem_poles >> 1);\n\t\t\tiobuf[1] = 0x06;\n\t\t\tiobuf[2] = 0x0c;\n\t\t\tiobuf[3] = 0;\n\t\t\tiobuf[4] = a >> 16;\n\t\t\tiobuf[5] = a >> 8;\n\t\t\tiobuf[6] = a;\n\t\t\tiobuf[7] = crc8dvbs2(iobuf + 2, 5);\n\t\t\tlen = 8;\n\t\t\tn = 0;\n\t\t\tbreak;\n\t}\n\tDMA_CNDTR(USART1_DMA_BASE, USART1_TX_DMA) = len;\n\tDMA_CCR(USART1_DMA_BASE, USART1_TX_DMA) = DMA_CCR_EN | DMA_CCR_TCIE | DMA_CCR_DIR | DMA_CCR_MINC | DMA_CCR_PSIZE_8BIT | DMA_CCR_MSIZE_8BIT;\n}\n\nvoid autotelem(void) {\n\tstatic int n;\n\tint x = 0;\n\tswitch (telmode) {\n\t\tcase 1: // KISS\n\t\t\tkisstelem();\n\t\t\tbreak;\n\t\tcase 4: // CRSF\n\t\t\tcrsftelem();\n\t\t\tbreak;\n\t}\n\tif (!dshotext) return;\n\tswitch (n++) { // Extended DSHOT telemetry\n\t\tcase 0:\n\t\t\tx = 0x200 | (temp1 & 0xff); // ESC temperature (C)\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tx = 0x800 | (temp2 & 0xff); // Motor temperature (C)\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tx = 0x400 | ((volt * 41 >> 10) & 0xff); // Voltage (V/4)\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tx = 0x600 | ((curr * 41 >> 12) & 0xff); // Current (A)\n\t\t\tn = 0;\n\t\t\tbreak;\n\t}\n\t__disable_irq();\n\tif (!dshotval) dshotval = x;\n\t__enable_irq();\n}\n"
  },
  {
    "path": "src/util.c",
    "content": "/*\n** Copyright (C) Arseny Vakhrushev <arseny.vakhrushev@me.com>\n**\n** This firmware is free software: you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n**\n** This firmware is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this firmware. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"common.h\"\n\n#ifndef HALL_MAP\n#elif HALL_MAP == 0xAFB35\n#define HALL1_PORT A\n#define HALL1_PIN1 15\n#define HALL2_PORT B\n#define HALL2_PIN2 3\n#define HALL2_PIN3 5\n#elif HALL_MAP == 0xB357\n#define HALL_PORT B\n#define HALL_PIN1 3\n#define HALL_PIN2 5\n#define HALL_PIN3 7\n#elif HALL_MAP == 0xB358\n#define HALL_PORT B\n#define HALL_PIN1 3\n#define HALL_PIN2 5\n#define HALL_PIN3 8\n#elif HALL_MAP == 0xB450\n#define HALL_PORT B\n#define HALL_PIN1 4\n#define HALL_PIN2 5\n#define HALL_PIN3 0\n#endif\n\n#ifndef BEC_MAP\n#elif BEC_MAP == 0xA45\n#define BEC_PORT A\n#define BEC_PIN1 4\n#define BEC_PIN2 5\n#elif BEC_MAP == 0xB35\n#define BEC_PORT B\n#define BEC_PIN1 3\n#define BEC_PIN2 5\n#elif BEC_MAP == 0xCEF\n#define BEC_PORT C\n#define BEC_PIN1 14\n#define BEC_PIN2 15\n#endif\n\n#ifndef LED_MAP\n#elif LED_MAP == 0xAF\n#define LED1_PORT A\n#define LED1_PIN 15\n#elif LED_MAP == 0xB8\n#define LED1_PORT B\n#define LED1_PIN 8\n#elif LED_MAP == 0xF2AF\n#define LED1_PORT F\n#define LED1_PIN 2\n#define LED2_PORT A\n#define LED2_PIN 15\n#elif LED_MAP == 0xAFB3B4\n#define LED1_PORT A\n#define LED1_PIN 15\n#define LED2_PORT B\n#define LED2_PIN 3\n#define LED3_PORT B\n#define LED3_PIN 4\n#elif LED_MAP == 0xAFB5B3\n#define LED1_PORT A\n#define LED1_PIN 15\n#define LED2_PORT B\n#define LED2_PIN 5\n#define LED3_PORT B\n#define LED3_PIN 3\n#elif LED_MAP == 0xB5B3AF\n#define LED1_PORT B\n#define LED1_PIN 5\n#define LED2_PORT B\n#define LED2_PIN 3\n#define LED3_PORT A\n#define LED3_PIN 15\n#elif LED_MAP == 0xB5B4B3\n#define LED1_PORT B\n#define LED1_PIN 5\n#define LED2_PORT B\n#define LED2_PIN 4\n#define LED3_PORT B\n#define LED3_PIN 3\n#elif LED_MAP == 0xB8B5B3\n#define LED1_PORT B\n#define LED1_PIN 8\n#define LED2_PORT B\n#define LED2_PIN 5\n#define LED3_PORT B\n#define LED3_PIN 3\n#endif\n\n#ifdef LED_INV\n#define LED1_INV\n#define LED2_INV\n#define LED3_INV\n#endif\n\n#ifdef LED_OD\n#define LED1_OD\n#define LED2_OD\n#define LED3_OD\n#endif\n\n#ifndef FLASH_CR_STRT\n#define FLASH_CR_STRT FLASH_CR_START\n#endif\n\nstatic char busy;\n\nvoid initgpio(void) {\n#if defined HALL_MAP && !defined USE_XOR\n#ifdef HALL1_PORT\n#ifdef HALL2_PIN2\n\tGPIO(HALL1_PORT, PUPDR) |= 1 << HALL1_PIN1 * 2;\n\tGPIO(HALL2_PORT, PUPDR) |= 1 << HALL2_PIN2 * 2 | 1 << HALL2_PIN3 * 2;\n\tGPIO(HALL1_PORT, MODER) &= ~(3 << HALL1_PIN1 * 2);\n\tGPIO(HALL2_PORT, MODER) &= ~(3 << HALL2_PIN2 * 2 | 3 << HALL2_PIN3 * 2);\n#else\n\tGPIO(HALL1_PORT, PUPDR) |= 1 << HALL1_PIN1 * 2 | 1 << HALL1_PIN2 * 2;\n\tGPIO(HALL2_PORT, PUPDR) |= 1 << HALL2_PIN3 * 2;\n\tGPIO(HALL1_PORT, MODER) &= ~(3 << HALL1_PIN1 * 2 | 3 << HALL1_PIN2 * 2);\n\tGPIO(HALL2_PORT, MODER) &= ~(3 << HALL2_PIN3 * 2);\n#endif\n#else\n\tGPIO(HALL_PORT, PUPDR) |= 1 << HALL_PIN1 * 2 | 1 << HALL_PIN2 * 2 | 1 << HALL_PIN3 * 2;\n\tGPIO(HALL_PORT, MODER) &= ~(3 << HALL_PIN1 * 2 | 3 << HALL_PIN2 * 2 | 3 << HALL_PIN3 * 2);\n#endif\n#endif\n#ifdef BEC_MAP\n\tint x = cfg.bec - BEC_MIN;\n#if BEC_MAP == 0xADE // SWD pins\n\tif (!(GPIOA_IDR & 0x6000)) { // External pull-down\n\t\tGPIOA_ODR |= (x & 3) << 13;\n\t\tGPIOA_OSPEEDR &= ~0x3c000000; // A13,A14 (low speed)\n\t\tGPIOA_PUPDR &= ~0x3c000000; // A13,A14 (no pull-up/pull-down)\n\t\tGPIOA_MODER ^= 0x3c000000; // A13,A14 (output)\n\t}\n#else\n\tint y = GPIO(BEC_PORT, ODR) | (x & 1) << BEC_PIN1;\n\tint z = GPIO(BEC_PORT, MODER) & ~(2 << BEC_PIN1 * 2);\n#ifdef BEC_PIN2\n#if BEC_PIN2 >= 1\n\ty |= (x & 2) << (BEC_PIN2 - 1);\n#else\n\ty |= (x & 2) >> (1 - BEC_PIN2);\n#endif\n\tz &= ~(2 << BEC_PIN2 * 2);\n#ifdef BEC_PIN3\n#if BEC_PIN3 >= 2\n\ty |= (x & 4) << (BEC_PIN3 - 2);\n#else\n\ty |= (x & 4) >> (2 - BEC_PIN3);\n#endif\n\tz &= ~(2 << BEC_PIN3 * 2);\n#endif\n#endif\n\tGPIO(BEC_PORT, ODR) = y;\n\tGPIO(BEC_PORT, MODER) = z;\n#endif\n#endif\n#ifdef ERPM_PIN\n\tGPIO(ERPM_PORT, MODER) = (GPIO(ERPM_PORT, MODER) & ~(3 << ERPM_PIN * 2)) | 1 << ERPM_PIN * 2;\n#endif\n#ifdef PARK_PIN\n\tGPIO(PARK_PORT, PUPDR) |= 1 << PARK_PIN * 2;\n\tGPIO(PARK_PORT, MODER) &= ~(3 << PARK_PIN * 2);\n#endif\n}\n\n__attribute__((__weak__))\nvoid initled(void) {\n#ifdef LED1_PORT\n#ifdef LED1_INV\n\tGPIO(LED1_PORT, ODR) |= 1 << LED1_PIN;\n#endif\n#ifdef LED1_OD\n\tGPIO(LED1_PORT, OTYPER) |= 1 << LED1_PIN;\n#endif\n\tGPIO(LED1_PORT, MODER) &= ~(2 << LED1_PIN * 2);\n#endif\n#ifdef LED2_PORT\n#ifdef LED2_INV\n\tGPIO(LED2_PORT, ODR) |= 1 << LED2_PIN;\n#endif\n#ifdef LED2_OD\n\tGPIO(LED2_PORT, OTYPER) |= 1 << LED2_PIN;\n#endif\n\tGPIO(LED2_PORT, MODER) &= ~(2 << LED2_PIN * 2);\n#endif\n#ifdef LED3_PORT\n#ifdef LED3_INV\n\tGPIO(LED3_PORT, ODR) |= 1 << LED3_PIN;\n#endif\n#ifdef LED3_OD\n\tGPIO(LED3_PORT, OTYPER) |= 1 << LED3_PIN;\n#endif\n\tGPIO(LED3_PORT, MODER) &= ~(2 << LED3_PIN * 2);\n#endif\n#ifdef LED4_PORT\n#ifdef LED4_INV\n\tGPIO(LED4_PORT, ODR) |= 1 << LED4_PIN;\n#endif\n#ifdef LED4_OD\n\tGPIO(LED4_PORT, OTYPER) |= 1 << LED4_PIN;\n#endif\n\tGPIO(LED4_PORT, MODER) &= ~(2 << LED4_PIN * 2);\n#endif\n}\n\n#ifdef HALL_MAP\nint hallcode(void) {\n#ifdef HALL1_PORT\n\tint x1 = GPIO(HALL1_PORT, IDR);\n\tint x2 = GPIO(HALL2_PORT, IDR);\n#ifdef HALL2_PIN2\n#if HALL2_PIN3 >= 2\n#if HALL2_PIN2 >= 1\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x2 & (1 << HALL2_PIN2)) >> (HALL2_PIN2 - 1) | (x2 & (1 << HALL2_PIN3)) >> (HALL2_PIN3 - 2);\n#else\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x2 & (1 << HALL2_PIN2)) << (1 - HALL2_PIN2) | (x2 & (1 << HALL2_PIN3)) >> (HALL2_PIN3 - 2);\n#endif\n#else\n#if HALL2_PIN2 >= 1\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x2 & (1 << HALL2_PIN2)) >> (HALL2_PIN2 - 1) | (x2 & (1 << HALL2_PIN3)) << (2 - HALL2_PIN3);\n#else\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x2 & (1 << HALL2_PIN2)) << (1 - HALL2_PIN2) | (x2 & (1 << HALL2_PIN3)) << (2 - HALL2_PIN3);\n#endif\n#endif\n#else\n#if HALL2_PIN3 >= 2\n#if HALL1_PIN2 >= 1\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x1 & (1 << HALL1_PIN2)) >> (HALL1_PIN2 - 1) | (x2 & (1 << HALL2_PIN3)) >> (HALL2_PIN3 - 2);\n#else\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x1 & (1 << HALL1_PIN2)) << (1 - HALL1_PIN2) | (x2 & (1 << HALL2_PIN3)) >> (HALL2_PIN3 - 2);\n#endif\n#else\n#if HALL1_PIN2 >= 1\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x1 & (1 << HALL1_PIN2)) >> (HALL1_PIN2 - 1) | (x2 & (1 << HALL2_PIN3)) << (2 - HALL2_PIN3);\n#else\n\treturn (x1 & (1 << HALL1_PIN1)) >> HALL1_PIN1 | (x1 & (1 << HALL1_PIN2)) << (1 - HALL1_PIN2) | (x2 & (1 << HALL2_PIN3)) << (2 - HALL2_PIN3);\n#endif\n#endif\n#endif\n#else\n\tint x = GPIO(HALL_PORT, IDR);\n#if HALL_PIN3 >= 2\n#if HALL_PIN2 >= 1\n\treturn (x & (1 << HALL_PIN1)) >> HALL_PIN1 | (x & (1 << HALL_PIN2)) >> (HALL_PIN2 - 1) | (x & (1 << HALL_PIN3)) >> (HALL_PIN3 - 2);\n#else\n\treturn (x & (1 << HALL_PIN1)) >> HALL_PIN1 | (x & (1 << HALL_PIN2)) << (1 - HALL_PIN2) | (x & (1 << HALL_PIN3)) >> (HALL_PIN3 - 2);\n#endif\n#else\n#if HALL_PIN2 >= 1\n\treturn (x & (1 << HALL_PIN1)) >> HALL_PIN1 | (x & (1 << HALL_PIN2)) >> (HALL_PIN2 - 1) | (x & (1 << HALL_PIN3)) << (2 - HALL_PIN3);\n#else\n\treturn (x & (1 << HALL_PIN1)) >> HALL_PIN1 | (x & (1 << HALL_PIN2)) << (1 - HALL_PIN2) | (x & (1 << HALL_PIN3)) << (2 - HALL_PIN3);\n#endif\n#endif\n#endif\n}\n#endif\n\n__attribute__((__weak__))\nvoid ledctl(int x) {\n#ifdef LED1_PORT\n#ifdef LED1_INV\n\tGPIO(LED1_PORT, BSRR) = x & 1 ? 1 << (LED1_PIN + 16) : 1 << LED1_PIN;\n#else\n\tGPIO(LED1_PORT, BSRR) = x & 1 ? 1 << LED1_PIN : 1 << (LED1_PIN + 16);\n#endif\n#endif\n#ifdef LED2_PORT\n#ifdef LED2_INV\n\tGPIO(LED2_PORT, BSRR) = x & 2 ? 1 << (LED2_PIN + 16) : 1 << LED2_PIN;\n#else\n\tGPIO(LED2_PORT, BSRR) = x & 2 ? 1 << LED2_PIN : 1 << (LED2_PIN + 16);\n#endif\n#endif\n#ifdef LED3_PORT\n#ifdef LED3_INV\n\tGPIO(LED3_PORT, BSRR) = x & 4 ? 1 << (LED3_PIN + 16) : 1 << LED3_PIN;\n#else\n\tGPIO(LED3_PORT, BSRR) = x & 4 ? 1 << LED3_PIN : 1 << (LED3_PIN + 16);\n#endif\n#endif\n#ifdef LED4_PORT\n#ifdef LED4_INV\n\tGPIO(LED4_PORT, BSRR) = x & 8 ? 1 << (LED4_PIN + 16) : 1 << LED4_PIN;\n#else\n\tGPIO(LED4_PORT, BSRR) = x & 8 ? 1 << LED4_PIN : 1 << (LED4_PIN + 16);\n#endif\n#endif\n}\n\n__attribute__((__weak__))\nvoid hsictl(int x) {\n\tint cr = RCC_CR;\n\tint tv = (cr & 0xf8) >> 3; // 5 bits\n\tRCC_CR = (cr & ~0xf8) | clamp(tv + x, 0, 0x1f) << 3;\n}\n\nchar crc8(const char *buf, int len) {\n\tstatic const char tbl[] = {\n\t\t0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d,\n\t\t0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d,\n\t\t0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,\n\t\t0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd,\n\t\t0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea,\n\t\t0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a,\n\t\t0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a,\n\t\t0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a,\n\t\t0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4,\n\t\t0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4,\n\t\t0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44,\n\t\t0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34,\n\t\t0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63,\n\t\t0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13,\n\t\t0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83,\n\t\t0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3,\n\t};\n\tchar crc = 0;\n\twhile (len--) crc = tbl[crc ^ *buf++];\n\treturn crc;\n}\n\nchar crc8dvbs2(const char *buf, int len) {\n\tstatic const char tbl[] = {\n\t\t0x00, 0xd5, 0x7f, 0xaa, 0xfe, 0x2b, 0x81, 0x54, 0x29, 0xfc, 0x56, 0x83, 0xd7, 0x02, 0xa8, 0x7d,\n\t\t0x52, 0x87, 0x2d, 0xf8, 0xac, 0x79, 0xd3, 0x06, 0x7b, 0xae, 0x04, 0xd1, 0x85, 0x50, 0xfa, 0x2f,\n\t\t0xa4, 0x71, 0xdb, 0x0e, 0x5a, 0x8f, 0x25, 0xf0, 0x8d, 0x58, 0xf2, 0x27, 0x73, 0xa6, 0x0c, 0xd9,\n\t\t0xf6, 0x23, 0x89, 0x5c, 0x08, 0xdd, 0x77, 0xa2, 0xdf, 0x0a, 0xa0, 0x75, 0x21, 0xf4, 0x5e, 0x8b,\n\t\t0x9d, 0x48, 0xe2, 0x37, 0x63, 0xb6, 0x1c, 0xc9, 0xb4, 0x61, 0xcb, 0x1e, 0x4a, 0x9f, 0x35, 0xe0,\n\t\t0xcf, 0x1a, 0xb0, 0x65, 0x31, 0xe4, 0x4e, 0x9b, 0xe6, 0x33, 0x99, 0x4c, 0x18, 0xcd, 0x67, 0xb2,\n\t\t0x39, 0xec, 0x46, 0x93, 0xc7, 0x12, 0xb8, 0x6d, 0x10, 0xc5, 0x6f, 0xba, 0xee, 0x3b, 0x91, 0x44,\n\t\t0x6b, 0xbe, 0x14, 0xc1, 0x95, 0x40, 0xea, 0x3f, 0x42, 0x97, 0x3d, 0xe8, 0xbc, 0x69, 0xc3, 0x16,\n\t\t0xef, 0x3a, 0x90, 0x45, 0x11, 0xc4, 0x6e, 0xbb, 0xc6, 0x13, 0xb9, 0x6c, 0x38, 0xed, 0x47, 0x92,\n\t\t0xbd, 0x68, 0xc2, 0x17, 0x43, 0x96, 0x3c, 0xe9, 0x94, 0x41, 0xeb, 0x3e, 0x6a, 0xbf, 0x15, 0xc0,\n\t\t0x4b, 0x9e, 0x34, 0xe1, 0xb5, 0x60, 0xca, 0x1f, 0x62, 0xb7, 0x1d, 0xc8, 0x9c, 0x49, 0xe3, 0x36,\n\t\t0x19, 0xcc, 0x66, 0xb3, 0xe7, 0x32, 0x98, 0x4d, 0x30, 0xe5, 0x4f, 0x9a, 0xce, 0x1b, 0xb1, 0x64,\n\t\t0x72, 0xa7, 0x0d, 0xd8, 0x8c, 0x59, 0xf3, 0x26, 0x5b, 0x8e, 0x24, 0xf1, 0xa5, 0x70, 0xda, 0x0f,\n\t\t0x20, 0xf5, 0x5f, 0x8a, 0xde, 0x0b, 0xa1, 0x74, 0x09, 0xdc, 0x76, 0xa3, 0xf7, 0x22, 0x88, 0x5d,\n\t\t0xd6, 0x03, 0xa9, 0x7c, 0x28, 0xfd, 0x57, 0x82, 0xff, 0x2a, 0x80, 0x55, 0x01, 0xd4, 0x7e, 0xab,\n\t\t0x84, 0x51, 0xfb, 0x2e, 0x7a, 0xaf, 0x05, 0xd0, 0xad, 0x78, 0xd2, 0x07, 0x53, 0x86, 0x2c, 0xf9,\n\t};\n\tchar crc = 0;\n\twhile (len--) crc = tbl[crc ^ *buf++];\n\treturn crc;\n}\n\nint scale(int x, int a1, int a2, int b1, int b2) {\n\tif (x <= a1) return b1;\n\tif (x >= a2) return b2;\n\treturn b1 + (x - a1) * (b2 - b1) / (a2 - a1);\n}\n\nint smooth(int *s, int x, int n) {\n\tint q;\n\tif (x < 0) return 0; // Sanity check\n\tif ((q = *s) < 0) *s = q = x << n; // Initialize state\n\treturn (*s = x + q - (q >> n)) >> n;\n}\n\nvoid initpid(PID *pid, int x) {\n\tpid->i = 0;\n\tpid->x = x;\n}\n\nint calcpid(PID *pid, int x, int y) {\n\tint p = x - y; // Proportional error\n\tint l = pid->Li; // Integral error limit\n\tint i = clamp(pid->i + p, -l, l); // Integral error\n\tint d = x - pid->x; // Derivative error\n\tpid->i = i;\n\tpid->x = x;\n\treturn pid->Kp * p + pid->Ki * i + pid->Kd * d;\n}\n\nvoid checkcfg(void) {\n#ifndef ANALOG\n#ifndef ANALOG_CHAN\n\tif (IO_ANALOG) cfg.arm = 1; // Ensure low level on startup\n\telse\n#endif\n\tcfg.arm = !!cfg.arm;\n#else\n\tcfg.arm = 0;\n#endif\n#ifdef PWM_ENABLE\n\tcfg.damp = 1;\n#else\n\tcfg.damp = !!cfg.damp;\n#endif\n\tcfg.revdir = !!cfg.revdir;\n\tcfg.brushed = !!cfg.brushed;\n\tcfg.timing = clamp(cfg.timing, 1, 31);\n\tcfg.sine_range = cfg.sine_range && !cfg.brushed ? clamp(cfg.sine_range, 5, 25) : 0;\n\tcfg.sine_power = clamp(cfg.sine_power, 1, 15);\n\tcfg.freq_min = clamp(cfg.freq_min, 16, 48);\n\tcfg.freq_max = clamp(cfg.freq_max, cfg.freq_min, 96);\n\tcfg.duty_min = clamp(cfg.duty_min, 1, 100);\n\tcfg.duty_max = clamp(cfg.duty_max, cfg.duty_min, 100);\n\tcfg.duty_spup = clamp(cfg.duty_spup, 1, 100);\n\tcfg.duty_ramp = clamp(cfg.duty_ramp, 0, 100);\n\tcfg.duty_rate = clamp(cfg.duty_rate, 1, 100);\n\tcfg.duty_drag = clamp(cfg.duty_drag, 0, 100);\n\tcfg.duty_lock = clamp(cfg.duty_lock, 0, cfg.brushed ? 0 : 2);\n\tcfg.throt_mode = clamp(cfg.throt_mode, 0, IO_ANALOG ? 0 : cfg.duty_lock ? 1 : 3);\n\tcfg.throt_rev = clamp(cfg.throt_rev, 0, 3);\n\tcfg.throt_brk = clamp(cfg.throt_brk, cfg.duty_drag, 100);\n\tcfg.throt_set = clamp(cfg.throt_set, 0, cfg.arm ? 0 : 100);\n\tcfg.throt_ztc = !!cfg.throt_ztc;\n\tcfg.throt_cal = !!cfg.throt_cal;\n\tcfg.throt_min = clamp(cfg.throt_min, 900, 1900);\n\tcfg.throt_max = clamp(cfg.throt_max, cfg.throt_min + 200, 2100);\n\tcfg.throt_mid = clamp(cfg.throt_mid, cfg.throt_min + 100, cfg.throt_max - 100);\n\tcfg.analog_min = clamp(cfg.analog_min, 0, 3200);\n\tcfg.analog_max = clamp(cfg.analog_max, cfg.analog_min + 200, 3400);\n#ifdef IO_PA2\n\tcfg.input_mode = clamp(cfg.input_mode, 0, 5);\n\tcfg.input_ch1 = clamp(cfg.input_ch1, 1, cfg.input_mode < 3 ? 0 : cfg.input_mode == 3 ? 14 : 16);\n\tcfg.input_ch2 = clamp(cfg.input_ch2, 0, cfg.input_mode < 3 ? 0 : cfg.input_mode == 3 ? 14 : 16);\n#else\n#if defined IO_PA6 || defined ANALOG_CHAN\n\tcfg.input_mode = clamp(cfg.input_mode, 0, 1);\n#else\n\tcfg.input_mode = 0;\n#endif\n\tcfg.input_ch1 = 0;\n\tcfg.input_ch2 = 0;\n#endif\n\tcfg.telem_mode = clamp(cfg.telem_mode, 0, 4);\n\tcfg.telem_phid =\n\t\tcfg.telem_mode == 2 ? clamp(cfg.telem_phid, 1, 2):\n\t\tcfg.telem_mode == 3 ? clamp(cfg.telem_phid, 1, 28):\n\t\tcfg.input_mode == 4 ? clamp(cfg.telem_phid, 0, 4) : 0;\n\tcfg.telem_poles = clamp(cfg.telem_poles & ~1, 2, 100);\n\tcfg.prot_stall = cfg.prot_stall && !cfg.brushed ? clamp(cfg.prot_stall, 1500, 3500) : 0;\n\tcfg.prot_temp = cfg.prot_temp ? clamp(cfg.prot_temp, 60, 140) : 0;\n#if SENS_CNT >= 3\n\tcfg.prot_sens = clamp(cfg.prot_sens, 0, 2);\n#else\n\tcfg.prot_sens = 0;\n#endif\n#if SENS_CNT >= 1 && VOLT_MUL > 0\n\tcfg.prot_volt = cfg.prot_volt ? clamp(cfg.prot_volt, 28, 38) : 0;\n\tcfg.prot_cells = clamp(cfg.prot_cells, 0, 24);\n#else\n\tcfg.prot_volt = 0;\n\tcfg.prot_cells = 0;\n#endif\n#if SENS_CNT >= 2 && CURR_MUL > 0\n\tcfg.prot_curr = clamp(cfg.prot_curr, 0, 999);\n#else\n\tcfg.prot_curr = 0;\n#endif\n#ifdef PARK_PIN\n\tcfg.prot_park = clamp(cfg.prot_park, 0, 4);\n#else\n\tcfg.prot_park = 0;\n#endif\n\tcfg.volume = clamp(cfg.volume, 0, 100);\n\tcfg.beacon = clamp(cfg.beacon, 0, 100);\n#ifdef BEC_MAP\n\tcfg.bec = clamp(cfg.bec, BEC_MIN, BEC_MAX);\n#else\n\tcfg.bec = 0;\n#endif\n#if LED_CNT > 0\n\tcfg.led &= (1 << LED_CNT) - 1;\n#else\n\tcfg.led = 0;\n#endif\n}\n\nint savecfg(void) {\n\tif (ertm || busy) return 0;\n\t__disable_irq();\n\tFLASH_KEYR = FLASH_KEYR_KEY1;\n\tFLASH_KEYR = FLASH_KEYR_KEY2;\n\tFLASH_SR = -1; // Clear errors\n\tFLASH_CR = FLASH_CR_PER;\n#ifdef STM32F0\n\tFLASH_AR = (uint32_t)_cfg;\n\tFLASH_CR = FLASH_CR_PER | FLASH_CR_STRT; // Erase page\n#else\n\tFLASH_CR = FLASH_CR_PER | FLASH_CR_STRT | ((uint32_t)(_cfg - _boot) >> 11) << FLASH_CR_PNB_SHIFT; // Erase page\n#endif\n\twhile (FLASH_SR & FLASH_SR_BSY);\n\tFLASH_CR = FLASH_CR_PG;\n#ifdef STM32F0\n#define T uint16_t\n#else\n#define T uint32_t\n#endif\n\tT *dst = (T *)_cfg;\n\tT *src = (T *)_cfg_start;\n\tT *end = (T *)_cfg_end;\n#undef T\n\twhile (src < end) { // Write data\n\t\t*dst++ = *src++;\n#ifndef STM32F0\n\t\t*dst++ = *src++;\n#endif\n\t\twhile (FLASH_SR & FLASH_SR_BSY);\n\t}\n\tFLASH_CR = FLASH_CR_LOCK;\n\t__enable_irq();\n#ifdef STM32F0\n\tif (FLASH_SR & (FLASH_SR_PGERR | FLASH_SR_WRPRTERR)) return 0;\n#else\n\tif (FLASH_SR & (FLASH_SR_PROGERR | FLASH_SR_WRPERR)) return 0;\n#endif\n\treturn !memcmp(_cfg, _cfg_start, _cfg_end - _cfg_start);\n}\n\nint resetcfg(void) {\n\t__disable_irq();\n\tmemcpy(&cfg, &cfgdata, sizeof cfgdata);\n\t__enable_irq();\n\tcheckcfg();\n\treturn savecfg();\n}\n\nvoid resetcom(void) {\n#ifdef PWM_ENABLE\n\tTIM1_CCMR1 = TIM_CCMR1_OC1M_FORCE_HIGH | TIM_CCMR1_OC2M_FORCE_HIGH;\n\tTIM1_CCMR2 = TIM_CCMR2_OC3M_FORCE_HIGH;\n\tint er = TIM_CCER_CC1NE | TIM_CCER_CC1NP | TIM_CCER_CC2NE | TIM_CCER_CC2NP | TIM_CCER_CC3NE | TIM_CCER_CC3NP;\n#else\n\tTIM1_CCMR1 = TIM_CCMR1_OC1M_FORCE_LOW | TIM_CCMR1_OC2M_FORCE_LOW;\n\tTIM1_CCMR2 = TIM_CCMR2_OC3M_FORCE_LOW;\n\tint er = TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE;\n#endif\n#ifdef INVERTED_HIGH\n\ter |= TIM_CCER_CC1P | TIM_CCER_CC2P | TIM_CCER_CC3P;\n#endif\n\tTIM1_CCER = er;\n\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n}\n\nstatic void delayf(void) {\n\tTIM6_EGR = TIM_EGR_UG; // Reset arming timeout\n\tif (!(TIM1_SR & TIM_SR_UIF)) return;\n\tTIM1_SR = ~TIM_SR_UIF;\n\tint a = TIM1_CCR1;\n\tint b = TIM1_CCR3;\n\tTIM1_CCR1 = b;\n\tTIM1_CCR3 = a;\n}\n\nint playmusic(const char *str, int vol) {\n\tstatic const uint16_t arr[] = {15287, 14429, 13619, 12856, 12133, 11452, 10810, 10203, 9630, 9090, 8579, 8097, 7643};\n\tchar *end;\n\tint tmp = strtol(str, &end, 10); // Tempo\n\tif (str == end) tmp = 125; // 120 BPM by default\n\telse {\n\t\tif (tmp < 10 || tmp > 999) return 0; // Sanity check\n\t\ttmp = 15000 / tmp;\n\t\tstr = end;\n\t}\n\tif (!vol || ertm || busy) return 0;\n\tbusy = 1;\n\tresetcom();\n#ifdef PWM_ENABLE\n\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2M_FORCE_LOW;\n\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM1;\n\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NP | TIM_CCER_CC2NE | TIM_CCER_CC2NP | TIM_CCER_CC3E | TIM_CCER_CC3NP;\n#else\n\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2M_FORCE_HIGH;\n\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM1;\n\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3E | TIM_CCER_CC3NE;\n#endif\n#ifdef INVERTED_HIGH\n\ter |= TIM_CCER_CC1P | TIM_CCER_CC2P | TIM_CCER_CC3P;\n#endif\n\tTIM1_CCER = er;\n\tTIM1_PSC = CLK_MHZ / 8 - 1; // 125ns resolution\n\tfor (int a, b, c = 0; (a = *str++);) {\n\t\tif (a >= 'a' && a <= 'g') a -= 'c', b = 0; // Low note\n\t\telse if (a >= 'A' && a <= 'G') a -= 'C', b = 1; // High note\n\t\telse if (a == '_') { // Pause\n\t\t\tTIM1_CCR1 = 0;\n\t\t\tTIM1_CCR3 = 0;\n\t\t\tgoto update;\n\t\t} else {\n\t\t\tif (a == '+' && !c++) continue; // Octave up\n\t\t\tif (a == '-' && c--) continue; // Octave down\n\t\t\tbreak; // Invalid specifier\n\t\t}\n\t\ta = (a + 7) % 7 << 1;\n\t\tif (a > 4) --a;\n\t\tif (*str == '#') ++a, ++str;\n\t\tTIM1_ARR = arr[a] >> (b + c); // Frequency\n\t\tTIM1_CCR1 = (DEAD_TIME + CLK_MHZ / 8 - 1) * 8 / CLK_MHZ + vol; // Volume\n\t\tTIM1_CCR3 = 0;\n\tupdate:\n\t\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n\t\ta = strtol(str, &end, 10); // Duration\n\t\tif (str == end) a = 1;\n\t\telse {\n\t\t\tif (a < 1 || a > 99) break; // Sanity check\n\t\t\tstr = end;\n\t\t}\n\t\tdelay(tmp * a, delayf);\n\t}\n\tTIM1_PSC = 0;\n\tTIM1_ARR = CLK_KHZ / 24 - 1;\n\tresetcom();\n\tbusy = 0;\n\treturn !str[-1];\n}\n\nvoid playsound(const char *buf, int vol) { // AU file format, 8-bit linear PCM, mono\n\tconst uint32_t *hdr = (const uint32_t *)buf;\n\tif (hdr[0] != 0x646e732e || hdr[3] != 0x2000000 || hdr[5] != 0x1000000 || !vol || ertm || busy) return;\n\tbusy = 1;\n\tresetcom();\n#ifdef PWM_ENABLE\n\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2M_FORCE_LOW;\n\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM1;\n\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NP | TIM_CCER_CC2NE | TIM_CCER_CC2NP | TIM_CCER_CC3E | TIM_CCER_CC3NP;\n#else\n\tTIM1_CCMR1 = TIM_CCMR1_OC1PE | TIM_CCMR1_OC1M_PWM1 | TIM_CCMR1_OC2M_FORCE_HIGH;\n\tTIM1_CCMR2 = TIM_CCMR2_OC3PE | TIM_CCMR2_OC3M_PWM1;\n\tint er = TIM_CCER_CC1E | TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3E | TIM_CCER_CC3NE;\n#endif\n#ifdef INVERTED_HIGH\n\ter |= TIM_CCER_CC1P | TIM_CCER_CC2P | TIM_CCER_CC3P;\n#endif\n\tTIM1_CCER = er;\n\tTIM1_CCR1 = 0;\n\tTIM1_CCR3 = 0;\n\tTIM1_ARR = CLK_KHZ / 24 - 1;\n\tTIM1_EGR = TIM_EGR_UG | TIM_EGR_COMG;\n\tTIM6_PSC = 0;\n\tTIM6_ARR = CLK_CNT(__builtin_bswap32(hdr[4])) - 1;\n\tTIM6_EGR = TIM_EGR_UG;\n\tTIM6_CR1 = TIM_CR1_CEN;\n\tbuf += __builtin_bswap32(hdr[1]);\n\tfor (int len = __builtin_bswap32(hdr[2]);;) {\n\t\tif (!(TIM6_SR & TIM_SR_UIF)) continue;\n\t\tTIM6_SR = ~TIM_SR_UIF;\n\t\tif (len-- <= 0) break;\n\t\tint8_t x = *buf++;\n\t\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE | TIM_CR1_UDIS;\n\t\tTIM1_CCR1 = DEAD_TIME + ((x + 128) * vol * CLK_MHZ >> 13);\n\t\tTIM1_CCR3 = DEAD_TIME + ((127 - x) * vol * CLK_MHZ >> 13);\n\t\tTIM1_CR1 = TIM_CR1_CEN | TIM_CR1_ARPE;\n\t}\n\tTIM6_CR1 = 0;\n\tresetcom();\n\tbusy = 0;\n}\n"
  }
]