Repository: purduesigbots/pros Branch: develop-pros-4 Commit: c0897ad1f709 Files: 204 Total size: 2.1 MB Directory structure: gitextract_74vec5n_/ ├── .arcconfig ├── .arclint ├── .clang-format ├── .github/ │ ├── CONTRIBUTING.md │ ├── ISSUE_TEMPLATE.md │ └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .gitmodules ├── .vs/ │ └── pros/ │ └── v16/ │ └── .suo ├── LICENSE ├── Makefile ├── README.md ├── STYLEGUIDE.md ├── VSCode.md ├── azure-build-libc.yaml ├── azure-pipelines.yml ├── common.mk ├── firmware/ │ ├── libc.a │ ├── libm.a │ ├── v5-common.ld │ ├── v5-hot.ld │ └── v5.ld ├── include/ │ ├── api.h │ ├── common/ │ │ ├── cobs.h │ │ ├── gid.h │ │ ├── linkedlist.h │ │ ├── set.h │ │ └── string.h │ ├── kapi.h │ ├── main.h │ ├── pros/ │ │ ├── abstract_motor.hpp │ │ ├── adi.h │ │ ├── adi.hpp │ │ ├── ai_vision.h │ │ ├── ai_vision.hpp │ │ ├── apix.h │ │ ├── colors.h │ │ ├── colors.hpp │ │ ├── device.h │ │ ├── device.hpp │ │ ├── distance.h │ │ ├── distance.hpp │ │ ├── error.h │ │ ├── ext_adi.h │ │ ├── gps.h │ │ ├── gps.hpp │ │ ├── imu.h │ │ ├── imu.hpp │ │ ├── link.h │ │ ├── link.hpp │ │ ├── llemu.h │ │ ├── llemu.hpp │ │ ├── misc.h │ │ ├── misc.hpp │ │ ├── motor_group.hpp │ │ ├── motors.h │ │ ├── motors.hpp │ │ ├── optical.h │ │ ├── optical.hpp │ │ ├── rotation.h │ │ ├── rotation.hpp │ │ ├── rtos.h │ │ ├── rtos.hpp │ │ ├── screen.h │ │ ├── screen.hpp │ │ ├── serial.h │ │ ├── serial.hpp │ │ ├── version.h │ │ ├── vision.h │ │ └── vision.hpp │ ├── rtos/ │ │ ├── FreeRTOS.h │ │ ├── FreeRTOSConfig.h │ │ ├── StackMacros.h │ │ ├── list.h │ │ ├── message_buffer.h │ │ ├── portable.h │ │ ├── portmacro.h │ │ ├── projdefs.h │ │ ├── queue.h │ │ ├── semphr.h │ │ ├── stack_macros.h │ │ ├── stream_buffer.h │ │ ├── task.h │ │ ├── tcb.h │ │ └── timers.h │ ├── system/ │ │ ├── dev/ │ │ │ ├── banners.h │ │ │ ├── dev.h │ │ │ ├── ser.h │ │ │ ├── usd.h │ │ │ └── vfs.h │ │ ├── hot.h │ │ ├── optimizers.h │ │ ├── user_functions/ │ │ │ ├── c_list.h │ │ │ ├── cpp_list.h │ │ │ └── list.h │ │ └── user_functions.h │ └── vdml/ │ ├── port.h │ ├── registry.h │ └── vdml.h ├── libv5rts-strip-options.txt ├── patch_headers.py ├── project.pros ├── public_symbols.txt ├── src/ │ ├── common/ │ │ ├── README.md │ │ ├── cobs.c │ │ ├── gid.c │ │ ├── linkedlist.c │ │ ├── set.c │ │ └── string.c │ ├── devices/ │ │ ├── README.md │ │ ├── battery.c │ │ ├── battery.cpp │ │ ├── controller.c │ │ ├── controller.cpp │ │ ├── registry.c │ │ ├── screen.c │ │ ├── screen.cpp │ │ ├── vdml.c │ │ ├── vdml_adi.c │ │ ├── vdml_adi.cpp │ │ ├── vdml_ai_vision.c │ │ ├── vdml_ai_vision.cpp │ │ ├── vdml_device.c │ │ ├── vdml_device.cpp │ │ ├── vdml_distance.c │ │ ├── vdml_distance.cpp │ │ ├── vdml_ext_adi.c │ │ ├── vdml_gps.c │ │ ├── vdml_gps.cpp │ │ ├── vdml_imu.c │ │ ├── vdml_imu.cpp │ │ ├── vdml_link.c │ │ ├── vdml_link.cpp │ │ ├── vdml_motorgroup.cpp │ │ ├── vdml_motors.c │ │ ├── vdml_motors.cpp │ │ ├── vdml_optical.c │ │ ├── vdml_optical.cpp │ │ ├── vdml_rotation.c │ │ ├── vdml_rotation.cpp │ │ ├── vdml_serial.c │ │ ├── vdml_serial.cpp │ │ ├── vdml_usd.c │ │ ├── vdml_usd.cpp │ │ ├── vdml_vision.c │ │ └── vdml_vision.cpp │ ├── main.cpp │ ├── rtos/ │ │ ├── LICENSE │ │ ├── README.md │ │ ├── heap_4.c │ │ ├── list.c │ │ ├── port.c │ │ ├── portASM.S │ │ ├── portmacro.h │ │ ├── queue.c │ │ ├── refactor.sh │ │ ├── refactor.tsv │ │ ├── rtos.cpp │ │ ├── semphr.c │ │ ├── stream_buffer.c │ │ ├── task_notify_when_deleting.c │ │ ├── tasks.c │ │ └── timers.c │ ├── system/ │ │ ├── cpp_support.cpp │ │ ├── dev/ │ │ │ ├── dev_driver.c │ │ │ ├── file_system_stubs.c │ │ │ ├── ser_daemon.c │ │ │ ├── ser_driver.c │ │ │ ├── usd_driver.c │ │ │ └── vfs.c │ │ ├── envlock.c │ │ ├── hot.c │ │ ├── mlock.c │ │ ├── newlib_stubs.c │ │ ├── newlib_stubs_support.cpp │ │ ├── rtos_hooks.c │ │ ├── startup.c │ │ ├── system_daemon.c │ │ ├── unwind.c │ │ ├── user_functions.c │ │ └── xilinx_vectors.s │ └── tests/ │ ├── adi.cpp │ ├── basic_test.c │ ├── basic_test.cpp │ ├── errno_reentrancy.c │ ├── exceptions.cpp │ ├── ext_adi.cpp │ ├── generic_serial.cpp │ ├── generic_serial_file.cpp │ ├── gyro.c │ ├── gyro.cpp │ ├── mutexes.c │ ├── pnuematics.cpp │ ├── rtos_function_linking.c │ ├── segfault.cpp │ ├── simple_names.c │ ├── simple_names.cpp │ ├── static_tast_states.c │ ├── task_notify_when_deleting.c │ └── vision_test.cpp ├── template-Makefile ├── template-gitignore ├── verify-symbols.sh └── version.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .arcconfig ================================================ { "phabricator.uri": "https://phabricator.purduesigbots.com/", "repoistory.callsign": "rRESTRICTEDPROS", "lint.engine": "ArcanistConfigurationDrivenLintEngine", "default-reviewers": "berman5 jhabibi jbuschjr", "load": [ "clang-format-linter" ] } ================================================ FILE: .arclint ================================================ { "linters": { "clang-format": { "type": "clang-format", "include": "(.*\\.(c|cpp|h|hpp)$)", "exclude": "(^(src|include)/(rtos/|display/lv_.+))" }, "spelling": { "type": "spelling", "include": "(.*)", "exclude": "(^(src|include)|(rtos/|display/lv_.*))" }, "text": { "type": "text", "include": "(.*)", "exclude": "(^(src|include)/(((rtos)/)|(system/dev/banners.h)|(display/((lv_.+)|(licence.txt)))))", "severity": { "2": "disabled", "3": "disabled" } } } } ================================================ FILE: .clang-format ================================================ BasedOnStyle: Google TabWidth: 2 Language: Cpp UseTab: ForIndentation ColumnLimit: 120 Standard: Cpp11 DerivePointerAlignment: false PointerAlignment: Left FixNamespaceComments: true ReflowComments: true SortIncludes: true AccessModifierOffset: 0 AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: Empty ================================================ FILE: .github/CONTRIBUTING.md ================================================ # Contributing to PROS :tada: :+1: :steam_locomotive: Thanks for taking the time to contribute! :steam_locomotive: :+1: :tada: **Did you find a bug?** - **Before opening an issue, make sure you are in the right repository!** purduesigbots maintains four repositories related to PROS: - [purduesigbots/pros](https://github.com/purduesigbots/pros): the repository containing the source code for the kernel the user-facing API. Issues should be opened here if they affect the code you write (e.g., "I would like to be able to do X with PROS," or "when I call X doesn't work as I expect") - [purduesigbots/pros-cli](https://github.com/purduesigbots/pros-cli): the repository containing the source code for the command line interface (CLI). Issues should be opened here if they concern the PROS CLI (e.g., problems with commands like `pros make`), as well as project creation and management. - [purduesigbots/pros-atom](https://github.com/purduesigbots/pros-vsc): the repository containing the source code for the VSCode extension. Issues should be opened here if they concern the coding experience within VSCode (e.g., "there is no button to do X," or "the linter is spamming my interface with errors"). - [purduesigbots/pros-docs](https://github.com/purduesigbots/pros-docs): the repository containing the source code for [our documentation website](https://pros.cs.purdue.edu). Issues should be opened here if they concern available documentation (e.g., "there is not guide on using ," or "the documentation says to do X, but only Y works") - **Verify the bug lies in PROS.** We receive quite a few reports that are due to bugs in user code, not the kernel. - Ensure the bug wasn't already reported by searching GitHub [issues](https://github.com/purduesigbots/pros/issues) - If you're unable to find an issue, [open](https://github.com/purduesigbots/pros/issues/new) a new one. **Did you patch a bug or add a new feature?** 1. [Fork](https://github.com/purduesigbots/pros/fork) and clone the repository 2. Create a new branch: `git checkout -b my-branch-name` 3. Make your changes. 4. Push to your fork and submit a pull request. 5. Wait for your pull request to be reviewed. In order to ensure that the PROS kernel is stable, we take extra time to test pull requests. As a result, your pull request may take some time to be merged into master. Here are a few tips that can help expedite your pull request being accepted: - Follow existing code's style. - Document why you made the changes you did. - Keep your change as focused as possible. If you have multiple independent changes, make a pull request for each. - If you did some testing, describe your procedure and results. - If you're fixing an issue, reference it by number. ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ #### Expected Behavior: #### Actual Behavior: #### Steps to reproduce: #### System information: Platform: PROS Kernel Version: #### Additional Information #### Screenshots/Output Dumps/Stack Traces ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ #### Summary: #### Motivation: ##### References (optional): #### Test Plan: - [ ] test item ================================================ FILE: .gitignore ================================================ .vscode/ .idea/ bin/ .*.sw* template/ version cquery_log.txt compile_commands.json .ccls-cache/ .ccls temp.log temp.errors .d/ .clangd/ .cache/ .DS_Store ================================================ FILE: .gitmodules ================================================ [submodule "firmware/libv5rts"] path = firmware/libv5rts url = git@github.com:purduesigbots/libv5rts.git ignore = dirty ================================================ FILE: LICENSE ================================================ PROS 4.0 contains modified or linked source code from the following packages: - FreeRTOS (src/rtos/LICENSE) Unless otherwise specified, PROS 4.0 is distributed under the Mozilla Public License Version 2.0, reproduced below: Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ================================================ FILE: Makefile ================================================ ################################################################################ ######################### User configurable parameters ######################### # filename extensions CEXTS:=c ASMEXTS:=s S CXXEXTS:=cpp c++ cc # probably shouldn't modify these, but you may need them below ROOT=. FWDIR:=$(ROOT)/firmware BINDIR=$(ROOT)/bin SRCDIR=$(ROOT)/src INCDIR=$(ROOT)/include EXTRA_INCDIR=$(FWDIR)/libv5rts/sdk/vexv5/patched_include # Directories to be excluded from all builds EXCLUDE_SRCDIRS+=$(SRCDIR)/tests C_STANDARD=gnu2x CXX_STANDARD=gnu++23 WARNFLAGS+=-Wall -Wpedantic EXTRA_CFLAGS+= EXTRA_CXXFLAGS=-D_PROS_KERNEL_SUPPRESS_LLEMU_WARNING .DEFAULT_GOAL=quick USE_PACKAGE:=0 # Set this to 1 to add additional rules to compile your project as a PROS library template IS_LIBRARY:=1 LIBNAME:=libpros VERSION=$(shell cat $(ROOT)/version) # EXCLUDE_SRC_FROM_LIB= $(SRCDIR)/unpublishedfile.c EXCLUDE_SRC_FROM_LIB+=$(EXCLUDE_SRCDIRS) # this line excludes opcontrol.c and similar files EXCLUDE_SRC_FROM_LIB+=$(foreach file, $(SRCDIR)/main,$(foreach cext,$(CEXTS),$(file).$(cext)) $(foreach cxxext,$(CXXEXTS),$(file).$(cxxext))) # files that get distributed to every user (beyond your source archive) - add # whatever files you want here. This line is configured to add all header files # that are in the the include directory get exported TEMPLATE_FILES=$(ROOT)/common.mk $(FWDIR)/v5.ld $(FWDIR)/v5-common.ld $(FWDIR)/v5-hot.ld TEMPLATE_FILES+=$(FWDIR)/libc.a $(FWDIR)/libm.a TEMPLATE_FILES+= $(INCDIR)/api.h $(INCDIR)/main.h $(INCDIR)/pros/*.* TEMPLATE_FILES+= $(SRCDIR)/main.cpp TEMPLATE_FILES+= $(ROOT)/template-gitignore PATCHED_SDK=$(FWDIR)/libv5rts/sdk/vexv5/libv5rts.patched.a EXTRA_LIB_DEPS=$(INCDIR)/api.h $(PATCHED_SDK) ################################################################################ ################################################################################ ########## Nothing below this line should be edited by typical users ########### -include ./common.mk .PHONY: $(INCDIR)/pros/version.h patch_sdk_headers clean $(INCDIR)/pros/version.h: version.py $(VV)python version.py patch_sdk_headers: patch_headers.py @echo "Patching SDK headers" $(VV)python patch_headers.py # Override clean, necessary to remove patched sdk on clean clean:: @echo "Cleaning patched SDK" @rm -f $(PATCHED_SDK) @rm -rf $(EXTRA_INCDIR) $(PATCHED_SDK): $(FWDIR)/libv5rts/sdk/vexv5/libv5rts.a $(call test_output_2,Stripping unwanted symbols from libv5rts.a ,$(STRIP) $^ @libv5rts-strip-options.txt -o $@, $(DONE_STRING)) CREATE_TEMPLATE_ARGS=--system "./**/*" CREATE_TEMPLATE_ARGS+=--user "src/main.{cpp,c,cc}" --user "include/main.{hpp,h,hh}" --user "Makefile" --user ".gitignore" CREATE_TEMPLATE_ARGS+=--target v5 CREATE_TEMPLATE_ARGS+=--output bin/monolith.bin --cold_output bin/cold.package.bin --hot_output bin/hot.package.bin --cold_addr 58720256 --hot_addr 125829120 template:: patch_sdk_headers clean-template library $(VV)mkdir -p $(TEMPLATE_DIR) @echo "Moving template files to $(TEMPLATE_DIR)" $Dif [ $(shell uname -s) == "Darwin" ]; then \ rsync -R $(TEMPLATE_FILES) $(TEMPLATE_DIR); \ else \ cp --parents -r $(TEMPLATE_FILES) $(TEMPLATE_DIR); \ fi $(VV)mkdir -p $(TEMPLATE_DIR)/firmware $Dcp $(LIBAR) $(TEMPLATE_DIR)/firmware $Dcp $(ROOT)/template-Makefile $(TEMPLATE_DIR)/Makefile $Dmv $(TEMPLATE_DIR)/template-gitignore $(TEMPLATE_DIR)/.gitignore @echo "Creating template" $Dpros c create-template $(TEMPLATE_DIR) kernel $(shell cat $(ROOT)/version) $(CREATE_TEMPLATE_ARGS) LIBV5RTS_EXTRACTION_DIR=$(BINDIR)/libv5rts $(LIBAR): patch_sdk_headers $(call GETALLOBJ,$(EXCLUDE_SRC_FROM_LIB)) $(EXTRA_LIB_DEPS) $(VV)mkdir -p $(LIBV5RTS_EXTRACTION_DIR) $(call test_output_2,Extracting libv5rts ,cd $(LIBV5RTS_EXTRACTION_DIR) && $(AR) x ../../$(PATCHED_SDK),$(DONE_STRING)) $(eval LIBV5RTS_OBJECTS := $(shell $(AR) t $(PATCHED_SDK))) -$Drm -f $@ $(call test_output_2,Creating $@ ,$(AR) rcs $@ $(addprefix $(LIBV5RTS_EXTRACTION_DIR)/, $(LIBV5RTS_OBJECTS)) $(call GETALLOBJ,$(EXCLUDE_SRC_FROM_LIB)),$(DONE_STRING)) # @echo -n "Stripping non-public symbols " # $(call test_output,$D$(OBJCOPY) -S -D -g --strip-unneeded --keep-symbols public_symbols.txt $@,$(DONE_STRING)) ================================================ FILE: README.md ================================================ # PROS Kernel for the VEX V5 Brain [![Build Status](https://dev.azure.com/purdue-acm-sigbots/Kernel/_apis/build/status/purduesigbots.pros?branchName=develop)](https://dev.azure.com/purdue-acm-sigbots/Kernel/_build/latest?definitionId=5&branchName=develop) ### What is PROS? PROS is a lightweight and fast alternative open source operating system for the VEX V5 Brain. PROS is built with developers in mind and with a focus on providing an environment for industry-applicable experience. Primary maintenance of PROS is done by students at Purdue University through [Purdue ACM SIGBots](http://purduesigbots.com). Inspiration for this project came from several computer science and engineering students itching to write code for the extended autonomous period. We created PROS to leverage this opportunity. All PROS development is open sourced and available for the community to inspect. We believe that sharing source improves PROS through community contributions and allows students to learn by example. PROS is built using the GCC toolchain and standard C/C++ practices (C23 & C++23 w/GNU extensions) to make the learning curve small. Structures, pointers, dynamic memory allocation, and function pointers are all available. Additionally, code is run on bare metal, allowing you to take full advantage of the microcontroller's power. You can develop code on Windows, OS X, or Linux. Code is compiled using GCC and the PROS CLI is available on most operating systems. The PROS development team makes distributions for Windows, OS X, and Debian-based Linux distributions. The PROS team develops a plugin for Atom to making developing projects in PROS the best possible experience. The highly customizable editor designed for the 21st century enables students to learn how to code in a modern environment. ### What's the difference between PROS 4 and 3? PROS 4 is a Kernel upgrade from PROS 4 to both decrease the size of the base Kernel, and provide utilities such as the base device class and liblvgl that makes it easier for both users and library writers to customize their PROS projects. This version also moves all documentation to a doxygen site rather than a Sphinx documentation page. ### What's the difference between PROS 2 and PROS 3? PROS 2 refers to the kernel that runs on the [VEX Arm Cortex-based Microcontroller](https://www.vexrobotics.com/276-2194.html). The source for this kernel is still available on the `cortex-master` branch. The future development for this version of the PROS kernel will be focused on maintenance and critical bugfixes. PROS 3 refers to the kernel that runs on the [VEX V5](https://www.vexrobotics.com/vexedr/v5) microcontroller platform. The majority of our development focus will be on this version of the PROS kernel. ### Does PROS support C++? - PROS 3.x and 4.x (V5) officially supports C++. We're still working on enabling all of the features of C++ (particularly in the I/O area). - PROS 2.x (Cortex) does not officially support C++. Some users have found ways around this, but be warned: we will not be able to help if you run into issues doing this. ### Cool, how do I get it? Pay a visit to our website, [pros.cs.purdue.edu](https://pros.cs.purdue.edu), to download our latest installer or view installation instructions for your preferred platform. ### How do I use it? We have a number of resources available on our website, including - [A basic tutorial to get you acquainted with the PROS ecosystem](https://pros.cs.purdue.edu/v5/getting-started/new-users.html) - [A series of tutorials on how to use some of the more advanced features of PROS](https://pros.cs.purdue.edu/v5/tutorials/index.html) - [Extensive documentation on the kernel's API](https://pros.cs.purdue.edu/v5/api/index.html) ### I still have questions! Drop us a line - at pros_development@cs.purdue.edu - on the [VEX Forum](https://www.vexforum.com/) - on [VEX Teams of the World Discord](https://discord.gg/xddjWGj) ### I think I found a bug! We maintain GitHub repositories for the three major components of the PROS ecosystem: - The Command Line Interface (cli) at [purduesigbots/pros-cli](https://github.com/purduesigbots/pros-cli) - The VS Code plugin at [purduesigbots/pros-vsc](https://github.com/purduesigbots/pros-vsc) - The kernel [here](https://github.com/purduesigbots/pros) If you find a problem with our documentation or tutorials, we have a repository for that, too, at [purduesigbots/pros-docs](https://github.com/purduesigbots/pros-docs). ### Hey! Why can't I build the PROS kernel? The PROS kernel depends on VEX's proprietary Software Development Kit (SDK), which is not publicly available. ================================================ FILE: STYLEGUIDE.md ================================================ # PROS Kernel Styleguide Maintaining a consistent coding style throughout the PROS kernel is important for future developers and students to learn about the PROS kernel. An inconsistent style can lead to confusion for everyone. The PROS style is based on the Google C++ coding style (with some modifications noted a bit farther down), which allows `clang-format` to be used on every file and get correctly formatted code. Some additional notes follow: ## File extensions - C source files will have the extension `.c` - C++ source files will have the extension `.cpp` - C header files will have the extension `.h` - C++ header files will have the extension `.hpp` ## Naming Conventions The PROS kernel follows these naming conventions: - Structures: `structname_s`: - Structure members: these do not have any special convention, as you will never see a structure member without seeing that it is in a structure. - Enumerated types: `enumname_e` - Enumerated type members: `E_ENUMNAME_MEMBERNAME` For example, in `task_state_e`, you might have members such as `E_TASK_STATE_RUNNING`. Note that "ENUMNAME" can be multiple words, separated by underscores. - Function pointers: `funcname_fn` - Type definitions: append `_t` to the end of the structure/enum/function pointer name - C++ classes: these should be named in UpperCamelCase (also known as PascalCase) - Class members: use lower_snake_case as normal, and use good sense when naming This section provides only a brief overview of the naming conventions used in the PROS kernel. For more about the motivations behind these, see section 4 (Naming) below. ## Documentation Use Doxygen-style comments as shown in the sections below. ### File-Level Comments These should be placed at the very start of a file. ```c /** * \file filename.h * * Short description of the file * * Extended description goes here. This should explain what the functions (etc) * in the file contains and a general description of what they do (no specifics, * but they should all have something in common anyway). * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ ``` ### Enum-Level Comments These should be placed immediately before the declaration of the enum. ```c /* * Short description of the enum * * Extended description of the enum goes here. This should explain general usage * patterns for the enum. */ enum my_enum { E_MEMBER_0, // short description of member 0 goes here. E_MEMBER_1, // these can be omitted if it's painfully obvious E_MEMBER_2, // what each is for, or if there are just so many of E_MEMBER_3, // them it doesn't make practical sense to E_MEMBER_4 // document them all. } ``` _Note: in the above example, the comments describing each member of the `enum` run together and form complete sentences for effect. Please do not do this in your code!_ ### Function-Level Comments These should be placed immediately before the function prototype they are describing in a header file. ```c /** * Brief description of the function. * * An extended description of the function (if applicable). * * This function uses the following values of errno when an error state is * reached: * ERRNO_VALUE - Description of what causes this error * * \param parameter_name * The parameter description * \param other_parameter_name * The parameter description * * \return The description of the return value, if this is longer than one line * then it will wrap around under the return statement */ ``` ### Inline Implementation Comments Sometimes it is necessary to explain a particularly complex statement or series of statements. In this case, you should use inline comments, placed either immediately before or trailing the line or lines in question. In general, prefer placing such comments before offending lines, unless the comment is quite short. These comments should start with a `//` followed by a space. If they are placed trailing a line, they should be separated from the end of the line by one space. ```c float Q_rsqrt(float number) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; // perform some absolute magic on these numbers to get the inverse square root i = *(long*)&y; // evil floating point bit level hacking i = 0x5f3759df - (i >> 1); // what the [heck]? y = *(float*)&i; y = y * (threehalfs - (x2 * y * y)); // 1st iteration //y = y * (threehalfs - (x2 * y * y)); // 2nd iteration, this can be removed return y; } ``` _Note: in the above example, there is a line of code that has been commented out. This is fine to do while testing, but any commented out lines of code should be removed before any merge into the master branch takes place, unless a compelling reason can be presented for them to remain._ All that being said, try to avoid code that is so complex that it requires inline comments for its purpose to be clear. #### Notes to Other Developers (Or Yourself) When writing code, it can sometimes be useful to leave notes to other developers or to yourself in the future. Examples of these include: - `// TODO: something that should be done` - `// NOTE: a note about something in the code` - `// NB: this is the same as NOTE, but it's in Latin, so it's fancier` - `// HACK: used to describe a particularly nasty way of solving a problem-- could be improved, but it works for now` - `// FIXME: this code is broken and should be fixed` - `// XXX: this is like FIXME, but it's worse (note that this has also been used in the same way as HACK, so you should use that or FIXME to clarify what is meant)` - `// BUG: this is used to mark a line of code that is known to cause a bug. kind of like FIXME, though it may include some more specific information than FIXME would` While it is not strictly necessary to use these keywords in comments, they can be helpful-- modern editors (like Atom or VSCode) either highlight some of these keywords by default or have extensions that do. This can make certain comments stand out even more when developers are "grepping" the codebase (visually or otherwise). ### Word Choice and Tense Content for the docs should follow the [Google Developer Documentation Style Guide](https://developers.google.com/style/), and the [API Reference Comments Section](https://developers.google.com/style/api-reference-comments) in particular. While the Google Style Guide should determine the vast majority of the docs' word choices, additionally follow these content-specific guides: - All ports, Smart, ADI, or otherwise, should be referred to as a port, not a channel or pin. - C++ functions should be written as their full function name, without removing the `pros::` namespace (e.g. `pros::Motor::move`). - All enumerated values referenced in the code comments should be written as their full name per the PROS Style Guide, not the `PROS_USE_SIMPLE_NAMES` version. (e.g. `E_MOTOR_GEARSET_18`, not `E_MOTOR_GEARSET_18`). ### C/C++ Format Guide The PROS Coding style is based on the [Google C++ Coding Style](https://google.github.io/styleguide/cppguide.html) with the following modifications: ``` TabWidth: 2 UseTab: ForIndentation ColumnLimit: 120 DerivePointerAlignment: false PointerAlignment: Left FixNamespaceComments: true ReflowComments: true SortIncludes: true AccessModifierOffset: 0 AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: Empty ``` ================================================ FILE: VSCode.md ================================================ Use the following include paths for intellisense completion: "${env:PROS_TOOLCHAIN}/arm-none-eabi/include", "${env:PROS_TOOLCHAIN}/lib/gcc/arm-none-eabi/6.3.1/include", "${workspaceRoot}", "${workspaceRoot}/include" Add "_INTELLISENSE" to your defines to fix certain intellisense errors that will actually compile without issue ================================================ FILE: azure-build-libc.yaml ================================================ ############################################################################### # # This pipeline builds newlib with the same flags as the official toolchain, # but adds -funwind-tables so we can have proper unwind info inside libc # ############################################################################### variables: source_url: 'https://developer.arm.com/-/media/Files/downloads/gnu-rm/8-2018q4/gcc-arm-none-eabi-8-2018-q4-major-src.tar.bz2' source_directory: 'gcc-arm-none-eabi-8-2018-q4-major' jobs: - job: BuildLibc pool: vmImage: 'ubuntu-16.04' timeoutInMinutes: 0 steps: - bash: | sudo apt-get install software-properties-common sudo dpkg --add-architecture i386 sudo add-apt-repository ppa:team-gcc-arm-embedded/ppa sudo apt-get update sudo apt-get install build-essential autoconf autogen bison dejagnu flex flip gawk git gperf gzip \ nsis openssh-client p7zip-full perl python-dev libisl-dev scons tcl tofrodos \ wget libncurses5-dev pv sudo apt-get install gcc-arm-embedded displayName: Install apt packages - bash: | curl -L $(source_url) -o $(source_directory).tar.bz2 pv -f $(source_directory).tar.bz2 | tar -xjf - displayName: Download/extract arm-none-eabi-gcc source - bash: | sed -i '95s/TERM|\\/TERM|agent.jobstatus|\\/' ./build-common.sh sed -i '302s/http:\/\/www.mr511.de\/software\//https:\/\/github.com\/gnu-mcu-eclipse\/files\/raw\/master\/libs\//' ./build-common.sh displayName: Edit ./build-common.sh workingDirectory: $(source_directory) - bash: | sed -i "294s/.*/saveenvvar CFLAGS_FOR_TARGET '-g -O2 -ffunction-sections -fdata-sections -funwind-tables'/" ./build-toolchain.sh head -n 316 ./build-toolchain.sh > ./build-toolchain.sh displayName: Edit ./build-toolchain.sh workingDirectory: $(source_directory) - bash: | ./install-sources.sh --skip_steps=mingw32 displayName: Install sources workingDirectory: $(source_directory) - bash: | ./build-prerequisites.sh --skip_steps=mingw32 displayName: Build prerequisites workingDirectory: $(source_directory) - bash: | export CFLAGS_FOR_TARGET='-g -O2 -ffunction-sections -fdata-sections -funwind-tables' export ROOT=`pwd` mkdir -p $ROOT/build-native/newlib pushd $ROOT/build-native/newlib $ROOT/src/newlib/configure \ --build="`uname -m | sed 'y/XI/xi/'`"-linux-gnu --host="`uname -m | sed 'y/XI/xi/'`"-linux-gnu \ --target=arm-none-eabi \ --prefix=$ROOT/newlib \ --enable-newlib-io-long-long \ --enable-newlib-io-c99-formats \ --enable-newlib-register-fini \ --enable-newlib-retargetable-locking \ --disable-newlib-supplied-syscalls \ --disable-nls \ make -j`grep ^processor /proc/cpuinfo|wc -l` make install ls -R $ROOT/newlib ls -R $ROOT/build-native/newlib cp $ROOT/newlib/arm-none-eabi/lib/thumb/v7-ar/libc.a $(Build.ArtifactStagingDirectory) cp $ROOT/newlib/arm-none-eabi/lib/thumb/v7-ar/libm.a $(Build.ArtifactStagingDirectory) ls $(Build.ArtifactStagingDirectory) TARGET_LIBRARIES=`find $(Build.ArtifactStagingDirectory) -name \*.a` for target_lib in $TARGET_LIBRARIES ; do echo Stripping $target_lib arm-none-eabi-objcopy -R .comment -R .note -R .debug_info -R .debug_aranges -R .debug_pubnames -R .debug_pubtypes -R .debug_abbrev -R .debug_line -R .debug_str -R .debug_ranges -R .debug_loc $target_lib || true done displayName: Build toolchain workingDirectory: $(source_directory) - task: PublishPipelineArtifact@0 inputs: artifactName: 'newlib' targetPath: $(Build.ArtifactStagingDirectory) ================================================ FILE: azure-pipelines.yml ================================================ jobs: - job: BuildTemplate variables: toolchain_update: 13.3.rel1 toolchain: https://developer.arm.com/-/media/Files/downloads/gnu/$(toolchain_update)/binrel/arm-gnu-toolchain-$(toolchain_update)-x86_64-arm-none-eabi.tar.xz pool: vmImage: 'ubuntu-latest' steps: - task: InstallSSHKey@0 inputs: sshKeySecureFile: id_sigbot_github_azure_devops hostName: $(gh.knownhosts) sshPublicKey: $(gh.publickey) - checkout: self - bash: | curl -LSso toolchain.tar.xz $(toolchain) tar -xJvf toolchain.tar.xz echo "##vso[task.prependpath]$(pwd)/arm-gnu-toolchain-$(toolchain_update)-x86_64-arm-none-eabi/bin" displayName: Install gcc-arm-embedded - task: UsePythonVersion@0 inputs: addToPath: true versionSpec: '3.11.0' - task: PipAuthenticate@1 inputs: artifactFeeds: 'pros-cli' # use official PyPi registry first and fall back to internal feed as needed onlyAddExtraIndex: true - bash: pip install pros-cli displayName: Install CLI - bash: | make template mkdir -p artifacts cp template/*.zip artifacts displayName: Build template - bash: | echo "##vso[build.UpdateBuildNumber]`cat version`" echo "##vso[task.setvariable variable=KernelVersion]`cat version`" displayName: Update Build Number - bash: | make displayName: Build binaries - task: PublishPipelineArtifact@0 inputs: targetPath: artifacts artifactName: template condition: succeeded() # - task: UniversalPackages@0 # inputs: # command: publish # publishDirectory: artifacts # vstsFeedPublish: 'pros-depot-nightly' # vstsFeedPackagePublish: 'kernel' # versionOption: custom # versionPublish: $(KernelVersion) # packagePublishDescription: 'CI Build of Kernel' # condition: and(succeeded(), or(eq(variables['Build.SourceBranch'], 'refs/heads/master'), eq(variables['Build.SourceBranch'], 'refs/heads/develop'))) ================================================ FILE: common.mk ================================================ ARCHTUPLE=arm-none-eabi- DEVICE=VEX EDR V5 MFLAGS=-mcpu=cortex-a9 -mfpu=neon-fp16 -mfloat-abi=hard -Os -g -mthumb CPPFLAGS=-D_POSIX_THREADS -D_UNIX98_THREAD_MUTEX_ATTRIBUTES -D_POSIX_TIMERS -D_POSIX_MONOTONIC_CLOCK GCCFLAGS=-ffunction-sections -fdata-sections -fdiagnostics-color -funwind-tables # Check if the llemu files in libvgl exist. If they do, define macros that the # llemu headers in the kernel repo can use to conditionally include the libvgl # versions ifneq (,$(wildcard ./include/liblvgl/llemu.h)) CPPFLAGS += -D_PROS_INCLUDE_LIBLVGL_LLEMU_H endif ifneq (,$(wildcard ./include/liblvgl/llemu.hpp)) CPPFLAGS += -D_PROS_INCLUDE_LIBLVGL_LLEMU_HPP endif WARNFLAGS+=-Wno-psabi SPACE := $() $() COMMA := , C_STANDARD?=gnu23 CXX_STANDARD?=gnu++26 DEPDIR := .d $(shell mkdir -p $(DEPDIR)) DEPFLAGS = -MT $$@ -MMD -MP -MF $(DEPDIR)/$$*.Td MAKEDEPFOLDER = -$(VV)mkdir -p $(DEPDIR)/$$(dir $$(patsubst $(BINDIR)/%, %, $(ROOT)/$$@)) RENAMEDEPENDENCYFILE = -$(VV)mv -f $(DEPDIR)/$$*.Td $$(patsubst $(SRCDIR)/%, $(DEPDIR)/%.d, $(ROOT)/$$<) && touch $$@ LIBRARIES+=$(wildcard $(FWDIR)/*.a) # Cannot include newlib and libc because not all of the req'd stubs are implemented EXCLUDE_COLD_LIBRARIES+=$(FWDIR)/libc.a $(FWDIR)/libm.a COLD_LIBRARIES=$(filter-out $(EXCLUDE_COLD_LIBRARIES), $(LIBRARIES)) wlprefix=-Wl,$(subst $(SPACE),$(COMMA),$1) LNK_FLAGS=--gc-sections --start-group $(strip $(LIBRARIES)) -lgcc -lstdc++ --end-group -T$(FWDIR)/v5-common.ld --no-warn-rwx-segments --sort-section=alignment --sort-common ASMFLAGS=$(MFLAGS) $(WARNFLAGS) CFLAGS=$(MFLAGS) $(CPPFLAGS) $(WARNFLAGS) $(GCCFLAGS) --std=$(C_STANDARD) CXXFLAGS=$(MFLAGS) $(CPPFLAGS) $(WARNFLAGS) $(GCCFLAGS) --std=$(CXX_STANDARD) LDFLAGS=$(MFLAGS) $(WARNFLAGS) -nostdlib $(GCCFLAGS) SIZEFLAGS=-d --common NUMFMTFLAGS=--to=iec --format %.2f --suffix=B AR:=$(ARCHTUPLE)ar # using arm-none-eabi-as generates a listing by default. This produces a super verbose output. # Using gcc accomplishes the same thing without the extra output AS:=$(ARCHTUPLE)gcc CC:=$(ARCHTUPLE)gcc CXX:=$(ARCHTUPLE)g++ LD:=$(ARCHTUPLE)g++ OBJCOPY:=$(ARCHTUPLE)objcopy SIZETOOL:=$(ARCHTUPLE)size READELF:=$(ARCHTUPLE)readelf STRIP:=$(ARCHTUPLE)strip ifneq (, $(shell command -v gnumfmt 2> /dev/null)) SIZES_NUMFMT:=| gnumfmt --field=-4 --header $(NUMFMTFLAGS) else ifneq (, $(shell command -v numfmt 2> /dev/null)) SIZES_NUMFMT:=| numfmt --field=-4 --header $(NUMFMTFLAGS) else SIZES_NUMFMT:= endif endif ifneq (, $(shell command -v sed 2> /dev/null)) SIZES_SED:=| sed -e 's/ dec/total/' else SIZES_SED:= endif rwildcard=$(foreach d,$(filter-out $3,$(wildcard $1*)),$(call rwildcard,$d/,$2,$3)$(filter $(subst *,%,$2),$d)) # Colors NO_COLOR=$(shell printf "%b" "\033[0m") OK_COLOR=$(shell printf "%b" "\033[32;01m") ERROR_COLOR=$(shell printf "%b" "\033[31;01m") WARN_COLOR=$(shell printf "%b" "\033[33;01m") STEP_COLOR=$(shell printf "%b" "\033[37;01m") OK_STRING=$(OK_COLOR)[OK]$(NO_COLOR) DONE_STRING=$(OK_COLOR)[DONE]$(NO_COLOR) ERROR_STRING=$(ERROR_COLOR)[ERRORS]$(NO_COLOR) WARN_STRING=$(WARN_COLOR)[WARNINGS]$(NO_COLOR) ECHO=/bin/printf "%s\n" echo=@$(ECHO) "$2$1$(NO_COLOR)" echon=@/bin/printf "%s" "$2$1$(NO_COLOR)" define test_output_2 @if test $(BUILD_VERBOSE) -eq $(or $4,1); then printf "%s\n" "$2"; fi; @output="$$($2 2>&1)"; exit=$$?; \ if test 0 -ne $$exit; then \ printf "%s%s\n" "$1" "$(ERROR_STRING)"; \ printf "%s\n" "$$output"; \ exit $$exit; \ elif test -n "$$output"; then \ printf "%s%s\n" "$1" "$(WARN_STRING)"; \ printf "%s\n" "$$output"; \ else \ printf "%s%s\n" "$1" "$3"; \ fi; endef define test_output @output=$$($1 2>&1); exit=$$?; \ if test 0 -ne $$exit; then \ printf "%s\n" "$(ERROR_STRING)" $$?; \ printf "%s\n" $$output; \ exit $$exit; \ elif test -n "$$output"; then \ printf "%s\n" "$(WARN_STRING)"; \ printf "%s" $$output; \ else \ printf "%s\n" "$2"; \ fi; endef # Makefile Verbosity ifeq ("$(origin VERBOSE)", "command line") BUILD_VERBOSE = $(VERBOSE) endif ifeq ("$(origin V)", "command line") BUILD_VERBOSE = $(V) endif ifndef BUILD_VERBOSE BUILD_VERBOSE = 0 endif # R is reduced (default messages) - build verbose = 0 # V is verbose messages - verbosity = 1 # VV is super verbose - verbosity = 2 ifeq ($(BUILD_VERBOSE), 0) R = @echo D = @ VV = @ endif ifeq ($(BUILD_VERBOSE), 1) R = @echo D = VV = @ endif ifeq ($(BUILD_VERBOSE), 2) R = D = VV = endif INCLUDE=$(foreach dir,$(INCDIR) $(EXTRA_INCDIR),-iquote"$(dir)") ASMSRC=$(foreach asmext,$(ASMEXTS),$(call rwildcard, $(SRCDIR),*.$(asmext), $1)) ASMOBJ=$(addprefix $(BINDIR)/,$(patsubst $(SRCDIR)/%,%.o,$(call ASMSRC,$1))) CSRC=$(foreach cext,$(CEXTS),$(call rwildcard, $(SRCDIR),*.$(cext), $1)) COBJ=$(addprefix $(BINDIR)/,$(patsubst $(SRCDIR)/%,%.o,$(call CSRC, $1))) CXXSRC=$(foreach cxxext,$(CXXEXTS),$(call rwildcard, $(SRCDIR),*.$(cxxext), $1)) CXXOBJ=$(addprefix $(BINDIR)/,$(patsubst $(SRCDIR)/%,%.o,$(call CXXSRC,$1))) GETALLOBJ=$(sort $(call ASMOBJ,$1) $(call COBJ,$1) $(call CXXOBJ,$1)) ARCHIVE_TEXT_LIST=$(subst $(SPACE),$(COMMA),$(notdir $(basename $(LIBRARIES)))) LDTIMEOBJ:=$(BINDIR)/_pros_ld_timestamp.o MONOLITH_BIN:=$(BINDIR)/monolith.bin MONOLITH_ELF:=$(basename $(MONOLITH_BIN)).elf HOT_BIN:=$(BINDIR)/hot.package.bin HOT_ELF:=$(basename $(HOT_BIN)).elf COLD_BIN:=$(BINDIR)/cold.package.bin COLD_ELF:=$(basename $(COLD_BIN)).elf # Check if USE_PACKAGE is defined to check for migration steps from purduesigbots/pros#87 ifndef USE_PACKAGE $(error Your Makefile must be migrated! Visit https://pros.cs.purdue.edu/v5/releases/kernel3.1.6.html to learn how) endif DEFAULT_BIN=$(MONOLITH_BIN) ifeq ($(USE_PACKAGE),1) DEFAULT_BIN=$(HOT_BIN) endif -include $(wildcard $(FWDIR)/*.mk) .PHONY: all clean quick quick: $(DEFAULT_BIN) all: clean $(DEFAULT_BIN) clean:: @echo Cleaning project -$Drm -rf $(BINDIR) -$Drm -rf $(DEPDIR) ifeq ($(IS_LIBRARY),1) ifeq ($(LIBNAME),libbest) $(error "You should rename your library! libbest is the default library name and should be changed") endif LIBAR=$(BINDIR)/$(LIBNAME).a TEMPLATE_DIR=$(ROOT)/template clean-template: @echo Cleaning $(TEMPLATE_DIR) -$Drm -rf $(TEMPLATE_DIR) $(LIBAR): $(call GETALLOBJ,$(EXCLUDE_SRC_FROM_LIB)) $(EXTRA_LIB_DEPS) -$Dmkdir $(BINDIR) -$Drm -f $@ $(call test_output_2,Creating $@ ,$(AR) rcs $@ $^, $(DONE_STRING)) .PHONY: library library: $(LIBAR) .PHONY: template template:: clean-template $(LIBAR) $Dpros c create-template . $(LIBNAME) $(VERSION) $(foreach file,$(TEMPLATE_FILES) $(LIBAR),--system "$(file)") --target v5 $(CREATE_TEMPLATE_FLAGS) endif # if project is a library source, compile the archive and link output.elf against the archive rather than source objects ifeq ($(IS_LIBRARY),1) ELF_DEPS+=$(filter-out $(call GETALLOBJ,$(EXCLUDE_SRC_FROM_LIB)), $(call GETALLOBJ,$(EXCLUDE_SRCDIRS))) LIBRARIES+=$(LIBAR) else ELF_DEPS+=$(call GETALLOBJ,$(EXCLUDE_SRCDIRS)) endif $(MONOLITH_BIN): $(MONOLITH_ELF) $(BINDIR) $(call test_output_2,Creating $@ for $(DEVICE) ,$(OBJCOPY) $< -O binary -R .hot_init $@,$(DONE_STRING)) $(MONOLITH_ELF): $(ELF_DEPS) $(LIBRARIES) $(call _pros_ld_timestamp) $(call test_output_2,Linking project with $(ARCHIVE_TEXT_LIST) ,$(LD) $(LDFLAGS) $(ELF_DEPS) $(LDTIMEOBJ) $(call wlprefix,-T$(FWDIR)/v5.ld $(LNK_FLAGS)) -o $@,$(OK_STRING)) @echo Section sizes: -$(VV)$(SIZETOOL) $(SIZEFLAGS) $@ $(SIZES_SED) $(SIZES_NUMFMT) $(COLD_BIN): $(COLD_ELF) $(call test_output_2,Creating cold package binary for $(DEVICE) ,$(OBJCOPY) $< -O binary -R .hot_init $@,$(DONE_STRING)) $(COLD_ELF): $(COLD_LIBRARIES) $(VV)mkdir -p $(dir $@) $(call test_output_2,Creating cold package with $(ARCHIVE_TEXT_LIST) ,$(LD) $(LDFLAGS) $(call wlprefix,--gc-keep-exported --whole-archive $^ -lstdc++ --no-whole-archive) $(call wlprefix,-T$(FWDIR)/v5.ld $(LNK_FLAGS) -o $@),$(OK_STRING)) $(call test_output_2,Stripping cold package ,$(OBJCOPY) --strip-symbol=install_hot_table --strip-symbol=__libc_init_array --strip-symbol=_PROS_COMPILE_DIRECTORY --strip-symbol=_PROS_COMPILE_TIMESTAMP --strip-symbol=_PROS_COMPILE_TIMESTAMP_INT $@ $@, $(DONE_STRING)) @echo Section sizes: -$(VV)$(SIZETOOL) $(SIZEFLAGS) $@ $(SIZES_SED) $(SIZES_NUMFMT) $(HOT_BIN): $(HOT_ELF) $(COLD_BIN) $(call test_output_2,Creating $@ for $(DEVICE) ,$(OBJCOPY) $< -O binary $@,$(DONE_STRING)) $(HOT_ELF): $(COLD_ELF) $(ELF_DEPS) $(call _pros_ld_timestamp) $(call test_output_2,Linking hot project with $(COLD_ELF) and $(ARCHIVE_TEXT_LIST) ,$(LD) -nostartfiles $(LDFLAGS) $(call wlprefix,-R $<) $(filter-out $<,$^) $(LDTIMEOBJ) $(LIBRARIES) $(call wlprefix,-T$(FWDIR)/v5-hot.ld $(LNK_FLAGS) -o $@),$(OK_STRING)) @printf "%s\n" "Section sizes:" -$(VV)$(SIZETOOL) $(SIZEFLAGS) $@ $(SIZES_SED) $(SIZES_NUMFMT) define asm_rule $(BINDIR)/%.$1.o: $(SRCDIR)/%.$1 $(VV)mkdir -p $$(dir $$@) $$(call test_output_2,Compiled $$< ,$(AS) -c $(ASMFLAGS) -o $$@ $$<,$(OK_STRING)) endef $(foreach asmext,$(ASMEXTS),$(eval $(call asm_rule,$(asmext)))) define c_rule $(BINDIR)/%.$1.o: $(SRCDIR)/%.$1 $(BINDIR)/%.$1.o: $(SRCDIR)/%.$1 $(DEPDIR)/$(basename %).d $(VV)mkdir -p $$(dir $$@) $(MAKEDEPFOLDER) $$(call test_output_2,Compiled $$< ,$(CC) -c $(INCLUDE) -iquote"$(INCDIR)/$$(dir $$*)" $(CFLAGS) $(EXTRA_CFLAGS) $(DEPFLAGS) -o $$@ $$<,$(OK_STRING)) $(RENAMEDEPENDENCYFILE) endef $(foreach cext,$(CEXTS),$(eval $(call c_rule,$(cext)))) define cxx_rule $(BINDIR)/%.$1.o: $(SRCDIR)/%.$1 $(BINDIR)/%.$1.o: $(SRCDIR)/%.$1 $(DEPDIR)/$(basename %).d $(VV)mkdir -p $$(dir $$@) $(MAKEDEPFOLDER) $$(call test_output_2,Compiled $$< ,$(CXX) -c $(INCLUDE) -iquote"$(INCDIR)/$$(dir $$*)" $(CXXFLAGS) $(EXTRA_CXXFLAGS) $(DEPFLAGS) -o $$@ $$<,$(OK_STRING)) $(RENAMEDEPENDENCYFILE) endef $(foreach cxxext,$(CXXEXTS),$(eval $(call cxx_rule,$(cxxext)))) define _pros_ld_timestamp $(VV)mkdir -p $(dir $(LDTIMEOBJ)) @# Pipe a line of code defining _PROS_COMPILE_TOOLSTAMP and _PROS_COMPILE_DIRECTORY into GCC, @# which allows compilation from stdin. We define _PROS_COMPILE_DIRECTORY using a command line-defined macro @# which is the pwd | tail bit, which will truncate the path to the last 23 characters @# @# const int _PROS_COMPILE_TIMESTAMP_INT = $(( $(date +%s) - $(date +%z) * 3600 )) @# char const * const _PROS_COMPILE_TIEMSTAMP = __DATE__ " " __TIME__ @# char const * const _PROS_COMPILE_DIRECTORY = "$(shell pwd | tail -c23)"; @# @# The shell command $$(($$(date +%s)+($$(date +%-z)/100*3600))) fetches the current @# unix timestamp, and then adds the UTC timezone offset to account for time zones. $(call test_output_2,Adding timestamp ,echo 'const int _PROS_COMPILE_TIMESTAMP_INT = $(shell echo $$(($$(date +%s)+($$(date +%-z)/100*3600)))); char const * const _PROS_COMPILE_TIMESTAMP = __DATE__ " " __TIME__; char const * const _PROS_COMPILE_DIRECTORY = "$(wildcard $(shell pwd | tail -c23))";' | $(CC) -c -x c $(CFLAGS) $(EXTRA_CFLAGS) -o $(LDTIMEOBJ) -,$(OK_STRING)) endef # these rules are for build-compile-commands, which just print out sysroot information cc-sysroot: @echo | $(CC) -c -x c $(CFLAGS) $(EXTRA_CFLAGS) --verbose -o /dev/null - cxx-sysroot: @echo | $(CXX) -c -x c++ $(CXXFLAGS) $(EXTRA_CXXFLAGS) --verbose -o /dev/null - $(DEPDIR)/%.d: ; .PRECIOUS: $(DEPDIR)/%.d include $(wildcard $(patsubst $(SRCDIR)/%,$(DEPDIR)/%.d,$(CSRC) $(CXXSRC))) ================================================ FILE: firmware/v5-common.ld ================================================ /* Define the sections, and where they are mapped in memory */ SECTIONS { /* This will get stripped out before uploading, but we need to place code here so we can at least link to it (install_hot_table) */ .hot_init : { KEEP (*(.hot_magic)) KEEP (*(.hot_init)) } > HOT_MEMORY .text : { KEEP (*(.vectors)) /* boot data should be exactly 32 bytes long */ *(.boot_data) . = 0x20; *(.boot) . = ALIGN(64); *(.freertos_vectors) *(.text) *(.text.*) *(.gnu.linkonce.t.*) *(.plt) *(.gnu_warning) *(.gcc_except_table) *(.glue_7) *(.glue_7t) *(.vfp11_veneer) *(.ARM.extab) *(.gnu.linkonce.armextab.*) } > RAM .init : { KEEP (*(.init)) } > RAM .fini : { KEEP (*(.fini)) } > RAM .rodata : { __rodata_start = .; *(.rodata) *(.rodata.*) *(.gnu.linkonce.r.*) __rodata_end = .; } > RAM .rodata1 : { __rodata1_start = .; *(.rodata1) *(.rodata1.*) __rodata1_end = .; } > RAM .sdata2 : { __sdata2_start = .; *(.sdata2) *(.sdata2.*) *(.gnu.linkonce.s2.*) __sdata2_end = .; } > RAM .sbss2 : { __sbss2_start = .; *(.sbss2) *(.sbss2.*) *(.gnu.linkonce.sb2.*) __sbss2_end = .; } > RAM .data : { __data_start = .; *(.data) *(.data.*) *(.gnu.linkonce.d.*) *(.jcr) *(.got) *(.got.plt) __data_end = .; } > RAM .data1 : { __data1_start = .; *(.data1) *(.data1.*) __data1_end = .; } > RAM .got : { *(.got) } > RAM .ctors : { __CTOR_LIST__ = .; ___CTORS_LIST___ = .; KEEP (*crtbegin.o(.ctors)) KEEP (*(EXCLUDE_FILE(*crtend.o) .ctors)) KEEP (*(SORT(.ctors.*))) KEEP (*(.ctors)) __CTOR_END__ = .; ___CTORS_END___ = .; } > RAM .dtors : { __DTOR_LIST__ = .; ___DTORS_LIST___ = .; KEEP (*crtbegin.o(.dtors)) KEEP (*(EXCLUDE_FILE(*crtend.o) .dtors)) KEEP (*(SORT(.dtors.*))) KEEP (*(.dtors)) __DTOR_END__ = .; ___DTORS_END___ = .; } > RAM .fixup : { __fixup_start = .; *(.fixup) __fixup_end = .; } > RAM .eh_frame : { *(.eh_frame) } > RAM .eh_framehdr : { __eh_framehdr_start = .; *(.eh_framehdr) __eh_framehdr_end = .; } > RAM .gcc_except_table : { *(.gcc_except_table) } > RAM .ARM.exidx : { __exidx_start = .; *(.ARM.exidx*) *(.gnu.linkonce.armexidix.*.*) __exidx_end = .; } > RAM .preinit_array : { __preinit_array_start = .; KEEP (*(SORT(.preinit_array.*))) KEEP (*(.preinit_array)) __preinit_array_end = .; } > RAM .init_array : { __init_array_start = .; KEEP (*(SORT(.init_array.*))) KEEP (*(.init_array)) __init_array_end = .; } > RAM .fini_array : { __fini_array_start = .; KEEP (*(SORT(.fini_array.*))) KEEP (*(.fini_array)) __fini_array_end = .; } > RAM /DISCARD/ : { *(.ARM.attributes*) } .sdata : { __sdata_start = .; *(.sdata) *(.sdata.*) *(.gnu.linkonce.s.*) __sdata_end = .; } > RAM .sbss (NOLOAD) : { __sbss_start = .; *(.sbss) *(.sbss.*) *(.gnu.linkonce.sb.*) __sbss_end = .; } > RAM .tdata : { __tdata_start = .; *(.tdata) *(.tdata.*) *(.gnu.linkonce.td.*) __tdata_end = .; } > RAM .tbss : { __tbss_start = .; *(.tbss) *(.tbss.*) *(.gnu.linkonce.tb.*) __tbss_end = .; } > RAM .bss (NOLOAD) : { __bss_start = .; *(.bss) *(.bss.*) *(.gnu.linkonce.b.*) __bss_end = .; } > RAM _SDA_BASE_ = __sdata_start + ((__sbss_end - __sdata_start) / 2 ); _SDA2_BASE_ = __sdata2_start + ((__sbss2_end - __sdata2_start) / 2 ); /* Stack section provides __stack for the partner SDK initialization (vexMain). This prevents the stack from being placed in .bss, which would cause corruption of variables at the end of .bss (see issue #783). FreeRTOS task stacks are dynamically allocated separately. */ .stack (NOLOAD) : ALIGN(8) { _stack_end = .; . += _STACK_SIZE; __stack = .; _stack_start = .; } > RAM .heap (NOLOAD) : { . = ALIGN(16); _heap = .; HeapBase = .; _heap_start = .; . += _HEAP_SIZE; _heap_end = .; HeapLimit = .; } > HEAP _end = .; } ================================================ FILE: firmware/v5-hot.ld ================================================ /* This stack is used during initialization, but FreeRTOS tasks have their own stack allocated in BSS or Heap (kernel tasks in FreeRTOS .bss heap; user tasks in standard heap) */ _STACK_SIZE = DEFINED(_STACK_SIZE) ? _STACK_SIZE : 0x2000; _HEAP_SIZE = DEFINED(_HEAP_SIZE) ? _HEAP_SIZE : 0x02E00000; /* ~48 MB */ /* Define Memories in the system */ start_of_cold_mem = 0x03800000; _COLD_MEM_SIZE = 0x04800000; end_of_cold_mem = start_of_cold_mem + _COLD_MEM_SIZE; start_of_hot_mem = 0x07800000; _HOT_MEM_SIZE = 0x00800000; end_of_hot_mem = start_of_hot_mem + _HOT_MEM_SIZE; MEMORY { /* user code 72M */ COLD_MEMORY : ORIGIN = start_of_cold_mem, LENGTH = _COLD_MEM_SIZE /* Just under 19 MB */ HEAP : ORIGIN = 0x04A00000, LENGTH = _HEAP_SIZE HOT_MEMORY : ORIGIN = start_of_hot_mem, LENGTH = _HOT_MEM_SIZE /* Just over 8 MB */ } REGION_ALIAS("RAM", HOT_MEMORY); ENTRY(install_hot_table) ================================================ FILE: firmware/v5.ld ================================================ /* This stack is used during initialization, but FreeRTOS tasks have their own stack allocated in BSS or Heap (kernel tasks in FreeRTOS .bss heap; user tasks in standard heap) */ _STACK_SIZE = DEFINED(_STACK_SIZE) ? _STACK_SIZE : 0x2000; _HEAP_SIZE = DEFINED(_HEAP_SIZE) ? _HEAP_SIZE : 0x02E00000; /* ~48 MB */ /* Define Memories in the system */ start_of_cold_mem = 0x03800000; _COLD_MEM_SIZE = 0x04800000; end_of_cold_mem = start_of_cold_mem + _COLD_MEM_SIZE; start_of_hot_mem = 0x07800000; _HOT_MEM_SIZE = 0x00800000; end_of_hot_mem = start_of_hot_mem + _HOT_MEM_SIZE; MEMORY { /* user code 72M */ COLD_MEMORY : ORIGIN = start_of_cold_mem, LENGTH = _COLD_MEM_SIZE /* Just under 19 MB */ HEAP : ORIGIN = 0x04A00000, LENGTH = _HEAP_SIZE HOT_MEMORY : ORIGIN = start_of_hot_mem, LENGTH = _HOT_MEM_SIZE /* Just over 8 MB */ } REGION_ALIAS("RAM", COLD_MEMORY); ENTRY(vexStartup) ================================================ FILE: include/api.h ================================================ /** * \file api.h * * PROS API header provides high-level user functionality * * Contains declarations for use by typical VEX programmers using PROS. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _PROS_API_H_ #define _PROS_API_H_ #ifdef __cplusplus #include #include #include #include #include #include #include #else /* (not) __cplusplus */ #include #include #include #include #include #include #include #include #endif /* __cplusplus */ #include "pros/adi.h" #include "pros/ai_vision.h" #include "pros/colors.h" #include "pros/device.h" #include "pros/distance.h" #include "pros/error.h" #include "pros/ext_adi.h" #include "pros/gps.h" #include "pros/imu.h" #include "pros/link.h" #include "pros/llemu.h" #include "pros/misc.h" #include "pros/motors.h" #include "pros/optical.h" #include "pros/rotation.h" #include "pros/rtos.h" #include "pros/screen.h" #include "pros/vision.h" #ifdef __cplusplus #include "pros/adi.hpp" #include "pros/ai_vision.hpp" #include "pros/colors.hpp" #include "pros/device.hpp" #include "pros/distance.hpp" #include "pros/gps.hpp" #include "pros/imu.hpp" #include "pros/link.hpp" #include "pros/llemu.hpp" #include "pros/misc.hpp" #include "pros/motor_group.hpp" #include "pros/motors.hpp" #include "pros/optical.hpp" #include "pros/rotation.hpp" #include "pros/rtos.hpp" #include "pros/screen.hpp" #include "pros/vision.hpp" #endif #endif // _PROS_API_H_ ================================================ FILE: include/common/cobs.h ================================================ /** * \file common/cobs.h * * Consistent Overhead Byte Stuffing header * * See common/cobs.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include #define COBS_ENCODE_MEASURE_MAX(src_len) ((src_len) + (((src_len) + 253) / 254)) /** * Encodes src in the Consistent Overhead Byte Stuffing algorithm, and writes * the result to dest. dest must be sufficiently long. use cobs_encode_measure() * to compute the size of the buff or use COBS_ENCODE_MEASURE_MAX(src_len) macro * to get the max buffer size needed (e.g. for static allocation) * * \param[out] dest * The location to write the stuffed data to * \param[in] src * The location of the incoming data * \param src_len * The length of the source data * \param prefix * The four character stream identifier * * \return The number of bytes written */ int cobs_encode(uint8_t* restrict dest, const uint8_t* restrict src, const size_t src_len, const uint32_t prefix); /** * Same as cobs_encode() but doesn't write to an output buffer. Used to * determine how much space is needed for src. * * \param[in] src * The location of the incoming data * \param src_len * The length of the source data * \param prefix * The four character stream identifier * * \return The size of src when encoded */ size_t cobs_encode_measure(const uint8_t* restrict src, const size_t src_len, const uint32_t prefix); ================================================ FILE: include/common/gid.h ================================================ /** * \file common/gid.h * * Globally unique Identifer facility header * * See common/gid.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include #include "api.h" struct gid_metadata { uint32_t* const bitmap; // a constant pointer to a bitmap const size_t max; // Maximum gid value const size_t reserved; // first n GIDs may be reserved, at most 32, but at least 1 const size_t bitmap_size; // Cached number of uint32_t's used to map gid_max. // Use gid_size_to_words to compute // internal usage to ensure that GIDs get delegated linearly before wrapping // around back to 0 size_t _cur_val; mutex_t _lock; }; #ifndef UINT32_WIDTH #define UINT32_WIDTH 32 #endif /** * convert the maximum number of gids into a number of words needed to store the * bitmap */ #define gid_size_to_words(size) (((size) + UINT32_WIDTH - 1) / UINT32_WIDTH) /** * Initializes a gid_metadata structure by "freeing" all IDs in the bitmap * * \param[in] metadata * The gid_metadata structure to initialize */ void gid_init(struct gid_metadata* const metadata); /** * Allocates a gid from the gid structure and returns it. * * \param[in] metadata * The gid_metadata to record to the gid structure * * \return The gid, or 0 if there are no more gids left. */ uint32_t gid_alloc(struct gid_metadata* const metadata); /** * Frees the gid specified from the structure. * * \param[in] metadata * The gid_metadata to free from the gid structure * \param id * The gid value indicating the metadata's position in the gid structure */ void gid_free(struct gid_metadata* const metadata, uint32_t id); /** * Checks if the gid specified is allocated. * * \param[in] metadata * The gid_metadata to check * \param id * The gid value indicating the metadata's position in the gid structure * * \return True if the given metadata/id combo is present in the gid structure, * false otherwise. */ bool gid_check(struct gid_metadata* metadata, uint32_t id); ================================================ FILE: include/common/linkedlist.h ================================================ /* * \file common/linkedlist.h * * Linked list implementation for internal use * * This file defines a linked list implementation that operates on the FreeRTOS * heap, and is able to generically store function pointers and data * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once typedef void (*generic_fn_t)(void); typedef struct ll_node_s { union { generic_fn_t func; // Note: a list should not contain both data/funcs void* data; } payload; struct ll_node_s* next; } ll_node_s_t; typedef struct { ll_node_s_t* head; } linked_list_s_t; /** * Initialize a linked list node storing an arbitrary function pointer * * \param func * Function pointer to store in the node * * \return A linked list node that stores a function pointer */ ll_node_s_t* linked_list_init_func_node(generic_fn_t func); /** * Initialize a linked list node storing a pointer to arbitrary data * * \param[in] data * Pointer to data * * \return A linked list node that stores some data */ ll_node_s_t* linked_list_init_data_node(void* data); /** * Initialize a linked list * * \return An initialized linked list */ linked_list_s_t* linked_list_init(); /** * Prepend a node containing a function pointer to a linked list * * If the provided linked list is NULL, it will be initialized first. * * \param[in, out] list * Linked list to which the node will be prepended * \param func * Function pointer with which to initialize the node */ void linked_list_prepend_func(linked_list_s_t* list, generic_fn_t func); /** * Prepend a node containing some data to a linked list * * If the provided linked list is NULL, it will be initialized first. * * \param[in, out] list * Linked list to which the node will be prepended * \param[in] data * Data with which to initialize the node */ void linked_list_prepend_data(linked_list_s_t* list, void* data); /** * Append a node containing a function pointer to a linked list * * If the provided linked list is NULL, it will be initialized first. * * \param[in, out] list * Linked list to which the node will be appended * \param func * Function pointer with which to initialize the node */ void linked_list_append_func(linked_list_s_t* list, generic_fn_t func); /** * Removes the node containing the given function pointer from the linked list * * \param[in, out] list * Linked list from which the node will be removed * \param func * Function pointer to be removed */ void linked_list_remove_func(linked_list_s_t* list, generic_fn_t func); /** * Append a node containing some data to a linked list * * If the provided linked list is NULL, it will be initialized first. * * \param[in, out] list * Linked list to which the node will be appended * \param data * Data with which to initialize the node */ void linked_list_append_data(linked_list_s_t* list, void* data); /** * Remove the node containing the given data from the linked list * * \param[in, out] list * Linked list from which the node will be removed * \param data * Data to be removed */ void linked_list_remove_data(linked_list_s_t* list, void* data); typedef void (*linked_list_foreach_fn_t)(ll_node_s_t*, void*); /** * Perform a function on every node in a linked list * * If the provided linked list is NULL, the function will terminate. * * \param list * Linked list upon which to perform the function * \param cb * Pointer to a callback function that will be provided the current node * as well as some extra data * \param extra_data * Extra data to pass to the callback function */ void linked_list_foreach(linked_list_s_t* list, linked_list_foreach_fn_t, void* extra_data); /** * Frees a linked_list_s_t, making it no longer a valid list. This does not free any * internal data, only the linekd_list structure. * * \param list * List to free */ void linked_list_free(linked_list_s_t* list); ================================================ FILE: include/common/set.h ================================================ /** * \file common/set.h * * Kernel-allocated thread-safe simple sets header * * See common/set.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include #include #include #include "kapi.h" struct set { uint32_t* arr; size_t used; size_t size; static_sem_s_t mtx_buf; mutex_t mtx; }; /** * Initializes a a set. * * \param set * A pointer to a set structure */ void set_initialize(struct set* const set); /** * Adds item to the set if it didn't already exist * * \param set * A pointer to the set structure * \param item * Item to add to the set * * \return Ttrue if the item was added to the set or was already present */ bool set_add(struct set* const set, uint32_t item); /** * Removes an item from the set * * \param set * A pointer to the set structure * \param item * The item to remove * * \return True if the item was removed (or was already not present) */ bool set_rm(struct set* const set, uint32_t item); /** * Checks if the set contains an item * * \param set * A pointer to the set structure * \param item * The item to check * * \return True if the item is in the set */ bool set_contains(struct set* set, uint32_t item); /** * Checks if the list contains an item * * \param list * A pointer to a list of words * \param size * The number of items in the list * \param item * The item to check * * \return True if the item is in the list */ bool list_contains(uint32_t const* const list, const size_t size, const uint32_t item); ================================================ FILE: include/common/string.h ================================================ /** * \file common/string.h * * Extra string functions header * * See common/string.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once /** * strdup but uses the kernel heap * * \param s * Pointer to the string to duplicate * * \return The duplicate string */ char* kstrdup(const char* s); /** * strndup but uses the kernel heap * * \param s * Pointer to the string to duplicate * \param n * The number of characters to duplicate * * \return The duplicate string */ char* kstrndup(const char* s, size_t n); ================================================ FILE: include/kapi.h ================================================ /** * \file kapi.h * * Kernel API header * * Contains additional declarations for use internally within kernel * development. This file includes the FreeRTOS header, which allows for * creation of statically allocated FreeRTOS primitives like tasks, semaphores, * and queues. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "api.h" #include "pros/apix.h" #include "rtos/FreeRTOS.h" #include "rtos/stream_buffer.h" #ifdef __cplusplus extern "C" { #define task_t pros::task_t #define task_fn_t pros::task_fn_t #define mutex_t pros::mutex_t #define sem_t pros::c::sem_t #define queue_t pros::c::queue_t #endif #define KDBG_FILENO 3 #define warn_printf(fmt, ...) dprintf(STDERR_FILENO, "%s:%d -- " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__) #define warn_wprint(str) wprintf("%s", str) #define kprintf(fmt, ...) dprintf(KDBG_FILENO, "%s:%d -- " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__) #define kprint(str) kprintf("%s", str) #ifndef PROS_RELEASING #define kassert(cond) \ do { \ if (!(cond)) { \ kprint("Assertion failed: " #cond); \ } \ } while (0) #else #define kassert(cond) #endif typedef uint32_t task_stack_t; /** * Suspends the scheduler without disabling interrupts. context switches will * not occur while the scheduler is suspended. RTOS ticks that occur while the * scheduler is suspended will be held pending until the scheduler has been * unsuspended with rtos_resume_all() * * When used correctly, this function ensures that operations occur atomically * w.r.t. multitasking. Functions like task_delay, queue_send, and other * functions MUST NOT be called while the scheduler is disabled. */ void rtos_suspend_all(void); /** * Resumes the scheduler. It does not resume unsuspended tasks that were * previously suspended by task_suspend. * * if(rtos_resume_all()) { * task_delay(0); // force context switch * } * \return True if a context switch is necessary. */ int32_t rtos_resume_all(void); /** * Creates a task using statically allocated buffers. All tasks used by the PROS * system must use statically allocated buffers. * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Pointer to the task entry function * \param parameters * Pointer to memory that will be used as a parameter for the task being * created. This memory should not typically come from stack, but rather * from dynamically (i.e., malloc'd) or statically allocated memory. * \param prio * The priority at which the task should run. * TASK_PRIO_DEFAULT plus/minus 1 or 2 is typically used. * \param stack_depth * The number of words (i.e. 4 * stack_depth) available on the task's * stack. TASK_STACK_DEPTH_DEFAULT is typically sufficienct. * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \return A handle by which the newly created task can be referenced. If an * error occurred, NULL will be returned and errno can be checked for hints as * to why task_create failed. */ task_t task_create_static(task_fn_t task_code, void* const param, uint32_t priority, const size_t stack_size, const char* const name, task_stack_t* const stack_buffer, static_task_s_t* const task_buffer); /** * Creates a statically allocated mutex. * * All FreeRTOS primitives must be created statically if they are required for * operation of the kernel. * * \param[out] mutex_buffer * A buffer to store the mutex in * * \return A handle to a newly created mutex. If an error occurred, NULL will be * returned and errno can be checked for hints as to why mutex_create failed. */ mutex_t mutex_create_static(static_sem_s_t* mutex_buffer); /** * Creates a statically allocated semaphore. * * All FreeRTOS primitives must be created statically if they are required for * operation of the kernel. * * \param max_count * The maximum count value that can be reached. * \param init_count * The initial count value assigned to the new semaphore. * \param[out] semaphore_buffer * A buffer to store the semaphore in * * \return A newly created semaphore. If an error occurred, NULL will be * returned and errno can be checked for hints as to why sem_create failed. */ sem_t sem_create_static(uint32_t max_count, uint32_t init_count, static_sem_s_t* semaphore_buffer); /** * Creates a statically allocated queue. * * All FreeRTOS primitives must be created statically if they are required for * operation of the kernel. * * \param length * The maximum number of items that the queue can contain. * \param item_size * The number of bytes each item in the queue will require. * \param[out] storage_buffer * A memory location for data storage * \param[out] queue_buffer * A buffer to store the queue in * * \return A handle to a newly created queue, or NULL if the queue cannot be * created. */ queue_t queue_create_static(uint32_t length, uint32_t item_size, uint8_t* storage_buffer, static_queue_s_t* queue_buffer); /** * Display a fatal error to the built-in LCD/touch screen. * * This function is intended to be used when the integrity of the RTOS cannot be * trusted. No thread-safety mechanisms are used and this function only relies * on the use of the libv5rts. * * \param[in] text * The text string to display to the screen */ void display_fatal_error(const char* text); /** * Prints hex characters to the terminal. * * \param[in] s * The array of hex characters to print * \param len * The number of hex characters to print */ void kprint_hex(uint8_t* s, size_t len); int32_t xTaskGetSchedulerState(); #define taskSCHEDULER_SUSPENDED ((int32_t)0) #define taskSCHEDULER_NOT_STARTED ((int32_t)1) #define taskSCHEDULER_RUNNING ((int32_t)2) #ifdef __cplusplus #undef task_t #undef task_fn_t #undef mutex_t } #endif ================================================ FILE: include/main.h ================================================ /** * \file main.h * * Contains common definitions and header files used throughout your PROS * project. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _PROS_MAIN_H_ #define _PROS_MAIN_H_ /** * If defined, some commonly used enums will have preprocessor macros which give * a shorter, more convenient naming pattern. If this isn't desired, simply * comment the following line out. * * For instance, E_CONTROLLER_MASTER has a shorter name: CONTROLLER_MASTER. * E_CONTROLLER_MASTER is pedantically correct within the PROS styleguide, but * not convenient for most student programmers. */ #define PROS_USE_SIMPLE_NAMES /** * If defined, C++ literals will be available for use. All literals are in the * pros::literals namespace. * * For instance, you can do `4_mtr = 50` to set motor 4's target velocity to 50 */ #define PROS_USE_LITERALS #include "api.h" /** * You should add more #includes here */ //#include "okapi/api.hpp" /** * If you find doing pros::Motor() to be tedious and you'd prefer just to do * Motor, you can use the namespace with the following commented out line. * * IMPORTANT: Only the okapi or pros namespace may be used, not both * concurrently! The okapi namespace will export all symbols inside the pros * namespace. */ // using namespace pros; // using namespace pros::literals; // using namespace okapi; /** * Prototypes for the competition control tasks are redefined here to ensure * that they can be called from user code (i.e. calling autonomous from a * button press in opcontrol() for testing purposes). */ #ifdef __cplusplus extern "C" { #endif void autonomous(void); void initialize(void); void disabled(void); void competition_initialize(void); void opcontrol(void); #ifdef __cplusplus } #endif #ifdef __cplusplus /** * You can add C++-only headers here */ //#include #endif #endif // _PROS_MAIN_H_ ================================================ FILE: include/pros/abstract_motor.hpp ================================================ /** * \file abstract_motor.hpp * \ingroup cpp-abstract-motor * * Contains prototypes for AbstractMotor, the abstract base class of both * motors and motor groups. Abstract motors cannot be directly constructed, but * you can use motors and motor groups as abstract motors. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _PROS_ABSTRACT_MOTORS_HPP_ #define _PROS_ABSTRACT_MOTORS_HPP_ #include #include #include "pros/device.hpp" #include "pros/motors.h" #include "rtos.hpp" namespace pros { inline namespace v5 { /** * \enum MotorBrake * Indicates the current 'brake mode' of a motor. */ enum class MotorBrake { coast = 0, ///< Motor coasts when stopped, traditional behavior brake = 1, ///< Motor brakes when stopped hold = 2, ///< Motor actively holds position when stopped invalid = INT32_MAX ///< Invalid brake mode }; /** * \enum MotorEncoderUnits * Indicates the units used by the motor encoders. */ enum class MotorEncoderUnits { degrees = 0, ///< Position is recorded as angle in degrees as a floating point number deg = 0, ///< Position is recorded as angle in degrees as a floating point number rotations = 1, ///< Position is recorded as angle in rotations as a floating point number counts = 2, ///< Position is recorded as raw encoder ticks as a whole number invalid = INT32_MAX ///< Invalid motor encoder units }; // Alias for MotorEncoderUnits using MotorUnits = MotorEncoderUnits; enum class MotorGears { ratio_36_to_1 = 0, ///< 36:1, 100 RPM, Red gear set red = ratio_36_to_1, ///< 36:1, 100 RPM, Red gear set rpm_100 = ratio_36_to_1, ///< 36:1, 100 RPM, Red gear set ratio_18_to_1 = 1, ///< 18:1, 200 RPM, Green gear set green = ratio_18_to_1, ///< 18:1, 200 RPM, Green gear set rpm_200 = ratio_18_to_1, ///< 18:1, 200 RPM, Green gear set ratio_6_to_1 = 2, ///< 6:1, 600 RPM, Blue gear set blue = ratio_6_to_1, ///< 6:1, 600 RPM, Blue gear set rpm_600 = ratio_6_to_1, ///< 6:1, 600 RPM, Blue gear set invalid = INT32_MAX ///< Error return code }; /** * \enum MotorType * Indicates the type of a motor */ enum class MotorType { v5 = 0, ///< 11w motor exp = 1, ///< 5.5w motor invalid = INT32_MAX ///< Error return code }; // Provide Aliases for MotorGears using MotorGearset = MotorGears; using MotorCart = MotorGears; using MotorCartridge = MotorGears; using MotorGear = MotorGears; /** * \ingroup cpp-abstract-motor */ class AbstractMotor { /** * \addtogroup cpp-abstract-motor * @{ */ public: /// \name Motor movement functions /// These functions allow programmers to make motors move ///@{ /** * Sets the voltage for the motor from -127 to 127. * * This is designed to map easily to the input from the controller's analog * stick for simple opcontrol use. The actual behavior of the motor is * analogous to use of motor_move(), or motorSet() from the PROS 2 API. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param voltage * The new motor voltage from -127 to 127 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t move(std::int32_t voltage) const = 0; /** * Sets the target absolute position for the motor to move to. * * This movement is relative to the position of the motor when initialized or * the position when it was most recently reset with * pros::Motor::set_zero_position(). * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param position * The absolute position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t move_absolute(const double position, const std::int32_t velocity) const = 0; /** * Sets the relative target position for the motor to move to. * * This movement is relative to the current position of the motor as given in * pros::Motor::motor_get_position(). Providing 10.0 as the position parameter * would result in the motor moving clockwise 10 units, no matter what the * current position is. * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param position * The relative position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t move_relative(const double position, const std::int32_t velocity) const = 0; /** * Sets the velocity for the motor. * * This velocity corresponds to different actual speeds depending on the * gearset used for the motor. This results in a range of +-100 for * E_MOTOR_GEARSET_36, +-200 for E_MOTOR_GEARSET_18, and +-600 for * E_MOTOR_GEARSET_6. The velocity is held with PID to ensure consistent * speed, as opposed to setting the motor's voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param velocity * The new motor velocity from -+-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t move_velocity(const std::int32_t velocity) const = 0; /** * Sets the output voltage for the motor from -12000 to 12000 in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1-21 * \param voltage * The new voltage value from -12000 to 12000 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t move_voltage(const std::int32_t voltage) const = 0; /** * Stops the motor using the currently configured brake mode. * * This function sets motor velocity to zero, which will cause it to act * according to the set brake mode. If brake mode is set to MOTOR_BRAKE_HOLD, * this function may behave differently than calling move_absolute(0) * or motor_move_relative(0). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor */ virtual std::int32_t brake(void) const = 0; /** * Changes the output velocity for a profiled movement (motor_move_absolute or * motor_move_relative). This will have no effect if the motor is not following * a profiled movement. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param velocity * The new motor velocity from +-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t modify_profiled_velocity(const std::int32_t velocity) const = 0; /** * Gets the target position set for the motor by the user, with a parameter * for the motor index. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The target position in its encoder units or PROS_ERR_F if the * operation failed, setting errno. */ virtual double get_target_position(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the target position(s) set for the motor(s) by the user * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * * \return A vector containing the target position(s) in its encoder units or PROS_ERR_F if the * operation failed, setting errno. */ virtual std::vector get_target_position_all(void) const = 0; /** * Gets the velocity commanded to the motor by the user. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The commanded motor velocity from +-100, +-200, or +-600, or * PROS_ERR if the operation failed, setting errno. */ virtual std::int32_t get_target_velocity(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the velocity/velocities commanded to the motor(s) by the user * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the commanded motor velocity/velocities from +-100, * +-200, or +-600, or PROS_ERR if the operation failed, setting errno. */ virtual std::vector get_target_velocity_all(void) const = 0; ///@} /// \name Motor telemetry functions /// \addtogroup cpp-motor-telemetry /// These functions allow programmers to collect telemetry from motors ///@{ /** * Gets the actual velocity of the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's actual velocity in RPM or PROS_ERR_F if the operation * failed, setting errno. */ virtual double get_actual_velocity(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the actual velocity/velocities of the motor(s) * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's/motors' actual velocity/velocities in RPM or PROS_ERR_F * if the operation failed, setting errno. */ virtual std::vector get_actual_velocity_all(void) const = 0; /** * Gets the current drawn by the motor in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's current in mA or PROS_ERR if the operation failed, * setting errno. */ virtual std::int32_t get_current_draw(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the current(s) drawn by the motor(s) in mA. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A vector conatining the motor's/motors' current(s) in mA or PROS_ERR if the operation failed, * setting errno. */ virtual std::vector get_current_draw_all(void) const = 0; /** * Gets the direction of movement for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 for moving in the positive direction, -1 for moving in the * negative direction, and PROS_ERR if the operation failed, setting errno. */ virtual std::int32_t get_direction(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the direction(s) of movement for the motor(s). * * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A vector containing 1 for moving in the positive direction, -1 for moving in the * negative direction, and PROS_ERR if the operation failed, setting errno. */ virtual std::vector get_direction_all(void) const = 0; /** * Gets the efficiency of the motor in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's efficiency in percent or PROS_ERR_F if the operation * failed, setting errno. */ virtual double get_efficiency(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the efficiency/efficiencies of the motor(s) in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A vector containing the motor's/motors' efficiency/efficiencies in percent or PROS_ERR_F if the operation * failed, setting errno. */ virtual std::vector get_efficiency_all(void) const = 0; /** * Gets the faults experienced by the motor. * * Compare this bitfield to the bitmasks in pros::motor_fault_e_t. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A bitfield containing the motor's faults. */ virtual std::uint32_t get_faults(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the faults experienced by the motor(s). * * Compare this bitfield to the bitmasks in pros::motor_fault_e_t. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \return A bitfield containing the motor's/motors' faults. */ virtual std::vector get_faults_all(void) const = 0; /** * Gets the flags set by the motor's operation. * * Compare this bitfield to the bitmasks in pros::motor_flag_e_t. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A bitfield containing the motor's flags. */ virtual std::uint32_t get_flags(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the flags set by the motor's/motors' operation. * * Compare this bitfield to the bitmasks in pros::motor_flag_e_t. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A bitfield containing the motor's/motors' flags. */ virtual std::vector get_flags_all(void) const = 0; /** * Gets the absolute position of the motor in its encoder units. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's absolute position in its encoder units or PROS_ERR_F * if the operation failed, setting errno. */ virtual double get_position(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the absolute position(s) of the motor(s) in its encoder units. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's/motors' absolute position(s) in its encoder units or PROS_ERR_F * if the operation failed, setting errno. */ virtual std::vector get_position_all(void) const = 0; /** * Gets the power drawn by the motor in Watts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. */ virtual double get_power(const std::uint8_t index = 0) const = 0; /** * Gets a vector containing the power(s) drawn by the motor(s) in Watts. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's/motors' power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. */ virtual std::vector get_power_all(void) const = 0; /** * Gets the raw encoder count of the motor at a given timestamp. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param[in] timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The raw encoder count at the given timestamp or PROS_ERR if the * operation failed. */ virtual std::int32_t get_raw_position(std::uint32_t* const timestamp, const std::uint8_t index = 0) const = 0; /** * Gets a vector of the raw encoder count(s) of the motor(s) at a given timestamp. * * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \param timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \return A vector containing the raw encoder count(s) at the given timestamp or PROS_ERR if the * operation failed. */ virtual std::vector get_raw_position_all(std::uint32_t* const timestamp) const = 0; /** * Gets the temperature of the motor in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's temperature in degrees Celsius or PROS_ERR_F if the * operation failed, setting errno. */ virtual double get_temperature(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the temperature(s) of the motor(s) in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector containing the motor's/motors' temperature(s) in degrees Celsius or PROS_ERR_F if the * operation failed, setting errno. */ virtual std::vector get_temperature_all(void) const = 0; /** * Gets the torque generated by the motor in Newton Meters (Nm). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's torque in Nm or PROS_ERR_F if the operation failed, * setting errno. */ virtual double get_torque(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the torque(s) generated by the motor(s) in Newton Meters (Nm). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector containing the motor's/motors' torque(s) in Nm or PROS_ERR_F if the operation failed, * setting errno. */ virtual std::vector get_torque_all(void) const = 0; /** * Gets the voltage delivered to the motor in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's voltage in mV or PROS_ERR_F if the operation failed, * setting errno. */ virtual std::int32_t get_voltage(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the voltage(s) delivered to the motor(s) in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector containing the motor's/motors' voltage(s) in mV or PROS_ERR_F if the operation failed, * setting errno. */ virtual std::vector get_voltage_all(void) const = 0; /** * Checks if the motor is drawing over its current limit. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the motor's current limit is being exceeded and 0 if the * current limit is not exceeded, or PROS_ERR if the operation failed, setting * errno. */ virtual std::int32_t is_over_current(const std::uint8_t index = 0) const = 0; /** * Gets a vector of whether each motor is drawing over its current limit. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the motor's current limit is being exceeded and 0 if the * current limit is not exceeded, or PROS_ERR if the operation failed, setting * errno. */ virtual std::vector is_over_current_all(void) const = 0; /** * Gets the temperature limit flag for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the temperature limit is exceeded and 0 if the temperature is * below the limit, or PROS_ERR if the operation failed, setting errno. */ virtual std::int32_t is_over_temp(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the temperature limit flag(s) for the motor(s). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the temperature limit is exceeded and 0 if the temperature is * below the limit, or PROS_ERR if the operation failed, setting errno. */ virtual std::vector is_over_temp_all(void) const = 0; ///@} /// \name Motor configuration functions /// \addtogroup cpp-motor-configuration /// These functions allow programmers to configure the behavior of motors ///@{ /** * Gets the brake mode that was set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return One of MotorBrake, according to what was set for the * motor, or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. */ virtual MotorBrake get_brake_mode(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the brake mode(s) that was set for the motor(s). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector containing MotorBrake(s), according to what was set for the * motor(s), or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. */ virtual std::vector get_brake_mode_all(void) const = 0; /** * Gets the current limit for the motor in mA. * * The default value is 2500 mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's current limit in mA or PROS_ERR if the operation failed, * setting errno. */ virtual std::int32_t get_current_limit(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the current limit(s) for the motor(s) in mA. * * The default value is 2500 mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector containing the motor's/motors' current limit(s) in mA or PROS_ERR if the operation failed, * setting errno. */ virtual std::vector get_current_limit_all(void) const = 0; /** * Gets the encoder units that were set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return One of MotorUnits according to what is set for the * motor or E_MOTOR_ENCODER_INVALID if the operation failed. */ virtual MotorUnits get_encoder_units(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the encoder units that were set for the motor(s). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector of MotorUnits according to what is set for the * motor(s) or E_MOTOR_ENCODER_INVALID if the operation failed. */ virtual std::vector get_encoder_units_all(void) const = 0; /** * Gets the gearset that was set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return One of MotorGears according to what is set for the motor, * or pros::MotorGears::invalid if the operation failed. */ virtual MotorGears get_gearing(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the gearset(s) that was/were set for the motor(s). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector of MotorGears according to what is set for the motor(s), * or pros::MotorGears::invalid if the operation failed. */ virtual std::vector get_gearing_all(void) const = 0; /** * @brief Gets returns a vector with all the port numbers in the motor group. * * @return std::vector */ virtual std::vector get_port_all(void) const = 0; /** * Gets the voltage limit set by the user. * * Default value is 0V, which means that there is no software limitation * imposed on the voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return The motor's voltage limit in V or PROS_ERR if the operation failed, * setting errno. */ virtual std::int32_t get_voltage_limit(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the voltage limit(s) set by the user. * * Default value is 0V, which means that there is no software limitation * imposed on the voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return A vector containing the motor's/motors' voltage limit(s) in V or PROS_ERR if the operation failed, * setting errno. */ virtual std::vector get_voltage_limit_all(void) const = 0; /** * Gets the operation direction of the motor as set by the user. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the motor has been reversed and 0 if the motor was not * reversed, or PROS_ERR if the operation failed, setting errno. */ virtual std::int32_t is_reversed(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the operation direction(s) of the motor(s) as set by the user. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the motor has been reversed and 0 if the motor was not * reversed, or PROS_ERR if the operation failed, setting errno. */ virtual std::vector is_reversed_all(void) const = 0; /** * Gets the type of the motor * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return One of MotorType according to the type of the motor, * or pros::MotorType::invalid if the operation failed */ virtual MotorType get_type(const std::uint8_t index = 0) const = 0; /** * Gets a vector of the type(s) of the motor(s). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector of MotorType according to the type(s) of the motor(s), * or pros::MotorType::invalid if the operation failed. */ virtual std::vector get_type_all(void) const = 0; /** * Sets one of MotorBrake to the motor. Works with the C enum * and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param mode * The MotorBrake to set for the motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_brake_mode(const MotorBrake mode, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_brake_mode(const pros::motor_brake_mode_e_t mode, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_brake_mode_all(const MotorBrake mode) const = 0; virtual std::int32_t set_brake_mode_all(const pros::motor_brake_mode_e_t mode) const = 0; /** * Sets the current limit for the motor in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param limit * The new current limit in mA * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_current_limit(const std::int32_t limit, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_current_limit_all(const std::int32_t limit) const = 0; /** * Sets one of MotorUnits for the motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param units * The new motor encoder units * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_encoder_units(const MotorUnits units, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_encoder_units(const pros::motor_encoder_units_e_t units, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_encoder_units_all(const MotorUnits units) const = 0; virtual std::int32_t set_encoder_units_all(const pros::motor_encoder_units_e_t units) const = 0; /** * Sets one of the gear cartridge (red, green, blue) for the motor. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param gearset * The new motor gearset * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_gearing(const MotorGears gearset, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_gearing(const pros::motor_gearset_e_t gearset, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_gearing_all(const MotorGears gearset) const = 0; virtual std::int32_t set_gearing_all(const pros::motor_gearset_e_t gearset) const = 0; /** * Sets the reverse flag for the motor. * * This will invert its movements and the values returned for its position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param reverse * True reverses the motor, false is default * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_reversed(const bool reverse, const std::uint8_t index = 0) = 0; virtual std::int32_t set_reversed_all(const bool reverse) = 0; /** * Sets the voltage limit for the motor in Volts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param limit * The new voltage limit in Volts * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_voltage_limit(const std::int32_t limit, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_voltage_limit_all(const std::int32_t limit) const = 0; /** * Sets the position for the motor in its encoder units. * * This will be the future reference point for the motor's "absolute" * position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param position * The new reference position in its encoder units * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t set_zero_position(const double position, const std::uint8_t index = 0) const = 0; virtual std::int32_t set_zero_position_all(const double position) const = 0; /** * Sets the "absolute" zero position of the motor to its current position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param index Optional parameter. * The index of the motor to get the target position of. * By default index is 0, and will return an error for an out of bounds index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ virtual std::int32_t tare_position(const std::uint8_t index = 0) const = 0; virtual std::int32_t tare_position_all(void) const = 0; virtual std::int8_t get_port(const std::uint8_t index = 0) const = 0; /** * @brief Returns the number of objects * * @return std::int8_t */ virtual std::int8_t size(void) const = 0; ///@} private: }; } // namespace v5 } // namespace pros ///@} #endif ================================================ FILE: include/pros/adi.h ================================================ /** * \file pros/adi.h * \ingroup c-adi * * Contains prototypes for interfacing with the ADI. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-adi ADI (TriPort) C API * \note The external ADI API can be found [here.](@ref ext-adi) * \note Additional example code for this module can be found in its [Tutorial.](@ref adi) */ #ifndef _PROS_ADI_H_ #define _PROS_ADI_H_ #include #include #ifndef PROS_ERR #define PROS_ERR (INT32_MAX) #endif #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \ingroup c-adi */ /** * \addtogroup c-adi * @{ */ /** * \enum adi_port_config_e * Represents the port type for an ADI port. */ typedef enum adi_port_config_e { E_ADI_ANALOG_IN = 0, E_ADI_ANALOG_OUT = 1, E_ADI_DIGITAL_IN = 2, E_ADI_DIGITAL_OUT = 3, #ifdef _INTELLISENSE #define _DEPRECATE_DIGITAL_IN = E_ADI_DIGITAL_IN #define _DEPRECATE_ANALOG_IN = E_ADI_ANALOG_IN #else #define _DEPRECATE_DIGITAL_IN __attribute__((deprecated("use E_ADI_DIGITAL_IN instead"))) = E_ADI_DIGITAL_IN #define _DEPRECATE_ANALOG_IN __attribute__((deprecated("use E_ADI_ANALOG_IN instead"))) = E_ADI_ANALOG_IN #endif E_ADI_SMART_BUTTON _DEPRECATE_DIGITAL_IN, E_ADI_SMART_POT _DEPRECATE_ANALOG_IN, E_ADI_LEGACY_BUTTON _DEPRECATE_DIGITAL_IN, E_ADI_LEGACY_POT _DEPRECATE_ANALOG_IN, E_ADI_LEGACY_LINE_SENSOR _DEPRECATE_ANALOG_IN, E_ADI_LEGACY_LIGHT_SENSOR _DEPRECATE_ANALOG_IN, E_ADI_LEGACY_GYRO = 10, E_ADI_LEGACY_ACCELEROMETER _DEPRECATE_ANALOG_IN, #undef _DEPRECATE_DIGITAL_IN #undef _DEPRECATE_ANALOG_IN E_ADI_LEGACY_SERVO = 12, E_ADI_LEGACY_PWM = 13, E_ADI_LEGACY_ENCODER = 14, E_ADI_LEGACY_ULTRASONIC = 15, E_ADI_TYPE_UNDEFINED = 255, E_ADI_ERR = PROS_ERR } adi_port_config_e_t; /** * \enum adi_potentiometer_type_e_t * Represents the potentiometer version type. */ typedef enum adi_potentiometer_type_e { E_ADI_POT_EDR = 0, E_ADI_POT_V2 } adi_potentiometer_type_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define ADI_ANALOG_IN pros::E_ADI_ANALOG_IN #define ADI_ANALOG_OUT pros::E_ADI_ANALOG_OUT #define ADI_DIGITAL_IN pros::E_ADI_DIGITAL_IN #define ADI_DIGITAL_OUT pros::E_ADI_DIGITAL_OUT #define ADI_SMART_BUTTON pros::E_ADI_SMART_BUTTON #define ADI_SMART_POT pros::E_ADI_SMART_POT #define ADI_LEGACY_BUTTON pros::E_ADI_LEGACY_BUTTON #define ADI_LEGACY_POT pros::E_ADI_LEGACY_POT #define ADI_LEGACY_LINE_SENSOR pros::E_ADI_LEGACY_LINE_SENSOR #define ADI_LEGACY_LIGHT_SENSOR pros::E_ADI_LEGACY_LIGHT_SENSOR #define ADI_LEGACY_GYRO pros::E_ADI_LEGACY_GYRO #define ADI_LEGACY_ACCELEROMETER pros::E_ADI_LEGACY_ACCELEROMETER #define ADI_LEGACY_SERVO pros::E_ADI_LEGACY_SERVO #define ADI_LEGACY_PWM pros::E_ADI_LEGACY_PWM #define ADI_LEGACY_ENCODER pros::E_ADI_LEGACY_ENCODER #define ADI_LEGACY_ULTRASONIC pros::E_ADI_LEGACY_ULTRASONIC #define ADI_TYPE_UNDEFINED pros::E_ADI_TYPE_UNDEFINED #define ADI_ERR pros::E_ADI_ERR #else #define ADI_ANALOG_IN E_ADI_ANALOG_IN #define ADI_ANALOG_OUT E_ADI_ANALOG_OUT #define ADI_DIGITAL_IN E_ADI_DIGITAL_IN #define ADI_DIGITAL_OUT E_ADI_DIGITAL_OUT #define ADI_SMART_BUTTON E_ADI_SMART_BUTTON #define ADI_SMART_POT E_ADI_SMART_POT #define ADI_LEGACY_BUTTON E_ADI_LEGACY_BUTTON #define ADI_LEGACY_POT E_ADI_LEGACY_POT #define ADI_LEGACY_LINE_SENSOR E_ADI_LEGACY_LINE_SENSOR #define ADI_LEGACY_LIGHT_SENSOR E_ADI_LEGACY_LIGHT_SENSOR #define ADI_LEGACY_GYRO E_ADI_LEGACY_GYRO #define ADI_LEGACY_ACCELEROMETER E_ADI_LEGACY_ACCELEROMETER #define ADI_LEGACY_SERVO E_ADI_LEGACY_SERVO #define ADI_LEGACY_PWM E_ADI_LEGACY_PWM #define ADI_LEGACY_ENCODER E_ADI_LEGACY_ENCODER #define ADI_LEGACY_ULTRASONIC E_ADI_LEGACY_ULTRASONIC #define ADI_TYPE_UNDEFINED E_ADI_TYPE_UNDEFINED #define ADI_ERR E_ADI_ERR #endif #endif #define INTERNAL_ADI_PORT 22 #define NUM_ADI_PORTS 8 #ifdef __cplusplus namespace c { #endif /** @} Add to group c-adi*/ /** * \ingroup c-adi */ /** * \addtogroup c-adi * @{ */ /** * Gets the configuration for the given ADI port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports. * * \param port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') for which to return * the configuration * * \return The ADI configuration for the given port * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * adi_port_set_config(ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * // Displays the value of E_ADI_ANALOG_IN * printf("Port Type: %d\n", adi_port_get_config(ANALOG_SENSOR_PORT)); * } * \endcode */ adi_port_config_e_t adi_port_get_config(uint8_t port); /** * Gets the value for the given ADI port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports. * * \param port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') for which the value * will be returned * * \return The value stored for the given port * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * adi_port_set_config(ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * printf("Port Value: %d\n", adi_get_value(ANALOG_SENSOR_PORT)); * } * \endcode */ int32_t adi_port_get_value(uint8_t port); /** * Configures an ADI port to act as a given sensor type. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports. * * \param port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param type * The configuration type for the port * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * adi_port_set_config(ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * } * \endcode */ int32_t adi_port_set_config(uint8_t port, adi_port_config_e_t type); /** * Sets the value for the given ADI port. * * This only works on ports configured as outputs, and the behavior will change * depending on the configuration of the port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports. * * \param port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') for which the value * will be set * \param value * The value to set the ADI port to * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void initialize() { * adi_port_set_config(DIGITAL_SENSOR_PORT, E_ADI_DIGITAL_OUT); * adi_set_value(DIGITAL_SENSOR_PORT, HIGH); * } * \endcode */ int32_t adi_port_set_value(uint8_t port, int32_t value); /** * Calibrates the analog sensor on the specified port and returns the new * calibration value. * * This method assumes that the true sensor value is not actively changing at * this time and computes an average from approximately 500 samples, 1 ms apart, * for a 0.5 s period of calibration. The average value thus calculated is * returned and stored for later calls to the adi_analog_read_calibrated() and * adi_analog_read_calibrated_HR() functions. These functions will return * the difference between this value and the current sensor value when called. * * Do not use this function when the sensor value might be unstable * (gyro rotation, accelerometer movement). * * \note The ADI currently returns data at 10ms intervals, in constrast to the * calibrate function’s 1ms sample rate. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * * \param port * The ADI port to calibrate (from 1-8, 'a'-'h', 'A'-'H') * * \return The average sensor value computed by this function * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * adi_analog_calibrate(ANALOG_SENSOR_PORT); * printf("Calibrated Reading: %d\n", adi_analog_read_calibrated(ANALOG_SENSOR_PORT)); * // All readings from then on will be calibrated * } * \endcode */ int32_t adi_analog_calibrate(uint8_t port); /** * Gets the 12-bit value of the specified port. * * The value returned is undefined if the analog pin has been switched to a * different mode. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an analog input * * \param port * The ADI port (from 1-8, 'a'-'h', 'A'-'H') for which the value will be * returned * * \return The analog sensor value, where a value of 0 reflects an input voltage * of nearly 0 V and a value of 4095 reflects an input voltage of nearly 5 V * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * printf("Sensor Reading: %d\n", adi_analog_read(ANALOG_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t adi_analog_read(uint8_t port); /** * Gets the 12 bit calibrated value of an analog input port. * * The adi_analog_calibrate() function must be run first. This function is * inappropriate for sensor values intended for integration, as round-off error * can accumulate causing drift over time. Use adi_analog_read_calibrated_HR() * instead. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an analog input * * \param port * The ADI port (from 1-8, 'a'-'h', 'A'-'H') for which the value will be * returned * * \return The difference of the sensor value from its calibrated default from * -4095 to 4095 * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * printf("Sensor Reading: %d\n", adi_analog_read_calibrated(ANALOG_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t adi_analog_read_calibrated(uint8_t port); /** * Gets the 16 bit calibrated value of an analog input port. * * The adi_analog_calibrate() function must be run first. This is intended for * integrated sensor values such as gyros and accelerometers to reduce drift due * to round-off, and should not be used on a sensor such as a line tracker * or potentiometer. * * The value returned actually has 16 bits of "precision", even though the ADC * only reads 12 bits, so that error induced by the average value being between * two values when integrated over time is trivial. Think of the value as the * true value times 16. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an analog input * * \param port * The ADI port (from 1-8, 'a'-'h', 'A'-'H') for which the value will be * returned * * \return The difference of the sensor value from its calibrated default from * -16384 to 16384 * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * adi_analog_calibrate(ANALOG_SENSOR_PORT); * printf("Sensor Reading: %d\n", adi_analog_read_calibrated_HR(ANALOG_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t adi_analog_read_calibrated_HR(uint8_t port); /** * Gets the digital value (1 or 0) of a port configured as a digital input. * * If the port is configured as some other mode, the digital value which * reflects the current state of the port is returned, which may or may not * differ from the currently set value. The return value is undefined for ports * configured as any mode other than a Digital Input. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a digital input * * \param port * The ADI port to read (from 1-8, 'a'-'h', 'A'-'H') * * \return True if the pin is HIGH, or false if it is LOW * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * printf("Sensor Value: %d\n", adi_digital_read(DIGITAL_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t adi_digital_read(uint8_t port); /** * Gets a rising-edge case for a digital button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under the * same circumstances, so only one task should call this function for any given * button. E.g., Task A calls this function for buttons 1 and 2. Task B may call * this function for button 3, but should not for buttons 1 or 2. A typical * use-case for this function is to call inside opcontrol to detect new button * presses, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a digital input * * \param port * The ADI port to read (from 1-8, 'a'-'h', 'A'-'H') * * \return 1 if the button is pressed and had not been pressed * the last time this function was called, 0 otherwise. * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * if (adi_digital_get_new_press(DIGITAL_SENSOR_PORT)) { * // Toggle pneumatics or other state operations * } * delay(5); * } * } * \endcode */ int32_t adi_digital_get_new_press(uint8_t port); /** * Sets the digital value (1 or 0) of a port configured as a digital output. * * If the port is configured as some other mode, behavior is undefined. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a digital output * * \param port * The ADI port to read (from 1-8, 'a'-'h', 'A'-'H') * \param value * An expression evaluating to "true" or "false" to set the output to * HIGH or LOW respectively, or the constants HIGH or LOW themselves * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define DIGITAL_SENSOR_PORT * * void opcontrol() { * bool state = LOW; * while (true) { * state != state; * adi_digital_write(DIGITAL_SENSOR_PORT, state); * delay(5); // toggle the sensor value every 50ms * } * } * \endcode */ int32_t adi_digital_write(uint8_t port, bool value); /** * Configures the port as an input or output with a variety of settings. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * * \param port * The ADI port to read (from 1-8, 'a'-'h', 'A'-'H') * \param mode * One of INPUT, INPUT_ANALOG, INPUT_FLOATING, OUTPUT, or OUTPUT_OD * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * adi_pin_mode(ANALOG_SENSOR_PORT, INPUT_ANALOG); * } * \endcode */ int32_t adi_pin_mode(uint8_t port, uint8_t mode); /** * Sets the speed of the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an motor * * \param port * The ADI port to set (from 1-8, 'a'-'h', 'A'-'H') * \param speed * The new signed speed; -127 is full reverse and 127 is full forward, * with 0 being off * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * adi_motor_set(MOTOR_PORT, 127); // Go full speed forward * delay(1000); * adi_motor_set(MOTOR_PORT, 0); // Stop the motor * } * \endcode */ int32_t adi_motor_set(uint8_t port, int8_t speed); /** * Gets the last set speed of the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an motor * * \param port * The ADI port to get (from 1-8, 'a'-'h', 'A'-'H') * * \return The last set speed of the motor on the given port * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * adi_motor_set(MOTOR_PORT, 127); // Go full speed forward * printf("Commanded Motor Power: %d\n", adi_motor_get(MOTOR_PORT)); // Will display 127 * delay(1000); * adi_motor_set(MOTOR_PORT, 0); // Stop the motor * } * \endcode */ int32_t adi_motor_get(uint8_t port); /** * Stops the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an motor * * \param port * The ADI port to set (from 1-8, 'a'-'h', 'A'-'H') * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * adi_motor_set(MOTOR_PORT, 127); // Go full speed forward * delay(1000); * // adi_motor_set(MOTOR_PORT, 0); // Stop the motor * adi_motor_stop(MOTOR_PORT); // use this instead * } * \endcode */ int32_t adi_motor_stop(uint8_t port); /** * Reference type for an initialized encoder. * * This merely contains the port number for the encoder. */ typedef int32_t adi_encoder_t; /** * Gets the number of ticks recorded by the encoder. * * There are 360 ticks in one revolution. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an encoder * * \param enc * The adi_encoder_t object from adi_encoder_init() to read * * \return The signed and cumulative number of counts since the last start or * reset * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * adi_encoder_t enc = adi_encoder_init(PORT_TOP, PORT_BOTTOM, false); * while (true) { * printf("Encoder Value: %d\n", adi_encoder_get(enc)); * delay(5); * } * } * \endcode */ int32_t adi_encoder_get(adi_encoder_t enc); /** * Creates an encoder object and configures the specified ports accordingly. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an encoder * * \param port_top * The "top" wire from the encoder sensor with the removable cover side * up. This should be in port 1, 3, 5, or 7 ('A', 'C', 'E', or 'G'). * \param port_bottom * The "bottom" wire from the encoder sensor * \param reverse * If "true", the sensor will count in the opposite direction * * \return An adi_encoder_t object to be stored and used for later calls to * encoder functions * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * adi_encoder_t enc = adi_encoder_init(PORT_TOP, PORT_BOTTOM, false); * while (true) { * printf("Encoder Value: %d\n", adi_encoder_get(enc)); * delay(5); * } * } * \endcode */ adi_encoder_t adi_encoder_init(uint8_t port_top, uint8_t port_bottom, bool reverse); /** * Sets the encoder value to zero. * * It is safe to use this method while an encoder is enabled. It is not * necessary to call this method before stopping or starting an encoder. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an encoder * * \param enc * The adi_encoder_t object from adi_encoder_init() to reset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * adi_encoder_t enc = adi_encoder_init(PORT_TOP, PORT_BOTTOM, false); * delay(1000); // Move the encoder around in this time * adi_encoder_reset(enc); // The encoder is now zero again * } * \endcode */ int32_t adi_encoder_reset(adi_encoder_t enc); /** * Disables the encoder and voids the configuration on its ports. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an encoder * * \param enc * The adi_encoder_t object from adi_encoder_init() to stop * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * adi_encoder_t enc = adi_encoder_init(PORT_TOP, PORT_BOTTOM, false); * // Use the encoder * adi_encoder_shutdown(enc); * } * \endcode */ int32_t adi_encoder_shutdown(adi_encoder_t enc); /** * Reference type for an initialized ultrasonic. * * This merely contains the port number for the ultrasonic. */ typedef int32_t adi_ultrasonic_t; /** * Gets the current ultrasonic sensor value in centimeters. * * If no object was found, zero is returned. If the ultrasonic sensor was never * started, the return value is undefined. Round and fluffy objects can cause * inaccurate values to be returned. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an ultrasonic * * \param ult * The adi_ultrasonic_t object from adi_ultrasonic_init() to read * * \return The distance to the nearest object in m^-4 (10000 indicates 1 meter), * measured from the sensor's mounting points. * * \b Example * \code * #define PORT_PING 1 * #define PORT_ECHO 2 * * void opcontrol() { * adi_ultrasonic_t ult = adi_ultrasonic_init(PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * printf("Distance: %d\n", adi_ultrasonic_get(ult)); * delay(5); * } * } * \endcode */ int32_t adi_ultrasonic_get(adi_ultrasonic_t ult); /** * Creates an ultrasonic object and configures the specified ports accordingly. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an ultrasonic * * \param port_ping * The port connected to the orange OUTPUT cable. This should be in port * 1, 3, 5, or 7 ('A', 'C', 'E', 'G'). * \param port_echo * The port connected to the yellow INPUT cable. This should be in the * next highest port following port_ping. * * \return An adi_ultrasonic_t object to be stored and used for later calls to * ultrasonic functions * * \b Example * \code * #define PORT_PING 1 * #define PORT_ECHO 2 * * void opcontrol() { * adi_ultrasonic_t ult = adi_ultrasonic_init(PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * printf("Distance: %d\n", adi_ultrasonic_get(ult)); * delay(5); * } * } * \endcode */ adi_ultrasonic_t adi_ultrasonic_init(uint8_t port_ping, uint8_t port_echo); /** * Disables the ultrasonic sensor and voids the configuration on its ports. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as an ultrasonic * * \param ult * The adi_ultrasonic_t object from adi_ultrasonic_init() to stop * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define PORT_PING 1 * #define PORT_ECHO 2 * * void opcontrol() { * adi_ultrasonic_t ult = adi_ultrasonic_init(PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * printf("Distance: %d\n", adi_ultrasonic_get(ult)); * delay(5); * } * adi_ultrasonic_shutdown(ult); * } * \endcode */ int32_t adi_ultrasonic_shutdown(adi_ultrasonic_t ult); /** * Reference type for an initialized gyroscope. * * This merely contains the port number for the gyroscope. */ typedef int32_t adi_gyro_t; /** * Gets the current gyro angle in tenths of a degree. Unless a multiplier is * applied to the gyro, the return value will be a whole number representing * the number of degrees of rotation times 10. * * There are 360 degrees in a circle, thus the gyro will return 3600 for one * whole rotation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a gyro * * \param gyro * The adi_gyro_t object for which the angle will be returned * * \return The gyro angle in degrees. * * \b Example * \code * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * * void opcontrol() { * adi_gyro_t gyro = adi_gyro_init(GYRO_PORT, GYRO_MULTIPLIER); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", adi_gyro_get(gyro)); * delay(5); * } * } * \endcode */ double adi_gyro_get(adi_gyro_t gyro); /** * Initializes a gyroscope on the given port. If the given port has not * previously been configured as a gyro, then this function starts a 1300 ms * calibration period. * * It is highly recommended that this function be called from initialize() when * the robot is stationary to ensure proper calibration. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a gyro * * \param port * The ADI port to initialize as a gyro (from 1-8, 'a'-'h', 'A'-'H') * \param multiplier * A scalar value that will be multiplied by the gyro heading value * supplied by the ADI * * \return An adi_gyro_t object containing the given port, or PROS_ERR if the * initialization failed. * * \b Example * \code * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * * void opcontrol() { * adi_gyro_t gyro = adi_gyro_init(GYRO_PORT, GYRO_MULTIPLIER); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", adi_gyro_get(gyro)); * delay(5); * } * } * \endcode */ adi_gyro_t adi_gyro_init(uint8_t port, double multiplier); /** * Resets the gyroscope value to zero. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a gyro * * \param gyro * The adi_gyro_t object for which the angle will be returned * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * * void opcontrol() { * adi_gyro_t gyro = adi_gyro_init(GYRO_PORT, GYRO_MULTIPLIER); * uint32_t now = millis(); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", adi_gyro_get(gyro)); * * if (millis() - now > 2000) { * // Reset the gyro every 2 seconds * adi_gyro_reset(gyro); * now = millis(); * } * * delay(5); * } * } * \endcode */ int32_t adi_gyro_reset(adi_gyro_t gyro); /** * Disables the gyro and voids the configuration on its port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a gyro * * \param gyro * The adi_gyro_t object to be shut down * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * * void opcontrol() { * adi_gyro_t gyro = adi_gyro_init(GYRO_PORT, GYRO_MULTIPLIER); * uint32_t now = millis(); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", adi_gyro_get(gyro)); * * if (millis() - now > 2000) { * adi_gyro_shutdown(gyro); * // Shut down the gyro after two seconds * break; * } * * delay(5); * } * } * \endcode */ int32_t adi_gyro_shutdown(adi_gyro_t gyro); /** * Reference type for an initialized potentiometer. * * This merely contains the port number for the potentiometer. */ typedef int32_t adi_potentiometer_t; /** * Initializes a potentiometer on the given port of the original potentiometer. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a potentiometer * * \param port * The ADI port to initialize as a gyro (from 1-8, 'a'-'h', 'A'-'H') * * \return An adi_potentiometer_t object containing the given port, or PROS_ERR if the * initialization failed. * * \b Example * \code * #define POTENTIOMETER_PORT 1 * * void opcontrol() { * adi_potentiometer_t potentiometer = adi_potentiometer_init(POTENTIOMETER_PORT); * while (true) { * // Print the potentiometer's angle * printf("Angle: %lf\n", adi_potentiometer_get_angle(potentiometer)); * delay(5); * } * } * \endcode */ adi_potentiometer_t adi_potentiometer_init(uint8_t port); /** * Initializes a potentiometer on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a potentiometer * * \param port * The ADI port to initialize as a gyro (from 1-8, 'a'-'h', 'A'-'H') * \param potentiometer_type * An adi_potentiometer_type_e_t enum value specifying the potentiometer version type * * \return An adi_potentiometer_t object containing the given port, or PROS_ERR if the * initialization failed. * * \b Example * \code * #define POTENTIOMETER_PORT 1 * #define POTENTIOMETER_TYPE E_ADI_POT_EDR * * void opcontrol() { * adi_potentiometer_t potentiometer = adi_potentiometer_type_init(POTENTIOMETER_PORT, POTENTIOMETER_TYPE); * while (true) { * // Print the potentiometer's angle * printf("Angle: %lf\n", adi_potentiometer_get_angle(potentiometer)); * delay(5); * } * } * \endcode */ adi_potentiometer_t adi_potentiometer_type_init(uint8_t port, adi_potentiometer_type_e_t potentiometer_type); /** * Gets the current potentiometer angle in tenths of a degree. * * The original potentiometer rotates 250 degrees thus returning an angle between 0-250 degrees. * Potentiometer V2 rotates 330 degrees thus returning an angle between 0-330 degrees. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a potentiometer * * \param potentiometer * The adi_potentiometer_t object for which the angle will be returned * * \return The potentiometer angle in degrees. * * \b Example * \code * #define POTENTIOMETER_PORT 1 * * void opcontrol() { * adi_potentiometer_t potentiometer = adi_potentiometer_t(POTENTIOMETER_PORT); * while (true) { * // Print the potnetiometer's angle * printf("Angle: %lf\n", adi_potentiometer_get_angle(potentiometer)); * delay(5); * } * } * \endcode */ double adi_potentiometer_get_angle(adi_potentiometer_t potentiometer); /** * Reference type for an initialized addressable led. * * This merely contains the port number for the led, unlike its use as an * object to store led data in the C++ API. */ typedef int32_t adi_led_t; /** * Initializes a led on the given port of the original led. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - The ADI port given is not a valid port as defined below * EADDRINUSE - The port is not configured for ADI output * * \param port * The ADI port to initialize as a led (from 1-8, 'a'-'h', 'A'-'H') * * \return An adi_led_t object containing the given port, or PROS_ERR if the * initialization failed, setting errno * * \b Example * \code * #define LED_PORT 1 * * void opcontrol() { * adi_led_t led = adi_led_init(LED_PORT); * uint32_t buffer[10] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF, 0x000000, 0x000000, 0x000000}; * while (true) { * // Set the led to the colors in the buffer * adi_led_set(led, buffer, 10); * delay(5); * } * } * \endcode */ adi_led_t adi_led_init(uint8_t port); /** * @brief Clear the entire led strip of color * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of buffer to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example * \code * #define LED_PORT 1 * * void opcontrol() { * adi_led_t led = adi_led_init(LED_PORT); * uint32_t buffer[10] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF, 0x000000, 0x000000, 0x000000}; * while (true) { * // Set the led to the colors in the buffer * adi_led_set(led, buffer, 10); * delay(5); * * // Clear the led strip * adi_led_clear(led); * delay(5); * } * } * \endcode */ int32_t adi_led_clear_all(adi_led_t led, uint32_t* buffer, uint32_t buffer_length); /** * @brief Set the entire led strip using the colors contained in the buffer * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of buffer to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example * \code * #define LED_PORT 1 * * void opcontrol() { * adi_led_t led = adi_led_init(LED_PORT); * uint32_t buffer[10] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF, 0x000000, 0x000000, 0x000000}; * while (true) { * // Set the led strip to the colors in the buffer * adi_led_set(led, buffer, 10); * delay(5); * } * } * \endcode */ int32_t adi_led_set(adi_led_t led, uint32_t* buffer, uint32_t buffer_length); /** * @brief Set the entire led strip to one color * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of buffer to clear * @param color color to set all the led strip value to * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example * \code * #define LED_PORT 1 * * void opcontrol() { * adi_led_t led = adi_led_init(LED_PORT); * uint32_t buffer[10] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF, 0x000000, 0x000000, 0x000000}; * while (true) { * // Set the led strip to red * adi_led_set_all(led, buffer, 10, 0xFF0000); * delay(5); * } * } * \endcode */ int32_t adi_led_set_all(adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color); /** * @brief Set one pixel on the led strip * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of the input buffer * @param color color to clear all the led strip to * @param pixel_position position of the pixel to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example * \code * #define LED_PORT 1 * * void opcontrol() { * adi_led_t led = adi_led_init(LED_PORT); * uint32_t buffer[10] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF, 0x000000, 0x000000, 0x000000}; * while (true) { * // Set the first pixel to red * adi_led_set_pixel(led, buffer, 10, 0xFF0000, 0); * delay(5); * } * } * \endcode */ int32_t adi_led_set_pixel(adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color, uint32_t pixel_position); /** * @brief Clear one pixel on the led strip * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of the input buffer * @param pixel_position position of the pixel to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example * \code * #define LED_PORT 1 * * void opcontrol() { * adi_led_t led = adi_led_init(LED_PORT); * uint32_t buffer[10] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0x00FFFF, 0xFF00FF, 0xFFFFFF, 0x000000, 0x000000, 0x000000}; * while (true) { * // Set the first pixel to red * adi_led_set_pixel(led, buffer, 10, 0xFF0000, 0); * delay(5); * * // Clear the first pixel * adi_led_clear_pixel(led, buffer, 10, 0); * delay(5); * } * } * \endcode */ int32_t adi_led_clear_pixel(adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t pixel_position); /** * \name Ease of use macro definitions * These functions provide ease of use definitions for the ADI functions. * @{ */ /** * Used for adi_digital_write() to specify a logic HIGH state to output. * * In reality, using any non-zero expression or "true" will work to set a pin to * HIGH. */ #define HIGH 1 /** * Used for adi_digital_write() to specify a logic LOW state to output. * * In reality, using a zero expression or "false" will work to set a pin to LOW. */ #define LOW 0 /** * adi_pin_mode() state for a digital input. */ #define INPUT 0x00 /** * adi_pin_mode() state for a digital output. */ #define OUTPUT 0x01 /** * adi_pin_mode() state for an analog input. */ #define INPUT_ANALOG 0x02 /** * adi_pin_mode() state for an analog output. */ #define OUTPUT_ANALOG 0x03 /** @} Name: Ease of use macro definitions*/ /** @} Add to group: c-adi*/ #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_ADI_H_ ================================================ FILE: include/pros/adi.hpp ================================================ /** * \file pros/adi.hpp * \ingroup cpp-adi * * Contains prototypes for interfacing with the ADI. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-adi ADI (TriPort) C++ API * \note The external ADI API can be found [here.](@ref ext-adi) * \note Additional example code for this module can be found in its [Tutorial.](@ref adi) */ #ifndef _PROS_ADI_HPP_ #define _PROS_ADI_HPP_ #include #include #include #include #include #include "pros/adi.h" #define LEGACY_TYPEDEF(old_name, new_name) using old_name [[deprecated("use " #new_name " instead")]] = new_name namespace pros { namespace adi { /** type definition for the pair of smart port and adi port for the basic adi devices */ using ext_adi_port_pair_t = std::pair; /** type definition for the triplet of smart port and two adi ports for the two wire adi devices*/ using ext_adi_port_tuple_t = std::tuple; /** * \ingroup cpp-adi */ class Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as a given sensor type. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param type * The configuration type for the port * * \b Example * \code * #define POTENTIOMETER_PORT 1 * #define POTENTIOMETER_TYPE pros::E_ADI_POT_EDR * * void opcontrol() { * pros::ADIPotentiometer potentiometer (POTENTIOMETER_PORT, POTENTIOMETER_TYPE); * while (true) { * // Get the potentiometer angle * std::cout << "Angle: " << potnetiometer.get_angle(); * pros::delay(10); * } * } * \endcode */ explicit Port(std::uint8_t adi_port, adi_port_config_e_t type = E_ADI_TYPE_UNDEFINED); /** * Configures an ADI port on an adi expander to act as a given sensor type. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the ADI port number * (from 1-8, 'a'-'h', 'A'-'H') to configure * \param type * The configuration type for the port * * \b Example * \code * #define ANALOG_SENSOR_PORT 'a' * #define EXT_ADI_SMART_PORT 1 * * void initialize() { * pros::adi::Port sensor ({EXT_ADI_SMART_PORT, ANALOG_SENSOR_PORT}, E_ADI_ANALOG_IN); * // Displays the value of E_ADI_ANALOG_IN * std::cout << "Port Type: " << sensor.get_config(); * } * \endcode */ explicit Port(ext_adi_port_pair_t port_pair, adi_port_config_e_t type = E_ADI_TYPE_UNDEFINED); /** * Gets the configuration for the given ADI port. * * \return The ADI configuration for the given port * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * void initialize() { * adi_port_set_config(ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * // Displays the value of E_ADI_ANALOG_IN * printf("Port Type: %d\n", adi_port_get_config(ANALOG_SENSOR_PORT)); * } * \endcode */ std::int32_t get_config() const; /** * Gets the value for the given ADI port. * * \return The value stored for the given port * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * pros::adi::Port sensor (ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * std::cout << "Port Value: " << sensor.get_value(); * } * \endcode */ std::int32_t get_value() const; /** * Configures an ADI port to act as a given sensor type. * * \param type * The configuration type for the port * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * pros::adi::Port sensor (ANALOG_SENSOR_PORT, E_ADI_DIGITAL_IN); * // Do things as a digital sensor * // Digital is unplugged and an analog is plugged in * sensor.set_config(E_ADI_ANALOG_IN); * } * \endcode */ std::int32_t set_config(adi_port_config_e_t type) const; /** * Sets the value for the given ADI port. * * This only works on ports configured as outputs, and the behavior will * change depending on the configuration of the port. * * \param value * The value to set the ADI port to * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void initialize() { * pros::adi::Port sensor (DIGITAL_SENSOR_PORT, E_ADI_DIGITAL_OUT); * sensor.set_value(DIGITAL_SENSOR_PORT, HIGH); * } * \endcode */ std::int32_t set_value(std::int32_t value) const; /** * Gets the port of the sensor. * * \return returns a tuple of integer ports. * * \note The parts of the tuple are {smart port, adi port, second adi port (when applicable)}. * * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 // 'A' * * void initialize() { * pros::adi::AnalogIn sensor (DIGITAL_SENSOR_PORT); * * // Getting values from the tuple using std::get * int sensorSmartPort = std::get<0>(sensor.get_port()); // First value * int sensorAdiPort = std::get<1>(sensor.get_port()); // Second value * * // Prints the first and second value from the port tuple (The Adi Port. The first value is the Smart Port) * printf("Sensor Smart Port: %d\n", sensorSmartPort); * printf("Sensor Adi Port: %d\n", sensorAdiPort); * } * \endcode */ virtual ext_adi_port_tuple_t get_port() const; protected: std::uint8_t _smart_port; std::uint8_t _adi_port; }; ///@} class AnalogIn : protected Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as an Analog Input. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * pros::ADIAnalogIn sensor (ANALOG_SENSOR_PORT); * while (true) { * // Use the sensor * } * } * \endcode */ explicit AnalogIn(std::uint8_t adi_port); /** * Configures an ADI port to act as an Analog Input. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define EXT_ADI_SENSOR_PORT 1 * #define ADI_PORT 'a' * * void opcontrol() { * pros::ADIAnalogIn sensor ({EXT_ADI_SMART_PORT, ADI_PORT}); * while (true) { * // Use the sensor * } * } * \endcode */ explicit AnalogIn(ext_adi_port_pair_t port_pair); /** * Calibrates the analog sensor on the specified port and returns the new * calibration value. * * This method assumes that the true sensor value is not actively changing at * this time and computes an average from approximately 500 samples, 1 ms * apart, for a 0.5 s period of calibration. The average value thus calculated * is returned and stored for later calls to the * pros::AnalogIn::get_value_calibrated() and * pros::AnalogIn::get_value_calibrated_HR() functions. These functions * will return the difference between this value and the current sensor value * when called. * * Do not use this function when the sensor value might be unstable (gyro * rotation, accelerometer movement). * * \note The ADI currently returns data at 10ms intervals, in contrast to the * calibrate function’s 1ms sample rate. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as an analog input * * \return The average sensor value computed by this function * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * pros::adi::AnalogIn sensor (ANALOG_SENSOR_PORT); * sensor.calibrate(ANALOG_SENSOR_PORT); * std::cout << "Calibrated Reading:" << sensor.get_value_calibrated(); * // All readings from then on will be calibrated * } * \endcode */ std::int32_t calibrate() const; /** * Gets the 12 bit calibrated value of an analog input port. * * The pros::adi::AnalogIn::calibrate() function must be run first. This * function is inappropriate for sensor values intended for integration, as * round-off error can accumulate causing drift over time. Use * pros::adi::AnalogIn::get_value_calibrated_HR() instead. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as an analog input * * \return The difference of the sensor value from its calibrated default from * -4095 to 4095 * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * pros::adi::AnalogIn sensor (ANALOG_SENSOR_PORT); * sensor.calibrate(ANALOG_SENSOR_PORT); * std::cout << "Calibrated Reading:" << sensor.get_value_calibrated(); * // All readings from then on will be calibrated * } * \endcode */ std::int32_t get_value_calibrated() const; /** * Gets the 16 bit calibrated value of an analog input port. * * The pros::adi::AnalogIn::calibrate() function must be run first. This is * intended for integrated sensor values such as gyros and accelerometers to * reduce drift due to round-off, and should not be used on a sensor such as a * line tracker or potentiometer. * * The value returned actually has 16 bits of "precision", even though the ADC * only reads 12 bits, so that error induced by the average value being * between two values when integrated over time is trivial. Think of the value * as the true value times 16. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as an analog input * * \return The difference of the sensor value from its calibrated default from * -16384 to 16384 * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * pros::adi::AnalogIn sensor (ANALOG_SENSOR_PORT); * sensor.calibrate(ANALOG_SENSOR_PORT); * std::cout << "Calibrated Reading:" << sensor.get_value_calibrated(); * // All readings from then on will be calibrated * } * \endcode */ std::int32_t get_value_calibrated_HR() const; /** * Reads an analog input channel and returns the 12-bit value. * * The value returned is undefined if the analog pin has been switched to a different mode. The meaning of the * returned value varies depending on the sensor attached. * * Inherited from ADIPort::get_value. * * This function uses the following values of errno when an error state is reached: * EADDRINUSE - The port is not configured as an analog input (e.g. the port has been reconfigured) * * \return The analog sensor value, where a value of 0 reflects an input * voltage of nearly 0 V and a value of 4095 reflects an input voltage of * nearly 5 V * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * pros::adi::AnalogIn sensor (ANALOG_SENSOR_PORT); * std::cout << "Sensor Reading:" << sensor.get_value(); * } * \endcode */ using Port::get_value; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * AnalogIn [smart_port: analog_in._smart_port, adi_port: analog_in._adi_port, * value calibrated: (12 bit calibrated value), * value calibrated HR: (16 bit calibrated value), value: (12 bit value)] */ friend std::ostream& operator<<(std::ostream& os, pros::adi::AnalogIn& analog_in); using Port::get_port; }; ///@} // using ADIPotentiometer = ADIAnalogIn; using LineSensor = AnalogIn; using LightSensor = AnalogIn; using Accelerometer = AnalogIn; class AnalogOut : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as an Analog Output. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * pros::AnalogOut sensor (ANALOG_SENSOR_PORT); * // Use the sensor * } * @endcode */ explicit AnalogOut(std::uint8_t adi_port); /** * Configures an ADI port on an adi_expander to act as an Analog Output. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \b Example * \code * #define EXT_ADI_SMART_PORT 1 * #define ADI_PORT 'a' * * void opcontrol() { * pros::AnalogOut sensor ({EXT_ADI_SMART_PORT, ADI_PORT}); * // Use the sensor * } * \endcode */ explicit AnalogOut(ext_adi_port_pair_t port_pair); /** * Sets the output for the Analog Output from 0 (0V) to 4095 (5V). * * Inherited from ADIPort::set_value. * * This function uses the following values of errno when an error state is reached: * EACCES - Another resource is currently trying to access the ADI. * * \param value * The value to set the ADI port to * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * pros::AnalogOut sensor (ANALOG_SENSOR_PORT); * sensor.set_value(4095); // Set the port to 5V * } * \endcode */ using Port::set_value; using Port::get_port; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * AnalogOut [smart_port: analog_out._smart_port, adi_port: analog_out._adi_port, * value: (value)] */ friend std::ostream& operator<<(std::ostream& os, pros::adi::AnalogOut& analog_out); }; ///@} class DigitalOut : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as a Digital Output. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param init_state * The initial state for the port * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * bool state = LOW; * pros::adi::DigitalOut sensor (DIGITAL_SENSOR_PORT, state); * while (true) { * state != state; * sensor.set_value(state); * pros::delay(10); // toggle the sensor value every 50ms * } * } * \endcode */ explicit DigitalOut(std::uint8_t adi_port, bool init_state = LOW); /** * Configures an ADI port on an adi_expander to act as a Digital Output. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param init_state * The initial state for the port * * \b Example * \code * #define EXT_ADI_SMART_PORT 1 * #define ADI_PORT 'a' * * void opcontrol() { * bool state = LOW; * pros::adi::DigitalOut sensor ({EXT_ADI_SMART_PORT , ADI_PORT}); * while (true) { * state != state; * sensor.set_value(state); * pros::delay(10); // toggle the sensor value every 50ms * } * } * \endcode */ explicit DigitalOut(ext_adi_port_pair_t port_pair, bool init_state = LOW); /** * Sets the digital value (1 or 0) of a pin. * * Inherited from ADIPort::set_value. * * This function uses the following values of errno when an error state is * reached: * EADDRINUSE - The port is not configured as a digital output (e.g. the port has been reconfigured) * * \param value * The value to set the ADI port to * * \return if the operation was successful or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * bool state = LOW; * pros::adi::DigitalOut sensor (DIGITAL_SENSOR_PORT); * while (true) { * state != state; * sensor.set_value(state); * pros::delay(10); // toggle the sensor value every 50ms * } * } * \endcode */ using Port::set_value; using Port::get_port; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * DigitalOut [smart_port: digital_out._smart_port, adi_port: digital_out._adi_port, * value: (value)] */ friend std::ostream& operator<<(std::ostream& os, pros::adi::DigitalOut& digital_out); }; ///@} class DigitalIn : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as a Digital Input. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * pros::adi::DigitalIn sensor (ANALOG_SENSOR_PORT); * // Use the sensor * } * \endcode */ explicit DigitalIn(std::uint8_t adi_port); /** * Configures an ADI port on an adi_expander to act as a Digital Input. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \b Example * \code * #define EXT_ADI_SMART_PORT 1 * #define ADI_PORT 'a' * * void opcontrol() { * pros::adi::DigitalIn sensor ({EXT_ADI_SMART_PORT, ADI_PORT}); * // Use the sensor * } * \endcode */ explicit DigitalIn(ext_adi_port_pair_t port_pair); /** * Gets a rising-edge case for a digital button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under * the same circumstances, so only one task should call this function for any * given button. E.g., Task A calls this function for buttons 1 and 2. Task B * may call this function for button 3, but should not for buttons 1 or 2. A * typical use-case for this function is to call inside opcontrol to detect * new button presses, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a digital input * * \return 1 if the button is pressed and had not been pressed the last time * this function was called, 0 otherwise. * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * pros::adi::DigitalIn sensor (DIGITAL_SENSOR_PORT); * while (true) { * if (sensor.get_new_press()) { * // Toggle pneumatics or other state operations * } * pros::delay(10); * } * } * \endcode */ std::int32_t get_new_press() const; /** * Gets the digital value (1 or 0) of a pin. * * Inherited from ADIPort::get_value. * * This function uses the following values of errno when an error state is reached: * * EADDRINUSE - The port is not configured as a digital input (e.g. the port has been reconfigured) * * Analogous to adi_digital_read. * * \return The value stored for the given port * * \b Example * \code * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * pros::adi::DigitalIn sensor (DIGITAL_SENSOR_PORT); * while (true) { * std::cout << "Sensor Value:" << sensor.get_value(); * pros::delay(10); * } * } * \endcode */ using Port::get_value; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * DigitalIn [smart_port: digital_in._smart_port, adi_port: digital_in._adi_port, * value: (value)] */ friend std::ostream& operator<<(std::ostream& os, pros::adi::DigitalIn& digital_in); using Port::get_port; }; ///@} // Derived Class(es) from DigitalIn using Button = DigitalIn; class Motor : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as a Motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * pros::adi::Motor motor (MOTOR_PORT); * motor.set_value(127); // Go full speed forward * std::cout << "Commanded Motor Power: " << motor.get_value(); // Will display 127 * delay(1000); * motor.set_value(0); // Stop the motor * } * \endcode */ explicit Motor(std::uint8_t adi_port); /** * Configures an ADI port on an adi_expander to act as a Motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * * \b Example * \code * #define EXT_ADI_SMART_PORT 1 * #define ADI_MOTOR_PORT 'a' * * void opcontrol() { * pros::adi::Motor motor ({EXT_ADI_SMART_PORT, ADI_MOTOR_PORT}); * motor.set_value(127); // Go full speed forward * std::cout << "Commanded Motor Power: " << motor.get_value(); // Will display 127 * delay(1000); * motor.set_value(0); // Stop the motor * } * \endcode */ explicit Motor(ext_adi_port_pair_t port_pair); /** * Stops the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * pros::adi::Motor motor (MOTOR_PORT); * motor.set_value(127); // Go full speed forward * std::cout << "Commanded Motor Power: " << motor.get_value(); // Will display 127 * delay(1000); * motor.stop(); // Stop the motor * } * \endcode */ std::int32_t stop() const; /** * Sets the speed of the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a motor * * \param value * The new signed speed; -127 is full reverse and 127 is full forward, * with 0 being off * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * pros::adi::Motor motor (MOTOR_PORT); * motor.set_value(127); // Go full speed forward * std::cout << "Commanded Motor Power: " << motor.get_value(); // Will display 127 * delay(1000); * motor.set_value(0); // Stop the motor * } * \endcode */ using Port::set_value; /** * Gets the last set speed of the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a motor * * \return The last set speed of the motor on the given * * \b Example * \code * #define MOTOR_PORT 1 * * void opcontrol() { * pros::adi::Motor motor (MOTOR_PORT); * motor.set_value(127); // Go full speed forward * std::cout << "Commanded Motor Power: " << motor.get_value(); // Will display 127 * delay(1000); * motor.set_value(0); // Stop the motor * } * \endcode */ using Port::get_value; using Port::get_port; }; ///@} class Encoder : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures a set of ADI ports to act as an Encoder. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port_top * The "top" wire from the encoder sensor with the removable cover side up * \param adi_port_bottom * The "bottom" wire from the encoder sensor * \param reverse * If "true", the sensor will count in the opposite direction * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * pros::adi::Encoder sensor (PORT_TOP, PORT_BOTTOM, false); * // Use the sensor * } * \endcode */ explicit Encoder(std::uint8_t adi_port_top, std::uint8_t adi_port_bottom, bool reversed = false); /** * Configures a set of ADI ports on an adi_expander to act as an Encoder. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_tuple * The tuple of the smart port number, the "top" wire from the encoder * sensor with the removable cover side up, and the "bottom" wire from * the encoder sensor * \param reverse * If "true", the sensor will count in theopposite direction * * \b Example * \code * #define PORT_TOP 'A' * #define PORT_BOTTOM 'B' * #define SMART_PORT 1 * * void opcontrol() { * pros::adi::Encoder sensor ({ SMART_PORT, PORT_TOP, PORT_BOTTOM }, false); * // Use the sensor * } * \endcode */ explicit Encoder(ext_adi_port_tuple_t port_tuple, bool reversed = false); /** * Sets the encoder value to zero. * * It is safe to use this method while an encoder is enabled. It is not * necessary to call this method before stopping or starting an encoder. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * pros::adi::Encoder sensor (PORT_TOP, PORT_BOTTOM, false); * delay(1000); // Move the encoder around in this time * sensor.reset(); // The encoder is now zero again * } * \endcode */ std::int32_t reset() const; /** * Gets the number of ticks recorded by the encoder. * * There are 360 ticks in one revolution. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a motor * * \return The signed and cumulative number of counts since the last start or * * \b Example * \code * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * pros::adi::Encoder sensor (PORT_TOP, PORT_BOTTOM, false); * while (true) { * std::cout << "Encoder Value: " << sensor.get_value(); * pros::delay(10); * } * } * \endcode */ std::int32_t get_value() const; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * Encoder [smart_port: encoder._smart_port, adi_port: encoder._adi_port, * value: (value)] */ friend std::ostream& operator<<(std::ostream& os, pros::adi::Encoder& encoder); ext_adi_port_tuple_t get_port() const override; private: ext_adi_port_pair_t _port_pair; }; ///@} class Ultrasonic : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures a set of ADI ports to act as an Ultrasonic sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_ping * The port connected to the orange OUTPUT cable. This should be in port * 1, 3, 5, or 7 ('A', 'C', 'E', 'G'). * \param port_echo * The port connected to the yellow INPUT cable. This should be in the * next highest port following port_ping. * * \b Example * \code * #define PORT_PING 1 * #define PORT_ECHO 2 * * void opcontrol() { * pros::adi::Ultrasonic sensor (PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * std::cout << "Distance: " << sensor.get_value(); * pros::delay(10); * } * } * \endcode */ explicit Ultrasonic(std::uint8_t adi_port_ping, std::uint8_t adi_port_echo); /** * Configures a set of ADI ports on an adi_expander to act as an Ultrasonic sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_tuple * The tuple of the smart port number, the port connected to the orange * OUTPUT cable (1, 3, 5, 7 or 'A', 'C', 'E', 'G'), and the port * connected to the yellow INPUT cable (the next) highest port * following port_ping). * * \b Example * \code * #define PORT_PING 'A' * #define PORT_ECHO 'B' * #define SMART_PORT 1 * * void opcontrol() { * pros::adi::Ultrasonic sensor ( {{ SMART_PORT, PORT_PING, PORT_ECHO }} ); * while (true) { * // Print the distance read by the ultrasonic * std::cout << "Distance: " << sensor.get_value(); * pros::delay(10); * } * } * \endcode */ explicit Ultrasonic(ext_adi_port_tuple_t port_tuple); /** * Gets the current ultrasonic sensor value in centimeters. * * If no object was found, zero is returned. If the ultrasonic sensor was * never started, the return value is undefined. Round and fluffy objects can * cause inaccurate values to be returned. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as an ultrasonic * * \return The distance to the nearest object in m^-4 (10000 indicates 1 * meter), measured from the sensor's mounting points. * * \b Example * \code * #define PORT_PING 1 * #define PORT_ECHO 2 * * void opcontrol() { * pros::adi::Ultrasonic sensor (PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * std::cout << "Distance: " << sensor.get_value(); * pros::delay(10); * } * } * \endcode */ std::int32_t get_value() const; using Port::get_port; }; ///@} class Gyro : private Port { /** * \addtogroup cpp-adi * @{ */ public: /** * Initializes a gyroscope on the given port. If the given port has not * previously been configured as a gyro, then this function starts a 1300ms * calibration period. * * It is highly recommended that an Gyro object be created in initialize() * when the robot is stationary to ensure proper calibration. If an Gyro * object is declared at the global scope, a hardcoded 1300ms delay at the * beginning of initialize will be necessary to ensure that the gyro's * returned values are correct at the beginning of autonomous/opcontrol. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port to initialize as a gyro (from 1-8, 'a'-'h', 'A'-'H') * \param multiplier * A scalar value that will be multiplied by the gyro heading value * supplied by the * * \b Example * \code * #define GYRO_PORT 1 * * void opcontrol() { * pros::adi::Gyro gyro (GYRO_PORT); * while (true) { * // Get the gyro heading * std::cout << "Distance: " << gyro.get_value(); * pros::delay(10); * } * } * \endcode */ explicit Gyro(std::uint8_t adi_port, double multiplier = 1); /** * Initializes a gyroscope on the given port of an adi expander. If the given * port has not previously been configured as a gyro, then this function starts * a 1300ms calibration period. * * It is highly recommended that an adi::Gyro object be created in initialize() * when the robot is stationary to ensure proper calibration. If an adi::Gyro * object is declared at the global scope, a hardcoded 1300ms delay at the * beginning of initialize will be necessary to ensure that the gyro's * returned values are correct at the beginning of autonomous/opcontrol. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param multiplier * A scalar value that will be multiplied by the gyro heading value * supplied by the * * \b Example * \code * #define ADI_GYRO_PORT 'a' * #define SMART_PORT 1 * * void opcontrol() { * pros::adi::Gyro gyro ({SMART_PORT ,ADI_GYRO_PORT}); * while (true) { * // Get the gyro heading * std::cout << "Distance: " << gyro.get_value(); * pros::delay(10); * } * } * \endcode */ explicit Gyro(ext_adi_port_pair_t port_pair, double multiplier = 1); /** * Gets the current gyro angle in tenths of a degree. Unless a multiplier is * applied to the gyro, the return value will be a whole number representing * the number of degrees of rotation times 10. * * There are 360 degrees in a circle, thus the gyro will return 3600 for one * whole rotation. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a gyro * * \return The gyro angle in degrees. * * \b Example * \code * #define GYRO_PORT 1 * * void opcontrol() { * pros::adi::Gyro gyro (GYRO_PORT); * while (true) { * // Get the gyro heading * std::cout << "Distance: " << gyro.get_value(); * pros::delay(10); * } * } * \endcode */ double get_value() const; /** * Resets the gyroscope value to zero. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a gyro * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GYRO_PORT 1 * * void opcontrol() { * pros::adi::Gyro gyro (GYRO_PORT); * std::uint32_t now = pros::millis(); * while (true) { * // Get the gyro heading * std::cout << "Distance: " << gyro.get_value(); * * if (pros::millis() - now > 2000) { * // Reset the gyro every 2 seconds * gyro.reset(); * now = pros::millis(); * } * * pros::delay(10); * } * } * \endcode */ std::int32_t reset() const; using Port::get_port; }; ///@} class Potentiometer : public AnalogIn { /** * \addtogroup cpp-adi * @{ */ public: /** * Configures an ADI port to act as a Potentiometer. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param potentiometer_type * An adi_potentiometer_type_e_t enum value specifying the potentiometer version type * * \b Example * \code * #define POTENTIOMETER_PORT 1 * #define POTENTIOMETER_TYPE pros::E_ADI_POT_EDR * * void opcontrol() { * pros::adi::Potentiometer potentiometer (POTENTIOMETER_PORT, POTENTIOMETER_TYPE); * while (true) { * // Get the potentiometer angle * std::cout << "Angle: " << potentiometer.get_angle(); * pros::delay(10); * } * } * \endcode */ explicit Potentiometer(std::uint8_t adi_port, adi_potentiometer_type_e_t potentiometer_type = E_ADI_POT_EDR); /** * Configures an ADI port on an adi_expander to act as a Potentiometer. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param potentiometer_type * An adi_potentiometer_type_e_t enum value specifying the potentiometer version type * * \b Example * \code * #define ADI_POTENTIOMETER_PORT 'a' * #define SMART_PORT 1 * * void opcontrol() { * pros::adi::Potentiometer potentiometer ({SMART_PORT, ADI_POTENTIOMETER_PORT}); * while (true) { * // Get the potentiometer angle * std::cout << "Angle: " << potentiometer.get_angle(); * pros::delay(10); * } * } * \endcode */ explicit Potentiometer(ext_adi_port_pair_t port_pair, adi_potentiometer_type_e_t potentiometer_type = E_ADI_POT_EDR); /** * Gets the current potentiometer angle in tenths of a degree. * * The original potentiometer rotates 250 degrees thus returning an angle between 0-250 degrees. * Potentiometer V2 rotates 330 degrees thus returning an angle between 0-330 degrees. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a potentiometer * * \return The potentiometer angle in degrees. * * \b Example * \code * #define ADI_POTENTIOMETER_PORT 'a' * #define SMART_PORT 1 * * void opcontrol() { * pros::adi::Potentiometer potentiometer ({{ SMART_PORT , ADI_POTENTIOMETER_PORT }}); * while (true) { * // Get the potentiometer angle * std::cout << "Angle: " << potentiometer.get_angle(); * pros::delay(10); * } * } * \endcode */ double get_angle() const; /** * Gets the 12-bit value of the specified port. * * The value returned is undefined if the analog pin has been switched to a * different mode. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a potentiometer * * \return The analog sensor value, where a value of 0 reflects an input * voltage of nearly 0 V and a value of 4095 reflects an input voltage of * nearly 5 V */ using AnalogIn::get_value; /** * Calibrates the potentiometer on the specified port and returns the new * calibration value. * * This method assumes that the potentiometer value is not actively changing at * this time and computes an average from approximately 500 samples, 1 ms * apart, for a 0.5 s period of calibration. The average value thus calculated * is returned and stored for later calls to the * pros::adi::Potentiometer::get_value_calibrated() function. This function * will return the difference between this value and the current sensor value * when called. * * Do not use this function when the potentiometer value might be unstable (rotating the potentiometer) * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a potentiometer * * \return The average potentiometer value computed by this function */ using AnalogIn::calibrate; /** * Gets the 12 bit calibrated value of a potentiometer port. * * The pros::adi::Potentiometer::calibrate() function must be run first. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port is not configured as a potentiometer * * \return The difference of the potentiometer value from its calibrated default from * -4095 to 4095 */ using AnalogIn::get_value_calibrated; /** * This is the overload for the << operator for printing to streams * Potentiometer [value: (value), value calibrated: (calibrated value), * angle: (angle)] * Prints in format(this below is all in one line with no new line): */ friend std::ostream& operator<<(std::ostream& os, pros::adi::Potentiometer& potentiometer); using Port::get_port; }; ///@} class Led : protected Port { /** * \addtogroup cpp-adi * @{ */ public: /** * @brief Configures an ADI port to act as a LED. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param length * The number of LEDs in the chain * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set entire LED strip to red * led.set_all(0xFF0000); * pros::delay(20); * } * } * \endcode * */ explicit Led(std::uint8_t adi_port, std::uint32_t length); /** * @brief Configures an ADI port on a adi_expander to act as a LED. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param length * The number of LEDs in the chain * * \b Example: * \code * #define LED_PORT 'a' * #define SMART_PORT 1 * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led ({SMART_PORT, LED_PORT}, LED_LENGTH); * while (true) { * // Set entire LED strip to red * led.set_all(0xFF0000); * pros::delay(20); * } * } * \endcode */ explicit Led(ext_adi_port_pair_t port_pair, std::uint32_t length); /** * @brief Operator overload to access the buffer in the ADILed class, it is * recommended that you call .update(); after doing any operations with this. * * @param i 0 indexed pixel of the lED * @return uint32_t& the address of the buffer at i to modify * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set the first 3 pixels to red, green, and blue * led.set_pixel(0xFF0000, 0); * led.set_pixel(0x00FF00, 1); * led.set_pixel(0x0000FF, 2); * pros::delay(20); * * // Use the [] operator to set the first pixel to black * led.operator[](0) = 0x000000; * led.update(); * pros::delay(20); * } * } */ std::uint32_t& operator[](size_t i); /** * @brief Clear the entire led strip of color * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A parameter is out of bounds/incorrect * EADDRINUSE - The port is not configured for ADI output * * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set the first 3 pixels to red, green, and blue * led.set_pixel(0xFF0000, 0); * led.set_pixel(0x00FF00, 1); * led.set_pixel(0x0000FF, 2); * pros::delay(20); * * // Clear the led strip of color * led.clear(); * pros::delay(20); * } * } * \endcode */ std::int32_t clear_all(); std::int32_t clear(); /** * @brief Force the LED strip to update with the current buffered values, this * should be called after any changes to the buffer using the [] operator. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A parameter is out of bounds/incorrect * EADDRINUSE - The port is not configured for ADI output * * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set the first 3 pixels to red, green, and blue * led.set_pixel(0xFF0000, 0); * led.set_pixel(0x00FF00, 1); * led.set_pixel(0x0000FF, 2); * pros::delay(20); * * // Use the [] operator to set the first pixel to black * led.operator[](0) = 0x000000; * // Update the led strip with the new values * led.update(); * pros::delay(20); * } * } * \endcode */ std::int32_t update() const; /** * @brief Set the entire led strip to one color * * This function uses the following values of errno when an error state is * reached: * EINVAL - A parameter is out of bounds/incorrect * EADDRINUSE - The port is not configured for ADI output * * @param color color to set all the led strip value to * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set the entire led strip to blue * led.set_all(0x0000FF); * pros::delay(20); * } * } * \endcode */ std::int32_t set_all(uint32_t color); /** * @brief Set one pixel on the led strip * * This function uses the following values of errno when an error state is * reached: * EINVAL - A parameter is out of bounds/incorrect * EADDRINUSE - The port is not configured for ADI output * * @param color color to clear all the led strip to * @param pixel_position position of the pixel to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set the first pixel to blue * led.set_pixel(0x0000FF, 0); * pros::delay(20); * } * } * \endcode */ std::int32_t set_pixel(uint32_t color, uint32_t pixel_position); /** * @brief Clear one pixel on the led strip * * This function uses the following values of errno when an error state is * reached: * EINVAL - A parameter is out of bounds/incorrect * EADDRINUSE - The port is not configured for ADI output * * @param pixel_position position of the pixel to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Set the first pixel to blue * led.set_pixel(0x0000FF, 0); * pros::delay(20); * * // Clear the first pixel * led.clear_pixel(0); * pros::delay(20); * } * } * \endcode */ std::int32_t clear_pixel(uint32_t pixel_position); /** * @brief Get the length of the led strip * * This function uses the following values of errno when an error state is * reached: * EINVAL - A parameter is out of bounds/incorrect * EADDRINUSE - The port is not configured for ADI output * * @return The length (in pixels) of the LED strip * * \b Example: * \code * #define LED_PORT 'a' * #define LED_LENGTH 3 * * void opcontrol() { * pros::Led led (LED_PORT, LED_LENGTH); * while (true) { * // Get the length of the led strip * int length = led.length(); * pros::lcd::print(1, "Length: %d", length); * pros::delay(20); * } * } * \endcode */ std::int32_t length(); using Port::get_port; protected: std::vector _buffer; }; ///@} /// @brief Alias for ADILed using LED = Led; class Pneumatics : public DigitalOut { /** * \addtogroup cpp-adi * @{ */ public: /** * Creates a Pneumatics object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param start_extended * If true, the pneumatic will start extended when the program starts. * By default, the piston starts retracted when the program starts. * \param extended_is_low * A flag to set whether the the pneumatic is extended when the ADI * it receives a high or a low value. When true, the extended state * corresponds to a output low on the ADI port. This allows the user * to reverse the behavior of the pneumatics if needed. * * /b Example: * \code * void opcontrol() { * pros::adi::Pneumatics left_piston('a', false); // Starts retracted, extends when the ADI port is high * pros::adi::Pneumatics right_piston('b', false, true); // Starts retracted, extends when the ADI port is low * * pros::Controller master(pros::E_CONTROLLER_MASTER); * * while (true) { * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_L1)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_L2)) { * left_piston.retract(); * } * * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_R1)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_2)) { * left_piston.retract(); * } * * pros::delay(10); * } * * \endcode */ explicit Pneumatics(std::uint8_t adi_port, bool start_extended, bool extended_is_low = false); /** * Creates a Pneumatics object for the given port pair. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * * \param port_pair * The pair of the smart port number (from 1-22) and the * ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param start_extended * If true, the pneumatic will start extended when the program starts. * By default, the piston starts retracted when the program starts. * \param extended_is_low * A flag to set whether the the pneumatic is extended when the ADI * it receives a high or a low value. When true, the extended state * corresponds to a output low on the ADI port. This allows the user * to reverse the behavior of the pneumatics if needed. * * /b Example: * \code * void opcontrol() { * pros::adi::Pneumatics left_piston({1, 'a'}, false); // Starts retracted, extends when the ADI port is high * pros::adi::Pneumatics right_piston({1, 'b'}, false, true); // Starts retracted, extends when the ADI port is *low * * pros::Controller master(pros::E_CONTROLLER_MASTER); * * while (true) { * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_L1)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_L2)) { * left_piston.retract(); * } * * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_R1)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_R2)) { * left_piston.retract(); * } * * pros::delay(10); * } * } * \endcode */ explicit Pneumatics(ext_adi_port_pair_t port_pair, bool start_extended, bool extended_is_low = false); /** * Extends the piston, if not already extended. * * \return 1 if the piston newly extended, 0 if the piston was already * extended, or PROS_ERR is the operation failed, setting errno. * * \b Example: * \code * void opcontrol() { * pros::adi::Pneumatics piston({1, 'a'}, false); // Starts retracted, extends when the ADI port is high * * pros::Controller master(pros::E_CONTROLLER_MASTER); * * while (true) { * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_X)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_B)) { * left_piston.retract(); * } * if(mastetr.get_digital(pros::E_CONTROLLER_DIGITAL_A)) { * left_piston.toggle(); * } * * pros::delay(10); * } * } * \endcode */ std::int32_t extend(); /** * Retracts the piston, if not already retracted. * * \return 1 if the piston newly retracted, 0 if the piston was already * retracted, or PROS_ERR is the operation failed, setting errno. * * \b Example: * \code * void opcontrol() { * pros::adi::Pneumatics piston({1, 'a'}, false); // Starts retracted, extends when the ADI port is high * * pros::Controller master(pros::E_CONTROLLER_MASTER); * * while (true) { * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_X)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_B)) { * left_piston.retract(); * } * if(mastetr.get_digital(pros::E_CONTROLLER_DIGITAL_A)) { * left_piston.toggle(); * } * * pros::delay(10); * } * } * \endcode */ std::int32_t retract(); /** * Puts the piston into the opposite state of its current state. * If it is retracted, it will extend. If it is extended, it will retract. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \return 1 if the piston successfully toggled, or PROS_ERR if the * operation failed, setting errno. * *\b Example: * \code * void opcontrol() { * pros::adi::Pneumatics piston({1, 'a'}, false); // Starts retracted, extends when the ADI port is high * * pros::Controller master(pros::E_CONTROLLER_MASTER); * * while (true) { * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_X)) { * left_piston.extend(); * } * if(master.get_digital(pros::E_CONTROLLER_DIGITAL_B)) { * left_piston.retract(); * } * if(mastetr.get_digital(pros::E_CONTROLLER_DIGITAL_A)) { * left_piston.toggle(); * } * * pros::delay(10); * } * } * \endcode */ std::int32_t toggle(); /** * Returns whether the piston is extended or not. * * \return true if the piston is extended, false if it is retracted. * * \b Example * \code * #define ADI_PNEUMATICS_PORT 'a' * * void opcontrol() { * pros::adi::Pneumatics pneumatics (ADI_PNEUMATICS_PORT); * while (true) { * // Check if the piston is extended * if (pneumatics.is_extended()) { * printf("The pneumatic is extended\n"); * } * else { * printf("The pneumatic is not extended\n"); * } * * pros::delay(10); * } * } * \endcode */ bool is_extended() const; private: bool state; // Holds the physical state of the ADI port bool extended_is_low; // A flag that sets whether extended corresponds to // a low signal }; ///@} } // namespace adi /* Pros4 upgrade backwards compatibility for ADI api. Prints a deprecated warning when user uses old pros::ADIDevice style API. Remove when and if fully removing old API. */ LEGACY_TYPEDEF(ADIPort, pros::adi::Port); LEGACY_TYPEDEF(ADIAnalogIn, pros::adi::AnalogIn); LEGACY_TYPEDEF(ADIAnalogOut, pros::adi::AnalogOut); LEGACY_TYPEDEF(ADIDigitalIn, pros::adi::DigitalIn); LEGACY_TYPEDEF(ADIDigitalOut, pros::adi::DigitalOut); LEGACY_TYPEDEF(ADIMotor, pros::adi::Motor); LEGACY_TYPEDEF(ADIGyro, pros::adi::Gyro); LEGACY_TYPEDEF(ADIEncoder, pros::adi::Encoder); LEGACY_TYPEDEF(ADIUltrasonic, pros::adi::Ultrasonic); LEGACY_TYPEDEF(LED, pros::adi::Led); // Backwards Compatibility for Derived Classes LEGACY_TYPEDEF(ADIPotentiometer, pros::adi::Potentiometer); LEGACY_TYPEDEF(ADILineSensor, pros::adi::LineSensor); LEGACY_TYPEDEF(ADILightSensor, pros::adi::LightSensor); LEGACY_TYPEDEF(ADIAccelerometer, pros::adi::Accelerometer); LEGACY_TYPEDEF(ADIButton, pros::adi::Button); LEGACY_TYPEDEF(ADIPneumatics, pros::adi::Pneumatics); LEGACY_TYPEDEF(ADILED, pros::adi::Led); LEGACY_TYPEDEF(ADILed, pros::adi::Led); } // namespace pros #endif // _PROS_ADI_HPP_ ================================================ FILE: include/pros/ai_vision.h ================================================ /** * \file pros/aivision.h * \ingroup c-aivision * * Contains prototypes for the VEX AI Vision Sensor-related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-aivision AI Vision Sensor C API * \note Additional example code for this module can be found in its [Tutorial.](@ref aivision) */ #ifndef _PROS_AIVISION_H_ #define _PROS_AIVISION_H_ /** * \addtogroup c-aivision * @{ */ /// \name Macros /// Parameters given by VEX ///@{ #define AIVISION_MAX_OBJECT_COUNT 24 #define AIVISION_MAX_CLASSNAME_COUNT 20 #define AIVISION_MODE_TAG_SET_BIT (1 << 29) ///@} ///@} #include #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \addtogroup c-aivision * @{ */ /** * \enum aivision_detected_type_e_t * This enumeration defines what kind of object is stored inside the union in aivision_object_s */ typedef enum aivision_detected_type { E_AIVISION_DETECTED_COLOR = (1 << 0), E_AIVISION_DETECTED_CODE = (1 << 1), E_AIVISION_DETECTED_OBJECT = (1 << 2), E_AIVISION_DETECTED_TAG = (1 << 3) } aivision_detected_type_e_t; /** * \enum aivision_mode_type_e_t * This enumeration defines what kinds of objects the ai vision sensor will scan for: * tags (april tags), colors (user defined colors), and objects (game elements), and all (all objects) */ typedef enum aivision_mode_type { E_AIVISION_MODE_TAGS = (1 << 0), E_AIVISION_MODE_COLORS = (1 << 1), E_AIVISION_MODE_OBJECTS = (1 << 2), E_AIVISION_MODE_COLOR_MERGE = (1 << 4), E_AIVISION_MODE_ALL = (1 << 0) | (1 << 1) | (1 << 2), } aivision_mode_type_e_t; /** * \struct aivision_color_s_t * This structure contains the parameters used by the AI Vision Sensor to define a color. hue_range and saturation_range * are ranges for hue and saturation that are acceptable. * For example, if a large hue range is specified for a blue color, colors that are more magenta or teal may be detected * as "blue". */ typedef struct aivision_color_s { uint8_t id; /**< id of color descriptor, can range from 1-7 */ uint8_t red; /**< red value of color */ uint8_t green; /**< green value of color */ uint8_t blue; /**< blue value of color */ float hue_range; /**< range by which detected color's hue can vary from the base color, can range from 1-40 */ float saturation_range; /**< range by which detected color's saturation can vary from base color, can range from 0.1-1 */ } aivision_color_s_t; /** * \struct aivision_code_s_t * This structure contains the parameters used by the AI Vision sensor to define a code. * Codes are a combination of color descriptors, and tells the AI Vision sensor to merge objects * close to each other that belong to the given color descriptors into a single object that matches * the code descriptor. * Codes must use at least 2, and no greater than 5, color descriptors. */ typedef struct aivision_code_s { uint8_t id; /**< id of code descriptor, can range from 1-5 */ uint8_t length; /**< number of color descriptors used by this code. */ int16_t c1; /**< id of first color descriptor */ int16_t c2; /**< id of second color descriptor */ int16_t c3; /**< id of third color descriptor */ int16_t c4; /**< id of fourth color descriptor */ int16_t c5; /**< id of fifth color descriptor */ } aivision_code_s_t; /** * \enum aivision_tag_family_e_t * This enumeration corresponds to a family of AprilTags. * \see https://april.eecs.umich.edu/software/apriltag */ typedef enum aivision_tag_family_e { TAG_CIRCLE_21H7 = 0, TAG_16H5 = 1, TAG_25H9 = 2, TAG_61H11 = 3 } aivision_tag_family_e_t; /** * \struct aivision_object_color_s_t * This structure contains a detected color. */ typedef struct __attribute__((packed)) aivision_object_color_s { uint16_t xoffset; // left edge (from camera's view) uint16_t yoffset; // top edge uint16_t width; uint16_t height; uint16_t angle; // angle, in tenths of a degree } aivision_object_color_s_t; /** * \struct aivision_object_tag_s_t * This structure contains a detected tag. */ typedef struct __attribute__((packed)) aivision_object_tag_s { int16_t x0; int16_t y0; int16_t x1; int16_t y1; int16_t x2; int16_t y2; int16_t x3; int16_t y3; } aivision_object_tag_s_t; typedef struct __attribute__((packed)) aivision_object_element_s { uint16_t xoffset; // left uint16_t yoffset; // top uint16_t width; uint16_t height; uint16_t score; // confidence that this struct is } aivision_object_element_s_t; /** * \struct aivision_object_s_t * This structure contains one of aivision_detected_type_e_t, stored in type * * If the object is a color, id stores the color's id * If the object is an April Tag, id stores the tag's id * If the object is an AI model element, id stores the element id as per * https://api.vex.com/v5/home/cpp/AiVision/AiObjdesc.html */ typedef struct __attribute__((packed)) aivision_object_s { uint8_t id; // object id uint8_t type; // object type union { aivision_object_color_s_t color; aivision_object_tag_s_t tag; aivision_object_element_s_t element; } object; } aivision_object_s_t; /// @} #ifdef __cplusplus namespace c { #endif /** * \addtogroup c-aivision * @{ */ /// \name Functions /** * Resets the AI Vision sensor to the initial state. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * aivision_reset(AIVISION_PORT); * } * \endcode */ int32_t aivision_reset(uint8_t port); /** * Returns a bitfield of the types of objects the AI vision sensor is currently searching for, * as per aivision_mode_type_e_t. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \return the bitfield if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * aivision_get_enabled_detection_types(AIVISION_PORT); * } * \endcode */ int32_t aivision_get_enabled_detection_types(uint8_t port); /** * Modifies the types of objects the AI vision sensor is currently searching for, as per aivision_mode_type_e_t. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * aivision_set_enabled_detection_types(1, 0b010, 0b101) would disable the detection of tags and objects, * and leave the setting of colors alone. * * \param port The V5 port number from 1-21 * \param bits the bits to set * \param bitmask the bitmask to apply * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t aivision_set_enabled_detection_types(uint8_t port, uint8_t bits, uint8_t bitmask); /** * Enable detecting these types of objects, a bitmask as per aivision_mode_type_e_t. * Enabling any given type of object will not disable the detection of other objects. * This must be done explicitly. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * // start or continue looking for AI model objects * aivision_enable_detection_types(AIVISION_PORT, aivision_mode_type_e_t::E_AIVISION_MODE_OBJECTS); * } * \endcode * * \param port The V5 port number from 1-21 * \param types_mask The types to enable * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t aivision_enable_detection_types(uint8_t port, uint8_t types_mask); /** * Disable detecting these types of objects, a bitmask as per aivision_mode_type_e_t. * Disabling any given type of object will not affect the detection of other objects. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * // stop looking for AI model objects (competition elements, for example) * aivision_disable_detection_types(AIVISION_PORT, aivision_mode_type_e_t::E_AIVISION_MODE_OBJECTS); * } * \endcode * * \param port The V5 port number from 1-21 * \param types_mask The types to enable * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t aivision_disable_detection_types(uint8_t port, uint8_t types_mask); /** * Sets the april tag family to detect. Use this function will override the enabled apriltag * detection family. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param family the tag family to configure the AI Vision sensor to detect * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t aivision_set_tag_family_override(uint8_t port, aivision_tag_family_e_t family); /** * Sets the april tag family to detect. Use this function will allow multiple apriltags * to be detected. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param family the tag family to configure the AI Vision sensor to detect * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t aivision_set_tag_family(uint8_t port, aivision_tag_family_e_t family); /** * Set a color configuration that the AI vision sensor will detect. * The color detection type must be separately enabled. * If a color with the same ID already is stored in the sensor, it will be overwritten. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param color the color to configure the AI Vision sensor to detect * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t aivision_set_color(uint8_t port, const aivision_color_s_t* color); /** * Get a color configuration that the AI vision sensor has stored. * If you attempt to get a color configuration that has not been previously used, the * behavior is not defined. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param id the id of color from 1-7 * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ aivision_color_s_t aivision_get_color(uint8_t port, uint32_t id); /** * Get a class name that the AI vision sensor has stored. * The AI Vision sensor may not correctly report classnames for the first several hundred milliseconds * of being plugged in. * By passing in -1 for the id, the function will return the number of class names the AI vision sensor reports. * For other values of id, the function return value is undefined * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param id the id of the class name from 0-(AIVISION_MAX_CLASSNAME_COUNT - 1) * \param class_name a string of length >=20 to store the classname. * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t aivision_get_class_name(uint8_t port, int32_t id, uint8_t* class_name); /** * Enable or disable the bounding box overlay the AI Vision sensor outputs on the USB port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param enabled if the overlay is enabled or disabled * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t aivision_set_usb_bounding_box_overlay(uint8_t port, bool enabled); /** * Runs auto white balance to adjust to different lighting conditions. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t aivision_start_awb(uint8_t port); /** * Get a code that the AI vision sensor has stored. * * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param id The id from 1-5 * \return the code, or a struct with an invalid ID if the operation failed, setting errno */ aivision_code_s_t aivision_get_code(uint8_t port, uint32_t id); /** * Set a code that the AI vision sensor will detect for. * The id of the code is stored in the aivision_code_s_t struct. If there is already a code * stored in the AI vision sensor with the id, this function will overwrite. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \param code The code to set * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t aivision_set_code(uint8_t port, const aivision_code_s_t* wcode); /** * Get the current number of objects detected by the AI vision sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \return the number of objects if the operation was successful or PROS_ERR if the operation failed, setting errno */ int32_t aivision_get_object_count(uint8_t port); /** * Get the detected object at a given object index; there are aivision_get_object_count objects and the index starts * from 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * @param port The V5 port number from 1-21 * @param object_index the object index * @return the detected object if the operation was successful or an invalid object type if the operation failed, * setting errno */ aivision_object_s_t aivision_get_object(uint8_t port, uint32_t object_index); /** * Get the current reported temperature of the AI Vision sensor in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port The V5 port number from 1-21 * \return the temperature if the operation was successful or PROS_ERR_F if the operation failed, setting errno */ double aivision_get_temperature(uint8_t port); ///@} #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_VISION_H_ ================================================ FILE: include/pros/ai_vision.hpp ================================================ /** * \file pros/aivision.hpp * \ingroup cpp-aivision * * Contains prototypes for the VEX AI Vision Sensor-related functions in C++. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-aivision AI Vision Sensor C++ API * \note Additional example code for this module can be found in its [Tutorial.](@ref aivision) */ #ifndef _PROS_AIVISION_HPP_ #define _PROS_AIVISION_HPP_ #include #include #include #include "pros/ai_vision.h" #include "pros/device.hpp" namespace pros { inline namespace v5 { /** * \enum AivisionDetectType * \ingroup cpp-aivision * Enum class for describing detection type of objects detected by the AI Vision Sensor. */ enum class AivisionDetectType : uint8_t { color = (1 << 0), /**< object was detected based on color descriptor */ code = (1 << 1), /**< object was detected based on code descriptor */ object = (1 << 2), /**< object was detected using AI model */ tag = (1 << 3) /**< object was detected as an AprilTag */ }; /** * \enum AivisionModeType * \ingroup cpp-aivision * Enum class for enabling/disabling detection types of AI Vision Sensor. */ enum class AivisionModeType : uint8_t { tags = (1 << 0), /**< AprilTag detection */ colors = (1 << 1), /**< color and code detection */ objects = (1 << 2), /**< AI model object detection */ color_merge = (1 << 4), /**< merge adjacent color detections */ all = (1 << 0) | (1 << 1) | (1 << 2), }; /** * \enum AivisionTagFamily * \ingroup cpp-aivision * Enum class for describing family of apriltags to detect. */ enum class AivisionTagFamily { tag_21H7 = 0, tag_16H5 = 1, tag_25H9 = 2, tag_61H11 = 3 }; /** * \ingroup cpp-aivision */ class AIVision : public Device { /** * \addtogroup cpp-aivision * @{ */ public: using Color = aivision_color_s_t; using Code = aivision_code_s_t; using Object = aivision_object_s_t; /** * Create a AI Vision Sensor object on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an AI vision sensor * * \param port * The V5 port number from 1-21 * * \b Example * \code * void opcontrol() { * pros::AIVision ai_sensor(2); // Creates a vision sensor on port two * } * \endcode */ explicit AIVision(const std::uint8_t port); AIVision(const Device& device) : AIVision(device.get_port()){}; /** * Gets all vision sensors. * * \return A vector of AIVision sensor objects. * * \b Example * \code * void opcontrol() { * std::vector aivision_all = pros::AIVision::get_all_devices(); // All AI vision sensors that are * connected * } * \endcode */ static std::vector get_all_devices(); /** * Check if the dected type is the same as the given type. * * \return true if the type is the same, false otherwise * * \b Example * \code * void opcontrol() { * pros::AIVision aivision(1); * pros::AIVision::Object object = aivision.get_object(0); * if (AIVision::is_type(AivisionDetectType::color, object)) { * printf("is color\n"); * } else if (AIVision::is_type(AivisionDetectType::object, object)) { * printf("is object\n"); * } else if (AIVision::is_type(AivisionDetectType::code, object)) { * printf("is code\n"); * } else if (AIVision::is_type(AivisionDetectType::tag, object)) { * printf("is tag\n"); * } else { * printf("unknown\n"); * } * } * \endcode */ static bool is_type(const Object& object, AivisionDetectType type); /** * Resets the AI Vision sensor to the initial state. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * aivision.reset(); * } * \endcode */ int32_t reset(); /** * Returns a bitfield of the types of objects the AI vision sensor is currently searching for, * as per AivisionModeType. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \return the bitfield if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * int32_t enabled_types = aivision.get_enabled_detection_types(); * printf("is tag: %d\n", enabled_types | AivisionModeType::tags); * } * \endcode */ int32_t get_enabled_detection_types(); /** * Enable detecting these types of objects, a bitmask as per aivision_mode_type_e_t. * Enabling any given type of object will not disable the detection of other objects. * This must be done explicitly. * * For this function you must use bitwise or to combine the types you want to enable. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * // start or continue looking for AI model objects * // enable aivision to look for tags and objects * aivision.enable_detection_types(AivisionModeType::tags | AivisionModeType::objects); * } * \endcode * * \param types_mask The types to enable * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t enable_detection_types(AivisionModeType types_mask); /** * Enable detecting these types of objects, a bitmask as per aivision_mode_type_e_t. * Enabling any given type of object will not disable the detection of other objects. * This must be done explicitly. * * For this function you can use comma separated values to combine the types you want to enable. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * // start or continue looking for AI model objects * // enable aivision to look for tags and objects * aivision.enable_detection_types(AivisionModeType::tags, AivisionModeType::objects); * } * \endcode * * \param types_mask The types to enable * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ template requires((std::conjunction_v...>)) int32_t enable_detection_types(Flags... flags) { auto types_mask = (static_cast(flags) | ...); return c::aivision_enable_detection_types(this->_port, static_cast(types_mask)); } /** * Disable detecting these types of objects, a bitmask as per aivision_mode_type_e_t. * Disabling any given type of object will not affect the detection of other objects. * * For this function you must use bitwise or to combine the types you want to disable. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * // stop looking for AI model objects (competition elements, for example) * // disable aivision to look for tags and objects * aivision.disable_detection_types(AivisionModeType::tags | AivisionModeType::objects); * } * \endcode * * \param types_mask The types to enable * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t disable_detection_types(AivisionModeType types_mask); /** * Disable detecting these types of objects, a bitmask as per aivision_mode_type_e_t. * Disabling any given type of object will not affect the detection of other objects. * * For this function you can use comma separated values to combine the types you want to disable. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \b Example * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * // stop looking for AI model objects (competition elements, for example) * // disable aivision to look for tags and objects * aivision.disable_detection_types(AivisionModeType::tags | AivisionModeType::objects); * } * \endcode * * \param types_mask The types to enable * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ template requires((std::conjunction_v...>)) int32_t disable_detection_types(Flags... flags) { auto types_mask = (static_cast(flags) | ...); return c::aivision_disable_detection_types(this->_port, static_cast(types_mask)); } /** * Sets the april tag family to detect. * If override is true, the AI vision sensor will only look for the given family. * Otherwise, it will add the given tag to the list of enabled tags. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * #define AIVISION_PORT 1 * void initialize() { * pros::AIVision aivision(AIVISION_PORT); * // set the only tag family to look for to 21H7 * aivision.set_tag_family(AivisionTagFamily::tag_21H7); * // add 16H5 to the list of enabled tag families * aivision.set_tag_family(AivisionTagFamily::tag_16H5); * // set the only tag family to look for to 25H9 * aivision.set_tag_family(AivisionTagFamily::tag_25H9, true); * } * \endcode * * \param family the tag family to configure the AI Vision sensor to detect * \param override if true, the given family will be set as the only enabled tag family. * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno. */ int32_t set_tag_family(AivisionTagFamily family, bool override = false); /** * Set a color configuration that the AI vision sensor will detect. * The color detection type must be separately enabled. * If a color with the same ID already is stored in the sensor, it will be overwritten. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * AIVision::Color color = {1, 207, 19, 25, 10.00, 0.20}; * aivision.set_color(color); * } * \endcode * * \param color the color to configure the AI Vision sensor to detect * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t set_color(const Color& color); /** * Get a color configuration that the AI vision sensor has stored. * If you attempt to get a color configuration that has not been previously used, the * behavior is not defined. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * AIVision::Code color = aivision.get_color(0); * printf("id: %d, red: %d, green: %d, blue: %d, hue_range: %f, saturation_range: %f\n", * color.id, color.red, color.green, color.blue, color.hue_range, color.saturation_range); * } * * \param id the id of color from 1-7 * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ AIVision::Color get_color(uint32_t id); /** * Set a code that the AI vision sensor will detect for. * The id of the code is stored in the aivision_code_s_t struct. If there is already a code * stored in the AI vision sensor with the id, this function will overwrite. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * AIVision::Code code = {1, 207, 19, 25, 10.00, 0.20}; * aivision.set_code(code); * } * * \endcode * * \param code The code to set * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ uint32_t set_code(const Code& code); /** * Get a code that the AI vision sensor has stored. * * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * AIVision::Code code = aivision.get_code(0); * printf("id: %d, length: %d, c1: %d, c2: %d, c3: %d, c4: %d, c5: %d\n", * code.id, code.length, code.c1, code.c2, code.c3, code.c4, code.c5); * ) * } * * \endcode * * \param id The id from 1-5 * \return the code, or a struct with an invalid ID if the operation failed, setting errno */ AIVision::Code get_code(uint32_t id); /** * Runs auto white balance to adjust to different lighting conditions. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t start_awb(); /** * Get a class name that the AI vision sensor has stored. * The AI Vision sensor may not correctly report classnames for the first several hundred milliseconds * of being plugged in. * By passing in -1 for the id, the function will return the number of class names the AI vision sensor reports. * For other values of id, the function return value is undefined * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * \code * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * char* class_name = new char[21]; * aivision.get_class_name(0, class_name); * printf("%s\n", class_name); * delete[] class_name; * } * * \endcode * * \param id the id of the class name from 0-(AIVISION_MAX_CLASSNAME_COUNT - 1) * \param class_name a string of length >=20 to store the classname. * \return PROS_SUCCESS if the operation was successful or PROS_ERR if the operation * failed, setting errno */ int32_t get_class_name(int32_t id, char* class_name); /** * Get a class name that the AI vision sensor has stored. * The AI Vision sensor may not correctly report classnames for the first several hundred milliseconds * of being plugged in. * By passing in -1 for the id, the function will return the number of class names the AI vision sensor reports. * For other values of id, the function return value is undefined * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * \code * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * auto name = aivision.get_class_name(1); * * if(name.has_value()) { * printf("Class name: %s\n", name.value().c_str()); * } else { * printf("Error: %ld\n", errno); * } * } * * \endcode * * \param id the id of the class name from 0-(AIVISION_MAX_CLASSNAME_COUNT - 1) * \return the class name string in std::optional if the operation was successful * or an empty optional if the operation failed, setting errno */ std::optional get_class_name(int32_t id); /** * Get the current number of objects detected by the AI vision sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * int32_t object_count = aivision.get_object_count(); * printf("%d\n", object_count); * } * \endcode * * \return the number of objects if the operation was successful or PROS_ERR if the operation failed, setting errno */ int32_t get_object_count(); /** * Get the detected object at a given object index; there are aivision_get_object_count objects and the index starts * from 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * int32_t object_count = aivision.get_object_count(); * for (int i = 0; i < object_count; i++) { * pros::AIVision::Object object = aivision.get_object(i); * printf("Object %d: %d\n", i, object.type); * } * } * * \endcode * * @param object_index the object index * @return the detected object if the operation was successful or an invalid object type if the operation failed, * setting errno */ Object get_object(uint32_t object_index); /** * Get all detected objects in a vector. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \code * #define AIVISION_PORT 1 * void opcontrol() { * pros::AIVision aivision(AIVISION_PORT); * auto objects = aivision.get_all_objects(); * for (const auto& object : objects) { * printf("Object %d: %d\n", object.id, object.type); * } * } * \endcode * * @return a vector of all detected objects */ std::vector get_all_objects(); /// @} }; } // namespace v5 } // namespace pros #endif // _PROS_VISION_HPP_ ================================================ FILE: include/pros/apix.h ================================================ /** * \file pros/apix.h * \ingroup apix * * PROS Extended API header * * Contains additional declarations for use by advaned users of PROS. These * functions do not typically have as much error handling or require deeper * knowledge of real time operating systems. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup apix Extended API * \note Also included in the Extended API is [LVGL.](https://lvgl.io/) */ #ifndef _PROS_API_EXTENDED_H_ #define _PROS_API_EXTENDED_H_ #include "api.h" #include "pros/device.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wall" #pragma GCC diagnostic pop #include "pros/serial.h" #ifdef __cplusplus #include "pros/serial.hpp" namespace pros::c { extern "C" { #endif /** * \ingroup apix */ /** * \addtogroup apix * @{ */ /// \name RTOS Facilities ///@{ typedef void* queue_t; typedef void* sem_t; /** * Unblocks a task in the Blocked state (e.g. waiting for a delay, on a * semaphore, etc.). * * \param task * The task to unblock * * \return True if the task was unblocked, false otherwise * * \b Example: * \code * task_t task = task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * task_delay(1000); * // in another task somewhere else, this will abort the task_delay bove: * task_abort_delay(task); * \endcode */ bool task_abort_delay(task_t task); /** * Notify a task when a target task is being deleted. * * \param target_task * The task being watched for deletion * \param task_to_notify * The task to notify when target_task is deleted * \param value * The value to supply to task_notify_ext * \param notify_action * The action to supply to task_notify_ext * * \b Example: * \code * task_t task_to_delete = task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * task_t task_to_notify = task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn2"); * * task_notify_ext(task_to_notify, 0, NOTIFY_ACTION_INCREMENT, NULL); * * task_notify_when_deleting(task_to_delete, task_get_current(), 0, NOTIFY_ACTION_NONE); * task_delete(task_to_delete); * \endcode */ void task_notify_when_deleting(task_t target_task, task_t task_to_notify, uint32_t value, notify_action_e_t notify_action); /** * Returns a handle to the current owner of a mutex. * * \param mutex * A mutex handle * * \return A handle to the current task that owns the mutex, or NULL if the * mutex isn't owned. * * \b Example: * \code * mutex_t mutex = mutex_create(); * * void task_fn(void* param) { * while(1) { * mutex_take(mutex, 1000); * // critical section * mutex_give(mutex); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * void opcontrol(void) { * while (1) { * if (joystick_get_digital(1, 7, JOY_UP)) { * task_t owner = mutex_get_owner(mutex); * if (owner != NULL) { * printf("Mutex is owned by task %s", task_get_name(owner)); * } else { * printf("Mutex is not owned"); * } * } * task_delay(20); * } * } * \endcode */ task_t mutex_get_owner(mutex_t mutex); /** * Creates a counting sempahore. * * \param max_count * The maximum count value that can be reached. * \param init_count * The initial count value assigned to the new semaphore. * * \return A newly created semaphore. If an error occurred, NULL will be * returned and errno can be checked for hints as to why sem_create failed. * * \b Example: * \code * // Binary semaphore acts as a mutex * sem_t sem = sem_create(1, 0); * * void task_fn(void* param) { * while(1) { * sem_take(sem, 1000); * // critical section * sem_give(sem); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * \endcode */ sem_t sem_create(uint32_t max_count, uint32_t init_count); /** * Deletes a semaphore (or binary semaphore) * * \param sem * Semaphore to delete * * \b Example: * \code * // Binary semaphore acts as a mutex * sem_t sem = sem_create(1, 0); * * void task_fn(void* param) { * while(1) { * sem_take(sem, 1000); * // critical section * sem_give(sem); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * void opcontrol(void) { * while (1) { * if (joystick_get_digital(1, 7, JOY_UP)) { * // honestly this is a bad example because you should never * // delete a semaphore like this * sem_delete(sem); * } * task_delay(20); * } * } * * \endcode */ void sem_delete(sem_t sem); /** * Creates a binary semaphore. * * \return A newly created semaphore. * * \b Example: * \code * // Binary semaphore acts as a mutex * sem_t sem = sem_binary_create(); * * void task_fn(void* param) { * while(1) { * sem_take(sem, 1000); * // critical section * sem_give(sem); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * \endcode */ sem_t sem_binary_create(void); /** * Waits for the semaphore's value to be greater than 0. If the value is already * greater than 0, this function immediately returns. * * \param sem * Semaphore to wait on * \param timeout * Time to wait before the semaphore's becomes available. A timeout of 0 * can be used to poll the sempahore. TIMEOUT_MAX can be used to block * indefinitely. * * \return True if the semaphore was successfully take, false otherwise. If * false is returned, then errno is set with a hint about why the sempahore * couldn't be taken. * * \b Example: * \code * // Binary semaphore acts as a mutex * sem_t sem = sem_create(1, 0); * * void task_fn(void* param) { * while(1) { * if(!sem_wait(sem, 1000)) { * printf("Failed to take semaphore"); * task_delay(1000); * continue; * } * // critical section * sem_give(sem); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * void opcontrol(void) { * while (1) { * if (sem_wait(sem, 0))) { * printf("Semaphore is available"); * } * task_delay(20); * } * } * \endcode */ bool sem_wait(sem_t sem, uint32_t timeout); /** * Increments a semaphore's value. * * \param sem * Semaphore to post * * \return True if the value was incremented, false otherwise. If false is * returned, then errno is set with a hint about why the semaphore couldn't be * taken. * * \b Example: * \code * // Binary semaphore acts as a mutex * sem_t sem = sem_create(1, 0); * * void task_fn(void* param) { * while(1) { * sem_post(sem); // increments, mimicking to "claim" * // critical section * sem_give(sem); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * \endcode */ bool sem_post(sem_t sem); /** * Returns the current value of the semaphore. * * \param sem * A semaphore handle * * \return The current value of the semaphore (e.g. the number of resources * available) * * \b Example of sem_get_count: * \code * // Binary semaphore acts as a mutex * sem_t sem = sem_create(1, 0); * printf("semaphore count: %d", sem_get_count(sem)); * // semaphore count: 0 * sem_take(sem, 1000); * printf("semaphore count: %d", sem_get_count(sem)); * // semaphore count: 1 * sem_give(sem); * printf("semaphore count: %d", sem_get_count(sem)); * // semaphore count: 0 * * \endcode */ uint32_t sem_get_count(sem_t sem); /** * Creates a queue. * * \param length * The maximum number of items that the queue can contain. * \param item_size * The number of bytes each item in the queue will require. * * \return A handle to a newly created queue, or NULL if the queue cannot be * created. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * int item[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * printf("queue length: %d", queue_get_length(queue)); * } * \endcode */ queue_t queue_create(uint32_t length, uint32_t item_size); /** * Posts an item to the front of a queue. The item is queued by copy, not by * reference. * * \param queue * The queue handle * \param item * A pointer to the item that will be placed on the queue. * \param timeout * Time to wait for space to become available. A timeout of 0 can be used * to attempt to post without blocking. TIMEOUT_MAX can be used to block * indefinitely. * * \return True if the item was preprended, false otherwise. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * int item[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * printf("queue length: %d", queue_get_length(queue)); * } */ bool queue_prepend(queue_t queue, const void* item, uint32_t timeout); /** * Posts an item to the end of a queue. The item is queued by copy, not by * reference. * * \param queue * The queue handle * \param item * A pointer to the item that will be placed on the queue. * \param timeout * Time to wait for space to become available. A timeout of 0 can be used * to attempt to post without blocking. TIMEOUT_MAX can be used to block * indefinitely. * * \return True if the item was preprended, false otherwise. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * int item[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * printf("queue length: %d", queue_get_length(queue)); * } * \endcode */ bool queue_append(queue_t queue, const void* item, uint32_t timeout); /** * Receive an item from a queue without removing the item from the queue. * * \param queue * The queue handle * \param buffer * Pointer to a buffer to which the received item will be copied * \param timeout * The maximum amount of time the task should block waiting for an item to receive should the queue be empty at * the time of the call. TIMEOUT_MAX can be used to block indefinitely. * * \return True if an item was copied into the buffer, false otherwise. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * char* item = "Hello! this is a test"; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * char* recv = malloc(sizeof("Hello! this is a test")); * queue_peek(queue, recv, 1000); * printf("Queue: %s", recv); * free(recv); * } * \endcode */ bool queue_peek(queue_t queue, void* const buffer, uint32_t timeout); /** * Receive an item from the queue. * * \param queue * The queue handle * \param buffer * Pointer to a buffer to which the received item will be copied * \param timeout * The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time * of the call. queue_recv() will return immediately if timeout * is zero and the queue is empty. * * \return True if an item was copied into the buffer, false otherwise. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * char* item = "Hello! this is a test"; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * char* recv = malloc(sizeof("Hello! this is a test")); * queue_recv(queue, recv, 1000); * printf("Queue: %s", recv); * free(recv); * } * \endcode */ bool queue_recv(queue_t queue, void* const buffer, uint32_t timeout); /** * Return the number of messages stored in a queue. * * \param queue * The queue handle. * * \return The number of messages available in the queue. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * * int item[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * printf("queue waiting: %d", queue_get_waiting(queue)); * } * \endcode */ uint32_t queue_get_waiting(const queue_t queue); /** * Return the number of spaces left in a queue. * * \param queue * The queue handle. * * \return The number of spaces available in the queue. * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * * int item[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * printf("queue available: %d", queue_get_available(queue)); * } * \endcode */ uint32_t queue_get_available(const queue_t queue); /** * Delete a queue. * * \param queue * Queue handle to delete * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * queue_delete(queue); * } * \endcode */ void queue_delete(queue_t queue); /** * Resets a queue to an empty state * * \param queue * Queue handle to reset * * \b Example: * \code * void opcontrol(void) { * queue_t queue = queue_create(10, sizeof(int)); * int item[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; * queue_prepend(queue, item, 1000); * queue_append(queue, item, 1000); * queue_reset(queue); * } * \endcode */ void queue_reset(queue_t queue); ///@} /// \name Device Registration ///@{ /** * Registers a device in the given zero-indexed port * * Registers a device of the given type in the given port into the registry, if * that type of device is detected to be plugged in to that port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-20), or a * a different device than specified is plugged in. * EADDRINUSE - The port is already registered to another device. * * \param port * The port number to register the device * \param device * The type of device to register * * \return 1 upon success, PROS_ERR upon failure * * \b Example: * \code * void opcontrol(void) { * registry_bind_port(1, E_DEVICE_MOTOR); * } * \endcode */ int registry_bind_port(uint8_t port, v5_device_e_t device_type); /** * Deregisters a devices from the given zero-indexed port * * Removes the device registed in the given port, if there is one. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-20). * * \param port * The port number to deregister * * \return 1 upon success, PROS_ERR upon failure * * \b Example: * \code * void opcontrol(void) { * registry_bind_port(1, E_DEVICE_MOTOR); * registry_unbind_port(1); * } * \endcode */ int registry_unbind_port(uint8_t port); /** * Returns the type of device registered to the zero-indexed port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-20). * * \param port * The V5 port number from 0-20 * * \return The type of device that is registered into the port (NOT what is * plugged in) * * \b Example: * \code * void opcontrol(void) { * registry_bind_port(1, E_DEVICE_MOTOR); * printf("port 1 is registered to a motor: %d", registry_get_bound_type(1) == E_DEVICE_MOTOR); * } * \endcode */ v5_device_e_t registry_get_bound_type(uint8_t port); /** * Returns the type of the device plugged into the zero-indexed port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-20). * * \param port * The V5 port number from 0-20 * * \return The type of device that is plugged into the port (NOT what is * registered) * * \b Example: * \code * void opcontrol(void) { * registry_bind_port(1, E_DEVICE_MOTOR); * printf("port 1 is registered to a motor: %d", registry_get_plugged_type(1) == E_DEVICE_MOTOR); * } * \endcode */ v5_device_e_t registry_get_plugged_type(uint8_t port); ///@} /// \name Startup options ///@{ /** * Enable/disable the PROS banner printed to the serial stream. * * \warning This function must be called BEFORE the PROS daemon starts. * The easiest way to acheive this is to NOT call this function directly, * and instead use the BANNER_ENABLE macro. * * \param enable * Whether the banner should be enabled or disabled. */ void enable_banner(bool enabled); /** * This priority value, when used with __attribute__((constructor( ))), is * guaranteed to run before PROS initializes. */ #define PRE_PROS_INIT_PRIORITY 101 /** * Enable/disable the PROS banner printed to the serial stream. * * \warning This macro must be used in global scope, outside of any function. * * \param enable * Whether the banner should be enabled or disabled. */ #ifdef __cplusplus #define ENABLE_BANNER(enabled) static_assert(!__builtin_strcmp(__FUNCTION__, "top level"), \ "Cannot use ENABLE_BANNER inside a function!"); \ __attribute__((constructor(PRE_PROS_INIT_PRIORITY))) static void _enable_banner_impl() \ { pros::c::enable_banner(enabled); } #else #define ENABLE_BANNER(enabled) static_assert(!__builtin_strcmp(__FUNCTION__, "top level"), \ "Cannot use ENABLE_BANNER inside a function!"); \ __attribute__((constructor(PRE_PROS_INIT_PRIORITY))) static void _enable_banner_impl() \ { enable_banner(enabled); } #endif ///@} /// \name Filesystem ///@{ /** * Control settings of the serial driver. * * \param action * An action to perform on the serial driver. See the SERCTL_* macros for * details on the different actions. * \param extra_arg * An argument to pass in based on the action * * \b Example: * \code * void opcontrol(void) { * serctl(SERCTL_SET_BAUDRATE, (void*) 9600); * } */ int32_t serctl(const uint32_t action, void* const extra_arg); /* * Control settings of the microSD card driver. * * \param action * An action to perform on the microSD card driver. See the USDCTL_* macros * for details on the different actions. * \param extra_arg * An argument to pass in based on the action */ // Not yet implemented // int32_t usdctl(const uint32_t action, void* const extra_arg); /** * Control settings of the way the file's driver treats the file * * \param file * A valid file descriptor number * \param action * An action to perform on the file's driver. See the *CTL_* macros for * details on the different actions. Note that the action passed in must * match the correct driver (e.g. don't perform a SERCTL_* action on a * microSD card file) * \param extra_arg * An argument to pass in based on the action * * \b Example: * \code * void opcontrol(void) { * int32_t fd = open("serial", O_RDWR); * fdctl(fd, SERCTL_SET_BAUDRATE, (void*) 9600); * } * \endcode */ int32_t fdctl(int file, const uint32_t action, void* const extra_arg); /** * Sets the reverse flag for the motor. * * This will invert its movements and the values returned for its position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1-21 * \param reverse * True reverses the motor, false is default * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_set_reversed(1, true); * printf("Is this motor reversed? %d\n", motor_is_reversed(1)); * } * \endcode */ int32_t motor_set_reversed(int8_t port, const bool reverse); /** * Gets the operation direction of the motor as set by the user. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1-21 * * \return 1 if the motor has been reversed and 0 if the motor was not reversed, * or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void initialize() { * printf("Is the motor reversed? %d\n", motor_is_reversed(1)); * // Prints "Is the motor reversed? 0" * } * \endcode */ int32_t motor_is_reversed(int8_t port); /** * Action macro to pass into serctl or fdctl that activates the stream * identifier. * * When used with serctl, the extra argument must be the little endian * representation of the stream identifier (e.g. "sout" -> 0x74756f73) * */ #define SERCTL_ACTIVATE 10 /** * Action macro to pass into serctl or fdctl that deactivates the stream * identifier. * * When used with serctl, the extra argument must be the little endian * representation of the stream identifier (e.g. "sout" -> 0x74756f73) * */ #define SERCTL_DEACTIVATE 11 /** * Action macro to pass into fdctl that enables blocking writes for the file * * The extra argument is not used with this action, provide any value (e.g. * NULL) instead * */ #define SERCTL_BLKWRITE 12 /** * Action macro to pass into fdctl that makes writes non-blocking for the file * * The extra argument is not used with this action, provide any value (e.g. * NULL) instead * */ #define SERCTL_NOBLKWRITE 13 /** * Action macro to pass into serctl that enables advanced stream multiplexing * capabilities * * The extra argument is not used with this action, provide any value (e.g. * NULL) instead * */ #define SERCTL_ENABLE_COBS 14 /** * Action macro to pass into serctl that disables advanced stream multiplexing * capabilities * * The extra argument is not used with this action, provide any value (e.g. * NULL) instead * */ #define SERCTL_DISABLE_COBS 15 /** * Action macro to check if there is data available from the Generic Serial * Device * */ #define DEVCTL_FIONREAD 16 /** * Action macro to check if there is space available in the Generic Serial * Device's output buffer * */ #define DEVCTL_FIONWRITE 18 /** * Action macro to set the Generic Serial Device's baudrate. * * The extra argument is the baudrate. */ #define DEVCTL_SET_BAUDRATE 17 ///@} ///@} #ifdef __cplusplus } } #endif #endif // _PROS_API_EXTENDED_H_ ================================================ FILE: include/pros/colors.h ================================================ /** * \file pros/colors.h * * Contains macro definitions of colors (as `uint32_t`) * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License v. 2.0. If a copy of the MPL was not distributed with this * file You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-colors Colors C API */ /** * \ingroup c-colors * \note These functions can be used for dynamic device instantiation. */ /** * \addtogroup c-colors * @{ */ #ifndef _PROS_COLORS_H_ #define _PROS_COLORS_H_ #define RGB2COLOR(R, G, B) ((R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff)) #define COLOR2R(COLOR) ((COLOR >> 16) & 0xff) #define COLOR2G(COLOR) ((COLOR >> 8) & 0xff) #define COLOR2B(COLOR) (COLOR & 0xff) #ifdef __cplusplus namespace pros { namespace c { #endif /** * \enum color_e_t * @brief * Enum of possible colors * * Contains common colors, all members are self descriptive. */ typedef enum color_e { COLOR_ALICE_BLUE = 0x00F0F8FF, COLOR_ANTIQUE_WHITE = 0x00FAEBD7, COLOR_AQUA = 0x0000FFFF, COLOR_AQUAMARINE = 0x007FFFD4, COLOR_AZURE = 0x00F0FFFF, COLOR_BEIGE = 0x00F5F5DC, COLOR_BISQUE = 0x00FFE4C4, COLOR_BLACK = 0x00000000, COLOR_BLANCHED_ALMOND = 0x00FFEBCD, COLOR_BLUE = 0x000000FF, COLOR_BLUE_VIOLET = 0x008A2BE2, COLOR_BROWN = 0x00A52A2A, COLOR_BURLY_WOOD = 0x00DEB887, COLOR_CADET_BLUE = 0x005F9EA0, COLOR_CHARTREUSE = 0x007FFF00, COLOR_CHOCOLATE = 0x00D2691E, COLOR_CORAL = 0x00FF7F50, COLOR_CORNFLOWER_BLUE = 0x006495ED, COLOR_CORNSILK = 0x00FFF8DC, COLOR_CRIMSON = 0x00DC143C, COLOR_CYAN = 0x0000FFFF, COLOR_DARK_BLUE = 0x0000008B, COLOR_DARK_CYAN = 0x00008B8B, COLOR_DARK_GOLDENROD = 0x00B8860B, COLOR_DARK_GRAY = 0x00A9A9A9, COLOR_DARK_GREY = COLOR_DARK_GRAY, COLOR_DARK_GREEN = 0x00006400, COLOR_DARK_KHAKI = 0x00BDB76B, COLOR_DARK_MAGENTA = 0x008B008B, COLOR_DARK_OLIVE_GREEN = 0x00556B2F, COLOR_DARK_ORANGE = 0x00FF8C00, COLOR_DARK_ORCHID = 0x009932CC, COLOR_DARK_RED = 0x008B0000, COLOR_DARK_SALMON = 0x00E9967A, COLOR_DARK_SEA_GREEN = 0x008FBC8F, COLOR_DARK_SLATE_GRAY = 0x002F4F4F, COLOR_DARK_SLATE_GREY = COLOR_DARK_SLATE_GRAY, COLOR_DARK_TURQUOISE = 0x0000CED1, COLOR_DARK_VIOLET = 0x009400D3, COLOR_DEEP_PINK = 0x00FF1493, COLOR_DEEP_SKY_BLUE = 0x0000BFFF, COLOR_DIM_GRAY = 0x00696969, COLOR_DIM_GREY = COLOR_DIM_GRAY, COLOR_DODGER_BLUE = 0x001E90FF, COLOR_FIRE_BRICK = 0x00B22222, COLOR_FLORAL_WHITE = 0x00FFFAF0, COLOR_FOREST_GREEN = 0x00228B22, COLOR_FUCHSIA = 0x00FF00FF, COLOR_GAINSBORO = 0x00DCDCDC, COLOR_GHOST_WHITE = 0x00F8F8FF, COLOR_GOLD = 0x00FFD700, COLOR_GOLDENROD = 0x00DAA520, COLOR_GRAY = 0x00808080, COLOR_GREY = COLOR_GRAY, COLOR_GREEN = 0x00008000, COLOR_GREEN_YELLOW = 0x00ADFF2F, COLOR_HONEYDEW = 0x00F0FFF0, COLOR_HOT_PINK = 0x00FF69B4, COLOR_INDIAN_RED = 0x00CD5C5C, COLOR_INDIGO = 0x004B0082, COLOR_IVORY = 0x00FFFFF0, COLOR_KHAKI = 0x00F0E68C, COLOR_LAVENDER = 0x00E6E6FA, COLOR_LAVENDER_BLUSH = 0x00FFF0F5, COLOR_LAWN_GREEN = 0x007CFC00, COLOR_LEMON_CHIFFON = 0x00FFFACD, COLOR_LIGHT_BLUE = 0x00ADD8E6, COLOR_LIGHT_CORAL = 0x00F08080, COLOR_LIGHT_CYAN = 0x00E0FFFF, COLOR_LIGHT_GOLDENROD_YELLOW = 0x00FAFAD2, COLOR_LIGHT_GREEN = 0x0090EE90, COLOR_LIGHT_GRAY = 0x00D3D3D3, COLOR_LIGHT_GREY = COLOR_LIGHT_GRAY, COLOR_LIGHT_PINK = 0x00FFB6C1, COLOR_LIGHT_SALMON = 0x00FFA07A, COLOR_LIGHT_SEA_GREEN = 0x0020B2AA, COLOR_LIGHT_SKY_BLUE = 0x0087CEFA, COLOR_LIGHT_SLATE_GRAY = 0x00778899, COLOR_LIGHT_SLATE_GREY = COLOR_LIGHT_SLATE_GRAY, COLOR_LIGHT_STEEL_BLUE = 0x00B0C4DE, COLOR_LIGHT_YELLOW = 0x00FFFFE0, COLOR_LIME = 0x0000FF00, COLOR_LIME_GREEN = 0x0032CD32, COLOR_LINEN = 0x00FAF0E6, COLOR_MAGENTA = 0x00FF00FF, COLOR_MAROON = 0x00800000, COLOR_MEDIUM_AQUAMARINE = 0x0066CDAA, COLOR_MEDIUM_BLUE = 0x000000CD, COLOR_MEDIUM_ORCHID = 0x00BA55D3, COLOR_MEDIUM_PURPLE = 0x009370DB, COLOR_MEDIUM_SEA_GREEN = 0x003CB371, COLOR_MEDIUM_SLATE_BLUE = 0x007B68EE, COLOR_MEDIUM_SPRING_GREEN = 0x0000FA9A, COLOR_MEDIUM_TURQUOISE = 0x0048D1CC, COLOR_MEDIUM_VIOLET_RED = 0x00C71585, COLOR_MIDNIGHT_BLUE = 0x00191970, COLOR_MINT_CREAM = 0x00F5FFFA, COLOR_MISTY_ROSE = 0x00FFE4E1, COLOR_MOCCASIN = 0x00FFE4B5, COLOR_NAVAJO_WHITE = 0x00FFDEAD, COLOR_NAVY = 0x00000080, COLOR_OLD_LACE = 0x00FDF5E6, COLOR_OLIVE = 0x00808000, COLOR_OLIVE_DRAB = 0x006B8E23, COLOR_ORANGE = 0x00FFA500, COLOR_ORANGE_RED = 0x00FF4500, COLOR_ORCHID = 0x00DA70D6, COLOR_PALE_GOLDENROD = 0x00EEE8AA, COLOR_PALE_GREEN = 0x0098FB98, COLOR_PALE_TURQUOISE = 0x00AFEEEE, COLOR_PALE_VIOLET_RED = 0x00DB7093, COLOR_PAPAY_WHIP = 0x00FFEFD5, COLOR_PEACH_PUFF = 0x00FFDAB9, COLOR_PERU = 0x00CD853F, COLOR_PINK = 0x00FFC0CB, COLOR_PLUM = 0x00DDA0DD, COLOR_POWDER_BLUE = 0x00B0E0E6, COLOR_PURPLE = 0x00800080, COLOR_RED = 0x00FF0000, COLOR_ROSY_BROWN = 0x00BC8F8F, COLOR_ROYAL_BLUE = 0x004169E1, COLOR_SADDLE_BROWN = 0x008B4513, COLOR_SALMON = 0x00FA8072, COLOR_SANDY_BROWN = 0x00F4A460, COLOR_SEA_GREEN = 0x002E8B57, COLOR_SEASHELL = 0x00FFF5EE, COLOR_SIENNA = 0x00A0522D, COLOR_SILVER = 0x00C0C0C0, COLOR_SKY_BLUE = 0x0087CEEB, COLOR_SLATE_BLUE = 0x006A5ACD, COLOR_SLATE_GRAY = 0x00708090, COLOR_SLATE_GREY = COLOR_SLATE_GRAY, COLOR_SNOW = 0x00FFFAFA, COLOR_SPRING_GREEN = 0x0000FF7F, COLOR_STEEL_BLUE = 0x004682B4, COLOR_TAN = 0x00D2B48C, COLOR_TEAL = 0x00008080, COLOR_THISTLE = 0x00D8BFD8, COLOR_TOMATO = 0x00FF6347, COLOR_TURQUOISE = 0x0040E0D0, COLOR_VIOLET = 0x00EE82EE, COLOR_WHEAT = 0x00F5DEB3, COLOR_WHITE = 0x00FFFFFF, COLOR_WHITE_SMOKE = 0x00F5F5F5, COLOR_YELLOW = 0x00FFFF00, COLOR_YELLOW_GREEN = 0x009ACD32, } color_e_t; ///@} #ifdef __cplusplus } // namespace c } // namespace pros #endif #endif // _PROS_COLORS_H_ ================================================ FILE: include/pros/colors.hpp ================================================ /** * \file pros/colors.hpp * * Contains enum class definitions of colors * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License v. 2.0. If a copy of the MPL was not distributed with this * file You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-colors C++ Color API */ #ifndef _PROS_COLORS_HPP_ #define _PROS_COLORS_HPP_ namespace pros{ /** * \ingroup cpp-colors */ /** * \addtogroup cpp-colors * @{ */ /** * \enum Color * @brief * Enum class of possible colors * * Contains common colors, all members are self descriptive. */ enum class Color { alice_blue = 0x00F0F8FF, antique_white = 0x00FAEBD7, aqua = 0x0000FFFF, aquamarine = 0x007FFFD4, azure = 0x00F0FFFF, beige = 0x00F5F5DC, bisque = 0x00FFE4C4, black = 0x00000000, blanched_almond = 0x00FFEBCD, blue = 0x000000FF, blue_violet = 0x008A2BE2, brown = 0x00A52A2A, burly_wood = 0x00DEB887, cadet_blue = 0x005F9EA0, chartreuse = 0x007FFF00, chocolate = 0x00D2691E, coral = 0x00FF7F50, cornflower_blue = 0x006495ED, cornsilk = 0x00FFF8DC, crimson = 0x00DC143C, cyan = 0x0000FFFF, dark_blue = 0x0000008B, dark_cyan = 0x00008B8B, dark_goldenrod = 0x00B8860B, dark_gray = 0x00A9A9A9, dark_grey = dark_gray, dark_green = 0x00006400, dark_khaki = 0x00BDB76B, dark_magenta = 0x008B008B, dark_olive_green = 0x00556B2F, dark_orange = 0x00FF8C00, dark_orchid = 0x009932CC, dark_red = 0x008B0000, dark_salmon = 0x00E9967A, dark_sea_green = 0x008FBC8F, dark_slate_gray = 0x002F4F4F, dark_slate_grey = dark_slate_gray, dark_turquoise = 0x0000CED1, dark_violet = 0x009400D3, deep_pink = 0x00FF1493, deep_sky_blue = 0x0000BFFF, dim_gray = 0x00696969, dim_grey = dim_gray, dodger_blue = 0x001E90FF, fire_brick = 0x00B22222, floral_white = 0x00FFFAF0, forest_green = 0x00228B22, fuchsia = 0x00FF00FF, gainsboro = 0x00DCDCDC, ghost_white = 0x00F8F8FF, gold = 0x00FFD700, goldenrod = 0x00DAA520, gray = 0x00808080, grey = gray, green = 0x00008000, green_yellow = 0x00ADFF2F, honeydew = 0x00F0FFF0, hot_pink = 0x00FF69B4, indian_red = 0x00CD5C5C, indigo = 0x004B0082, ivory = 0x00FFFFF0, khaki = 0x00F0E68C, lavender = 0x00E6E6FA, lavender_blush = 0x00FFF0F5, lawn_green = 0x007CFC00, lemon_chiffon = 0x00FFFACD, light_blue = 0x00ADD8E6, light_coral = 0x00F08080, light_cyan = 0x00E0FFFF, light_goldenrod_yellow = 0x00FAFAD2, light_green = 0x0090EE90, light_gray = 0x00D3D3D3, light_grey = light_gray, light_pink = 0x00FFB6C1, light_salmon = 0x00FFA07A, light_sea_green = 0x0020B2AA, light_sky_blue = 0x0087CEFA, light_slate_gray = 0x00778899, light_slate_grey = light_slate_gray, light_steel_blue = 0x00B0C4DE, light_yellow = 0x00FFFFE0, lime = 0x0000FF00, lime_green = 0x0032CD32, linen = 0x00FAF0E6, magenta = 0x00FF00FF, maroon = 0x00800000, medium_aquamarine = 0x0066CDAA, medium_blue = 0x000000CD, medium_orchid = 0x00BA55D3, medium_purple = 0x009370DB, medium_sea_green = 0x003CB371, medium_slate_blue = 0x007B68EE, medium_spring_green = 0x0000FA9A, medium_turquoise = 0x0048D1CC, medium_violet_red = 0x00C71585, midnight_blue = 0x00191970, mint_cream = 0x00F5FFFA, misty_rose = 0x00FFE4E1, moccasin = 0x00FFE4B5, navajo_white = 0x00FFDEAD, navy = 0x00000080, old_lace = 0x00FDF5E6, olive = 0x00808000, olive_drab = 0x006B8E23, orange = 0x00FFA500, orange_red = 0x00FF4500, orchid = 0x00DA70D6, pale_goldenrod = 0x00EEE8AA, pale_green = 0x0098FB98, pale_turquoise = 0x00AFEEEE, pale_violet_red = 0x00DB7093, papay_whip = 0x00FFEFD5, peach_puff = 0x00FFDAB9, peru = 0x00CD853F, pink = 0x00FFC0CB, plum = 0x00DDA0DD, powder_blue = 0x00B0E0E6, purple = 0x00800080, red = 0x00FF0000, rosy_brown = 0x00BC8F8F, royal_blue = 0x004169E1, saddle_brown = 0x008B4513, salmon = 0x00FA8072, sandy_brown = 0x00F4A460, sea_green = 0x002E8B57, seashell = 0x00FFF5EE, sienna = 0x00A0522D, silver = 0x00C0C0C0, sky_blue = 0x0087CEEB, slate_blue = 0x006A5ACD, slate_gray = 0x00708090, slate_grey = slate_gray, snow = 0x00FFFAFA, spring_green = 0x0000FF7F, steel_blue = 0x004682B4, tan = 0x00D2B48C, teal = 0x00008080, thistle = 0x00D8BFD8, tomato = 0x00FF6347, turquoise = 0x0040E0D0, violet = 0x00EE82EE, wheat = 0x00F5DEB3, white = 0x00FFFFFF, white_smoke = 0x00F5F5F5, yellow = 0x00FFFF00, yellow_green = 0x009ACD32, }; } // namespace pros ///@} #endif //_PROS_COLORS_HPP_ ================================================ FILE: include/pros/device.h ================================================ /** * \file pros/device.h * * Contains functions for interacting with VEX devices. * * * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-device VEX Generic Device C API (For Advanced Users) */ #ifndef _PROS_DEVICE_H_ #define _PROS_DEVICE_H_ #include #ifdef __cplusplus namespace pros::c { extern "C" { #endif /** * \ingroup c-device * \note These functions can be used for dynamic device instantiation. */ /** * \addtogroup c-device * @{ */ /** * \enum v5_device_e * \brief * List of possible v5 devices * * This list contains all current V5 Devices, and mirrors V5_DeviceType from the * api. */ typedef enum v5_device_e { E_DEVICE_NONE = 0, ///< No device is plugged into the port E_DEVICE_MOTOR = 2, ///< A motor is plugged into the port E_DEVICE_ROTATION = 4, ///< A rotation sensor is plugged into the port E_DEVICE_IMU = 6, ///< An inertial sensor is plugged into the port E_DEVICE_DISTANCE = 7, ///< A distance sensor is plugged into the port E_DEVICE_RADIO = 8, ///< A radio is plugged into the port E_DEVICE_VISION = 11, ///< A vision sensor is plugged into the port E_DEVICE_ADI = 12, ///< This port is an ADI expander E_DEVICE_OPTICAL = 16, ///< An optical sensor is plugged into the port E_DEVICE_GPS = 20, ///< A GPS sensor is plugged into the port E_DEVICE_AIVISION = 29, ///< An AI Vision sensor is plugged into the port E_DEVICE_SERIAL = 129, ///< A serial device is plugged into the port E_DEVICE_GENERIC __attribute__((deprecated("use E_DEVICE_SERIAL instead"))) = E_DEVICE_SERIAL, E_DEVICE_UNDEFINED = 255 ///< The device type is not defined, or is not a valid device } v5_device_e_t; /** * Gets the type of device on given port. * * \return The device type as an enum. * * \b Example * \code * #define DEVICE_PORT 1 * * void opcontrol() { * while (true) { * v5_device_e_t pt = get_plugged_type(DEVICE_PORT); * printf("device plugged type: {plugged type: %d}\n", pt); * delay(20); * } * } * \endcode */ v5_device_e_t get_plugged_type(uint8_t port); ///@} #ifdef __cplusplus } // namespace c } // namespace pros #endif #endif // _PROS_DEVICE_H_ ================================================ FILE: include/pros/device.hpp ================================================ /** * \file pros/device.hpp * * Base class for all smart devices. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-device VEX Generic Device C++ API (For Advanced Users) */ #ifndef _PROS_DEVICE_HPP_ #define _PROS_DEVICE_HPP_ #include "pros/misc.hpp" #include "pros/rtos.hpp" namespace pros { inline namespace v5 { /** * \ingroup cpp-device * \note These functions can be used for dynamic device instantiation. */ /** * \addtogroup cpp-device * @{ */ /** * \enum DeviceType * \brief * Enum of possible v5 devices. * * Contains all current V5 Devices. */ enum class DeviceType { none = 0, ///< No device is plugged into the port motor = 2, ///< A motor is plugged into the port rotation = 4, ///< A rotation sensor is plugged into the port imu = 6, ///< An inertial sensor is plugged into the port distance = 7, ///< A distance sensor is plugged into the port radio = 8, ///< A radio is plugged into the port vision = 11, ///< A vision sensor is plugged into the port adi = 12, ///< This port is an ADI expander optical = 16, ///< An optical sensor is plugged into the port gps = 20, ///< A GPS sensor is plugged into the port aivision = 29, ///< An AI vision sensor is plugged into the port serial = 129, ///< A serial device is plugged into the port undefined = 255 ///< The device type is not defined, or is not a valid device }; class Device { public: /** * Creates a Device object. * * \param port The V5 port number from 1-21 * * \b Example * \code * #define DEVICE_PORT 1 * * void opcontrol() { * Device device(DEVICE_PORT); * } * \endcode */ explicit Device(const std::uint8_t port); /** * Gets the port number of the Smart Device. * * \return The smart device's port number. * * \b Example * \code * void opcontrol() { * #define DEVICE_PORT 1 * while (true) { * Device device(DEVICE_PORT); * printf("device plugged type: {port: %d}\n", device.get_port()); * delay(20); * } * } * \endcode */ std::uint8_t get_port(void) const; /** * Checks if the device is installed. * * \return true if the corresponding device is installed, false otherwise. * \b Example * * \code * #define DEVICE_PORT 1 * * void opcontrol() { * Device device(DEVICE_PORT); * while (true) { * printf("device plugged type: {is_installed: %d}\n", device.is_installed()); * delay(20); * } * } * \endcode */ virtual bool is_installed(); /** * Gets the type of device. * * This function uses the following values of errno when an error state is * reached: * EACCES - Mutex of port cannot be taken (access denied). * * \return The device type as an enum. * * \b Example * \code * #define DEVICE_PORT 1 * * void opcontrol() { Device device(DEVICE_PORT); * while (true) { * DeviceType dt = device.get_plugged_type(); * printf("device plugged type: {plugged type: %d}\n", dt); * delay(20); * } * } * \endcode */ pros::DeviceType get_plugged_type() const; /** * Gets the type of device on a given port. * * This function uses the following values of errno when an error state is * reached: * EACCES - Mutex of port cannot be taken (access denied). * * \param port The V5 port number from 1-21 * * \return The device type as an enum. * * \b Example * \code * #define DEVICE_PORT 1 * * void opcontrol() { * while (true) { * DeviceType dt = pros::Device::get_plugged_type(DEVICE_PORT); * printf("device plugged type: {plugged type: %d}\n", dt); * delay(20); * } * } * \endcode */ static pros::DeviceType get_plugged_type(std::uint8_t port); /** * Gets all devices of a given device type. * * \param device_type The pros::DeviceType enum that matches the type of device desired. * * \return A vector of Device objects for the given device type. * * \b Example * \code * void opcontrol() { * std::vector motor_devices = pros::Device::get_all_devices(pros::DeviceType::motor); // All Device objects are motors * } * \endcode */ static std::vector get_all_devices(pros::DeviceType device_type = pros::DeviceType::undefined); protected: /** * Creates a Device object. * * \param port The V5 port number from 1-21 * * \param deviceType The type of the constructed device */ Device(const std::uint8_t port, const enum DeviceType deviceType) : _port(port), _deviceType(deviceType) {} protected: const std::uint8_t _port; const enum DeviceType _deviceType = pros::DeviceType::none; ///@} }; } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/distance.h ================================================ /** * \file pros/distance.h * \ingroup c-distance * * Contains prototypes for functions related to the VEX Distance sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-distance VEX Distance Sensor C API */ #ifndef _PROS_DISTANCE_H_ #define _PROS_DISTANCE_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif /** * \ingroup c-distance */ /** * \addtogroup c-distance * @{ */ /** * Get the currently measured distance from the sensor in mm * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \param port The V5 Distance Sensor port number from 1-21 * \return The distance value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { * while (true) { * printf("Distance Value: %d mm\n", distance_get(DISTANCE_PORT)); * delay(20); * } * } * \endcode */ int32_t distance_get(uint8_t port); /** * Get the confidence in the distance reading * * This is a value that has a range of 0 to 63. 63 means high confidence, * lower values imply less confidence. Confidence is only available * when distance is > 200mm (the value 10 is returned in this scenario). * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \param port The V5 Distance Sensor port number from 1-21 * \return The confidence value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { * while (true) { * printf("Distance Confidence Value: %d\n", distance_get_confidence(DISTANCE_PORT)); * delay(20); * } * } * \endcode */ int32_t distance_get_confidence(uint8_t port); /** * Get the current guess at relative object size * * This is a value that has a range of 0 to 400. * A 18" x 30" grey card will return a value of approximately 75 * in typical room lighting. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \param port The V5 Distance Sensor port number from 1-21 * \return The size value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { * while (true) { * printf("Distance Object Size: %d\n", distance_get_object_size(DISTANCE_PORT)); * delay(20); * } * } * \endcode */ int32_t distance_get_object_size(uint8_t port); /** * Get the object velocity in m/s * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \param port The V5 Distance Sensor port number from 1-21 * \return The velocity value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { * while (true) { * printf("Distance Object Velocity: %f\n", distance_get_object_velocity(DISTANCE_PORT)); * delay(20); * } * } * \endcode */ double distance_get_object_velocity(uint8_t port); ///@} #ifdef __cplusplus } } } #endif #endif ================================================ FILE: include/pros/distance.hpp ================================================ /** * \file pros/distance.hpp * \ingroup cpp-distance * * Contains prototypes for the V5 Distance Sensor-related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-distance VEX Distance Sensor C++ API */ #ifndef _PROS_DISTANCE_HPP_ #define _PROS_DISTANCE_HPP_ #include #include #include "pros/device.hpp" #include "pros/distance.h" namespace pros { inline namespace v5 { /** * \ingroup cpp-distance */ class Distance : public Device { /** * \addtogroup cpp-distance * @{ */ public: /** * Creates a Distance Sensor object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a Distance Sensor * * \param port * The V5 port number from 1-21 * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { * Distance distance(DISTANCE_PORT); * } * \endcode */ Distance(const std::uint8_t port); Distance(const Device& device) : Distance(device.get_port()){}; /** * Get the currently measured distance from the sensor in mm * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \return The distance value or PROS_ERR if the operation failed, setting * errno. Will return 9999 if the sensor can not detect an object. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { Distance distance(DISTANCE_PORT); * while (true) { * printf("Distance: %d\n", distance.get()); * delay(20); * } * } * \endcode */ virtual std::int32_t get(); /** * Get the currently measured distance from the sensor in mm. * \note This function is identical to get(). * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \return The distance value or PROS_ERR if the operation failed, setting * errno. Will return 9999 if the sensor can not detect an object. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { Distance distance(DISTANCE_PORT); * while (true) { * printf("Distance: %d\n", distance.get_distance()); * delay(20); * } * } * \endcode */ virtual std::int32_t get_distance(); /** * Gets all distance sensors. * * \return A vector of Distance sensor objects. * * \b Example * \code * void opcontrol() { * std::vector distance_all = pros::Distance::get_all_devices(); // All distance sensors that are * connected * } * \endcode */ static std::vector get_all_devices(); /** * Get the confidence in the distance reading * * This is a value that has a range of 0 to 63. 63 means high confidence, * lower values imply less confidence. Confidence is only available * when distance is > 200mm. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \return The confidence value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { Distance distance(DISTANCE_PORT); * while (true) { * printf("Distance confidence: %d\n", distance.get_confidence()); * delay(20); * } * } * \endcode */ virtual std::int32_t get_confidence(); /** * Get the current guess at relative object size * * This is a value that has a range of 0 to 400. * A 18" x 30" grey card will return a value of approximately 75 * in typical room lighting. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \return The size value or PROS_ERR if the operation failed, setting * errno. Will return -1 if the sensor is not able to determine object size. * * \b Example * \code * #define DISTANCE_PORT 1 * * void opcontrol() { Distance distance(DISTANCE_PORT); * while (true) { * printf("Distance object size: %d\n", distance.get_object_size()); * delay(20); * } * } * \endcode */ virtual std::int32_t get_object_size(); /** * Get the object velocity in m/s * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Distance Sensor * * \return The velocity value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * * void opcontrol() { * Distance distance(DISTANCE_PORT); * while (true) { * printf("Distance object velocity: %f\n", distance.get_object_velocity()); * delay(20); * } * } * \endcode */ virtual double get_object_velocity(); /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * Distance [port: (port number), distance: (distance), confidence: (confidence), * object size: (object size), object velocity: (object velocity)] */ friend std::ostream& operator<<(std::ostream& os, pros::Distance& distance); private: ///@} }; namespace literals { /** * Constructs a Distance sensor object from a literal ending in _dist via calling the constructor * * \return a pros::Distance for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Distance dist = 2_dist; //Makes an dist object on port 2 * } * \endcode */ const pros::Distance operator""_dist(const unsigned long long int d); } // namespace literals } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/error.h ================================================ /** * \file pros/error.h * * Contains macro definitions for return types, mostly errors * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _PROS_ERROR_H_ #define _PROS_ERROR_H_ #include "limits.h" // Different Byte Size Errors /// @brief /// Return This on Byte Sized Return Error #define PROS_ERR_BYTE (INT8_MAX) /// @brief /// Return This on 2 Byte Sized Return Error #define PROS_ERR_2_BYTE (INT16_MAX) /// @brief /// Return This on 4 Byte Sized Return Error #define PROS_ERR (INT32_MAX) /// @brief /// Return This on 8 Byte Sized Return Error #define PROS_ERR_F (INFINITY) /// @brief /// Return This on Success (1) #define PROS_SUCCESS (1) #endif ================================================ FILE: include/pros/ext_adi.h ================================================ /** * \file pros/ext_adi.h * \ingroup ext-adi * * Contains prototypes for interfacing with the 3-Wire Expander. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup ext-adi ADI Expander C API * \note The internal ADI API can be found [here.](@ref c-adi) */ #ifndef _PROS_EXT_ADI_H_ #define _PROS_EXT_ADI_H_ #include #include #include "adi.h" #include "pros/adi.h" #ifndef PROS_ERR #define PROS_ERR (INT32_MAX) #endif #ifdef __cplusplus extern "C" { namespace pros { #endif #ifdef __cplusplus namespace c { #endif /** * \ingroup ext-adi */ /** * \addtogroup ext-adi * @{ */ /******************************************************************************/ /** General ADI Use Functions **/ /** **/ /** These functions allow for interaction with any ADI port type **/ /******************************************************************************/ /** * Gets the configuration for the given ADI port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') for which to return * the configuration * * \return The ADI configuration for the given port * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * ext_adi_port_set_config(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * // Displays the value of E_ADI_ANALOG_IN * printf("Port Type: %d\n", ext_adi_port_get_config(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT)); * } * \endcode */ adi_port_config_e_t ext_adi_port_get_config(uint8_t smart_port, uint8_t adi_port); /** * Gets the value for the given ADI port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') for which to return * the configuration * * \return The value stored for the given port * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * ext_adi_port_set_config(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * printf("Port Value: %d\n", ext_adi_get_value(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT)); * } * \endcode */ int32_t ext_adi_port_get_value(uint8_t smart_port, uint8_t adi_port); /** * Configures an ADI port to act as a given sensor type. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param type * The configuration type for the port * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * ext_adi_port_set_config(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT, E_ADI_ANALOG_IN); * } * \endcode */ int32_t ext_adi_port_set_config(uint8_t smart_port, uint8_t adi_port, adi_port_config_e_t type); /** * Sets the value for the given ADI port. * * This only works on ports configured as outputs, and the behavior will change * depending on the configuration of the port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') for which the value * will be set * \param value * The value to set the ADI port to * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define DIGITAL_SENSOR_PORT 1 * * void initialize() { * ext_adi_port_set_config(ADI_EXPANDER_PORT, DIGITAL_SENSOR_PORT, E_ADI_DIGITAL_OUT); * ext_adi_set_value(ADI_EXPANDER_PORT, DIGITAL_SENSOR_PORT, HIGH); * } * \endcode */ int32_t ext_adi_port_set_value(uint8_t smart_port, uint8_t adi_port, int32_t value); /** * Calibrates the analog sensor on the specified port and returns the new * calibration value. * * This method assumes that the true sensor value is not actively changing at * this time and computes an average from approximately 500 samples, 1 ms apart, * for a 0.5 s period of calibration. The average value thus calculated is * returned and stored for later calls to the adi_analog_read_calibrated() and * adi_analog_read_calibrated_HR() functions. These functions will return * the difference between this value and the current sensor value when called. * * Do not use this function when the sensor value might be unstable * (gyro rotation, accelerometer movement). * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port to calibrate (from 1-8, 'a'-'h', 'A'-'H') * * \return The average sensor value computed by this function * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * ext_adi_analog_calibrate(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT); * printf("Calibrated Reading: %d\n", * ext_adi_analog_read_calibrated(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT)); * // All readings from then on will be calibrated * } * \endcode */ int32_t ext_adi_analog_calibrate(uint8_t smart_port, uint8_t adi_port); /** * Gets the 12-bit value of the specified port. * * The value returned is undefined if the analog pin has been switched to a * different mode. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an analog input * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port (from 1-8, 'a'-'h', 'A'-'H') for which the value will be * returned * * \return The analog sensor value, where a value of 0 reflects an input voltage * of nearly 0 V and a value of 4095 reflects an input voltage of nearly 5 V * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * printf("Sensor Reading: %d\n", ext_adi_analog_read(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t ext_adi_analog_read(uint8_t smart_port, uint8_t adi_port); /** * Gets the 12 bit calibrated value of an analog input port. * * The adi_analog_calibrate() function must be run first. This function is * inappropriate for sensor values intended for integration, as round-off error * can accumulate causing drift over time. Use adi_analog_read_calibrated_HR() * instead. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an analog input * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port (from 1-8, 'a'-'h', 'A'-'H') for which the value will be * returned * * \return The difference of the sensor value from its calibrated default from * -4095 to 4095 * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * printf("Sensor Reading: %d\n", ext_adi_analog_read_calibrated(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t ext_adi_analog_read_calibrated(uint8_t smart_port, uint8_t adi_port); /** * Gets the 16 bit calibrated value of an analog input port. * * The adi_analog_calibrate() function must be run first. This is intended for * integrated sensor values such as gyros and accelerometers to reduce drift due * to round-off, and should not be used on a sensor such as a line tracker * or potentiometer. * * The value returned actually has 16 bits of "precision", even though the ADC * only reads 12 bits, so that error induced by the average value being between * two values when integrated over time is trivial. Think of the value as the * true value times 16. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an analog input * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port (from 1-8, 'a'-'h', 'A'-'H') for which the value will be * returned * * \return The difference of the sensor value from its calibrated default from * -16384 to 16384 * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * ext_adi_analog_calibrate(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT); * * printf("Sensor Reading: %d\n", ext_adi_analog_read_calibrated_HR(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t ext_adi_analog_read_calibrated_HR(uint8_t smart_port, uint8_t adi_port); /** * Gets the digital value (1 or 0) of a port configured as a digital input. * * If the port is configured as some other mode, the digital value which * reflects the current state of the port is returned, which may or may not * differ from the currently set value. The return value is undefined for ports * configured as any mode other than a Digital Input. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a digital input * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port to read (from 1-8, 'a'-'h', 'A'-'H') * * \return True if the pin is HIGH, or false if it is LOW * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * printf(“Sensor Value: %dn”, * ext_adi_digital_read(ADI_EXPANDER_PORT, DIGITAL_SENSOR_PORT)); * delay(5); * } * } * \endcode */ int32_t ext_adi_digital_read(uint8_t smart_port, uint8_t adi_port); /** * Gets a rising-edge case for a digital button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under the * same circumstances, so only one task should call this function for any given * button. E.g., Task A calls this function for buttons 1 and 2. Task B may call * this function for button 3, but should not for buttons 1 or 2. A typical * use-case for this function is to call inside opcontrol to detect new button * presses, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a digital input * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port to read (from 1-8, 'a'-'h', 'A'-'H') * * \return 1 if the button is pressed and had not been pressed * the last time this function was called, 0 otherwise. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * while (true) { * if (ext_adi_digital_get_new_press(ADI_EXPANDER_PORT, DIGITAL_SENSOR_PORT)) { * // Toggle pneumatics or other state operations * } * delay(5); * } * } * \endcode */ int32_t ext_adi_digital_get_new_press(uint8_t smart_port, uint8_t adi_port); /** * Sets the digital value (1 or 0) of a port configured as a digital output. * * If the port is configured as some other mode, behavior is undefined. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a digital output * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param value * An expression evaluating to "true" or "false" to set the output to * HIGH or LOW respectively, or the constants HIGH or LOW themselves * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define DIGITAL_SENSOR_PORT 1 * * void opcontrol() { * bool state = LOW; * while (true) { * state != state; * ext_adi_digital_write(ADI_EXPANDER_PORT, DIGITAL_SENSOR_PORT, state); * * delay(5); // toggle the sensor value every 50ms * } * } * \endcode */ int32_t ext_adi_digital_write(uint8_t smart_port, uint8_t adi_port, bool value); /** * Configures the port as an input or output with a variety of settings. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param mode * One of INPUT, INPUT_ANALOG, INPUT_FLOATING, OUTPUT, or OUTPUT_OD * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define ANALOG_SENSOR_PORT 1 * * void initialize() { * ext_adi_pin_mode(ADI_EXPANDER_PORT, ANALOG_SENSOR_PORT, INPUT_ANALOG); * } * \endcode */ int32_t ext_adi_pin_mode(uint8_t smart_port, uint8_t adi_port, uint8_t mode); /** * Sets the speed of the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an motor * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port number (from 1-8, 'a'-'h', 'A'-'H') to configure * \param speed * The new signed speed; -127 is full reverse and 127 is full forward, * with 0 being off * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define MOTOR_PORT 1 * * void opcontrol() { * ext_adi_motor_set(ADI_EXPANDER_PORT, MOTOR_PORT, 127); // Go full speed forward * delay(1000); * ext_adi_motor_set(ADI_EXPANDER_PORT, MOTOR_PORT, 0); // Stop the motor * } * \endcode */ int32_t ext_adi_motor_set(uint8_t smart_port, uint8_t adi_port, int8_t speed); /** * Gets the last set speed of the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an motor * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port to get (from 1-8, 'a'-'h', 'A'-'H') * * \return The last set speed of the motor on the given port * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 # * define MOTOR_PORT 1 * * void opcontrol() { * ext_adi_motor_set(ADI_EXPANDER_PORT, * MOTOR_PORT, 127); // Go full speed forward * printf(“Commanded Motor Power: %dn”, * ext_adi_motor_get(ADI_EXPANDER_PORT, MOTOR_PORT)); // Will display 127 * delay(1000); * ext_adi_motor_set(ADI_EXPANDER_PORT, MOTOR_PORT, 0); // Stop the motor * } * \endcode */ int32_t ext_adi_motor_get(uint8_t smart_port, uint8_t adi_port); /** * Stops the motor on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an motor * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port to set (from 1-8, 'a'-'h', 'A'-'H') * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define MOTOR_PORT 1 * * void opcontrol() { * ext_adi_motor_set(ADI_EXPANDER_PORT, MOTOR_PORT, 127); // Go full speed forward * delay(1000); * ext_adi_motor_set(ADI_EXPANDER_PORT, MOTOR_PORT, 0); // Stop the motor * ext_adi_motor_stop(ADI_EXPANDER_PORT, MOTOR_PORT); // use this instead * } * \endcode */ int32_t ext_adi_motor_stop(uint8_t smart_port, uint8_t adi_port); /** * Reference type for an initialized encoder. * * This merely contains the port number for the encoder. */ typedef int32_t ext_adi_encoder_t; /** * Gets the number of ticks recorded by the encoder. * * There are 360 ticks in one revolution. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an encoder * * \param enc * The adi_encoder_t object from adi_encoder_init() to read * * \return The signed and cumulative number of counts since the last start or * reset * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define PORT_TOP 1 #define PORT_BOTTOM 2 * * void opcontrol() { * ext_adi_encoder_t enc = ext_adi_encoder_init(ADI_EXPANDER_PORT, * PORT_TOP, PORT_BOTTOM, false); * while (true) { * printf(“Encoder Value: %dn”, * ext_adi_encoder_get(enc)); * delay(5); * } * } * \endcode */ int32_t ext_adi_encoder_get(ext_adi_encoder_t enc); /** * Creates an encoder object and configures the specified ports accordingly. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an encoder * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port_top * The "top" wire from the encoder sensor with the removable cover side * up. This should be in port 1, 3, 5, or 7 ('A', 'C', 'E', or 'G'). * \param adi_port_bottom * The "bottom" wire from the encoder sensor * \param reverse * If "true", the sensor will count in the opposite direction * * \return An adi_encoder_t object to be stored and used for later calls to * encoder functions * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * ext_adi_encoder_t enc = ext_adi_encoder_init(ADI_EXPANDER_PORT, PORT_TOP, PORT_BOTTOM, false); * while (true) { * printf("Encoder Value: %d\n", ext_adi_encoder_get(enc)); * delay(5); * } * } * \endcode */ ext_adi_encoder_t ext_adi_encoder_init(uint8_t smart_port, uint8_t adi_port_top, uint8_t adi_port_bottom, bool reverse); /** * Sets the encoder value to zero. * * It is safe to use this method while an encoder is enabled. It is not * necessary to call this method before stopping or starting an encoder. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an encoder * * \param enc * The adi_encoder_t object from adi_encoder_init() to reset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * ext_adi_encoder_t enc = ext_adi_encoder_init(ADI_EXPANDER_PORT, PORT_TOP, PORT_BOTTOM, false); * delay(1000); // Move the encoder around in this time * ext_adi_encoder_reset(enc); // The encoder is now zero again * } * \endcode */ int32_t ext_adi_encoder_reset(ext_adi_encoder_t enc); /** * Disables the encoder and voids the configuration on its ports. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an encoder * * \param enc * The adi_encoder_t object from adi_encoder_init() to stop * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define ADI_EXPANDER_PORT 20 * #define PORT_TOP 1 * #define PORT_BOTTOM 2 * * void opcontrol() { * ext_adi_encoder_t enc = ext_adi_encoder_init(ADI_EXPANDER_PORT, PORT_TOP, PORT_BOTTOM, false); * // Use the encoder * ext_adi_encoder_shutdown(enc); * } * \endcode */ int32_t ext_adi_encoder_shutdown(ext_adi_encoder_t enc); /** * Reference type for an initialized ultrasonic. * * This merely contains the port number for the ultrasonic. */ typedef int32_t ext_adi_ultrasonic_t; /** * Gets the current ultrasonic sensor value in centimeters. * * If no object was found, zero is returned. If the ultrasonic sensor was never * started, the return value is undefined. Round and fluffy objects can cause * inaccurate values to be returned. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an ultrasonic * * \param ult * The adi_ultrasonic_t object from adi_ultrasonic_init() to read * * \return The distance to the nearest object in m^-4 (10000 indicates 1 meter), * measured from the sensor's mounting points. * * \b Example * \code * * #define PORT_PING 1 * #define PORT_ECHO 2 * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_ultrasonic_t ult = ext_adi_ultrasonic_init(ADI_EXPANDER_PORT, PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * printf("Distance: %d\n", ext_adi_ultrasonic_get(ult)); * delay(5); * } * } * \endcode */ int32_t ext_adi_ultrasonic_get(ext_adi_ultrasonic_t ult); /** * Creates an ultrasonic object and configures the specified ports accordingly. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an ultrasonic * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port_ping * The port connected to the orange OUTPUT cable. This should be in port * 1, 3, 5, or 7 ('A', 'C', 'E', 'G'). * \param adi_port_echo * The port connected to the yellow INPUT cable. This should be in the * next highest port following port_ping. * * \return An adi_ultrasonic_t object to be stored and used for later calls to * ultrasonic functions * * \b Example * \code * * #define PORT_PING 1 * #define PORT_ECHO 2 * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_ultrasonic_t ult = ext_adi_ultrasonic_init(ADI_EXPANDER_PORT, PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * printf("Distance: %d\n", ext_adi_ultrasonic_get(ult)); * delay(5); * } * } * \endcode */ ext_adi_ultrasonic_t ext_adi_ultrasonic_init(uint8_t smart_port, uint8_t adi_port_ping, uint8_t adi_port_echo); /** * Disables the ultrasonic sensor and voids the configuration on its ports. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as an ultrasonic * * \param ult * The adi_ultrasonic_t object from adi_ultrasonic_init() to stop * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define PORT_PING 1 * #define PORT_ECHO 2 * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_ultrasonic_t ult = ext_adi_ultrasonic_init(ADI_EXPANDER_PORT, PORT_PING, PORT_ECHO); * while (true) { * // Print the distance read by the ultrasonic * printf("Distance: %d\n", ext_adi_ultrasonic_get(ult)); * delay(5); * } * ext_adi_ultrasonic_shutdown(ult); * } * \endcode */ int32_t ext_adi_ultrasonic_shutdown(ext_adi_ultrasonic_t ult); /** * Reference type for an initialized gyroscope. * * This merely contains the port number for the gyroscope. * * (Might Be useless with the wire expander.) */ typedef int32_t ext_adi_gyro_t; /** * Gets the current gyro angle in tenths of a degree. Unless a multiplier is * applied to the gyro, the return value will be a whole number representing * the number of degrees of rotation times 10. * * There are 360 degrees in a circle, thus the gyro will return 3600 for one * whole rotation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a gyro * * \param gyro * The adi_gyro_t object for which the angle will be returned * * \return The gyro angle in degrees. * * \b Example * \code * * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_gyro_t gyro = ext_adi_gyro_init(ADI_EXPANDER_PORT, GYRO_PORT, GYRO_MULTIPLIER); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", ext_adi_gyro_get(gyro)); * delay(5); * } * } * \endcode */ double ext_adi_gyro_get(ext_adi_gyro_t gyro); /** * Initializes a gyroscope on the given port. If the given port has not * previously been configured as a gyro, then this function starts a 1300 ms * calibration period. * * It is highly recommended that this function be called from initialize() when * the robot is stationary to ensure proper calibration. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a gyro * * \param smart_port * The smart port number that the ADI Expander is in * \param adi_port * The ADI port to initialize as a gyro (from 1-8, 'a'-'h', 'A'-'H') * \param multiplier * A scalar value that will be multiplied by the gyro heading value * supplied by the ADI * * \return An adi_gyro_t object containing the given port, or PROS_ERR if the * initialization failed. * * \b Example * \code * * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_gyro_t gyro = ext_adi_gyro_init(ADI_EXPANDER_PORT, GYRO_PORT, GYRO_MULTIPLIER); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", ext_adi_gyro_get(gyro)); * delay(5); * } * } * \endcode */ ext_adi_gyro_t ext_adi_gyro_init(uint8_t smart_port, uint8_t adi_port, double multiplier); /** * Resets the gyroscope value to zero. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a gyro * * \param gyro * The adi_gyro_t object for which the angle will be returned * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_gyro_t gyro = ext_adi_gyro_init(ADI_EXPANDER_PORT, GYRO_PORT, GYRO_MULTIPLIER); * uint32_t now = millis(); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", ext_adi_gyro_get(gyro)); * * if (millis() - now > 2000) { * // Reset the gyro every 2 seconds * ext_adi_gyro_reset(gyro); * now = millis(); * } * * delay(5); * } * } * \endcode */ int32_t ext_adi_gyro_reset(ext_adi_gyro_t gyro); /** * Disables the gyro and voids the configuration on its port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - Either the ADI port value or the smart port value is not within its * valid range (ADI port: 1-8, 'a'-'h', or 'A'-'H'; smart port: 1-21). * EADDRINUSE - The port is not configured as a gyro * * \param gyro * The adi_gyro_t object to be shut down * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define GYRO_PORT 1 * #define GYRO_MULTIPLIER 1 // Standard behavior * #define ADI_EXPANDER_PORT 20 * * void opcontrol() { * ext_adi_gyro_t gyro = ext_adi_gyro_init(ADI_EXPANDER_PORT, GYRO_PORT, GYRO_MULTIPLIER); * uint32_t now = millis(); * while (true) { * // Print the gyro's heading * printf("Heading: %lf\n", ext_adi_gyro_get(gyro)); * * if (millis() - now > 2000) { * ext_adi_gyro_shutdown(gyro); * // Shut down the gyro after two seconds * break; * } * * delay(5); * } * } * \endcode */ int32_t ext_adi_gyro_shutdown(ext_adi_gyro_t gyro); /** * Reference type for an initialized potentiometer. * * This merely contains the port number for the potentiometer. */ typedef int32_t ext_adi_potentiometer_t; /** * Initializes a potentiometer on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a potentiometer * * \param port * The ADI port to initialize as a gyro (from 1-8, 'a'-'h', 'A'-'H') * \param potentiometer_type * An adi_potentiometer_type_e_t enum value specifying the potentiometer version type * * \return An adi_potentiometer_t object containing the given port, or PROS_ERR if the * initialization failed. */ ext_adi_potentiometer_t ext_adi_potentiometer_init(uint8_t smart_port, uint8_t adi_port, adi_potentiometer_type_e_t potentiometer_type); /** * Gets the current potentiometer angle in tenths of a degree. * * The original potentiometer rotates 250 degrees thus returning an angle between 0-250 degrees. * Potentiometer V2 rotates 333 degrees thus returning an angle between 0-333 degrees. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EADDRINUSE - The port is not configured as a potentiometer * * \param potentiometer * The adi_potentiometer_t object for which the angle will be returned * * \return The potentiometer angle in degrees. */ double ext_adi_potentiometer_get_angle(ext_adi_potentiometer_t potentiometer); /** * Reference type for an initialized addressable led. * * This merely contains the port number for the led, unlike its use as an * object to store led data in the C++ API. */ typedef int32_t ext_adi_led_t; /** * Initializes a led on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * \param smart_port * The smart port with the adi expander (1-21) * \param adi_port * The ADI port to initialize as a led (from 1-8, 'a'-'h', 'A'-'H') * * \return An ext_adi_led_t object containing the given port, or PROS_ERR if the * initialization failed. * * \b Example: * \code * #define SMART_PORT 1 * #define ADI_PORT 'A' * * void opcontrol() { * // Initialize a led on smart port 1 and adi port A * ext_adi_led_t led = ext_adi_led_init(SMART_PORT, ADI_PORT); * // Initialize a buffer with a single color of red * uint32_t buffer[1] = {0xFF0000}; * * while (true) { * // Set the led to colors in the buffer * ext_adi_led_set(led, buffer, 1); * delay(5); * } * } * \endcode */ ext_adi_led_t ext_adi_led_init(uint8_t smart_port, uint8_t adi_port); /** * @brief Clear the entire led strip of color * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of buffer to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define SMART_PORT 1 * #define ADI_PORT 'A' * * void opcontrol() { * // Initialize a led on smart port 1 and adi port A * ext_adi_led_t led = ext_adi_led_init(SMART_PORT, ADI_PORT); * // Initialize a buffer with a single color of red * uint32_t buffer[1] = {0xFF0000}; * * while (true) { * // Set the led to colors in the buffer * ext_adi_led_set(led, buffer, 1); * delay(5); * * // Clear the led * ext_adi_led_clear_all(led, buffer, 1); * delay(5); * } * } * \endcode */ int32_t ext_adi_led_clear_all(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length); /** * @brief Set the entire led strip using the colors contained in the buffer * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of buffer to clear * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define SMART_PORT 1 * #define ADI_PORT 'A' * * void opcontrol() { * // Initialize a led on smart port 1 and adi port A * ext_adi_led_t led = ext_adi_led_init(SMART_PORT, ADI_PORT); * // Initialize a buffer with a single color of red * uint32_t buffer[1] = {0xFF0000}; * * while (true) { * // Set the led to colors in the buffer * ext_adi_led_set(led, buffer, 1); * delay(5); * } * } * \endcode */ int32_t ext_adi_led_set(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length); /** * @brief Set the entire led strip to one color * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of buffer to clear * @param color color to set all the led strip value to * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define SMART_PORT 1 * #define ADI_PORT 'A' * * void opcontrol() { * // Initialize a led on smart port 1 and adi port A * ext_adi_led_t led = ext_adi_led_init(SMART_PORT, ADI_PORT); * // Initialize a buffer with a single color of red * uint32_t buffer[1] = {0xFF0000}; * * while (true) { * // Set the entire led strip to red * ext_adi_led_set_all(led, buffer, 1, 0xFF0000); * delay(5); * } * } * \endcode */ int32_t ext_adi_led_set_all(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color); /** * @brief Set one pixel on the led strip * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of the input buffer * @param color color to clear all the led strip to * @param pixel_position position of the pixel to clear (0 indexed) * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define SMART_PORT 1 * #define ADI_PORT 'A' * * void opcontrol() { * // Initialize a led on smart port 1 and adi port A * ext_adi_led_t led = ext_adi_led_init(SMART_PORT, ADI_PORT); * // Initialize a buffer with multiple colors * uint32_t buffer[3] = {0xFF0000, 0x00FF00, 0x0000FF}; * * while (true) { * // Set the first pixel to red * ext_adi_led_set_pixel(led, buffer, 3, 0xFF0000, 0); * delay(5); * } * } * \endcode */ int32_t ext_adi_led_set_pixel(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color, uint32_t pixel_position); /** * @brief Clear one pixel on the led strip * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of ADI Ports * EINVAL - A given value is not correct, or the buffer is null * EADDRINUSE - The port is not configured for ADI output * * @param led port of type adi_led_t * @param buffer array of colors in format 0xRRGGBB, recommended that individual RGB value not to exceed 0x80 due to current draw * @param buffer_length length of the input buffer * @param pixel_position position of the pixel to clear (0 indexed) * @return PROS_SUCCESS if successful, PROS_ERR if not * * \b Example: * \code * #define SMART_PORT 1 * #define ADI_PORT 'A' * * void opcontrol() { * // Initialize a led on smart port 1 and adi port A * ext_adi_led_t led = ext_adi_led_init(SMART_PORT, ADI_PORT); * // Initialize a buffer with multiple colors * uint32_t buffer[3] = {0xFF0000, 0x00FF00, 0x0000FF}; * * while (true) { * // Set the first pixel to red * ext_adi_led_set_pixel(led, buffer, 3, 0xFF0000, 0); * delay(5); * * // Clear the first pixel * ext_adi_led_clear_pixel(led, buffer, 3, 0); * delay(5); * } * } * \endcode */ int32_t ext_adi_led_clear_pixel(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t pixel_position); ///@} #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_ADI_H_ ================================================ FILE: include/pros/gps.h ================================================ /** * \file pros/gps.h * \ingroup c-gps * * Contains prototypes for functions related to the VEX GPS. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-gps VEX GPS Sensor C API * \note For a pros-specific usage guide on the GPS, please check out our article [here.](@ref gps) */ #ifndef _PROS_GPS_H_ #define _PROS_GPS_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \ingroup c-gps */ /** * \addtogroup c-gps * @{ */ /** * \struct gps_position_s_t */ typedef struct __attribute__((__packed__)) gps_position_s { /// X Position (meters) double x; /// Y Position (meters) double y; } gps_position_s_t; /** * \struct gps_status_s_t */ typedef struct __attribute__((__packed__)) gps_status_s { /// X Position (meters) double x; /// Y Position (meters) double y; /// Perceived Pitch based on GPS + IMU double pitch; /// Perceived Roll based on GPS + IMU double roll; /// Perceived Yaw based on GPS + IMU double yaw; } gps_status_s_t; /** * \struct gps_orientation_s_t */ typedef struct __attribute__((__packed__)) gps_orientation_s { /// Perceived Pitch based on GPS + IMU double pitch; /// Perceived Roll based on GPS + IMU double roll; /// Perceived Yaw based on GPS + IMU double yaw; } gps_orientation_s_t; /** * \struct gps_raw_s */ struct gps_raw_s { /// Perceived Pitch based on GPS + IMU double x; /// Perceived Roll based on GPS + IMU double y; /// Perceived Yaw based on GPS + IMU double z; }; /** * \struct gps_accel_s_t * */ typedef struct gps_raw_s gps_accel_s_t; /** * \struct gps_gyro_s_t * */ typedef struct gps_raw_s gps_gyro_s_t; #ifdef __cplusplus namespace c { #endif /** * Set the GPS's offset relative to the center of turning in meters, * as well as its initial position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \param xOffset * Cartesian 4-Quadrant X offset from center of turning (meters) * \param yOffset * Cartesian 4-Quadrant Y offset from center of turning (meters) * \param xInitial * Initial 4-Quadrant X Position, with (0,0) being at the center of the field (meters) * \param yInitial * Initial 4-Quadrant Y Position, with (0,0) being at the center of the field (meters) * \param headingInitial * Heading with 0 being north on the field, in degrees [0,360) going clockwise * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * #define X_OFFSET .225 * #define Y_OFFSET .223 * #define X_INITIAL 1.54 * #define Y_INITIAL 1.14 * #define HEADING_INITIAL 90 * * void initialize() { * gps_initialize_full(GPS_PORT, X_OFFSET, Y_OFFSET, X_INITIAL, Y_INITIAL, HEADING_INITIAL); * } * \endcode */ int32_t gps_initialize_full(uint8_t port, double xInitial, double yInitial, double headingInitial, double xOffset, double yOffset); /** * Set the GPS's offset relative to the center of turning in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \param xOffset * Cartesian 4-Quadrant X offset from center of turning (meters) * \param yOffset * Cartesian 4-Quadrant Y offset from center of turning (meters) * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * #define X_OFFSET -.225 * #define Y_OFFSET .225 * * void initialize() { * gps_set_offset(GPS_PORT, X_OFFSET, Y_OFFSET); * } * \endcode */ int32_t gps_set_offset(uint8_t port, double xOffset, double yOffset); /** * Get the GPS's cartesian location relative to the center of turning/origin in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \return A struct (gps_position_s_t) containing the X and Y values if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_position_s_t pos; * * while (true) { * pos = gps_get_offset(GPS_PORT); * screen_print(TEXT_MEDIUM, 1, "X Offset: %4d, Y Offset: %4d", pos.x, pos.y); * delay(20); * } * } * \endcode */ gps_position_s_t gps_get_offset(uint8_t port); /** * Sets the robot's location relative to the center of the field in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \param xInitial * Initial 4-Quadrant X Position, with (0,0) being at the center of the field (meters) * \param yInitial * Initial 4-Quadrant Y Position, with (0,0) being at the center of the field (meters) * \param headingInitial * Heading with 0 being north on the field, in degrees [0,360) going clockwise * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * #define X_INITIAL -1.15 * #define Y_INITIAL 1.45 * #define HEADING_INITIAL 90 * * void initialize() { * gps_set_position(GPS_PORT, X_INITIAL, Y_INITIAL, HEADING_INITIAL); * } * \endcode */ int32_t gps_set_position(uint8_t port, double xInitial, double yInitial, double headingInitial); /** * Set the GPS sensor's data rate in milliseconds, only applies to IMU on GPS. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \param rate * Data rate in milliseconds (Minimum: 5 ms) * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * #define GPS_DATA_RATE 5 * * void initialize() { * gps_set_data_rate(GPS_PORT, GPS_DATA_RATE); * while (true) { * // Do something * } * } * \endcode */ int32_t gps_set_data_rate(uint8_t port, uint32_t rate); /** * Get the possible RMS (Root Mean Squared) error in meters for GPS position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return Possible RMS (Root Mean Squared) error in meters for GPS position. * If the operation failed, returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double error; * error = gps_get_error(GPS_PORT); * screen_print(TEXT_MEDIUM, 1, "Error: %4d", error); * } * \endcode */ double gps_get_error(uint8_t port); /** * Gets the position and roll, yaw, and pitch of the GPS. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return A struct (gps_status_s_t) containing values mentioned above. * If the operation failed, all the structure's members are filled with * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_status_s_t status; * * while (true) { * status = gps_get_position_and_orientation(GPS_PORT); * printf("X: %f, Y: %f, Pitch: %f, Roll: %f, Yaw: %f\n", status.x, status.y, status.pitch, status.roll, status.yaw); * delay(20); * } * } * \endcode */ gps_status_s_t gps_get_position_and_orientation(uint8_t port); /** * Gets the x and y position on the field of the GPS in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return A struct (gps_position_s_t) containing values mentioned above. * If the operation failed, all the structure's members are filled with * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_position_s_t position; * * while (true) { * position = gps_get_position(GPS_PORT); * printf("X: %f, Y: %f\n", position.x, position.y); * delay(20); * } * } * \endcode */ gps_position_s_t gps_get_position(uint8_t port); /** * Gets the X position in meters of the robot relative to the starting position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The X position in meters. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double pos_x; * * while (true) { * pos_x = gps_get_position_x(GPS_PORT); * printf("X: %f\n", pos_x); * delay(20); * } * } * \endcode */ double gps_get_position_x(uint8_t port); /** * Gets the Y position in meters of the robot relative to the starting position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The Y position in meters. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double pos_y; * * while (true) { * pos_y = gps_get_position_y(GPS_PORT); * printf("Y: %f\n", pos_y); * delay(20); * } * } * \endcode */ double gps_get_position_y(uint8_t port); /** * Gets the pitch, roll, and yaw of the GPS relative to the starting orientation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return A struct (gps_orientation_s_t) containing values mentioned above. * If the operation failed, all the structure's members are filled with * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_orientation_s_t orientation; * * while (true) { * orientation = gps_get_orientation(GPS_PORT); * printf("pitch: %f, roll: %f, yaw: %f\n", orientation.pitch, orientation.roll, orientation.yaw); * delay(20); * } * } * \endcode */ gps_orientation_s_t gps_get_orientation(uint8_t port); /** * Gets the pitch of the robot in degrees relative to the starting oreintation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The pitch in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double pitch; * * while (true) { * pitch = gps_get_pitch(GPS_PORT); * printf("pitch: %f\n", pitch); * delay(20); * } * } * \endcode */ double gps_get_pitch(uint8_t port); /** * Gets the roll of the robot in degrees relative to the starting oreintation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The roll in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double roll; * * while (true) { * roll = gps_get_roll(GPS_PORT); * printf("roll: %f\n", roll); * delay(20); * } * } * \endcode */ double gps_get_roll(uint8_t port); /** * Gets the yaw of the robot in degrees relative to the starting oreintation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The yaw in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double yaw; * * while (true) { * yaw = gps_get_yaw(GPS_PORT); * printf("yaw: %f\n", yaw); * delay(20); * } * } * \endcode */ double gps_get_yaw(uint8_t port); /** * Get the heading in [0,360) degree values. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The heading in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double heading; * * while (true) { * heading = gps_get_heading(GPS_PORT); * printf("heading: %f\n", heading); * delay(20); * } * } * \endcode */ double gps_get_heading(uint8_t port); /** * Get the heading in the max double value and min double value scale. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * * \return The heading in [DOUBLE_MIN, DOUBLE_MAX] values. If the operation * fails, returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double heading_raw; * * while (true) { * heading_raw = gps_get_heading_raw(GPS_PORT); * printf("heading_raw: %f\n", heading_raw); * delay(20); * } * } * \endcode */ double gps_get_heading_raw(uint8_t port); /** * Get the GPS's raw gyroscope values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \return A struct (gps_gyro_s_t) containing values mentioned above. * If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_gyro_s_t gyro; * * while (true) { * gyro = gps_get_gyro(GPS_PORT); * printf("Gyro: %f %f %f\n", gyro.x, gyro.y, gyro.z); * delay(20); * } * } * \endcode */ gps_gyro_s_t gps_get_gyro_rate(uint8_t port); /** * Get the GPS's raw gyroscope value in x-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \return The raw gyroscope value in x-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double gyro_x; * * while (true) { * gyro_x = gps_get_gyro_x(GPS_PORT); * printf("gyro_x: %f\n", gyro_x); * delay(20); * } * } * \endcode */ double gps_get_gyro_rate_x(uint8_t port); /** * Get the GPS's raw gyroscope value in y-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \return The raw gyroscope value in y-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double gyro_y; * * while (true) { * gyro_y = gps_get_gyro_y(GPS_PORT); * printf("gyro_y: %f\n", gyro_y); * delay(20); * } * } * \endcode */ double gps_get_gyro_rate_y(uint8_t port); /** * Get the GPS's raw gyroscope value in z-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \return The raw gyroscope value in z-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double gyro_z; * * while (true) { * gyro_z = gps_get_gyro_z(GPS_PORT); * printf("gyro_z: %f\n", gyro_z); * delay(20); * } * } * \endcode */ double gps_get_gyro_rate_z(uint8_t port); /** * Get the GPS's raw accelerometer values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS's port number from 1-21 * \return A struct (gps_accel_s_t) containing values mentioned above. * If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_accel_s_t accel; * * while (true) { * accel = gps_get_accel(GPS_PORT); * printf("X: %f, Y: %f, Z: %f\n", accel.x, accel.y, accel.z); * delay(20); * } * } * \endcode */ gps_accel_s_t gps_get_accel(uint8_t port); /** * Get the GPS's raw accelerometer value in x-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS's port number from 1-21 * \return The raw accelerometer value in x-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double accel_x; * * while (true) { * accel_x = gps_get_accel_x(GPS_PORT); * printf("accel_x: %f\n", accel_x); * delay(20); * } * } * \endcode */ double gps_get_accel_x(uint8_t port); /** * Get the GPS's raw accelerometer value in y-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS's port number from 1-21 * \return The raw accelerometer value in y-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double accel_y; * * while (true) { * accel_y = gps_get_accel_y(GPS_PORT); * printf("accel_y: %f\n", accel_y); * delay(20); * } * } * \endcode */ double gps_get_accel_y(uint8_t port); /** * Get the GPS's raw accelerometer value in z-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS's port number from 1-21 * \return The raw accelerometer value in z-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * double accel_z; * * while (true) { * accel_z = gps_get_accel_z(GPS_PORT); * printf("accel_z: %f\n", accel_z); * delay(20); * } * } * \endcode */ double gps_get_accel_z(uint8_t port); #ifdef __cplusplus } } } #endif #endif ================================================ FILE: include/pros/gps.hpp ================================================ /** * \file pros/gps.hpp * \ingroup cpp-gps * * Contains prototypes for functions related to the VEX GPS. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-gps VEX GPS Sensor C API * \note For a pros-specific usage guide on the GPS, please check out our article [here.](@ref gps) */ #ifndef _PROS_GPS_HPP_ #define _PROS_GPS_HPP_ #include #include #include #include "pros/device.hpp" #include "pros/gps.h" namespace pros { inline namespace v5 { /** * \ingroup cpp-gps * @{ */ class Gps : public Device { /** * \addtogroup cpp-gps * @{ */ public: /** * Creates a GPS object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 port number from 1-21 * \b Example: * \code * pros::Gps gps(1); * \endcode * */ Gps(const std::uint8_t port) : Device(port, DeviceType::gps){}; Gps(const Device& device) : Gps(device.get_port()){}; /** * Creates a GPS object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 port number from 1-21 * \param xInitial * Cartesian 4-Quadrant X initial position (meters) * \param yInitial * Cartesian 4-Quadrant Y initial position (meters) * \param headingInitial * Initial heading (degrees) * * \b Example: * \code * pros::Gps gps(1, 1.30, 1.20, 90); * \endcode * */ explicit Gps(const std::uint8_t port, double xInitial, double yInitial, double headingInitial) : Device(port, DeviceType::gps) { pros::c::gps_set_position(port, xInitial, yInitial, headingInitial); }; /** * Creates a GPS object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 port number from 1-21 * \param xOffset * Cartesian 4-Quadrant X offset from center of turning (meters) * \param yOffset * Cartesian 4-Quadrant Y offset from center of turning (meters) * * \b Example: * \code * pros::Gps gps(1, 1.30, 1.20); * \endcode * */ explicit Gps(const std::uint8_t port, double xOffset, double yOffset) : Device(port, DeviceType::gps) { pros::c::gps_set_offset(port, xOffset, yOffset); }; /** * Creates a GPS object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 port number from 1-21 * \param xInitial * Initial 4-Quadrant X Position, with (0,0) being at the center of the field (meters) * \param yInitial * Initial 4-Quadrant Y Position, with (0,0) being at the center of the field (meters) * \param headingInitial * Initial Heading, with 0 being North, 90 being East, 180 being South, and 270 being West (degrees) * \param xOffset * Cartesian 4-Quadrant X offset from center of turning (meters) * \param yOffset * Cartesian 4-Quadrant Y offset from center of turning (meters) * * \b Example: * \code * pros::Gps gps(1, 1.30, 1.20, 180, 1.30, 1.20); * \endcode * */ explicit Gps(const std::uint8_t port, double xInitial, double yInitial, double headingInitial, double xOffset, double yOffset) : Device(port, DeviceType::gps) { pros::c::gps_initialize_full(port, xInitial, yInitial, headingInitial, xOffset, yOffset); }; /** * Set the GPS's offset relative to the center of turning in meters, * as well as its initial position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param xOffset * Cartesian 4-Quadrant X offset from center of turning (meters) * \param yOffset * Cartesian 4-Quadrant Y offset from center of turning (meters) * \param xInitial * Initial 4-Quadrant X Position, with (0,0) being at the center of the field (meters) * \param yInitial * Initial 4-Quadrant Y Position, with (0,0) being at the center of the field (meters) * \param headingInitial * Heading with 0 being north on the field, in degrees [0,360) going clockwise * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT, 1.1, 1.2, 180, .4, .4); * // this is equivalent to the above line * gps.initialize_full(1.1, 1.2, 180, .4, .4); * while (true) { * delay(20); * } * } * \endcode */ virtual std::int32_t initialize_full(double xInitial, double yInitial, double headingInitial, double xOffset, double yOffset) const; /** * Set the GPS's offset relative to the center of turning in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param xOffset * Cartesian 4-Quadrant X offset from center of turning (meters) * \param yOffset * Cartesian 4-Quadrant Y offset from center of turning (meters) * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT, 1.1, 1.2, 180, .4, .4); * // this is equivalent to the above line * gps.set_offset(.4, .4); * while (true) { * delay(20); * } * } * \endcode */ virtual std::int32_t set_offset(double xOffset, double yOffset) const; /** * Gets all GPS sensors. * * \return A vector of Gps sensor objects. * * \b Example * \code * void opcontrol() { * std::vector gps_all = pros::Gps::get_all_devices(); // All GPS sensors that are connected * } * \endcode */ static std::vector get_all_devices(); /** * Get the GPS's cartesian location relative to the center of turning/origin in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param port * The V5 GPS port number from 1-21 * \return A struct (gps_position_s_t) containing the X and Y values if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * gps_position_s_t pos; * Gps gps(GPS_PORT); * while (true) { * pos = gps.get_offset(); * screen_print(TEXT_MEDIUM, 1, "X Offset: %4d, Y Offset: %4d", pos.x, pos.y); * delay(20); * } * } * \endcode */ virtual pros::gps_position_s_t get_offset() const; /** * Sets the robot's location relative to the center of the field in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param xInitial * Initial 4-Quadrant X Position, with (0,0) being at the center of the field (meters) * \param yInitial * Initial 4-Quadrant Y Position, with (0,0) being at the center of the field (meters) * \param headingInitial * Heading with 0 being north on the field, in degrees [0,360) going clockwise * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * gps.set_position(1.3, 1.4, 180); * while (true) { * printf("X: %f, Y: %f, Heading: %f\n", gps.get_position().x, * gps.get_position().y, gps.get_position().heading); * delay(20); * } * } * \endcode */ virtual std::int32_t set_position(double xInitial, double yInitial, double headingInitial) const; /** * Set the GPS sensor's data rate in milliseconds, only applies to IMU on GPS. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \param rate * Data rate in milliseconds (Minimum: 5 ms) * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * gps.set_data_rate(10); * while (true) { * printf("X: %f, Y: %f, Heading: %f\n", gps.get_position().x, * gps.get_position().y, gps.get_position().heading); * delay(10); * } * } * \endcode */ virtual std::int32_t set_data_rate(std::uint32_t rate) const; /** * Get the possible RMS (Root Mean Squared) error in meters for GPS position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return Possible RMS (Root Mean Squared) error in meters for GPS position. * If the operation failed, returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * double error = gps.get_error(); * printf("Error: %f\n", error); * pros::delay(20); * } * \endcode */ virtual double get_error() const; /** * Gets the position and roll, yaw, and pitch of the GPS. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * * \return A struct (gps_status_s_t) containing values mentioned above. * If the operation failed, all the structure's members are filled with * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * gps_status_s_t status; * while (true) { * status = gps.get_position_and_orientation(); * printf("X: %f, Y: %f, Roll: %f, Pitch: %f, Yaw: %f\n", * status.x, status.y, status.roll, status.pitch, status.yaw); * delay(20); * } * } * \endcode */ virtual pros::gps_status_s_t get_position_and_orientation() const; /** * Gets the x and y position on the field of the GPS in meters. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return A struct (gps_position_s_t) containing values mentioned above. * If the operation failed, all the structure's members are filled with * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * gps_position_s_t position; * while (true) { * position = gps.get_position(); * printf("X: %f, Y: %f\n", position.x, position.y); * delay(20); * } * } * \endcode */ virtual pros::gps_position_s_t get_position() const; /** * Gets the X position in meters of the robot relative to the starting position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The X position in meters. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double pos_x = gps.get_position_x(); * printf("X: %f\n", pos_x); * pros::delay(20); * } * } * \endcode */ virtual double get_position_x() const; /** * Gets the Y position in meters of the robot relative to the starting position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The Y position in meters. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double pos_y = gps.get_position_y(); * printf("Y: %f\n", pos_y); * pros::delay(20); * } * } * \endcode */ virtual double get_position_y() const; /** * Gets the pitch, roll, and yaw of the GPS relative to the starting orientation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return A struct (gps_orientation_s_t) containing values mentioned above. * If the operation failed, all the structure's members are filled with * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * gps_orientation_s_t orientation; * while (true) { * orientation = gps.get_orientation(); * printf("pitch: %f, roll: %f, yaw: %f\n", orientation.pitch, * orientation.roll, orientation.yaw); * delay(20); * } * } * \endcode */ virtual pros::gps_orientation_s_t get_orientation() const; /** * Gets the pitch of the robot in degrees relative to the starting oreintation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The pitch in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double pitch = gps.get_pitch(); * printf("pitch: %f\n", pitch); * pros::delay(20); * } * } * \endcode */ virtual double get_pitch() const; /** * Gets the roll of the robot in degrees relative to the starting oreintation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The roll in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double roll = gps.get_roll(); * printf("roll: %f\n", roll); * pros::delay(20); * } * } * \endcode */ virtual double get_roll() const; /** * Gets the yaw of the robot in degrees relative to the starting oreintation. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The yaw in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double yaw = gps.get_yaw(); * printf("yaw: %f\n", yaw); * pros::delay(20); * } * } * \endcode */ virtual double get_yaw() const; /** * Get the heading in [0,360) degree values. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * * \return The heading in [0,360) degree values. If the operation failed, * returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double heading = gps.get_heading(); * printf("Heading: %f\n", heading); * pros::delay(20); * } * } * \endcode */ virtual double get_heading() const; /** * Get the heading in the max double value and min double value scale. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The heading in [DOUBLE_MIN, DOUBLE_MAX] values. If the operation * fails, returns PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double heading = gps.get_heading_raw(); * printf("Heading: %f\n", heading); * pros::delay(20); * } * } * \endcode */ virtual double get_heading_raw() const; /** * Get the GPS's raw gyroscope value in z-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The raw gyroscope value in z-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double gyro_z = gps.get_gyro_z(); * printf("gyro_z: %f\n", gyro_z); * pros::delay(20); * } * } * \endcode */ virtual pros::gps_gyro_s_t get_gyro_rate() const; /** * Get the GPS's raw gyroscope value in x-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The raw gyroscope value in x-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double gyro_x = gps.get_gyro_x(); * printf("gyro_x: %f\n", gyro_x); * pros::delay(20); * } * } * \endcode */ virtual double get_gyro_rate_x() const; /** * Get the GPS's raw gyroscope value in y-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The raw gyroscope value in y-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double gyro_y = gps.get_gyro_y(); * printf("gyro_y: %f\n", gyro_y); * pros::delay(20); * } * } * \endcode */ virtual double get_gyro_rate_y() const; /** * Get the GPS's raw gyroscope value in z-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a GPS * EAGAIN - The sensor is still calibrating * * \return The raw gyroscope value in z-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double gyro_z = gps.get_gyro_z(); * printf("gyro_z: %f\n", gyro_z); * pros::delay(20); * } * } * \endcode */ virtual double get_gyro_rate_z() const; /** * Get the GPS's raw accelerometer values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \return The raw accelerometer values. If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. */ virtual pros::gps_accel_s_t get_accel() const; /** * Get the GPS's raw accelerometer value in x-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \return The raw accelerometer value in x-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double accel_x = gps.get_accel_x(); * printf("accel_x: %f\n", accel_x); * pros::delay(20); * } * } * \endcode */ virtual double get_accel_x() const; /** * Get the GPS's raw accelerometer value in y-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \return The raw accelerometer value in y-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double accel_y = gps.get_accel_y(); * printf("accel_y: %f\n", accel_y); * pros::delay(20); * } * } * \endcode */ virtual double get_accel_y() const; /** * Get the GPS's raw accelerometer value in z-axis * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an GPS * EAGAIN - The sensor is still calibrating * * \return The raw accelerometer value in z-axis. If the operation fails, returns * PROS_ERR_F and errno is set. * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * double accel_z = gps.get_accel_z(); * printf("accel_z: %f\n", accel_z); * pros::delay(20); * } * } * \endcode */ virtual double get_accel_z() const; /** * This is the overload for the << operator for printing to streams * * Prints in format: * Gps [port: gps._port, x: (x position), y: (y position), heading: (gps heading), rotation: (gps rotation)] * * \b Example * \code * #define GPS_PORT 1 * * void opcontrol() { * Gps gps(GPS_PORT); * while(true) { * std::cout << gps << std::endl; * pros::delay(20); * } * } * \endcode */ friend std::ostream& operator<<(std::ostream& os, const pros::Gps& gps); /** * Gets a gps sensor that is plugged in to the brain * * \note The first time this function is called it returns the gps sensor at the lowest port * If this function is called multiple times, it will cycle through all the ports. * For example, if you have 1 gps sensor on the robot * this function will always return a gps sensor object for that port. * If you have 2 gps sensors, all the odd numered calls to this function will return objects * for the lower port number, * all the even number calls will return gps objects for the higher port number * * * This functions uses the following values of errno when an error state is * reached: * ENODEV - No gps sensor is plugged into the brain * * \return A gps object corresponding to a port that a gps sensor is connected to the brain * If no gps sensor is plugged in, it returns a gps sensor on port PROS_ERR_BYTE * */ static Gps get_gps(); ///@} }; // Gps Class namespace literals { /** * Constructs a Gps object with the given port number * * \b Example * \code * using namespace literals; * * void opcontrol() { * pros::Gps gps = 1_gps; * while (true) { * pos = gps.get_position(); * screen_print(TEXT_MEDIUM, 1, "X Position: %4d, Y Position: %4d", pos.x, pos.y); * delay(20); * } * } * \endcode */ const pros::Gps operator""_gps(const unsigned long long int g); } // namespace literals /// @brief /// Alias for Gps is GPS for user convenience. using GPS = Gps; } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/imu.h ================================================ /** * \file pros/imu.h * \ingroup c-imu * * Contains prototypes for functions related to the VEX Inertial sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-imu VEX Inertial Sensor C API */ #ifndef _PROS_IMU_H_ #define _PROS_IMU_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \ingroup c-imu * */ /** * \addtogroup c-imu * @{ */ /** * \enum imu_status_e_t * @brief Indicates IMU status. */ typedef enum imu_status_e { E_IMU_STATUS_READY = 0, // IMU is connected but not currently calibrating /** The IMU is calibrating */ E_IMU_STATUS_CALIBRATING = 1, /** Used to indicate that an error state was reached in the imu_get_status function,\ not that the IMU is necessarily in an error state */ E_IMU_STATUS_ERROR = 0xFF, } imu_status_e_t; typedef enum imu_orientation_e { E_IMU_Z_UP = 0, // IMU has the Z axis UP (VEX Logo facing DOWN) E_IMU_Z_DOWN = 1, // IMU has the Z axis DOWN (VEX Logo facing UP) E_IMU_X_UP = 2, // IMU has the X axis UP E_IMU_X_DOWN = 3, // IMU has the X axis DOWN E_IMU_Y_UP = 4, // IMU has the Y axis UP E_IMU_Y_DOWN = 5, // IMU has the Y axis DOWN E_IMU_ORIENTATION_ERROR = 0xFF // NOTE: used for returning an error from the get_physical_orientation function, not // that the IMU is necessarily in an error state } imu_orientation_e_t; /** * \struct quaternion_s_t */ typedef struct __attribute__((__packed__)) quaternion_s { double x; double y; double z; double w; } quaternion_s_t; /** * \struct imu_raw_s * */ struct imu_raw_s { double x; double y; double z; }; /** * \struct imu_gyro_s_t * */ typedef struct imu_raw_s imu_gyro_s_t; /** * \struct imu_accel_s_t * */ typedef struct imu_raw_s imu_accel_s_t; /** * \struct euler_s_t * */ typedef struct __attribute__((__packed__)) euler_s { double pitch; double roll; double yaw; } euler_s_t; #ifdef __cplusplus namespace c { #endif /** * \def IMU_MINIMUM_DATA_RATE */ #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define IMU_STATUS_CALIBRATING pros::E_IMU_STATUS_CALIBRATING #define IMU_STATUS_ERROR pros::E_IMU_STATUS_ERROR #else #define IMU_STATUS_CALIBRATING E_IMU_STATUS_CALIBRATING #define IMU_STATUS_ERROR E_IMU_STATUS_ERROR #endif #endif #define IMU_MINIMUM_DATA_RATE 5 /** * Calibrate IMU * * Calibration takes approximately 2 seconds, but this function only blocks * until the IMU status flag is set properly to E_IMU_STATUS_CALIBRATING, * with a minimum blocking time of 5ms. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is already calibrating, or time out setting the status flag. * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void initialize() { * imu_reset(IMU_PORT); * int time = millis(); * int iter = 0; * while (imu_get_status(IMU_PORT) & E_IMU_STATUS_CALIBRATING) { * printf("IMU calibrating... %d\n", iter); * iter += 10; * delay(10); * } * // should print about 2000 ms * printf("IMU is done calibrating (took %d ms)\n", iter - time); * } * \endcode */ int32_t imu_reset(uint8_t port); /** * Calibrate IMU and Blocks while Calibrating * * Calibration takes approximately 2 seconds and blocks during this period, * with a timeout for this operation being set a 3 seconds as a safety margin. * Like the other reset function, this function also blocks until the IMU * status flag is set properly to E_IMU_STATUS_CALIBRATING, with a minimum * blocking time of 5ms and a timeout of 1 second if it's never set. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is already calibrating, or time out setting the status flag. * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed (timing out or port claim failure), setting errno. */ int32_t imu_reset_blocking(uint8_t port); /** * Set the Inertial Sensor's refresh interval in milliseconds. * * The rate may be specified in increments of 5ms, and will be rounded down to * the nearest increment. The minimum allowable refresh rate is 5ms. The default * rate is 10ms. * * As values are copied into the shared memory buffer only at 10ms intervals, * setting this value to less than 10ms does not mean that you can poll the * sensor's values any faster. However, it will guarantee that the data is as * recent as possible. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param rate The data refresh interval in milliseconds * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * \endcode */ int32_t imu_set_data_rate(uint8_t port, uint32_t rate); /** * Get the total number of degrees the Inertial Sensor has spun about the z-axis * * This value is theoretically unbounded. Clockwise rotations are represented * with positive degree values, while counterclockwise rotations are represented * with negative ones. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The degree value or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * printf("IMU get rotation: %f degrees\n", imu_get_rotation(IMU_PORT)); * delay(20); * } * } * \endcode */ double imu_get_rotation(uint8_t port); /** * Get the Inertial Sensor's heading relative to the initial direction of its * x-axis * * This value is bounded by [0,360). Clockwise rotations are represented with * positive degree values, while counterclockwise rotations are represented with * negative ones. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The degree value or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * printf("IMU get heading: %f degrees\n", imu_get_heading(IMU_PORT)); * delay(20); * } * } * \endcode */ double imu_get_heading(uint8_t port); /** * Get a quaternion representing the Inertial Sensor's orientation * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The quaternion representing the sensor's orientation. If the * operation failed, all the quaternion's members are filled with PROS_ERR_F and * errno is set. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * quaternion_s_t qt = imu_get_quaternion(IMU_PORT); * printf("IMU quaternion: {x: %f, y: %f, z: %f, w: %f}\n", qt.x, qt.y, qt.z, qt.w); * delay(20); * } * } * \endcode */ quaternion_s_t imu_get_quaternion(uint8_t port); /** * Get the Euler angles representing the Inertial Sensor's orientation * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The Euler angles representing the sensor's orientation. If the * operation failed, all the structure's members are filled with PROS_ERR_F and * errno is set. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * euler_s_t eu = imu_get_euler(IMU_PORT); * printf("IMU euler angles: {pitch: %f, roll: %f, yaw: %f}\n", eu.pitch, eu.roll, eu.yaw); * delay(20); * } * } * \endcode */ euler_s_t imu_get_euler(uint8_t port); /** * Get the Inertial Sensor's raw gyroscope values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The pitch angle, or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * printf("IMU pitch: %f\n", imu_get_pitch(IMU_PORT)); * delay(20); * } * } * \endcode */ imu_gyro_s_t imu_get_gyro_rate(uint8_t port); /** * Get the Inertial Sensor's raw acceleroneter values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The roll angle, or PROS_ERR_F if the operation failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * printf("IMU roll: %f\n", imu_get_roll(IMU_PORT)); * delay(20); * } * } * \endcode */ imu_accel_s_t imu_get_accel(uint8_t port); /** * Get the Inertial Sensor's status * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The yaw angle, or PROS_ERR_F if the operation failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * printf("IMU yaw: %f\n", imu_get_yaw(IMU_PORT)); * delay(20); * } * } * \endcode */ imu_status_e_t imu_get_status(uint8_t port); // Value set functions: /** * Sets the current reading of the Inertial Sensor's euler values to * target euler values. Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The raw gyroscope values. If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * int32_t val = imu_set_euler(IMU_PORT, {45, 60, 90}); * printf("IMU : {gyro vals: %d}\n", val); * delay(20); * } * } * \endcode */ int32_t imu_set_euler(uint8_t port, euler_s_t target); /** * Get the Inertial Sensor's pitch angle bounded by (-180,180) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The raw accelerometer values. If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * imu_accel_s_t accel = imu_get_accel(IMU_PORT); * printf("IMU accel values: {x: %f, y: %f, z: %f}\n", accel.x, accel.y, accel.z); * delay(20); * } * } * \endcode */ double imu_get_pitch(uint8_t port); /** * Get the Inertial Sensor's roll angle bounded by (-180,180) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The Inertial Sensor's status code, or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void initialize() { * imu_reset(IMU_PORT); * int time = millis(); * int iter = 0; * while (imu_get_status(IMU_PORT) & E_IMU_STATUS_CALIBRATING) { * printf("IMU calibrating... %d\n", iter); * iter += 10; * delay(10); * } * // should print about 2000 ms * printf("IMU is done calibrating (took %d ms)\n", iter - time); * } * \endcode */ double imu_get_roll(uint8_t port); /** * Get the Inertial Sensor's yaw angle bounded by (-180,180) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The yaw angle, or PROS_ERR_F if the operation failed, setting errno. */ double imu_get_yaw(uint8_t port); // NOTE: not used // void imu_set_mode(uint8_t port, uint32_t mode); // uint32_t imu_get_mode(uint8_t port); /** * \name Value Reset Functions * @{ */ /** * Resets the current reading of the Inertial Sensor's heading to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare_heading(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare_heading(uint8_t port); /** * Resets the current reading of the Inertial Sensor's rotation to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare_rotation(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare_rotation(uint8_t port); /** * Resets the current reading of the Inertial Sensor's pitch to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare_pitch(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare_pitch(uint8_t port); /** * Resets the current reading of the Inertial Sensor's roll to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare_roll(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare_roll(uint8_t port); /** * Resets the current reading of the Inertial Sensor's yaw to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare_yaw(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare_yaw(uint8_t port); /** * Reset all 3 euler values of the Inertial Sensor to 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare_euler(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare_euler(uint8_t port); /** * Resets all 5 values of the Inertial Sensor to 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_tare(IMU_PORT); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_tare(uint8_t port); /** @} */ /** * \name Value Set Functions * @{ */ /** * Sets the current reading of the Inertial Sensor's euler values to * target euler values. Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target euler values for the euler values to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_set_euler(IMU_PORT, {45,45,45}); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_set_euler(uint8_t port, euler_s_t target); /** * Sets the current reading of the Inertial Sensor's rotation to target value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the rotation value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_set_rotation(IMU_PORT, 45); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_set_rotation(uint8_t port, double target); /** * Sets the current reading of the Inertial Sensor's heading to target value * Target will default to 360 if above 360 and default to 0 if below 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the heading value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_set_heading(IMU_PORT, 45); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_set_heading(uint8_t port, double target); /** * Sets the current reading of the Inertial Sensor's pitch to target value * Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the pitch value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_set_pitch(IMU_PORT, 45); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_set_pitch(uint8_t port, double target); /** * Sets the current reading of the Inertial Sensor's roll to target value * Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the roll value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_set_roll(IMU_PORT, 45); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_set_roll(uint8_t port, double target); /** * Sets the current reading of the Inertial Sensor's yaw to target value * Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the yaw value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define IMU_PORT 1void opcontrol() { * * while (true) { * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * imu_set_yaw(IMU_PORT, 45); * } * pros::delay(20); * } * } * \endcode */ int32_t imu_set_yaw(uint8_t port, double target); /** * Returns the physical orientation of the IMU * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * * \param port * The V5 Inertial Sensor port number from 1-21 * \returns The orientation of the Inertial Sensor or PROS_ERR if an error occured. * */ imu_orientation_e_t imu_get_physical_orientation(uint8_t port); /** @} */ /** @} */ #ifdef __cplusplus } } } #endif #endif ================================================ FILE: include/pros/imu.hpp ================================================ /** * \file pros/imu.hpp * \ingroup cpp-imu * * Contains prototypes for functions related to the VEX Inertial sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-imu VEX Inertial Sensor C++ API */ #ifndef _PROS_IMU_HPP_ #define _PROS_IMU_HPP_ #include #include #include "pros/device.hpp" #include "pros/imu.h" namespace pros { /** * \ingroup cpp-imu * */ /** * \addtogroup cpp-imu * @{ */ /** * \enum Imu_Status * @brief Indicates IMU status. */ enum class ImuStatus { ready = 0, /** The IMU is calibrating */ calibrating = 19, /** Used to indicate that an error state was reached in the imu_get_status function,\ not that the IMU is necessarily in an error state */ error = 0xFF, }; inline namespace v5 { /** * \ingroup cpp-imu */ class Imu : public Device { /** * \addtogroup cpp-imu * @{ */ public: /** * Creates an Imu object for the given port * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * * \param port * The V5 Inertial Sensor port number from 1-21 * * \b Example * \code * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Do something with the sensor data * } * } * \endcode */ Imu(const std::uint8_t port) : Device(port, DeviceType::imu){}; Imu(const Device& device) : Imu(device.get_port()){}; /** * Gets a IMU sensor that is plugged in to the brain * * \note The first time this function is called it returns the IMU sensor at the lowest port * If this function is called multiple times, it will cycle through all the ports. * For example, if you have 1 IMU sensor on the robot * this function will always return a IMU sensor object for that port. * If you have 2 IMU sensors, all the odd numered calls to this function will return objects * for the lower port number, * all the even number calls will return IMU objects for the higher port number * * * This functions uses the following values of errno when an error state is * reached: * ENODEV - No IMU sensor is plugged into the brain * * \return A IMU object corresponding to a port that a IMU sensor is connected to the brain * If no IMU sensor is plugged in, it returns a IMU sensor on port PROS_ERR_BYTE * */ static Imu get_imu(); /** * Calibrate IMU * * Calibration takes approximately 2 seconds and blocks during this period if * the blocking param is true, with a timeout for this operation being set a 3 * seconds as a safety margin. This function also blocks until the IMU * status flag is set properly to E_IMU_STATUS_CALIBRATING, with a minimum * blocking time of 5ms and a timeout of 1 second if it's never set. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is already calibrating, or time out setting the status flag. * * \param blocking * Whether this function blocks during calibration. * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * // Block until calibration is complete * imu.reset(true); * } * \endcode */ virtual std::int32_t reset(bool blocking = false) const; /** * Set the Inertial Sensor's refresh interval in milliseconds. * * The rate may be specified in increments of 5ms, and will be rounded down to * the nearest increment. The minimum allowable refresh rate is 5ms. The default * rate is 10ms. * * As values are copied into the shared memory buffer only at 10ms intervals, * setting this value to less than 10ms does not mean that you can poll the * sensor's values any faster. However, it will guarantee that the data is as * recent as possible. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param rate The data refresh interval in milliseconds * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the refresh rate to 5ms * std::int32_t status = imu.set_data_rate(5); * delay(20); * * // Check if the operation was successful * if (status == PROS_ERR) { * // Do something with the error * } * * // Do something with the sensor data * } * } * \endcode */ virtual std::int32_t set_data_rate(std::uint32_t rate) const; /** * Gets all IMU sensors. * * \return A vector of Imu sensor objects. * * \b Example * \code * void opcontrol() { * std::vector imu_all = pros::Imu::get_all_devices(); // All IMU sensors that are connected * } * \endcode */ static std::vector get_all_devices(); /** * Get the total number of degrees the Inertial Sensor has spun about the z-axis * * This value is theoretically unbounded. Clockwise rotations are represented * with positive degree values, while counterclockwise rotations are represented * with negative ones. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The degree value or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the total number of degrees the sensor has spun * printf("Total rotation: %f\n", imu.get_rotation()); * delay(20); * } * } * \endcode */ virtual double get_rotation() const; /** * Get the Inertial Sensor's heading relative to the initial direction of its * x-axis * * This value is bounded by [0,360). Clockwise rotations are represented with * positive degree values, while counterclockwise rotations are represented with * negative ones. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The degree value or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's heading * printf("Heading: %f\n", imu.get_heading()); * delay(20); * } * } * \endcode */ virtual double get_heading() const; /** * Get a quaternion representing the Inertial Sensor's orientation * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The quaternion representing the sensor's orientation. If the * operation failed, all the quaternion's members are filled with PROS_ERR_F and * errno is set. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's quaternion * pros::quaternion_s_t quat = imu.get_quaternion(); * cout << "Quaternion: " << quat.w << ", " << quat.x << ", " << quat.y << ", " << quat.z << endl; * delay(20); * } * } * \endcode */ virtual pros::quaternion_s_t get_quaternion() const; /** * Get the Euler angles representing the Inertial Sensor's orientation * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The Euler angles representing the sensor's orientation. If the * operation failed, all the structure's members are filled with PROS_ERR_F and * errno is set. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's Euler angles * pros::euler_s_t euler = imu.get_euler(); * cout << "Euler: " << euler.roll << ", " << euler.pitch << ", " << euler.yaw << endl; * delay(20); * } * } * \endcode */ virtual pros::euler_s_t get_euler() const; /** * Get the Inertial Sensor's pitch angle bounded by (-180,180) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The pitch angle, or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's pitch * printf("Pitch: %f\n", imu.get_pitch()); * delay(20); * } * } * \endcode */ virtual double get_pitch() const; /** * Get the Inertial Sensor's roll angle bounded by (-180,180) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The roll angle, or PROS_ERR_F if the operation failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's roll * printf("Roll: %f\n", imu.get_roll()); * delay(20); * } * } * \endcode */ virtual double get_roll() const; /** * Get the Inertial Sensor's yaw angle bounded by (-180,180) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The yaw angle, or PROS_ERR_F if the operation failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's yaw * printf("Yaw: %f\n", imu.get_yaw()); * delay(20); * } * } * \endcode */ virtual double get_yaw() const; /** * Get the Inertial Sensor's raw gyroscope values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The raw gyroscope values. If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's raw gyroscope values * pros::imu_gyro_s_t gyro = imu.get_gyro_rate(); * cout << "Gyro: " << gyro.x << ", " << gyro.y << ", " << gyro.z << endl; * delay(20); * } * } * \endcode */ virtual pros::imu_gyro_s_t get_gyro_rate() const; /** * Resets the current reading of the Inertial Sensor's rotation to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's rotation value to 10 * imu.set_rotation(10); * delay(20); * * // Do something with sensor * * // Reset the sensor's rotation value to 0 * imu.tare_rotation(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare_rotation() const; /** * Resets the current reading of the Inertial Sensor's heading to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's heading value to 10 * imu.set_heading(10); * delay(20); * * // Do something with sensor * * // Reset the sensor's heading value to 0 * imu.tare_heading(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare_heading() const; /** * Resets the current reading of the Inertial Sensor's pitch to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's pitch value to 10 * imu.set_pitch(10); * delay(20); * * // Do something with sensor * * // Reset the sensor's pitch value to 0 * imu.tare_pitch(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare_pitch() const; /** * Resets the current reading of the Inertial Sensor's yaw to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's yaw value to 10 * imu.set_yaw(10); * delay(20); * * // Do something with sensor * * // Reset the sensor's yaw value to 0 * imu.tare_yaw(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare_yaw() const; /** * Resets the current reading of the Inertial Sensor's roll to zero * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's roll value to 10 * imu.set_roll(10); * delay(20); * * // Do something with sensor * * // Reset the sensor's roll value to 0 * imu.tare_roll(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare_roll() const; /** * Resets all 5 values of the Inertial Sensor to 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Reset all values of the sensor to 0 * imu.tare(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare() const; /** * Reset all 3 euler values of the Inertial Sensor to 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Reset all euler values of the sensor to 0 * imu.tare_euler(); * delay(20); * } * } * \endcode */ virtual std::int32_t tare_euler() const; /** * Sets the current reading of the Inertial Sensor's heading to target value * Target will default to 360 if above 360 and default to 0 if below 0. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the heading value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's heading value to 10 * imu.set_heading(10); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual std::int32_t set_heading(const double target) const; /** * Sets the current reading of the Inertial Sensor's rotation to target value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the rotation value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's rotation value to 10 * imu.set_rotation(10); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual std::int32_t set_rotation(const double target) const; /** * Sets the current reading of the Inertial Sensor's yaw to target value * Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for yaw value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's yaw value to 10 * imu.set_yaw(10); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual std::int32_t set_yaw(const double target) const; /** * Sets the current reading of the Inertial Sensor's pitch to target value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target value for the pitch value to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's pitch value to 10 * imu.set_pitch(10); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual std::int32_t set_pitch(const double target) const; /** * Sets the current reading of the Inertial Sensor's roll to target value * Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target euler values for the euler values to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's roll value to 100 * imu.set_roll(100); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual std::int32_t set_roll(const double target) const; /** * Sets the current reading of the Inertial Sensor's euler values to * target euler values. Will default to +/- 180 if target exceeds +/- 180. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \param target * Target euler values for the euler values to be set to * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Set the sensor's euler values to 50 * imu.set_euler(50); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual std::int32_t set_euler(const pros::euler_s_t target) const; /** * Get the Inertial Sensor's raw accelerometer values * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The raw accelerometer values. If the operation failed, all the * structure's members are filled with PROS_ERR_F and errno is set. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's raw accelerometer values * pros::imu_accel_s_t accel = imu.get_accel(); * printf("x: %f, y: %f, z: %f\n", accel.x, accel.y, accel.z); * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual pros::imu_accel_s_t get_accel() const; /** * Get the Inertial Sensor's status * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * EAGAIN - The sensor is still calibrating * * \param port * The V5 Inertial Sensor port number from 1-21 * \return The Inertial Sensor's status code, or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Get the sensor's status * pros::ImuStatus status = imu.get_status(); * cout << "Status: " << status << endl; * delay(20); * * // Do something with sensor * } * } * \endcode */ virtual pros::ImuStatus get_status() const; /** * Check whether the IMU is calibrating * * \return true if the V5 Inertial Sensor is calibrating or false * false if it is not. * * \b Example * \code * * #define IMU_PORT 1 * * void opcontrol() { * pros::Imu imu(IMU_PORT); * * while (true) { * // Calibrate the sensor * imu.reset(); * delay(20); * * // Check if the sensor is calibrating * if (imu.is_calibrating()) { * printf("Calibrating...\n"); * } * * // Do something with sensor * } * } * \endcode */ virtual bool is_calibrating() const; /** * Returns the physical orientation of the IMU * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Inertial Sensor * * \param port * The V5 Inertial Sensor port number from 1-21 * \returns The physical orientation of the Inertial Sensor or PROS_ERR if an error occured. * */ virtual imu_orientation_e_t get_physical_orientation() const; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * Imu [port: imu._port, rotation: (rotation), heading: (heading), * pitch: (pitch angle), roll: (roll angle), yaw: (yaw angle), * gyro rate: {x,y,z}, get accel: {x,y,z}, calibrating: (calibrating boolean)] */ friend std::ostream& operator<<(std::ostream& os, const pros::Imu& imu); ///@} }; namespace literals { /** * Constructs a Imu from a literal ending in _imu via calling the constructor * * \return a pros::Imu for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Imu imu = 2_imu; //Makes an IMU object on port 2 * } * \endcode */ const pros::Imu operator""_imu(const unsigned long long int i); } // namespace literals using IMU = Imu; } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/link.h ================================================ /** * \file pros/link.h * \ingroup c-link * * Contains prototypes for functions related to the robot to robot communications. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-link VEX Link C API */ #ifndef _PROS_LINK_H_ #define _PROS_LINK_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \ingroup c-link * */ /** * \addtogroup c-link * @{ */ /** * \enum link_type_e_t * \brief Enum for the type of link (TX or RX) */ typedef enum link_type_e { E_LINK_RECIEVER = 0, ///< Indicates that the radio is a reciever. E_LINK_TRANSMITTER, ///< Indicates that the link is a transmitter. E_LINK_RX = E_LINK_RECIEVER, ///< Alias for E_LINK_RECIEVER E_LINK_TX = E_LINK_TRANSMITTER ///< Alias for E_LINK_TRANSMITTER } link_type_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define LINK_RECEIVER pros::E_LINK_RECEIVER #define LINK_TRANSMITTER pros::E_LINK_TRANSMITTER #define LINK_RX pros::E_LINK_RX #define LINK_TX pros::E_LINK_TX #else #define LINK_RECEIVER E_LINK_RECEIVER #define LINK_TRANSMITTER E_LINK_TRANSMITTER #define LINK_RX E_LINK_RX #define LINK_TX E_LINK_TX #endif #endif /// @brief /// The maximum size of a link buffer #define LINK_BUFFER_SIZE 512 #ifdef __cplusplus namespace c { #endif /** * Initializes a link on a radio port, with an indicated type. There might be a * 1 to 2 second delay from when this function is called to when the link is initializes. * PROS currently only supports the use of one radio per brain. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * \param link_id * Unique link ID in the form of a string, needs to be different from other links in * the area. * \param type * Indicates whether the radio link on the brain is a transmitter or receiver, * with the transmitter having double the transmitting bandwidth as the receiving * end (1040 bytes/s vs 520 bytes/s). * * \return PROS_ERR if initialization fails, 1 if the initialization succeeds. * * \b Example * \code * #define LINK_TRANSMITTER_PORT 1 * #define LINK_ID "ROBOT1" * * void initialize() { * link_init(LINK_TRANSMITTER_PORT, LINK_ID, E_LINK_TRANSMITTER); * } * \endcode */ uint32_t link_init(uint8_t port, const char* link_id, link_type_e_t type); /** * Initializes a link on a radio port, with an indicated type and the ability for * vexlink to override the controller radio. There might be a 1 to 2 second delay * from when this function is called to when the link is initializes. * PROS currently only supports the use of one radio per brain. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * \param link_id * Unique link ID in the form of a string, needs to be different from other links in * the area. * \param type * Indicates whether the radio link on the brain is a transmitter or receiver, * with the transmitter having double the transmitting bandwidth as the receiving * end (1040 bytes/s vs 520 bytes/s). * * \return PROS_ERR if initialization fails, 1 if the initialization succeeds. * * \b Example * \code * #define LINK_PORT 1 * #define LINK_ID "ROBOT1" * * void initialize() { * link_init(LINK_PORT, LINK_ID, E_LINK_TRANSMITTER); * link_init_override(LINK_PORT, LINK_ID, E_LINK_TRANSMITTER); * } * \endcode */ uint32_t link_init_override(uint8_t port, const char* link_id, link_type_e_t type); /** * Checks if a radio link on a port is active or not. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * * \return If a radio is connected to a port and it's connected to a link. * * \b Example * \code * #define LINK_TRANSMITTER_PORT 1 * * void opcontrol() { * while (true) { * if (link_connected(LINK_TRANSMITTER_PORT)) { * screen_print(TEXT_MEDIUM, 1, "Link connected!"); * } * delay(20); * } * } * \endcode */ bool link_connected(uint8_t port); /** * Returns the bytes of data available to be read * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * * \return PROS_ERR if port is not a link/radio, else the bytes available to be * read by the user. * * \b Example * \code * #define LINK_RECIVER_PORT 1 * * void opcontrol() { * while (true) { * uint32_t receiveable_size = link_raw_receivable_size(LINK_RECIVER_PORT); * screen_print(TEXT_MEDIUM, 1, "link_raw_receiveable_size: %d", receiveable_size); * delay(20); * } * } * \endcode */ uint32_t link_raw_receivable_size(uint8_t port); /** * Returns the bytes of data available in transmission buffer. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * * \return PROS_ERR if port is not a link/radio, * * \b Example * \code * #define LINK_TRANSMITTER_PORT 1 * * void opcontrol() { * while (true) { * uint32_t transmittable_size = link_raw_transmittable_size(LINK_TRANSMITTER_PORT); * screen_print(TEXT_MEDIUM, 1, "link_raw_transmittable_size: %d", transmittable_size); * delay(20); * } * } * \endcode */ uint32_t link_raw_transmittable_size(uint8_t port); /** * Send raw serial data through vexlink. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EBUSY - The transmitter buffer is still busy with a previous transmission, and there is no * room in the FIFO buffer (queue) to transmit the data. * EINVAL - The data given is NULL * * \param port * The port of the radio for the intended link. * \param data * Buffer with data to send * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link, and the successfully transmitted * data size if it succeeded. * * \b Example * \code * #define LINK_TRANSMITTER_PORT 1 * * void opcontrol() { * while (true) { * char* data = "Hello!"; * link_transmit_raw(LINK_TRANSMITTER_PORT, (void*)data, sizeof(*data) * sizeof(data)); * delay(20); * } * } * \endcode */ uint32_t link_transmit_raw(uint8_t port, void* data, uint16_t data_size); /** * Receive raw serial data through vexlink. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EINVAL - The destination given is NULL, or the size given is larger than the FIFO buffer * or destination buffer. * * \param port * The port of the radio for the intended link. * \param dest * Destination buffer to read data to * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link, and the successfully received * data size if it succeeded. * * \b Example * \code * #define LINK_RECIVER_PORT 1 * * void opcontrol() { * while (true) { * char* result; * char* expected = "Hello!"; * link_receive_raw(LINK_RECIVER_PORT, (void*)result, sizeof(*expected) * sizeof(expected)); * delay(20); * } * } * \endcode */ uint32_t link_receive_raw(uint8_t port, void* dest, uint16_t data_size); /** * Send packeted message through vexlink, with a checksum and start byte. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EBUSY - The transmitter buffer is still busy with a previous transmission, and there is no * room in the FIFO buffer (queue) to transmit the data. * EINVAL - The data given is NULL * * \param port * The port of the radio for the intended link. * \param data * Buffer with data to send * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link, and the successfully transmitted * data size if it succeeded. * * \b Example * \code * #define LINK_TRANSMITTER_PORT 1 * * void opcontrol() { * while (true) { * char* data = "Hello!"; * link_transmit(LINK_TRANSMITTER_PORT, (void*)data, sizeof(*data) * sizeof(data)); * delay(20); * } * } * \endcode */ uint32_t link_transmit(uint8_t port, void* data, uint16_t data_size); /** * Receive packeted message through vexlink, with a checksum and start byte. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EINVAL - The destination given is NULL, or the size given is larger than the FIFO buffer * or destination buffer. * EBADMSG - Protocol error related to start byte, data size, or checksum. * * \param port * The port of the radio for the intended link. * \param dest * Destination buffer to read data to * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link or protocol error, and the successfully * transmitted data size if it succeeded. * * \b Example * \code * #define LINK_RECIVER_PORT 1 * * void opcontrol() { * while (true) { * char* result; * char* expected = "Hello!"; * link_receive(LINK_RECIVER_PORT, (void*)result, sizeof(*expected) * sizeof(expected)); * delay(20); * } * } * \endcode */ uint32_t link_receive(uint8_t port, void* dest, uint16_t data_size); /** * Clear the receive buffer of the link, and discarding the data. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * * \return PROS_ERR if port is not a link, and the successfully received * data size if it succeeded. * * \b Example * \code * #define LINK_TRANSMITTER_PORT 1 * * void opcontrol() { * while (true) { * char* data = "Hello!"; * link_transmit(LINK_TRANSMITTER_PORT, (void*)data, sizeof(*data) * sizeof(data)); * link_clear_receive_buf(LINK_TRANSMITTER_PORT); * delay(20); * } * } * \endcode */ uint32_t link_clear_receive_buf(uint8_t port); ///@} #ifdef __cplusplus } } } #endif #endif ================================================ FILE: include/pros/link.hpp ================================================ /** * \file pros/link.hpp * \ingroup cpp-link * * Contains prototypes for functions related to robot to robot communications. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-link VEX Link C++ API */ #ifndef _PROS_LINK_HPP_ #define _PROS_LINK_HPP_ #include #include #include "pros/link.h" #include "pros/device.hpp" namespace pros { /** * \ingroup cpp-link */ class Link : public Device { /** * \addtogroup cpp-link * ///@{ */ private: public: /** * Initializes a link on a radio port, with an indicated type. There might be a * 1 to 2 second delay from when this function is called to when the link is initializes. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \param port * The port of the radio for the intended link. * \param link_id * Unique link ID in the form of a string, needs to be different from other links in * the area. * \param type * Indicates whether the radio link on the brain is a transmitter or receiver, * with the transmitter having double the transmitting bandwidth as the receiving * end (1040 bytes/s vs 520 bytes/s). * \param ov * Indicates if the radio on the given port needs vexlink to override the controller radio. Defualts to True. * * \return PROS_ERR if initialization fails, 1 if the initialization succeeds. * * \b Example: * \code * pros::Link link(1, "my_link", pros::E_LINK_TX); * \endcode */ explicit Link(const std::uint8_t port, const std::string link_id, link_type_e_t type, bool ov = true); /** * Checks if a radio link on a port is active or not. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \return If a radio is connected to a port and it's connected to a link. * * \b Example: * \code * pros::Link link(1, "my_link", pros::E_LINK_TX); * if (link.connected()) { * // do something * } * \endcode */ bool connected(); /** * Returns the bytes of data number of without protocol available to be read * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \return PROS_ERR if port is not a link/radio, else the bytes available to be * read by the user. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * printf("Bytes available to read: %d", link.receivable_size()); * } * \endcode */ std::uint32_t raw_receivable_size(); /** * Returns the bytes of data available in transmission buffer. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \return PROS_ERR if port is not a link/radio, * else the bytes available to be transmitted by the user. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * printf("Bytes available to transmit: %d", link.transmittable_size()); * } */ std::uint32_t raw_transmittable_size(); /** * Send raw serial data through vexlink. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EBUSY - The transmitter buffer is still busy with a previous transmission, and there is no * room in the FIFO buffer (queue) to transmit the data. * EINVAL - The data given is NULL * * \param data * Buffer with data to send * \param data_size * Buffer with data to send * * \return PROS_ERR if port is not a link, and the successfully transmitted * data size if it succeeded. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * std::uint8_t data[4] = {0x01, 0x02, 0x03, 0x04}; * link.transmit_raw(data, 4); * } * * \endcode */ std::uint32_t transmit_raw(void* data, std::uint16_t data_size); /** * Receive raw serial data through vexlink. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EINVAL - The destination given is NULL, or the size given is larger than the FIFO buffer * or destination buffer. * * \param dest * Destination buffer to read data to * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link, and the successfully received * data size if it succeeded. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * std::uint8_t data[4]; * link.receive_raw(data, 4); * } * \endcode */ std::uint32_t receive_raw(void* dest, std::uint16_t data_size); /** * Send packeted message through vexlink, with a checksum and start byte. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EBUSY - The transmitter buffer is still busy with a previous transmission, and there is no * room in the FIFO buffer (queue) to transmit the data. * EINVAL - The data given is NULL * * \param data * Buffer with data to send * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link, and the successfully transmitted * data size if it succeeded. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * std::uint8_t data[4] = {0x01, 0x02, 0x03, 0x04}; * link.transmit(data, 4); * } * \endcode */ std::uint32_t transmit(void* data, std::uint16_t data_size); /** * Receive packeted message through vexlink, with a checksum and start byte. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * EINVAL - The destination given is NULL, or the size given is larger than the FIFO buffer * or destination buffer. * EBADMSG - Protocol error related to start byte, data size, or checksum. * \param dest * Destination buffer to read data to * \param data_size * Bytes of data to be read to the destination buffer * * \return PROS_ERR if port is not a link, and the successfully received * data size if it succeeded. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * std::uint8_t data[4]; * link.receive(data, 4); * } * \endcode */ std::uint32_t receive(void* dest, std::uint16_t data_size); /** * Clear the receive buffer of the link, and discarding the data. * * \note This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a radio. * ENXIO - The sensor is still calibrating, or no link is connected via the radio. * * \return PROS_ERR if port is not a link, 1 if the operation succeeded. * * \b Example: * \code * void opcontrol() { * pros::Link link(1, "my_link", pros::E_LINK_TX); * link.clear_receive_buf(); * } * \endcode */ std::uint32_t clear_receive_buf(); ///@} }; } // namespace pros #endif ================================================ FILE: include/pros/llemu.h ================================================ #ifndef _PROS_LLEMU_H_ #define _PROS_LLEMU_H_ // TODO:? Should there be weak symbols for the C api in here as well? #include "stdbool.h" #include "stdint.h" /******************************************************************************/ /** LLEMU Conditional Include **/ /** **/ /** When the libvgl versions of llemu.h is present, common.mk will **/ /** define a macro which lets this file know that liblvgl's llemu.h is **/ /** present. If it is, we conditionally include it so that it gets **/ /** included into api.h. **/ /******************************************************************************/ #ifdef _PROS_INCLUDE_LIBLVGL_LLEMU_H #include "liblvgl/llemu.h" #endif #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif//__cplusplus /** * Displays a formatted string on the emulated three-button LCD screen. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The LCD has not been initialized. Call lcd_initialize() first. * EINVAL - The line number specified is not in the range [0-7] * * \param line * The line on which to display the text [0-7] * \param fmt * Format string * \param ... * Optional list of arguments for the format string * * \return True if the operation was successful, or false otherwise, setting * errno values as specified above. */ bool __attribute__((weak)) lcd_print(__attribute__((unused)) int16_t line, __attribute__((unused)) const char* fmt, ...) { return false; } #ifdef __cplusplus } // namespace c } // namespace pros } // extern "C" #endif//__cplusplus #endif // _PROS_LLEMU_H_ ================================================ FILE: include/pros/llemu.hpp ================================================ /** * \file pros/llemu.hpp * \ingroup cpp-llemu * * Legacy LCD Emulator * * \details This file defines a high-level API for emulating the three-button, UART-based * VEX LCD, containing a set of functions that facilitate the use of a software- * emulated version of the classic VEX LCD module. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _PROS_LLEMU_HPP_ #define _PROS_LLEMU_HPP_ #include #include /******************************************************************************/ /** LLEMU Conditional Include **/ /** **/ /** When the libvgl versions of llemu.hpp is present, common.mk will **/ /** define a macro which lets this file know that liblvgl's llemu.hpp is **/ /** present. If it is, we conditionally include it so that it gets **/ /** included into api.h. **/ /******************************************************************************/ #ifdef _PROS_INCLUDE_LIBLVGL_LLEMU_HPP #include "liblvgl/llemu.hpp" #endif /******************************************************************************/ /** LLEMU Weak Stubs **/ /** **/ /** These functions allow main.cpp to be compiled without LVGL present **/ /******************************************************************************/ namespace pros { /** * \ingroup cpp-llemu */ #if defined(_PROS_KERNEL_SUPPRESS_LLEMU_WARNING) || defined(_PROS_INCLUDE_LIBLVGL_LLEMU_HPP) namespace lcd { #else namespace [[deprecated("Without liblvgl, LLEMU functions will not display anything. To install liblvgl run \"pros c install liblvgl\" in the PROS terminal.")]] lcd { #endif #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" namespace { template T convert_args(T arg) { return arg; } const char* convert_args(const std::string& arg) { return arg.c_str(); } } // namespace #pragma GCC diagnostic pop using lcd_btn_cb_fn_t = void (*)(void); /* * These weak symbols allow the example main.cpp in to compile even when * the liblvgl template is missing from the project. * * For documentation on these functions, please see the doxygen comments for * these functions in the libvgl llemu headers. */ extern __attribute__((weak)) bool is_initialized(void); extern __attribute__((weak)) bool initialize(void); extern __attribute__((weak)) bool shutdown(void); extern __attribute__((weak)) bool set_text(std::int16_t line, std::string text); extern __attribute__((weak)) bool clear(void); extern __attribute__((weak)) bool clear_line(std::int16_t line); // TODO: Text_Align is defined in liblvgl so this ain't going to compile for now. // extern __attribute__((weak)) void set_text_align(Text_Align text_align); extern __attribute__((weak)) void register_btn0_cb(lcd_btn_cb_fn_t cb); extern __attribute__((weak)) void register_btn1_cb(lcd_btn_cb_fn_t cb); extern __attribute__((weak)) void register_btn2_cb(lcd_btn_cb_fn_t cb); extern __attribute__((weak)) std::uint8_t read_buttons(void); /** * \addtogroup cpp-llemu * @{ */ /* * Note: This template resides in this file since the */ /** * Displays a formatted string on the emulated three-button LCD screen. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The LCD has not been initialized. Call lcd_initialize() first. * EINVAL - The line number specified is not in the range [0-7] * * \param line * The line on which to display the text [0-7] * \param fmt * Format string * \param ...args * Optional list of arguments for the format string * * \return True if the operation was successful, or false otherwise, setting * errno values as specified above. * * \b Example * \code * #include "pros/llemu.hpp" * * void initialize() { * pros::lcd::initialize(); * pros::lcd::print(0, "My formatted text: %d!", 2); * } * \endcode */ template bool print(std::int16_t line, const char* fmt, Params... args) { return pros::c::lcd_print(line, fmt, convert_args(args)...); } #ifndef LCD_BTN_LEFT #define LCD_BTN_LEFT 4 #endif #ifndef LCD_BTN_CENTER #define LCD_BTN_CENTER 2 #endif #ifndef LCD_BTN_RIGHT #define LCD_BTN_RIGHT 1 #endif /// @} } // namespace lcd } // namespace pros #endif // _PROS_LLEMU_HPP_ ================================================ FILE: include/pros/misc.h ================================================ /** * \file pros/misc.h * \ingroup c-misc * * Contains prototypes for miscellaneous functions pertaining to the controller, * battery, and competition control. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reservered. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-misc Miscellaneous C API * \note Additional example code for this module can be found in its [Tutorial.](@ref controller) */ #ifndef _PROS_MISC_H_ #define _PROS_MISC_H_ #include #define NUM_V5_PORTS (22) /** * \ingroup c-misc */ /** * \addtogroup c-misc * @{ */ /// \name V5 Competition //@{ /*#define COMPETITION_DISABLED (1 << 0) #define COMPETITION_AUTONOMOUS (1 << 1) #define COMPETITION_CONNECTED (1 << 2) #define COMPETITION_SYSTEM (1 << 3)*/ typedef enum { COMPETITION_DISABLED = 1 << 0, COMPETITION_CONNECTED = 1 << 2, COMPETITION_AUTONOMOUS = 1 << 1, COMPETITION_SYSTEM = 1 << 3, } competition_status; #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif /** * \fn competition_get_status(void) * Get the current status of the competition control. * * \return The competition control status as a mask of bits with * COMPETITION_{ENABLED,AUTONOMOUS,CONNECTED}. * * \b Example * \code * void initialize() { * if (competition_get_status() & COMPETITION_CONNECTED == true) { * // Field Control is Connected * // Run LCD Selector code or similar * } * } * \endcode */ uint8_t competition_get_status(void); /** * \fn competition_is_disabled() * * \return True if the V5 Brain is disabled, false otherwise. * * \b Example * \code * void my_task_fn(void* ignore) { * while (!competition_is_disabled()) { * // Run competition tasks (like Lift Control or similar) * } * } * * void initialize() { * task_t my_task = task_create(my_task_fn, NULL, TASK_PRIO_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "My Task"); * } * \endcode */ uint8_t competition_is_disabled(void); /** * \return True if the V5 Brain is connected to competition control, false otherwise. * * \b Example * \code * void initialize() { * if (competition_is_connected()) { * // Field Control is Connected * // Run LCD Selector code or similar * } * } * \endcode */ uint8_t competition_is_connected(void); /** * \return True if the V5 Brain is in autonomous mode, false otherwise. * * \b Example * \code * void my_task_fn(void* ignore) { * while (!competition_is_autonomous()) { * // Wait to do anything until autonomous starts * delay(2); * } * while (competition_is_autonomous()) { * // Run whatever code is desired to just execute in autonomous * } * } * * void initialize() { * task_t my_task = task_create(my_task_fn, NULL, TASK_PRIO_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "My Task"); * } * \endcode */ uint8_t competition_is_autonomous(void); /** * \return True if the V5 Brain is connected to VEXnet Field Controller, false otherwise. * * \b Example * \code * void initialize() { * if (competition_is_field()) { * // connected to VEXnet Field Controller * } * } * \endcode */ uint8_t competition_is_field(void); /** * \return True if the V5 Brain is connected to VEXnet Competition Switch, false otherwise. * * \b Example * \code * void initialize() { * if (competition_is_switch()) { * // connected to VEXnet Competition Switch * } * } */ uint8_t competition_is_switch(void); #ifdef __cplusplus } } } #endif ///@} /// \name V5 Controller ///@{ #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \enum */ typedef enum { /// The master controller. E_CONTROLLER_MASTER = 0, /// The partner controller. E_CONTROLLER_PARTNER } controller_id_e_t; /** * \enum */ typedef enum { /// The horizontal axis of the controller’s left analog stick. E_CONTROLLER_ANALOG_LEFT_X = 0, /// The vertical axis of the controller’s left analog stick. E_CONTROLLER_ANALOG_LEFT_Y, /// The horizontal axis of the controller’s right analog stick. E_CONTROLLER_ANALOG_RIGHT_X, /// The vertical axis of the controller’s right analog stick. E_CONTROLLER_ANALOG_RIGHT_Y } controller_analog_e_t; /** * \enum */ typedef enum { /// The first trigger on the left side of the controller. E_CONTROLLER_DIGITAL_L1 = 6, /// The second trigger on the left side of the controller. E_CONTROLLER_DIGITAL_L2, /// The first trigger on the right side of the controller. E_CONTROLLER_DIGITAL_R1, /// The second trigger on the right side of the controller. E_CONTROLLER_DIGITAL_R2, /// The up arrow on the left arrow pad of the controller. E_CONTROLLER_DIGITAL_UP, /// The down arrow on the left arrow pad of the controller. E_CONTROLLER_DIGITAL_DOWN, /// The left arrow on the left arrow pad of the controller. E_CONTROLLER_DIGITAL_LEFT, /// The right arrow on the left arrow pad of the controller. E_CONTROLLER_DIGITAL_RIGHT, /// The ‘X’ button on the right button pad of the controller. E_CONTROLLER_DIGITAL_X, /// The ‘B’ button on the right button pad of the controller. E_CONTROLLER_DIGITAL_B, /// The ‘Y’ button on the right button pad of the controller. E_CONTROLLER_DIGITAL_Y, /// The ‘A’ button on the right button pad of the controller. E_CONTROLLER_DIGITAL_A, /// The power button on the front of the controller. E_CONTROLLER_DIGITAL_POWER } controller_digital_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define CONTROLLER_MASTER pros::E_CONTROLLER_MASTER #define CONTROLLER_PARTNER pros::E_CONTROLLER_PARTNER #define ANALOG_LEFT_X pros::E_CONTROLLER_ANALOG_LEFT_X #define ANALOG_LEFT_Y pros::E_CONTROLLER_ANALOG_LEFT_Y #define ANALOG_RIGHT_X pros::E_CONTROLLER_ANALOG_RIGHT_X #define ANALOG_RIGHT_Y pros::E_CONTROLLER_ANALOG_RIGHT_Y #define DIGITAL_L1 pros::E_CONTROLLER_DIGITAL_L1 #define DIGITAL_L2 pros::E_CONTROLLER_DIGITAL_L2 #define DIGITAL_R1 pros::E_CONTROLLER_DIGITAL_R1 #define DIGITAL_R2 pros::E_CONTROLLER_DIGITAL_R2 #define DIGITAL_UP pros::E_CONTROLLER_DIGITAL_UP #define DIGITAL_DOWN pros::E_CONTROLLER_DIGITAL_DOWN #define DIGITAL_LEFT pros::E_CONTROLLER_DIGITAL_LEFT #define DIGITAL_RIGHT pros::E_CONTROLLER_DIGITAL_RIGHT #define DIGITAL_X pros::E_CONTROLLER_DIGITAL_X #define DIGITAL_B pros::E_CONTROLLER_DIGITAL_B #define DIGITAL_Y pros::E_CONTROLLER_DIGITAL_Y #define DIGITAL_A pros::E_CONTROLLER_DIGITAL_A #define DIGITAL_POWER pros::E_CONTROLLER_DIGITAL_POWER #else #define CONTROLLER_MASTER E_CONTROLLER_MASTER #define CONTROLLER_PARTNER E_CONTROLLER_PARTNER #define ANALOG_LEFT_X E_CONTROLLER_ANALOG_LEFT_X #define ANALOG_LEFT_Y E_CONTROLLER_ANALOG_LEFT_Y #define ANALOG_RIGHT_X E_CONTROLLER_ANALOG_RIGHT_X #define ANALOG_RIGHT_Y E_CONTROLLER_ANALOG_RIGHT_Y #define DIGITAL_L1 E_CONTROLLER_DIGITAL_L1 #define DIGITAL_L2 E_CONTROLLER_DIGITAL_L2 #define DIGITAL_R1 E_CONTROLLER_DIGITAL_R1 #define DIGITAL_R2 E_CONTROLLER_DIGITAL_R2 #define DIGITAL_UP E_CONTROLLER_DIGITAL_UP #define DIGITAL_DOWN E_CONTROLLER_DIGITAL_DOWN #define DIGITAL_LEFT E_CONTROLLER_DIGITAL_LEFT #define DIGITAL_RIGHT E_CONTROLLER_DIGITAL_RIGHT #define DIGITAL_X E_CONTROLLER_DIGITAL_X #define DIGITAL_B E_CONTROLLER_DIGITAL_B #define DIGITAL_Y E_CONTROLLER_DIGITAL_Y #define DIGITAL_A E_CONTROLLER_DIGITAL_A #endif #endif /** * \def Given an id and a port, this macro sets the port variable based on the id and allows the mutex to take that * port. * * \returns error (in the function/scope it's in) if the controller failed to connect or an invalid id is given. */ #define CONTROLLER_PORT_MUTEX_TAKE(id, port) \ switch (id) { \ case E_CONTROLLER_MASTER: \ port = V5_PORT_CONTROLLER_1; \ break; \ case E_CONTROLLER_PARTNER: \ port = V5_PORT_CONTROLLER_2; \ break; \ default: \ errno = EINVAL; \ return PROS_ERR; \ } \ if (!internal_port_mutex_take(port)) { \ errno = EACCES; \ return PROS_ERR; \ } #ifdef __cplusplus namespace c { #endif /** * Checks if the controller is connected. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * * \return 1 if the controller is connected, 0 otherwise * * \b Example * \code * void initialize() { * if (competition_is_connected()) { * // Field Control is Connected * // Run LCD Selector code or similar * } * } * \endcode */ int32_t controller_is_connected(controller_id_e_t id); /** * Gets the value of an analog channel (joystick) on a controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param channel * The analog channel to get. * Must be one of ANALOG_LEFT_X, ANALOG_LEFT_Y, ANALOG_RIGHT_X, * ANALOG_RIGHT_Y * * \return The current reading of the analog channel: [-127, 127]. * If the controller was not connected, then 0 is returned * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * delay(2); * } * } * \endcode */ int32_t controller_get_analog(controller_id_e_t id, controller_analog_e_t channel); /** * Gets the battery capacity of the given controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER * * \return The controller's battery capacity * * \b Example * \code * void initialize() { * printf("Battery Capacity: %d\n", controller_get_battery_capacity(E_CONTROLLER_MASTER)); * } * \endcode */ int32_t controller_get_battery_capacity(controller_id_e_t id); /** * Gets the battery level of the given controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER * * \return The controller's battery level * * \b Example * \code * void initialize() { * printf("Battery Level: %d\n", controller_get_battery_level(E_CONTROLLER_MASTER)); * } * \endcode */ int32_t controller_get_battery_level(controller_id_e_t id); /** * Checks if a digital channel (button) on the controller is currently pressed. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param button * The button to read. * Must be one of DIGITAL_{RIGHT,DOWN,LEFT,UP,A,B,Y,X,R1,R2,L1,L2} * * \return 1 if the button on the controller is pressed. * If the controller was not connected, then 0 is returned * * \b Example * \code * void opcontrol() { * while (true) { * if (controller_get_digital(E_CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_A)) { * motor_set(1, 100); * } * else { * motor_set(1, 0); * } * delay(2); * } * } * \endcode */ int32_t controller_get_digital(controller_id_e_t id, controller_digital_e_t button); /** * Returns a rising-edge case for a controller button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under the * same circumstances, so only one task should call this function for any given * button. E.g., Task A calls this function for buttons 1 and 2. Task B may call * this function for button 3, but should not for buttons 1 or 2. A typical * use-case for this function is to call inside opcontrol to detect new button * presses, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param button * The button to read. Must be one of * DIGITAL_{RIGHT,DOWN,LEFT,UP,A,B,Y,X,R1,R2,L1,L2} * * \return 1 if the button on the controller is pressed and had not been pressed * the last time this function was called, 0 otherwise. * * \b Example * \code * void opcontrol() { * while (true) { * if (controller_get_digital_new_press(E_CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_A)) { * // Toggle pneumatics or other similar actions * } * * delay(2); * } * } * \endcode */ int32_t controller_get_digital_new_press(controller_id_e_t id, controller_digital_e_t button); /** * Returns a falling-edge case for a controller button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under * the same circumstances, so only one task should call this function for any * given button. E.g., Task A calls this function for buttons 1 and 2. * Task B may call this function for button 3, but should not for buttons * 1 or 2. A typical use-case for this function is to call inside opcontrol * to detect new button releases, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param button * The button to read. Must be one of * DIGITAL_{RIGHT,DOWN,LEFT,UP,A,B,Y,X,R1,R2,L1,L2} * * \return 1 if the button on the controller is not pressed and had been * pressed the last time this function was called, 0 otherwise. * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (master.get_digital_new_release(pros::E_CONTROLLER_DIGITAL_A)) { * // Toggle pneumatics or other similar actions * } * * delay(2); * } * } * \endcode */ int32_t controller_get_digital_new_release(controller_id_e_t id, controller_digital_e_t button); /** * Sets text to the controller LCD screen. * * \note Controller text setting is a slow process, so updates faster than 10ms * when on a wired connection or 50ms over Vexnet will not be applied to the controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * EAGAIN - Could not send the text to the controller. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param line * The line number at which the text will be displayed [0-2] * \param col * The column number at which the text will be displayed [0-14] * \param fmt * The format string to print to the controller * \param ... * The argument list for the format string * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * int count = 0; * while (true) { * if (!(count % 25)) { * // Only print every 50ms, the controller text update rate is slow * controller_print(E_CONTROLLER_MASTER, 0, 0, "Counter: %d", count); * } * count++; * delay(2); * } * } * \endcode */ int32_t controller_print(controller_id_e_t id, uint8_t line, uint8_t col, const char* fmt, ...); /** * Sets text to the controller LCD screen. * * \note Controller text setting is a slow process, so updates faster than 10ms * when on a wired connection or 50ms over Vexnet will not be applied to the controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * EAGAIN - Could not send the text to the controller. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param line * The line number at which the text will be displayed [0-2] * \param col * The column number at which the text will be displayed [0-14] * \param str * The pre-formatted string to print to the controller * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * int count = 0; * while (true) { * if (!(count % 25)) { * // Only print every 50ms, the controller text update rate is slow * controller_set_text(E_CONTROLLER_MASTER, 0, 0, "Example text"); * } * count++; * delay(2); * } * } * \endcode */ int32_t controller_set_text(controller_id_e_t id, uint8_t line, uint8_t col, const char* str); /** * Clears an individual line of the controller screen. * * \note Controller text setting is currently in beta, so continuous, fast * updates will not work well. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param line * The line number to clear [0-2] * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * controller_set_text(E_CONTROLLER_MASTER, 0, 0, "Example"); * delay(100); * controller_clear_line(E_CONTROLLER_MASTER, 0); * } * \endcode */ int32_t controller_clear_line(controller_id_e_t id, uint8_t line); /** * Clears all of the lines on the controller screen. * * \note Controller text setting is a slow process, so updates faster than 10ms * when on a wired connection or 50ms over Vexnet will not be applied to the controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * EAGAIN - Could not send the text to the controller. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * controller_set_text(E_CONTROLLER_MASTER, 0, 0, "Example"); * delay(100); * controller_clear(E_CONTROLLER_MASTER); * } * \endcode */ int32_t controller_clear(controller_id_e_t id); /** * Rumble the controller. * * \note Controller rumble activation is a slow process, so updates faster than 10ms * when on a wired connection or 50ms over Vexnet will not be applied to the controller. * * This function uses the following values of errno when an error state is * reached: * EINVAL - A value other than E_CONTROLLER_MASTER or E_CONTROLLER_PARTNER is * given. * EACCES - Another resource is currently trying to access the controller port. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER * \param rumble_pattern * A string consisting of the characters '.', '-', and ' ', where dots * are short rumbles, dashes are long rumbles, and spaces are pauses. * Maximum supported length is 8 characters. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * int count = 0; * while (true) { * if (!(count % 25)) { * // Only send every 50ms, the controller update rate is slow * controller_rumble(E_CONTROLLER_MASTER, ". - . -"); * } * count++; * delay(2); * } * } * \endcode */ int32_t controller_rumble(controller_id_e_t id, const char* rumble_pattern); /** * Gets the current voltage of the battery, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current voltage of the battery * * \b Example * \code * void initialize() { * printf("Battery's Voltage: %d\n", battery_get_voltage()); * } * \endcode */ int32_t battery_get_voltage(void); /** * Gets the current current of the battery, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current current of the battery * * \b Example * \code * void initialize() { * printf("Battery Current: %d\n", battery_get_current()); * } * \endcode */ int32_t battery_get_current(void); /** * Gets the current temperature of the battery, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current temperature of the battery * * \b Example * \code * void initialize() { * printf("Battery's Temperature: %d\n", battery_get_temperature()); * } * \endcode */ double battery_get_temperature(void); /** * Gets the current capacity of the battery, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current capacity of the battery * * \b Example * \code * void initialize() { * printf("Battery Level: %d\n", battery_get_capacity()); * } * \endcode */ double battery_get_capacity(void); /** * Checks if the SD card is installed. * * \return 1 if the SD card is installed, 0 otherwise * * \b Example * \code * void opcontrol() { * printf("%i", usd_is_installed()); * } * \endcode */ int32_t usd_is_installed(void); /** * Lists the files in a directory specified by the path * Puts the list of file names (NOT DIRECTORIES) into the buffer seperated by newlines * * This function uses the following values of errno when an error state is * reached: * * EIO - Hard error occured in the low level disk I/O layer * EINVAL - file or directory is invalid, or length is invalid * EBUSY - THe physical drinve cannot work * ENOENT - cannot find the path or file * EINVAL - the path name format is invalid * EACCES - Access denied or directory full * EEXIST - Access denied * EROFS - SD card is write protected * ENXIO - drive number is invalid or not a FAT32 drive * ENOBUFS - drive has no work area * ENFILE - too many open files * * * * \note use a path of "\" to list the files in the main directory NOT "/usd/" * DO NOT PREPEND YOUR PATHS WITH "/usd/" * * \return 1 on success or PROS_ERR on failure setting errno * * \b Example * \code * void opcontrol() { * char* test = (char*) malloc(128); * pros::c::usd_list_files("/", test, 128); * pros::delay(200); * printf("%s\n", test); //Prints the file names in the root directory seperated by newlines * pros::delay(100); * pros::c::usd_list_files("/test", test, 128); * pros::delay(200); * printf("%s\n", test); //Prints the names of files in the folder named test seperated by newlines * pros::delay(100); * } * \endcode */ int32_t usd_list_files(const char* path, char* buffer, int32_t len); /******************************************************************************/ /** Date and Time **/ /******************************************************************************/ extern const char* baked_date; extern const char* baked_time; typedef struct { uint16_t year; // Year - 1980 uint8_t day; uint8_t month; // 1 = January } date_s_t; typedef struct { uint8_t hour; uint8_t min; uint8_t sec; uint8_t sec_hund; // hundredths of a second } time_s_t; ///@} ///@} #ifdef __cplusplus } } // namespace pros } #endif #endif // _PROS_MISC_H_ ================================================ FILE: include/pros/misc.hpp ================================================ /** * \file pros/misc.hpp * \ingroup cpp-pros * * Contains prototypes for miscellaneous functions pertaining to the controller, * battery, and competition control. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reservered. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-misc Miscellaneous C++ API * \note Additional example code for this module can be found in its [Tutorial.](@ref controller) */ #ifndef _PROS_MISC_HPP_ #define _PROS_MISC_HPP_ #include #include #include "pros/misc.h" namespace pros { inline namespace v5 { /** * \ingroup cpp-misc */ class Controller { /** * \addtogroup cpp-misc * ///@{ */ public: /** * Creates a controller object for the given controller id. * * \param id * The ID of the controller (e.g. the master or partner controller). * Must be one of CONTROLLER_MASTER or CONTROLLER_PARTNER */ explicit Controller(controller_id_e_t id); /** * Checks if the controller is connected. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \return 1 if the controller is connected, 0 otherwise * * \b Example * \code * void status_display_controller(){ * pros::Controller master(pros::E_CONTROLLER_MASTER); * if(!master.is_connected()) { * pros::lcd::print(0, "Main controller is not connected!"); * } * } * \endcode */ std::int32_t is_connected(void); /** * Gets the value of an analog channel (joystick) on a controller. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param channel * The analog channel to get. * Must be one of ANALOG_LEFT_X, ANALOG_LEFT_Y, ANALOG_RIGHT_X, * ANALOG_RIGHT_Y * * \return The current reading of the analog channel: [-127, 127]. * If the controller was not connected, then 0 is returned * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * motor_move(1, master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * delay(2); * } * } * \endcode */ std::int32_t get_analog(controller_analog_e_t channel); /** * Gets the battery capacity of the controller. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \return The controller's battery capacity * * \b Example * \code * void initialize() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * printf("Battery Capacity: %d\n", master.get_battery_capacity()); * } * \endcode */ std::int32_t get_battery_capacity(void); /** * Gets the battery level of the controller. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \return The controller's battery level * * \b Example * \code * void initialize() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * printf("Battery Level: %d\n", master.get_battery_level()); * } * \endcode */ std::int32_t get_battery_level(void); /** * Checks if a digital channel (button) on the controller is currently * pressed. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param button * The button to read. Must be one of * DIGITAL_{RIGHT,DOWN,LEFT,UP,A,B,Y,X,R1,R2,L1,L2} * * \return 1 if the button on the controller is pressed. * If the controller was not connected, then 0 is returned * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (master.get_digital(pros::E_CONTROLLER_DIGITAL_A)) { * motor_set(1, 100); * } * else { * motor_set(1, 0); * } * delay(2); * } * } * \endcode */ std::int32_t get_digital(controller_digital_e_t button); /** * Returns a rising-edge case for a controller button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under * the same circumstances, so only one task should call this function for any * given button. E.g., Task A calls this function for buttons 1 and 2. * Task B may call this function for button 3, but should not for buttons * 1 or 2. A typical use-case for this function is to call inside opcontrol * to detect new button presses, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param button * The button to read. Must be one of * DIGITAL_{RIGHT,DOWN,LEFT,UP,A,B,Y,X,R1,R2,L1,L2} * * \return 1 if the button on the controller is pressed and had not been * pressed the last time this function was called, 0 otherwise. * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (master.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_A)) { * // Toggle pneumatics or other similar actions * } * * delay(2); * } * } * \endcode */ std::int32_t get_digital_new_press(controller_digital_e_t button); /** * Returns a falling-edge case for a controller button press. * * This function is not thread-safe. * Multiple tasks polling a single button may return different results under * the same circumstances, so only one task should call this function for any * given button. E.g., Task A calls this function for buttons 1 and 2. * Task B may call this function for button 3, but should not for buttons * 1 or 2. A typical use-case for this function is to call inside opcontrol * to detect new button releases, and not in any other tasks. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param button * The button to read. Must be one of * DIGITAL_{RIGHT,DOWN,LEFT,UP,A,B,Y,X,R1,R2,L1,L2} * * \return 1 if the button on the controller is not pressed and had been * pressed the last time this function was called, 0 otherwise. * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (master.get_digital_new_release(pros::E_CONTROLLER_DIGITAL_A)) { * // Toggle pneumatics or other similar actions * } * * delay(2); * } * } * \endcode */ std::int32_t get_digital_new_release(controller_digital_e_t button); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" template T convert_args(T arg) { return arg; } const char* convert_args(const std::string& arg) { return arg.c_str(); } #pragma GCC diagnostic pop /** * Sets text to the controller LCD screen. * * \note Controller text setting is currently in beta, so continuous, fast * updates will not work well. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param line * The line number at which the text will be displayed [0-2] * \param col * The column number at which the text will be displayed [0-14] * \param fmt * The format string to print to the controller * \param ... * The argument list for the format string * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * int count = 0; * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (!(count % 25)) { * // Only print every 50ms, the controller text update rate is slow * master.print(0, 0, "Counter: %d", count); * } * count++; * delay(2); * } * } * \endcode */ template std::int32_t print(std::uint8_t line, std::uint8_t col, const char* fmt, Params... args) { return pros::c::controller_print(_id, line, col, fmt, convert_args(args)...); } /** * Sets text to the controller LCD screen. * * \note Controller text setting is currently in beta, so continuous, fast * updates will not work well. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param line * The line number at which the text will be displayed [0-2] * \param col * The column number at which the text will be displayed [0-14] * \param str * The pre-formatted string to print to the controller * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * int count = 0; * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (!(count % 25)) { * // Only print every 50ms, the controller text update rate is slow * master.set_text(0, 0, "Example text"); * } * count++; * delay(2); * } * } * \endcode */ std::int32_t set_text(std::uint8_t line, std::uint8_t col, const char* str); std::int32_t set_text(std::uint8_t line, std::uint8_t col, const std::string& str); /** * Clears an individual line of the controller screen. * * \note Controller text setting is currently in beta, so continuous, fast * updates will not work well. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param line * The line number to clear [0-2] * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * master.set_text(0, 0, "Example"); * delay(100); * master.clear_line(0); * } * \endcode */ std::int32_t clear_line(std::uint8_t line); /** * Rumble the controller. * * \note Controller rumble activation is currently in beta, so continuous, fast * updates will not work well. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \param rumble_pattern * A string consisting of the characters '.', '-', and ' ', where dots * are short rumbles, dashes are long rumbles, and spaces are pauses. * Maximum supported length is 8 characters. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * int count = 0; * pros::Controller master(pros::E_CONTROLLER_MASTER); * while (true) { * if (!(count % 25)) { * // Only send every 50ms, the controller update rate is slow * master.rumble(". - . -"); * } * count++; * delay(2); * } * } * \endcode */ std::int32_t rumble(const char* rumble_pattern); /** * Clears all of the lines on the controller screen. * * \note Controller text setting is currently in beta, so continuous, fast * updates will not work well. On vexOS version 1.0.0 this function will * block for 110ms. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the controller * port. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Controller master(pros::E_CONTROLLER_MASTER); * master.set_text(0, 0, "Example"); * delay(100); * master.clear(); * } * \endcode */ std::int32_t clear(void); private: controller_id_e_t _id; ///@} }; } // namespace v5 namespace battery { /** * \addtogroup cpp-misc * ///@{ */ /** * Gets the current voltage of the battery, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current voltage of the battery * * \b Example * \code * void initialize() { * printf("Battery Level: %.2f\n", get_capacity()); * } * \endcode */ double get_capacity(void); /** * Gets the current current of the battery in milliamps, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current current of the battery * * \b Example * \code * void initialize() { * printf("Battery Current: %d\n", get_current()); * } * \endcode */ int32_t get_current(void); /** * Gets the current temperature of the battery, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current temperature of the battery * * \b Example * \code * void initialize() { * printf("Battery's Temperature: %.2f\n", get_temperature()); * } * \endcode */ double get_temperature(void); /** * Gets the current capacity of the battery in millivolts, as reported by VEXos. * * This function uses the following values of errno when an error state is * reached: * EACCES - Another resource is currently trying to access the battery port. * * \return The current capacity of the battery * * \b Example * \code * void initialize() { * printf("Battery's Voltage: %d\n", get_voltage()); * } * \endcode */ int32_t get_voltage(void); ///@} } // namespace battery namespace competition { /** * Get the current status of the competition control. * * \return The competition control status as a mask of bits with * COMPETITION_{ENABLED,AUTONOMOUS,CONNECTED}. * * \b Example * \code * void status_display_task(){ * if(!is_connected()) { * pros::lcd::print(0, "V5 Brain is not connected!"); * } * if(is_autonomous()) { * pros::lcd::print(0, "V5 Brain is in autonomous mode!"); * } * if(!is_disabled()) { * pros::lcd::print(0, "V5 Brain is disabled!"); * } * \endcode */ std::uint8_t get_status(void); std::uint8_t is_autonomous(void); std::uint8_t is_connected(void); std::uint8_t is_disabled(void); std::uint8_t is_field_control(void); std::uint8_t is_competition_switch(void); } // namespace competition namespace usd { /** * Checks if the SD card is installed. * * \return 1 if the SD card is installed, 0 otherwise * * \b Example * \code * void opcontrol() { * printf("%i", is_installed()); * } * \endcode */ std::int32_t is_installed(void); /** * Lists the files in a directory specified by the path * Puts the list of file names (NOT DIRECTORIES) into the buffer seperated by newlines * * This function uses the following values of errno when an error state is * reached: * * EIO - Hard error occured in the low level disk I/O layer * EINVAL - file or directory is invalid, or length is invalid * EBUSY - THe physical drinve cannot work * ENOENT - cannot find the path or file * EINVAL - the path name format is invalid * EACCES - Access denied or directory full * EEXIST - Access denied * EROFS - SD card is write protected * ENXIO - drive number is invalid or not a FAT32 drive * ENOBUFS - drive has no work area * ENFILE - too many open files * * * * \note use a path of "\" to list the files in the main directory NOT "/usd/" * DO NOT PREPEND YOUR PATHS WITH "/usd/" * * \return 1 on success or PROS_ERR on failure setting errno * * \b Example * \code * void opcontrol() { * char* test = (char*) malloc(128); * pros::usd::list_files("/", test, 128); * pros::delay(200); * printf("%s\n", test); //Prints the file names in the root directory seperated by newlines * pros::delay(100); * pros::list_files("/test", test, 128); * pros::delay(200); * printf("%s\n", test); //Prints the names of files in the folder named test seperated by newlines * pros::delay(100); * } * \endcode */ std::int32_t list_files(const char* path, char* buffer, std::int32_t len); } // namespace usd } // namespace pros #endif // _PROS_MISC_HPP_ ================================================ FILE: include/pros/motor_group.hpp ================================================ /** * \file pros/motor_group.hpp * \ingroup cpp-motor-group * * Contains prototypes for the V5 Motor-related functions. * * Visit https://pros.cs.purdue.edu/v5/tutorials/topical/motors.html to learn * more. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-motor-group Motors C++ API * \note Additional example code for this module can be found in its [Tutorial](@ref motors). */ #ifndef _PROS_MOTOR_GROUP_HPP_ #define _PROS_MOTOR_GROUP_HPP_ #include #include #include "pros/abstract_motor.hpp" #include "pros/colors.hpp" #include "pros/device.hpp" #include "pros/motors.h" #include "pros/motors.hpp" #include "rtos.hpp" namespace pros { inline namespace v5 { class MotorGroup : public virtual AbstractMotor { /** * \addtogroup cpp-motor-group * @{ */ public: /** * Constructs a new MotorGroup object. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * A initializer list of V5 port numbers from 1 to 21, or from -21 to -1 for reversed motors. * A reversed motor will reverse the input or output movement functions and movement related * telemetry in order to produce consistant behavior with non-reversed motors * * \param gearset = pros::v5::MotorGears::invalid * Optional parameter for the gearset for the motor. * Does not explicitly set the motor gearset if it is invalid or not specified * * \param encoder_units = pros::v5::MotorUnits::invalid * Optional parameter for the encoder units of the motor * Does not explicitly set the motor units if it is invalid or not specified * * \b Example * \code * void opcontrol() { * MotorGroup first_mg({1, -2}); //Creates a motor on port 1 and a reversed motor on port 2 * MotorGroup rotations_mg({4, 5}, pros::v5::MotorGears::blue, pros::v5::MotorUnits::rotations); * //Creates a motor group on ports 4 and 5 with blue motors using rotaions as the encoder units * } * \endcode */ MotorGroup(const std::initializer_list, const pros::v5::MotorGears gearset = pros::v5::MotorGears::invalid, const pros::v5::MotorUnits encoder_units = pros::v5::MotorUnits::invalid); /** * Constructs a new MotorGroup object. * * This function uses the following values of errno when an error state is * reached: * * ENXIO - The given value is not within the range of V5 ports |1-21|. * * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * \param port * A initializer list of V5 port numbers from 1 to 21, or from -21 to -1 for reversed motors. * A reversed motor will reverse the input or output movement functions and movement related * telemetry in order to produce consistant behavior with non-reversed motors * * \param gearset = pros::v5::MotorGears::invalid * \param gearset = pros::v5::MotorGears::green * Optional parameter for the gearset for the motor. * Does not explicitly set the motor gearset if it is invalid or not specified * * \param encoder_units = pros::v5::MotorUnits::invalid * Optional parameter for the encoder units of the motor * Does not explicitly set the motor units if it is invalid or not specified * * \b Example * \code * void opcontrol() { * MotorGroup first_mg({1, -2}); //Creates a motor on port 1 and a reversed motor on port 2 with * with both motors using the green gearset and degrees as the encoder units * MotorGroup rotations_mg({4, 5}, pros::v5::MotorGears::blue, pros::v5::MotorUnits::rotations); * //Creates a motor group on ports 4 and 5 with blue motors using rotaions as the encoder units * } * \endcode */ MotorGroup(const std::vector& ports, const pros::v5::MotorGears gearset = pros::v5::MotorGears::invalid, const pros::v5::MotorUnits encoder_units = pros::v5::MotorUnits::invalid); /** * Constructs a new MotorGroup object from an abstract motor. * * This function uses the following values of errno when an error state is * reached: * * ENXIO - The given value is not within the range of V5 ports |1-21|. * * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * \param abstract_motor * The abstract motor to turn into a motor group * Uses abstract_motor.get_port_all() to get the vector of ports * * * \b Example * \code * void opcontrol() { * MotorGroup first_mg({1, -2}); //Creates a motor on port 1 and a reversed motor on port 2 with * with both motors using the green gearset and degrees as the encoder units * AbstractMotor abs_mtr_group = first_mg; * MotorGroup new_mg = (MotorGroup) abs_mtr_group; * } * \endcode */ MotorGroup(AbstractMotor& motor_group); /// \name Motor movement functions /// These functions allow programmers to make motors move ///@{ /** * Sets the voltage for the motor group from -127 to 127. * * This is designed to map easily to the input from the controller's analog * stick for simple opcontrol use. The actual behavior of the motor is * analogous to use of motor_move() * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param voltage * The new voltage from -127 to 127 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup MotorGroup ({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg.move(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * pros::delay(2); * } * } * \endcode */ std::int32_t move(std::int32_t voltage) const; /** * Sets the target absolute position for the motor group to move to. * * This movement is relative to the position of the motor when initialized or * the position when it was most recently reset with * pros::Motor::set_zero_position(). * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - the motor group has size 0 * * \param position * The absolute position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg ({1,3}); * mg.move_absolute(100, 100); // Moves 100 units forward * while (!((mg.get_position() < 105) && (mg.get_position() > 95))) { * // Continue running this loop as long as the mg is not within +-5 units of its goal * pros::delay(2); * } * mg.move_absolute(100, 100); // This does not cause a movement * while (!((mg.get_position() < 105) && (mg.get_position() > 95))) { * pros::delay(2); * } * mg.tare_position(); * mg.move_absolute(100, 100); // Moves 100 units forward * while (!((mg.get_position() < 105) && (mg.get_position() > 95))) { * pros::delay(2); * } * } * \endcode */ std::int32_t move_absolute(const double position, const std::int32_t velocity) const; /** * Sets the relative target position for the motor group to move to. * * This movement is relative to the current position of each motor as given in * pros::MotorGroup::get_position(). Providing 10.0 as the position parameter * would result in the motor moving 10 units, no matter what the * current position is. * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param position * The relative position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_relative(100, 100); // Moves 100 units forward * while (!((mg.get_position() < 105) && (mg.get_position() > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * pros::delay(2); * } * mg.move_relative(100, 100); // Also moves 100 units forward * while (!((mg.get_position() < 205) && (mg.get_position() > 195))) { * pros::delay(2); * } * } * \endcode */ std::int32_t move_relative(const double position, const std::int32_t velocity) const; /** * Sets the velocity for the motor group. * * This velocity corresponds to different actual speeds depending on the * gearset used for the motor. This results in a range of +-100 for * E_MOTOR_GEARSET_36, +-200 for E_MOTOR_GEARSET_18, and +-600 for * E_MOTOR_GEARSET_6. The velocity is held with PID to ensure consistent * speed, as opposed to setting the motor's voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param velocity * The new velocity from +-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_velocity(100); * pros::delay(1000); // Move at 100 RPM for 1 second * mg.move_velocity(0); * } * \endcode */ std::int32_t move_velocity(const std::int32_t velocity) const; /** * Sets the output voltage for the motor group from -12000 to 12000 in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param voltage * The new voltage value from -12000 to 12000 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * mg.move_voltage(12000); * pros::delay(1000); // Move at max voltage for 1 second * mg.move_voltage(0); * } * \endcode */ std::int32_t move_voltage(const std::int32_t voltage) const; /** * Stops the motor group using the currently configured brake mode. * * This function sets motor velocity to zero, which will cause it to act * according to the set brake mode. If brake mode is set to MOTOR_BRAKE_HOLD, * this function may behave differently than calling move_absolute(0) * or motor_move_relative(0). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * Motor motor(1); * mg.move_voltage(12000); * pros::delay(1000); // Move at max voltage for 1 second * motor.brake(); * } * \endcode */ std::int32_t brake(void) const; /** * Changes the output velocity for a profiled movement (move_absolute or * move_relative). This will have no effect if the motor group is not following * a profiled movement. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param velocity * The new motor velocity from +-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg ({1,3}); * mg.move_absolute(100, 100); * pros::delay(100); * mg.modify_profiled_velocity(0); // Stop the motor group early * } * \endcode */ std::int32_t modify_profiled_velocity(const std::int32_t velocity) const; /** * Gets the target position set for a motor in the motor group, with a parameter * for the motor index. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The target position in its encoder units or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_absolute(100, 100); * // get the target position from motor at index 1. (port 3) * std::cout << "Motor Target: " << mg.get_target_position(1); * // Prints 100 * } * \endcode */ double get_target_position(const std::uint8_t index) const; /** * Gets a vector of the the target positions set for the motor group * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The Motor group is empty * * \return The a vector of the target positions in its encoder units or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_absolute(100, 100); * std::cout << "Motor Target: " << mg.get_target_position_all()[0]; * // Prints 100 * } * \endcode */ std::vector get_target_position_all(void) const; /** * Gets the velocity commanded to the motor by the user at the index specified. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * EDOM - The motor group was empty * * \param index Optional parameter. * The zero indexed index of the motor in the motor group * * \return The commanded motor velocity from +-100, +-200, or +-600, or * PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg ({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg.move_velocity(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * // get the target velocity from motor at index 1. (port 3) * std::cout << "Motor Velocity: " << mg.get_target_velocity(1); * pros::delay(2); * } * } * \endcode */ std::int32_t get_target_velocity(const std::uint8_t index = 0) const; /** * Gets a vector of the velocity commanded to the motor by the user * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - THe motor group is empty * * \return A vector of the commanded motor velocity from +-100, +-200, or +-600, or * PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg ({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg.move_velocity(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * std::cout << "Motor Velocity: " << mg.get_target_velocity_all(); * pros::delay(2); * } * } * \endcode */ std::vector get_target_velocity_all(void) const; ///@} /// \name Motor telemetry functions /// These functions allow programmers to collect telemetry from motors ///@{ /** * Gets the actual velocity of a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - THe motor group is empty * * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter. * The zero indexed index of the motor in the motor group * * \return The motor's actual velocity in RPM or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * while (true) { * mg = controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y); * // get the actual velocity from motor at index 1. (port 3) * printf("Actual velocity: %lf\n", mg.get_actual_velocity(1)); * pros::delay(2); * } * } * \endcode */ double get_actual_velocity(const std::uint8_t index = 0) const; /** * Gets a vector of the the actual velocity of each motor the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - THe motor group is empty * * \return A vector of the each motor's actual velocity in RPM or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * while (true) { * mg = controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y); * // get the target velocity from motor at index 1. (port 3) * printf("Actual velocity: %lf\n", mg.get_actual_velocity(1)); * pros::delay(2); * } * } * \endcode */ std::vector get_actual_velocity_all(void) const; /** * Gets the current drawn by a motor in the motor group in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter. * The zero indexed index of the motor in the motor group * * \return The motor's current in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * //Print the current draw for the motor at index 1. (port 3) * std::cout << "Motor Current Draw: " << mg.get_current_draw(1); * pros::delay(2); * } * } * \endcode */ std::int32_t get_current_draw(const std::uint8_t index = 0) const; /** * Gets a vector of the current drawn each motor in the motor group in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * * \return A vector with each motor's current in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Current Draw: " << mg.get_current_draw_all(); * pros::delay(2); * } * } * \endcode */ std::vector get_current_draw_all(void) const; /** * Gets the direction of movement for a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 for moving in the positive direction, -1 for moving in the * negative direction, and PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * //Print the motor direction for the motor at index 1. (port 3) * std::cout << "Motor Direction: " << mg.get_direction(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_direction(const std::uint8_t index = 0) const; /** * Gets a vector of the directions of movement for each motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * \return 1 for moving in the positive direction, -1 for moving in the * negative direction, and PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Direction: " << mg.get_direction_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_direction_all(void) const; /** * Gets the efficiency of a motor in the motor group in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's efficiency in percent or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * //Prints the efficiency of the motor at index 1 (port 3) * std::cout << "Motor Efficiency: " << mg.get_efficiency(1); * pros::delay(2); * } * } * \endcode */ double get_efficiency(const std::uint8_t index = 0) const; /** * Gets a vector of the efficiency of each motor in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - THe motor group is empty * * \return A vector containing each motor's efficiency in percent or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Efficiency: " << mg.get_efficiency_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_efficiency_all(void) const; /** * Gets the faults experienced by a motor in the motor group. * * Compare this bitfield to the bitmasks in pros::motor_fault_e_t. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return A bitfield containing the motor's faults. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << mg.get_faults(); * pros::delay(2); * } * } * \endcode */ std::uint32_t get_faults(const std::uint8_t index = 0) const; /** * Gets a vector of the faults experienced by each motor in the motor group. * * Compare these bitfields to the bitmasks in pros::motor_fault_e_t. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * EDOM - The motor group is empty * * * \return A vector containing the bitfields containing each motor's faults. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << mg.get_faults_all(); * pros::delay(2); * } * } * \endcode */ std::vector get_faults_all(void) const; /** * Gets the flags set by a motor in the motor group's operation. * * Compare this bitfield to the bitmasks in pros::motor_flag_e_t. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return A bitfield containing the motor's flags. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << mg.get_faults(1); * pros::delay(2); * } * } * \endcode */ std::uint32_t get_flags(const std::uint8_t index = 0) const; /** * Gets a vector of the flags set by each motor in the motor groups's operation. * * Compare this bitfield to the bitmasks in pros::motor_flag_e_t. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A bitfield containing the motor's flags. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << mg.get_faults_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_flags_all(void) const; /** * Gets the absolute position of a motor in the motor group in its encoder units. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's absolute position in its encoder units or PROS_ERR_F * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << mg.get_position(1); * pros::delay(2); * } * } * \endcode */ double get_position(const std::uint8_t index = 0) const; /** * Gets a vector of the absolute position of each motor in its encoder units. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector of the motor's absolute position in its encoder units or PROS_ERR_F * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << mg.get_position_all(); * pros::delay(2); * } * } * \endcode */ std::vector get_position_all(void) const; /** * Gets the power drawn by a motor in the motor group in Watts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Power: " << mg.get_power(); * pros::delay(2); * } * } * \endcode */ double get_power(const std::uint8_t index = 0) const; /** * Gets a vector of the power drawn by each motor in the motor group in Watts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector of each motor's power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Power: " << mg.get_power_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_power_all(void) const; /** * Gets the raw encoder count of a motor in the motor group at a given timestamp. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * * \param timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The raw encoder count at the given timestamp or PROS_ERR if the * operation failed. * * \b Example * \code * void opcontrol() { * std::uint32_t now = pros::millis(); * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << mg.get_raw_position(&now); * pros::delay(2); * } * } * \endcode */ std::int32_t get_raw_position(std::uint32_t* const timestamp, const std::uint8_t index = 0) const; /** * Gets the raw encoder count of each motor at a given timestamp. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \return A vector of each raw encoder count at the given timestamp or PROS_ERR if the * operation failed. * * \b Example * \code * void opcontrol() { * std::uint32_t now = pros::millis(); * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << mg.get_raw_position_all(&now)[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_raw_position_all(std::uint32_t* const timestamp) const; /** * Gets the temperature of a motor in the motor group in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's temperature in degrees Celsius or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Temperature: " << mg.get_temperature(); * pros::delay(2); * } * } * \endcode */ double get_temperature(const std::uint8_t index = 0) const; /** * Gets the temperature of each motor in the motor group in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector of each motor's temperature in degrees Celsius or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Temperature: " << mg.get_temperature_all()[1]; * pros::delay(2); * } * } * \endcode */ std::vector get_temperature_all(void) const; /** * Gets the torque generated by a motor in the motor groupin Newton Meters (Nm). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's torque in Nm or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Torque: " << mg.get_torque(); * pros::delay(2); * } * } * \endcode */ double get_torque(const std::uint8_t index = 0) const; /** * Gets a vector of the torque generated by each motor in Newton Meters (Nm). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector containing each motor's torque in Nm or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Torque: " << mg.get_torque(); * pros::delay(2); * } * } * \endcode */ std::vector get_torque_all(void) const; /** * Gets the voltage delivered to a motor in the motor group in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's voltage in mV or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Voltage: " << mg.get_voltage(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_voltage(const std::uint8_t index = 0) const; /** * Gets a vector of the voltage delivered to each motor in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector of each motor's voltage in mV or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Voltage: " << mg.get_voltage_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_voltage_all(void) const; /** * Checks if a motor in the motor group is drawing over its current limit. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the motor's current limit is being exceeded and 0 if the * current limit is not exceeded, or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its current limit?: " << mg.is_over_current(); * pros::delay(2); * } * } * \endcode */ std::int32_t is_over_current(const std::uint8_t index = 0) const; /** * Checks if each motor in the motor group is drawing over its current limit. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector containing the following for each motor: 1 if the motor's current limit is being exceeded and 0 if * the current limit is not exceeded, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its current limit?: " << motor.is_over_current_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector is_over_current_all(void) const; /** * Gets the temperature limit flag for a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the temperature limit is exceeded and 0 if the temperature is * below the limit, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its temperature limit?: " << motor.is_over_temp(); * pros::delay(2); * } * } * \endcode */ std::int32_t is_over_temp(const std::uint8_t index = 0) const; /** * Gets a vector with the temperature limit flag for each motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return 1 if the temperature limit is exceeded and 0 if the temperature is * below the limit, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its temperature limit?: " << motor.is_over_temp(); * pros::delay(2); * } * } * \endcode */ std::vector is_over_temp_all(void) const; ///@} /// \name Motor configuration functions /// These functions allow programmers to configure the behavior of motors ///@{ /** * Gets the brake mode that was set for a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return One of MotorBrake, according to what was set for the * motor, or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << mg.get_brake_mode(); * } * \endcode */ MotorBrake get_brake_mode(const std::uint8_t index = 0) const; /** * Gets a vector with the brake mode that was set for each motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector with one of MotorBrake for each motor in the motor group, according to what was set for the * motor, or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << mg.get_brake_mode_all()[0]; * } * \endcode */ std::vector get_brake_mode_all(void) const; /** * Gets the current limit for a motor in the motor group in mA. * * The default value is 2500 mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's current limit in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * while (true) { * std::cout << "Motor Current Limit: " << mg.get_current_limit(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_current_limit(const std::uint8_t index = 0) const; /** * Gets a vector of the current limit for each motor in the motor group in mA. * * The default value is 2500 mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector of each motor's current limit in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * while (true) { * std::cout << "Motor Current Limit: " << mg.get_current_limit_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_current_limit_all(void) const; /** * Gets the encoder units that were set for a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return One of MotorUnits according to what is set for the * motor or E_MOTOR_ENCODER_INVALID if the operation failed. * * \b Example * \code * void initialize() { * pros::MotorGroup mg ({1,3}, E_MOTOR_GEARSET_06, false, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Encoder Units: " << mg.get_encoder_units(); * } * \endcode */ MotorUnits get_encoder_units(const std::uint8_t index = 0) const; /** * Gets a vector of the encoder units that were set for each motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector with the following for each motor, One of MotorUnits according to what is set for the * motor or E_MOTOR_ENCODER_INVALID if the operation failed. * * \b Example * \code * void initialize() { * pros::MotorGroup mg ({1,3}, E_MOTOR_GEARSET_06, false, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Encoder Units: " << mg.get_encoder_units_all()[0]; * } * \endcode */ std::vector get_encoder_units_all(void) const; /** * Gets the gearset that was set for a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * *\param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return One of MotorGears according to what is set for the motor, * or pros::MotorGears::invalid if the operation failed. * * \b Example * \code * void initialize() { * pros::MotorGroup mg ({1,3}, E_MOTOR_GEARSET_06, false, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Gearing: " << mg.get_gearing(); * } * \endcode */ MotorGears get_gearing(const std::uint8_t index = 0) const; /** * Gets a vector of the gearset that was set for each motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * * \return A vector with one of MotorGears according to what is set for the motor, * or pros::MotorGears::invalid if the operation failed for each motor. * * \b Example * \code * void initialize() { * pros::MotorGroup mg ({1,3}, E_MOTOR_GEARSET_06, false, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Gearing: " << mg.get_gearing_all()[0]; * } * \endcode */ std::vector get_gearing_all(void) const; /** * Gets a vector with all the port numbers in the motor group. * A port will be negative if the motor in the motor group is reversed * * @return a vector with all the port numbers for the motor group */ std::vector get_port_all(void) const; /** * Gets the voltage limit of a motor in the motor group set by the user. * * Default value is 0V, which means that there is no software limitation * imposed on the voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * *\param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The motor's voltage limit in V or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * std::cout << "Motor Voltage Limit: " << mg.get_voltage_limit(1); * } * \endcode */ std::int32_t get_voltage_limit(const std::uint8_t index = 0) const; /** * Gets a vector of the voltage limit of each motor in the motor group * * Default value is 0V, which means that there is no software limitation * imposed on the voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The Motor group is empty * * \return The motor's voltage limit in V or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * std::cout << "Motor Voltage Limit: " << mg.get_voltage_limit_all()[0]; * } * \endcode */ std::vector get_voltage_limit_all(void) const; /** * Gets the operation direction of a motor in the motor group as set by the user. * * This function uses the following values of errno when an error state is * reached: * * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * *\param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the motor has been reversed and 0 if the motor was not * reversed, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * std::cout << "Is the motor reversed? " << motor.is_reversed(); * // Prints "0" * } * \endcode */ std::int32_t is_reversed(const std::uint8_t index = 0) const; /** * Gets a vector of the operation direction of each motor in the motor group as set by the user. * * This function uses the following values of errno when an error state is * reached: * EDOM - The motor group is empty * * \return A vector conatining the following for each motor: 1 if the motor has been reversed and 0 if the motor was * not reversed, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * std::cout << "Is the motor reversed? " << motor.is_reversed_all()[0]; * // Prints "0" * } * \endcode */ std::vector is_reversed_all(void) const; /** * Gets the type of a motor in the motor group. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * *\param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return One of MotorType according to the type of the motor, * or pros::MotorType::invalid if the operation failed. * * \b Example * \code * void initialize() { * pros::MotorGroup mg ({1,3}, E_MOTOR_GEARSET_06, false, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Type: " << mg.get_type(); * } * \endcode */ MotorType get_type(const std::uint8_t index = 0) const; /** * Gets a vector of the type of each motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \return A vector with one of MotorType according to the type of the motor, * or pros::MotorType::invalid if the operation failed for each motor. * * \b Example * \code * void initialize() { * pros::MotorGroup mg ({1,3}, E_MOTOR_GEARSET_06, false, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Type: " << mg.get_type_all()[0]; * } * \endcode */ std::vector get_type_all(void) const; /** * Sets one of MotorBrake to a motor in the motor group. Works with the C enum * and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param mode * The MotorBrake to set for the motor * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_brake_mode(pros::MotorBrake::brake, 1); * std::cout << "Brake Mode: " << mg.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode(const MotorBrake mode, const std::uint8_t index = 0) const; /** * Sets one of MotorBrake to a motor in the motor group. Works with the C enum * and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param mode * The MotorBrake to set for the motor * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD, 1); * std::cout << "Brake Mode: " << mg.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode(const pros::motor_brake_mode_e_t mode, const std::uint8_t index = 0) const; /** * Sets one of MotorBrake all the motors in the motor group. Works with the C enum * and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param mode * The MotorBrake to set for the motor * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_brake_mode_all(pros::MotorBrake:brake); * std::cout << "Brake Mode: " << mg.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode_all(const MotorBrake mode) const; /** * Sets one of MotorBrake to a motor in the motor group. Works with the C enum * and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param mode * The MotorBrake to set for the motor * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_brake_mode_all(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << mg.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode_all(const pros::motor_brake_mode_e_t mode) const; /** * Sets the current limit for one motor in the motor group in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param limit * The new current limit in mA * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * * mg.set_current_limit(1000); * while (true) { * mg = controller_get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will reduce its output at 1000 mA instead of the default 2500 mA * pros::delay(2); * } * } * \endcode */ std::int32_t set_current_limit(const std::int32_t limit, const std::uint8_t index = 0) const; /** * Sets the current limit for every motor in the motor group in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group was empty * * \param limit * The new current limit in mA * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * * mg.set_current_limit_all(1000); * while (true) { * mg = controller_get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will reduce its output at 1000 mA instead of the default 2500 mA * pros::delay(2); * } * } * \endcode */ std::int32_t set_current_limit_all(const std::int32_t limit) const; /** * Sets one of MotorUnits for one motor in the motor group's motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param units * The new motor encoder units * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_encoder_units(E_MOTOR_ENCODER_DEGREES, 1); * std::cout << "Encoder Units: " << mg.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units(const MotorUnits units, const std::uint8_t index = 0) const; /** * Sets one of MotorUnits for one motor in the motor group's motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param units * The new motor encoder units * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_encoder_units(E_MOTOR_ENCODER_DEGREES, 1); * std::cout << "Encoder Units: " << mg.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units(const pros::motor_encoder_units_e_t units, const std::uint8_t index = 0) const; /** * Sets one of MotorUnits for every motor in the motor group's motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param units * The new motor encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_encoder_units_all(E_MOTOR_ENCODER_DEGREES); * std::cout << "Encoder Units: " << mg.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units_all(const MotorUnits units) const; /** * Sets one of MotorUnits for every motor in the motor group's motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param units * The new motor encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_encoder_units_all(E_MOTOR_ENCODER_DEGREES); * std::cout << "Encoder Units: " << mg.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units_all(const pros::motor_encoder_units_e_t units) const; /** * Sets one of the gear cartridge (red, green, blue) for one motor in the motor group. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * E2BIG - The size of the vector mismatches the number of motors in the motor group * * \note If there are more motors than gearsets passed in, * only the first n motors will have their gearsets changed where n is the number of gearsets passed in. * If there are more gearsets passed in than motors, then the only the first m gearsets will be used, * where m is the number of motors. In either case, errno will be set to E2BIG, but the operation still occurs * * * \param gearset * The new geatset of the motor * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_gearing(pros::MotorGears::blue, 1); * std::cout << "Gearset: " << mg.get_gearing(); * } * \endcode */ std::int32_t set_gearing(std::vector gearsets) const; /** * Sets one of the gear cartridge (red, green, blue) for one motor in the motor group. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param gearset * The new geatset of the motor * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_gearing(E_MOTOR_GEARSET_06, 1); * std::cout << "Gearset: " << mg.get_gearing(); * } * \endcode */ std::int32_t set_gearing(const pros::motor_gearset_e_t gearset, const std::uint8_t index = 0) const; /** * Sets the gear cartridge (red, green, blue) for each motor in the motor group by taking in a vector of the * cartridges. Usable with the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * E2BIG - The size of the vector mismatches the number of motors in the motor group * * \note If there are more motors than gearsets passed in, * only the first n motors will have their gearsets changed where n is the number of gearsets passed in. * If there are more gearsets passed in than motors, then the only the first m gearsets will be used, * where m is the number of motors. In either case, errno will be set to E2BIG, but the operation still occurs * * \param gearset * The a vector containing the new geatsets of the motors * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_gearing(pros::MotorGears::blue, 1); * std::cout << "Gearset: " << mg.get_gearing(); * } * \endcode */ std::int32_t set_gearing(std::vector gearsets) const; /** * Sets one of the gear cartridge (red, green, blue) for one motor in the motor group. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param gearset * The new geatset of the motor * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_gearing(E_MOTOR_GEARSET_06, 1); * std::cout << "Gearset: " << mg.get_gearing(); * } * \endcode */ std::int32_t set_gearing(const MotorGears gearset, const std::uint8_t index = 0) const; /** * Sets one of the gear cartridge (red, green, blue) for one motor in the motor group. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param gearset * The new geatset of the motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_gearing_all(E_MOTOR_GEARSET_06); * std::cout << "Gearset: " << mg.get_gearing(); * } * \endcode */ std::int32_t set_gearing_all(const MotorGears gearset) const; /** * Sets one of the gear cartridge (red, green, blue) for every motor in the motor group. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param gearset * The new geatset of the motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_gearing_all(E_MOTOR_GEARSET_06); * std::cout << "Gearset: " << mg.get_gearing(); * } * \endcode */ std::int32_t set_gearing_all(const pros::motor_gearset_e_t gearset) const; /** * sets the reversal for a motor in the motor group. * * This will invert its movements and the values returned for its position. * * This function uses the following values of errno when an error state is * reached: * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param reverse * True reverses the motor, false is default * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * //reverse the motor at index 1 (port 3) * mg.set_reversed(true, 1); * std::cout << "Is this motor reversed? " << motor.is_reversed(1); * pros::delay(100); * // unreverse the motor at index 1 (port 3) * mg.set_reversed(false, 1); * std::cout << "Is this motor reversed? " << motor.is_reversed(1); * } * \endcode */ std::int32_t set_reversed(const bool reverse, const std::uint8_t index = 0); /** * Sets the reversal for all the motors in the motor group. * * This will invert its movements and the values returned for its position. * * This function uses the following values of errno when an error state is * reached: * EDOM - The motor group is empty * * \param reverse * True reverses the motor, false is default * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::MotorGroup mg({1,3}); * mg.set_reversed_all(true); * std::cout << "Is this motor reversed? " << motor.is_reversed(); * } * \endcode */ std::int32_t set_reversed_all(const bool reverse); /** * Sets the voltage limit for a motor in the motor group in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param limit * The new voltage limit in Volts * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * * mg.set_voltage_limit(10000, 1); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor on at index 1 (port 3) will not output more than 10 V * pros::delay(2); * } * } * \endcode */ std::int32_t set_voltage_limit(const std::int32_t limit, const std::uint8_t index = 0) const; /** * Sets the voltage limit for every motor in the motor group in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param limit * The new voltage limit in Volts * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * pros::Controller master (E_CONTROLLER_MASTER); * * mg.set_voltage_limit_all(10000); * while (true) { * mg = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will not output more than 10 V * pros::delay(2); * } * } * \endcode */ std::int32_t set_voltage_limit_all(const std::int32_t limit) const; /** * Sets the position for a motor in the motor group in its encoder units. * * This will be the future reference point for the motor's "absolute" * position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param position * The new reference position in its encoder units * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_absolute(100, 100); // Moves 100 units forward * mg.move_absolute(100, 100); // This does not cause a movement * mg.set_zero_position(80); * mg.set_zero_position(80, 1); * mg.move_absolute(100, 100); // Moves 20 units forward * } * \endcode * */ std::int32_t set_zero_position(const double position, const std::uint8_t index = 0) const; /** * Sets the position for every motor in the motor group in its encoder units. * * This will be the future reference point for the motor's "absolute" * position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * * \param position * The new reference position in its encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_absolute(100, 100); // Moves 100 units forward * mg.move_absolute(100, 100); // This does not cause a movement * * mg.set_zero_position_all(80); * mg.move_absolute(100, 100); // Moves 20 units forward * } * \endcode * */ std::int32_t set_zero_position_all(const double position) const; /** * Sets the "absolute" zero position of a motor in the motor group to its current position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EDOM - The motor group is empty * EOVERFLOW - The index is greater than or equal to MotorGroup::size() * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_absolute(100, 100); // Moves 100 units forward * mg.move_absolute(100, 100); // This does not cause a movement * * mg.tare_position(); * mg.tare_position(1); * * mg.move_absolute(100, 100); // Moves 100 units forward * } * \endcode */ std::int32_t tare_position(const std::uint8_t index = 0) const; /** * Sets the "absolute" zero position of every motor in the motor group to its current position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::MotorGroup mg({1,3}); * mg.move_absolute(100, 100); // Moves 100 units forward * mg.move_absolute(100, 100); // This does not cause a movement * mg.tare_position_all(); * mg.move_absolute(100, 100); // Moves 100 units forward * } * \endcode */ std::int32_t tare_position_all(void) const; /** * Returns the number of motors in the motor group * * \return the number of motors in the motor group */ std::int8_t size(void) const; /** * Gets the port of a motor in the motor group via index * * \param index Optional parameter, 0 by default. * The zero indexed index of the motor in the motor group * * \return The port of the motor at the specified index. * The return value is negative if the corresponding motor is reversed */ std::int8_t get_port(const std::uint8_t index = 0) const; /** * Appends all the motors in the other motor group reference to this motor group * * Maintains the order of the other motor group * */ void operator+=(AbstractMotor&); /** * Appends all the motors in the other motor group reference to this motor group * * Maintains the order of the other motor group * */ void append(AbstractMotor&); /** * Removes the all motors on the port (regardless of reversal) from the motor group * * \param port The port to remove from the motor group * */ void erase_port(std::int8_t port); ///@} private: /** * The ordered vector of ports used by the motor group */ std::vector _ports; mutable pros::Mutex _MotorGroup_mutex; }; } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/motors.h ================================================ /** * \file pros/motors.h * \ingroup c-motors * * Contains prototypes for the V5 Motor-related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-motors Motors C API * \note Additional example code for this module can be found in its [Tutorial](@ref motors). */ #ifndef _PROS_MOTORS_H_ #define _PROS_MOTORS_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif /** * \ingroup c-motors */ /** * \addtogroup c-motors * @{ */ /// \name Motor movement functions /// These functions allow programmers to make motors move ///@{ /** * Sets the voltage for the motor from -127 to 127. * * This is designed to map easily to the input from the controller's analog * stick for simple opcontrol use. The actual behavior of the motor is analogous * to use of motor_move_voltage(). * * \note This function will not respect brake modes, and simply sets the voltage to the desired value. * * \note A negative port will negate the input voltage * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param voltage * The new motor voltage from -127 to 127 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * delay(2); * } * } * \endcode */ int32_t motor_move(int8_t port, int32_t voltage); /** * Stops the motor using the currently configured brake mode. * * This function sets motor velocity to zero, which will cause it to act * according to the set brake mode. If brake mode is set to MOTOR_BRAKE_HOLD, * this function may behave differently than calling motor_move_absolute(port, 0) * or motor_move_relative(port, 0). * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move(1, 127); * delay(1000); * motor_break(1); * } * \endcode */ int32_t motor_brake(int8_t port); /** * Sets the target absolute position for the motor to move to. * * This movement is relative to the position of the motor when initialized or * the position when it was most recently reset with motor_set_zero_position(). * * \note This function simply sets the target for the motor, it does not block program * execution until the movement finishes. The example code shows how to block until a movement is finished. * * \note A negative port number will negate the target position * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param position * The absolute position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_absolute(1, 100, 100); // Moves 100 units forward * while (!((motor_get_position(1) < 105) && (motor_get_position(1) > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * delay(2); * } * motor_move_absolute(1, 100, 100); // This will not cause a movement * while(!((motor_get_position(1) < 105) && (motor_get_position(1) > 95))) { * delay(2); * } * * motor_tare_position(1); * motor_move_absolute(1, 100, 100); // Moves 100 units forward * while (!((motor_get_position(1) < 105) && (motor_get_position(1) > 95))) { * delay(2); * } * } * \endcode */ int32_t motor_move_absolute(int8_t port, double position, const int32_t velocity); /** * Sets the relative target position for the motor to move to. * * This movement is relative to the current position of the motor as given in * motor_get_position(). Providing 10.0 as the position parameter would result * in the motor moving clockwise 10 units, no matter what the current position * is. * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. The example code shows how to * block until a movement is finished. * * \note A negative port will negate the target position * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param position * The relative position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_relative(1, 100, 100); // Moves 100 units forward * while (!((motor_get_position(1) < 105) && (motor_get_position(1) > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * delay(2); * } * * motor_move_relative(1, 100, 100); // Also moves 100 units forward * while (!((motor_get_position(1) < 205) && (motor_get_position(1) > 195))) { * delay(2); * } * } * \endcode */ int32_t motor_move_relative(int8_t port, double position, const int32_t velocity); /** * Sets the velocity for the motor. * * This velocity corresponds to different actual speeds depending on the gearset * used for the motor. This results in a range of +-100 for E_MOTOR_GEARSET_36, * +-200 for E_MOTOR_GEARSET_18, and +-600 for E_MOTOR_GEARSET_6. The velocity * is held with PID to ensure consistent speed, as opposed to setting the * motor's voltage. * * \note A negative port will negate the velocity * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param velocity * The new motor velocity from +-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_velocity(1, 100); * delay(1000); // Move at 100 RPM for 1 second * motor_move_velocity(1, 0); * } * \endcode */ int32_t motor_move_velocity(int8_t port, const int32_t velocity); /** * Sets the output voltage for the motor from -12000 to 12000 in millivolts. * * \note A negative port negates the voltage * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \note This function will not respect brake modes, and simply sets the * voltage to the desired value. * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param voltage * The new voltage value from -12000 to 12000 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_voltage(1, 12000); * delay(1000); // Move at max voltage for 1 second * motor_move_voltage(1, 0); * } * \endcode */ int32_t motor_move_voltage(int8_t port, const int32_t voltage); /** * Changes the output velocity for a profiled movement (motor_move_absolute or * motor_move_relative). This will have no effect if the motor is not following * a profiled movement. * * \note A negative port negates the velocity * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param velocity * The new motor velocity from +-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_absolute(1, 100, 100); * delay(100); * motor_modify_profiled_velocity(1, 0); // Stop the motor early * } * \endcode */ int32_t motor_modify_profiled_velocity(int8_t port, const int32_t velocity); /** * Gets the target position set for the motor by the user. * * \note A negative port negates the return value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The target position in its encoder units or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_absolute(1, 100, 100); * printf("Motor Target: %d\n", motor_get_target_position(1)); * // Prints 100 * } * \endcode */ double motor_get_target_position(int8_t port); /** * Gets the velocity commanded to the motor by the user. * * \note A negative port negates the return value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The commanded motor velocity from +-100, +-200, or +-600, or PROS_ERR * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move_velocity(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Commanded Velocity: %d\n", motor_get_target_velocity(1)); * delay(2); * } * } * \endcode */ int32_t motor_get_target_velocity(int8_t port); ///@} /// \name Motor telemetry functions /// These functions allow programmers to collect telemetry from motors ///@{ /** * Gets the actual velocity of the motor. * * \note A negative port negates the return value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's actual velocity in RPM or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Actual velocity: %lf\n", motor_get_actual_velocity(1)); * delay(2); * } * } * \endcode */ double motor_get_actual_velocity(int8_t port); /** * Gets the current drawn by the motor in mA. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's current in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Current Draw: %d\n", motor_get_current_draw(1)); * delay(2); * } * } * \endcode */ int32_t motor_get_current_draw(int8_t port); /** * Gets the direction of movement for the motor. * * \note A negative port number negates the return value. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return 1 for moving in the positive direction, -1 for moving in the * negative direction, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Direction: %d\n", motor_get_direction(1)); * delay(2); * } * } * \endcode */ int32_t motor_get_direction(int8_t port); /** * Gets the efficiency of the motor in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's efficiency in percent or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Efficiency: %d\n", motor_get_efficiency(1)); * delay(2); * } * } * \endcode */ double motor_get_efficiency(int8_t port); /** * Checks if the motor is drawing over its current limit. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return 1 if the motor's current limit is being exceeded and 0 if the current * limit is not exceeded, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Current Limit Hit?: %d\n", motor_is_over_current(1)); * delay(2); * } * } * \endcode */ int32_t motor_is_over_current(int8_t port); /** * Checks if the motor's temperature is above its limit. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return 1 if the temperature limit is exceeded and 0 if the the temperature * is below the limit, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Temp Limit: %d\n", motor_is_over_temp(1)); * delay(2); * } * } * \endcode */ int32_t motor_is_over_temp(int8_t port); #ifdef __cplusplus } // namespace c #endif /** * \enum motor_fault_e_t */ typedef enum motor_fault_e { /// No faults E_MOTOR_FAULT_NO_FAULTS = 0x00, /// Analogous to motor_is_over_temp() E_MOTOR_FAULT_MOTOR_OVER_TEMP = 0x01, /// Indicates a motor h-bridge fault E_MOTOR_FAULT_DRIVER_FAULT = 0x02, /// Analogous to motor_is_over_current() E_MOTOR_FAULT_OVER_CURRENT = 0x04, /// Indicates an h-bridge over current E_MOTOR_FAULT_DRV_OVER_CURRENT = 0x08 } motor_fault_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define MOTOR_FAULT_NO_FAULTS pros::E_MOTOR_FAULT_NO_FAULTS #define MOTOR_FAULT_MOTOR_OVER_TEMP pros::E_MOTOR_FAULT_MOTOR_OVER_TEMP #define MOTOR_FAULT_DRIVER_FAULT pros::E_MOTOR_FAULT_DRIVER_FAULT #define MOTOR_FAULT_OVER_CURRENT pros::E_MOTOR_FAULT_DRV_OVER_CURRENT #define MOTOR_FAULT_DRV_OVER_CURRENT pros::E_MOTOR_FAULT_DRV_OVER_CURRENT #else #define MOTOR_FAULT_NO_FAULTS E_MOTOR_FAULT_NO_FAULTS #define MOTOR_FAULT_MOTOR_OVER_TEMP E_MOTOR_FAULT_MOTOR_OVER_TEMP #define MOTOR_FAULT_DRIVER_FAULT E_MOTOR_FAULT_DRIVER_FAULT #define MOTOR_FAULT_OVER_CURRENT E_MOTOR_FAULT_DRV_OVER_CURRENT #define MOTOR_FAULT_DRV_OVER_CURRENT E_MOTOR_FAULT_DRV_OVER_CURRENT #endif #endif #ifdef __cplusplus namespace c { #endif /** * Gets the faults experienced by the motor. * * Compare this bitfield to the bitmasks in motor_fault_e_t. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1-21 * * \return A bitfield containing the motor's faults. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Faults: %d\n", motor_get_faults(1)); * delay(2); * } * } * \endcode */ uint32_t motor_get_faults(int8_t port); #ifdef __cplusplus } // namespace c #endif /** * \enum motor_flag_e_t * */ typedef enum motor_flag_e { ///There are no flags raised E_MOTOR_FLAGS_NONE = 0x00, /// Cannot currently communicate to the motor E_MOTOR_FLAGS_BUSY = 0x01, /// Analogous to motor_is_stopped() E_MOTOR_FLAGS_ZERO_VELOCITY = 0x02, /// Analogous to motor_get_zero_position_flag() E_MOTOR_FLAGS_ZERO_POSITION = 0x04 } motor_flag_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define MOTOR_FLAGS_NONE pros::E_MOTOR_FLAGS_NONE #define MOTOR_FLAGS_BUSY pros::E_MOTOR_FLAGS_BUSY #define MOTOR_FLAGS_ZERO_VELOCITY pros::E_MOTOR_FLAGS_ZERO_VELOCITY #define MOTOR_FLAGS_ZERO_POSITION pros::E_MOTOR_FLAGS_ZERO_POSITION #else #define MOTOR_FLAGS_NONE E_MOTOR_FLAGS_NONE #define MOTOR_FLAGS_BUSY E_MOTOR_FLAGS_BUSY #define MOTOR_FLAGS_ZERO_VELOCITY E_MOTOR_FLAGS_ZERO_VELOCITY #define MOTOR_FLAGS_ZERO_POSITION E_MOTOR_FLAGS_ZERO_POSITION #endif #endif #ifdef __cplusplus namespace c { #endif /** * Gets the flags set by the motor's operation. * * Compare this bitfield to the bitmasks in motor_flag_e_t. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return A bitfield containing the motor's flags. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Flags: %d\n", motor_get_flags(1)); * delay(2); * } * } * \endcode */ uint32_t motor_get_flags(int8_t port); /** * Gets the raw encoder count of the motor at a given timestamp. * * \note A negative port value negates the return value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param[in] timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \return The raw encoder count at the given timestamp or PROS_ERR if the * operation failed. * * \b Example * \code * void opcontrol() { * uint32_t now = millis(); * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Encoder Count: %d\n", motor_get_raw_position(1, &now)); * delay(2); * } * } * \endcode */ int32_t motor_get_raw_position(int8_t port, uint32_t* const timestamp); /** * Gets the absolute position of the motor in its encoder units. * * \note A negative port value negates the return value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's absolute position in its encoder units or PROS_ERR_F * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Position: %lf\n", motor_get_position(1)); * delay(2); * } * } * \endcode */ double motor_get_position(int8_t port); /** * Gets the power drawn by the motor in Watts. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * uint32_t now = millis(); * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Power: %lf\n", motor_get_power(1)); * delay(2); * } * } * \endcode */ double motor_get_power(int8_t port); /** * Gets the temperature of the motor in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's temperature in degrees Celsius or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Temperature: %lf\n", motor_get_temperature(1)); * delay(2); * } * } * \endcode */ double motor_get_temperature(int8_t port); /** * Gets the torque generated by the motor in Newton Meters (Nm). * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's torque in Nm or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Torque: %lf\n", motor_get_torque(1)); * delay(2); * } * } * \endcode */ double motor_get_torque(int8_t port); /** * Gets the voltage delivered to the motor in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's voltage in mV or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * printf("Motor Voltage: %lf\n", motor_get_voltage(1)); * delay(2); * } * } * \endcode */ int32_t motor_get_voltage(int8_t port); ///@} /// \name Motor configuration functions /// These functions allow programmers to configure the behavior of motors ///@{ #ifdef __cplusplus } // namespace c #endif /** * \enum motor_brake_mode_e_t * Indicates the current 'brake mode' of a motor. */ typedef enum motor_brake_mode_e { /// Motor coasts when stopped, traditional behavior E_MOTOR_BRAKE_COAST = 0, /// Motor brakes when stopped E_MOTOR_BRAKE_BRAKE = 1, /// Motor actively holds position when stopped E_MOTOR_BRAKE_HOLD = 2, /// Invalid brake mode E_MOTOR_BRAKE_INVALID = INT32_MAX } motor_brake_mode_e_t; /** * \enum motor_encoder_units_e_t * Indicates the units used by the motor encoders. */ typedef enum motor_encoder_units_e { /// Position is recorded as angle in degrees as a floating point number E_MOTOR_ENCODER_DEGREES = 0, /// Position is recorded as angle in rotations as a floating point number E_MOTOR_ENCODER_ROTATIONS = 1, /// Position is recorded as raw encoder ticks as a whole number E_MOTOR_ENCODER_COUNTS = 2, ///Invalid motor encoder units E_MOTOR_ENCODER_INVALID = INT32_MAX } motor_encoder_units_e_t; /** * \enum motor_gearset_e_t * Indicates the current internal gear ratio of a motor. */ typedef enum motor_gearset_e { E_MOTOR_GEARSET_36 = 0, // 36:1, 100 RPM, Red gear set E_MOTOR_GEAR_RED = E_MOTOR_GEARSET_36, // 36:1, 100 RPM, Red gear set E_MOTOR_GEAR_100 = E_MOTOR_GEARSET_36, // 36:1, 100 RPM, Red gear set E_MOTOR_GEARSET_18 = 1, // 18:1, 200 RPM, Green gear set E_MOTOR_GEAR_GREEN = E_MOTOR_GEARSET_18, // 18:1, 200 RPM, Green gear set E_MOTOR_GEAR_200 = E_MOTOR_GEARSET_18, // 18:1, 200 RPM, Green gear set E_MOTOR_GEARSET_06 = 2, // 6:1, 600 RPM, Blue gear set E_MOTOR_GEAR_BLUE = E_MOTOR_GEARSET_06, // 6:1, 600 RPM, Blue gear set E_MOTOR_GEAR_600 = E_MOTOR_GEARSET_06, // 6:1, 600 RPM, Blue gear set E_MOTOR_GEARSET_INVALID = INT32_MAX, // Error: Invalid Gearset } motor_gearset_e_t; /** * \enum motor_type_e_t * Indicates the type of a motor */ typedef enum motor_type_e { E_MOTOR_TYPE_V5 = 0, // 11 watt V5 motor E_MOTOR_TYPE_EXP = 1, // 5.5 watt EXP motor E_MOTOR_TYPE_INVALID = INT32_MAX, // Error: invalid type } motor_type_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define MOTOR_BRAKE_COAST pros::E_MOTOR_BRAKE_COAST #define MOTOR_BRAKE_BRAKE pros::E_MOTOR_BRAKE_BRAKE #define MOTOR_BRAKE_HOLD pros::E_MOTOR_BRAKE_HOLD #define MOTOR_BRAKE_INVALID pros::E_MOTOR_BRAKE_INVALID #define MOTOR_ENCODER_DEGREES pros::E_MOTOR_ENCODER_DEGREES #define MOTOR_ENCODER_ROTATIONS pros::E_MOTOR_ENCODER_ROTATIONS #define MOTOR_ENCODER_COUNTS pros::E_MOTOR_ENCODER_COUNTS #define MOTOR_ENCODER_INVALID pros::E_MOTOR_ENCODER_INVALID #define MOTOR_GEARSET_36 pros::E_MOTOR_GEARSET_36 #define MOTOR_GEAR_RED pros::E_MOTOR_GEAR_RED #define MOTOR_GEAR_100 pros::E_MOTOR_GEAR_100 #define MOTOR_GEARSET_18 pros::E_MOTOR_GEARSET_18 #define MOTOR_GEAR_GREEN pros::E_MOTOR_GEAR_GREEN #define MOTOR_GEAR_200 pros::E_MOTOR_GEAR_200 #define MOTOR_GEARSET_06 pros::E_MOTOR_GEARSET_06 #define MOTOR_GEARSET_6 pros::E_MOTOR_GEARSET_06 #define MOTOR_GEAR_BLUE pros::E_MOTOR_GEAR_BLUE #define MOTOR_GEAR_600 pros::E_MOTOR_GEAR_600 #define MOTOR_GEARSET_INVALID pros::E_MOTOR_GEARSET_INVALID #define MOTOR_TYPE_V5 pros::E_MOTOR_TYPE_V5 #define MOTOR_TYPE_EXP pros::E_MOTOR_TYPE_EXP #define MOTOR_TYPE_INVALID pros::E_MOTOR_TYPE_INVALID #else #define MOTOR_BRAKE_COAST E_MOTOR_BRAKE_COAST #define MOTOR_BRAKE_BRAKE E_MOTOR_BRAKE_BRAKE #define MOTOR_BRAKE_HOLD E_MOTOR_BRAKE_HOLD #define MOTOR_BRAKE_INVALID E_MOTOR_BRAKE_INVALID #define MOTOR_ENCODER_DEGREES E_MOTOR_ENCODER_DEGREES #define MOTOR_ENCODER_ROTATIONS E_MOTOR_ENCODER_ROTATIONS #define MOTOR_ENCODER_COUNTS E_MOTOR_ENCODER_COUNTS #define MOTOR_ENCODER_INVALID E_MOTOR_ENCODER_INVALID #define MOTOR_GEARSET_36 E_MOTOR_GEARSET_36 #define MOTOR_GEAR_RED E_MOTOR_GEAR_RED #define MOTOR_GEAR_100 E_MOTOR_GEAR_100 #define MOTOR_GEARSET_18 E_MOTOR_GEARSET_18 #define MOTOR_GEAR_GREEN E_MOTOR_GEAR_GREEN #define MOTOR_GEAR_200 E_MOTOR_GEAR_200 #define MOTOR_GEARSET_06 E_MOTOR_GEARSET_06 #define MOTOR_GEARSET_6 E_MOTOR_GEARSET_06 #define MOTOR_GEAR_BLUE E_MOTOR_GEAR_BLUE #define MOTOR_GEAR_600 E_MOTOR_GEAR_600 #define MOTOR_GEARSET_INVALID E_MOTOR_GEARSET_INVALID #define MOTOR_TYPE_V5 E_MOTOR_TYPE_V5 #define MOTOR_TYPE_EXP E_MOTOR_TYPE_EXP #define MOTOR_TYPE_INVALID E_MOTOR_TYPE_INVALID #endif #endif /** * \struct motor_pid_full_s_t * * Holds the information about a Motor's position or velocity PID controls. * * These values are in 4.4 format, meaning that a value of 0x20 represents 2.0, * 0x21 represents 2.0625, 0x22 represents 2.125, etc. */ typedef struct motor_pid_full_s { /// The feedforward constant uint8_t kf; /// The proportional constant uint8_t kp; /// The integral constants uint8_t ki; /// The derivative constant uint8_t kd; /// A constant used for filtering the profile acceleration uint8_t filter; /// The integral limit uint16_t limit; /// The threshold for determining if a position movement hasreached its goa l. This has no effect for velocity PID calculations. uint8_t threshold; /// The rate at which the PID computation is run in ms uint8_t loopspeed; } motor_pid_full_s_t; /** * \struct motor_pid_s_t * * Holds just the constants for a Motor's position or velocity PID controls. * * These values are in 4.4 format, meaning that a value of 0x20 represents 2.0, * 0x21 represents 2.0625, 0x22 represents 2.125, etc. */ typedef struct motor_pid_s { /// The feedforward constant uint8_t kf; /// The proportional constant uint8_t kp; /// The integral constants uint8_t ki; /// The derivative constant uint8_t kd; } motor_pid_s_t; #ifdef __cplusplus namespace c { #endif /** * Sets the position for the motor in its encoder units. * * This will be the future reference point for the motor's "absolute" position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param position * The new reference position in its encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * * \code * void autonomous() { * motor_move_absolute(1, 100, 100); // Moves 100 units forward * while (!((motor_get_position(1) - 100 < 105) && (motor_get_position(1) - 100 > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * delay(2); * } * motor_move_absolute(1, 100, 100); // This does not cause a movement * while (!((motor_get_position(1) - 100 < 105) && (motor_get_position(1) - 100 > 95))) { * delay(2); * } * * motor_set_zero_position(1, 80); * motor_move_absolute(1, 100, 100); // Moves 20 units forward * while (!((motor_get_position(1) - 100 < 105) && (motor_get_position(1) - 100 > 95))) { * delay(2); * } * } * \endcode */ int32_t motor_set_zero_position(int8_t port, const double position); /** * Sets the "absolute" zero position of the motor to its current position. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_move_absolute(1, 100, 100); // Moves 100 units forward * while (!((motor_get_position(1) - 100 < 105) && (motor_get_position(1) - 100 > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * delay(2); * } * motor_move_absolute(1, 100, 100); // This does not cause a movement * while (!((motor_get_position(1) - 100 < 105) && (motor_get_position(1) - 100 > 95))) { * delay(2); * } * * motor_tare_position(1); * motor_move_absolute(1, 100, 100); // Moves 100 units forward * while (!((motor_get_position(1) - 100 < 105) && (motor_get_position(1) - 100 > 95))) { * delay(2); * } * } * \endcode */ int32_t motor_tare_position(int8_t port); /** * Sets one of motor_brake_mode_e_t to the motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param mode * The motor_brake_mode_e_t to set for the motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * motor_set_brake_mode(1, E_MOTOR_BRAKE_HOLD); * printf("Brake Mode: %d\n", motor_get_brake_mode(1)); * } * \endcode */ int32_t motor_set_brake_mode(int8_t port, const motor_brake_mode_e_t mode); /** * Sets the current limit for the motor in mA. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param limit * The new current limit in mA * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * motor_set_current_limit(1, 1000); * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * // The motor will reduce its output at 1000 mA instead of the default 2500 mA * delay(2); * } * } * \endcode */ int32_t motor_set_current_limit(int8_t port, const int32_t limit); /** * Sets one of motor_encoder_units_e_t for the motor encoder. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param units * The new motor encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * motor_set_encoder_units(1, E_MOTOR_ENCODER_DEGREES); * printf("Encoder Units: %d\n", motor_get_encoder_units(1)); * } * \endcode */ int32_t motor_set_encoder_units(int8_t port, const motor_encoder_units_e_t units); /** * Sets one of motor_gearset_e_t for the motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param gearset * The new motor gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * motor_set_gearing(1, E_MOTOR_GEARSET_06); * printf("Brake Mode: %d\n", motor_get_gearing(1)); * } * \endcode */ int32_t motor_set_gearing(int8_t port, const motor_gearset_e_t gearset); /** * Sets the voltage limit for the motor in Volts. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * \param limit * The new voltage limit in Volts * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor_set_voltage_limit(1, 10000); * while (true) { * motor_move(1, controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y)); * // The motor will not output more than 10 V * delay(2); * } * } * \endcode */ int32_t motor_set_voltage_limit(int8_t port, const int32_t limit); /** * Gets the brake mode that was set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return One of motor_brake_mode_e_t, according to what was set for the motor, * or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. * * \b Example * \code * void initialize() { * motor_set_brake_mode(1, E_MOTOR_BRAKE_HOLD); * printf("Brake Mode: %d\n", motor_get_brake_mode(1)); * } * \endcode */ motor_brake_mode_e_t motor_get_brake_mode(int8_t port); /** * Gets the current limit for the motor in mA. * * The default value is 2500 mA. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's current limit in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void initialize() { * printf("Motor Current Limit: %d\n", motor_get_current_limit(1)); * // Prints "Motor Current Limit: 2500" * } * \endcode */ int32_t motor_get_current_limit(int8_t port); /** * Gets the encoder units that were set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return One of motor_encoder_units_e_t according to what is set for the motor * or E_MOTOR_ENCODER_INVALID if the operation failed. */ motor_encoder_units_e_t motor_get_encoder_units(int8_t port); /** * Gets the gearset that was set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return One of motor_gearset_e_t according to what is set for the motor, * or E_GEARSET_INVALID if the operation failed. * * \b Example * \code * void initialize() { * printf("Motor Encoder Units: %d\n", motor_get_encoder_units(1)); * // Prints E_MOTOR_ENCODER_DEGREES by default * } * \endcode */ motor_gearset_e_t motor_get_gearing(int8_t port); /** * Gets the voltage limit set by the user. * * Default value is 0V, which means that there is no software limitation imposed * on the voltage. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return The motor's voltage limit in V or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void initialize() { * printf("Motor Voltage Limit: %d\n", motor_get_voltage_limit(1)); * // Prints 0 by default, indicating no limit * } * \endcode */ int32_t motor_get_voltage_limit(int8_t port); /** * Get the type of the motor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21| * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors * * \return One of motor_type_e_t according to the type of the motor, or * E_MOTOR_TYPE_INVALID if the operation failed. * * \b Example * \code * void initialize() { * printf("Motor Type: %d\n", motor_get_type(1)); * // Prints the type of the motor * } * \endcode */ motor_type_e_t motor_get_type(int8_t port); ///@} ///@} #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_MOTORS_H_ ================================================ FILE: include/pros/motors.hpp ================================================ /** * \file pros/motors.hpp * \ingroup cpp-motors * * Contains prototypes for the V5 Motor-related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-motors Motors C++ API * \note Additional example code for this module can be found in its [Tutorial](@ref motors). */ #ifndef _PROS_MOTORS_HPP_ #define _PROS_MOTORS_HPP_ #include #include #include "pros/abstract_motor.hpp" #include "pros/device.hpp" #include "pros/motors.h" #include "rtos.hpp" namespace pros { inline namespace v5 { class Motor : public AbstractMotor, public Device { public: /** * \addtogroup cpp-motors * @{ */ /** * Constructs a new Motor object. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed motors. * A reversed motor will reverse the input or output movement functions and movement related * telemetry in order to produce consistant behavior with non-reversed motors * * \param gearset = pros::v5::MotorGears::green * Optional parameter for the gearset for the motor. * Does not explicitly set the gearset if not specified or if the gearset is invalid * * \param encoder_units = pros::v5::MotorUnits::degrees * Optional parameter for the encoder units of the motor * Does not explicitly set the gearset if not specified or if the gearset is invalid * * \b Example * \code * void opcontrol() { * Motor first_motor(1); //Creates a motor on port 1 without altering gearset or encoder units * Motor reversed_motor(-2); //Creates a reversed motor on port 1 port 1 without altering gearset or encoder units * Motor blue_motor(3, pros::v5::MotorGears::blue); //Creates a motor on port 3 with blue gear set * Motor rotations_motor(4, pros::v5::MotorGears::green, pros::v5::MotorUnits::rotations); //port 4 w/ rotations * * } * \endcode * */ Motor(const std::int8_t port, const pros::v5::MotorGears gearset = pros::v5::MotorGears::invalid, const pros::v5::MotorUnits encoder_units = pros::v5::MotorUnits::invalid); Motor(const Device& device) : Motor(device.get_port()){}; /// \name Motor movement functions /// These functions allow programmers to make motors move ///@{ /** * Sets the voltage for the motor from -127 to 127. * * This is designed to map easily to the input from the controller's analog * stick for simple opcontrol use. The actual behavior of the motor is * analogous to use of motor_move(). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param voltage * The new motor voltage from -127 to 127 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor Motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor.move(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * pros::delay(2); * } * } * \endcode */ std::int32_t move(std::int32_t voltage) const; /** * Sets the target absolute position for the motor to move to. * * This movement is relative to the position of the motor when initialized or * the position when it was most recently reset with * pros::Motor::set_zero_position(). * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. * * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param position * The absolute position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); // Moves 100 units forward * while (!((motor.get_position() < 105) && (motor.get_position() > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * pros::delay(2); * } * motor.move_absolute(100, 100); // This does not cause a movement * while (!((motor.get_position() < 105) && (motor.get_position() > 95))) { * pros::delay(2); * } * motor.tare_position(); * motor.move_absolute(100, 100); // Moves 100 units forward * while (!((motor.get_position() < 105) && (motor.get_position() > 95))) { * pros::delay(2); * } * } * \endcode */ std::int32_t move_absolute(const double position, const std::int32_t velocity) const; /** * Sets the relative target position for the motor to move to. * * This movement is relative to the current position of the motor as given in * pros::Motor::motor_get_position(). Providing 10.0 as the position parameter * would result in the motor moving clockwise 10 units (counter clockwise if reversed), * no matter what the current position is. * * \note This function simply sets the target for the motor, it does not block * program execution until the movement finishes. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param position * The relative position to move to in the motor's encoder units * \param velocity * The maximum allowable velocity for the movement in RPM * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_relative(100, 100); // Moves 100 units forward * while (!((motor.get_position() < 105) && (motor.get_position() > 95))) { * // Continue running this loop as long as the motor is not within +-5 units of its goal * pros::delay(2); * } * motor.move_relative(100, 100); // Also moves 100 units forward * while (!((motor.get_position() < 205) && (motor.get_position() > 195))) { * pros::delay(2); * } * } * \endcode */ std::int32_t move_relative(const double position, const std::int32_t velocity) const; /** * Sets the velocity for the motor. * * This velocity corresponds to different actual speeds depending on the * gearset used for the motor. This results in a range of +-100 for * E_MOTOR_GEARSET_36, +-200 for E_MOTOR_GEARSET_18, and +-600 for * E_MOTOR_GEARSET_6. The velocity is held with PID to ensure consistent * speed, as opposed to setting the motor's voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param velocity * The new motor velocity from -+-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_velocity(100); * pros::delay(1000); // Move at 100 RPM for 1 second * motor.move_velocity(0); * } * \endcode */ std::int32_t move_velocity(const std::int32_t velocity) const; /** * Sets the output voltage for the motor from -12000 to 12000 in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param port * The V5 port number from 1-21 * \param voltage * The new voltage value from -12000 to 12000 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * motor.move_voltage(12000); * pros::delay(1000); // Move at max voltage for 1 second * motor.move_voltage(0); * } * \endcode */ std::int32_t move_voltage(const std::int32_t voltage) const; /** * Stops the motor using the currently configured brake mode. * * This function sets motor velocity to zero, which will cause it to act * according to the set brake mode. If brake mode is set to MOTOR_BRAKE_HOLD, * this function may behave differently than calling move_absolute(0) * or motor_move_relative(0). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * Motor motor(1); * motor.move_voltage(12000); * pros::delay(1000); // Move at max voltage for 1 second * motor.brake(); * } * \endcode */ std::int32_t brake(void) const; /** * Changes the output velocity for a profiled movement (motor_move_absolute or * motor_move_relative). This will have no effect if the motor is not following * a profiled movement. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param velocity * The new motor velocity from +-100, +-200, or +-600 depending on the * motor's gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); * pros::delay(100); * motor.modify_profiled_velocity(0); // Stop the motor early * } * \endcode */ std::int32_t modify_profiled_velocity(const std::int32_t velocity) const; ///@} /// \name Motor telemetry functions /// These functions allow programmers to collect telemetry from motors ///@{ /** * Gets the target position set for the motor by the user * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The target position in its encoder units or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); * std::cout << "Motor Target: " << motor.get_target_position(); * // Prints 100 * } * \endcode */ double get_target_position(const std::uint8_t index = 0) const; /** * Gets the velocity commanded to the motor by the user at the index specified. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The commanded motor velocity from +-100, +-200, or +-600, or * PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor.move_velocity(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * std::cout << "Motor Velocity: " << motor.get_target_velocity(); * // Prints the value of E_CONTROLLER_ANALOG_LEFT_Y * pros::delay(2); * } * } * \endcode */ std::int32_t get_target_velocity(const std::uint8_t index = 0) const; /** * Gets the actual velocity of the motor. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's actual velocity in RPM or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * while (true) { * motor = controller_get_analog(E_CONTROLLER_MASTER, E_CONTROLLER_ANALOG_LEFT_Y); * printf("Actual velocity: %lf\n", motor.get_actual_velocity()); * pros::delay(2); * } * } * \endcode */ double get_actual_velocity(const std::uint8_t index = 0) const; /** * Gets the current drawn by the motor in mA. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's current in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Current Draw: " << motor.get_current_draw(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_current_draw(const std::uint8_t index = 0) const; /** * Gets the direction of movement for the motor. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 for moving in the positive direction, -1 for moving in the * negative direction, and PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Direction: " << motor.get_direction(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_direction(const std::uint8_t index = 0) const; /** * Gets the efficiency of the motor in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's efficiency in percent or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Efficiency: " << motor.get_efficiency(); * pros::delay(2); * } * } * \endcode */ double get_efficiency(const std::uint8_t index = 0) const; /** * Gets the faults experienced by the motor. * * Compare this bitfield to the bitmasks in pros::motor_fault_e_t. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * * \return A bitfield containing the motor's faults. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << motor.get_faults();pros::delay(2); * } * } * \endcode */ std::uint32_t get_faults(const std::uint8_t index = 0) const; /** * Gets the flags set by the motor's operation. * * Compare this bitfield to the bitmasks in pros::motor_flag_e_t. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return A bitfield containing the motor's flags. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << motor.get_faults(); * pros::delay(2); * } * } * \endcode */ std::uint32_t get_flags(const std::uint8_t index = 0) const; /** * Gets the absolute position of the motor in its encoder units. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's absolute position in its encoder units or PROS_ERR_F * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << motor.get_position(); * pros::delay(2); * } * } * \endcode */ double get_position(const std::uint8_t index = 0) const; /** * Gets the power drawn by the motor in Watts. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Power: " << motor.get_power(); * pros::delay(2); * } * } * \endcode */ double get_power(const std::uint8_t index = 0) const; /** * Gets the raw encoder count of the motor at a given timestamp. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * * \param timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * * * \return The raw encoder count at the given timestamp or PROS_ERR if the * operation failed. * * \b Example * \code * void opcontrol() { * std::uint32_t now = pros::millis(); * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << motor.get_raw_position(&now); * pros::delay(2); * } * } * \endcode */ std::int32_t get_raw_position(std::uint32_t* const timestamp, const std::uint8_t index = 0) const; /** * Gets the temperature of the motor in degrees Celsius. * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's temperature in degrees Celsius or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Temperature: " << motor.get_temperature(); * pros::delay(2); * } * } * \endcode */ double get_temperature(const std::uint8_t index = 0) const; /** * Gets the torque generated by the motor in Newton Meters (Nm). * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's torque in Nm or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Torque: " << motor.get_torque(); * pros::delay(2); * } * } * \endcode */ double get_torque(const std::uint8_t index = 0) const; /** * Gets the voltage delivered to the motor in millivolts. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's voltage in mV or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Voltage: " << motor.get_voltage(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_voltage(const std::uint8_t index = 0) const; /** * Checks if the motor is drawing over its current limit. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the motor's current limit is being exceeded and 0 if the * current limit is not exceeded, or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its current limit?: " << motor.is_over_current(); * pros::delay(2); * } * } * \endcode */ std::int32_t is_over_current(const std::uint8_t index = 0) const; /** * Gets the temperature limit flag for the motor. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the temperature limit is exceeded and 0 if the temperature is * below the limit, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its temperature limit?: " << motor.is_over_temp(); * pros::delay(2); * } * } * \endcode */ std::int32_t is_over_temp(const std::uint8_t index = 0) const; ///@} /// \name Motor configuration functions /// These functions allow programmers to configure the behavior of motors ///@{ /** * Gets the brake mode that was set for the motor. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return One of MotorBrake, according to what was set for the * motor, or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << motor.get_brake_mode(); * } * \endcode */ MotorBrake get_brake_mode(const std::uint8_t index = 0) const; /** * Gets the current limit for the motor in mA. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return The motor's current limit in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * while (true) { * std::cout << "Motor Current Limit: " << motor.get_current_limit(); * pros::delay(2); * } * } * \endcode */ std::int32_t get_current_limit(const std::uint8_t index = 0) const; /** * Gets the encoder units that were set for the motor. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return One of MotorUnits according to what is set for the * motor or E_MOTOR_ENCODER_INVALID if the operation failed. * * \b Example * \code * void initialize() { * pros::Motor motor (1, E_MOTOR_GEARSET_06, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Encoder Units: " << motor.get_encoder_units(); * } * \endcode */ MotorUnits get_encoder_units(const std::uint8_t index = 0) const; /** * Gets the gearset that was set for the motor. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return One of MotorGears according to what is set for the motor, * or pros::MotorGears::invalid if the operation failed. * * \b Example * \code * void initialize() { * pros::Motor motor (1, E_MOTOR_GEARSET_06, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Gearing: " << motor.get_gearing(); * } * \endcode */ MotorGears get_gearing(const std::uint8_t index = 0) const; /** * Gets the voltage limit set by the user. * * Default value is 0V, which means that there is no software limitation * imposed on the voltage. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \b Example * \code * void initialize() { * pros::Motor motor (1); * std::cout << "Motor Voltage Limit: " << motor.get_voltage_limit(); * } * \endcode */ std::int32_t get_voltage_limit(const std::uint8_t index = 0) const; /** * Gets whether the motor is reversed or not * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the motor has been reversed and 0 if the motor was not * reversed, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * std::cout << "Is the motor reversed? " << motor.is_reversed(); * // Prints "0" * } * \endcode */ std::int32_t is_reversed(const std::uint8_t index = 0) const; /** * Gets the type of the motor * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the type of. * By default index is 0, and will return an error for a non-zero index * * \return One of MotorType according to the type of the motor, * or pros::MotorType::invalid if the operation failed. * * \b Example * \code * void initialize() { * pros::Motor motor (1, E_MOTOR_GEARSET_06, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Type: " << motor.get_type(); * } * \endcode */ MotorType get_type(const std::uint8_t index = 0) const; /** * Sets one of Motor_Brake to the motor. * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * * \param mode * The MotorBrake to set for the motor * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << motor.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode(const MotorBrake mode, const std::uint8_t index = 0) const; /** * Sets one of MotorBrake to the motor. * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * * \param mode * The MotorBrake to set for the motor * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << motor.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode(const pros::motor_brake_mode_e_t mode, const std::uint8_t index = 0) const; /** * Sets the current limit for the motor in mA. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param limit * The new current limit in mA * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * * motor.set_current_limit(1000); * while (true) { * motor = controller_get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will reduce its output at 1000 mA instead of the default 2500 mA * pros::delay(2); * } * } * \endcode */ std::int32_t set_current_limit(const std::int32_t limit, const std::uint8_t index = 0) const; /** * Sets one of MotorUnits for the motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param units * The new motor encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_encoder_units(E_MOTOR_ENCODER_DEGREES); * std::cout << "Encoder Units: " << motor.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units(const MotorUnits units, const std::uint8_t index = 0) const; /** * Sets one of MotorUnits for the motor encoder. Works with the C * enum and the C++ enum class. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * * \param units * The new motor encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_encoder_units(E_MOTOR_ENCODER_DEGREES); * std::cout << "Encoder Units: " << motor.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units(const pros::motor_encoder_units_e_t units, const std::uint8_t index = 0) const; /** * Sets one of the gear cartridge (red, green, blue) for the motor. Usable with * the C++ enum class and the C enum. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * \param gearset * The new motor gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_gearing(E_MOTOR_GEARSET_06); * std::cout << "Gearset: " << motor.get_gearing(); * } * \endcode */ std::int32_t set_gearing(const MotorGears gearset, const std::uint8_t index = 0) const; /** * Sets one of the gear cartridge (red, green, blue) for the motor. Usable with * the C++ enum class and the C enum. * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param gearset * The new motor gearset * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_gearing(E_MOTOR_GEARSET_06); * std::cout << "Gearset: " << motor.get_gearing(); * } * \endcode */ std::int32_t set_gearing(const pros::motor_gearset_e_t gearset, const std::uint8_t index = 0) const; /** * Sets the reverse flag for the motor. * * This will invert its movements and the values returned for its position. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * EOVERFLOW - The index is non 0 * * \param reverse * True reverses the motor, false is default direction * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_reversed(true); * std::cout << "Is this motor reversed? " << motor.is_reversed(); * } * \endcode */ std::int32_t set_reversed(const bool reverse, const std::uint8_t index = 0); /** * Sets the voltage limit for the motor in Volts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param limit * The new voltage limit in Volts * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * * motor.set_voltage_limit(10000); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will not output more than 10 V * pros::delay(2); * } * } * \endcode */ std::int32_t set_voltage_limit(const std::int32_t limit, const std::uint8_t index = 0) const; /** * Sets the position for the motor in its encoder units. * * This will be the future reference point for the motor's "absolute" * position. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param position * The new reference position in its encoder units * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); // Moves 100 units forward * motor.move_absolute(100, 100); // This does not cause a movement * * motor.set_zero_position(80); * motor.move_absolute(100, 100); // Moves 20 units forward * } * \endcode * */ std::int32_t set_zero_position(const double position, const std::uint8_t index = 0) const; /** * Sets the "absolute" zero position of the motor to its current position. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); // Moves 100 units forward * motor.move_absolute(100, 100); // This does not cause a movement * * motor.tare_position(); * motor.move_absolute(100, 100); // Moves 100 units forward * } * \endcode */ std::int32_t tare_position(const std::uint8_t index = 0) const; /** * Gets the number of motors. * * \return Always returns 1 * */ std::int8_t size(void) const; /** * Gets all motors. * * \return A vector of Motor objects. * * \b Example * \code * void opcontrol() { * std::vector motor_all = pros::Motor::get_all_devices(); // All motors that are connected * } * \endcode */ static std::vector get_all_devices(); /** * gets the port number of the motor * * \return The signed port of the motor. (negative if the motor is reversed) * */ std::int8_t get_port(const std::uint8_t index = 0) const; ///@} /// \name Additional motor functions /// These functions allow for motors and motor groups to be used interchangeably ///@{ /** * Gets a vector containing the target position set for the motor by the user * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * * \return A vector containing the target position in its encoder units or PROS_ERR_F if the * operation failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); * std::cout << "Motor Target: " << motor.get_target_position_all()[0]; * // Prints 100 * } * \endcode */ std::vector get_target_position_all(void) const; /** * Gets a vector containing the velocity commanded to the motor by the user * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the commanded motor velocity from +-100, * +-200, or +-600, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor.move_velocity(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * std::cout << "Motor Velocity: " << motor.get_target_velocity_all()[0]; * // Prints the value of E_CONTROLLER_ANALOG_LEFT_Y * pros::delay(2); * } * } * \endcode */ std::vector get_target_velocity_all(void) const; /** * Gets a vector containing the actual velocity commanded of the motor * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's actual velocity in RPM or PROS_ERR_F * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor.move_velocity(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); * std::cout << "Motor Velocity: " << motor.get_actual_velocity_all()[0]; * // Prints the value of E_CONTROLLER_ANALOG_LEFT_Y * pros::delay(2); * } * } * \endcode */ std::vector get_actual_velocity_all(void) const; /** * Gets a vector containing the current drawn by the motor in mA. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A vector containing the motor's current in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Current Draw: " << motor.get_current_draw_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_current_draw_all(void) const; /** * Gets a vector containing the direction of movement for the motor. * * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A vector containing 1 for moving in the positive direction, -1 for moving in the * negative direction, and PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Direction: " << motor.get_direction_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_direction_all(void) const; /** * Gets a vector containing the efficiency of the motor in percent. * * An efficiency of 100% means that the motor is moving electrically while * drawing no electrical power, and an efficiency of 0% means that the motor * is drawing power but not moving. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A vector containing The motor's efficiency in percent or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Efficiency: " << motor.get_efficiency(); * pros::delay(2); * } * } * \endcode */ std::vector get_efficiency_all(void) const; /** * Gets a vector of the faults experienced by the motor. * * Compare this bitfield to the bitmasks in pros::motor_fault_e_t. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \return A bitfield containing the motor's faults. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << motor.get_faults_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_faults_all(void) const; /** * Gets a vector of the flags set by the motor's operation. * * Compare this bitfield to the bitmasks in pros::motor_flag_e_t. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * * \return A bitfield containing the motor's flags. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Faults: " << motor.get_faults_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_flags_all(void) const; /** * Gets a vector containing the absolute position of the motor in its encoder units. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's absolute position in its encoder units or PROS_ERR_F * if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << motor.get_position_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_position_all(void) const; /** * Gets a vector containing the power drawn by the motor in Watts. * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's power draw in Watts or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Power: " << motor.get_power_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_power_all(void) const; /** * Gets a vector of the raw encoder count of the motor at a given timestamp. * * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * \param timestamp * A pointer to a time in milliseconds for which the encoder count * will be returned. If NULL, the timestamp at which the encoder * count was read will not be supplied * * \return A vector containing the raw encoder count at the given timestamp or PROS_ERR if the * operation failed. * * \b Example * \code * void opcontrol() { * std::uint32_t now = pros::millis(); * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Position: " << motor.get_raw_position(&now); * pros::delay(2); * } * } * \endcode */ std::vector get_raw_position_all(std::uint32_t* const timestamp) const; /** * Gets a vector of the temperature of the motor in degrees Celsius. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector contaioning the motor's temperature in degrees Celsius * or PROS_ERR_F if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Temperature: " << motor.get_temperature_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_temperature_all(void) const; /** * Gets a vector of the torque generated by the motor in Newton Meters (Nm). * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's torque in Nm or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Torque: " << motor.get_torque(); * pros::delay(2); * } * } * \endcode */ std::vector get_torque_all(void) const; /** * Gets a vector of the voltage delivered to the motor in millivolts. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * * \return A vector of the motor's voltage in mV or PROS_ERR_F if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Motor Voltage: " << motor.get_voltage_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_voltage_all(void) const; /** * Checks if the motor is drawing over its current limit. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing 1 if the motor's current limit is being exceeded and 0 if the * current limit is not exceeded, or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its current limit?: " << motor.is_over_current_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector is_over_current_all(void) const; /** * Gets the temperature limit flag for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing 1 if the temperature limit is exceeded and 0 if the temperature is * below the limit, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * std::cout << "Is the motor over its temperature limit?: " << motor.is_over_temp_all(); * pros::delay(2); * } * } * \endcode */ std::vector is_over_temp_all(void) const; /** * Gets a vector containing the brake mode that was set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return One of Motor_Brake, according to what was set for the * motor, or E_MOTOR_BRAKE_INVALID if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << motor.get_brake_mode(); * } * \endcode */ std::vector get_brake_mode_all(void) const; /** * Gets a vector containing the current limit for the motor in mA. * * The default value is 2500 mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's current limit in mA or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * while (true) { * std::cout << "Motor Current Limit: " << motor.get_current_limit_all()[0]; * pros::delay(2); * } * } * \endcode */ std::vector get_current_limit_all(void) const; /** * Gets a vector containing the encoder units that were set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing One of Motor_Units according to what is set for the * motor or E_MOTOR_ENCODER_INVALID if the operation failed. * * \b Example * \code * void initialize() { * pros::Motor motor (1, E_MOTOR_GEARSET_06, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Encoder Units: " << motor.get_encoder_units_all()[0]; * } * \endcode */ std::vector get_encoder_units_all(void) const; /** * Gets a vector containing the gearset that was set for the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing one of Motor_Gears according to what is set for the motor, * or pros::Motor_Gears::invalid if the operation failed. * * \b Example * \code * void initialize() { * pros::Motor motor (1, E_MOTOR_GEARSET_06, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Gearing: " << motor.get_gearing_all()[0]; * } * \endcode */ std::vector get_gearing_all(void) const; /** * Gets returns a vector with all the port numbers in the motor group. * * \return A vector containing the signed port of the motor. (negative if the motor is reversed) */ std::vector get_port_all(void) const; /** * Gets a vector of the voltage limit set by the user. * * Default value is 0V, which means that there is no software limitation * imposed on the voltage. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing the motor's voltage limit in V or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * std::cout << "Motor Voltage Limit: " << motor.get_voltage_limit_all()[0]; * } * \endcode */ std::vector get_voltage_limit_all(void) const; /** * Gets a vector containg whether the motor is reversed or not * * \return A vector containing 1 if the motor has been reversed and 0 if the motor was not * reversed, or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * std::cout << "Is the motor reversed? " << motor.is_reversed_all()[0]; * // Prints "0" * } * \endcode */ std::vector is_reversed_all(void) const; /** * Gets a vector containing the type of the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return A vector containing one of MotorType according to the type of the motor, * or pros::MotorType::invalid if the operation failed. * * \b Example * \code * void initialize() { * pros::Motor motor (1, E_MOTOR_GEARSET_06, E_MOTOR_ENCODER_COUNTS); * std::cout << "Motor Type: " << motor.get_type_all()[0]; * } * \endcode */ std::vector get_type_all(void) const; /** * Sets one of Motor_Brake to the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param mode * The Motor_Brake to set for the motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_brake_mode_all(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << motor.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode_all(const MotorBrake mode) const; /** * Sets one of Motor_Brake to the motor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param mode * The Motor_Brake to set for the motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_brake_mode_all(pros::E_MOTOR_BRAKE_HOLD); * std::cout << "Brake Mode: " << motor.get_brake_mode(); * } * \endcode */ std::int32_t set_brake_mode_all(const pros::motor_brake_mode_e_t mode) const; /** * Sets the current limit for the motor in mA. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param limit * The new current limit in mA * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * * motor.set_current_limit_all(1000); * while (true) { * motor = controller_get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will reduce its output at 1000 mA instead of the default 2500 mA * pros::delay(2); * } * } * \endcode */ std::int32_t set_current_limit_all(const std::int32_t limit) const; /** * Sets one of Motor_Units for the motor encoder. Works with the C * enum and the C++ enum class. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * * \param units * The new motor encoder units * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_encoder_units_all(E_MOTOR_ENCODER_DEGREES); * std::cout << "Encoder Units: " << motor.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units_all(const MotorUnits units) const; /** * Sets one of Motor_Units for the motor encoder. Works with the C * enum and the C++ enum class. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param units * The new motor encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_encoder_units_all(E_MOTOR_ENCODER_DEGREES); * std::cout << "Encoder Units: " << motor.get_encoder_units(); * } * \endcode */ std::int32_t set_encoder_units_all(const pros::motor_encoder_units_e_t units) const; /** * Sets one of the gear cartridge (red, green, blue) for the motor. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param gearset * The new motor gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_gearing_all(E_MOTOR_GEARSET_06); * std::cout << "Gearset: " << motor.get_gearing(); * } * \endcode */ std::int32_t set_gearing_all(const MotorGears gearset) const; /** * Sets one of the gear cartridge (red, green, blue) for the motor. Usable with * the C++ enum class and the C enum. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param gearset * The new motor gearset * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_gearing_all(E_MOTOR_GEARSET_06); * std::cout << "Gearset: " << motor.get_gearing(); * } * \endcode */ std::int32_t set_gearing_all(const pros::motor_gearset_e_t gearset) const; /** * Sets the reverse flag for the motor. * * This will invert its movements and the values returned for its position. * * * \param reverse * True reverses the motor, false is default direction * * \return 1 * * \b Example * \code * void initialize() { * pros::Motor motor (1); * motor.set_reversed_all(true); * std::cout << "Is this motor reversed? " << motor.is_reversed(); * } * \endcode */ std::int32_t set_reversed_all(const bool reverse); /** * Sets the voltage limit for the motor in Volts. * * \note This is one of many Motor functions that takes in an optional index parameter. * This parameter can be ignored by most users but exists to give a shared base class * for motors and motor groups * * This function uses the following values of errno when an error state is * reached: * * ENODEV - The port cannot be configured as a motor * * EOVERFLOW - The index is non 0 * * \param limit * The new voltage limit in Volts * * \param index Optional parameter. * The zero-indexed index of the motor to get the target position of. * By default index is 0, and will return an error for a non-zero index * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * pros::Controller master (E_CONTROLLER_MASTER); * * motor.set_voltage_limit_all(10000); * while (true) { * motor = master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y); * // The motor will not output more than 10 V * pros::delay(2); * } * } * \endcode */ std::int32_t set_voltage_limit_all(const std::int32_t limit) const; /** * Sets the position for the motor in its encoder units. * * This will be the future reference point for the motor's "absolute" * position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \param position * The new reference position in its encoder units * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); // Moves 100 units forward * motor.move_absolute(100, 100); // This does not cause a movement * * motor.set_zero_position_all(80); * motor.move_absolute(100, 100); // Moves 20 units forward * } * \endcode * */ std::int32_t set_zero_position_all(const double position) const; /** * Sets the "absolute" zero position of the motor to its current position. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a motor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void autonomous() { * pros::Motor motor (1); * motor.move_absolute(100, 100); // Moves 100 units forward * motor.move_absolute(100, 100); // This does not cause a movement * * motor.tare_position_all(); * motor.move_absolute(100, 100); // Moves 100 units forward * } * \endcode */ std::int32_t tare_position_all(void) const; ///@} private: /** * The port of the motor. Negative ports indicate that the motor is reversed */ std::int8_t _port; }; namespace literals { /** * Constructs a Motor from a literal ending in _mtr * * \return a pros::Motor for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Motor motor = 2_mtr; //Makes an Motor object on port 2 * } * \endcode */ const pros::Motor operator""_mtr(const unsigned long long int m); /** * Constructs a reversed Motor from a literal ending in _rmtr * * \return a pros::Motor for the corresponding port that is reversed * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::motor motor = 2_rmtr; //Makes an reversed Motor object on port 2 * } * \endcode */ const pros::Motor operator""_rmtr(const unsigned long long int m); } // namespace literals } // namespace v5 } // namespace pros #endif // _PROS_MOTORS_HPP_ ================================================ FILE: include/pros/optical.h ================================================ /** * \file pros/optical.h * \ingroup c-optical * * Contains prototypes for functions related to the VEX Optical sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-optical VEX Optical Sensor C API */ #ifndef _PROS_OPTICAL_H_ #define _PROS_OPTICAL_H_ #include #include #include "error.h" #define OPT_GESTURE_ERR (INT8_MAX) #define OPT_COUNT_ERR (INT16_MAX) #define OPT_TIME_ERR PROS_ERR #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif /** * \ingroup c-optical */ /** * \addtogroup c-optical * @{ */ /** * \enum optical_direction_e_t */ typedef enum optical_direction_e { NO_GESTURE = 0, /// The direction indicating an upward gesture. UP = 1, /// The direction indicating a downward gesture. DOWN = 2, /// The direction indicating a rightward gesture. RIGHT = 3, /// The direction indicating a leftward gesture. LEFT = 4, ERROR = PROS_ERR } optical_direction_e_t; /** * \struct optical_rgb_s_t * The RGB and Brightness values for the optical sensor. */ typedef struct optical_rgb_s { double red; double green; double blue; double brightness; } optical_rgb_s_t; /** * \struct optical_raw_s_t * The RGB and clear values for the optical sensor. */ typedef struct optical_raw_s { uint32_t clear; uint32_t red; uint32_t green; uint32_t blue; } optical_raw_s_t; /** * \struct optical_gesture_s_t * This structure contains the raw gesture data. */ typedef struct optical_gesture_s { uint8_t udata; ///Up data uint8_t ddata; ///Down data uint8_t ldata; ///Left data uint8_t rdata; ///Right data uint8_t type; ///Type of gesture uint8_t pad; ///Padding uint16_t count; ///Number of gestures uint32_t time; ///Time since gesture recognized } optical_gesture_s_t; /** * \name Functions * @{ */ /** * Get the detected color hue * * This is not available if gestures are being detected. Hue has a * range of 0 to 359.999 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return hue value if the operation was successful or PROS_ERR_F if the operation * failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * printf("Hue value: %lf \n", optical_get_hue(OPTICAL_PORT)); * delay(20); * } * } * \endcode */ double optical_get_hue(uint8_t port); /** * Get the detected color saturation * * This is not available if gestures are being detected. Saturation has a * range of 0 to 1.0 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return saturation value if the operation was successful or PROS_ERR_F if * the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * printf("Saturation value: %lf \n", optical_get_saturation(OPTICAL_PORT)); * delay(20); * } * } * \endcode */ double optical_get_saturation(uint8_t port); /** * Get the detected color brightness * * This is not available if gestures are being detected. Brightness has a * range of 0 to 1.0 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return brightness value if the operation was successful or PROS_ERR_F if * the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * printf("Brightness value: %lf \n", optical_get_brightness(OPTICAL_PORT)); * delay(20); * } * } * \endcode */ double optical_get_brightness(uint8_t port); /** * Get the detected proximity value * * This is not available if gestures are being detected. proximity has * a range of 0 to 255. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return poximity value if the operation was successful or PROS_ERR if * the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * printf("Proximity value: %d \n", optical_get_proximity(OPTICAL_PORT)); * delay(20); * } * } * \endcode */ int32_t optical_get_proximity(uint8_t port); /** * Set the pwm value of the White LED * * value that ranges from 0 to 100 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * optical_set_led_pwm(OPTICAL_PORT, 50); * delay(20); * } * } * \endcode */ int32_t optical_set_led_pwm(uint8_t port, uint8_t value); /** * Get the pwm value of the White LED * * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return LED pwm value that ranges from 0 to 100 if the operation was * successful or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * printf("PWM Value: %d \n", optical_get_led_pwm(OPTICAL_PORT)); * delay(20); * } * } * \endcode */ int32_t optical_get_led_pwm(uint8_t port); /** * Get the processed RGBC data from the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return rgb value if the operation was successful or an optical_rgb_s_t with * all fields set to PROS_ERR if the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * optical_rgb_s_t RGB_values; * void opcontrol() { * while (true) { * RGB_values = optical_get_rgb(OPTICAL_PORT); * printf("Red value: %lf \n", RGB_values.red); * printf("Green value: %lf \n", RGB_values.green); * printf("Blue value: %lf \n", RGB_values.blue); * printf("Brightness value: %lf \n", RGB_values.brightness); * delay(20); * } * } * \endcode */ optical_rgb_s_t optical_get_rgb(uint8_t port); /** * Get the raw, unprocessed RGBC data from the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return raw rgb value if the operation was successful or an optical_raw_s_t * with all fields set to PROS_ERR if the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * optical_raw_s_t raw_values; * void opcontrol() { * while (true) { * raw_values = optical_get_raw(OPTICAL_PORT); * printf("Red value: %ld \n", raw_values.red); * printf("Green value: %ld \n", raw_values.green); * printf("Blue value: %ld \n", raw_values.blue); * printf("Clear value: %ld \n", raw_values.clear); * delay(20); * } * } * \endcode */ optical_raw_s_t optical_get_raw(uint8_t port); /** * Get the most recent gesture data from the sensor * * Gestures will be cleared after 500mS * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return gesture value if the operation was successful or PROS_ERR if * the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * optical_direction_e_t gesture; * void opcontrol() { * while (true) { * gesture = optical_get_gesture(OPTICAL_PORT); * printf("Gesture value: %d \n", gesture); * delay(20); * } * } * \endcode */ optical_direction_e_t optical_get_gesture(uint8_t port); /** * Get the most recent raw gesture data from the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return gesture value if the operation was successful or an optical_gesture_s_t * with all fields set to PROS_ERR if the operation failed, setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * optical_gesture_s_t raw_gesture; * void opcontrol() { * while (true) { * raw_gesture = optical_get_gesture_raw(OPTICAL_PORT); * printf("Up data: %u \n", raw_gesture.udata); * printf("Down data: %u \n", raw_gesture.ddata); * printf("Left data: %u \n", raw_gesture.ldata); * printf("Right data: %u \n", raw_gesture.rdata); * printf("Type: %u \n", raw_gesture.type); * printf("Count: %u \n", raw_gesture.count); * printf("Time: %lu \n", raw_gesture.time); * delay(20); * } * } * \endcode */ optical_gesture_s_t optical_get_gesture_raw(uint8_t port); /** * Enable gesture detection on the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * optical_enable_gesture(OPTICAL_PORT); * delay(20); * } * } * \endcode */ int32_t optical_enable_gesture(uint8_t port); /** * Disable gesture detection on the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. * * \b Example * \code * #define OPTICAL_PORT 1 * * void opcontrol() { * while (true) { * optical_disable_gesture(OPTICAL_PORT); * delay(20); * } * } * \endcode */ int32_t optical_disable_gesture(uint8_t port); /** * Get integration time (update rate) of the optical sensor in milliseconds, with * minimum time being * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \return Integration time in milliseconds if the operation is successful * or PROS_ERR_F if the operation failed, setting errno. */ double optical_get_integration_time(uint8_t port); /** * Set integration time (update rate) of the optical sensor in milliseconds. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 Optical Sensor port number from 1-21 * \param time * The desired integration time in milliseconds * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. */ int32_t optical_set_integration_time(uint8_t port, double time); ///@} ///@} #ifdef __cplusplus } } } #endif #endif ================================================ FILE: include/pros/optical.hpp ================================================ /** * \file pros/optical.hpp * \ingroup cpp-optical * * Contains prototypes for functions related to the VEX Optical sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-optical VEX Optical Sensor C++ API */ #ifndef _PROS_OPTICAL_HPP_ #define _PROS_OPTICAL_HPP_ #include #include #include #include "pros/device.hpp" #include "pros/optical.h" namespace pros { inline namespace v5 { /** * \ingroup cpp-optical */ class Optical : public Device { /** * \addtogroup cpp-optical * @{ */ public: /** * Creates an Optical Sensor object for the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param port * The V5 port number from 1-21 * * \b Example: * \code{.cpp} * pros::Optical optical(1); * \endcode */ Optical(const std::uint8_t port); Optical(const Device& device) : Optical(device.get_port()){}; /** * Gets all optical sensors. * * \return A vector of Optical sensor objects. * * \b Example * \code * void opcontrol() { * std::vector optical_all = pros::Optical::get_all_devices(); // All optical sensors that are connected * } * \endcode */ static std::vector get_all_devices(); /** * Get the detected color hue * * This is not available if gestures are being detected. Hue has a * range of 0 to 359.999 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return hue value if the operation was successful or PROS_ERR_F if the operation * failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * std::cout << "Hue: " << optical.get_hue() << std::endl; * } * \endcode */ virtual double get_hue(); /** * Get the detected color saturation * * This is not available if gestures are being detected. Saturation has a * range of 0 to 1.0 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return saturation value if the operation was successful or PROS_ERR_F if * the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * std::cout << "Saturation: " << optical.get_saturation() << std::endl; * } * \endcode */ virtual double get_saturation(); /** * Get the detected color brightness * * This is not available if gestures are being detected. Brightness has a * range of 0 to 1.0 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return brightness value if the operation was successful or PROS_ERR_F if * the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * std::cout << "Brightness: " << optical.get_brightness() << std::endl; * } * \endcode */ virtual double get_brightness(); /** * Get the detected proximity value * * This is not available if gestures are being detected. proximity has * a range of 0 to 255. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return Proximity value if the operation was successful or PROS_ERR if * the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * std::cout << "Proximity: " << optical.get_proximity() << std::endl; * } * \endcode */ virtual std::int32_t get_proximity(); /** * Set the pwm value of the White LED on the sensor * * value that ranges from 0 to 100 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return The Error code encountered or PROS_SUCCESS. * * \b Example: * \code{.cpp} * void initialize() { * pros::Optical optical(1); * optical.set_led_pwm(100); * } * \endcode */ virtual std::int32_t set_led_pwm(uint8_t value); /** * Get the pwm value of the White LED on the sensor * * value that ranges from 0 to 100 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return LED pwm value if the operation was successful or PROS_ERR if * the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * optical.set_led_pwm(100); * std::cout << "LED PWM: " << optical.get_led_pwm() << std::endl; * } * \endcode */ virtual std::int32_t get_led_pwm(); /** * Get the processed RGBC data from the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return rgb value if the operation was successful or an optical_rgb_s_t * with all fields set to PROS_ERR if the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * pros::c::optical_rgb_s_t rgb = optical.get_rgb(); * while(1) { * std::cout << "Red: " << rgb.red << std::endl; * std::cout << "Green: " << rgb.green << std::endl; * std::cout << "Blue: " << rgb.blue << std::endl; * std::cout << "Brightness: " << rgb.brightness << std::endl; * pros::delay(20); * } * } * \endcode */ virtual pros::c::optical_rgb_s_t get_rgb(); /** * Get the raw un-processed RGBC data from the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return raw rgb value if the operation was successful or an optical_raw_s_t * with all fields set to PROS_ERR if the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * pros::c::optical_raw_s_t raw = optical.get_raw(); * while (1) { * std::cout << "Red: " << raw.red << std::endl; * std::cout << "Green: " << raw.green << std::endl; * std::cout << "Blue: " << raw.blue << std::endl; * std::cout << "Clear: " << raw.clear << std::endl; * pros::delay(20); * } * } * \endcode */ virtual pros::c::optical_raw_s_t get_raw(); /** * Get the most recent gesture data from the sensor * * Gestures will be cleared after 500mS * * * 0 = no gesture, * 1 = up (towards cable), * 2 = down, * 3 = right, * 4 = left * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return gesture value if the operation was successful or PROS_ERR if * the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * while(1) { * std::cout << "Gesture: " << optical.get_gesture() << std::endl; * pros::delay(20); * } * } * \endcode */ virtual pros::c::optical_direction_e_t get_gesture(); /** * Get the most recent raw gesture data from the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return gesture value if the operation was successful or an optical_gesture_s_t * with all fields set to PROS_ERR if the operation failed, setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * optical.enable_gesture(); * while(1) { * pros::c::optical_gesture_s_t gesture = optical.get_gesture_raw(); * std::cout << "Gesture raw data: " << std::endl; * std::cout << "Up data: " << gesture.udata << std::endl; * std::cout << "Down data: " << gesture.ddata << std::endl; * std::cout << "Left data: " << gesture.ldata << std::endl; * std::cout << "Right data: " << gesture.rdata << std::endl; * std::cout << "Type: " << gesture.type << std::endl; * std::cout << "Count: " << gesture.count << std::endl; * std::cout << "Time: " << gesture.time << std::endl; * pros::delay(20); * } * } * \endcode */ virtual pros::c::optical_gesture_s_t get_gesture_raw(); /** * Enable gesture detection on the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * optical.enable_gesture(); * while(1) { * pros::c::optical_gesture_s_t gesture = optical.get_gesture_raw(); * std::cout << "Gesture raw data: " << std::endl; * std::cout << "Up data: " << gesture.udata << std::endl; * std::cout << "Down data: " << gesture.ddata << std::endl; * std::cout << "Left data: " << gesture.ldata << std::endl; * std::cout << "Right data: " << gesture.rdata << std::endl; * std::cout << "Type: " << gesture.type << std::endl; * std::cout << "Count: " << gesture.count << std::endl; * std::cout << "Time: " << gesture.time << std::endl; * pros::delay(20); * } * } * \endcode */ virtual std::int32_t enable_gesture(); /** * Disable gesture detection on the sensor * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code{.cpp} * void opcontrol() { * pros::Optical optical(1); * optical.enable_gesture(); * while(1) { * if(optical.get_gesture() != 0) { * std::cout << "Gesture detected!"<< std::endl; * optical.disable_gesture(); * } * pros::delay(20); * } * } * \endcode */ virtual std::int32_t disable_gesture(); /** * Get integration time (update rate) of the optical sensor in milliseconds. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \return Integration time in milliseconds if the operation is successful * or PROS_ERR_F if the operation failed, setting errno. */ double get_integration_time(); /** * Set integration time (update rate) of the optical sensor in milliseconds, with * minimum time being 3 ms and maximum time being 712 ms. Default is 100 ms, with the * optical sensor communciating with the V5 brain every 20 ms. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Optical Sensor * * \param time The desired integration time in milliseconds * \return 1 if the operation is successful or PROS_ERR if the operation failed, * setting errno. */ std::int32_t set_integration_time(double time); /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * Optical [port: (port number), hue: (hue), saturation: (saturation), * brightness: (brightness), proximity: (proximity), rgb: {red, green, blue}] * * \b Example: * \code{.cpp} * pros::Optical optical(1); * std::cout << optical << std::endl; * \endcode */ friend std::ostream& operator<<(std::ostream& os, pros::Optical& optical); private: ///@} }; namespace literals { /** * Constructs a Optical sensor from a literal ending in _opt * * \return a pros::Optical for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Optical opt = 2_opt; //Makes an Optical object on port 2 * } * \endcode */ const pros::Optical operator""_opt(const unsigned long long int o); } // namespace literals } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/rotation.h ================================================ /** * \file pros/rotation.h * \ingroup c-rotation * * Contains prototypes for functions related to the VEX Rotation Sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-rotation VEX Rotation Sensor C API */ #ifndef _PROS_ROTATION_H_ #define _PROS_ROTATION_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif /** * \ingroup c-rotation */ /** * \addtogroup c-rotation * @{ */ #define ROTATION_MINIMUM_DATA_RATE 5 /** * Reset Rotation Sensor * * Reset the current absolute position to be the same as the * Rotation Sensor angle. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_reset(ROTATION_PORT); * } * delay(20); * } * } * \endcode */ int32_t rotation_reset(uint8_t port); /** * Set the Rotation Sensor's refresh interval in milliseconds. * * The rate may be specified in increments of 5ms, and will be rounded down to * the nearest increment. The minimum allowable refresh rate is 5ms. The default * rate is 10ms. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \param rate The data refresh interval in milliseconds * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void initialize() { * pros::Rotation rotation_sensor(ROTATION_PORT); * rotation_set_data_rate(ROTATION_PORT, 5); * } * \endcode */ int32_t rotation_set_data_rate(uint8_t port, uint32_t rate); /** * Set the Rotation Sensor position reading to a desired rotation value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \param position * The position in terms of ticks * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_set_position(ROTATION_PORT, 600); * } * delay(20); * } * } * \endcode */ int32_t rotation_set_position(uint8_t port, int32_t position); /** * Reset the Rotation Sensor position to 0 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_reset_position(ROTATION_PORT); * } * delay(20); * } * } * \endcode */ int32_t rotation_reset_position(uint8_t port); /** * Get the Rotation Sensor's current position in centidegrees * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \return The position value or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * while (true) { * printf("Position: %d centidegrees \n", rotation_get_position(ROTATION_PORT)); * delay(20); * } * } * \endcode */ int32_t rotation_get_position(uint8_t port); /** * Get the Rotation Sensor's current velocity in centidegrees per second * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \return The velocity value or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * while (true) { * printf("Velocity: %d centidegrees per second \n", rotation_get_velocity(ROTATION_PORT)); * delay(20); * } * } * \endcode */ int32_t rotation_get_velocity(uint8_t port); /** * Get the Rotation Sensor's current angle in centidegrees (0-36000) * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \return The angle value (0-36000) or PROS_ERR_F if the operation failed, setting * errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * while (true) { * printf("Angle: %d centidegrees \n", rotation_get_angle(ROTATION_PORT)); * delay(20); * } * } * \endcode */ int32_t rotation_get_angle(uint8_t port); /** * Set the Rotation Sensor's direction reversed flag * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \param value * Determines if the direction of the Rotation Sensor is reversed or not. * * \return 1 if operation succeeded or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * Rotation rotation_sensor(ROTATION_PORT); * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_set_reversed(ROTATION_PORT, true); // Reverses the Rotation Sensor on ROTATION_PORT * } * delay(20); * } * } * \endcode */ int32_t rotation_set_reversed(uint8_t port, bool value); /** * Reverse the Rotation Sensor's direction * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * Rotation rotation_sensor(ROTATION_PORT); * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_reverse(ROTATION_PORT); * } * delay(20); * } * } * \endcode */ int32_t rotation_reverse(uint8_t port); /** * Initialize the Rotation Sensor with a reverse flag * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \param reverse_flag * Determines if the Rotation Sensor is reversed or not. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * Rotation rotation_sensor(ROTATION_PORT); * bool reverse_flag = true; * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_init_reverse(ROTATION_PORT, reverse_flag); * } * delay(20); * } * } * \endcode */ int32_t rotation_init_reverse(uint8_t port, bool reverse_flag); /** * Get the Rotation Sensor's reversed flag * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * * \return Boolean value of if the Rotation Sensor's direction is reversed or not * or PROS_ERR if the operation failed, setting errno. * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * Rotation rotation_sensor(ROTATION_PORT); * while (true) { * * if(controller_get_digital(CONTROLLER_MASTER, E_CONTROLLER_DIGITAL_X)){ * rotation_get_reversed(ROTATION_PORT); * } * delay(20); * } * } * \endcode */ int32_t rotation_get_reversed(uint8_t port); ///@} #ifdef __cplusplus } //namespace C } //namespace pros } //extern "C" #endif #endif ================================================ FILE: include/pros/rotation.hpp ================================================ /** * \file pros/rotation.hpp * \ingroup cpp-rotation * * Contains prototypes for functions related to the VEX Rotation Sensor. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-rotation VEX Rotation Sensor C++ API */ #ifndef _PROS_ROTATION_HPP_ #define _PROS_ROTATION_HPP_ #include #include #include "pros/device.hpp" #include "pros/rotation.h" namespace pros { inline namespace v5 { /** * \ingroup cpp-rotation */ class Rotation : public Device { /** * \addtogroup cpp-rotation * @{ */ public: /** * Constructs a new Rotation Sensor object * * ENXIO - The given value is not within the range of V5 ports |1-21|. * ENODEV - The port cannot be configured as a Rotation Sensor * * \param port * The V5 port number from 1 to 21, or from -21 to -1 for reversed Rotation Sensors. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); //Creates a Rotation Sensor on port 1 * pros::Rotation reversed_rotation_sensor(-2); //Creates a reversed Rotation Sensor on port 2 * } * \endcode */ Rotation(const std::int8_t port); Rotation(const Device& device) : Rotation(device.get_port()){}; /** * Reset the Rotation Sensor * * Reset the current absolute position to be the same as the * Rotation Sensor angle. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * if(master.get_analog(E_CONTROLLER_DIGITAL_X) { * rotation_sensor.reset(); * } * pros::delay(20); * } * } * \endcode */ virtual std::int32_t reset(); /** * Set the Rotation Sensor's refresh interval in milliseconds. * * The rate may be specified in increments of 5ms, and will be rounded down to * the nearest increment. The minimum allowable refresh rate is 5ms. The default * rate is 10ms. * * As values are copied into the shared memory buffer only at 10ms intervals, * setting this value to less than 10ms does not mean that you can poll the * sensor's values any faster. However, it will guarantee that the data is as * recent as possible. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param rate The data refresh interval in milliseconds * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Rotation rotation_sensor(1); * rotation_sensor.set_data_rate(5); * } * \endcode */ virtual std::int32_t set_data_rate(std::uint32_t rate) const; /** * Set the Rotation Sensor position reading to a desired rotation value * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param position * The position in terms of ticks * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * if(master.get_analog(E_CONTROLLER_DIGITAL_X) { * rotation_sensor.set_position(600); * } * pros::delay(20); * } * } * \endcode */ virtual std::int32_t set_position(std::int32_t position) const; /** * Reset the Rotation Sensor position to 0 * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param position * The position in terms of ticks * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * if(master.get_analog(E_CONTROLLER_DIGITAL_X) { * rotation_sensor.reset_position(); * } * pros::delay(20); * } * } * \endcode */ virtual std::int32_t reset_position(void) const; /** * Gets all rotation sensors. * * \return A vector of Rotation sensor objects. * * \b Example * \code * void opcontrol() { * std::vector rotation_all = pros::Rotation::get_all_devices(); // All rotation sensors that are connected * } * \endcode */ static std::vector get_all_devices(); /** * Get the Rotation Sensor's current position in centidegrees * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \return The position value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * while (true) { * printf("Position: %d Ticks \n", rotation_sensor.get_position()); * delay(20); * } * } * \endcode */ virtual std::int32_t get_position() const; /** * Get the Rotation Sensor's current velocity in centidegrees per second * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param port * The V5 Rotation Sensor port number from 1-21 * \return The velocity value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * while (true) { * printf("Velocity: %d centidegrees per second \n", rotation_sensor.get_velocity)); * delay(20); * } * } * \endcode */ virtual std::int32_t get_velocity() const; /** * Get the Rotation Sensor's current position in centidegrees * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \return The angle value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * while (true) { * printf("Angle: %d centidegrees \n", rotation_sensor.get_angle()); * delay(20); * } * } * \endcode */ virtual std::int32_t get_angle() const; /** * Set the Rotation Sensor's direction reversed flag * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \param value * Determines if the direction of the rotational sensor is * reversed or not. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * if(master.get_analog(E_CONTROLLER_DIGITAL_X) { * rotation_sensor.set_reversed(true); // Reverses the Rotation Sensor * } * pros::delay(20); * } * } * \endcode */ virtual std::int32_t set_reversed(bool value) const; /** * Reverse the Rotation Sensor's direction. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * pros::Controller master (E_CONTROLLER_MASTER); * while (true) { * if(master.get_analog(E_CONTROLLER_DIGITAL_X) { * rotation_sensor.reverse(); * } * pros::delay(20); * } * } * \endcode */ virtual std::int32_t reverse() const; /** * Get the Rotation Sensor's reversed flag * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as an Rotation Sensor * * \return Reversed value or PROS_ERR if the operation failed, setting * errno. * * \b Example * \code * void opcontrol() { * pros::Rotation rotation_sensor(1); * while (true) { * printf("Reversed: %d \n", rotation_sensor.get_reversed()); * delay(20); * } * } * \endcode */ virtual std::int32_t get_reversed() const; /** * This is the overload for the << operator for printing to streams * * Prints in format(this below is all in one line with no new line): * Rotation [port: rotation._port, position: (rotation position), velocity: (rotation velocity), * angle: (rotation angle), reversed: (reversed boolean)] * * \b Example * \code * #define ROTATION_PORT 1 * * void opcontrol() { * pros::Rotation rotation_sensor(1); * while(true) { * std::cout << rotation_sensor << std::endl; * pros::delay(20); * } * } * \endcode */ friend std::ostream& operator<<(std::ostream& os, const pros::Rotation& rotation); ///@} }; namespace literals { /** * Constructs a Rotation sensor from a literal ending in _rot * * \return a pros::Rotation for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Rotation rotation = 2_rot; //Makes an Motor object on port 2 * } * \endcode */ const pros::Rotation operator""_rot(const unsigned long long int r); } // namespace literals } // namespace v5 } // namespace pros #endif ================================================ FILE: include/pros/rtos.h ================================================ /** * \file pros/rtos.h * \ingroup c-rtos * * Contains declarations for the PROS RTOS kernel for use by typical VEX * programmers. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-rtos RTOS Facilities C API * \note Additional example code for this module can be found in its [Tutorial.](@ref multitasking) */ #ifndef _PROS_RTOS_H_ #define _PROS_RTOS_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { #endif /// \ingroup c-rtos /// \addtogroup c-rtos /// @{ /// \name Macros /// @{ /** * The highest priority that can be assigned to a task. * * A task with this priority will always run if it is available to. Beware of * deadlocks when using this priority. */ #define TASK_PRIORITY_MAX 16 /** * The lowest priority that can be assigned to a task. * * This can cause severe performance problems and is generally not recommended * that users use this priority. */ #define TASK_PRIORITY_MIN 1 /** * The default task priority, which should be used for most tasks unless you * have a specific need for a higher or lower priority task. * * The default tasks, such as autonomous(), are run with this priority */ #define TASK_PRIORITY_DEFAULT 8 /** * The recommended stack size for a new task. * * This stack size is used for the default tasks such as autonomous(). This * size is 8,192 words, or 32,768 bytes. This should be enough for the majority * of tasks */ #define TASK_STACK_DEPTH_DEFAULT 0x2000 /** * The minimal stack size for a task. * * This equates to 512 words, or 2,048 bytes. */ #define TASK_STACK_DEPTH_MIN 0x200 /** * The maximum number of characters allowed in a task's name. */ #define TASK_NAME_MAX_LEN 32 /** * The maximum timeout value that can be given to, for instance, a mutex grab. */ #define TIMEOUT_MAX ((uint32_t)0xffffffffUL) /// @} Name: Macros /// \name Typedefs /// @{ /** * An opaque type that points to a task handle. This is used for referencing a * task. */ typedef void* task_t; /** * A pointer to a task's function. * * Such a function is called when a task starts, and exiting said function will * terminate the task. */ typedef void (*task_fn_t)(void*); /// @} Name: Typedefs /// \name Enumerations /// @{ /** * The state of a task. */ typedef enum { E_TASK_STATE_RUNNING = 0, /**< The task is actively executing. */ E_TASK_STATE_READY, /**< The task exists and is available to run, but is not currently running. */ E_TASK_STATE_BLOCKED, /**< The task is delayed or blocked by a mutex, semaphore, or I/O operation. */ E_TASK_STATE_SUSPENDED, /**< The task is supended using task_suspend. */ E_TASK_STATE_DELETED, /**< The task has been deleted using task_delete. */ E_TASK_STATE_INVALID /**< The task handle does not point to a current or past task.*/ } task_state_e_t; /** * brief The action to take when a task is notified. */ typedef enum { E_NOTIFY_ACTION_NONE, /**< The task’s notification value will not be touched.*/ E_NOTIFY_ACTION_BITS, /**< The task’s notification value will be bitwise ORed with the new value.*/ E_NOTIFY_ACTION_INCR, /**< The task’s notification value will be incremented by one, effectively using it as a notification counter.*/ E_NOTIFY_ACTION_OWRITE, /**< The task’s notification value will be unconditionally set to the new value.*/ E_NOTIFY_ACTION_NO_OWRITE /**< The task’s notification value will be set to the new value if the task does not already have a pending notification.*/ } notify_action_e_t; /// @} Name: Enumerations /// \name Simple enum names /// @{ #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define TASK_STATE_RUNNING pros::E_TASK_STATE_RUNNING #define TASK_STATE_READY pros::E_TASK_STATE_READY #define TASK_STATE_BLOCKED pros::E_TASK_STATE_BLOCKED #define TASK_STATE_SUSPENDED pros::E_TASK_STATE_SUSPENDED #define TASK_STATE_DELETED pros::E_TASK_STATE_DELETED #define TASK_STATE_INVALID pros::E_TASK_STATE_INVALID #define NOTIFY_ACTION_NONE pros::E_NOTIFY_ACTION_NONE #define NOTIFY_ACTION_BITS pros::E_NOTIFY_ACTION_BITS #define NOTIFY_ACTION_INCR pros::E_NOTIFY_ACTION_INCR #define NOTIFY_ACTION_OWRITE pros::E_NOTIFY_ACTION_OWRITE #define NOTIFY_ACTION_NO_OWRITE pros::E_NOTIFY_ACTION_NO_OWRITE #else #define TASK_STATE_RUNNING E_TASK_STATE_RUNNING #define TASK_STATE_READY E_TASK_STATE_READY #define TASK_STATE_BLOCKED E_TASK_STATE_BLOCKED #define TASK_STATE_SUSPENDED E_TASK_STATE_SUSPENDED #define TASK_STATE_DELETED E_TASK_STATE_DELETED #define TASK_STATE_INVALID E_TASK_STATE_INVALID #define NOTIFY_ACTION_NONE E_NOTIFY_ACTION_NONE #define NOTIFY_ACTION_BITS E_NOTIFY_ACTION_BITS #define NOTIFY_ACTION_INCR E_NOTIFY_ACTION_INCR #define NOTIFY_ACTION_OWRITE E_NOTIFY_ACTION_OWRITE #define NOTIFY_ACTION_NO_OWRITE E_NOTIFY_ACTION_NO_OWRITE #endif #endif /// @} Name: Simple enum names /// \name Typedefs /** * A [mutex.](@ref multitasking) * * A mutex is a synchronization object that can be used to protect a shared * resource from being accessed by multiple tasks at the same time. A mutex can * be claimed by a task, which will prevent other tasks from claiming it until * that task releases it. */ typedef void* mutex_t; /// @} Name: Typedefs /** * The task handle of the currently running task. */ #ifdef __cplusplus #define CURRENT_TASK ((pros::task_t)NULL) #else #define CURRENT_TASK ((task_t)NULL) #endif /// @} (add to group: c-rtos) #ifdef __cplusplus namespace c { #endif /// \ingroup c-rtos /// \addtogroup c-rtos /// @{ /** * Gets the number of milliseconds since PROS initialized. * * \return The number of milliseconds since PROS initialized * * \b Example * \code * void opcontrol() { * uint32_t now = millis(); * while (true) { * // Do opcontrol things * task_delay_until(&now, 2); * } * } * \endcode */ uint32_t millis(void); /** * Gets the number of microseconds since PROS initialized, * * \return The number of microseconds since PROS initialized * * \b Example * \code * void opcontrol() { * uint64_t now = micros(); * while (true) { * // Do opcontrol things * task_delay_until(&now, 2000); * } * } * \endcode */ uint64_t micros(void); /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Pointer to the task entry function * \param parameters * Pointer to memory that will be used as a parameter for the task being * created. This memory should not typically come from stack, but rather * from dynamically (i.e., malloc'd) or statically allocated memory. * \param prio * The priority at which the task should run. * TASK_PRIO_DEFAULT plus/minus 1 or 2 is typically used. * \param stack_depth * The number of words (i.e. 4 * stack_depth) available on the task's * stack. TASK_STACK_DEPTH_DEFAULT is typically sufficienct. * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \return A handle by which the newly created task can be referenced. If an * error occurred, NULL will be returned and errno can be checked for hints as * to why task_create failed. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * } * \endcode */ task_t task_create(task_fn_t function, void* const parameters, uint32_t prio, const uint16_t stack_depth, const char* const name); /** * Removes a task from the RTOS real time kernel's management. The task being * deleted will be removed from all ready, blocked, suspended and event lists. * * Memory dynamically allocated by the task is not automatically freed, and * should be freed before the task is deleted. * * \param task * The handle of the task to be deleted. Passing NULL will cause the * calling task to be deleted. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * // Do other things * task_delete(my_task); * } * \endcode */ void task_delete(task_t task); /** * Delays the current task for a given number of milliseconds. * * This is not the best method to have a task execute code at predefined * intervals, as the delay time is measured from when the delay is requested. * To delay cyclically, use task_delay_until(). * * \param milliseconds * The number of milliseconds to wait (1000 milliseconds per second) * * \b Example * \code * void opcontrol() { * while (true) { * // Do opcontrol things * task_delay(2); * } * } * \endcode */ void task_delay(const uint32_t milliseconds); /** * Delays the current task for a given number of milliseconds. * * This is not the best method to have a task execute code at predefined * intervals, as the delay time is measured from when the delay is requested. * To delay cyclically, use task_delay_until(). * * \param milliseconds * The number of milliseconds to wait (1000 milliseconds per second) * * \b Example * \code * void opcontrol() { * while (true) { * // Do opcontrol things * delay(2); * } * } * \endcode */ void delay(const uint32_t milliseconds); /** * Delays the current task until a specified time. This function can be used * by periodic tasks to ensure a constant execution frequency. * * The task will be woken up at the time *prev_time + delta, and *prev_time will * be updated to reflect the time at which the task will unblock. * * \param prev_time * A pointer to the location storing the setpoint time. This should * typically be initialized to the return value of millis(). * \param delta * The number of milliseconds to wait (1000 milliseconds per second) * * \b Example * \code * void opcontrol() { * uint32_t now = millis(); * while (true) { * // Do opcontrol things * task_delay_until(&now, 2); * } * } * \endcode */ void task_delay_until(uint32_t* const prev_time, const uint32_t delta); /** * Gets the priority of the specified task. * * \param task * The task to check * * \return The priority of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * printf("Task Priority: %d\n", task_get_priority(my_task)); * } * \endcode */ uint32_t task_get_priority(task_t task); /** * Sets the priority of the specified task. * * If the specified task's state is available to be scheduled (e.g. not blocked) * and new priority is higher than the currently running task, a context switch * may occur. * * \param task * The task to set * \param prio * The new priority of the task * * \b Example * \code * void my_task_fn(void* ign) { * // Do things * } * * void opcontrol() { * task_t my_task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "Example Task"); * task_set_priority(my_task, TASK_PRIORITY_DEFAULT + 1); * } * \endcode */ void task_set_priority(task_t task, uint32_t prio); /** * Gets the state of the specified task. * * \param task * The task to check * * \return The state of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * printf("Task's State: %d\n", task_get_state(my_task)); * } * \endcode */ task_state_e_t task_get_state(task_t task); /** * Suspends the specified task, making it ineligible to be scheduled. * * \param task * The task to suspend * * \b Example * \code * mutex_t counter_mutex; * int counter = 0; * * void my_task_fn(void* param) { * while(true) { * mutex_take(counter_mutex, TIMEOUT_MAX);// Mutexes are used for protecting shared resources * counter++; * mutex_give(counter_mutex); * pros::delay(10); * } * } * * void opcontrol() { * task_t task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT,; * * while(true) { * mutex_take(counter_mutex, TIMEOUT_MAX); * if(counter > 100) { * task_suspepend(task); * } * mutex_give(counter_mutex); * pros::delay(10); * } * } * \endcode */ void task_suspend(task_t task); /** * Resumes the specified task, making it eligible to be scheduled. * * \param task * The task to resume * * \b Example * \code * void my_task_fn(void* param) { * while(true) { * // Do stuff * delay(10); * } * } * * task_t task; * * void initialize() { * task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * } * * void autonomous() { * task_resume(task); * * // Run autonomous , then suspend the task so it doesn't interfere run * * // outside of autonomous or opcontrol * task_suspend(task); * } * * void opcontrol() { * task_resume(task); * // Opctonrol code here * task_suspend(task); * } * * \endcode */ void task_resume(task_t task); /** * Gets the number of tasks the kernel is currently managing, including all * ready, blocked, or suspended tasks. A task that has been deleted, but not yet * reaped by the idle task will also be included in the count. Tasks recently * created may take one context switch to be counted. * * \return The number of tasks that are currently being managed by the kernel. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * printf("Number of Running Tasks: %d\n", task_get_count()); * } * \endcode */ uint32_t task_get_count(void); /** * Gets the name of the specified task. * * \param task * The task to check * * \return A pointer to the name of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * printf("Task Name: %d\n", task_get_name(my_task)); * } * \endcode */ char* task_get_name(task_t task); /** * Gets a task handle from the specified name * * The operation takes a relatively long time and should be used sparingly. * * \param name * The name to query * * \return A task handle with a matching name, or NULL if none were found. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * // Do other things * task_delete(task_get_by_name("My Task")); * } * \endcode */ task_t task_get_by_name(const char* name); /** * Get the currently running task handle. This could be useful if a task * wants to tell another task about itself. * * \return The currently running task handle. * * \b Example * \code * void my_task_fn(void* param) { * task_t this_task = task_get_current(); * if (task_get_state(this_take) == E_TASK_STATE_RUNNING) { * printf("This task is currently running\n"); * } * // ... * } * * void initialize() { * task_t my_task = task_create(my_task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * } * \endcode */ task_t task_get_current(); /** * Sends a simple notification to task and increments the notification counter. * * \param task * The task to notify * * \return Always returns true. * * \b Example * \code * void my_task_fn(void* ign) { * while(task_notify_take(true) == 0) { * // Code while waiting * } * puts("I was unblocked!"); * } * * void opcontrol() { * task_t my_task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "Notify me! Task"); * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task_notify(my_task); * } * } * } * \endcode */ uint32_t task_notify(task_t task); /** * * Utilizes task notifications to wait until specified task is complete and deleted, * then continues to execute the program. Analogous to std::thread::join in C++. * * \param task * The handle of the task to wait on. * * \return void * * \b Example * \code * void my_task_fn(void* ign) { * lcd_print(1, "%s running", task_get_name(NULL)); * task_delay(1000); * lcd_print(2, "End of %s", task_get_name(NULL)); * } * * void opcontrol() { * task_t my_task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "Example Task"); * lcd_set_text(0, "Running task."); * task_join(my_task); * lcd_set_text(3, "Task completed."); * } * \endcode */ void task_join(task_t task); /** * Sends a notification to a task, optionally performing some action. Will also * retrieve the value of the notification in the target task before modifying * the notification value. * * \param task * The task to notify * \param value * The value used in performing the action * \param action * An action to optionally perform on the receiving task's notification * value * \param prev_value * A pointer to store the previous value of the target task's * notification, may be NULL * * \return Dependent on the notification action. * For NOTIFY_ACTION_NO_WRITE: return 0 if the value could be written without * needing to overwrite, 1 otherwise. * For all other NOTIFY_ACTION values: always return 0 * * \b Example * \code * void my_task_fn(void* param) { * while(true) { * // Wait until we have been notified 20 times before running the code * if(task_notify_take(false, TIMEOUT_MAX) == 20) { * // ... Code to do stuff here ... * * // Reset the notification counter * task_notify_take(true, TIMEOUT_MAX); * } * delay(10); * } * } * * void opcontrol() { * task_t task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * * int count = 0; * * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task_notify_ext(task, 1, NOTIFY_ACTION_INCREMENT, &count); * } * * delay(20); * } * } * \endcode */ uint32_t task_notify_ext(task_t task, uint32_t value, notify_action_e_t action, uint32_t* prev_value); /** * Waits for a notification to be nonzero. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \param clear_on_exit * If true (1), then the notification value is cleared. * If false (0), then the notification value is decremented. * \param timeout * Specifies the amount of time to be spent waiting for a notification * to occur. * * \return The value of the task's notification value before it is decremented * or cleared * * \b Example * \code * void my_task_fn(void* ign) { * task_t current_task = task_get_current(); * while(task_notify_take(current_task, true, TIMEOUT_MAX)) { * puts("I was unblocked!"); * } * } * * void opcontrol() { * task_t my_task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "Notify me! Task"); * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task_notify(my_task); * } * } * } * \endcode */ uint32_t task_notify_take(bool clear_on_exit, uint32_t timeout); /** * Clears the notification for a task. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \param task * The task to clear * * \return False if there was not a notification waiting, true if there was * * \b Example * \code * void my_task_fn(void* param) { * task_t task = task_get_current(); * while(true) { * printf("Waiting for notification...\n"); * printf("Got a notification: %d\n", task_notify_take(task, false, TIMEOUT_MAX)); * * task_notify_clear(task); * delay(10): * } * } * * void opcontrol() { * task_t task = task_create(my_task_fn, NULL, TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "My Task"); * * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task_notify(task); * } * delay(10); * } * } * \endcode */ bool task_notify_clear(task_t task); /** * Creates a mutex. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \return A handle to a newly created mutex. If an error occurred, NULL will be * returned and errno can be checked for hints as to why mutex_create failed. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * mutex_t odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * mutex_take(odom_mutex, MAX_DELAY); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * mutex_give(odom_mutex); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * mutex_take(odom_mutex, MAX_DELAY); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * mutex_give(odom_mutex); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * mutex_take(odom_mutex, MAX_DELAY); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * mutex_give(odom_mutex); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = mutex_create(); * * task_create(odom_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Odometry Task"); * task_create(chassis_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Chassis Task"); * } * \endcode */ mutex_t mutex_create(void); /** * Takes and locks a mutex, waiting for up to a certain number of milliseconds * before timing out. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \param mutex * Mutex to attempt to lock. * \param timeout * Time to wait before the mutex becomes available. A timeout of 0 can * be used to poll the mutex. TIMEOUT_MAX can be used to block * indefinitely. * * \return True if the mutex was successfully taken, false otherwise. If false * is returned, then errno is set with a hint about why the the mutex * couldn't be taken. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * mutex_t odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * mutex_take(odom_mutex, MAX_DELAY); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * mutex_give(odom_mutex); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * mutex_take(odom_mutex, MAX_DELAY); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * mutex_give(odom_mutex); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * mutex_take(odom_mutex, MAX_DELAY); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * mutex_give(odom_mutex); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = mutex_create(); * * task_create(odom_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Odometry Task"); * task_create(chassis_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Chassis Task"); * } * \endcode */ bool mutex_take(mutex_t mutex, uint32_t timeout); /** * Unlocks a mutex. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \param mutex * Mutex to unlock. * * \return True if the mutex was successfully returned, false otherwise. If * false is returned, then errno is set with a hint about why the mutex * couldn't be returned. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * mutex_t odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * mutex_take(odom_mutex, MAX_DELAY); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * mutex_give(odom_mutex); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * mutex_take(odom_mutex, MAX_DELAY); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * mutex_give(odom_mutex); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * mutex_take(odom_mutex, MAX_DELAY); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * mutex_give(odom_mutex); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = mutex_create(); * * task_create(odom_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Odometry Task"); * task_create(chassis_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Chassis Task"); * } * \endcode */ bool mutex_give(mutex_t mutex); /** * Creates a recursive mutex which can be locked recursively by the owner. * * \return A newly created recursive mutex. * * \b Example: * \code * mutex_t mutex = mutex_recursive_create(); * * void task_fn(void* param) { * while(1) { * mutex_recursive_take(mutex, 1000); * // critical section * mutex_recursive_give(mutex); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * \endcode */ mutex_t mutex_recursive_create(void); /** * Takes a recursive mutex. * * \param mutex * A mutex handle created by mutex_recursive_create * \param wait_time * Amount of time to wait before timing out * * \return 1 if the mutex was obtained, 0 otherwise * * \b Example: * \code * mutex_t mutex = mutex_recursive_create(); * * void task_fn(void* param) { * while(1) { * mutex_recursive_take(mutex, 1000); * // critical section * mutex_recursive_give(mutex); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * \endcode */ bool mutex_recursive_take(mutex_t mutex, uint32_t timeout); /** * Gives a recursive mutex. * * \param mutex * A mutex handle created by mutex_recursive_create * * \return 1 if the mutex was obtained, 0 otherwise * * \b Example: * \code * mutex_t mutex = mutex_recursive_create(); * * void task_fn(void* param) { * while(1) { * mutex_recursive_take(mutex, 1000); * // critical section * mutex_recursive_give(mutex); * task_delay(1000); * } * } * task_create(task_fn, (void*)"PROS", TASK_PRIORITY_DEFAULT, * TASK_STACK_DEPTH_DEFAULT, "task_fn"); * * \endcode */ bool mutex_recursive_give(mutex_t mutex); /** * Deletes a mutex or recursive mutex * * \param mutex * Mutex to unlock. * * \b Example * \code * mutex_t mutex = mutex_create(); * // Acquire the mutex; other tasks using this command will wait until the mutex is released * // timeout can specify the maximum time to wait, or MAX_DELAY to wait forever * // If the timeout expires, "false" will be returned, otherwise "true" * mutex_take(mutex, MAX_DELAY); * // do some work * // Release the mutex for other tasks * mutex_give(mutex); * // Delete the mutex * mutex_delete(mutex); * \endcode */ void mutex_delete(mutex_t mutex); /// @} Add to group: c-rtos #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_RTOS_H_ ================================================ FILE: include/pros/rtos.hpp ================================================ /** * \file pros/rtos.hpp * \ingroup cpp-rtos * * Contains declarations for the PROS RTOS kernel for use by typical VEX * programmers. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-rtos RTOS Facilities C++ API * \note Additional example code for this module can be found in its [Tutorial.](@ref multitasking) */ #ifndef _PROS_RTOS_HPP_ #define _PROS_RTOS_HPP_ #include "pros/rtos.h" #undef delay #include #include #include #include #include #include #include #include namespace pros { inline namespace rtos { /** * \ingroup cpp-rtos */ class Task { /** * \addtogroup cpp-rtos * @{ */ public: /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Pointer to the task entry function * \param parameters * Pointer to memory that will be used as a parameter for the task * being created. This memory should not typically come from stack, * but rather from dynamically (i.e., malloc'd) or statically * allocated memory. * \param prio * The priority at which the task should run. * TASK_PRIO_DEFAULT plus/minus 1 or 2 is typically used. * \param stack_depth * The number of words (i.e. 4 * stack_depth) available on the task's * stack. TASK_STACK_DEPTH_DEFAULT is typically sufficienct. * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, (void*)"PROS"); * } * \endcode */ Task(task_fn_t function, void* parameters = nullptr, std::uint32_t prio = TASK_PRIORITY_DEFAULT, std::uint16_t stack_depth = TASK_STACK_DEPTH_DEFAULT, const char* name = ""); /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Pointer to the task entry function * \param parameters * Pointer to memory that will be used as a parameter for the task * being created. This memory should not typically come from stack, * but rather from dynamically (i.e., malloc'd) or statically * allocated memory. * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, (void*)"PROS", "My Task"); * } * \endcode */ Task(task_fn_t function, void* parameters, const char* name); /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Callable object to use as entry function * \param prio * The priority at which the task should run. * TASK_PRIO_DEFAULT plus/minus 1 or 2 is typically used. * \param stack_depth * The number of words (i.e. 4 * stack_depth) available on the task's * stack. TASK_STACK_DEPTH_DEFAULT is typically sufficienct. * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::c::task_t my_task = pros::Task::create(my_task_fn, (void*)"PROS"); * } * \endcode */ template static task_t create(F&& function, std::uint32_t prio = TASK_PRIORITY_DEFAULT, std::uint16_t stack_depth = TASK_STACK_DEPTH_DEFAULT, const char* name = "") { static_assert(std::is_invocable_r_v); return pros::c::task_create( [](void* parameters) { std::unique_ptr> ptr{static_cast*>(parameters)}; (*ptr)(); }, new std::function(std::forward(function)), prio, stack_depth, name); } /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Callable object to use as entry function * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::c::task_t my_task = pros::Task::create(my_task_fn, "My Task"); * } * \endcode */ template static task_t create(F&& function, const char* name) { return Task::create(std::forward(function), TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, name); } /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Callable object to use as entry function * \param prio * The priority at which the task should run. * TASK_PRIO_DEFAULT plus/minus 1 or 2 is typically used. * \param stack_depth * The number of words (i.e. 4 * stack_depth) available on the task's * stack. TASK_STACK_DEPTH_DEFAULT is typically sufficient. * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \b Example * \code * * void initialize() { * // Create a task function using lambdas * auto task_fn = [](void* param) { * printf("Hello %s\n", (char*)param); * } * * pros::Task my_task(task_fn, (void*)"PROS", "My Task"); * } * \endcode */ template explicit Task(F&& function, std::uint32_t prio = TASK_PRIORITY_DEFAULT, std::uint16_t stack_depth = TASK_STACK_DEPTH_DEFAULT, const char* name = "") : Task( [](void* parameters) { std::unique_ptr> ptr{static_cast*>(parameters)}; (*ptr)(); }, new std::function(std::forward(function)), prio, stack_depth, name) { static_assert(std::is_invocable_r_v); } /** * Creates a new task and add it to the list of tasks that are ready to run. * * This function uses the following values of errno when an error state is * reached: * ENOMEM - The stack cannot be used as the TCB was not created. * * \param function * Callable object to use as entry function * \param name * A descriptive name for the task. This is mainly used to facilitate * debugging. The name may be up to 32 characters long. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task( * [](void* param) { * printf("Inside the task!\n"); * }, * "My Task" * ); * } * \endcode */ template Task(F&& function, const char* name) : Task(std::forward(function), TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, name) {} /** * Create a C++ task object from a task handle * * \param task * A task handle from task_create() for which to create a pros::Task * object. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::c::task_t my_task = pros::Task::create(my_task_fn, "My Task"); * * pros::Task my_task_cpp(my_task); * } * \endcode */ explicit Task(task_t task); /** * Get the currently running Task * * @return The currently running Task. * * \b Example * \code * void my_task_fn(void* param) { * printf("The name of this task is \"%s\"\n", pros::Task::current().get_name() * } * * void initialize() { * pros::Task my_task(my_task_fn, pros::TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "My Task"); * } * \endcode */ static Task current(); /** * Creates a task object from the passed task handle. * * \param in * A task handle from task_create() for which to create a pros::Task * object. * * \b Example * \code * void my_task_fn(void* param) { * printf("The name of this task is \"%s\"\n", pros::Task::current().get_name() * } * * void initialize() { * pros::c::task_t my_task = pros::Task::create(my_task_fn, "My Task"); * * pros::Task my_task_cpp = my_task; * } * \endcode */ Task& operator=(task_t in); /** * Removes the Task from the RTOS real time kernel's management. This task * will be removed from all ready, blocked, suspended and event lists. * * Memory dynamically allocated by the task is not automatically freed, and * should be freed before the task is deleted. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, "My Task"); * * my_task.remove(); * } * \endcode */ void remove(); /** * Gets the priority of the specified task. * * \return The priority of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, "My Task"); * * printf("Task Priority: %d\n", my_task.get_priority()); * } * \endcode */ std::uint32_t get_priority(); /** * Sets the priority of the specified task. * * If the specified task's state is available to be scheduled (e.g. not * blocked) and new priority is higher than the currently running task, * a context switch may occur. * * \param prio * The new priority of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, "My Task"); * * Task.set_priority(pros::DEFAULT_PRIORITY + 1); * } * \endcode */ void set_priority(std::uint32_t prio); /** * Gets the state of the specified task. * * \return The state of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, "My Task"); * * printf("Task State: %d\n", my_task.get_state()); * } * \endcode */ std::uint32_t get_state(); /** * Suspends the specified task, making it ineligible to be scheduled. * * \b Example * \code * pros::Mutex counter_mutex; * int counter = 0; * * void my_task_fn(void* param) { * while(true) { * counter_mutex.take(); // Mutexes are used for protecting shared resources * counter++; * counter_mutex.give(); * pros::delay(10); * } * } * * void opcontrol() { * pros::Task task(my_task_fn, "My Task"); * * while(true) { * counter_mutex.take(); * if(counter > 100) { * task_suspepend(task); * } * counter_mutex.give(); * pros::delay(10); * } * } * \endcode */ void suspend(); /** * Resumes the specified task, making it eligible to be scheduled. * * \param task * The task to resume * * \b Example * \code * void my_task_fn(void* param) { * while(true) { * // Do stuff * pros::delay(10); * } * } * * pros::Task task(my_task_fn); * * void autonomous() { * task.resume(); * * // Run autonomous , then suspend the task so it doesn't interfere run * // outside of autonomous or opcontrol * task.suspend(); * } * * void opcontrol() { * task.resume(); * // Opctonrol code here * task.suspend(); * } * * \endcode */ void resume(); /** * Gets the name of the specified task. * * \return A pointer to the name of the task * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, "My Task"); * printf("Number of Running Tasks: %d\n", my_task.get_name()); * } * \endcode */ const char* get_name(); /** * Convert this object to a C task_t handle * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void initialize() { * pros::Task my_task(my_task_fn, "My Task"); * * pros::c::task_t my_task_c = (pros::c::task_t)my_task; * } * \endcode */ explicit operator task_t() { return task; } /** * Sends a simple notification to task and increments the notification * counter. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \return Always returns true. * * \b Example * \code * void my_task_fn(void* ign) { * while(pros::Task::current_task().notify_take(true) == 0) { * // Code while waiting * } * puts("I was unblocked!"); * } * * void opcontrol() { * pros::Task my_task(my_task_fn); * * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * my_task.notify(); * } * } * } * \endcode */ std::uint32_t notify(); /** * Utilizes task notifications to wait until specified task is complete and deleted, * then continues to execute the program. Analogous to std::thread::join in C++. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \return void * * \b Example * \code * void my_task_fn(void* ign) { * lcd_print(1, "%s running", pros::Task::current_task().get_name()); * task_delay(1000); * lcd_print(2, "End of %s", pros::Task::current_task().get_name()); * } * * void opcontrol() { * pros::Task my_task(my_task_fn); * pros::lcd::set_text(0, "Running task."); * my_task.join(); * pros::lcd::lcd_set_text(3, "Task completed."); * } * \endcode */ void join(); /** * Sends a notification to a task, optionally performing some action. Will * also retrieve the value of the notification in the target task before * modifying the notification value. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \param value * The value used in performing the action * \param action * An action to optionally perform on the receiving task's notification * value * \param prev_value * A pointer to store the previous value of the target task's * notification, may be NULL * * \return Dependent on the notification action. * For NOTIFY_ACTION_NO_WRITE: return 0 if the value could be written without * needing to overwrite, 1 otherwise. * For all other NOTIFY_ACTION values: always return 0 * * \b Example * \code * void my_task_fn(void* param) { * pros::Task task = pros::Task::current(); * * while(true) { * // Wait until we have been notified 20 times before running the code * if(task.notify_take(false, TIMEOUT_MAX) == 20) { * // ... Code to do stuff here ... * * // Reset the notification counter * task.notify_clear(); * } * delay(10); * } * } * * void opcontrol() { * pros::Task task(my_task_fn); * * int count = 0; * * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task.notify_ext(1, NOTIFY_ACTION_INCREMENT, &count); * } * * delay(20); * } * } * \endcode */ std::uint32_t notify_ext(std::uint32_t value, notify_action_e_t action, std::uint32_t* prev_value); /** * Waits for a notification to be nonzero. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \param clear_on_exit * If true (1), then the notification value is cleared. * If false (0), then the notification value is decremented. * \param timeout * Specifies the amount of time to be spent waiting for a notification * to occur. * * \return The value of the task's notification value before it is decremented * or cleared * * \b Example * \code * void my_task_fn(void* ign) { * pros::Task task = pros::task::current(); * while(task.notify_take(true, TIMEOUT_MAX)) { * puts("I was unblocked!"); * } * } * * void opcontrol() { * pros::Task task(my_task_fn); * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task.notify(my_task); * } * } * } * \endcode */ static std::uint32_t notify_take(bool clear_on_exit, std::uint32_t timeout); /** * Clears the notification for a task. * * See https://pros.cs.purdue.edu/v5/tutorials/topical/notifications.html for * details. * * \return False if there was not a notification waiting, true if there was * \b Example * \code * void my_task_fn(void* param) { * pros::Task task = pros::Task::current(); * while(true) { * printf("Waiting for notification...\n"); * printf("Got a notification: %d\n", task.notify_take(false, TIMEOUT_MAX)); * * tasK_notify(task); * delay(10): * } * } * * void opcontrol() { * pros::Task task(my_task_fn); * while(true) { * if(controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1)) { * task.notify(); * } * delay(10); * } * } * \endcode */ bool notify_clear(); /** * Delays the current task for a specified number of milliseconds. * * This is not the best method to have a task execute code at predefined * intervals, as the delay time is measured from when the delay is requested. * To delay cyclically, use task_delay_until(). * * \param milliseconds * The number of milliseconds to wait (1000 milliseconds per second) * * \b Example * \code * void opcontrol() { * while (true) { * // Do opcontrol things * pros::Task::delay(2); * } * \endcode */ static void delay(const std::uint32_t milliseconds); /** * Delays the current Task until a specified time. This function can be used by * periodic tasks to ensure a constant execution frequency. * * The task will be woken up at the time *prev_time + delta, and *prev_time * will be updated to reflect the time at which the task will unblock. * * \param prev_time * A pointer to the location storing the setpoint time. This should * typically be initialized to the return value from pros::millis(). * \param delta * The number of milliseconds to wait (1000 milliseconds per second) * * \b Example * \code * void opcontrol() { * while (true) { * // Do opcontrol things * pros::Task::delay(2); * } * } * \endcode */ static void delay_until(std::uint32_t* const prev_time, const std::uint32_t delta); /** * Gets the number of tasks the kernel is currently managing, including all * ready, blocked, or suspended tasks. A task that has been deleted, but not * yet reaped by the idle task will also be included in the count. * Tasks recently created may take one context switch to be counted. * * \return The number of tasks that are currently being managed by the kernel. * * \b Example * \code * void my_task_fn(void* param) { * printf("Hello %s\n", (char*)param); * // ... * } * * void opcontrol() { * pros::Task my_task(my_task_fn); * printf("There are %d tasks running\n", pros::Task::get_count()); * } * \endcode */ static std::uint32_t get_count(); private: task_t task{}; }; // STL Clock compliant clock struct Clock { using rep = std::uint32_t; using period = std::milli; using duration = std::chrono::duration; using time_point = std::chrono::time_point; const bool is_steady = true; /** * Gets the current time. * * Effectively a wrapper around pros::millis() * * \return The current time * * \b Example * \code * void opcontrol() { * pros::Clock::time_point start = pros::Clock::now(); * pros::Clock::time_point end = pros::Clock::now(); * pros::Clock::duration duration = end - start; * printf("Duration: %d\n", duration.count()); * * if(duration.count() == 500) { * // If you see this comment in the DOCS, ping @pros in VTOW. * // If you are the first person to do so, you will receive a free PROS * // holo! * printf("Duration is 500 milliseconds\n"); * } * } * \endcode */ static time_point now(); }; class Mutex { std::atomic mutex{nullptr}; mutex_t lazy_init(); public: constexpr Mutex() { if (!std::is_constant_evaluated()) { lazy_init(); } } // disable copy and move construction and assignment per Mutex requirements // (see https://en.cppreference.com/w/cpp/named_req/Mutex) Mutex(const Mutex&) = delete; Mutex(Mutex&&) = delete; Mutex& operator=(const Mutex&) = delete; Mutex& operator=(Mutex&&) = delete; /** * Takes and locks a mutex indefinetly. * * See * https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \return True if the mutex was successfully taken, false otherwise. If false * is returned, then errno is set with a hint about why the the mutex * couldn't be taken * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::Mutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.take(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.give(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.take(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.give(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.take(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.give(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::Mutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ bool take(); /** * Takes and locks a mutex, waiting for up to a certain number of milliseconds * before timing out. * * See * https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \param timeout * Time to wait before the mutex becomes available. A timeout of 0 can * be used to poll the mutex. TIMEOUT_MAX can be used to block * indefinitely. * * \return True if the mutex was successfully taken, false otherwise. If false * is returned, then errno is set with a hint about why the the mutex * couldn't be taken. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::Mutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.take(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.give(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.take(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.give(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.take(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.give(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::Mutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ bool take(std::uint32_t timeout); /** * Unlocks a mutex. * * See * https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \return True if the mutex was successfully returned, false otherwise. If * false is returned, then errno is set with a hint about why the mutex * couldn't be returned. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::Mutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.take(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.give(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.take(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.give(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.take(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.give(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::Mutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ bool give(); /** * Takes and locks a mutex, waiting for up to TIMEOUT_MAX milliseconds. * * Effectively equivalent to calling pros::Mutex::take with TIMEOUT_MAX as * the parameter. * * Conforms to named requirment BasicLockable * \see https://en.cppreference.com/w/cpp/named_req/BasicLockable * * \note Consider using a std::unique_lock, std::lock_guard, or * std::scoped_lock instead of interacting with the Mutex directly. * * \exception std::system_error Mutex could not be locked within TIMEOUT_MAX * milliseconds. see errno for details. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::Mutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.lock(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.unlock(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.lock(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.unlock(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.lock(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.unlock(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::Mutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ void lock(); /** * Unlocks a mutex. * * Equivalent to calling pros::Mutex::give. * * Conforms to named requirement BasicLockable * \see https://en.cppreference.com/w/cpp/named_req/BasicLockable * * \note Consider using a std::unique_lock, std::lock_guard, or * std::scoped_lock instead of interacting with the Mutex direcly. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::Mutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.lock(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.unlock(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.lock(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.unlock(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.lock(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.unlock(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::Mutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ void unlock(); /** * Try to lock a mutex. * * Returns immediately if unsucessful. * * Conforms to named requirement Lockable * \see https://en.cppreference.com/w/cpp/named_req/Lockable * * \return True when lock was acquired succesfully, or false otherwise. * * pros::Mutex mutex; * * void my_task_fn(void* param) { * while (true) { * if(mutex.try_lock()) { * printf("Mutex aquired successfully!\n"); * // Do stuff that requires the protected resource here * } * else { * printf("Mutex not aquired!\n"); * } * } * } */ [[nodiscard]] bool try_lock(); /** * Takes and locks a mutex, waiting for a specified duration. * * Equivalent to calling pros::Mutex::take with a duration specified in * milliseconds. * * Conforms to named requirement TimedLockable * \see https://en.cppreference.com/w/cpp/named_req/TimedLockable * * \param rel_time Time to wait before the mutex becomes available. * \return True if the lock was acquired succesfully, otherwise false. * * \b Example * \code * void my_task_fn(void* param) { * while (true) { * if(mutex.try_lock_for(std::chrono::milliseconds(100))) { * printf("Mutex aquired successfully!\n"); * // Do stuff that requires the protected resource here * } * else { * printf("Mutex not aquired after 100 milliseconds!\n"); * } * } * } * \endcode */ template [[nodiscard]] bool try_lock_for(const std::chrono::duration& rel_time) { return take(std::chrono::duration_cast(rel_time).count()); } /** * Takes and locks a mutex, waiting until a specified time. * * Conforms to named requirement TimedLockable * \see https://en.cppreference.com/w/cpp/named_req/TimedLockable * * \param abs_time Time point until which to wait for the mutex. * \return True if the lock was acquired succesfully, otherwise false. * * \b Example * \code * void my_task_fn(void* param) { * while (true) { * // Get the current time point * auto now = std::chrono::system_clock::now(); * * // Calculate the time point 100 milliseconds from now * auto abs_time = now + std::chrono::milliseconds(100); * * if(mutex.try_lock_until(abs_time)) { * printf("Mutex aquired successfully!\n"); * // Do stuff that requires the protected resource here * } * else { * printf("Mutex not aquired after 100 milliseconds!\n"); * } * } * } * \endcode */ template bool try_lock_until(const std::chrono::time_point& abs_time) { return take(std::max(static_cast(0), (abs_time - Clock::now()).count())); } ~Mutex(); ///@} }; class RecursiveMutex { std::atomic mutex{nullptr}; mutex_t lazy_init(); public: constexpr RecursiveMutex() { if (!std::is_constant_evaluated()) { lazy_init(); } } // disable copy and move construction and assignment per Mutex requirements // (see https://en.cppreference.com/w/cpp/named_req/Mutex) RecursiveMutex(const RecursiveMutex&) = delete; RecursiveMutex(RecursiveMutex&&) = delete; RecursiveMutex& operator=(const RecursiveMutex&) = delete; RecursiveMutex& operator=(RecursiveMutex&&) = delete; /** * Takes and locks a mutex indefinetly. * * See * https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \return True if the mutex was successfully taken, false otherwise. If false * is returned, then errno is set with a hint about why the the mutex * couldn't be taken * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::RecursiveMutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.take(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.give(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.take(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.give(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.take(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.give(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::RecursiveMutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ bool take(); /** * Takes and locks a mutex, waiting for up to a certain number of milliseconds * before timing out. * * See * https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \param timeout * Time to wait before the mutex becomes available. A timeout of 0 can * be used to poll the mutex. TIMEOUT_MAX can be used to block * indefinitely. * * \return True if the mutex was successfully taken, false otherwise. If false * is returned, then errno is set with a hint about why the the mutex * couldn't be taken. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::RecursiveMutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.take(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.give(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.take(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.give(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.take(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.give(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::RecursiveMutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ bool take(std::uint32_t timeout); /** * Unlocks a mutex. * * See * https://pros.cs.purdue.edu/v5/tutorials/topical/multitasking.html#mutexes * for details. * * \return True if the mutex was successfully returned, false otherwise. If * false is returned, then errno is set with a hint about why the mutex * couldn't be returned. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::RecursiveMutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.take(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.give(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.take(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.give(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.take(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.give(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::RecursiveMutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ bool give(); /** * Takes and locks a mutex, waiting for up to TIMEOUT_MAX milliseconds. * * Effectively equivalent to calling pros::RecursiveMutex::take with TIMEOUT_MAX as * the parameter. * * Conforms to named requirment BasicLockable * \see https://en.cppreference.com/w/cpp/named_req/BasicLockable * * \note Consider using a std::unique_lock, std::lock_guard, or * std::scoped_lock instead of interacting with the Mutex directly. * * \exception std::system_error Mutex could not be locked within TIMEOUT_MAX * milliseconds. see errno for details. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::RecursiveMutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.lock(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.unlock(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.lock(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.unlock(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.lock(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.unlock(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::RecursiveMutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ void lock(); /** * Unlocks a mutex. * * Equivalent to calling pros::RecursiveMutex::give. * * Conforms to named requirement BasicLockable * \see https://en.cppreference.com/w/cpp/named_req/BasicLockable * * \note Consider using a std::unique_lock, std::lock_guard, or * std::scoped_lock instead of interacting with the Mutex direcly. * * \b Example * \code * // Global variables for the robot's odometry, which the rest of the robot's * // subsystems will utilize * double odom_x = 0.0; * double odom_y = 0.0; * double odom_heading = 0.0; * * // This mutex protects the odometry data. Whenever we read or write to the * // odometry data, we should make copies into the local variables, and read * // all 3 values at once to avoid errors. * pros::RecursiveMutex odom_mutex; * * void odom_task(void* param) { * while(true) { * // First we fetch the odom coordinates from the previous iteration of the * // odometry task. These are put into local variables so that we can * // keep the size of the critical section as small as possible. This lets * // other tasks that need to use the odometry data run until we need to * // update it again. * odom_mutex.lock(); * double x_old = odom_x; * double y_old = odom_y; * double heading_old = odom_heading; * odom_mutex.unlock(); * * double x_new = 0.0; * double y_new = 0.0; * double heading_new = 0.0; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * odom_mutex.lock(); * odom_x = x_new; * odom_y = y_new; * odom_heading = heading_new; * odom_mutex.unlock(); * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * // Here we copy the current odom values into local variables so that * // we can use them without worrying about the odometry task changing say, * // the y value right after we've read the x. This ensures our values are * // sound. * odom_mutex.lock(); * double current_x = odom_x; * double current_y = odom_y; * double current_heading = odom_heading; * odom_mutex.unlock(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::RecursiveMutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * \endcode. */ void unlock(); /** * Try to lock a mutex. * * Returns immediately if unsucessful. * * Conforms to named requirement Lockable * \see https://en.cppreference.com/w/cpp/named_req/Lockable * * \return True when lock was acquired succesfully, or false otherwise. * * pros::RecursiveMutex mutex; * * void my_task_fn(void* param) { * while (true) { * if(mutex.try_lock()) { * printf("Mutex aquired successfully!\n"); * // Do stuff that requires the protected resource here * } * else { * printf("Mutex not aquired!\n"); * } * } * } */ [[nodiscard]] bool try_lock(); /** * Takes and locks a mutex, waiting for a specified duration. * * Equivalent to calling pros::RecursiveMutex::take with a duration specified in * milliseconds. * * Conforms to named requirement TimedLockable * \see https://en.cppreference.com/w/cpp/named_req/TimedLockable * * \param rel_time Time to wait before the mutex becomes available. * \return True if the lock was acquired succesfully, otherwise false. * * \b Example * \code * void my_task_fn(void* param) { * while (true) { * if(mutex.try_lock_for(std::chrono::milliseconds(100))) { * printf("Mutex aquired successfully!\n"); * // Do stuff that requires the protected resource here * } * else { * printf("Mutex not aquired after 100 milliseconds!\n"); * } * } * } * \endcode */ template [[nodiscard]] bool try_lock_for(const std::chrono::duration& rel_time) { return take(std::chrono::duration_cast(rel_time).count()); } /** * Takes and locks a mutex, waiting until a specified time. * * Conforms to named requirement TimedLockable * \see https://en.cppreference.com/w/cpp/named_req/TimedLockable * * \param abs_time Time point until which to wait for the mutex. * \return True if the lock was acquired succesfully, otherwise false. * * \b Example * \code * void my_task_fn(void* param) { * while (true) { * // Get the current time point * auto now = std::chrono::system_clock::now(); * * // Calculate the time point 100 milliseconds from now * auto abs_time = now + std::chrono::milliseconds(100); * * if(mutex.try_lock_until(abs_time)) { * printf("Mutex aquired successfully!\n"); * // Do stuff that requires the protected resource here * } * else { * printf("Mutex not aquired after 100 milliseconds!\n"); * } * } * } * \endcode */ template bool try_lock_until(const std::chrono::time_point& abs_time) { return take(std::max(static_cast(0), (abs_time - Clock::now()).count())); } ~RecursiveMutex(); ///@} }; template class MutexVar; template class MutexVarLock { Mutex& mutex; Var& var; friend class MutexVar; constexpr MutexVarLock(Mutex& mutex, Var& var) : mutex(mutex), var(var) {} public: /** * Accesses the value of the mutex-protected variable. */ constexpr Var& operator*() const { return var; } /** * Accesses the value of the mutex-protected variable. */ constexpr Var* operator->() const { return &var; } ~MutexVarLock() { mutex.unlock(); } }; template class MutexVar { Mutex mutex; Var var; public: /** * Creates a mutex-protected variable which is initialized with the given * constructor arguments. * * \param args * The arguments to provide to the Var constructor. * * \b Example * \code * // We create a pose class to contain all our odometry data in a single * // variable that can be protected by a MutexVar. Otherwise, we would have * // three seperate variables which could not be protected in a single * // MutexVar * struct Pose { * double x; * double y; * double heading; * } * * pros::MutexVar odom_pose(0.0, 0.0, 0.0); * * void odom_task(void* param) { * while(true) { * Pose old_pose = *odom_pose.lock(); * * Pose new_pose{0.0, 0.0, 0.0}; * * // --- Calculate new pose for the robot here --- * * // Now that we have the new pose, we can update the global variables * * *odom_pose.take() = new_pose; * * delay(10); * } * } * * void chassis_task(void* param) { * while(true) { * * Pose cur_pose = *odom_pose.take(); * * // ---- Move the robot using the current locations goes here ---- * * delay(10); * } * } * * void initialize() { * odom_mutex = pros::Mutex(); * * pros::Task odom_task(odom_task, "Odometry Task"); * pros::Task chassis_task(odom_task, "Chassis Control Task"); * } * * \endcode */ template MutexVar(Args&&... args) : mutex(), var(std::forward(args)...) {} /** * Try to lock the mutex-protected variable. * * \param timeout * Time to wait before the mutex becomes available, in milliseconds. A * timeout of 0 can be used to poll the mutex. * * \return A std::optional which contains a MutexVarLock providing access to * the protected variable if locking is successful. * * \b Example * \code * pros::MutexVar odom_pose; * * void my_task(void* param) { * while(true) { * std::optional> cur_pose_opt = odom_pose.try_lock(100); * * if(cur_pose_opt.has_value()) { * Pose* cur_pose = **cur_pose_opt; * } * else { * printf("Could not lock the mutex var!"); * } * * pros::delay(10); * } * } * \endcode */ std::optional> try_lock(std::uint32_t timeout) { if (mutex.take(timeout)) { return {{mutex, var}}; } else { return {}; } } /** * Try to lock the mutex-protected variable. * * \param timeout * Time to wait before the mutex becomes available. A timeout of 0 can * be used to poll the mutex. * * \return A std::optional which contains a MutexVarLock providing access to * the protected variable if locking is successful. * * \b Example * \code * pros::MutexVar odom_pose; * * void my_task(void* param) { * while(true) { * std::chrono::duration timeout(100); * std::optional> cur_pose_opt = odom_pose.try_lock(timeout); * * if(cur_pose_opt.has_value()) { * Pose* cur_pose = **cur_pose_opt; * } * else { * printf("Could not lock the mutex var!"); * } * * pros::delay(10); * } * } * \endcode */ template std::optional> try_lock(const std::chrono::duration& rel_time) { try_lock(std::chrono::duration_cast(rel_time).count()); } /** * Lock the mutex-protected variable, waiting indefinitely. * * \return A MutexVarLock providing access to the protected variable. * * \b Example * \code * pros::MutexVar odom_pose; * * void my_task(void* param) { * while(true) { * pros::delay(10); * * pros::MutexVarLock cur_pose = odom_pose.lock(); * Pose cur_pose = *cur_pose; * * // do stuff with cur_pose * } * } * \endcode */ MutexVarLock lock() { while (!mutex.take(TIMEOUT_MAX)) ; return {mutex, var}; } }; /** * Gets the number of milliseconds since PROS initialized. * * \return The number of milliseconds since PROS initialized */ using pros::c::millis; /** * Gets the number of microseconds since PROS initialized. * * \return The number of microseconds since PROS initialized */ using pros::c::micros; /** * Delays a task for a given number of milliseconds. * * This is not the best method to have a task execute code at predefined * intervals, as the delay time is measured from when the delay is requested. * To delay cyclically, use task_delay_until(). * * \param milliseconds * The number of milliseconds to wait (1000 milliseconds per second) */ using pros::c::delay; } // namespace rtos } // namespace pros #endif // _PROS_RTOS_HPP_ ================================================ FILE: include/pros/screen.h ================================================ /** * \file screen.h * \ingroup c-screen * * Brain screen display and touch functions. * * Contains user calls to the v5 screen for touching and displaying graphics. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-screen Simplified Brain Screen C API * */ #ifndef _PROS_SCREEN_H_ #define _PROS_SCREEN_H_ #include #include #define _GNU_SOURCE #include #undef _GNU_SOURCE #include #include "pros/colors.h" // c color macros #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \ingroup c-screen */ /** * \addtogroup c-screen * @{ */ /** * \enum text_format_e_t * Different font sizes that can be used in printing text. */ typedef enum { /// Small text font size E_TEXT_SMALL = 0, /// Normal/Medium text font size E_TEXT_MEDIUM, /// Large text font size E_TEXT_LARGE, /// Medium centered text E_TEXT_MEDIUM_CENTER, /// Large centered text E_TEXT_LARGE_CENTER } text_format_e_t; /** * \enum last_touch_e_t * Enum indicating what the current touch status is for the touchscreen. */ typedef enum { /// Last interaction with screen was a quick press E_TOUCH_RELEASED = 0, /// Last interaction with screen was a release E_TOUCH_PRESSED, /// User is holding screen down E_TOUCH_HELD, /// An error occured while taking/returning the mutex E_TOUCH_ERROR } last_touch_e_t; /** * \struct screen_touch_status_s_t * Struct representing screen touch status, screen last x, screen last y, press count, release count. */ typedef struct screen_touch_status_s { last_touch_e_t touch_status; ///< Represents if the screen is being held, released, or pressed. int16_t x; ///< Represents the x value of the location of the touch. int16_t y; ///< Represents the y value of the location of the touch. int32_t press_count; ///< Represents how many times the screen has be pressed. int32_t release_count; ///< Represents how many times the user released after a touch on the screen. } screen_touch_status_s_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define TEXT_SMALL pros::E_TEXT_SMALL #define TEXT_MEDIUM pros::E_TEXT_MEDIUM #define TEXT_LARGE pros::E_TEXT_LARGE #define TEXT_MEDIUM_CENTER pros::E_TEXT_MEDIUM_CENTER #define TEXT_LARGE_CENTER pros::E_TEXT_LARGE_CENTER #define TOUCH_RELEASED pros::E_TOUCH_RELEASED #define TOUCH_PRESSED pros::E_TOUCH_PRESSED #define TOUCH_HELD pros::E_TOUCH_HELD #else #define TEXT_SMALL E_TEXT_SMALL #define TEXT_MEDIUM E_TEXT_MEDIUM #define TEXT_LARGE E_TEXT_LARGE #define TEXT_MEDIUM_CENTER E_TEXT_MEDIUM_CENTER #define TEXT_LARGE_CENTER E_TEXT_LARGE_CENTER #define TOUCH_RELEASED E_TOUCH_RELEASED #define TOUCH_PRESSED E_TOUCH_PRESSED #define TOUCH_HELD E_TOUCH_HELD #endif #endif typedef void (*touch_event_cb_fn_t)(); #ifdef __cplusplus namespace c { #endif /// \name Screen Graphical Display Functions /// These functions allow programmers to display shapes on the v5 screen ///@{ /** * Set the pen color for subsequent graphics operations * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param color The pen color to set (it is recommended to use values * from the enum defined in colors.h) * * \return Returns 1 if the mutex was successfully returned, or PROS_ERR if * there was an error either taking or returning the screen mutex. * * \b Example * \code * void initialize() { * screen_set_pen(COLOR_RED); * } * * void opcontrol() { * int iter = 0; * while(1){ * // This should print in red. * screen_print(TEXT_MEDIUM, 1, "%d", iter++); * } * } * \endcode */ uint32_t screen_set_pen(uint32_t color); /** * Set the eraser color for erasing and the current background. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param color The background color to set (it is recommended to use values * from the enum defined in colors.h) * * \return Returns 1 if the mutex was successfully returned, or * PROS_ERR if there was an error either taking or returning the screen mutex. * * \b Example * \code * void initialize() { * screen_set_eraser(COLOR_RED); * } * * void opcontrol() { * while(1){ * // This should turn the screen red. * screen_erase(); * } * } * \endcode */ uint32_t screen_set_eraser(uint32_t color); /** * Get the current pen color. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \return The current pen color in the form of a value from the enum defined * in colors.h, or PROS_ERR if there was an error taking or returning * the screen mutex. * * \b Example * \code * void initialize() { * screen_set_pen(COLOR_RED); * } * * void opcontrol() { * while(1){ * // Should print number equivalent to COLOR_RED defined in colors.h. * screen_print(TEXT_MEDIUM, 1, "%d", screen_get_pen()); * } * } * \endcode */ uint32_t screen_get_pen(void); /** * Get the current eraser color. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \return The current eraser color in the form of a value from the enum * defined in colors.h, or PROS_ERR if there was an error taking or * returning the screen mutex. * * \b Example * \code * void initialize() { * screen_set_eraser(COLOR_RED); * } * * void opcontrol() { * while(1){ * // Should print number equivalent to COLOR_RED defined in colors.h. * screen_print(TEXT_MEDIUM, 1, "%d", screen_get_eraser()); * } * } * \endcode */ uint32_t screen_get_eraser(void); /** * Clear display with eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void initialize() { * screen_set_eraser(COLOR_RED); * } * * void opcontrol() { * while(1){ * // This should turn the screen red. * screen_erase(); * } * } * \endcode */ uint32_t screen_erase(void); /** * Scroll lines on the display upwards. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param start_line The line from which scrolling will start * \param lines The number of lines to scroll up * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * screen_print(TEXT_MEDIUM, 4, "Line Here"); * // Scroll 3 lines * screen_scroll(4, 3); * } * \endcode */ uint32_t screen_scroll(int16_t start_line, int16_t lines); /** * Scroll lines within a region on the display * * This function behaves in the same way as `screen_scroll`, except that you * specify a rectangular region within which to scroll lines instead of a start * line. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first corner of the * rectangular region * \param x1, y1 The (x,y) coordinates of the second corner of the * rectangular region * \param lines The number of lines to scroll upwards * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * screen_print(TEXT_MEDIUM, 1, "Line Here"); * // Scrolls area of screen upwards slightly. including line of text * screen_scroll_area(0,0, 400, 200, 3); * } * \endcode */ uint32_t screen_scroll_area(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t lines); /** * Copy a screen region (designated by a rectangle) from an off-screen buffer * to the screen * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first corner of the * rectangular region of the screen * \param x1, y1 The (x,y) coordinates of the second corner of the * rectangular region of the screen * \param buf Off-screen buffer containing screen data * \param stride Off-screen buffer width in pixels, such that image size * is stride-padding * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * uint32_t* buf = malloc(sizeof(uint32_t) * 400 * 200); * screen_print(TEXT_MEDIUM, 1, "Line Here"); * // Copies area of the screen including text * screen_copy_area(0, 0, 400, 200, (uint32_t*)buf, 400 + 1); * // Equation for stride is x2 - x1 + 1 * } * \endcode */ uint32_t screen_copy_area(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint32_t* buf, int32_t stride); /** * Draw a single pixel on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the pixel * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * int i = 0; * void opcontrol() { * while(i < 200){ * screen_draw_pixel(100,i++); * // Draws a line at x = 100 gradually down the screen, pixel by pixel * delay(200); * } * } * \endcode */ uint32_t screen_draw_pixel(int16_t x, int16_t y); /** * Erase a pixel from the screen (Sets the location) * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the erased * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Color the Screen in Red * screen_set_pen(COLOR_RED); * screen_fill_rect(0,0,400,200); * int i = 0; * while(i < 200){ * screen_erase_pixel(100,i++); * // Erases a line at x = 100 gradually down the screen, pixel by pixel * delay(200); * } * } * \endcode */ uint32_t screen_erase_pixel(int16_t x, int16_t y); /** * Draw a line on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x, y) coordinates of the first point of the line * \param x1, y1 The (x, y) coordinates of the second point of the line * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * screen_set_pen(COLOR_RED); * // Draw line down the screen at x = 100 * screen_draw_line(100,0,100,200); * } * \endcode */ uint32_t screen_draw_line(int16_t x0, int16_t y0, int16_t x1, int16_t y1); /** * Erase a line on the screen using the current eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x, y) coordinates of the first point of the line * \param x1, y1 The (x, y) coordinates of the second point of the line * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Color the Screen in Red * screen_set_pen(COLOR_RED); * screen_fill_rect(0,0,400,200); * // Erase line down the screen at x = 100 * screen_erase_line(100,0,100,200); * } * \endcode */ uint32_t screen_erase_line(int16_t x0, int16_t y0, int16_t x1, int16_t y1); /** * Draw a rectangle on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first point of the rectangle * \param x1, y1 The (x,y) coordinates of the second point of the rectangle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * screen_set_pen(COLOR_RED); * screen_draw_rect(1,1,480,200); * } * \endcode */ uint32_t screen_draw_rect(int16_t x0, int16_t y0, int16_t x1, int16_t y1); /** * Erase a rectangle on the screen using the current eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first point of the rectangle * \param x1, y1 The (x,y) coordinates of the second point of the rectangle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Draw Box Around Half the Screen in Red * screen_set_eraser(COLOR_RED); * screen_erase_rect(5,5,240,200); * } * \endcode */ uint32_t screen_erase_rect(int16_t x0, int16_t y0, int16_t x1, int16_t y1); /** * Fill a rectangular region of the screen using the current pen * color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first point of the rectangle * \param x1, y1 The (x,y) coordinates of the second point of the rectangle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Fill Around Half the Screen in Red * screen_set_pen(COLOR_RED); * screen_fill_rect(5,5,240,200); * } * \endcode */ uint32_t screen_fill_rect(int16_t x0, int16_t y0, int16_t x1, int16_t y1); /** * Draw a circle on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the center of the circle * \param r The radius of the circle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Draw a circle with radius of 100 in red * screen_set_pen(COLOR_RED); * screen_draw_circle(240, 200, 100); * } * \endcode */ uint32_t screen_draw_circle(int16_t x, int16_t y, int16_t radius); /** * Erase a circle on the screen using the current eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the center of the circle * \param r The radius of the circle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * screen_set_pen(COLOR_RED); * screen_fill_rect(5,5,240,200); * // Erase a circle with radius of 100 in COLOR_BLUE * screen_set_pen(COLOR_BLUE); * screen_erase_circle(240, 200, 100); * } * \endcode */ uint32_t screen_erase_circle(int16_t x, int16_t y, int16_t radius); /** * Fill a circular region of the screen using the current pen * color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the center of the circle * \param r The radius of the circle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * screen_set_pen(COLOR_RED); * screen_fill_rect(5,5,240,200); * // Fill a circlular area with radius of 100 in COLOR_BLUE * screen_set_pen(COLOR_BLUE); * screen_fill_circle(240, 200, 100); * } * \endcode */ uint32_t screen_fill_circle(int16_t x, int16_t y, int16_t radius); ///@} /// \name Screen Text Display Functions /// These functions allow programmers to display text on the v5 screen ///@{ /** * Print a formatted string to the screen on the specified line * * Will default to a medium sized font by default if invalid txt_fmt is given. * * \param txt_fmt Text format enum that determines if the text is medium, large, medium_center, or large_center. (DOES * NOT SUPPORT SMALL) \param line The line number on which to print \param text Format string \param ... Optional list * of arguments for the format string * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * int i = 0; * * screen_set_pen(COLOR_BLUE); * while(1){ * // Will print seconds started since program started on line 3 * screen_print(TEXT_MEDIUM, 3, "Seconds Passed: %3d", i++); * delay(1000); * } * } * \endcode */ uint32_t screen_print(text_format_e_t txt_fmt, const int16_t line, const char* text, ...); /** * Print a formatted string to the screen at the specified point * * Will default to a medium sized font by default if invalid txt_fmt is given. * * Text formats medium_center and large_center will default to medium and large respectively. * * \param txt_fmt Text format enum that determines if the text is small, medium, or large. * \param x The y coordinate of the top left corner of the string * \param y The x coordinate of the top left corner of the string * \param text Format string * \param ... Optional list of arguments for the format string * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * int i = 0; * * screen_set_pen(COLOR_BLUE); * while(1){ * // Will print seconds started since program started. * screen_print_at(TEXT_SMALL, 3, "Seconds Passed: %3d", i++); * delay(1000); * } * } * \endcode */ uint32_t screen_print_at(text_format_e_t txt_fmt, const int16_t x, const int16_t y, const char* text, ...); /** * Print a formatted string to the screen on the specified line * * Same as `display_printf` except that this uses a `va_list` instead of the * ellipsis operator so this can be used by other functions. * * Will default to a medium sized font by default if invalid txt_fmt is given. * Exposed mostly for writing libraries and custom functions. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param txt_fmt Text format enum that determines if the text is medium, large, medium_center, or large_center. (DOES * NOT SUPPORT SMALL) \param line The line number on which to print \param text Format string \param args List of * arguments for the format string * * \return 1 if there were no errors, or PROS_ERR if an error occured * while taking or returning the screen mutex. * * */ uint32_t screen_vprintf(text_format_e_t txt_fmt, const int16_t line, const char* text, va_list args); /** * Print a formatted string to the screen at the specified coordinates * * Same as `display_printf_at` except that this uses a `va_list` instead of the * ellipsis operator so this can be used by other functions. * * Will default to a medium sized font by default if invalid txt_fmt is given. * * Text formats medium_center and large_center will default to medium and large respectively. * Exposed mostly for writing libraries and custom functions. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param txt_fmt Text format enum that determines if the text is small, medium, or large. * \param x, y The (x,y) coordinates of the top left corner of the string * \param text Format string * \param args List of arguments for the format string * * \return 1 if there were no errors, or PROS_ERR if an error occured * while taking or returning the screen mutex. * */ uint32_t screen_vprintf_at(text_format_e_t txt_fmt, const int16_t x, const int16_t y, const char* text, va_list args); ///@} /// \name Screen Touch Functions /// These functions allow programmers to access information about screen touches ///@{ /** * Gets the touch status of the last touch of the screen. * * \return The last_touch_e_t enum specifier that indicates the last touch status of the screen (E_TOUCH_EVENT_RELEASE, * E_TOUCH_EVENT_PRESS, or E_TOUCH_EVENT_PRESS_AND_HOLD). This will be released by default if no action was taken. If an * error occured, the screen_touch_status_s_t will have its last_touch_e_t enum specifier set to E_TOUCH_ERR, and other * values set to -1. * * \b Example * \code * void opcontrol() { * int i = 0; * screen_touch_status_s_t status; * while(1){ * status = screen_touch_status(); * * // Will print various information about the last touch * screen_print(TEXT_MEDIUM, 1, "Touch Status (Type): %d", status.touch_status); * screen_print(TEXT_MEDIUM, 2, "Last X: %d", status.x); * screen_print(TEXT_MEDIUM, 3, "Last Y: %d", status.y); * screen_print(TEXT_MEDIUM, 4, "Press Count: %d", status.press_count); * screen_print(TEXT_MEDIUM, 5, "Release Count: %d", status.release_count); * delay(20); * } * } * \endcode */ screen_touch_status_s_t screen_touch_status(void); /** * Assigns a callback function to be called when a certain touch event happens. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param cb Function pointer to callback when event type happens * \param event_type Touch event that will trigger the callback. * * \return 1 if there were no errors, or PROS_ERR if an error occured * while taking or returning the screen mutex. * * \b Example * \code * touch_event_cb_fn_t changePixel(){ * screen_touch_status_s_t status = screen_touch_status(); * screen_draw_pixel(status.x,status.y); * return NULL; * } * * void opcontrol() { * screen_touch_callback(changePixel(), TOUCH_PRESSED); * while(1) delay(20); * } * \endcode */ uint32_t screen_touch_callback(touch_event_cb_fn_t cb, last_touch_e_t event_type); ///@} ///@} #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif ================================================ FILE: include/pros/screen.hpp ================================================ /** * \file screen.hpp * \ingroup cpp-screen * * Brain screen display and touch functions. * * Contains user calls to the v5 screen for touching and displaying graphics. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-screen Simplified Brain Screen C++ API */ #ifndef _PROS_SCREEN_HPP_ #define _PROS_SCREEN_HPP_ #include "pros/screen.h" #include "pros/colors.hpp" #include #include namespace pros { namespace screen { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" namespace { template T convert_args(T arg) { return arg; } const char* convert_args(const std::string& arg) { return arg.c_str(); } } // namespace #pragma GCC diagnostic pop /** * \ingroup cpp-screen */ /** * \addtogroup cpp-screen * @{ */ /******************************************************************************/ /** Screen Graphical Display Functions **/ /** **/ /** These functions allow programmers to display shapes on the v5 screen **/ /******************************************************************************/ /** * Set the pen color for subsequent graphics operations * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param color The pen color to set (it is recommended to use values * from the enum defined in colors.hpp) * * \return Returns 1 if the mutex was successfully returned, or PROS_ERR if * there was an error either taking or returning the screen mutex. * * \b Example * \code * void initialize() { * pros::screen::set_pen(red); * } * * void opcontrol() { * int iter = 0; * while(1){ * // This should print in red. * pros::screen::print(TEXT_MEDIUM, 1, "%d", iter++); * } * } * * \endcode */ std::uint32_t set_pen(pros::Color color); /** * Set the pen color for subsequent graphics operations * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param color The pen color to set (in hex form) * * \return Returns 1 if the mutex was successfully returned, or PROS_ERR if * there was an error either taking or returning the screen mutex. * * \b Example * \code * void initialize() { * //set pen color to red * pros::screen::set_pen(0x00FF0000); * } * * void opcontrol() { * int iter = 0; * while(1){ * // This should print in red. * pros::screen::print(TEXT_MEDIUM, 1, "%d", iter++); * } * } * * \endcode */ std::uint32_t set_pen(std::uint32_t color); /** * Set the eraser color for erasing and the current background. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param color The background color to set (it is recommended to use values * from the enum defined in colors.hpp) * * \return Returns 1 if the mutex was successfully returned, or PROS_ERR * if there was an error either taking or returning the screen mutex. * * \b Example * \code * void initialize() { * //set eraser color to red * set_eraser(red); * } * * void opcontrol() { * int iter = 0; * while(1){ * // This should print in red. * pros::screen::print(TEXT_MEDIUM, 1, "%d", iter++); * } * } * * \endcode */ std::uint32_t set_eraser(pros::Color color); /** * Set the eraser color for erasing and the current background. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param color The background color to set to set (in hex form) * * \return Returns 1 if the mutex was successfully returned, or PROS_ERR * if there was an error either taking or returning the screen mutex. * * \b Example * \code * void initialize() { * //set eraser color to red * pros::screen::set_eraser(0x00FF0000); * } * * void opcontrol() { * while(1){ * // This should turn the screen red. * pros::screen::erase(); * } * } * \endcode */ std::uint32_t set_eraser(std::uint32_t color); /** * Get the current pen color. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \return The current pen color in the form of a value from the enum * defined in colors.h, or PROS_ERR if there was an error taking or * returning the screen mutex. * * \b Example * \code * void initialize() { * pros::screen::set_pen(red); * } * * void opcontrol() { * while(1){ * // Should print number equivalent to red defined in colors.hpp. * pros::screen::print(TEXT_MEDIUM, 1, "%d", get_pen()); * } * } * \endcode */ std::uint32_t get_pen(); /** * Get the current eraser color. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \return The current eraser color in the form of a value from the enum * defined in colors.h, or PROS_ERR if there was an error taking or * returning the screen mutex. * * \b Example * \code * void initialize() { * pros::screen::set_eraser(red); * } * * void opcontrol() { * while(1){ * // Should print number equivalent to red defined in colors.h. * pros::screen::print(TEXT_MEDIUM, 1, "%d", get_eraser()); * } * } * \endcode */ std::uint32_t get_eraser(); /** * Clear display with eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * * \b Example * \code * void initialize() { * pros::screen::set_eraser(red); * } * * void opcontrol() { * while(1){ * // This should turn the screen red. * pros::screen::erase(); * } * } * \endcode */ std::uint32_t erase(); /** * Scroll lines on the display upwards. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param start_line The line from which scrolling will start * \param lines The number of lines to scroll up * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * pros::screen::print(TEXT_MEDIUM, 4, "Line Here"); * // Scroll 3 lines * pros::screen::scroll(4, 3); * } * \endcode */ std::uint32_t scroll(const std::int16_t start_line, const std::int16_t lines); /** * Scroll lines within a region on the display * * This function behaves in the same way as `screen_scroll`, except that you * specify a rectangular region within which to scroll lines instead of a start * line. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first corner of the * rectangular region * \param x1, y1 The (x,y) coordinates of the second corner of the * rectangular region * \param lines The number of lines to scroll upwards * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * pros::screen::print(TEXT_MEDIUM, 1, "Line Here"); * // Scrolls area of screen upwards slightly. including line of text * pros::screen::scroll_area(0,0, 400, 200, 3); * } * \endcode */ std::uint32_t scroll_area(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1, std::int16_t lines); /** * Copy a screen region (designated by a rectangle) from an off-screen buffer * to the screen * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first corner of the * rectangular region of the screen * \param x1, y1 The (x,y) coordinates of the second corner of the * rectangular region of the screen * \param buf Off-screen buffer containing screen data * \param stride Off-screen buffer width in pixels, such that image size * is stride-padding * * \return 1 if there were no errors, or PROS_ERR if an error occured taking * or returning the screen mutex. * * \b Example * \code * void opcontrol() { * uint32_t* buf = malloc(sizeof(uint32_t) * 400 * 200); * pros::screen::print(TEXT_MEDIUM, 1, "Line Here"); * // Copies area of the screen including text * pros::screen::copy_area(0, 0, 400, 200, (uint32_t*)buf, 400 + 1); * // Equation for stride is x2 - x1 + 1 * } * \endcode */ std::uint32_t copy_area(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1, uint32_t* buf, const std::int32_t stride); /** * Draw a single pixel on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the pixel * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * int i = 0; * void opcontrol() { * while(i < 200){ * pros::screen::draw_pixel(100,i++); * // Draws a line at x = 100 gradually down the screen, pixel by pixel * pros::delay(200); * } * } * \endcode */ std::uint32_t draw_pixel(const std::int16_t x, const std::int16_t y); /** * Erase a pixel from the screen (Sets the location) * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the erased * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Color the Screen in Red * pros::screen::set_pen(red); * pros::screen::fill_rect(0,0,400,200); * int i = 0; * while(i < 200){ * pros::screen::erase_pixel(100,i++); * // Erases a line at x = 100 gradually down the screen, pixel by pixel * pros::delay(200); * } * } * \endcode */ std::uint32_t erase_pixel(const std::int16_t x, const std::int16_t y); /** * Draw a line on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x, y) coordinates of the first point of the line * \param x1, y1 The (x, y) coordinates of the second point of the line * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * pros::screen::set_pen(red); * // Draw line down the screen at x = 100 * pros::screen::draw_line(100,0,100,200); * } * \endcode */ std::uint32_t draw_line(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1); /** * Erase a line on the screen using the current eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x, y) coordinates of the first point of the line * \param x1, y1 The (x, y) coordinates of the second point of the line * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Color the Screen in Red * pros::screen::set_pen(red); * pros::screen::fill_rect(0,0,400,200); * // Erase line down the screen at x = 100 * pros::screen::erase_line(100,0,100,200); * } * \endcode */ std::uint32_t erase_line(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1); /** * Draw a rectangle on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first point of the rectangle * \param x1, y1 The (x,y) coordinates of the second point of the rectangle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * pros::screen::set_pen(red); * pros::screen::draw_rect(1,1,480,200); * } * \endcode */ std::uint32_t draw_rect(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1); /** * Erase a rectangle on the screen using the current eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first point of the rectangle * \param x1, y1 The (x,y) coordinates of the second point of the rectangle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Draw Box Around Half the Screen in Red * pros::screen::set_eraser(red); * pros::screen::erase_rect(5,5,240,200); * } * \endcode */ std::uint32_t erase_rect(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1); /** * Fill a rectangular region of the screen using the current pen * color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x0, y0 The (x,y) coordinates of the first point of the rectangle * \param x1, y1 The (x,y) coordinates of the second point of the rectangle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Fill Around Half the Screen in Red * pros::screen::set_pen(red); * pros::screen::fill_rect(5,5,240,200); * } * \endcode */ std::uint32_t fill_rect(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1); /** * Draw a circle on the screen using the current pen color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the center of the circle * \param r The radius of the circle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * // Draw a circle with radius of 100 in red * pros::screen::set_pen(red); * pros::screen::draw_circle(240, 200, 100); * } * \endcode */ std::uint32_t draw_circle(const std::int16_t x, const std::int16_t y, const std::int16_t radius); /** * Erase a circle on the screen using the current eraser color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the center of the circle * \param r The radius of the circle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * pros::screen::set_pen(red); * pros::screen::fill_rect(5,5,240,200); * // Erase a circle with radius of 100 in blue * pros::screen::set_pen(blue); * pros::screen::erase_circle(240, 200, 100); * } * \endcode */ std::uint32_t erase_circle(const std::int16_t x, const std::int16_t y, const std::int16_t radius); /** * Fill a circular region of the screen using the current pen * color * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param x, y The (x,y) coordinates of the center of the circle * \param r The radius of the circle * * \return 1 if there were no errors, or PROS_ERR if an error occured * taking or returning the screen mutex. * * \b Example * \code * void opcontrol() { * pros::screen::set_pen(red); * pros::screen::fill_rect(5,5,240,200); * // Fill a circlular area with radius of 100 in blue * pros::screen::set_pen(blue); * pros::screen::fill_circle(240, 200, 100); * } * \endcode */ std::uint32_t fill_circle(const std::int16_t x, const std::int16_t y, const std::int16_t radius); /******************************************************************************/ /** Screen Text Display Functions **/ /** **/ /** These functions allow programmers to display text on the v5 screen **/ /******************************************************************************/ /** * Print a formatted string to the screen, overwrite available for printing at location too. * * Will default to a medium sized font by default if invalid txt_fmt is given. * * \param txt_fmt Text format enum that determines if the text is medium, large, medium_center, or large_center. (DOES NOT SUPPORT SMALL) * \param line The line number on which to print * \param x The (x,y) coordinates of the top left corner of the string * \param y The (x,y) coordinates of the top left corner of the string * \param fmt Format string * \param ... Optional list of arguments for the format string * * \b Example * \code * void opcontrol() { * int i = 0; * pros::screen::set_pen(blue); * while(1){ * // Will print seconds started since program started on line 3 * pros::screen::print(pros::TEXT_MEDIUM, 3, "Seconds Passed: %3d", i++); * pros::delay(1000); * } * } */ template void print(pros::text_format_e_t txt_fmt, const std::int16_t line, const char* text, Params... args){ pros::c::screen_print(txt_fmt, line, text, convert_args(args)...); } template void print(pros::text_format_e_t txt_fmt, const std::int16_t x, const std::int16_t y, const char* text, Params... args){ pros::c::screen_print_at(txt_fmt, x, y, text, convert_args(args)...); } /******************************************************************************/ /** Screen Touch Functions **/ /** **/ /** These functions allow programmers to access **/ /** information about screen touches **/ /******************************************************************************/ /** * Gets the touch status of the last touch of the screen. * * \return The last_touch_e_t enum specifier that indicates the last touch status of the screen (E_TOUCH_EVENT_RELEASE, E_TOUCH_EVENT_PRESS, or E_TOUCH_EVENT_PRESS_AND_HOLD). * This will be released by default if no action was taken. * If an error occured, the screen_touch_status_s_t will have its * last_touch_e_t enum specifier set to E_TOUCH_ERR, and other values set to -1. * * \b Example * \code * void opcontrol() { * int i = 0; * pros::screen_touch_status_s_t status; * while(1){ * status = pros::touch_status(); * * // Will print various information about the last touch * pros::screen::print(TEXT_MEDIUM, 1, "Touch Status (Type): %d", status.touch_status); * pros::screen::print(TEXT_MEDIUM, 2, "Last X: %d", status.x); * pros::screen::print(TEXT_MEDIUM, 3, "Last Y: %d", status.y); * pros::screen::print(TEXT_MEDIUM, 4, "Press Count: %d", status.press_count); * pros::screen::print(TEXT_MEDIUM, 5, "Release Count: %d", status.release_count); * pros::delay(20); * } * } * \endcode */ screen_touch_status_s_t touch_status(); /** * Assigns a callback function to be called when a certain touch event happens. * * This function uses the following values of errno when an error state is * reached: * EACCESS - Another resource is currently trying to access the screen mutex. * * \param cb Function pointer to callback when event type happens * \param event_type Touch event that will trigger the callback. * * \return 1 if there were no errors, or PROS_ERR if an error occured * while taking or returning the screen mutex. * * \b Example * \code * touch_event_cb_fn_t changePixel(){ * pros::screen_touch_status_s_t status = pros::screen::touch_status(); * pros::screen::draw_pixel(status.x,status.y); * return NULL; * } * * void opcontrol() { * pros::screen::touch_callback(changePixel(), TOUCH_PRESSED); * while(1) { * pros::delay(20); * } * } * \endcode */ std::uint32_t touch_callback(touch_event_cb_fn_t cb, last_touch_e_t event_type); } // namespace screen } // namespace pros extern __attribute__((weak)) void lvgl_init() {} ///@} #endif //header guard ================================================ FILE: include/pros/serial.h ================================================ /** * \file pros/serial.h * \ingroup c-serial * * Contains prototypes for the V5 Generic Serial related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-serial Generic Serial C API */ #ifndef _PROS_SERIAL_H_ #define _PROS_SERIAL_H_ #include #include #ifdef __cplusplus extern "C" { namespace pros { namespace c { #endif /** * \ingroup c-serial */ /** * \addtogroup c-serial * @{ */ /// \name Serial communication functions /// These functions allow programmers to communicate using UART over RS485 ///@{ /** * Enables generic serial on the given port. * * \note This function must be called before any of the generic serial * functions will work. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * } * \endcode */ int32_t serial_enable(uint8_t port); /** * Sets the baudrate for the serial port to operate at. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * \param baudrate * The baudrate to operate at * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * serial_write(1, "Hello World!", 12); * delay(100); * } * } * \endcode */ int32_t serial_set_baudrate(uint8_t port, int32_t baudrate); /** * Clears the internal input and output FIFO buffers. * * This can be useful to reset state and remove old, potentially unneeded data * from the input FIFO buffer or to cancel sending any data in the output FIFO * buffer. * * \note This function does not cause the data in the output buffer to be * written, it simply clears the internal buffers. Unlike stdout, generic * serial does not use buffered IO (the FIFO buffers are written as soon * as possible). * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * serial_flush(1); * serial_write(1, "Hello World!", 12); * delay(100); * } * } * \endcode */ int32_t serial_flush(uint8_t port); /** * Returns the number of bytes available to be read in the the port's FIFO * input buffer. * * \note This function does not actually read any bytes, is simply returns the * number of bytes available to be read. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \return The number of bytes avaliable to be read or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_get_read_avail(1) >= 12) { * char buffer[12]; * serial_read(1, buffer, 12); * printf("%s", buffer); * } * delay(100); * } * } * \endcode */ int32_t serial_get_read_avail(uint8_t port); /** * Returns the number of bytes free in the port's FIFO output buffer. * * \note This function does not actually write any bytes, is simply returns the * number of bytes free in the port's buffer. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \return The number of bytes free or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_get_write_free(1) >= 12) { * serial_write(1, "Hello World!", 12); * } * delay(100); * } * } * \endcode */ int32_t serial_get_write_free(uint8_t port); /** * Reads the next byte avaliable in the port's input buffer without removing it. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \return The next byte avaliable to be read, -1 if none are available, or * PROS_ERR if the operation failed, setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_peek_byte(1) == 'H') { * char buffer[12]; * serial_read(1, buffer, 12); * printf("%s", buffer); * } * delay(100); * } * } * \endcode */ int32_t serial_peek_byte(uint8_t port); /** * Reads the next byte avaliable in the port's input buffer. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \return The next byte avaliable to be read, -1 if none are available, or * PROS_ERR if the operation failed, setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_read_byte(1) == 'H') { * char buffer[12]; * serial_read(1, buffer, 12); * printf("%s", buffer); * } * delay(100); * } * } * \endcode */ int32_t serial_read_byte(uint8_t port); /** * Reads up to the next length bytes from the port's input buffer and places * them in the user supplied buffer. * * \note This function will only return bytes that are currently avaliable to be * read and will not block waiting for any to arrive. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * \param buffer * The location to place the data read * \param length * The maximum number of bytes to read * * \return The number of bytes read or PROS_ERR if the operation failed, setting * errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_get_read_avail(1) >= 12) { * char buffer[12]; * serial_read(1, buffer, 12); * printf("%s", buffer); * } * delay(100); * } * } * \endcode */ int32_t serial_read(uint8_t port, uint8_t* buffer, int32_t length); /** * Write the given byte to the port's output buffer. * * \note Data in the port's output buffer is written to the serial port as soon * as possible on a FIFO basis and can not be done manually by the user. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * EIO - Serious internal write error. * * \param port * The V5 port number from 1-21 * \param buffer * The byte to write * * \return The number of bytes written or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_get_write_free(1) >= 12) { * serial_write_byte(1, 'H'); * serial_write_byte(1, 'e'); * serial_write_byte(1, 'l'); * serial_write_byte(1, 'l'); * serial_write_byte(1, 'o'); * serial_write_byte(1, ' '); * serial_write_byte(1, 'W'); * serial_write_byte(1, 'o'); * serial_write_byte(1, 'r'); * serial_write_byte(1, 'l'); * serial_write_byte(1, 'd'); * serial_write_byte(1, '!'); * serial_write_byte(1, '\n'); * } * delay(100); * } * } * \endcode */ int32_t serial_write_byte(uint8_t port, uint8_t buffer); /** * Writes up to length bytes from the user supplied buffer to the port's output * buffer. * * \note Data in the port's output buffer is written to the serial port as soon * as possible on a FIFO basis and can not be done manually by the user. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * EIO - Serious internal write error. * * \param port * The V5 port number from 1-21 * \param buffer * The data to write * \param length * The maximum number of bytes to write * * \return The number of bytes written or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code{.c} * void opcontrol() { * serial_enable(1); * serial_set_baudrate(1, 9600); * while (true) { * if (serial_get_write_free(1) >= 12) { * serial_write(1, "Hello World!\n", 12); * } * delay(100); * } * } * \endcode */ int32_t serial_write(uint8_t port, uint8_t* buffer, int32_t length); ///@} ///@} #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_SERIAL_H_ ================================================ FILE: include/pros/serial.hpp ================================================ /** * \file pros/serial.hpp * \ingroup cpp-serial * * Contains prototypes for the V5 Generic Serial related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-serial Generic Serial C++ API */ #ifndef _PROS_SERIAL_HPP_ #define _PROS_SERIAL_HPP_ #include #include "pros/device.hpp" #include "pros/serial.h" namespace pros { /** * \ingroup cpp-serial * @{ */ class Serial : public Device { /** * \addtogroup cpp-serial * @{ */ public: /** * Creates a Serial object for the given port and specifications. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * \param baudrate * The baudrate to run the port at * * \b Example: * \code * pros::Serial serial(1, 9600); * \endcode */ explicit Serial(std::uint8_t port, std::int32_t baudrate); /** * Creates a Serial object for the given port without a set baudrate. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 1-21 * * \b Example: * \code * pros::Serial serial(1); * \endcode */ explicit Serial(std::uint8_t port); /******************************************************************************/ /** Serial communication functions **/ /** **/ /** These functions allow programmers to communicate using UART over RS485 **/ /******************************************************************************/ /** * Sets the baudrate for the serial port to operate at. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param baudrate * The baudrate to operate at * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code * pros::Serial serial(1); * serial.set_baudrate(9600); * \endcode */ virtual std::int32_t set_baudrate(std::int32_t baudrate) const; /** * Clears the internal input and output FIFO buffers. * * This can be useful to reset state and remove old, potentially unneeded data * from the input FIFO buffer or to cancel sending any data in the output FIFO * buffer. * * \note This function does not cause the data in the output buffer to be * written, it simply clears the internal buffers. Unlike stdout, generic * serial does not use buffered IO (the FIFO buffers are written as soon * as possible). * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code * pros::Serial serial(1); * serial.flush(); * \endcode */ virtual std::int32_t flush() const; /** * Returns the number of bytes available to be read in the the port's FIFO * input buffer. * * \note This function does not actually read any bytes, is simply returns the * number of bytes available to be read. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \return The number of bytes avaliable to be read or PROS_ERR if the operation * failed, setting errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * if(serial.get_read_avail() > 0) { * std::uint8_t byte = serial.read_byte(); * } * } * \endcode */ virtual std::int32_t get_read_avail() const; /** * Returns the number of bytes free in the port's FIFO output buffer. * * \note This function does not actually write any bytes, is simply returns the * number of bytes free in the port's buffer. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \return The number of bytes free or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * if(serial.get_write_free() > 0) { * serial.write_byte(0x01); * pros::delay(10); * } * } * \endcode */ virtual std::int32_t get_write_free() const; /** * Reads the next byte avaliable in the port's input buffer without removing it. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \return The next byte avaliable to be read, -1 if none are available, or * PROS_ERR if the operation failed, setting errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * if(serial.peek_byte() == 0x01) { * serial.read_byte(); * } * } * \endcode */ virtual std::int32_t peek_byte() const; /** * Reads the next byte avaliable in the port's input buffer. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \return The next byte avaliable to be read, -1 if none are available, or * PROS_ERR if the operation failed, setting errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * if(serial.read_byte() == 0x01) { * // Do something * } * } * \endcode */ virtual std::int32_t read_byte() const; /** * Reads up to the next length bytes from the port's input buffer and places * them in the user supplied buffer. * * \note This function will only return bytes that are currently avaliable to be * read and will not block waiting for any to arrive. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param buffer * The location to place the data read * \param length * The maximum number of bytes to read * * \return The number of bytes read or PROS_ERR if the operation failed, setting * errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * std::uint8_t buffer[10]; * serial.read(buffer, 10); * } * \endcode */ virtual std::int32_t read(std::uint8_t* buffer, std::int32_t length) const; /** * Write the given byte to the port's output buffer. * * \note Data in the port's output buffer is written to the serial port as soon * as possible on a FIFO basis and can not be done manually by the user. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * EIO - Serious internal write error. * * \param buffer * The byte to write * * \return The number of bytes written or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * serial.write_byte(0x01); * } * \endcode */ virtual std::int32_t write_byte(std::uint8_t buffer) const; /** * Writes up to length bytes from the user supplied buffer to the port's output * buffer. * * \note Data in the port's output buffer is written to the serial port as soon * as possible on a FIFO basis and can not be done manually by the user. * * This function uses the following values of errno when an error state is * reached: * EINVAL - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * EIO - Serious internal write error. * * \param buffer * The data to write * \param length * The maximum number of bytes to write * * \return The number of bytes written or PROS_ERR if the operation failed, * setting errno. * * \b Example: * \code * void opcontrol() { * pros::Serial serial(1); * std::uint8_t buffer[10]; * serial.write(buffer, 10); * } * \endcode */ virtual std::int32_t write(std::uint8_t* buffer, std::int32_t length) const; private: ///@} }; namespace literals { /** * Constructs a Serial device from a litteral ending in _ser * * \return a pros::Serial for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Serial serial = 2_ser; //Makes an Serial device object on port 2 * } * \endcode */ const pros::Serial operator""_ser(const unsigned long long int m); } // namespace literals } // namespace pros #endif // _PROS_SERIAL_HPP_ ================================================ FILE: include/pros/version.h ================================================ /** * \file version.h * * PROS Version Information * * Contains PROS kernel version information * * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #define PROS_VERSION_MAJOR 4 #define PROS_VERSION_MINOR 2 #define PROS_VERSION_PATCH 1 #define PROS_VERSION_STRING "4.2.1" ================================================ FILE: include/pros/vision.h ================================================ /** * \file pros/vision.h * \ingroup c-vision * * Contains prototypes for the VEX Vision Sensor-related functions. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup c-vision Vision Sensor C API * \note Additional example code for this module can be found in its [Tutorial.](@ref vision) */ #ifndef _PROS_VISION_H_ #define _PROS_VISION_H_ /** * \ingroup c-vision */ /** * \addtogroup c-vision * @{ */ /// \name Macros ///Parameters given by VEX ///@{ #define VISION_OBJECT_ERR_SIG 255 /** * The width of the Vision Sensor’s field of view. */ #define VISION_FOV_WIDTH 316 /** * The height of the Vision Sensor’s field of view. */ #define VISION_FOV_HEIGHT 212 ///@} #include #ifdef __cplusplus extern "C" { namespace pros { #endif /** * \enum vision_object_type_e_t * This enumeration defines the different types of objects that can be detected by the Vision Sensor */ typedef enum vision_object_type { E_VISION_OBJECT_NORMAL = 0, E_VISION_OBJECT_COLOR_CODE = 1, E_VISION_OBJECT_LINE = 2 } vision_object_type_e_t; /** * \struct vision_signature_s_t * This structure contains the parameters used by the Vision Sensor to detect objects. */ typedef struct __attribute__((__packed__)) vision_signature { uint8_t id; uint8_t _pad[3]; float range; int32_t u_min; int32_t u_max; int32_t u_mean; int32_t v_min; int32_t v_max; int32_t v_mean; uint32_t rgb; uint32_t type; } vision_signature_s_t; /** * \typedef vision_color_code_t * Color codes are just signatures with multiple IDs and a different type. */ typedef uint16_t vision_color_code_t; /** * \struct vision_object_s_t * This structure contains a descriptor of an object detected by the Vision Sensor */ typedef struct __attribute__((__packed__)) vision_object { /// Object signature uint16_t signature; /// Object type, e.g. normal, color code, or line detection vision_object_type_e_t type; /// Left boundary coordinate of the object int16_t left_coord; /// Top boundary coordinate of the object int16_t top_coord; /// Width of the object int16_t width; /// Height of the object int16_t height; /// Angle of a color code object in 0.1 degree units (e.g. 10 -> 1 degree, 155 -> 15.5 degrees) uint16_t angle; /// Coordinates of the middle of the object (computed from the values above) int16_t x_middle_coord; /// Coordinates of the middle of the object (computed from the values above) int16_t y_middle_coord; } vision_object_s_t; /** * \enum vision_zero * This enumeration defines different zero points for returned vision objects. */ typedef enum vision_zero { /// (0,0) coordinate is the top left of the FOV E_VISION_ZERO_TOPLEFT = 0, /// (0,0) coordinate is the center of the FOV E_VISION_ZERO_CENTER = 1 } vision_zero_e_t; #ifdef PROS_USE_SIMPLE_NAMES #ifdef __cplusplus #define VISION_OBJECT_NORMAL pros::E_VISION_OBJECT_NORMAL #define VISION_OBJECT_COLOR_CODE pros::E_VISION_OBJECT_COLOR_CODE #define VISION_OBJECT_LINE pros::E_VISION_OBJECT_LINE #define VISION_ZERO_TOPLEFT pros::E_VISION_ZERO_TOPLEFT #define VISION_ZERO_CENTER pros::E_VISION_ZERO_CENTER #else #define VISION_OBJECT_NORMAL E_VISION_OBJECT_NORMAL #define VISION_OBJECT_COLOR_CODE E_VISION_OBJECT_COLOR_CODE #define VISION_OBJECT_LINE E_VISION_OBJECT_LINE #define VISION_ZERO_TOPLEFT E_VISION_ZERO_TOPLEFT #define VISION_ZERO_CENTER E_VISION_ZERO_CENTER #endif #endif #ifdef __cplusplus namespace c { #endif /// \name Functions ///@{ /** * Clears the vision sensor LED color, reseting it back to its default behavior, * displaying the most prominent object signature color. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * void initialize() { * vision_clear_led(VISION_PORT); * } * \endcode */ int32_t vision_clear_led(uint8_t port); /** * Creates a signature from the vision sensor utility * * \param id * The signature ID * \param u_min * Minimum value on U axis * \param u_max * Maximum value on U axis * \param u_mean * Mean value on U axis * \param v_min * Minimum value on V axis * \param v_max * Maximum value on V axis * \param v_mean * Mean value on V axis * \param range * Scale factor * \param type * Signature type * * \return A vision_signature_s_t that can be set using vision_set_signature * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * // values acquired from the vision utility * vision_signature_s_t RED_SIG = * vision_signature_from_utility(EXAMPLE_SIG, 8973, 11143, 10058, -2119, -1053, -1586, 5.4, 0); * vision_set_signature(VISION_PORT, EXAMPLE_SIG, &RED_SIG); * while (true) { * vision_signature_s_t rtn = vision_get_by_sig(VISION_PORT, 0, EXAMPLE_SIG); * // Gets the largest object of the EXAMPLE_SIG signature * printf("sig: %d", rtn.signature); * // Prints "sig: 1" * delay(2); * } * } * \endcode */ vision_signature_s_t vision_signature_from_utility(const int32_t id, const int32_t u_min, const int32_t u_max, const int32_t u_mean, const int32_t v_min, const int32_t v_max, const int32_t v_mean, const float range, const int32_t type); /** * Creates a color code that represents a combination of the given signature * IDs. If fewer than 5 signatures are to be a part of the color code, pass 0 * for the additional function parameters. * * This function uses the following values of errno when an error state is * reached: * EINVAL - Fewer than two signatures have been provided or one of the * signatures is out of its [1-7] range (or 0 when omitted). * * \param port * The V5 port number from 1-21 * \param sig_id1 * The first signature id [1-7] to add to the color code * \param sig_id2 * The second signature id [1-7] to add to the color code * \param sig_id3 * The third signature id [1-7] to add to the color code * \param sig_id4 * The fourth signature id [1-7] to add to the color code * \param sig_id5 * The fifth signature id [1-7] to add to the color code * * \return A vision_color_code_t object containing the color code information. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define OTHER_SIG 2 * * void opcontrol() { * vision_color_code_t code1 = vision_create_color_code(VISION_PORT, EXAMPLE_SIG, OTHER_SIG); * } * \endcode */ vision_color_code_t vision_create_color_code(uint8_t port, const uint32_t sig_id1, const uint32_t sig_id2, const uint32_t sig_id3, const uint32_t sig_id4, const uint32_t sig_id5); /** * Gets the nth largest object according to size_id. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * EHOSTDOWN - Reading the vision sensor failed for an unknown reason. * * \param port * The V5 port number from 1-21 * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * * \return The vision_object_s_t object corresponding to the given size id, or * PROS_ERR if an error occurred. * * \b Example * \code * #define VISION_PORT 1 * * void opcontrol() { * while (true) { * vision_object_s_t rtn = vision_get_by_size(VISION_PORT, 0); * // Gets the largest object * printf("sig: %d", rtn.signature); * delay(2); * } * } * \endcode */ vision_object_s_t vision_get_by_size(uint8_t port, const uint32_t size_id); /** * Gets the nth largest object of the given signature according to size_id. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * EINVAL - sig_id is outside the range [1-8] * EDOM - size_id is greater than the number of available objects. * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param port * The V5 port number from 1-21 * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param signature * The signature ID [1-7] for which an object will be returned. * * \return The vision_object_s_t object corresponding to the given signature and * size_id, or PROS_ERR if an error occurred. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * while (true) { * vision_object_s_t rtn = vision_get_by_sig(VISION_PORT, 0, EXAMPLE_SIG); * // Gets the largest object of the EXAMPLE_SIG signature * printf("sig: %d", rtn.signature); * // Prints "sig: 1" * delay(2); * } * } * \endcode */ vision_object_s_t vision_get_by_sig(uint8_t port, const uint32_t size_id, const uint32_t sig_id); /** * Gets the nth largest object of the given color code according to size_id. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param port * The V5 port number from 1-21 * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param color_code * The vision_color_code_t for which an object will be returned * * \return The vision_object_s_t object corresponding to the given color code * and size_id, or PROS_ERR if an error occurred. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define OTHER_SIG 2 * * void opcontrol() { * vision_color_code_t code1 = vision_create_color_code(VISION_PORT, EXAMPLE_SIG, OTHER_SIG); * while (true) { * vision_object_s_t rtn = vision_get_by_code(VISION_PORT, 0, code1); * // Gets the largest object * printf("sig: %d", rtn.signature); * delay(2); * } * } * \endcode */ vision_object_s_t vision_get_by_code(uint8_t port, const uint32_t size_id, const vision_color_code_t color_code); /** * Gets the exposure parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * * \return The current exposure setting from [0,150], PROS_ERR if an error * occurred * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * if (vision_get_exposure(VISION_PORT) < 50) * vision_set_exposure(VISION_PORT, 50); * } * \endcode */ int32_t vision_get_exposure(uint8_t port); /** * Gets the number of objects currently detected by the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * * \return The number of objects detected on the specified vision sensor. * Returns PROS_ERR if the port was invalid or an error occurred. * * \b Example * \code * #define VISION_PORT 1 * * void opcontrol() { * while (true) { * printf("Number of Objects Detected: %d\n", vision_get_object_count(VISION_PORT)); * delay(2); * } * } * \endcode */ int32_t vision_get_object_count(uint8_t port); /** * Get the white balance parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * * \return The current RGB white balance setting of the sensor * * \b Example * \code * #define VISION_PORT 1 * #define VISION_WHITE 0xff * * void initialize() { * if (vision_get_white_balance(VISION_PORT) != VISION_WHITE) * vision_set_white_balance(VISION_PORT, VISION_WHITE); * } * \endcode */ int32_t vision_get_white_balance(uint8_t port); /** * Prints the contents of the signature as an initializer list to the terminal. * * \param sig * The signature for which the contents will be printed * * \return 1 if no errors occured, PROS_ERR otherwise * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * vision_signature_s_t sig = vision_get_signature(VISION_PORT, EXAMPLE_SIG); * vision_print_signature(sig); * } * \endcode */ int32_t vision_print_signature(const vision_signature_s_t sig); /** * Reads up to object_count object descriptors into object_arr. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21), or * fewer than object_count number of objects were found. * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * * \param port * The V5 port number from 1-21 * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param object_count * The number of objects to read * \param[out] object_arr * A pointer to copy the objects into * * \return The number of object signatures copied. This number will be less than * object_count if there are fewer objects detected by the vision sensor. * Returns PROS_ERR if the port was invalid, an error occurred, or fewer objects * than size_id were found. All objects in object_arr that were not found are * given VISION_OBJECT_ERR_SIG as their signature. * * \b Example * \code * #define VISION_PORT 1 * #define NUM_VISION_OBJECTS 4 * * void opcontrol() { * vision_object_s_t object_arr[NUM_VISION_OBJECTS]; * while (true) { * vision_read_by_size(VISION_PORT, 0, NUM_VISION_OBJECTS, object_arr); * printf("sig: %d", object_arr[0].signature); * // Prints the signature of the largest object found * delay(2); * } * } * \endcode */ int32_t vision_read_by_size(uint8_t port, const uint32_t size_id, const uint32_t object_count, vision_object_s_t* const object_arr); /** * Reads up to object_count object descriptors into object_arr. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21), or * fewer than object_count number of objects were found. * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * * \param port * The V5 port number from 1-21 * \param object_count * The number of objects to read * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param signature * The signature ID [1-7] for which objects will be returned. * \param[out] object_arr * A pointer to copy the objects into * * \return The number of object signatures copied. This number will be less than * object_count if there are fewer objects detected by the vision sensor. * Returns PROS_ERR if the port was invalid, an error occurred, or fewer objects * than size_id were found. All objects in object_arr that were not found are * given VISION_OBJECT_ERR_SIG as their signature. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define NUM_VISION_OBJECTS 4 * * void opcontrol() { * vision_object_s_t object_arr[NUM_VISION_OBJECTS]; * while (true) { * vision_read_by_sig(VISION_PORT, 0, EXAMPLE_SIG, NUM_VISION_OBJECTS, object_arr); * printf("sig: %d", object_arr[0].signature); * // Prints "sig: 1" * delay(2); * } * } * \endcode */ int32_t vision_read_by_sig(uint8_t port, const uint32_t size_id, const uint32_t sig_id, const uint32_t object_count, vision_object_s_t* const object_arr); /** * Reads up to object_count object descriptors into object_arr. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21), or * fewer than object_count number of objects were found. * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * \param object_count * The number of objects to read * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param color_code * The vision_color_code_t for which objects will be returned * \param[out] object_arr * A pointer to copy the objects into * * \return The number of object signatures copied. This number will be less than * object_count if there are fewer objects detected by the vision sensor. * Returns PROS_ERR if the port was invalid, an error occurred, or fewer objects * than size_id were found. All objects in object_arr that were not found are * given VISION_OBJECT_ERR_SIG as their signature. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define OTHER_SIG 2 * #define NUM_VISION_OBJECTS 4 * * void opcontrol() { * vision_object_s_t object_arr[NUM_VISION_OBJECTS]; * vision_color_code_t code1 = vision_create_color_code(VISION_PORT, EXAMPLE_SIG, OTHER_SIG, 0, 0, 0); * while (true) { * vision_read_by_code(VISION_PORT, 0, code1, NUM_VISION_OBJECTS, object_arr); * printf("sig: %d", object_arr[0].signature); * // Prints the signature of the largest object found * delay(2); * } * } * \endcode */ int32_t vision_read_by_code(uint8_t port, const uint32_t size_id, const vision_color_code_t color_code, const uint32_t object_count, vision_object_s_t* const object_arr); /** * Gets the object detection signature with the given id number. * * \param port * The V5 port number from 1-21 * \param signature_id * The signature id to read * * \return A vision_signature_s_t containing information about the signature. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * vision_signature_s_t sig = vision_get_signature(VISION_PORT, EXAMPLE_SIG); * vision_print_signature(sig); * } * \endcode */ vision_signature_s_t vision_get_signature(uint8_t port, const uint8_t signature_id); /** * Stores the supplied object detection signature onto the vision sensor. * * \note This saves the signature in volatile memory, and the signature will be * lost as soon as the sensor is powered down. * * \param port * The V5 port number from 1-21 * \param signature_id * The signature id to store into * \param[in] signature_ptr * A pointer to the signature to save * * \return 1 if no errors occured, PROS_ERR otherwise * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * vision_signature_s_t sig = vision_get_signature(VISION_PORT, EXAMPLE_SIG); * sig.range = 10.0; * vision_set_signature(VISION_PORT, EXAMPLE_SIG, &sig); * } * \endcode */ int32_t vision_set_signature(uint8_t port, const uint8_t signature_id, vision_signature_s_t* const signature_ptr); /** * Enables/disables auto white-balancing on the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * EINVAL - enable was not 0 or 1 * * \param port * The V5 port number from 1-21 * \param enabled * Pass 0 to disable, 1 to enable * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * vision_set_auto_white_balance(VISION_PORT, true); * } * \endcode */ int32_t vision_set_auto_white_balance(uint8_t port, const uint8_t enable); /** * Sets the exposure parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * \param percent * The new exposure setting from [0,150] * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * if (vision_get_exposure(VISION_PORT) < 50) * vision_set_exposure(VISION_PORT, 50); * } * \endcode */ int32_t vision_set_exposure(uint8_t port, const uint8_t exposure); /** * Sets the vision sensor LED color, overriding the automatic behavior. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * \param rgb * An RGB code to set the LED to * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * vision_set_led(VISION_PORT, COLOR_BLANCHED_ALMOND); * } * \endcode */ int32_t vision_set_led(uint8_t port, const int32_t rgb); /** * Sets the white balance parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * \param rgb * The new RGB white balance setting of the sensor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * #define VISION_WHITE 0xff * * void initialize() { * vision_set_white_balance(VISION_PORT, VISION_WHITE); * } * \endcode */ int32_t vision_set_white_balance(uint8_t port, const int32_t rgb); /** * Sets the (0,0) coordinate for the Field of View. * * This will affect the coordinates returned for each request for a * vision_object_s_t from the sensor, so it is recommended that this function * only be used to configure the sensor at the beginning of its use. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * \param zero_point * One of vision_zero_e_t to set the (0,0) coordinate for the FOV * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * vision_set_zero_point(VISION_PORT, E_VISION_ZERO_CENTER); * } * \endcode */ int32_t vision_set_zero_point(uint8_t port, vision_zero_e_t zero_point); /** * Sets the Wi-Fi mode of the Vision sensor * * This functions uses the following values of errno when an error state is * reached: * ENXIO - The given port is not within the range of V5 ports (1-21) * EACCESS - Anothe resources is currently trying to access the port * * \param port * The V5 port number from 1-21 * \param enable * Disable Wi-Fi on the Vision sensor if 0, enable otherwise (e.g. 1) * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * vision_set_wifi_mode(VISION_PORT, 0); * } * \endcode */ int32_t vision_set_wifi_mode(uint8_t port, const uint8_t enable); ///@} ///@} #ifdef __cplusplus } // namespace c } // namespace pros } #endif #endif // _PROS_VISION_H_ ================================================ FILE: include/pros/vision.hpp ================================================ /** * \file pros/vision.hpp * \ingroup cpp-vision * * Contains prototypes for the VEX Vision Sensor-related functions in C++. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \defgroup cpp-vision Vision Sensor C++ API * \note Additional example code for this module can be found in its [Tutorial.](@ref vision) */ #ifndef _PROS_VISION_HPP_ #define _PROS_VISION_HPP_ #include #include "pros/device.hpp" #include "pros/vision.h" namespace pros { inline namespace v5 { /** * \ingroup cpp-vision */ class Vision : public Device { /** * \addtogroup cpp-vision * @{ */ public: /** * Create a Vision Sensor object on the given port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * ENODEV - The port cannot be configured as a vision sensor * * \param port * The V5 port number from 1-21 * \param zero_point * One of vision_zero_e_t to set the (0,0) coordinate for the FOV * * \b Example * \code * void opcontrol() { * pros::Vision vision_sensor(1); // Creates a vision sensor on port one, with the zero point set to top left * } * \endcode */ Vision(std::uint8_t port, vision_zero_e_t zero_point = E_VISION_ZERO_TOPLEFT); Vision(const Device& device) : Vision(device.get_port()){}; /** * Clears the vision sensor LED color, reseting it back to its default * behavior, displaying the most prominent object signature color. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * void initialize() { * pros::Vision vision_sensor(1); * vision_sensor.clear_led(); * } * \endcode */ std::int32_t clear_led(void) const; /** * Creates a signature from the vision sensor utility * * \param id * The signature ID * \param u_min * Minimum value on U axis * \param u_max * Maximum value on U axis * \param u_mean * Mean value on U axis * \param v_min * Minimum value on V axis * \param v_max * Maximum value on V axis * \param v_mean * Mean value on V axis * \param rgb * Scale factor * \param type * Signature type * * \return A vision_signature_s_t that can be set using Vision::set_signature * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * // values acquired from the vision utility * vision_signature_s_t RED_SIG = * vision_signature_from_utility(EXAMPLE_SIG, 8973, 11143, 10058, -2119, -1053, -1586, 5.4, 0); * vision_sensor.set_signature(EXAMPLE_SIG, &RED_SIG); * while (true) { * vision_signature_s_t rtn = vision_sensor.get_by_sig(VISION_PORT, 0, EXAMPLE_SIG); * // Gets the largest object of the EXAMPLE_SIG signature * printf("sig: %d", rtn.signature); * // Prints "sig: 1" * delay(2); * } * } * \endcode */ static vision_signature_s_t signature_from_utility(const std::int32_t id, const std::int32_t u_min, const std::int32_t u_max, const std::int32_t u_mean, const std::int32_t v_min, const std::int32_t v_max, const std::int32_t v_mean, const float range, const std::int32_t type); /** * Creates a color code that represents a combination of the given signature * IDs. * * This function uses the following values of errno when an error state is * reached: * EINVAL - Fewer than two signatures have been provided or one of the * signatures is out of its [1-7] range (or 0 when omitted). * * \param sig_id1 * The first signature id [1-7] to add to the color code * \param sig_id2 * The second signature id [1-7] to add to the color code * \param sig_id3 * The third signature id [1-7] to add to the color code * \param sig_id4 * The fourth signature id [1-7] to add to the color code * \param sig_id5 * The fifth signature id [1-7] to add to the color code * * \return A vision_color_code_t object containing the color code information. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define OTHER_SIG 2 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_color_code_t code1 = vision_sensor.create_color_code(EXAMPLE_SIG, OTHER_SIG); * } * \endcode */ vision_color_code_t create_color_code(const std::uint32_t sig_id1, const std::uint32_t sig_id2, const std::uint32_t sig_id3 = 0, const std::uint32_t sig_id4 = 0, const std::uint32_t sig_id5 = 0) const; /** * Gets all vision sensors. * * \return A vector of Vision sensor objects. * * \b Example * \code * void opcontrol() { * std::vector vision_all = pros::Vision::get_all_devices(); // All vision sensors that are connected * } * \endcode */ static std::vector get_all_devices(); /** * Gets the nth largest object according to size_id. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * * \return The vision_object_s_t object corresponding to the given size id, or * PROS_ERR if an error occurred. * * \b Example * \code * #define VISION_PORT 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * while (true) { * vision_object_s_t rtn = vision_sensor.get_by_size(0); * // Gets the largest object * printf("sig: %d", rtn.signature); * delay(2); * } * } * \endcode */ vision_object_s_t get_by_size(const std::uint32_t size_id) const; /** * Gets the nth largest object of the given signature according to size_id. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * EINVAL - sig_id is outside the range [1-8] * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param signature * The vision_signature_s_t signature for which an object will be * returned. * * \return The vision_object_s_t object corresponding to the given signature * and size_id, or PROS_ERR if an error occurred. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * while (true) { * vision_object_s_t rtn = vision_sensor.get_by_sig(0, EXAMPLE_SIG); * // Gets the largest object of the EXAMPLE_SIG signature * printf("sig: %d", rtn.signature); * // Prints "sig: 1" * delay(2); * } * } * \endcode */ vision_object_s_t get_by_sig(const std::uint32_t size_id, const std::uint32_t sig_id) const; /** * Gets the nth largest object of the given color code according to size_id. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * EAGAIN - Reading the Vision Sensor failed for an unknown reason. * * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param color_code * The vision_color_code_t for which an object will be returned * * \return The vision_object_s_t object corresponding to the given color code * and size_id, or PROS_ERR if an error occurred. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define OTHER_SIG 2 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_color_code_t code1 = vision_sensor.create_color_code(EXAMPLE_SIG, OTHER_SIG); * while (true) { * vision_object_s_t rtn = vision_sensor.get_by_code(0, code1); * // Gets the largest object * printf("sig: %d", rtn.signature); * delay(2); * } * } * \endcode */ vision_object_s_t get_by_code(const std::uint32_t size_id, const vision_color_code_t color_code) const; /** * Gets the exposure parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \return The current exposure parameter from [0,150], * PROS_ERR if an error occurred * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * if (vision_sensor.get_exposure() < 50) * vision_sensor.set_exposure(50); * } * \endcode */ std::int32_t get_exposure(void) const; /** * Gets the number of objects currently detected by the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \return The number of objects detected on the specified vision sensor. * Returns PROS_ERR if the port was invalid or an error occurred. * * \b Example * \code * #define VISION_PORT 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * while (true) { * printf("Number of Objects Detected: %d\n", vision_sensor.get_object_count()); * delay(2); * } * } * \endcode */ std::int32_t get_object_count(void) const; /** * Gets the object detection signature with the given id number. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param signature_id * The signature id to read * * \return A vision_signature_s_t containing information about the signature. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_signature_s_t sig = vision_sensor.get_signature(EXAMPLE_SIG); * vision_sensor.print_signature(sig); * } * \endcode */ vision_signature_s_t get_signature(const std::uint8_t signature_id) const; /** * Get the white balance parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \return The current RGB white balance setting of the sensor * * \b Example * \code * #define VISION_PORT 1 * #define VISION_WHITE 0xff * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * if (vision_sensor.get_white_balance() != VISION_WHITE) * vision_sensor.set_white_balance(VISION_WHITE); * } * \endcode */ std::int32_t get_white_balance(void) const; /** * Reads up to object_count object descriptors into object_arr. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param object_count * The number of objects to read * \param[out] object_arr * A pointer to copy the objects into * * \return The number of object signatures copied. This number will be less than * object_count if there are fewer objects detected by the vision sensor. * Returns PROS_ERR if the port was invalid, an error occurred, or fewer objects * than size_id were found. All objects in object_arr that were not found are * given VISION_OBJECT_ERR_SIG as their signature. * * \b Example * \code * #define VISION_PORT 1 * #define NUM_VISION_OBJECTS 4 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_object_s_t object_arr[NUM_VISION_OBJECTS]; * while (true) { * vision_sensor.read_by_size(0, NUM_VISION_OBJECTS, object_arr); * printf("sig: %d", object_arr[0].signature); * // Prints the signature of the largest object found * delay(2); * } * } * \endcode */ std::int32_t read_by_size(const std::uint32_t size_id, const std::uint32_t object_count, vision_object_s_t* const object_arr) const; /** * Reads up to object_count object descriptors into object_arr. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * EDOM - size_id is greater than the number of available objects. * EINVAL - sig_id is outside the range [1-8] * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param object_count * The number of objects to read * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param signature * The vision_signature_s_t signature for which an object will be * returned. * \param[out] object_arr * A pointer to copy the objects into * * \return The number of object signatures copied. This number will be less than * object_count if there are fewer objects detected by the vision sensor. * Returns PROS_ERR if the port was invalid, an error occurred, or fewer objects * than size_id were found. All objects in object_arr that were not found are * given VISION_OBJECT_ERR_SIG as their signature. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define NUM_VISION_OBJECTS 4 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_object_s_t object_arr[NUM_VISION_OBJECTS]; * while (true) { * vision_sensor.read_by_sig(0, EXAMPLE_SIG, NUM_VISION_OBJECTS, object_arr); * printf("sig: %d", object_arr[0].signature); * // Prints "sig: 1" * delay(2); * } * } * \endcode */ std::int32_t read_by_sig(const std::uint32_t size_id, const std::uint32_t sig_id, const std::uint32_t object_count, vision_object_s_t* const object_arr) const; /** * Reads up to object_count object descriptors into object_arr. * * This function uses the following values of errno when an error state is * reached: * EDOM - size_id is greater than the number of available objects. * ENODEV - The port cannot be configured as a vision sensor * EAGAIN - Reading the vision sensor failed for an unknown reason. * * \param object_count * The number of objects to read * \param size_id * The object to read from a list roughly ordered by object size * (0 is the largest item, 1 is the second largest, etc.) * \param color_code * The vision_color_code_t for which objects will be returned * \param[out] object_arr * A pointer to copy the objects into * * \return The number of object signatures copied. This number will be less than * object_count if there are fewer objects detected by the vision sensor. * Returns PROS_ERR if the port was invalid, an error occurred, or fewer objects * than size_id were found. All objects in object_arr that were not found are * given VISION_OBJECT_ERR_SIG as their signature. * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * #define OTHER_SIG 2 * #define NUM_VISION_OBJECTS 4 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_object_s_t object_arr[NUM_VISION_OBJECTS]; * vision_color_code_t code1 = vision_sensor.create_color_code(EXAMPLE_SIG, OTHER_SIG, 0, 0, 0); * while (true) { * vision_sensor.read_by_code(0, code1, NUM_VISION_OBJECTS, object_arr); * printf("sig: %d", object_arr[0].signature); * // Prints the signature of the largest object found * delay(2); * } * } * \endcode */ int32_t read_by_code(const std::uint32_t size_id, const vision_color_code_t color_code, const std::uint32_t object_count, vision_object_s_t* const object_arr) const; /** * Prints the contents of the signature as an initializer list to the terminal. * * \param sig * The signature for which the contents will be printed * * \return 1 if no errors occured, PROS_ERR otherwise * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_signature_s_t sig = visionsensor.get_signature(EXAMPLE_SIG); * vision_print_signature(sig); * } * \endcode */ static std::int32_t print_signature(const vision_signature_s_t sig); /** * Enables/disables auto white-balancing on the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param enabled * Pass 0 to disable, 1 to enable * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * vision_sensor.set_auto_white_balance(true); * } * \endcode */ std::int32_t set_auto_white_balance(const std::uint8_t enable) const; /** * Sets the exposure parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param percent * The new exposure setting from [0,150]. * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * if (vision_sensor.get_exposure() < 50) * vision_sensor.set_exposure(50); * } * \endcode */ std::int32_t set_exposure(const std::uint8_t exposure) const; /** * Sets the vision sensor LED color, overriding the automatic behavior. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param rgb * An RGB code to set the LED to * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * vision_sensor.set_led(COLOR_BLANCHED_ALMOND); * } * \endcode */ std::int32_t set_led(const std::int32_t rgb) const; /** * Stores the supplied object detection signature onto the vision sensor. * * NOTE: This saves the signature in volatile memory, and the signature will be * lost as soon as the sensor is powered down. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * EINVAL - sig_id is outside the range [1-8] * * \param signature_id * The signature id to store into * \param[in] signature_ptr * A pointer to the signature to save * * \return 1 if no errors occured, PROS_ERR otherwise * * \b Example * \code * #define VISION_PORT 1 * #define EXAMPLE_SIG 1 * * void opcontrol() { * pros::Vision vision_sensor(VISION_PORT); * vision_signature_s_t sig = vision_sensor.get_signature(EXAMPLE_SIG); * sig.range = 10.0; * vision_sensor.set_signature(EXAMPLE_SIG, &sig); * } * \endcode */ std::int32_t set_signature(const std::uint8_t signature_id, vision_signature_s_t* const signature_ptr) const; /** * Sets the white balance parameter of the Vision Sensor. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param rgb * The new RGB white balance setting of the sensor * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * #define VISION_WHITE 0xff * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * vision_sensor.set_white_balance(VISION_WHITE); * } * \endcode */ std::int32_t set_white_balance(const std::int32_t rgb) const; /** * Sets the (0,0) coordinate for the Field of View. * * This will affect the coordinates returned for each request for a * vision_object_s_t from the sensor, so it is recommended that this function * only be used to configure the sensor at the beginning of its use. * * This function uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param zero_point * One of vision_zero_e_t to set the (0,0) coordinate for the FOV * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * vision_sensor.set_zero_point(E_VISION_ZERO_CENTER); * } * \endcode */ std::int32_t set_zero_point(vision_zero_e_t zero_point) const; /** * Sets the Wi-Fi mode of the Vision sensor * * This functions uses the following values of errno when an error state is * reached: * ENODEV - The port cannot be configured as a vision sensor * * \param enable * Disable Wi-Fi on the Vision sensor if 0, enable otherwise (e.g. 1) * * \return 1 if the operation was successful or PROS_ERR if the operation * failed, setting errno. * * \b Example * \code * #define VISION_PORT 1 * * void initialize() { * pros::Vision vision_sensor(VISION_PORT); * vision_sensor.set_wifi_mode(0); * } * \endcode */ std::int32_t set_wifi_mode(const std::uint8_t enable) const; /** * Gets a vision sensor that is plugged in to the brain * * \note The first time this function is called it returns the vision sensor at the lowest port * If this function is called multiple times, it will cycle through all the ports. * For example, if you have 1 vision sensor on the robot * this function will always return a vision sensor object for that port. * If you have 2 vision sensors, all the odd numered calls to this function will return objects * for the lower port number, * all the even number calls will return vision objects for the higher port number * * * This functions uses the following values of errno when an error state is * reached: * ENODEV - No vision sensor is plugged into the brain * * \return A vision object corresponding to a port that a vision sensor is connected to the brain * If no vision sensor is plugged in, it returns a vision sensor on port PROS_ERR_BYTE * */ static Vision get_vision(); private: ///@} }; } // namespace v5 namespace literals { /** * Constructs a Vision sensor from a litteral ending in _vis * * \return a pros::Vision for the corresponding port * * \b Example * \code * using namespace pros::literals; * void opcontrol() { * pros::Vision vision = 2_vis; //Makes an Vision sensor object on port 2 * } * \endcode */ const pros::Vision operator""_vis(const unsigned long long int m); } // namespace literals } // namespace pros #endif // _PROS_VISION_HPP_ ================================================ FILE: include/rtos/FreeRTOS.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef INC_FREERTOS_H #define INC_FREERTOS_H /* * Include the generic headers required for the FreeRTOS port being used. */ #include #include #include #include /* * If stdint.h cannot be located then: * + If using GCC ensure the -nostdint options is *not* being used. * + Ensure the project's include path includes the directory in which your * compiler stores stdint.h. * + Set any compiler options necessary for it to support C99, as technically * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any * other way). * + The FreeRTOS download includes a simple stdint.h definition that can be * used in cases where none is provided by the compiler. The files only * contains the typedefs required to build FreeRTOS. Read the instructions * in FreeRTOS/source/stdint.readme for more information. */ #include /* READ COMMENT ABOVE. */ #ifdef __cplusplus extern "C" { #endif /* Application specific configuration options. */ #include "FreeRTOSConfig.h" /* Basic FreeRTOS definitions. */ #include "projdefs.h" /* Definitions specific to the port being used. */ #include "portable.h" /* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ #ifndef configUSE_NEWLIB_REENTRANT #define configUSE_NEWLIB_REENTRANT 0 #endif /* Required if struct _reent is used. */ #if ( configUSE_NEWLIB_REENTRANT == 1 ) #include #endif /* * Check all the required application specific macros have been defined. * These macros are application specific and (as downloaded) are defined * within FreeRTOSConfig.h. */ #ifndef configMINIMAL_STACK_SIZE #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. #endif #ifndef configMAX_PRIORITIES #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. #endif #if configMAX_PRIORITIES < 1 #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. #endif #ifndef configUSE_PREEMPTION #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_IDLE_HOOK #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_TICK_HOOK #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_16_BIT_TICKS #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. #endif #ifndef configUSE_CO_ROUTINES #define configUSE_CO_ROUTINES 0 #endif #ifndef INCLUDE_vTaskPrioritySet #define INCLUDE_vTaskPrioritySet 0 #endif #ifndef INCLUDE_uxTaskPriorityGet #define INCLUDE_uxTaskPriorityGet 0 #endif #ifndef INCLUDE_vTaskDelete #define INCLUDE_vTaskDelete 0 #endif #ifndef INCLUDE_vTaskSuspend #define INCLUDE_vTaskSuspend 0 #endif #ifndef INCLUDE_vTaskDelayUntil #define INCLUDE_vTaskDelayUntil 0 #endif #ifndef INCLUDE_vTaskDelay #define INCLUDE_vTaskDelay 0 #endif #ifndef INCLUDE_xTaskGetIdleTaskHandle #define INCLUDE_xTaskGetIdleTaskHandle 0 #endif #ifndef INCLUDE_xTaskAbortDelay #define INCLUDE_xTaskAbortDelay 0 #endif #ifndef INCLUDE_xQueueGetMutexHolder #define INCLUDE_xQueueGetMutexHolder 0 #endif #ifndef INCLUDE_xSemaphoreGetMutexHolder #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder #endif #ifndef INCLUDE_xTaskGetHandle #define INCLUDE_xTaskGetHandle 0 #endif #ifndef INCLUDE_uxTaskGetStackHighWaterMark #define INCLUDE_uxTaskGetStackHighWaterMark 0 #endif #ifndef INCLUDE_eTaskGetState #define INCLUDE_eTaskGetState 0 #endif #ifndef INCLUDE_xTaskResumeFromISR #define INCLUDE_xTaskResumeFromISR 1 #endif #ifndef INCLUDE_xTimerPendFunctionCall #define INCLUDE_xTimerPendFunctionCall 0 #endif #ifndef INCLUDE_xTaskGetSchedulerState #define INCLUDE_xTaskGetSchedulerState 0 #endif #ifndef INCLUDE_xTaskGetCurrentTaskHandle #define INCLUDE_xTaskGetCurrentTaskHandle 0 #endif #if configUSE_CO_ROUTINES != 0 #ifndef configMAX_CO_ROUTINE_PRIORITIES #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. #endif #endif #ifndef configUSE_DAEMON_TASK_STARTUP_HOOK #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 #endif #ifndef configUSE_APPLICATION_TASK_TAG #define configUSE_APPLICATION_TASK_TAG 0 #endif #ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 #endif #ifndef configUSE_RECURSIVE_MUTEXES #define configUSE_RECURSIVE_MUTEXES 0 #endif #ifndef configUSE_MUTEXES #define configUSE_MUTEXES 0 #endif #ifndef configUSE_TIMERS #define configUSE_TIMERS 0 #endif #ifndef configUSE_COUNTING_SEMAPHORES #define configUSE_COUNTING_SEMAPHORES 0 #endif #ifndef configUSE_ALTERNATIVE_API #define configUSE_ALTERNATIVE_API 0 #endif #ifndef portCRITICAL_NESTING_IN_TCB #define portCRITICAL_NESTING_IN_TCB 0 #endif #ifndef configMAX_TASK_NAME_LEN #define configMAX_TASK_NAME_LEN 16 #endif #ifndef configIDLE_SHOULD_YIELD #define configIDLE_SHOULD_YIELD 1 #endif #if configMAX_TASK_NAME_LEN < 1 #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h #endif #ifndef configASSERT #define configASSERT( x ) #define configASSERT_DEFINED 0 #else #define configASSERT_DEFINED 1 #endif /* The timers module relies on xTaskGetSchedulerState(). */ #if configUSE_TIMERS == 1 #ifndef configTIMER_TASK_PRIORITY #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. #endif /* configTIMER_TASK_PRIORITY */ #ifndef configTIMER_QUEUE_LENGTH #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. #endif /* configTIMER_QUEUE_LENGTH */ #ifndef configTIMER_TASK_STACK_DEPTH #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. #endif /* configTIMER_TASK_STACK_DEPTH */ #endif /* configUSE_TIMERS */ #ifndef portSET_INTERRUPT_MASK_FROM_ISR #define portSET_INTERRUPT_MASK_FROM_ISR() 0 #endif #ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue #endif #ifndef portCLEAN_UP_TCB #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef portPRE_TASK_DELETE_HOOK #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) #endif #ifndef portSETUP_TCB #define portSETUP_TCB( pxTCB ) ( void ) pxTCB #endif #ifndef configQUEUE_REGISTRY_SIZE #define configQUEUE_REGISTRY_SIZE 0U #endif #if ( configQUEUE_REGISTRY_SIZE < 1 ) #define vQueueAddToRegistry( xQueue, pcName ) #define vQueueUnregisterQueue( xQueue ) #define pcQueueGetName( xQueue ) #endif #ifndef portPOINTER_SIZE_TYPE #define portPOINTER_SIZE_TYPE uint32_t #endif /* Remove any unused trace macros. */ #ifndef traceSTART /* Used to perform any necessary initialisation - for example, open a file into which trace is to be written. */ #define traceSTART() #endif #ifndef traceEND /* Use to close a trace, for example close a file into which trace has been written. */ #define traceEND() #endif #ifndef traceTASK_SWITCHED_IN /* Called after a task has been selected to run. pxCurrentTCB holds a pointer to the task control block of the selected task. */ #define traceTASK_SWITCHED_IN() #endif #ifndef traceINCREASE_TICK_COUNT /* Called before stepping the tick count after waking from tickless idle sleep. */ #define traceINCREASE_TICK_COUNT( x ) #endif #ifndef traceLOW_POWER_IDLE_BEGIN /* Called immediately before entering tickless idle. */ #define traceLOW_POWER_IDLE_BEGIN() #endif #ifndef traceLOW_POWER_IDLE_END /* Called when returning to the Idle task after a tickless idle. */ #define traceLOW_POWER_IDLE_END() #endif #ifndef traceTASK_SWITCHED_OUT /* Called before a task has been selected to run. pxCurrentTCB holds a pointer to the task control block of the task being switched out. */ #define traceTASK_SWITCHED_OUT() #endif #ifndef traceTASK_PRIORITY_INHERIT /* Called when a task attempts to take a mutex that is already held by a lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task that holds the mutex. uxInheritedPriority is the priority the mutex holder will inherit (the priority of the task that is attempting to obtain the muted. */ #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) #endif #ifndef traceTASK_PRIORITY_DISINHERIT /* Called when a task releases a mutex, the holding of which had resulted in the task inheriting the priority of a higher priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the mutex. uxOriginalPriority is the task's configured (base) priority. */ #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) #endif #ifndef traceBLOCKING_ON_QUEUE_RECEIVE /* Task is about to block because it cannot read from a queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore upon which the read was attempted. pxCurrentTCB points to the TCB of the task that attempted the read. */ #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_PEEK /* Task is about to block because it cannot read from a queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore upon which the read was attempted. pxCurrentTCB points to the TCB of the task that attempted the read. */ #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) #endif #ifndef traceBLOCKING_ON_QUEUE_SEND /* Task is about to block because it cannot write to a queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore upon which the write was attempted. pxCurrentTCB points to the TCB of the task that attempted the write. */ #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) #endif #ifndef configCHECK_FOR_STACK_OVERFLOW #define configCHECK_FOR_STACK_OVERFLOW 0 #endif #ifndef configRECORD_STACK_HIGH_ADDRESS #define configRECORD_STACK_HIGH_ADDRESS 0 #endif #ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 #endif /* The following event macros are embedded in the kernel API calls. */ #ifndef traceMOVED_TASK_TO_READY_STATE #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef tracePOST_MOVED_TASK_TO_READY_STATE #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) #endif #ifndef traceQUEUE_CREATE #define traceQUEUE_CREATE( pxNewQueue ) #endif #ifndef traceQUEUE_CREATE_FAILED #define traceQUEUE_CREATE_FAILED( ucQueueType ) #endif #ifndef traceCREATE_MUTEX #define traceCREATE_MUTEX( pxNewQueue ) #endif #ifndef traceCREATE_MUTEX_FAILED #define traceCREATE_MUTEX_FAILED() #endif #ifndef traceGIVE_MUTEX_RECURSIVE #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceGIVE_MUTEX_RECURSIVE_FAILED #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) #endif #ifndef traceTAKE_MUTEX_RECURSIVE_FAILED #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) #endif #ifndef traceCREATE_COUNTING_SEMAPHORE #define traceCREATE_COUNTING_SEMAPHORE() #endif #ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED #define traceCREATE_COUNTING_SEMAPHORE_FAILED() #endif #ifndef traceQUEUE_SEND #define traceQUEUE_SEND( pxQueue ) #endif #ifndef traceQUEUE_SEND_FAILED #define traceQUEUE_SEND_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE #define traceQUEUE_RECEIVE( pxQueue ) #endif #ifndef traceQUEUE_PEEK #define traceQUEUE_PEEK( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FAILED #define traceQUEUE_PEEK_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FAILED #define traceQUEUE_RECEIVE_FAILED( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR #define traceQUEUE_SEND_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_SEND_FROM_ISR_FAILED #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) #endif #ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_PEEK_FROM_ISR_FAILED #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) #endif #ifndef traceQUEUE_DELETE #define traceQUEUE_DELETE( pxQueue ) #endif #ifndef traceTASK_CREATE #define traceTASK_CREATE( pxNewTCB ) #endif #ifndef traceTASK_CREATE_FAILED #define traceTASK_CREATE_FAILED() #endif #ifndef traceTASK_DELETE #define traceTASK_DELETE( pxTaskToDelete ) #endif #ifndef traceTASK_DELAY_UNTIL #define traceTASK_DELAY_UNTIL( x ) #endif #ifndef traceTASK_DELAY #define traceTASK_DELAY() #endif #ifndef traceTASK_PRIORITY_SET #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) #endif #ifndef traceTASK_SUSPEND #define traceTASK_SUSPEND( pxTaskToSuspend ) #endif #ifndef traceTASK_RESUME #define traceTASK_RESUME( pxTaskToResume ) #endif #ifndef traceTASK_RESUME_FROM_ISR #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) #endif #ifndef traceTASK_INCREMENT_TICK #define traceTASK_INCREMENT_TICK( xTickCount ) #endif #ifndef traceTIMER_CREATE #define traceTIMER_CREATE( pxNewTimer ) #endif #ifndef traceTIMER_CREATE_FAILED #define traceTIMER_CREATE_FAILED() #endif #ifndef traceTIMER_COMMAND_SEND #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) #endif #ifndef traceTIMER_EXPIRED #define traceTIMER_EXPIRED( pxTimer ) #endif #ifndef traceTIMER_COMMAND_RECEIVED #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) #endif #ifndef traceMALLOC #define traceMALLOC( pvAddress, uiSize ) #endif #ifndef traceFREE #define traceFREE( pvAddress, uiSize ) #endif #ifndef traceEVENT_GROUP_CREATE #define traceEVENT_GROUP_CREATE( xEventGroup ) #endif #ifndef traceEVENT_GROUP_CREATE_FAILED #define traceEVENT_GROUP_CREATE_FAILED() #endif #ifndef traceEVENT_GROUP_SYNC_BLOCK #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_SYNC_END #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) #endif #ifndef traceEVENT_GROUP_WAIT_BITS_END #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred #endif #ifndef traceEVENT_GROUP_CLEAR_BITS #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) #endif #ifndef traceEVENT_GROUP_SET_BITS #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) #endif #ifndef traceEVENT_GROUP_DELETE #define traceEVENT_GROUP_DELETE( xEventGroup ) #endif #ifndef tracePEND_FUNC_CALL #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef tracePEND_FUNC_CALL_FROM_ISR #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) #endif #ifndef traceQUEUE_REGISTRY_ADD #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) #endif #ifndef traceTASK_NOTIFY_TAKE_BLOCK #define traceTASK_NOTIFY_TAKE_BLOCK() #endif #ifndef traceTASK_NOTIFY_TAKE #define traceTASK_NOTIFY_TAKE() #endif #ifndef traceTASK_NOTIFY_WAIT_BLOCK #define traceTASK_NOTIFY_WAIT_BLOCK() #endif #ifndef traceTASK_NOTIFY_WAIT #define traceTASK_NOTIFY_WAIT() #endif #ifndef traceTASK_NOTIFY #define traceTASK_NOTIFY() #endif #ifndef traceTASK_NOTIFY_FROM_ISR #define traceTASK_NOTIFY_FROM_ISR() #endif #ifndef traceTASK_NOTIFY_GIVE_FROM_ISR #define traceTASK_NOTIFY_GIVE_FROM_ISR() #endif #ifndef traceSTREAM_BUFFER_CREATE_FAILED #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_CREATE #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) #endif #ifndef traceSTREAM_BUFFER_DELETE #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RESET #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) #endif #ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_SEND #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) #endif #ifndef traceSTREAM_BUFFER_SEND_FAILED #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_SEND_FROM_ISR #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) #endif #ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE_FAILED #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) #endif #ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) #endif #ifndef configGENERATE_RUN_TIME_STATS #define configGENERATE_RUN_TIME_STATS 0 #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ #ifndef portGET_RUN_TIME_COUNTER_VALUE #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ #endif /* portGET_RUN_TIME_COUNTER_VALUE */ #endif /* configGENERATE_RUN_TIME_STATS */ #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() #endif #ifndef configUSE_MALLOC_FAILED_HOOK #define configUSE_MALLOC_FAILED_HOOK 0 #endif #ifndef portPRIVILEGE_BIT #define portPRIVILEGE_BIT ( ( uint32_t ) 0x00 ) #endif #ifndef portYIELD_WITHIN_API #define portYIELD_WITHIN_API portYIELD #endif #ifndef portSUPPRESS_TICKS_AND_SLEEP #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) #endif #ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 #endif #if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 #endif #ifndef configUSE_TICKLESS_IDLE #define configUSE_TICKLESS_IDLE 0 #endif #ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) #endif #ifndef configPRE_SLEEP_PROCESSING #define configPRE_SLEEP_PROCESSING( x ) #endif #ifndef configPOST_SLEEP_PROCESSING #define configPOST_SLEEP_PROCESSING( x ) #endif #ifndef configUSE_QUEUE_SETS #define configUSE_QUEUE_SETS 0 #endif #ifndef portTASK_USES_FLOATING_POINT #define portTASK_USES_FLOATING_POINT() #endif #ifndef portTASK_CALLS_SECURE_FUNCTIONS #define portTASK_CALLS_SECURE_FUNCTIONS() #endif #ifndef configUSE_TIME_SLICING #define configUSE_TIME_SLICING 1 #endif #ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 #endif #ifndef configUSE_STATS_FORMATTING_FUNCTIONS #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #endif #ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() #endif #ifndef configUSE_TRACE_FACILITY #define configUSE_TRACE_FACILITY 0 #endif #ifndef mtCOVERAGE_TEST_MARKER #define mtCOVERAGE_TEST_MARKER() #endif #ifndef mtCOVERAGE_TEST_DELAY #define mtCOVERAGE_TEST_DELAY() #endif #ifndef portASSERT_IF_IN_ISR #define portASSERT_IF_IN_ISR() #endif #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 #endif #ifndef configAPPLICATION_ALLOCATED_HEAP #define configAPPLICATION_ALLOCATED_HEAP 0 #endif #ifndef configUSE_TASK_NOTIFICATIONS #define configUSE_TASK_NOTIFICATIONS 1 #endif #ifndef portTICK_TYPE_IS_ATOMIC #define portTICK_TYPE_IS_ATOMIC 0 #endif #ifndef configSUPPORT_STATIC_ALLOCATION /* Defaults to 0 for backward compatibility. */ #define configSUPPORT_STATIC_ALLOCATION 0 #endif #ifndef configSUPPORT_DYNAMIC_ALLOCATION /* Defaults to 1 for backward compatibility. */ #define configSUPPORT_DYNAMIC_ALLOCATION 1 #endif #ifndef configSTACK_DEPTH_TYPE /* Defaults to uint16_t for backward compatibility, but can be overridden in FreeRTOSConfig.h if uint16_t is too restrictive. */ #define configSTACK_DEPTH_TYPE uint16_t #endif /* Sanity check the configuration. */ #if( configUSE_TICKLESS_IDLE != 0 ) #if( INCLUDE_vTaskSuspend != 1 ) #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 #endif /* INCLUDE_vTaskSuspend */ #endif /* configUSE_TICKLESS_IDLE */ #if( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. #endif #if( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) #error configUSE_MUTEXES must be set to 1 to use recursive mutexes #endif #ifndef configINITIAL_TICK_COUNT #define configINITIAL_TICK_COUNT 0 #endif #if( portTICK_TYPE_IS_ATOMIC == 0 ) /* Either variables of tick type cannot be read atomically, or portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when the tick count is returned to the standard critical section macros. */ #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) #else /* The tick type can be read atomically, so critical sections used when the tick count is returned can be defined away. */ #define portTICK_TYPE_ENTER_CRITICAL() #define portTICK_TYPE_EXIT_CRITICAL() #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x #endif /* Definitions to allow backward compatibility with FreeRTOS versions prior to V8 if desired. */ #ifndef configENABLE_BACKWARD_COMPATIBILITY #define configENABLE_BACKWARD_COMPATIBILITY 1 #endif #ifndef configPRINTF /* configPRINTF() was not defined, so define it away to nothing. To use configPRINTF() then define it as follows (where MyPrintFunction() is provided by the application writer): void MyPrintFunction(const char *pcFormat, ... ); #define configPRINTF( X ) MyPrintFunction X Then call like a standard printf() function, but placing brackets around all parameters so they are passed as a single parameter. For example: configPRINTF( ("Value = %d", MyVariable) ); */ #define configPRINTF( X ) #endif #ifndef configMAX /* The application writer has not provided their own MAX macro, so define the following generic implementation. */ #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) #endif #ifndef configMIN /* The application writer has not provided their own MAX macro, so define the following generic implementation. */ #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) #endif #if configENABLE_BACKWARD_COMPATIBILITY == 1 #define eTaskStateGet task_get_state #define portTickType uint32_t #define xTaskHandle task_t #define xQueueHandle queue_t #define xSemaphoreHandle sem_t #define xQueueSetHandle QueueSetHandle_t #define xQueueSetMemberHandle QueueSetMemberHandle_t #define xTimeOutType TimeOut_t #define xMemoryRegion MemoryRegion_t #define xTaskParameters TaskParameters_t #define xTaskStatusType TaskStatus_t #define xTimerHandle TimerHandle_t #define xCoRoutineHandle CoRoutineHandle_t #define pdTASK_HOOK_CODE TaskHookFunction_t #define portTICK_RATE_MS portTICK_PERIOD_MS #define pcTaskGetTaskName task_get_name #define pcTimerGetTimerName pcTimerGetName #define pcQueueGetQueueName pcQueueGetName #define vTaskGetTaskInfo vTaskGetInfo /* Backward compatibility within the scheduler code only - these definitions are not really required but are included for completeness. */ #define tmrTIMER_CALLBACK TimerCallbackFunction_t #define pdTASK_CODE task_fn_t #define xListItem list_item_t #define xList List_t #endif /* configENABLE_BACKWARD_COMPATIBILITY */ #if( configUSE_ALTERNATIVE_API != 0 ) #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 #endif /* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even if floating point hardware is otherwise supported by the FreeRTOS port in use. This constant is not supported by all FreeRTOS ports that include floating point support. */ #ifndef configUSE_TASK_FPU_SUPPORT #define configUSE_TASK_FPU_SUPPORT 1 #endif /* * In line with software engineering best practice, FreeRTOS implements a strict * data hiding policy, so the real structures used by FreeRTOS to maintain the * state of tasks, queues, semaphores, etc. are not accessible to the application * code. However, if the application writer wants to statically allocate such * an object then the size of the object needs to be know. Dummy structures * that are guaranteed to have the same size and alignment requirements of the * real objects are used for this purpose. The dummy list and list item * structures below are used for inclusion in such a dummy structure. */ struct xSTATIC_LIST_ITEM { uint32_t xDummy1; void *pvDummy2[ 4 ]; }; typedef struct xSTATIC_LIST_ITEM StaticListItem_t; /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ struct xSTATIC_MINI_LIST_ITEM { uint32_t xDummy1; void *pvDummy2[ 2 ]; }; typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; /* See the comments above the struct xSTATIC_LIST_ITEM definition. */ typedef struct xSTATIC_LIST { uint32_t uxDummy1; void *pvDummy2; StaticMiniListItem_t xDummy3; } StaticList_t; /* * In line with software engineering best practice, especially when supplying a * library that is likely to change in future versions, FreeRTOS implements a * strict data hiding policy. This means the Task structure used internally by * FreeRTOS is not accessible to application code. However, if the application * writer wants to statically allocate the memory required to create a task then * the size of the task object needs to be know. The static_task_s_t structure * below is provided for this purpose. Its sizes and alignment requirements are * guaranteed to match those of the genuine structure, no matter which * architecture is being used, and no matter how the values in FreeRTOSConfig.h * are set. Its contents are somewhat obfuscated in the hope users will * recognise that it would be unwise to make direct use of the structure members. */ typedef struct xSTATIC_TCB { void *pxDummy1; #if ( portUSING_MPU_WRAPPERS == 1 ) xMPU_SETTINGS xDummy2; #endif StaticListItem_t xDummy3[ 2 ]; uint32_t uxDummy5; void *pxDummy6; uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) void *pxDummy8; #endif #if ( portCRITICAL_NESTING_IN_TCB == 1 ) uint32_t uxDummy9; #endif #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxDummy10[ 2 ]; #endif #if ( configUSE_MUTEXES == 1 ) uint32_t uxDummy12[ 2 ]; #endif #if ( configUSE_APPLICATION_TASK_TAG == 1 ) void *pxDummy14; #endif #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) uint32_t ulDummy16; #endif #if ( configUSE_NEWLIB_REENTRANT == 1 ) struct _reent xDummy17; #endif #if ( configUSE_TASK_NOTIFICATIONS == 1 ) uint32_t ulDummy18; uint8_t ucDummy19; #endif #if( ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) || ( portUSING_MPU_WRAPPERS == 1 ) ) uint8_t uxDummy20; #endif #if( INCLUDE_xTaskAbortDelay == 1 ) uint8_t ucDummy21; #endif } static_task_s_t; /* * In line with software engineering best practice, especially when supplying a * library that is likely to change in future versions, FreeRTOS implements a * strict data hiding policy. This means the Queue structure used internally by * FreeRTOS is not accessible to application code. However, if the application * writer wants to statically allocate the memory required to create a queue * then the size of the queue object needs to be know. The static_queue_s_t * structure below is provided for this purpose. Its sizes and alignment * requirements are guaranteed to match those of the genuine structure, no * matter which architecture is being used, and no matter how the values in * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope * users will recognise that it would be unwise to make direct use of the * structure members. */ typedef struct xSTATIC_QUEUE { void *pvDummy1[ 3 ]; union { void *pvDummy2; uint32_t uxDummy2; } u; StaticList_t xDummy3[ 2 ]; uint32_t uxDummy4[ 3 ]; uint8_t ucDummy5[ 2 ]; #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) uint8_t ucDummy6; #endif #if ( configUSE_QUEUE_SETS == 1 ) void *pvDummy7; #endif #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxDummy8; uint8_t ucDummy9; #endif } static_queue_s_t; typedef static_queue_s_t static_sem_s_t; /* * In line with software engineering best practice, especially when supplying a * library that is likely to change in future versions, FreeRTOS implements a * strict data hiding policy. This means the event group structure used * internally by FreeRTOS is not accessible to application code. However, if * the application writer wants to statically allocate the memory required to * create an event group then the size of the event group object needs to be * know. The StaticEventGroup_t structure below is provided for this purpose. * Its sizes and alignment requirements are guaranteed to match those of the * genuine structure, no matter which architecture is being used, and no matter * how the values in FreeRTOSConfig.h are set. Its contents are somewhat * obfuscated in the hope users will recognise that it would be unwise to make * direct use of the structure members. */ typedef struct xSTATIC_EVENT_GROUP { uint32_t xDummy1; StaticList_t xDummy2; #if( configUSE_TRACE_FACILITY == 1 ) uint32_t uxDummy3; #endif #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) uint8_t ucDummy4; #endif } StaticEventGroup_t; /* * In line with software engineering best practice, especially when supplying a * library that is likely to change in future versions, FreeRTOS implements a * strict data hiding policy. This means the software timer structure used * internally by FreeRTOS is not accessible to application code. However, if * the application writer wants to statically allocate the memory required to * create a software timer then the size of the queue object needs to be know. * The StaticTimer_t structure below is provided for this purpose. Its sizes * and alignment requirements are guaranteed to match those of the genuine * structure, no matter which architecture is being used, and no matter how the * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in * the hope users will recognise that it would be unwise to make direct use of * the structure members. */ typedef struct xSTATIC_TIMER { void *pvDummy1; StaticListItem_t xDummy2; uint32_t xDummy3; uint32_t uxDummy4; void *pvDummy5[ 2 ]; #if( configUSE_TRACE_FACILITY == 1 ) uint32_t uxDummy6; #endif #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) uint8_t ucDummy7; #endif } StaticTimer_t; /* * In line with software engineering best practice, especially when supplying a * library that is likely to change in future versions, FreeRTOS implements a * strict data hiding policy. This means the stream buffer structure used * internally by FreeRTOS is not accessible to application code. However, if * the application writer wants to statically allocate the memory required to * create a stream buffer then the size of the stream buffer object needs to be * know. The static_stream_buf_s_t structure below is provided for this purpose. * Its size and alignment requirements are guaranteed to match those of the * genuine structure, no matter which architecture is being used, and no matter * how the values in FreeRTOSConfig.h are set. Its contents are somewhat * obfuscated in the hope users will recognise that it would be unwise to make * direct use of the structure members. */ typedef struct xSTATIC_STREAM_BUFFER { size_t uxDummy1[ 4 ]; void * pvDummy2[ 3 ]; uint8_t ucDummy3; #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxDummy4; #endif } static_stream_buf_s_t; /* Message buffers are built on stream buffers. */ typedef static_stream_buf_s_t static_msg_buf_s_t; #ifdef __cplusplus } #endif #endif /* INC_FREERTOS_H */ ================================================ FILE: include/rtos/FreeRTOSConfig.h ================================================ /* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ #ifndef FREERTOS_CONFIG_H #define FREERTOS_CONFIG_H //#include "xparameters.h" // fix memset warnings #include "string.h" /*----------------------------------------------------------- * Application specific definitions. * * These definitions should be adjusted for your particular hardware and * application requirements. * * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. * * See http://www.freertos.org/a00110.html. *----------------------------------------------------------*/ /* * The FreeRTOS Cortex-A port implements a full interrupt nesting model. * * Interrupts that are assigned a priority at or below * configMAX_API_CALL_INTERRUPT_PRIORITY (which counter-intuitively in the ARM * generic interrupt controller [GIC] means a priority that has a numerical * value above configMAX_API_CALL_INTERRUPT_PRIORITY) can call FreeRTOS safe API * functions and will nest. * * Interrupts that are assigned a priority above * configMAX_API_CALL_INTERRUPT_PRIORITY (which in the GIC means a numerical * value below configMAX_API_CALL_INTERRUPT_PRIORITY) cannot call any FreeRTOS * API functions, will nest, and will not be masked by FreeRTOS critical * sections (although it is necessary for interrupts to be globally disabled * extremely briefly as the interrupt mask is updated in the GIC). * * FreeRTOS functions that can be called from an interrupt are those that end in * "FromISR". FreeRTOS maintains a separate interrupt safe API to enable * interrupt entry to be shorter, faster, simpler and smaller. * * The Zynq implements 256 unique interrupt priorities. For the purpose of * setting configMAX_API_CALL_INTERRUPT_PRIORITY 255 represents the lowest * priority. */ #define configMAX_API_CALL_INTERRUPT_PRIORITY 18 #define configCPU_CLOCK_HZ 100000000UL #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #define configUSE_TICKLESS_IDLE 0 #define configTICK_RATE_HZ ( ( uint32_t ) 1000 ) #define configPERIPHERAL_CLOCK_HZ ( 33333000UL ) #define configUSE_PREEMPTION 1 #define configUSE_IDLE_HOOK 1 #define configUSE_TICK_HOOK 0 #define configMAX_PRIORITIES ( 16 ) #define configMINIMAL_STACK_SIZE ( ( unsigned short ) 250 ) // allocate 1 MB for FreeRTOS heap #define configTOTAL_HEAP_SIZE ( 0x100000 ) #define configMAX_TASK_NAME_LEN ( 32 ) #define configUSE_TRACE_FACILITY 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 #define configUSE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 8 #define configCHECK_FOR_STACK_OVERFLOW 2 #define configUSE_RECURSIVE_MUTEXES 1 #define configUSE_MALLOC_FAILED_HOOK 1 #define configUSE_APPLICATION_TASK_TAG 0 #define configUSE_COUNTING_SEMAPHORES 1 #define configUSE_QUEUE_SETS 0 #define configSUPPORT_STATIC_ALLOCATION 1 #define configUSE_NEWLIB_REENTRANT 1 #define configSTACK_DEPTH_TYPE size_t #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 2 /* Include the query-heap CLI command to query the free heap space. */ #define configINCLUDE_QUERY_HEAP_COMMAND 1 /* Software timer definitions. */ #define configUSE_TIMERS 1 #define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) #define configTIMER_QUEUE_LENGTH 5 #define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 ) /* If configUSE_TASK_FPU_SUPPORT is set to 1 (or undefined) then each task will be created without an FPU context, and a task must call vTaskUsesFPU() before making use of any FPU registers. If configUSE_TASK_FPU_SUPPORT is set to 2 then tasks are created with an FPU context by default, and calling vTaskUsesFPU() has no effect. */ #define configUSE_TASK_FPU_SUPPORT 2 /* Set the following definitions to 1 to include the API function, or zero to exclude the API function. */ #define INCLUDE_vTaskPrioritySet 1 #define INCLUDE_uxTaskPriorityGet 1 #define INCLUDE_vTaskDelete 1 #define INCLUDE_vTaskCleanUpResources 1 #define INCLUDE_vTaskSuspend 1 #define INCLUDE_vTaskDelayUntil 1 #define INCLUDE_vTaskDelay 1 #define INCLUDE_xTimerPendFunctionCall 1 #define INCLUDE_eTaskGetState 1 #define INCLUDE_xTaskAbortDelay 1 #define INCLUDE_xTaskGetTaskHandle 1 #define INCLUDE_xTaskGetHandle 1 #define INCLUDE_xTaskGetSchedulerState 1 #define INCLUDE_xQueueGetMutexHolder 1 /* This demo makes use of one or more example stats formatting functions. These format the raw data provided by the uxTaskGetSystemState() function in to human readable ASCII form. See the notes in the implementation of vTaskList() within FreeRTOS/Source/tasks.c for limitations. */ #define configUSE_STATS_FORMATTING_FUNCTIONS 1 /* The private watchdog is used to generate run time stats. */ extern void vInitialiseTimerForRunTimeStats( void ); extern uint32_t vexSystemWatchdogGet( void ); #define configGENERATE_RUN_TIME_STATS 1 #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() vInitialiseTimerForRunTimeStats() #define portGET_RUN_TIME_COUNTER_VALUE() vexSystemWatchdogGet() /* The size of the global output buffer that is available for use when there are multiple command interpreters running at once (for example, one on a UART and one on TCP/IP). This is done to prevent an output buffer being defined by each implementation - which would waste RAM. In this case, there is only one command interpreter running. */ #define configCOMMAND_INT_MAX_OUTPUT_SIZE 2096 /* Normal assert() semantics without relying on the provision of an assert.h header file. */ void vAssertCalled( const char * pcFile, unsigned long ulLine ); #define configASSERT( x ) if( ( x ) == 0 ) vAssertCalled( __FILE__, __LINE__ ); /* If configTASK_RETURN_ADDRESS is not defined then a task that attempts to return from its implementing function will end up in a "task exit error" function - which contains a call to configASSERT(). However this can give GCC some problems when it tries to unwind the stack, as the exit error function has nothing to return to. To avoid this define configTASK_RETURN_ADDRESS to 0. */ #define configTASK_RETURN_ADDRESS NULL /****** Hardware specific settings. *******************************************/ /* * The application must provide a function that configures a peripheral to * create the FreeRTOS tick interrupt, then define configSETUP_TICK_INTERRUPT() * in FreeRTOSConfig.h to call the function. This file contains a function * that is suitable for use on the Zynq MPU. FreeRTOS_Tick_Handler() must * be installed as the peripheral's interrupt handler. */ void rtos_tick_interrupt_config( void ); #define configSETUP_TICK_INTERRUPT() rtos_tick_interrupt_config() void rtos_tick_interrupt_clear( void ); #define configCLEAR_TICK_INTERRUPT() rtos_tick_interrupt_clear() /* The following constant describe the hardware, and are correct for the Zynq MPU. */ //#define configINTERRUPT_CONTROLLER_BASE_ADDRESS ( XPAR_PS7_SCUGIC_0_DIST_BASEADDR ) #define configINTERRUPT_CONTROLLER_BASE_ADDRESS ( 0xF8F01000 ) #define configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET ( -0xf00 ) #define configUNIQUE_INTERRUPT_PRIORITIES 32 #endif /* FREERTOS_CONFIG_H */ ================================================ FILE: include/rtos/StackMacros.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef STACK_MACROS_H #define STACK_MACROS_H #ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. #endif /* * Call the stack overflow hook function if the stack of the task being swapped * out is currently overflowed, or looks like it might have overflowed in the * past. * * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check * the current stack state only - comparing the current top of stack value to * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 * will also cause the last few stack bytes to be checked to ensure the value * to which the bytes were set when the task was created have not been * overwritten. Note this second test does not guarantee that an overflowed * stack will always be recognised. */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) /* Only the current stack state is to be checked. */ #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ /* Is the currently saved stack pointer within the stack limit? */ \ if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) /* Only the current stack state is to be checked. */ #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ \ /* Is the currently saved stack pointer within the stack limit? */ \ if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ \ if( ( pulStack[ 0 ] != ulCheckValue ) || \ ( pulStack[ 1 ] != ulCheckValue ) || \ ( pulStack[ 2 ] != ulCheckValue ) || \ ( pulStack[ 3 ] != ulCheckValue ) ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ \ \ pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ \ /* Has the extremity of the task stack ever been written over? */ \ if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ /* Remove stack overflow macro if not being used. */ #ifndef taskCHECK_FOR_STACK_OVERFLOW #define taskCHECK_FOR_STACK_OVERFLOW() #endif #endif /* STACK_MACROS_H */ ================================================ FILE: include/rtos/list.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* * This is the list implementation used by the scheduler. While it is tailored * heavily for the schedulers needs, it is also available for use by * application code. * * list_ts can only store pointers to list_item_ts. Each list_item_t contains a * numeric value (xItemValue). Most of the time the lists are sorted in * descending item value order. * * Lists are created already containing one list item. The value of this * item is the maximum possible that can be stored, it is therefore always at * the end of the list and acts as a marker. The list member pxHead always * points to this marker - even though it is at the tail of the list. This * is because the tail contains a wrap back pointer to the true head of * the list. * * In addition to it's value, each list item contains a pointer to the next * item in the list (pxNext), a pointer to the list it is in (pxContainer) * and a pointer to back to the object that contains it. These later two * pointers are included for efficiency of list manipulation. There is * effectively a two way link between the object containing the list item and * the list item itself. * * * \page ListIntroduction List Implementation * \ingroup FreeRTOSIntro */ #ifndef INC_FREERTOS_H #error FreeRTOS.h must be included before list.h #endif #ifndef LIST_H #define LIST_H /* * The list structure members are modified from within interrupts, and therefore * by rights should be declared volatile. However, they are only modified in a * functionally atomic way (within critical sections of with the scheduler * suspended) and are either passed by reference into a function or indexed via * a volatile variable. Therefore, in all use cases tested so far, the volatile * qualifier can be omitted in order to provide a moderate performance * improvement without adversely affecting functional behaviour. The assembly * instructions generated by the IAR, ARM and GCC compilers when the respective * compiler's options were set for maximum optimisation has been inspected and * deemed to be as intended. That said, as compiler technology advances, and * especially if aggressive cross module optimisation is used (a use case that * has not been exercised to any great extend) then it is feasible that the * volatile qualifier will be needed for correct optimisation. It is expected * that a compiler removing essential code because, without the volatile * qualifier on the list structure members and with aggressive cross module * optimisation, the compiler deemed the code unnecessary will result in * complete and obvious failure of the scheduler. If this is ever experienced * then the volatile qualifier can be inserted in the relevant places within the * list structures by simply defining configLIST_VOLATILE to volatile in * FreeRTOSConfig.h (as per the example at the bottom of this comment block). * If configLIST_VOLATILE is not defined then the preprocessor directives below * will simply #define configLIST_VOLATILE away completely. * * To use volatile list structure members then add the following line to * FreeRTOSConfig.h (without the quotes): * "#define configLIST_VOLATILE volatile" */ #ifndef configLIST_VOLATILE #define configLIST_VOLATILE #endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ #ifdef __cplusplus extern "C" { #endif /* Macros that can be used to place known values within the list structures, then check that the known values do not get corrupted during the execution of the application. These may catch the list data structures being overwritten in memory. They will not catch data errors caused by incorrect configuration or use of FreeRTOS.*/ #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) /* Define the macros to do nothing. */ #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE #define listFIRST_LIST_INTEGRITY_CHECK_VALUE #define listSECOND_LIST_INTEGRITY_CHECK_VALUE #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) #define listTEST_LIST_INTEGRITY( pxList ) #else /* Define macros that add new members into the list structures. */ #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE uint32_t xListItemIntegrityValue1; #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE uint32_t xListItemIntegrityValue2; #define listFIRST_LIST_INTEGRITY_CHECK_VALUE uint32_t xListIntegrityValue1; #define listSECOND_LIST_INTEGRITY_CHECK_VALUE uint32_t xListIntegrityValue2; /* Define macros that set the new structure members to known values. */ #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE /* Define macros that will assert if one of the structure members does not contain its expected value. */ #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) #endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ /* * Definition of the only type of object that a list can contain. */ struct xLIST_ITEM { listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ configLIST_VOLATILE uint32_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next list_item_t in the list. */ struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous list_item_t in the list. */ void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ void * configLIST_VOLATILE pvContainer; /*< Pointer to the list in which this list item is placed (if any). */ listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ }; typedef struct xLIST_ITEM list_item_t; /* For some reason lint wants this as two separate definitions. */ struct xMINI_LIST_ITEM { listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ configLIST_VOLATILE uint32_t xItemValue; struct xLIST_ITEM * configLIST_VOLATILE pxNext; struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; }; typedef struct xMINI_LIST_ITEM MiniListItem_t; /* * Definition of the type of queue used by the scheduler. */ typedef struct xLIST { listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ volatile uint32_t uxNumberOfItems; list_item_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ } List_t; /* * Access macro to set the owner of a list item. The owner of a list item * is the object (usually a TCB) that contains the list item. * * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER * \ingroup LinkedList */ #define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) /* * Access macro to get the owner of a list item. The owner of a list item * is the object (usually a TCB) that contains the list item. * * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER * \ingroup LinkedList */ #define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) /* * Access macro to set the value of the list item. In most cases the value is * used to sort the list in descending order. * * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE * \ingroup LinkedList */ #define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) /* * Access macro to retrieve the value of the list item. The value can * represent anything - for example the priority of a task, or the time at * which a task should be unblocked. * * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE * \ingroup LinkedList */ #define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) /* * Access macro to retrieve the value of the list item at the head of a given * list. * * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE * \ingroup LinkedList */ #define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) /* * Return the list item at the head of the list. * * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY * \ingroup LinkedList */ #define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) /* * Return the list item at the head of the list. * * \page listGET_NEXT listGET_NEXT * \ingroup LinkedList */ #define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) /* * Return the list item that marks the end of the list * * \page listGET_END_MARKER listGET_END_MARKER * \ingroup LinkedList */ #define listGET_END_MARKER( pxList ) ( ( list_item_t const * ) ( &( ( pxList )->xListEnd ) ) ) /* * Access macro to determine if a list contains any items. The macro will * only have the value true if the list is empty. * * \page listLIST_IS_EMPTY listLIST_IS_EMPTY * \ingroup LinkedList */ #define listLIST_IS_EMPTY( pxList ) ( ( int32_t ) ( ( pxList )->uxNumberOfItems == ( uint32_t ) 0 ) ) /* * Access macro to return the number of items in the list. */ #define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) /* * Access function to obtain the owner of the next entry in a list. * * The list member pxIndex is used to walk through a list. Calling * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list * and returns that entry's pxOwner parameter. Using multiple calls to this * function it is therefore possible to move through every item contained in * a list. * * The pxOwner parameter of a list item is a pointer to the object that owns * the list item. In the scheduler this is normally a task control block. * The pxOwner parameter effectively creates a two way link between the list * item and its owner. * * @param pxTCB pxTCB is set to the address of the owner of the next list item. * @param pxList The list from which the next item owner is to be returned. * * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY * \ingroup LinkedList */ #define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ { \ List_t * const pxConstList = ( pxList ); \ /* Increment the index to the next item and return the item, ensuring */ \ /* we don't return the marker used at the end of the list. */ \ ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ { \ ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ } \ ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ } /* * Access function to obtain the owner of the first entry in a list. Lists * are normally sorted in ascending item value order. * * This function returns the pxOwner member of the first item in the list. * The pxOwner parameter of a list item is a pointer to the object that owns * the list item. In the scheduler this is normally a task control block. * The pxOwner parameter effectively creates a two way link between the list * item and its owner. * * @param pxList The list from which the owner of the head item is to be * returned. * * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY * \ingroup LinkedList */ #define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner ) /* * Check to see if a list item is within a list. The list item maintains a * "container" pointer that points to the list it is in. All this macro does * is check to see if the container and the list match. * * @param pxList The list we want to know if the list item is within. * @param pxListItem The list item we want to know if is in the list. * @return pdTRUE if the list item is in the list, otherwise pdFALSE. */ #define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( int32_t ) ( ( pxListItem )->pvContainer == ( void * ) ( pxList ) ) ) /* * Return the list a list item is contained within (referenced from). * * @param pxListItem The list item being queried. * @return A pointer to the List_t object that references the pxListItem */ #define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pvContainer ) /* * This provides a crude means of knowing if a list has been initialised, as * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() * function. */ #define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) /* * Must be called before a list is used! This initialises all the members * of the list structure and inserts the xListEnd item into the list as a * marker to the back of the list. * * @param pxList Pointer to the list being initialised. * * \page vListInitialise vListInitialise * \ingroup LinkedList */ void vListInitialise( List_t * const pxList ) ; /* * Must be called before a list item is used. This sets the list container to * null so the item does not think that it is already contained in a list. * * @param pxItem Pointer to the list item being initialised. * * \page vListInitialiseItem vListInitialiseItem * \ingroup LinkedList */ void vListInitialiseItem( list_item_t * const pxItem ) ; /* * Insert a list item into a list. The item will be inserted into the list in * a position determined by its item value (descending item value order). * * @param pxList The list into which the item is to be inserted. * * @param pxNewListItem The item that is to be placed in the list. * * \page vListInsert vListInsert * \ingroup LinkedList */ void vListInsert( List_t * const pxList, list_item_t * const pxNewListItem ) ; /* * Insert a list item into a list. The item will be inserted in a position * such that it will be the last item within the list returned by multiple * calls to listGET_OWNER_OF_NEXT_ENTRY. * * The list member pxIndex is used to walk through a list. Calling * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. * Placing an item in a list using vListInsertEnd effectively places the item * in the list position pointed to by pxIndex. This means that every other * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before * the pxIndex parameter again points to the item being inserted. * * @param pxList The list into which the item is to be inserted. * * @param pxNewListItem The list item to be inserted into the list. * * \page vListInsertEnd vListInsertEnd * \ingroup LinkedList */ void vListInsertEnd( List_t * const pxList, list_item_t * const pxNewListItem ) ; /* * Remove an item from a list. The list item has a pointer to the list that * it is in, so only the list item need be passed into the function. * * @param uxListRemove The item to be removed. The item will remove itself from * the list pointed to by it's pxContainer parameter. * * @return The number of items that remain in the list after the list item has * been removed. * * \page uxListRemove uxListRemove * \ingroup LinkedList */ uint32_t uxListRemove( list_item_t * const pxItemToRemove ) ; #ifdef __cplusplus } #endif #endif ================================================ FILE: include/rtos/message_buffer.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* * Message buffers build functionality on top of FreeRTOS stream buffers. * Whereas stream buffers are used to send a continuous stream of data from one * task or interrupt to another, message buffers are used to send variable * length discrete messages from one task or interrupt to another. Their * implementation is light weight, making them particularly suited for interrupt * to task and core to core communication scenarios. * * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer * implementation (so also the message buffer implementation, as message buffers * are built on top of stream buffers) assumes there is only one task or * interrupt that will write to the buffer (the writer), and only one task or * interrupt that will read from the buffer (the reader). It is safe for the * writer and reader to be different tasks or interrupts, but, unlike other * FreeRTOS objects, it is not safe to have multiple different writers or * multiple different readers. If there are to be multiple different writers * then the application writer must place each call to a writing API function * (such as msg_buf_send()) inside a critical section and set the send * block time to 0. Likewise, if there are to be multiple different readers * then the application writer must place each call to a reading API function * (such as xMessageBufferRead()) inside a critical section and set the receive * timeout to 0. * * Message buffers hold variable length messages. To enable that, when a * message is written to the message buffer an additional sizeof( size_t ) bytes * are also written to store the message's length (that happens internally, with * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit * architecture, so writing a 10 byte message to a message buffer on a 32-bit * architecture will actually reduce the available space in the message buffer * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length * of the message). */ #ifndef FREERTOS_MESSAGE_BUFFER_H #define FREERTOS_MESSAGE_BUFFER_H /* Message buffers are built onto of stream buffers. */ #include "stream_buffer.h" #if defined( __cplusplus ) extern "C" { #endif /** * Type by which message buffers are referenced. For example, a call to * xMessageBufferCreate() returns an msg_buf_t variable that can * then be used as a parameter to msg_buf_send(), msg_buf_recv(), * etc. */ typedef void * msg_buf_t; /*-----------------------------------------------------------*/ /** * message_buffer.h *
msg_buf_t xMessageBufferCreate( size_t xBufferSizeBytes );
* * Creates a new message buffer using dynamically allocated memory. See * xMessageBufferCreateStatic() for a version that uses statically allocated * memory (memory that is allocated at compile time). * * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in * FreeRTOSConfig.h for xMessageBufferCreate() to be available. * * @param xBufferSizeBytes The total number of bytes (not messages) the message * buffer will be able to hold at any one time. When a message is written to * the message buffer an additional sizeof( size_t ) bytes are also written to * store the message's length. sizeof( size_t ) is typically 4 bytes on a * 32-bit architecture, so on most 32-bit architectures a 10 byte message will * take up 14 bytes of message buffer space. * * @return If NULL is returned, then the message buffer cannot be created * because there is insufficient heap memory available for FreeRTOS to allocate * the message buffer data structures and storage area. A non-NULL value being * returned indicates that the message buffer has been created successfully - * the returned value should be stored as the handle to the created message * buffer. * * Example use:

void vAFunction( void )
{
msg_buf_t xMessageBuffer;
const size_t xMessageBufferSizeBytes = 100;

    // Create a message buffer that can hold 100 bytes.  The memory used to hold
    // both the message buffer structure and the messages themselves is allocated
    // dynamically.  Each message added to the buffer consumes an additional 4
    // bytes which are used to hold the lengh of the message.
    xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes );

    if( xMessageBuffer == NULL )
    {
        // There was not enough heap memory space available to create the
        // message buffer.
    }
    else
    {
        // The message buffer was created successfully and can now be used.
    }

* \defgroup xMessageBufferCreate xMessageBufferCreate * \ingroup MessageBufferManagement */ #define xMessageBufferCreate( xBufferSizeBytes ) ( msg_buf_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE ) /** * message_buffer.h *
msg_buf_t xMessageBufferCreateStatic( size_t xBufferSizeBytes,
                                                  uint8_t *pucMessageBufferStorageArea,
                                                  static_msg_buf_s_t *pxStaticMessageBuffer );
* Creates a new message buffer using statically allocated memory. See * xMessageBufferCreate() for a version that uses dynamically allocated memory. * * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the * pucMessageBufferStorageArea parameter. When a message is written to the * message buffer an additional sizeof( size_t ) bytes are also written to store * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit * architecture, so on most 32-bit architecture a 10 byte message will take up * 14 bytes of message buffer space. The maximum number of bytes that can be * stored in the message buffer is actually (xBufferSizeBytes - 1). * * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at * least xBufferSizeBytes + 1 big. This is the array to which messages are * copied when they are written to the message buffer. * * @param pxStaticMessageBuffer Must point to a variable of type * static_msg_buf_s_t, which will be used to hold the message buffer's data * structure. * * @return If the message buffer is created successfully then a handle to the * created message buffer is returned. If either pucMessageBufferStorageArea or * pxStaticmessageBuffer are NULL then NULL is returned. * * Example use:

// Used to dimension the array used to hold the messages.  The available space
// will actually be one less than this, so 999.
#define STORAGE_SIZE_BYTES 1000

// Defines the memory that will actually hold the messages within the message
// buffer.
static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];

// The variable used to hold the message buffer structure.
static_msg_buf_s_t xMessageBufferStruct;

void MyFunction( void )
{
msg_buf_t xMessageBuffer;

    xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucBufferStorage ),
                                                 ucBufferStorage,
                                                 &xMessageBufferStruct );

    // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer
    // parameters were NULL, xMessageBuffer will not be NULL, and can be used to
    // reference the created message buffer in other message buffer API calls.

    // Other code that uses the message buffer can go here.
}

* \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic * \ingroup MessageBufferManagement */ #define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) ( msg_buf_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer ) /** * message_buffer.h *
size_t msg_buf_send( msg_buf_t xMessageBuffer,
                           const void *pvTxData,
                           size_t xDataLengthBytes,
                           uint32_t xTicksToWait );
 *
 * Sends a discrete message to the message buffer.  The message can be any
 * length that fits within the buffer's free space, and is copied into the
 * buffer.
 *
 * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
 * implementation (so also the message buffer implementation, as message buffers
 * are built on top of stream buffers) assumes there is only one task or
 * interrupt that will write to the buffer (the writer), and only one task or
 * interrupt that will read from the buffer (the reader).  It is safe for the
 * writer and reader to be different tasks or interrupts, but, unlike other
 * FreeRTOS objects, it is not safe to have multiple different writers or
 * multiple different readers.  If there are to be multiple different writers
 * then the application writer must place each call to a writing API function
 * (such as msg_buf_send()) inside a critical section and set the send
 * block time to 0.  Likewise, if there are to be multiple different readers
 * then the application writer must place each call to a reading API function
 * (such as xMessageBufferRead()) inside a critical section and set the receive
 * block time to 0.
 *
 * Use msg_buf_send() to write to a message buffer from a task.  Use
 * xMessageBufferSendFromISR() to write to a message buffer from an interrupt
 * service routine (ISR).
 *
 * @param xMessageBuffer The handle of the message buffer to which a message is
 * being sent.
 *
 * @param pvTxData A pointer to the message that is to be copied into the
 * message buffer.
 *
 * @param xDataLengthBytes The length of the message.  That is, the number of
 * bytes to copy from pvTxData into the message buffer.  When a message is
 * written to the message buffer an additional sizeof( size_t ) bytes are also
 * written to store the message's length.  sizeof( size_t ) is typically 4 bytes
 * on a 32-bit architecture, so on most 32-bit architecture setting
 * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24
 * bytes (20 bytes of message data and 4 bytes to hold the message length).
 *
 * @param xTicksToWait The maximum amount of time the calling task should remain
 * in the Blocked state to wait for enough space to become available in the
 * message buffer, should the message buffer have insufficient space when
 * msg_buf_send() is called.  The calling task will never block if
 * xTicksToWait is zero.  The block time is specified in tick periods, so the
 * absolute time it represents is dependent on the tick frequency.  The macro
 * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into
 * a time specified in ticks.  Setting xTicksToWait to portMAX_DELAY will cause
 * the task to wait indefinitely (without timing out), provided
 * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h.  Tasks do not use any
 * CPU time when they are in the Blocked state.
 *
 * @return The number of bytes written to the message buffer.  If the call to
 * msg_buf_send() times out before there was enough space to write the
 * message into the message buffer then zero is returned.  If the call did not
 * time out then xDataLengthBytes is returned.
 *
 * Example use:
void vAFunction( msg_buf_t xMessageBuffer )
{
size_t xBytesSent;
uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
char *pcStringToSend = "String to send";
const uint32_t x100ms = pdMS_TO_TICKS( 100 );

    // Send an array to the message buffer, blocking for a maximum of 100ms to
    // wait for enough space to be available in the message buffer.
    xBytesSent = msg_buf_send( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );

    if( xBytesSent != sizeof( ucArrayToSend ) )
    {
        // The call to msg_buf_send() times out before there was enough
        // space in the buffer for the data to be written.
    }

    // Send the string to the message buffer.  Return immediately if there is
    // not enough space in the buffer.
    xBytesSent = msg_buf_send( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );

    if( xBytesSent != strlen( pcStringToSend ) )
    {
        // The string could not be added to the message buffer because there was
        // not enough free space in the buffer.
    }
}
* \defgroup msg_buf_send msg_buf_send * \ingroup MessageBufferManagement */ #define msg_buf_send( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) stream_buf_send( ( stream_buf_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) /** * message_buffer.h *
size_t xMessageBufferSendFromISR( msg_buf_t xMessageBuffer,
                                  const void *pvTxData,
                                  size_t xDataLengthBytes,
                                  int32_t *pxHigherPriorityTaskWoken );
 *
 * Interrupt safe version of the API function that sends a discrete message to
 * the message buffer.  The message can be any length that fits within the
 * buffer's free space, and is copied into the buffer.
 *
 * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
 * implementation (so also the message buffer implementation, as message buffers
 * are built on top of stream buffers) assumes there is only one task or
 * interrupt that will write to the buffer (the writer), and only one task or
 * interrupt that will read from the buffer (the reader).  It is safe for the
 * writer and reader to be different tasks or interrupts, but, unlike other
 * FreeRTOS objects, it is not safe to have multiple different writers or
 * multiple different readers.  If there are to be multiple different writers
 * then the application writer must place each call to a writing API function
 * (such as msg_buf_send()) inside a critical section and set the send
 * block time to 0.  Likewise, if there are to be multiple different readers
 * then the application writer must place each call to a reading API function
 * (such as xMessageBufferRead()) inside a critical section and set the receive
 * block time to 0.
 *
 * Use msg_buf_send() to write to a message buffer from a task.  Use
 * xMessageBufferSendFromISR() to write to a message buffer from an interrupt
 * service routine (ISR).
 *
 * @param xMessageBuffer The handle of the message buffer to which a message is
 * being sent.
 *
 * @param pvTxData A pointer to the message that is to be copied into the
 * message buffer.
 *
 * @param xDataLengthBytes The length of the message.  That is, the number of
 * bytes to copy from pvTxData into the message buffer.  When a message is
 * written to the message buffer an additional sizeof( size_t ) bytes are also
 * written to store the message's length.  sizeof( size_t ) is typically 4 bytes
 * on a 32-bit architecture, so on most 32-bit architecture setting
 * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24
 * bytes (20 bytes of message data and 4 bytes to hold the message length).
 *
 * @param pxHigherPriorityTaskWoken  It is possible that a message buffer will
 * have a task blocked on it waiting for data.  Calling
 * xMessageBufferSendFromISR() can make data available, and so cause a task that
 * was waiting for data to leave the Blocked state.  If calling
 * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the
 * unblocked task has a priority higher than the currently executing task (the
 * task that was interrupted), then, internally, xMessageBufferSendFromISR()
 * will set *pxHigherPriorityTaskWoken to pdTRUE.  If
 * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a
 * context switch should be performed before the interrupt is exited.  This will
 * ensure that the interrupt returns directly to the highest priority Ready
 * state task.  *pxHigherPriorityTaskWoken should be set to pdFALSE before it
 * is passed into the function.  See the code example below for an example.
 *
 * @return The number of bytes actually written to the message buffer.  If the
 * message buffer didn't have enough free space for the message to be stored
 * then 0 is returned, otherwise xDataLengthBytes is returned.
 *
 * Example use:
// A message buffer that has already been created.
msg_buf_t xMessageBuffer;

void vAnInterruptServiceRoutine( void )
{
size_t xBytesSent;
char *pcStringToSend = "String to send";
int32_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.

    // Attempt to send the string to the message buffer.
    xBytesSent = xMessageBufferSendFromISR( xMessageBuffer,
                                            ( void * ) pcStringToSend,
                                            strlen( pcStringToSend ),
                                            &xHigherPriorityTaskWoken );

    if( xBytesSent != strlen( pcStringToSend ) )
    {
        // The string could not be added to the message buffer because there was
        // not enough free space in the buffer.
    }

    // If xHigherPriorityTaskWoken was set to pdTRUE inside
    // xMessageBufferSendFromISR() then a task that has a priority above the
    // priority of the currently executing task was unblocked and a context
    // switch should be performed to ensure the ISR returns to the unblocked
    // task.  In most FreeRTOS ports this is done by simply passing
    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
    // variables value, and perform the context switch if necessary.  Check the
    // documentation for the port in use for port specific instructions.
    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
* \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR * \ingroup MessageBufferManagement */ #define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferSendFromISR( ( stream_buf_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) /** * message_buffer.h *
size_t msg_buf_recv( msg_buf_t xMessageBuffer,
                              void *pvRxData,
                              size_t xBufferLengthBytes,
                              uint32_t xTicksToWait );
* * Receives a discrete message from a message buffer. Messages can be of * variable length and are copied out of the buffer. * * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer * implementation (so also the message buffer implementation, as message buffers * are built on top of stream buffers) assumes there is only one task or * interrupt that will write to the buffer (the writer), and only one task or * interrupt that will read from the buffer (the reader). It is safe for the * writer and reader to be different tasks or interrupts, but, unlike other * FreeRTOS objects, it is not safe to have multiple different writers or * multiple different readers. If there are to be multiple different writers * then the application writer must place each call to a writing API function * (such as msg_buf_send()) inside a critical section and set the send * block time to 0. Likewise, if there are to be multiple different readers * then the application writer must place each call to a reading API function * (such as xMessageBufferRead()) inside a critical section and set the receive * block time to 0. * * Use msg_buf_recv() to read from a message buffer from a task. Use * xMessageBufferReceiveFromISR() to read from a message buffer from an * interrupt service routine (ISR). * * @param xMessageBuffer The handle of the message buffer from which a message * is being received. * * @param pvRxData A pointer to the buffer into which the received message is * to be copied. * * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData * parameter. This sets the maximum length of the message that can be received. * If xBufferLengthBytes is too small to hold the next message then the message * will be left in the message buffer and 0 will be returned. * * @param xTicksToWait The maximum amount of time the task should remain in the * Blocked state to wait for a message, should the message buffer be empty. * msg_buf_recv() will return immediately if xTicksToWait is zero and * the message buffer is empty. The block time is specified in tick periods, so * the absolute time it represents is dependent on the tick frequency. The * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will * cause the task to wait indefinitely (without timing out), provided * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any * CPU time when they are in the Blocked state. * * @return The length, in bytes, of the message read from the message buffer, if * any. If msg_buf_recv() times out before a message became available * then zero is returned. If the length of the message is greater than * xBufferLengthBytes then the message will be left in the message buffer and * zero is returned. * * Example use:
void vAFunction( MessageBuffer_t xMessageBuffer )
{
uint8_t ucRxData[ 20 ];
size_t xReceivedBytes;
const uint32_t xBlockTime = pdMS_TO_TICKS( 20 );

    // Receive the next message from the message buffer.  Wait in the Blocked
    // state (so not using any CPU processing time) for a maximum of 100ms for
    // a message to become available.
    xReceivedBytes = msg_buf_recv( xMessageBuffer,
                                            ( void * ) ucRxData,
                                            sizeof( ucRxData ),
                                            xBlockTime );

    if( xReceivedBytes > 0 )
    {
        // A ucRxData contains a message that is xReceivedBytes long.  Process
        // the message here....
    }
}
* \defgroup msg_buf_recv msg_buf_recv * \ingroup MessageBufferManagement */ #define msg_buf_recv( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) stream_buf_recv( ( stream_buf_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) /** * message_buffer.h *
size_t xMessageBufferReceiveFromISR( msg_buf_t xMessageBuffer,
                                     void *pvRxData,
                                     size_t xBufferLengthBytes,
                                     int32_t *pxHigherPriorityTaskWoken );
* * An interrupt safe version of the API function that receives a discrete * message from a message buffer. Messages can be of variable length and are * copied out of the buffer. * * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer * implementation (so also the message buffer implementation, as message buffers * are built on top of stream buffers) assumes there is only one task or * interrupt that will write to the buffer (the writer), and only one task or * interrupt that will read from the buffer (the reader). It is safe for the * writer and reader to be different tasks or interrupts, but, unlike other * FreeRTOS objects, it is not safe to have multiple different writers or * multiple different readers. If there are to be multiple different writers * then the application writer must place each call to a writing API function * (such as msg_buf_send()) inside a critical section and set the send * block time to 0. Likewise, if there are to be multiple different readers * then the application writer must place each call to a reading API function * (such as xMessageBufferRead()) inside a critical section and set the receive * block time to 0. * * Use msg_buf_recv() to read from a message buffer from a task. Use * xMessageBufferReceiveFromISR() to read from a message buffer from an * interrupt service routine (ISR). * * @param xMessageBuffer The handle of the message buffer from which a message * is being received. * * @param pvRxData A pointer to the buffer into which the received message is * to be copied. * * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData * parameter. This sets the maximum length of the message that can be received. * If xBufferLengthBytes is too small to hold the next message then the message * will be left in the message buffer and 0 will be returned. * * @param pxHigherPriorityTaskWoken It is possible that a message buffer will * have a task blocked on it waiting for space to become available. Calling * xMessageBufferReceiveFromISR() can make space available, and so cause a task * that is waiting for space to leave the Blocked state. If calling * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and * the unblocked task has a priority higher than the currently executing task * (the task that was interrupted), then, internally, * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a * context switch should be performed before the interrupt is exited. That will * ensure the interrupt returns directly to the highest priority Ready state * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is * passed into the function. See the code example below for an example. * * @return The length, in bytes, of the message read from the message buffer, if * any. * * Example use:
// A message buffer that has already been created.
MessageBuffer_t xMessageBuffer;

void vAnInterruptServiceRoutine( void )
{
uint8_t ucRxData[ 20 ];
size_t xReceivedBytes;
int32_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.

    // Receive the next message from the message buffer.
    xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer,
                                                  ( void * ) ucRxData,
                                                  sizeof( ucRxData ),
                                                  &xHigherPriorityTaskWoken );

    if( xReceivedBytes > 0 )
    {
        // A ucRxData contains a message that is xReceivedBytes long.  Process
        // the message here....
    }

    // If xHigherPriorityTaskWoken was set to pdTRUE inside
    // xMessageBufferReceiveFromISR() then a task that has a priority above the
    // priority of the currently executing task was unblocked and a context
    // switch should be performed to ensure the ISR returns to the unblocked
    // task.  In most FreeRTOS ports this is done by simply passing
    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
    // variables value, and perform the context switch if necessary.  Check the
    // documentation for the port in use for port specific instructions.
    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
* \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR * \ingroup MessageBufferManagement */ #define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferReceiveFromISR( ( stream_buf_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) /** * message_buffer.h *
void vMessageBufferDelete( msg_buf_t xMessageBuffer );
* * Deletes a message buffer that was previously created using a call to * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), * then the allocated memory is freed. * * A message buffer handle must not be used after the message buffer has been * deleted. * * @param xMessageBuffer The handle of the message buffer to be deleted. * */ #define vMessageBufferDelete( xMessageBuffer ) vStreamBufferDelete( ( stream_buf_t ) xMessageBuffer ) /** * message_buffer.h
int32_t msg_buf_is_full( msg_buf_t xMessageBuffer ) );
* * Tests to see if a message buffer is full. A message buffer is full if it * cannot accept any more messages, of any size, until space is made available * by a message being removed from the message buffer. * * @param xMessageBuffer The handle of the message buffer being queried. * * @return If the message buffer referenced by xMessageBuffer is full then * pdTRUE is returned. Otherwise pdFALSE is returned. */ #define msg_buf_is_full( xMessageBuffer ) stream_buf_is_full( ( stream_buf_t ) xMessageBuffer ) /** * message_buffer.h
int32_t msg_buf_is_empty( msg_buf_t xMessageBuffer ) );
* * Tests to see if a message buffer is empty (does not contain any messages). * * @param xMessageBuffer The handle of the message buffer being queried. * * @return If the message buffer referenced by xMessageBuffer is empty then * pdTRUE is returned. Otherwise pdFALSE is returned. * */ #define msg_buf_is_empty( xMessageBuffer ) stream_buf_is_empty( ( stream_buf_t ) xMessageBuffer ) /** * message_buffer.h
int32_t msg_buf_reset( msg_buf_t xMessageBuffer );
* * Resets a message buffer to its initial empty state, discarding any message it * contained. * * A message buffer can only be reset if there are no tasks blocked on it. * * @param xMessageBuffer The handle of the message buffer being reset. * * @return If the message buffer was reset then pdPASS is returned. If the * message buffer could not be reset because either there was a task blocked on * the message queue to wait for space to become available, or to wait for a * a message to be available, then pdFAIL is returned. * * \defgroup msg_buf_reset msg_buf_reset * \ingroup MessageBufferManagement */ #define msg_buf_reset( xMessageBuffer ) stream_buf_reset( ( stream_buf_t ) xMessageBuffer ) /** * message_buffer.h
size_t xMessageBufferSpaceAvailable( msg_buf_t xMessageBuffer ) );
* Returns the number of bytes of free space in the message buffer. * * @param xMessageBuffer The handle of the message buffer being queried. * * @return The number of bytes that can be written to the message buffer before * the message buffer would be full. When a message is written to the message * buffer an additional sizeof( size_t ) bytes are also written to store the * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit * architecture, so if msg_buf_get_unused() returns 10, then the size * of the largest message that can be written to the message buffer is 6 bytes. * * \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable * \ingroup MessageBufferManagement */ #define xMessageBufferSpaceAvailable( xMessageBuffer ) stream_buf_get_unused( ( stream_buf_t ) xMessageBuffer ) /** * message_buffer.h *
int32_t xMessageBufferSendCompletedFromISR( msg_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken );
* * For advanced users only. * * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when * data is sent to a message buffer or stream buffer. If there was a task that * was blocked on the message or stream buffer waiting for data to arrive then * the sbSEND_COMPLETED() macro sends a notification to the task to remove it * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same * thing. It is provided to enable application writers to implement their own * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. * * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for * additional information. * * @param xStreamBuffer The handle of the stream buffer to which data was * written. * * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be * initialised to pdFALSE before it is passed into * xMessageBufferSendCompletedFromISR(). If calling * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, * and the task has a priority above the priority of the currently running task, * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a * context switch should be performed before exiting the ISR. * * @return If a task was removed from the Blocked state then pdTRUE is returned. * Otherwise pdFALSE is returned. * * \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR * \ingroup StreamBufferManagement */ #define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferSendCompletedFromISR( ( stream_buf_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) /** * message_buffer.h *
int32_t xMessageBufferReceiveCompletedFromISR( msg_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken );
* * For advanced users only. * * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when * data is read out of a message buffer or stream buffer. If there was a task * that was blocked on the message or stream buffer waiting for data to arrive * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() * does the same thing. It is provided to enable application writers to * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT * ANY OTHER TIME. * * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for * additional information. * * @param xStreamBuffer The handle of the stream buffer from which data was * read. * * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be * initialised to pdFALSE before it is passed into * xMessageBufferReceiveCompletedFromISR(). If calling * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, * and the task has a priority above the priority of the currently running task, * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a * context switch should be performed before exiting the ISR. * * @return If a task was removed from the Blocked state then pdTRUE is returned. * Otherwise pdFALSE is returned. * * \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR * \ingroup StreamBufferManagement */ #define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferReceiveCompletedFromISR( ( stream_buf_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) #if defined( __cplusplus ) } /* extern "C" */ #endif #endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ ================================================ FILE: include/rtos/portable.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /*----------------------------------------------------------- * Portable layer API. Each function must be defined for each port. *----------------------------------------------------------*/ #ifndef PORTABLE_H #define PORTABLE_H /* If portENTER_CRITICAL is not defined then including deprecated_definitions.h did not result in a portmacro.h header file being included - and it should be included here. In this case the path to the correct portmacro.h header file must be set in the compiler's include path. */ #ifndef portENTER_CRITICAL #include "portmacro.h" #endif #if portBYTE_ALIGNMENT == 32 #define portBYTE_ALIGNMENT_MASK ( 0x001f ) #endif #if portBYTE_ALIGNMENT == 16 #define portBYTE_ALIGNMENT_MASK ( 0x000f ) #endif #if portBYTE_ALIGNMENT == 8 #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) #endif #if portBYTE_ALIGNMENT == 4 #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) #endif #if portBYTE_ALIGNMENT == 2 #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) #endif #if portBYTE_ALIGNMENT == 1 #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) #endif #ifndef portBYTE_ALIGNMENT_MASK #error "Invalid portBYTE_ALIGNMENT definition" #endif #ifndef portNUM_CONFIGURABLE_REGIONS #define portNUM_CONFIGURABLE_REGIONS 1 #endif #ifdef __cplusplus extern "C" { #endif /* * Setup the stack of a new task so it is ready to be placed under the * scheduler control. The registers have to be placed on the stack in * the order that the port expects to find them. * */ task_stack_t *pxPortInitialiseStack( task_stack_t *pxTopOfStack, task_fn_t pxCode, void *pvParameters ) ; /* Used by heap_5.c. */ typedef struct HeapRegion { uint8_t *pucStartAddress; size_t xSizeInBytes; } HeapRegion_t; /* * Used to define multiple heap regions for use by heap_5.c. This function * must be called before any calls to kmalloc() - not creating a task, * queue, semaphore, mutex, software timer, event group, etc. will result in * kmalloc being called. * * pxHeapRegions passes in an array of HeapRegion_t structures - each of which * defines a region of memory that can be used as the heap. The array is * terminated by a HeapRegions_t structure that has a size of 0. The region * with the lowest start address must appear first in the array. */ void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) ; /* * Map to the memory management routines required for the port. */ void *kmalloc( size_t xSize ) ; void kfree( void *pv ) ; void vPortInitialiseBlocks( void ) ; size_t xPortGetFreeHeapSize( void ) ; size_t xPortGetMinimumEverFreeHeapSize( void ) ; /* * Setup the hardware ready for the scheduler to take control. This generally * sets up a tick interrupt and sets timers for the correct tick frequency. */ int32_t xPortStartScheduler( void ) ; /* * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so * the hardware is left in its original condition after the scheduler stops * executing. */ void vPortEndScheduler( void ) ; #ifdef __cplusplus } #endif #endif /* PORTABLE_H */ ================================================ FILE: include/rtos/portmacro.h ================================================ /* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ #ifndef PORTMACRO_H #define PORTMACRO_H #ifdef __cplusplus extern "C" { #endif /*----------------------------------------------------------- * Port specific definitions. * * The settings in this file configure FreeRTOS correctly for the given hardware * and compiler. * * These settings should not be altered. *----------------------------------------------------------- */ /* Type definitions. */ #define portCHAR char #define portFLOAT float #define portDOUBLE double #define portLONG long #define portSHORT short #define portSTACK_TYPE uint32_t #define portBASE_TYPE long typedef portSTACK_TYPE task_stack_t; typedef long int32_t; typedef unsigned long uint32_t; typedef uint32_t uint32_t; #define portMAX_DELAY ( uint32_t ) 0xffffffffUL /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do not need to be guarded with a critical section. */ #define portTICK_TYPE_IS_ATOMIC 1 /*-----------------------------------------------------------*/ /* Hardware specifics. */ #define portSTACK_GROWTH ( -1 ) #define portTICK_PERIOD_MS ( ( uint32_t ) 1000 / configTICK_RATE_HZ ) #define portBYTE_ALIGNMENT 8 /*-----------------------------------------------------------*/ /* Task utilities. */ /* Called at the end of an ISR that can cause a context switch. */ #define portEND_SWITCHING_ISR( xSwitchRequired )\ { \ extern uint32_t ulPortYieldRequired; \ \ if( xSwitchRequired != pdFALSE ) \ { \ ulPortYieldRequired = pdTRUE; \ } \ } #define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) #define portYIELD() __asm volatile ( "SWI 0" ); /*----------------------------------------------------------- * Critical section control *----------------------------------------------------------*/ extern void vPortEnterCritical( void ); extern void vPortExitCritical( void ); extern uint32_t ulPortSetInterruptMask( void ); extern void vPortClearInterruptMask( uint32_t ulNewMaskValue ); extern void vPortInstallFreeRTOSVectorTable( void ); /* These macros do not globally disable/enable interrupts. They do mask off interrupts that have a priority below configMAX_API_CALL_INTERRUPT_PRIORITY. */ #define portENTER_CRITICAL() vPortEnterCritical(); #define portEXIT_CRITICAL() vPortExitCritical(); #define portDISABLE_INTERRUPTS() ulPortSetInterruptMask() #define portENABLE_INTERRUPTS() vPortClearInterruptMask( 0 ) #define portSET_INTERRUPT_MASK_FROM_ISR() ulPortSetInterruptMask() #define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortClearInterruptMask(x) /*-----------------------------------------------------------*/ /* Task function macros as described on the FreeRTOS.org WEB site. These are not required for this port but included in case common demo code that uses these macros is used. */ #define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) #define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) /* Prototype of the FreeRTOS tick handler. This must be installed as the handler for whichever peripheral is used to generate the RTOS tick. */ void FreeRTOS_Tick_Handler( void ); /* If configUSE_TASK_FPU_SUPPORT is set to 1 (or left undefined) then tasks are created without an FPU context and must call vPortTaskUsesFPU() to give themselves an FPU context before using any FPU instructions. If configUSE_TASK_FPU_SUPPORT is set to 2 then all tasks will have an FPU context by default. */ #if( configUSE_TASK_FPU_SUPPORT != 2 ) void vPortTaskUsesFPU( void ); #else /* Each task has an FPU context already, so define this function away to nothing to prevent it being called accidentally. */ #define vPortTaskUsesFPU() #endif #define portTASK_USES_FLOATING_POINT() vPortTaskUsesFPU() #define portLOWEST_INTERRUPT_PRIORITY ( ( ( uint32_t ) configUNIQUE_INTERRUPT_PRIORITIES ) - 1UL ) #define portLOWEST_USABLE_INTERRUPT_PRIORITY ( portLOWEST_INTERRUPT_PRIORITY - 1UL ) /* Architecture specific optimisations. */ #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #endif #if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 /* Store/clear the ready priorities in a bit map. */ #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) /*-----------------------------------------------------------*/ #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - ( uint32_t ) __builtin_clz( uxReadyPriorities ) ) #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ #ifdef configASSERT void vPortValidateInterruptPriority( void ); #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority() #endif /* configASSERT */ #define portNOP() __asm volatile( "NOP" ) #define portINLINE __inline #ifdef __cplusplus } /* extern C */ #endif /* The number of bits to shift for an interrupt priority is dependent on the number of bits implemented by the interrupt controller. */ #if configUNIQUE_INTERRUPT_PRIORITIES == 16 #define portPRIORITY_SHIFT 4 #define portMAX_BINARY_POINT_VALUE 3 #elif configUNIQUE_INTERRUPT_PRIORITIES == 32 #define portPRIORITY_SHIFT 3 #define portMAX_BINARY_POINT_VALUE 2 #elif configUNIQUE_INTERRUPT_PRIORITIES == 64 #define portPRIORITY_SHIFT 2 #define portMAX_BINARY_POINT_VALUE 1 #elif configUNIQUE_INTERRUPT_PRIORITIES == 128 #define portPRIORITY_SHIFT 1 #define portMAX_BINARY_POINT_VALUE 0 #elif configUNIQUE_INTERRUPT_PRIORITIES == 256 #define portPRIORITY_SHIFT 0 #define portMAX_BINARY_POINT_VALUE 0 #else #error Invalid configUNIQUE_INTERRUPT_PRIORITIES setting. configUNIQUE_INTERRUPT_PRIORITIES must be set to the number of unique priorities implemented by the target hardware #endif /* Interrupt controller access addresses. */ #define portICCPMR_PRIORITY_MASK_OFFSET ( 0x04 ) #define portICCIAR_INTERRUPT_ACKNOWLEDGE_OFFSET ( 0x0C ) #define portICCEOIR_END_OF_INTERRUPT_OFFSET ( 0x10 ) #define portICCBPR_BINARY_POINT_OFFSET ( 0x08 ) #define portICCRPR_RUNNING_PRIORITY_OFFSET ( 0x14 ) #define portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS ( configINTERRUPT_CONTROLLER_BASE_ADDRESS + configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET ) #define portICCPMR_PRIORITY_MASK_REGISTER ( *( ( volatile uint32_t * ) ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCPMR_PRIORITY_MASK_OFFSET ) ) ) #define portICCIAR_INTERRUPT_ACKNOWLEDGE_REGISTER_ADDRESS ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCIAR_INTERRUPT_ACKNOWLEDGE_OFFSET ) #define portICCEOIR_END_OF_INTERRUPT_REGISTER_ADDRESS ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCEOIR_END_OF_INTERRUPT_OFFSET ) #define portICCPMR_PRIORITY_MASK_REGISTER_ADDRESS ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCPMR_PRIORITY_MASK_OFFSET ) #define portICCBPR_BINARY_POINT_REGISTER ( *( ( const volatile uint32_t * ) ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCBPR_BINARY_POINT_OFFSET ) ) ) #define portICCRPR_RUNNING_PRIORITY_REGISTER ( *( ( const volatile uint32_t * ) ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCRPR_RUNNING_PRIORITY_OFFSET ) ) ) #endif /* PORTMACRO_H */ ================================================ FILE: include/rtos/projdefs.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef PROJDEFS_H #define PROJDEFS_H /* * Defines the prototype to which task functions must conform. Defined in this * file to ensure the type is known before portable.h is included. */ typedef void (*task_fn_t)( void * ); /* Converts a time in milliseconds to a time in ticks. This macro can be overridden by a macro of the same name defined in FreeRTOSConfig.h in case the definition here is not suitable for your application. */ #ifndef pdMS_TO_TICKS #define pdMS_TO_TICKS( xTimeInMs ) ( ( uint32_t ) ( ( ( uint32_t ) ( xTimeInMs ) * ( uint32_t ) configTICK_RATE_HZ ) / ( uint32_t ) 1000 ) ) #endif #define pdFALSE ( ( int32_t ) 0 ) #define pdTRUE ( ( int32_t ) 1 ) #define pdPASS ( pdTRUE ) #define pdFAIL ( pdFALSE ) #define errQUEUE_EMPTY ( ( int32_t ) 0 ) #define errQUEUE_FULL ( ( int32_t ) 0 ) /* FreeRTOS error definitions. */ #define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) #define errQUEUE_BLOCKED ( -4 ) #define errQUEUE_YIELD ( -5 ) /* Macros used for basic data corruption checks. */ #ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 #endif #if( configUSE_16_BIT_TICKS == 1 ) #define pdINTEGRITY_CHECK_VALUE 0x5a5a #else #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL #endif /* The following errno values are used by FreeRTOS+ components, not FreeRTOS itself. */ #define pdFREERTOS_ERRNO_NONE 0 /* No errors */ #define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ #define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ #define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ #define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ #define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ #define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ #define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ #define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ #define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ #define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ #define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ #define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ #define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ #define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ #define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ #define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ #define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ #define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ #define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ #define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ #define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ #define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ #define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ #define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ #define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ #define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ #define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ #define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ #define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ #define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ #define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ #define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ #define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ #define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ #define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ #define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ #define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ #define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ /* The following endian values are used by FreeRTOS+ components, not FreeRTOS itself. */ #define pdFREERTOS_LITTLE_ENDIAN 0 #define pdFREERTOS_BIG_ENDIAN 1 /* Re-defining endian values for generic naming. */ #define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN #define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN #endif /* PROJDEFS_H */ ================================================ FILE: include/rtos/queue.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef QUEUE_H #define QUEUE_H #ifndef INC_FREERTOS_H #error "include FreeRTOS.h" must appear in source files before "include queue.h" #endif #ifdef __cplusplus extern "C" { #endif /** * Type by which queues are referenced. For example, a call to queue_create() * returns an queue_t variable that can then be used as a parameter to * xQueueSend(), queue_recv(), etc. */ typedef void * queue_t; /** * Type by which queue sets are referenced. For example, a call to * xQueueCreateSet() returns an xQueueSet variable that can then be used as a * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. */ typedef void * QueueSetHandle_t; /** * Queue sets can contain both queues and semaphores, so the * QueueSetMemberHandle_t is defined as a type to be used where a parameter or * return value can be either an queue_t or an sem_t. */ typedef void * QueueSetMemberHandle_t; /* For internal use only. */ #define queueSEND_TO_BACK ( ( int32_t ) 0 ) #define queueSEND_TO_FRONT ( ( int32_t ) 1 ) #define queueOVERWRITE ( ( int32_t ) 2 ) /* For internal use only. These definitions *must* match those in queue.c. */ #define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) #define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) #define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) #define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) #define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) #define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) /** * queue. h *
 queue_t queue_create(
							  uint32_t uxQueueLength,
							  uint32_t uxItemSize
						  );
 * 
* * Creates a new queue instance, and returns a handle by which the new queue * can be referenced. * * Internally, within the FreeRTOS implementation, queues use two blocks of * memory. The first block is used to hold the queue's data structures. The * second block is used to hold items placed into the queue. If a queue is * created using queue_create() then both blocks of memory are automatically * dynamically allocated inside the queue_create() function. (see * http://www.freertos.org/a00111.html). If a queue is created using * queue_create_static() then the application writer must provide the memory that * will get used by the queue. queue_create_static() therefore allows a queue to * be created without using any dynamic memory allocation. * * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html * * @param uxQueueLength The maximum number of items that the queue can contain. * * @param uxItemSize The number of bytes each item in the queue will require. * Items are queued by copy, not by reference, so this is the number of bytes * that will be copied for each posted item. Each item on the queue must be * the same size. * * @return If the queue is successfully create then a handle to the newly * created queue is returned. If the queue cannot be created then 0 is * returned. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 };

 void vATask( void *pvParameters )
 {
 queue_t xQueue1, xQueue2;

	// Create a queue capable of containing 10 uint32_t values.
	xQueue1 = queue_create( 10, sizeof( uint32_t ) );
	if( xQueue1 == 0 )
	{
		// Queue was not created and must not be used.
	}

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue2 = queue_create( 10, sizeof( struct AMessage * ) );
	if( xQueue2 == 0 )
	{
		// Queue was not created and must not be used.
	}

	// ... Rest of task code.
 }
 
* \defgroup queue_create queue_create * \ingroup QueueManagement */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) queue_t queue_create(uint32_t uxQueueLength, uint32_t uxItemSize); #endif /** * queue. h *
 queue_t queue_create_static(
							  uint32_t uxQueueLength,
							  uint32_t uxItemSize,
							  uint8_t *pucQueueStorageBuffer,
							  static_queue_s_t *pxQueueBuffer
						  );
 * 
* * Creates a new queue instance, and returns a handle by which the new queue * can be referenced. * * Internally, within the FreeRTOS implementation, queues use two blocks of * memory. The first block is used to hold the queue's data structures. The * second block is used to hold items placed into the queue. If a queue is * created using queue_create() then both blocks of memory are automatically * dynamically allocated inside the queue_create() function. (see * http://www.freertos.org/a00111.html). If a queue is created using * queue_create_static() then the application writer must provide the memory that * will get used by the queue. queue_create_static() therefore allows a queue to * be created without using any dynamic memory allocation. * * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html * * @param uxQueueLength The maximum number of items that the queue can contain. * * @param uxItemSize The number of bytes each item in the queue will require. * Items are queued by copy, not by reference, so this is the number of bytes * that will be copied for each posted item. Each item on the queue must be * the same size. * * @param pucQueueStorageBuffer If uxItemSize is not zero then * pucQueueStorageBuffer must point to a uint8_t array that is at least large * enough to hold the maximum number of items that can be in the queue at any * one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is * zero then pucQueueStorageBuffer can be NULL. * * @param pxQueueBuffer Must point to a variable of type static_queue_s_t, which * will be used to hold the queue's data structure. * * @return If the queue is created then a handle to the created queue is * returned. If pxQueueBuffer is NULL then NULL is returned. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 };

 #define QUEUE_LENGTH 10
 #define ITEM_SIZE sizeof( uint32_t )

 // xQueueBuffer will hold the queue structure.
 static_queue_s_t xQueueBuffer;

 // ucQueueStorage will hold the items posted to the queue.  Must be at least
 // [(queue length) * ( queue item size)] bytes long.
 uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ];

 void vATask( void *pvParameters )
 {
 queue_t xQueue1;

	// Create a queue capable of containing 10 uint32_t values.
	xQueue1 = queue_create( QUEUE_LENGTH, // The number of items the queue can hold.
							ITEM_SIZE	  // The size of each item in the queue
							&( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue.
							&xQueueBuffer ); // The buffer that will hold the queue structure.

	// The queue is guaranteed to be created successfully as no dynamic memory
	// allocation is used.  Therefore xQueue1 is now a handle to a valid queue.

	// ... Rest of task code.
 }
 
* \defgroup queue_create_static queue_create_static * \ingroup QueueManagement */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) queue_t queue_create_static(uint32_t uxQueueLength, uint32_t uxItemSize, uint8_t *pucQueueStorageBuffer, static_queue_s_t *pxQueueBuffer); #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * queue. h *
 int32_t queue_prepend(
								   queue_t	xQueue,
								   const void		*pvItemToQueue,
								   uint32_t		xTicksToWait
							   );
 * 
* * Post an item to the front of a queue. The item is queued by copy, not by * reference. This function must not be called from an interrupt service * routine. See xQueueSendFromISR () for an alternative which may be used * in an ISR. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param xTicksToWait The maximum amount of time the task should block * waiting for space to become available on the queue, should it already * be full. The call will return immediately if this is set to 0 and the * queue is full. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 } xMessage;

 uint32_t ulVar = 10UL;

 void vATask( void *pvParameters )
 {
 queue_t xQueue1, xQueue2;
 struct AMessage *pxMessage;

	// Create a queue capable of containing 10 uint32_t values.
	xQueue1 = queue_create( 10, sizeof( uint32_t ) );

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue2 = queue_create( 10, sizeof( struct AMessage * ) );

	// ...

	if( xQueue1 != 0 )
	{
		// Send an uint32_t.  Wait for 10 ticks for space to become
		// available if necessary.
		if( queue_prepend( xQueue1, ( void * ) &ulVar, ( uint32_t ) 10 ) != pdPASS )
		{
			// Failed to post the message, even after 10 ticks.
		}
	}

	if( xQueue2 != 0 )
	{
		// Send a pointer to a struct AMessage object.  Don't block if the
		// queue is already full.
		pxMessage = & xMessage;
		queue_prepend( xQueue2, ( void * ) &pxMessage, ( uint32_t ) 0 );
	}

	// ... Rest of task code.
 }
 
* \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ bool queue_prepend(queue_t queue, const void* item, uint32_t timeout); /** * queue. h *
 int32_t queue_append(
								   queue_t	xQueue,
								   const void		*pvItemToQueue,
								   uint32_t		xTicksToWait
							   );
 * 
* * This is a macro that calls xQueueGenericSend(). * * Post an item to the back of a queue. The item is queued by copy, not by * reference. This function must not be called from an interrupt service * routine. See xQueueSendFromISR () for an alternative which may be used * in an ISR. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param xTicksToWait The maximum amount of time the task should block * waiting for space to become available on the queue, should it already * be full. The call will return immediately if this is set to 0 and the queue * is full. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 } xMessage;

 uint32_t ulVar = 10UL;

 void vATask( void *pvParameters )
 {
 queue_t xQueue1, xQueue2;
 struct AMessage *pxMessage;

	// Create a queue capable of containing 10 uint32_t values.
	xQueue1 = queue_create( 10, sizeof( uint32_t ) );

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue2 = queue_create( 10, sizeof( struct AMessage * ) );

	// ...

	if( xQueue1 != 0 )
	{
		// Send an uint32_t.  Wait for 10 ticks for space to become
		// available if necessary.
		if( queue_append( xQueue1, ( void * ) &ulVar, ( uint32_t ) 10 ) != pdPASS )
		{
			// Failed to post the message, even after 10 ticks.
		}
	}

	if( xQueue2 != 0 )
	{
		// Send a pointer to a struct AMessage object.  Don't block if the
		// queue is already full.
		pxMessage = & xMessage;
		queue_append( xQueue2, ( void * ) &pxMessage, ( uint32_t ) 0 );
	}

	// ... Rest of task code.
 }
 
* \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ bool queue_append(queue_t queue, const void* item, uint32_t timeout); /** * queue. h *
 int32_t xQueueSend(
							  queue_t xQueue,
							  const void * pvItemToQueue,
							  uint32_t xTicksToWait
						 );
 * 
* * This is a macro that calls xQueueGenericSend(). It is included for * backward compatibility with versions of FreeRTOS.org that did not * include the queue_prepend() and queue_append() macros. It is * equivalent to queue_append(). * * Post an item on a queue. The item is queued by copy, not by reference. * This function must not be called from an interrupt service routine. * See xQueueSendFromISR () for an alternative which may be used in an ISR. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param xTicksToWait The maximum amount of time the task should block * waiting for space to become available on the queue, should it already * be full. The call will return immediately if this is set to 0 and the * queue is full. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 } xMessage;

 uint32_t ulVar = 10UL;

 void vATask( void *pvParameters )
 {
 queue_t xQueue1, xQueue2;
 struct AMessage *pxMessage;

	// Create a queue capable of containing 10 uint32_t values.
	xQueue1 = queue_create( 10, sizeof( uint32_t ) );

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue2 = queue_create( 10, sizeof( struct AMessage * ) );

	// ...

	if( xQueue1 != 0 )
	{
		// Send an uint32_t.  Wait for 10 ticks for space to become
		// available if necessary.
		if( xQueueSend( xQueue1, ( void * ) &ulVar, ( uint32_t ) 10 ) != pdPASS )
		{
			// Failed to post the message, even after 10 ticks.
		}
	}

	if( xQueue2 != 0 )
	{
		// Send a pointer to a struct AMessage object.  Don't block if the
		// queue is already full.
		pxMessage = & xMessage;
		xQueueSend( xQueue2, ( void * ) &pxMessage, ( uint32_t ) 0 );
	}

	// ... Rest of task code.
 }
 
* \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ #define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) /** * queue. h *
 int32_t queue_overwrite(
							  queue_t xQueue,
							  const void * pvItemToQueue
						 );
 * 
* * Only for use with queues that have a length of one - so the queue is either * empty or full. * * Post an item on a queue. If the queue is already full then overwrite the * value held in the queue. The item is queued by copy, not by reference. * * This function must not be called from an interrupt service routine. * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. * * @param xQueue The handle of the queue to which the data is being sent. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @return queue_overwrite() is a macro that calls xQueueGenericSend(), and * therefore has the same return values as queue_prepend(). However, pdPASS * is the only value that can be returned because queue_overwrite() will write * to the queue even when the queue is already full. * * Example usage:

 void vFunction( void *pvParameters )
 {
 queue_t xQueue;
 uint32_t ulVarToSend, ulValReceived;

	// Create a queue to hold one uint32_t value.  It is strongly
	// recommended *not* to use queue_overwrite() on queues that can
	// contain more than one value, and doing so will trigger an assertion
	// if configASSERT() is defined.
	xQueue = queue_create( 1, sizeof( uint32_t ) );

	// Write the value 10 to the queue using queue_overwrite().
	ulVarToSend = 10;
	queue_overwrite( xQueue, &ulVarToSend );

	// Peeking the queue should now return 10, but leave the value 10 in
	// the queue.  A block time of zero is used as it is known that the
	// queue holds a value.
	ulValReceived = 0;
	queue_peek( xQueue, &ulValReceived, 0 );

	if( ulValReceived != 10 )
	{
		// Error unless the item was removed by a different task.
	}

	// The queue is still full.  Use queue_overwrite() to overwrite the
	// value held in the queue with 100.
	ulVarToSend = 100;
	queue_overwrite( xQueue, &ulVarToSend );

	// This time read from the queue, leaving the queue empty once more.
	// A block time of 0 is used again.
	queue_recv( xQueue, &ulValReceived, 0 );

	// The value read should be the last value written, even though the
	// queue was already full when the value was written.
	if( ulValReceived != 100 )
	{
		// Error!
	}

	// ...
}
 
* \defgroup queue_overwrite queue_overwrite * \ingroup QueueManagement */ #define queue_overwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE ) /** * queue. h *
 int32_t xQueueGenericSend(
									queue_t xQueue,
									const void * pvItemToQueue,
									uint32_t xTicksToWait
									int32_t xCopyPosition
								);
 * 
* * It is preferred that the macros xQueueSend(), queue_prepend() and * queue_append() are used in place of calling this function directly. * * Post an item on a queue. The item is queued by copy, not by reference. * This function must not be called from an interrupt service routine. * See xQueueSendFromISR () for an alternative which may be used in an ISR. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param xTicksToWait The maximum amount of time the task should block * waiting for space to become available on the queue, should it already * be full. The call will return immediately if this is set to 0 and the * queue is full. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the * item at the back of the queue, or queueSEND_TO_FRONT to place the item * at the front of the queue (for high priority messages). * * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 } xMessage;

 uint32_t ulVar = 10UL;

 void vATask( void *pvParameters )
 {
 queue_t xQueue1, xQueue2;
 struct AMessage *pxMessage;

	// Create a queue capable of containing 10 uint32_t values.
	xQueue1 = queue_create( 10, sizeof( uint32_t ) );

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue2 = queue_create( 10, sizeof( struct AMessage * ) );

	// ...

	if( xQueue1 != 0 )
	{
		// Send an uint32_t.  Wait for 10 ticks for space to become
		// available if necessary.
		if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( uint32_t ) 10, queueSEND_TO_BACK ) != pdPASS )
		{
			// Failed to post the message, even after 10 ticks.
		}
	}

	if( xQueue2 != 0 )
	{
		// Send a pointer to a struct AMessage object.  Don't block if the
		// queue is already full.
		pxMessage = & xMessage;
		xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( uint32_t ) 0, queueSEND_TO_BACK );
	}

	// ... Rest of task code.
 }
 
* \defgroup xQueueSend xQueueSend * \ingroup QueueManagement */ int32_t xQueueGenericSend( queue_t xQueue, const void * const pvItemToQueue, uint32_t xTicksToWait, const int32_t xCopyPosition ) ; /** * queue. h *
 int32_t queue_peek(
							 queue_t xQueue,
							 void * const pvBuffer,
							 uint32_t xTicksToWait
						 );
* * Receive an item from a queue without removing the item from the queue. * The item is received by copy so a buffer of adequate size must be * provided. The number of bytes copied into the buffer was defined when * the queue was created. * * Successfully received items remain on the queue so will be returned again * by the next call, or a call to queue_recv(). * * This macro must not be used in an interrupt service routine. See * xQueuePeekFromISR() for an alternative that can be called from an interrupt * service routine. * * @param xQueue The handle to the queue from which the item is to be * received. * * @param pvBuffer Pointer to the buffer into which the received item will * be copied. * * @param xTicksToWait The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time * of the call. The time is defined in tick periods so the constant * portTICK_PERIOD_MS should be used to convert to real time if this is required. * queue_peek() will return immediately if xTicksToWait is 0 and the queue * is empty. * * @return pdTRUE if an item was successfully received from the queue, * otherwise pdFALSE. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 } xMessage;

 queue_t xQueue;

 // Task to create a queue and post a value.
 void vATask( void *pvParameters )
 {
 struct AMessage *pxMessage;

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue = queue_create( 10, sizeof( struct AMessage * ) );
	if( xQueue == 0 )
	{
		// Failed to create the queue.
	}

	// ...

	// Send a pointer to a struct AMessage object.  Don't block if the
	// queue is already full.
	pxMessage = & xMessage;
	xQueueSend( xQueue, ( void * ) &pxMessage, ( uint32_t ) 0 );

	// ... Rest of task code.
 }

 // Task to peek the data from the queue.
 void vADifferentTask( void *pvParameters )
 {
 struct AMessage *pxRxedMessage;

	if( xQueue != 0 )
	{
		// Peek a message on the created queue.  Block for 10 ticks if a
		// message is not immediately available.
		if( queue_peek( xQueue, &( pxRxedMessage ), ( uint32_t ) 10 ) )
		{
			// pcRxedMessage now points to the struct AMessage variable posted
			// by vATask, but the item still remains on the queue.
		}
	}

	// ... Rest of task code.
 }
 
* \defgroup queue_peek queue_peek * \ingroup QueueManagement */ int32_t queue_peek( queue_t xQueue, void * const pvBuffer, uint32_t xTicksToWait ) ; /** * queue. h *
 int32_t xQueuePeekFromISR(
									queue_t xQueue,
									void *pvBuffer,
								);
* * A version of queue_peek() that can be called from an interrupt service * routine (ISR). * * Receive an item from a queue without removing the item from the queue. * The item is received by copy so a buffer of adequate size must be * provided. The number of bytes copied into the buffer was defined when * the queue was created. * * Successfully received items remain on the queue so will be returned again * by the next call, or a call to queue_recv(). * * @param xQueue The handle to the queue from which the item is to be * received. * * @param pvBuffer Pointer to the buffer into which the received item will * be copied. * * @return pdTRUE if an item was successfully received from the queue, * otherwise pdFALSE. * * \defgroup xQueuePeekFromISR xQueuePeekFromISR * \ingroup QueueManagement */ int32_t xQueuePeekFromISR( queue_t xQueue, void * const pvBuffer ) ; /** * queue. h *
 int32_t queue_recv(
								 queue_t xQueue,
								 void *pvBuffer,
								 uint32_t xTicksToWait
							);
* * Receive an item from a queue. The item is received by copy so a buffer of * adequate size must be provided. The number of bytes copied into the buffer * was defined when the queue was created. * * Successfully received items are removed from the queue. * * This function must not be used in an interrupt service routine. See * xQueueReceiveFromISR for an alternative that can. * * @param xQueue The handle to the queue from which the item is to be * received. * * @param pvBuffer Pointer to the buffer into which the received item will * be copied. * * @param xTicksToWait The maximum amount of time the task should block * waiting for an item to receive should the queue be empty at the time * of the call. queue_recv() will return immediately if xTicksToWait * is zero and the queue is empty. The time is defined in tick periods so the * constant portTICK_PERIOD_MS should be used to convert to real time if this is * required. * * @return pdTRUE if an item was successfully received from the queue, * otherwise pdFALSE. * * Example usage:
 struct AMessage
 {
	char ucMessageID;
	char ucData[ 20 ];
 } xMessage;

 queue_t xQueue;

 // Task to create a queue and post a value.
 void vATask( void *pvParameters )
 {
 struct AMessage *pxMessage;

	// Create a queue capable of containing 10 pointers to AMessage structures.
	// These should be passed by pointer as they contain a lot of data.
	xQueue = queue_create( 10, sizeof( struct AMessage * ) );
	if( xQueue == 0 )
	{
		// Failed to create the queue.
	}

	// ...

	// Send a pointer to a struct AMessage object.  Don't block if the
	// queue is already full.
	pxMessage = & xMessage;
	xQueueSend( xQueue, ( void * ) &pxMessage, ( uint32_t ) 0 );

	// ... Rest of task code.
 }

 // Task to receive from the queue.
 void vADifferentTask( void *pvParameters )
 {
 struct AMessage *pxRxedMessage;

	if( xQueue != 0 )
	{
		// Receive a message on the created queue.  Block for 10 ticks if a
		// message is not immediately available.
		if( queue_recv( xQueue, &( pxRxedMessage ), ( uint32_t ) 10 ) )
		{
			// pcRxedMessage now points to the struct AMessage variable posted
			// by vATask.
		}
	}

	// ... Rest of task code.
 }
 
* \defgroup queue_recv queue_recv * \ingroup QueueManagement */ int32_t queue_recv( queue_t xQueue, void * const pvBuffer, uint32_t xTicksToWait ) ; /** * queue. h *
uint32_t queue_get_waiting( const queue_t xQueue );
* * Return the number of messages stored in a queue. * * @param xQueue A handle to the queue being queried. * * @return The number of messages available in the queue. * * \defgroup queue_get_waiting queue_get_waiting * \ingroup QueueManagement */ uint32_t queue_get_waiting( const queue_t xQueue ) ; /** * queue. h *
uint32_t queue_get_available( const queue_t xQueue );
* * Return the number of free spaces available in a queue. This is equal to the * number of items that can be sent to the queue before the queue becomes full * if no items are removed. * * @param xQueue A handle to the queue being queried. * * @return The number of spaces available in the queue. * * \defgroup queue_get_waiting queue_get_waiting * \ingroup QueueManagement */ uint32_t queue_get_available( const queue_t xQueue ) ; /** * queue. h *
void queue_delete( queue_t xQueue );
* * Delete a queue - freeing all the memory allocated for storing of items * placed on the queue. * * @param xQueue A handle to the queue to be deleted. * * \defgroup queue_delete queue_delete * \ingroup QueueManagement */ void queue_delete( queue_t xQueue ) ; /** * queue. h *
 int32_t xQueueSendToFrontFromISR(
										 queue_t xQueue,
										 const void *pvItemToQueue,
										 int32_t *pxHigherPriorityTaskWoken
									  );
 
* * This is a macro that calls xQueueGenericSendFromISR(). * * Post an item to the front of a queue. It is safe to use this macro from * within an interrupt service routine. * * Items are queued by copy not reference so it is preferable to only * queue small items, especially when called from an ISR. In most cases * it would be preferable to store a pointer to the item being queued. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return pdTRUE if the data was successfully sent to the queue, otherwise * errQUEUE_FULL. * * Example usage for buffered IO (where the ISR can obtain more than one value * per call):
 void vBufferISR( void )
 {
 char cIn;
 int32_t xHigherPrioritTaskWoken;

	// We have not woken a task at the start of the ISR.
	xHigherPriorityTaskWoken = pdFALSE;

	// Loop until the buffer is empty.
	do
	{
		// Obtain a byte from the buffer.
		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );

		// Post the byte.
		xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );

	} while( portINPUT_BYTE( BUFFER_COUNT ) );

	// Now the buffer is empty we can switch context if necessary.
	if( xHigherPriorityTaskWoken )
	{
		taskYIELD ();
	}
 }
 
* * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement */ #define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT ) /** * queue. h *
 int32_t xQueueSendToBackFromISR(
										 queue_t xQueue,
										 const void *pvItemToQueue,
										 int32_t *pxHigherPriorityTaskWoken
									  );
 
* * This is a macro that calls xQueueGenericSendFromISR(). * * Post an item to the back of a queue. It is safe to use this macro from * within an interrupt service routine. * * Items are queued by copy not reference so it is preferable to only * queue small items, especially when called from an ISR. In most cases * it would be preferable to store a pointer to the item being queued. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return pdTRUE if the data was successfully sent to the queue, otherwise * errQUEUE_FULL. * * Example usage for buffered IO (where the ISR can obtain more than one value * per call):
 void vBufferISR( void )
 {
 char cIn;
 int32_t xHigherPriorityTaskWoken;

	// We have not woken a task at the start of the ISR.
	xHigherPriorityTaskWoken = pdFALSE;

	// Loop until the buffer is empty.
	do
	{
		// Obtain a byte from the buffer.
		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );

		// Post the byte.
		xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );

	} while( portINPUT_BYTE( BUFFER_COUNT ) );

	// Now the buffer is empty we can switch context if necessary.
	if( xHigherPriorityTaskWoken )
	{
		taskYIELD ();
	}
 }
 
* * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement */ #define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) /** * queue. h *
 int32_t xQueueOverwriteFromISR(
							  queue_t xQueue,
							  const void * pvItemToQueue,
							  int32_t *pxHigherPriorityTaskWoken
						 );
 * 
* * A version of queue_overwrite() that can be used in an interrupt service * routine (ISR). * * Only for use with queues that can hold a single item - so the queue is either * empty or full. * * Post an item on a queue. If the queue is already full then overwrite the * value held in the queue. The item is queued by copy, not by reference. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return xQueueOverwriteFromISR() is a macro that calls * xQueueGenericSendFromISR(), and therefore has the same return values as * xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be * returned because xQueueOverwriteFromISR() will write to the queue even when * the queue is already full. * * Example usage:

 queue_t xQueue;

 void vFunction( void *pvParameters )
 {
 	// Create a queue to hold one uint32_t value.  It is strongly
	// recommended *not* to use xQueueOverwriteFromISR() on queues that can
	// contain more than one value, and doing so will trigger an assertion
	// if configASSERT() is defined.
	xQueue = queue_create( 1, sizeof( uint32_t ) );
}

void vAnInterruptHandler( void )
{
// xHigherPriorityTaskWoken must be set to pdFALSE before it is used.
int32_t xHigherPriorityTaskWoken = pdFALSE;
uint32_t ulVarToSend, ulValReceived;

	// Write the value 10 to the queue using xQueueOverwriteFromISR().
	ulVarToSend = 10;
	xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );

	// The queue is full, but calling xQueueOverwriteFromISR() again will still
	// pass because the value held in the queue will be overwritten with the
	// new value.
	ulVarToSend = 100;
	xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );

	// Reading from the queue will now return 100.

	// ...

	if( xHigherPrioritytaskWoken == pdTRUE )
	{
		// Writing to the queue caused a task to unblock and the unblocked task
		// has a priority higher than or equal to the priority of the currently
		// executing task (the task this interrupt interrupted).  Perform a context
		// switch so this interrupt returns directly to the unblocked task.
		portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port.
	}
}
 
* \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR * \ingroup QueueManagement */ #define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE ) /** * queue. h *
 int32_t xQueueSendFromISR(
									 queue_t xQueue,
									 const void *pvItemToQueue,
									 int32_t *pxHigherPriorityTaskWoken
								);
 
* * This is a macro that calls xQueueGenericSendFromISR(). It is included * for backward compatibility with versions of FreeRTOS.org that did not * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() * macros. * * Post an item to the back of a queue. It is safe to use this function from * within an interrupt service routine. * * Items are queued by copy not reference so it is preferable to only * queue small items, especially when called from an ISR. In most cases * it would be preferable to store a pointer to the item being queued. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param pxHigherPriorityTaskWoken xQueueSendFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xQueueSendFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return pdTRUE if the data was successfully sent to the queue, otherwise * errQUEUE_FULL. * * Example usage for buffered IO (where the ISR can obtain more than one value * per call):
 void vBufferISR( void )
 {
 char cIn;
 int32_t xHigherPriorityTaskWoken;

	// We have not woken a task at the start of the ISR.
	xHigherPriorityTaskWoken = pdFALSE;

	// Loop until the buffer is empty.
	do
	{
		// Obtain a byte from the buffer.
		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );

		// Post the byte.
		xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );

	} while( portINPUT_BYTE( BUFFER_COUNT ) );

	// Now the buffer is empty we can switch context if necessary.
	if( xHigherPriorityTaskWoken )
	{
		// Actual macro used here is port specific.
		portYIELD_FROM_ISR ();
	}
 }
 
* * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement */ #define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) /** * queue. h *
 int32_t xQueueGenericSendFromISR(
										   queue_t		xQueue,
										   const	void	*pvItemToQueue,
										   int32_t	*pxHigherPriorityTaskWoken,
										   int32_t	xCopyPosition
									   );
 
* * It is preferred that the macros xQueueSendFromISR(), * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place * of calling this function directly. xQueueGiveFromISR() is an * equivalent for use by semaphores that don't actually copy any data. * * Post an item on a queue. It is safe to use this function from within an * interrupt service routine. * * Items are queued by copy not reference so it is preferable to only * queue small items, especially when called from an ISR. In most cases * it would be preferable to store a pointer to the item being queued. * * @param xQueue The handle to the queue on which the item is to be posted. * * @param pvItemToQueue A pointer to the item that is to be placed on the * queue. The size of the items the queue will hold was defined when the * queue was created, so this many bytes will be copied from pvItemToQueue * into the queue storage area. * * @param pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the * item at the back of the queue, or queueSEND_TO_FRONT to place the item * at the front of the queue (for high priority messages). * * @return pdTRUE if the data was successfully sent to the queue, otherwise * errQUEUE_FULL. * * Example usage for buffered IO (where the ISR can obtain more than one value * per call):
 void vBufferISR( void )
 {
 char cIn;
 int32_t xHigherPriorityTaskWokenByPost;

	// We have not woken a task at the start of the ISR.
	xHigherPriorityTaskWokenByPost = pdFALSE;

	// Loop until the buffer is empty.
	do
	{
		// Obtain a byte from the buffer.
		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );

		// Post each byte.
		xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK );

	} while( portINPUT_BYTE( BUFFER_COUNT ) );

	// Now the buffer is empty we can switch context if necessary.  Note that the
	// name of the yield function required is port specific.
	if( xHigherPriorityTaskWokenByPost )
	{
		taskYIELD_YIELD_FROM_ISR();
	}
 }
 
* * \defgroup xQueueSendFromISR xQueueSendFromISR * \ingroup QueueManagement */ int32_t xQueueGenericSendFromISR( queue_t xQueue, const void * const pvItemToQueue, int32_t * const pxHigherPriorityTaskWoken, const int32_t xCopyPosition ) ; int32_t xQueueGiveFromISR( queue_t xQueue, int32_t * const pxHigherPriorityTaskWoken ) ; /** * queue. h *
 int32_t xQueueReceiveFromISR(
									   queue_t	xQueue,
									   void	*pvBuffer,
									   int32_t *pxTaskWoken
								   );
 * 
* * Receive an item from a queue. It is safe to use this function from within an * interrupt service routine. * * @param xQueue The handle to the queue from which the item is to be * received. * * @param pvBuffer Pointer to the buffer into which the received item will * be copied. * * @param pxTaskWoken A task may be blocked waiting for space to become * available on the queue. If xQueueReceiveFromISR causes such a task to * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will * remain unchanged. * * @return pdTRUE if an item was successfully received from the queue, * otherwise pdFALSE. * * Example usage:

 queue_t xQueue;

 // Function to create a queue and post some values.
 void vAFunction( void *pvParameters )
 {
 char cValueToPost;
 const uint32_t xTicksToWait = ( uint32_t )0xff;

	// Create a queue capable of containing 10 characters.
	xQueue = queue_create( 10, sizeof( char ) );
	if( xQueue == 0 )
	{
		// Failed to create the queue.
	}

	// ...

	// Post some characters that will be used within an ISR.  If the queue
	// is full then this task will block for xTicksToWait ticks.
	cValueToPost = 'a';
	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
	cValueToPost = 'b';
	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );

	// ... keep posting characters ... this task may block when the queue
	// becomes full.

	cValueToPost = 'c';
	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
 }

 // ISR that outputs all the characters received on the queue.
 void vISR_Routine( void )
 {
 int32_t xTaskWokenByReceive = pdFALSE;
 char cRxedChar;

	while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) )
	{
		// A character was received.  Output the character now.
		vOutputCharacter( cRxedChar );

		// If removing the character from the queue woke the task that was
		// posting onto the queue cTaskWokenByReceive will have been set to
		// pdTRUE.  No matter how many times this loop iterates only one
		// task will be woken.
	}

	if( cTaskWokenByPost != ( char ) pdFALSE;
	{
		taskYIELD ();
	}
 }
 
* \defgroup xQueueReceiveFromISR xQueueReceiveFromISR * \ingroup QueueManagement */ int32_t xQueueReceiveFromISR( queue_t xQueue, void * const pvBuffer, int32_t * const pxHigherPriorityTaskWoken ) ; /* * Utilities to query queues that are safe to use from an ISR. These utilities * should be used only from witin an ISR, or within a critical section. */ int32_t xQueueIsQueueEmptyFromISR( const queue_t xQueue ) ; int32_t xQueueIsQueueFullFromISR( const queue_t xQueue ) ; uint32_t uxQueueMessagesWaitingFromISR( const queue_t xQueue ) ; /* * The functions defined above are for passing data to and from tasks. The * functions below are the equivalents for passing data to and from * co-routines. * * These functions are called from the co-routine macro implementation and * should not be called directly from application code. Instead use the macro * wrappers defined within croutine.h. */ int32_t xQueueCRSendFromISR( queue_t xQueue, const void *pvItemToQueue, int32_t xCoRoutinePreviouslyWoken ); int32_t xQueueCRReceiveFromISR( queue_t xQueue, void *pvBuffer, int32_t *pxTaskWoken ); int32_t xQueueCRSend( queue_t xQueue, const void *pvItemToQueue, uint32_t xTicksToWait ); int32_t xQueueCRReceive( queue_t xQueue, void *pvBuffer, uint32_t xTicksToWait ); /* * For internal use only. Use mutex_create(), * sem_create() or mutex_get_owner() instead of calling * these functions directly. */ queue_t xQueueCreateMutex( const uint8_t ucQueueType ) ; queue_t xQueueCreateMutexStatic( const uint8_t ucQueueType, static_queue_s_t *pxStaticQueue ) ; queue_t xQueueCreateCountingSemaphore( const uint32_t uxMaxCount, const uint32_t uxInitialCount ) ; queue_t xQueueCreateCountingSemaphoreStatic( const uint32_t uxMaxCount, const uint32_t uxInitialCount, static_queue_s_t *pxStaticQueue ) ; int32_t xQueueSemaphoreTake( queue_t xQueue, uint32_t xTicksToWait ) ; void* xQueueGetMutexHolder( queue_t xSemaphore ) ; void* xQueueGetMutexHolderFromISR( queue_t xSemaphore ) ; /* * For internal use only. Use xSemaphoreTakeMutexRecursive() or * xSemaphoreGiveMutexRecursive() instead of calling these functions directly. */ int32_t xQueueTakeMutexRecursive( queue_t xMutex, uint32_t xTicksToWait ) ; int32_t xQueueGiveMutexRecursive( queue_t pxMutex ) ; /* * Reset a queue back to its original empty state. The return value is now * obsolete and is always set to pdPASS. */ void queue_reset(queue_t queue); /* * The registry is provided as a means for kernel aware debuggers to * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add * a queue, semaphore or mutex handle to the registry if you want the handle * to be available to a kernel aware debugger. If you are not using a kernel * aware debugger then this function can be ignored. * * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the * registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 * within FreeRTOSConfig.h for the registry to be available. Its value * does not effect the number of queues, semaphores and mutexes that can be * created - just the number that the registry can hold. * * @param xQueue The handle of the queue being added to the registry. This * is the handle returned by a call to queue_create(). Semaphore and mutex * handles can also be passed in here. * * @param pcName The name to be associated with the handle. This is the * name that the kernel aware debugger will display. The queue registry only * stores a pointer to the string - so the string must be persistent (global or * preferably in ROM/Flash), not on the stack. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) void vQueueAddToRegistry( queue_t xQueue, const char *pcName ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #endif /* * The registry is provided as a means for kernel aware debuggers to * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add * a queue, semaphore or mutex handle to the registry if you want the handle * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to * remove the queue, semaphore or mutex from the register. If you are not using * a kernel aware debugger then this function can be ignored. * * @param xQueue The handle of the queue being removed from the registry. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) void vQueueUnregisterQueue( queue_t xQueue ) ; #endif /* * The queue registry is provided as a means for kernel aware debuggers to * locate queues, semaphores and mutexes. Call pcQueueGetName() to look * up and return the name of a queue in the queue registry from the queue's * handle. * * @param xQueue The handle of the queue the name of which will be returned. * @return If the queue is in the registry then a pointer to the name of the * queue is returned. If the queue is not in the registry then NULL is * returned. */ #if( configQUEUE_REGISTRY_SIZE > 0 ) const char *pcQueueGetName( queue_t xQueue ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #endif /* * Generic version of the function used to creaet a queue using dynamic memory * allocation. This is called by other functions and macros that create other * RTOS objects that use the queue structure as their base. */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) queue_t xQueueGenericCreate( const uint32_t uxQueueLength, const uint32_t uxItemSize, const uint8_t ucQueueType ) ; #endif /* * Generic version of the function used to creaet a queue using dynamic memory * allocation. This is called by other functions and macros that create other * RTOS objects that use the queue structure as their base. */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) queue_t xQueueGenericCreateStatic( const uint32_t uxQueueLength, const uint32_t uxItemSize, uint8_t *pucQueueStorage, static_queue_s_t *pxStaticQueue, const uint8_t ucQueueType ) ; #endif /* * Queue sets provide a mechanism to allow a task to block (pend) on a read * operation from multiple queues or semaphores simultaneously. * * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this * function. * * A queue set must be explicitly created using a call to xQueueCreateSet() * before it can be used. Once created, standard FreeRTOS queues and semaphores * can be added to the set using calls to xQueueAddToSet(). * xQueueSelectFromSet() is then used to determine which, if any, of the queues * or semaphores contained in the set is in a state where a queue read or * semaphore take operation would be successful. * * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html * for reasons why queue sets are very rarely needed in practice as there are * simpler methods of blocking on multiple objects. * * Note 2: Blocking on a queue set that contains a mutex will not cause the * mutex holder to inherit the priority of the blocked task. * * Note 3: An additional 4 bytes of RAM is required for each space in a every * queue added to a queue set. Therefore counting semaphores that have a high * maximum count value should not be added to a queue set. * * Note 4: A receive (in the case of a queue) or take (in the case of a * semaphore) operation must not be performed on a member of a queue set unless * a call to xQueueSelectFromSet() has first returned a handle to that set member. * * @param uxEventQueueLength Queue sets store events that occur on * the queues and semaphores contained in the set. uxEventQueueLength specifies * the maximum number of events that can be queued at once. To be absolutely * certain that events are not lost uxEventQueueLength should be set to the * total sum of the length of the queues added to the set, where binary * semaphores and mutexes have a length of 1, and counting semaphores have a * length set by their maximum count value. Examples: * + If a queue set is to hold a queue of length 5, another queue of length 12, * and a binary semaphore, then uxEventQueueLength should be set to * (5 + 12 + 1), or 18. * + If a queue set is to hold three binary semaphores then uxEventQueueLength * should be set to (1 + 1 + 1 ), or 3. * + If a queue set is to hold a counting semaphore that has a maximum count of * 5, and a counting semaphore that has a maximum count of 3, then * uxEventQueueLength should be set to (5 + 3), or 8. * * @return If the queue set is created successfully then a handle to the created * queue set is returned. Otherwise NULL is returned. */ QueueSetHandle_t xQueueCreateSet( const uint32_t uxEventQueueLength ) ; /* * Adds a queue or semaphore to a queue set that was previously created by a * call to xQueueCreateSet(). * * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this * function. * * Note 1: A receive (in the case of a queue) or take (in the case of a * semaphore) operation must not be performed on a member of a queue set unless * a call to xQueueSelectFromSet() has first returned a handle to that set member. * * @param xQueueOrSemaphore The handle of the queue or semaphore being added to * the queue set (cast to an QueueSetMemberHandle_t type). * * @param xQueueSet The handle of the queue set to which the queue or semaphore * is being added. * * @return If the queue or semaphore was successfully added to the queue set * then pdPASS is returned. If the queue could not be successfully added to the * queue set because it is already a member of a different queue set then pdFAIL * is returned. */ int32_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) ; /* * Removes a queue or semaphore from a queue set. A queue or semaphore can only * be removed from a set if the queue or semaphore is empty. * * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this * function. * * @param xQueueOrSemaphore The handle of the queue or semaphore being removed * from the queue set (cast to an QueueSetMemberHandle_t type). * * @param xQueueSet The handle of the queue set in which the queue or semaphore * is included. * * @return If the queue or semaphore was successfully removed from the queue set * then pdPASS is returned. If the queue was not in the queue set, or the * queue (or semaphore) was not empty, then pdFAIL is returned. */ int32_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) ; /* * xQueueSelectFromSet() selects from the members of a queue set a queue or * semaphore that either contains data (in the case of a queue) or is available * to take (in the case of a semaphore). xQueueSelectFromSet() effectively * allows a task to block (pend) on a read operation on all the queues and * semaphores in a queue set simultaneously. * * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this * function. * * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html * for reasons why queue sets are very rarely needed in practice as there are * simpler methods of blocking on multiple objects. * * Note 2: Blocking on a queue set that contains a mutex will not cause the * mutex holder to inherit the priority of the blocked task. * * Note 3: A receive (in the case of a queue) or take (in the case of a * semaphore) operation must not be performed on a member of a queue set unless * a call to xQueueSelectFromSet() has first returned a handle to that set member. * * @param xQueueSet The queue set on which the task will (potentially) block. * * @param xTicksToWait The maximum time, in ticks, that the calling task will * remain in the Blocked state (with other tasks executing) to wait for a member * of the queue set to be ready for a successful queue read or semaphore take * operation. * * @return xQueueSelectFromSet() will return the handle of a queue (cast to * a QueueSetMemberHandle_t type) contained in the queue set that contains data, * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained * in the queue set that is available, or NULL if no such queue or semaphore * exists before before the specified block time expires. */ QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const uint32_t xTicksToWait ) ; /* * A version of xQueueSelectFromSet() that can be used from an ISR. */ QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) ; /* Not public API functions. */ void vQueueWaitForMessageRestricted( queue_t xQueue, uint32_t xTicksToWait, const int32_t xWaitIndefinitely ) ; int32_t xQueueGenericReset( queue_t xQueue, int32_t xNewQueue ) ; void vQueueSetQueueNumber( queue_t xQueue, uint32_t uxQueueNumber ) ; uint32_t uxQueueGetQueueNumber( queue_t xQueue ) ; uint8_t ucQueueGetQueueType( queue_t xQueue ) ; #ifdef __cplusplus } #endif #endif /* QUEUE_H */ ================================================ FILE: include/rtos/semphr.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef SEMAPHORE_H #define SEMAPHORE_H #ifndef INC_FREERTOS_H #error "include FreeRTOS.h" must appear in source files before "include semphr.h" #endif #include "queue.h" #include "task.h" typedef queue_t sem_t; typedef queue_t mutex_t; #define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) #define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) #define semGIVE_BLOCK_TIME ( ( uint32_t ) 0U ) /** * semphr. h *
vSemaphoreCreateBinary( sem_t xSemaphore )
* * In many usage scenarios it is faster and more memory efficient to use a * direct to task notification in place of a binary semaphore! * http://www.freertos.org/RTOS-task-notifications.html * * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the * sem_binary_create() function. Note that binary semaphores created using * the vSemaphoreCreateBinary() macro are created in a state such that the * first call to 'take' the semaphore would pass, whereas binary semaphores * created using sem_binary_create() are created in a state such that the * the semaphore must first be 'given' before it can be 'taken'. * * Macro that implements a semaphore by using the existing queue mechanism. * The queue length is 1 as this is a binary semaphore. The data size is 0 * as we don't want to actually store any data - we just want to know if the * queue is empty or full. * * This type of semaphore can be used for pure synchronisation between tasks or * between an interrupt and a task. The semaphore need not be given back once * obtained, so one task/interrupt can continuously 'give' the semaphore while * another continuously 'takes' the semaphore. For this reason this type of * semaphore does not use a priority inheritance mechanism. For an alternative * that does use priority inheritance see mutex_create(). * * @param xSemaphore Handle to the created semaphore. Should be of type sem_t. * * Example usage:
 sem_t xSemaphore = NULL;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
    // This is a macro so pass the variable in directly.
    vSemaphoreCreateBinary( xSemaphore );

    if( xSemaphore != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) #define vSemaphoreCreateBinary( xSemaphore ) \ { \ ( xSemaphore ) = xQueueGenericCreate( ( uint32_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ if( ( xSemaphore ) != NULL ) \ { \ ( void ) sem_post( ( xSemaphore ) ); \ } \ } #endif /** * semphr. h *
sem_t sem_binary_create( void )
* * Creates a new binary semaphore instance, and returns a handle by which the * new semaphore can be referenced. * * In many usage scenarios it is faster and more memory efficient to use a * direct to task notification in place of a binary semaphore! * http://www.freertos.org/RTOS-task-notifications.html * * Internally, within the FreeRTOS implementation, binary semaphores use a block * of memory, in which the semaphore structure is stored. If a binary semaphore * is created using sem_binary_create() then the required memory is * automatically dynamically allocated inside the sem_binary_create() * function. (see http://www.freertos.org/a00111.html). If a binary semaphore * is created using xSemaphoreCreateBinaryStatic() then the application writer * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a * binary semaphore to be created without using any dynamic memory allocation. * * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this * sem_binary_create() function. Note that binary semaphores created using * the vSemaphoreCreateBinary() macro are created in a state such that the * first call to 'take' the semaphore would pass, whereas binary semaphores * created using sem_binary_create() are created in a state such that the * the semaphore must first be 'given' before it can be 'taken'. * * This type of semaphore can be used for pure synchronisation between tasks or * between an interrupt and a task. The semaphore need not be given back once * obtained, so one task/interrupt can continuously 'give' the semaphore while * another continuously 'takes' the semaphore. For this reason this type of * semaphore does not use a priority inheritance mechanism. For an alternative * that does use priority inheritance see mutex_create(). * * @return Handle to the created semaphore, or NULL if the memory required to * hold the semaphore's data structures could not be allocated. * * Example usage:
 sem_t xSemaphore = NULL;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to sem_binary_create().
    // This is a macro so pass the variable in directly.
    xSemaphore = sem_binary_create();

    if( xSemaphore != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup sem_binary_create sem_binary_create * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) sem_t sem_binary_create(); #endif /** * semphr. h *
sem_t xSemaphoreCreateBinaryStatic( static_sem_s_t *pxSemaphoreBuffer )
* * Creates a new binary semaphore instance, and returns a handle by which the * new semaphore can be referenced. * * NOTE: In many usage scenarios it is faster and more memory efficient to use a * direct to task notification in place of a binary semaphore! * http://www.freertos.org/RTOS-task-notifications.html * * Internally, within the FreeRTOS implementation, binary semaphores use a block * of memory, in which the semaphore structure is stored. If a binary semaphore * is created using sem_binary_create() then the required memory is * automatically dynamically allocated inside the sem_binary_create() * function. (see http://www.freertos.org/a00111.html). If a binary semaphore * is created using xSemaphoreCreateBinaryStatic() then the application writer * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a * binary semaphore to be created without using any dynamic memory allocation. * * This type of semaphore can be used for pure synchronisation between tasks or * between an interrupt and a task. The semaphore need not be given back once * obtained, so one task/interrupt can continuously 'give' the semaphore while * another continuously 'takes' the semaphore. For this reason this type of * semaphore does not use a priority inheritance mechanism. For an alternative * that does use priority inheritance see mutex_create(). * * @param pxSemaphoreBuffer Must point to a variable of type static_sem_s_t, * which will then be used to hold the semaphore's data structure, removing the * need for the memory to be allocated dynamically. * * @return If the semaphore is created then a handle to the created semaphore is * returned. If pxSemaphoreBuffer is NULL then NULL is returned. * * Example usage:
 sem_t xSemaphore = NULL;
 static_sem_s_t xSemaphoreBuffer;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to sem_binary_create().
    // The semaphore's data structures will be placed in the xSemaphoreBuffer
    // variable, the address of which is passed into the function.  The
    // function's parameter is not NULL, so the function will not attempt any
    // dynamic memory allocation, and therefore the function will not return
    // return NULL.
    xSemaphore = sem_binary_create( &xSemaphoreBuffer );

    // Rest of task code goes here.
 }
 
* \defgroup xSemaphoreCreateBinaryStatic xSemaphoreCreateBinaryStatic * \ingroup Semaphores */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( uint32_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * semphr. h *
sem_wait(
 *                   sem_t xSemaphore,
 *                   uint32_t xBlockTime
 *               )
* * Macro to obtain a semaphore. The semaphore must have previously been * created with a call to sem_binary_create(), mutex_create() or * sem_create(). * * @param xSemaphore A handle to the semaphore being taken - obtained when * the semaphore was created. * * @param xBlockTime The time in ticks to wait for the semaphore to become * available. The macro portTICK_PERIOD_MS can be used to convert this to a * real time. A block time of zero can be used to poll the semaphore. A block * time of portMAX_DELAY can be used to block indefinitely (provided * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). * * @return pdTRUE if the semaphore was obtained. pdFALSE * if xBlockTime expired without the semaphore becoming available. * * Example usage:
 sem_t xSemaphore = NULL;

 // A task that creates a semaphore.
 void vATask( void * pvParameters )
 {
    // Create the semaphore to guard a shared resource.
    xSemaphore = sem_binary_create();
 }

 // A task that uses the semaphore.
 void vAnotherTask( void * pvParameters )
 {
    // ... Do other things.

    if( xSemaphore != NULL )
    {
        // See if we can obtain the semaphore.  If the semaphore is not available
        // wait 10 ticks to see if it becomes free.
        if( sem_wait( xSemaphore, ( uint32_t ) 10 ) == pdTRUE )
        {
            // We were able to obtain the semaphore and can now access the
            // shared resource.

            // ...

            // We have finished accessing the shared resource.  Release the
            // semaphore.
            sem_post( xSemaphore );
        }
        else
        {
            // We could not obtain the semaphore and can therefore not access
            // the shared resource safely.
        }
    }
 }
 
* \defgroup sem_wait sem_wait * \ingroup Semaphores */ uint8_t sem_wait(sem_t sem, uint32_t block_time); /** * semphr. h * mutex_recursive_take( * sem_t xMutex, * uint32_t xBlockTime * ) * * Macro to recursively obtain, or 'take', a mutex type semaphore. * The mutex must have previously been created using a call to * mutex_recursive_create(); * * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this * macro to be available. * * This macro must not be used on mutexes created using mutex_create(). * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * @param xMutex A handle to the mutex being obtained. This is the * handle returned by mutex_recursive_create(); * * @param xBlockTime The time in ticks to wait for the semaphore to become * available. The macro portTICK_PERIOD_MS can be used to convert this to a * real time. A block time of zero can be used to poll the semaphore. If * the task already owns the semaphore then mutex_recursive_take() will * return immediately no matter what the value of xBlockTime. * * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime * expired without the semaphore becoming available. * * Example usage:
 sem_t xMutex = NULL;

 // A task that creates a mutex.
 void vATask( void * pvParameters )
 {
    // Create the mutex to guard a shared resource.
    xMutex = mutex_recursive_create();
 }

 // A task that uses the mutex.
 void vAnotherTask( void * pvParameters )
 {
    // ... Do other things.

    if( xMutex != NULL )
    {
        // See if we can obtain the mutex.  If the mutex is not available
        // wait 10 ticks to see if it becomes free.
        if( mutex_recursive_take( xSemaphore, ( uint32_t ) 10 ) == pdTRUE )
        {
            // We were able to obtain the mutex and can now access the
            // shared resource.

            // ...
            // For some reason due to the nature of the code further calls to
            // mutex_recursive_take() are made on the same mutex.  In real
            // code these would not be just sequential calls as this would make
            // no sense.  Instead the calls are likely to be buried inside
            // a more complex call structure.
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );

            // The mutex has now been 'taken' three times, so will not be
            // available to another task until it has also been given back
            // three times.  Again it is unlikely that real code would have
            // these calls sequentially, but instead buried in a more complex
            // call structure.  This is just for illustrative purposes.
            mutex_recursive_give( xMutex );
            mutex_recursive_give( xMutex );
            mutex_recursive_give( xMutex );

            // Now the mutex can be taken by other tasks.
        }
        else
        {
            // We could not obtain the mutex and can therefore not access
            // the shared resource safely.
        }
    }
 }
 
* \defgroup mutex_recursive_take mutex_recursive_take * \ingroup Semaphores */ #if( configUSE_RECURSIVE_MUTEXES == 1 ) uint8_t mutex_recursive_take(mutex_t mutex, uint32_t block_time); #endif /** * semphr. h *
sem_post( sem_t xSemaphore )
* * Macro to release a semaphore. The semaphore must have previously been * created with a call to sem_binary_create(), mutex_create() or * sem_create(). and obtained using sSemaphoreTake(). * * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for * an alternative which can be used from an ISR. * * This macro must also not be used on semaphores created using * mutex_recursive_create(). * * @param xSemaphore A handle to the semaphore being released. This is the * handle returned when the semaphore was created. * * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. * Semaphores are implemented using queues. An error can occur if there is * no space on the queue to post a message - indicating that the * semaphore was not first obtained correctly. * * Example usage:
 sem_t xSemaphore = NULL;

 void vATask( void * pvParameters )
 {
    // Create the semaphore to guard a shared resource.
    xSemaphore = vSemaphoreCreateBinary();

    if( xSemaphore != NULL )
    {
        if( sem_post( xSemaphore ) != pdTRUE )
        {
            // We would expect this call to fail because we cannot give
            // a semaphore without first "taking" it!
        }

        // Obtain the semaphore - don't block if the semaphore is not
        // immediately available.
        if( sem_wait( xSemaphore, ( uint32_t ) 0 ) )
        {
            // We now have the semaphore and can access the shared resource.

            // ...

            // We have finished accessing the shared resource so can free the
            // semaphore.
            if( sem_post( xSemaphore ) != pdTRUE )
            {
                // We would not expect this call to fail because we must have
                // obtained the semaphore to get here.
            }
        }
    }
 }
 
* \defgroup sem_post sem_post * \ingroup Semaphores */ uint8_t sem_post(sem_t sem); /** * semphr. h *
mutex_recursive_give( sem_t xMutex )
* * Macro to recursively release, or 'give', a mutex type semaphore. * The mutex must have previously been created using a call to * mutex_recursive_create(); * * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this * macro to be available. * * This macro must not be used on mutexes created using mutex_create(). * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * @param xMutex A handle to the mutex being released, or 'given'. This is the * handle returned by mutex_create(); * * @return pdTRUE if the semaphore was given. * * Example usage:
 sem_t xMutex = NULL;

 // A task that creates a mutex.
 void vATask( void * pvParameters )
 {
    // Create the mutex to guard a shared resource.
    xMutex = mutex_recursive_create();
 }

 // A task that uses the mutex.
 void vAnotherTask( void * pvParameters )
 {
    // ... Do other things.

    if( xMutex != NULL )
    {
        // See if we can obtain the mutex.  If the mutex is not available
        // wait 10 ticks to see if it becomes free.
        if( mutex_recursive_take( xMutex, ( uint32_t ) 10 ) == pdTRUE )
        {
            // We were able to obtain the mutex and can now access the
            // shared resource.

            // ...
            // For some reason due to the nature of the code further calls to
			// mutex_recursive_take() are made on the same mutex.  In real
			// code these would not be just sequential calls as this would make
			// no sense.  Instead the calls are likely to be buried inside
			// a more complex call structure.
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );

            // The mutex has now been 'taken' three times, so will not be
			// available to another task until it has also been given back
			// three times.  Again it is unlikely that real code would have
			// these calls sequentially, it would be more likely that the calls
			// to mutex_recursive_give() would be called as a call stack
			// unwound.  This is just for demonstrative purposes.
            mutex_recursive_give( xMutex );
			mutex_recursive_give( xMutex );
			mutex_recursive_give( xMutex );

			// Now the mutex can be taken by other tasks.
        }
        else
        {
            // We could not obtain the mutex and can therefore not access
            // the shared resource safely.
        }
    }
 }
 
* \defgroup mutex_recursive_give mutex_recursive_give * \ingroup Semaphores */ #if( configUSE_RECURSIVE_MUTEXES == 1 ) uint8_t mutex_recursive_give(mutex_t mutex); #endif /** * semphr. h *
 xSemaphoreGiveFromISR(
                          sem_t xSemaphore,
                          int32_t *pxHigherPriorityTaskWoken
                      )
* * Macro to release a semaphore. The semaphore must have previously been * created with a call to sem_binary_create() or sem_create(). * * Mutex type semaphores (those created using a call to mutex_create()) * must not be used with this macro. * * This macro can be used from an ISR. * * @param xSemaphore A handle to the semaphore being released. This is the * handle returned when the semaphore was created. * * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. * * Example usage:
 \#define LONG_TIME 0xffff
 \#define TICKS_TO_WAIT	10
 sem_t xSemaphore = NULL;

 // Repetitive task.
 void vATask( void * pvParameters )
 {
    for( ;; )
    {
        // We want this task to run every 10 ticks of a timer.  The semaphore
        // was created before this task was started.

        // Block waiting for the semaphore to become available.
        if( sem_wait( xSemaphore, LONG_TIME ) == pdTRUE )
        {
            // It is time to execute.

            // ...

            // We have finished our task.  Return to the top of the loop where
            // we will block on the semaphore until it is time to execute
            // again.  Note when using the semaphore for synchronisation with an
			// ISR in this manner there is no need to 'give' the semaphore back.
        }
    }
 }

 // Timer ISR
 void vTimerISR( void * pvParameters )
 {
 static uint8_t ucLocalTickCount = 0;
 static int32_t xHigherPriorityTaskWoken;

    // A timer tick has occurred.

    // ... Do other time functions.

    // Is it time for vATask () to run?
	xHigherPriorityTaskWoken = pdFALSE;
    ucLocalTickCount++;
    if( ucLocalTickCount >= TICKS_TO_WAIT )
    {
        // Unblock the task by releasing the semaphore.
        xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken );

        // Reset the count so we release the semaphore again in 10 ticks time.
        ucLocalTickCount = 0;
    }

    if( xHigherPriorityTaskWoken != pdFALSE )
    {
        // We can force a context switch here.  Context switching from an
        // ISR uses port specific syntax.  Check the demo task for your port
        // to find the syntax required.
    }
 }
 
* \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR * \ingroup Semaphores */ #define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( queue_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) /** * semphr. h *
 xSemaphoreTakeFromISR(
                          sem_t xSemaphore,
                          int32_t *pxHigherPriorityTaskWoken
                      )
* * Macro to take a semaphore from an ISR. The semaphore must have * previously been created with a call to sem_binary_create() or * sem_create(). * * Mutex type semaphores (those created using a call to mutex_create()) * must not be used with this macro. * * This macro can be used from an ISR, however taking a semaphore from an ISR * is not a common operation. It is likely to only be useful when taking a * counting semaphore when an interrupt is obtaining an object from a resource * pool (when the semaphore count indicates the number of resources available). * * @param xSemaphore A handle to the semaphore being taken. This is the * handle returned when the semaphore was created. * * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task * to unblock, and the unblocked task has a priority higher than the currently * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then * a context switch should be requested before the interrupt is exited. * * @return pdTRUE if the semaphore was successfully taken, otherwise * pdFALSE */ #define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( queue_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) /** * semphr. h *
sem_t mutex_create( void )
* * Creates a new mutex type semaphore instance, and returns a handle by which * the new mutex can be referenced. * * Internally, within the FreeRTOS implementation, mutex semaphores use a block * of memory, in which the mutex structure is stored. If a mutex is created * using mutex_create() then the required memory is automatically * dynamically allocated inside the mutex_create() function. (see * http://www.freertos.org/a00111.html). If a mutex is created using * mutex_create_static() then the application writer must provided the * memory. mutex_create_static() therefore allows a mutex to be created * without using any dynamic memory allocation. * * Mutexes created using this function can be accessed using the sem_wait() * and sem_post() macros. The mutex_recursive_take() and * mutex_recursive_give() macros must not be used. * * This type of semaphore uses a priority inheritance mechanism so a task * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the * semaphore it is no longer required. * * Mutex type semaphores cannot be used from within interrupt service routines. * * See sem_binary_create() for an alternative implementation that can be * used for pure synchronisation (where one task or interrupt always 'gives' the * semaphore and another always 'takes' the semaphore) and from within interrupt * service routines. * * @return If the mutex was successfully created then a handle to the created * semaphore is returned. If there was not enough heap to allocate the mutex * data structures then NULL is returned. * * Example usage:
 sem_t xSemaphore;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to mutex_create().
    // This is a macro so pass the variable in directly.
    xSemaphore = mutex_create();

    if( xSemaphore != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup mutex_create mutex_create * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) mutex_t mutex_create(); #endif /** * semphr. h *
sem_t mutex_create_static( static_sem_s_t *pxMutexBuffer )
* * Creates a new mutex type semaphore instance, and returns a handle by which * the new mutex can be referenced. * * Internally, within the FreeRTOS implementation, mutex semaphores use a block * of memory, in which the mutex structure is stored. If a mutex is created * using mutex_create() then the required memory is automatically * dynamically allocated inside the mutex_create() function. (see * http://www.freertos.org/a00111.html). If a mutex is created using * mutex_create_static() then the application writer must provided the * memory. mutex_create_static() therefore allows a mutex to be created * without using any dynamic memory allocation. * * Mutexes created using this function can be accessed using the sem_wait() * and sem_post() macros. The mutex_recursive_take() and * mutex_recursive_give() macros must not be used. * * This type of semaphore uses a priority inheritance mechanism so a task * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the * semaphore it is no longer required. * * Mutex type semaphores cannot be used from within interrupt service routines. * * See sem_binary_create() for an alternative implementation that can be * used for pure synchronisation (where one task or interrupt always 'gives' the * semaphore and another always 'takes' the semaphore) and from within interrupt * service routines. * * @param pxMutexBuffer Must point to a variable of type static_sem_s_t, * which will be used to hold the mutex's data structure, removing the need for * the memory to be allocated dynamically. * * @return If the mutex was successfully created then a handle to the created * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. * * Example usage:
 sem_t xSemaphore;
 static_sem_s_t xMutexBuffer;

 void vATask( void * pvParameters )
 {
    // A mutex cannot be used before it has been created.  xMutexBuffer is
    // into mutex_create_static() so no dynamic memory allocation is
    // attempted.
    xSemaphore = mutex_create_static( &xMutexBuffer );

    // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
    // so there is no need to check it.
 }
 
* \defgroup mutex_create_static mutex_create_static * \ingroup Semaphores */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) mutex_t mutex_create_static(static_sem_s_t* pxMutexBuffer); #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * semphr. h *
sem_t mutex_recursive_create( void )
* * Creates a new recursive mutex type semaphore instance, and returns a handle * by which the new recursive mutex can be referenced. * * Internally, within the FreeRTOS implementation, recursive mutexs use a block * of memory, in which the mutex structure is stored. If a recursive mutex is * created using mutex_recursive_create() then the required memory is * automatically dynamically allocated inside the * mutex_recursive_create() function. (see * http://www.freertos.org/a00111.html). If a recursive mutex is created using * xSemaphoreCreateRecursiveMutexStatic() then the application writer must * provide the memory that will get used by the mutex. * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to * be created without using any dynamic memory allocation. * * Mutexes created using this macro can be accessed using the * mutex_recursive_take() and mutex_recursive_give() macros. The * sem_wait() and sem_post() macros must not be used. * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * This type of semaphore uses a priority inheritance mechanism so a task * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the * semaphore it is no longer required. * * Mutex type semaphores cannot be used from within interrupt service routines. * * See sem_binary_create() for an alternative implementation that can be * used for pure synchronisation (where one task or interrupt always 'gives' the * semaphore and another always 'takes' the semaphore) and from within interrupt * service routines. * * @return xSemaphore Handle to the created mutex semaphore. Should be of type * sem_t. * * Example usage:
 sem_t xSemaphore;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to mutex_create().
    // This is a macro so pass the variable in directly.
    xSemaphore = mutex_recursive_create();

    if( xSemaphore != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup mutex_recursive_create mutex_recursive_create * \ingroup Semaphores */ #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) mutex_t mutex_recursive_create(); #endif /** * semphr. h *
sem_t xSemaphoreCreateRecursiveMutexStatic( static_sem_s_t *pxMutexBuffer )
* * Creates a new recursive mutex type semaphore instance, and returns a handle * by which the new recursive mutex can be referenced. * * Internally, within the FreeRTOS implementation, recursive mutexs use a block * of memory, in which the mutex structure is stored. If a recursive mutex is * created using mutex_recursive_create() then the required memory is * automatically dynamically allocated inside the * mutex_recursive_create() function. (see * http://www.freertos.org/a00111.html). If a recursive mutex is created using * xSemaphoreCreateRecursiveMutexStatic() then the application writer must * provide the memory that will get used by the mutex. * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to * be created without using any dynamic memory allocation. * * Mutexes created using this macro can be accessed using the * mutex_recursive_take() and mutex_recursive_give() macros. The * sem_wait() and sem_post() macros must not be used. * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * This type of semaphore uses a priority inheritance mechanism so a task * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the * semaphore it is no longer required. * * Mutex type semaphores cannot be used from within interrupt service routines. * * See sem_binary_create() for an alternative implementation that can be * used for pure synchronisation (where one task or interrupt always 'gives' the * semaphore and another always 'takes' the semaphore) and from within interrupt * service routines. * * @param pxMutexBuffer Must point to a variable of type static_sem_s_t, * which will then be used to hold the recursive mutex's data structure, * removing the need for the memory to be allocated dynamically. * * @return If the recursive mutex was successfully created then a handle to the * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is * returned. * * Example usage:
 sem_t xSemaphore;
 static_sem_s_t xMutexBuffer;

 void vATask( void * pvParameters )
 {
    // A recursive semaphore cannot be used before it is created.  Here a
    // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic().
    // The address of xMutexBuffer is passed into the function, and will hold
    // the mutexes data structures - so no dynamic memory allocation will be
    // attempted.
    xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer );

    // As no dynamic memory allocation was performed, xSemaphore cannot be NULL,
    // so there is no need to check it.
 }
 
* \defgroup xSemaphoreCreateRecursiveMutexStatic xSemaphoreCreateRecursiveMutexStatic * \ingroup Semaphores */ #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore ) #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * semphr. h *
sem_t sem_create( uint32_t uxMaxCount, uint32_t uxInitialCount )
* * Creates a new counting semaphore instance, and returns a handle by which the * new counting semaphore can be referenced. * * In many usage scenarios it is faster and more memory efficient to use a * direct to task notification in place of a counting semaphore! * http://www.freertos.org/RTOS-task-notifications.html * * Internally, within the FreeRTOS implementation, counting semaphores use a * block of memory, in which the counting semaphore structure is stored. If a * counting semaphore is created using sem_create() then the * required memory is automatically dynamically allocated inside the * sem_create() function. (see * http://www.freertos.org/a00111.html). If a counting semaphore is created * using sem_create_static() then the application writer can * instead optionally provide the memory that will get used by the counting * semaphore. sem_create_static() therefore allows a counting * semaphore to be created without using any dynamic memory allocation. * * Counting semaphores are typically used for two things: * * 1) Counting events. * * In this usage scenario an event handler will 'give' a semaphore each time * an event occurs (incrementing the semaphore count value), and a handler * task will 'take' a semaphore each time it processes an event * (decrementing the semaphore count value). The count value is therefore * the difference between the number of events that have occurred and the * number that have been processed. In this case it is desirable for the * initial count value to be zero. * * 2) Resource management. * * In this usage scenario the count value indicates the number of resources * available. To obtain control of a resource a task must first obtain a * semaphore - decrementing the semaphore count value. When the count value * reaches zero there are no free resources. When a task finishes with the * resource it 'gives' the semaphore back - incrementing the semaphore count * value. In this case it is desirable for the initial count value to be * equal to the maximum count value, indicating that all resources are free. * * @param uxMaxCount The maximum count value that can be reached. When the * semaphore reaches this value it can no longer be 'given'. * * @param uxInitialCount The count value assigned to the semaphore when it is * created. * * @return Handle to the created semaphore. Null if the semaphore could not be * created. * * Example usage:
 sem_t xSemaphore;

 void vATask( void * pvParameters )
 {
 sem_t xSemaphore = NULL;

    // Semaphore cannot be used before a call to sem_create().
    // The max value to which the semaphore can count should be 10, and the
    // initial value assigned to the count should be 0.
    xSemaphore = sem_create( 10, 0 );

    if( xSemaphore != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup sem_create sem_create * \ingroup Semaphores */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) sem_t sem_create(uint32_t uxMaxCount, uint32_t uxInitialCount); #endif /** * semphr. h *
sem_t sem_create_static( uint32_t uxMaxCount, uint32_t uxInitialCount, static_sem_s_t *pxSemaphoreBuffer )
* * Creates a new counting semaphore instance, and returns a handle by which the * new counting semaphore can be referenced. * * In many usage scenarios it is faster and more memory efficient to use a * direct to task notification in place of a counting semaphore! * http://www.freertos.org/RTOS-task-notifications.html * * Internally, within the FreeRTOS implementation, counting semaphores use a * block of memory, in which the counting semaphore structure is stored. If a * counting semaphore is created using sem_create() then the * required memory is automatically dynamically allocated inside the * sem_create() function. (see * http://www.freertos.org/a00111.html). If a counting semaphore is created * using sem_create_static() then the application writer must * provide the memory. sem_create_static() therefore allows a * counting semaphore to be created without using any dynamic memory allocation. * * Counting semaphores are typically used for two things: * * 1) Counting events. * * In this usage scenario an event handler will 'give' a semaphore each time * an event occurs (incrementing the semaphore count value), and a handler * task will 'take' a semaphore each time it processes an event * (decrementing the semaphore count value). The count value is therefore * the difference between the number of events that have occurred and the * number that have been processed. In this case it is desirable for the * initial count value to be zero. * * 2) Resource management. * * In this usage scenario the count value indicates the number of resources * available. To obtain control of a resource a task must first obtain a * semaphore - decrementing the semaphore count value. When the count value * reaches zero there are no free resources. When a task finishes with the * resource it 'gives' the semaphore back - incrementing the semaphore count * value. In this case it is desirable for the initial count value to be * equal to the maximum count value, indicating that all resources are free. * * @param uxMaxCount The maximum count value that can be reached. When the * semaphore reaches this value it can no longer be 'given'. * * @param uxInitialCount The count value assigned to the semaphore when it is * created. * * @param pxSemaphoreBuffer Must point to a variable of type static_sem_s_t, * which will then be used to hold the semaphore's data structure, removing the * need for the memory to be allocated dynamically. * * @return If the counting semaphore was successfully created then a handle to * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL * then NULL is returned. * * Example usage:
 sem_t xSemaphore;
 static_sem_s_t xSemaphoreBuffer;

 void vATask( void * pvParameters )
 {
 sem_t xSemaphore = NULL;

    // Counting semaphore cannot be used before they have been created.  Create
    // a counting semaphore using sem_create_static().  The max
    // value to which the semaphore can count is 10, and the initial value
    // assigned to the count will be 0.  The address of xSemaphoreBuffer is
    // passed in and will be used to hold the semaphore structure, so no dynamic
    // memory allocation will be used.
    xSemaphore = sem_create( 10, 0, &xSemaphoreBuffer );

    // No memory allocation was attempted so xSemaphore cannot be NULL, so there
    // is no need to check its value.
 }
 
* \defgroup sem_create_static sem_create_static * \ingroup Semaphores */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) sem_t sem_create_static(uint32_t uxMaxCount, uint32_t uxInitialCount, static_sem_s_t* pxSemaphoreBuffer); #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * semphr. h *
void sem_delete( sem_t xSemaphore );
* * Delete a semaphore. This function must be used with care. For example, * do not delete a mutex type semaphore if the mutex is held by a task. * * @param xSemaphore A handle to the semaphore to be deleted. * * \defgroup sem_delete sem_delete * \ingroup Semaphores */ void sem_delete(sem_t xSemaphore); /** * semphr.h *
task_t mutex_get_owner( sem_t xMutex );
* * If xMutex is indeed a mutex type semaphore, return the current mutex holder. * If xMutex is not a mutex type semaphore, or the mutex is available (not held * by a task), return NULL. * * Note: This is a good way of determining if the calling task is the mutex * holder, but not a good way of determining the identity of the mutex holder as * the holder may change between the function exiting and the returned value * being tested. */ task_t mutex_get_owner(sem_t xMutex); /** * semphr.h *
task_t xSemaphoreGetMutexHolderFromISR( sem_t xMutex );
* * If xMutex is indeed a mutex type semaphore, return the current mutex holder. * If xMutex is not a mutex type semaphore, or the mutex is available (not held * by a task), return NULL. * */ #define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) /** * semphr.h *
uint32_t sem_get_count( sem_t xSemaphore );
* * If the semaphore is a counting semaphore then sem_get_count() returns * its current count value. If the semaphore is a binary semaphore then * sem_get_count() returns 1 if the semaphore is available, and 0 if the * semaphore is not available. * */ uint32_t sem_get_count(sem_t xSemaphore); #endif /* SEMAPHORE_H */ ================================================ FILE: include/rtos/stack_macros.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef STACK_MACROS_H #define STACK_MACROS_H /* * Call the stack overflow hook function if the stack of the task being swapped * out is currently overflowed, or looks like it might have overflowed in the * past. * * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check * the current stack state only - comparing the current top of stack value to * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 * will also cause the last few stack bytes to be checked to ensure the value * to which the bytes were set when the task was created have not been * overwritten. Note this second test does not guarantee that an overflowed * stack will always be recognised. */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) /* Only the current stack state is to be checked. */ #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ /* Is the currently saved stack pointer within the stack limit? */ \ if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) /* Only the current stack state is to be checked. */ #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ \ /* Is the currently saved stack pointer within the stack limit? */ \ if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ \ if( ( pulStack[ 0 ] != ulCheckValue ) || \ ( pulStack[ 1 ] != ulCheckValue ) || \ ( pulStack[ 2 ] != ulCheckValue ) || \ ( pulStack[ 3 ] != ulCheckValue ) ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) #define taskCHECK_FOR_STACK_OVERFLOW() \ { \ int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ \ \ pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ \ /* Has the extremity of the task stack ever been written over? */ \ if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ { \ vApplicationStackOverflowHook( ( task_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ } \ } #endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ /*-----------------------------------------------------------*/ /* Remove stack overflow macro if not being used. */ #ifndef taskCHECK_FOR_STACK_OVERFLOW #define taskCHECK_FOR_STACK_OVERFLOW() #endif #endif /* STACK_MACROS_H */ ================================================ FILE: include/rtos/stream_buffer.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* * Stream buffers are used to send a continuous stream of data from one task or * interrupt to another. Their implementation is light weight, making them * particularly suited for interrupt to task and core to core communication * scenarios. * * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer * implementation (so also the message buffer implementation, as message buffers * are built on top of stream buffers) assumes there is only one task or * interrupt that will write to the buffer (the writer), and only one task or * interrupt that will read from the buffer (the reader). It is safe for the * writer and reader to be different tasks or interrupts, but, unlike other * FreeRTOS objects, it is not safe to have multiple different writers or * multiple different readers. If there are to be multiple different writers * then the application writer must place each call to a writing API function * (such as stream_buf_send()) inside a critical section and set the send * block time to 0. Likewise, if there are to be multiple different readers * then the application writer must place each call to a reading API function * (such as xStreamBufferRead()) inside a critical section section and set the * receive block time to 0. * */ #ifndef STREAM_BUFFER_H #define STREAM_BUFFER_H #if defined( __cplusplus ) extern "C" { #endif /** * Type by which stream buffers are referenced. For example, a call to * stream_buf_create() returns an stream_buf_t variable that can * then be used as a parameter to stream_buf_send(), stream_buf_recv(), * etc. */ typedef void * stream_buf_t; /** * message_buffer.h *
stream_buf_t stream_buf_create( size_t xBufferSizeBytes, size_t xTriggerLevelBytes );
* * Creates a new stream buffer using dynamically allocated memory. See * stream_buf_create_static() for a version that uses statically allocated * memory (memory that is allocated at compile time). * * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in * FreeRTOSConfig.h for stream_buf_create() to be available. * * @param xBufferSizeBytes The total number of bytes the stream buffer will be * able to hold at any one time. * * @param xTriggerLevelBytes The number of bytes that must be in the stream * buffer before a task that is blocked on the stream buffer to wait for data is * moved out of the blocked state. For example, if a task is blocked on a read * of an empty stream buffer that has a trigger level of 1 then the task will be * unblocked when a single byte is written to the buffer or the task's block * time expires. As another example, if a task is blocked on a read of an empty * stream buffer that has a trigger level of 10 then the task will not be * unblocked until the stream buffer contains at least 10 bytes or the task's * block time expires. If a reading task's block time expires before the * trigger level is reached then the task will still receive however many bytes * are actually available. Setting a trigger level of 0 will result in a * trigger level of 1 being used. It is not valid to specify a trigger level * that is greater than the buffer size. * * @return If NULL is returned, then the stream buffer cannot be created * because there is insufficient heap memory available for FreeRTOS to allocate * the stream buffer data structures and storage area. A non-NULL value being * returned indicates that the stream buffer has been created successfully - * the returned value should be stored as the handle to the created stream * buffer. * * Example use:

void vAFunction( void )
{
stream_buf_t xStreamBuffer;
const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10;

    // Create a stream buffer that can hold 100 bytes.  The memory used to hold
    // both the stream buffer structure and the data in the stream buffer is
    // allocated dynamically.
    xStreamBuffer = stream_buf_create( xStreamBufferSizeBytes, xTriggerLevel );

    if( xStreamBuffer == NULL )
    {
        // There was not enough heap memory space available to create the
        // stream buffer.
    }
    else
    {
        // The stream buffer was created successfully and can now be used.
    }
}
* \defgroup stream_buf_create stream_buf_create * \ingroup StreamBufferManagement */ #define stream_buf_create( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE ) /** * stream_buffer.h *
stream_buf_t stream_buf_create_static( size_t xBufferSizeBytes,
                                                size_t xTriggerLevelBytes,
                                                uint8_t *pucStreamBufferStorageArea,
                                                static_stream_buf_s_t *pxStaticStreamBuffer );
* Creates a new stream buffer using statically allocated memory. See * stream_buf_create() for a version that uses dynamically allocated memory. * * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for * stream_buf_create_static() to be available. * * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the * pucStreamBufferStorageArea parameter. * * @param xTriggerLevelBytes The number of bytes that must be in the stream * buffer before a task that is blocked on the stream buffer to wait for data is * moved out of the blocked state. For example, if a task is blocked on a read * of an empty stream buffer that has a trigger level of 1 then the task will be * unblocked when a single byte is written to the buffer or the task's block * time expires. As another example, if a task is blocked on a read of an empty * stream buffer that has a trigger level of 10 then the task will not be * unblocked until the stream buffer contains at least 10 bytes or the task's * block time expires. If a reading task's block time expires before the * trigger level is reached then the task will still receive however many bytes * are actually available. Setting a trigger level of 0 will result in a * trigger level of 1 being used. It is not valid to specify a trigger level * that is greater than the buffer size. * * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at * least xBufferSizeBytes + 1 big. This is the array to which streams are * copied when they are written to the stream buffer. * * @param pxStaticStreamBuffer Must point to a variable of type * static_stream_buf_s_t, which will be used to hold the stream buffer's data * structure. * * @return If the stream buffer is created successfully then a handle to the * created stream buffer is returned. If either pucStreamBufferStorageArea or * pxStaticstreamBuffer are NULL then NULL is returned. * * Example use:

// Used to dimension the array used to hold the streams.  The available space
// will actually be one less than this, so 999.
#define STORAGE_SIZE_BYTES 1000

// Defines the memory that will actually hold the streams within the stream
// buffer.
static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];

// The variable used to hold the stream buffer structure.
static_stream_buf_s_t xStreamBufferStruct;

void MyFunction( void )
{
stream_buf_t xStreamBuffer;
const size_t xTriggerLevel = 1;

    xStreamBuffer = stream_buf_create_static( sizeof( ucBufferStorage ),
                                               xTriggerLevel,
                                               ucBufferStorage,
                                               &xStreamBufferStruct );

    // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer
    // parameters were NULL, xStreamBuffer will not be NULL, and can be used to
    // reference the created stream buffer in other stream buffer API calls.

    // Other code that uses the stream buffer can go here.
}

* \defgroup stream_buf_create_static stream_buf_create_static * \ingroup StreamBufferManagement */ #define stream_buf_create_static( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer ) /** * stream_buffer.h *
size_t stream_buf_send( stream_buf_t xStreamBuffer,
                          const void *pvTxData,
                          size_t xDataLengthBytes,
                          uint32_t xTicksToWait );
 *
 * Sends bytes to a stream buffer.  The bytes are copied into the stream buffer.
 *
 * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
 * implementation (so also the message buffer implementation, as message buffers
 * are built on top of stream buffers) assumes there is only one task or
 * interrupt that will write to the buffer (the writer), and only one task or
 * interrupt that will read from the buffer (the reader).  It is safe for the
 * writer and reader to be different tasks or interrupts, but, unlike other
 * FreeRTOS objects, it is not safe to have multiple different writers or
 * multiple different readers.  If there are to be multiple different writers
 * then the application writer must place each call to a writing API function
 * (such as stream_buf_send()) inside a critical section and set the send
 * block time to 0.  Likewise, if there are to be multiple different readers
 * then the application writer must place each call to a reading API function
 * (such as xStreamBufferRead()) inside a critical section and set the receive
 * block time to 0.
 *
 * Use stream_buf_send() to write to a stream buffer from a task.  Use
 * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt
 * service routine (ISR).
 *
 * @param xStreamBuffer The handle of the stream buffer to which a stream is
 * being sent.
 *
 * @param pvTxData A pointer to the buffer that holds the bytes to be copied
 * into the stream buffer.
 *
 * @param xDataLengthBytes   The maximum number of bytes to copy from pvTxData
 * into the stream buffer.
 *
 * @param xTicksToWait The maximum amount of time the task should remain in the
 * Blocked state to wait for enough space to become available in the stream
 * buffer, should the stream buffer contain too little space to hold the
 * another xDataLengthBytes bytes.  The block time is specified in tick periods,
 * so the absolute time it represents is dependent on the tick frequency.  The
 * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds
 * into a time specified in ticks.  Setting xTicksToWait to portMAX_DELAY will
 * cause the task to wait indefinitely (without timing out), provided
 * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h.  If a task times out
 * before it can write all xDataLengthBytes into the buffer it will still write
 * as many bytes as possible.  A task does not use any CPU time when it is in
 * the blocked state.
 *
 * @return The number of bytes written to the stream buffer.  If a task times
 * out before it can write all xDataLengthBytes into the buffer it will still
 * write as many bytes as possible.
 *
 * Example use:
void vAFunction( stream_buf_t xStreamBuffer )
{
size_t xBytesSent;
uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
char *pcStringToSend = "String to send";
const uint32_t x100ms = pdMS_TO_TICKS( 100 );

    // Send an array to the stream buffer, blocking for a maximum of 100ms to
    // wait for enough space to be available in the stream buffer.
    xBytesSent = stream_buf_send( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );

    if( xBytesSent != sizeof( ucArrayToSend ) )
    {
        // The call to stream_buf_send() times out before there was enough
        // space in the buffer for the data to be written, but it did
        // successfully write xBytesSent bytes.
    }

    // Send the string to the stream buffer.  Return immediately if there is not
    // enough space in the buffer.
    xBytesSent = stream_buf_send( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );

    if( xBytesSent != strlen( pcStringToSend ) )
    {
        // The entire string could not be added to the stream buffer because
        // there was not enough free space in the buffer, but xBytesSent bytes
        // were sent.  Could try again to send the remaining bytes.
    }
}
* \defgroup stream_buf_send stream_buf_send * \ingroup StreamBufferManagement */ size_t stream_buf_send( stream_buf_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, uint32_t xTicksToWait ) ; /** * stream_buffer.h *
size_t xStreamBufferSendFromISR( stream_buf_t xStreamBuffer,
                                 const void *pvTxData,
                                 size_t xDataLengthBytes,
                                 int32_t *pxHigherPriorityTaskWoken );
 *
 * Interrupt safe version of the API function that sends a stream of bytes to
 * the stream buffer.
 *
 * ***NOTE***:  Uniquely among FreeRTOS objects, the stream buffer
 * implementation (so also the message buffer implementation, as message buffers
 * are built on top of stream buffers) assumes there is only one task or
 * interrupt that will write to the buffer (the writer), and only one task or
 * interrupt that will read from the buffer (the reader).  It is safe for the
 * writer and reader to be different tasks or interrupts, but, unlike other
 * FreeRTOS objects, it is not safe to have multiple different writers or
 * multiple different readers.  If there are to be multiple different writers
 * then the application writer must place each call to a writing API function
 * (such as stream_buf_send()) inside a critical section and set the send
 * block time to 0.  Likewise, if there are to be multiple different readers
 * then the application writer must place each call to a reading API function
 * (such as xStreamBufferRead()) inside a critical section and set the receive
 * block time to 0.
 *
 * Use stream_buf_send() to write to a stream buffer from a task.  Use
 * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt
 * service routine (ISR).
 *
 * @param xStreamBuffer The handle of the stream buffer to which a stream is
 * being sent.
 *
 * @param pvTxData A pointer to the data that is to be copied into the stream
 * buffer.
 *
 * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData
 * into the stream buffer.
 *
 * @param pxHigherPriorityTaskWoken  It is possible that a stream buffer will
 * have a task blocked on it waiting for data.  Calling
 * xStreamBufferSendFromISR() can make data available, and so cause a task that
 * was waiting for data to leave the Blocked state.  If calling
 * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the
 * unblocked task has a priority higher than the currently executing task (the
 * task that was interrupted), then, internally, xStreamBufferSendFromISR()
 * will set *pxHigherPriorityTaskWoken to pdTRUE.  If
 * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a
 * context switch should be performed before the interrupt is exited.  This will
 * ensure that the interrupt returns directly to the highest priority Ready
 * state task.  *pxHigherPriorityTaskWoken should be set to pdFALSE before it
 * is passed into the function.  See the example code below for an example.
 *
 * @return The number of bytes actually written to the stream buffer, which will
 * be less than xDataLengthBytes if the stream buffer didn't have enough free
 * space for all the bytes to be written.
 *
 * Example use:
// A stream buffer that has already been created.
stream_buf_t xStreamBuffer;

void vAnInterruptServiceRoutine( void )
{
size_t xBytesSent;
char *pcStringToSend = "String to send";
int32_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.

    // Attempt to send the string to the stream buffer.
    xBytesSent = xStreamBufferSendFromISR( xStreamBuffer,
                                           ( void * ) pcStringToSend,
                                           strlen( pcStringToSend ),
                                           &xHigherPriorityTaskWoken );

    if( xBytesSent != strlen( pcStringToSend ) )
    {
        // There was not enough free space in the stream buffer for the entire
        // string to be written, ut xBytesSent bytes were written.
    }

    // If xHigherPriorityTaskWoken was set to pdTRUE inside
    // xStreamBufferSendFromISR() then a task that has a priority above the
    // priority of the currently executing task was unblocked and a context
    // switch should be performed to ensure the ISR returns to the unblocked
    // task.  In most FreeRTOS ports this is done by simply passing
    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
    // variables value, and perform the context switch if necessary.  Check the
    // documentation for the port in use for port specific instructions.
    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
* \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR * \ingroup StreamBufferManagement */ size_t xStreamBufferSendFromISR( stream_buf_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, int32_t * const pxHigherPriorityTaskWoken ) ; /** * stream_buffer.h *
size_t stream_buf_recv( stream_buf_t xStreamBuffer,
                             void *pvRxData,
                             size_t xBufferLengthBytes,
                             uint32_t xTicksToWait );
* * Receives bytes from a stream buffer. * * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer * implementation (so also the message buffer implementation, as message buffers * are built on top of stream buffers) assumes there is only one task or * interrupt that will write to the buffer (the writer), and only one task or * interrupt that will read from the buffer (the reader). It is safe for the * writer and reader to be different tasks or interrupts, but, unlike other * FreeRTOS objects, it is not safe to have multiple different writers or * multiple different readers. If there are to be multiple different writers * then the application writer must place each call to a writing API function * (such as stream_buf_send()) inside a critical section and set the send * block time to 0. Likewise, if there are to be multiple different readers * then the application writer must place each call to a reading API function * (such as xStreamBufferRead()) inside a critical section and set the receive * block time to 0. * * Use stream_buf_recv() to read from a stream buffer from a task. Use * xStreamBufferReceiveFromISR() to read from a stream buffer from an * interrupt service routine (ISR). * * @param xStreamBuffer The handle of the stream buffer from which bytes are to * be received. * * @param pvRxData A pointer to the buffer into which the received bytes will be * copied. * * @param xBufferLengthBytes The length of the buffer pointed to by the * pvRxData parameter. This sets the maximum number of bytes to receive in one * call. stream_buf_recv will return as many bytes as possible up to a * maximum set by xBufferLengthBytes. * * @param xTicksToWait The maximum amount of time the task should remain in the * Blocked state to wait for data to become available if the stream buffer is * empty. stream_buf_recv() will return immediately if xTicksToWait is * zero. The block time is specified in tick periods, so the absolute time it * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can * be used to convert a time specified in milliseconds into a time specified in * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the * Blocked state. * * @return The number of bytes actually read from the stream buffer, which will * be less than xBufferLengthBytes if the call to stream_buf_recv() timed * out before xBufferLengthBytes were available. * * Example use:
void vAFunction( StreamBuffer_t xStreamBuffer )
{
uint8_t ucRxData[ 20 ];
size_t xReceivedBytes;
const uint32_t xBlockTime = pdMS_TO_TICKS( 20 );

    // Receive up to another sizeof( ucRxData ) bytes from the stream buffer.
    // Wait in the Blocked state (so not using any CPU processing time) for a
    // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be
    // available.
    xReceivedBytes = stream_buf_recv( xStreamBuffer,
                                           ( void * ) ucRxData,
                                           sizeof( ucRxData ),
                                           xBlockTime );

    if( xReceivedBytes > 0 )
    {
        // A ucRxData contains another xReceivedBytes bytes of data, which can
        // be processed here....
    }
}
* \defgroup stream_buf_recv stream_buf_recv * \ingroup StreamBufferManagement */ size_t stream_buf_recv( stream_buf_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, uint32_t xTicksToWait ) ; /** * stream_buffer.h *
size_t xStreamBufferReceiveFromISR( stream_buf_t xStreamBuffer,
                                    void *pvRxData,
                                    size_t xBufferLengthBytes,
                                    int32_t *pxHigherPriorityTaskWoken );
* * An interrupt safe version of the API function that receives bytes from a * stream buffer. * * Use stream_buf_recv() to read bytes from a stream buffer from a task. * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an * interrupt service routine (ISR). * * @param xStreamBuffer The handle of the stream buffer from which a stream * is being received. * * @param pvRxData A pointer to the buffer into which the received bytes are * copied. * * @param xBufferLengthBytes The length of the buffer pointed to by the * pvRxData parameter. This sets the maximum number of bytes to receive in one * call. stream_buf_recv will return as many bytes as possible up to a * maximum set by xBufferLengthBytes. * * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will * have a task blocked on it waiting for space to become available. Calling * xStreamBufferReceiveFromISR() can make space available, and so cause a task * that is waiting for space to leave the Blocked state. If calling * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and * the unblocked task has a priority higher than the currently executing task * (the task that was interrupted), then, internally, * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a * context switch should be performed before the interrupt is exited. That will * ensure the interrupt returns directly to the highest priority Ready state * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is * passed into the function. See the code example below for an example. * * @return The number of bytes read from the stream buffer, if any. * * Example use:
// A stream buffer that has already been created.
StreamBuffer_t xStreamBuffer;

void vAnInterruptServiceRoutine( void )
{
uint8_t ucRxData[ 20 ];
size_t xReceivedBytes;
int32_t xHigherPriorityTaskWoken = pdFALSE;  // Initialised to pdFALSE.

    // Receive the next stream from the stream buffer.
    xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer,
                                                  ( void * ) ucRxData,
                                                  sizeof( ucRxData ),
                                                  &xHigherPriorityTaskWoken );

    if( xReceivedBytes > 0 )
    {
        // ucRxData contains xReceivedBytes read from the stream buffer.
        // Process the stream here....
    }

    // If xHigherPriorityTaskWoken was set to pdTRUE inside
    // xStreamBufferReceiveFromISR() then a task that has a priority above the
    // priority of the currently executing task was unblocked and a context
    // switch should be performed to ensure the ISR returns to the unblocked
    // task.  In most FreeRTOS ports this is done by simply passing
    // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
    // variables value, and perform the context switch if necessary.  Check the
    // documentation for the port in use for port specific instructions.
    taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
* \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR * \ingroup StreamBufferManagement */ size_t xStreamBufferReceiveFromISR( stream_buf_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, int32_t * const pxHigherPriorityTaskWoken ) ; /** * stream_buffer.h *
void vStreamBufferDelete( stream_buf_t xStreamBuffer );
* * Deletes a stream buffer that was previously created using a call to * stream_buf_create() or stream_buf_create_static(). If the stream * buffer was created using dynamic memory (that is, by stream_buf_create()), * then the allocated memory is freed. * * A stream buffer handle must not be used after the stream buffer has been * deleted. * * @param xStreamBuffer The handle of the stream buffer to be deleted. * * \defgroup vStreamBufferDelete vStreamBufferDelete * \ingroup StreamBufferManagement */ void vStreamBufferDelete( stream_buf_t xStreamBuffer ) ; /** * stream_buffer.h *
int32_t stream_buf_is_full( stream_buf_t xStreamBuffer );
* * Queries a stream buffer to see if it is full. A stream buffer is full if it * does not have any free space, and therefore cannot accept any more data. * * @param xStreamBuffer The handle of the stream buffer being queried. * * @return If the stream buffer is full then pdTRUE is returned. Otherwise * pdFALSE is returned. * * \defgroup stream_buf_is_full stream_buf_is_full * \ingroup StreamBufferManagement */ int32_t stream_buf_is_full( stream_buf_t xStreamBuffer ) ; /** * stream_buffer.h *
int32_t stream_buf_is_empty( stream_buf_t xStreamBuffer );
* * Queries a stream buffer to see if it is empty. A stream buffer is empty if * it does not contain any data. * * @param xStreamBuffer The handle of the stream buffer being queried. * * @return If the stream buffer is empty then pdTRUE is returned. Otherwise * pdFALSE is returned. * * \defgroup stream_buf_is_empty stream_buf_is_empty * \ingroup StreamBufferManagement */ int32_t stream_buf_is_empty( stream_buf_t xStreamBuffer ) ; /** * stream_buffer.h *
int32_t stream_buf_reset( stream_buf_t xStreamBuffer );
* * Resets a stream buffer to its initial, empty, state. Any data that was in * the stream buffer is discarded. A stream buffer can only be reset if there * are no tasks blocked waiting to either send to or receive from the stream * buffer. * * @param xStreamBuffer The handle of the stream buffer being reset. * * @return If the stream buffer is reset then pdPASS is returned. If there was * a task blocked waiting to send to or read from the stream buffer then the * stream buffer is not reset and pdFAIL is returned. * * \defgroup stream_buf_reset stream_buf_reset * \ingroup StreamBufferManagement */ int32_t stream_buf_reset( stream_buf_t xStreamBuffer ) ; /** * stream_buffer.h *
size_t stream_buf_get_unused( stream_buf_t xStreamBuffer );
* * Queries a stream buffer to see how much free space it contains, which is * equal to the amount of data that can be sent to the stream buffer before it * is full. * * @param xStreamBuffer The handle of the stream buffer being queried. * * @return The number of bytes that can be written to the stream buffer before * the stream buffer would be full. * * \defgroup stream_buf_get_unused stream_buf_get_unused * \ingroup StreamBufferManagement */ size_t stream_buf_get_unused( stream_buf_t xStreamBuffer ) ; /** * stream_buffer.h *
size_t stream_buf_get_used( stream_buf_t xStreamBuffer );
* * Queries a stream buffer to see how much data it contains, which is equal to * the number of bytes that can be read from the stream buffer before the stream * buffer would be empty. * * @param xStreamBuffer The handle of the stream buffer being queried. * * @return The number of bytes that can be read from the stream buffer before * the stream buffer would be empty. * * \defgroup stream_buf_get_used stream_buf_get_used * \ingroup StreamBufferManagement */ size_t stream_buf_get_used( stream_buf_t xStreamBuffer ) ; /** * stream_buffer.h *
int32_t stream_buf_set_trigger( stream_buf_t xStreamBuffer, size_t xTriggerLevel );
* * A stream buffer's trigger level is the number of bytes that must be in the * stream buffer before a task that is blocked on the stream buffer to * wait for data is moved out of the blocked state. For example, if a task is * blocked on a read of an empty stream buffer that has a trigger level of 1 * then the task will be unblocked when a single byte is written to the buffer * or the task's block time expires. As another example, if a task is blocked * on a read of an empty stream buffer that has a trigger level of 10 then the * task will not be unblocked until the stream buffer contains at least 10 bytes * or the task's block time expires. If a reading task's block time expires * before the trigger level is reached then the task will still receive however * many bytes are actually available. Setting a trigger level of 0 will result * in a trigger level of 1 being used. It is not valid to specify a trigger * level that is greater than the buffer size. * * A trigger level is set when the stream buffer is created, and can be modified * using stream_buf_set_trigger(). * * @param xStreamBuffer The handle of the stream buffer being updated. * * @param xTriggerLevel The new trigger level for the stream buffer. * * @return If xTriggerLevel was less than or equal to the stream buffer's length * then the trigger level will be updated and pdTRUE is returned. Otherwise * pdFALSE is returned. * * \defgroup stream_buf_set_trigger stream_buf_set_trigger * \ingroup StreamBufferManagement */ int32_t stream_buf_set_trigger( stream_buf_t xStreamBuffer, size_t xTriggerLevel ) ; /** * stream_buffer.h *
int32_t xStreamBufferSendCompletedFromISR( stream_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken );
* * For advanced users only. * * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when * data is sent to a message buffer or stream buffer. If there was a task that * was blocked on the message or stream buffer waiting for data to arrive then * the sbSEND_COMPLETED() macro sends a notification to the task to remove it * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same * thing. It is provided to enable application writers to implement their own * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. * * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for * additional information. * * @param xStreamBuffer The handle of the stream buffer to which data was * written. * * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be * initialised to pdFALSE before it is passed into * xStreamBufferSendCompletedFromISR(). If calling * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, * and the task has a priority above the priority of the currently running task, * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a * context switch should be performed before exiting the ISR. * * @return If a task was removed from the Blocked state then pdTRUE is returned. * Otherwise pdFALSE is returned. * * \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR * \ingroup StreamBufferManagement */ int32_t xStreamBufferSendCompletedFromISR( stream_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken ) ; /** * stream_buffer.h *
int32_t xStreamBufferReceiveCompletedFromISR( stream_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken );
* * For advanced users only. * * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when * data is read out of a message buffer or stream buffer. If there was a task * that was blocked on the message or stream buffer waiting for data to arrive * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() * does the same thing. It is provided to enable application writers to * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT * ANY OTHER TIME. * * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for * additional information. * * @param xStreamBuffer The handle of the stream buffer from which data was * read. * * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be * initialised to pdFALSE before it is passed into * xStreamBufferReceiveCompletedFromISR(). If calling * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, * and the task has a priority above the priority of the currently running task, * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a * context switch should be performed before exiting the ISR. * * @return If a task was removed from the Blocked state then pdTRUE is returned. * Otherwise pdFALSE is returned. * * \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR * \ingroup StreamBufferManagement */ int32_t xStreamBufferReceiveCompletedFromISR( stream_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken ) ; /* Functions below here are not part of the public API. */ stream_buf_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, int32_t xIsMessageBuffer ) ; stream_buf_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, int32_t xIsMessageBuffer, uint8_t * const pucStreamBufferStorageArea, static_stream_buf_s_t * const pxStaticStreamBuffer ) ; #if( configUSE_TRACE_FACILITY == 1 ) void vStreamBufferSetStreamBufferNumber( stream_buf_t xStreamBuffer, uint32_t uxStreamBufferNumber ) ; uint32_t uxStreamBufferGetStreamBufferNumber( stream_buf_t xStreamBuffer ) ; uint8_t ucStreamBufferGetStreamBufferType( stream_buf_t xStreamBuffer ) ; #endif #if defined( __cplusplus ) } #endif #endif /* !defined( STREAM_BUFFER_H ) */ ================================================ FILE: include/rtos/task.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include "FreeRTOS.h" #ifndef INC_TASK_H #define INC_TASK_H #ifndef INC_FREERTOS_H #error "include FreeRTOS.h must appear in source files before include task.h" #endif #include "list.h" #ifdef __cplusplus extern "C" { #endif /*----------------------------------------------------------- * MACROS AND DEFINITIONS *----------------------------------------------------------*/ #define tskKERNEL_VERSION_NUMBER "V10.0.1" #define tskKERNEL_VERSION_MAJOR 10 #define tskKERNEL_VERSION_MINOR 0 #define tskKERNEL_VERSION_BUILD 1 /** * task. h * * Type by which tasks are referenced. For example, a call to task_create * returns (via a pointer parameter) an task_t variable that can then * be used as a parameter to task_delete to delete the task. * * \defgroup task_t task_t * \ingroup Tasks */ typedef void * task_t; /* * Defines the prototype to which the application task hook function must * conform. */ typedef int32_t (*TaskHookFunction_t)( void * ); /* Task states returned by task_get_state. */ typedef enum { E_TASK_STATE_RUNNING = 0, /* A task is querying the state of itself, so must be running. */ E_TASK_STATE_READY, /* The task being queried is in a read or pending ready list. */ E_TASK_STATE_BLOCKED, /* The task being queried is in the Blocked state. */ E_TASK_STATE_SUSPENDED, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ E_TASK_STATE_DELETED, /* The task being queried has been deleted, but its TCB has not yet been freed. */ E_TASK_STATE_INVALID /* Used as an 'invalid state' value. */ } task_state_e_t; /* Actions that can be performed when vTaskNotify() is called. */ typedef enum { E_NOTIFY_ACTION_NONE = 0, /* Notify the task without updating its notify value. */ E_NOTIFY_ACTION_BITS, /* Set bits in the task's notification value. */ E_NOTIFY_ACTION_INCR, /* Increment the task's notification value. */ E_NOTIFY_ACTION_OWRITE, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ E_NOTIFY_ACTION_NO_OWRITE /* Set the task's notification value if the previous value has been read by the task. */ } notify_action_e_t; /* * Used internally only. */ typedef struct xTIME_OUT { int32_t xOverflowCount; uint32_t xTimeOnEntering; } TimeOut_t; /* * Parameters required to create an MPU protected task. */ typedef struct xTASK_PARAMETERS { task_fn_t pvTaskCode; const char * const pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ uint16_t usStackDepth; void *pvParameters; uint32_t uxPriority; task_stack_t *puxStackBuffer; } TaskParameters_t; /* Used with the uxTaskGetSystemState() function to return the state of each task in the system. */ typedef struct xTASK_STATUS { task_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ const char *pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ uint32_t xTaskNumber; /* A number unique to the task. */ task_state_e_t eCurrentState; /* The state in which the task existed when the structure was populated. */ uint32_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ uint32_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ task_stack_t *pxStackBase; /* Points to the lowest address of the task's stack area. */ uint16_t usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ } TaskStatus_t; /* Possible return values for eTaskConfirmSleepModeStatus(). */ typedef enum { eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */ eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ } eSleepModeStatus; /** * Defines the priority used by the idle task. This must not be modified. * * \ingroup TaskUtils */ #define tskIDLE_PRIORITY ( ( uint32_t ) 0U ) /** * task. h * * Macro for forcing a context switch. * * \defgroup taskYIELD taskYIELD * \ingroup SchedulerControl */ #define taskYIELD() portYIELD() /** * task. h * * Macro to mark the start of a critical code region. Preemptive context * switches cannot occur when in a critical region. * * NOTE: This may alter the stack (depending on the portable implementation) * so must be used with care! * * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL * \ingroup SchedulerControl */ #define taskENTER_CRITICAL() portENTER_CRITICAL() #define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() /** * task. h * * Macro to mark the end of a critical code region. Preemptive context * switches cannot occur when in a critical region. * * NOTE: This may alter the stack (depending on the portable implementation) * so must be used with care! * * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL * \ingroup SchedulerControl */ #define taskEXIT_CRITICAL() portEXIT_CRITICAL() #define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) /** * task. h * * Macro to disable all maskable interrupts. * * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS * \ingroup SchedulerControl */ #define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() /** * task. h * * Macro to enable microcontroller interrupts. * * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS * \ingroup SchedulerControl */ #define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() /* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is 0 to generate more optimal code when configASSERT() is defined as the constant is used in assert() statements. */ #define taskSCHEDULER_SUSPENDED ( ( int32_t ) 0 ) #define taskSCHEDULER_NOT_STARTED ( ( int32_t ) 1 ) #define taskSCHEDULER_RUNNING ( ( int32_t ) 2 ) /*----------------------------------------------------------- * TASK CREATION API *----------------------------------------------------------*/ /** * task. h *
 int32_t task_create(
							  task_fn_t pvTaskCode,
							  const char * const pcName,
							  configSTACK_DEPTH_TYPE usStackDepth,
							  void *pvParameters,
							  uint32_t uxPriority,
							  task_t *pvCreatedTask
						  );
* * Create a new task and add it to the list of tasks that are ready to run. * * Internally, within the FreeRTOS implementation, tasks use two blocks of * memory. The first block is used to hold the task's data structures. The * second block is used by the task as its stack. If a task is created using * task_create() then both blocks of memory are automatically dynamically * allocated inside the task_create() function. (see * http://www.freertos.org/a00111.html). If a task is created using * task_create_static() then the application writer must provide the required * memory. task_create_static() therefore allows a task to be created without * using any dynamic memory allocation. * * See task_create_static() for a version that does not use any dynamic memory * allocation. * * task_create() can only be used to create a task that has unrestricted * access to the entire microcontroller memory map. Systems that include MPU * support can alternatively create an MPU constrained task using * xTaskCreateRestricted(). * * @param pvTaskCode Pointer to the task entry function. Tasks * must be implemented to never return (i.e. continuous loop). * * @param pcName A descriptive name for the task. This is mainly used to * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default * is 16. * * @param usStackDepth The size of the task stack specified as the number of * variables the stack can hold - not the number of bytes. For example, if * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes * will be allocated for stack storage. * * @param pvParameters Pointer that will be used as the parameter for the task * being created. * * @param uxPriority The priority at which the task should run. Systems that * include MPU support can optionally create tasks in a privileged (system) * mode by setting bit portPRIVILEGE_BIT of the priority parameter. For * example, to create a privileged task at priority 2 the uxPriority parameter * should be set to ( 2 | portPRIVILEGE_BIT ). * * @param pvCreatedTask Used to pass back a handle by which the created task * can be referenced. * * @return pdPASS if the task was successfully created and added to a ready * list, otherwise an error code defined in the file projdefs.h * * Example usage:
 // Task to be created.
 void vTaskCode( void * pvParameters )
 {
	 for( ;; )
	 {
		 // Task code goes here.
	 }
 }

 // Function that creates a task.
 void vOtherFunction( void )
 {
 static uint8_t ucParameterToPass;
 task_t xHandle = NULL;

	 // Create the task, storing the handle.  Note that the passed parameter ucParameterToPass
	 // must exist for the lifetime of the task, so in this case is declared static.  If it was just an
	 // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time
	 // the new task attempts to access it.
	 task_create( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle );
     configASSERT( xHandle );

	 // Use the handle to delete the task.
     if( xHandle != NULL )
     {
	     task_delete( xHandle );
     }
 }
   
* \defgroup task_create task_create * \ingroup Tasks */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) task_t task_create(task_fn_t function, void* const parameters, uint32_t prio, const uint16_t stack_depth, const char* const name); #endif /** * task. h *
 task_t task_create_static( task_fn_t pvTaskCode,
								 const char * const pcName,
								 uint32_t ulStackDepth,
								 void *pvParameters,
								 uint32_t uxPriority,
								 task_stack_t *pxStackBuffer,
								 static_task_s_t *pxTaskBuffer );
* * Create a new task and add it to the list of tasks that are ready to run. * * Internally, within the FreeRTOS implementation, tasks use two blocks of * memory. The first block is used to hold the task's data structures. The * second block is used by the task as its stack. If a task is created using * task_create() then both blocks of memory are automatically dynamically * allocated inside the task_create() function. (see * http://www.freertos.org/a00111.html). If a task is created using * task_create_static() then the application writer must provide the required * memory. task_create_static() therefore allows a task to be created without * using any dynamic memory allocation. * * @param pvTaskCode Pointer to the task entry function. Tasks * must be implemented to never return (i.e. continuous loop). * * @param pcName A descriptive name for the task. This is mainly used to * facilitate debugging. The maximum length of the string is defined by * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. * * @param ulStackDepth The size of the task stack specified as the number of * variables the stack can hold - not the number of bytes. For example, if * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes * will be allocated for stack storage. * * @param pvParameters Pointer that will be used as the parameter for the task * being created. * * @param uxPriority The priority at which the task will run. * * @param pxStackBuffer Must point to a task_stack_t array that has at least * ulStackDepth indexes - the array will then be used as the task's stack, * removing the need for the stack to be allocated dynamically. * * @param pxTaskBuffer Must point to a variable of type static_task_s_t, which will * then be used to hold the task's data structures, removing the need for the * memory to be allocated dynamically. * * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will * be created and pdPASS is returned. If either pxStackBuffer or pxTaskBuffer * are NULL then the task will not be created and * errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned. * * Example usage:

    // Dimensions the buffer that the task being created will use as its stack.
    // NOTE:  This is the number of words the stack will hold, not the number of
    // bytes.  For example, if each stack item is 32-bits, and this is set to 100,
    // then 400 bytes (100 * 32-bits) will be allocated.
    #define STACK_SIZE 200

    // Structure that will hold the TCB of the task being created.
    static_task_s_t xTaskBuffer;

    // Buffer that the task being created will use as its stack.  Note this is
    // an array of task_stack_t variables.  The size of task_stack_t is dependent on
    // the RTOS port.
    task_stack_t xStack[ STACK_SIZE ];

    // Function that implements the task being created.
    void vTaskCode( void * pvParameters )
    {
        // The parameter value is expected to be 1 as 1 is passed in the
        // pvParameters value in the call to task_create_static().
        configASSERT( ( uint32_t ) pvParameters == 1UL );

        for( ;; )
        {
            // Task code goes here.
        }
    }

    // Function that creates a task.
    void vOtherFunction( void )
    {
        task_t xHandle = NULL;

        // Create the task without using any dynamic memory allocation.
        xHandle = task_create_static(
                      vTaskCode,       // Function that implements the task.
                      "NAME",          // Text name for the task.
                      STACK_SIZE,      // Stack size in words, not bytes.
                      ( void * ) 1,    // Parameter passed into the task.
                      tskIDLE_PRIORITY,// Priority at which the task is created.
                      xStack,          // Array to use as the task's stack.
                      &xTaskBuffer );  // Variable to hold the task's data structure.

        // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have
        // been created, and xHandle will be the task's handle.  Use the handle
        // to suspend the task.
        task_suspend( xHandle );
    }
   
* \defgroup task_create_static task_create_static * \ingroup Tasks */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) task_t task_create_static( task_fn_t task_code, void* const param, uint32_t priority, const size_t stack_size, const char* const name, task_stack_t * const stack_buffer, static_task_s_t * const task_buffer ) ; #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * task. h *
void task_delete( task_t xTask );
* * INCLUDE_vTaskDelete must be defined as 1 for this function to be available. * See the configuration section for more information. * * Remove a task from the RTOS real time kernel's management. The task being * deleted will be removed from all ready, blocked, suspended and event lists. * * NOTE: The idle task is responsible for freeing the kernel allocated * memory from tasks that have been deleted. It is therefore important that * the idle task is not starved of microcontroller processing time if your * application makes any calls to task_delete (). Memory allocated by the * task code is not automatically freed, and should be freed before the task * is deleted. * * See the demo application file death.c for sample code that utilises * task_delete (). * * @param xTask The handle of the task to be deleted. Passing NULL will * cause the calling task to be deleted. * * Example usage:
 void vOtherFunction( void )
 {
 task_t xHandle;

	 // Create the task, storing the handle.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );

	 // Use the handle to delete the task.
	 task_delete( xHandle );
 }
   
* \defgroup task_delete task_delete * \ingroup Tasks */ void task_delete( task_t xTaskToDelete ) ; /*----------------------------------------------------------- * TASK CONTROL API *----------------------------------------------------------*/ /** * task. h *
void task_delay( const uint32_t xTicksToDelay );
* * Delay a task for a given number of ticks. The actual time that the * task remains blocked depends on the tick rate. The constant * portTICK_PERIOD_MS can be used to calculate real time from the tick * rate - with the resolution of one tick period. * * INCLUDE_vTaskDelay must be defined as 1 for this function to be available. * See the configuration section for more information. * * * task_delay() specifies a time at which the task wishes to unblock relative to * the time at which task_delay() is called. For example, specifying a block * period of 100 ticks will cause the task to unblock 100 ticks after * task_delay() is called. task_delay() does not therefore provide a good method * of controlling the frequency of a periodic task as the path taken through the * code, as well as other task and interrupt activity, will effect the frequency * at which task_delay() gets called and therefore the time at which the task * next executes. See task_delay_until() for an alternative API function designed * to facilitate fixed frequency execution. It does this by specifying an * absolute time (rather than a relative time) at which the calling task should * unblock. * * @param xTicksToDelay The amount of time, in tick periods, that * the calling task should block. * * Example usage: void vTaskFunction( void * pvParameters ) { // Block for 500ms. const uint32_t xDelay = 500 / portTICK_PERIOD_MS; for( ;; ) { // Simply toggle the LED every 500ms, blocking between each toggle. vToggleLED(); task_delay( xDelay ); } } * \defgroup task_delay task_delay * \ingroup TaskCtrl */ void task_delay( const uint32_t xTicksToDelay ) ; /** * task. h *
void task_delay_until( uint32_t *pxPreviousWakeTime, const uint32_t xTimeIncrement );
* * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available. * See the configuration section for more information. * * Delay a task until a specified time. This function can be used by periodic * tasks to ensure a constant execution frequency. * * This function differs from task_delay () in one important aspect: task_delay () will * cause a task to block for the specified number of ticks from the time task_delay () is * called. It is therefore difficult to use task_delay () by itself to generate a fixed * execution frequency as the time between a task starting to execute and that task * calling task_delay () may not be fixed [the task may take a different path though the * code between calls, or may get interrupted or preempted a different number of times * each time it executes]. * * Whereas task_delay () specifies a wake time relative to the time at which the function * is called, task_delay_until () specifies the absolute (exact) time at which it wishes to * unblock. * * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick * rate - with the resolution of one tick period. * * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the * task was last unblocked. The variable must be initialised with the current time * prior to its first use (see the example below). Following this the variable is * automatically updated within task_delay_until (). * * @param xTimeIncrement The cycle time period. The task will be unblocked at * time *pxPreviousWakeTime + xTimeIncrement. Calling task_delay_until with the * same xTimeIncrement parameter value will cause the task to execute with * a fixed interface period. * * Example usage:
 // Perform an action every 10 ticks.
 void vTaskFunction( void * pvParameters )
 {
 uint32_t xLastWakeTime;
 const uint32_t xFrequency = 10;

	 // Initialise the xLastWakeTime variable with the current time.
	 xLastWakeTime = millis ();
	 for( ;; )
	 {
		 // Wait for the next cycle.
		 task_delay_until( &xLastWakeTime, xFrequency );

		 // Perform action here.
	 }
 }
   
* \defgroup task_delay_until task_delay_until * \ingroup TaskCtrl */ void task_delay_until( uint32_t * const pxPreviousWakeTime, const uint32_t xTimeIncrement ) ; /** * task. h *
int32_t task_abort_delay( task_t xTask );
* * INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this * function to be available. * * A task will enter the Blocked state when it is waiting for an event. The * event it is waiting for can be a temporal event (waiting for a time), such * as when task_delay() is called, or an event on an object, such as when * queue_recv() or task_notify_take() is called. If the handle of a task * that is in the Blocked state is used in a call to task_abort_delay() then the * task will leave the Blocked state, and return from whichever function call * placed the task into the Blocked state. * * @param xTask The handle of the task to remove from the Blocked state. * * @return If the task referenced by xTask was not in the Blocked state then * pdFAIL is returned. Otherwise pdPASS is returned. * * \defgroup task_abort_delay task_abort_delay * \ingroup TaskCtrl */ int32_t task_abort_delay( task_t xTask ) ; /** * task. h *
uint32_t task_get_priority( task_t xTask );
* * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. * See the configuration section for more information. * * Obtain the priority of any task. * * @param xTask Handle of the task to be queried. Passing a NULL * handle results in the priority of the calling task being returned. * * @return The priority of xTask. * * Example usage:
 void vAFunction( void )
 {
 task_t xHandle;

	 // Create a task, storing the handle.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );

	 // ...

	 // Use the handle to obtain the priority of the created task.
	 // It was created with tskIDLE_PRIORITY, but may have changed
	 // it itself.
	 if( task_get_priority( xHandle ) != tskIDLE_PRIORITY )
	 {
		 // The task has changed it's priority.
	 }

	 // ...

	 // Is our priority higher than the created task?
	 if( task_get_priority( xHandle ) < task_get_priority( NULL ) )
	 {
		 // Our priority (obtained using NULL handle) is higher.
	 }
 }
   
* \defgroup task_get_priority task_get_priority * \ingroup TaskCtrl */ uint32_t task_get_priority( task_t xTask ) ; /** * task. h *
uint32_t uxTaskPriorityGetFromISR( task_t xTask );
* * A version of task_get_priority() that can be used from an ISR. */ uint32_t uxTaskPriorityGetFromISR( task_t xTask ) ; /** * task. h *
task_state_e_t task_get_state( task_t xTask );
* * INCLUDE_eTaskGetState must be defined as 1 for this function to be available. * See the configuration section for more information. * * Obtain the state of any task. States are encoded by the task_state_e_t * enumerated type. * * @param xTask Handle of the task to be queried. * * @return The state of xTask at the time the function was called. Note the * state of the task might change between the function being called, and the * functions return value being tested by the calling task. */ task_state_e_t task_get_state( task_t xTask ) ; /** * task. h *
void vTaskGetInfo( task_t xTask, TaskStatus_t *pxTaskStatus, int32_t xGetFreeStackSpace, task_state_e_t eState );
* * configUSE_TRACE_FACILITY must be defined as 1 for this function to be * available. See the configuration section for more information. * * Populates a TaskStatus_t structure with information about a task. * * @param xTask Handle of the task being queried. If xTask is NULL then * information will be returned about the calling task. * * @param pxTaskStatus A pointer to the TaskStatus_t structure that will be * filled with information about the task referenced by the handle passed using * the xTask parameter. * * @xGetFreeStackSpace The TaskStatus_t structure contains a member to report * the stack high water mark of the task being queried. Calculating the stack * high water mark takes a relatively long time, and can make the system * temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to * allow the high water mark checking to be skipped. The high watermark value * will only be written to the TaskStatus_t structure if xGetFreeStackSpace is * not set to pdFALSE; * * @param eState The TaskStatus_t structure contains a member to report the * state of the task being queried. Obtaining the task state is not as fast as * a simple assignment - so the eState parameter is provided to allow the state * information to be omitted from the TaskStatus_t structure. To obtain state * information then set eState to E_TASK_STATE_INVALID - otherwise the value passed in * eState will be reported as the task state in the TaskStatus_t structure. * * Example usage:
 void vAFunction( void )
 {
 task_t xHandle;
 TaskStatus_t xTaskDetails;

    // Obtain the handle of a task from its name.
    xHandle = task_get_by_name( "Task_Name" );

    // Check the handle is not NULL.
    configASSERT( xHandle );

    // Use the handle to obtain further information about the task.
    vTaskGetInfo( xHandle,
                  &xTaskDetails,
                  pdTRUE, // Include the high water mark in xTaskDetails.
                  E_TASK_STATE_INVALID ); // Include the task state in xTaskDetails.
 }
   
* \defgroup vTaskGetInfo vTaskGetInfo * \ingroup TaskCtrl */ void vTaskGetInfo( task_t xTask, TaskStatus_t *pxTaskStatus, int32_t xGetFreeStackSpace, task_state_e_t eState ) ; /** * task. h *
void task_set_priority( task_t xTask, uint32_t uxNewPriority );
* * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. * See the configuration section for more information. * * Set the priority of any task. * * A context switch will occur before the function returns if the priority * being set is higher than the currently executing task. * * @param xTask Handle to the task for which the priority is being set. * Passing a NULL handle results in the priority of the calling task being set. * * @param uxNewPriority The priority to which the task will be set. * * Example usage:
 void vAFunction( void )
 {
 task_t xHandle;

	 // Create a task, storing the handle.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );

	 // ...

	 // Use the handle to raise the priority of the created task.
	 task_set_priority( xHandle, tskIDLE_PRIORITY + 1 );

	 // ...

	 // Use a NULL handle to raise our priority to the same value.
	 task_set_priority( NULL, tskIDLE_PRIORITY + 1 );
 }
   
* \defgroup task_set_priority task_set_priority * \ingroup TaskCtrl */ void task_set_priority( task_t xTask, uint32_t uxNewPriority ) ; /** * task. h *
void task_suspend( task_t xTaskToSuspend );
* * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. * See the configuration section for more information. * * Suspend any task. When suspended a task will never get any microcontroller * processing time, no matter what its priority. * * Calls to task_suspend are not accumulative - * i.e. calling task_suspend () twice on the same task still only requires one * call to task_resume () to ready the suspended task. * * @param xTaskToSuspend Handle to the task being suspended. Passing a NULL * handle will cause the calling task to be suspended. * * Example usage:
 void vAFunction( void )
 {
 task_t xHandle;

	 // Create a task, storing the handle.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );

	 // ...

	 // Use the handle to suspend the created task.
	 task_suspend( xHandle );

	 // ...

	 // The created task will not run during this period, unless
	 // another task calls task_resume( xHandle ).

	 //...


	 // Suspend ourselves.
	 task_suspend( NULL );

	 // We cannot get here unless another task calls task_resume
	 // with our handle as the parameter.
 }
   
* \defgroup task_suspend task_suspend * \ingroup TaskCtrl */ void task_suspend( task_t xTaskToSuspend ) ; /** * task. h *
void task_resume( task_t xTaskToResume );
* * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. * See the configuration section for more information. * * Resumes a suspended task. * * A task that has been suspended by one or more calls to task_suspend () * will be made available for running again by a single call to * task_resume (). * * @param xTaskToResume Handle to the task being readied. * * Example usage:
 void vAFunction( void )
 {
 task_t xHandle;

	 // Create a task, storing the handle.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );

	 // ...

	 // Use the handle to suspend the created task.
	 task_suspend( xHandle );

	 // ...

	 // The created task will not run during this period, unless
	 // another task calls task_resume( xHandle ).

	 //...


	 // Resume the suspended task ourselves.
	 task_resume( xHandle );

	 // The created task will once again get microcontroller processing
	 // time in accordance with its priority within the system.
 }
   
* \defgroup task_resume task_resume * \ingroup TaskCtrl */ void task_resume( task_t xTaskToResume ) ; /** * task. h *
void xTaskResumeFromISR( task_t xTaskToResume );
* * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be * available. See the configuration section for more information. * * An implementation of task_resume() that can be called from within an ISR. * * A task that has been suspended by one or more calls to task_suspend () * will be made available for running again by a single call to * xTaskResumeFromISR (). * * xTaskResumeFromISR() should not be used to synchronise a task with an * interrupt if there is a chance that the interrupt could arrive prior to the * task being suspended - as this can lead to interrupts being missed. Use of a * semaphore as a synchronisation mechanism would avoid this eventuality. * * @param xTaskToResume Handle to the task being readied. * * @return pdTRUE if resuming the task should result in a context switch, * otherwise pdFALSE. This is used by the ISR to determine if a context switch * may be required following the ISR. * * \defgroup vTaskResumeFromISR vTaskResumeFromISR * \ingroup TaskCtrl */ int32_t xTaskResumeFromISR( task_t xTaskToResume ) ; /*----------------------------------------------------------- * SCHEDULER CONTROL *----------------------------------------------------------*/ /** * task. h *
void rtos_sched_start( void );
* * Starts the real time kernel tick processing. After calling the kernel * has control over which tasks are executed and when. * * See the demo application file main.c for an example of creating * tasks and starting the kernel. * * Example usage:
 void vAFunction( void )
 {
	 // Create at least one task before starting the kernel.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );

	 // Start the real time kernel with preemption.
	 rtos_sched_start ();

	 // Will not get here unless a task calls rtos_sched_stop ()
 }
   
* * \defgroup rtos_sched_start rtos_sched_start * \ingroup SchedulerControl */ void rtos_sched_start( void ) ; /** * task. h *
void rtos_sched_stop( void );
* * NOTE: At the time of writing only the x86 real mode port, which runs on a PC * in place of DOS, implements this function. * * Stops the real time kernel tick. All created tasks will be automatically * deleted and multitasking (either preemptive or cooperative) will * stop. Execution then resumes from the point where rtos_sched_start () * was called, as if rtos_sched_start () had just returned. * * See the demo application file main. c in the demo/PC directory for an * example that uses rtos_sched_stop (). * * rtos_sched_stop () requires an exit function to be defined within the * portable layer (see vPortEndScheduler () in port. c for the PC port). This * performs hardware specific operations such as stopping the kernel tick. * * rtos_sched_stop () will cause all of the resources allocated by the * kernel to be freed - but will not free resources allocated by application * tasks. * * Example usage:
 void vTaskCode( void * pvParameters )
 {
	 for( ;; )
	 {
		 // Task code goes here.

		 // At some point we want to end the real time kernel processing
		 // so call ...
		 rtos_sched_stop ();
	 }
 }

 void vAFunction( void )
 {
	 // Create at least one task before starting the kernel.
	 task_create( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );

	 // Start the real time kernel with preemption.
	 rtos_sched_start ();

	 // Will only get here when the vTaskCode () task has called
	 // rtos_sched_stop ().  When we get here we are back to single task
	 // execution.
 }
   
* * \defgroup rtos_sched_stop rtos_sched_stop * \ingroup SchedulerControl */ void rtos_sched_stop( void ) ; /** * task. h *
void rtos_suspend_all( void );
* * Suspends the scheduler without disabling interrupts. Context switches will * not occur while the scheduler is suspended. * * After calling rtos_suspend_all () the calling task will continue to execute * without risk of being swapped out until a call to rtos_resume_all () has been * made. * * API functions that have the potential to cause a context switch (for example, * task_delay_until(), xQueueSend(), etc.) must not be called while the scheduler * is suspended. * * Example usage:
 void vTask1( void * pvParameters )
 {
	 for( ;; )
	 {
		 // Task code goes here.

		 // ...

		 // At some point the task wants to perform a long operation during
		 // which it does not want to get swapped out.  It cannot use
		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
		 // operation may cause interrupts to be missed - including the
		 // ticks.

		 // Prevent the real time kernel swapping out the task.
		 rtos_suspend_all ();

		 // Perform the operation here.  There is no need to use critical
		 // sections as we have all the microcontroller processing time.
		 // During this time interrupts will still operate and the kernel
		 // tick count will be maintained.

		 // ...

		 // The operation is complete.  Restart the kernel.
		 rtos_resume_all ();
	 }
 }
   
* \defgroup rtos_suspend_all rtos_suspend_all * \ingroup SchedulerControl */ void rtos_suspend_all( void ) ; /** * task. h *
int32_t rtos_resume_all( void );
* * Resumes scheduler activity after it was suspended by a call to * rtos_suspend_all(). * * rtos_resume_all() only resumes the scheduler. It does not unsuspend tasks * that were previously suspended by a call to task_suspend(). * * @return If resuming the scheduler caused a context switch then pdTRUE is * returned, otherwise pdFALSE is returned. * * Example usage:
 void vTask1( void * pvParameters )
 {
	 for( ;; )
	 {
		 // Task code goes here.

		 // ...

		 // At some point the task wants to perform a long operation during
		 // which it does not want to get swapped out.  It cannot use
		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
		 // operation may cause interrupts to be missed - including the
		 // ticks.

		 // Prevent the real time kernel swapping out the task.
		 rtos_suspend_all ();

		 // Perform the operation here.  There is no need to use critical
		 // sections as we have all the microcontroller processing time.
		 // During this time interrupts will still operate and the real
		 // time kernel tick count will be maintained.

		 // ...

		 // The operation is complete.  Restart the kernel.  We want to force
		 // a context switch - but there is no point if resuming the scheduler
		 // caused a context switch already.
		 if( !rtos_resume_all () )
		 {
			  taskYIELD ();
		 }
	 }
 }
   
* \defgroup rtos_resume_all rtos_resume_all * \ingroup SchedulerControl */ int32_t rtos_resume_all( void ) ; /*----------------------------------------------------------- * TASK UTILITIES *----------------------------------------------------------*/ /** * task. h *
uint32_t millis( void );
* * @return The count of ticks since rtos_sched_start was called. * * \defgroup millis millis * \ingroup TaskUtils */ uint32_t millis( void ) ; /** * task. h *
uint32_t xTaskGetTickCountFromISR( void );
* * @return The count of ticks since rtos_sched_start was called. * * This is a version of millis() that is safe to be called from an * ISR - provided that uint32_t is the natural word size of the * microcontroller being used or interrupt nesting is either not supported or * not being used. * * \defgroup xTaskGetTickCountFromISR xTaskGetTickCountFromISR * \ingroup TaskUtils */ uint32_t xTaskGetTickCountFromISR( void ) ; /** * task. h *
uint16_t task_get_count( void );
* * @return The number of tasks that the real time kernel is currently managing. * This includes all ready, blocked and suspended tasks. A task that * has been deleted but not yet freed by the idle task will also be * included in the count. * * \defgroup task_get_count task_get_count * \ingroup TaskUtils */ uint32_t task_get_count( void ) ; /** * task. h *
char *task_get_name( task_t xTaskToQuery );
* * @return The text (human readable) name of the task referenced by the handle * xTaskToQuery. A task can query its own name by either passing in its own * handle, or by setting xTaskToQuery to NULL. * * \defgroup task_get_name task_get_name * \ingroup TaskUtils */ char *task_get_name( task_t xTaskToQuery ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ /** * task. h *
task_t task_get_by_name( const char *pcNameToQuery );
* * NOTE: This function takes a relatively long time to complete and should be * used sparingly. * * @return The handle of the task that has the human readable name pcNameToQuery. * NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle * must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. * * \defgroup pcTaskGetHandle pcTaskGetHandle * \ingroup TaskUtils */ task_t task_get_by_name( const char *pcNameToQuery ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ /** * task.h *
uint32_t uxTaskGetStackHighWaterMark( task_t xTask );
* * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for * this function to be available. * * Returns the high water mark of the stack associated with xTask. That is, * the minimum free stack space there has been (in words, so on a 32 bit machine * a value of 1 means 4 bytes) since the task started. The smaller the returned * number the closer the task has come to overflowing its stack. * * @param xTask Handle of the task associated with the stack to be checked. * Set xTask to NULL to check the stack of the calling task. * * @return The smallest amount of free stack space there has been (in words, so * actual spaces on the stack rather than bytes) since the task referenced by * xTask was created. */ uint32_t uxTaskGetStackHighWaterMark( task_t xTask ) ; /* When using trace macros it is sometimes necessary to include task.h before FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, so the following two prototypes will cause a compilation error. This can be fixed by simply guarding against the inclusion of these two prototypes unless they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration constant. */ #ifdef configUSE_APPLICATION_TASK_TAG #if configUSE_APPLICATION_TASK_TAG == 1 /** * task.h *
void vTaskSetApplicationTaskTag( task_t xTask, TaskHookFunction_t pxHookFunction );
* * Sets pxHookFunction to be the task hook function used by the task xTask. * Passing xTask as NULL has the effect of setting the calling tasks hook * function. */ void vTaskSetApplicationTaskTag( task_t xTask, TaskHookFunction_t pxHookFunction ) ; /** * task.h *
void xTaskGetApplicationTaskTag( task_t xTask );
* * Returns the pxHookFunction value assigned to the task xTask. */ TaskHookFunction_t xTaskGetApplicationTaskTag( task_t xTask ) ; #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ #endif /* ifdef configUSE_APPLICATION_TASK_TAG */ #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) /* Each task contains an array of pointers that is dimensioned by the configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The kernel does not use the pointers itself, so the application writer can use the pointers for any purpose they wish. The following two functions are used to set and query a pointer respectively. */ void vTaskSetThreadLocalStoragePointer( task_t xTaskToSet, int32_t xIndex, void *pvValue ) ; void *pvTaskGetThreadLocalStoragePointer( task_t xTaskToQuery, int32_t xIndex ) ; #endif /** * task.h *
int32_t xTaskCallApplicationTaskHook( task_t xTask, void *pvParameter );
* * Calls the hook function associated with xTask. Passing xTask as NULL has * the effect of calling the Running tasks (the calling task) hook function. * * pvParameter is passed to the hook function for the task to interpret as it * wants. The return value is the value returned by the task hook function * registered by the user. */ int32_t xTaskCallApplicationTaskHook( task_t xTask, void *pvParameter ) ; /** * xTaskGetIdleTaskHandle() is only available if * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. * * Simply returns the handle of the idle task. It is not valid to call * xTaskGetIdleTaskHandle() before the scheduler has been started. */ task_t xTaskGetIdleTaskHandle( void ) ; /** * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for * uxTaskGetSystemState() to be available. * * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in * the system. TaskStatus_t structures contain, among other things, members * for the task handle, task name, task priority, task state, and total amount * of run time consumed by the task. See the TaskStatus_t structure * definition in this file for the full member list. * * NOTE: This function is intended for debugging use only as its use results in * the scheduler remaining suspended for an extended period. * * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures. * The array must contain at least one TaskStatus_t structure for each task * that is under the control of the RTOS. The number of tasks under the control * of the RTOS can be determined using the task_get_count() API function. * * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray * parameter. The size is specified as the number of indexes in the array, or * the number of TaskStatus_t structures contained in the array, not by the * number of bytes in the array. * * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the * total run time (as defined by the run time stats clock, see * http://www.freertos.org/rtos-run-time-stats.html) since the target booted. * pulTotalRunTime can be set to NULL to omit the total run time information. * * @return The number of TaskStatus_t structures that were populated by * uxTaskGetSystemState(). This should equal the number returned by the * task_get_count() API function, but will be zero if the value passed * in the uxArraySize parameter was too small. * * Example usage:
    // This example demonstrates how a human readable table of run time stats
	// information is generated from raw data provided by uxTaskGetSystemState().
	// The human readable table is written to pcWriteBuffer
	void vTaskGetRunTimeStats( char *pcWriteBuffer )
	{
	TaskStatus_t *pxTaskStatusArray;
	volatile uint32_t uxArraySize, x;
	uint32_t ulTotalRunTime, ulStatsAsPercentage;

		// Make sure the write buffer does not contain a string.
		*pcWriteBuffer = 0x00;

		// Take a snapshot of the number of tasks in case it changes while this
		// function is executing.
		uxArraySize = task_get_count();

		// Allocate a TaskStatus_t structure for each task.  An array could be
		// allocated statically at compile time.
		pxTaskStatusArray = kmalloc( uxArraySize * sizeof( TaskStatus_t ) );

		if( pxTaskStatusArray != NULL )
		{
			// Generate raw status information about each task.
			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );

			// For percentage calculations.
			ulTotalRunTime /= 100UL;

			// Avoid divide by zero errors.
			if( ulTotalRunTime > 0 )
			{
				// For each populated position in the pxTaskStatusArray array,
				// format the raw data as human readable ASCII data
				for( x = 0; x < uxArraySize; x++ )
				{
					// What percentage of the total run time has the task used?
					// This will always be rounded down to the nearest integer.
					// ulTotalRunTimeDiv100 has already been divided by 100.
					ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;

					if( ulStatsAsPercentage > 0UL )
					{
						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
					}
					else
					{
						// If the percentage is zero here then the task has
						// consumed less than 1% of the total run time.
						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
					}

					pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
				}
			}

			// The array is no longer needed, free the memory it consumes.
			kfree( pxTaskStatusArray );
		}
	}
	
*/ uint32_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const uint32_t uxArraySize, uint32_t * const pulTotalRunTime ) ; /** * task. h *
void vTaskList( char *pcWriteBuffer );
* * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must * both be defined as 1 for this function to be available. See the * configuration section of the FreeRTOS.org website for more information. * * NOTE 1: This function will disable interrupts for its duration. It is * not intended for normal application runtime use but as a debug aid. * * Lists all the current tasks, along with their current state and stack * usage high water mark. * * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or * suspended ('S'). * * PLEASE NOTE: * * This function is provided for convenience only, and is used by many of the * demo applications. Do not consider it to be part of the scheduler. * * vTaskList() calls uxTaskGetSystemState(), then formats part of the * uxTaskGetSystemState() output into a human readable table that displays task * names, states and stack usage. * * vTaskList() has a dependency on the sprintf() C library function that might * bloat the code size, use a lot of stack, and provide different results on * different platforms. An alternative, tiny, third party, and limited * functionality implementation of sprintf() is provided in many of the * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note * printf-stdarg.c does not provide a full snprintf() implementation!). * * It is recommended that production systems call uxTaskGetSystemState() * directly to get access to raw stats data, rather than indirectly through a * call to vTaskList(). * * @param pcWriteBuffer A buffer into which the above mentioned details * will be written, in ASCII form. This buffer is assumed to be large * enough to contain the generated report. Approximately 40 bytes per * task should be sufficient. * * \defgroup vTaskList vTaskList * \ingroup TaskUtils */ void vTaskList( char * pcWriteBuffer ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ /** * task. h *
void vTaskGetRunTimeStats( char *pcWriteBuffer );
* * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS * must both be defined as 1 for this function to be available. The application * must also then provide definitions for * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() * to configure a peripheral timer/counter and return the timers current count * value respectively. The counter should be at least 10 times the frequency of * the tick count. * * NOTE 1: This function will disable interrupts for its duration. It is * not intended for normal application runtime use but as a debug aid. * * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total * accumulated execution time being stored for each task. The resolution * of the accumulated time value depends on the frequency of the timer * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. * Calling vTaskGetRunTimeStats() writes the total execution time of each * task into a buffer, both as an absolute count value and as a percentage * of the total system execution time. * * NOTE 2: * * This function is provided for convenience only, and is used by many of the * demo applications. Do not consider it to be part of the scheduler. * * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the * uxTaskGetSystemState() output into a human readable table that displays the * amount of time each task has spent in the Running state in both absolute and * percentage terms. * * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function * that might bloat the code size, use a lot of stack, and provide different * results on different platforms. An alternative, tiny, third party, and * limited functionality implementation of sprintf() is provided in many of the * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note * printf-stdarg.c does not provide a full snprintf() implementation!). * * It is recommended that production systems call uxTaskGetSystemState() directly * to get access to raw stats data, rather than indirectly through a call to * vTaskGetRunTimeStats(). * * @param pcWriteBuffer A buffer into which the execution times will be * written, in ASCII form. This buffer is assumed to be large enough to * contain the generated report. Approximately 40 bytes per task should * be sufficient. * * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats * \ingroup TaskUtils */ void vTaskGetRunTimeStats( char *pcWriteBuffer ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ /** * task. h *
int32_t xTaskNotify( task_t xTaskToNotify, uint32_t ulValue, notify_action_e_t eAction );
* * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this * function to be available. * * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private * "notification value", which is a 32-bit unsigned integer (uint32_t). * * Events can be sent to a task using an intermediary object. Examples of such * objects are queues, semaphores, mutexes and event groups. Task notifications * are a method of sending an event directly to a task without the need for such * an intermediary object. * * A notification sent to a task can optionally perform an action, such as * update, overwrite or increment the task's notification value. In that way * task notifications can be used to send data to a task, or be used as light * weight and fast binary or counting semaphores. * * A notification sent to a task will remain pending until it is cleared by the * task calling task_notify_wait() or task_notify_take(). If the task was * already in the Blocked state to wait for a notification when the notification * arrives then the task will automatically be removed from the Blocked state * (unblocked) and the notification cleared. * * A task can use task_notify_wait() to [optionally] block to wait for a * notification to be pending, or task_notify_take() to [optionally] block * to wait for its notification value to have a non-zero value. The task does * not consume any CPU time while it is in the Blocked state. * * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. * * @param xTaskToNotify The handle of the task being notified. The handle to a * task can be returned from the task_create() API function used to create the * task, and the handle of the currently running task can be obtained by calling * task_get_current(). * * @param ulValue Data that can be sent with the notification. How the data is * used depends on the value of the eAction parameter. * * @param eAction Specifies how the notification updates the task's notification * value, if at all. Valid values for eAction are as follows: * * E_NOTIFY_ACTION_BITS - * The task's notification value is bitwise ORed with ulValue. xTaskNofify() * always returns pdPASS in this case. * * E_NOTIFY_ACTION_INCR - * The task's notification value is incremented. ulValue is not used and * xTaskNotify() always returns pdPASS in this case. * * E_NOTIFY_ACTION_OWRITE - * The task's notification value is set to the value of ulValue, even if the * task being notified had not yet processed the previous notification (the * task already had a notification pending). xTaskNotify() always returns * pdPASS in this case. * * E_NOTIFY_ACTION_NO_OWRITE - * If the task being notified did not already have a notification pending then * the task's notification value is set to ulValue and xTaskNotify() will * return pdPASS. If the task being notified already had a notification * pending then no action is performed and pdFAIL is returned. * * E_NOTIFY_ACTION_NONE - * The task receives a notification without its notification value being * updated. ulValue is not used and xTaskNotify() always returns pdPASS in * this case. * * pulPreviousNotificationValue - * Can be used to pass out the subject task's notification value before any * bits are modified by the notify function. * * @return Dependent on the value of eAction. See the description of the * eAction parameter. * * \defgroup xTaskNotify xTaskNotify * \ingroup TaskNotifications */ int32_t task_notify_ext( task_t xTaskToNotify, uint32_t ulValue, notify_action_e_t eAction, uint32_t *pulPreviousNotificationValue ) ; #define xTaskNotify( xTaskToNotify, ulValue, eAction ) task_notify_ext( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL ) #define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) task_notify_ext( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) /** * task. h *
int32_t xTaskNotifyFromISR( task_t xTaskToNotify, uint32_t ulValue, notify_action_e_t eAction, int32_t *pxHigherPriorityTaskWoken );
* * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this * function to be available. * * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private * "notification value", which is a 32-bit unsigned integer (uint32_t). * * A version of xTaskNotify() that can be used from an interrupt service routine * (ISR). * * Events can be sent to a task using an intermediary object. Examples of such * objects are queues, semaphores, mutexes and event groups. Task notifications * are a method of sending an event directly to a task without the need for such * an intermediary object. * * A notification sent to a task can optionally perform an action, such as * update, overwrite or increment the task's notification value. In that way * task notifications can be used to send data to a task, or be used as light * weight and fast binary or counting semaphores. * * A notification sent to a task will remain pending until it is cleared by the * task calling task_notify_wait() or task_notify_take(). If the task was * already in the Blocked state to wait for a notification when the notification * arrives then the task will automatically be removed from the Blocked state * (unblocked) and the notification cleared. * * A task can use task_notify_wait() to [optionally] block to wait for a * notification to be pending, or task_notify_take() to [optionally] block * to wait for its notification value to have a non-zero value. The task does * not consume any CPU time while it is in the Blocked state. * * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. * * @param xTaskToNotify The handle of the task being notified. The handle to a * task can be returned from the task_create() API function used to create the * task, and the handle of the currently running task can be obtained by calling * task_get_current(). * * @param ulValue Data that can be sent with the notification. How the data is * used depends on the value of the eAction parameter. * * @param eAction Specifies how the notification updates the task's notification * value, if at all. Valid values for eAction are as follows: * * E_NOTIFY_ACTION_BITS - * The task's notification value is bitwise ORed with ulValue. xTaskNofify() * always returns pdPASS in this case. * * E_NOTIFY_ACTION_INCR - * The task's notification value is incremented. ulValue is not used and * xTaskNotify() always returns pdPASS in this case. * * E_NOTIFY_ACTION_OWRITE - * The task's notification value is set to the value of ulValue, even if the * task being notified had not yet processed the previous notification (the * task already had a notification pending). xTaskNotify() always returns * pdPASS in this case. * * E_NOTIFY_ACTION_NO_OWRITE - * If the task being notified did not already have a notification pending then * the task's notification value is set to ulValue and xTaskNotify() will * return pdPASS. If the task being notified already had a notification * pending then no action is performed and pdFAIL is returned. * * E_NOTIFY_ACTION_NONE - * The task receives a notification without its notification value being * updated. ulValue is not used and xTaskNotify() always returns pdPASS in * this case. * * @param pxHigherPriorityTaskWoken xTaskNotifyFromISR() will set * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the * task to which the notification was sent to leave the Blocked state, and the * unblocked task has a priority higher than the currently running task. If * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should * be requested before the interrupt is exited. How a context switch is * requested from an ISR is dependent on the port - see the documentation page * for the port in use. * * @return Dependent on the value of eAction. See the description of the * eAction parameter. * * \defgroup xTaskNotify xTaskNotify * \ingroup TaskNotifications */ int32_t xTaskGenericNotifyFromISR( task_t xTaskToNotify, uint32_t ulValue, notify_action_e_t eAction, uint32_t *pulPreviousNotificationValue, int32_t *pxHigherPriorityTaskWoken ) ; #define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) #define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) /** * task. h *
int32_t task_notify_wait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, uint32_t xTicksToWait );
* * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this * function to be available. * * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private * "notification value", which is a 32-bit unsigned integer (uint32_t). * * Events can be sent to a task using an intermediary object. Examples of such * objects are queues, semaphores, mutexes and event groups. Task notifications * are a method of sending an event directly to a task without the need for such * an intermediary object. * * A notification sent to a task can optionally perform an action, such as * update, overwrite or increment the task's notification value. In that way * task notifications can be used to send data to a task, or be used as light * weight and fast binary or counting semaphores. * * A notification sent to a task will remain pending until it is cleared by the * task calling task_notify_wait() or task_notify_take(). If the task was * already in the Blocked state to wait for a notification when the notification * arrives then the task will automatically be removed from the Blocked state * (unblocked) and the notification cleared. * * A task can use task_notify_wait() to [optionally] block to wait for a * notification to be pending, or task_notify_take() to [optionally] block * to wait for its notification value to have a non-zero value. The task does * not consume any CPU time while it is in the Blocked state. * * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. * * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value * will be cleared in the calling task's notification value before the task * checks to see if any notifications are pending, and optionally blocks if no * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have * the effect of resetting the task's notification value to 0. Setting * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. * * @param ulBitsToClearOnExit If a notification is pending or received before * the calling task exits the task_notify_wait() function then the task's * notification value (see the xTaskNotify() API function) is passed out using * the pulNotificationValue parameter. Then any bits that are set in * ulBitsToClearOnExit will be cleared in the task's notification value (note * *pulNotificationValue is set before any bits are cleared). Setting * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL * (if limits.h is not included) will have the effect of resetting the task's * notification value to 0 before the function exits. Setting * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged * when the function exits (in which case the value passed out in * pulNotificationValue will match the task's notification value). * * @param pulNotificationValue Used to pass the task's notification value out * of the function. Note the value passed out will not be effected by the * clearing of any bits caused by ulBitsToClearOnExit being non-zero. * * @param xTicksToWait The maximum amount of time that the task should wait in * the Blocked state for a notification to be received, should a notification * not already be pending when task_notify_wait() was called. The task * will not consume any processing time while it is in the Blocked state. This * is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be * used to convert a time specified in milliseconds to a time specified in * ticks. * * @return If a notification was received (including notifications that were * already pending when task_notify_wait was called) then pdPASS is * returned. Otherwise pdFAIL is returned. * * \defgroup task_notify_wait task_notify_wait * \ingroup TaskNotifications */ int32_t task_notify_wait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, uint32_t xTicksToWait ) ; /** * task. h *
int32_t task_notify( task_t xTaskToNotify );
* * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro * to be available. * * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private * "notification value", which is a 32-bit unsigned integer (uint32_t). * * Events can be sent to a task using an intermediary object. Examples of such * objects are queues, semaphores, mutexes and event groups. Task notifications * are a method of sending an event directly to a task without the need for such * an intermediary object. * * A notification sent to a task can optionally perform an action, such as * update, overwrite or increment the task's notification value. In that way * task notifications can be used to send data to a task, or be used as light * weight and fast binary or counting semaphores. * * xTaskNotifyGive() is a helper macro intended for use when task notifications * are used as light weight and faster binary or counting semaphore equivalents. * Actual FreeRTOS semaphores are given using the sem_post() API function, * the equivalent action that instead uses a task notification is * xTaskNotifyGive(). * * When task notifications are being used as a binary or counting semaphore * equivalent then the task being notified should wait for the notification * using the ulTaskNotificationTake() API function rather than the * task_notify_wait() API function. * * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details. * * @param xTaskToNotify The handle of the task being notified. The handle to a * task can be returned from the task_create() API function used to create the * task, and the handle of the currently running task can be obtained by calling * task_get_current(). * * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the * eAction parameter set to E_NOTIFY_ACTION_INCR - so pdPASS is always returned. * * \defgroup xTaskNotifyGive xTaskNotifyGive * \ingroup TaskNotifications */ int32_t task_notify(task_t xTaskToNotify); /** * task. h *
void vTaskNotifyGiveFromISR( task_t xTaskHandle, int32_t *pxHigherPriorityTaskWoken );
 *
 * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
 * to be available.
 *
 * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
 * "notification value", which is a 32-bit unsigned integer (uint32_t).
 *
 * A version of xTaskNotifyGive() that can be called from an interrupt service
 * routine (ISR).
 *
 * Events can be sent to a task using an intermediary object.  Examples of such
 * objects are queues, semaphores, mutexes and event groups.  Task notifications
 * are a method of sending an event directly to a task without the need for such
 * an intermediary object.
 *
 * A notification sent to a task can optionally perform an action, such as
 * update, overwrite or increment the task's notification value.  In that way
 * task notifications can be used to send data to a task, or be used as light
 * weight and fast binary or counting semaphores.
 *
 * vTaskNotifyGiveFromISR() is intended for use when task notifications are
 * used as light weight and faster binary or counting semaphore equivalents.
 * Actual FreeRTOS semaphores are given from an ISR using the
 * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses
 * a task notification is vTaskNotifyGiveFromISR().
 *
 * When task notifications are being used as a binary or counting semaphore
 * equivalent then the task being notified should wait for the notification
 * using the ulTaskNotificationTake() API function rather than the
 * task_notify_wait() API function.
 *
 * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
 *
 * @param xTaskToNotify The handle of the task being notified.  The handle to a
 * task can be returned from the task_create() API function used to create the
 * task, and the handle of the currently running task can be obtained by calling
 * task_get_current().
 *
 * @param pxHigherPriorityTaskWoken  vTaskNotifyGiveFromISR() will set
 * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
 * task to which the notification was sent to leave the Blocked state, and the
 * unblocked task has a priority higher than the currently running task.  If
 * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch
 * should be requested before the interrupt is exited.  How a context switch is
 * requested from an ISR is dependent on the port - see the documentation page
 * for the port in use.
 *
 * \defgroup task_notify_wait task_notify_wait
 * \ingroup TaskNotifications
 */
void vTaskNotifyGiveFromISR( task_t xTaskToNotify, int32_t *pxHigherPriorityTaskWoken ) ;

/**
 * task. h
 * 
uint32_t task_notify_take( int32_t xClearCountOnExit, uint32_t xTicksToWait );
* * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this * function to be available. * * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private * "notification value", which is a 32-bit unsigned integer (uint32_t). * * Events can be sent to a task using an intermediary object. Examples of such * objects are queues, semaphores, mutexes and event groups. Task notifications * are a method of sending an event directly to a task without the need for such * an intermediary object. * * A notification sent to a task can optionally perform an action, such as * update, overwrite or increment the task's notification value. In that way * task notifications can be used to send data to a task, or be used as light * weight and fast binary or counting semaphores. * * task_notify_take() is intended for use when a task notification is used as a * faster and lighter weight binary or counting semaphore alternative. Actual * FreeRTOS semaphores are taken using the sem_wait() API function, the * equivalent action that instead uses a task notification is * task_notify_take(). * * When a task is using its notification value as a binary or counting semaphore * other tasks should send notifications to it using the xTaskNotifyGive() * macro, or xTaskNotify() function with the eAction parameter set to * E_NOTIFY_ACTION_INCR. * * task_notify_take() can either clear the task's notification value to * zero on exit, in which case the notification value acts like a binary * semaphore, or decrement the task's notification value on exit, in which case * the notification value acts like a counting semaphore. * * A task can use task_notify_take() to [optionally] block to wait for a * the task's notification value to be non-zero. The task does not consume any * CPU time while it is in the Blocked state. * * Where as task_notify_wait() will return when a notification is pending, * task_notify_take() will return when the task's notification value is * not zero. * * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. * * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's * notification value is decremented when the function exits. In this way the * notification value acts like a counting semaphore. If xClearCountOnExit is * not pdFALSE then the task's notification value is cleared to zero when the * function exits. In this way the notification value acts like a binary * semaphore. * * @param xTicksToWait The maximum amount of time that the task should wait in * the Blocked state for the task's notification value to be greater than zero, * should the count not already be greater than zero when * task_notify_take() was called. The task will not consume any processing * time while it is in the Blocked state. This is specified in kernel ticks, * the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time * specified in milliseconds to a time specified in ticks. * * @return The task's notification count before it is either cleared to zero or * decremented (see the xClearCountOnExit parameter). * * \defgroup task_notify_take task_notify_take * \ingroup TaskNotifications */ uint32_t task_notify_take( bool xClearCountOnExit, uint32_t xTicksToWait ) ; /** * task. h *
int32_t task_notify_clear( task_t xTask );
* * If the notification state of the task referenced by the handle xTask is * eNotified, then set the task's notification state to eNotWaitingNotification. * The task's notification value is not altered. Set xTask to NULL to clear the * notification state of the calling task. * * @return pdTRUE if the task's notification state was set to * eNotWaitingNotification, otherwise pdFALSE. * \defgroup task_notify_clear task_notify_clear * \ingroup TaskNotifications */ int32_t task_notify_clear( task_t xTask ); /*----------------------------------------------------------- * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES *----------------------------------------------------------*/ /* * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. * * Called from the real time kernel tick (either preemptive or cooperative), * this increments the tick count and checks if any tasks that are blocked * for a finite period required removing from a blocked list and placing on * a ready list. If a non-zero value is returned then a context switch is * required because either: * + A task was removed from a blocked list because its timeout had expired, * or * + Time slicing is in use and there is a task of equal priority to the * currently running task. */ int32_t xTaskIncrementTick( void ) ; /* * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. * * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. * * Removes the calling task from the ready list and places it both * on the list of tasks waiting for a particular event, and the * list of delayed tasks. The task will be removed from both lists * and replaced on the ready list should either the event occur (and * there be no higher priority tasks waiting on the same event) or * the delay period expires. * * The 'unordered' version replaces the event list item value with the * xItemValue value, and inserts the list item at the end of the list. * * The 'ordered' version uses the existing event list item value (which is the * owning tasks priority) to insert the list item into the event list is task * priority order. * * @param pxEventList The list containing tasks that are blocked waiting * for the event to occur. * * @param xItemValue The item value to use for the event list item when the * event list is not ordered by task priority. * * @param xTicksToWait The maximum amount of time that the task should wait * for the event to occur. This is specified in kernel ticks,the constant * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time * period. */ void vTaskPlaceOnEventList( List_t * const pxEventList, const uint32_t xTicksToWait ) ; void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const uint32_t xItemValue, const uint32_t xTicksToWait ) ; /* * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. * * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. * * This function performs nearly the same function as vTaskPlaceOnEventList(). * The difference being that this function does not permit tasks to block * indefinitely, whereas vTaskPlaceOnEventList() does. * */ void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, uint32_t xTicksToWait, const int32_t xWaitIndefinitely ) ; /* * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. * * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. * * Removes a task from both the specified event list and the list of blocked * tasks, and places it on a ready queue. * * xTaskRemoveFromEventList()/vTaskRemoveFromUnorderedEventList() will be called * if either an event occurs to unblock a task, or the block timeout period * expires. * * xTaskRemoveFromEventList() is used when the event list is in task priority * order. It removes the list item from the head of the event list as that will * have the highest priority owning task of all the tasks on the event list. * vTaskRemoveFromUnorderedEventList() is used when the event list is not * ordered and the event list items hold something other than the owning tasks * priority. In this case the event list item value is updated to the value * passed in the xItemValue parameter. * * @return pdTRUE if the task being removed has a higher priority than the task * making the call, otherwise pdFALSE. */ int32_t xTaskRemoveFromEventList( const List_t * const pxEventList ) ; void vTaskRemoveFromUnorderedEventList( list_item_t * pxEventListItem, const uint32_t xItemValue ) ; /* * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. * * Sets the pointer to the current TCB to the TCB of the highest priority task * that is ready to run. */ void vTaskSwitchContext( void ) ; /* * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY * THE EVENT BITS MODULE. */ uint32_t uxTaskResetEventItemValue( void ) ; /* * Return the handle of the calling task. */ task_t task_get_current( void ) ; /* * Capture the current time status for future reference. */ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) ; /* * Compare the time status now with that previously captured to see if the * timeout has expired. */ int32_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, uint32_t * const pxTicksToWait ) ; /* * Shortcut used by the queue implementation to prevent unnecessary call to * taskYIELD(); */ void vTaskMissedYield( void ) ; /* * Returns the scheduler state as taskSCHEDULER_RUNNING, * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED. */ int32_t xTaskGetSchedulerState( void ) ; /* * Raises the priority of the mutex holder to that of the calling task should * the mutex holder have a priority less than the calling task. */ int32_t xTaskPriorityInherit( task_t const pxMutexHolder ) ; /* * Set the priority of a task back to its proper priority in the case that it * inherited a higher priority while it was holding a semaphore. */ int32_t xTaskPriorityDisinherit( task_t const pxMutexHolder ) ; /* * If a higher priority task attempting to obtain a mutex caused a lower * priority task to inherit the higher priority task's priority - but the higher * priority task then timed out without obtaining the mutex, then the lower * priority task will disinherit the priority again - but only down as far as * the highest priority task that is still waiting for the mutex (if there were * more than one task waiting for the mutex). */ void vTaskPriorityDisinheritAfterTimeout( task_t const pxMutexHolder, uint32_t uxHighestPriorityWaitingTask ) ; /* * Get the uxTCBNumber assigned to the task referenced by the xTask parameter. */ uint32_t uxTaskGetTaskNumber( task_t xTask ) ; /* * Set the uxTaskNumber of the task referenced by the xTask parameter to * uxHandle. */ void vTaskSetTaskNumber( task_t xTask, const uint32_t uxHandle ) ; /* * Only available when configUSE_TICKLESS_IDLE is set to 1. * If tickless mode is being used, or a low power mode is implemented, then * the tick interrupt will not execute during idle periods. When this is the * case, the tick count value maintained by the scheduler needs to be kept up * to date with the actual execution time by being skipped forward by a time * equal to the idle period. */ void vTaskStepTick( const uint32_t xTicksToJump ) ; /* * Only avilable when configUSE_TICKLESS_IDLE is set to 1. * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port * specific sleep function to determine if it is ok to proceed with the sleep, * and if it is ok to proceed, if it is ok to sleep indefinitely. * * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only * called with the scheduler suspended, not from within a critical section. It * is therefore possible for an interrupt to request a context switch between * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being * entered. eTaskConfirmSleepModeStatus() should be called from a short * critical section between the timer being stopped and the sleep mode being * entered to ensure it is ok to proceed into the sleep mode. */ eSleepModeStatus eTaskConfirmSleepModeStatus( void ) ; /* * For internal use only. Increment the mutex held count when a mutex is * taken and return the handle of the task that has taken the mutex. */ void *pvTaskIncrementMutexHeldCount( void ) ; /* * For internal use only. Same as vTaskSetTimeOutState(), but without a critial * section. */ void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) ; #ifdef __cplusplus } #endif #endif /* INC_TASK_H */ ================================================ FILE: include/rtos/tcb.h ================================================ #pragma once #include "rtos/FreeRTOS.h" #include "rtos/list.h" /* * Task control block. A task control block (TCB) is allocated for each task, * and stores task state information, including a pointer to the task's context * (the task's run time environment, including register values) */ typedef struct tskTaskControlBlock { volatile task_stack_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ list_item_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ list_item_t xEventListItem; /*< Used to reference a task from an event list. */ uint32_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ task_stack_t *pxStack; /*< Points to the start of the stack. */ char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) task_stack_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ #endif #if ( portCRITICAL_NESTING_IN_TCB == 1 ) uint32_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ #endif #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ uint32_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ #endif #if ( configUSE_MUTEXES == 1 ) uint32_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ uint32_t uxMutexesHeld; #endif #if ( configUSE_APPLICATION_TASK_TAG == 1 ) TaskHookFunction_t pxTaskTag; #endif #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; #endif #if( configGENERATE_RUN_TIME_STATS == 1 ) uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ #endif #if ( configUSE_NEWLIB_REENTRANT == 1 ) /* Allocate a Newlib reent structure that is specific to this task. Note Newlib support has been included by popular demand, but is not used by the FreeRTOS maintainers themselves. FreeRTOS is not responsible for resulting newlib operation. User must be familiar with newlib and must provide system-wide implementations of the necessary stubs. Be warned that (at the time of writing) the current newlib design implements a system-wide malloc() that must be provided with locks. */ struct _reent xNewLib_reent; #endif #if( configUSE_TASK_NOTIFICATIONS == 1 ) volatile uint32_t ulNotifiedValue; volatile uint8_t ucNotifyState; #endif /* See the comments above the definition of tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ #endif #if( INCLUDE_xTaskAbortDelay == 1 ) uint8_t ucDelayAborted; #endif } tskTCB; /* The old tskTCB name is maintained above then typedefed to the new TCB_t name below to enable the use of older kernel aware debuggers. */ typedef tskTCB TCB_t; /*lint -save -e956 A manual analysis and inspection has been used to determine which static variables must be declared volatile. */ extern TCB_t * volatile pxCurrentTCB; ================================================ FILE: include/rtos/timers.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef TIMERS_H #define TIMERS_H #ifndef INC_FREERTOS_H #error "include FreeRTOS.h must appear in source files before include timers.h" #endif /*lint -save -e537 This headers are only multiply included if the application code happens to also be including task.h. */ #include "task.h" /*lint -restore */ #ifdef __cplusplus extern "C" { #endif /*----------------------------------------------------------- * MACROS AND DEFINITIONS *----------------------------------------------------------*/ /* IDs for commands that can be sent/received on the timer queue. These are to be used solely through the macros that make up the public software timer API, as defined below. The commands that are sent from interrupts must use the highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task or interrupt version of the queue send function should be used. */ #define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( int32_t ) -2 ) #define tmrCOMMAND_EXECUTE_CALLBACK ( ( int32_t ) -1 ) #define tmrCOMMAND_START_DONT_TRACE ( ( int32_t ) 0 ) #define tmrCOMMAND_START ( ( int32_t ) 1 ) #define tmrCOMMAND_RESET ( ( int32_t ) 2 ) #define tmrCOMMAND_STOP ( ( int32_t ) 3 ) #define tmrCOMMAND_CHANGE_PERIOD ( ( int32_t ) 4 ) #define tmrCOMMAND_DELETE ( ( int32_t ) 5 ) #define tmrFIRST_FROM_ISR_COMMAND ( ( int32_t ) 6 ) #define tmrCOMMAND_START_FROM_ISR ( ( int32_t ) 6 ) #define tmrCOMMAND_RESET_FROM_ISR ( ( int32_t ) 7 ) #define tmrCOMMAND_STOP_FROM_ISR ( ( int32_t ) 8 ) #define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( int32_t ) 9 ) /** * Type by which software timers are referenced. For example, a call to * xTimerCreate() returns an TimerHandle_t variable that can then be used to * reference the subject timer in calls to other software timer API functions * (for example, xTimerStart(), xTimerReset(), etc.). */ typedef void * TimerHandle_t; /* * Defines the prototype to which timer callback functions must conform. */ typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer ); /* * Defines the prototype to which functions used with the * xTimerPendFunctionCallFromISR() function must conform. */ typedef void (*PendedFunction_t)( void *, uint32_t ); /** * TimerHandle_t xTimerCreate( const char * const pcTimerName, * uint32_t xTimerPeriodInTicks, * uint32_t uxAutoReload, * void * pvTimerID, * TimerCallbackFunction_t pxCallbackFunction ); * * Creates a new software timer instance, and returns a handle by which the * created software timer can be referenced. * * Internally, within the FreeRTOS implementation, software timers use a block * of memory, in which the timer data structure is stored. If a software timer * is created using xTimerCreate() then the required memory is automatically * dynamically allocated inside the xTimerCreate() function. (see * http://www.freertos.org/a00111.html). If a software timer is created using * xTimerCreateStatic() then the application writer must provide the memory that * will get used by the software timer. xTimerCreateStatic() therefore allows a * software timer to be created without using any dynamic memory allocation. * * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and * xTimerChangePeriodFromISR() API functions can all be used to transition a * timer into the active state. * * @param pcTimerName A text name that is assigned to the timer. This is done * purely to assist debugging. The kernel itself only ever references a timer * by its handle, and never by its name. * * @param xTimerPeriodInTicks The timer period. The time is defined in tick * periods so the constant portTICK_PERIOD_MS can be used to convert a time that * has been specified in milliseconds. For example, if the timer must expire * after 100 ticks, then xTimerPeriodInTicks should be set to 100. * Alternatively, if the timer must expire after 500ms, then xPeriod can be set * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or * equal to 1000. * * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and * enter the dormant state after it expires. * * @param pvTimerID An identifier that is assigned to the timer being created. * Typically this would be used in the timer callback function to identify which * timer expired when the same callback function is assigned to more than one * timer. * * @param pxCallbackFunction The function to call when the timer expires. * Callback functions must have the prototype defined by TimerCallbackFunction_t, * which is "void vCallbackFunction( TimerHandle_t xTimer );". * * @return If the timer is successfully created then a handle to the newly * created timer is returned. If the timer cannot be created (because either * there is insufficient FreeRTOS heap remaining to allocate the timer * structures, or the timer period was set to 0) then NULL is returned. * * Example usage: * @verbatim * #define NUM_TIMERS 5 * * // An array to hold handles to the created timers. * TimerHandle_t xTimers[ NUM_TIMERS ]; * * // An array to hold a count of the number of times each timer expires. * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; * * // Define a callback function that will be used by multiple timer instances. * // The callback function does nothing but count the number of times the * // associated timer expires, and stop the timer once the timer has expired * // 10 times. * void vTimerCallback( TimerHandle_t pxTimer ) * { * int32_t lArrayIndex; * const int32_t xMaxExpiryCountBeforeStopping = 10; * * // Optionally do something if the pxTimer parameter is NULL. * configASSERT( pxTimer ); * * // Which timer expired? * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); * * // Increment the number of times that pxTimer has expired. * lExpireCounters[ lArrayIndex ] += 1; * * // If the timer has expired 10 times then stop it from running. * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) * { * // Do not use a block time if calling a timer API function from a * // timer callback function, as doing so could cause a deadlock! * xTimerStop( pxTimer, 0 ); * } * } * * void main( void ) * { * int32_t x; * * // Create then start some timers. Starting the timers before the scheduler * // has been started means the timers will start running immediately that * // the scheduler starts. * for( x = 0; x < NUM_TIMERS; x++ ) * { * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. * ( 100 * x ), // The timer period in ticks. * pdTRUE, // The timers will auto-reload themselves when they expire. * ( void * ) x, // Assign each timer a unique id equal to its array index. * vTimerCallback // Each timer calls the same callback when it expires. * ); * * if( xTimers[ x ] == NULL ) * { * // The timer was not created. * } * else * { * // Start the timer. No block time is specified, and even if one was * // it would be ignored because the scheduler has not yet been * // started. * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) * { * // The timer could not be set into the Active state. * } * } * } * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timers running as they have already * // been set into the active state. * rtos_sched_start(); * * // Should not reach here. * for( ;; ); * } * @endverbatim */ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t xTimerPeriodInTicks, const uint32_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) ; #endif /** * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, * uint32_t xTimerPeriodInTicks, * uint32_t uxAutoReload, * void * pvTimerID, * TimerCallbackFunction_t pxCallbackFunction, * StaticTimer_t *pxTimerBuffer ); * * Creates a new software timer instance, and returns a handle by which the * created software timer can be referenced. * * Internally, within the FreeRTOS implementation, software timers use a block * of memory, in which the timer data structure is stored. If a software timer * is created using xTimerCreate() then the required memory is automatically * dynamically allocated inside the xTimerCreate() function. (see * http://www.freertos.org/a00111.html). If a software timer is created using * xTimerCreateStatic() then the application writer must provide the memory that * will get used by the software timer. xTimerCreateStatic() therefore allows a * software timer to be created without using any dynamic memory allocation. * * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and * xTimerChangePeriodFromISR() API functions can all be used to transition a * timer into the active state. * * @param pcTimerName A text name that is assigned to the timer. This is done * purely to assist debugging. The kernel itself only ever references a timer * by its handle, and never by its name. * * @param xTimerPeriodInTicks The timer period. The time is defined in tick * periods so the constant portTICK_PERIOD_MS can be used to convert a time that * has been specified in milliseconds. For example, if the timer must expire * after 100 ticks, then xTimerPeriodInTicks should be set to 100. * Alternatively, if the timer must expire after 500ms, then xPeriod can be set * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or * equal to 1000. * * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and * enter the dormant state after it expires. * * @param pvTimerID An identifier that is assigned to the timer being created. * Typically this would be used in the timer callback function to identify which * timer expired when the same callback function is assigned to more than one * timer. * * @param pxCallbackFunction The function to call when the timer expires. * Callback functions must have the prototype defined by TimerCallbackFunction_t, * which is "void vCallbackFunction( TimerHandle_t xTimer );". * * @param pxTimerBuffer Must point to a variable of type StaticTimer_t, which * will be then be used to hold the software timer's data structures, removing * the need for the memory to be allocated dynamically. * * @return If the timer is created then a handle to the created timer is * returned. If pxTimerBuffer was NULL then NULL is returned. * * Example usage: * @verbatim * * // The buffer used to hold the software timer's data structure. * static StaticTimer_t xTimerBuffer; * * // A variable that will be incremented by the software timer's callback * // function. * uint32_t uxVariableToIncrement = 0; * * // A software timer callback function that increments a variable passed to * // it when the software timer was created. After the 5th increment the * // callback function stops the software timer. * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) * { * uint32_t *puxVariableToIncrement; * int32_t xReturned; * * // Obtain the address of the variable to increment from the timer ID. * puxVariableToIncrement = ( uint32_t * ) pvTimerGetTimerID( xExpiredTimer ); * * // Increment the variable to show the timer callback has executed. * ( *puxVariableToIncrement )++; * * // If this callback has executed the required number of times, stop the * // timer. * if( *puxVariableToIncrement == 5 ) * { * // This is called from a timer callback so must not block. * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); * } * } * * * void main( void ) * { * // Create the software time. xTimerCreateStatic() has an extra parameter * // than the normal xTimerCreate() API function. The parameter is a pointer * // to the StaticTimer_t structure that will hold the software timer * // structure. If the parameter is passed as NULL then the structure will be * // allocated dynamically, just as if xTimerCreate() had been called. * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. * xTimerPeriod, // The period of the timer in ticks. * pdTRUE, // This is an auto-reload timer. * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function * prvTimerCallback, // The function to execute when the timer expires. * &xTimerBuffer ); // The buffer that will hold the software timer structure. * * // The scheduler has not started yet so a block time is not used. * xReturned = xTimerStart( xTimer, 0 ); * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timers running as they have already * // been set into the active state. * rtos_sched_start(); * * // Should not reach here. * for( ;; ); * } * @endverbatim */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t xTimerPeriodInTicks, const uint32_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer ) ; #endif /* configSUPPORT_STATIC_ALLOCATION */ /** * void *pvTimerGetTimerID( TimerHandle_t xTimer ); * * Returns the ID assigned to the timer. * * IDs are assigned to timers using the pvTimerID parameter of the call to * xTimerCreated() that was used to create the timer, and by calling the * vTimerSetTimerID() API function. * * If the same callback function is assigned to multiple timers then the timer * ID can be used as time specific (timer local) storage. * * @param xTimer The timer being queried. * * @return The ID assigned to the timer being queried. * * Example usage: * * See the xTimerCreate() API function example usage scenario. */ void *pvTimerGetTimerID( const TimerHandle_t xTimer ) ; /** * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); * * Sets the ID assigned to the timer. * * IDs are assigned to timers using the pvTimerID parameter of the call to * xTimerCreated() that was used to create the timer. * * If the same callback function is assigned to multiple timers then the timer * ID can be used as time specific (timer local) storage. * * @param xTimer The timer being updated. * * @param pvNewID The ID to assign to the timer. * * Example usage: * * See the xTimerCreate() API function example usage scenario. */ void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) ; /** * int32_t xTimerIsTimerActive( TimerHandle_t xTimer ); * * Queries a timer to see if it is active or dormant. * * A timer will be dormant if: * 1) It has been created but not started, or * 2) It is an expired one-shot timer that has not been restarted. * * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the * active state. * * @param xTimer The timer being queried. * * @return pdFALSE will be returned if the timer is dormant. A value other than * pdFALSE will be returned if the timer is active. * * Example usage: * @verbatim * // This function assumes xTimer has already been created. * void vAFunction( TimerHandle_t xTimer ) * { * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" * { * // xTimer is active, do something. * } * else * { * // xTimer is not active, do something else. * } * } * @endverbatim */ int32_t xTimerIsTimerActive( TimerHandle_t xTimer ) ; /** * task_t xTimerGetTimerDaemonTaskHandle( void ); * * Simply returns the handle of the timer service/daemon task. It it not valid * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. */ task_t xTimerGetTimerDaemonTaskHandle( void ) ; /** * int32_t xTimerStart( TimerHandle_t xTimer, uint32_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task * through a queue called the timer command queue. The timer command queue is * private to the kernel itself and is not directly accessible to application * code. The length of the timer command queue is set by the * configTIMER_QUEUE_LENGTH configuration constant. * * xTimerStart() starts a timer that was previously created using the * xTimerCreate() API function. If the timer had already been started and was * already in the active state, then xTimerStart() has equivalent functionality * to the xTimerReset() API function. * * Starting a timer ensures the timer is in the active state. If the timer * is not stopped, deleted, or reset in the mean time, the callback function * associated with the timer will get called 'n' ticks after xTimerStart() was * called, where 'n' is the timers defined period. * * It is valid to call xTimerStart() before the scheduler has been started, but * when this is done the timer will not actually start until the scheduler is * started, and the timers expiry time will be relative to when the scheduler is * started, not relative to when xTimerStart() was called. * * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() * to be available. * * @param xTimer The handle of the timer being started/restarted. * * @param xTicksToWait Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the start command to be successfully * sent to the timer command queue, should the queue already be full when * xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called * before the scheduler is started. * * @return pdFAIL will be returned if the start command could not be sent to * the timer command queue even after xTicksToWait ticks had passed. pdPASS will * be returned if the command was successfully sent to the timer command queue. * When the command is actually processed will depend on the priority of the * timer service/daemon task relative to other tasks in the system, although the * timers expiry time is relative to when xTimerStart() is actually called. The * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY * configuration constant. * * Example usage: * * See the xTimerCreate() API function example usage scenario. * */ #define xTimerStart( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( millis() ), NULL, ( xTicksToWait ) ) /** * int32_t xTimerStop( TimerHandle_t xTimer, uint32_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task * through a queue called the timer command queue. The timer command queue is * private to the kernel itself and is not directly accessible to application * code. The length of the timer command queue is set by the * configTIMER_QUEUE_LENGTH configuration constant. * * xTimerStop() stops a timer that was previously started using either of the * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. * * Stopping a timer ensures the timer is not in the active state. * * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() * to be available. * * @param xTimer The handle of the timer being stopped. * * @param xTicksToWait Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the stop command to be successfully * sent to the timer command queue, should the queue already be full when * xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called * before the scheduler is started. * * @return pdFAIL will be returned if the stop command could not be sent to * the timer command queue even after xTicksToWait ticks had passed. pdPASS will * be returned if the command was successfully sent to the timer command queue. * When the command is actually processed will depend on the priority of the * timer service/daemon task relative to other tasks in the system. The timer * service/daemon task priority is set by the configTIMER_TASK_PRIORITY * configuration constant. * * Example usage: * * See the xTimerCreate() API function example usage scenario. * */ #define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) /** * int32_t xTimerChangePeriod( TimerHandle_t xTimer, * uint32_t xNewPeriod, * uint32_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task * through a queue called the timer command queue. The timer command queue is * private to the kernel itself and is not directly accessible to application * code. The length of the timer command queue is set by the * configTIMER_QUEUE_LENGTH configuration constant. * * xTimerChangePeriod() changes the period of a timer that was previously * created using the xTimerCreate() API function. * * xTimerChangePeriod() can be called to change the period of an active or * dormant state timer. * * The configUSE_TIMERS configuration constant must be set to 1 for * xTimerChangePeriod() to be available. * * @param xTimer The handle of the timer that is having its period changed. * * @param xNewPeriod The new period for xTimer. Timer periods are specified in * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time * that has been specified in milliseconds. For example, if the timer must * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, * if the timer must expire after 500ms, then xNewPeriod can be set to * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than * or equal to 1000. * * @param xTicksToWait Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the change period command to be * successfully sent to the timer command queue, should the queue already be * full when xTimerChangePeriod() was called. xTicksToWait is ignored if * xTimerChangePeriod() is called before the scheduler is started. * * @return pdFAIL will be returned if the change period command could not be * sent to the timer command queue even after xTicksToWait ticks had passed. * pdPASS will be returned if the command was successfully sent to the timer * command queue. When the command is actually processed will depend on the * priority of the timer service/daemon task relative to other tasks in the * system. The timer service/daemon task priority is set by the * configTIMER_TASK_PRIORITY configuration constant. * * Example usage: * @verbatim * // This function assumes xTimer has already been created. If the timer * // referenced by xTimer is already active when it is called, then the timer * // is deleted. If the timer referenced by xTimer is not active when it is * // called, then the period of the timer is set to 500ms and the timer is * // started. * void vAFunction( TimerHandle_t xTimer ) * { * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" * { * // xTimer is already active - delete it. * xTimerDelete( xTimer ); * } * else * { * // xTimer is not active, change its period to 500ms. This will also * // cause the timer to start. Block for a maximum of 100 ticks if the * // change period command cannot immediately be sent to the timer * // command queue. * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) * { * // The command was successfully sent. * } * else * { * // The command could not be sent, even after waiting for 100 ticks * // to pass. Take appropriate action here. * } * } * } * @endverbatim */ #define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) ) /** * int32_t xTimerDelete( TimerHandle_t xTimer, uint32_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task * through a queue called the timer command queue. The timer command queue is * private to the kernel itself and is not directly accessible to application * code. The length of the timer command queue is set by the * configTIMER_QUEUE_LENGTH configuration constant. * * xTimerDelete() deletes a timer that was previously created using the * xTimerCreate() API function. * * The configUSE_TIMERS configuration constant must be set to 1 for * xTimerDelete() to be available. * * @param xTimer The handle of the timer being deleted. * * @param xTicksToWait Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the delete command to be * successfully sent to the timer command queue, should the queue already be * full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() * is called before the scheduler is started. * * @return pdFAIL will be returned if the delete command could not be sent to * the timer command queue even after xTicksToWait ticks had passed. pdPASS will * be returned if the command was successfully sent to the timer command queue. * When the command is actually processed will depend on the priority of the * timer service/daemon task relative to other tasks in the system. The timer * service/daemon task priority is set by the configTIMER_TASK_PRIORITY * configuration constant. * * Example usage: * * See the xTimerChangePeriod() API function example usage scenario. */ #define xTimerDelete( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) ) /** * int32_t xTimerReset( TimerHandle_t xTimer, uint32_t xTicksToWait ); * * Timer functionality is provided by a timer service/daemon task. Many of the * public FreeRTOS timer API functions send commands to the timer service task * through a queue called the timer command queue. The timer command queue is * private to the kernel itself and is not directly accessible to application * code. The length of the timer command queue is set by the * configTIMER_QUEUE_LENGTH configuration constant. * * xTimerReset() re-starts a timer that was previously created using the * xTimerCreate() API function. If the timer had already been started and was * already in the active state, then xTimerReset() will cause the timer to * re-evaluate its expiry time so that it is relative to when xTimerReset() was * called. If the timer was in the dormant state then xTimerReset() has * equivalent functionality to the xTimerStart() API function. * * Resetting a timer ensures the timer is in the active state. If the timer * is not stopped, deleted, or reset in the mean time, the callback function * associated with the timer will get called 'n' ticks after xTimerReset() was * called, where 'n' is the timers defined period. * * It is valid to call xTimerReset() before the scheduler has been started, but * when this is done the timer will not actually start until the scheduler is * started, and the timers expiry time will be relative to when the scheduler is * started, not relative to when xTimerReset() was called. * * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() * to be available. * * @param xTimer The handle of the timer being reset/started/restarted. * * @param xTicksToWait Specifies the time, in ticks, that the calling task should * be held in the Blocked state to wait for the reset command to be successfully * sent to the timer command queue, should the queue already be full when * xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called * before the scheduler is started. * * @return pdFAIL will be returned if the reset command could not be sent to * the timer command queue even after xTicksToWait ticks had passed. pdPASS will * be returned if the command was successfully sent to the timer command queue. * When the command is actually processed will depend on the priority of the * timer service/daemon task relative to other tasks in the system, although the * timers expiry time is relative to when xTimerStart() is actually called. The * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY * configuration constant. * * Example usage: * @verbatim * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer. * * TimerHandle_t xBacklightTimer = NULL; * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press event handler. * void vKeyPressEventHandler( char cKey ) * { * // Ensure the LCD back-light is on, then reset the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. Wait 10 ticks for the command to be successfully sent * // if it cannot be sent immediately. * vSetBacklightState( BACKLIGHT_ON ); * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) * { * // The reset command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * } * * void main( void ) * { * int32_t x; * * // Create then start the one-shot timer that is responsible for turning * // the back-light off if no keys are pressed within a 5 second period. * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. * pdFALSE, // The timer is a one-shot timer. * 0, // The id is not used by the callback so can take any value. * vBacklightTimerCallback // The callback function that switches the LCD back-light off. * ); * * if( xBacklightTimer == NULL ) * { * // The timer was not created. * } * else * { * // Start the timer. No block time is specified, and even if one was * // it would be ignored because the scheduler has not yet been * // started. * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) * { * // The timer could not be set into the Active state. * } * } * * // ... * // Create tasks here. * // ... * * // Starting the scheduler will start the timer running as it has already * // been set into the active state. * rtos_sched_start(); * * // Should not reach here. * for( ;; ); * } * @endverbatim */ #define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( millis() ), NULL, ( xTicksToWait ) ) /** * int32_t xTimerStartFromISR( TimerHandle_t xTimer, * int32_t *pxHigherPriorityTaskWoken ); * * A version of xTimerStart() that can be called from an interrupt service * routine. * * @param xTimer The handle of the timer being started/restarted. * * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most * of its time in the Blocked state, waiting for messages to arrive on the timer * command queue. Calling xTimerStartFromISR() writes a message to the timer * command queue, so has the potential to transition the timer service/daemon * task out of the Blocked state. If calling xTimerStartFromISR() causes the * timer service/daemon task to leave the Blocked state, and the timer service/ * daemon task has a priority equal to or greater than the currently executing * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will * get set to pdTRUE internally within the xTimerStartFromISR() function. If * xTimerStartFromISR() sets this value to pdTRUE then a context switch should * be performed before the interrupt exits. * * @return pdFAIL will be returned if the start command could not be sent to * the timer command queue. pdPASS will be returned if the command was * successfully sent to the timer command queue. When the command is actually * processed will depend on the priority of the timer service/daemon task * relative to other tasks in the system, although the timers expiry time is * relative to when xTimerStartFromISR() is actually called. The timer * service/daemon task priority is set by the configTIMER_TASK_PRIORITY * configuration constant. * * Example usage: * @verbatim * // This scenario assumes xBacklightTimer has already been created. When a * // key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer, and unlike the example given for * // the xTimerReset() function, the key press event handler is an interrupt * // service routine. * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press interrupt service routine. * void vKeyPressEventInterruptHandler( void ) * { * int32_t xHigherPriorityTaskWoken = pdFALSE; * * // Ensure the LCD back-light is on, then restart the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. This is an interrupt service routine so can only * // call FreeRTOS API functions that end in "FromISR". * vSetBacklightState( BACKLIGHT_ON ); * * // xTimerStartFromISR() or xTimerResetFromISR() could be called here * // as both cause the timer to re-calculate its expiry time. * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was * // declared (in this function). * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The start command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * @endverbatim */ #define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) /** * int32_t xTimerStopFromISR( TimerHandle_t xTimer, * int32_t *pxHigherPriorityTaskWoken ); * * A version of xTimerStop() that can be called from an interrupt service * routine. * * @param xTimer The handle of the timer being stopped. * * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most * of its time in the Blocked state, waiting for messages to arrive on the timer * command queue. Calling xTimerStopFromISR() writes a message to the timer * command queue, so has the potential to transition the timer service/daemon * task out of the Blocked state. If calling xTimerStopFromISR() causes the * timer service/daemon task to leave the Blocked state, and the timer service/ * daemon task has a priority equal to or greater than the currently executing * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will * get set to pdTRUE internally within the xTimerStopFromISR() function. If * xTimerStopFromISR() sets this value to pdTRUE then a context switch should * be performed before the interrupt exits. * * @return pdFAIL will be returned if the stop command could not be sent to * the timer command queue. pdPASS will be returned if the command was * successfully sent to the timer command queue. When the command is actually * processed will depend on the priority of the timer service/daemon task * relative to other tasks in the system. The timer service/daemon task * priority is set by the configTIMER_TASK_PRIORITY configuration constant. * * Example usage: * @verbatim * // This scenario assumes xTimer has already been created and started. When * // an interrupt occurs, the timer should be simply stopped. * * // The interrupt service routine that stops the timer. * void vAnExampleInterruptServiceRoutine( void ) * { * int32_t xHigherPriorityTaskWoken = pdFALSE; * * // The interrupt has occurred - simply stop the timer. * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined * // (within this function). As this is an interrupt service routine, only * // FreeRTOS API functions that end in "FromISR" can be used. * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The stop command was not executed successfully. Take appropriate * // action here. * } * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * @endverbatim */ #define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U ) /** * int32_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, * uint32_t xNewPeriod, * int32_t *pxHigherPriorityTaskWoken ); * * A version of xTimerChangePeriod() that can be called from an interrupt * service routine. * * @param xTimer The handle of the timer that is having its period changed. * * @param xNewPeriod The new period for xTimer. Timer periods are specified in * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time * that has been specified in milliseconds. For example, if the timer must * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, * if the timer must expire after 500ms, then xNewPeriod can be set to * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than * or equal to 1000. * * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most * of its time in the Blocked state, waiting for messages to arrive on the timer * command queue. Calling xTimerChangePeriodFromISR() writes a message to the * timer command queue, so has the potential to transition the timer service/ * daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() * causes the timer service/daemon task to leave the Blocked state, and the * timer service/daemon task has a priority equal to or greater than the * currently executing task (the task that was interrupted), then * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the * xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets * this value to pdTRUE then a context switch should be performed before the * interrupt exits. * * @return pdFAIL will be returned if the command to change the timers period * could not be sent to the timer command queue. pdPASS will be returned if the * command was successfully sent to the timer command queue. When the command * is actually processed will depend on the priority of the timer service/daemon * task relative to other tasks in the system. The timer service/daemon task * priority is set by the configTIMER_TASK_PRIORITY configuration constant. * * Example usage: * @verbatim * // This scenario assumes xTimer has already been created and started. When * // an interrupt occurs, the period of xTimer should be changed to 500ms. * * // The interrupt service routine that changes the period of xTimer. * void vAnExampleInterruptServiceRoutine( void ) * { * int32_t xHigherPriorityTaskWoken = pdFALSE; * * // The interrupt has occurred - change the period of xTimer to 500ms. * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined * // (within this function). As this is an interrupt service routine, only * // FreeRTOS API functions that end in "FromISR" can be used. * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The command to change the timers period was not executed * // successfully. Take appropriate action here. * } * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * @endverbatim */ #define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) /** * int32_t xTimerResetFromISR( TimerHandle_t xTimer, * int32_t *pxHigherPriorityTaskWoken ); * * A version of xTimerReset() that can be called from an interrupt service * routine. * * @param xTimer The handle of the timer that is to be started, reset, or * restarted. * * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most * of its time in the Blocked state, waiting for messages to arrive on the timer * command queue. Calling xTimerResetFromISR() writes a message to the timer * command queue, so has the potential to transition the timer service/daemon * task out of the Blocked state. If calling xTimerResetFromISR() causes the * timer service/daemon task to leave the Blocked state, and the timer service/ * daemon task has a priority equal to or greater than the currently executing * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will * get set to pdTRUE internally within the xTimerResetFromISR() function. If * xTimerResetFromISR() sets this value to pdTRUE then a context switch should * be performed before the interrupt exits. * * @return pdFAIL will be returned if the reset command could not be sent to * the timer command queue. pdPASS will be returned if the command was * successfully sent to the timer command queue. When the command is actually * processed will depend on the priority of the timer service/daemon task * relative to other tasks in the system, although the timers expiry time is * relative to when xTimerResetFromISR() is actually called. The timer service/daemon * task priority is set by the configTIMER_TASK_PRIORITY configuration constant. * * Example usage: * @verbatim * // This scenario assumes xBacklightTimer has already been created. When a * // key is pressed, an LCD back-light is switched on. If 5 seconds pass * // without a key being pressed, then the LCD back-light is switched off. In * // this case, the timer is a one-shot timer, and unlike the example given for * // the xTimerReset() function, the key press event handler is an interrupt * // service routine. * * // The callback function assigned to the one-shot timer. In this case the * // parameter is not used. * void vBacklightTimerCallback( TimerHandle_t pxTimer ) * { * // The timer expired, therefore 5 seconds must have passed since a key * // was pressed. Switch off the LCD back-light. * vSetBacklightState( BACKLIGHT_OFF ); * } * * // The key press interrupt service routine. * void vKeyPressEventInterruptHandler( void ) * { * int32_t xHigherPriorityTaskWoken = pdFALSE; * * // Ensure the LCD back-light is on, then reset the timer that is * // responsible for turning the back-light off after 5 seconds of * // key inactivity. This is an interrupt service routine so can only * // call FreeRTOS API functions that end in "FromISR". * vSetBacklightState( BACKLIGHT_ON ); * * // xTimerStartFromISR() or xTimerResetFromISR() could be called here * // as both cause the timer to re-calculate its expiry time. * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was * // declared (in this function). * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) * { * // The reset command was not executed successfully. Take appropriate * // action here. * } * * // Perform the rest of the key processing here. * * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch * // should be performed. The syntax required to perform a context switch * // from inside an ISR varies from port to port, and from compiler to * // compiler. Inspect the demos for the port you are using to find the * // actual syntax required. * if( xHigherPriorityTaskWoken != pdFALSE ) * { * // Call the interrupt safe yield function here (actual function * // depends on the FreeRTOS port being used). * } * } * @endverbatim */ #define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) /** * int32_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, * void *pvParameter1, * uint32_t ulParameter2, * int32_t *pxHigherPriorityTaskWoken ); * * * Used from application interrupt service routines to defer the execution of a * function to the RTOS daemon task (the timer service task, hence this function * is implemented in timers.c and is prefixed with 'Timer'). * * Ideally an interrupt service routine (ISR) is kept as short as possible, but * sometimes an ISR either has a lot of processing to do, or needs to perform * processing that is not deterministic. In these cases * xTimerPendFunctionCallFromISR() can be used to defer processing of a function * to the RTOS daemon task. * * A mechanism is provided that allows the interrupt to return directly to the * task that will subsequently execute the pended callback function. This * allows the callback function to execute contiguously in time with the * interrupt - just as if the callback had executed in the interrupt itself. * * @param xFunctionToPend The function to execute from the timer service/ * daemon task. The function must conform to the PendedFunction_t * prototype. * * @param pvParameter1 The value of the callback function's first parameter. * The parameter has a void * type to allow it to be used to pass any type. * For example, unsigned longs can be cast to a void *, or the void * can be * used to point to a structure. * * @param ulParameter2 The value of the callback function's second parameter. * * @param pxHigherPriorityTaskWoken As mentioned above, calling this function * will result in a message being sent to the timer daemon task. If the * priority of the timer daemon task (which is set using * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of * the currently running task (the task the interrupt interrupted) then * *pxHigherPriorityTaskWoken will be set to pdTRUE within * xTimerPendFunctionCallFromISR(), indicating that a context switch should be * requested before the interrupt exits. For that reason * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the * example code below. * * @return pdPASS is returned if the message was successfully sent to the * timer daemon task, otherwise pdFALSE is returned. * * Example usage: * @verbatim * * // The callback function that will execute in the context of the daemon task. * // Note callback functions must all use this same prototype. * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) * { * int32_t xInterfaceToService; * * // The interface that requires servicing is passed in the second * // parameter. The first parameter is not used in this case. * xInterfaceToService = ( int32_t ) ulParameter2; * * // ...Perform the processing here... * } * * // An ISR that receives data packets from multiple interfaces * void vAnISR( void ) * { * int32_t xInterfaceToService, xHigherPriorityTaskWoken; * * // Query the hardware to determine which interface needs processing. * xInterfaceToService = prvCheckInterfaces(); * * // The actual processing is to be deferred to a task. Request the * // vProcessInterface() callback function is executed, passing in the * // number of the interface that needs processing. The interface to * // service is passed in the second parameter. The first parameter is * // not used in this case. * xHigherPriorityTaskWoken = pdFALSE; * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); * * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context * // switch should be requested. The macro used is port specific and will * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to * // the documentation page for the port being used. * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); * * } * @endverbatim */ int32_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, int32_t *pxHigherPriorityTaskWoken ) ; /** * int32_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, * void *pvParameter1, * uint32_t ulParameter2, * uint32_t xTicksToWait ); * * * Used to defer the execution of a function to the RTOS daemon task (the timer * service task, hence this function is implemented in timers.c and is prefixed * with 'Timer'). * * @param xFunctionToPend The function to execute from the timer service/ * daemon task. The function must conform to the PendedFunction_t * prototype. * * @param pvParameter1 The value of the callback function's first parameter. * The parameter has a void * type to allow it to be used to pass any type. * For example, unsigned longs can be cast to a void *, or the void * can be * used to point to a structure. * * @param ulParameter2 The value of the callback function's second parameter. * * @param xTicksToWait Calling this function will result in a message being * sent to the timer daemon task on a queue. xTicksToWait is the amount of * time the calling task should remain in the Blocked state (so not using any * processing time) for space to become available on the timer queue if the * queue is found to be full. * * @return pdPASS is returned if the message was successfully sent to the * timer daemon task, otherwise pdFALSE is returned. * */ int32_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, uint32_t xTicksToWait ) ; /** * const char * const pcTimerGetName( TimerHandle_t xTimer ); * * Returns the name that was assigned to a timer when the timer was created. * * @param xTimer The handle of the timer being queried. * * @return The name assigned to the timer specified by the xTimer parameter. */ const char * pcTimerGetName( TimerHandle_t xTimer ) ; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ /** * uint32_t xTimerGetPeriod( TimerHandle_t xTimer ); * * Returns the period of a timer. * * @param xTimer The handle of the timer being queried. * * @return The period of the timer in ticks. */ uint32_t xTimerGetPeriod( TimerHandle_t xTimer ) ; /** * uint32_t xTimerGetExpiryTime( TimerHandle_t xTimer ); * * Returns the time in ticks at which the timer will expire. If this is less * than the current tick count then the expiry time has overflowed from the * current time. * * @param xTimer The handle of the timer being queried. * * @return If the timer is running then the time in ticks at which the timer * will next expire is returned. If the timer is not running then the return * value is undefined. */ uint32_t xTimerGetExpiryTime( TimerHandle_t xTimer ) ; /* * Functions beyond this part are not part of the public API and are intended * for use by the kernel only. */ int32_t xTimerCreateTimerTask( void ) ; int32_t xTimerGenericCommand( TimerHandle_t xTimer, const int32_t xCommandID, const uint32_t xOptionalValue, int32_t * const pxHigherPriorityTaskWoken, const uint32_t xTicksToWait ) ; #if( configUSE_TRACE_FACILITY == 1 ) void vTimerSetTimerNumber( TimerHandle_t xTimer, uint32_t uxTimerNumber ) ; uint32_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) ; #endif #ifdef __cplusplus } #endif #endif /* TIMERS_H */ ================================================ FILE: include/system/dev/banners.h ================================================ /** * \file system/dev/banners.h * * PROS banners printed over serial line * * This file should only be included ONCE (in system/dev/serial_daemon.c) * * See system/dev/serial_daemon.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once // The banners look extra messed up due to the ANSI escape sequences and needing // to escape backslashes and quotes static char const* const short_banner = "\n\n\n" "  _____ _____ ____ _____ \n" " | __ \\| __ \\ / __ \\ / ____| Powered by " "PROS for VEX V5\n" " | |__) | |__) | | | | (___  Version: %29s\n" " | ___/| _ /| | | |\\___ \\  Uptime: %23lu.%03lu " "s\n" " | | | | \\ \\| |__| |____) | Compiled: %29s\n" " |_| |_| \\_\\\\____/|_____/  Directory:%29s\n" "\n\n"; static char const* const large_banner = "\n\n\n" " _+=+_\n" "  .-` . `-.  8888888b. 8888888b. .d88888b. " ".d8888b.\n" "  _+` \" `+_  888 Y88b 888 Y88b d88P\" " "\"Y88b d88P Y88b\n" " \\\\\\sssssssssssss/// 888 888 888 888 888 " "888 Y88b.\n" " .ss\\ * /ss. 888 d88P 888 d88P " "888 888 \"Y888b.\n" " .+bm .s * s. md+. " "8888888P\" 8888888P\" 888 888 " "\"Y88b.\n" ".hMMMMs . * . sMMMMh. 888 " " 888 T88b 888 888 " "\"888\n" " `\\hMMMb \\ | / dMMMh: " "888 888 T88b Y88b. .d88P Y88b " "d88P\n" " -SNMNo - oNMNs- 888 " "888 T88b \"Y88888P\" \"Y8888P\"\n" " `+dMh\\./dMd/\n" " `:yNy:` Powered by PROS " "for VEX V5\n" " \" Copyright (c) Purdue University " "ACM SIGBots\n" "Version:%13s Platform: V%d.%d.%d (b%d) " "Uptime:%5lu.%03lu s\n" "Compiled: %20s Directory: %22s\n" "\n\n"; ================================================ FILE: include/system/dev/dev.h ================================================ /** * \file system/dev/dev.h * * Generic Serial Device driver header * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "vfs.h" extern const struct fs_driver* const dev_driver; int dev_open_r(struct _reent* r, const char* path, int flags, int mode); void dev_initialize(void); ================================================ FILE: include/system/dev/ser.h ================================================ /** * \file system/dev/ser.h * * Serial driver header * * See system/dev/ser_driver.c and system/dev/ser_daemon.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "vfs.h" extern const struct fs_driver* const ser_driver; int ser_open_r(struct _reent* r, const char* path, int flags, int mode); void ser_initialize(void); ================================================ FILE: include/system/dev/usd.h ================================================ /** * \file system/dev/usd.h * * microSD card driver header * * See system/dev/usd_driver.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "vfs.h" extern const struct fs_driver* const usd_driver; int usd_open_r(struct _reent* r, const char* path, int flags, int mode); void usd_initialize(void); ================================================ FILE: include/system/dev/vfs.h ================================================ /** * \file system/dev/vfs.h * * Virtual File System header * * See system/dev/vfs.c for discussion * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include #include #include #include struct fs_driver { ssize_t (*read_r)(struct _reent*, void* const, uint8_t*, const size_t); int (*write_r)(struct _reent*, void* const, const uint8_t*, const size_t); int (*close_r)(struct _reent*, void* const); int (*fstat_r)(struct _reent*, void* const, struct stat*); int (*isatty_r)(struct _reent*, void* const); off_t (*lseek_r)(struct _reent*, void* const, off_t, int); int (*ctl)(void* const, const uint32_t, void* const); }; struct file_entry { struct fs_driver const* driver; void* arg; }; // adds an entry to the file table int vfs_add_entry_r(struct _reent* r, struct fs_driver const* const driver, void* arg); // update an entry to the file table. Returns -1 if there was an error. // If driver is NULL, then the driver isn't updated. If arg is (void*)-1, then // the arg isn't updated. int vfs_update_entry(int file, struct fs_driver const* const driver, void* arg); ================================================ FILE: include/system/hot.h ================================================ #pragma once struct hot_table { char const* compile_timestamp; char const* compile_directory; void* __exidx_start; void* __exidx_end; struct { #define FUNC(F) void (*F)(); #include "system/user_functions/list.h" #undef FUNC } functions; }; extern struct hot_table* const HOT_TABLE; ================================================ FILE: include/system/optimizers.h ================================================ /** * \file system/optimizers.h * * Optimizers for the kernel * * Probably shouldn't use anything from this header * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once // See https://stackoverflow.com/q/109710 for discussion #define likely(cond) __builtin_expect(!!(cond), 1) #define unlikely(cond) __builtin_expect(!!(cond), 0) ================================================ FILE: include/system/user_functions/c_list.h ================================================ #ifndef FUNC #error "FUNC must be defined" #endif FUNC(autonomous) FUNC(initialize) FUNC(opcontrol) FUNC(disabled) FUNC(competition_initialize) ================================================ FILE: include/system/user_functions/cpp_list.h ================================================ #ifndef FUNC #error "FUNC must be defined" #endif FUNC(cpp_autonomous) FUNC(cpp_initialize) FUNC(cpp_opcontrol) FUNC(cpp_disabled) FUNC(cpp_competition_initialize) ================================================ FILE: include/system/user_functions/list.h ================================================ #ifndef FUNC #error "FUNC must be defined" #endif #include "system/user_functions/c_list.h" #include "system/user_functions/cpp_list.h" ================================================ FILE: include/system/user_functions.h ================================================ #pragma once #define FUNC(F) void user_ ##F(); #include "system/user_functions/list.h" #undef FUNC ================================================ FILE: include/vdml/port.h ================================================ /** * \file devices/port.h * * This file contains the standard header info for port macros and bit masks, * used mostly for the adi expander. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #define SMART_PORT_BITS 16 #define SMART_PORT_MASK ((1 << SMART_PORT_BITS) - 1) /** * Macro Description: Given a merged ports variable, it sets the smart port and adi port to the values inside the * int32_t. */ #define get_ports(ports, smart_port, adi_port) \ { \ uint32_t uport = (uint32_t)ports; \ smart_port = uport & SMART_PORT_MASK; \ adi_port = uport >> SMART_PORT_BITS; \ } static inline uint32_t merge_adi_ports(uint8_t smart_port, uint8_t adi_port) { return (adi_port << SMART_PORT_BITS) | smart_port; } ================================================ FILE: include/vdml/registry.h ================================================ /** * \file vdml/registry.h * * This file contains the standard header info for the VDML (Vex Data Management * Layer) registry. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "pros/apix.h" #include "v5_api.h" #include "vdml/vdml.h" #ifdef __cplusplus #define v5_device_e_t pros::c::v5_device_e_t extern "C" { #endif typedef struct { v5_device_e_t device_type; V5_DeviceT device_info; uint8_t pad[128]; // 16 bytes in adi_data_s_t times 8 ADI Ports = 128 } v5_smart_device_s_t; /* * Detects the devices that are plugged in. * * Pulls the type names of plugged-in devices and stores them in the buffer * registry_types. */ void registry_update_types(); /* * Returns the information on the device registered to the port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * * \param port * The V5 port number from 1-21 * * \return A struct containing the device type and the info needed for api * functions */ v5_smart_device_s_t* registry_get_device(uint8_t port); /* * Returns the information on the device registered to the port. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * * \param port * The V5 port number from 0-32 * * \return A struct containing the device type and the info needed for api * functions */ v5_smart_device_s_t* registry_get_device_internal(uint8_t port); /* * Checks whether there is a discrepancy between the binding of the port and * what is actually plugged in. * * If a device is plugged in but not registered, registers the port. * If a device is not plugged in and a device is registered, warns the user. * If one type of device is registered but another is plugged in, warns the user. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * * \param port * The V5 port number from 1-21 * \param expected_t * The expected type (i.e., the type of function being called. If * E_DEVICE_NONE, indicates that background processing is calling this, * and a mismatch will only occur if there is an actual discrepancy * between what is registered and what is plugged in. * * \return 0 if the device registered matches the device plugged and the * expected device matches both of those or is E_DEVICE_NONE, 1 if the * registered device is not plugged in, and 2 if there is a mismatch. PROS_ERR * on exception. */ int32_t registry_validate_binding(uint8_t port, v5_device_e_t expected_t); #ifdef __cplusplus } #undef v5_device_e_t #endif ================================================ FILE: include/vdml/vdml.h ================================================ /** * \file vdml/vdml.h * * This file contains all types and functions used throughout multiple VDML * (Vex Data Management Layer) files. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include #include #include "vdml/registry.h" #ifdef __cplusplus #define v5_device_e_t pros::c::v5_device_e_t #endif #ifdef __cplusplus extern "C" { #endif /** * Macro, returns true if the port is in range of user configurable ports, * false otherwise. */ #define VALIDATE_PORT_NO(PORT) ((PORT) >= 0 && (PORT) < NUM_V5_PORTS) #define VALIDATE_PORT_NO_INTERNAL(PORT) ((PORT) >= 0 && (PORT) < V5_MAX_DEVICE_PORTS) /** * Macro that handles error checking, sanity checking, automatic registration, * and mutex taking for all of the motor wrapper functions. * If port is out of range, the calling function sets errno and returns. * If a port isn't yet registered, it registered as a motor automatically. * If a mutex cannot be taken, errno is set to EACCES (access denied) and * returns. * * \param port * The V5 port number from 0-20 * \param device_type * The v5_device_e_t that the port is configured as * \param error_code * The error code that return if error checking failed */ #define claim_port(port, device_type, error_code) \ if (registry_validate_binding(port, device_type) != 0) { \ return error_code; \ } \ v5_smart_device_s_t* device = registry_get_device(port); \ if (!port_mutex_take(port)) { \ errno = EACCES; \ return error_code; \ } /** * Function like claim_port. This macro should only be used in functions * that return int32_t or enums as PROS_ERR could be returned. * * \param port * The V5 port number from 0-20 * \param device_type * The v5_device_e_t that the port is configured as */ #define claim_port_i(port, device_type) claim_port(port, device_type, PROS_ERR) /** * Function like claim_port. This macro should only be used in functions * that return double or float as PROS_ERR_F could be returned. * * \param port * The V5 port number from 0-20 * \param device_type * The v5_device_e_t that the port is configured as */ #define claim_port_f(port, device_type) claim_port(port, device_type, PROS_ERR_F) /** * A function that executes claim_port and allows you to execute a block of * code if an error occurs. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (1-21). * EACCES - Another resource is currently trying to access the port. * * \param port * The V5 port number from 0-20 * \param device_type * The v5_device_e_t that the port is configured as * * \return 1 if the operation was successful or 0 if the operation * failed, setting errno. */ int32_t claim_port_try(uint8_t port, v5_device_e_t type); /** * Macro that release the mutex for the given port and sets errno to 0 if the * function is an accessor wrapper whos return value is PROS_ERR or PROS_ERR_F. * * \param port * The V5 port number from 0-20 * \param rtn * The desired return value * * \return The rtn parameter */ #define return_port(port, rtn) \ port_mutex_give(port); \ return rtn; /** * Bitmap to indicate if a port has had an error printed or not. */ extern int32_t port_errors; /** * Sets the port's bit to 1, indicating there has already been an error on this * port. * * \param port * The V5 port number to set from 0-20 */ void vdml_set_port_error(uint8_t port); /** * Sets the port's bit to 0, effectively resetting it. * * \param port * The V5 port number to unset from 0-20 */ void vdml_unset_port_error(uint8_t port); /** * Gets the error bit for the port, indicating whether or not there has been an * error on this port. * * \param port * The V5 port number to check from 0-20 * * \return True if the port's bit is set, false otherwise. */ bool vdml_get_port_error(uint8_t port); /** * Claims the mutex for the given port. * * Reserves the mutex for this port. Any other tasks trying to access this port * will block until the mutex is returned. If a higher-priortiy task attempts * to claim this port, the task which has the port claimed will temporarily be * raised to an equal priority until the mutex is given, reducing the impact of * the delay. See FreeRTOS documentation for more details. * * This MUST be called before any call to the v5 api to maintain thread saftey. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-20). * * \param port * The V5 port number to claim from 0-20 * * \return 1 if the mutex was successfully taken, 0 if not, -1 if port is * invalid. */ int port_mutex_take(uint8_t port); /** * Returns the mutex for the given port. * * Frees the mutex for this port, allowing other tasks to continue. * * WARNING: If a mutex was claimed by a task, this MUST be called immediately * after the port is no longer needed by that task in order to prevent delays in * other tasks. * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-20). * * \param port * The V5 port number to free from 0-20 */ int port_mutex_give(uint8_t port); /** * Executes port_mutex_take() for all of the V5 Smart Ports. */ void port_mutex_take_all(); /** * Executes port_mutex_give() for all of the V5 Smart Ports. */ void port_mutex_give_all(); /** * Obtains a port mutex with bounds checking for V5_MAX_PORTS (32) not user * exposed device ports (20). Intended for internal usage for protecting * thread-safety on devices such as the controller and battery * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-32). * * \param port * The V5 port number from 0-32 * * \return True if the mutex was successfully taken, false otherwise. If false * is returned, then errno is set with a hint about why the the mutex * couldn't be taken. */ int internal_port_mutex_take(uint8_t port); /** * Returns a port mutex with bounds checking for V5_MAX_PORTS (32) not user * exposed device ports (20). Intended for internal usage for protecting * thread-safety on devices such as the controller and battery * * This function uses the following values of errno when an error state is * reached: * ENXIO - The given value is not within the range of V5 ports (0-32). * * \param port * The V5 port number from 0-32 * * \return True if the mutex was successfully returned, false otherwise. If * false is returned, then errno is set with a hint about why the mutex * couldn't be returned. */ int internal_port_mutex_give(uint8_t port); #define V5_PORT_BATTERY 24 #define V5_PORT_CONTROLLER_1 25 #define V5_PORT_CONTROLLER_2 26 #ifdef __cplusplus } #undef v5_device_e_t #endif ================================================ FILE: libv5rts-strip-options.txt ================================================ -N open -N _fstat -N fcntl -N lseek -N read -N write -N isatty -R .ARM.attributes ================================================ FILE: patch_headers.py ================================================ ''' Adds __attribute__((pcs("aapcs")) to all sdk function declarations to allow properly linking with the sdk (which uses the soft float abi) when building pros with the hard float abi ''' from os import listdir, makedirs from os.path import isfile, join, exists, dirname, realpath def print_and_exit(message): print(message) print("Failed to patch libv5rts") exit(1) # get the current directory try: current_dir = dirname(realpath(__file__)) except: print_and_exit("Could not get working directory!") # set the include path and the include path of the patched SDK include_path = current_dir + "/firmware/libv5rts/sdk/vexv5/include/" patched_include_path = current_dir + "/firmware/libv5rts/sdk/vexv5/patched_include/" # create the include path if it does not exist already if exists(patched_include_path): print("libv5rts already patched") exit(0) else: try: makedirs(patched_include_path) except: print_and_exit("Could not create directory for patched libv5rts") # get a list of files in the include path try: all_files = listdir(include_path) except: print_and_exit("Error getting directories and files in include path") files = [] for f in all_files: if isfile(join(include_path, f)) and str(f).endswith(".h"): files.append(f) # patch headers for file_name in files: header_file = "" output = "" skip_next_line = False try: with open(join(include_path, file_name), "r") as file: header_file = file.read() except: print_and_exit("Failed to open file in v5rts") for line in header_file.splitlines(): if skip_next_line: # This line is a macro continuation if not line.endswith(("\\")): # macro continuation ends here skip_next_line = False continue if line.strip().startswith(("/", "*")): # it's a comment output += f"{line}\n" continue if line.strip().startswith(("#")): # it's a preprocessor directive output += f"{line}\n" if line.endswith(("\\")): skip_next_line = True continue if line.strip().startswith(("}", "{", "extern")): # it's an extern c block or struct definition output += f"{line}\n" continue if line.strip().startswith(("typedef", "struct", "enum")): # it's a struct/enum definition or typedef output += f"{line}\n" continue if not line or line.isspace(): # it's blank output += f"{line}\n" continue if ");" not in line: # just in case something that isn't a function slips past the previous checks # ");" should only occur in a function definition output += f"{line}\n" continue output += f"__attribute__((pcs(\"aapcs\"))) {line}\n" try: with open(join(patched_include_path, file_name), "w") as file: file.write(output) except: print_and_exit("Failed to write patched file") print("libv5rts patched successfully") ================================================ FILE: project.pros ================================================ {"py/object": "pros.conductor.project.Project", "py/state": {"project_name": "kernel-dev", "target": "v5", "templates": {"kernel": {"py/object": "pros.conductor.templates.local_template.LocalTemplate", "location": "./template", "metadata": {"origin": "local", "output": "bin/monolith.bin", "hot_output": "bin/hot.package.bin", "cold_output": "bin/cold.package.bin", "cold_addr": 58720256, "hot_addr": 125829120}, "name": "kernel", "supported_kernels": null, "system_files": [], "target": "v5", "user_files": [], "version": "3.0.0-beta1"}}, "upload_options": {}}} ================================================ FILE: public_symbols.txt ================================================ millis task_create task_delete task_delay task_delay_until task_get_priority task_set_priority task_get_state task_suspend task_resume task_get_count task_get_name task_get_by_name task_notify task_notify_ext task_notify_take task_notify_clear mutex_create mutex_take mutex_give sem_create sem_wait sem_post task_abort_delay sem_binary_create mutex_recursive_create mutex_recursive_take mutex_recursive_give mutex_get_owner sem_get_count queue_create queue_prepend queue_append queue_peek queue_recv queue_get_waiting queue_get_available queue_delete queue_reset ================================================ FILE: src/common/README.md ================================================ # Common Facilities This folder contains common facilities used throughout the PROS 3 kernel, such as JSON parsing. ================================================ FILE: src/common/cobs.c ================================================ /** * \file common/cobs.c * * Consistent Overhead Byte Stuffing * * Contains an implementation of Consistent Overhead Byte Stuffing, adapted from * https://github.com/jacquesf/COBS-Consistent-Overhead-Byte-Stuffing * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "cobs.h" size_t cobs_encode_measure(const uint8_t* restrict src, const size_t src_len, const uint32_t prefix) { size_t read_idx = 0; size_t write_idx = 1; uint8_t code = 1; uint8_t* prefix_bytes = (uint8_t*)&(prefix); for (read_idx = 0; read_idx < 4; read_idx++) { if (prefix_bytes[read_idx] == 0) { code = 1; write_idx++; } else { write_idx++; code++; // code will never be 0xff since the length will always be 4 } } read_idx = 0; while (read_idx < src_len) { if (src[read_idx] == 0) { code = 1; write_idx++; read_idx++; } else { write_idx++; read_idx++; code++; if (code == 0xff) { code = 1; write_idx++; } } } return write_idx; } int cobs_encode(uint8_t* restrict dest, const uint8_t* restrict src, const size_t src_len, const uint32_t prefix) { size_t read_idx = 0; size_t write_idx = 1; size_t code_idx = 0; uint8_t code = 1; uint8_t* prefix_bytes = (uint8_t*)&prefix; for (read_idx = 0; read_idx < 4;) { if (prefix_bytes[read_idx] == 0) { dest[code_idx] = code; code = 1; code_idx = write_idx++; read_idx++; } else { dest[write_idx++] = prefix_bytes[read_idx++]; code++; // code will never be 0xff since the length of the prefix is 4 } } read_idx = 0; while (read_idx < src_len) { if (src[read_idx] == 0) { dest[code_idx] = code; code = 1; code_idx = write_idx++; read_idx++; } else { dest[write_idx++] = src[read_idx++]; code++; if (code == 0xff) { dest[code_idx] = code; code = 1; code_idx = write_idx++; } } } dest[code_idx] = code; return write_idx; } ================================================ FILE: src/common/gid.c ================================================ /** * \file gid.c * * Globally Unique Identifiers Map * * Contains an implementation to efficiently assign globally unique IDs * e.g. to assign entries in a global table * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include "common/gid.h" #include "kapi.h" // Note: the V5 is a 32-bit architecture, so we'll use 32-bit integers void gid_init(struct gid_metadata* const metadata) { // metadata arguments aren't checked for correctness since this is an // internal data structure size_t i; for (i = 0; i < metadata->bitmap_size; i++) { metadata->bitmap[i] = ~0; } metadata->bitmap[0] = (~0 << (metadata->reserved)); metadata->_lock = mutex_create(); return; } uint32_t gid_alloc(struct gid_metadata* const metadata) { if (mutex_take(metadata->_lock, TIMEOUT_MAX)) { size_t i; uint32_t gid = 0; uint32_t* gid_word = NULL; uint32_t gid_idx = 0; // check if the _cur_val + 1 is free if (!gid_check(metadata, (metadata->_cur_val + 1) % metadata->max)) { // that gid was free! so allocate it gid = metadata->_cur_val = (metadata->_cur_val + 1) % metadata->max; gid_word = metadata->bitmap + (gid / UINT32_WIDTH); gid_idx = gid % UINT32_WIDTH; goto return_gid; } else { for (i = 0; i < metadata->bitmap_size; i++) { gid_word = metadata->bitmap + i; if (*gid_word == 0) { // all GIDs in this word are assigned continue; } // __builtin_ctz counts trailing zeros. This effectively returns the // position of the first unassigned gid withing the word gid_idx = __builtin_ctz(*gid_word); gid = gid_idx + (i * UINT32_WIDTH); // mark the id as allocated goto return_gid; } } return_gid: if (gid > metadata->max || gid == 0) { mutex_give(metadata->_lock); return 0; } *gid_word &= ~(1 << gid_idx); metadata->_cur_val = gid; mutex_give(metadata->_lock); return gid; } return 0; } void gid_free(struct gid_metadata* const metadata, uint32_t id) { if (id > metadata->max || id == 0) { return; } size_t word_idx = id / UINT32_WIDTH; metadata->bitmap[word_idx] |= 1 << (id % UINT32_WIDTH); } bool gid_check(struct gid_metadata* metadata, uint32_t id) { if (id > metadata->max) { return false; } size_t word_idx = id / UINT32_WIDTH; return (metadata->bitmap[word_idx] & (1 << (id % UINT32_WIDTH))) ? false : true; } ================================================ FILE: src/common/linkedlist.c ================================================ /* * \file common/linkedlist.c * * Linked list implementation for internal use * * This file defines a linked list implementation that operates on the FreeRTOS * heap, and is able to generically store function pointers and data * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include // NULL #include "common/linkedlist.h" #include "kapi.h" // NOTE: Do not intermix data and function payloads. This may cause data to be // re-evaluated as a pointer to an area in memory and a false free or add. ll_node_s_t* linked_list_init_func_node(generic_fn_t func) { ll_node_s_t* node = (ll_node_s_t*)kmalloc(sizeof *node); node->payload.func = func; node->next = NULL; return node; } ll_node_s_t* linked_list_init_data_node(void* data) { ll_node_s_t* node = (ll_node_s_t*)kmalloc(sizeof *node); node->payload.data = data; node->next = NULL; return node; } linked_list_s_t* linked_list_init() { linked_list_s_t* list = (linked_list_s_t*)kmalloc(sizeof *list); list->head = NULL; return list; } void linked_list_prepend_func(linked_list_s_t* list, generic_fn_t func) { if (list == NULL) list = linked_list_init(); ll_node_s_t* n = linked_list_init_func_node(func); n->next = list->head; list->head = n; } void linked_list_prepend_data(linked_list_s_t* list, void* data) { if (list == NULL) list = linked_list_init(); ll_node_s_t* n = linked_list_init_data_node(data); n->next = list->head; list->head = n; } void linked_list_append_func(linked_list_s_t* list, generic_fn_t func) { if (list == NULL) list = linked_list_init(); ll_node_s_t* n = linked_list_init_func_node(func); if (list->head == NULL) { list->head = n; return; } ll_node_s_t* it = list->head; while (it->next != NULL) it = it->next; it->next = n; } void linked_list_remove_func(linked_list_s_t* list, generic_fn_t func) { if (list == NULL || list->head == NULL) return; ll_node_s_t* it = list->head; ll_node_s_t* p = NULL; while (it != NULL) { if (it->payload.func == func) { if (p == NULL) list->head = it->next; else p->next = it->next; kfree(it); break; } p = it; it = it->next; } } void linked_list_append_data(linked_list_s_t* list, void* data) { if (list == NULL) list = linked_list_init(); ll_node_s_t* n = linked_list_init_data_node(data); if (list->head == NULL) { list->head = n; return; } ll_node_s_t* it = list->head; while (it->next != NULL) it = it->next; it->next = n; } void linked_list_remove_data(linked_list_s_t* list, void* data) { if (list == NULL || list->head == NULL) return; ll_node_s_t* it = list->head; ll_node_s_t* p = NULL; while (it != NULL) { if (it->payload.data == data) { if (p == NULL) list->head = it->next; else p->next = it->next; kfree(it); break; } p = it; it = it->next; } } void linked_list_foreach(linked_list_s_t* list, linked_list_foreach_fn_t cb, void* extra_data) { if (list == NULL || list->head == NULL) return; ll_node_s_t* it = list->head; while (it != NULL) { cb(it, extra_data); it = it->next; } } void linked_list_free(linked_list_s_t* list) { if (list == NULL || list->head == NULL) return; while (list->head != NULL) { ll_node_s_t* node = list->head; list->head = node->next; kfree(node); } kfree(list); } ================================================ FILE: src/common/set.c ================================================ /** * \file common/set.c * * Contains an implementation of a thread-safe basic set in the kernel heap. * It's used to check which streams are enabled in ser_driver for the moment, * but also has list_contains which may be useful in other contexts. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "common/set.h" #include "kapi.h" #include "system/optimizers.h" void set_initialize(struct set* const set) { set->arr = kmalloc(8 * sizeof(*(set->arr))); set->used = 0; set->size = 8; set->mtx = mutex_create_static(&(set->mtx_buf)); } bool set_add(struct set* const set, uint32_t item) { size_t i = 0; if (!mutex_take(set->mtx, TIMEOUT_MAX)) { return false; } for (i = 0; i < set->used; i++) { if (set->arr[i] == item) { mutex_give(set->mtx); return true; } } if (set->used == set->size) { uint32_t* temp = set->arr; set->arr = kmalloc((set->size + 8) * sizeof(*(set->arr))); if (unlikely(set->arr == NULL)) { set->arr = temp; mutex_give(set->mtx); return false; } memcpy(set->arr, temp, set->size * sizeof(*(set->arr))); set->size += 8; } set->arr[set->used] = item; set->used++; mutex_give(set->mtx); return true; } bool set_rm(struct set* set, uint32_t item) { size_t i = 0; if (!mutex_take(set->mtx, TIMEOUT_MAX)) { return false; } for (i = 0; i < set->used - 1; i++) { if (set->arr[i] == item) { memcpy(set->arr + i, set->arr + i + 1, set->used - i - 1); set->used--; mutex_give(set->mtx); return true; } } if (set->arr[set->used] == item) { // this is the last item, no need to do memcpy, just decrement the counter set->used--; } mutex_give(set->mtx); return true; } bool set_contains(struct set* set, uint32_t item) { if (!mutex_take(set->mtx, TIMEOUT_MAX)) { return false; } bool ret = list_contains(set->arr, set->used, item); mutex_give(set->mtx); return ret; } bool list_contains(uint32_t const* list, const size_t size, const uint32_t item) { uint32_t const* const end = list + size; while (list <= end) { if (*list == item) { return true; } list++; } return false; } ================================================ FILE: src/common/string.c ================================================ /** * \file common/string.c * * Contains extra string functions useful for PROS and kstrdup/kstrndup which * use the kernel heap instead of the user heap * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "kapi.h" char* kstrndup(const char* s, size_t n) { size_t copy_len = strnlen(s, n); // strlen max'd out at n char* dupstr = kmalloc(n + 1); if (!dupstr) { return NULL; } memset(dupstr, 0, n + 1); memcpy(dupstr, s, copy_len); return dupstr; } char* kstrdup(const char* s) { return kstrndup(s, strlen(s)); } void kprint_hex(uint8_t* s, size_t len) { for (size_t i = 0; i < len; i++) { if (i % 16 == 0) { printf("\n%u:\t", i); } printf("0x%02x ", s[i]); } printf("\n"); } ================================================ FILE: src/devices/README.md ================================================ # Devices These source files implement VDML - the VEX Data Mesh Layer, which controls the V5 Smart Devices and other peripherals. ================================================ FILE: src/devices/battery.c ================================================ /** * \file devices/battery.c * * Contains functions for interacting with the V5 Battery. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "v5_api.h" #include "vdml/vdml.h" int32_t battery_get_voltage(void) { if (!internal_port_mutex_take(V5_PORT_BATTERY)) { errno = EACCES; return PROS_ERR; } double rtn = vexBatteryVoltageGet(); internal_port_mutex_give(V5_PORT_BATTERY); return rtn; } int32_t battery_get_current(void) { if (!internal_port_mutex_take(V5_PORT_BATTERY)) { errno = EACCES; return PROS_ERR; } double rtn = vexBatteryCurrentGet(); internal_port_mutex_give(V5_PORT_BATTERY); return rtn; } double battery_get_temperature(void) { if (!internal_port_mutex_take(V5_PORT_BATTERY)) { errno = EACCES; return PROS_ERR_F; } double rtn = vexBatteryTemperatureGet(); internal_port_mutex_give(V5_PORT_BATTERY); return rtn; } double battery_get_capacity(void) { if (!internal_port_mutex_take(V5_PORT_BATTERY)) { errno = EACCES; return PROS_ERR_F; } double rtn = vexBatteryCapacityGet(); internal_port_mutex_give(V5_PORT_BATTERY); return rtn; } ================================================ FILE: src/devices/battery.cpp ================================================ /** * \file devices/battery.cpp * * Contains functions for interacting with the V5 Battery. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" namespace pros { namespace battery { using namespace pros::c; double get_capacity(void) { return battery_get_capacity(); } std::int32_t get_current(void) { return battery_get_current(); } double get_temperature(void) { return battery_get_temperature(); } std::int32_t get_voltage(void) { return battery_get_voltage(); } } // namespace battery } // namespace pros ================================================ FILE: src/devices/controller.c ================================================ /** * \file devices/controller.c * * Contains functions for interacting with the V5 Controller. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include "kapi.h" #include "v5_api.h" #include "vdml/vdml.h" #define CONTROLLER_MAX_COLS ( 20U ) #define CONTROLLER_MAX_CHARS ( 31U ) // From enum in misc.h #define NUM_BUTTONS 13 // button_pressed is used for get_digital_new_press and button_released is used for get_digital_new_release typedef struct __attribute__((__may_alias__)) controller_data { bool button_pressed[NUM_BUTTONS]; bool button_released[NUM_BUTTONS]; } controller_data_s_t; static controller_data_s_t data[2] = { { .button_pressed = {false}, .button_released = {true, true, true, true, true, true, true, true, true, true, true, true, true}, }, { .button_pressed = {false}, .button_released = {true, true, true, true, true, true, true, true, true, true, true, true, true}, } }; static bool get_button_pressed(int port, int button) { return data[port - V5_PORT_CONTROLLER_1].button_pressed[button]; } static void set_button_pressed(int port, int button, bool state) { data[port - V5_PORT_CONTROLLER_1].button_pressed[button] = state; } static bool get_button_released(int port, int button) { return data[port - V5_PORT_CONTROLLER_1].button_released[button]; } static void set_button_released(int port, int button, bool state) { data[port - V5_PORT_CONTROLLER_1].button_released[button] = state; } int32_t controller_is_connected(controller_id_e_t id) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) int32_t rtn = vexControllerConnectionStatusGet(id); internal_port_mutex_give(port); return rtn; } int32_t controller_get_analog(controller_id_e_t id, controller_analog_e_t channel) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) int32_t rtn = vexControllerGet(id, channel); internal_port_mutex_give(port); return rtn; } int32_t controller_get_battery_capacity(controller_id_e_t id) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) int32_t rtn = vexControllerGet(id, BatteryCapacity); internal_port_mutex_give(port); return rtn; } int32_t controller_get_battery_level(controller_id_e_t id) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) int32_t rtn = vexControllerGet(id, BatteryLevel); internal_port_mutex_give(port); return rtn; } int32_t controller_get_digital(controller_id_e_t id, controller_digital_e_t button) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) // the buttons enum starts at 6, the correct place for the libv5rts int32_t rtn = vexControllerGet(id, button); internal_port_mutex_give(port); return rtn; } int32_t controller_get_digital_new_press(controller_id_e_t id, controller_digital_e_t button) { int32_t pressed = controller_get_digital(id, button); uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) uint8_t button_num = button - E_CONTROLLER_DIGITAL_L1; if (!pressed) { set_button_pressed(port, button_num, false); } if (pressed && !get_button_pressed(port, button_num)) { // button is currently pressed and was not detected as being pressed during // last check set_button_pressed(port, button_num, true); internal_port_mutex_give(port); return true; } else { internal_port_mutex_give(port); return false; // button is not pressed or was already detected } } int32_t controller_get_digital_new_release(controller_id_e_t id, controller_digital_e_t button) { int32_t pressed = controller_get_digital(id, button); uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) uint8_t button_num = button - E_CONTROLLER_DIGITAL_L1; if (pressed) { set_button_released(port, button_num, false); } if (!pressed && !get_button_released(port, button_num)) { // button is currently not pressed and was detected as being pressed during // last check set_button_released(port, button_num, true); internal_port_mutex_give(port); return true; } else { internal_port_mutex_give(port); return false; // button is pressed or was already detected } } int32_t controller_set_text(controller_id_e_t id, uint8_t line, uint8_t col, const char* str) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) line++; if (col >= CONTROLLER_MAX_COLS) col = CONTROLLER_MAX_COLS; else col++; char* buf = strndup(str, CONTROLLER_MAX_CHARS + 1); uint32_t rtn_val = vexControllerTextSet(id, line, col, buf); free(buf); internal_port_mutex_give(port); if (!rtn_val) { errno = EAGAIN; return PROS_ERR; } return 1; } int32_t controller_print(controller_id_e_t id, uint8_t line, uint8_t col, const char* fmt, ...) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port) line++; if (col >= CONTROLLER_MAX_COLS) col = CONTROLLER_MAX_COLS; else col++; va_list args; va_start(args, fmt); char* buf = (char*)malloc(CONTROLLER_MAX_CHARS + 1); vsnprintf(buf, CONTROLLER_MAX_CHARS + 1, fmt, args); uint32_t rtn_val = vexControllerTextSet(id, line, col, buf); free(buf); va_end(args); internal_port_mutex_give(port); if (!rtn_val) { errno = EAGAIN; return PROS_ERR; } return 1; } int32_t controller_clear_line(controller_id_e_t id, uint8_t line) { uint8_t port; CONTROLLER_PORT_MUTEX_TAKE(id, port); int32_t rtn; if (vexSystemVersion() >= 0x1000C38) { static char* clear = ""; rtn = vexControllerTextSet(id, ++line, 1, clear); } else { static char* clear = " "; kassert(strlen(clear) == CONTROLLER_MAX_COLS); rtn = vexControllerTextSet(id, ++line, 1, clear); } internal_port_mutex_give(port); return rtn; } int32_t controller_clear(controller_id_e_t id) { if (vexSystemVersion() > 0x01000000) { return controller_print(id, -1, 0, ""); } else { for (int i = 0; i < 3; i++) { int32_t rtn = controller_clear_line(id, i); if (rtn == PROS_ERR) return PROS_ERR; if (i != 2) delay(55); } return 1; } } int32_t controller_rumble(controller_id_e_t id, const char* rumble_pattern) { return controller_set_text(id, 3, 0, rumble_pattern); } uint8_t competition_get_status(void) { return vexCompetitionStatus(); } uint8_t competition_is_disabled(void) { return (competition_get_status() & COMPETITION_DISABLED) != 0; } uint8_t competition_is_connected(void) { return (competition_get_status() & COMPETITION_CONNECTED) != 0; } uint8_t competition_is_autonomous(void) { return (competition_get_status() & COMPETITION_AUTONOMOUS) != 0; } uint8_t competition_is_field(void) { return ((competition_get_status() & COMPETITION_SYSTEM) != 0) && competition_is_connected(); } uint8_t competition_is_switch(void) { return ((competition_get_status() & COMPETITION_SYSTEM) == 0) && competition_is_connected(); } ================================================ FILE: src/devices/controller.cpp ================================================ /** * \file devices/controller.cpp * * Contains functions for interacting with the V5 Controller, as well as the * competition control functions. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" namespace pros { inline namespace v5 { using namespace pros::c; Controller::Controller(pros::controller_id_e_t id) : _id(id) {} std::int32_t Controller::is_connected(void) { return controller_is_connected(_id); } std::int32_t Controller::get_analog(pros::controller_analog_e_t channel) { return controller_get_analog(_id, channel); } std::int32_t Controller::get_battery_capacity(void) { return controller_get_battery_capacity(_id); } std::int32_t Controller::get_battery_level(void) { return controller_get_battery_level(_id); } std::int32_t Controller::get_digital(pros::controller_digital_e_t button) { return controller_get_digital(_id, button); } std::int32_t Controller::get_digital_new_press(pros::controller_digital_e_t button) { return controller_get_digital_new_press(_id, button); } std::int32_t Controller::get_digital_new_release(pros::controller_digital_e_t button) { return controller_get_digital_new_release(_id, button); } std::int32_t Controller::set_text(std::uint8_t line, std::uint8_t col, const char* str) { return controller_set_text(_id, line, col, str); } std::int32_t Controller::set_text(std::uint8_t line, std::uint8_t col, const std::string& str) { return controller_set_text(_id, line, col, str.c_str()); } std::int32_t Controller::clear_line(std::uint8_t line) { return controller_clear_line(_id, line); } std::int32_t Controller::clear(void) { return controller_clear(_id); } std::int32_t Controller::rumble(const char* rumble_pattern) { return controller_rumble(_id, rumble_pattern); } } // namespace v5 namespace competition { using namespace pros::c; std::uint8_t get_status(void) { return competition_get_status(); } std::uint8_t is_autonomous(void) { return competition_is_autonomous(); } std::uint8_t is_connected(void) { return competition_is_connected(); } std::uint8_t is_disabled(void) { return competition_is_disabled(); } std::uint8_t is_field_control(void) { return competition_is_field(); } std::uint8_t is_competition_switch(void) { return competition_is_switch(); } } // namespace competition } // namespace pros ================================================ FILE: src/devices/registry.c ================================================ /** * \file devices/registry.c * * This file is the VDML (Vex Data Management Layer) Registry. It keeps track of * what devices are in use on the V5. Therefore, in order to use V5 devices with * PROS, they must be registered and deregistered using the registry. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include "api.h" #include "kapi.h" #include "pros/misc.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" static v5_smart_device_s_t registry[V5_MAX_DEVICE_PORTS]; static V5_DeviceType registry_types[V5_MAX_DEVICE_PORTS]; void registry_init() { int i; kprint("[VDML][INFO]Initializing registry\n"); registry_update_types(); for (i = 0; i < NUM_V5_PORTS; i++) { registry[i].device_type = (v5_device_e_t)registry_types[i]; registry[i].device_info = vexDeviceGetByIndex(i); if (registry[i].device_type != E_DEVICE_NONE) { kprintf("[VDML][INFO]Register device in port %d", i + 1); } } kprint("[VDML][INFO]Done initializing registry\n"); } void registry_update_types() { vexDeviceGetStatus(registry_types); } int registry_bind_port(uint8_t port, v5_device_e_t device_type) { if (!VALIDATE_PORT_NO(port)) { kprintf("[VDML][ERROR]Registration: Invalid port number %d\n", port + 1); errno = ENXIO; return PROS_ERR; } if (registry[port].device_type != E_DEVICE_NONE) { kprintf("[VDML][ERROR]Registration: Port already in use %d\n", port + 1); errno = EADDRINUSE; return PROS_ERR; } if ((v5_device_e_t)registry_types[port] != device_type && (v5_device_e_t)registry_types[port] != E_DEVICE_NONE) { kprintf("[VDML][ERROR]Registration: Device mismatch in port %d\n", port + 1); errno = EADDRINUSE; return PROS_ERR; } kprintf("[VDML][INFO]Registering device in port %d\n", port + 1); v5_smart_device_s_t device; device.device_type = device_type; device.device_info = vexDeviceGetByIndex(port); registry[port] = device; return 1; } int registry_unbind_port(uint8_t port) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return PROS_ERR; } registry[port].device_type = E_DEVICE_NONE; registry[port].device_info = NULL; return 1; } v5_smart_device_s_t* registry_get_device(uint8_t port) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return NULL; } return ®istry[port]; } v5_smart_device_s_t* registry_get_device_internal(uint8_t port) { if (!VALIDATE_PORT_NO_INTERNAL(port)) { errno = ENXIO; return NULL; } return ®istry[port]; } v5_device_e_t registry_get_bound_type(uint8_t port) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return E_DEVICE_UNDEFINED; } return registry[port].device_type; } v5_device_e_t registry_get_plugged_type(uint8_t port) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return -1; } return registry_types[port]; } int32_t registry_validate_binding(uint8_t port, v5_device_e_t expected_t) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return PROS_ERR; } // Get the registered and plugged types v5_device_e_t registered_t = registry_get_bound_type(port); v5_device_e_t actual_t = registry_get_plugged_type(port); // Auto register the port if needed if (registered_t == E_DEVICE_NONE && actual_t != E_DEVICE_NONE) { registry_bind_port(port, actual_t); registered_t = registry_get_bound_type(port); } if ((expected_t == registered_t || expected_t == E_DEVICE_NONE) && registered_t == actual_t) { // All are same OR expected is none (bgp) AND reg = act. // All good vdml_unset_port_error(port); return 0; } else if (actual_t == E_DEVICE_NONE) { // Warn about nothing plugged if (!vdml_get_port_error(port)) { kprintf("[VDML][WARNING] No device in port %d. Is it plugged in?\n", port + 1); vdml_set_port_error(port); } errno = ENODEV; return 1; } else { // Warn about a mismatch if (!vdml_get_port_error(port)) { kprintf("[VDML][WARNING] Device mismatch in port %d.\n", port + 1); vdml_set_port_error(port); } errno = EADDRINUSE; return 2; } } ================================================ FILE: src/devices/screen.c ================================================ /** * \file screen.c * * \brief Brain screen display and touch functions. * * Contains user calls to the v5 screen for touching and displaying graphics. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/screen.h" #include #include #include #include "common/linkedlist.h" #include "kapi.h" #include "pros/apix.h" #include "v5_api.h" // vexDisplay* /******************************************************************************/ /** Screen Graphical Display Functions **/ /** **/ /** These functions allow programmers to display shapes on the v5 screen **/ /******************************************************************************/ static mutex_t _screen_mutex = NULL; typedef struct touch_event_position_data_s { int16_t x; int16_t y; } touch_event_position_data_s_t; uint32_t screen_set_pen(uint32_t color){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayForegroundColor(color); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_set_eraser(uint32_t color){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayBackgroundColor(color); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_get_pen(void){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } uint32_t color = vexDisplayForegroundColorGet(); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } return color; } uint32_t screen_get_eraser(void){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } uint32_t color = vexDisplayBackgroundColorGet(); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } return color; } uint32_t screen_erase(void){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayErase(); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_scroll(int16_t start_line, int16_t lines){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayScroll(start_line, lines); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_scroll_area(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t lines){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayScrollRect(x0, y0, x1, y1, lines); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_copy_area(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint32_t* buf, int32_t stride){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayCopyRect(x0, y0, x1, y1, buf, stride); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_draw_pixel(int16_t x, int16_t y){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayPixelSet(x, y); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_erase_pixel(int16_t x, int16_t y){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayPixelClear(x, y); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_draw_line(int16_t x0, int16_t y0, int16_t x1, int16_t y1){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayLineDraw(x0, y0, x1, y1); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_erase_line(int16_t x0, int16_t y0, int16_t x1, int16_t y1){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayLineClear(x0, y0, x1, y1); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_draw_rect(int16_t x0, int16_t y0, int16_t x1, int16_t y1){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayRectDraw(x0, y0, x1, y1); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_erase_rect(int16_t x0, int16_t y0, int16_t x1, int16_t y1){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayRectClear(x0, y0, x1, y1); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_fill_rect(int16_t x0, int16_t y0, int16_t x1, int16_t y1){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayRectFill(x0, y0, x1, y1); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_draw_circle(int16_t x, int16_t y, int16_t radius){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayCircleDraw(x, y, radius); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_erase_circle(int16_t x, int16_t y, int16_t radius){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayCircleClear(x, y, radius); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_fill_circle(int16_t x, int16_t y, int16_t radius){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } vexDisplayCircleFill(x, y, radius); if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } /******************************************************************************/ /** Screen Text Display Functions **/ /** **/ /** These functions allow programmers to display text on the v5 screen **/ /******************************************************************************/ uint32_t screen_print(text_format_e_t txt_fmt, const int16_t line, const char* text, ...){ va_list args; va_start(args, text); if (screen_vprintf((uint8_t)txt_fmt, line, text, args) == PROS_ERR) { return PROS_ERR; } va_end(args); return 1; } uint32_t screen_print_at(text_format_e_t txt_fmt, int16_t x, int16_t y, const char* text, ...){ va_list args; va_start(args, text); if (screen_vprintf_at((uint8_t)txt_fmt, x, y, text, args) == PROS_ERR) { return PROS_ERR; } va_end(args); return 1; } uint32_t screen_vprintf(text_format_e_t txt_fmt, const int16_t line, const char* text, va_list args){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } char* out; vasprintf(&out, text, args); va_list empty; switch(txt_fmt){ case E_TEXT_SMALL: case E_TEXT_MEDIUM: { vexDisplayVString(line, out, empty); break; } case E_TEXT_LARGE: { vexDisplayVBigString(line, out, empty); break; } case E_TEXT_MEDIUM_CENTER: { vexDisplayVCenteredString(line, out, empty); break; } case E_TEXT_LARGE_CENTER: { vexDisplayVBigCenteredString(line, out, empty); break; } default: { vexDisplayVString(line, out, empty); break; } } if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } uint32_t screen_vprintf_at(text_format_e_t txt_fmt, const int16_t x, const int16_t y, const char* text, va_list args){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } char* out; vasprintf(&out, text, args); va_list empty; switch(txt_fmt){ case E_TEXT_SMALL: { vexDisplayVSmallStringAt(x, y, out, empty); break; } case E_TEXT_MEDIUM: case E_TEXT_MEDIUM_CENTER: { vexDisplayVStringAt(x, y, out, empty); break; } case E_TEXT_LARGE: case E_TEXT_LARGE_CENTER: { vexDisplayVBigStringAt(x, y, out, empty); break; } default: { vexDisplayVStringAt(x, y, out, empty); break; } } if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } /******************************************************************************/ /** Screen Touch Functions **/ /** **/ /** These functions allow programmers to access **/ /** information about screen touches **/ /******************************************************************************/ static const screen_touch_status_s_t PROS_SCREEN_ERR = {.touch_status = E_TOUCH_ERROR, .x = -1, .y = -1, .press_count = -1, .release_count = -1}; screen_touch_status_s_t screen_touch_status(void){ if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_SCREEN_ERR; } V5_TouchStatus v5_touch_status; screen_touch_status_s_t rtv; vexTouchDataGet(&v5_touch_status); rtv.touch_status = (last_touch_e_t)v5_touch_status.lastEvent; rtv.x = v5_touch_status.lastXpos; rtv.y = v5_touch_status.lastYpos; rtv.press_count = v5_touch_status.pressCount; rtv.release_count = v5_touch_status.releaseCount; if (!mutex_give(_screen_mutex)) { errno = EACCES; return PROS_SCREEN_ERR; } return rtv; } static linked_list_s_t* _touch_event_release_handler_list = NULL; static linked_list_s_t* _touch_event_press_handler_list = NULL; static linked_list_s_t* _touch_event_press_auto_handler_list = NULL; static void _set_up_touch_callback_storage() { _touch_event_release_handler_list = linked_list_init(); _touch_event_press_handler_list = linked_list_init(); _touch_event_press_auto_handler_list = linked_list_init(); } uint32_t screen_touch_callback(touch_event_cb_fn_t cb, last_touch_e_t event_type) { if (!mutex_take(_screen_mutex, TIMEOUT_MAX)) { errno = EACCES; return PROS_ERR; } switch (event_type) { case E_TOUCH_RELEASED: linked_list_prepend_func(_touch_event_release_handler_list, (generic_fn_t)cb); break; case E_TOUCH_PRESSED: linked_list_prepend_func(_touch_event_press_handler_list, (generic_fn_t)cb); break; case E_TOUCH_HELD: linked_list_prepend_func(_touch_event_press_auto_handler_list, (generic_fn_t)cb); break; case E_TOUCH_ERROR: return PROS_ERR; break; } if (!mutex_give(_screen_mutex)) { return PROS_ERR; } else { return 1; } } static task_stack_t touch_handle_task_stack[TASK_STACK_DEPTH_DEFAULT]; static static_task_s_t touch_handle_task_buffer; static task_t touch_handle_task; // volatile because some linters think this is going to be optimized out static volatile void _handle_cb(ll_node_s_t* current, void* extra_data) { (current->payload.func)(); } static inline bool _touch_status_equivalent(V5_TouchStatus x, V5_TouchStatus y) { return (x.lastEvent == y.lastEvent) && (x.lastXpos == y.lastXpos) && (x.lastYpos == y.lastYpos); } void _touch_handle_task(void* ignore) { V5_TouchStatus current = {0}, last = {0}; while (true) { mutex_take(_screen_mutex, TIMEOUT_MAX); vexTouchDataGet(¤t); mutex_give(_screen_mutex); if (!_touch_status_equivalent(current, last)) { switch (current.lastEvent) { case E_TOUCH_RELEASED: linked_list_foreach(_touch_event_release_handler_list, _handle_cb, NULL); break; case E_TOUCH_PRESSED: linked_list_foreach(_touch_event_press_handler_list, _handle_cb, NULL); break; case E_TOUCH_HELD: linked_list_foreach(_touch_event_press_auto_handler_list, _handle_cb, NULL); break; } last = current; } delay(10); } } // internal functions for different mechanisms void display_fatal_error(const char* text) { // in fatal error state, cannot rely on integrity of the RTOS char s[50]; strncpy(s, text, 50); vexDisplayForegroundColor(COLOR_RED); vexDisplayRectFill(0, 0, 480, 19); vexDisplayRectFill(0, 0, 27, 240); vexDisplayRectFill(453, 0, 480, 240); vexDisplayRectFill(0, 179, 480, 240); vexDisplayForegroundColor(0x1A1917); vexDisplayRectFill(50, 190, 130, 230); vexDisplayRectFill(200, 190, 280, 230); vexDisplayRectFill(350, 190, 430, 230); vexDisplayCenteredString(0, s); } void graphical_context_daemon_initialize(void) { _screen_mutex = mutex_create(); _set_up_touch_callback_storage(); touch_handle_task = task_create_static(_touch_handle_task, NULL, TASK_PRIORITY_MIN + 2, TASK_STACK_DEPTH_DEFAULT, "PROS Graphics Touch Handler", touch_handle_task_stack, &touch_handle_task_buffer); } ================================================ FILE: src/devices/screen.cpp ================================================ /** * \file screen.cpp * * \brief Brain screen display and touch functions. * * Contains user calls to the v5 screen for touching and displaying graphics. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/screen.hpp" #include namespace pros { namespace screen { std::uint32_t set_pen(pros::Color color){ return pros::c::screen_set_pen((uint32_t)color); } std::uint32_t set_eraser(pros::Color color){ return pros::c::screen_set_eraser((uint32_t)color); } std::uint32_t set_pen(std::uint32_t color){ return pros::c::screen_set_pen(color); } std::uint32_t set_eraser(std::uint32_t color) { return pros::c::screen_set_eraser(color); } std::uint32_t get_pen(){ return pros::c::screen_get_pen(); } std::uint32_t get_eraser(){ return pros::c::screen_get_eraser(); } std::uint32_t erase(){ return pros::c::screen_erase(); } std::uint32_t scroll(const std::int16_t start_line, const std::int16_t lines){ return pros::c::screen_scroll(start_line, lines); } std::uint32_t scroll_area(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1, std::int16_t lines){ return pros::c::screen_scroll_area(x0, y0, x1, y1, lines); } std::uint32_t copy_area(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1, uint32_t* buf, const std::int32_t stride){ return pros::c::screen_copy_area( x0, y0, x1, y1, buf, stride); } std::uint32_t draw_pixel(const std::int16_t x, const std::int16_t y){ return pros::c::screen_draw_pixel(x, y); } std::uint32_t erase_pixel(const std::int16_t x, const std::int16_t y){ return pros::c::screen_erase_pixel(x, y); } std::uint32_t draw_line(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1){ return pros::c::screen_draw_line(x0, y0, x1, y1); } std::uint32_t erase_line(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1){ return pros::c::screen_erase_line(x0, y0, x1, y1); } std::uint32_t draw_rect(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1){ return pros::c::screen_draw_rect(x0, y0, x1, y1); } std::uint32_t erase_rect(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1){ return pros::c::screen_erase_rect(x0, y0, x1, y1); } std::uint32_t fill_rect(const std::int16_t x0, const std::int16_t y0, const std::int16_t x1, const std::int16_t y1){ return pros::c::screen_fill_rect(x0, y0, x1, y1); } std::uint32_t draw_circle(const std::int16_t x, const std::int16_t y, const std::int16_t radius){ return pros::c::screen_draw_circle(x, y, radius); } std::uint32_t erase_circle(const std::int16_t x, const std::int16_t y, const std::int16_t radius){ return pros::c::screen_erase_circle(x, y, radius); } std::uint32_t fill_circle(const std::int16_t x, const std::int16_t y, const std::int16_t radius){ return pros::c::screen_fill_circle(x, y, radius); } screen_touch_status_s_t touch_status() { return pros::c::screen_touch_status(); } std::uint32_t touch_callback(touch_event_cb_fn_t cb, last_touch_e_t event_type){ return pros::c::screen_touch_callback(cb, event_type); } /******************************************************************************/ /** LLEMU Weak Stubs **/ /** **/ /** These functions allow main.cpp to be compiled without LVGL present **/ /******************************************************************************/ namespace lcd { #if !defined(_PROS_INCLUDE_LIBLVGL_LLEMU_HPP) && defined(_PROS_KERNEL_SUPPRESS_LLEMU_WARNING) #warning "liblvgl is not installed. As this is a kernel build, this warning will only be shown once." #endif using lcd_btn_cb_fn_t = void (*)(void); extern __attribute__((weak)) bool is_initialized(void) {return false;} extern __attribute__((weak)) bool initialize(void) {return false;} extern __attribute__((weak)) bool shutdown(void) {return false;} extern __attribute__((weak)) bool set_text(std::int16_t line, std::string text) {return false;} extern __attribute__((weak)) bool clear(void) {return false;} extern __attribute__((weak)) bool clear_line(std::int16_t line) {return false;} // TODO: Text_Align is defined in liblvgl so this ain't going to compile for now. // extern __attribute__((weak)) void set_text_align(Text_Align text_align) {} extern __attribute__((weak)) void register_btn0_cb(lcd_btn_cb_fn_t cb) {} extern __attribute__((weak)) void register_btn1_cb(lcd_btn_cb_fn_t cb) {} extern __attribute__((weak)) void register_btn2_cb(lcd_btn_cb_fn_t cb) {} extern __attribute__((weak)) std::uint8_t read_buttons(void) {return 0xf;} template extern __attribute__((weak)) bool print(std::int16_t line, const char* fmt, Params... args) {return false;} } // namespace lcd } // namespace screen } // namespace pros ================================================ FILE: src/devices/vdml.c ================================================ /** * \file devices/vdml.c * * VDML - VEX Data Management Layer * * VDML ensures thread saftey for operations on smart devices by maintaining * an array of RTOS Mutexes and implementing functions to take and give them. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "vdml/vdml.h" #include "kapi.h" #include "v5_api.h" #include "vdml/registry.h" #include #include /** * Bitmap to indicate if a port has had an error printed or not. */ int32_t port_errors; extern void registry_init(); extern void port_mutex_init(); int32_t claim_port_try(uint8_t port, v5_device_e_t type) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return 0; } if (registry_validate_binding(port, type) != 0) { return 0; } if (!port_mutex_take(port)) { errno = EACCES; return 0; } return 1; } /** * We have V5_MAX_DEVICE_PORTS so that we can do thread safety on things like * controllers, batteries which are sort of like smart devices internally to the * V5 */ mutex_t port_mutexes[V5_MAX_DEVICE_PORTS]; // Mutexes for each port static_sem_s_t port_mutex_bufs[V5_MAX_DEVICE_PORTS]; // Stack mem for rtos /** * Shorcut to initialize all of VDML (mutexes and register) */ void vdml_initialize() { port_mutex_init(); registry_init(); } /** * Initializes the mutexes for the motor ports. * * Initializes a static array of FreeRTOS mutexes to protect against race * conditions. For example, we don't want the Background processing task to run * at the same time that we set a motor, because bad information may be * returned, or worse. */ void port_mutex_init() { for (int i = 0; i < V5_MAX_DEVICE_PORTS; i++) { port_mutexes[i] = mutex_create_static(&(port_mutex_bufs[i])); } } int port_mutex_take(uint8_t port) { if (port >= V5_MAX_DEVICE_PORTS) { errno = ENXIO; return PROS_ERR; } return xTaskGetSchedulerState() != taskSCHEDULER_RUNNING || mutex_take(port_mutexes[port], TIMEOUT_MAX); } int internal_port_mutex_take(uint8_t port) { if (port >= V5_MAX_DEVICE_PORTS) { errno = ENXIO; return PROS_ERR; } return mutex_take(port_mutexes[port], TIMEOUT_MAX); } static inline char* print_num(char* buff, int num) { *buff++ = (num / 10) + '0'; *buff++ = (num % 10) + '0'; return buff; } int port_mutex_give(uint8_t port) { if (port >= V5_MAX_DEVICE_PORTS) { errno = ENXIO; return PROS_ERR; } return xTaskGetSchedulerState() != taskSCHEDULER_RUNNING || mutex_give(port_mutexes[port]); } int internal_port_mutex_give(uint8_t port) { if (port >= V5_MAX_DEVICE_PORTS) { errno = ENXIO; return PROS_ERR; } return mutex_give(port_mutexes[port]); } void port_mutex_take_all() { for (int i = 0; i < V5_MAX_DEVICE_PORTS; i++) { port_mutex_take(i); } } void port_mutex_give_all() { for (int i = 0; i < V5_MAX_DEVICE_PORTS; i++) { port_mutex_give(i); } } void vdml_set_port_error(uint8_t port) { if (VALIDATE_PORT_NO(port)) { port_errors |= (1 << port); } } void vdml_unset_port_error(uint8_t port) { if (VALIDATE_PORT_NO(port)) { port_errors &= ~(1 << port); } } bool vdml_get_port_error(uint8_t port) { if (VALIDATE_PORT_NO(port)) { return (port_errors >> port) & 1; } else { return false; } } #if 0 void vdml_reset_port_error() { port_errors = 0; } #endif /** * Background processing function for the VDML system. * * This function should be called by the system daemon approximately every * 2 milliseconds. * * Updates the registry type array, detecting what devices are actually * plugged in according to the system, then compares that with the registry * records. * * On warnings, no operation is performed. */ void vdml_background_processing() { // We're not removing this outright since we want to revisit the idea of logging // the errors with devices in the future #if 0 static int32_t last_port_errors = 0; static int cycle = 0; cycle++; if (cycle % 5000 == 0) { vdml_reset_port_error(); last_port_errors = 0; } #endif // Refresh actual device types. registry_update_types(); #if 0 // Validate the ports. Warn if mismatch. uint8_t error_arr[NUM_V5_PORTS]; int num_errors = 0; int mismatch_errors = 0; for (int i = 0; i < NUM_V5_PORTS; i++) { error_arr[i] = registry_validate_binding(i, E_DEVICE_NONE); if (error_arr[i] != 0) num_errors++; if (error_arr[i] == 2) mismatch_errors++; } // Every 50 ms if (cycle % 50 == 0) { if (last_port_errors == port_errors) { goto end_render_errors; } char line[50]; char* line_ptr = line; if (num_errors == 0) line[0] = (char)0; else if (num_errors <= 6) { // If we have 1-6 total errors (unplugged + mismatch), we can // display a line indicating the ports where these errors occur strcpy(line_ptr, "PORTS"); line_ptr += 5; // 5 is length of "PORTS" if (mismatch_errors != 0) { strcpy(line_ptr, " MISMATCHED: "); line_ptr += 13; // 13 is length of previous string for (int i = 0; i < NUM_V5_PORTS; i++) { if (error_arr[i] == 2) { line_ptr = print_num(line_ptr, i + 1); *line_ptr++ = ','; } } line_ptr--; } if (num_errors != mismatch_errors) { strcpy(line_ptr, " UNPLUGGED: "); line_ptr += 12; // 12 is length of previous string for (int i = 0; i < NUM_V5_PORTS; i++) { if (error_arr[i] == 1) { line_ptr = print_num(line_ptr, i + 1); *line_ptr++ = ','; } } line_ptr--; } } else { /* If we have > 6 errors, we display the following: * PORT ERRORS: 1..... 6..... 11..... 16..... * where each . represents a port. A '.' indicates * there is no error on that port, a 'U' indicates * the registry expected a device there but there isn't * one, and a 'M' indicates the plugged in devices doesn't * match what we expect. The numbers are just a visual reference * to aid in determining what ports have errors. */ strcpy(line_ptr, "PORT ERRORS:"); line_ptr += 12; // 12 is length of previous string for (int i = 0; i < NUM_V5_PORTS; i++) { if (i % 5 == 0) { *line_ptr++ = ' '; line_ptr = print_num(line_ptr, i + 1); } switch (error_arr[i]) { case 0: *line_ptr++ = '.'; break; case 1: *line_ptr++ = 'U'; break; case 2: *line_ptr++ = 'M'; break; // Should never happen default: *line_ptr++ = '?'; break; } } } // Null terminate the string *line_ptr = '\0'; end_render_errors: last_port_errors = port_errors; } #endif } ================================================ FILE: src/devices/vdml_adi.c ================================================ /** * \file devices/vdml_adi.c * * Contains functions for interacting with the V5 ADI. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "vdml/registry.h" #include "vdml/vdml.h" adi_port_config_e_t adi_port_get_config(uint8_t port) { return ext_adi_port_get_config(INTERNAL_ADI_PORT, port); } int32_t adi_port_get_value(uint8_t port) { return ext_adi_port_get_value(INTERNAL_ADI_PORT, port); } int32_t adi_port_set_config(uint8_t port, adi_port_config_e_t type) { return ext_adi_port_set_config(INTERNAL_ADI_PORT, port, type); } int32_t adi_port_set_value(uint8_t port, int32_t value) { return ext_adi_port_set_value(INTERNAL_ADI_PORT, port, value); } int32_t adi_analog_calibrate(uint8_t port) { return ext_adi_analog_calibrate(INTERNAL_ADI_PORT, port); } int32_t adi_analog_read(uint8_t port) { return ext_adi_analog_read(INTERNAL_ADI_PORT, port); } int32_t adi_analog_read_calibrated(uint8_t port) { return ext_adi_analog_read_calibrated(INTERNAL_ADI_PORT, port); } int32_t adi_analog_read_calibrated_HR(uint8_t port) { return ext_adi_analog_read_calibrated_HR(INTERNAL_ADI_PORT, port); } int32_t adi_digital_read(uint8_t port) { return ext_adi_digital_read(INTERNAL_ADI_PORT, port); } int32_t adi_digital_get_new_press(uint8_t port) { return ext_adi_digital_get_new_press(INTERNAL_ADI_PORT, port); } int32_t adi_digital_write(uint8_t port, bool value) { return ext_adi_digital_write(INTERNAL_ADI_PORT, port, value); } int32_t adi_pin_mode(uint8_t port, uint8_t mode) { return ext_adi_pin_mode(INTERNAL_ADI_PORT, port, mode); } int32_t adi_motor_set(uint8_t port, int8_t speed) { return ext_adi_motor_set(INTERNAL_ADI_PORT, port, speed); } int32_t adi_motor_get(uint8_t port) { return ext_adi_motor_get(INTERNAL_ADI_PORT, port); } int32_t adi_motor_stop(uint8_t port) { return ext_adi_motor_stop(INTERNAL_ADI_PORT, port); } adi_encoder_t adi_encoder_init(uint8_t port_top, uint8_t port_bottom, bool reverse) { return (adi_encoder_t)ext_adi_encoder_init(INTERNAL_ADI_PORT, port_top, port_bottom, reverse); } int32_t adi_encoder_get(adi_encoder_t enc) { return ext_adi_encoder_get((ext_adi_encoder_t)enc); } int32_t adi_encoder_reset(adi_encoder_t enc) { return ext_adi_encoder_reset((ext_adi_encoder_t)enc); } int32_t adi_encoder_shutdown(adi_encoder_t enc) { return ext_adi_encoder_shutdown((ext_adi_encoder_t)enc); } adi_ultrasonic_t adi_ultrasonic_init(uint8_t port_ping, uint8_t port_echo) { return (adi_ultrasonic_t)ext_adi_ultrasonic_init(INTERNAL_ADI_PORT, port_ping, port_echo); } int32_t adi_ultrasonic_get(adi_ultrasonic_t ult) { return ext_adi_ultrasonic_get((ext_adi_ultrasonic_t)ult); } int32_t adi_ultrasonic_shutdown(adi_ultrasonic_t ult) { return ext_adi_ultrasonic_shutdown((ext_adi_ultrasonic_t)ult); } adi_gyro_t adi_gyro_init(uint8_t adi_port, double multiplier) { return (adi_gyro_t)ext_adi_gyro_init(INTERNAL_ADI_PORT, adi_port, multiplier); } double adi_gyro_get(adi_gyro_t gyro) { return ext_adi_gyro_get((ext_adi_gyro_t)gyro); } int32_t adi_gyro_reset(adi_gyro_t gyro) { return ext_adi_gyro_reset((ext_adi_gyro_t)gyro); } int32_t adi_gyro_shutdown(adi_gyro_t gyro) { return ext_adi_gyro_shutdown((ext_adi_gyro_t)gyro); } adi_potentiometer_t adi_potentiometer_init(uint8_t port) { return (adi_potentiometer_t)ext_adi_potentiometer_init(INTERNAL_ADI_PORT, port, E_ADI_POT_EDR); } adi_potentiometer_t adi_potentiometer_type_init(uint8_t port, adi_potentiometer_type_e_t potentiometer_type) { return (adi_potentiometer_t)ext_adi_potentiometer_init(INTERNAL_ADI_PORT, port, potentiometer_type); } double adi_potentiometer_get_angle(adi_potentiometer_t potentiometer) { return ext_adi_potentiometer_get_angle((ext_adi_potentiometer_t)potentiometer); } adi_led_t adi_led_init(uint8_t port) { return (adi_led_t)ext_adi_led_init(INTERNAL_ADI_PORT, port); } int32_t adi_led_set(adi_led_t led, uint32_t* buffer, uint32_t buffer_length) { return ext_adi_led_set(led, buffer, buffer_length); } int32_t adi_led_set_pixel(adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color, uint32_t pixel_position) { return ext_adi_led_set_pixel((ext_adi_led_t)led, buffer, buffer_length, color, pixel_position); } int32_t adi_led_set_all(adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color) { return ext_adi_led_set_all((ext_adi_led_t)led, buffer, buffer_length, color); } int32_t adi_led_clear_all(adi_led_t led, uint32_t* buffer, uint32_t buffer_length) { return ext_adi_led_set_all((ext_adi_led_t)led, buffer, buffer_length, 0); } int32_t adi_led_clear_pixel(adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t pixel_position) { return ext_adi_led_set_pixel((ext_adi_led_t)led, buffer, buffer_length, 0, pixel_position); } ================================================ FILE: src/devices/vdml_adi.cpp ================================================ /** * \file devices/vdml_adi.cpp * * Contains functions for interacting with the V5 ADI. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "pros/adi.hpp" #include "vdml/port.h" #define MAX_LED 64 namespace pros { namespace adi { using namespace pros::c; Port::Port(std::uint8_t adi_port, adi_port_config_e_t type) : _smart_port(INTERNAL_ADI_PORT), _adi_port(adi_port) { ext_adi_port_set_config(_smart_port, _adi_port, type); } Port::Port(ext_adi_port_pair_t port_pair, adi_port_config_e_t type) : _smart_port(port_pair.first), _adi_port(port_pair.second) { ext_adi_port_set_config(_smart_port, _adi_port, type); } std::int32_t Port::set_config(adi_port_config_e_t type) const { return ext_adi_port_set_config(_smart_port, _adi_port, type); } std::int32_t Port::get_config() const { return ext_adi_port_get_config(_smart_port, _adi_port); } std::int32_t Port::set_value(std::int32_t value) const { return ext_adi_port_set_value(_smart_port, _adi_port, value); } std::int32_t Port::get_value() const { return ext_adi_port_get_value(_smart_port, _adi_port); } ext_adi_port_tuple_t Port::get_port() const { return std::make_tuple(_smart_port, _adi_port, PROS_ERR_BYTE); } AnalogIn::AnalogIn(std::uint8_t adi_port) : Port(adi_port, E_ADI_ANALOG_IN) {} AnalogIn::AnalogIn(ext_adi_port_pair_t port_pair) : Port(port_pair, E_ADI_ANALOG_IN) {} std::int32_t AnalogIn::calibrate() const { return ext_adi_analog_calibrate(_smart_port, _adi_port); } std::int32_t AnalogIn::get_value_calibrated() const { return ext_adi_analog_read_calibrated(_smart_port, _adi_port); } std::int32_t AnalogIn::get_value_calibrated_HR() const { return ext_adi_analog_read_calibrated_HR(_smart_port, _adi_port); } std::ostream& operator<<(std::ostream& os, pros::adi::AnalogIn& analog_in) { os << "AnalogIn ["; os << "smart_port: " << +analog_in._smart_port; os << ", adi_port: " << ((analog_in._adi_port > 10) ? analog_in._adi_port : +analog_in._adi_port); os << ", value calibrated: " << analog_in.get_value_calibrated(); os << ", value calibrated HR: " << analog_in.get_value_calibrated_HR(); os << ", value: " << analog_in.get_value(); os << "]"; return os; } AnalogOut::AnalogOut(std::uint8_t adi_port) : Port(adi_port, E_ADI_ANALOG_OUT) {} AnalogOut::AnalogOut(ext_adi_port_pair_t port_pair) : Port(port_pair, E_ADI_ANALOG_OUT) {} std::ostream& operator<<(std::ostream& os, pros::adi::AnalogOut& analog_out) { os << "AnalogOut ["; os << "smart_port: " << +analog_out._smart_port; os << ", adi_port: " << ((analog_out._adi_port > 10) ? analog_out._adi_port : +analog_out._adi_port); os << ", value: " << analog_out.get_value(); os << "]"; return os; } DigitalIn::DigitalIn(std::uint8_t adi_port) : Port(adi_port, E_ADI_DIGITAL_IN) {} DigitalIn::DigitalIn(ext_adi_port_pair_t port_pair) : Port(port_pair, E_ADI_DIGITAL_IN) {} std::int32_t DigitalIn::get_new_press() const { return ext_adi_digital_get_new_press(_smart_port, _adi_port); } std::ostream& operator<<(std::ostream& os, pros::adi::DigitalIn& digital_in) { os << "DigitalIn ["; os << "smart_port: " << +digital_in._smart_port; os << ", adi_port: " << ((digital_in._adi_port > 10) ? digital_in._adi_port : +digital_in._adi_port); os << ", value: " << digital_in.get_value(); os << "]"; return os; } DigitalOut::DigitalOut(std::uint8_t adi_port, bool init_state) : Port(adi_port, E_ADI_DIGITAL_OUT) { set_value(init_state); } DigitalOut::DigitalOut(ext_adi_port_pair_t port_pair, bool init_state) : ADIPort(port_pair, E_ADI_DIGITAL_OUT) { set_value(init_state); } std::ostream& operator<<(std::ostream& os, pros::adi::DigitalOut& digital_out) { os << "DigitalOut ["; os << "smart_port: " << +digital_out._smart_port; os << ", adi_port: " << ((digital_out._adi_port > 10) ? digital_out._adi_port : +digital_out._adi_port); os << ", value: " << digital_out.get_value(); os << "]"; return os; } Motor::Motor(std::uint8_t adi_port) : Port(adi_port, E_ADI_LEGACY_PWM) { stop(); } Motor::Motor(ext_adi_port_pair_t port_pair) : Port(port_pair, E_ADI_LEGACY_PWM) { stop(); } std::int32_t Motor::stop() const { return ext_adi_motor_stop(_smart_port, _adi_port); } Encoder::Encoder(std::uint8_t adi_port_top, std::uint8_t adi_port_bottom, bool reversed) : Port(adi_port_top), _port_pair(adi_port_top, adi_port_bottom) { std::int32_t _port = ext_adi_encoder_init(INTERNAL_ADI_PORT, adi_port_top, adi_port_bottom, reversed); get_ports(_port, _smart_port, _adi_port); } Encoder::Encoder(ext_adi_port_tuple_t port_tuple, bool reversed) : Port(std::get<1>(port_tuple)), _port_pair(std::get<1>(port_tuple), std::get<2>(port_tuple)) { std::int32_t _port = ext_adi_encoder_init(std::get<0>(port_tuple), std::get<1>(port_tuple), std::get<2>(port_tuple), reversed); get_ports(_port, _smart_port, _adi_port); } std::int32_t Encoder::reset() const { return ext_adi_encoder_reset(merge_adi_ports(_smart_port, _adi_port)); } std::int32_t Encoder::get_value() const { return ext_adi_encoder_get(merge_adi_ports(_smart_port, _adi_port)); } ext_adi_port_tuple_t ADIEncoder::get_port() const { return std::make_tuple(_smart_port, std::get<0>(_port_pair), std::get<1>(_port_pair)); } std::ostream& operator<<(std::ostream& os, pros::adi::Encoder& encoder) { os << "Encoder ["; os << "smart_port: " << +encoder._smart_port; os << ", adi_port: " << ((encoder._adi_port > 10) ? encoder._adi_port : +encoder._adi_port); os << ", value: " << encoder.get_value(); os << "]"; return os; } Ultrasonic::Ultrasonic(std::uint8_t adi_port_ping, std::uint8_t adi_port_echo) : Port(adi_port_ping) { std::int32_t _port = ext_adi_ultrasonic_init(INTERNAL_ADI_PORT, adi_port_ping, adi_port_echo); get_ports(_port, _smart_port, _adi_port); } Ultrasonic::Ultrasonic(ext_adi_port_tuple_t port_tuple) : Port(std::get<1>(port_tuple)) { std::int32_t _port = ext_adi_ultrasonic_init(std::get<0>(port_tuple), std::get<1>(port_tuple), std::get<2>(port_tuple)); get_ports(_port, _smart_port, _adi_port); } std::int32_t Ultrasonic::get_value() const { return ext_adi_ultrasonic_get(merge_adi_ports(_smart_port, _adi_port)); } Gyro::Gyro(std::uint8_t adi_port, double multiplier) : Port(adi_port) { std::int32_t _port = ext_adi_gyro_init(INTERNAL_ADI_PORT, adi_port, multiplier); get_ports(_port, _smart_port, _adi_port); } Gyro::Gyro(ext_adi_port_pair_t port_pair, double multiplier) : ADIPort(std::get<1>(port_pair)) { std::int32_t _port = ext_adi_gyro_init(port_pair.first, port_pair.second, multiplier); get_ports(_port, _smart_port, _adi_port); } double Gyro::get_value() const { return ext_adi_gyro_get(merge_adi_ports(_smart_port, _adi_port)); } std::int32_t Gyro::reset() const { return ext_adi_gyro_reset(merge_adi_ports(_smart_port, _adi_port)); } Potentiometer::Potentiometer(std::uint8_t adi_port, adi_potentiometer_type_e_t potentiometer_type) : AnalogIn(adi_port) { std::int32_t _port = ext_adi_potentiometer_init(INTERNAL_ADI_PORT, adi_port, potentiometer_type); get_ports(_port, _smart_port, _adi_port); } Potentiometer::Potentiometer(ext_adi_port_pair_t port_pair, adi_potentiometer_type_e_t potentiometer_type) : AnalogIn(std::get<1>(port_pair)) { std::int32_t _port = ext_adi_potentiometer_init(port_pair.first, port_pair.second, potentiometer_type); get_ports(_port, _smart_port, _adi_port); } double Potentiometer::get_angle() const { uint8_t temp_smart = _smart_port - 1; return ext_adi_potentiometer_get_angle(merge_adi_ports(temp_smart, _adi_port)); } Led::Led(std::uint8_t adi_port, std::uint32_t length) : Port(adi_port) { std::int32_t _port = ext_adi_led_init(INTERNAL_ADI_PORT, adi_port); get_ports(_port, _smart_port, _adi_port); if (length < 1) { length = 0; } if (length > MAX_LED) { length = MAX_LED; } _buffer.resize(length, 0); } Led::Led(ext_adi_port_pair_t port_pair, std::uint32_t length) : Port(std::get<1>(port_pair)) { std::int32_t _port = ext_adi_led_init(port_pair.first, port_pair.second); get_ports(_port, _smart_port, _adi_port); if (length < 1) { length = 0; } if (length > MAX_LED) { length = MAX_LED; } _buffer.resize(length, 0); } uint32_t& Led::operator[] (size_t index) { return _buffer[index]; } std::int32_t Led::update() const { return ext_adi_led_set(merge_adi_ports(_smart_port, _adi_port), (uint32_t*)_buffer.data(), _buffer.size()); } std::int32_t Led::length() { return _buffer.size(); } std::int32_t Led::set_all(uint32_t color) { return ext_adi_led_set_all((adi_led_t)merge_adi_ports(_smart_port, _adi_port), (uint32_t*)_buffer.data(), _buffer.size(), color); } std::int32_t Led::set_pixel(uint32_t color, uint32_t pixel_position) { return ext_adi_led_set_pixel((adi_led_t)merge_adi_ports(_smart_port, _adi_port), (uint32_t*)_buffer.data(), _buffer.size(), color, pixel_position); } std::int32_t Led::clear_all() { return ext_adi_led_clear_all((adi_led_t)merge_adi_ports(_smart_port, _adi_port), (uint32_t*)_buffer.data(), _buffer.size()); } std::int32_t Led::clear() { return ext_adi_led_clear_all((adi_led_t)merge_adi_ports(_smart_port, _adi_port), (uint32_t*)_buffer.data(), _buffer.size()); } std::int32_t Led::clear_pixel(uint32_t pixel_position) { return ext_adi_led_clear_pixel((adi_led_t)merge_adi_ports(_smart_port, _adi_port), (uint32_t*)_buffer.data(), _buffer.size(), pixel_position); } Pneumatics::Pneumatics(std::uint8_t adi_port, bool start_extended, bool extended_is_low) : DigitalOut(adi_port), state(start_extended ^ extended_is_low), extended_is_low(extended_is_low) { set_value(state); } Pneumatics::Pneumatics(ext_adi_port_pair_t port_pair, bool start_extended, bool extended_is_low) : DigitalOut(port_pair), state(start_extended ^ extended_is_low), extended_is_low(extended_is_low) { set_value(state); } std::int32_t Pneumatics::extend() { bool old_state = state; state = !extended_is_low; if(set_value(state) == PROS_ERR) { return PROS_ERR; } return state != old_state; } std::int32_t Pneumatics::retract() { bool old_state = state; state = extended_is_low; if(set_value(state) == PROS_ERR) { return PROS_ERR; } return state != old_state; } std::int32_t Pneumatics::toggle() { state = !state; return set_value(state); } bool Pneumatics::is_extended() const { return state ^ extended_is_low; } std::ostream& operator<<(std::ostream& os, pros::adi::Potentiometer& potentiometer) { os << "Potentiometer ["; os << "smart_port: " << +potentiometer._smart_port; os << ", adi_port: " << ((potentiometer._adi_port > 10) ? potentiometer._adi_port : +potentiometer._adi_port); os << ", value: " << potentiometer.get_value(); os << ", value calibrated: " << potentiometer.get_value_calibrated(); os << ", angle: " << potentiometer.get_angle(); os << "]"; return os; } } // namespace adi } // namespace pros ================================================ FILE: src/devices/vdml_ai_vision.c ================================================ /** * \file devices/vdml_aivision.c * * Contains functions for interacting with the V5 Vision Sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/ai_vision.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define AIVISION_COLOR_ERR_INIT \ { .id = PROS_ERR_BYTE, .red = PROS_ERR_BYTE, .green = PROS_ERR_BYTE, .blue = PROS_ERR_BYTE, \ .hue_range = PROS_ERR_F, .saturation_range = PROS_ERR_F \ } #define AIVISION_CODE_ERR_INIT \ { .id = PROS_ERR_BYTE, .length = PROS_ERR_BYTE, .c1 = PROS_ERR_2_BYTE, .c2 = PROS_ERR_2_BYTE, \ .c3 = PROS_ERR_2_BYTE, .c4 = PROS_ERR_2_BYTE, .c5 = PROS_ERR_2_BYTE \ } #define AIVISION_OBJECT_ERR_INIT \ { .id = PROS_ERR_BYTE, .type = PROS_ERR_BYTE } int32_t aivision_reset(uint8_t port) { claim_port_i(port - 1, E_DEVICE_AIVISION); vexDeviceAiVisionReset(device->device_info); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_set_enabled_detection_types(uint8_t port, uint8_t bits, uint8_t bitmask) { claim_port_i(port - 1, E_DEVICE_AIVISION); vexDeviceAiVisionEnableSet(device->device_info, bits, bitmask); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_get_enabled_detection_types(uint8_t port) { claim_port_i(port - 1, E_DEVICE_AIVISION); uint8_t enabled_detection_types = vexDeviceAiVisionEnableGet(device->device_info); return_port(port - 1, enabled_detection_types); } int32_t aivision_enable_detection_types(uint8_t port, uint8_t types_mask) { claim_port_i(port - 1, E_DEVICE_AIVISION); vexDeviceAiVisionEnableSet(device->device_info, types_mask, types_mask); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_disable_detection_types(uint8_t port, uint8_t types_mask) { claim_port_i(port - 1, E_DEVICE_AIVISION); vexDeviceAiVisionEnableSet(device->device_info, 0, types_mask); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_get_class_name(uint8_t port, int32_t id, uint8_t* class_name) { claim_port_i(port - 1, E_DEVICE_AIVISION); vexDeviceAiVisionClassNameGet(device->device_info, id, class_name); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_set_color(uint8_t port, const aivision_color_s_t* color) { claim_port_i(port - 1, E_DEVICE_AIVISION); V5_DeviceAiVisionColor _color; _color.id = color->id; _color.red = color->red; _color.grn = color->green; _color.blu = color->blue; _color.hangle = color->hue_range; _color.hdsat = color->saturation_range; vexDeviceAiVisionColorSet(device->device_info, &_color); return_port(port - 1, PROS_SUCCESS); } aivision_color_s_t aivision_get_color(uint8_t port, uint32_t id) { aivision_color_s_t color = AIVISION_COLOR_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_AIVISION)) { return color; } V5_DeviceAiVisionColor _color; v5_smart_device_s_t* device = registry_get_device(port - 1); vexDeviceAiVisionColorGet(device->device_info, id, &_color); color.id = _color.id; color.red = _color.red; color.green = _color.grn; color.blue = _color.blu; color.hue_range = _color.hangle; color.saturation_range = _color.hdsat; return_port(port - 1, color); } int32_t aivision_get_object_count(uint8_t port) { claim_port_i(port - 1, E_DEVICE_AIVISION); int32_t result = vexDeviceAiVisionObjectCountGet(device->device_info); return_port(port - 1, result); } double aivision_get_temperature(uint8_t port) { claim_port_f(port - 1, E_DEVICE_AIVISION); double result = vexDeviceAiVisionTemperatureGet(device->device_info); return_port(port - 1, result); } int32_t aivision_set_tag_family(uint8_t port, aivision_tag_family_e_t family) { claim_port_i(port - 1, E_DEVICE_AIVISION); uint32_t tag_family_flag = vexDeviceAiVisionStatusGet(device->device_info); tag_family_flag &= !(0xff << 16); tag_family_flag |= (uint32_t)family << 16; vexDeviceAiVisionModeSet(device->device_info, tag_family_flag | AIVISION_MODE_TAG_SET_BIT); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_set_tag_family_override(uint8_t port, aivision_tag_family_e_t family) { claim_port_i(port - 1, E_DEVICE_AIVISION); uint32_t tag_family_flag = (uint32_t)family << 16; vexDeviceAiVisionModeSet(device->device_info, tag_family_flag | AIVISION_MODE_TAG_SET_BIT); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_set_usb_bounding_box_overlay(uint8_t port, bool enabled) { claim_port_i(port - 1, E_DEVICE_AIVISION); uint32_t mode = vexDeviceAiVisionStatusGet(device->device_info); if (enabled) { mode &= 0x7F; } else { mode = (mode != 0) | 0x80; } mode = (mode << 8) | (1 << 25); vexDeviceAiVisionModeSet(device->device_info, mode); return_port(port - 1, PROS_SUCCESS); } int32_t aivision_start_awb(uint8_t port) { claim_port_i(port - 1, E_DEVICE_AIVISION); uint32_t mode = (1 << 18) | (1 << 27); vexDeviceAiVisionModeSet(device->device_info, mode); return_port(port - 1, PROS_SUCCESS); } aivision_object_s_t aivision_get_object(uint8_t port, uint32_t object_index) { aivision_object_s_t result = AIVISION_OBJECT_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_AIVISION)) { return result; } v5_smart_device_s_t* device = registry_get_device(port - 1); vexDeviceAiVisionObjectGet(device->device_info, object_index, (V5_DeviceAiVisionObject*)&result); return_port(port - 1, result); } aivision_code_s_t aivision_get_code(uint8_t port, uint32_t id) { aivision_code_s_t code = AIVISION_CODE_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_AIVISION)) { return code; } v5_smart_device_s_t* device = registry_get_device(port - 1); V5_DeviceAiVisionCode _code; vexDeviceAiVisionCodeGet(device->device_info, id, &_code); code.id = _code.id; code.length = _code.len; code.c1 = _code.c1; code.c2 = _code.c2; code.c3 = _code.c3; code.c4 = _code.c4; code.c5 = _code.c5; return_port(port - 1, code); } int32_t aivision_set_code(uint8_t port, const aivision_code_s_t* code) { claim_port_i(port - 1, E_DEVICE_AIVISION); V5_DeviceAiVisionCode _code; _code.id = code->id; _code.len = code->length; _code.c1 = code->c1; _code.c2 = code->c2; _code.c3 = code->c3; _code.c4 = code->c4; _code.c5 = code->c5; vexDeviceAiVisionCodeSet(device->device_info, &_code); return_port(port - 1, PROS_SUCCESS); } ================================================ FILE: src/devices/vdml_ai_vision.cpp ================================================ /** * \file devices/vdml_vision.cpp * * Contains functions for interacting with the V5 Vision Sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/ai_vision.hpp" #include "pros/device.h" #include "vdml/vdml.h" namespace pros { inline namespace v5 { using namespace pros::c; AivisionModeType operator|(AivisionModeType lhs, AivisionModeType rhs) { return static_cast(static_cast(lhs) | static_cast(rhs)); } AIVision::AIVision(const uint8_t port) : Device(port, DeviceType::aivision) { // empty constructor } std::vector AIVision::get_all_devices() { std::vector matching_devices{Device::get_all_devices(DeviceType::aivision)}; std::vector return_vector; for (const auto& device : matching_devices) { return_vector.push_back(device); } return return_vector; } bool AIVision::is_type(const Object& object, AivisionDetectType type) { return static_cast(type) == object.type; } int32_t AIVision::reset() { return c::aivision_reset(this->_port); } int32_t AIVision::get_enabled_detection_types() { return c::aivision_get_enabled_detection_types(this->_port); } int32_t AIVision::enable_detection_types(AivisionModeType types_mask) { return c::aivision_enable_detection_types(this->_port, static_cast(types_mask)); } int32_t AIVision::disable_detection_types(AivisionModeType types_mask) { return c::aivision_disable_detection_types(this->_port, static_cast(types_mask)); } int32_t AIVision::set_tag_family(AivisionTagFamily family, bool override) { if (override) { return c::aivision_set_tag_family_override(this->_port, static_cast(family)); } return c::aivision_set_tag_family(this->_port, static_cast(family)); } int32_t AIVision::set_color(const pros::AIVision::Color& color) { auto _color = static_cast(color); return c::aivision_set_color(this->_port, &_color); } AIVision::Color AIVision::get_color(uint32_t id) { return c::aivision_get_color(this->_port, id); } int32_t AIVision::get_object_count() { return c::aivision_get_object_count(this->_port); } AIVision::Object AIVision::get_object(uint32_t object_index) { return c::aivision_get_object(this->_port, object_index); } int32_t AIVision::get_class_name(int32_t id, char* class_name) { return c::aivision_get_class_name(this->_port, id, (uint8_t*)class_name); } std::optional AIVision::get_class_name(int32_t id) { char class_name[21]; uint32_t result = c::aivision_get_class_name(this->_port, id, (uint8_t*)class_name); if (result == PROS_SUCCESS) { return std::string(class_name); } return std::nullopt; } int32_t AIVision::start_awb() { return c::aivision_start_awb(this->_port); } AIVision::Code AIVision::get_code(uint32_t id) { return c::aivision_get_code(this->_port, id); } uint32_t AIVision::set_code(const pros::AIVision::Code& code) { auto _code = static_cast(code); return c::aivision_set_code(this->_port, &_code); } std::vector AIVision::get_all_objects() { int32_t count = this->get_object_count(); if (count < 0 || count == PROS_ERR) { return {}; } std::vector objects = std::vector(); objects.reserve(count); for (int idx = 0; idx < count; idx++) { objects.emplace_back(this->get_object(idx)); } return objects; } } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_device.c ================================================ /** * \file devices/vdml_device.c * * Contains functions for interacting with VEX devices. * * * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/device.h" #include "vdml/vdml.h" v5_device_e_t get_plugged_type(uint8_t port) { if (!port_mutex_take(port - 1)) { errno = EACCES; return E_DEVICE_UNDEFINED; } v5_device_e_t type = registry_get_plugged_type(port - 1); return_port(port - 1, type); } ================================================ FILE: src/devices/vdml_device.cpp ================================================ /** * \file devices/vdml_device.cpp * * Base class for all smart devices. * * * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/device.hpp" #include "vdml/vdml.h" namespace pros { inline namespace v5 { bool Device::is_installed() { std::uint8_t zero_indexed_port = _port - 1; port_mutex_take(zero_indexed_port); pros::DeviceType plugged_device_type = (pros::DeviceType)pros::c::registry_get_plugged_type(zero_indexed_port); return_port(zero_indexed_port, _deviceType == plugged_device_type); } std::uint8_t Device::get_port(void) const { return _port; } pros::DeviceType Device::get_plugged_type() const { return(get_plugged_type(_port)); } pros::DeviceType Device::get_plugged_type(std::uint8_t port) { if (!port_mutex_take(port - 1)) { errno = EACCES; return DeviceType::undefined; } DeviceType type = (DeviceType) pros::c::registry_get_plugged_type(port - 1); return_port(port - 1, type); } std::vector Device::get_all_devices(pros::DeviceType device_type) { std::vector device_list {}; for (std::uint8_t curr_port = 0; curr_port < 21; ++curr_port) { if (!port_mutex_take(curr_port)) { errno = EACCES; continue; } pros::DeviceType type = (DeviceType) pros::c::registry_get_plugged_type(curr_port); if (device_type == type) {; device_list.push_back(Device {static_cast(curr_port + 1)}); } port_mutex_give(curr_port); } return device_list; } Device::Device(const std::uint8_t port) : _port(port) {} } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_distance.c ================================================ /** * \file devices/vdml_distance.c * * Contains functions for interacting with the VEX Distance sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "pros/distance.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define ERROR_DISTANCE_BAD_PORT(device, err_return) \ if (!(vexDeviceDistanceStatusGet(device->device_info) == 0x82 || \ vexDeviceDistanceStatusGet(device->device_info) == 0x86)) { \ errno = EAGAIN; \ return_port(port - 1, err_return); \ } int32_t distance_get(uint8_t port) { claim_port_i(port - 1, E_DEVICE_DISTANCE); ERROR_DISTANCE_BAD_PORT(device, PROS_ERR); int32_t rtn = vexDeviceDistanceDistanceGet(device->device_info); return_port(port - 1, rtn); } int32_t distance_get_confidence(uint8_t port) { claim_port_i(port - 1, E_DEVICE_DISTANCE); ERROR_DISTANCE_BAD_PORT(device, PROS_ERR); int32_t rtn = vexDeviceDistanceConfidenceGet(device->device_info); return_port(port - 1, rtn); } int32_t distance_get_object_size(uint8_t port) { claim_port_i(port - 1, E_DEVICE_DISTANCE); ERROR_DISTANCE_BAD_PORT(device, PROS_ERR); int32_t rtn = vexDeviceDistanceObjectSizeGet(device->device_info); return_port(port - 1, rtn); } double distance_get_object_velocity(uint8_t port) { claim_port_i(port - 1, E_DEVICE_DISTANCE); ERROR_DISTANCE_BAD_PORT(device, PROS_ERR); double rtn = vexDeviceDistanceObjectVelocityGet(device->device_info); return_port(port - 1, rtn); } ================================================ FILE: src/devices/vdml_distance.cpp ================================================ /** * \file devices/vdml_distance.cpp * * Contains functions for interacting with the VEX Distance sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/distance.hpp" #include "vdml/vdml.h" namespace pros { inline namespace v5 { Distance::Distance(const std::uint8_t port) : Device(port, DeviceType::distance) {} std::int32_t Distance::get() { return pros::c::distance_get(_port); } std::int32_t Distance::get_distance() { return get(); } std::vector Distance::get_all_devices() { std::vector matching_devices {Device::get_all_devices(DeviceType::distance)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } std::int32_t Distance::get_confidence() { return pros::c::distance_get_confidence(_port); } std::int32_t Distance::get_object_size() { return pros::c::distance_get_object_size(_port); } double Distance::get_object_velocity() { return pros::c::distance_get_object_velocity(_port); } std::ostream& operator<<(std::ostream& os, pros::Distance& distance) { os << "Distance ["; os << "port: " << distance.get_port(); os << ", distance: " << distance.get(); os << ", confidence: " << distance.get_confidence(); os << ", object size: " << distance.get_object_size(); os << ", object velocity: " << distance.get_object_velocity(); os << "]"; return os; } namespace literals { const pros::Distance operator""_dist(const unsigned long long int d) { return pros::Distance(d); } } // namespace literals } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_ext_adi.c ================================================ /** * \file devices/vdml_ext_adi.c * * Contains functions for interacting with the V5 3-Wire Expander. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include "kapi.h" #include "pros/adi.h" #include "pros/ext_adi.h" #include "v5_api.h" #include "vdml/port.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define ADI_MOTOR_MAX_SPEED 127 #define ADI_MOTOR_MIN_SPEED -128 #define NUM_MAX_TWOWIRE 4 #define MAX_LED 64 // Theoretical calibration time is 1024ms, but in practice this seemed to be the // actual time that it takes. #define GYRO_CALIBRATION_TIME 1300 typedef union adi_data { struct { int32_t calib; } analog_data; struct { bool was_pressed; } digital_data; struct { bool reversed; } encoder_data; struct { adi_potentiometer_type_e_t potentiometer_type; } potentiometer_data; struct __attribute__((packed)) { double multiplier; double tare_value; } gyro_data; } adi_data_s_t; // These 2 functions aren't in v5_api.h but should be... so we're going to directly expose them with an extern "C". #ifdef __cplusplus extern "C" { #endif // private addressable LED API int32_t vexDeviceAdiAddrLedSet(V5_DeviceT device, uint32_t port, uint32_t* pData, uint32_t nOffset, uint32_t nLength, uint32_t options); int32_t vexAdiAddrLedSet(uint32_t index, uint32_t port, uint32_t* pData, uint32_t nOffset, uint32_t nLength, uint32_t options); #ifdef __cplusplus } #endif #define transform_adi_port(port) \ if (port >= 'a' && port <= 'h') \ port -= 'a'; \ else if (port >= 'A' && port <= 'H') \ port -= 'A'; \ else \ port--; \ if (port > 7 || port < 0) { \ errno = ENXIO; \ return PROS_ERR; \ } #define validate_type(device, adi_port, smart_port, type) \ adi_port_config_e_t config = (adi_port_config_e_t)vexDeviceAdiPortConfigGet(device->device_info, adi_port); \ if (config != type) { \ errno = EADDRINUSE; \ printf("Error: validate_type\n"); \ return_port(smart_port, PROS_ERR); \ } #define validate_type_f(device, adi_port, smart_port, type) \ adi_port_config_e_t config = (adi_port_config_e_t)vexDeviceAdiPortConfigGet(device->device_info, adi_port); \ if (config != type) { \ errno = EADDRINUSE; \ return_port(smart_port, PROS_ERR_F); \ } #define validate_motor(device, adi_port, smart_port) \ adi_port_config_e_t config = (adi_port_config_e_t)vexDeviceAdiPortConfigGet(device->device_info, adi_port); \ if (config != E_ADI_LEGACY_PWM && config != E_ADI_LEGACY_SERVO) { \ errno = EADDRINUSE; \ return_port(smart_port, PROS_ERR); \ } /* * Validates 3 things: * - Ports next to each other * - Both ports are initialized and valid (individually) * * Returns PROS_ERR if one of these is false. */ #define validate_twowire(port_top, port_bottom) \ if (abs(port_top - port_bottom) > 1) { \ errno = ENXIO; \ return PROS_ERR; \ } \ int port; \ if (port_top < port_bottom) \ port = port_top; \ else if (port_bottom < port_top) \ port = port_bottom; \ else { \ errno = EINVAL; \ return PROS_ERR; \ } \ if (port % 2 == 1) { \ errno = EINVAL; \ return PROS_ERR; \ } adi_port_config_e_t ext_adi_port_get_config(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); adi_port_config_e_t rtn = (adi_port_config_e_t)vexDeviceAdiPortConfigGet(device->device_info, adi_port); return_port(smart_port - 1, rtn); } int32_t ext_adi_port_get_value(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); int32_t rtn = vexDeviceAdiValueGet(device->device_info, adi_port); return_port(smart_port - 1, rtn); } int32_t ext_adi_port_set_config(uint8_t smart_port, uint8_t adi_port, adi_port_config_e_t type) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); vexDeviceAdiPortConfigSet(device->device_info, adi_port, (V5_AdiPortConfiguration)type); return_port(smart_port - 1, 1); } int32_t ext_adi_port_set_value(uint8_t smart_port, uint8_t adi_port, int32_t value) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); vexDeviceAdiValueSet(device->device_info, adi_port, value); return_port(smart_port - 1, 1); } int32_t ext_adi_analog_calibrate(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_ANALOG_IN); uint32_t total = 0; for (uint32_t i = 0; i < 512; i++) { total += vexDeviceAdiValueGet(device->device_info, adi_port); task_delay(1); // TODO: If smart ports (and the ADI) only update every 10ms, this really only reads 56 samples, // maybe change to a 10ms } adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; adi_data->analog_data.calib = (int32_t)((total + 16) >> 5); return_port(smart_port - 1, (int32_t)((total + 256) >> 9)); } int32_t ext_adi_analog_read(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_ANALOG_IN); int32_t rtn = vexDeviceAdiValueGet(device->device_info, adi_port); return_port(smart_port - 1, rtn); } int32_t ext_adi_analog_read_calibrated(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_ANALOG_IN); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; int32_t rtn = vexDeviceAdiValueGet(device->device_info, adi_port) - (adi_data->analog_data.calib >> 4); return_port(smart_port - 1, rtn); } int32_t ext_adi_analog_read_calibrated_HR(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_ANALOG_IN); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; int32_t rtn = (vexDeviceAdiValueGet(device->device_info, adi_port) << 4) - adi_data->analog_data.calib; return_port(smart_port - 1, rtn); } int32_t ext_adi_digital_read(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_DIGITAL_IN); int32_t rtn = vexDeviceAdiValueGet(device->device_info, adi_port); return_port(smart_port - 1, rtn); } int32_t ext_adi_digital_get_new_press(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_DIGITAL_IN); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; int32_t pressed = vexDeviceAdiValueGet(device->device_info, adi_port); if (!pressed) adi_data->digital_data.was_pressed = false; else if (!adi_data->digital_data.was_pressed) { // Button is currently pressed and was not detected as being pressed during last check adi_data->digital_data.was_pressed = true; return_port(smart_port - 1, true); } return_port(smart_port - 1, false); } int32_t ext_adi_digital_write(uint8_t smart_port, uint8_t adi_port, bool value) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_DIGITAL_OUT); vexDeviceAdiValueSet(device->device_info, adi_port, (int32_t)value); return_port(smart_port - 1, 1); } int32_t ext_adi_pin_mode(uint8_t smart_port, uint8_t adi_port, uint8_t mode) { switch (mode) { case INPUT: ext_adi_port_set_config(smart_port, adi_port, E_ADI_DIGITAL_IN); break; case OUTPUT: ext_adi_port_set_config(smart_port, adi_port, E_ADI_DIGITAL_OUT); break; case INPUT_ANALOG: ext_adi_port_set_config(smart_port, adi_port, E_ADI_ANALOG_IN); break; case OUTPUT_ANALOG: ext_adi_port_set_config(smart_port, adi_port, E_ADI_ANALOG_OUT); break; default: errno = EINVAL; return PROS_ERR; }; return 1; } int32_t ext_adi_motor_set(uint8_t smart_port, uint8_t adi_port, int8_t speed) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_motor(device, adi_port, smart_port - 1); if (speed > ADI_MOTOR_MAX_SPEED) speed = ADI_MOTOR_MAX_SPEED; else if (speed < ADI_MOTOR_MIN_SPEED) speed = ADI_MOTOR_MIN_SPEED; vexDeviceAdiValueSet(device->device_info, adi_port, speed); return_port(smart_port - 1, 1); } int32_t ext_adi_motor_get(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_motor(device, adi_port, smart_port - 1); int32_t rtn = vexDeviceAdiValueGet(device->device_info, adi_port) - ADI_MOTOR_MAX_SPEED; return_port(smart_port - 1, rtn); } int32_t ext_adi_motor_stop(uint8_t smart_port, uint8_t adi_port) { return ext_adi_motor_set(smart_port, adi_port, 0); } ext_adi_encoder_t ext_adi_encoder_init(uint8_t smart_port, uint8_t adi_port_top, uint8_t adi_port_bottom, bool reverse) { transform_adi_port(adi_port_top); transform_adi_port(adi_port_bottom); validate_twowire(adi_port_top, adi_port_bottom); claim_port_i(smart_port - 1, E_DEVICE_ADI); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[port]; adi_data->encoder_data.reversed = reverse; vexDeviceAdiPortConfigSet(device->device_info, port, E_ADI_LEGACY_ENCODER); return_port(smart_port - 1, merge_adi_ports(smart_port, port + 1)); } int32_t ext_adi_encoder_get(ext_adi_encoder_t enc) { uint8_t smart_port, adi_port; get_ports(enc, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_ENCODER); int32_t rtn; adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; if (adi_data->encoder_data.reversed) rtn = -vexDeviceAdiValueGet(device->device_info, adi_port); else rtn = vexDeviceAdiValueGet(device->device_info, adi_port); return_port(smart_port - 1, rtn); } int32_t ext_adi_encoder_reset(ext_adi_encoder_t enc) { uint8_t smart_port, adi_port; get_ports(enc, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_ENCODER); vexDeviceAdiValueSet(device->device_info, adi_port, 0); return_port(smart_port - 1, 1); } int32_t ext_adi_encoder_shutdown(ext_adi_encoder_t enc) { uint8_t smart_port, adi_port; get_ports(enc, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_ENCODER); vexDeviceAdiPortConfigSet(device->device_info, adi_port, E_ADI_TYPE_UNDEFINED); return_port(smart_port - 1, 1); } ext_adi_ultrasonic_t ext_adi_ultrasonic_init(uint8_t smart_port, uint8_t adi_port_ping, uint8_t adi_port_echo) { transform_adi_port(adi_port_ping); transform_adi_port(adi_port_echo); validate_twowire(adi_port_ping, adi_port_echo); if (port != adi_port_ping) { errno = EINVAL; return PROS_ERR; } claim_port_i(smart_port - 1, E_DEVICE_ADI); vexDeviceAdiPortConfigSet(device->device_info, port, E_ADI_LEGACY_ULTRASONIC); return_port(smart_port - 1, merge_adi_ports(smart_port, port + 1)); } int32_t ext_adi_ultrasonic_get(ext_adi_ultrasonic_t ult) { uint8_t smart_port, adi_port; get_ports(ult, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_ULTRASONIC); int32_t rtn = vexDeviceAdiValueGet(device->device_info, adi_port); return_port(smart_port - 1, rtn); } int32_t ext_adi_ultrasonic_shutdown(ext_adi_ultrasonic_t ult) { uint8_t smart_port, adi_port; get_ports(ult, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_ULTRASONIC); vexDeviceAdiPortConfigSet(device->device_info, adi_port, E_ADI_TYPE_UNDEFINED); return_port(smart_port - 1, 1); } ext_adi_gyro_t ext_adi_gyro_init(uint8_t smart_port, uint8_t adi_port, double multiplier) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); if (multiplier == 0) multiplier = 1; adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; adi_data->gyro_data.multiplier = multiplier; adi_data->gyro_data.tare_value = 0; adi_port_config_e_t config = vexDeviceAdiPortConfigGet(device->device_info, adi_port); if (config == E_ADI_LEGACY_GYRO) { // Port has already been calibrated, no need to do that again return_port(smart_port - 1, merge_adi_ports(smart_port, adi_port + 1)); } vexDeviceAdiPortConfigSet(device->device_info, adi_port, E_ADI_LEGACY_GYRO); if (xTaskGetSchedulerState() == taskSCHEDULER_RUNNING) { // If the scheduler is currently running (meaning that this is not called // from a global constructor, for example) then delay for the duration of // the calibration time in VexOS. delay(GYRO_CALIBRATION_TIME); } return_port(smart_port - 1, merge_adi_ports(smart_port, adi_port + 1)); } double ext_adi_gyro_get(ext_adi_gyro_t gyro) { uint8_t smart_port, adi_port; get_ports(gyro, smart_port, adi_port); transform_adi_port(adi_port); claim_port_f(smart_port - 1, E_DEVICE_ADI); validate_type_f(device, adi_port, smart_port - 1, E_ADI_LEGACY_GYRO); double rtv = (double)vexDeviceAdiValueGet(device->device_info, adi_port); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; rtv -= adi_data->gyro_data.tare_value; rtv *= adi_data->gyro_data.multiplier; return_port(smart_port - 1, rtv); } int32_t ext_adi_gyro_reset(ext_adi_gyro_t gyro) { uint8_t smart_port, adi_port; get_ports(gyro, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_GYRO); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; adi_data->gyro_data.tare_value = vexDeviceAdiValueGet(device->device_info, adi_port); return_port(smart_port - 1, 1); } int32_t ext_adi_gyro_shutdown(ext_adi_gyro_t gyro) { uint8_t smart_port, adi_port; get_ports(gyro, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_LEGACY_GYRO); vexDeviceAdiPortConfigSet(device->device_info, adi_port, E_ADI_TYPE_UNDEFINED); return_port(smart_port - 1, 1); } ext_adi_potentiometer_t ext_adi_potentiometer_init(uint8_t smart_port, uint8_t adi_port, adi_potentiometer_type_e_t potentiometer_type) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; adi_data->potentiometer_data.potentiometer_type = potentiometer_type; vexDeviceAdiPortConfigSet(device->device_info, adi_port, E_ADI_ANALOG_IN); return_port(smart_port - 1, merge_adi_ports(smart_port, adi_port + 1)); } double ext_adi_potentiometer_get_angle(ext_adi_potentiometer_t potentiometer) { double rtn; uint8_t smart_port, adi_port; get_ports(potentiometer, smart_port, adi_port); transform_adi_port(adi_port); claim_port_f(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_ANALOG_IN); adi_data_s_t* const adi_data = &((adi_data_s_t*)(device->pad))[adi_port]; switch (adi_data->potentiometer_data.potentiometer_type) { case E_ADI_POT_EDR: rtn = vexDeviceAdiValueGet(device->device_info, adi_port) * 250 / 4095.0; break; case E_ADI_POT_V2: rtn = vexDeviceAdiValueGet(device->device_info, adi_port) * 330 / 4095.0; break; default: errno = ENXIO; rtn = PROS_ERR_F; } return_port(smart_port - 1, rtn); } ext_adi_led_t ext_adi_led_init(uint8_t smart_port, uint8_t adi_port) { transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); vexDeviceAdiPortConfigSet(device->device_info, adi_port, (V5_AdiPortConfiguration)E_ADI_DIGITAL_OUT); return_port(smart_port - 1, merge_adi_ports(smart_port, adi_port + 1)); } int32_t ext_adi_led_set(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length) { uint8_t smart_port, adi_port; get_ports(led, smart_port, adi_port); transform_adi_port(adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); validate_type(device, adi_port, smart_port - 1, E_ADI_DIGITAL_OUT); if (buffer_length > MAX_LED) { buffer_length = MAX_LED; } else if (buffer == NULL || buffer_length < 1) { errno = EINVAL; return_port(smart_port - 1, PROS_ERR); } uint32_t rtv = (uint32_t)vexDeviceAdiAddrLedSet(device->device_info, adi_port, buffer, 0, buffer_length, 0); return_port(smart_port - 1, rtv); } int32_t ext_adi_led_set_pixel(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color, uint32_t pixel_position) { uint8_t smart_port, adi_port; get_ports(led, smart_port, adi_port); claim_port_i(smart_port - 1, E_DEVICE_ADI); transform_adi_port(adi_port); validate_type(device, adi_port, smart_port - 1, E_ADI_DIGITAL_OUT); if (buffer == NULL || pixel_position < 0 || buffer_length >= MAX_LED || buffer_length < 1 || pixel_position > buffer_length - 1) { errno = EINVAL; return_port(smart_port - 1, PROS_ERR); } buffer[pixel_position] = color; uint32_t rtv = (uint32_t)vexDeviceAdiAddrLedSet(device->device_info, adi_port, buffer, 0, buffer_length, 0); return_port(smart_port - 1, rtv); } int32_t ext_adi_led_set_all(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t color) { for (int i = 0; i < buffer_length; i++) { buffer[i] = color; } return ext_adi_led_set(led, buffer, buffer_length); } int32_t ext_adi_led_clear_all(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length) { return ext_adi_led_set_all(led, buffer, buffer_length, 0); } int32_t ext_adi_led_clear_pixel(ext_adi_led_t led, uint32_t* buffer, uint32_t buffer_length, uint32_t pixel_position) { return ext_adi_led_set_pixel(led, buffer, buffer_length, 0, pixel_position); } ================================================ FILE: src/devices/vdml_gps.c ================================================ /** * \file devices/vdml_gps.c * * Contains functions for interacting with the VEX GPS. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "pros/gps.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define GPS_MINIMUM_DATA_RATE 5 #define GPS_STATUS_ERR_INIT \ { .x = PROS_ERR_F, .y = PROS_ERR_F, .roll = PROS_ERR_F, .pitch = PROS_ERR_F, .yaw = PROS_ERR_F } #define GPS_RAW_ERR_INIT \ { .x = PROS_ERR_F, .y = PROS_ERR_F, .z = PROS_ERR_F } int32_t gps_initialize_full(uint8_t port, double xInitial, double yInitial, double headingInitial, double xOffset, double yOffset) { claim_port_i(port - 1, E_DEVICE_GPS); vexDeviceGpsOriginSet(device->device_info, xOffset, yOffset); vexDeviceGpsInitialPositionSet(device->device_info, xInitial, yInitial, headingInitial); return_port(port - 1, PROS_SUCCESS); } int32_t gps_set_offset(uint8_t port, double xOffset, double yOffset) { claim_port_i(port - 1, E_DEVICE_GPS); vexDeviceGpsOriginSet(device->device_info, xOffset, yOffset); return_port(port - 1, PROS_SUCCESS); } gps_position_s_t gps_get_offset(uint8_t port) { gps_position_s_t rtv = {PROS_ERR_F, PROS_ERR_F}; if (!claim_port_try(port - 1, E_DEVICE_GPS)) { return rtv; } // This is necessary for warning suppression as a packed struct's address // may be misaligned. double x = PROS_ERR_F; double y = PROS_ERR_F; v5_smart_device_s_t* device = registry_get_device(port - 1); vexDeviceGpsOriginGet(device->device_info, &x, &y); rtv.x = x; rtv.y = y; return_port(port - 1, rtv); } int32_t gps_set_position(uint8_t port, double xInitial, double yInitial, double headingInitial) { claim_port_i(port - 1, E_DEVICE_GPS); vexDeviceGpsInitialPositionSet(device->device_info, xInitial, yInitial, headingInitial); return_port(port - 1, PROS_SUCCESS); } int32_t gps_set_data_rate(uint8_t port, uint32_t rate) { claim_port_i(port - 1, E_DEVICE_GPS); // rate is not less than 5ms, and rounded down to nearest increment of 5 if (rate < GPS_MINIMUM_DATA_RATE) { rate = GPS_MINIMUM_DATA_RATE; } else { rate -= rate % GPS_MINIMUM_DATA_RATE; } vexDeviceGpsDataRateSet(device->device_info, rate); return_port(port - 1, PROS_SUCCESS); } double gps_get_error(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); double rtv = vexDeviceGpsErrorGet(device->device_info); return_port(port - 1, rtv); } gps_status_s_t gps_get_position_and_orientation(uint8_t port) { gps_status_s_t rtv = GPS_STATUS_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_GPS)) { return rtv; } v5_smart_device_s_t* device = registry_get_device(port - 1); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); rtv.x = data.position_x; rtv.y = data.position_y; rtv.pitch = data.pitch; rtv.roll = data.roll; rtv.yaw = data.yaw; return_port(port - 1, rtv); } gps_position_s_t gps_get_position(uint8_t port) { gps_position_s_t rtv = {PROS_ERR_F, PROS_ERR_F}; if (!claim_port_try(port - 1, E_DEVICE_GPS)) { return rtv; } v5_smart_device_s_t* device = registry_get_device(port - 1); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); rtv.x = data.position_x; rtv.y = data.position_y; return_port(port - 1, rtv); } double gps_get_position_x(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); double rtv = data.position_x; return_port(port - 1, rtv); } double gps_get_position_y(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); double rtv = data.position_y; return_port(port - 1, rtv); } gps_orientation_s_t gps_get_orientation(uint8_t port) { gps_orientation_s_t rtv = {PROS_ERR_F, PROS_ERR_F, PROS_ERR_F}; if (!claim_port_try(port - 1, E_DEVICE_GPS)) { return rtv; } v5_smart_device_s_t* device = registry_get_device(port - 1); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); rtv.pitch = data.pitch; rtv.roll = data.roll; rtv.yaw = data.yaw; return_port(port - 1, rtv); } double gps_get_pitch(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); double rtv = data.pitch; return_port(port - 1, rtv); } double gps_get_roll(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); double rtv = data.roll; return_port(port - 1, rtv); } double gps_get_yaw(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsAttitude data; vexDeviceGpsAttitudeGet(device->device_info, &data, false); double rtv = data.yaw; return_port(port - 1, rtv); } double gps_get_heading(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); double rtv = vexDeviceGpsDegreesGet(device->device_info); return_port(port - 1, rtv); } double gps_get_heading_raw(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); double rtv = vexDeviceGpsHeadingGet(device->device_info); return_port(port - 1, rtv); } gps_gyro_s_t gps_get_gyro_rate(uint8_t port) { gps_gyro_s_t rtv = GPS_RAW_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_GPS)) { return rtv; } v5_smart_device_s_t* device = registry_get_device(port - 1); V5_DeviceGpsRaw data; vexDeviceGpsRawGyroGet(device->device_info, &data); rtv.x = data.x; rtv.y = data.y; rtv.z = data.z; return_port(port - 1, rtv); } double gps_get_gyro_rate_x(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsRaw data; vexDeviceGpsRawGyroGet(device->device_info, &data); double rtv = data.x; return_port(port - 1, rtv); } double gps_get_gyro_rate_y(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsRaw data; vexDeviceGpsRawGyroGet(device->device_info, &data); double rtv = data.y; return_port(port - 1, rtv); } double gps_get_gyro_rate_z(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsRaw data; vexDeviceGpsRawGyroGet(device->device_info, &data); double rtv = data.z; return_port(port - 1, rtv); } gps_accel_s_t gps_get_accel(uint8_t port) { gps_accel_s_t rtv = GPS_RAW_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_GPS)) { return rtv; } v5_smart_device_s_t* device = registry_get_device(port - 1); V5_DeviceGpsRaw data; vexDeviceGpsRawAccelGet(device->device_info, &data); rtv.x = data.x; rtv.y = data.y; rtv.z = data.z; return_port(port - 1, rtv); } double gps_get_accel_x(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsRaw data; vexDeviceGpsRawAccelGet(device->device_info, &data); double rtv = data.x; return_port(port - 1, rtv); } double gps_get_accel_y(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsRaw data; vexDeviceGpsRawAccelGet(device->device_info, &data); double rtv = data.y; return_port(port - 1, rtv); } double gps_get_accel_z(uint8_t port) { claim_port_f(port - 1, E_DEVICE_GPS); V5_DeviceGpsRaw data; vexDeviceGpsRawAccelGet(device->device_info, &data); double rtv = data.z; return_port(port - 1, rtv); } ================================================ FILE: src/devices/vdml_gps.cpp ================================================ /** * \file devices/vdml_gps.cpp * * Contains functions for interacting with the VEX GPS. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/device.h" #include "pros/gps.hpp" #include "vdml/vdml.h" namespace pros { inline namespace v5 { std::int32_t Gps::initialize_full(double xInitial, double yInitial, double headingInitial, double xOffset, double yOffset) const { return pros::c::gps_initialize_full(_port, xInitial, yInitial, headingInitial, xOffset, yOffset); } std::int32_t Gps::set_offset(double xOffset, double yOffset) const { return pros::c::gps_set_offset(_port, xOffset, yOffset); } pros::gps_position_s_t Gps::get_offset() const { return pros::c::gps_get_offset(_port); } std::int32_t Gps::set_position(double xInitial, double yInitial, double headingInitial) const { return pros::c::gps_set_position(_port, xInitial, yInitial, headingInitial); } std::int32_t Gps::set_data_rate(std::uint32_t rate) const { return pros::c::gps_set_data_rate(_port, rate); } std::vector Gps::get_all_devices() { std::vector matching_devices {Device::get_all_devices(DeviceType::gps)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } double Gps::get_error() const { return pros::c::gps_get_error(_port); } pros::gps_status_s_t Gps::get_position_and_orientation() const { return pros::c::gps_get_position_and_orientation(_port); } pros::gps_position_s_t Gps::get_position() const { return pros::c::gps_get_position(_port); } double Gps::get_position_x() const { return pros::c::gps_get_position_x(_port); } double Gps::get_position_y() const { return pros::c::gps_get_position_y(_port); } pros::gps_orientation_s_t Gps::get_orientation() const { return pros::c::gps_get_orientation(_port); } double Gps::get_pitch() const { return pros::c::gps_get_pitch(_port); } double Gps::get_roll() const { return pros::c::gps_get_roll(_port); } double Gps::get_yaw() const { return pros::c::gps_get_yaw(_port); } double Gps::get_heading() const { return pros::c::gps_get_heading(_port); } double Gps::get_heading_raw() const { return pros::c::gps_get_heading_raw(_port); } pros::gps_gyro_s_t Gps::get_gyro_rate() const { return pros::c::gps_get_gyro_rate(_port); } double Gps::get_gyro_rate_x() const { return pros::c::gps_get_gyro_rate_x(_port); } double Gps::get_gyro_rate_y() const { return pros::c::gps_get_gyro_rate_y(_port); } double Gps::get_gyro_rate_z() const { return pros::c::gps_get_gyro_rate_z(_port); } pros::gps_accel_s_t Gps::get_accel() const { return pros::c::gps_get_accel(_port); } double Gps::get_accel_x() const { return pros::c::gps_get_accel_x(_port); } double Gps::get_accel_y() const { return pros::c::gps_get_accel_y(_port); } double Gps::get_accel_z() const { return pros::c::gps_get_accel_z(_port); } std::ostream& operator<<(std::ostream& os, const pros::Gps& gps) { pros::gps_status_s_t data = gps.get_position_and_orientation(); os << "Gps ["; os << "port: " << gps._port; os << ", x: " << data.x; os << ", y: " << data.y; os << ", heading: " << gps.get_heading(); os << "]"; return os; } pros::Gps pros::Gps::get_gps() { static int curr_gps_port = 0; curr_gps_port = curr_gps_port % 21; for (int i = 0; i < 21; i++) { if (registry_get_device(curr_gps_port)->device_type == pros::c::E_DEVICE_GPS) { curr_gps_port++; return Gps(curr_gps_port); } curr_gps_port++; curr_gps_port = curr_gps_port % 21; } errno = ENODEV; return Gps(PROS_ERR_BYTE); } namespace literals { const pros::Gps operator""_gps(const unsigned long long int g) { return pros::Gps(g); } } // namespace literals } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_imu.c ================================================ /** * \file devices/vdml_imu.c * * Contains functions for interacting with the VEX Inertial sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "pros/imu.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define IMU_EULER_LIMIT 180 #define IMU_HEADING_MAX 360 #define DEGTORAD (M_PI / 180) #define ERROR_IMU_STILL_CALIBRATING(port, device, err_return) \ if (vexDeviceImuStatusGet(device->device_info) & E_IMU_STATUS_CALIBRATING) { \ errno = EAGAIN; \ return_port(port - 1, err_return); \ } #define IMU_RESET_FLAG_SET_TIMEOUT 1000 #define IMU_RESET_TIMEOUT 3000 // Canonically this should be 2s, but 3s for good margin typedef struct __attribute__((packed, __may_alias__)) imu_reset_data { double heading_offset; double rotation_offset; double pitch_offset; double yaw_offset; double roll_offset; } imu_data_s_t; int32_t imu_reset(uint8_t port) { claim_port_i(port - 1, E_DEVICE_IMU); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); vexDeviceImuReset(device->device_info); // delay for vexos to set calibration flag, background processing must be called for flag // to be set. uint16_t timeoutCount = 0; // releasing mutex so vexBackgrounProcessing can run without being blocked. do { port_mutex_give(port - 1); task_delay(5); timeoutCount += 5; claim_port_i(port - 1, E_DEVICE_IMU); if (timeoutCount >= IMU_RESET_FLAG_SET_TIMEOUT) { port_mutex_give(port - 1); errno = EAGAIN; return PROS_ERR; } device = device; // suppressing compiler warning } while (!(vexDeviceImuStatusGet(device->device_info) & E_IMU_STATUS_CALIBRATING)); port_mutex_give(port - 1); return 1; } int32_t imu_reset_blocking(uint8_t port) { claim_port_i(port - 1, E_DEVICE_IMU); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); vexDeviceImuReset(device->device_info); // delay for vexos to set calibration flag, background processing must be called for flag // to be set. uint16_t timeoutCount = 0; // releasing mutex so vexBackgroundProcessing can run without being blocked. do { port_mutex_give(port - 1); task_delay(5); timeoutCount += 5; claim_port_i(port - 1, E_DEVICE_IMU); if (timeoutCount >= IMU_RESET_FLAG_SET_TIMEOUT) { port_mutex_give(port - 1); errno = EAGAIN; return PROS_ERR; } device = device; // suppressing compiler warning } while (!(vexDeviceImuStatusGet(device->device_info) & E_IMU_STATUS_CALIBRATING)); // same concept here, we add a blocking delay for the blocking version to wait // until the IMU calibrating flag is cleared do { port_mutex_give(port - 1); task_delay(5); timeoutCount += 5; claim_port_i(port - 1, E_DEVICE_IMU); if (timeoutCount >= IMU_RESET_TIMEOUT) { port_mutex_give(port - 1); errno = EAGAIN; return PROS_ERR; } device = device; // suppressing compiler warning } while (vexDeviceImuStatusGet(device->device_info) & E_IMU_STATUS_CALIBRATING); port_mutex_give(port - 1); return 1; } int32_t imu_set_data_rate(uint8_t port, uint32_t rate) { claim_port_i(port - 1, E_DEVICE_IMU); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); // rate is not less than 5ms, and rounded down to nearest increment of 5 if (rate < IMU_MINIMUM_DATA_RATE) { rate = IMU_MINIMUM_DATA_RATE; } else { rate -= rate % IMU_MINIMUM_DATA_RATE; } vexDeviceImuDataRateSet(device->device_info, rate); return_port(port - 1, PROS_SUCCESS); } double imu_get_rotation(uint8_t port) { claim_port_f(port - 1, E_DEVICE_IMU); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR_F); double rtn = vexDeviceImuHeadingGet(device->device_info) + ((imu_data_s_t*)registry_get_device(port - 1)->pad)->rotation_offset; return_port(port - 1, rtn); } double imu_get_heading(uint8_t port) { claim_port_f(port - 1, E_DEVICE_IMU); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR_F); double rtn = vexDeviceImuDegreesGet(device->device_info) + ((imu_data_s_t*)registry_get_device(port - 1)->pad)->heading_offset; // Restricting value to raw boundaries return_port(port - 1, fmod((rtn + IMU_HEADING_MAX), (double)IMU_HEADING_MAX)); } #define QUATERNION_ERR_INIT \ { .x = PROS_ERR_F, .y = PROS_ERR_F, .z = PROS_ERR_F, .w = PROS_ERR_F } quaternion_s_t imu_get_quaternion(uint8_t port) { quaternion_s_t rtn = QUATERNION_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, rtn); euler_s_t euler; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler); imu_data_s_t* data = (imu_data_s_t*)device->pad; // To calculate the quaternion values, we first get the euler values, add the offsets, // and then do the calculations. double roll = fmod(euler.roll + data->roll_offset, 2.0 * IMU_EULER_LIMIT); double yaw = fmod(euler.yaw + data->yaw_offset, 2.0 * IMU_EULER_LIMIT); double pitch = fmod(euler.pitch + data->pitch_offset, 2.0 * IMU_EULER_LIMIT); double cy = cos(DEGTORAD * yaw * 0.5); double sy = sin(DEGTORAD * yaw * 0.5); double cp = cos(DEGTORAD * pitch * 0.5); double sp = sin(DEGTORAD * pitch * 0.5); double cr = cos(DEGTORAD * roll * 0.5); double sr = sin(DEGTORAD * roll * 0.5); rtn.w = cr * cp * cy + sr * sp * sy; rtn.x = sr * cp * cy - cr * sp * sy; rtn.y = cr * sp * cy + sr * cp * sy; rtn.z = cr * cp * sy - sr * sp * cy; return_port(port - 1, rtn); } #define ATTITUDE_ERR_INIT \ { .pitch = PROS_ERR_F, .roll = PROS_ERR_F, .yaw = PROS_ERR_F } euler_s_t imu_get_euler(uint8_t port) { euler_s_t rtn = ATTITUDE_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } v5_smart_device_s_t* device = registry_get_device(port - 1); imu_data_s_t* data = (imu_data_s_t*)device->pad; ERROR_IMU_STILL_CALIBRATING(port, device, rtn); vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&rtn); rtn.pitch += data->pitch_offset; rtn.yaw += data->yaw_offset; rtn.roll += data->roll_offset; rtn.roll = fmod(rtn.roll, 2.0 * IMU_EULER_LIMIT); rtn.yaw = fmod(rtn.yaw, 2.0 * IMU_EULER_LIMIT); rtn.pitch = fmod(rtn.pitch, 2.0 * IMU_EULER_LIMIT); return_port(port - 1, rtn); } double imu_get_pitch(uint8_t port) { double rtn = PROS_ERR_F; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } euler_s_t euler_values; v5_smart_device_s_t* device = registry_get_device(port - 1); vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); rtn = euler_values.pitch + ((imu_data_s_t*)registry_get_device(port - 1)->pad)->pitch_offset; // Restricting value to raw boundaries return_port(port - 1, fmod(rtn, 2.0 * IMU_EULER_LIMIT)); } double imu_get_roll(uint8_t port) { double rtn = PROS_ERR_F; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } euler_s_t euler_values; v5_smart_device_s_t* device = registry_get_device(port - 1); vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); rtn = euler_values.roll + ((imu_data_s_t*)registry_get_device(port - 1)->pad)->roll_offset; // Restricting value to raw boundaries return_port(port - 1, fmod(rtn, 2.0 * IMU_EULER_LIMIT)); } double imu_get_yaw(uint8_t port) { double rtn = PROS_ERR_F; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } euler_s_t euler_values; v5_smart_device_s_t* device = registry_get_device(port - 1); vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); rtn = euler_values.yaw + ((imu_data_s_t*)registry_get_device(port - 1)->pad)->yaw_offset; // Restricting value to raw boundaries return_port(port - 1, fmod(rtn, 2.0 * IMU_EULER_LIMIT)); } #define RAW_IMU_ERR_INIT {.x = PROS_ERR_F, .y = PROS_ERR_F, .z = PROS_ERR_F}; imu_gyro_s_t imu_get_gyro_rate(uint8_t port) { imu_gyro_s_t rtn = RAW_IMU_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, rtn); // NOTE: `V5_DeviceImuRaw` has the same form as a quaternion, but this call // never fills the `w` field, so we make a dummy quaternion container and copy // the (x,y,z) part into the return struct quaternion_s_t dummy; vexDeviceImuRawGyroGet(device->device_info, (V5_DeviceImuRaw*)&dummy); rtn.x = dummy.x; rtn.y = dummy.y; rtn.z = dummy.z; return_port(port - 1, rtn); } imu_accel_s_t imu_get_accel(uint8_t port) { imu_accel_s_t rtn = RAW_IMU_ERR_INIT; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, rtn); // NOTE: this is the same as `imu_get_raw_gyro` quaternion_s_t dummy; vexDeviceImuRawAccelGet(device->device_info, (V5_DeviceImuRaw*)&dummy); rtn.x = dummy.x; rtn.y = dummy.y; rtn.z = dummy.z; return_port(port - 1, rtn); } imu_status_e_t imu_get_status(uint8_t port) { imu_status_e_t rtn = E_IMU_STATUS_ERROR; if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return rtn; } v5_smart_device_s_t* device = registry_get_device(port - 1); rtn = vexDeviceImuStatusGet(device->device_info); return_port(port - 1, rtn); } // Reset Functions: int32_t imu_tare(uint8_t port) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; data->rotation_offset = -vexDeviceImuHeadingGet(device->device_info); data->heading_offset = -vexDeviceImuDegreesGet(device->device_info); data->pitch_offset = -euler_values.pitch; data->roll_offset = -euler_values.roll; data->yaw_offset = -euler_values.yaw; return_port(port - 1, PROS_SUCCESS); } int32_t imu_tare_euler(uint8_t port) { return imu_set_euler(port, (euler_s_t){0, 0, 0}); } int32_t imu_tare_heading(uint8_t port) { return imu_set_heading(port, 0); } int32_t imu_tare_rotation(uint8_t port) { return imu_set_rotation(port, 0); } int32_t imu_tare_pitch(uint8_t port) { return imu_set_pitch(port, 0); } int32_t imu_tare_roll(uint8_t port) { return imu_set_roll(port, 0); } int32_t imu_tare_yaw(uint8_t port) { return imu_set_yaw(port, 0); } // Setter Functions: int32_t imu_set_rotation(uint8_t port, double target) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; data->rotation_offset = target - vexDeviceImuHeadingGet(device->device_info); return_port(port - 1, PROS_SUCCESS); } int32_t imu_set_heading(uint8_t port, double target) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; if (target > IMU_HEADING_MAX) target = IMU_HEADING_MAX; if (target < 0) target = 0; data->heading_offset = target - vexDeviceImuDegreesGet(device->device_info); return_port(port - 1, PROS_SUCCESS); } int32_t imu_set_pitch(uint8_t port, double target) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; if (target > IMU_EULER_LIMIT) target = IMU_EULER_LIMIT; if (target < -IMU_EULER_LIMIT) target = -IMU_EULER_LIMIT; data->pitch_offset = target - euler_values.pitch; return_port(port - 1, PROS_SUCCESS); } int32_t imu_set_roll(uint8_t port, double target) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; if (target > IMU_EULER_LIMIT) target = IMU_EULER_LIMIT; if (target < -IMU_EULER_LIMIT) target = -IMU_EULER_LIMIT; data->roll_offset = target - euler_values.roll; return_port(port - 1, PROS_SUCCESS); } int32_t imu_set_yaw(uint8_t port, double target) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); ERROR_IMU_STILL_CALIBRATING(port, device, PROS_ERR); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; data->yaw_offset = target - euler_values.yaw; if (target > IMU_EULER_LIMIT) target = IMU_EULER_LIMIT; if (target < -IMU_EULER_LIMIT) target = -IMU_EULER_LIMIT; return_port(port - 1, PROS_SUCCESS); } int32_t imu_set_euler(uint8_t port, euler_s_t target) { if (!claim_port_try(port - 1, E_DEVICE_IMU)) { return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); euler_s_t euler_values; vexDeviceImuAttitudeGet(device->device_info, (V5_DeviceImuAttitude*)&euler_values); imu_data_s_t* data = (imu_data_s_t*)device->pad; if (target.pitch > IMU_EULER_LIMIT) target.pitch = IMU_EULER_LIMIT; if (target.pitch < -IMU_EULER_LIMIT) target.pitch = -IMU_EULER_LIMIT; if (target.yaw > IMU_EULER_LIMIT) target.yaw = IMU_EULER_LIMIT; if (target.yaw < -IMU_EULER_LIMIT) target.yaw = -IMU_EULER_LIMIT; if (target.roll > IMU_EULER_LIMIT) target.roll = IMU_EULER_LIMIT; if (target.roll < -IMU_EULER_LIMIT) target.roll = -IMU_EULER_LIMIT; data->pitch_offset = target.pitch - euler_values.pitch; data->roll_offset = target.roll - euler_values.roll; data->yaw_offset = target.yaw - euler_values.yaw; return_port(port - 1, PROS_SUCCESS); } imu_orientation_e_t imu_get_physical_orientation(uint8_t port) { imu_status_e_t status = imu_get_status(port); if (status == E_IMU_STATUS_ERROR) { return E_IMU_ORIENTATION_ERROR; } return (status >> 1) & 7; } ================================================ FILE: src/devices/vdml_imu.cpp ================================================ /** * \file devices/vdml_imu.cpp * * Contains functions for interacting with the VEX Inertial sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "pros/imu.hpp" #include "vdml/vdml.h" namespace pros { inline namespace v5 { std::int32_t Imu::reset(bool blocking /*= false*/) const { return blocking ? pros::c::imu_reset_blocking(_port) : pros::c::imu_reset(_port); } std::int32_t Imu::set_data_rate(std::uint32_t rate) const { return pros::c::imu_set_data_rate(_port, rate); } std::vector Imu::get_all_devices() { std::vector matching_devices {Device::get_all_devices(DeviceType::imu)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } double Imu::get_rotation() const { return pros::c::imu_get_rotation(_port); } double Imu::get_heading() const { return pros::c::imu_get_heading(_port); } pros::quaternion_s_t Imu::get_quaternion() const { return pros::c::imu_get_quaternion(_port); } pros::euler_s_t Imu::get_euler() const { return pros::c::imu_get_euler(_port); } double Imu::get_pitch() const { return get_euler().pitch; } double Imu::get_roll() const { return get_euler().roll; } double Imu::get_yaw() const { return get_euler().yaw; } pros::imu_gyro_s_t Imu::get_gyro_rate() const { return pros::c::imu_get_gyro_rate(_port); } pros::imu_accel_s_t Imu::get_accel() const { return pros::c::imu_get_accel(_port); } pros::ImuStatus Imu::get_status() const { return static_cast(pros::c::imu_get_status(_port)); } bool Imu::is_calibrating() const { imu_status_e_t status = pros::c::imu_get_status(_port); if (status == E_IMU_STATUS_ERROR) { return false; } return status & E_IMU_STATUS_CALIBRATING; } std::int32_t Imu::tare_heading() const { return pros::c::imu_tare_heading(_port); } std::int32_t Imu::tare_rotation() const { return pros::c::imu_tare_rotation(_port); } std::int32_t Imu::tare_pitch() const { return pros::c::imu_tare_pitch(_port); } std::int32_t Imu::tare_yaw() const { return pros::c::imu_tare_yaw(_port); } std::int32_t Imu::tare_roll() const { return pros::c::imu_tare_roll(_port); } std::int32_t Imu::tare_euler() const { return pros::c::imu_tare_euler(_port); } std::int32_t Imu::set_heading(double target) const { return pros::c::imu_set_heading(_port, target); } std::int32_t Imu::set_rotation(double target) const { return pros::c::imu_set_rotation(_port, target); } std::int32_t Imu::set_pitch(double target) const { return pros::c::imu_set_pitch(_port, target); } std::int32_t Imu::set_yaw(double target) const { return pros::c::imu_set_yaw(_port, target); } std::int32_t Imu::set_roll(double target) const { return pros::c::imu_set_roll(_port, target); } std::int32_t Imu::set_euler(pros::euler_s_t target) const { return pros::c::imu_set_euler(_port, target); } std::int32_t Imu::tare() const { return pros::c::imu_tare(_port); } imu_orientation_e_t Imu::get_physical_orientation() const { return pros::c::imu_get_physical_orientation(_port); } Imu Imu::get_imu() { static int curr_imu_port = 0; curr_imu_port = curr_imu_port % 21; for (int i = 0; i < 21; i++) { if (registry_get_device(curr_imu_port)->device_type == pros::c::E_DEVICE_IMU) { curr_imu_port++; return Imu(curr_imu_port); } curr_imu_port++; curr_imu_port = curr_imu_port % 21; } errno = ENODEV; return Imu(PROS_ERR_BYTE); } std::ostream& operator<<(std::ostream& os, const pros::Imu& imu) { pros::imu_gyro_s_t gyro = imu.get_gyro_rate(); pros::imu_accel_s_t accel = imu.get_accel(); os << "Imu ["; os << "port: " << imu._port; os << ", rotation: " << imu.get_rotation(); os << ", heading: " << imu.get_heading(); os << ", pitch: " << imu.get_pitch(); os << ", roll: " << imu.get_roll(); os << ", yaw: " << imu.get_yaw(); os << ", gyro rate: " << "{" << gyro.x << "," << gyro.y << "," << gyro.z << "}"; os << ", get accel: " << "{" << accel.x << "," << accel.y << "," << accel.z << "}"; os << ", calibrating: " << imu.is_calibrating(); os << "]"; return os; } namespace literals { const pros::Imu operator""_imu(const unsigned long long int i) { return pros::Imu(i); } } // namespace literals } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_link.c ================================================ /** * \file vdml_link.c * * \brief Contains source code for functions related to the robot to robot communications. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/link.h" #include "kapi.h" #include "pros/apix.h" #include "vdml/vdml.h" #include #define PROTOCOL_SIZE 4 // Protocol Size static const uint8_t START_BYTE = 0x33; // internal function for clearing the rx buffer static uint32_t _clear_rx_buf(v5_smart_device_s_t* device) { uint8_t buf[LINK_BUFFER_SIZE]; return vexDeviceGenericRadioReceive(device->device_info, (uint8_t*)buf, vexDeviceGenericRadioReceiveAvail(device->device_info)); } //custom claim_port style wrapper for link_init due to type mismatching otherwise, limit of one radio per brain static uint32_t _link_init(uint8_t port, const char* link_id, link_type_e_t type, bool ov) { if (!port_mutex_take(port)) { errno = EACCES; return PROS_ERR; } v5_device_e_t plugged_type = registry_get_plugged_type(port); if (plugged_type == E_DEVICE_RADIO || plugged_type == E_DEVICE_NONE) { if (!VALIDATE_PORT_NO(port)) { errno = ENXIO; return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port); vexDeviceGenericRadioConnection(device->device_info, (char* )link_id, type, ov); // Hack: Force v5 to recognize the plugged type as a serial device the next time we touch the device registry_unbind_port(port); return_port(port, PROS_SUCCESS); } errno = ENODEV; return_port(port, PROS_ERR); } uint32_t link_init(uint8_t port, const char* link_id, link_type_e_t type) { return _link_init(port - 1, link_id, type, false); } uint32_t link_init_override(uint8_t port, const char* link_id, link_type_e_t type) { return _link_init(port - 1, link_id, type, true); } bool link_connected(uint8_t port) { claim_port(port - 1, E_DEVICE_SERIAL, false); bool rtv = vexDeviceGenericRadioLinkStatus(device->device_info); return_port(port - 1, rtv); } uint32_t link_raw_receivable_size(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); uint32_t rtv = vexDeviceGenericRadioReceiveAvail(device->device_info); return_port(port - 1, rtv); } uint32_t link_raw_transmittable_size(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); uint32_t rtv = vexDeviceGenericRadioWriteFree(device->device_info); return_port(port - 1, rtv); } uint32_t link_transmit_raw(uint8_t port, void* data, uint16_t data_size) { if(data == NULL) { errno = EINVAL; return PROS_ERR; } claim_port_i(port - 1, E_DEVICE_SERIAL); if(!vexDeviceGenericRadioLinkStatus(device->device_info)) { errno = ENXIO; return_port(port - 1, PROS_ERR); } if(data_size > vexDeviceGenericRadioWriteFree(device->device_info)) { errno = EBUSY; return_port(port - 1, PROS_ERR); } uint32_t rtv = vexDeviceGenericRadioTransmit(device->device_info, (uint8_t*)data, data_size); return_port(port - 1, rtv); } uint32_t link_receive_raw(uint8_t port, void* dest, uint16_t data_size) { if(dest == NULL) { errno = EINVAL; return PROS_ERR; } claim_port_i(port - 1, E_DEVICE_SERIAL); if(!vexDeviceGenericRadioLinkStatus(device->device_info)) { errno = ENXIO; return_port(port - 1, PROS_ERR); } if(data_size > vexDeviceGenericRadioReceiveAvail(device->device_info)) { errno = EBUSY; return_port(port - 1, PROS_ERR); } uint32_t rtv = vexDeviceGenericRadioReceive(device->device_info, (uint8_t*)dest, data_size); return_port(port - 1, rtv); } uint32_t link_transmit(uint8_t port, void* data, uint16_t data_size) { if(data == NULL) { errno = EINVAL; return PROS_ERR; } claim_port_i(port - 1, E_DEVICE_SERIAL); if(!vexDeviceGenericRadioLinkStatus(device->device_info)) { errno = ENXIO; return_port(port - 1, PROS_ERR); } if(data_size + PROTOCOL_SIZE > vexDeviceGenericRadioWriteFree(device->device_info)) { errno = EBUSY; return_port(port - 1, PROS_ERR); } // calculated checksum uint8_t checksum = START_BYTE; uint8_t size_tx_buf[2]; size_tx_buf[1] = (data_size >> 8) & 0xff; size_tx_buf[0] = (data_size) & 0xff; checksum ^= size_tx_buf[1]; checksum ^= size_tx_buf[0]; for(int i = 0; i < data_size; i++) { checksum ^= ((uint8_t*)data)[i]; } uint32_t rtv = 0; // send protocol rtv += vexDeviceGenericRadioTransmit(device->device_info, (uint8_t*)&START_BYTE, 1); rtv += vexDeviceGenericRadioTransmit(device->device_info, size_tx_buf, 2); rtv += vexDeviceGenericRadioTransmit(device->device_info, (uint8_t*)data, data_size); rtv += vexDeviceGenericRadioTransmit(device->device_info, &checksum, 1); return_port(port - 1, rtv); } uint32_t link_receive(uint8_t port, void* dest, uint16_t data_size) { if(dest == NULL) { errno = EINVAL; return PROS_ERR; } claim_port_i(port - 1, E_DEVICE_SERIAL); if(!vexDeviceGenericRadioLinkStatus(device->device_info)) { errno = ENXIO; return_port(port - 1, PROS_ERR); } if(data_size + PROTOCOL_SIZE > vexDeviceGenericRadioReceiveAvail(device->device_info)) { errno = EBUSY; return_port(port - 1, PROS_ERR); } uint8_t header_byte; uint8_t received_size; // process protocol received_size = vexDeviceGenericRadioReceive(device->device_info, &header_byte, 1); // 0x33 if(START_BYTE != header_byte || received_size != 1) { kprintf("[VEXLINK] Invalid Header Byte Received Port %d, header byte: %x", port, header_byte); errno = EBADMSG; return_port(port - 1, PROS_ERR); } // datasize uint16_t received_data_size; received_size = vexDeviceGenericRadioReceive(device->device_info, (uint8_t*)&received_data_size, 2); if(received_size != 2 || received_data_size != data_size) { _clear_rx_buf(device); kprintf("[VEXLINK] Invalid Data Size (Size: %d ) Received Port %d, flushing RX buffer!\n", received_data_size, port); errno = EBADMSG; return_port(port - 1, PROS_ERR); } // receive data uint32_t rtv = vexDeviceGenericRadioReceive(device->device_info, (uint8_t*)dest, data_size); if(rtv != data_size || received_data_size != data_size) { kprintf("[VEXLINK] Invalid Data Received Port %d, flushing RX buffer!\n", port); errno = EBADMSG; _clear_rx_buf(device); return_port(port - 1, PROS_ERR); } uint8_t received_checksum; received_size = vexDeviceGenericRadioReceive(device->device_info, &received_checksum, 1); // check checksum uint8_t calculated_checksum = START_BYTE; calculated_checksum ^= (data_size >> 8) & 0xff; calculated_checksum ^= (data_size) & 0xff; for(int i = 0; i < data_size; i++) { calculated_checksum ^= ((uint8_t*)dest)[i]; } if(calculated_checksum != received_checksum || received_size != 1) { kprintf("[VEXLINK] Checksum Mismatch Port %d!, Checksum: %x\n", port, received_checksum); errno = EBADMSG; return_port(port - 1, PROS_ERR); } return_port(port - 1, rtv); } uint32_t link_clear_receive_buf(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); uint32_t rtv = _clear_rx_buf(device); return_port(port - 1, rtv); } ================================================ FILE: src/devices/vdml_link.cpp ================================================ /** * \file vdml_link.cpp * * \brief Contains source code for functions related to the robot to robot communications. * * This file should not be modified by users, since it gets replaced whenever * a kernel upgrade occurs. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/link.hpp" #include "vdml/vdml.h" namespace pros { Link::Link(const std::uint8_t port, const std::string link_id, link_type_e_t type, bool ov) : Device(port, DeviceType::radio) { (ov) ? pros::c::link_init_override(_port, link_id.c_str(), type) : pros::c::link_init(_port, link_id.c_str(), type); } bool Link::connected() { return pros::c::link_connected(_port); } std::uint32_t Link::raw_receivable_size() { return pros::c::link_raw_receivable_size(_port); } std::uint32_t Link::raw_transmittable_size() { return pros::c::link_raw_transmittable_size(_port); } std::uint32_t Link::transmit_raw(void* data, std::uint16_t data_size) { return pros::c::link_transmit_raw(_port, data, data_size); } std::uint32_t Link::receive_raw(void* dest, std::uint16_t data_size) { return pros::c::link_receive_raw(_port, dest, data_size); } std::uint32_t Link::transmit(void* data, std::uint16_t data_size) { return pros::c::link_transmit(_port, data, data_size); } std::uint32_t Link::receive(void* dest, std::uint16_t data_size) { return pros::c::link_receive(_port, dest, data_size); } std::uint32_t Link::clear_receive_buf() { return pros::c::link_clear_receive_buf(_port); } } // namespace pros ================================================ FILE: src/devices/vdml_motorgroup.cpp ================================================ /** * \file devices/vdml_motors.cpp * * Contains functions for interacting with the V5 Motors. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "kapi.h" #include "pros/abstract_motor.hpp" #include "pros/motor_group.hpp" #include "pros/motors.hpp" namespace pros { inline namespace v5 { using namespace pros::c; #define empty_MotorGroup_check(error) \ if (_ports.size() <= 0) { \ errno = EDOM; \ return error; \ } #define MotorGroup_index_check(error, index) \ if (_ports.size() <= index || index < 0) { \ errno = EOVERFLOW; \ return error; \ } #define empty_MotorGroup_check_vector(error, vector) \ if (_ports.size() <= 0) { \ errno = EDOM; \ vector.push_back(error); \ return vector; \ } MotorGroup::MotorGroup(AbstractMotor& motor_group) : MotorGroup(motor_group.get_port_all()) {} MotorGroup::MotorGroup(const std::initializer_list ports, const pros::v5::MotorGears gearset, const pros::v5::MotorUnits encoder_units) : _ports(ports) { if (gearset != pros::v5::MotorGears::invalid) { set_gearing_all(gearset); } if (encoder_units != pros::v5::MotorUnits::invalid) { set_encoder_units_all(encoder_units); } } MotorGroup::MotorGroup(const std::vector& ports, const pros::v5::MotorGears gearset, const pros::v5::MotorUnits encoder_units) : _ports(ports) { if (gearset != pros::v5::MotorGears::invalid) { set_gearing_all(gearset); } if (encoder_units != pros::v5::MotorUnits::invalid) { set_encoder_units_all(encoder_units); } } std::int32_t MotorGroup::move(std::int32_t voltage) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_move(*it, voltage); } return motor_move(_ports[0], voltage); } std::int32_t MotorGroup::move_absolute(const double position, const std::int32_t velocity) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_move_absolute(*it, position, velocity); } return motor_move_absolute(_ports[0], position, velocity); } std::int32_t MotorGroup::move_relative(const double position, const std::int32_t velocity) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_move_relative(*it, position, velocity); } return motor_move_relative(_ports[0], position, velocity); } std::int32_t MotorGroup::move_velocity(const std::int32_t velocity) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_move_velocity(*it, velocity); } return motor_move_velocity(_ports[0], velocity); } std::int32_t MotorGroup::move_voltage(const std::int32_t voltage) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_move_voltage(*it, voltage); } return motor_move_voltage(_ports[0], voltage); } std::int32_t MotorGroup::brake(void) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_brake(*it); } return motor_brake(_ports[0]); } std::int32_t MotorGroup::modify_profiled_velocity(const std::int32_t velocity) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_modify_profiled_velocity(*it, velocity); } return motor_modify_profiled_velocity(_ports[0], velocity); } double MotorGroup::get_actual_velocity(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_actual_velocity(_ports[index]); } std::vector MotorGroup::get_actual_velocity_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_actual_velocity(*it)); } return return_vector; } pros::v5::MotorBrake MotorGroup::get_brake_mode(const std::uint8_t index) const { empty_MotorGroup_check(pros::v5::MotorBrake::invalid); MotorGroup_index_check(pros::v5::MotorBrake::invalid, index); return static_cast(motor_get_brake_mode(_ports[index])); } std::vector MotorGroup::get_brake_mode_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(pros::v5::MotorBrake::invalid, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(static_cast(motor_get_brake_mode(*it))); } return return_vector; } std::int32_t MotorGroup::get_current_draw(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_current_draw(_ports[index]); } std::vector MotorGroup::get_current_draw_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_current_draw(*it)); } return return_vector; } std::int32_t MotorGroup::get_current_limit(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_current_limit(_ports[index]); } std::vector MotorGroup::get_current_limit_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_current_limit(*it)); } return return_vector; } std::int32_t MotorGroup::is_over_current(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_is_over_current(_ports[index]); } std::vector MotorGroup::is_over_current_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_is_over_current(*it)); } return return_vector; } std::int32_t MotorGroup::get_direction(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); int ret = motor_get_direction(_ports[index]); ret = _ports[index] >= 0 ? ret : ret * -1; return ret; } std::vector MotorGroup::get_direction_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { int ret = motor_get_direction(*it); ret = *it >= 0 ? ret : ret * -1; return_vector.push_back(ret); } return return_vector; } double MotorGroup::get_efficiency(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_efficiency(_ports[index]); } std::vector MotorGroup::get_efficiency_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_efficiency(*it)); } return return_vector; } pros::v5::MotorUnits MotorGroup::get_encoder_units(const std::uint8_t index) const { empty_MotorGroup_check(pros::v5::MotorUnits::invalid); MotorGroup_index_check(pros::v5::MotorUnits::invalid, index); return static_cast(motor_get_encoder_units(_ports[index])); } std::vector MotorGroup::get_encoder_units_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(pros::v5::MotorUnits::invalid, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(static_cast(motor_get_encoder_units(*it))); } return return_vector; } std::uint32_t MotorGroup::get_faults(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_faults(_ports[index]); } std::vector MotorGroup::get_faults_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_faults(*it)); } return return_vector; } std::uint32_t MotorGroup::get_flags(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_flags(_ports[index]); } std::vector MotorGroup::get_flags_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_flags(*it)); } return return_vector; } pros::v5::MotorGears MotorGroup::get_gearing(const std::uint8_t index) const { empty_MotorGroup_check(pros::v5::MotorGears::invalid); MotorGroup_index_check(pros::v5::MotorGears::invalid, index); return static_cast(motor_get_gearing(_ports[index])); } std::vector MotorGroup::get_gearing_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(pros::v5::MotorGears::invalid, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(static_cast(motor_get_gearing(*it))); } return return_vector; } std::int32_t MotorGroup::get_raw_position(std::uint32_t* const timestamp, std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_raw_position(_ports[index], timestamp); } std::vector MotorGroup::get_raw_position_all(std::uint32_t* const timestamp) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_raw_position(*it, timestamp)); } return return_vector; } std::int32_t MotorGroup::is_over_temp(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_is_over_temp(_ports[index]); } std::vector MotorGroup::is_over_temp_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_is_over_temp(*it)); } return return_vector; } double MotorGroup::get_position(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_position(_ports[index]); } std::vector MotorGroup::get_position_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_position(*it)); } return return_vector; } double MotorGroup::get_power(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_power(_ports[index]); } std::vector MotorGroup::get_power_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_power(*it)); } return return_vector; } std::int32_t MotorGroup::is_reversed(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_is_reversed(index); } std::vector MotorGroup::is_reversed_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_is_reversed(*it)); } return return_vector; } pros::v5::MotorType MotorGroup::get_type(const std::uint8_t index) const { empty_MotorGroup_check(pros::v5::MotorType::invalid); MotorGroup_index_check(pros::v5::MotorType::invalid, index); return static_cast(motor_get_type(_ports[index])); } std::vector MotorGroup::get_type_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(pros::v5::MotorType::invalid, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(static_cast(motor_get_type(*it))); } return return_vector; } double MotorGroup::get_temperature(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_temperature(_ports[index]); } std::vector MotorGroup::get_temperature_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_temperature(*it)); } return return_vector; } double MotorGroup::get_target_position(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_target_position(_ports[index]); } std::vector MotorGroup::get_target_position_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_target_position(*it)); } return return_vector; } double MotorGroup::get_torque(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_F); MotorGroup_index_check(PROS_ERR_F, index); return motor_get_torque(_ports[index]); } std::vector MotorGroup::get_torque_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR_F, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_torque(*it)); } return return_vector; } std::int32_t MotorGroup::get_target_velocity(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_target_velocity(_ports[index]); } std::vector MotorGroup::get_target_velocity_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_target_velocity(*it)); } return return_vector; } std::int32_t MotorGroup::get_voltage(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_voltage(_ports[index]); } std::vector MotorGroup::get_voltage_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_voltage(*it)); } return return_vector; } std::int32_t MotorGroup::get_voltage_limit(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_get_voltage_limit(_ports[index]); } std::vector MotorGroup::get_voltage_limit_all(void) const { std::vector return_vector; empty_MotorGroup_check_vector(PROS_ERR, return_vector); for (auto it = _ports.begin(); it < _ports.end(); it++) { return_vector.push_back(motor_get_voltage_limit(*it)); } return return_vector; } std::int8_t MotorGroup::get_port(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR_BYTE); MotorGroup_index_check(PROS_ERR_BYTE, index); return _ports[index]; } std::vector MotorGroup::get_port_all(void) const { return _ports; } std::int32_t MotorGroup::tare_position(const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_tare_position(_ports[index]); } std::int32_t MotorGroup::tare_position_all(void) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_tare_position(*it); } return motor_tare_position(_ports[0]); } std::int32_t MotorGroup::set_brake_mode(const pros::motor_brake_mode_e_t mode, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_brake_mode(_ports[index], mode); } std::int32_t MotorGroup::set_brake_mode(const pros::v5::MotorBrake mode, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_brake_mode(_ports[index], static_cast(mode)); } std::int32_t MotorGroup::set_brake_mode_all(const pros::motor_brake_mode_e_t mode) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_brake_mode(*it, mode); } return motor_set_brake_mode(_ports[0], mode); } std::int32_t MotorGroup::set_brake_mode_all(const pros::v5::MotorBrake mode) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_brake_mode(*it, static_cast(mode)); } return motor_set_brake_mode(_ports[0], static_cast(mode)); } std::int32_t MotorGroup::set_current_limit(const std::int32_t limit, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_current_limit(_ports[index], limit); } std::int32_t MotorGroup::set_current_limit_all(const std::int32_t limit) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_current_limit(*it, limit); } return motor_set_current_limit(_ports[0], limit); } std::int32_t MotorGroup::set_encoder_units_all(const pros::motor_encoder_units_e_t units) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_encoder_units(*it, units); } return motor_set_encoder_units(_ports[0], units); } std::int32_t MotorGroup::set_encoder_units_all(const pros::v5::MotorUnits units) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_encoder_units(*it, static_cast(units)); } return motor_set_encoder_units(_ports[0], static_cast(units)); } std::int32_t MotorGroup::set_encoder_units(const pros::motor_encoder_units_e_t units, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_encoder_units(_ports[index], units); } std::int32_t MotorGroup::set_encoder_units(const pros::v5::MotorUnits units, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_encoder_units(_ports[index], static_cast(units)); } std::int32_t MotorGroup::set_gearing(const motor_gearset_e_t gearset, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_gearing(_ports[index], gearset); } std::int32_t MotorGroup::set_gearing(std::vector gearsets) const { empty_MotorGroup_check(PROS_ERR); for (std::size_t i = 0; i < gearsets.size(); i++) { this->set_gearing(gearsets[i], _ports[i]); } if (gearsets.size() != _ports.size()) { errno = E2BIG; } return PROS_SUCCESS; } std::int32_t MotorGroup::set_gearing(std::vector gearsets) const { empty_MotorGroup_check(PROS_ERR); for (std::size_t i = 0; i < gearsets.size(); i++) { this->set_gearing(gearsets[i], _ports[i]); } if (gearsets.size() != _ports.size()) { errno = E2BIG; } return PROS_SUCCESS; } std::int32_t MotorGroup::set_gearing(const pros::v5::MotorGear gearset, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_gearing(_ports[index], (motor_gearset_e_t)gearset); } std::int32_t MotorGroup::set_gearing_all(const motor_gearset_e_t gearset) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_gearing(*it, gearset); } return motor_set_gearing(_ports[0], gearset); } std::int32_t MotorGroup::set_gearing_all(const pros::v5::MotorGear gearset) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_gearing(*it, (motor_gearset_e_t)gearset); } return motor_set_gearing(_ports[0], (motor_gearset_e_t)gearset); } std::int32_t MotorGroup::set_zero_position(const double position, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_zero_position(_ports[index], position); } std::int32_t MotorGroup::set_zero_position_all(const double position) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_zero_position(*it, position); } return motor_set_zero_position(_ports[0], position); } std::int32_t MotorGroup::set_reversed(const bool reverse, const std::uint8_t index) { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); std::int8_t abs_port = std::abs(_ports[index]); if (reverse) { _ports[index] = -abs_port; } else { _ports[index] = abs_port; } return PROS_SUCCESS; } std::int32_t MotorGroup::set_reversed_all(const bool reverse) { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin(); it < _ports.end(); it++) { std::int8_t abs_port = std::abs(_ports[*it]); if (reverse) { _ports[*it] = -abs_port; } else { _ports[*it] = abs_port; } } return PROS_SUCCESS; } std::int32_t MotorGroup::set_voltage_limit(const std::int32_t limit, const std::uint8_t index) const { empty_MotorGroup_check(PROS_ERR); MotorGroup_index_check(PROS_ERR, index); return motor_set_voltage_limit(_ports[index], limit); } std::int32_t MotorGroup::set_voltage_limit_all(const std::int32_t limit) const { empty_MotorGroup_check(PROS_ERR); for (auto it = _ports.begin() + 1; it < _ports.end(); it++) { motor_set_voltage_limit(*it, limit); } return motor_set_voltage_limit(_ports[0], limit); } std::int8_t MotorGroup::size() const { return _ports.size(); } void MotorGroup::operator+=(AbstractMotor& other) { auto ports = other.get_port_all(); for (auto it = ports.begin(); it < ports.end(); it++) { auto port = *it; _ports.push_back(port); } } void MotorGroup::append(AbstractMotor& other) { (*this) += other; } void MotorGroup::erase_port(std::int8_t port) { auto it = _ports.begin(); while (it < _ports.end()) { if (std::abs(*it) == std::abs(port)) { _ports.erase(it); } else { it++; } } } } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_motors.c ================================================ /** * \file devices/vdml_motors.c * * Contains functions for interacting with the V5 Motors. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include "kapi.h" #include "pros/colors.h" #include "pros/motors.h" #include "pros/apix.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define MOTOR_MOVE_RANGE 127 #define MOTOR_VOLTAGE_RANGE 12000 // Movement functions int32_t motor_move(int8_t port, int32_t voltage) { if (voltage > 127) { voltage = 127; } else if (voltage < -127) { voltage = -127; } if (port < 0) { voltage = -voltage; } port = abs(port); // Remap the input voltage range to the motor voltage // scale to [-127, 127] -> [-12000, 12000] int32_t command = (((voltage + MOTOR_MOVE_RANGE) * (MOTOR_VOLTAGE_RANGE)) / (MOTOR_MOVE_RANGE)); command -= MOTOR_VOLTAGE_RANGE; return motor_move_voltage(port, command); } int32_t motor_brake(int8_t port) { return motor_move_velocity(port, 0); } int32_t motor_move_absolute(int8_t port, double position, int32_t velocity) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); if (port < 0) position = -position; vexDeviceMotorAbsoluteTargetSet(device->device_info, position, velocity); return_port(abs_port - 1, PROS_SUCCESS); } int32_t motor_move_relative(int8_t port, double position, int32_t velocity) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); if (port < 0) position = -position; vexDeviceMotorRelativeTargetSet(device->device_info, position, velocity); return_port(abs_port - 1, PROS_SUCCESS); } int32_t motor_move_velocity(int8_t port, int32_t velocity) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); if (port < 0) velocity = -velocity; vexDeviceMotorVelocitySet(device->device_info, velocity); return_port(abs_port - 1, PROS_SUCCESS); } int32_t motor_move_voltage(int8_t port, int32_t voltage) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); if (port < 0) voltage = -voltage; vexDeviceMotorVoltageSet(device->device_info, voltage); return_port(abs_port - 1, PROS_SUCCESS); } int32_t motor_modify_profiled_velocity(int8_t port, int32_t velocity) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); if (port < 0) velocity = -velocity; vexDeviceMotorVelocityUpdate(device->device_info, velocity); return_port(abs_port - 1, PROS_SUCCESS); } double motor_get_target_position(int8_t port) { uint8_t abs_port = abs(port); claim_port_f(abs_port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorTargetGet(device->device_info); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } int32_t motor_get_target_velocity(int8_t port) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorVelocityGet(device->device_info); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } // Telemetry functions double motor_get_actual_velocity(int8_t port) { uint8_t abs_port = abs(port); claim_port_f(abs_port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorActualVelocityGet(device->device_info); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } int32_t motor_get_current_draw(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorCurrentGet(device->device_info); return_port(port - 1, rtn); } int32_t motor_get_direction(int8_t port) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorDirectionGet(device->device_info); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } double motor_get_efficiency(int8_t port) { port = abs(port); claim_port_f(port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorEfficiencyGet(device->device_info); return_port(port - 1, rtn); } int32_t motor_is_over_current(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int rtn = vexDeviceMotorCurrentLimitFlagGet(device->device_info); return_port(port - 1, rtn); } int32_t motor_is_over_temp(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int rtn = vexDeviceMotorOverTempFlagGet(device->device_info); return_port(port - 1, rtn); } uint32_t motor_get_faults(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); uint32_t rtn = vexDeviceMotorFaultsGet(device->device_info); return_port(port - 1, rtn); } uint32_t motor_get_flags(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); uint32_t rtn = vexDeviceMotorFlagsGet(device->device_info); return_port(port - 1, rtn); } int32_t motor_get_raw_position(int8_t port, uint32_t* const timestamp) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorPositionRawGet(device->device_info, timestamp); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } double motor_get_position(int8_t port) { uint8_t abs_port = abs(port); claim_port_f(abs_port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorPositionGet(device->device_info); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } double motor_get_power(int8_t port) { port = abs(port); claim_port_f(port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorPowerGet(device->device_info); return_port(port - 1, rtn); } double motor_get_temperature(int8_t port) { port = abs(port); claim_port_f(port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorTemperatureGet(device->device_info); return_port(port - 1, rtn); } double motor_get_torque(int8_t port) { port = abs(port); claim_port_f(port - 1, E_DEVICE_MOTOR); double rtn = vexDeviceMotorTorqueGet(device->device_info); return_port(port - 1, rtn); } int32_t motor_get_voltage(int8_t port) { uint8_t abs_port = abs(port); claim_port_i(abs_port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorVoltageGet(device->device_info); if (port < 0) rtn = -rtn; return_port(abs_port - 1, rtn); } // Config functions int32_t motor_set_zero_position(int8_t port, const double position) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorPositionSet(device->device_info, position); return_port(port - 1, PROS_SUCCESS); } int32_t motor_tare_position(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorPositionReset(device->device_info); return_port(port - 1, PROS_SUCCESS); } int32_t motor_set_brake_mode(int8_t port, const motor_brake_mode_e_t mode) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorBrakeModeSet(device->device_info, (V5MotorBrakeMode)mode); return_port(port - 1, PROS_SUCCESS); } int32_t motor_set_current_limit(int8_t port, const int32_t limit) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorCurrentLimitSet(device->device_info, limit); return_port(port - 1, PROS_SUCCESS); } int32_t motor_set_encoder_units(int8_t port, const motor_encoder_units_e_t units) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorEncoderUnitsSet(device->device_info, (V5MotorEncoderUnits)units); return_port(port - 1, PROS_SUCCESS); } int32_t motor_set_gearing(int8_t port, const motor_gearset_e_t gearset) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorGearingSet(device->device_info, (V5MotorGearset)gearset); return_port(port - 1, PROS_SUCCESS); } int32_t motor_set_reversed(int8_t port, const bool reverse) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorReverseFlagSet(device->device_info, reverse); return_port(port - 1, PROS_SUCCESS); } int32_t motor_set_voltage_limit(int8_t port, const int32_t limit) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); vexDeviceMotorVoltageLimitSet(device->device_info, limit); return_port(port - 1, PROS_SUCCESS); } motor_brake_mode_e_t motor_get_brake_mode(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); V5MotorBrakeMode rtn = vexDeviceMotorBrakeModeGet(device->device_info); return_port(port - 1, (motor_brake_mode_e_t)rtn); } int32_t motor_get_current_limit(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorCurrentLimitGet(device->device_info); return_port(port - 1, rtn); } motor_encoder_units_e_t motor_get_encoder_units(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); V5MotorEncoderUnits rtn = vexDeviceMotorEncoderUnitsGet(device->device_info); return_port(port - 1, (motor_encoder_units_e_t)rtn); } motor_gearset_e_t motor_get_gearing(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); V5MotorGearset rtn = vexDeviceMotorGearingGet(device->device_info); return_port(port - 1, (motor_gearset_e_t)rtn); } int32_t motor_is_reversed(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int rtn = vexDeviceMotorReverseFlagGet(device->device_info); return_port(port - 1, rtn); } int32_t motor_get_voltage_limit(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorVoltageLimitGet(device->device_info); return_port(port - 1, rtn); } motor_type_e_t motor_get_type(int8_t port) { port = abs(port); claim_port_i(port - 1, E_DEVICE_MOTOR); int32_t rtn = vexDeviceMotorTypeGet(device->device_info); return_port(port - 1, rtn); } ================================================ FILE: src/devices/vdml_motors.cpp ================================================ /** * \file devices/vdml_motors.cpp * * Contains functions for interacting with the V5 Motors. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "pros/motors.hpp" #include "vdml/vdml.h" #include namespace pros { inline namespace v5 { using namespace pros::c; Motor::Motor(const std::int8_t port, const pros::v5::MotorGears gearset, const pros::v5::MotorUnits encoder_units) : Device(std::abs(port), DeviceType::motor), _port(port) { if (gearset != pros::v5::MotorGears::invalid) { set_gearing(gearset); } if (encoder_units != pros::v5::MotorEncoderUnits::invalid) { set_encoder_units(encoder_units); } } std::int32_t Motor::move(std::int32_t voltage) const { return motor_move(_port, voltage); } std::int32_t Motor::move_absolute(const double position, const std::int32_t velocity) const { return motor_move_absolute(_port, position, velocity); } std::int32_t Motor::move_relative(const double position, const std::int32_t velocity) const { return motor_move_relative(_port, position, velocity); } std::int32_t Motor::move_velocity(const std::int32_t velocity) const { return motor_move_velocity(_port, velocity); } std::int32_t Motor::move_voltage(const std::int32_t voltage) const { return motor_move_voltage(_port, voltage); } std::int32_t Motor::brake(void) const { return motor_brake(_port); } std::int32_t Motor::modify_profiled_velocity(const std::int32_t velocity) const { return motor_modify_profiled_velocity(_port, velocity); } double Motor::get_actual_velocity(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR_F; } return motor_get_actual_velocity(_port); } std::vector Motor::get_actual_velocity_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_actual_velocity(_port)); return return_vector; } pros::v5::MotorBrake Motor::get_brake_mode(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return pros::v5::MotorBrake::invalid; } return static_cast(motor_get_brake_mode(_port)); } std::vector Motor::get_brake_mode_all() const { std::vector return_vector; return_vector.push_back(static_cast(motor_get_brake_mode(_port))); return return_vector; } std::int32_t Motor::get_current_draw(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_current_draw(_port); } std::vector Motor::get_current_draw_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_current_draw(_port)); return return_vector; } std::int32_t Motor::get_current_limit(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_current_limit(_port); } std::vector Motor::get_current_limit_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_current_limit(_port)); return return_vector; } std::int32_t Motor::is_over_current(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_is_over_current(_port); } std::vector Motor::is_over_current_all(void) const { std::vector return_vector; return_vector.push_back(motor_is_over_current(_port)); return return_vector; } std::int32_t Motor::get_direction(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } int ret = motor_get_direction(_port); ret = _port >= 0 ? ret : ret * -1; return ret; } std::vector Motor::get_direction_all(void) const { std::vector return_vector; int ret = motor_get_direction(_port); ret = _port >= 0 ? ret : ret * -1; return_vector.push_back(ret); return return_vector; } double Motor::get_efficiency(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR_F; } return motor_get_efficiency(_port); } std::vector Motor::get_efficiency_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_efficiency(_port)); return return_vector; } pros::v5::MotorUnits Motor::get_encoder_units(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return pros::v5::MotorUnits::invalid; } return static_cast(motor_get_encoder_units(_port)); } std::vector Motor::get_encoder_units_all(void) const { std::vector return_vector; return_vector.push_back(static_cast(motor_get_encoder_units(_port))); return return_vector; } std::uint32_t Motor::get_faults(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_faults(_port); } std::vector Motor::get_faults_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_faults(_port)); return return_vector; } std::uint32_t Motor::get_flags(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_flags(_port); } std::vector Motor::get_flags_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_flags(_port)); return return_vector; } pros::v5::MotorGears Motor::get_gearing(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return pros::v5::MotorGears::invalid; } return static_cast(motor_get_gearing(_port)); } std::vector Motor::get_gearing_all(void) const { std::vector return_vector; return_vector.push_back(static_cast(motor_get_gearing(_port))); return return_vector; } std::int32_t Motor::get_raw_position(std::uint32_t* const timestamp, std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_raw_position(_port, timestamp); } std::vector Motor::get_raw_position_all(std::uint32_t* const timestamp) const { std::vector return_vector; return_vector.push_back(motor_get_raw_position(_port, timestamp)); return return_vector; } std::int32_t Motor::is_over_temp(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_is_over_temp(_port); } std::vector Motor::is_over_temp_all(void) const { std::vector return_vector; return_vector.push_back(motor_is_over_temp(_port)); return return_vector; } double Motor::get_position(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR_F; } return motor_get_position(_port); } std::vector Motor::get_position_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_position(_port)); return return_vector; } double Motor::get_power(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_power(_port); } std::vector Motor::get_power_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_power(_port)); return return_vector; } std::int32_t Motor::is_reversed(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return _port < 0; } std::vector Motor::is_reversed_all(void) const { std::vector return_vector; return_vector.push_back(_port < 0); return return_vector; } pros::v5::MotorType Motor::get_type(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return pros::v5::MotorType::invalid; } return static_cast(motor_get_type(_port)); } std::vector Motor::get_type_all(void) const { std::vector return_vector; return_vector.push_back(static_cast(motor_get_type(_port))); return return_vector; } double Motor::get_temperature(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR_F; } return motor_get_temperature(_port); } std::vector Motor::get_temperature_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_temperature(_port)); return return_vector; } double Motor::get_target_position(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_target_position(_port); } std::vector Motor::get_target_position_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_target_position(_port)); return return_vector; } double Motor::get_torque(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_torque(_port); } std::vector Motor::get_torque_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_torque(_port)); return return_vector; } std::int32_t Motor::get_target_velocity(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_target_velocity(_port); } std::vector Motor::get_target_velocity_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_target_velocity(_port)); return return_vector; } std::int32_t Motor::get_voltage(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_voltage(_port); } std::vector Motor::get_voltage_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_voltage(_port)); return return_vector; } std::int32_t Motor::get_voltage_limit(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_get_voltage_limit(_port); } std::vector Motor::get_voltage_limit_all(void) const { std::vector return_vector; return_vector.push_back(motor_get_voltage_limit(_port)); return return_vector; } std::vector Motor::get_all_devices() { std::vector matching_devices {Device::get_all_devices(DeviceType::motor)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } std::int8_t Motor::get_port(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR_BYTE; } return _port; } std::vector Motor::get_port_all(void) const { std::vector return_vector; return_vector.push_back(_port); return return_vector; } std::int32_t Motor::tare_position(const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_tare_position(_port); } std::int32_t Motor::set_brake_mode(const pros::motor_brake_mode_e_t mode, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_brake_mode(_port, mode); } std::int32_t Motor::set_brake_mode(const pros::v5::MotorBrake mode, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_brake_mode(_port, static_cast(mode)); } std::int32_t Motor::set_current_limit(const std::int32_t limit, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_current_limit(_port, limit); } std::int32_t Motor::set_encoder_units(const pros::motor_encoder_units_e_t units, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_encoder_units(_port, units); } std::int32_t Motor::set_encoder_units(const pros::v5::MotorUnits units, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_encoder_units(_port, static_cast(units)); } std::int32_t Motor::set_gearing(const motor_gearset_e_t gearset, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_gearing(_port, gearset); } std::int32_t Motor::set_gearing(const pros::v5::MotorGear gearset, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_gearing(_port, static_cast(gearset)); } std::int32_t Motor::set_zero_position(const double position, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_zero_position(_port, position); } std::int32_t Motor::set_reversed(const bool reverse, const std::uint8_t index) { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } std::int8_t abs_port = std::abs(_port); if (reverse) { _port = -abs_port; } else { _port = abs_port; } return PROS_SUCCESS; } std::int32_t Motor::set_voltage_limit(const std::int32_t limit, const std::uint8_t index) const { if (index != 0) { errno = EOVERFLOW; return PROS_ERR; } return motor_set_voltage_limit(_port, limit); } std::int32_t Motor::tare_position_all(void) const { return motor_tare_position(_port); } std::int32_t Motor::set_brake_mode_all(const pros::motor_brake_mode_e_t mode) const { return motor_set_brake_mode(_port, mode); } std::int32_t Motor::set_brake_mode_all(const pros::v5::MotorBrake mode) const { return motor_set_brake_mode(_port, static_cast(mode)); } std::int32_t Motor::set_current_limit_all(const std::int32_t limit) const { return motor_set_current_limit(_port, limit); } std::int32_t Motor::set_encoder_units_all(const pros::motor_encoder_units_e_t units) const { return motor_set_encoder_units(_port, units); } std::int32_t Motor::set_encoder_units_all(const pros::v5::MotorUnits units) const { return motor_set_encoder_units(_port, static_cast(units)); } std::int32_t Motor::set_gearing_all(const motor_gearset_e_t gearset) const { return motor_set_gearing(_port, gearset); } std::int32_t Motor::set_gearing_all(const pros::v5::MotorGear gearset) const { return motor_set_gearing(_port, static_cast(gearset)); } std::int32_t Motor::set_zero_position_all(const double position) const { return motor_set_zero_position(_port, position); } std::int32_t Motor::set_reversed_all(const bool reverse) { std::int8_t abs_port = std::abs(_port); if (reverse) { _port = -abs_port; } else { _port = abs_port; } return PROS_SUCCESS; } std::int32_t Motor::set_voltage_limit_all(const std::int32_t limit) const { return motor_set_voltage_limit(_port, limit); } std::int8_t Motor::size() const { return 1; } std::ostream& operator<<(std::ostream& os, pros::Motor& motor) { os << "Motor ["; os << "port: " << motor.get_port(); os << ", brake mode: " << (int)motor.get_brake_mode(); os << ", current draw: " << motor.get_current_draw(); os << ", current limit: " << motor.get_current_limit(); os << ", direction: " << motor.get_direction(); os << ", efficiency: " << motor.get_efficiency(); os << ", encoder units: " << (int)motor.get_encoder_units(); os << ", gearing: " << (int)motor.get_gearing(); os << ", over temp: " << motor.is_over_temp(); os << ", position: " << motor.get_position(); os << ", reversed: " << motor.is_reversed(); os << ", temperature: " << motor.get_temperature(); os << ", torque: " << motor.get_torque(); os << ", voltage: " << motor.get_voltage(); os << "]"; return os; } } // namespace v5 namespace literals { const pros::Motor operator""_mtr(const unsigned long long int m) { return pros::Motor(m); } const pros::Motor operator""_rmtr(const unsigned long long int m) { return pros::Motor(-m); } } // namespace literals } // namespace pros ================================================ FILE: src/devices/vdml_optical.c ================================================ /** * \file devices/vdml_optical.c * * Contains functions for interacting with the VEX Optical sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "pros/optical.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" // Source for these figures: // https://www.vexforum.com/t/v5-optical-sensor-refresh-rate/109632/9 #define MIN_INTEGRATION_TIME 3 // ms #define MAX_INTEGRATION_TIME 712 // ms double optical_get_hue(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); double rtn = vexDeviceOpticalHueGet(device->device_info); return_port(port - 1, rtn); } double optical_get_saturation(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); double rtn = vexDeviceOpticalSatGet(device->device_info); return_port(port - 1, rtn); } double optical_get_brightness(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); double rtn = vexDeviceOpticalBrightnessGet(device->device_info); return_port(port - 1, rtn); } int32_t optical_get_proximity(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); double rtn = vexDeviceOpticalProximityGet(device->device_info); return_port(port - 1, rtn); } int32_t optical_set_led_pwm(uint8_t port, uint8_t value) { claim_port_i(port - 1, E_DEVICE_OPTICAL); vexDeviceOpticalLedPwmSet(device->device_info, value); return_port(port - 1, PROS_SUCCESS); } int32_t optical_get_led_pwm(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); int32_t rtn = vexDeviceOpticalLedPwmGet(device->device_info); return_port(port - 1, rtn); } #define RGB_ERR_INIT \ { .red = PROS_ERR_F, .green = PROS_ERR_F, .blue = PROS_ERR_F, .brightness = PROS_ERR_F } optical_rgb_s_t optical_get_rgb(uint8_t port) { optical_rgb_s_t rtn = RGB_ERR_INIT; v5_smart_device_s_t* device; if (!claim_port_try(port - 1, E_DEVICE_OPTICAL)) { return rtn; } device = registry_get_device(port - 1); V5_DeviceOpticalRgb rgb; vexDeviceOpticalRgbGet(device->device_info, &rgb); rtn.red = rgb.red; rtn.green = rgb.green; rtn.blue = rgb.blue; rtn.brightness = rgb.brightness; return_port(port - 1, rtn); } #define RAW_ERR_INIT \ { .clear = PROS_ERR, .red = PROS_ERR, .green = PROS_ERR, .blue = PROS_ERR } optical_raw_s_t optical_get_raw(uint8_t port) { optical_raw_s_t rtn = RAW_ERR_INIT; v5_smart_device_s_t* device; if (!claim_port_try(port - 1, E_DEVICE_OPTICAL)) { return rtn; } device = registry_get_device(port - 1); V5_DeviceOpticalRaw rgb; vexDeviceOpticalRawGet(device->device_info, &rgb); rtn.clear = rgb.clear; rtn.red = rgb.red; rtn.green = rgb.green; rtn.blue = rgb.blue; return_port(port - 1, rtn); } optical_direction_e_t optical_get_gesture(uint8_t port) { claim_port(port - 1, E_DEVICE_OPTICAL, OPT_GESTURE_ERR); optical_direction_e_t rtn = vexDeviceOpticalGestureGet(device->device_info, NULL); return_port(port - 1, rtn); } #define GESTURE_ERR_INIT \ { \ .udata = OPT_GESTURE_ERR, .ddata = OPT_GESTURE_ERR, .ldata = OPT_GESTURE_ERR, .rdata = OPT_GESTURE_ERR, \ .type = OPT_GESTURE_ERR, .pad = OPT_GESTURE_ERR, .count = OPT_COUNT_ERR, .time = OPT_TIME_ERR \ } optical_gesture_s_t optical_get_gesture_raw(uint8_t port) { optical_gesture_s_t rtn = GESTURE_ERR_INIT; v5_smart_device_s_t* device; if (!claim_port_try(port - 1, E_DEVICE_OPTICAL)) { return rtn; } device = registry_get_device(port - 1); V5_DeviceOpticalGesture gesture; vexDeviceOpticalGestureGet(device->device_info, &gesture); rtn.udata = gesture.udata; rtn.ddata = gesture.ddata; rtn.ldata = gesture.ldata; rtn.rdata = gesture.rdata; rtn.type = gesture.type; rtn.pad = gesture.pad; rtn.count = gesture.count; rtn.time = gesture.time; return_port(port - 1, rtn); } int32_t optical_enable_gesture(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); vexDeviceOpticalGestureEnable(device->device_info); return_port(port - 1, PROS_SUCCESS); } int32_t optical_disable_gesture(uint8_t port) { claim_port_i(port - 1, E_DEVICE_OPTICAL); vexDeviceOpticalGestureDisable(device->device_info); return_port(port - 1, PROS_SUCCESS); } double optical_get_integration_time(uint8_t port) { claim_port_f(port - 1, E_DEVICE_OPTICAL); double rtv = vexDeviceOpticalIntegrationTimeGet(device->device_info); return_port(port - 1, rtv); } int32_t optical_set_integration_time(uint8_t port, double time) { claim_port_i(port - 1, E_DEVICE_OPTICAL); // going to set the time to minimum of 3 ms, 3 ms is possible but impractical. time = time < MIN_INTEGRATION_TIME ? MIN_INTEGRATION_TIME : time; // also boundary limit max integration time too time = time > MAX_INTEGRATION_TIME ? MAX_INTEGRATION_TIME : time; vexDeviceOpticalIntegrationTimeSet(device->device_info, time); return_port(port - 1, PROS_SUCCESS); } ================================================ FILE: src/devices/vdml_optical.cpp ================================================ /** * \file devices/vdml_optical.cpp * * Contains functions for interacting with the VEX Optical sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/optical.h" #include "pros/optical.hpp" #include "vdml/vdml.h" namespace pros { inline namespace v5 { using namespace pros::c; Optical::Optical(std::uint8_t port) : Device(port, DeviceType::optical) {} std::vector Optical::get_all_devices() { std::vector matching_devices {Device::get_all_devices(DeviceType::optical)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } double Optical::get_hue(){ return optical_get_hue(_port); } double Optical::get_saturation(){ return optical_get_saturation(_port); } double Optical::get_brightness(){ return optical_get_brightness(_port); } std::int32_t Optical::get_proximity(){ return optical_get_proximity(_port); } std::int32_t Optical::set_led_pwm(std::uint8_t value){ return optical_set_led_pwm(_port, value); } std::int32_t Optical::get_led_pwm(){ return optical_get_led_pwm(_port); } optical_rgb_s_t Optical::get_rgb(){ return optical_get_rgb(_port); } optical_raw_s_t Optical::get_raw(){ return optical_get_raw(_port); } optical_direction_e_t Optical::get_gesture(){ return optical_get_gesture(_port); } optical_gesture_s_t Optical::get_gesture_raw(){ return optical_get_gesture_raw(_port); } std::int32_t Optical::enable_gesture(){ return optical_enable_gesture(_port); } std::int32_t Optical::disable_gesture(){ return optical_disable_gesture(_port); } double Optical::get_integration_time() { return optical_get_integration_time(_port); } std::int32_t Optical::set_integration_time(double time) { return optical_set_integration_time(_port, time); } std::ostream& operator<<(std::ostream& os, pros::Optical& optical) { pros::c::optical_rgb_s_t rgb = optical.get_rgb(); os << "Optical ["; os << "port: " << optical.get_port(); os << ", hue: " << optical.get_hue(); os << ", saturation: " << optical.get_saturation(); os << ", brightness: " << optical.get_brightness(); os << ", proximity: " << optical.get_proximity(); os << ", rgb: " << "{" << rgb.red << ","<< rgb.green << "," << rgb.blue << "}"; os << "]"; return os; } namespace literals { const pros::Optical operator""_opt(const unsigned long long int o) { return pros::Optical(o); } } // } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_rotation.c ================================================ /** * \file devices/vdml_rotation.c * * Contains functions for interacting with the VEX Rotation sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "pros/rotation.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" #define ROTATION_RESET_TIMEOUT 1000 int32_t rotation_reset(uint8_t port) { claim_port_i(port - 1, E_DEVICE_ROTATION); vexDeviceAbsEncReset(device->device_info); return_port(port - 1, PROS_SUCCESS); } int32_t rotation_set_data_rate(uint8_t port, uint32_t rate) { claim_port_i(port - 1, E_DEVICE_ROTATION); // rate is not less than 5ms, and rounded down to nearest increment of 5 if (rate < ROTATION_MINIMUM_DATA_RATE) { rate = ROTATION_MINIMUM_DATA_RATE; } else { rate -= rate % ROTATION_MINIMUM_DATA_RATE; } vexDeviceAbsEncDataRateSet(device->device_info, rate); return_port(port - 1, PROS_SUCCESS); } int32_t rotation_reset_position(uint8_t port) { claim_port_i(port - 1, E_DEVICE_ROTATION); vexDeviceAbsEncPositionSet(device->device_info, 0); return_port(port - 1, PROS_SUCCESS); } int32_t rotation_set_position(uint8_t port, int32_t position) { claim_port_i(port - 1, E_DEVICE_ROTATION); vexDeviceAbsEncPositionSet(device->device_info, position); return_port(port - 1, PROS_SUCCESS); } int32_t rotation_get_position(uint8_t port) { claim_port_i(port - 1, E_DEVICE_ROTATION); int32_t rtn = vexDeviceAbsEncPositionGet(device->device_info); return_port(port - 1, rtn); } int32_t rotation_get_velocity(uint8_t port) { claim_port_i(port - 1, E_DEVICE_ROTATION); int32_t rtn = vexDeviceAbsEncVelocityGet(device->device_info); return_port(port - 1, rtn); } int32_t rotation_get_angle(uint8_t port) { claim_port_i(port - 1, E_DEVICE_ROTATION); int32_t rtn = vexDeviceAbsEncAngleGet(device->device_info); return_port(port - 1, rtn); } int32_t rotation_set_reversed(uint8_t port, bool value) { claim_port_i(port - 1, E_DEVICE_ROTATION); vexDeviceAbsEncReverseFlagSet(device->device_info, value); return_port(port - 1, PROS_SUCCESS); } int32_t rotation_init_reverse(uint8_t port, bool reverse_flag) { claim_port_i(port - 1, E_DEVICE_ROTATION); uint16_t timeoutCount = 0; // releasing mutex so vexBackgrounProcessing can run without being blocked. do { port_mutex_give(port - 1); task_delay(5); timeoutCount += 5; claim_port_i(port - 1, E_DEVICE_ROTATION); if (timeoutCount >= ROTATION_RESET_TIMEOUT) { port_mutex_give(port - 1); errno = EAGAIN; return PROS_ERR; } device = device; // suppressing compiler warning } while(vexDeviceAbsEncStatusGet(device->device_info) == 0); vexAbsEncReverseFlagSet(port - 1, reverse_flag); return_port(port - 1, 1) } int32_t rotation_reverse(uint8_t port){ claim_port_i(port - 1, E_DEVICE_ROTATION); vexDeviceAbsEncReverseFlagSet(device->device_info, !vexDeviceAbsEncReverseFlagGet(device->device_info)); return_port(port - 1, PROS_SUCCESS); } int32_t rotation_get_reversed(uint8_t port) { claim_port_i(port - 1, E_DEVICE_ROTATION); int32_t rtn = vexDeviceAbsEncReverseFlagGet(device->device_info); return_port(port - 1, rtn); } ================================================ FILE: src/devices/vdml_rotation.cpp ================================================ /** * \file devices/vdml_rotation.cpp * * Contains functions for interacting with the VEX Rotation sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/rotation.hpp" #include "vdml/vdml.h" namespace pros { inline namespace v5 { Rotation::Rotation(const std::int8_t port) : Device(abs(port), DeviceType::rotation) { if (port < 0) { pros::c::rotation_set_reversed(abs(port), true); } else { pros::c::rotation_set_reversed(port, false); } } std::int32_t Rotation::reset() { return pros::c::rotation_reset(_port); } std::int32_t Rotation::set_data_rate(std::uint32_t rate) const { return pros::c::rotation_set_data_rate(_port, rate); } std::int32_t Rotation::set_position(std::int32_t position) const { return pros::c::rotation_set_position(_port, position); } std::int32_t Rotation::reset_position(void) const { return pros::c::rotation_reset_position(_port); } std::vector Rotation::get_all_devices() { std::vector matching_devices {Device::get_all_devices(DeviceType::rotation)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } std::int32_t Rotation::get_position(void) const { return pros::c::rotation_get_position(_port); } std::int32_t Rotation::get_velocity(void) const { return pros::c::rotation_get_velocity(_port); } std::int32_t Rotation::get_angle(void) const { return pros::c::rotation_get_angle(_port); } std::int32_t Rotation::set_reversed(bool value) const { return pros::c::rotation_set_reversed(_port, value); } std::int32_t Rotation::reverse(void) const { return pros::c::rotation_reverse(_port); } std::int32_t Rotation::get_reversed(void) const { return pros::c::rotation_get_reversed(_port); } std::ostream& operator<<(std::ostream& os, const pros::Rotation& rotation) { os << "Rotation ["; os << "port: " << rotation._port; os << ", position: " << rotation.get_position(); os << ", velocity: " << rotation.get_velocity(); os << ", angle: " << rotation.get_angle(); os << ", reversed: " << rotation.get_reversed(); os << "]"; return os; } namespace literals { const pros::Rotation operator""_rot(const unsigned long long int r) { return pros::Rotation(r); } } // namespace literals } // namespace v5 } // namespace pros ================================================ FILE: src/devices/vdml_serial.c ================================================ /** * \file devices/vdml_serial.c * * Contains functions for interacting with V5 Generic Serial devices. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include "kapi.h" #include "pros/serial.h" #include "v5_api.h" #include "vdml/registry.h" #include "vdml/vdml.h" // Control function int32_t serial_enable(uint8_t port) { /** * claim_port_i(port - 1, E_DEVICE_SERIAL) is not used because it requires * the port to already be of the requested type in VEXos, which will not yet * be the case for generic serial as vexDeviceGenericSerialEnable is what * switches the port into the correct mode */ if (!VALIDATE_PORT_NO(port - 1)) { errno = EINVAL; return PROS_ERR; } v5_smart_device_s_t* device = registry_get_device(port - 1); if (!port_mutex_take(port - 1)) { errno = EACCES; return PROS_ERR; } vexDeviceGenericSerialEnable(device->device_info, 0); return_port(port - 1, PROS_SUCCESS); } int32_t serial_set_baudrate(uint8_t port, int32_t baudrate) { claim_port_i(port - 1, E_DEVICE_SERIAL); vexDeviceGenericSerialBaudrate(device->device_info, baudrate); return_port(port - 1, PROS_SUCCESS); } int32_t serial_flush(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); vexDeviceGenericSerialFlush(device->device_info); return_port(port - 1, PROS_SUCCESS); } // Telemetry functions int32_t serial_get_read_avail(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialReceiveAvail(device->device_info); return_port(port - 1, rtn); } int32_t serial_get_write_free(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialWriteFree(device->device_info); return_port(port - 1, rtn); } // Read functions int32_t serial_peek_byte(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialPeekChar(device->device_info); return_port(port - 1, rtn); } int32_t serial_read_byte(uint8_t port) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialReadChar(device->device_info); return_port(port - 1, rtn); } int32_t serial_read(uint8_t port, uint8_t* buffer, int32_t length) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialReceive(device->device_info, buffer, length); return_port(port - 1, rtn); } // Write functions int32_t serial_write_byte(uint8_t port, uint8_t buffer) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialWriteChar(device->device_info, buffer); if (rtn == -1) { errno = EIO; return_port(port - 1, PROS_ERR); } return_port(port - 1, rtn); } int32_t serial_write(uint8_t port, uint8_t* buffer, int32_t length) { claim_port_i(port - 1, E_DEVICE_SERIAL); int32_t rtn = vexDeviceGenericSerialTransmit(device->device_info, buffer, length); if (rtn == -1) { errno = EIO; return_port(port - 1, PROS_ERR); } return_port(port - 1, rtn); } ================================================ FILE: src/devices/vdml_serial.cpp ================================================ /** * \file devices/vdml_serial.cpp * * Contains functions for interacting with V5 Generic Serial devices. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "pros/serial.hpp" #include "vdml/vdml.h" namespace pros { using namespace pros::c; Serial::Serial(std::uint8_t port, std::int32_t baudrate) : Device(port, DeviceType::serial) { serial_enable(port); set_baudrate(baudrate); } Serial::Serial(std::uint8_t port) : Device(port, DeviceType::serial) { serial_enable(port); } std::int32_t Serial::set_baudrate(std::int32_t baudrate) const { return serial_set_baudrate(_port, baudrate); } std::int32_t Serial::flush() const { return serial_flush(_port); } std::int32_t Serial::get_read_avail() const { return serial_get_read_avail(_port); } std::int32_t Serial::get_write_free() const { return serial_get_write_free(_port); } std::int32_t Serial::peek_byte() const { return serial_peek_byte(_port); } std::int32_t Serial::read_byte() const { return serial_read_byte(_port); } std::int32_t Serial::read(std::uint8_t* buffer, std::int32_t length) const { return serial_read(_port, buffer, length); } std::int32_t Serial::write_byte(std::uint8_t buffer) const { return serial_write_byte(_port, buffer); } std::int32_t Serial::write(std::uint8_t* buffer, std::int32_t length) const { return serial_write(_port, buffer, length); } namespace literals { const pros::Serial operator""_ser(const unsigned long long int m) { return pros::Serial(m); } } // namespace literals } // namespace pros ================================================ FILE: src/devices/vdml_usd.c ================================================ /** * \file devices/usd.c * * Contains functions for interacting with the SD card. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "v5_api.h" int32_t usd_is_installed(void) { return vexFileDriveStatus(0); } static const int FRESULTMAP[] = {0, EIO, EINVAL, EBUSY, ENOENT, ENOENT, EINVAL, EACCES, // FR_DENIED EEXIST, EINVAL, EROFS, ENXIO, ENOBUFS, ENXIO, EIO, EACCES, // FR_LOCKED ENOBUFS, ENFILE, EINVAL}; int32_t usd_list_files(const char* path, char* buffer, int32_t len) { FRESULT result = vexFileDirectoryGet(path, buffer, len); if (result != F_OK) { errno = FRESULTMAP[result]; return PROS_ERR; } return PROS_SUCCESS; } ================================================ FILE: src/devices/vdml_usd.cpp ================================================ /** * \file devices/usd.cpp * * Contains functions for interacting with the SD card. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" namespace pros { namespace usd { using namespace pros::c; std::int32_t is_installed(void) { return usd_is_installed(); } int32_t list_files(const char* path, char* buffer, int32_t len) { return usd_list_files(path, buffer, len); } } // namespace usd } // namespace pros ================================================ FILE: src/devices/vdml_vision.c ================================================ /** * \file devices/vdml_vision.c * * Contains functions for interacting with the V5 Vision Sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "v5_api.h" #include "v5_apitypes.h" #include "vdml/registry.h" #include "vdml/vdml.h" typedef struct vision_data { vision_zero_e_t zero_point; } vision_data_s_t; static vision_zero_e_t get_zero_point(uint8_t port) { return ((vision_data_s_t*)registry_get_device(port)->pad)->zero_point; } static void set_zero_point(uint8_t port, vision_zero_e_t zero_point) { vision_data_s_t* data = (vision_data_s_t*)registry_get_device(port)->pad; data->zero_point = zero_point; } static void _vision_transform_coords(uint8_t port, vision_object_s_t* object_ptr) { switch (get_zero_point(port)) { case E_VISION_ZERO_CENTER: object_ptr->left_coord -= VISION_FOV_WIDTH / 2; object_ptr->top_coord = (VISION_FOV_HEIGHT / 2) - object_ptr->top_coord; break; default: break; } object_ptr->x_middle_coord = object_ptr->left_coord + (object_ptr->width / 2); object_ptr->y_middle_coord = object_ptr->top_coord - (object_ptr->height / 2); } int32_t vision_get_object_count(uint8_t port) { claim_port_i(port - 1, E_DEVICE_VISION); int32_t rtn = vexDeviceVisionObjectCountGet(device->device_info); return_port(port - 1, rtn); } vision_object_s_t vision_get_by_size(uint8_t port, const uint32_t size_id) { vision_object_s_t rtn; v5_smart_device_s_t* device; if (!claim_port_try(port - 1, E_DEVICE_VISION)) { rtn.signature = VISION_OBJECT_ERR_SIG; return rtn; } device = registry_get_device(port - 1); if ((uint32_t)vexDeviceVisionObjectCountGet(device->device_info) <= size_id) { errno = EDOM; rtn.signature = VISION_OBJECT_ERR_SIG; goto leave; } if (vexDeviceVisionObjectGet(device->device_info, size_id, (V5_DeviceVisionObject*)&rtn) == 0) { errno = EAGAIN; rtn.signature = VISION_OBJECT_ERR_SIG; goto leave; } _vision_transform_coords(port - 1, &rtn); leave: port_mutex_give(port - 1); return rtn; } vision_object_s_t _vision_get_by_sig(uint8_t port, const uint32_t size_id, const uint32_t sig_id) { vision_object_s_t rtn; rtn.signature = VISION_OBJECT_ERR_SIG; v5_smart_device_s_t* device; uint8_t count = 0; int32_t object_count = 0; if (!claim_port_try(port - 1, E_DEVICE_VISION)) { goto err_return_no_mutex; } device = registry_get_device(port - 1); object_count = vexDeviceVisionObjectCountGet(device->device_info); if ((uint32_t)object_count <= size_id) { errno = EDOM; goto err_return; } for (uint8_t i = 0; i <= object_count; i++) { vision_object_s_t check; if (vexDeviceVisionObjectGet(device->device_info, i, (V5_DeviceVisionObject*)&check) == PROS_ERR) { errno = EAGAIN; rtn = check; goto err_return; } if (check.signature == sig_id) { if (count == size_id) { rtn = check; _vision_transform_coords(port - 1, &rtn); port_mutex_give(port - 1); return rtn; } count++; } } errno = EDOM; // we read through all the objects and none matched sig_id and size_id err_return: port_mutex_give(port - 1); err_return_no_mutex: rtn.signature = VISION_OBJECT_ERR_SIG; return rtn; } vision_object_s_t vision_get_by_sig(uint8_t port, const uint32_t size_id, const uint32_t sig_id) { if (sig_id > 7 || sig_id == 0) { errno = EINVAL; vision_object_s_t rtn; rtn.signature = VISION_OBJECT_ERR_SIG; return rtn; } return _vision_get_by_sig(port, size_id, sig_id); } vision_object_s_t vision_get_by_code(uint8_t port, const uint32_t size_id, const vision_color_code_t color_code) { return _vision_get_by_sig(port, size_id, color_code); } int32_t vision_read_by_size(uint8_t port, const uint32_t size_id, const uint32_t object_count, vision_object_s_t* const object_arr) { claim_port_i(port - 1, E_DEVICE_VISION); for (uint8_t i = 0; i < object_count; i++) { object_arr[i].signature = VISION_OBJECT_ERR_SIG; } uint32_t c = vexDeviceVisionObjectCountGet(device->device_info); if (c <= size_id) { port_mutex_give(port - 1); errno = EDOM; return PROS_ERR; } else if (c > object_count + size_id) { c = object_count + size_id; } for (uint32_t i = size_id; i < c; i++) { if (!vexDeviceVisionObjectGet(device->device_info, i, (V5_DeviceVisionObject*)(object_arr + i))) { errno = EAGAIN; object_arr[i].signature = VISION_OBJECT_ERR_SIG; break; } _vision_transform_coords(port - 1, &object_arr[i]); } return_port(port - 1, c); } int32_t _vision_read_by_sig(uint8_t port, const uint32_t size_id, const uint32_t sig_id, const uint32_t object_count, vision_object_s_t* const object_arr) { claim_port_i(port - 1, E_DEVICE_VISION); for (uint8_t i = 0; i < object_count; i++) { object_arr[i].signature = VISION_OBJECT_ERR_SIG; } uint32_t c = vexDeviceVisionObjectCountGet(device->device_info); if (c <= size_id) { errno = EDOM; port_mutex_give(port - 1); return PROS_ERR; } if (c > object_count) { c = object_count; } uint32_t j = 0; // track how many objects we've placed into object_arr uint32_t seen = 0; // track how many objects we've seen matching sig_id for (uint8_t i = 0; i < c; i++) { // loop through all objects on sensor // place i-th object on vision sensor on j-th position in object_arr if (!vexDeviceVisionObjectGet(device->device_info, i, (V5_DeviceVisionObject*)(object_arr + j))) { errno = EAGAIN; object_arr[i].signature = VISION_OBJECT_ERR_SIG; goto rtn; } // check if this (j-th) object matches sig_id if (object_arr[j].signature == sig_id) { seen++; if (seen >= size_id) { // have we seen enough objects to start adding to object_arr? // if so, transform the coords and "commit" it by incrementing j _vision_transform_coords(port - 1, &object_arr[j]); j++; if (j == object_count) goto rtn; } } } errno = EDOM; // read through all objects and couldn't find enough objects matching filter parameters rtn: return_port(port - 1, j); } int32_t vision_read_by_sig(uint8_t port, const uint32_t size_id, const uint32_t sig_id, const uint32_t object_count, vision_object_s_t* const object_arr) { if (sig_id > 7 || sig_id == 0) { errno = EINVAL; for (uint8_t i = 0; i < object_count; i++) { object_arr[i].signature = VISION_OBJECT_ERR_SIG; } return PROS_ERR; } return _vision_read_by_sig(port, size_id, sig_id, object_count, object_arr); } int32_t vision_read_by_code(uint8_t port, const uint32_t size_id, const vision_color_code_t color_code, const uint32_t object_count, vision_object_s_t* const object_arr) { return _vision_read_by_sig(port, size_id, color_code, object_count, object_arr); } vision_signature_s_t vision_get_signature(uint8_t port, const uint8_t signature_id) { vision_signature_s_t sig; sig.id = VISION_OBJECT_ERR_SIG; if (signature_id > 7 || signature_id == 0) { errno = EINVAL; return sig; } int32_t rtn = claim_port_try(port - 1, E_DEVICE_VISION); if (!rtn) { return sig; } v5_smart_device_s_t* device = registry_get_device(port - 1); rtn = vexDeviceVisionSignatureGet(device->device_info, signature_id, (V5_DeviceVisionSignature*)&sig); if (!rtn || !sig._pad[0]) { // sig._pad[0] is flags, will be set to 1 if data is valid and signatures are sent errno = EAGAIN; sig.id = VISION_OBJECT_ERR_SIG; } port_mutex_give(port - 1); return sig; } int32_t vision_set_signature(uint8_t port, const uint8_t signature_id, vision_signature_s_t* const signature_ptr) { if (signature_id > 7 || signature_id == 0) { errno = EINVAL; return PROS_ERR; } signature_ptr->id = signature_id; claim_port_i(port - 1, E_DEVICE_VISION); vexDeviceVisionSignatureSet(device->device_info, (V5_DeviceVisionSignature*)signature_ptr); return_port(port - 1, PROS_SUCCESS); } vision_signature_s_t vision_signature_from_utility(const int32_t id, const int32_t u_min, const int32_t u_max, const int32_t u_mean, const int32_t v_min, const int32_t v_max, const int32_t v_mean, const float range, const int32_t type) { vision_signature_s_t sig = {0}; sig.id = id; sig.range = range; sig.u_min = u_min; sig.u_max = u_max; sig.u_mean = u_mean; sig.v_min = v_min; sig.v_max = v_max; sig.v_mean = v_mean; sig.type = type; return sig; } vision_color_code_t vision_create_color_code(uint8_t port, const uint32_t sig_id1, const uint32_t sig_id2, const uint32_t sig_id3, const uint32_t sig_id4, const uint32_t sig_id5) { uint16_t id = 0; if (!sig_id1 || !sig_id2 || sig_id1 > 7 || sig_id2 > 7 || sig_id3 > 7 || sig_id4 > 7 || sig_id5 > 7) { // Need to at least have two signatures to make a color code, and they all // must be in the range [0-7] errno = EINVAL; id = VISION_OBJECT_ERR_SIG; return id; } const uint32_t sigs[5] = {sig_id1, sig_id2, sig_id3, sig_id4, sig_id5}; for (size_t i = 0; i < 5 && sigs[i]; i++) { register const uint32_t sig_id = sigs[i]; id = (id << 3) | sig_id; vision_signature_s_t stored_sig = vision_get_signature(port, sig_id); if (stored_sig.type != E_VISION_OBJECT_COLOR_CODE) { stored_sig.type = E_VISION_OBJECT_COLOR_CODE; vision_set_signature(port, sig_id, &stored_sig); } } return id; } int32_t vision_set_led(uint8_t port, const int32_t rgb) { claim_port_i(port - 1, E_DEVICE_VISION); vexDeviceVisionLedModeSet(device->device_info, 1); V5_DeviceVisionRgb _rgb = {.red = COLOR2R(rgb), .blue = COLOR2B(rgb), .green = COLOR2G(rgb), .brightness = 255}; vexDeviceVisionLedColorSet(device->device_info, _rgb); return_port(port - 1, PROS_SUCCESS); } int32_t vision_clear_led(uint8_t port) { claim_port_i(port - 1, E_DEVICE_VISION); vexDeviceVisionLedModeSet(device->device_info, 0); return_port(port - 1, PROS_SUCCESS); } int32_t vision_set_exposure(uint8_t port, const uint8_t percent) { claim_port_i(port - 1, E_DEVICE_VISION); // This translation comes from VEX to match the brightness represented in vision utility vexDeviceVisionBrightnessSet(device->device_info, (((int)((percent * 100) + 50)) / 255)); return_port(port - 1, PROS_SUCCESS); } int32_t vision_get_exposure(uint8_t port) { claim_port_i(port - 1, E_DEVICE_VISION); // This translation comes from VEX to match the brightness represented in vision utility int32_t rtn = ((vexDeviceVisionBrightnessGet(device->device_info) * 255) + 50) / 100; return_port(port - 1, rtn); } int32_t vision_set_auto_white_balance(uint8_t port, const uint8_t enable) { if (enable != 0 && enable != 1) { errno = EINVAL; return PROS_ERR; } claim_port_i(port - 1, E_DEVICE_VISION); vexDeviceVisionWhiteBalanceModeSet(device->device_info, enable + 1); return_port(port - 1, PROS_SUCCESS); } int32_t vision_set_white_balance(uint8_t port, const int32_t rgb) { claim_port_i(port - 1, E_DEVICE_VISION); vexDeviceVisionWhiteBalanceModeSet(device->device_info, 2); V5_DeviceVisionRgb _rgb = {.red = COLOR2R(rgb), .blue = COLOR2B(rgb), .green = COLOR2G(rgb), .brightness = 255}; vexDeviceVisionWhiteBalanceSet(device->device_info, _rgb); return_port(port - 1, PROS_SUCCESS); } int32_t vision_get_white_balance(uint8_t port) { claim_port_i(port - 1, E_DEVICE_VISION); V5_DeviceVisionRgb rgb = vexDeviceVisionWhiteBalanceGet(device->device_info); return_port(port - 1, RGB2COLOR(rgb.red, rgb.green, rgb.blue)); } int32_t vision_set_zero_point(uint8_t port, vision_zero_e_t zero_point) { if (!VALIDATE_PORT_NO(port - 1)) { errno = ENXIO; return PROS_ERR; } if (registry_validate_binding(port - 1, E_DEVICE_VISION) != 0) { errno = ENODEV; return PROS_ERR; } if (!port_mutex_take(port - 1)) { errno = EACCES; return PROS_ERR; } set_zero_point(port - 1, zero_point); return_port(port - 1, PROS_SUCCESS); } int32_t vision_set_wifi_mode(uint8_t port, const uint8_t enable) { claim_port_i(port - 1, E_DEVICE_VISION); vexDeviceVisionWifiModeSet(device->device_info, !!enable); return_port(port - 1, PROS_SUCCESS); } int32_t vision_print_signature(const vision_signature_s_t sig) { printf("\n\npros::vision_signature_s_t SIG_%d = {", sig.id); printf("%d, {%d, %d, %d}, %f, %ld, %ld, %ld, %ld, %ld, %ld, %ld, %ld};\n\n", sig.id, sig._pad[0], sig._pad[1], sig._pad[2], sig.range, sig.u_min, sig.u_max, sig.u_mean, sig.v_min, sig.v_max, sig.v_mean, sig.rgb, sig.type); return 1; } ================================================ FILE: src/devices/vdml_vision.cpp ================================================ /** * \file devices/vdml_vision.cpp * * Contains functions for interacting with the V5 Vision Sensor. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "vdml/vdml.h" namespace pros { inline namespace v5 { using namespace pros::c; Vision::Vision(std::uint8_t port, vision_zero_e_t zero_point) : Device(port, DeviceType::vision) { vision_set_zero_point(port, zero_point); } std::int32_t Vision::clear_led(void) const { return vision_clear_led(_port); } vision_signature_s_t Vision::signature_from_utility(const std::int32_t id, const std::int32_t u_min, const std::int32_t u_max, const std::int32_t u_mean, const std::int32_t v_min, const std::int32_t v_max, const std::int32_t v_mean, const float range, const std::int32_t type) { return c::vision_signature_from_utility(id, u_min, u_max, u_mean, v_min, v_max, v_mean, range, type); } vision_color_code_t Vision::create_color_code(const std::uint32_t sig_id1, const std::uint32_t sig_id2, const std::uint32_t sig_id3, const std::uint32_t sig_id4, const std::uint32_t sig_id5) const { return vision_create_color_code(_port, sig_id1, sig_id2, sig_id3, sig_id4, sig_id5); } std::vector Vision::get_all_devices() { std::vector matching_devices{Device::get_all_devices(DeviceType::vision)}; std::vector return_vector; for (auto device : matching_devices) { return_vector.push_back(device); } return return_vector; } vision_object_s_t Vision::get_by_size(const std::uint32_t size_id) const { return vision_get_by_size(_port, size_id); } vision_object_s_t Vision::get_by_sig(const std::uint32_t size_id, const std::uint32_t sig_id) const { return vision_get_by_sig(_port, size_id, sig_id); } vision_object_s_t Vision::get_by_code(const std::uint32_t size_id, const vision_color_code_t color_code) const { return vision_get_by_code(_port, size_id, color_code); } int32_t Vision::get_exposure(void) const { return vision_get_exposure(_port); } int32_t Vision::get_object_count(void) const { return vision_get_object_count(_port); } std::int32_t Vision::get_white_balance(void) const { return vision_get_white_balance(_port); } int32_t Vision::read_by_size(const std::uint32_t size_id, const std::uint32_t object_count, vision_object_s_t* const object_arr) const { return vision_read_by_size(_port, size_id, object_count, object_arr); } int32_t Vision::read_by_sig(const std::uint32_t size_id, const std::uint32_t sig_id, const std::uint32_t object_count, vision_object_s_t* const object_arr) const { return vision_read_by_sig(_port, size_id, sig_id, object_count, object_arr); } int32_t Vision::read_by_code(const std::uint32_t size_id, const vision_color_code_t color_code, const std::uint32_t object_count, vision_object_s_t* const object_arr) const { return vision_read_by_code(_port, size_id, color_code, object_count, object_arr); } vision_signature_s_t Vision::get_signature(const std::uint8_t signature_id) const { return vision_get_signature(_port, signature_id); } std::int32_t Vision::print_signature(const vision_signature_s_t sig) { return vision_print_signature(sig); } std::int32_t Vision::set_signature(const std::uint8_t signature_id, vision_signature_s_t* const signature_ptr) const { return vision_set_signature(_port, signature_id, signature_ptr); } std::int32_t Vision::set_auto_white_balance(const std::uint8_t enable) const { return vision_set_auto_white_balance(_port, enable); } std::int32_t Vision::set_exposure(const std::uint8_t exposure) const { return vision_set_exposure(_port, exposure); } std::int32_t Vision::set_led(const std::int32_t rgb) const { return vision_set_led(_port, rgb); } std::int32_t Vision::set_white_balance(const std::int32_t rgb) const { return vision_set_white_balance(_port, rgb); } std::int32_t Vision::set_zero_point(vision_zero_e_t zero_point) const { return vision_set_zero_point(_port, zero_point); } std::int32_t Vision::set_wifi_mode(const std::uint8_t enable) const { return vision_set_wifi_mode(_port, enable); } Vision Vision::get_vision() { static int curr_vision_port = 0; curr_vision_port = curr_vision_port % 21; for (int i = 0; i < 21; i++) { if (registry_get_device(curr_vision_port)->device_type == pros::c::E_DEVICE_VISION) { curr_vision_port++; return Vision(curr_vision_port); } curr_vision_port++; curr_vision_port = curr_vision_port % 21; } errno = ENODEV; return Vision(PROS_ERR_BYTE); } } // namespace v5 namespace literals { const pros::Vision operator""_vis(const unsigned long long int m) { return Vision(m); } } // namespace literals } // namespace pros ================================================ FILE: src/main.cpp ================================================ #include "main.h" /** * A callback function for LLEMU's center button. * * When this callback is fired, it will toggle line 2 of the LCD text between * "I was pressed!" and nothing. */ void on_center_button() { static bool pressed = false; pressed = !pressed; if (pressed) { pros::lcd::set_text(2, "I was pressed!"); } else { pros::lcd::clear_line(2); } } /** * Runs initialization code. This occurs as soon as the program is started. * * All other competition modes are blocked by initialize; it is recommended * to keep execution time for this mode under a few seconds. */ void initialize() { pros::lcd::initialize(); pros::lcd::set_text(1, "Hello PROS User!"); pros::lcd::register_btn1_cb(on_center_button); } /** * Runs while the robot is in the disabled state of Field Management System or * the VEX Competition Switch, following either autonomous or opcontrol. When * the robot is enabled, this task will exit. */ void disabled() {} /** * Runs after initialize(), and before autonomous when connected to the Field * Management System or the VEX Competition Switch. This is intended for * competition-specific initialization routines, such as an autonomous selector * on the LCD. * * This task will exit when the robot is enabled and autonomous or opcontrol * starts. */ void competition_initialize() {} /** * Runs the user autonomous code. This function will be started in its own task * with the default priority and stack size whenever the robot is enabled via * the Field Management System or the VEX Competition Switch in the autonomous * mode. Alternatively, this function may be called in initialize or opcontrol * for non-competition testing purposes. * * If the robot is disabled or communications is lost, the autonomous task * will be stopped. Re-enabling the robot will restart the task, not re-start it * from where it left off. */ void autonomous() {} /** * Runs the operator control code. This function will be started in its own task * with the default priority and stack size whenever the robot is enabled via * the Field Management System or the VEX Competition Switch in the operator * control mode. * * If no competition control is connected, this function will run immediately * following initialize(). * * If the robot is disabled or communications is lost, the * operator control task will be stopped. Re-enabling the robot will restart the * task, not resume it from where it left off. */ void opcontrol() { pros::Controller master(pros::E_CONTROLLER_MASTER); pros::MotorGroup left_mg({1, -2, 3}); // Creates a motor group with forwards ports 1 & 3 and reversed port 2 pros::MotorGroup right_mg({-4, 5, -6}); // Creates a motor group with forwards port 5 and reversed ports 4 & 6 while (true) { pros::lcd::print(0, "%d %d %d", (pros::lcd::read_buttons() & LCD_BTN_LEFT) >> 2, (pros::lcd::read_buttons() & LCD_BTN_CENTER) >> 1, (pros::lcd::read_buttons() & LCD_BTN_RIGHT) >> 0); // Prints status of the emulated screen LCDs // Arcade control scheme int dir = master.get_analog(ANALOG_LEFT_Y); // Gets amount forward/backward from left joystick int turn = master.get_analog(ANALOG_RIGHT_X); // Gets the turn left/right from right joystick left_mg.move(dir - turn); // Sets left motor voltage right_mg.move(dir + turn); // Sets right motor voltage pros::delay(20); // Run for 20 ms then update } } ================================================ FILE: src/rtos/LICENSE ================================================ The FreeRTOS kernel is released under the MIT open source license, the text of which is provided below. This license covers the FreeRTOS kernel source files, which are located in the /FreeRTOS/Source directory of the official FreeRTOS kernel download. It also covers most of the source files in the demo application projects, which are located in the /FreeRTOS/Demo directory of the official FreeRTOS download. The demo projects may also include third party software that is not part of FreeRTOS and is licensed separately to FreeRTOS. Examples of third party software includes header files provided by chip or tools vendors, linker scripts, peripheral drivers, etc. All the software in subdirectories of the /FreeRTOS directory is either open source or distributed with permission, and is free for use. For the avoidance of doubt, refer to the comments at the top of each source file. License text: ------------- Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: src/rtos/README.md ================================================ ## The FreeRTOS Kernel Library __Note: modifiying these files may break PROS or make PROS unstable__ _This file serves as an introduction to how PROS uses FreeRTOS if you're just_ _getting started with development of the PROS kernel. It also contains some_ _notes from configuring FreeRTOS to work with the V5._ PROS 3 uses FreeRTOS 9.0.0 to implement scheduling, queues, and lists - the barebones of an operating system. In some respects, FreeRTOS could be thought of as a C library that we have ported to the V5. It of course does more significant work that a typical application library. Since computer architectures are different and FreeRTOS aims to work with many embedded architectures, some work must be done to let FreeRTOS work with the hardware. FreeRTOS provides many demo projects and the developers recommend modifying one of the projects to suit the needs of the project. Since the V5 is Zynq-7000 board, we're modifying the Cortex\_A9\_Zynq\_ZC702 demo. You should read some of FreeRTOS's documentation and/or take an equivalent of Purdue's CS250 (Computer Architecture) and CS354 (Operating Systems) for requisite background knowledge. For more info about the Zynq/A9 port, see FreeRTOS's documentation on [Zynq](http://www.freertos.org/RTOS-Xilinx-Zynq.html) and the [A9](http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html). ## Modifications to FreeRTOS We've somewhat significantly refactored the FreeRTOS kernel so that any FreeRTOS functions used within PROS align with the PROS coding style. See refactor.tsv in this directory. We've removed the use of `int32_t` and `uint32_t` from any public facing API since we felt it unnecessary. Additionally, all variables pertaining to ticks on the PROS internal or public facing APIs have become millisecond precision, and the conversion done immediately upon entering the functiion. ================================================ FILE: src/rtos/heap_4.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* * A sample implementation of kmalloc() and kfree() that combines * (coalescences) adjacent memory blocks as they are freed, and in so doing * limits memory fragmentation. * * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the * memory management pages of http://www.FreeRTOS.org for more information. */ #include #include "FreeRTOS.h" #include "task.h" #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 #endif /* Block sizes must not get too small. */ #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) /* Assumes 8bit bytes! */ #define heapBITS_PER_BYTE ( ( size_t ) 8 ) /* Allocate the memory for the heap. */ #if( configAPPLICATION_ALLOCATED_HEAP == 1 ) /* The application writer has already defined the array used for the RTOS heap - probably so it can be placed in a special segment or address. */ extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #else static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; #endif /* configAPPLICATION_ALLOCATED_HEAP */ /* Define the linked list structure. This is used to link free blocks in order of their memory address. */ typedef struct A_BLOCK_LINK { struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; /*-----------------------------------------------------------*/ /* * Inserts a block of memory that is being freed into the correct position in * the list of free memory blocks. The block being freed will be merged with * the block in front it and/or the block behind it if the memory blocks are * adjacent to each other. */ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); /* * Called automatically to setup the required heap structures the first time * kmalloc() is called. */ static void prvHeapInit( void ); /*-----------------------------------------------------------*/ /* The size of the structure placed at the beginning of each allocated memory block must by correctly byte aligned. */ static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; /* Keeps track of the number of free bytes remaining, but says nothing about fragmentation. */ static size_t xFreeBytesRemaining = 0U; static size_t xMinimumEverFreeBytesRemaining = 0U; /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize member of an BlockLink_t structure is set then the block belongs to the application. When the bit is free the block is still part of the free heap space. */ static size_t xBlockAllocatedBit = 0; /*-----------------------------------------------------------*/ void *kmalloc( size_t xWantedSize ) { BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; void *pvReturn = NULL; rtos_suspend_all(); { /* If this is the first call to malloc then the heap will require initialisation to setup the list of free blocks. */ if( pxEnd == NULL ) { prvHeapInit(); } else { mtCOVERAGE_TEST_MARKER(); } /* Check the requested block size is not so large that the top bit is set. The top bit of the block size member of the BlockLink_t structure is used to determine who owns the block - the application or the kernel, so it must be free. */ if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) { /* The wanted size is increased so it can contain a BlockLink_t structure in addition to the requested amount of bytes. */ if( xWantedSize > 0 ) { xWantedSize += xHeapStructSize; /* Ensure that blocks are always aligned to the required number of bytes. */ if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) { /* Byte alignment required. */ xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) { /* Traverse the list from the start (lowest address) block until one of adequate size is found. */ pxPreviousBlock = &xStart; pxBlock = xStart.pxNextFreeBlock; while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) { pxPreviousBlock = pxBlock; pxBlock = pxBlock->pxNextFreeBlock; } /* If the end marker was reached then a block of adequate size was not found. */ if( pxBlock != pxEnd ) { /* Return the memory space pointed to - jumping over the BlockLink_t structure at its start. */ pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); /* This block is being returned for use so must be taken out of the list of free blocks. */ pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; /* If the block is larger than required it can be split into two. */ if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) { /* This block is to be split into two. Create a new block following the number of bytes requested. The void cast is used to prevent byte alignment warnings from the compiler. */ pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); /* Calculate the sizes of two blocks split from the single block. */ pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; pxBlock->xBlockSize = xWantedSize; /* Insert the new block into the list of free blocks. */ prvInsertBlockIntoFreeList( pxNewBlockLink ); } else { mtCOVERAGE_TEST_MARKER(); } xFreeBytesRemaining -= pxBlock->xBlockSize; if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) { xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; } else { mtCOVERAGE_TEST_MARKER(); } /* The block is being returned - it is allocated and owned by the application and has no "next" block. */ pxBlock->xBlockSize |= xBlockAllocatedBit; pxBlock->pxNextFreeBlock = NULL; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } traceMALLOC( pvReturn, xWantedSize ); } ( void ) rtos_resume_all(); #if( configUSE_MALLOC_FAILED_HOOK == 1 ) { if( pvReturn == NULL ) { extern void vApplicationMallocFailedHook( void ); vApplicationMallocFailedHook(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); return pvReturn; } /*-----------------------------------------------------------*/ void kfree( void *pv ) { uint8_t *puc = ( uint8_t * ) pv; BlockLink_t *pxLink; if( pv != NULL ) { /* The memory being freed will have an BlockLink_t structure immediately before it. */ puc -= xHeapStructSize; /* This casting is to keep the compiler from issuing warnings. */ pxLink = ( void * ) puc; /* Check the block is actually allocated. */ configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); configASSERT( pxLink->pxNextFreeBlock == NULL ); if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) { if( pxLink->pxNextFreeBlock == NULL ) { /* The block is being returned to the heap - it is no longer allocated. */ pxLink->xBlockSize &= ~xBlockAllocatedBit; rtos_suspend_all(); { /* Add this block to the list of free blocks. */ xFreeBytesRemaining += pxLink->xBlockSize; traceFREE( pv, pxLink->xBlockSize ); prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); } ( void ) rtos_resume_all(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } } /*-----------------------------------------------------------*/ size_t xPortGetFreeHeapSize( void ) { return xFreeBytesRemaining; } /*-----------------------------------------------------------*/ size_t xPortGetMinimumEverFreeHeapSize( void ) { return xMinimumEverFreeBytesRemaining; } /*-----------------------------------------------------------*/ void vPortInitialiseBlocks( void ) { /* This just exists to keep the linker quiet. */ } /*-----------------------------------------------------------*/ static void prvHeapInit( void ) { BlockLink_t *pxFirstFreeBlock; uint8_t *pucAlignedHeap; size_t uxAddress; size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; /* Ensure the heap starts on a correctly aligned boundary. */ uxAddress = ( size_t ) ucHeap; if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) { uxAddress += ( portBYTE_ALIGNMENT - 1 ); uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; } pucAlignedHeap = ( uint8_t * ) uxAddress; /* xStart is used to hold a pointer to the first item in the list of free blocks. The void cast is used to prevent compiler warnings. */ xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; xStart.xBlockSize = ( size_t ) 0; /* pxEnd is used to mark the end of the list of free blocks and is inserted at the end of the heap space. */ uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; uxAddress -= xHeapStructSize; uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); pxEnd = ( void * ) uxAddress; pxEnd->xBlockSize = 0; pxEnd->pxNextFreeBlock = NULL; /* To start with there is a single free block that is sized to take up the entire heap space, minus the space taken by pxEnd. */ pxFirstFreeBlock = ( void * ) pucAlignedHeap; pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; pxFirstFreeBlock->pxNextFreeBlock = pxEnd; /* Only one block exists - and it covers the entire usable heap space. */ xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; /* Work out the position of the top bit in a size_t variable. */ xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); } /*-----------------------------------------------------------*/ static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) { BlockLink_t *pxIterator; uint8_t *puc; /* Iterate through the list until a block is found that has a higher address than the block being inserted. */ for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) { /* Nothing to do here, just iterate to the right position. */ } /* Do the block being inserted, and the block it is being inserted after make a contiguous block of memory? */ puc = ( uint8_t * ) pxIterator; if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) { pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; pxBlockToInsert = pxIterator; } else { mtCOVERAGE_TEST_MARKER(); } /* Do the block being inserted, and the block it is being inserted before make a contiguous block of memory? */ puc = ( uint8_t * ) pxBlockToInsert; if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) { if( pxIterator->pxNextFreeBlock != pxEnd ) { /* Form one big block from the two blocks. */ pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; } else { pxBlockToInsert->pxNextFreeBlock = pxEnd; } } else { pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; } /* If the block being inserted plugged a gab, so was merged with the block before and the block after, then it's pxNextFreeBlock pointer will have already been set, and should not be set here as that would make it point to itself. */ if( pxIterator != pxBlockToInsert ) { pxIterator->pxNextFreeBlock = pxBlockToInsert; } else { mtCOVERAGE_TEST_MARKER(); } } ================================================ FILE: src/rtos/list.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include #include "FreeRTOS.h" #include "list.h" /*----------------------------------------------------------- * PUBLIC LIST API documented in list.h *----------------------------------------------------------*/ void vListInitialise( List_t * const pxList ) { /* The list structure contains a list item which is used to mark the end of the list. To initialise the list the list end is inserted as the only list entry. */ pxList->pxIndex = ( list_item_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ /* The list end value is the highest possible value in the list to ensure it remains at the end of the list. */ pxList->xListEnd.xItemValue = portMAX_DELAY; /* The list end next and previous pointers point to itself so we know when the list is empty. */ pxList->xListEnd.pxNext = ( list_item_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ pxList->xListEnd.pxPrevious = ( list_item_t * ) &( pxList->xListEnd );/*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ pxList->uxNumberOfItems = ( uint32_t ) 0U; /* Write known values into the list if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); } /*-----------------------------------------------------------*/ void vListInitialiseItem( list_item_t * const pxItem ) { /* Make sure the list item is not recorded as being on a list. */ pxItem->pvContainer = NULL; /* Write known values into the list item if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); } /*-----------------------------------------------------------*/ void vListInsertEnd( List_t * const pxList, list_item_t * const pxNewListItem ) { list_item_t * const pxIndex = pxList->pxIndex; /* Only effective when configASSERT() is also defined, these tests may catch the list data structures being overwritten in memory. They will not catch data errors caused by incorrect configuration or use of FreeRTOS. */ listTEST_LIST_INTEGRITY( pxList ); listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); /* Insert a new list item into pxList, but rather than sort the list, makes the new list item the last item to be removed by a call to listGET_OWNER_OF_NEXT_ENTRY(). */ pxNewListItem->pxNext = pxIndex; pxNewListItem->pxPrevious = pxIndex->pxPrevious; /* Only used during decision coverage testing. */ mtCOVERAGE_TEST_DELAY(); pxIndex->pxPrevious->pxNext = pxNewListItem; pxIndex->pxPrevious = pxNewListItem; /* Remember which list the item is in. */ pxNewListItem->pvContainer = ( void * ) pxList; ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ void vListInsert( List_t * const pxList, list_item_t * const pxNewListItem ) { list_item_t *pxIterator; const uint32_t xValueOfInsertion = pxNewListItem->xItemValue; /* Only effective when configASSERT() is also defined, these tests may catch the list data structures being overwritten in memory. They will not catch data errors caused by incorrect configuration or use of FreeRTOS. */ listTEST_LIST_INTEGRITY( pxList ); listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); /* Insert the new list item into the list, sorted in xItemValue order. If the list already contains a list item with the same item value then the new list item should be placed after it. This ensures that TCB's which are stored in ready lists (all of which have the same xItemValue value) get a share of the CPU. However, if the xItemValue is the same as the back marker the iteration loop below will not end. Therefore the value is checked first, and the algorithm slightly modified if necessary. */ if( xValueOfInsertion == portMAX_DELAY ) { pxIterator = pxList->xListEnd.pxPrevious; } else { /* *** NOTE *********************************************************** If you find your application is crashing here then likely causes are listed below. In addition see http://www.freertos.org/FAQHelp.html for more tips, and ensure configASSERT() is defined! http://www.freertos.org/a00110.html#configASSERT 1) Stack overflow - see http://www.freertos.org/Stacks-and-stack-overflow-checking.html 2) Incorrect interrupt priority assignment, especially on Cortex-M parts where numerically high priority values denote low actual interrupt priorities, which can seem counter intuitive. See http://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition of configMAX_SYSCALL_INTERRUPT_PRIORITY on http://www.freertos.org/a00110.html 3) Calling an API function from within a critical section or when the scheduler is suspended, or calling an API function that does not end in "FromISR" from an interrupt. 4) Using a queue or semaphore before it has been initialised or before the scheduler has been started (are interrupts firing before rtos_sched_start() has been called?). **********************************************************************/ for( pxIterator = ( list_item_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 The mini list structure is used as the list end to save RAM. This is checked and valid. */ { /* There is nothing to do here, just iterating to the wanted insertion position. */ } } pxNewListItem->pxNext = pxIterator->pxNext; pxNewListItem->pxNext->pxPrevious = pxNewListItem; pxNewListItem->pxPrevious = pxIterator; pxIterator->pxNext = pxNewListItem; /* Remember which list the item is in. This allows fast removal of the item later. */ pxNewListItem->pvContainer = ( void * ) pxList; ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ uint32_t uxListRemove( list_item_t * const pxItemToRemove ) { /* The list item knows which list it is in. Obtain the list from the list item. */ List_t * const pxList = ( List_t * ) pxItemToRemove->pvContainer; pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; /* Only used during decision coverage testing. */ mtCOVERAGE_TEST_DELAY(); /* Make sure the index is left pointing to a valid item. */ if( pxList->pxIndex == pxItemToRemove ) { pxList->pxIndex = pxItemToRemove->pxPrevious; } else { mtCOVERAGE_TEST_MARKER(); } pxItemToRemove->pvContainer = NULL; ( pxList->uxNumberOfItems )--; return pxList->uxNumberOfItems; } /*-----------------------------------------------------------*/ ================================================ FILE: src/rtos/port.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* Standard includes. */ #include /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" #ifndef configINTERRUPT_CONTROLLER_BASE_ADDRESS #error configINTERRUPT_CONTROLLER_BASE_ADDRESS must be defined. See http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html #endif #ifndef configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET #error configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET must be defined. See http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html #endif #ifndef configUNIQUE_INTERRUPT_PRIORITIES #error configUNIQUE_INTERRUPT_PRIORITIES must be defined. See http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html #endif #ifndef configSETUP_TICK_INTERRUPT #error configSETUP_TICK_INTERRUPT() must be defined. See http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html #endif /* configSETUP_TICK_INTERRUPT */ #ifndef configMAX_API_CALL_INTERRUPT_PRIORITY #error configMAX_API_CALL_INTERRUPT_PRIORITY must be defined. See http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html #endif #if configMAX_API_CALL_INTERRUPT_PRIORITY == 0 #error configMAX_API_CALL_INTERRUPT_PRIORITY must not be set to 0 #endif #if configMAX_API_CALL_INTERRUPT_PRIORITY > configUNIQUE_INTERRUPT_PRIORITIES #error configMAX_API_CALL_INTERRUPT_PRIORITY must be less than or equal to configUNIQUE_INTERRUPT_PRIORITIES as the lower the numeric priority value the higher the logical interrupt priority #endif #if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 /* Check the configuration. */ #if( configMAX_PRIORITIES > 32 ) #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. #endif #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ /* In case security extensions are implemented. */ #if configMAX_API_CALL_INTERRUPT_PRIORITY <= ( configUNIQUE_INTERRUPT_PRIORITIES / 2 ) #error configMAX_API_CALL_INTERRUPT_PRIORITY must be greater than ( configUNIQUE_INTERRUPT_PRIORITIES / 2 ) #endif /* Some vendor specific files default configCLEAR_TICK_INTERRUPT() in portmacro.h. */ #ifndef configCLEAR_TICK_INTERRUPT #define configCLEAR_TICK_INTERRUPT() #endif /* A critical section is exited when the critical section nesting count reaches this value. */ #define portNO_CRITICAL_NESTING ( ( uint32_t ) 0 ) /* In all GICs 255 can be written to the priority mask register to unmask all (but the lowest) interrupt priority. */ #define portUNMASK_VALUE ( 0xFFUL ) /* Tasks are not created with a floating point context, but can be given a floating point context after they have been created. A variable is stored as part of the tasks context that holds portNO_FLOATING_POINT_CONTEXT if the task does not have an FPU context, or any other value if the task does have an FPU context. */ #define portNO_FLOATING_POINT_CONTEXT ( ( task_stack_t ) 0 ) /* Constants required to setup the initial task context. */ #define portINITIAL_SPSR ( ( task_stack_t ) 0x1f ) /* System mode, ARM mode, IRQ enabled FIQ enabled. */ #define portTHUMB_MODE_BIT ( ( task_stack_t ) 0x20 ) #define portINTERRUPT_ENABLE_BIT ( 0x80UL ) #define portTHUMB_MODE_ADDRESS ( 0x01UL ) /* Used by portASSERT_IF_INTERRUPT_PRIORITY_INVALID() when ensuring the binary point is zero. */ #define portBINARY_POINT_BITS ( ( uint8_t ) 0x03 ) /* Masks all bits in the APSR other than the mode bits. */ #define portAPSR_MODE_BITS_MASK ( 0x1F ) /* The value of the mode bits in the APSR when the CPU is executing in user mode. */ #define portAPSR_USER_MODE ( 0x10 ) /* The critical section macros only mask interrupts up to an application determined priority level. Sometimes it is necessary to turn interrupt off in the CPU itself before modifying certain hardware registers. */ #define portCPU_IRQ_DISABLE() \ __asm volatile ( "CPSID i" ::: "memory" ); \ __asm volatile ( "DSB" ); \ __asm volatile ( "ISB" ); #define portCPU_IRQ_ENABLE() \ __asm volatile ( "CPSIE i" ::: "memory" ); \ __asm volatile ( "DSB" ); \ __asm volatile ( "ISB" ); /* Macro to unmask all interrupt priorities. */ #define portCLEAR_INTERRUPT_MASK() \ { \ portCPU_IRQ_DISABLE(); \ portICCPMR_PRIORITY_MASK_REGISTER = portUNMASK_VALUE; \ __asm volatile ( "DSB \n" \ "ISB \n" ); \ portCPU_IRQ_ENABLE(); \ } #define portINTERRUPT_PRIORITY_REGISTER_OFFSET 0x400UL #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff ) #define portBIT_0_SET ( ( uint8_t ) 0x01 ) /* Let the user override the pre-loading of the initial LR with the address of prvTaskExitError() in case it messes up unwinding of the stack in the debugger. */ #ifdef configTASK_RETURN_ADDRESS #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS #else #define portTASK_RETURN_ADDRESS prvTaskExitError #endif /* The space on the stack required to hold the FPU registers. This is 32 64-bit registers, plus a 32-bit status register. */ #define portFPU_REGISTER_WORDS ( ( 32 * 2 ) + 1 ) /*-----------------------------------------------------------*/ /* * Starts the first task executing. This function is necessarily written in * assembly code so is implemented in portASM.s. */ extern void vPortRestoreTaskContext( void ); /* * Used to catch tasks that attempt to return from their implementing function. */ static void prvTaskExitError( void ); /* * If the application provides an implementation of vApplicationIRQHandler(), * then it will get called directly without saving the FPU registers on * interrupt entry, and this weak implementation of * vApplicationFPUSafeIRQHandler() is just provided to remove linkage errors - * it should never actually get called so its implementation contains a * call to configASSERT() that will always fail. * * If the application provides its own implementation of * vApplicationFPUSafeIRQHandler() then the implementation of * vApplicationIRQHandler() provided in portASM.S will save the FPU registers * before calling it. * * Therefore, if the application writer wants FPU registers to be saved on * interrupt entry their IRQ handler must be called * vApplicationFPUSafeIRQHandler(), and if the application writer does not want * FPU registers to be saved on interrupt entry their IRQ handler must be * called vApplicationIRQHandler(). */ void vApplicationFPUSafeIRQHandler( uint32_t ulICCIAR ) __attribute__((weak) ); /*-----------------------------------------------------------*/ /* A variable is used to keep track of the critical section nesting. This variable has to be stored as part of the task context and must be initialised to a non zero value to ensure interrupts don't inadvertently become unmasked before the scheduler starts. As it is stored as part of the task context it will automatically be set to 0 when the first task is started. */ volatile uint32_t ulCriticalNesting = 9999UL; /* Saved as part of the task context. If ulPortTaskHasFPUContext is non-zero then a floating point context must be saved and restored for the task. */ volatile uint32_t ulPortTaskHasFPUContext = pdFALSE; /* Set to 1 to pend a context switch from an ISR. */ volatile uint32_t ulPortYieldRequired = pdFALSE; /* Counts the interrupt nesting depth. A context switch is only performed if if the nesting depth is 0. */ volatile uint32_t ulPortInterruptNesting = 0UL; /* Used in the asm file. */ __attribute__(( used )) const uint32_t ulICCIAR = portICCIAR_INTERRUPT_ACKNOWLEDGE_REGISTER_ADDRESS; __attribute__(( used )) const uint32_t ulICCEOIR = portICCEOIR_END_OF_INTERRUPT_REGISTER_ADDRESS; __attribute__(( used )) const uint32_t ulICCPMR = portICCPMR_PRIORITY_MASK_REGISTER_ADDRESS; __attribute__(( used )) const uint32_t ulMaxAPIPriorityMask = ( configMAX_API_CALL_INTERRUPT_PRIORITY << portPRIORITY_SHIFT ); /*-----------------------------------------------------------*/ void task_clean_up() { // TODO: Make this a kernel debugging statement // vexDisplayString(1, "Reaping dying task: %s", task_get_name(NULL)); task_delete(NULL); } /* * See header file for description. */ task_stack_t *pxPortInitialiseStack( task_stack_t *pxTopOfStack, task_fn_t pxCode, void *pvParameters ) { /* Setup the initial stack of the task. The stack is set exactly as expected by the portRESTORE_CONTEXT() macro. The fist real value on the stack is the status register, which is set for system mode, with interrupts enabled. A few NULLs are added first to ensure GDB does not try decoding a non-existent return address. */ *pxTopOfStack = ( task_stack_t ) NULL; pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) NULL; pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) NULL; pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) portINITIAL_SPSR; if( ( ( uint32_t ) pxCode & portTHUMB_MODE_ADDRESS ) != 0x00UL ) { /* The task will start in THUMB mode. */ *pxTopOfStack |= portTHUMB_MODE_BIT; } pxTopOfStack--; /* Next the return address, which in this case is the start of the task. */ extern void task_fn_wrapper(task_fn_t fn, void* args); *pxTopOfStack = ( task_stack_t ) task_fn_wrapper; pxTopOfStack--; /* Next all the registers other than the stack pointer. */ *pxTopOfStack = ( task_stack_t ) task_clean_up; /* R14 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x12121212; /* R12 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x11111111; /* R11 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x10101010; /* R10 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x09090909; /* R9 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x08080808; /* R8 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x07070707; /* R7 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x06060606; /* R6 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x05050505; /* R5 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x04040404; /* R4 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x03030303; /* R3 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) 0x02020202; /* R2 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) pvParameters; /* R1 */ pxTopOfStack--; *pxTopOfStack = ( task_stack_t ) pxCode; /* R0 */ pxTopOfStack--; /* The task will start with a critical nesting count of 0 as interrupts are enabled. */ *pxTopOfStack = portNO_CRITICAL_NESTING; #if( configUSE_TASK_FPU_SUPPORT == 1 ) { /* The task will start without a floating point context. A task that uses the floating point hardware must call vPortTaskUsesFPU() before executing any floating point instructions. */ pxTopOfStack--; *pxTopOfStack = portNO_FLOATING_POINT_CONTEXT; } #elif( configUSE_TASK_FPU_SUPPORT == 2 ) { /* The task will start with a floating point context. Leave enough space for the registers - and ensure they are initialised to 0. */ pxTopOfStack -= portFPU_REGISTER_WORDS; memset( pxTopOfStack, 0x00, portFPU_REGISTER_WORDS * sizeof( task_stack_t ) ); pxTopOfStack--; *pxTopOfStack = pdTRUE; ulPortTaskHasFPUContext = pdTRUE; } #else { #error Invalid configUSE_TASK_FPU_SUPPORT setting - configUSE_TASK_FPU_SUPPORT must be set to 1, 2, or left undefined. } #endif return pxTopOfStack; } /*-----------------------------------------------------------*/ static void prvTaskExitError( void ) { /* A function that implements a task must not exit or attempt to return to its caller as there is nothing to return to. If a task wants to exit it should instead call task_delete( NULL ). Artificially force an assert() to be triggered if configASSERT() is defined, then stop here so application writers can catch the error. */ configASSERT( ulPortInterruptNesting == ~0UL ); portDISABLE_INTERRUPTS(); for( ;; ); } /*-----------------------------------------------------------*/ int32_t xPortStartScheduler( void ) { uint32_t ulAPSR; #if( configASSERT_DEFINED == 1 ) { volatile uint32_t ulOriginalPriority; volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( configINTERRUPT_CONTROLLER_BASE_ADDRESS + portINTERRUPT_PRIORITY_REGISTER_OFFSET ); volatile uint8_t ucMaxPriorityValue; /* Determine how many priority bits are implemented in the GIC. Save the interrupt priority value that is about to be clobbered. */ ulOriginalPriority = *pucFirstUserPriorityRegister; /* Determine the number of priority bits available. First write to all possible bits. */ *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE; /* Read the value back to see how many bits stuck. */ ucMaxPriorityValue = *pucFirstUserPriorityRegister; /* Shift to the least significant bits. */ while( ( ucMaxPriorityValue & portBIT_0_SET ) != portBIT_0_SET ) { ucMaxPriorityValue >>= ( uint8_t ) 0x01; } /* Sanity check configUNIQUE_INTERRUPT_PRIORITIES matches the read value. */ configASSERT( ucMaxPriorityValue == portLOWEST_INTERRUPT_PRIORITY ); /* Restore the clobbered interrupt priority register to its original value. */ *pucFirstUserPriorityRegister = ulOriginalPriority; } #endif /* conifgASSERT_DEFINED */ /* Only continue if the CPU is not in User mode. The CPU must be in a Privileged mode for the scheduler to start. */ __asm volatile ( "MRS %0, APSR" : "=r" ( ulAPSR ) :: "memory" ); ulAPSR &= portAPSR_MODE_BITS_MASK; configASSERT( ulAPSR != portAPSR_USER_MODE ); if( ulAPSR != portAPSR_USER_MODE ) { /* Only continue if the binary point value is set to its lowest possible setting. See the comments in vPortValidateInterruptPriority() below for more information. */ configASSERT( ( portICCBPR_BINARY_POINT_REGISTER & portBINARY_POINT_BITS ) <= portMAX_BINARY_POINT_VALUE ); if( ( portICCBPR_BINARY_POINT_REGISTER & portBINARY_POINT_BITS ) <= portMAX_BINARY_POINT_VALUE ) { /* Interrupts are turned off in the CPU itself to ensure tick does not execute while the scheduler is being started. Interrupts are automatically turned back on in the CPU when the first task starts executing. */ portCPU_IRQ_DISABLE(); /* Start the timer that generates the tick ISR. */ configSETUP_TICK_INTERRUPT(); /* Start the first task executing. */ vPortRestoreTaskContext(); } } /* Will only get here if rtos_sched_start() was called with the CPU in a non-privileged mode or the binary point register was not set to its lowest possible value. prvTaskExitError() is referenced to prevent a compiler warning about it being defined but not referenced in the case that the user defines their own exit address. */ ( void ) prvTaskExitError; return 0; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { /* Not implemented in ports where there is nothing to return to. Artificially force an assert. */ configASSERT( ulCriticalNesting == 1000UL ); } /*-----------------------------------------------------------*/ void vPortEnterCritical( void ) { /* Mask interrupts up to the max syscall interrupt priority. */ ulPortSetInterruptMask(); /* Now interrupts are disabled ulCriticalNesting can be accessed directly. Increment ulCriticalNesting to keep a count of how many times portENTER_CRITICAL() has been called. */ ulCriticalNesting++; /* This is not the interrupt safe version of the enter critical function so assert() if it is being called from an interrupt context. Only API functions that end in "FromISR" can be used in an interrupt. Only assert if the critical nesting count is 1 to protect against recursive calls if the assert function also uses a critical section. */ if( ulCriticalNesting == 1 ) { configASSERT( ulPortInterruptNesting == 0 ); } } /*-----------------------------------------------------------*/ void vPortExitCritical( void ) { if( ulCriticalNesting > portNO_CRITICAL_NESTING ) { /* Decrement the nesting count as the critical section is being exited. */ ulCriticalNesting--; /* If the nesting level has reached zero then all interrupt priorities must be re-enabled. */ if( ulCriticalNesting == portNO_CRITICAL_NESTING ) { /* Critical nesting has reached zero so all interrupt priorities should be unmasked. */ portCLEAR_INTERRUPT_MASK(); } } } /*-----------------------------------------------------------*/ void FreeRTOS_Tick_Handler( void ) { /* Set interrupt mask before altering scheduler structures. The tick handler runs at the lowest priority, so interrupts cannot already be masked, so there is no need to save and restore the current mask value. It is necessary to turn off interrupts in the CPU itself while the ICCPMR is being updated. */ portCPU_IRQ_DISABLE(); portICCPMR_PRIORITY_MASK_REGISTER = ( uint32_t ) ( configMAX_API_CALL_INTERRUPT_PRIORITY << portPRIORITY_SHIFT ); __asm volatile ( "dsb \n" "isb \n" ::: "memory" ); portCPU_IRQ_ENABLE(); /* Increment the RTOS tick. */ if( xTaskIncrementTick() != pdFALSE ) { ulPortYieldRequired = pdTRUE; } /* Ensure all interrupt priorities are active again. */ portCLEAR_INTERRUPT_MASK(); configCLEAR_TICK_INTERRUPT(); } /*-----------------------------------------------------------*/ #if( configUSE_TASK_FPU_SUPPORT != 2 ) void vPortTaskUsesFPU( void ) { uint32_t ulInitialFPSCR = 0; /* A task is registering the fact that it needs an FPU context. Set the FPU flag (which is saved as part of the task context). */ ulPortTaskHasFPUContext = pdTRUE; /* Initialise the floating point status register. */ __asm volatile ( "FMXR FPSCR, %0" :: "r" (ulInitialFPSCR) : "memory" ); } #endif /* configUSE_TASK_FPU_SUPPORT */ /*-----------------------------------------------------------*/ void vPortClearInterruptMask( uint32_t ulNewMaskValue ) { if( ulNewMaskValue == pdFALSE ) { portCLEAR_INTERRUPT_MASK(); } } /*-----------------------------------------------------------*/ uint32_t ulPortSetInterruptMask( void ) { uint32_t ulReturn; /* Interrupt in the CPU must be turned off while the ICCPMR is being updated. */ portCPU_IRQ_DISABLE(); if( portICCPMR_PRIORITY_MASK_REGISTER == ( uint32_t ) ( configMAX_API_CALL_INTERRUPT_PRIORITY << portPRIORITY_SHIFT ) ) { /* Interrupts were already masked. */ ulReturn = pdTRUE; } else { ulReturn = pdFALSE; portICCPMR_PRIORITY_MASK_REGISTER = ( uint32_t ) ( configMAX_API_CALL_INTERRUPT_PRIORITY << portPRIORITY_SHIFT ); __asm volatile ( "dsb \n" "isb \n" ::: "memory" ); } portCPU_IRQ_ENABLE(); return ulReturn; } /*-----------------------------------------------------------*/ #if( configASSERT_DEFINED == 1 ) void vPortValidateInterruptPriority( void ) { /* The following assertion will fail if a service routine (ISR) for an interrupt that has been assigned a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API function. ISR safe FreeRTOS API functions must *only* be called from interrupts that have been assigned a priority at or below configMAX_SYSCALL_INTERRUPT_PRIORITY. Numerically low interrupt priority numbers represent logically high interrupt priorities, therefore the priority of the interrupt must be set to a value equal to or numerically *higher* than configMAX_SYSCALL_INTERRUPT_PRIORITY. FreeRTOS maintains separate thread and ISR API functions to ensure interrupt entry is as fast and simple as possible. */ configASSERT( portICCRPR_RUNNING_PRIORITY_REGISTER >= ( uint32_t ) ( configMAX_API_CALL_INTERRUPT_PRIORITY << portPRIORITY_SHIFT ) ); /* Priority grouping: The interrupt controller (GIC) allows the bits that define each interrupt's priority to be split between bits that define the interrupt's pre-emption priority bits and bits that define the interrupt's sub-priority. For simplicity all bits must be defined to be pre-emption priority bits. The following assertion will fail if this is not the case (if some bits represent a sub-priority). The priority grouping is configured by the GIC's binary point register (ICCBPR). Writing 0 to ICCBPR will ensure it is set to its lowest possible value (which may be above 0). */ configASSERT( ( portICCBPR_BINARY_POINT_REGISTER & portBINARY_POINT_BITS ) <= portMAX_BINARY_POINT_VALUE ); } #endif /* configASSERT_DEFINED */ /*-----------------------------------------------------------*/ void vApplicationFPUSafeIRQHandler( uint32_t ulICCIAR ) { ( void ) ulICCIAR; configASSERT( ( volatile void * ) NULL ); } ================================================ FILE: src/rtos/portASM.S ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ .text .arm .set SYS_MODE, 0x1f .set SVC_MODE, 0x13 .set IRQ_MODE, 0x12 /* Hardware registers. */ .extern ulICCIAR .extern ulICCEOIR .extern ulICCPMR /* Variables and functions. */ .extern ulMaxAPIPriorityMask .extern _freertos_vector_table .extern pxCurrentTCB .extern vTaskSwitchContext .extern vApplicationIRQHandler .extern ulPortInterruptNesting .extern ulPortTaskHasFPUContext .global FreeRTOS_IRQ_Handler .global FreeRTOS_SWI_Handler .global vPortRestoreTaskContext .macro portSAVE_CONTEXT /* Save the LR and SPSR onto the system mode stack before switching to system mode to save the remaining system mode registers. */ SRSDB sp!, #SYS_MODE CPS #SYS_MODE PUSH {R0-R12, R14} /* Push the critical nesting count. */ LDR R2, ulCriticalNestingConst LDR R1, [R2] PUSH {R1} /* Does the task have a floating point context that needs saving? If ulPortTaskHasFPUContext is 0 then no. */ LDR R2, ulPortTaskHasFPUContextConst LDR R3, [R2] CMP R3, #0 /* Save the floating point context, if any. */ FMRXNE R1, FPSCR VPUSHNE {D0-D15} VPUSHNE {D16-D31} PUSHNE {R1} /* Save ulPortTaskHasFPUContext itself. */ PUSH {R3} /* Save the stack pointer in the TCB. */ LDR R0, pxCurrentTCBConst LDR R1, [R0] STR SP, [R1] .endm ; /**********************************************************************/ .macro portRESTORE_CONTEXT /* Set the SP to point to the stack of the task being restored. */ LDR R0, pxCurrentTCBConst LDR R1, [R0] LDR SP, [R1] /* Is there a floating point context to restore? If the restored ulPortTaskHasFPUContext is zero then no. */ LDR R0, ulPortTaskHasFPUContextConst POP {R1} STR R1, [R0] CMP R1, #0 /* Restore the floating point context, if any. */ POPNE {R0} VPOPNE {D16-D31} VPOPNE {D0-D15} VMSRNE FPSCR, R0 /* Restore the critical section nesting depth. */ LDR R0, ulCriticalNestingConst POP {R1} STR R1, [R0] /* Ensure the priority mask is correct for the critical nesting depth. */ LDR R2, ulICCPMRConst LDR R2, [R2] CMP R1, #0 MOVEQ R4, #255 LDRNE R4, ulMaxAPIPriorityMaskConst LDRNE R4, [R4] STR R4, [R2] /* Restore all system mode registers other than the SP (which is already being used). */ POP {R0-R12, R14} /* Return to the task code, loading CPSR on the way. */ RFEIA sp! .endm /****************************************************************************** * SVC handler is used to start the scheduler. *****************************************************************************/ .align 4 .type FreeRTOS_SWI_Handler, %function FreeRTOS_SWI_Handler: /* Save the context of the current task and select a new task to run. */ portSAVE_CONTEXT LDR R0, vTaskSwitchContextConst BLX R0 portRESTORE_CONTEXT /****************************************************************************** * vPortRestoreTaskContext is used to start the scheduler. *****************************************************************************/ .type vPortRestoreTaskContext, %function vPortRestoreTaskContext: /* Switch to system mode. */ CPS #SYS_MODE portRESTORE_CONTEXT .align 4 .type FreeRTOS_IRQ_Handler, %function FreeRTOS_IRQ_Handler: /* Return to the interrupted instruction. */ SUB lr, lr, #4 /* Push the return address and SPSR. */ PUSH {lr} MRS lr, SPSR PUSH {lr} /* Change to supervisor mode to allow reentry. */ CPS #SVC_MODE /* Push used registers. */ PUSH {r0-r4, r12} /* Increment nesting count. r3 holds the address of ulPortInterruptNesting for future use. r1 holds the original ulPortInterruptNesting value for future use. */ LDR r3, ulPortInterruptNestingConst LDR r1, [r3] ADD r4, r1, #1 STR r4, [r3] /* Read value from the interrupt acknowledge register, which is stored in r0 for future parameter and interrupt clearing use. */ LDR r2, ulICCIARConst LDR r2, [r2] LDR r0, [r2] /* Ensure bit 2 of the stack pointer is clear. r2 holds the bit 2 value for future use. _RB_ Does this ever actually need to be done provided the start of the stack is 8-byte aligned? */ MOV r2, sp AND r2, r2, #4 SUB sp, sp, r2 /* Call the interrupt handler. r4 pushed to maintain alignment. */ PUSH {r0-r4, lr} LDR r1, vApplicationIRQHandlerConst BLX r1 POP {r0-r4, lr} ADD sp, sp, r2 CPSID i DSB ISB /* Write the value read from ICCIAR to ICCEOIR. */ LDR r4, ulICCEOIRConst LDR r4, [r4] STR r0, [r4] /* Restore the old nesting count. */ STR r1, [r3] /* A context switch is never performed if the nesting count is not 0. */ CMP r1, #0 BNE exit_without_switch /* Did the interrupt request a context switch? r1 holds the address of ulPortYieldRequired and r0 the value of ulPortYieldRequired for future use. */ LDR r1, =ulPortYieldRequired LDR r0, [r1] CMP r0, #0 BNE switch_before_exit exit_without_switch: /* No context switch. Restore used registers, LR_irq and SPSR before returning. */ POP {r0-r4, r12} CPS #IRQ_MODE POP {LR} MSR SPSR_cxsf, LR POP {LR} MOVS PC, LR switch_before_exit: /* A context swtich is to be performed. Clear the context switch pending flag. */ MOV r0, #0 STR r0, [r1] /* Restore used registers, LR-irq and SPSR before saving the context to the task stack. */ POP {r0-r4, r12} CPS #IRQ_MODE POP {LR} MSR SPSR_cxsf, LR POP {LR} portSAVE_CONTEXT /* Call the function that selects the new task to execute. vTaskSwitchContext() if vTaskSwitchContext() uses LDRD or STRD instructions, or 8 byte aligned stack allocated data. LR does not need saving as a new LR will be loaded by portRESTORE_CONTEXT anyway. */ LDR R0, vTaskSwitchContextConst BLX R0 /* Restore the context of, and branch to, the task selected to execute next. */ portRESTORE_CONTEXT /****************************************************************************** * If the application provides an implementation of vApplicationIRQHandler(), * then it will get called directly without saving the FPU registers on * interrupt entry, and this weak implementation of * vApplicationIRQHandler() will not get called. * * If the application provides its own implementation of * vApplicationFPUSafeIRQHandler() then this implementation of * vApplicationIRQHandler() will be called, save the FPU registers, and then * call vApplicationFPUSafeIRQHandler(). * * Therefore, if the application writer wants FPU registers to be saved on * interrupt entry their IRQ handler must be called * vApplicationFPUSafeIRQHandler(), and if the application writer does not want * FPU registers to be saved on interrupt entry their IRQ handler must be * called vApplicationIRQHandler(). *****************************************************************************/ .align 4 .weak vApplicationIRQHandler .type vApplicationIRQHandler, %function vApplicationIRQHandler: PUSH {LR} FMRX R1, FPSCR VPUSH {D0-D15} VPUSH {D16-D31} PUSH {R1} LDR r1, vApplicationFPUSafeIRQHandlerConst BLX r1 POP {R0} VPOP {D16-D31} VPOP {D0-D15} VMSR FPSCR, R0 POP {PC} ulICCIARConst: .word ulICCIAR ulICCEOIRConst: .word ulICCEOIR ulICCPMRConst: .word ulICCPMR pxCurrentTCBConst: .word pxCurrentTCB ulCriticalNestingConst: .word ulCriticalNesting ulPortTaskHasFPUContextConst: .word ulPortTaskHasFPUContext ulMaxAPIPriorityMaskConst: .word ulMaxAPIPriorityMask vTaskSwitchContextConst: .word vTaskSwitchContext vApplicationIRQHandlerConst: .word vApplicationIRQHandler ulPortInterruptNestingConst: .word ulPortInterruptNesting vApplicationFPUSafeIRQHandlerConst: .word vApplicationFPUSafeIRQHandler .end ================================================ FILE: src/rtos/portmacro.h ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef PORTMACRO_H #define PORTMACRO_H #ifdef __cplusplus extern "C" { #endif /*----------------------------------------------------------- * Port specific definitions. * * The settings in this file configure FreeRTOS correctly for the given hardware * and compiler. * * These settings should not be altered. *----------------------------------------------------------- */ /* Type definitions. */ #define portCHAR char #define portFLOAT float #define portDOUBLE double #define portLONG long #define portSHORT short #define portSTACK_TYPE uint32_t #define portBASE_TYPE long typedef portSTACK_TYPE task_stack_t; typedef long int32_t; typedef unsigned long uint32_t; typedef uint32_t uint32_t; #define portMAX_DELAY ( uint32_t ) 0xffffffffUL /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do not need to be guarded with a critical section. */ #define portTICK_TYPE_IS_ATOMIC 1 /*-----------------------------------------------------------*/ /* Hardware specifics. */ #define portSTACK_GROWTH ( -1 ) #define portTICK_PERIOD_MS ( ( uint32_t ) 1000 / configTICK_RATE_HZ ) #define portBYTE_ALIGNMENT 8 /*-----------------------------------------------------------*/ /* Task utilities. */ /* Called at the end of an ISR that can cause a context switch. */ #define portEND_SWITCHING_ISR( xSwitchRequired )\ { \ extern uint32_t ulPortYieldRequired; \ \ if( xSwitchRequired != pdFALSE ) \ { \ ulPortYieldRequired = pdTRUE; \ } \ } #define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) #define portYIELD() __asm volatile ( "SWI 0" ::: "memory" ); /*----------------------------------------------------------- * Critical section control *----------------------------------------------------------*/ extern void vPortEnterCritical( void ); extern void vPortExitCritical( void ); extern uint32_t ulPortSetInterruptMask( void ); extern void vPortClearInterruptMask( uint32_t ulNewMaskValue ); extern void vPortInstallFreeRTOSVectorTable( void ); /* These macros do not globally disable/enable interrupts. They do mask off interrupts that have a priority below configMAX_API_CALL_INTERRUPT_PRIORITY. */ #define portENTER_CRITICAL() vPortEnterCritical(); #define portEXIT_CRITICAL() vPortExitCritical(); #define portDISABLE_INTERRUPTS() ulPortSetInterruptMask() #define portENABLE_INTERRUPTS() vPortClearInterruptMask( 0 ) #define portSET_INTERRUPT_MASK_FROM_ISR() ulPortSetInterruptMask() #define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortClearInterruptMask(x) /*-----------------------------------------------------------*/ /* Task function macros as described on the FreeRTOS.org WEB site. These are not required for this port but included in case common demo code that uses these macros is used. */ #define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) #define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) /* Prototype of the FreeRTOS tick handler. This must be installed as the handler for whichever peripheral is used to generate the RTOS tick. */ void FreeRTOS_Tick_Handler( void ); /* If configUSE_TASK_FPU_SUPPORT is set to 1 (or left undefined) then tasks are created without an FPU context and must call vPortTaskUsesFPU() to give themselves an FPU context before using any FPU instructions. If configUSE_TASK_FPU_SUPPORT is set to 2 then all tasks will have an FPU context by default. */ #if( configUSE_TASK_FPU_SUPPORT != 2 ) void vPortTaskUsesFPU( void ); #else /* Each task has an FPU context already, so define this function away to nothing to prevent it being called accidentally. */ #define vPortTaskUsesFPU() #endif #define portTASK_USES_FLOATING_POINT() vPortTaskUsesFPU() #define portLOWEST_INTERRUPT_PRIORITY ( ( ( uint32_t ) configUNIQUE_INTERRUPT_PRIORITIES ) - 1UL ) #define portLOWEST_USABLE_INTERRUPT_PRIORITY ( portLOWEST_INTERRUPT_PRIORITY - 1UL ) /* Architecture specific optimisations. */ #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 #endif #if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 /* Store/clear the ready priorities in a bit map. */ #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) /*-----------------------------------------------------------*/ #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - ( uint32_t ) __builtin_clz( uxReadyPriorities ) ) #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ #ifdef configASSERT void vPortValidateInterruptPriority( void ); #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority() #endif /* configASSERT */ #define portNOP() __asm volatile( "NOP" ) #define portINLINE __inline #ifdef __cplusplus } /* extern C */ #endif /* The number of bits to shift for an interrupt priority is dependent on the number of bits implemented by the interrupt controller. */ #if configUNIQUE_INTERRUPT_PRIORITIES == 16 #define portPRIORITY_SHIFT 4 #define portMAX_BINARY_POINT_VALUE 3 #elif configUNIQUE_INTERRUPT_PRIORITIES == 32 #define portPRIORITY_SHIFT 3 #define portMAX_BINARY_POINT_VALUE 2 #elif configUNIQUE_INTERRUPT_PRIORITIES == 64 #define portPRIORITY_SHIFT 2 #define portMAX_BINARY_POINT_VALUE 1 #elif configUNIQUE_INTERRUPT_PRIORITIES == 128 #define portPRIORITY_SHIFT 1 #define portMAX_BINARY_POINT_VALUE 0 #elif configUNIQUE_INTERRUPT_PRIORITIES == 256 #define portPRIORITY_SHIFT 0 #define portMAX_BINARY_POINT_VALUE 0 #else #error Invalid configUNIQUE_INTERRUPT_PRIORITIES setting. configUNIQUE_INTERRUPT_PRIORITIES must be set to the number of unique priorities implemented by the target hardware #endif /* Interrupt controller access addresses. */ #define portICCPMR_PRIORITY_MASK_OFFSET ( 0x04 ) #define portICCIAR_INTERRUPT_ACKNOWLEDGE_OFFSET ( 0x0C ) #define portICCEOIR_END_OF_INTERRUPT_OFFSET ( 0x10 ) #define portICCBPR_BINARY_POINT_OFFSET ( 0x08 ) #define portICCRPR_RUNNING_PRIORITY_OFFSET ( 0x14 ) #define portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS ( configINTERRUPT_CONTROLLER_BASE_ADDRESS + configINTERRUPT_CONTROLLER_CPU_INTERFACE_OFFSET ) #define portICCPMR_PRIORITY_MASK_REGISTER ( *( ( volatile uint32_t * ) ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCPMR_PRIORITY_MASK_OFFSET ) ) ) #define portICCIAR_INTERRUPT_ACKNOWLEDGE_REGISTER_ADDRESS ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCIAR_INTERRUPT_ACKNOWLEDGE_OFFSET ) #define portICCEOIR_END_OF_INTERRUPT_REGISTER_ADDRESS ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCEOIR_END_OF_INTERRUPT_OFFSET ) #define portICCPMR_PRIORITY_MASK_REGISTER_ADDRESS ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCPMR_PRIORITY_MASK_OFFSET ) #define portICCBPR_BINARY_POINT_REGISTER ( *( ( const volatile uint32_t * ) ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCBPR_BINARY_POINT_OFFSET ) ) ) #define portICCRPR_RUNNING_PRIORITY_REGISTER ( *( ( const volatile uint32_t * ) ( portINTERRUPT_CONTROLLER_CPU_INTERFACE_ADDRESS + portICCRPR_RUNNING_PRIORITY_OFFSET ) ) ) #endif /* PORTMACRO_H */ ================================================ FILE: src/rtos/queue.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include #include #include "FreeRTOS.h" #include "task.h" #include "queue.h" /* Constants used with the cRxLock and cTxLock structure members. */ #define queueUNLOCKED ( ( int8_t ) -1 ) #define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) /* When the Queue_t structure is used to represent a base queue its pcHead and pcTail members are used as pointers into the queue storage area. When the Queue_t structure is used to represent a mutex pcHead and pcTail pointers are not necessary, and the pcHead pointer is set to NULL to indicate that the pcTail pointer actually points to the mutex holder (if any). Map alternative names to the pcHead and pcTail structure members to ensure the readability of the code is maintained despite this dual use of two structure members. An alternative implementation would be to use a union, but use of a union is against the coding standard (although an exception to the standard has been permitted where the dual use also significantly changes the type of the structure member). */ #define pxMutexHolder pcTail #define uxQueueType pcHead #define queueQUEUE_IS_MUTEX NULL /* Semaphores do not actually store or copy data, so have an item size of zero. */ #define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint32_t ) 0 ) #define queueMUTEX_GIVE_BLOCK_TIME ( ( uint32_t ) 0U ) #if( configUSE_PREEMPTION == 0 ) /* If the cooperative scheduler is being used then a yield should not be performed just because a higher priority task has been woken. */ #define queueYIELD_IF_USING_PREEMPTION() #else #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() #endif /* * Definition of the queue used by the scheduler. * Items are queued by copy, not reference. See the following link for the * rationale: http://www.freertos.org/Embedded-RTOS-Queues.html */ typedef struct QueueDefinition { int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ union /* Use of a union is an exception to the coding standard to ensure two mutually exclusive structure members don't appear simultaneously (wasting RAM). */ { int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ uint32_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ } u; List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ volatile uint32_t uxMessagesWaiting;/*< The number of items currently in the queue. */ uint32_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ uint32_t uxItemSize; /*< The size of each items that the queue will hold. */ volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ #endif #if ( configUSE_QUEUE_SETS == 1 ) struct QueueDefinition *pxQueueSetContainer; #endif #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxQueueNumber; uint8_t ucQueueType; #endif } xQUEUE; /* The old xQUEUE name is maintained above then typedefed to the new Queue_t name below to enable the use of older kernel aware debuggers. */ typedef xQUEUE Queue_t; /*-----------------------------------------------------------*/ /* * The queue registry is just a means for kernel aware debuggers to locate * queue structures. It has no other purpose so is an optional component. */ #if ( configQUEUE_REGISTRY_SIZE > 0 ) /* The type stored within the queue registry array. This allows a name to be assigned to each queue making kernel aware debugging a little more user friendly. */ typedef struct QUEUE_REGISTRY_ITEM { const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ queue_t xHandle; } xQueueRegistryItem; /* The old xQueueRegistryItem name is maintained above then typedefed to the new xQueueRegistryItem name below to enable the use of older kernel aware debuggers. */ typedef xQueueRegistryItem QueueRegistryItem_t; /* The queue registry is simply an array of QueueRegistryItem_t structures. The pcQueueName member of a structure being NULL is indicative of the array position being vacant. */ QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; #endif /* configQUEUE_REGISTRY_SIZE */ /* * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not * prevent an ISR from adding or removing items to the queue, but does prevent * an ISR from removing tasks from the queue event lists. If an ISR finds a * queue is locked it will instead increment the appropriate queue lock count * to indicate that a task may require unblocking. When the queue in unlocked * these lock counts are inspected, and the appropriate action taken. */ static void prvUnlockQueue( Queue_t * const pxQueue ) ; /* * Uses a critical section to determine if there is any data in a queue. * * @return pdTRUE if the queue contains no items, otherwise pdFALSE. */ static int32_t prvIsQueueEmpty( const Queue_t *pxQueue ) ; /* * Uses a critical section to determine if there is any space in a queue. * * @return pdTRUE if there is no space, otherwise pdFALSE; */ static int32_t prvIsQueueFull( const Queue_t *pxQueue ) ; /* * Copies an item into the queue, either at the front of the queue or the * back of the queue. */ static int32_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const int32_t xPosition ) ; /* * Copies an item out of a queue. */ static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const buffer ) ; #if ( configUSE_QUEUE_SETS == 1 ) /* * Checks to see if a queue is a member of a queue set, and if so, notifies * the queue set that the queue contains data. */ static int32_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const int32_t xCopyPosition ) ; #endif /* * Called after a Queue_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ static void prvInitialiseNewQueue( const uint32_t uxQueueLength, const uint32_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) ; /* * Mutexes are a special type of queue. When a mutex is created, first the * queue is created, then prvInitialiseMutex() is called to configure the queue * as a mutex. */ #if( configUSE_MUTEXES == 1 ) static void prvInitialiseMutex( Queue_t *pxNewQueue ) ; #endif #if( configUSE_MUTEXES == 1 ) /* * If a task waiting for a mutex causes the mutex holder to inherit a * priority, but the waiting task times out, then the holder should * disinherit the priority - but only down to the highest priority of any * other tasks that are waiting for the same mutex. This function returns * that priority. */ static uint32_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) ; #endif /*-----------------------------------------------------------*/ /* * Macro to mark a queue as locked. Locking a queue prevents an ISR from * accessing the queue event lists. */ #define prvLockQueue( pxQueue ) \ taskENTER_CRITICAL(); \ { \ if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ { \ ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ } \ if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ { \ ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ } \ } \ taskEXIT_CRITICAL() /*-----------------------------------------------------------*/ int32_t xQueueGenericReset( queue_t xQueue, int32_t xNewQueue ) { Queue_t * const pxQueue = ( Queue_t * ) xQueue; configASSERT( pxQueue ); taskENTER_CRITICAL(); { pxQueue->pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); pxQueue->uxMessagesWaiting = ( uint32_t ) 0U; pxQueue->pcWriteTo = pxQueue->pcHead; pxQueue->u.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - ( uint32_t ) 1U ) * pxQueue->uxItemSize ); pxQueue->cRxLock = queueUNLOCKED; pxQueue->cTxLock = queueUNLOCKED; if( xNewQueue == pdFALSE ) { /* If there are tasks blocked waiting to read from the queue, then the tasks will remain blocked as after this function exits the queue will still be empty. If there are tasks blocked waiting to write to the queue, then one should be unblocked as after this function exits it will be possible to write to it. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { /* Ensure the event queues start in the correct state. */ vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); } } taskEXIT_CRITICAL(); /* A value is returned for calling semantic consistency with previous versions. */ return pdPASS; } /*-----------------------------------------------------------*/ /** Generic Reset "Macros" **/ void queue_reset(queue_t queue) { xQueueGenericReset(queue, pdFALSE); } #if( configSUPPORT_STATIC_ALLOCATION == 1 ) queue_t xQueueGenericCreateStatic( const uint32_t uxQueueLength, const uint32_t uxItemSize, uint8_t *pucQueueStorage, static_queue_s_t *pxStaticQueue, const uint8_t ucQueueType ) { Queue_t *pxNewQueue; configASSERT( uxQueueLength > ( uint32_t ) 0 ); /* The static_queue_s_t structure and the queue storage area must be supplied. */ configASSERT( pxStaticQueue != NULL ); /* A queue storage area should be provided if the item size is not 0, and should not be provided if the item size is 0. */ configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); #if( configASSERT_DEFINED == 1 ) { /* Sanity check that the size of the structure used to declare a variable of type static_queue_s_t or static_sem_s_t equals the size of the real queue and semaphore structures. */ volatile size_t xSize = sizeof( static_queue_s_t ); configASSERT( xSize == sizeof( Queue_t ) ); } #endif /* configASSERT_DEFINED */ /* The address of a statically allocated queue was passed in, use it. The address of a statically allocated storage area was also passed in but is already set. */ pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ if( pxNewQueue != NULL ) { #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) { /* Queues can be allocated wither statically or dynamically, so note this queue was allocated statically in case the queue is later deleted. */ pxNewQueue->ucStaticallyAllocated = pdTRUE; } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); } else { traceQUEUE_CREATE_FAILED( ucQueueType ); } return pxNewQueue; } queue_t queue_create_static(uint32_t uxQueueLength, uint32_t uxItemSize, uint8_t* pucQueueStorage, static_queue_s_t* pxQueueBuffer) { return xQueueGenericCreateStatic(uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer, queueQUEUE_TYPE_BASE); } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) queue_t xQueueGenericCreate( const uint32_t uxQueueLength, const uint32_t uxItemSize, const uint8_t ucQueueType ) { Queue_t *pxNewQueue; size_t xQueueSizeInBytes; uint8_t *pucQueueStorage; configASSERT( uxQueueLength > ( uint32_t ) 0 ); if( uxItemSize == ( uint32_t ) 0 ) { /* There is not going to be a queue storage area. */ xQueueSizeInBytes = ( size_t ) 0; } else { /* Allocate enough space to hold the maximum number of items that can be in the queue at any time. */ xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ } pxNewQueue = ( Queue_t * ) kmalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); if( pxNewQueue != NULL ) { /* Jump past the queue structure to find the location of the queue storage area. */ pucQueueStorage = ( ( uint8_t * ) pxNewQueue ) + sizeof( Queue_t ); #if( configSUPPORT_STATIC_ALLOCATION == 1 ) { /* Queues can be created either statically or dynamically, so note this task was created dynamically in case it is later deleted. */ pxNewQueue->ucStaticallyAllocated = pdFALSE; } #endif /* configSUPPORT_STATIC_ALLOCATION */ prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); } else { traceQUEUE_CREATE_FAILED( ucQueueType ); errno = ENOMEM; } return pxNewQueue; } queue_t queue_create(uint32_t length, uint32_t item_size) { return xQueueGenericCreate((length), (item_size), (queueQUEUE_TYPE_BASE)); } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ static void prvInitialiseNewQueue( const uint32_t uxQueueLength, const uint32_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) { /* Remove compiler warnings about unused parameters should configUSE_TRACE_FACILITY not be set to 1. */ ( void ) ucQueueType; if( uxItemSize == ( uint32_t ) 0 ) { /* No RAM was allocated for the queue storage area, but PC head cannot be set to NULL because NULL is used as a key to say the queue is used as a mutex. Therefore just set pcHead to point to the queue as a benign value that is known to be within the memory map. */ pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; } else { /* Set the head to the start of the queue storage area. */ pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; } /* Initialise the queue members as described where the queue type is defined. */ pxNewQueue->uxLength = uxQueueLength; pxNewQueue->uxItemSize = uxItemSize; ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); #if ( configUSE_TRACE_FACILITY == 1 ) { pxNewQueue->ucQueueType = ucQueueType; } #endif /* configUSE_TRACE_FACILITY */ #if( configUSE_QUEUE_SETS == 1 ) { pxNewQueue->pxQueueSetContainer = NULL; } #endif /* configUSE_QUEUE_SETS */ traceQUEUE_CREATE( pxNewQueue ); } /*-----------------------------------------------------------*/ #if( configUSE_MUTEXES == 1 ) static void prvInitialiseMutex( Queue_t *pxNewQueue ) { if( pxNewQueue != NULL ) { /* The queue create function will set all the queue structure members correctly for a generic queue, but this function is creating a mutex. Overwrite those members that need to be set differently - in particular the information required for priority inheritance. */ pxNewQueue->pxMutexHolder = NULL; pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; /* In case this is a recursive mutex. */ pxNewQueue->u.uxRecursiveCallCount = 0; traceCREATE_MUTEX( pxNewQueue ); /* Start with the semaphore in the expected state. */ ( void ) xQueueGenericSend( pxNewQueue, NULL, ( uint32_t ) 0U, queueSEND_TO_BACK ); } else { traceCREATE_MUTEX_FAILED(); } } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) queue_t xQueueCreateMutex( const uint8_t ucQueueType ) { Queue_t *pxNewQueue; const uint32_t uxMutexLength = ( uint32_t ) 1, uxMutexSize = ( uint32_t ) 0; pxNewQueue = ( Queue_t * ) xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); prvInitialiseMutex( pxNewQueue ); return pxNewQueue; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) queue_t xQueueCreateMutexStatic( const uint8_t ucQueueType, static_queue_s_t *pxStaticQueue ) { Queue_t *pxNewQueue; const uint32_t uxMutexLength = ( uint32_t ) 1, uxMutexSize = ( uint32_t ) 0; /* Prevent compiler warnings about unused parameters if configUSE_TRACE_FACILITY does not equal 1. */ ( void ) ucQueueType; pxNewQueue = ( Queue_t * ) xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); prvInitialiseMutex( pxNewQueue ); return pxNewQueue; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) void* xQueueGetMutexHolder( queue_t xSemaphore ) { void *pxReturn; /* This function is called by mutex_get_owner(), and should not be called directly. Note: This is a good way of determining if the calling task is the mutex holder, but not a good way of determining the identity of the mutex holder, as the holder may change between the following critical section exiting and the function returning. */ taskENTER_CRITICAL(); { if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) { pxReturn = ( void * ) ( ( Queue_t * ) xSemaphore )->pxMutexHolder; } else { pxReturn = NULL; } } taskEXIT_CRITICAL(); return pxReturn; } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ #endif /*-----------------------------------------------------------*/ #if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) void* xQueueGetMutexHolderFromISR( queue_t xSemaphore ) { void *pxReturn; configASSERT( xSemaphore ); /* Mutexes cannot be used in interrupt service routines, so the mutex holder should not change in an ISR, and therefore a critical section is not required here. */ if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) { pxReturn = ( void * ) ( ( Queue_t * ) xSemaphore )->pxMutexHolder; } else { pxReturn = NULL; } return pxReturn; } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ #endif /*-----------------------------------------------------------*/ #if ( configUSE_RECURSIVE_MUTEXES == 1 ) int32_t xQueueGiveMutexRecursive( queue_t xMutex ) { int32_t xReturn; Queue_t * const pxMutex = ( Queue_t * ) xMutex; configASSERT( pxMutex ); /* If this is the task that holds the mutex then pxMutexHolder will not change outside of this task. If this task does not hold the mutex then pxMutexHolder can never coincidentally equal the tasks handle, and as this is the only condition we are interested in it does not matter if pxMutexHolder is accessed simultaneously by another task. Therefore no mutual exclusion is required to test the pxMutexHolder variable. */ if( pxMutex->pxMutexHolder == ( void * ) task_get_current() ) /*lint !e961 Not a redundant cast as task_t is a typedef. */ { traceGIVE_MUTEX_RECURSIVE( pxMutex ); /* uxRecursiveCallCount cannot be zero if pxMutexHolder is equal to the task handle, therefore no underflow check is required. Also, uxRecursiveCallCount is only modified by the mutex holder, and as there can only be one, no mutual exclusion is required to modify the uxRecursiveCallCount member. */ ( pxMutex->u.uxRecursiveCallCount )--; /* Has the recursive call count unwound to 0? */ if( pxMutex->u.uxRecursiveCallCount == ( uint32_t ) 0 ) { /* Return the mutex. This will automatically unblock any other task that might be waiting to access the mutex. */ ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); } else { mtCOVERAGE_TEST_MARKER(); } xReturn = pdPASS; } else { /* The mutex cannot be given because the calling task is not the holder. */ xReturn = pdFAIL; traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); } return xReturn; } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_RECURSIVE_MUTEXES == 1 ) int32_t xQueueTakeMutexRecursive( queue_t xMutex, uint32_t timeout ) { int32_t xReturn; Queue_t * const pxMutex = ( Queue_t * ) xMutex; configASSERT( pxMutex ); /* Comments regarding mutual exclusion as per those within xQueueGiveMutexRecursive(). */ traceTAKE_MUTEX_RECURSIVE( pxMutex ); if( pxMutex->pxMutexHolder == ( void * ) task_get_current() ) /*lint !e961 Cast is not redundant as task_t is a typedef. */ { ( pxMutex->u.uxRecursiveCallCount )++; xReturn = pdPASS; } else { xReturn = xQueueSemaphoreTake( pxMutex, timeout ); /* pdPASS will only be returned if the mutex was successfully obtained. The calling task may have entered the Blocked state before reaching here. */ if( xReturn != pdFAIL ) { ( pxMutex->u.uxRecursiveCallCount )++; } else { traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); } } return xReturn; } #endif /* configUSE_RECURSIVE_MUTEXES */ /*-----------------------------------------------------------*/ #if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) queue_t xQueueCreateCountingSemaphoreStatic( const uint32_t uxMaxCount, const uint32_t uxInitialCount, static_queue_s_t *pxStaticQueue ) { queue_t xHandle; configASSERT( uxMaxCount != 0 ); configASSERT( uxInitialCount <= uxMaxCount ); xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); if( xHandle != NULL ) { ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; traceCREATE_COUNTING_SEMAPHORE(); } else { traceCREATE_COUNTING_SEMAPHORE_FAILED(); } return xHandle; } #endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ #if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) queue_t xQueueCreateCountingSemaphore( const uint32_t uxMaxCount, const uint32_t uxInitialCount ) { queue_t xHandle; configASSERT( uxMaxCount != 0 ); configASSERT( uxInitialCount <= uxMaxCount ); xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); if( xHandle != NULL ) { ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; traceCREATE_COUNTING_SEMAPHORE(); } else { traceCREATE_COUNTING_SEMAPHORE_FAILED(); } return xHandle; } #endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ int32_t xQueueGenericSend( queue_t xQueue, const void * const pvItemToQueue, uint32_t timeout, const int32_t xCopyPosition ) { int32_t xEntryTimeSet = pdFALSE, xYieldRequired; TimeOut_t xTimeOut; Queue_t * const pxQueue = ( Queue_t * ) xQueue; configASSERT( pxQueue ); configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( uint32_t ) 0U ) ) ); configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) { configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( timeout != 0 ) ) ); } #endif /* This function relaxes the coding standard somewhat to allow return statements within the function itself. This is done in the interest of execution time efficiency. */ for( ;; ) { taskENTER_CRITICAL(); { /* Is there room on the queue now? The running task must be the highest priority task wanting to access the queue. If the head item in the queue is to be overwritten then it does not matter if the queue is full. */ if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) { traceQUEUE_SEND( pxQueue ); xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); #if ( configUSE_QUEUE_SETS == 1 ) { if( pxQueue->pxQueueSetContainer != NULL ) { if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) { /* The queue is a member of a queue set, and posting to the queue set caused a higher priority task to unblock. A context switch is required. */ queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { /* If there was a task waiting for data to arrive on the queue then unblock it now. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The unblocked task has a priority higher than our own so yield immediately. Yes it is ok to do this from within the critical section - the kernel takes care of that. */ queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else if( xYieldRequired != pdFALSE ) { /* This path is a special case that will only get executed if the task was holding multiple mutexes and the mutexes were given back in an order that is different to that in which they were taken. */ queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } } #else /* configUSE_QUEUE_SETS */ { /* If there was a task waiting for data to arrive on the queue then unblock it now. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The unblocked task has a priority higher than our own so yield immediately. Yes it is ok to do this from within the critical section - the kernel takes care of that. */ queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else if( xYieldRequired != pdFALSE ) { /* This path is a special case that will only get executed if the task was holding multiple mutexes and the mutexes were given back in an order that is different to that in which they were taken. */ queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_QUEUE_SETS */ taskEXIT_CRITICAL(); return pdPASS; } else { if( timeout == ( uint32_t ) 0 ) { /* The queue was full and no block time is specified (or the block time has expired) so leave now. */ taskEXIT_CRITICAL(); /* Return to the original privilege level before exiting the function. */ traceQUEUE_SEND_FAILED( pxQueue ); errno = ENOSPC; return errQUEUE_FULL; } else if( xEntryTimeSet == pdFALSE ) { /* The queue was full and a block time was specified so configure the timeout structure. */ vTaskInternalSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } else { /* Entry time was already set. */ mtCOVERAGE_TEST_MARKER(); } } } taskEXIT_CRITICAL(); /* Interrupts and other tasks can send to and receive from the queue now the critical section has been exited. */ rtos_suspend_all(); prvLockQueue( pxQueue ); /* Update the timeout state to see if it has expired yet. */ if( xTaskCheckForTimeOut( &xTimeOut, &timeout ) == pdFALSE ) { if( prvIsQueueFull( pxQueue ) != pdFALSE ) { traceBLOCKING_ON_QUEUE_SEND( pxQueue ); vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), timeout ); /* Unlocking the queue means queue events can effect the event list. It is possible that interrupts occurring now remove this task from the event list again - but as the scheduler is suspended the task will go onto the pending ready last instead of the actual ready list. */ prvUnlockQueue( pxQueue ); /* Resuming the scheduler will move tasks from the pending ready list into the ready list - so it is feasible that this task is already in a ready list before it yields - in which case the yield will not cause a context switch unless there is also a higher priority task in the pending ready list. */ if( rtos_resume_all() == pdFALSE ) { portYIELD_WITHIN_API(); } } else { /* Try again. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); } } else { /* The timeout has expired. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); traceQUEUE_SEND_FAILED( pxQueue ); return errQUEUE_FULL; } } } /*-----------------------------------------------------------*/ /** Queue Generic Send "Macros" **/ bool queue_prepend(queue_t queue, const void* item, uint32_t timeout) { return xQueueGenericSend(queue, item, timeout, queueSEND_TO_FRONT); } bool queue_append(queue_t queue, const void* item, uint32_t timeout) { return xQueueGenericSend(queue, item, timeout, queueSEND_TO_BACK); } int32_t xQueueGenericSendFromISR( queue_t xQueue, const void * const pvItemToQueue, int32_t * const pxHigherPriorityTaskWoken, const int32_t xCopyPosition ) { int32_t xReturn; uint32_t uxSavedInterruptStatus; Queue_t * const pxQueue = ( Queue_t * ) xQueue; configASSERT( pxQueue ); configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( uint32_t ) 0U ) ) ); configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are kept permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); /* Similar to xQueueGenericSend, except without blocking if there is no room in the queue. Also don't directly wake a task that was blocked on a queue read, instead return a flag to say whether a context switch is required or not (i.e. has a task with a higher priority than us been woken by this post). */ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) { const int8_t cTxLock = pxQueue->cTxLock; traceQUEUE_SEND_FROM_ISR( pxQueue ); /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a semaphore or mutex. That means prvCopyDataToQueue() cannot result in a task disinheriting a priority and prvCopyDataToQueue() can be called here even though the disinherit function does not check if the scheduler is suspended before accessing the ready lists. */ ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); /* The event list is not altered if the queue is locked. This will be done when the queue is unlocked later. */ if( cTxLock == queueUNLOCKED ) { #if ( configUSE_QUEUE_SETS == 1 ) { if( pxQueue->pxQueueSetContainer != NULL ) { if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) != pdFALSE ) { /* The queue is a member of a queue set, and posting to the queue set caused a higher priority task to unblock. A context switch is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } } #else /* configUSE_QUEUE_SETS */ { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_QUEUE_SETS */ } else { /* Increment the lock count so the task that unlocks the queue knows that data was posted while it was locked. */ pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); } xReturn = pdPASS; } else { traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); xReturn = errQUEUE_FULL; } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ int32_t xQueueGiveFromISR( queue_t xQueue, int32_t * const pxHigherPriorityTaskWoken ) { int32_t xReturn; uint32_t uxSavedInterruptStatus; Queue_t * const pxQueue = ( Queue_t * ) xQueue; /* Similar to xQueueGenericSendFromISR() but used with semaphores where the item size is 0. Don't directly wake a task that was blocked on a queue read, instead return a flag to say whether a context switch is required or not (i.e. has a task with a higher priority than us been woken by this post). */ configASSERT( pxQueue ); /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() if the item size is not 0. */ configASSERT( pxQueue->uxItemSize == 0 ); /* Normally a mutex would not be given from an interrupt, especially if there is a mutex holder, as priority inheritance makes no sense for an interrupts, only tasks. */ configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->pxMutexHolder != NULL ) ) ); /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are kept permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { const uint32_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; /* When the queue is used to implement a semaphore no data is ever moved through the queue but it is still valid to see if the queue 'has space'. */ if( uxMessagesWaiting < pxQueue->uxLength ) { const int8_t cTxLock = pxQueue->cTxLock; traceQUEUE_SEND_FROM_ISR( pxQueue ); /* A task can only have an inherited priority if it is a mutex holder - and if there is a mutex holder then the mutex cannot be given from an ISR. As this is the ISR version of the function it can be assumed there is no mutex holder and no need to determine if priority disinheritance is needed. Simply increase the count of messages (semaphores) available. */ pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( uint32_t ) 1; /* The event list is not altered if the queue is locked. This will be done when the queue is unlocked later. */ if( cTxLock == queueUNLOCKED ) { #if ( configUSE_QUEUE_SETS == 1 ) { if( pxQueue->pxQueueSetContainer != NULL ) { if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) { /* The semaphore is a member of a queue set, and posting to the queue set caused a higher priority task to unblock. A context switch is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } } #else /* configUSE_QUEUE_SETS */ { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_QUEUE_SETS */ } else { /* Increment the lock count so the task that unlocks the queue knows that data was posted while it was locked. */ pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); } xReturn = pdPASS; } else { traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); xReturn = errQUEUE_FULL; } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ int32_t queue_recv(queue_t queue, void* const buffer, uint32_t timeout) { int32_t xEntryTimeSet = pdFALSE; TimeOut_t xTimeOut; Queue_t * const pxQueue = ( Queue_t * ) queue; /* Check the pointer is not NULL. */ configASSERT( ( pxQueue ) ); /* The buffer into which data is received can only be NULL if the data size is zero (so no data is copied into the buffer. */ configASSERT( !( ( ( buffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( uint32_t ) 0U ) ) ); /* Cannot block if the scheduler is suspended. */ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) { configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( timeout != 0 ) ) ); } #endif /* This function relaxes the coding standard somewhat to allow return statements within the function itself. This is done in the interest of execution time efficiency. */ for( ;; ) { taskENTER_CRITICAL(); { const uint32_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; /* Is there data in the queue now? To be running the calling task must be the highest priority task wanting to access the queue. */ if( uxMessagesWaiting > ( uint32_t ) 0 ) { /* Data available, remove one item. */ prvCopyDataFromQueue( pxQueue, buffer ); traceQUEUE_RECEIVE( pxQueue ); pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( uint32_t ) 1; /* There is now space in the queue, were any tasks waiting to post to the queue? If so, unblock the highest priority waiting task. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } taskEXIT_CRITICAL(); return pdPASS; } else { if( timeout == ( uint32_t ) 0 ) { /* The queue was empty and no block time is specified (or the block time has expired) so leave now. */ taskEXIT_CRITICAL(); traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } else if( xEntryTimeSet == pdFALSE ) { /* The queue was empty and a block time was specified so configure the timeout structure. */ vTaskInternalSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } else { /* Entry time was already set. */ mtCOVERAGE_TEST_MARKER(); } } } taskEXIT_CRITICAL(); /* Interrupts and other tasks can send to and receive from the queue now the critical section has been exited. */ rtos_suspend_all(); prvLockQueue( pxQueue ); /* Update the timeout state to see if it has expired yet. */ if( xTaskCheckForTimeOut( &xTimeOut, &timeout ) == pdFALSE ) { /* The timeout has not expired. If the queue is still empty place the task on the list of tasks waiting to receive from the queue. */ if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) { traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), timeout ); prvUnlockQueue( pxQueue ); if( rtos_resume_all() == pdFALSE ) { portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } else { /* The queue contains data again. Loop back to try and read the data. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); } } else { /* Timed out. If there is no data in the queue exit, otherwise loop back and attempt to read the data. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) { traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } else { mtCOVERAGE_TEST_MARKER(); } } } } /*-----------------------------------------------------------*/ int32_t xQueueSemaphoreTake( queue_t xQueue, uint32_t timeout ) { int32_t xEntryTimeSet = pdFALSE; TimeOut_t xTimeOut; Queue_t * const pxQueue = ( Queue_t * ) xQueue; #if( configUSE_MUTEXES == 1 ) int32_t xInheritanceOccurred = pdFALSE; #endif /* Check the queue pointer is not NULL. */ configASSERT( ( pxQueue ) ); /* Check this really is a semaphore, in which case the item size will be 0. */ configASSERT( pxQueue->uxItemSize == 0 ); /* Cannot block if the scheduler is suspended. */ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) { configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( timeout != 0 ) ) ); } #endif /* This function relaxes the coding standard somewhat to allow return statements within the function itself. This is done in the interest of execution time efficiency. */ for( ;; ) { taskENTER_CRITICAL(); { /* Semaphores are queues with an item size of 0, and where the number of messages in the queue is the semaphore's count value. */ const uint32_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; /* Is there data in the queue now? To be running the calling task must be the highest priority task wanting to access the queue. */ if( uxSemaphoreCount > ( uint32_t ) 0 ) { traceQUEUE_RECEIVE( pxQueue ); /* Semaphores are queues with a data size of zero and where the messages waiting is the semaphore's count. Reduce the count. */ pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( uint32_t ) 1; #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { /* Record the information required to implement priority inheritance should it become necessary. */ pxQueue->pxMutexHolder = ( int8_t * ) pvTaskIncrementMutexHeldCount(); /*lint !e961 Cast is not redundant as task_t is a typedef. */ } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_MUTEXES */ /* Check to see if other tasks are blocked waiting to give the semaphore, and if so, unblock the highest priority such task. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } taskEXIT_CRITICAL(); return pdPASS; } else { if( timeout == ( uint32_t ) 0 ) { /* For inheritance to have occurred there must have been an initial timeout, and an adjusted timeout cannot become 0, as if it were 0 the function would have exited. */ #if( configUSE_MUTEXES == 1 ) { configASSERT( xInheritanceOccurred == pdFALSE ); } #endif /* configUSE_MUTEXES */ /* The semaphore count was 0 and no block time is specified (or the block time has expired) so exit now. */ taskEXIT_CRITICAL(); traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } else if( xEntryTimeSet == pdFALSE ) { /* The semaphore count was 0 and a block time was specified so configure the timeout structure ready to block. */ vTaskInternalSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } else { /* Entry time was already set. */ mtCOVERAGE_TEST_MARKER(); } } } taskEXIT_CRITICAL(); /* Interrupts and other tasks can give to and take from the semaphore now the critical section has been exited. */ rtos_suspend_all(); prvLockQueue( pxQueue ); /* Update the timeout state to see if it has expired yet. */ if( xTaskCheckForTimeOut( &xTimeOut, &timeout ) == pdFALSE ) { /* A block time is specified and not expired. If the semaphore count is 0 then enter the Blocked state to wait for a semaphore to become available. As semaphores are implemented with queues the queue being empty is equivalent to the semaphore count being 0. */ if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) { traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { taskENTER_CRITICAL(); { xInheritanceOccurred = xTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder ); } taskEXIT_CRITICAL(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), timeout ); prvUnlockQueue( pxQueue ); if( rtos_resume_all() == pdFALSE ) { portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } else { /* There was no timeout and the semaphore count was not 0, so attempt to take the semaphore again. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); } } else { /* Timed out. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); /* If the semaphore count is 0 exit now as the timeout has expired. Otherwise return to attempt to take the semaphore that is known to be available. As semaphores are implemented by queues the queue being empty is equivalent to the semaphore count being 0. */ if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) { #if ( configUSE_MUTEXES == 1 ) { /* xInheritanceOccurred could only have be set if pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to test the mutex type again to check it is actually a mutex. */ if( xInheritanceOccurred != pdFALSE ) { taskENTER_CRITICAL(); { uint32_t uxHighestWaitingPriority; /* This task blocking on the mutex caused another task to inherit this task's priority. Now this task has timed out the priority should be disinherited again, but only as low as the next highest priority task that is waiting for the same mutex. */ uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); vTaskPriorityDisinheritAfterTimeout( ( void * ) pxQueue->pxMutexHolder, uxHighestWaitingPriority ); } taskEXIT_CRITICAL(); } } #endif /* configUSE_MUTEXES */ traceQUEUE_RECEIVE_FAILED( pxQueue ); return errQUEUE_EMPTY; } else { mtCOVERAGE_TEST_MARKER(); } } } } /*-----------------------------------------------------------*/ int32_t queue_peek(queue_t queue, void* const buffer, uint32_t timeout) { int32_t xEntryTimeSet = pdFALSE; TimeOut_t xTimeOut; int8_t *pcOriginalReadPosition; Queue_t * const pxQueue = ( Queue_t * ) queue; /* Check the pointer is not NULL. */ configASSERT( ( pxQueue ) ); /* The buffer into which data is received can only be NULL if the data size is zero (so no data is copied into the buffer. */ configASSERT( !( ( ( buffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( uint32_t ) 0U ) ) ); /* Cannot block if the scheduler is suspended. */ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) { configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( timeout != 0 ) ) ); } #endif /* This function relaxes the coding standard somewhat to allow return statements within the function itself. This is done in the interest of execution time efficiency. */ for( ;; ) { taskENTER_CRITICAL(); { const uint32_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; /* Is there data in the queue now? To be running the calling task must be the highest priority task wanting to access the queue. */ if( uxMessagesWaiting > ( uint32_t ) 0 ) { /* Remember the read position so it can be reset after the data is read from the queue as this function is only peeking the data, not removing it. */ pcOriginalReadPosition = pxQueue->u.pcReadFrom; prvCopyDataFromQueue( pxQueue, buffer ); traceQUEUE_PEEK( pxQueue ); /* The data is not being removed, so reset the read pointer. */ pxQueue->u.pcReadFrom = pcOriginalReadPosition; /* The data is being left in the queue, so see if there are any other tasks waiting for the data. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority than this task. */ queueYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } taskEXIT_CRITICAL(); return pdPASS; } else { if( timeout == ( uint32_t ) 0 ) { /* The queue was empty and no block time is specified (or the block time has expired) so leave now. */ taskEXIT_CRITICAL(); traceQUEUE_PEEK_FAILED( pxQueue ); return errQUEUE_EMPTY; } else if( xEntryTimeSet == pdFALSE ) { /* The queue was empty and a block time was specified so configure the timeout structure ready to enter the blocked state. */ vTaskInternalSetTimeOutState( &xTimeOut ); xEntryTimeSet = pdTRUE; } else { /* Entry time was already set. */ mtCOVERAGE_TEST_MARKER(); } } } taskEXIT_CRITICAL(); /* Interrupts and other tasks can send to and receive from the queue now the critical section has been exited. */ rtos_suspend_all(); prvLockQueue( pxQueue ); /* Update the timeout state to see if it has expired yet. */ if( xTaskCheckForTimeOut( &xTimeOut, &timeout ) == pdFALSE ) { /* Timeout has not expired yet, check to see if there is data in the queue now, and if not enter the Blocked state to wait for data. */ if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) { traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), timeout ); prvUnlockQueue( pxQueue ); if( rtos_resume_all() == pdFALSE ) { portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } else { /* There is data in the queue now, so don't enter the blocked state, instead return to try and obtain the data. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); } } else { /* The timeout has expired. If there is still no data in the queue exit, otherwise go back and try to read the data again. */ prvUnlockQueue( pxQueue ); ( void ) rtos_resume_all(); if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) { traceQUEUE_PEEK_FAILED( pxQueue ); return errQUEUE_EMPTY; } else { mtCOVERAGE_TEST_MARKER(); } } } } /*-----------------------------------------------------------*/ int32_t xQueueReceiveFromISR( queue_t xQueue, void * const buffer, int32_t * const pxHigherPriorityTaskWoken ) { int32_t xReturn; uint32_t uxSavedInterruptStatus; Queue_t * const pxQueue = ( Queue_t * ) xQueue; configASSERT( pxQueue ); configASSERT( !( ( buffer == NULL ) && ( pxQueue->uxItemSize != ( uint32_t ) 0U ) ) ); /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are kept permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { const uint32_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; /* Cannot block in an ISR, so check there is data available. */ if( uxMessagesWaiting > ( uint32_t ) 0 ) { const int8_t cRxLock = pxQueue->cRxLock; traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); prvCopyDataFromQueue( pxQueue, buffer ); pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( uint32_t ) 1; /* If the queue is locked the event list will not be modified. Instead update the lock count so the task that unlocks the queue will know that an ISR has removed data while the queue was locked. */ if( cRxLock == queueUNLOCKED ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { /* The task waiting has a higher priority than us so force a context switch. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { /* Increment the lock count so the task that unlocks the queue knows that data was removed while it was locked. */ pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); } xReturn = pdPASS; } else { xReturn = pdFAIL; traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ int32_t xQueuePeekFromISR( queue_t xQueue, void * const buffer ) { int32_t xReturn; uint32_t uxSavedInterruptStatus; int8_t *pcOriginalReadPosition; Queue_t * const pxQueue = ( Queue_t * ) xQueue; configASSERT( pxQueue ); configASSERT( !( ( buffer == NULL ) && ( pxQueue->uxItemSize != ( uint32_t ) 0U ) ) ); configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are kept permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { /* Cannot block in an ISR, so check there is data available. */ if( pxQueue->uxMessagesWaiting > ( uint32_t ) 0 ) { traceQUEUE_PEEK_FROM_ISR( pxQueue ); /* Remember the read position so it can be reset as nothing is actually being removed from the queue. */ pcOriginalReadPosition = pxQueue->u.pcReadFrom; prvCopyDataFromQueue( pxQueue, buffer ); pxQueue->u.pcReadFrom = pcOriginalReadPosition; xReturn = pdPASS; } else { xReturn = pdFAIL; traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ uint32_t queue_get_waiting(const queue_t queue) { uint32_t uxReturn; configASSERT( queue ); taskENTER_CRITICAL(); { uxReturn = ( ( Queue_t * ) queue )->uxMessagesWaiting; } taskEXIT_CRITICAL(); return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ uint32_t queue_get_available(const queue_t queue) { uint32_t uxReturn; Queue_t *pxQueue; pxQueue = ( Queue_t * ) queue; configASSERT( pxQueue ); taskENTER_CRITICAL(); { uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; } taskEXIT_CRITICAL(); return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ uint32_t uxQueueMessagesWaitingFromISR( const queue_t xQueue ) { uint32_t uxReturn; configASSERT( xQueue ); uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; return uxReturn; } /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ /*-----------------------------------------------------------*/ void queue_delete(queue_t queue) { Queue_t * const pxQueue = ( Queue_t * ) queue; configASSERT( pxQueue ); traceQUEUE_DELETE( pxQueue ); #if ( configQUEUE_REGISTRY_SIZE > 0 ) { vQueueUnregisterQueue( pxQueue ); } #endif #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) { /* The queue can only have been allocated dynamically - free it again. */ kfree( pxQueue ); } #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) { /* The queue could have been allocated statically or dynamically, so check before attempting to free the memory. */ if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) { kfree( pxQueue ); } else { mtCOVERAGE_TEST_MARKER(); } } #else { /* The queue must have been statically allocated, so is not going to be deleted. Avoid compiler warnings about the unused parameter. */ ( void ) pxQueue; } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxQueueGetQueueNumber( queue_t xQueue ) { return ( ( Queue_t * ) xQueue )->uxQueueNumber; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) void vQueueSetQueueNumber( queue_t xQueue, uint32_t uxQueueNumber ) { ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) uint8_t ucQueueGetQueueType( queue_t xQueue ) { return ( ( Queue_t * ) xQueue )->ucQueueType; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if( configUSE_MUTEXES == 1 ) static uint32_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) { uint32_t uxHighestPriorityOfWaitingTasks; /* If a task waiting for a mutex causes the mutex holder to inherit a priority, but the waiting task times out, then the holder should disinherit the priority - but only down to the highest priority of any other tasks that are waiting for the same mutex. For this purpose, return the priority of the highest priority task that is waiting for the mutex. */ if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0 ) { uxHighestPriorityOfWaitingTasks = configMAX_PRIORITIES - listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); } else { uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; } return uxHighestPriorityOfWaitingTasks; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ static int32_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const int32_t xPosition ) { int32_t xReturn = pdFALSE; uint32_t uxMessagesWaiting; /* This function is called from a critical section. */ uxMessagesWaiting = pxQueue->uxMessagesWaiting; if( pxQueue->uxItemSize == ( uint32_t ) 0 ) { #if ( configUSE_MUTEXES == 1 ) { if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) { /* The mutex is no longer being held. */ xReturn = xTaskPriorityDisinherit( ( void * ) pxQueue->pxMutexHolder ); pxQueue->pxMutexHolder = NULL; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_MUTEXES */ } else if( xPosition == queueSEND_TO_BACK ) { ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. */ pxQueue->pcWriteTo += pxQueue->uxItemSize; if( pxQueue->pcWriteTo >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ { pxQueue->pcWriteTo = pxQueue->pcHead; } else { mtCOVERAGE_TEST_MARKER(); } } else { ( void ) memcpy( ( void * ) pxQueue->u.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ pxQueue->u.pcReadFrom -= pxQueue->uxItemSize; if( pxQueue->u.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ { pxQueue->u.pcReadFrom = ( pxQueue->pcTail - pxQueue->uxItemSize ); } else { mtCOVERAGE_TEST_MARKER(); } if( xPosition == queueOVERWRITE ) { if( uxMessagesWaiting > ( uint32_t ) 0 ) { /* An item is not being added but overwritten, so subtract one from the recorded number of items in the queue so when one is added again below the number of recorded items remains correct. */ --uxMessagesWaiting; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( uint32_t ) 1; return xReturn; } /*-----------------------------------------------------------*/ static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const buffer ) { if( pxQueue->uxItemSize != ( uint32_t ) 0 ) { pxQueue->u.pcReadFrom += pxQueue->uxItemSize; if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ { pxQueue->u.pcReadFrom = pxQueue->pcHead; } else { mtCOVERAGE_TEST_MARKER(); } ( void ) memcpy( ( void * ) buffer, ( void * ) pxQueue->u.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. */ } } /*-----------------------------------------------------------*/ static void prvUnlockQueue( Queue_t * const pxQueue ) { /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ /* The lock counts contains the number of extra data items placed or removed from the queue while the queue was locked. When a queue is locked items can be added or removed, but the event lists cannot be updated. */ taskENTER_CRITICAL(); { int8_t cTxLock = pxQueue->cTxLock; /* See if data was added to the queue while it was locked. */ while( cTxLock > queueLOCKED_UNMODIFIED ) { /* Data was posted while the queue was locked. Are any tasks blocked waiting for data to become available? */ #if ( configUSE_QUEUE_SETS == 1 ) { if( pxQueue->pxQueueSetContainer != NULL ) { if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) != pdFALSE ) { /* The queue is a member of a queue set, and posting to the queue set caused a higher priority task to unblock. A context switch is required. */ vTaskMissedYield(); } else { mtCOVERAGE_TEST_MARKER(); } } else { /* Tasks that are removed from the event list will get added to the pending ready list as the scheduler is still suspended. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ vTaskMissedYield(); } else { mtCOVERAGE_TEST_MARKER(); } } else { break; } } } #else /* configUSE_QUEUE_SETS */ { /* Tasks that are removed from the event list will get added to the pending ready list as the scheduler is still suspended. */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority so record that a context switch is required. */ vTaskMissedYield(); } else { mtCOVERAGE_TEST_MARKER(); } } else { break; } } #endif /* configUSE_QUEUE_SETS */ --cTxLock; } pxQueue->cTxLock = queueUNLOCKED; } taskEXIT_CRITICAL(); /* Do the same for the Rx lock. */ taskENTER_CRITICAL(); { int8_t cRxLock = pxQueue->cRxLock; while( cRxLock > queueLOCKED_UNMODIFIED ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { vTaskMissedYield(); } else { mtCOVERAGE_TEST_MARKER(); } --cRxLock; } else { break; } } pxQueue->cRxLock = queueUNLOCKED; } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ static int32_t prvIsQueueEmpty( const Queue_t *pxQueue ) { int32_t xReturn; taskENTER_CRITICAL(); { if( pxQueue->uxMessagesWaiting == ( uint32_t ) 0 ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } } taskEXIT_CRITICAL(); return xReturn; } /*-----------------------------------------------------------*/ int32_t xQueueIsQueueEmptyFromISR( const queue_t xQueue ) { int32_t xReturn; configASSERT( xQueue ); if( ( ( Queue_t * ) xQueue )->uxMessagesWaiting == ( uint32_t ) 0 ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ /*-----------------------------------------------------------*/ static int32_t prvIsQueueFull( const Queue_t *pxQueue ) { int32_t xReturn; taskENTER_CRITICAL(); { if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } } taskEXIT_CRITICAL(); return xReturn; } /*-----------------------------------------------------------*/ int32_t xQueueIsQueueFullFromISR( const queue_t xQueue ) { int32_t xReturn; configASSERT( xQueue ); if( ( ( Queue_t * ) xQueue )->uxMessagesWaiting == ( ( Queue_t * ) xQueue )->uxLength ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) int32_t xQueueCRSend( queue_t xQueue, const void *pvItemToQueue, uint32_t timeout ) { int32_t xReturn; Queue_t * const pxQueue = ( Queue_t * ) xQueue; /* If the queue is already full we may have to block. A critical section is required to prevent an interrupt removing something from the queue between the check to see if the queue is full and blocking on the queue. */ portDISABLE_INTERRUPTS(); { if( prvIsQueueFull( pxQueue ) != pdFALSE ) { /* The queue is full - do we want to block or just leave without posting? */ if( timeout > ( uint32_t ) 0 ) { /* As this is called from a coroutine we cannot block directly, but return indicating that we need to block. */ vCoRoutineAddToDelayedList( timeout, &( pxQueue->xTasksWaitingToSend ) ); portENABLE_INTERRUPTS(); return errQUEUE_BLOCKED; } else { portENABLE_INTERRUPTS(); return errQUEUE_FULL; } } } portENABLE_INTERRUPTS(); portDISABLE_INTERRUPTS(); { if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { /* There is room in the queue, copy the data into the queue. */ prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); xReturn = pdPASS; /* Were any co-routines waiting for data to become available? */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { /* In this instance the co-routine could be placed directly into the ready list as we are within a critical section. Instead the same pending ready list mechanism is used as if the event were caused from within an interrupt. */ if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The co-routine waiting has a higher priority so record that a yield might be appropriate. */ xReturn = errQUEUE_YIELD; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { xReturn = errQUEUE_FULL; } } portENABLE_INTERRUPTS(); return xReturn; } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) int32_t xQueueCRReceive( queue_t xQueue, void *buffer, uint32_t timeout ) { int32_t xReturn; Queue_t * const pxQueue = ( Queue_t * ) xQueue; /* If the queue is already empty we may have to block. A critical section is required to prevent an interrupt adding something to the queue between the check to see if the queue is empty and blocking on the queue. */ portDISABLE_INTERRUPTS(); { if( pxQueue->uxMessagesWaiting == ( uint32_t ) 0 ) { /* There are no messages in the queue, do we want to block or just leave with nothing? */ if( timeout > ( uint32_t ) 0 ) { /* As this is a co-routine we cannot block directly, but return indicating that we need to block. */ vCoRoutineAddToDelayedList( timeout, &( pxQueue->xTasksWaitingToReceive ) ); portENABLE_INTERRUPTS(); return errQUEUE_BLOCKED; } else { portENABLE_INTERRUPTS(); return errQUEUE_FULL; } } else { mtCOVERAGE_TEST_MARKER(); } } portENABLE_INTERRUPTS(); portDISABLE_INTERRUPTS(); { if( pxQueue->uxMessagesWaiting > ( uint32_t ) 0 ) { /* Data is available from the queue. */ pxQueue->u.pcReadFrom += pxQueue->uxItemSize; if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) { pxQueue->u.pcReadFrom = pxQueue->pcHead; } else { mtCOVERAGE_TEST_MARKER(); } --( pxQueue->uxMessagesWaiting ); ( void ) memcpy( ( void * ) buffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); xReturn = pdPASS; /* Were any co-routines waiting for space to become available? */ if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { /* In this instance the co-routine could be placed directly into the ready list as we are within a critical section. Instead the same pending ready list mechanism is used as if the event were caused from within an interrupt. */ if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { xReturn = errQUEUE_YIELD; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { xReturn = pdFAIL; } } portENABLE_INTERRUPTS(); return xReturn; } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) int32_t xQueueCRSendFromISR( queue_t xQueue, const void *pvItemToQueue, int32_t xCoRoutinePreviouslyWoken ) { Queue_t * const pxQueue = ( Queue_t * ) xQueue; /* Cannot block within an ISR so if there is no space on the queue then exit without doing anything. */ if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) { prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); /* We only want to wake one co-routine per ISR, so check that a co-routine has not already been woken. */ if( xCoRoutinePreviouslyWoken == pdFALSE ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) { return pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } return xCoRoutinePreviouslyWoken; } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configUSE_CO_ROUTINES == 1 ) int32_t xQueueCRReceiveFromISR( queue_t xQueue, void *buffer, int32_t *pxCoRoutineWoken ) { int32_t xReturn; Queue_t * const pxQueue = ( Queue_t * ) xQueue; /* We cannot block from an ISR, so check there is data available. If not then just leave without doing anything. */ if( pxQueue->uxMessagesWaiting > ( uint32_t ) 0 ) { /* Copy the data from the queue. */ pxQueue->u.pcReadFrom += pxQueue->uxItemSize; if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) { pxQueue->u.pcReadFrom = pxQueue->pcHead; } else { mtCOVERAGE_TEST_MARKER(); } --( pxQueue->uxMessagesWaiting ); ( void ) memcpy( ( void * ) buffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); if( ( *pxCoRoutineWoken ) == pdFALSE ) { if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) { if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) { *pxCoRoutineWoken = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } xReturn = pdPASS; } else { xReturn = pdFAIL; } return xReturn; } #endif /* configUSE_CO_ROUTINES */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) void vQueueAddToRegistry( queue_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { uint32_t ux; /* See if there is an empty space in the registry. A NULL name denotes a free slot. */ for( ux = ( uint32_t ) 0U; ux < ( uint32_t ) configQUEUE_REGISTRY_SIZE; ux++ ) { if( xQueueRegistry[ ux ].pcQueueName == NULL ) { /* Store the information on this queue. */ xQueueRegistry[ ux ].pcQueueName = pcQueueName; xQueueRegistry[ ux ].xHandle = xQueue; traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); break; } else { mtCOVERAGE_TEST_MARKER(); } } } #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) const char *pcQueueGetName( queue_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { uint32_t ux; const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ /* Note there is nothing here to protect against another task adding or removing entries from the registry while it is being searched. */ for( ux = ( uint32_t ) 0U; ux < ( uint32_t ) configQUEUE_REGISTRY_SIZE; ux++ ) { if( xQueueRegistry[ ux ].xHandle == xQueue ) { pcReturn = xQueueRegistry[ ux ].pcQueueName; break; } else { mtCOVERAGE_TEST_MARKER(); } } return pcReturn; } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configQUEUE_REGISTRY_SIZE > 0 ) void vQueueUnregisterQueue( queue_t xQueue ) { uint32_t ux; /* See if the handle of the queue being unregistered in actually in the registry. */ for( ux = ( uint32_t ) 0U; ux < ( uint32_t ) configQUEUE_REGISTRY_SIZE; ux++ ) { if( xQueueRegistry[ ux ].xHandle == xQueue ) { /* Set the name to NULL to show that this slot if free again. */ xQueueRegistry[ ux ].pcQueueName = NULL; /* Set the handle to NULL to ensure the same queue handle cannot appear in the registry twice if it is added, removed, then added again. */ xQueueRegistry[ ux ].xHandle = ( queue_t ) 0; break; } else { mtCOVERAGE_TEST_MARKER(); } } } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ #endif /* configQUEUE_REGISTRY_SIZE */ /*-----------------------------------------------------------*/ #if ( configUSE_TIMERS == 1 ) void vQueueWaitForMessageRestricted( queue_t xQueue, uint32_t timeout, const int32_t xWaitIndefinitely ) { Queue_t * const pxQueue = ( Queue_t * ) xQueue; /* This function should not be called by application code hence the 'Restricted' in its name. It is not part of the public API. It is designed for use by kernel code, and has special calling requirements. It can result in vListInsert() being called on a list that can only possibly ever have one item in it, so the list will be fast, but even so it should be called with the scheduler locked and not from a critical section. */ /* Only do anything if there are no messages in the queue. This function will not actually cause the task to block, just place it on a blocked list. It will not block until the scheduler is unlocked - at which time a yield will be performed. If an item is added to the queue while the queue is locked, and the calling task blocks on the queue, then the calling task will be immediately unblocked when the queue is unlocked. */ prvLockQueue( pxQueue ); if( pxQueue->uxMessagesWaiting == ( uint32_t ) 0U ) { /* There is nothing in the queue, block for the specified period. */ vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), timeout, xWaitIndefinitely ); } else { mtCOVERAGE_TEST_MARKER(); } prvUnlockQueue( pxQueue ); } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ #if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) QueueSetHandle_t xQueueCreateSet( const uint32_t uxEventQueueLength ) { QueueSetHandle_t pxQueue; pxQueue = xQueueGenericCreate( uxEventQueueLength, ( uint32_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); return pxQueue; } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) int32_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) { int32_t xReturn; taskENTER_CRITICAL(); { if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) { /* Cannot add a queue/semaphore to more than one queue set. */ xReturn = pdFAIL; } else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( uint32_t ) 0 ) { /* Cannot add a queue/semaphore to a queue set if there are already items in the queue/semaphore. */ xReturn = pdFAIL; } else { ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; xReturn = pdPASS; } } taskEXIT_CRITICAL(); return xReturn; } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) int32_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) { int32_t xReturn; Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) { /* The queue was not a member of the set. */ xReturn = pdFAIL; } else if( pxQueueOrSemaphore->uxMessagesWaiting != ( uint32_t ) 0 ) { /* It is dangerous to remove a queue from a set when the queue is not empty because the queue set will still hold pending events for the queue. */ xReturn = pdFAIL; } else { taskENTER_CRITICAL(); { /* The queue is no longer contained in the set. */ pxQueueOrSemaphore->pxQueueSetContainer = NULL; } taskEXIT_CRITICAL(); xReturn = pdPASS; } return xReturn; } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, uint32_t const timeout ) { QueueSetMemberHandle_t xReturn = NULL; ( void ) queue_recv( ( queue_t ) xQueueSet, &xReturn, timeout ); /*lint !e961 Casting from one typedef to another is not redundant. */ return xReturn; } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) { QueueSetMemberHandle_t xReturn = NULL; ( void ) xQueueReceiveFromISR( ( queue_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ return xReturn; } #endif /* configUSE_QUEUE_SETS */ /*-----------------------------------------------------------*/ #if ( configUSE_QUEUE_SETS == 1 ) static int32_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const int32_t xCopyPosition ) { Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; int32_t xReturn = pdFALSE; /* This function must be called form a critical section. */ configASSERT( pxQueueSetContainer ); configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) { const int8_t cTxLock = pxQueueSetContainer->cTxLock; traceQUEUE_SEND( pxQueueSetContainer ); /* The data copied is the handle of the queue that contains data. */ xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition ); if( cTxLock == queueUNLOCKED ) { if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) { if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) { /* The task waiting has a higher priority. */ xReturn = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); } } else { mtCOVERAGE_TEST_MARKER(); } return xReturn; } #endif /* configUSE_QUEUE_SETS */ ================================================ FILE: src/rtos/refactor.sh ================================================ # Change the current order of the awk print is to convert FreeRTOS style to PROS # style. Change from `$1, $2` to `$2, $1` to go the other way. cat src/rtos/refactor.tsv | dos2unix | awk '/^\s*$/ {next;} {if(NR>1) { printf "s/\\\\<%s\\\\>/%s/g\n", $1, $2 } }' | xargs -I '{}' zsh -c 'echo "{}"; sed -i "{}" **/*.(h|c|md|s|S|cpp|c++|cc)' ================================================ FILE: src/rtos/refactor.tsv ================================================ Original Refactored TaskHandle_t task_t TaskFunction_t task_fn_t eTaskState task_state_e_t eRunning E_TASK_STATE_RUNNING eReady E_TASK_STATE_READY eBlocked E_TASK_STATE_BLOCKED eSuspended E_TASK_STATE_SUSPENDED eDeleted E_TASK_STATE_DELETED eInvalid E_TASK_STATE_INVALID eNotifyAction notify_action_e_t eNoAction E_NOTIFY_ACTION_NONE eSetBits E_NOTIFY_ACTION_BITS eIncrement E_NOTIFY_ACTION_INCR eSetValueWithOverwrite E_NOTIFY_ACTION_OWRITE eSetValueWithoutOverwrite E_NOTIFY_ACTION_NO_OWRITE QueueHandle_t queue_t SemaphoreHandle_t sem_t MutexHandle_t mutex_t StackType_t task_stack_t StaticTask_t static_task_s_t BaseType_t int32_t UBaseType_t uint32_t TickType_t uint32_t ListItem_t list_item_t StaticSemaphore_t static_sem_s_t StaticQueue_t static_queue_s_t StreamBufferHandle_t stream_buf_t StaticStreamBuffer_t static_stream_buf_s_t MessageBufferHandle_t msg_buf_t StaticMessageBuffer_t static_msg_buf_s_t xTaskCreate task_create xTaskCreateStatic task_create_static vTaskDelete task_delete vTaskDelay task_delay vTaskDelayUntil task_delay_until uxTaskPriorityGet task_get_priority vTaskPrioritySet task_set_priority eTaskGetState task_get_state vTaskSuspend task_suspend vTaskResume task_resume xTaskAbortDelay task_abort_delay vTaskStartScheduler rtos_sched_start vTaskEndScheduler rtos_sched_stop vTaskSuspendAll rtos_suspend_all xTaskResumeAll rtos_resume_all xTaskGetTickCount millis uxTaskGetNumberOfTasks task_get_count pcTaskGetName task_get_name xTaskGetHandle task_get_by_name xTaskGenericNotify task_notify_ext ulTaskNotifyTake task_notify_take xTaskNotifyWait task_notify_wait xTaskNotifyStateClear task_notify_clear xTaskGetCurrentTaskHandle task_get_current xQueueCreate queue_create xQueueSendToFront queue_prepend xQueueSendToBack queue_append xQueueOverwrite queue_overwrite xQueuePeek queue_peek xQueueReceive queue_recv uxQueueMessagesWaiting queue_get_waiting uxQueueSpacesAvailable queue_get_available vQueueDelete queue_delete xSemaphoreCreateBinary sem_binary_create xSemaphoreTake sem_wait xSemaphoreTakeRecursive mutex_recursive_take xSemaphoreGive sem_post xSemaphoreGiveRecursive mutex_recursive_give xSemaphoreCreateMutex mutex_create xSemaphoreCreateRecursiveMutex mutex_recursive_create xSemaphoreCreateCounting sem_create vSemaphoreDelete sem_delete xSemaphoreGetMutexHolder mutex_get_owner uxSemaphoreGetCount sem_get_count pvPortMalloc kmalloc vPortFree kfree xSemaphoreCreateMutexStatic mutex_create_static xSemaphoreCreateCountingStatic sem_create_static xQueueCreateStatic queue_create_static xStreamBufferCreateStatic stream_buf_create_static xStreamBufferCreate stream_buf_create xStreamBufferSend stream_buf_send xStreamBufferReceive stream_buf_recv xStreamBufferDelete stream_buf_delete xStreamBufferBytesAvailable stream_buf_get_used xStreamBufferSpacesAvailable stream_buf_get_unused xStreamBufferSetTriggerLevel stream_buf_set_trigger xStreamBufferReset stream_buf_reset xStreamBufferIsEmpty stream_buf_is_empty xStreamBufferIsFull stream_buf_is_full xMessageBufferSend msg_buf_send xMessageBufferReceive msg_buf_recv xMessageBufferDelete msg_buf_delete xMessageBufferSpacesAvailable msg_buf_get_unused xMessageBufferReset msg_buf_reset xMessageBufferIsEmpty msg_buf_is_empty xMessageBufferIsFull msg_buf_is_full ================================================ FILE: src/rtos/rtos.cpp ================================================ /** * \file rtos/rtos.cpp * * Contains functions for the PROS RTOS kernel for use by typical * VEX programmers. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/rtos.hpp" #include #include #include "kapi.h" #include "system/optimizers.h" /* definitions needed from task.h, since directly including it conflicts with definitions in pros/rtos.h */ #define taskENTER_CRITICAL() portENTER_CRITICAL() #define taskEXIT_CRITICAL() portEXIT_CRITICAL() namespace pros { using namespace pros::c; Task::Task(task_fn_t function, void* parameters, std::uint32_t prio, std::uint16_t stack_depth, const char* name) { task = task_create(function, parameters, prio, stack_depth, name); } Task::Task(task_fn_t function, void* parameters, const char* name) : Task(function, parameters, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, name) {} Task::Task(task_t task) : task(task) {} Task& Task::operator=(const task_t in) { task = in; return *this; } Task Task::current() { return Task{task_get_current()}; } void Task::remove() { return task_delete(task); } std::uint32_t Task::get_priority() { return task_get_priority(task); } void Task::set_priority(std::uint32_t prio) { task_set_priority(task, prio); } std::uint32_t Task::get_state() { return task_get_state(task); } void Task::suspend() { task_suspend(task); } void Task::resume() { task_resume(task); } const char* Task::get_name() { return task_get_name(task); } std::uint32_t Task::notify() { return task_notify(task); } void Task::join() { return task_join(task); } std::uint32_t Task::notify_ext(std::uint32_t value, notify_action_e_t action, std::uint32_t* prev_value) { return task_notify_ext(task, value, action, prev_value); } std::uint32_t Task::notify_take(bool clear_on_exit, std::uint32_t timeout) { return task_notify_take(clear_on_exit, timeout); } bool Task::notify_clear() { return task_notify_clear(task); } void Task::delay(const std::uint32_t milliseconds) { task_delay(milliseconds); } void Task::delay_until(std::uint32_t* const prev_time, const std::uint32_t delta) { task_delay_until(prev_time, delta); } std::uint32_t Task::get_count() { return task_get_count(); } Clock::time_point Clock::now() { return Clock::time_point{Clock::duration{millis()}}; } mutex_t Mutex::lazy_init() { mutex_t _mutex; if(unlikely((_mutex = mutex.load(std::memory_order::relaxed)) == nullptr)) { taskENTER_CRITICAL(); if(likely((_mutex = mutex.load()) == nullptr)) { mutex.store((_mutex = pros::c::mutex_create())); } taskEXIT_CRITICAL(); } return _mutex; } bool Mutex::take() { return mutex_take(lazy_init(), TIMEOUT_MAX); } bool Mutex::take(std::uint32_t timeout) { return mutex_take(lazy_init(), timeout); } bool Mutex::give() { return mutex_give(lazy_init()); } void Mutex::lock() { if (!take(TIMEOUT_MAX)) { throw std::system_error(errno, std::system_category(), "Cannot obtain lock!"); } } void Mutex::unlock() { give(); } bool Mutex::try_lock() { return take(0); } Mutex::~Mutex() { mutex_t _mutex = mutex.exchange(reinterpret_cast(~0)); pros::c::mutex_delete(_mutex); } mutex_t RecursiveMutex::lazy_init() { mutex_t _mutex; if(unlikely((_mutex = mutex.load(std::memory_order::relaxed)) == nullptr)) { taskENTER_CRITICAL(); if(likely((_mutex = mutex.load()) == nullptr)) { mutex.store((_mutex = pros::c::mutex_recursive_create())); } taskEXIT_CRITICAL(); } return _mutex; } bool RecursiveMutex::take() { return mutex_recursive_take(lazy_init(), TIMEOUT_MAX); } bool RecursiveMutex::take(std::uint32_t timeout) { return mutex_recursive_take(lazy_init(), timeout); } bool RecursiveMutex::give() { return mutex_recursive_give(lazy_init()); } void RecursiveMutex::lock() { if (!take(TIMEOUT_MAX)) { throw std::system_error(errno, std::system_category(), "Cannot obtain lock!"); } } void RecursiveMutex::unlock() { give(); } bool RecursiveMutex::try_lock() { return take(0); } RecursiveMutex::~RecursiveMutex() { mutex_t _mutex = mutex.exchange(reinterpret_cast(~0)); pros::c::mutex_delete(_mutex); } } // namespace pros ================================================ FILE: src/rtos/semphr.c ================================================ #include "FreeRTOS.h" #include "semphr.h" /** * semphr. h *
sem_wait(
 *                   sem_t sem,
 *                   uint32_t xBlockTime
 *               )
* * Macro to obtain a semaphore. The semaphore must have previously been * created with a call to sem_binary_create(), mutex_create() or * sem_create(). * * @param sem A handle to the semaphore being taken - obtained when * the semaphore was created. * * @param xBlockTime The time in ticks to wait for the semaphore to become * available. The macro portTICK_PERIOD_MS can be used to convert this to a * real time. A block time of zero can be used to poll the semaphore. A block * time of portMAX_DELAY can be used to block indefinitely (provided * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). * * @return pdTRUE if the semaphore was obtained. pdFALSE * if xBlockTime expired without the semaphore becoming available. * * Example usage:
 sem_t sem = NULL;

 // A task that creates a semaphore.
 void vATask( void * pvParameters )
 {
    // Create the semaphore to guard a shared resource.
    sem = sem_binary_create();
 }

 // A task that uses the semaphore.
 void vAnotherTask( void * pvParameters )
 {
    // ... Do other things.

    if( sem != NULL )
    {
        // See if we can obtain the semaphore.  If the semaphore is not available
        // wait 10 ticks to see if it becomes free.
        if( sem_wait( sem, ( uint32_t ) 10 ) == pdTRUE )
        {
            // We were able to obtain the semaphore and can now access the
            // shared resource.

            // ...

            // We have finished accessing the shared resource.  Release the
            // semaphore.
            sem_post( sem );
        }
        else
        {
            // We could not obtain the semaphore and can therefore not access
            // the shared resource safely.
        }
    }
 }
 
* \defgroup sem_wait sem_wait * \ingroup Semaphores */ uint8_t sem_wait(sem_t sem, uint32_t timeout) { return xQueueSemaphoreTake( ( sem ), ( timeout ) ); } /** * semphr. h *
sem_post( sem_t sem )
* * Macro to release a semaphore. The semaphore must have previously been * created with a call to sem_binary_create(), mutex_create() or * sem_create(). and obtained using sSemaphoreTake(). * * This macro must not be used from an ISR. See semGiveFromISR () for * an alternative which can be used from an ISR. * * This macro must also not be used on semaphores created using * mutex_recursive_create(). * * @param sem A handle to the semaphore being released. This is the * handle returned when the semaphore was created. * * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. * Semaphores are implemented using queues. An error can occur if there is * no space on the queue to post a message - indicating that the * semaphore was not first obtained correctly. * * Example usage:
 sem_t sem = NULL;

 void vATask( void * pvParameters )
 {
    // Create the semaphore to guard a shared resource.
    sem = vSemaphoreCreateBinary();

    if( sem != NULL )
    {
        if( sem_post( sem ) != pdTRUE )
        {
            // We would expect this call to fail because we cannot give
            // a semaphore without first "taking" it!
        }

        // Obtain the semaphore - don't block if the semaphore is not
        // immediately available.
        if( sem_wait( sem, ( uint32_t ) 0 ) )
        {
            // We now have the semaphore and can access the shared resource.

            // ...

            // We have finished accessing the shared resource so can free the
            // semaphore.
            if( sem_post( sem ) != pdTRUE )
            {
                // We would not expect this call to fail because we must have
                // obtained the semaphore to get here.
            }
        }
    }
 }
 
* \defgroup sem_post sem_post * \ingroup Semaphores */ uint8_t sem_post(sem_t sem) { return xQueueGenericSend((queue_t)(sem), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK); } /** * semphr. h *
sem_t mutex_create( void )
* * Creates a new mutex type semaphore instance, and returns a handle by which * the new mutex can be referenced. * * Internally, within the FreeRTOS implementation, mutex semaphores use a block * of memory, in which the mutex structure is stored. If a mutex is created * using mutex_create() then the required memory is automatically * dynamically allocated inside the mutex_create() function. (see * http://www.freertos.org/a00111.html). If a mutex is created using * mutex_create_static() then the application writer must provided the * memory. mutex_create_static() therefore allows a mutex to be created * without using any dynamic memory allocation. * * Mutexes created using this function can be accessed using the sem_wait() * and sem_post() macros. The mutex_recursive_take() and * mutex_recursive_give() macros must not be used. * * This type of semaphore uses a priority inheritance mechanism so a task * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the * semaphore it is no longer required. * * Mutex type semaphores cannot be used from within interrupt service routines. * * See sem_binary_create() for an alternative implementation that can be * used for pure synchronisation (where one task or interrupt always 'gives' the * semaphore and another always 'takes' the semaphore) and from within interrupt * service routines. * * @return If the mutex was successfully created then a handle to the created * semaphore is returned. If there was not enough heap to allocate the mutex * data structures then NULL is returned. * * Example usage:
 sem_t sem;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to mutex_create().
    // This is a macro so pass the variable in directly.
    sem = mutex_create();

    if( sem != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup mutex_create mutex_create * \ingroup Semaphores */ mutex_t mutex_create(void) { return (mutex_t)xQueueCreateMutex(queueQUEUE_TYPE_MUTEX); } uint8_t mutex_give(mutex_t mutex) { return xQueueGenericSend((queue_t)(mutex), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK); } uint8_t mutex_take(mutex_t mutex, uint32_t timeout) { return xQueueSemaphoreTake( ( mutex ), ( timeout ) ); } void mutex_delete(mutex_t mutex){ sem_delete((sem_t)(mutex)); } /** * semphr. h *
sem_t sem_binary_create( void )
* * Creates a new binary semaphore instance, and returns a handle by which the * new semaphore can be referenced. * * In many usage scenarios it is faster and more memory efficient to use a * direct to task notification in place of a binary semaphore! * http://www.freertos.org/RTOS-task-notifications.html * * Internally, within the FreeRTOS implementation, binary semaphores use a block * of memory, in which the semaphore structure is stored. If a binary semaphore * is created using sem_binary_create() then the required memory is * automatically dynamically allocated inside the sem_binary_create() * function. (see http://www.freertos.org/a00111.html). If a binary semaphore * is created using semCreateBinaryStatic() then the application writer * must provide the memory. semCreateBinaryStatic() therefore allows a * binary semaphore to be created without using any dynamic memory allocation. * * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this * sem_binary_create() function. Note that binary semaphores created using * the vSemaphoreCreateBinary() macro are created in a state such that the * first call to 'take' the semaphore would pass, whereas binary semaphores * created using sem_binary_create() are created in a state such that the * the semaphore must first be 'given' before it can be 'taken'. * * This type of semaphore can be used for pure synchronisation between tasks or * between an interrupt and a task. The semaphore need not be given back once * obtained, so one task/interrupt can continuously 'give' the semaphore while * another continuously 'takes' the semaphore. For this reason this type of * semaphore does not use a priority inheritance mechanism. For an alternative * that does use priority inheritance see mutex_create(). * * @return Handle to the created semaphore, or NULL if the memory required to * hold the semaphore's data structures could not be allocated. * * Example usage:
 sem_t sem = NULL;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to sem_binary_create().
    // This is a macro so pass the variable in directly.
    sem = sem_binary_create();

    if( sem != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup sem_binary_create sem_binary_create * \ingroup Semaphores */ sem_t sem_binary_create(void) { return xQueueGenericCreate((uint32_t)1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE); } /** * semphr. h *
sem_t mutex_recursive_create( void )
* * Creates a new recursive mutex type semaphore instance, and returns a handle * by which the new recursive mutex can be referenced. * * Internally, within the FreeRTOS implementation, recursive mutexs use a block * of memory, in which the mutex structure is stored. If a recursive mutex is * created using mutex_recursive_create() then the required memory is * automatically dynamically allocated inside the * mutex_recursive_create() function. (see * http://www.freertos.org/a00111.html). If a recursive mutex is created using * semCreateRecursiveMutexStatic() then the application writer must * provide the memory that will get used by the mutex. * semCreateRecursiveMutexStatic() therefore allows a recursive mutex to * be created without using any dynamic memory allocation. * * Mutexes created using this macro can be accessed using the * mutex_recursive_take() and mutex_recursive_give() macros. The * sem_wait() and sem_post() macros must not be used. * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * This type of semaphore uses a priority inheritance mechanism so a task * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the * semaphore it is no longer required. * * Mutex type semaphores cannot be used from within interrupt service routines. * * See sem_binary_create() for an alternative implementation that can be * used for pure synchronisation (where one task or interrupt always 'gives' the * semaphore and another always 'takes' the semaphore) and from within interrupt * service routines. * * @return sem Handle to the created mutex semaphore. Should be of type * sem_t. * * Example usage:
 sem_t sem;

 void vATask( void * pvParameters )
 {
    // Semaphore cannot be used before a call to mutex_create().
    // This is a macro so pass the variable in directly.
    sem = mutex_recursive_create();

    if( sem != NULL )
    {
        // The semaphore was created successfully.
        // The semaphore can now be used.
    }
 }
 
* \defgroup mutex_recursive_create mutex_recursive_create * \ingroup Semaphores */ mutex_t mutex_recursive_create(void) { return xQueueCreateMutex(queueQUEUE_TYPE_RECURSIVE_MUTEX); } /** * semphr. h *
mutex_recursive_give( sem_t xMutex )
* * Macro to recursively release, or 'give', a mutex type semaphore. * The mutex must have previously been created using a call to * mutex_recursive_create(); * * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this * macro to be available. * * This macro must not be used on mutexes created using mutex_create(). * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * @param xMutex A handle to the mutex being released, or 'given'. This is the * handle returned by mutex_create(); * * @return pdTRUE if the semaphore was given. * * Example usage:
 sem_t xMutex = NULL;

 // A task that creates a mutex.
 void vATask( void * pvParameters )
 {
    // Create the mutex to guard a shared resource.
    xMutex = mutex_recursive_create();
 }

 // A task that uses the mutex.
 void vAnotherTask( void * pvParameters )
 {
    // ... Do other things.

    if( xMutex != NULL )
    {
        // See if we can obtain the mutex.  If the mutex is not available
        // wait 10 ticks to see if it becomes free.
        if( mutex_recursive_take( xMutex, ( uint32_t ) 10 ) == pdTRUE )
        {
            // We were able to obtain the mutex and can now access the
            // shared resource.

            // ...
            // For some reason due to the nature of the code further calls to
                        // mutex_recursive_take() are made on the same mutex.  In real
                        // code these would not be just sequential calls as this would make
                        // no sense.  Instead the calls are likely to be buried inside
                        // a more complex call structure.
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );

            // The mutex has now been 'taken' three times, so will not be
                        // available to another task until it has also been given back
                        // three times.  Again it is unlikely that real code would have
                        // these calls sequentially, it would be more likely that the calls
                        // to mutex_recursive_give() would be called as a call stack
                        // unwound.  This is just for demonstrative purposes.
            mutex_recursive_give( xMutex );
                        mutex_recursive_give( xMutex );
                        mutex_recursive_give( xMutex );

                        // Now the mutex can be taken by other tasks.
        }
        else
        {
            // We could not obtain the mutex and can therefore not access
            // the shared resource safely.
        }
    }
 }
 
* \defgroup mutex_recursive_give mutex_recursive_give * \ingroup Semaphores */ uint8_t mutex_recursive_give(mutex_t mutex) { return xQueueGiveMutexRecursive((mutex)); } /** * semphr. h * mutex_recursive_take( * sem_t xMutex, * uint32_t xBlockTime * ) * * Macro to recursively obtain, or 'take', a mutex type semaphore. * The mutex must have previously been created using a call to * mutex_recursive_create(); * * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this * macro to be available. * * This macro must not be used on mutexes created using mutex_create(). * * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex * doesn't become available again until the owner has called * mutex_recursive_give() for each successful 'take' request. For example, * if a task successfully 'takes' the same mutex 5 times then the mutex will * not be available to any other task until it has also 'given' the mutex back * exactly five times. * * @param xMutex A handle to the mutex being obtained. This is the * handle returned by mutex_recursive_create(); * * @param xBlockTime The time in ticks to wait for the semaphore to become * available. The macro portTICK_PERIOD_MS can be used to convert this to a * real time. A block time of zero can be used to poll the semaphore. If * the task already owns the semaphore then mutex_recursive_take() will * return immediately no matter what the value of xBlockTime. * * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime * expired without the semaphore becoming available. * * Example usage:
 sem_t xMutex = NULL;

 // A task that creates a mutex.
 void vATask( void * pvParameters )
 {
    // Create the mutex to guard a shared resource.
    xMutex = mutex_recursive_create();
 }

 // A task that uses the mutex.
 void vAnotherTask( void * pvParameters )
 {
    // ... Do other things.

    if( xMutex != NULL )
    {
        // See if we can obtain the mutex.  If the mutex is not available
        // wait 10 ticks to see if it becomes free.
        if( mutex_recursive_take( sem, ( uint32_t ) 10 ) == pdTRUE )
        {
            // We were able to obtain the mutex and can now access the
            // shared resource.

            // ...
            // For some reason due to the nature of the code further calls to
                        // mutex_recursive_take() are made on the same mutex.  In real
                        // code these would not be just sequential calls as this would make
                        // no sense.  Instead the calls are likely to be buried inside
                        // a more complex call structure.
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );
            mutex_recursive_take( xMutex, ( uint32_t ) 10 );

            // The mutex has now been 'taken' three times, so will not be
                        // available to another task until it has also been given back
                        // three times.  Again it is unlikely that real code would have
                        // these calls sequentially, but instead buried in a more complex
                        // call structure.  This is just for illustrative purposes.
            mutex_recursive_give( xMutex );
                        mutex_recursive_give( xMutex );
                        mutex_recursive_give( xMutex );

                        // Now the mutex can be taken by other tasks.
        }
        else
        {
            // We could not obtain the mutex and can therefore not access
            // the shared resource safely.
        }
    }
 }
 
* \defgroup mutex_recursive_take mutex_recursive_take * \ingroup Semaphores */ uint8_t mutex_recursive_take(mutex_t mutex, uint32_t timeout) { return xQueueTakeMutexRecursive((mutex), (timeout)); } sem_t sem_create(uint32_t max_count, uint32_t init_count) { return xQueueCreateCountingSemaphore((max_count), (init_count)); } void sem_delete(sem_t sem) { queue_delete((queue_t)(sem)); } task_t mutex_get_owner(mutex_t mutex) { return xQueueGetMutexHolder((mutex)); } uint32_t sem_get_count(sem_t sem) { return queue_get_waiting((queue_t)(sem)); } mutex_t mutex_create_static(static_sem_s_t* pxMutexBuffer) { return xQueueCreateMutexStatic(queueQUEUE_TYPE_MUTEX, (pxMutexBuffer)); } sem_t sem_create_static(uint32_t max_count, uint32_t init_count, static_sem_s_t* psemBuffer) { return xQueueCreateCountingSemaphoreStatic((max_count), (init_count), (psemBuffer)); } ================================================ FILE: src/rtos/stream_buffer.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* Standard includes. */ #include #include /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "stream_buffer.h" #if( configUSE_TASK_NOTIFICATIONS != 1 ) #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c #endif /* Lint e961 and e750 are suppressed as a MISRA exception justified because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the header files above, but not in this file, in order to generate the correct privileged Vs unprivileged linkage and placement. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ /* If the user has not provided application specific Rx notification macros, or #defined the notification macros away, them provide default implementations that uses task notifications. */ /*lint -save -e9026 Function like macros allowed and needed here so they can be overidden. */ #ifndef sbRECEIVE_COMPLETED #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ rtos_suspend_all(); \ { \ if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ { \ ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ ( uint32_t ) 0, \ E_NOTIFY_ACTION_NONE ); \ ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ } \ } \ ( void ) rtos_resume_all(); #endif /* sbRECEIVE_COMPLETED */ #ifndef sbRECEIVE_COMPLETED_FROM_ISR #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ pxHigherPriorityTaskWoken ) \ { \ uint32_t uxSavedInterruptStatus; \ \ uxSavedInterruptStatus = ( uint32_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ { \ if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ { \ ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ ( uint32_t ) 0, \ E_NOTIFY_ACTION_NONE, \ pxHigherPriorityTaskWoken ); \ ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ } \ } \ portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ } #endif /* sbRECEIVE_COMPLETED_FROM_ISR */ /* If the user has not provided an application specific Tx notification macro, or #defined the notification macro away, them provide a default implementation that uses task notifications. */ #ifndef sbSEND_COMPLETED #define sbSEND_COMPLETED( pxStreamBuffer ) \ rtos_suspend_all(); \ { \ if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ { \ ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ ( uint32_t ) 0, \ E_NOTIFY_ACTION_NONE ); \ ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ } \ } \ ( void ) rtos_resume_all(); #endif /* sbSEND_COMPLETED */ #ifndef sbSEND_COMPLETE_FROM_ISR #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ { \ uint32_t uxSavedInterruptStatus; \ \ uxSavedInterruptStatus = ( uint32_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ { \ if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ { \ ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ ( uint32_t ) 0, \ E_NOTIFY_ACTION_NONE, \ pxHigherPriorityTaskWoken ); \ ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ } \ } \ portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ } #endif /* sbSEND_COMPLETE_FROM_ISR */ /*lint -restore (9026) */ /* The number of bytes used to hold the length of a message in the buffer. */ #define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( size_t ) ) /* Bits stored in the ucFlags field of the stream buffer. */ #define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ #define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ /*-----------------------------------------------------------*/ /* Structure that hold state information on the buffer. */ typedef struct xSTREAM_BUFFER /*lint !e9058 Style convention uses tag. */ { volatile size_t xTail; /* Index to the next item to read within the buffer. */ volatile size_t xHead; /* Index to the next item to write within the buffer. */ size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ volatile task_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ volatile task_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ uint8_t ucFlags; #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxStreamBufferNumber; /* Used for tracing purposes. */ #endif } StreamBuffer_t; /* * The number of bytes available to be read from the buffer. */ static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) ; /* * Add xCount bytes from pucData into the pxStreamBuffer message buffer. * Returns the number of bytes written, which will either equal xCount in the * success case, or 0 if there was not enough space in the buffer (in which case * no data is written into the buffer). */ static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) ; /* * If the stream buffer is being used as a message buffer, then reads an entire * message out of the buffer. If the stream buffer is being used as a stream * buffer then read as many bytes as possible from the buffer. * prvReadBytesFromBuffer() is called to actually extract the bytes from the * buffer's data storage area. */ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, size_t xBytesAvailable, size_t xBytesToStoreMessageLength ) ; /* * If the stream buffer is being used as a message buffer, then writes an entire * message to the buffer. If the stream buffer is being used as a stream * buffer then write as many bytes as possible to the buffer. * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's * data storage area. */ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, const void * pvTxData, size_t xDataLengthBytes, size_t xSpace, size_t xRequiredSpace ) ; /* * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them * to pucData. */ static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *pucData, size_t xMaxCount, size_t xBytesAvailable ); /* * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to * initialise the members of the newly created stream buffer structure. */ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, uint8_t * const pucBuffer, size_t xBufferSizeBytes, size_t xTriggerLevelBytes, int32_t xIsMessageBuffer ) ; /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) stream_buf_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, int32_t xIsMessageBuffer ) { uint8_t *pucAllocatedMemory; /* In case the stream buffer is going to be used as a message buffer (that is, it will hold discrete messages with a little meta data that says how big the next message is) check the buffer will be large enough to hold at least one message. */ configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); /* A trigger level of 0 would cause a waiting task to unblock even when the buffer was empty. */ if( xTriggerLevelBytes == ( size_t ) 0 ) { xTriggerLevelBytes = ( size_t ) 1; /*lint !e9044 Parameter modified to ensure it doesn't have a dangerous value. */ } /* A stream buffer requires a StreamBuffer_t structure and a buffer. Both are allocated in a single call to kmalloc(). The StreamBuffer_t structure is placed at the start of the allocated memory and the buffer follows immediately after. The requested size is incremented so the free space is returned as the user would expect - this is a quirk of the implementation that means otherwise the free space would be reported as one byte smaller than would be logically expected. */ xBufferSizeBytes++; pucAllocatedMemory = ( uint8_t * ) kmalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ if( pucAllocatedMemory != NULL ) { prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer ); traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); } else { traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); } return ( stream_buf_t * ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) stream_buf_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, int32_t xIsMessageBuffer, uint8_t * const pucStreamBufferStorageArea, static_stream_buf_s_t * const pxStaticStreamBuffer ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as static_stream_buf_s_t is opaque Streambuffer_t. */ stream_buf_t xReturn; configASSERT( pucStreamBufferStorageArea ); configASSERT( pxStaticStreamBuffer ); configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); /* A trigger level of 0 would cause a waiting task to unblock even when the buffer was empty. */ if( xTriggerLevelBytes == ( size_t ) 0 ) { xTriggerLevelBytes = ( size_t ) 1; /*lint !e9044 Function parameter deliberately modified to ensure it is in range. */ } /* In case the stream buffer is going to be used as a message buffer (that is, it will hold discrete messages with a little meta data that says how big the next message is) check the buffer will be large enough to hold at least one message. */ configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); #if( configASSERT_DEFINED == 1 ) { /* Sanity check that the size of the structure used to declare a variable of type static_stream_buf_s_t equals the size of the real message buffer structure. */ volatile size_t xSize = sizeof( static_stream_buf_s_t ); configASSERT( xSize == sizeof( StreamBuffer_t ) ); } #endif /* configASSERT_DEFINED */ if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) { prvInitialiseNewStreamBuffer( pxStreamBuffer, pucStreamBufferStorageArea, xBufferSizeBytes, xTriggerLevelBytes, xIsMessageBuffer ); /* Remember this was statically allocated in case it is ever deleted again. */ pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); xReturn = ( stream_buf_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ } else { xReturn = NULL; traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); } return xReturn; } #endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /*-----------------------------------------------------------*/ void vStreamBufferDelete( stream_buf_t xStreamBuffer ) { StreamBuffer_t * pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ configASSERT( pxStreamBuffer ); traceSTREAM_BUFFER_DELETE( xStreamBuffer ); if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) { #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) { /* Both the structure and the buffer were allocated using a single call to kmalloc(), hence only one call to kfree() is required. */ kfree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by kmalloc(). */ } #else { /* Should not be possible to get here, ucFlags must be corrupt. Force an assert. */ configASSERT( xStreamBuffer == ( stream_buf_t ) ~0 ); } #endif } else { /* The structure and buffer were not allocated dynamically and cannot be freed - just scrub the structure so future use will assert. */ memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); } } /*-----------------------------------------------------------*/ int32_t stream_buf_reset( stream_buf_t xStreamBuffer ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ int32_t xReturn = pdFAIL, xIsMessageBuffer; #if( configUSE_TRACE_FACILITY == 1 ) uint32_t uxStreamBufferNumber; #endif configASSERT( pxStreamBuffer ); #if( configUSE_TRACE_FACILITY == 1 ) { /* Store the stream buffer number so it can be restored after the reset. */ uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; } #endif /* Can only reset a message buffer if there are no tasks blocked on it. */ if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) { if( pxStreamBuffer->xTaskWaitingToSend == NULL ) { if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { xIsMessageBuffer = pdTRUE; } else { xIsMessageBuffer = pdFALSE; } prvInitialiseNewStreamBuffer( pxStreamBuffer, pxStreamBuffer->pucBuffer, pxStreamBuffer->xLength, pxStreamBuffer->xTriggerLevelBytes, xIsMessageBuffer ); xReturn = pdPASS; #if( configUSE_TRACE_FACILITY == 1 ) { pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; } #endif traceSTREAM_BUFFER_RESET( xStreamBuffer ); } } return xReturn; } /*-----------------------------------------------------------*/ int32_t stream_buf_set_trigger( stream_buf_t xStreamBuffer, size_t xTriggerLevel ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ int32_t xReturn; configASSERT( pxStreamBuffer ); /* It is not valid for the trigger level to be 0. */ if( xTriggerLevel == ( size_t ) 0 ) { xTriggerLevel = ( size_t ) 1; /*lint !e9044 Parameter modified to ensure it doesn't have a dangerous value. */ } /* The trigger level is the number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ if( xTriggerLevel <= pxStreamBuffer->xLength ) { pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; xReturn = pdPASS; } else { xReturn = pdFALSE; } return xReturn; } /*-----------------------------------------------------------*/ size_t stream_buf_get_unused( stream_buf_t xStreamBuffer ) { const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ size_t xSpace; configASSERT( pxStreamBuffer ); xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; xSpace -= pxStreamBuffer->xHead; xSpace -= ( size_t ) 1; if( xSpace >= pxStreamBuffer->xLength ) { xSpace -= pxStreamBuffer->xLength; } else { mtCOVERAGE_TEST_MARKER(); } return xSpace; } /*-----------------------------------------------------------*/ size_t stream_buf_get_used( stream_buf_t xStreamBuffer ) { const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ size_t xReturn; configASSERT( pxStreamBuffer ); xReturn = prvBytesInBuffer( pxStreamBuffer ); return xReturn; } /*-----------------------------------------------------------*/ size_t stream_buf_send( stream_buf_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, uint32_t xTicksToWait ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ size_t xReturn, xSpace = 0; size_t xRequiredSpace = xDataLengthBytes; TimeOut_t xTimeOut; configASSERT( pvTxData ); configASSERT( pxStreamBuffer ); /* This send function is used to write to both message buffers and stream buffers. If this is a message buffer then the space needed must be increased by the amount of bytes needed to store the length of the message. */ if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; } else { mtCOVERAGE_TEST_MARKER(); } if( xTicksToWait != ( uint32_t ) 0 ) { vTaskSetTimeOutState( &xTimeOut ); do { /* Wait until the required number of bytes are free in the message buffer. */ taskENTER_CRITICAL(); { xSpace = stream_buf_get_unused( pxStreamBuffer ); if( xSpace < xRequiredSpace ) { /* Clear notification state as going to wait for space. */ ( void ) task_notify_clear( NULL ); /* Should only be one writer. */ configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); pxStreamBuffer->xTaskWaitingToSend = task_get_current(); } else { taskEXIT_CRITICAL(); break; } } taskEXIT_CRITICAL(); traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); ( void ) task_notify_wait( ( uint32_t ) 0, UINT32_MAX, NULL, xTicksToWait ); pxStreamBuffer->xTaskWaitingToSend = NULL; } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); } else { mtCOVERAGE_TEST_MARKER(); } if( xSpace == ( size_t ) 0 ) { xSpace = stream_buf_get_unused( pxStreamBuffer ); } else { mtCOVERAGE_TEST_MARKER(); } taskENTER_CRITICAL(); xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); taskEXIT_CRITICAL(); if( xReturn > ( size_t ) 0 ) { traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); /* Was a task waiting for the data? */ if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) { sbSEND_COMPLETED( pxStreamBuffer ); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); } return xReturn; } /*-----------------------------------------------------------*/ size_t xStreamBufferSendFromISR( stream_buf_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, int32_t * const pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ size_t xReturn, xSpace; size_t xRequiredSpace = xDataLengthBytes; configASSERT( pvTxData ); configASSERT( pxStreamBuffer ); /* This send function is used to write to both message buffers and stream buffers. If this is a message buffer then the space needed must be increased by the amount of bytes needed to store the length of the message. */ if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; } else { mtCOVERAGE_TEST_MARKER(); } xSpace = stream_buf_get_unused( pxStreamBuffer ); xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); if( xReturn > ( size_t ) 0 ) { /* Was a task waiting for the data? */ if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) { sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); return xReturn; } /*-----------------------------------------------------------*/ static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, const void * pvTxData, size_t xDataLengthBytes, size_t xSpace, size_t xRequiredSpace ) { int32_t xShouldWrite; size_t xReturn; if( xSpace == ( size_t ) 0 ) { /* Doesn't matter if this is a stream buffer or a message buffer, there is no space to write. */ xShouldWrite = pdFALSE; } else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) { /* This is a stream buffer, as opposed to a message buffer, so writing a stream of bytes rather than discrete messages. Write as many bytes as possible. */ xShouldWrite = pdTRUE; xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); /*lint !e9044 Function parameter modified to ensure it is capped to available space. */ } else if( xSpace >= xRequiredSpace ) { /* This is a message buffer, as opposed to a stream buffer, and there is enough space to write both the message length and the message itself into the buffer. Start by writing the length of the data, the data itself will be written later in this function. */ xShouldWrite = pdTRUE; taskENTER_CRITICAL(); ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); taskEXIT_CRITICAL(); } else { /* There is space available, but not enough space. */ xShouldWrite = pdFALSE; } if( xShouldWrite != pdFALSE ) { /* Writes the data itself. */ taskENTER_CRITICAL(); xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ taskEXIT_CRITICAL(); } else { xReturn = 0; } return xReturn; } /*-----------------------------------------------------------*/ size_t stream_buf_recv( stream_buf_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, uint32_t xTicksToWait ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; configASSERT( pvRxData ); configASSERT( pxStreamBuffer ); /* This receive function is used by both message buffers, which store discrete messages, and stream buffers, which store a continuous stream of bytes. Discrete messages include an additional sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; } else { xBytesToStoreMessageLength = 0; } if( xTicksToWait != ( uint32_t ) 0 ) { /* Checking if there is data and clearing the notification state must be performed atomically. */ taskENTER_CRITICAL(); { xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); /* If this function was invoked by a message buffer read then xBytesToStoreMessageLength holds the number of bytes used to hold the length of the next discrete message. If this function was invoked by a stream buffer read then xBytesToStoreMessageLength will be 0. */ if( xBytesAvailable <= xBytesToStoreMessageLength ) { /* Clear notification state as going to wait for data. */ ( void ) task_notify_clear( NULL ); /* Should only be one reader. */ configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); pxStreamBuffer->xTaskWaitingToReceive = task_get_current(); } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); if( xBytesAvailable <= xBytesToStoreMessageLength ) { /* Wait for data to be available. */ traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); ( void ) task_notify_wait( ( uint32_t ) 0, UINT32_MAX, NULL, xTicksToWait ); pxStreamBuffer->xTaskWaitingToReceive = NULL; /* Recheck the data available after blocking. */ xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); } else { mtCOVERAGE_TEST_MARKER(); } } else { xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); } /* Whether receiving a discrete message (where xBytesToStoreMessageLength holds the number of bytes used to store the message length) or a stream of bytes (where xBytesToStoreMessageLength is zero), the number of bytes available must be greater than xBytesToStoreMessageLength to be able to read bytes from the buffer. */ if( xBytesAvailable > xBytesToStoreMessageLength ) { xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); /* Was a task waiting for space in the buffer? */ if( xReceivedLength != ( size_t ) 0 ) { traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); sbRECEIVE_COMPLETED( pxStreamBuffer ); } else { mtCOVERAGE_TEST_MARKER(); } } else { traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); mtCOVERAGE_TEST_MARKER(); } return xReceivedLength; } /*-----------------------------------------------------------*/ size_t xStreamBufferReceiveFromISR( stream_buf_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, int32_t * const pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; configASSERT( pvRxData ); configASSERT( pxStreamBuffer ); /* This receive function is used by both message buffers, which store discrete messages, and stream buffers, which store a continuous stream of bytes. Discrete messages include an additional sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; } else { xBytesToStoreMessageLength = 0; } xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); /* Whether receiving a discrete message (where xBytesToStoreMessageLength holds the number of bytes used to store the message length) or a stream of bytes (where xBytesToStoreMessageLength is zero), the number of bytes available must be greater than xBytesToStoreMessageLength to be able to read bytes from the buffer. */ if( xBytesAvailable > xBytesToStoreMessageLength ) { xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); /* Was a task waiting for space in the buffer? */ if( xReceivedLength != ( size_t ) 0 ) { sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); return xReceivedLength; } /*-----------------------------------------------------------*/ static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, size_t xBytesAvailable, size_t xBytesToStoreMessageLength ) { size_t xOriginalTail, xReceivedLength, xNextMessageLength; if( xBytesToStoreMessageLength != ( size_t ) 0 ) { /* A discrete message is being received. First receive the length of the message. A copy of the tail is stored so the buffer can be returned to its prior state if the length of the message is too large for the provided buffer. */ xOriginalTail = pxStreamBuffer->xTail; taskENTER_CRITICAL(); ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); taskEXIT_CRITICAL(); /* Reduce the number of bytes available by the number of bytes just read out. */ xBytesAvailable -= xBytesToStoreMessageLength; /* Check there is enough space in the buffer provided by the user. */ if( xNextMessageLength > xBufferLengthBytes ) { /* The user has provided insufficient space to read the message so return the buffer to its previous state (so the length of the message is in the buffer again). */ pxStreamBuffer->xTail = xOriginalTail; xNextMessageLength = 0; } else { mtCOVERAGE_TEST_MARKER(); } } else { /* A stream of bytes is being received (as opposed to a discrete message), so read as many bytes as possible. */ xNextMessageLength = xBufferLengthBytes; } /* Read the actual data. */ taskENTER_CRITICAL(); xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ taskEXIT_CRITICAL(); return xReceivedLength; } /*-----------------------------------------------------------*/ int32_t stream_buf_is_empty( stream_buf_t xStreamBuffer ) { const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ int32_t xReturn; size_t xTail; configASSERT( pxStreamBuffer ); /* True if no bytes are available. */ xTail = pxStreamBuffer->xTail; if( pxStreamBuffer->xHead == xTail ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } /*-----------------------------------------------------------*/ int32_t stream_buf_is_full( stream_buf_t xStreamBuffer ) { int32_t xReturn; size_t xBytesToStoreMessageLength; const StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ configASSERT( pxStreamBuffer ); /* This generic version of the receive function is used by both message buffers, which store discrete messages, and stream buffers, which store a continuous stream of bytes. Discrete messages include an additional sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) { xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; } else { xBytesToStoreMessageLength = 0; } /* True if the available space equals zero. */ if( stream_buf_get_unused( xStreamBuffer ) <= xBytesToStoreMessageLength ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } /*-----------------------------------------------------------*/ int32_t xStreamBufferSendCompletedFromISR( stream_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ int32_t xReturn; uint32_t uxSavedInterruptStatus; configASSERT( pxStreamBuffer ); uxSavedInterruptStatus = ( uint32_t ) portSET_INTERRUPT_MASK_FROM_ISR(); { if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) { ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, ( uint32_t ) 0, E_NOTIFY_ACTION_NONE, pxHigherPriorityTaskWoken ); ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; xReturn = pdTRUE; } else { xReturn = pdFALSE; } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ int32_t xStreamBufferReceiveCompletedFromISR( stream_buf_t xStreamBuffer, int32_t *pxHigherPriorityTaskWoken ) { StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) xStreamBuffer; /*lint !e9087 !e9079 Safe cast as stream_buf_t is opaque Streambuffer_t. */ int32_t xReturn; uint32_t uxSavedInterruptStatus; configASSERT( pxStreamBuffer ); uxSavedInterruptStatus = ( uint32_t ) portSET_INTERRUPT_MASK_FROM_ISR(); { if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) { ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, ( uint32_t ) 0, E_NOTIFY_ACTION_NONE, pxHigherPriorityTaskWoken ); ( pxStreamBuffer )->xTaskWaitingToSend = NULL; xReturn = pdTRUE; } else { xReturn = pdFALSE; } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) { size_t xNextHead, xFirstLength; configASSERT( xCount > ( size_t ) 0 ); xNextHead = pxStreamBuffer->xHead; /* Calculate the number of bytes that can be added in the first write - which may be less than the total number of bytes that need to be added if the buffer will wrap back to the beginning. */ xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); /* Write as many bytes as can be written in the first write. */ configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); memcpy( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ /* If the number of bytes written was less than the number that could be written in the first write... */ if( xCount > xFirstLength ) { /* ...then write the remaining bytes to the start of the buffer. */ configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ } else { mtCOVERAGE_TEST_MARKER(); } xNextHead += xCount; if( xNextHead >= pxStreamBuffer->xLength ) { xNextHead -= pxStreamBuffer->xLength; } else { mtCOVERAGE_TEST_MARKER(); } pxStreamBuffer->xHead = xNextHead; return xCount; } /*-----------------------------------------------------------*/ static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *pucData, size_t xMaxCount, size_t xBytesAvailable ) { size_t xCount, xFirstLength, xNextTail; /* Use the minimum of the wanted bytes and the available bytes. */ xCount = configMIN( xBytesAvailable, xMaxCount ); if( xCount > ( size_t ) 0 ) { xNextTail = pxStreamBuffer->xTail; /* Calculate the number of bytes that can be read - which may be less than the number wanted if the data wraps around to the start of the buffer. */ xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); /* Obtain the number of bytes it is possible to obtain in the first read. Asserts check bounds of read and write. */ configASSERT( xFirstLength <= xMaxCount ); configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ /* If the total number of wanted bytes is greater than the number that could be read in the first read... */ if( xCount > xFirstLength ) { /*...then read the remaining bytes from the start of the buffer. */ configASSERT( xCount <= xMaxCount ); memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ } else { mtCOVERAGE_TEST_MARKER(); } /* Move the tail pointer to effectively remove the data read from the buffer. */ xNextTail += xCount; if( xNextTail >= pxStreamBuffer->xLength ) { xNextTail -= pxStreamBuffer->xLength; } pxStreamBuffer->xTail = xNextTail; } else { mtCOVERAGE_TEST_MARKER(); } return xCount; } /*-----------------------------------------------------------*/ static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) { /* Returns the distance between xTail and xHead. */ size_t xCount; xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; xCount -= pxStreamBuffer->xTail; if ( xCount >= pxStreamBuffer->xLength ) { xCount -= pxStreamBuffer->xLength; } else { mtCOVERAGE_TEST_MARKER(); } return xCount; } /*-----------------------------------------------------------*/ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, uint8_t * const pucBuffer, size_t xBufferSizeBytes, size_t xTriggerLevelBytes, int32_t xIsMessageBuffer ) { /* Assert here is deliberately writing to the entire buffer to ensure it can be written to without generating exceptions, and is setting the buffer to a known value to assist in development/debugging. */ #if( configASSERT_DEFINED == 1 ) { /* The value written just has to be identifiable when looking at the memory. Don't use 0xA5 as that is the stack fill value and could result in confusion as to what is actually being observed. */ const int32_t xWriteValue = 0x55; configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); } #endif memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ pxStreamBuffer->pucBuffer = pucBuffer; pxStreamBuffer->xLength = xBufferSizeBytes; pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; if( xIsMessageBuffer != pdFALSE ) { pxStreamBuffer->ucFlags |= sbFLAGS_IS_MESSAGE_BUFFER; } } #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxStreamBufferGetStreamBufferNumber( stream_buf_t xStreamBuffer ) { return ( ( StreamBuffer_t * ) xStreamBuffer )->uxStreamBufferNumber; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) void vStreamBufferSetStreamBufferNumber( stream_buf_t xStreamBuffer, uint32_t uxStreamBufferNumber ) { ( ( StreamBuffer_t * ) xStreamBuffer )->uxStreamBufferNumber = uxStreamBufferNumber; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) uint8_t ucStreamBufferGetStreamBufferType( stream_buf_t xStreamBuffer ) { return ( ( StreamBuffer_t * )xStreamBuffer )->ucFlags | sbFLAGS_IS_MESSAGE_BUFFER; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ ================================================ FILE: src/rtos/task_notify_when_deleting.c ================================================ #include "kapi.h" #include "common/linkedlist.h" // NOTE: can't just include task.h because of redefinition that goes on in kapi // include chain, so we just prototype what we need here void *pvTaskGetThreadLocalStoragePointer( task_t xTaskToQuery, int32_t xIndex ); void vTaskSetThreadLocalStoragePointer( task_t xTaskToSet, int32_t xIndex, void *pvValue ); #include "rtos/tcb.h" // This increments configNUM_THREAD_LOCAL_STORAGE_POINTERS by 2 #define SUBSCRIBERS_TLSP_IDX 0 #define SUBSCRIPTIONS_TLSP_IDX 1 static static_sem_s_t task_notify_when_deleting_mutex_buf; static mutex_t task_notify_when_deleting_mutex; struct notify_delete_action { task_t task_to_notify; uint32_t value; notify_action_e_t notify_action; }; struct _find_task_args { task_t task; struct notify_delete_action* found_action; }; static void _find_task_cb(ll_node_s_t* node, void* extra) { struct notify_delete_action* action = node->payload.data; struct _find_task_args* args = extra; if(action->task_to_notify == args->task) { args->found_action = action; } } static struct notify_delete_action* _find_task(linked_list_s_t* ll, task_t task) { struct _find_task_args args = { .task = task, .found_action = NULL }; linked_list_foreach(ll, _find_task_cb, &args); return args.found_action; } void task_notify_when_deleting_init() { task_notify_when_deleting_mutex = mutex_create_static(&task_notify_when_deleting_mutex_buf); } void task_notify_when_deleting(task_t target_task, task_t task_to_notify, uint32_t value, notify_action_e_t notify_action) { task_to_notify = (task_to_notify == NULL) ? pxCurrentTCB : task_to_notify; target_task = (target_task == NULL) ? pxCurrentTCB : target_task; // It doesn't make sense for a task to notify itself, and make sure that // neither task is NULL (implying that scheduler hasn't started yet) if (task_to_notify == target_task || !task_to_notify || !target_task) { return; } // Return immediately if the target task is already deleted if (eTaskStateGet(target_task) == E_TASK_STATE_DELETED) { return; } mutex_take(task_notify_when_deleting_mutex, TIMEOUT_MAX); // task_to_notify maintains a list of the tasks whose deletion it cares about. // This will allow us to unsubscribe from notification if/when task_to_notify // is deleted linked_list_s_t* subscriptions_ll = pvTaskGetThreadLocalStoragePointer(task_to_notify, SUBSCRIPTIONS_TLSP_IDX); if (subscriptions_ll == NULL) { subscriptions_ll = linked_list_init(); vTaskSetThreadLocalStoragePointer(task_to_notify, SUBSCRIPTIONS_TLSP_IDX, subscriptions_ll); } if (subscriptions_ll != NULL) { // check whether task_to_notify is already subscribed to target_task. if so, // do nothing ll_node_s_t* it = subscriptions_ll->head; bool found = false; while (it != NULL && !found) { found = it->payload.data == target_task; it = it->next; } if (!found) { linked_list_prepend_data(subscriptions_ll, target_task); } } // similarly, target_task maintains a list of the tasks it needs to notify // when being deleted linked_list_s_t* target_ll = pvTaskGetThreadLocalStoragePointer(target_task, SUBSCRIBERS_TLSP_IDX); if (target_ll == NULL) { target_ll = linked_list_init(); vTaskSetThreadLocalStoragePointer(target_task, SUBSCRIBERS_TLSP_IDX, target_ll); } if (target_ll != NULL) { // Try to find the task_to_notify in the target linked list // i.e., target_task was already configured to notify task_to_notify struct notify_delete_action* action = _find_task(target_ll, task_to_notify); // action wasn't found, so add it to the linked list if (action == NULL) { action = (struct notify_delete_action*)kmalloc(sizeof(struct notify_delete_action)); if (action != NULL) { linked_list_prepend_data(target_ll, action); } } // update the action (whether it was found or newly allocated) if (action != NULL) { action->task_to_notify = task_to_notify; action->notify_action = notify_action; action->value = value; } } mutex_give(task_notify_when_deleting_mutex); } // NOTE: this code is untested, probably works, but also has a terrible name (task_notify_when_deleting_unsubscribe) // void task_notify_when_deleting_unsubscribe(task_t target_task, task_t task_to_notify) { // task_to_notify = (task_to_notify == NULL) ? pxCurrentTCB : task_to_notify; // target_task = (target_task == NULL) ? pxCurrentTCB : target_task; // // if (task_to_notify == target_task || !task_to_notify || !target_task) { // return; // } // // linked_list_s_t* ll = pvTaskGetThreadLocalStoragePointer(target_task, TLSP_IDX); // if (ll != NULL) { // struct notify_delete_action* action = _find_task(ll, task_to_notify); // if (action != NULL) { // linked_list_remove_data(ll, action); // kfree(action); // } // } // } static void unsubscribe_hook_cb(ll_node_s_t* node, void* task_to_remove) { task_t subscription = node->payload.data; linked_list_s_t* subscriptions_list = pvTaskGetThreadLocalStoragePointer(subscription, SUBSCRIBERS_TLSP_IDX); if (subscriptions_list != NULL) { linked_list_remove_data(subscriptions_list, task_to_remove); } } static void delete_hook_cb(ll_node_s_t* node, void* ignore) { struct notify_delete_action* action = node->payload.data; if (action != NULL) { task_notify_ext(action->task_to_notify, action->value, action->notify_action, NULL); kfree(action); node->payload.data = NULL; } } void task_notify_when_deleting_hook(task_t task) { mutex_take(task_notify_when_deleting_mutex, TIMEOUT_MAX); // if this task was subscribed to any other task deletion events, unsubscribe linked_list_s_t* ll = pvTaskGetThreadLocalStoragePointer(task, SUBSCRIPTIONS_TLSP_IDX); if (ll != NULL) { linked_list_foreach(ll, unsubscribe_hook_cb, task); linked_list_free(ll); vTaskSetThreadLocalStoragePointer(task, SUBSCRIPTIONS_TLSP_IDX, NULL); } // notify subscribed tasks of this task's deletion ll = pvTaskGetThreadLocalStoragePointer(task, SUBSCRIBERS_TLSP_IDX); if (ll != NULL) { linked_list_foreach(ll, delete_hook_cb, NULL); linked_list_free(ll); vTaskSetThreadLocalStoragePointer(task, SUBSCRIBERS_TLSP_IDX, NULL); // for good measure } mutex_give(task_notify_when_deleting_mutex); } ================================================ FILE: src/rtos/tasks.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* Standard includes. */ #include #include #include "v5_api.h" /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "timers.h" #include "stack_macros.h" /* Lint e961 and e750 are suppressed as a MISRA exception justified because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the header files above, but not in this file, in order to generate the correct privileged Vs unprivileged linkage and placement. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ /* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting functions but without including stdio.h here. */ #if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) /* At the bottom of this file are two optional functions that can be used to generate human readable text from the raw data generated by the uxTaskGetSystemState() function. Note the formatting functions are provided for convenience only, and are NOT considered part of the kernel. */ #include #endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ #if( configUSE_PREEMPTION == 0 ) /* If the cooperative scheduler is being used then a yield should not be performed just because a higher priority task has been woken. */ #define taskYIELD_IF_USING_PREEMPTION() #else #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() #endif /* Values that can be assigned to the ucNotifyState member of the TCB. */ #define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) #define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) #define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) /* * The value used to fill the stack of a task when the task is created. This * is used purely for checking the high water mark for tasks. */ #define tskSTACK_FILL_BYTE ( 0xa5U ) /* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using dynamically allocated RAM, in which case when any task is deleted it is known that both the task's stack and TCB need to be freed. Sometimes the FreeRTOSConfig.h settings only allow a task to be created using statically allocated RAM, in which case when any task is deleted it is known that neither the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h settings allow a task to be created using either statically or dynamically allocated RAM, in which case a member of the TCB is used to record whether the stack and/or TCB were allocated statically or dynamically, so when a task is deleted the RAM that was allocated dynamically is freed again and no attempt is made to free the RAM that was allocated statically. tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a task to be created using either statically or dynamically allocated RAM. Note that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with a statically allocated stack and a dynamically allocated TCB. !!!NOTE!!! If the definition of tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is changed then the definition of static_task_s_t must also be updated. */ #define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) #define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) #define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) #define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) /* If any of the following are set then task stacks are filled with a known value so the high water mark can be determined. If none of the following are set then don't fill the stack so there is no unnecessary dependency on memset. */ #if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 #else #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 #endif /* * Macros used by vListTask to indicate which state a task is in. */ #define tskRUNNING_CHAR ( 'X' ) #define tskBLOCKED_CHAR ( 'B' ) #define tskREADY_CHAR ( 'R' ) #define tskDELETED_CHAR ( 'D' ) #define tskSUSPENDED_CHAR ( 'S' ) /* * Some kernel aware debuggers require the data the debugger needs access to be * global, rather than file scope. */ #ifdef portREMOVE_STATIC_QUALIFIER #define static #endif /* The name allocated to the Idle task. This can be overridden by defining configIDLE_TASK_NAME in FreeRTOSConfig.h. */ #ifndef configIDLE_TASK_NAME #define configIDLE_TASK_NAME "IDLE" #endif #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is performed in a generic way that is not optimised to any particular microcontroller architecture. */ /* uxTopReadyPriority holds the priority of the highest priority ready state task. */ #define taskRECORD_READY_PRIORITY( uxPriority ) \ { \ if( ( uxPriority ) > uxTopReadyPriority ) \ { \ uxTopReadyPriority = ( uxPriority ); \ } \ } /* taskRECORD_READY_PRIORITY */ /*-----------------------------------------------------------*/ #define taskSELECT_HIGHEST_PRIORITY_TASK() \ { \ uint32_t uxTopPriority = uxTopReadyPriority; \ \ /* Find the highest priority queue that contains ready tasks. */ \ while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ { \ configASSERT( uxTopPriority ); \ --uxTopPriority; \ } \ \ /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ the same priority get an equal share of the processor time. */ \ listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ uxTopReadyPriority = uxTopPriority; \ } /* taskSELECT_HIGHEST_PRIORITY_TASK */ /*-----------------------------------------------------------*/ /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as they are only required when a port optimised method of task selection is being used. */ #define taskRESET_READY_PRIORITY( uxPriority ) #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) #else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is performed in a way that is tailored to the particular microcontroller architecture being used. */ /* A port optimised version is provided. Call the port defined macros. */ #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) /*-----------------------------------------------------------*/ #define taskSELECT_HIGHEST_PRIORITY_TASK() \ { \ uint32_t uxTopPriority; \ \ /* Find the highest priority list that contains ready tasks. */ \ portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ /*-----------------------------------------------------------*/ /* A port optimised version is provided, call it only if the TCB being reset is being referenced from a ready list. If it is referenced from a delayed or suspended list then it won't be in a ready list. */ #define taskRESET_READY_PRIORITY( uxPriority ) \ { \ if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( uint32_t ) 0 ) \ { \ portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ } \ } #endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ /*-----------------------------------------------------------*/ /* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick count overflows. */ #define taskSWITCH_DELAYED_LISTS() \ { \ List_t *pxTemp; \ \ /* The delayed tasks list should be empty when the lists are switched. */ \ configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ \ pxTemp = pxDelayedTaskList; \ pxDelayedTaskList = pxOverflowDelayedTaskList; \ pxOverflowDelayedTaskList = pxTemp; \ xNumOfOverflows++; \ prvResetNextTaskUnblockTime(); \ } /*-----------------------------------------------------------*/ /* * Place the task represented by pxTCB into the appropriate ready list for * the task. It is inserted at the end of the list. */ #define prvAddTaskToReadyList( pxTCB ) \ traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) /*-----------------------------------------------------------*/ /* * Several functions take an task_t parameter that can optionally be NULL, * where NULL is used to indicate that the handle of the currently executing * task should be used in place of the parameter. This macro simply checks to * see if the parameter is NULL and returns a pointer to the appropriate TCB. */ #define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? ( TCB_t * ) pxCurrentTCB : ( TCB_t * ) ( pxHandle ) ) /* The item value of the event list item is normally used to hold the priority of the task to which it belongs (coded to allow it to be held in reverse priority order). However, it is occasionally borrowed for other purposes. It is important its value is not updated due to a task priority change while it is being used for another purpose. The following bit definition is used to inform the scheduler that the value should not be changed - in which case it is the responsibility of whichever module is using the value to ensure it gets set back to its original value when it is released. */ #if( configUSE_16_BIT_TICKS == 1 ) #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U #else #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL #endif #include "tcb.h" /*lint -save -e956 A manual analysis and inspection has been used to determine which static variables must be declared volatile. */ TCB_t * volatile pxCurrentTCB = NULL; /* Lists for ready and blocked tasks. --------------------*/ static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */ static List_t xDelayedTaskList1; /*< Delayed tasks. */ static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ #if( INCLUDE_vTaskDelete == 1 ) static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ static volatile uint32_t uxDeletedTasksWaitingCleanUp = ( uint32_t ) 0U; #endif #if ( INCLUDE_vTaskSuspend == 1 ) static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ #endif /* Other file private variables. --------------------------------*/ static volatile uint32_t uxCurrentNumberOfTasks = ( uint32_t ) 0U; static volatile uint32_t xTickCount = ( uint32_t ) configINITIAL_TICK_COUNT; static volatile uint32_t uxTopReadyPriority = tskIDLE_PRIORITY; static volatile int32_t xSchedulerRunning = pdFALSE; static volatile uint32_t uxPendedTicks = ( uint32_t ) 0U; static volatile int32_t xYieldPending = pdFALSE; static volatile int32_t xNumOfOverflows = ( int32_t ) 0; static uint32_t uxTaskNumber = ( uint32_t ) 0U; static volatile uint32_t xNextTaskUnblockTime = ( uint32_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ static task_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ /* Context switches are held pending while the scheduler is suspended. Also, interrupts must not manipulate the xStateListItem of a TCB, or any of the lists the xStateListItem can be referenced from, if the scheduler is suspended. If an interrupt needs to unblock a task while the scheduler is suspended then it moves the task's event list item into the xPendingReadyList, ready for the kernel to move the task from the pending ready list into the real ready list when the scheduler is unsuspended. The pending ready list itself can only be accessed from a critical section. */ static volatile uint32_t uxSchedulerSuspended = ( uint32_t ) pdFALSE; #if ( configGENERATE_RUN_TIME_STATS == 1 ) static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ #endif /*lint -restore */ /*-----------------------------------------------------------*/ /* Callback function prototypes. --------------------------*/ #if( configCHECK_FOR_STACK_OVERFLOW > 0 ) extern void vApplicationStackOverflowHook( task_t task, char *pcTaskName ); #endif #if( configUSE_TICK_HOOK > 0 ) extern void vApplicationTickHook( void ); #endif #if( configSUPPORT_STATIC_ALLOCATION == 1 ) extern void vApplicationGetIdleTaskMemory( static_task_s_t **ppxIdleTaskTCBBuffer, task_stack_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); #endif /* File private functions. --------------------------------*/ /** * Utility task that simply returns pdTRUE if the task referenced by task is * currently in the Suspended state, or pdFALSE if the task referenced by task * is in any other state. */ #if ( INCLUDE_vTaskSuspend == 1 ) static int32_t prvTaskIsTaskSuspended( const task_t task ) ; #endif /* INCLUDE_vTaskSuspend */ /* * Utility to ready all the lists used by the scheduler. This is called * automatically upon the creation of the first task. */ static void prvInitialiseTaskLists( void ) ; /* * The idle task, which as all tasks is implemented as a never ending loop. * The idle task is automatically created and added to the ready lists upon * creation of the first user task. * * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific * language extensions. The equivalent prototype for this function is: * * void prvIdleTask( void *pvParameters ); * */ static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ); /* * Utility to free all memory allocated by the scheduler to hold a TCB, * including the stack pointed to by the TCB. * * This does not free memory allocated by the task itself (i.e. memory * allocated by calls to kmalloc from within the tasks application code). */ #if ( INCLUDE_vTaskDelete == 1 ) static void prvDeleteTCB( TCB_t *pxTCB ) ; #endif /* * Used only by the idle task. This checks to see if anything has been placed * in the list of tasks waiting to be deleted. If so the task is cleaned up * and its TCB deleted. */ static void prvCheckTasksWaitingTermination( void ) ; /* * The currently executing task is entering the Blocked state. Add the task to * either the current or the overflow delayed task list. */ static void prvAddCurrentTaskToDelayedList( uint32_t timeout, const int32_t xCanBlockIndefinitely ) ; /* * Fills an TaskStatus_t structure with information on each task that is * referenced from the pxList list (which may be a ready list, a delayed list, * a suspended list, etc.). * * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM * NORMAL APPLICATION CODE. */ #if ( configUSE_TRACE_FACILITY == 1 ) static uint32_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, task_state_e_t eState ) ; #endif /* * Searches pxList for a task with name name - returning a handle to * the task if it is found, or NULL if the task is not found. */ #if ( INCLUDE_xTaskGetHandle == 1 ) static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char name[] ) ; #endif /* * When a task is created, the stack of the task is filled with a known value. * This function determines the 'high water mark' of the task stack by * determining how much of the stack remains at the original preset value. */ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) static uint16_t prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) ; #endif /* * Return the amount of time, in ticks, that will pass before the kernel will * next move a task from the Blocked state to the Running state. * * This conditional compilation should use inequality to 0, not equality to 1. * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user * defined low power mode implementations require configUSE_TICKLESS_IDLE to be * set to a value other than 1. */ #if ( configUSE_TICKLESS_IDLE != 0 ) static uint32_t prvGetExpectedIdleTime( void ) ; #endif /* * Set xNextTaskUnblockTime to the time at which the next Blocked state task * will exit the Blocked state. */ static void prvResetNextTaskUnblockTime( void ); #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) /* * Helper function used to pad task names with spaces when printing out * human readable tables of task information. */ static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) ; #endif /* * Called after a Task_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ static void prvInitialiseNewTask( task_fn_t pxTaskCode, const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t ulStackDepth, void * const pvParameters, uint32_t uxPriority, task_t * const pxCreatedTask, TCB_t *pxNewTCB ) ; /* * Called after a new task has been created and initialised to place the task * under the control of the scheduler. */ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) ; /* * freertos_tasks_c_additions_init() should only be called if the user definable * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro * called by the function. */ #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT static void freertos_tasks_c_additions_init( void ) ; #endif /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) task_t task_create_static( task_fn_t task_code, void* const param, uint32_t priority, const size_t stack_size, const char* const name, task_stack_t * const stack_buffer, static_task_s_t * const task_buffer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { TCB_t *pxNewTCB; task_t xReturn; configASSERT( stack_buffer != NULL ); configASSERT( task_buffer != NULL ); #if( configASSERT_DEFINED == 1 ) { /* Sanity check that the size of the structure used to declare a variable of type static_task_s_t equals the size of the real task structure. */ volatile size_t xSize = sizeof( static_task_s_t ); configASSERT( xSize == sizeof( TCB_t ) ); } #endif /* configASSERT_DEFINED */ if ((task_buffer != NULL) && (stack_buffer != NULL)) { /* Finish task termination if the TCB is awaiting termination by the IDLE task. xTasksWaitingTermination list would then have a pointer to (this) task in an active task list, which would end up destroying that list in unexpected ways */ void task_finish_termination(TCB_t*); task_finish_termination((TCB_t*)task_buffer); /* The memory used for the task's TCB and stack are passed into this function - use them. */ pxNewTCB = (TCB_t*)task_buffer; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ pxNewTCB->pxStack = (task_stack_t*)stack_buffer; #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ { /* Tasks can be created statically or dynamically, so note this task was created statically in case the task is later deleted. */ pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ prvInitialiseNewTask( task_code, name, stack_size, param, priority, &xReturn, pxNewTCB ); prvAddNewTaskToReadyList( pxNewTCB ); } else { errno = EINVAL; xReturn = NULL; } return xReturn; } #endif /* SUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) task_t task_create(task_fn_t function, void* const parameters, uint32_t prio, const uint16_t stack_depth, const char* const name) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { TCB_t* new_tcb; task_t return_val = NULL; /* If the stack grows down then allocate the stack then the TCB so the stack does not grow into the TCB. Likewise if the stack grows up then allocate the TCB then the stack. */ #if( portSTACK_GROWTH > 0 ) { /* Allocate space for the TCB. Where the memory comes from depends on the implementation of the port malloc function and whether or not static allocation is being used. */ new_tcb = ( TCB_t * ) kmalloc( sizeof( TCB_t ) ); if( new_tcb != NULL ) { /* Allocate space for the stack used by the task being created. The base of the stack memory stored in the TCB so the task can be deleted later if required. */ new_tcb->pxStack = ( task_stack_t * ) kmalloc( ( ( ( size_t ) usStackDepth ) * sizeof( task_stack_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ if( new_tcb->pxStack == NULL ) { /* Could not allocate the stack. Delete the allocated TCB. */ kfree( new_tcb ); new_tcb = NULL; } } } #else /* portSTACK_GROWTH */ { task_stack_t* stack; /* Allocate space for the stack used by the task being created. */ stack = ( task_stack_t * ) kmalloc( ( ( ( size_t ) stack_depth ) * sizeof( task_stack_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ if( stack != NULL ) { /* Allocate space for the TCB. */ new_tcb = ( TCB_t * ) kmalloc( sizeof( TCB_t ) ); /*lint !e961 MISRA exception as the casts are only redundant for some paths. */ if( new_tcb != NULL ) { /* Store the stack location in the TCB. */ new_tcb->pxStack = stack; } else { /* The stack cannot be used as the TCB was not created. Free it again. */ errno = ENOMEM; kfree(stack); } } else { errno = ENOMEM; new_tcb = NULL; } } #endif /* portSTACK_GROWTH */ if (new_tcb != NULL ) { #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ { /* Tasks can be created statically or dynamically, so note this task was created dynamically in case it is later deleted. */ new_tcb->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; } #endif /* configSUPPORT_STATIC_ALLOCATION */ prvInitialiseNewTask(function, name, ( uint32_t ) stack_depth, parameters, prio, &return_val, new_tcb); prvAddNewTaskToReadyList(new_tcb); } else { return_val = NULL; errno = ENOMEM; } return return_val; } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ /*-----------------------------------------------------------*/ static void prvInitialiseNewTask( task_fn_t pxTaskCode, const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t ulStackDepth, void * const pvParameters, uint32_t uxPriority, task_t * const pxCreatedTask, TCB_t *pxNewTCB ) { task_stack_t *pxTopOfStack; uint32_t x; /* Avoid dependency on memset() if it is not required. */ #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) { /* Fill the stack with a known value to assist debugging. */ ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( task_stack_t ) ); } #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ /* Calculate the top of stack address. This depends on whether the stack grows from high memory to low (as per the 80x86) or vice versa. portSTACK_GROWTH is used to make the result positive or negative as required by the port. */ #if( portSTACK_GROWTH < 0 ) { pxTopOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); pxTopOfStack = ( task_stack_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. */ /* Check the alignment of the calculated top of stack is correct. */ configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) { /* Also record the stack's high address, which may assist debugging. */ pxNewTCB->pxEndOfStack = pxTopOfStack; } #endif /* configRECORD_STACK_HIGH_ADDRESS */ } #else /* portSTACK_GROWTH */ { pxTopOfStack = pxNewTCB->pxStack; /* Check the alignment of the stack buffer is correct. */ configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); /* The other extreme of the stack space is required if stack checking is performed. */ pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); } #endif /* portSTACK_GROWTH */ /* Store the task name in the TCB. */ for( x = ( uint32_t ) 0; x < ( uint32_t ) configMAX_TASK_NAME_LEN; x++ ) { pxNewTCB->pcTaskName[ x ] = pcName[ x ]; /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than configMAX_TASK_NAME_LEN characters just in case the memory after the string is not accessible (extremely unlikely). */ if( pcName[ x ] == 0x00 ) { break; } else { mtCOVERAGE_TEST_MARKER(); } } /* Ensure the name string is terminated in the case that the string length was greater or equal to configMAX_TASK_NAME_LEN. */ pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; /* This is used as an array index so must ensure it's not too large. First remove the privilege bit if one is present. */ if( uxPriority >= ( uint32_t ) configMAX_PRIORITIES ) { uxPriority = ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) 1U; } else { mtCOVERAGE_TEST_MARKER(); } pxNewTCB->uxPriority = uxPriority; #if ( configUSE_MUTEXES == 1 ) { pxNewTCB->uxBasePriority = uxPriority; pxNewTCB->uxMutexesHeld = 0; } #endif /* configUSE_MUTEXES */ vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); /* Set the pxNewTCB as a link back from the list_item_t. This is so we can get back to the containing TCB from a generic item in a list. */ listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); /* Event lists are always in priority order. */ listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); #if ( portCRITICAL_NESTING_IN_TCB == 1 ) { pxNewTCB->uxCriticalNesting = ( uint32_t ) 0U; } #endif /* portCRITICAL_NESTING_IN_TCB */ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) { pxNewTCB->pxTaskTag = NULL; } #endif /* configUSE_APPLICATION_TASK_TAG */ #if ( configGENERATE_RUN_TIME_STATS == 1 ) { pxNewTCB->ulRunTimeCounter = 0UL; } #endif /* configGENERATE_RUN_TIME_STATS */ #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) { for( x = 0; x < ( uint32_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) { pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; } } #endif #if ( configUSE_TASK_NOTIFICATIONS == 1 ) { pxNewTCB->ulNotifiedValue = 0; pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; } #endif #if ( configUSE_NEWLIB_REENTRANT == 1 ) { /* Initialise this task's Newlib reent structure. */ _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); } #endif #if( INCLUDE_xTaskAbortDelay == 1 ) { pxNewTCB->ucDelayAborted = pdFALSE; } #endif /* Initialize the TCB stack to look as if the task was already running, but had been interrupted by the scheduler. The return address is set to the start of the task function. Once the stack has been initialised the top of stack variable is updated. */ pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); if( ( void * ) pxCreatedTask != NULL ) { /* Pass the handle out in an anonymous way. The handle can be used to change the created task's priority, delete the created task, etc.*/ *pxCreatedTask = ( task_t ) pxNewTCB; } else { mtCOVERAGE_TEST_MARKER(); } } /*-----------------------------------------------------------*/ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) { /* Ensure interrupts don't access the task lists while the lists are being updated. */ taskENTER_CRITICAL(); { uxCurrentNumberOfTasks++; if( pxCurrentTCB == NULL ) { /* There are no other tasks, or all the other tasks are in the suspended state - make this the current task. */ pxCurrentTCB = pxNewTCB; if( uxCurrentNumberOfTasks == ( uint32_t ) 1 ) { /* This is the first task to be created so do the preliminary initialisation required. We will not recover if this call fails, but we will report the failure. */ prvInitialiseTaskLists(); } else { mtCOVERAGE_TEST_MARKER(); } } else { /* If the scheduler is not already running, make this task the current task if it is the highest priority task to be created so far. */ if( xSchedulerRunning == pdFALSE ) { if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) { pxCurrentTCB = pxNewTCB; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } uxTaskNumber++; #if ( configUSE_TRACE_FACILITY == 1 ) { /* Add a counter into the TCB for tracing only. */ pxNewTCB->uxTCBNumber = uxTaskNumber; } #endif /* configUSE_TRACE_FACILITY */ traceTASK_CREATE( pxNewTCB ); prvAddTaskToReadyList( pxNewTCB ); portSETUP_TCB( pxNewTCB ); } taskEXIT_CRITICAL(); if( xSchedulerRunning != pdFALSE ) { /* If the created task is of a higher priority than the current task then it should run now. */ if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) { taskYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) void task_delete(task_t task) { TCB_t *pxTCB; void task_notify_when_deleting_hook(task_t); task_notify_when_deleting_hook(task); taskENTER_CRITICAL(); { /* If null is passed in here then it is the calling task that is being deleted. */ pxTCB = prvGetTCBFromHandle( task ); /* Remove task from the ready list. */ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { taskRESET_READY_PRIORITY( pxTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); } /* Is the task waiting on an event also? */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); } /* Increment the uxTaskNumber also so kernel aware debuggers can detect that the task lists need re-generating. This is done before portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will not return. */ uxTaskNumber++; if( pxTCB == pxCurrentTCB ) { /* A task is deleting itself. This cannot complete within the task itself, as a context switch to another task is required. Place the task in the termination list. The idle task will check the termination list and free up any memory allocated by the scheduler for the TCB and stack of the deleted task. */ vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); /* Increment the ucTasksDeleted variable so the idle task knows there is a task that has been deleted and that it should therefore check the xTasksWaitingTermination list. */ ++uxDeletedTasksWaitingCleanUp; /* The pre-delete hook is primarily for the Windows simulator, in which Windows specific clean up operations are performed, after which it is not possible to yield away from this task - hence xYieldPending is used to latch that a context switch is required. */ portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); } else { --uxCurrentNumberOfTasks; prvDeleteTCB( pxTCB ); /* Reset the next expected unblock time in case it referred to the task that has just been deleted. */ prvResetNextTaskUnblockTime(); } traceTASK_DELETE( pxTCB ); } taskEXIT_CRITICAL(); /* Force a reschedule if it is the currently running task that has just been deleted. */ if( xSchedulerRunning != pdFALSE ) { if( pxTCB == pxCurrentTCB ) { configASSERT( uxSchedulerSuspended == 0 ); portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } } // Check if a task is awaiting termination and finish termination if it is void task_finish_termination(TCB_t* pxTCB) { uint8_t doCleanup = 0; taskENTER_CRITICAL(); { list_item_t* pxStateListItem = &( pxTCB->xStateListItem ); if (pxStateListItem != NULL) { List_t* pxStateList = ( List_t * ) listLIST_ITEM_CONTAINER( pxStateListItem ); if (pxStateList == &xTasksWaitingTermination && listGET_NEXT( pxStateListItem )->pxPrevious == pxStateListItem) { ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); --uxCurrentNumberOfTasks; --uxDeletedTasksWaitingCleanUp; doCleanup = 1; } } } taskEXIT_CRITICAL(); if (doCleanup == 1) { prvDeleteTCB(pxTCB); } } #endif /* INCLUDE_vTaskDelete */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelayUntil == 1 ) void task_delay_until(uint32_t* const prev_time, const uint32_t delta) { uint32_t xTimeToWake; int32_t xAlreadyYielded, xShouldDelay = pdFALSE; configASSERT( prev_time ); configASSERT( ( delta > 0U ) ); configASSERT( uxSchedulerSuspended == 0 ); const uint32_t xTicksIncrement = pdMS_TO_TICKS(delta); rtos_suspend_all(); { /* Minor optimisation. The tick count cannot change in this block. */ const uint32_t xConstTickCount = xTickCount; /* Generate the tick time at which the task wants to wake. */ xTimeToWake = *prev_time + xTicksIncrement; if( xConstTickCount < *prev_time ) { /* The tick count has overflowed since this function was lasted called. In this case the only time we should ever actually delay is if the wake time has also overflowed, and the wake time is greater than the tick time. When this is the case it is as if neither time had overflowed. */ if( ( xTimeToWake < *prev_time ) && ( xTimeToWake > xConstTickCount ) ) { xShouldDelay = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { /* The tick time has not overflowed. In this case we will delay if either the wake time has overflowed, and/or the tick time is less than the wake time. */ if( ( xTimeToWake < *prev_time ) || ( xTimeToWake > xConstTickCount ) ) { xShouldDelay = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } /* Update the wake time ready for the next call. */ *prev_time = xTimeToWake; if( xShouldDelay != pdFALSE ) { traceTASK_DELAY_UNTIL( xTimeToWake ); /* prvAddCurrentTaskToDelayedList() needs the block time, not the time to wake, so subtract the current tick count. */ prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); } else { mtCOVERAGE_TEST_MARKER(); } } xAlreadyYielded = rtos_resume_all(); /* Force a reschedule if rtos_resume_all has not already done so, we may have put ourselves to sleep. */ if( xAlreadyYielded == pdFALSE ) { portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* INCLUDE_vTaskDelayUntil */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelay == 1 ) void task_delay(const uint32_t milliseconds) { int32_t xAlreadyYielded = pdFALSE; /* A delay time of zero just forces a reschedule. */ if( milliseconds > ( uint32_t ) 0U ) { configASSERT( uxSchedulerSuspended == 0 ); rtos_suspend_all(); { traceTASK_DELAY(); /* A task that is removed from the event list while the scheduler is suspended will not get placed in the ready list or removed from the blocked list until the scheduler is resumed. This task cannot be in an event list as it is the currently executing task. */ prvAddCurrentTaskToDelayedList( milliseconds, pdFALSE ); } xAlreadyYielded = rtos_resume_all(); } else { mtCOVERAGE_TEST_MARKER(); } /* Force a reschedule if rtos_resume_all has not already done so, we may have put ourselves to sleep. */ if( xAlreadyYielded == pdFALSE ) { portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } void delay(const uint32_t milliseconds) { task_delay(milliseconds); } #endif /* INCLUDE_vTaskDelay */ /*-----------------------------------------------------------*/ #if( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) ) task_state_e_t task_get_state(task_t task) { task_state_e_t eReturn; List_t *pxStateList; const TCB_t * const pxTCB = ( TCB_t * ) task; configASSERT( pxTCB ); if( pxTCB == pxCurrentTCB ) { /* The task calling this function is querying its own state. */ eReturn = E_TASK_STATE_RUNNING; } else { taskENTER_CRITICAL(); { pxStateList = ( List_t * ) listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); } taskEXIT_CRITICAL(); if( ( pxStateList == pxDelayedTaskList ) || ( pxStateList == pxOverflowDelayedTaskList ) ) { /* The task being queried is referenced from one of the Blocked lists. */ eReturn = E_TASK_STATE_BLOCKED; } #if ( INCLUDE_vTaskSuspend == 1 ) else if( pxStateList == &xSuspendedTaskList ) { /* The task being queried is referenced from the suspended list. Is it genuinely suspended or is it block indefinitely? */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) { eReturn = E_TASK_STATE_SUSPENDED; } else { eReturn = E_TASK_STATE_BLOCKED; } } #endif #if ( INCLUDE_vTaskDelete == 1 ) else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) { /* The task being queried is referenced from the deleted tasks list, or it is not referenced from any lists at all. */ eReturn = E_TASK_STATE_DELETED; } #endif else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ { /* If the task is not in any other state, it must be in the Ready (including pending ready) state. */ eReturn = E_TASK_STATE_READY; } } return eReturn; } /*lint !e818 task cannot be a pointer to const because it is a typedef. */ #endif /* INCLUDE_eTaskGetState */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) uint32_t task_get_priority(task_t task) { TCB_t *pxTCB; uint32_t uxReturn; taskENTER_CRITICAL(); { /* If null is passed in here then it is the priority of the that called task_get_priority() that is being queried. */ pxTCB = prvGetTCBFromHandle( task ); uxReturn = pxTCB->uxPriority; } taskEXIT_CRITICAL(); return uxReturn; } #endif /* INCLUDE_uxTaskPriorityGet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskPriorityGet == 1 ) uint32_t uxTaskPriorityGetFromISR( task_t task ) { TCB_t *pxTCB; uint32_t uxReturn, uxSavedInterruptState; /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are keep permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); { /* If null is passed in here then it is the priority of the calling task that is being queried. */ pxTCB = prvGetTCBFromHandle( task ); uxReturn = pxTCB->uxPriority; } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); return uxReturn; } #endif /* INCLUDE_uxTaskPriorityGet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskPrioritySet == 1 ) void task_set_priority(task_t task, uint32_t prio) { TCB_t *pxTCB; uint32_t uxCurrentBasePriority, uxPriorityUsedOnEntry; int32_t xYieldRequired = pdFALSE; configASSERT( ( prio < configMAX_PRIORITIES ) ); /* Ensure the new priority is valid. */ if( prio >= ( uint32_t ) configMAX_PRIORITIES ) { prio = ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) 1U; } else { mtCOVERAGE_TEST_MARKER(); } taskENTER_CRITICAL(); { /* If null is passed in here then it is the priority of the calling task that is being changed. */ pxTCB = prvGetTCBFromHandle( task ); traceTASK_PRIORITY_SET( pxTCB, prio ); #if ( configUSE_MUTEXES == 1 ) { uxCurrentBasePriority = pxTCB->uxBasePriority; } #else { uxCurrentBasePriority = pxTCB->uxPriority; } #endif if( uxCurrentBasePriority != prio ) { /* The priority change may have readied a task of higher priority than the calling task. */ if( prio > uxCurrentBasePriority ) { if( pxTCB != pxCurrentTCB ) { /* The priority of a task other than the currently running task is being raised. Is the priority being raised above that of the running task? */ if( prio >= pxCurrentTCB->uxPriority ) { xYieldRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { /* The priority of the running task is being raised, but the running task must already be the highest priority task able to run so no yield is required. */ } } else if( pxTCB == pxCurrentTCB ) { /* Setting the priority of the running task down means there may now be another task of higher priority that is ready to execute. */ xYieldRequired = pdTRUE; } else { /* Setting the priority of any other task down does not require a yield as the running task must be above the new priority of the task being modified. */ } /* Remember the ready list the task might be referenced from before its uxPriority member is changed so the taskRESET_READY_PRIORITY() macro can function correctly. */ uxPriorityUsedOnEntry = pxTCB->uxPriority; #if ( configUSE_MUTEXES == 1 ) { /* Only change the priority being used if the task is not currently using an inherited priority. */ if( pxTCB->uxBasePriority == pxTCB->uxPriority ) { pxTCB->uxPriority = prio; } else { mtCOVERAGE_TEST_MARKER(); } /* The base priority gets set whatever. */ pxTCB->uxBasePriority = prio; } #else { pxTCB->uxPriority = prio; } #endif /* Only reset the event list item value if the value is not being used for anything else. */ if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) { listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) prio ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ } else { mtCOVERAGE_TEST_MARKER(); } /* If the task is in the blocked or suspended list we need do nothing more than change its priority variable. However, if the task is in a ready list it needs to be removed and placed in the list appropriate to its new priority. */ if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) { /* The task is currently in its ready list - remove before adding it to it's new ready list. As we are in a critical section we can do this even if the scheduler is suspended. */ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { /* It is known that the task is in its ready list so there is no need to check again and the port level reset macro can be called directly. */ portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); } else { mtCOVERAGE_TEST_MARKER(); } prvAddTaskToReadyList( pxTCB ); } else { mtCOVERAGE_TEST_MARKER(); } if( xYieldRequired != pdFALSE ) { taskYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } /* Remove compiler warning about unused variables when the port optimised task selection is not being used. */ ( void ) uxPriorityUsedOnEntry; } } taskEXIT_CRITICAL(); } #endif /* INCLUDE_vTaskPrioritySet */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) void task_suspend(task_t task) { TCB_t *pxTCB; taskENTER_CRITICAL(); { /* If null is passed in here then it is the running task that is being suspended. */ pxTCB = prvGetTCBFromHandle( task ); traceTASK_SUSPEND( pxTCB ); /* Remove task from the ready/delayed list and place in the suspended list. */ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { taskRESET_READY_PRIORITY( pxTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); } /* Is the task waiting on an event also? */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); } vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); #if( configUSE_TASK_NOTIFICATIONS == 1 ) { if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) { /* The task was blocked to wait for a notification, but is now suspended, so no notification was received. */ pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; } } #endif } taskEXIT_CRITICAL(); if( xSchedulerRunning != pdFALSE ) { /* Reset the next expected unblock time in case it referred to the task that is now in the Suspended state. */ taskENTER_CRITICAL(); { prvResetNextTaskUnblockTime(); } taskEXIT_CRITICAL(); } else { mtCOVERAGE_TEST_MARKER(); } if( pxTCB == pxCurrentTCB ) { if( xSchedulerRunning != pdFALSE ) { /* The current task has just been suspended. */ configASSERT( uxSchedulerSuspended == 0 ); portYIELD_WITHIN_API(); } else { /* The scheduler is not running, but the task that was pointed to by pxCurrentTCB has just been suspended and pxCurrentTCB must be adjusted to point to a different task. */ if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) { /* No other tasks are ready, so set pxCurrentTCB back to NULL so when the next task is created pxCurrentTCB will be set to point to it no matter what its relative priority is. */ pxCurrentTCB = NULL; } else { vTaskSwitchContext(); } } } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) static int32_t prvTaskIsTaskSuspended( const task_t task ) { int32_t xReturn = pdFALSE; const TCB_t * const pxTCB = ( TCB_t * ) task; /* Accesses xPendingReadyList so must be called from a critical section. */ /* It does not make sense to check if the calling task is suspended. */ configASSERT( task ); /* Is the task being resumed actually in the suspended list? */ if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) { /* Has the task already been resumed from within an ISR? */ if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) { /* Is it in the suspended list because it is in the Suspended state, or because is is blocked with no timeout? */ if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ { xReturn = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } return xReturn; } /*lint !e818 task cannot be a pointer to const because it is a typedef. */ #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskSuspend == 1 ) void task_resume(task_t task) { TCB_t * const pxTCB = ( TCB_t * ) task; /* It does not make sense to resume the calling task. */ configASSERT( task ); /* The parameter cannot be NULL as it is impossible to resume the currently executing task. */ if( ( pxTCB != NULL ) && ( pxTCB != pxCurrentTCB ) ) { taskENTER_CRITICAL(); { if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) { traceTASK_RESUME( pxTCB ); /* The ready list can be accessed even if the scheduler is suspended because this is inside a critical section. */ ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); prvAddTaskToReadyList( pxTCB ); /* A higher priority task may have just been resumed. */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { /* This yield may not cause the task just resumed to run, but will leave the lists in the correct state for the next yield. */ taskYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* INCLUDE_vTaskSuspend */ /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) int32_t xTaskResumeFromISR( task_t task ) { int32_t xYieldRequired = pdFALSE; TCB_t * const pxTCB = ( TCB_t * ) task; uint32_t uxSavedInterruptStatus; configASSERT( task ); /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are keep permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) { traceTASK_RESUME_FROM_ISR( pxTCB ); /* Check the ready lists can be accessed. */ if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { /* Ready lists can be accessed so move the task from the suspended list to the ready list directly. */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { xYieldRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); prvAddTaskToReadyList( pxTCB ); } else { /* The delayed or ready lists cannot be accessed so the task is held in the pending ready list until the scheduler is unsuspended. */ vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); } } else { mtCOVERAGE_TEST_MARKER(); } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xYieldRequired; } #endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ /*-----------------------------------------------------------*/ void rtos_sched_start( void ) { int32_t xReturn; /* Add the idle task at the lowest priority. */ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) { static_task_s_t *pxIdleTaskTCBBuffer = NULL; task_stack_t *pxIdleTaskStackBuffer = NULL; uint32_t ulIdleTaskStackSize; /* The Idle task is created using user provided RAM - obtain the address of the RAM then create the idle task. */ vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); xIdleTaskHandle = task_create_static( prvIdleTask, ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), ulIdleTaskStackSize, configIDLE_TASK_NAME, pxIdleTaskStackBuffer, pxIdleTaskTCBBuffer); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ if( xIdleTaskHandle != NULL ) { xReturn = pdPASS; } else { xReturn = pdFAIL; } } #else { /* The Idle task is being created using dynamically allocated RAM. */ xIdleTaskHandle = task_create( prvIdleTask, ( void * ) NULL, ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), configMINIMAL_STACK_SIZE, configIDLE_TASK_NAME); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ } #endif /* configSUPPORT_STATIC_ALLOCATION */ #if ( configUSE_TIMERS == 1 ) { if( xReturn == pdPASS ) { xReturn = xTimerCreateTimerTask(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_TIMERS */ if( xReturn == pdPASS ) { /* freertos_tasks_c_additions_init() should only be called if the user definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro called by the function. */ #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT { freertos_tasks_c_additions_init(); } #endif /* Interrupts are turned off here, to ensure a tick does not occur before or during the call to xPortStartScheduler(). The stacks of the created tasks contain a status word with interrupts switched on so interrupts will automatically get re-enabled when the first task starts to run. */ portDISABLE_INTERRUPTS(); #if ( configUSE_NEWLIB_REENTRANT == 1 ) { /* Switch Newlib's _impure_ptr variable to point to the _reent structure specific to the task that will run first. */ _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); } #endif /* configUSE_NEWLIB_REENTRANT */ xNextTaskUnblockTime = portMAX_DELAY; xSchedulerRunning = pdTRUE; xTickCount = ( uint32_t ) 0U; /* If configGENERATE_RUN_TIME_STATS is defined then the following macro must be defined to configure the timer/counter used to generate the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS is set to 0 and the following line fails to build then ensure you do not have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your FreeRTOSConfig.h file. */ portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); /* Setting up the timer tick is hardware specific and thus in the portable interface. */ if( xPortStartScheduler() != pdFALSE ) { /* Should not reach here as if the scheduler is running the function will not return. */ } else { /* Should only reach here if a task calls xTaskEndScheduler(). */ } } else { /* This line will only be reached if the kernel could not be started, because there was not enough FreeRTOS heap to create the idle task or the timer task. */ configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); } /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, meaning xIdleTaskHandle is not used anywhere else. */ ( void ) xIdleTaskHandle; } /*-----------------------------------------------------------*/ void rtos_sched_stop( void ) { /* Stop the scheduler interrupts and call the portable scheduler end routine so the original ISRs can be restored if necessary. The port layer must ensure interrupts enable bit is left in the correct state. */ portDISABLE_INTERRUPTS(); xSchedulerRunning = pdFALSE; vPortEndScheduler(); } /*----------------------------------------------------------*/ void rtos_suspend_all( void ) { /* A critical section is not required as the variable is of type int32_t. Please read Richard Barry's reply in the following link to a post in the FreeRTOS support forum before reporting this as a bug! - http://goo.gl/wu4acr */ ++uxSchedulerSuspended; } /*----------------------------------------------------------*/ #if ( configUSE_TICKLESS_IDLE != 0 ) static uint32_t prvGetExpectedIdleTime( void ) { uint32_t xReturn; uint32_t uxHigherPriorityReadyTasks = pdFALSE; /* uxHigherPriorityReadyTasks takes care of the case where configUSE_PREEMPTION is 0, so there may be tasks above the idle priority task that are in the Ready state, even though the idle task is running. */ #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) { if( uxTopReadyPriority > tskIDLE_PRIORITY ) { uxHigherPriorityReadyTasks = pdTRUE; } } #else { const uint32_t uxLeastSignificantBit = ( uint32_t ) 0x01; /* When port optimised task selection is used the uxTopReadyPriority variable is used as a bit map. If bits other than the least significant bit are set then there are tasks that have a priority above the idle priority that are in the Ready state. This takes care of the case where the co-operative scheduler is in use. */ if( uxTopReadyPriority > uxLeastSignificantBit ) { uxHigherPriorityReadyTasks = pdTRUE; } } #endif if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) { xReturn = 0; } else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) { /* There are other idle priority tasks in the ready state. If time slicing is used then the very next tick interrupt must be processed. */ xReturn = 0; } else if( uxHigherPriorityReadyTasks != pdFALSE ) { /* There are tasks in the Ready state that have a priority above the idle priority. This path can only be reached if configUSE_PREEMPTION is 0. */ xReturn = 0; } else { xReturn = xNextTaskUnblockTime - xTickCount; } return xReturn; } #endif /* configUSE_TICKLESS_IDLE */ /*----------------------------------------------------------*/ int32_t rtos_resume_all( void ) { TCB_t *pxTCB = NULL; int32_t xAlreadyYielded = pdFALSE; /* If uxSchedulerSuspended is zero then this function does not match a previous call to rtos_suspend_all(). */ configASSERT( uxSchedulerSuspended ); /* It is possible that an ISR caused a task to be removed from an event list while the scheduler was suspended. If this was the case then the removed task will have been added to the xPendingReadyList. Once the scheduler has been resumed it is safe to move all the pending ready tasks from this list into their appropriate ready list. */ taskENTER_CRITICAL(); { --uxSchedulerSuspended; if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { if( uxCurrentNumberOfTasks > ( uint32_t ) 0U ) { /* Move any readied tasks from the pending list into the appropriate ready list. */ while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) { pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); prvAddTaskToReadyList( pxTCB ); /* If the moved task has a priority higher than the current task then a yield must be performed. */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { xYieldPending = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } if( pxTCB != NULL ) { /* A task was unblocked while the scheduler was suspended, which may have prevented the next unblock time from being re-calculated, in which case re-calculate it now. Mainly important for low power tickless implementations, where this can prevent an unnecessary exit from low power state. */ prvResetNextTaskUnblockTime(); } /* If any ticks occurred while the scheduler was suspended then they should be processed now. This ensures the tick count does not slip, and that any delayed tasks are resumed at the correct time. */ { uint32_t uxPendedCounts = uxPendedTicks; /* Non-volatile copy. */ if( uxPendedCounts > ( uint32_t ) 0U ) { do { if( xTaskIncrementTick() != pdFALSE ) { xYieldPending = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } --uxPendedCounts; } while( uxPendedCounts > ( uint32_t ) 0U ); uxPendedTicks = 0; } else { mtCOVERAGE_TEST_MARKER(); } } if( xYieldPending != pdFALSE ) { #if( configUSE_PREEMPTION != 0 ) { xAlreadyYielded = pdTRUE; } #endif taskYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); return xAlreadyYielded; } /*-----------------------------------------------------------*/ uint32_t millis(void) { uint32_t xTicks; /* Critical section required if running on a 16 bit processor. */ portTICK_TYPE_ENTER_CRITICAL(); { xTicks = xTickCount; } portTICK_TYPE_EXIT_CRITICAL(); return xTicks * (configTICK_RATE_HZ / 1000); } uint64_t micros(void) { return vexSystemHighResTimeGet(); } /*-----------------------------------------------------------*/ uint32_t xTaskGetTickCountFromISR( void ) { uint32_t xReturn; uint32_t uxSavedInterruptStatus; /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are kept permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); { xReturn = xTickCount; } portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } /*-----------------------------------------------------------*/ uint32_t task_get_count(void) { /* A critical section is not required because the variables are of type int32_t. */ return uxCurrentNumberOfTasks; } /*-----------------------------------------------------------*/ char *task_get_name(task_t task) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { TCB_t *pxTCB; /* If null is passed in here then the name of the calling task is being queried. */ pxTCB = prvGetTCBFromHandle( task ); configASSERT( pxTCB ); return &( pxTCB->pcTaskName[ 0 ] ); } /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetHandle == 1 ) static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char name[] ) { TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; uint32_t x; char cNextChar; /* This function is called with the scheduler suspended. */ if( listCURRENT_LIST_LENGTH( pxList ) > ( uint32_t ) 0 ) { listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); do { listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /* Check each character in the name looking for a match or mismatch. */ for( x = ( uint32_t ) 0; x < ( uint32_t ) configMAX_TASK_NAME_LEN; x++ ) { cNextChar = pxNextTCB->pcTaskName[ x ]; if( cNextChar != name[ x ] ) { /* Characters didn't match. */ break; } else if( cNextChar == 0x00 ) { /* Both strings terminated, a match must have been found. */ pxReturn = pxNextTCB; break; } else { mtCOVERAGE_TEST_MARKER(); } } if( pxReturn != NULL ) { /* The handle has been found. */ break; } } while( pxNextTCB != pxFirstTCB ); } else { mtCOVERAGE_TEST_MARKER(); } return pxReturn; } #endif /* INCLUDE_xTaskGetHandle */ /*-----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetHandle == 1 ) task_t task_get_by_name(const char* name) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { uint32_t uxQueue = configMAX_PRIORITIES; TCB_t* pxTCB; /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ configASSERT( strlen( name ) < configMAX_TASK_NAME_LEN ); rtos_suspend_all(); { /* Search the ready lists. */ do { uxQueue--; pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), name ); if( pxTCB != NULL ) { /* Found the handle. */ break; } } while( uxQueue > ( uint32_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ /* Search the delayed lists. */ if( pxTCB == NULL ) { pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, name ); } if( pxTCB == NULL ) { pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, name ); } #if ( INCLUDE_vTaskSuspend == 1 ) { if( pxTCB == NULL ) { /* Search the suspended list. */ pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, name ); } } #endif #if( INCLUDE_vTaskDelete == 1 ) { if( pxTCB == NULL ) { /* Search the deleted list. */ pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, name ); } } #endif } ( void ) rtos_resume_all(); return ( task_t ) pxTCB; } #endif /* INCLUDE_xTaskGetHandle */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const uint32_t uxArraySize, uint32_t * const pulTotalRunTime ) { uint32_t uxTask = 0, uxQueue = configMAX_PRIORITIES; rtos_suspend_all(); { /* Is there a space in the array for each task in the system? */ if( uxArraySize >= uxCurrentNumberOfTasks ) { /* Fill in an TaskStatus_t structure with information on each task in the Ready state. */ do { uxQueue--; uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), E_TASK_STATE_READY ); } while( uxQueue > ( uint32_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ /* Fill in an TaskStatus_t structure with information on each task in the Blocked state. */ uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, E_TASK_STATE_BLOCKED ); uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, E_TASK_STATE_BLOCKED ); #if( INCLUDE_vTaskDelete == 1 ) { /* Fill in an TaskStatus_t structure with information on each task that has been deleted but not yet cleaned up. */ uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, E_TASK_STATE_DELETED ); } #endif #if ( INCLUDE_vTaskSuspend == 1 ) { /* Fill in an TaskStatus_t structure with information on each task in the Suspended state. */ uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, E_TASK_STATE_SUSPENDED ); } #endif #if ( configGENERATE_RUN_TIME_STATS == 1) { if( pulTotalRunTime != NULL ) { #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); #else *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); #endif } } #else { if( pulTotalRunTime != NULL ) { *pulTotalRunTime = 0; } } #endif } else { mtCOVERAGE_TEST_MARKER(); } } ( void ) rtos_resume_all(); return uxTask; } #endif /* configUSE_TRACE_FACILITY */ /*----------------------------------------------------------*/ #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) task_t xTaskGetIdleTaskHandle( void ) { /* If xTaskGetIdleTaskHandle() is called before the scheduler has been started, then xIdleTaskHandle will be NULL. */ configASSERT( ( xIdleTaskHandle != NULL ) ); return xIdleTaskHandle; } #endif /* INCLUDE_xTaskGetIdleTaskHandle */ /*----------------------------------------------------------*/ /* This conditional compilation should use inequality to 0, not equality to 1. This is to ensure vTaskStepTick() is available when user defined low power mode implementations require configUSE_TICKLESS_IDLE to be set to a value other than 1. */ #if ( configUSE_TICKLESS_IDLE != 0 ) void vTaskStepTick( const uint32_t xTicksToJump ) { /* Correct the tick count value after a period during which the tick was suppressed. Note this does *not* call the tick hook function for each stepped tick. */ configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); xTickCount += xTicksToJump; traceINCREASE_TICK_COUNT( xTicksToJump ); } #endif /* configUSE_TICKLESS_IDLE */ /*----------------------------------------------------------*/ #if ( INCLUDE_xTaskAbortDelay == 1 ) int32_t task_abort_delay(task_t task) { TCB_t *pxTCB = ( TCB_t * ) task; int32_t xReturn; configASSERT( pxTCB ); rtos_suspend_all(); { /* A task can only be prematurely removed from the Blocked state if it is actually in the Blocked state. */ if( task_get_state( task ) == E_TASK_STATE_BLOCKED ) { xReturn = pdPASS; /* Remove the reference to the task from the blocked list. An interrupt won't touch the xStateListItem because the scheduler is suspended. */ ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); /* Is the task waiting on an event also? If so remove it from the event list too. Interrupts can touch the event list item, even though the scheduler is suspended, so a critical section is used. */ taskENTER_CRITICAL(); { if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); pxTCB->ucDelayAborted = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); /* Place the unblocked task into the appropriate ready list. */ prvAddTaskToReadyList( pxTCB ); /* A task being unblocked cannot cause an immediate context switch if preemption is turned off. */ #if ( configUSE_PREEMPTION == 1 ) { /* Preemption is on, but a context switch should only be performed if the unblocked task has a priority that is equal to or higher than the currently executing task. */ if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) { /* Pend the yield to be performed when the scheduler is unsuspended. */ xYieldPending = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_PREEMPTION */ } else { xReturn = pdFAIL; } } ( void ) rtos_resume_all(); return xReturn; } #endif /* INCLUDE_xTaskAbortDelay */ /*----------------------------------------------------------*/ int32_t xTaskIncrementTick( void ) { TCB_t * pxTCB; uint32_t xItemValue; int32_t xSwitchRequired = pdFALSE; /* Called by the portable layer each time a tick interrupt occurs. Increments the tick then checks to see if the new tick value will cause any tasks to be unblocked. */ traceTASK_INCREMENT_TICK( xTickCount ); if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { /* Minor optimisation. The tick count cannot change in this block. */ const uint32_t xConstTickCount = xTickCount + ( uint32_t ) 1; /* Increment the RTOS tick, switching the delayed and overflowed delayed lists if it wraps to 0. */ xTickCount = xConstTickCount; if( xConstTickCount == ( uint32_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ { taskSWITCH_DELAYED_LISTS(); } else { mtCOVERAGE_TEST_MARKER(); } /* See if this tick has made a timeout expire. Tasks are stored in the queue in the order of their wake time - meaning once one task has been found whose block time has not expired there is no need to look any further down the list. */ if( xConstTickCount >= xNextTaskUnblockTime ) { for( ;; ) { if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) { /* The delayed list is empty. Set xNextTaskUnblockTime to the maximum possible value so it is extremely unlikely that the if( xTickCount >= xNextTaskUnblockTime ) test will pass next time through. */ xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ break; } else { /* The delayed list is not empty, get the value of the item at the head of the delayed list. This is the time at which the task at the head of the delayed list must be removed from the Blocked state. */ pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); if( xConstTickCount < xItemValue ) { /* It is not time to unblock this item yet, but the item value is the time at which the task at the head of the blocked list must be removed from the Blocked state - so record the item value in xNextTaskUnblockTime. */ xNextTaskUnblockTime = xItemValue; break; } else { mtCOVERAGE_TEST_MARKER(); } /* It is time to remove the item from the Blocked state. */ ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); /* Is the task waiting on an event also? If so remove it from the event list. */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); } /* Place the unblocked task into the appropriate ready list. */ prvAddTaskToReadyList( pxTCB ); /* A task being unblocked cannot cause an immediate context switch if preemption is turned off. */ #if ( configUSE_PREEMPTION == 1 ) { /* Preemption is on, but a context switch should only be performed if the unblocked task has a priority that is equal to or higher than the currently executing task. */ if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) { xSwitchRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_PREEMPTION */ } } } /* Tasks of equal priority to the currently running task will share processing time (time slice) if preemption is on, and the application writer has not explicitly turned time slicing off. */ #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) { if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( uint32_t ) 1 ) { xSwitchRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ #if ( configUSE_TICK_HOOK == 1 ) { /* Guard against the tick hook being called when the pended tick count is being unwound (when the scheduler is being unlocked). */ if( uxPendedTicks == ( uint32_t ) 0U ) { vApplicationTickHook(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_TICK_HOOK */ } else { ++uxPendedTicks; /* The tick hook gets called at regular intervals, even if the scheduler is locked. */ #if ( configUSE_TICK_HOOK == 1 ) { vApplicationTickHook(); } #endif } #if ( configUSE_PREEMPTION == 1 ) { if( xYieldPending != pdFALSE ) { xSwitchRequired = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_PREEMPTION */ return xSwitchRequired; } /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) void vTaskSetApplicationTaskTag( task_t task, TaskHookFunction_t pxHookFunction ) { TCB_t *xTCB; /* If task is NULL then it is the task hook of the calling task that is getting set. */ if( task == NULL ) { xTCB = ( TCB_t * ) pxCurrentTCB; } else { xTCB = ( TCB_t * ) task; } /* Save the hook function in the TCB. A critical section is required as the value can be accessed from an interrupt. */ taskENTER_CRITICAL(); xTCB->pxTaskTag = pxHookFunction; taskEXIT_CRITICAL(); } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) TaskHookFunction_t xTaskGetApplicationTaskTag( task_t task ) { TCB_t *xTCB; TaskHookFunction_t xReturn; /* If task is NULL then we are setting our own task hook. */ if( task == NULL ) { xTCB = ( TCB_t * ) pxCurrentTCB; } else { xTCB = ( TCB_t * ) task; } /* Save the hook function in the TCB. A critical section is required as the value can be accessed from an interrupt. */ taskENTER_CRITICAL(); { xReturn = xTCB->pxTaskTag; } taskEXIT_CRITICAL(); return xReturn; } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ #if ( configUSE_APPLICATION_TASK_TAG == 1 ) int32_t xTaskCallApplicationTaskHook( task_t task, void *pvParameter ) { TCB_t *xTCB; int32_t xReturn; /* If task is NULL then we are calling our own task hook. */ if( task == NULL ) { xTCB = ( TCB_t * ) pxCurrentTCB; } else { xTCB = ( TCB_t * ) task; } if( xTCB->pxTaskTag != NULL ) { xReturn = xTCB->pxTaskTag( pvParameter ); } else { xReturn = pdFAIL; } return xReturn; } #endif /* configUSE_APPLICATION_TASK_TAG */ /*-----------------------------------------------------------*/ void vTaskSwitchContext( void ) { if( uxSchedulerSuspended != ( uint32_t ) pdFALSE ) { /* The scheduler is currently suspended - do not allow a context switch. */ xYieldPending = pdTRUE; } else { xYieldPending = pdFALSE; traceTASK_SWITCHED_OUT(); #if ( configGENERATE_RUN_TIME_STATS == 1 ) { #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); #else ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); #endif /* Add the amount of time the task has been running to the accumulated time so far. The time the task started running was stored in ulTaskSwitchedInTime. Note that there is no overflow protection here so count values are only valid until the timer overflows. The guard against negative values is to protect against suspect run time stat counter implementations - which are provided by the application, not the kernel. */ if( ulTotalRunTime > ulTaskSwitchedInTime ) { pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); } else { mtCOVERAGE_TEST_MARKER(); } ulTaskSwitchedInTime = ulTotalRunTime; } #endif /* configGENERATE_RUN_TIME_STATS */ /* Check for stack overflow, if configured. */ taskCHECK_FOR_STACK_OVERFLOW(); /* Select a new task to run using either the generic C or port optimised asm code. */ taskSELECT_HIGHEST_PRIORITY_TASK(); traceTASK_SWITCHED_IN(); #if ( configUSE_NEWLIB_REENTRANT == 1 ) { /* Switch Newlib's _impure_ptr variable to point to the _reent structure specific to this task. */ _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); } #endif /* configUSE_NEWLIB_REENTRANT */ } } /*-----------------------------------------------------------*/ void vTaskPlaceOnEventList( List_t * const pxEventList, const uint32_t timeout ) { configASSERT( pxEventList ); /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ /* Place the event list item of the TCB in the appropriate event list. This is placed in the list in priority order so the highest priority task is the first to be woken by the event. The queue that contains the event list is locked, preventing simultaneous access from interrupts. */ vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); prvAddCurrentTaskToDelayedList( timeout, pdTRUE ); } /*-----------------------------------------------------------*/ void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const uint32_t xItemValue, const uint32_t timeout ) { configASSERT( pxEventList ); /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by the event groups implementation. */ configASSERT( uxSchedulerSuspended != 0 ); /* Store the item value in the event list item. It is safe to access the event list item here as interrupts won't access the event list item of a task that is not in the Blocked state. */ listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); /* Place the event list item of the TCB at the end of the appropriate event list. It is safe to access the event list here because it is part of an event group implementation - and interrupts don't access event groups directly (instead they access them indirectly by pending function calls to the task level). */ vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); prvAddCurrentTaskToDelayedList( timeout, pdTRUE ); } /*-----------------------------------------------------------*/ #if( configUSE_TIMERS == 1 ) void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, uint32_t timeout, const int32_t xWaitIndefinitely ) { configASSERT( pxEventList ); /* This function should not be called by application code hence the 'Restricted' in its name. It is not part of the public API. It is designed for use by kernel code, and has special calling requirements - it should be called with the scheduler suspended. */ /* Place the event list item of the TCB in the appropriate event list. In this case it is assume that this is the only task that is going to be waiting on this event list, so the faster vListInsertEnd() function can be used in place of vListInsert. */ vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); /* If the task should block indefinitely then set the block time to a value that will be recognised as an indefinite delay inside the prvAddCurrentTaskToDelayedList() function. */ if( xWaitIndefinitely != pdFALSE ) { timeout = portMAX_DELAY; } traceTASK_DELAY_UNTIL( ( xTickCount + timeout ) ); prvAddCurrentTaskToDelayedList( timeout, xWaitIndefinitely ); } #endif /* configUSE_TIMERS */ /*-----------------------------------------------------------*/ int32_t xTaskRemoveFromEventList( const List_t * const pxEventList ) { TCB_t *pxUnblockedTCB; int32_t xReturn; /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be called from a critical section within an ISR. */ /* The event list is sorted in priority order, so the first in the list can be removed as it is known to be the highest priority. Remove the TCB from the delayed list, and add it to the ready list. If an event is for a queue that is locked then this function will never get called - the lock count on the queue will get modified instead. This means exclusive access to the event list is guaranteed here. This function assumes that a check has already been made to ensure that pxEventList is not empty. */ pxUnblockedTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); configASSERT( pxUnblockedTCB ); ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); prvAddTaskToReadyList( pxUnblockedTCB ); } else { /* The delayed and ready lists cannot be accessed, so hold this task pending until the scheduler is resumed. */ vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); } if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) { /* Return true if the task removed from the event list has a higher priority than the calling task. This allows the calling task to know if it should force a context switch now. */ xReturn = pdTRUE; /* Mark that a yield is pending in case the user is not using the "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ xYieldPending = pdTRUE; } else { xReturn = pdFALSE; } #if( configUSE_TICKLESS_IDLE != 0 ) { /* If a task is blocked on a kernel object then xNextTaskUnblockTime might be set to the blocked task's time out time. If the task is unblocked for a reason other than a timeout xNextTaskUnblockTime is normally left unchanged, because it is automatically reset to a new value when the tick count equals xNextTaskUnblockTime. However if tickless idling is used it might be more important to enter sleep mode at the earliest possible time - so reset xNextTaskUnblockTime here to ensure it is updated at the earliest possible time. */ prvResetNextTaskUnblockTime(); } #endif return xReturn; } /*-----------------------------------------------------------*/ void vTaskRemoveFromUnorderedEventList( list_item_t * pxEventListItem, const uint32_t xItemValue ) { TCB_t *pxUnblockedTCB; /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by the event flags implementation. */ configASSERT( uxSchedulerSuspended != pdFALSE ); /* Store the new item value in the event list. */ listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); /* Remove the event list form the event flag. Interrupts do not access event flags. */ pxUnblockedTCB = ( TCB_t * ) listGET_LIST_ITEM_OWNER( pxEventListItem ); configASSERT( pxUnblockedTCB ); ( void ) uxListRemove( pxEventListItem ); /* Remove the task from the delayed list and add it to the ready list. The scheduler is suspended so interrupts will not be accessing the ready lists. */ ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); prvAddTaskToReadyList( pxUnblockedTCB ); if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) { /* The unblocked task has a priority above that of the calling task, so a context switch is required. This function is called with the scheduler suspended so xYieldPending is set so the context switch occurs immediately that the scheduler is resumed (unsuspended). */ xYieldPending = pdTRUE; } } /*-----------------------------------------------------------*/ void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) { configASSERT( pxTimeOut ); taskENTER_CRITICAL(); { pxTimeOut->xOverflowCount = xNumOfOverflows; pxTimeOut->xTimeOnEntering = xTickCount; } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) { /* For internal use only as it does not use a critical section. */ pxTimeOut->xOverflowCount = xNumOfOverflows; pxTimeOut->xTimeOnEntering = xTickCount; } /*-----------------------------------------------------------*/ int32_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, uint32_t * const pxTicksToWait ) { int32_t xReturn; configASSERT( pxTimeOut ); configASSERT( pxTicksToWait ); taskENTER_CRITICAL(); { /* Minor optimisation. The tick count cannot change in this block. */ const uint32_t xConstTickCount = xTickCount; const uint32_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; #if( INCLUDE_xTaskAbortDelay == 1 ) if( pxCurrentTCB->ucDelayAborted != pdFALSE ) { /* The delay was aborted, which is not the same as a time out, but has the same result. */ pxCurrentTCB->ucDelayAborted = pdFALSE; xReturn = pdTRUE; } else #endif #if ( INCLUDE_vTaskSuspend == 1 ) if( *pxTicksToWait == portMAX_DELAY ) { /* If INCLUDE_vTaskSuspend is set to 1 and the block time specified is the maximum block time then the task should block indefinitely, and therefore never time out. */ xReturn = pdFALSE; } else #endif if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ { /* The tick count is greater than the time at which vTaskSetTimeout() was called, but has also overflowed since vTaskSetTimeOut() was called. It must have wrapped all the way around and gone past again. This passed since vTaskSetTimeout() was called. */ xReturn = pdTRUE; } else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ { /* Not a genuine timeout. Adjust parameters for time remaining. */ *pxTicksToWait -= xElapsedTime; vTaskInternalSetTimeOutState( pxTimeOut ); xReturn = pdFALSE; } else { *pxTicksToWait = 0; xReturn = pdTRUE; } } taskEXIT_CRITICAL(); return xReturn; } /*-----------------------------------------------------------*/ void vTaskMissedYield( void ) { xYieldPending = pdTRUE; } /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxTaskGetTaskNumber( task_t task ) { uint32_t uxReturn; TCB_t *pxTCB; if( task != NULL ) { pxTCB = ( TCB_t * ) task; uxReturn = pxTCB->uxTaskNumber; } else { uxReturn = 0U; } return uxReturn; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) void vTaskSetTaskNumber( task_t task, const uint32_t uxHandle ) { TCB_t *pxTCB; if( task != NULL ) { pxTCB = ( TCB_t * ) task; pxTCB->uxTaskNumber = uxHandle; } } #endif /* configUSE_TRACE_FACILITY */ /* * ----------------------------------------------------------- * The Idle task. * ---------------------------------------------------------- * * The portTASK_FUNCTION() macro is used to allow port/compiler specific * language extensions. The equivalent prototype for this function is: * * void prvIdleTask( void *pvParameters ); * */ static portTASK_FUNCTION( prvIdleTask, pvParameters ) { /* Stop warnings. */ ( void ) pvParameters; /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE SCHEDULER IS STARTED. **/ /* In case a task that has a secure context deletes itself, in which case the idle task is responsible for deleting the task's secure context, if any. */ portTASK_CALLS_SECURE_FUNCTIONS(); for( ;; ) { /* See if any tasks have deleted themselves - if so then the idle task is responsible for freeing the deleted task's TCB and stack. */ prvCheckTasksWaitingTermination(); #if ( configUSE_PREEMPTION == 0 ) { /* If we are not using preemption we keep forcing a task switch to see if any other task has become available. If we are using preemption we don't need to do this as any task becoming available will automatically get the processor anyway. */ taskYIELD(); } #endif /* configUSE_PREEMPTION */ #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) { /* When using preemption tasks of equal priority will be timesliced. If a task that is sharing the idle priority is ready to run then the idle task should yield before the end of the timeslice. A critical region is not required here as we are just reading from the list, and an occasional incorrect value will not matter. If the ready list at the idle priority contains more than one task then a task other than the idle task is ready to execute. */ if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( uint32_t ) 1 ) { taskYIELD(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ #if ( configUSE_IDLE_HOOK == 1 ) { extern void vApplicationIdleHook( void ); /* Call the user defined function from within the idle task. This allows the application designer to add background functionality without the overhead of a separate task. NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, CALL A FUNCTION THAT MIGHT BLOCK. */ vApplicationIdleHook(); } #endif /* configUSE_IDLE_HOOK */ /* This conditional compilation should use inequality to 0, not equality to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when user defined low power mode implementations require configUSE_TICKLESS_IDLE to be set to a value other than 1. */ #if ( configUSE_TICKLESS_IDLE != 0 ) { uint32_t xExpectedIdleTime; /* It is not desirable to suspend then resume the scheduler on each iteration of the idle task. Therefore, a preliminary test of the expected idle time is performed without the scheduler suspended. The result here is not necessarily valid. */ xExpectedIdleTime = prvGetExpectedIdleTime(); if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) { rtos_suspend_all(); { /* Now the scheduler is suspended, the expected idle time can be sampled again, and this time its value can be used. */ configASSERT( xNextTaskUnblockTime >= xTickCount ); xExpectedIdleTime = prvGetExpectedIdleTime(); /* Define the following macro to set xExpectedIdleTime to 0 if the application does not want portSUPPRESS_TICKS_AND_SLEEP() to be called. */ configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) { traceLOW_POWER_IDLE_BEGIN(); portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); traceLOW_POWER_IDLE_END(); } else { mtCOVERAGE_TEST_MARKER(); } } ( void ) rtos_resume_all(); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_TICKLESS_IDLE */ } } /*-----------------------------------------------------------*/ #if( configUSE_TICKLESS_IDLE != 0 ) eSleepModeStatus eTaskConfirmSleepModeStatus( void ) { /* The idle task exists in addition to the application tasks. */ const uint32_t uxNonApplicationTasks = 1; eSleepModeStatus eReturn = eStandardSleep; if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) { /* A task was made ready while the scheduler was suspended. */ eReturn = eAbortSleep; } else if( xYieldPending != pdFALSE ) { /* A yield was pended while the scheduler was suspended. */ eReturn = eAbortSleep; } else { /* If all the tasks are in the suspended list (which might mean they have an infinite block time rather than actually being suspended) then it is safe to turn all clocks off and just wait for external interrupts. */ if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) { eReturn = eNoTasksWaitingTimeout; } else { mtCOVERAGE_TEST_MARKER(); } } return eReturn; } #endif /* configUSE_TICKLESS_IDLE */ /*-----------------------------------------------------------*/ #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) void vTaskSetThreadLocalStoragePointer( task_t xTaskToSet, int32_t xIndex, void *pvValue ) { TCB_t *pxTCB; if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) { pxTCB = prvGetTCBFromHandle( xTaskToSet ); pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; } } #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ /*-----------------------------------------------------------*/ #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) void *pvTaskGetThreadLocalStoragePointer( task_t xTaskToQuery, int32_t xIndex ) { void *pvReturn = NULL; TCB_t *pxTCB; if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) { pxTCB = prvGetTCBFromHandle( xTaskToQuery ); pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; } else { pvReturn = NULL; } return pvReturn; } #endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ /*-----------------------------------------------------------*/ static void prvInitialiseTaskLists( void ) { uint32_t uxPriority; for( uxPriority = ( uint32_t ) 0U; uxPriority < ( uint32_t ) configMAX_PRIORITIES; uxPriority++ ) { vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); } vListInitialise( &xDelayedTaskList1 ); vListInitialise( &xDelayedTaskList2 ); vListInitialise( &xPendingReadyList ); #if ( INCLUDE_vTaskDelete == 1 ) { vListInitialise( &xTasksWaitingTermination ); } #endif /* INCLUDE_vTaskDelete */ #if ( INCLUDE_vTaskSuspend == 1 ) { vListInitialise( &xSuspendedTaskList ); } #endif /* INCLUDE_vTaskSuspend */ /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList using list2. */ pxDelayedTaskList = &xDelayedTaskList1; pxOverflowDelayedTaskList = &xDelayedTaskList2; } /*-----------------------------------------------------------*/ static void prvCheckTasksWaitingTermination( void ) { /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ #if ( INCLUDE_vTaskDelete == 1 ) { TCB_t *pxTCB; /* uxDeletedTasksWaitingCleanUp is used to prevent rtos_suspend_all() being called too often in the idle task. */ while( uxDeletedTasksWaitingCleanUp > ( uint32_t ) 0U ) { taskENTER_CRITICAL(); { pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); --uxCurrentNumberOfTasks; --uxDeletedTasksWaitingCleanUp; } taskEXIT_CRITICAL(); prvDeleteTCB( pxTCB ); } } #endif /* INCLUDE_vTaskDelete */ } /*-----------------------------------------------------------*/ #if( configUSE_TRACE_FACILITY == 1 ) void vTaskGetInfo( task_t task, TaskStatus_t *pxTaskStatus, int32_t xGetFreeStackSpace, task_state_e_t eState ) { TCB_t *pxTCB; /* task is NULL then get the state of the calling task. */ pxTCB = prvGetTCBFromHandle( task ); pxTaskStatus->xHandle = ( task_t ) pxTCB; pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; pxTaskStatus->pxStackBase = pxTCB->pxStack; pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; #if ( configUSE_MUTEXES == 1 ) { pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; } #else { pxTaskStatus->uxBasePriority = 0; } #endif #if ( configGENERATE_RUN_TIME_STATS == 1 ) { pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; } #else { pxTaskStatus->ulRunTimeCounter = 0; } #endif /* Obtaining the task state is a little fiddly, so is only done if the value of eState passed into this function is E_TASK_STATE_INVALID - otherwise the state is just set to whatever is passed in. */ if( eState != E_TASK_STATE_INVALID ) { if( pxTCB == pxCurrentTCB ) { pxTaskStatus->eCurrentState = E_TASK_STATE_RUNNING; } else { pxTaskStatus->eCurrentState = eState; #if ( INCLUDE_vTaskSuspend == 1 ) { /* If the task is in the suspended list then there is a chance it is actually just blocked indefinitely - so really it should be reported as being in the Blocked state. */ if( eState == E_TASK_STATE_SUSPENDED ) { rtos_suspend_all(); { if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { pxTaskStatus->eCurrentState = E_TASK_STATE_BLOCKED; } } ( void ) rtos_resume_all(); } } #endif /* INCLUDE_vTaskSuspend */ } } else { pxTaskStatus->eCurrentState = task_get_state( pxTCB ); } /* Obtaining the stack space takes some time, so the xGetFreeStackSpace parameter is provided to allow it to be skipped. */ if( xGetFreeStackSpace != pdFALSE ) { #if ( portSTACK_GROWTH > 0 ) { pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); } #else { pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); } #endif } else { pxTaskStatus->usStackHighWaterMark = 0; } } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) static uint32_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, task_state_e_t eState ) { configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; uint32_t uxTask = 0; if( listCURRENT_LIST_LENGTH( pxList ) > ( uint32_t ) 0 ) { listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /* Populate an TaskStatus_t structure within the pxTaskStatusArray array for each task that is referenced from pxList. See the definition of TaskStatus_t in task.h for the meaning of each TaskStatus_t structure member. */ do { listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); vTaskGetInfo( ( task_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); uxTask++; } while( pxNextTCB != pxFirstTCB ); } else { mtCOVERAGE_TEST_MARKER(); } return uxTask; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) static uint16_t prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) { uint32_t ulCount = 0U; while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) { pucStackByte -= portSTACK_GROWTH; ulCount++; } ulCount /= ( uint32_t ) sizeof( task_stack_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ return ( uint16_t ) ulCount; } #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) uint32_t uxTaskGetStackHighWaterMark( task_t task ) { TCB_t *pxTCB; uint8_t *pucEndOfStack; uint32_t uxReturn; pxTCB = prvGetTCBFromHandle( task ); #if portSTACK_GROWTH < 0 { pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; } #else { pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; } #endif uxReturn = ( uint32_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); return uxReturn; } #endif /* INCLUDE_uxTaskGetStackHighWaterMark */ /*-----------------------------------------------------------*/ #if ( INCLUDE_vTaskDelete == 1 ) static void prvDeleteTCB( TCB_t *pxTCB ) { /* This call is required specifically for the TriCore port. It must be above the kfree() calls. The call is also used by ports/demos that want to allocate and clean RAM statically. */ portCLEAN_UP_TCB( pxTCB ); /* Free up the memory allocated by the scheduler for the task. It is up to the task to free any memory allocated at the application level. */ #if ( configUSE_NEWLIB_REENTRANT == 1 ) { _reclaim_reent( &( pxTCB->xNewLib_reent ) ); } #endif /* configUSE_NEWLIB_REENTRANT */ #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 )) { /* The task can only have been allocated dynamically - free both the stack and TCB. */ kfree( pxTCB->pxStack ); kfree( pxTCB ); } #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ { /* The task could have been allocated statically or dynamically, so check what was statically allocated before trying to free the memory. */ if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) { /* Both the stack and TCB were allocated dynamically, so both must be freed. */ kfree( pxTCB->pxStack ); kfree( pxTCB ); } else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) { /* Only the stack was statically allocated, so the TCB is the only memory that must be freed. */ kfree( pxTCB ); } else { /* Neither the stack nor the TCB were allocated dynamically, so nothing needs to be freed. */ configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); mtCOVERAGE_TEST_MARKER(); } } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ } #endif /* INCLUDE_vTaskDelete */ /*-----------------------------------------------------------*/ static void prvResetNextTaskUnblockTime( void ) { TCB_t *pxTCB; if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) { /* The new current delayed list is empty. Set xNextTaskUnblockTime to the maximum possible value so it is extremely unlikely that the if( xTickCount >= xNextTaskUnblockTime ) test will pass until there is an item in the delayed list. */ xNextTaskUnblockTime = portMAX_DELAY; } else { /* The new current delayed list is not empty, get the value of the item at the head of the delayed list. This is the time at which the task at the head of the delayed list should be removed from the Blocked state. */ ( pxTCB ) = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); } } /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) task_t task_get_current( void ) { task_t xReturn; /* A critical section is not required as this is not called from an interrupt and the current TCB will always be the same for any individual execution thread. */ xReturn = pxCurrentTCB; return xReturn; } #endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) int32_t xTaskGetSchedulerState( void ) { int32_t xReturn; if( xSchedulerRunning == pdFALSE ) { xReturn = taskSCHEDULER_NOT_STARTED; } else { if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { xReturn = taskSCHEDULER_RUNNING; } else { xReturn = taskSCHEDULER_SUSPENDED; } } return xReturn; } #endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) int32_t xTaskPriorityInherit( task_t const pxMutexHolder ) { TCB_t * const pxMutexHolderTCB = ( TCB_t * ) pxMutexHolder; int32_t xReturn = pdFALSE; /* If the mutex was given back by an interrupt while the queue was locked then the mutex holder might now be NULL. _RB_ Is this still needed as interrupts can no longer use mutexes? */ if( pxMutexHolder != NULL ) { /* If the holder of the mutex has a priority below the priority of the task attempting to obtain the mutex then it will temporarily inherit the priority of the task attempting to obtain the mutex. */ if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) { /* Adjust the mutex holder state to account for its new priority. Only reset the event list item value if the value is not being used for anything else. */ if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) { listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ } else { mtCOVERAGE_TEST_MARKER(); } /* If the task being modified is in the ready state it will need to be moved into a new list. */ if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) { if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { taskRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); } /* Inherit the priority before being moved into the new list. */ pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; prvAddTaskToReadyList( pxMutexHolderTCB ); } else { /* Just inherit the priority. */ pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; } traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); /* Inheritance occurred. */ xReturn = pdTRUE; } else { if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) { /* The base priority of the mutex holder is lower than the priority of the task attempting to take the mutex, but the current priority of the mutex holder is not lower than the priority of the task attempting to take the mutex. Therefore the mutex holder must have already inherited a priority, but inheritance would have occurred if that had not been the case. */ xReturn = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } } else { mtCOVERAGE_TEST_MARKER(); } return xReturn; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) int32_t xTaskPriorityDisinherit( task_t const pxMutexHolder ) { TCB_t * const pxTCB = ( TCB_t * ) pxMutexHolder; int32_t xReturn = pdFALSE; if( pxMutexHolder != NULL ) { /* A task can only have an inherited priority if it holds the mutex. If the mutex is held by a task then it cannot be given from an interrupt, and if a mutex is given by the holding task then it must be the running state task. */ configASSERT( pxTCB == pxCurrentTCB ); configASSERT( pxTCB->uxMutexesHeld ); ( pxTCB->uxMutexesHeld )--; /* Has the holder of the mutex inherited the priority of another task? */ if( pxTCB->uxPriority != pxTCB->uxBasePriority ) { /* Only disinherit if no other mutexes are held. */ if( pxTCB->uxMutexesHeld == ( uint32_t ) 0 ) { /* A task can only have an inherited priority if it holds the mutex. If the mutex is held by a task then it cannot be given from an interrupt, and if a mutex is given by the holding task then it must be the running state task. Remove the holding task from the ready list. */ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { taskRESET_READY_PRIORITY( pxTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); } /* Disinherit the priority before adding the task into the new ready list. */ traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); pxTCB->uxPriority = pxTCB->uxBasePriority; /* Reset the event list item value. It cannot be in use for any other purpose if this task is running, and it must be running to give back the mutex. */ listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ prvAddTaskToReadyList( pxTCB ); /* Return true to indicate that a context switch is required. This is only actually required in the corner case whereby multiple mutexes were held and the mutexes were given back in an order different to that in which they were taken. If a context switch did not occur when the first mutex was returned, even if a task was waiting on it, then a context switch should occur when the last mutex is returned whether a task is waiting on it or not. */ xReturn = pdTRUE; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } return xReturn; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) void vTaskPriorityDisinheritAfterTimeout( task_t const pxMutexHolder, uint32_t uxHighestPriorityWaitingTask ) { TCB_t * const pxTCB = ( TCB_t * ) pxMutexHolder; uint32_t uxPriorityUsedOnEntry, uxPriorityToUse; const uint32_t uxOnlyOneMutexHeld = ( uint32_t ) 1; if( pxMutexHolder != NULL ) { /* If pxMutexHolder is not NULL then the holder must hold at least one mutex. */ configASSERT( pxTCB->uxMutexesHeld ); /* Determine the priority to which the priority of the task that holds the mutex should be set. This will be the greater of the holding task's base priority and the priority of the highest priority task that is waiting to obtain the mutex. */ if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) { uxPriorityToUse = uxHighestPriorityWaitingTask; } else { uxPriorityToUse = pxTCB->uxBasePriority; } /* Does the priority need to change? */ if( pxTCB->uxPriority != uxPriorityToUse ) { /* Only disinherit if no other mutexes are held. This is a simplification in the priority inheritance implementation. If the task that holds the mutex is also holding other mutexes then the other mutexes may have caused the priority inheritance. */ if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) { /* If a task has timed out because it already holds the mutex it was trying to obtain then it cannot of inherited its own priority. */ configASSERT( pxTCB != pxCurrentTCB ); /* Disinherit the priority, remembering the previous priority to facilitate determining the subject task's state. */ traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); uxPriorityUsedOnEntry = pxTCB->uxPriority; pxTCB->uxPriority = uxPriorityToUse; /* Only reset the event list item value if the value is not being used for anything else. */ if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) { listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ } else { mtCOVERAGE_TEST_MARKER(); } /* If the running task is not the task that holds the mutex then the task that holds the mutex could be in either the Ready, Blocked or Suspended states. Only remove the task from its current state list if it is in the Ready state as the task's priority is going to change and there is one Ready list per priority. */ if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) { if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { taskRESET_READY_PRIORITY( pxTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); } prvAddTaskToReadyList( pxTCB ); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) void vTaskEnterCritical( void ) { portDISABLE_INTERRUPTS(); if( xSchedulerRunning != pdFALSE ) { ( pxCurrentTCB->uxCriticalNesting )++; /* This is not the interrupt safe version of the enter critical function so assert() if it is being called from an interrupt context. Only API functions that end in "FromISR" can be used in an interrupt. Only assert if the critical nesting count is 1 to protect against recursive calls if the assert function also uses a critical section. */ if( pxCurrentTCB->uxCriticalNesting == 1 ) { portASSERT_IF_IN_ISR(); } } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ #if ( portCRITICAL_NESTING_IN_TCB == 1 ) void vTaskExitCritical( void ) { if( xSchedulerRunning != pdFALSE ) { if( pxCurrentTCB->uxCriticalNesting > 0U ) { ( pxCurrentTCB->uxCriticalNesting )--; if( pxCurrentTCB->uxCriticalNesting == 0U ) { portENABLE_INTERRUPTS(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) { size_t x; /* Start by copying the entire string. */ strcpy( pcBuffer, pcTaskName ); /* Pad the end of the string with spaces to ensure columns line up when printed out. */ for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) { pcBuffer[ x ] = ' '; } /* Terminate. */ pcBuffer[ x ] = 0x00; /* Return the new end of string. */ return &( pcBuffer[ x ] ); } #endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ /*-----------------------------------------------------------*/ #if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) void vTaskList( char * pcWriteBuffer ) { TaskStatus_t *pxTaskStatusArray; volatile uint32_t uxArraySize, x; char cStatus; /* * PLEASE NOTE: * * This function is provided for convenience only, and is used by many * of the demo applications. Do not consider it to be part of the * scheduler. * * vTaskList() calls uxTaskGetSystemState(), then formats part of the * uxTaskGetSystemState() output into a human readable table that * displays task names, states and stack usage. * * vTaskList() has a dependency on the sprintf() C library function that * might bloat the code size, use a lot of stack, and provide different * results on different platforms. An alternative, tiny, third party, * and limited functionality implementation of sprintf() is provided in * many of the FreeRTOS/Demo sub-directories in a file called * printf-stdarg.c (note printf-stdarg.c does not provide a full * snprintf() implementation!). * * It is recommended that production systems call uxTaskGetSystemState() * directly to get access to raw stats data, rather than indirectly * through a call to vTaskList(). */ /* Make sure the write buffer does not contain a string. */ *pcWriteBuffer = 0x00; /* Take a snapshot of the number of tasks in case it changes while this function is executing. */ uxArraySize = uxCurrentNumberOfTasks; /* Allocate an array index for each task. NOTE! if configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then kmalloc() will equate to NULL. */ pxTaskStatusArray = kmalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); if( pxTaskStatusArray != NULL ) { /* Generate the (binary) data. */ uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); /* Create a human readable table from the binary data. */ for( x = 0; x < uxArraySize; x++ ) { switch( pxTaskStatusArray[ x ].eCurrentState ) { case E_TASK_STATE_RUNNING: cStatus = tskRUNNING_CHAR; break; case E_TASK_STATE_READY: cStatus = tskREADY_CHAR; break; case E_TASK_STATE_BLOCKED: cStatus = tskBLOCKED_CHAR; break; case E_TASK_STATE_SUSPENDED: cStatus = tskSUSPENDED_CHAR; break; case E_TASK_STATE_DELETED: cStatus = tskDELETED_CHAR; break; default: /* Should not get here, but it is included to prevent static checking errors. */ cStatus = 0x00; break; } /* Write the task name to the string, padding with spaces so it can be printed in tabular form more easily. */ pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); /* Write the rest of the string. */ sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); pcWriteBuffer += strlen( pcWriteBuffer ); } /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION is 0 then kfree() will be #defined to nothing. */ kfree( pxTaskStatusArray ); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ /*----------------------------------------------------------*/ #if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) void vTaskGetRunTimeStats( char *pcWriteBuffer ) { TaskStatus_t *pxTaskStatusArray; volatile uint32_t uxArraySize, x; uint32_t ulTotalTime, ulStatsAsPercentage; #if( configUSE_TRACE_FACILITY != 1 ) { #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). } #endif /* * PLEASE NOTE: * * This function is provided for convenience only, and is used by many * of the demo applications. Do not consider it to be part of the * scheduler. * * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part * of the uxTaskGetSystemState() output into a human readable table that * displays the amount of time each task has spent in the Running state * in both absolute and percentage terms. * * vTaskGetRunTimeStats() has a dependency on the sprintf() C library * function that might bloat the code size, use a lot of stack, and * provide different results on different platforms. An alternative, * tiny, third party, and limited functionality implementation of * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in * a file called printf-stdarg.c (note printf-stdarg.c does not provide * a full snprintf() implementation!). * * It is recommended that production systems call uxTaskGetSystemState() * directly to get access to raw stats data, rather than indirectly * through a call to vTaskGetRunTimeStats(). */ /* Make sure the write buffer does not contain a string. */ *pcWriteBuffer = 0x00; /* Take a snapshot of the number of tasks in case it changes while this function is executing. */ uxArraySize = uxCurrentNumberOfTasks; /* Allocate an array index for each task. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then kmalloc() will equate to NULL. */ pxTaskStatusArray = kmalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); if( pxTaskStatusArray != NULL ) { /* Generate the (binary) data. */ uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); /* For percentage calculations. */ ulTotalTime /= 100UL; /* Avoid divide by zero errors. */ if( ulTotalTime > 0 ) { /* Create a human readable table from the binary data. */ for( x = 0; x < uxArraySize; x++ ) { /* What percentage of the total run time has the task used? This will always be rounded down to the nearest integer. ulTotalRunTimeDiv100 has already been divided by 100. */ ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; /* Write the task name to the string, padding with spaces so it can be printed in tabular form more easily. */ pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); if( ulStatsAsPercentage > 0UL ) { #ifdef portLU_PRINTF_SPECIFIER_REQUIRED { sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); } #else { /* sizeof( int ) == sizeof( long ) so a smaller printf() library can be used. */ sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); } #endif } else { /* If the percentage is zero here then the task has consumed less than 1% of the total run time. */ #ifdef portLU_PRINTF_SPECIFIER_REQUIRED { sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); } #else { /* sizeof( int ) == sizeof( long ) so a smaller printf() library can be used. */ sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); } #endif } pcWriteBuffer += strlen( pcWriteBuffer ); } } else { mtCOVERAGE_TEST_MARKER(); } /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION is 0 then kfree() will be #defined to nothing. */ kfree( pxTaskStatusArray ); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ /*-----------------------------------------------------------*/ uint32_t uxTaskResetEventItemValue( void ) { uint32_t uxReturn; uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); /* Reset the event list item to its normal value - so it can be used with queues and semaphores. */ listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( uint32_t ) configMAX_PRIORITIES - ( uint32_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ return uxReturn; } /*-----------------------------------------------------------*/ #if ( configUSE_MUTEXES == 1 ) void *pvTaskIncrementMutexHeldCount( void ) { /* If mutex_create() is called before any tasks have been created then pxCurrentTCB will be NULL. */ if( pxCurrentTCB != NULL ) { ( pxCurrentTCB->uxMutexesHeld )++; } return pxCurrentTCB; } #endif /* configUSE_MUTEXES */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) uint32_t task_notify_take(bool clear_on_exit, uint32_t timeout) { uint32_t ulReturn; taskENTER_CRITICAL(); { /* Only block if the notification count is not already non-zero. */ if( pxCurrentTCB->ulNotifiedValue == 0UL ) { /* Mark this task as waiting for a notification. */ pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; if( timeout > ( uint32_t ) 0 ) { prvAddCurrentTaskToDelayedList( timeout, pdTRUE ); traceTASK_NOTIFY_TAKE_BLOCK(); /* All ports are written to allow a yield in a critical section (some will yield immediately, others wait until the critical section exits) - but it is not something that application code should ever do. */ portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); taskENTER_CRITICAL(); { traceTASK_NOTIFY_TAKE(); ulReturn = pxCurrentTCB->ulNotifiedValue; if( ulReturn != 0UL ) { if( clear_on_exit != pdFALSE ) { pxCurrentTCB->ulNotifiedValue = 0UL; } else { pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; } } else { mtCOVERAGE_TEST_MARKER(); } pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; } taskEXIT_CRITICAL(); return ulReturn; } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) int32_t task_notify_wait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, uint32_t timeout ) { int32_t xReturn; taskENTER_CRITICAL(); { /* Only block if a notification is not already pending. */ if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) { /* Clear bits in the task's notification value as bits may get set by the notifying task or interrupt. This can be used to clear the value to zero. */ pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; /* Mark this task as waiting for a notification. */ pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; if( timeout > ( uint32_t ) 0 ) { prvAddCurrentTaskToDelayedList( timeout, pdTRUE ); traceTASK_NOTIFY_WAIT_BLOCK(); /* All ports are written to allow a yield in a critical section (some will yield immediately, others wait until the critical section exits) - but it is not something that application code should ever do. */ portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); taskENTER_CRITICAL(); { traceTASK_NOTIFY_WAIT(); if( pulNotificationValue != NULL ) { /* Output the current notification value, which may or may not have changed. */ *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; } /* If ucNotifyValue is set then either the task never entered the blocked state (because a notification was already pending) or the task unblocked because of a notification. Otherwise the task unblocked because of a timeout. */ if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) { /* A notification was not received. */ xReturn = pdFALSE; } else { /* A notification was already pending or a notification was received while the task was waiting. */ pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; xReturn = pdTRUE; } pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; } taskEXIT_CRITICAL(); return xReturn; } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) int32_t task_notify_ext(task_t task, uint32_t value, notify_action_e_t action, uint32_t* prev_value) { TCB_t * pxTCB; int32_t xReturn = pdPASS; uint8_t ucOriginalNotifyState; configASSERT( task ); pxTCB = ( TCB_t * ) task; taskENTER_CRITICAL(); { if( prev_value != NULL ) { *prev_value = pxTCB->ulNotifiedValue; } ucOriginalNotifyState = pxTCB->ucNotifyState; pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; switch( action ) { case E_NOTIFY_ACTION_BITS : pxTCB->ulNotifiedValue |= value; break; case E_NOTIFY_ACTION_INCR : ( pxTCB->ulNotifiedValue )++; break; case E_NOTIFY_ACTION_OWRITE : pxTCB->ulNotifiedValue = value; break; case E_NOTIFY_ACTION_NO_OWRITE : if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) { pxTCB->ulNotifiedValue = value; } else { /* The value could not be written to the task. */ xReturn = pdFAIL; } break; case E_NOTIFY_ACTION_NONE: /* The task is being notified without its notify value being updated. */ break; } traceTASK_NOTIFY(); /* If the task is in the blocked state specifically to wait for a notification then unblock it now. */ if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) { ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); prvAddTaskToReadyList( pxTCB ); /* The task should not have been on an event list. */ configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); #if( configUSE_TICKLESS_IDLE != 0 ) { /* If a task is blocked waiting for a notification then xNextTaskUnblockTime might be set to the blocked task's time out time. If the task is unblocked for a reason other than a timeout xNextTaskUnblockTime is normally left unchanged, because it will automatically get reset to a new value when the tick count equals xNextTaskUnblockTime. However if tickless idling is used it might be more important to enter sleep mode at the earliest possible time - so reset xNextTaskUnblockTime here to ensure it is updated at the earliest possible time. */ prvResetNextTaskUnblockTime(); } #endif if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) { /* The notified task has a priority above the currently executing task so a yield is required. */ taskYIELD_IF_USING_PREEMPTION(); } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); return xReturn; } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) int32_t xTaskGenericNotifyFromISR( task_t task, uint32_t value, notify_action_e_t action, uint32_t *prev_value, int32_t *pxHigherPriorityTaskWoken ) { TCB_t * pxTCB; uint8_t ucOriginalNotifyState; int32_t xReturn = pdPASS; uint32_t uxSavedInterruptStatus; configASSERT( task ); /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are keep permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); pxTCB = ( TCB_t * ) task; uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { if( prev_value != NULL ) { *prev_value = pxTCB->ulNotifiedValue; } ucOriginalNotifyState = pxTCB->ucNotifyState; pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; switch( action ) { case E_NOTIFY_ACTION_BITS : pxTCB->ulNotifiedValue |= value; break; case E_NOTIFY_ACTION_INCR : ( pxTCB->ulNotifiedValue )++; break; case E_NOTIFY_ACTION_OWRITE : pxTCB->ulNotifiedValue = value; break; case E_NOTIFY_ACTION_NO_OWRITE : if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) { pxTCB->ulNotifiedValue = value; } else { /* The value could not be written to the task. */ xReturn = pdFAIL; } break; case E_NOTIFY_ACTION_NONE : /* The task is being notified without its notify value being updated. */ break; } traceTASK_NOTIFY_FROM_ISR(); /* If the task is in the blocked state specifically to wait for a notification then unblock it now. */ if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) { /* The task should not have been on an event list. */ configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); prvAddTaskToReadyList( pxTCB ); } else { /* The delayed and ready lists cannot be accessed, so hold this task pending until the scheduler is resumed. */ vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); } if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) { /* The notified task has a priority above the currently executing task so a yield is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { /* Mark that a yield is pending in case the user is not using the "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ xYieldPending = pdTRUE; } } else { mtCOVERAGE_TEST_MARKER(); } } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); return xReturn; } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) void vTaskNotifyGiveFromISR( task_t task, int32_t *pxHigherPriorityTaskWoken ) { TCB_t * pxTCB; uint8_t ucOriginalNotifyState; uint32_t uxSavedInterruptStatus; configASSERT( task ); /* RTOS ports that support interrupt nesting have the concept of a maximum system call (or maximum API call) interrupt priority. Interrupts that are above the maximum system call priority are keep permanently enabled, even when the RTOS kernel is in a critical section, but cannot make any calls to FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion failure if a FreeRTOS API function is called from an interrupt that has been assigned a priority above the configured maximum system call priority. Only FreeRTOS functions that end in FromISR can be called from interrupts that have been assigned a priority at or (logically) below the maximum system call interrupt priority. FreeRTOS maintains a separate interrupt safe API to ensure interrupt entry is as fast and as simple as possible. More information (albeit Cortex-M specific) is provided on the following link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); pxTCB = ( TCB_t * ) task; uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); { ucOriginalNotifyState = pxTCB->ucNotifyState; pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; /* 'Giving' is equivalent to incrementing a count in a counting semaphore. */ ( pxTCB->ulNotifiedValue )++; traceTASK_NOTIFY_GIVE_FROM_ISR(); /* If the task is in the blocked state specifically to wait for a notification then unblock it now. */ if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) { /* The task should not have been on an event list. */ configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); if( uxSchedulerSuspended == ( uint32_t ) pdFALSE ) { ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); prvAddTaskToReadyList( pxTCB ); } else { /* The delayed and ready lists cannot be accessed, so hold this task pending until the scheduler is resumed. */ vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); } if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) { /* The notified task has a priority above the currently executing task so a yield is required. */ if( pxHigherPriorityTaskWoken != NULL ) { *pxHigherPriorityTaskWoken = pdTRUE; } else { /* Mark that a yield is pending in case the user is not using the "xHigherPriorityTaskWoken" parameter in an ISR safe FreeRTOS function. */ xYieldPending = pdTRUE; } } else { mtCOVERAGE_TEST_MARKER(); } } } portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) int32_t task_notify_clear(task_t task) { TCB_t *pxTCB; int32_t xReturn; /* If null is passed in here then it is the calling task that is having its notification state cleared. */ pxTCB = prvGetTCBFromHandle( task ); taskENTER_CRITICAL(); { if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) { pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; xReturn = pdPASS; } else { xReturn = pdFAIL; } } taskEXIT_CRITICAL(); return xReturn; } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) int32_t task_notify(task_t task) { return task_notify_ext((task), (0), E_NOTIFY_ACTION_INCR, NULL); } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ /*-----------------------------------------------------------*/ #if( configUSE_TASK_NOTIFICATIONS == 1 ) void task_join(task_t task) { if(!task) return; TaskStatus_t xTaskDetails; extern void task_notify_when_deleting(task_t, task_t, uint32_t, notify_action_e_t); task_notify_when_deleting(task, NULL, 1, E_NOTIFY_ACTION_INCR); do { vTaskGetInfo(task, &xTaskDetails, pdTRUE, E_TASK_STATE_INVALID); } while (!task_notify_take(true, 20) && xTaskDetails.eCurrentState != E_TASK_STATE_DELETED); } #endif /* configUSE_TASK_NOTIFICATIONS */ /*-----------------------------------------------------------*/ /*-----------------------------------------------------------*/ static void prvAddCurrentTaskToDelayedList( uint32_t timeout, const int32_t xCanBlockIndefinitely ) { uint32_t xTimeToWake; const uint32_t xConstTickCount = xTickCount; #if( INCLUDE_xTaskAbortDelay == 1 ) { /* About to enter a delayed list, so ensure the ucDelayAborted flag is reset to pdFALSE so it can be detected as having been set to pdTRUE when the task leaves the Blocked state. */ pxCurrentTCB->ucDelayAborted = pdFALSE; } #endif /* Remove the task from the ready list before adding it to the blocked list as the same list item is used for both lists. */ if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( uint32_t ) 0 ) { /* The current task must be in a ready list, so there is no need to check, and the port reset macro can be called directly. */ portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); } else { mtCOVERAGE_TEST_MARKER(); } #if ( INCLUDE_vTaskSuspend == 1 ) { if( ( timeout == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) { /* Add the task to the suspended task list instead of a delayed task list to ensure it is not woken by a timing event. It will block indefinitely. */ vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); } else { /* Calculate the time at which the task should be woken if the event does not occur. This may overflow but this doesn't matter, the kernel will manage it correctly. */ xTimeToWake = xConstTickCount + timeout; /* The list item will be inserted in wake time order. */ listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); if( xTimeToWake < xConstTickCount ) { /* Wake time has overflowed. Place this item in the overflow list. */ vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); } else { /* The wake time has not overflowed, so the current block list is used. */ vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); /* If the task entering the blocked state was placed at the head of the list of blocked tasks then xNextTaskUnblockTime needs to be updated too. */ if( xTimeToWake < xNextTaskUnblockTime ) { xNextTaskUnblockTime = xTimeToWake; } else { mtCOVERAGE_TEST_MARKER(); } } } } #else /* INCLUDE_vTaskSuspend */ { /* Calculate the time at which the task should be woken if the event does not occur. This may overflow but this doesn't matter, the kernel will manage it correctly. */ xTimeToWake = xConstTickCount + timeout; /* The list item will be inserted in wake time order. */ listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); if( xTimeToWake < xConstTickCount ) { /* Wake time has overflowed. Place this item in the overflow list. */ vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); } else { /* The wake time has not overflowed, so the current block list is used. */ vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); /* If the task entering the blocked state was placed at the head of the list of blocked tasks then xNextTaskUnblockTime needs to be updated too. */ if( xTimeToWake < xNextTaskUnblockTime ) { xNextTaskUnblockTime = xTimeToWake; } else { mtCOVERAGE_TEST_MARKER(); } } /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ ( void ) xCanBlockIndefinitely; } #endif /* INCLUDE_vTaskSuspend */ } /* Code below here allows additional code to be inserted into this source file, especially where access to file scope functions and data is needed (for example when performing module tests). */ #ifdef FREERTOS_MODULE_TEST #include "tasks_test_access_functions.h" #endif #if( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) #include "freertos_tasks_c_additions.h" static void freertos_tasks_c_additions_init( void ) { #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT FREERTOS_TASKS_C_ADDITIONS_INIT(); #endif } #endif ================================================ FILE: src/rtos/timers.c ================================================ /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* Standard includes. */ #include /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. #endif /* Lint e961 and e750 are suppressed as a MISRA exception justified because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the header files above, but not in this file, in order to generate the correct privileged Vs unprivileged linkage and placement. */ #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */ /* This entire source file will be skipped if the application is not configured to include software timer functionality. This #if is closed at the very bottom of this file. If you want to include software timer functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ #if ( configUSE_TIMERS == 1 ) /* Misc definitions. */ #define tmrNO_DELAY ( uint32_t ) 0U /* The name assigned to the timer service task. This can be overridden by defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ #ifndef configTIMER_SERVICE_TASK_NAME #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" #endif /* The definition of the timers themselves. */ typedef struct tmrTimerControl { const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ list_item_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ uint32_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ uint32_t uxAutoReload; /*<< Set to pdTRUE if the timer should be automatically restarted once expired. Set to pdFALSE if the timer is, in effect, a one-shot timer. */ void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ #if( configUSE_TRACE_FACILITY == 1 ) uint32_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ #endif #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) uint8_t ucStaticallyAllocated; /*<< Set to pdTRUE if the timer was created statically so no attempt is made to free the memory again if the timer is later deleted. */ #endif } xTIMER; /* The old xTIMER name is maintained above then typedefed to the new Timer_t name below to enable the use of older kernel aware debuggers. */ typedef xTIMER Timer_t; /* The definition of messages that can be sent and received on the timer queue. Two types of message can be queued - messages that manipulate a software timer, and messages that request the execution of a non-timer related callback. The two message types are defined in two separate structures, xTimerParametersType and xCallbackParametersType respectively. */ typedef struct tmrTimerParameters { uint32_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ } TimerParameter_t; typedef struct tmrCallbackParameters { PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ } CallbackParameters_t; /* The structure that contains the two message types, along with an identifier that is used to determine which message type is valid. */ typedef struct tmrTimerQueueMessage { int32_t xMessageID; /*<< The command being sent to the timer service task. */ union { TimerParameter_t xTimerParameters; /* Don't include xCallbackParameters if it is not going to be used as it makes the structure (and therefore the timer queue) larger. */ #if ( INCLUDE_xTimerPendFunctionCall == 1 ) CallbackParameters_t xCallbackParameters; #endif /* INCLUDE_xTimerPendFunctionCall */ } u; } DaemonTaskMessage_t; /*lint -save -e956 A manual analysis and inspection has been used to determine which static variables must be declared volatile. */ /* The list in which active timers are stored. Timers are referenced in expire time order, with the nearest expiry time at the front of the list. Only the timer service task is allowed to access these lists. */ static List_t xActiveTimerList1; static List_t xActiveTimerList2; static List_t *pxCurrentTimerList; static List_t *pxOverflowTimerList; /* A queue that is used to send commands to the timer service task. */ static queue_t xTimerQueue = NULL; static task_t xTimerTaskHandle = NULL; /*lint -restore */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) /* If static allocation is supported then the application must provide the following callback function - which enables the application to optionally provide the memory that will be used by the timer task as the task's stack and TCB. */ extern void vApplicationGetTimerTaskMemory( static_task_s_t **ppxTimerTaskTCBBuffer, task_stack_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); #endif /* * Initialise the infrastructure used by the timer service task if it has not * been initialised already. */ static void prvCheckForValidListAndQueue( void ) ; /* * The timer service task (daemon). Timer functionality is controlled by this * task. Other tasks communicate with the timer service task using the * xTimerQueue queue. */ static void prvTimerTask( void *pvParameters ) ; /* * Called by the timer service task to interpret and process a command it * received on the timer queue. */ static void prvProcessReceivedCommands( void ) ; /* * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, * depending on if the expire time causes a timer counter overflow. */ static int32_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const uint32_t xNextExpiryTime, const uint32_t xTimeNow, const uint32_t xCommandTime ) ; /* * An active timer has reached its expire time. Reload the timer if it is an * auto reload timer, then call its callback. */ static void prvProcessExpiredTimer( const uint32_t xNextExpireTime, const uint32_t xTimeNow ) ; /* * The tick count has overflowed. Switch the timer lists after ensuring the * current timer list does not still reference some timers. */ static void prvSwitchTimerLists( void ) ; /* * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE * if a tick count overflow occurred since prvSampleTimeNow() was last called. */ static uint32_t prvSampleTimeNow( int32_t * const pxTimerListsWereSwitched ) ; /* * If the timer list contains any active timers then return the expire time of * the timer that will expire first and set *pxListWasEmpty to false. If the * timer list does not contain any timers then return 0 and set *pxListWasEmpty * to pdTRUE. */ static uint32_t prvGetNextExpireTime( int32_t * const pxListWasEmpty ) ; /* * If a timer has expired, process it. Otherwise, block the timer service task * until either a timer does expire or a command is received. */ static void prvProcessTimerOrBlockTask( const uint32_t xNextExpireTime, int32_t xListWasEmpty ) ; /* * Called after a Timer_t structure has been allocated either statically or * dynamically to fill in the structure's members. */ static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t xTimerPeriodInTicks, const uint32_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, Timer_t *pxNewTimer ) ; /*-----------------------------------------------------------*/ int32_t xTimerCreateTimerTask( void ) { int32_t xReturn = pdFAIL; /* This function is called when the scheduler is started if configUSE_TIMERS is set to 1. Check that the infrastructure used by the timer service task has been created/initialised. If timers have already been created then the initialisation will already have been performed. */ prvCheckForValidListAndQueue(); if( xTimerQueue != NULL ) { #if( configSUPPORT_STATIC_ALLOCATION == 1 ) { static_task_s_t *pxTimerTaskTCBBuffer = NULL; task_stack_t *pxTimerTaskStackBuffer = NULL; uint32_t ulTimerTaskStackSize; vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); xTimerTaskHandle = task_create_static( prvTimerTask, NULL, ( ( uint32_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, ulTimerTaskStackSize, configTIMER_SERVICE_TASK_NAME, pxTimerTaskStackBuffer, pxTimerTaskTCBBuffer ); if( xTimerTaskHandle != NULL ) { xReturn = pdPASS; } } #else { xReturn = task_create( prvTimerTask, configTIMER_SERVICE_TASK_NAME, configTIMER_TASK_STACK_DEPTH, NULL, ( ( uint32_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, &xTimerTaskHandle ); } #endif /* configSUPPORT_STATIC_ALLOCATION */ } else { mtCOVERAGE_TEST_MARKER(); } configASSERT( xReturn ); return xReturn; } /*-----------------------------------------------------------*/ #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t xTimerPeriodInTicks, const uint32_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) { Timer_t *pxNewTimer; pxNewTimer = ( Timer_t * ) kmalloc( sizeof( Timer_t ) ); if( pxNewTimer != NULL ) { prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); #if( configSUPPORT_STATIC_ALLOCATION == 1 ) { /* Timers can be created statically or dynamically, so note this timer was created dynamically in case the timer is later deleted. */ pxNewTimer->ucStaticallyAllocated = pdFALSE; } #endif /* configSUPPORT_STATIC_ALLOCATION */ } return pxNewTimer; } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if( configSUPPORT_STATIC_ALLOCATION == 1 ) TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t xTimerPeriodInTicks, const uint32_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer ) { Timer_t *pxNewTimer; #if( configASSERT_DEFINED == 1 ) { /* Sanity check that the size of the structure used to declare a variable of type StaticTimer_t equals the size of the real timer structure. */ volatile size_t xSize = sizeof( StaticTimer_t ); configASSERT( xSize == sizeof( Timer_t ) ); } #endif /* configASSERT_DEFINED */ /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ configASSERT( pxTimerBuffer ); pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ if( pxNewTimer != NULL ) { prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) { /* Timers can be created statically or dynamically so note this timer was created statically in case it is later deleted. */ pxNewTimer->ucStaticallyAllocated = pdTRUE; } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ } return pxNewTimer; } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ const uint32_t xTimerPeriodInTicks, const uint32_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, Timer_t *pxNewTimer ) { /* 0 is not a valid value for xTimerPeriodInTicks. */ configASSERT( ( xTimerPeriodInTicks > 0 ) ); if( pxNewTimer != NULL ) { /* Ensure the infrastructure used by the timer service task has been created/initialised. */ prvCheckForValidListAndQueue(); /* Initialise the timer structure members using the function parameters. */ pxNewTimer->pcTimerName = pcTimerName; pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; pxNewTimer->uxAutoReload = uxAutoReload; pxNewTimer->pvTimerID = pvTimerID; pxNewTimer->pxCallbackFunction = pxCallbackFunction; vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); traceTIMER_CREATE( pxNewTimer ); } } /*-----------------------------------------------------------*/ int32_t xTimerGenericCommand( TimerHandle_t xTimer, const int32_t xCommandID, const uint32_t xOptionalValue, int32_t * const pxHigherPriorityTaskWoken, const uint32_t xTicksToWait ) { int32_t xReturn = pdFAIL; DaemonTaskMessage_t xMessage; configASSERT( xTimer ); /* Send a message to the timer service task to perform a particular action on a particular timer definition. */ if( xTimerQueue != NULL ) { /* Send a command to the timer service task to start the xTimer timer. */ xMessage.xMessageID = xCommandID; xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; xMessage.u.xTimerParameters.pxTimer = ( Timer_t * ) xTimer; if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) { if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) { xReturn = queue_append( xTimerQueue, &xMessage, xTicksToWait ); } else { xReturn = queue_append( xTimerQueue, &xMessage, tmrNO_DELAY ); } } else { xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); } traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); } else { mtCOVERAGE_TEST_MARKER(); } return xReturn; } /*-----------------------------------------------------------*/ task_t xTimerGetTimerDaemonTaskHandle( void ) { /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been started, then xTimerTaskHandle will be NULL. */ configASSERT( ( xTimerTaskHandle != NULL ) ); return xTimerTaskHandle; } /*-----------------------------------------------------------*/ uint32_t xTimerGetPeriod( TimerHandle_t xTimer ) { Timer_t *pxTimer = ( Timer_t * ) xTimer; configASSERT( xTimer ); return pxTimer->xTimerPeriodInTicks; } /*-----------------------------------------------------------*/ uint32_t xTimerGetExpiryTime( TimerHandle_t xTimer ) { Timer_t * pxTimer = ( Timer_t * ) xTimer; uint32_t xReturn; configASSERT( xTimer ); xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); return xReturn; } /*-----------------------------------------------------------*/ const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { Timer_t *pxTimer = ( Timer_t * ) xTimer; configASSERT( xTimer ); return pxTimer->pcTimerName; } /*-----------------------------------------------------------*/ static void prvProcessExpiredTimer( const uint32_t xNextExpireTime, const uint32_t xTimeNow ) { int32_t xResult; Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /* Remove the timer from the list of active timers. A check has already been performed to ensure the list is not empty. */ ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); traceTIMER_EXPIRED( pxTimer ); /* If the timer is an auto reload timer then calculate the next expiry time and re-insert the timer in the list of active timers. */ if( pxTimer->uxAutoReload == ( uint32_t ) pdTRUE ) { /* The timer is inserted into a list using a time relative to anything other than the current time. It will therefore be inserted into the correct list relative to the time this task thinks it is now. */ if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) { /* The timer expired before it was added to the active timer list. Reload it now. */ xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); configASSERT( xResult ); ( void ) xResult; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } /* Call the timer callback. */ pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); } /*-----------------------------------------------------------*/ static void prvTimerTask( void *pvParameters ) { uint32_t xNextExpireTime; int32_t xListWasEmpty; /* Just to avoid compiler warnings. */ ( void ) pvParameters; #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) { extern void vApplicationDaemonTaskStartupHook( void ); /* Allow the application writer to execute some code in the context of this task at the point the task starts executing. This is useful if the application includes initialisation code that would benefit from executing after the scheduler has been started. */ vApplicationDaemonTaskStartupHook(); } #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ for( ;; ) { /* Query the timers list to see if it contains any timers, and if so, obtain the time at which the next timer will expire. */ xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); /* If a timer has expired, process it. Otherwise, block this task until either a timer does expire, or a command is received. */ prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); /* Empty the command queue. */ prvProcessReceivedCommands(); } } /*-----------------------------------------------------------*/ static void prvProcessTimerOrBlockTask( const uint32_t xNextExpireTime, int32_t xListWasEmpty ) { uint32_t xTimeNow; int32_t xTimerListsWereSwitched; rtos_suspend_all(); { /* Obtain the time now to make an assessment as to whether the timer has expired or not. If obtaining the time causes the lists to switch then don't process this timer as any timers that remained in the list when the lists were switched will have been processed within the prvSampleTimeNow() function. */ xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); if( xTimerListsWereSwitched == pdFALSE ) { /* The tick count has not overflowed, has the timer expired? */ if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) { ( void ) rtos_resume_all(); prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); } else { /* The tick count has not overflowed, and the next expire time has not been reached yet. This task should therefore block to wait for the next expire time or a command to be received - whichever comes first. The following line cannot be reached unless xNextExpireTime > xTimeNow, except in the case when the current timer list is empty. */ if( xListWasEmpty != pdFALSE ) { /* The current timer list is empty - is the overflow list also empty? */ xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); } vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); if( rtos_resume_all() == pdFALSE ) { /* Yield to wait for either a command to arrive, or the block time to expire. If a command arrived between the critical section being exited and this yield then the yield will not cause the task to block. */ portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } } else { ( void ) rtos_resume_all(); } } } /*-----------------------------------------------------------*/ static uint32_t prvGetNextExpireTime( int32_t * const pxListWasEmpty ) { uint32_t xNextExpireTime; /* Timers are listed in expiry time order, with the head of the list referencing the task that will expire first. Obtain the time at which the timer with the nearest expiry time will expire. If there are no active timers then just set the next expire time to 0. That will cause this task to unblock when the tick count overflows, at which point the timer lists will be switched and the next expiry time can be re-assessed. */ *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); if( *pxListWasEmpty == pdFALSE ) { xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); } else { /* Ensure the task unblocks when the tick count rolls over. */ xNextExpireTime = ( uint32_t ) 0U; } return xNextExpireTime; } /*-----------------------------------------------------------*/ static uint32_t prvSampleTimeNow( int32_t * const pxTimerListsWereSwitched ) { uint32_t xTimeNow; static uint32_t xLastTime = ( uint32_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ xTimeNow = millis(); if( xTimeNow < xLastTime ) { prvSwitchTimerLists(); *pxTimerListsWereSwitched = pdTRUE; } else { *pxTimerListsWereSwitched = pdFALSE; } xLastTime = xTimeNow; return xTimeNow; } /*-----------------------------------------------------------*/ static int32_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const uint32_t xNextExpiryTime, const uint32_t xTimeNow, const uint32_t xCommandTime ) { int32_t xProcessTimerNow = pdFALSE; listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); if( xNextExpiryTime <= xTimeNow ) { /* Has the expiry time elapsed between the command to start/reset a timer was issued, and the time the command was processed? */ if( ( ( uint32_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ { /* The time between a command being issued and the command being processed actually exceeds the timers period. */ xProcessTimerNow = pdTRUE; } else { vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); } } else { if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) { /* If, since the command was issued, the tick count has overflowed but the expiry time has not, then the timer must have already passed its expiry time and should be processed immediately. */ xProcessTimerNow = pdTRUE; } else { vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); } } return xProcessTimerNow; } /*-----------------------------------------------------------*/ static void prvProcessReceivedCommands( void ) { DaemonTaskMessage_t xMessage; Timer_t *pxTimer; int32_t xTimerListsWereSwitched, xResult; uint32_t xTimeNow; while( queue_recv( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless queue_recv() returns pdTRUE. */ { #if ( INCLUDE_xTimerPendFunctionCall == 1 ) { /* Negative commands are pended function calls rather than timer commands. */ if( xMessage.xMessageID < ( int32_t ) 0 ) { const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); /* The timer uses the xCallbackParameters member to request a callback be executed. Check the callback is not NULL. */ configASSERT( pxCallback ); /* Call the function. */ pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* INCLUDE_xTimerPendFunctionCall */ /* Commands that are positive are timer commands rather than pended function calls. */ if( xMessage.xMessageID >= ( int32_t ) 0 ) { /* The messages uses the xTimerParameters member to work on a software timer. */ pxTimer = xMessage.u.xTimerParameters.pxTimer; if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ { /* The timer is in a list, remove it. */ ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); } traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); /* In this case the xTimerListsWereSwitched parameter is not used, but it must be present in the function call. prvSampleTimeNow() must be called after the message is received from xTimerQueue so there is no possibility of a higher priority task adding a message to the message queue with a time that is ahead of the timer daemon task (because it pre-empted the timer daemon task after the xTimeNow value was set). */ xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); switch( xMessage.xMessageID ) { case tmrCOMMAND_START : case tmrCOMMAND_START_FROM_ISR : case tmrCOMMAND_RESET : case tmrCOMMAND_RESET_FROM_ISR : case tmrCOMMAND_START_DONT_TRACE : /* Start or restart a timer. */ if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) { /* The timer expired before it was added to the active timer list. Process it now. */ pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); traceTIMER_EXPIRED( pxTimer ); if( pxTimer->uxAutoReload == ( uint32_t ) pdTRUE ) { xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); configASSERT( xResult ); ( void ) xResult; } else { mtCOVERAGE_TEST_MARKER(); } } else { mtCOVERAGE_TEST_MARKER(); } break; case tmrCOMMAND_STOP : case tmrCOMMAND_STOP_FROM_ISR : /* The timer has already been removed from the active list. There is nothing to do here. */ break; case tmrCOMMAND_CHANGE_PERIOD : case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); /* The new period does not really have a reference, and can be longer or shorter than the old one. The command time is therefore set to the current time, and as the period cannot be zero the next expiry time can only be in the future, meaning (unlike for the xTimerStart() case above) there is no fail case that needs to be handled here. */ ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); break; case tmrCOMMAND_DELETE : /* The timer has already been removed from the active list, just free up the memory if the memory was dynamically allocated. */ #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) { /* The timer can only have been allocated dynamically - free it again. */ kfree( pxTimer ); } #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) { /* The timer could have been allocated statically or dynamically, so check before attempting to free the memory. */ if( pxTimer->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) { kfree( pxTimer ); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ break; default : /* Don't expect to get here. */ break; } } } } /*-----------------------------------------------------------*/ static void prvSwitchTimerLists( void ) { uint32_t xNextExpireTime, xReloadTime; List_t *pxTemp; Timer_t *pxTimer; int32_t xResult; /* The tick count has overflowed. The timer lists must be switched. If there are any timers still referenced from the current timer list then they must have expired and should be processed before the lists are switched. */ while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) { xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); /* Remove the timer from the list. */ pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); traceTIMER_EXPIRED( pxTimer ); /* Execute its callback, then send a command to restart the timer if it is an auto-reload timer. It cannot be restarted here as the lists have not yet been switched. */ pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); if( pxTimer->uxAutoReload == ( uint32_t ) pdTRUE ) { /* Calculate the reload value, and if the reload value results in the timer going into the same timer list then it has already expired and the timer should be re-inserted into the current list so it is processed again within this loop. Otherwise a command should be sent to restart the timer to ensure it is only inserted into a list after the lists have been swapped. */ xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); if( xReloadTime > xNextExpireTime ) { listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); } else { xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); configASSERT( xResult ); ( void ) xResult; } } else { mtCOVERAGE_TEST_MARKER(); } } pxTemp = pxCurrentTimerList; pxCurrentTimerList = pxOverflowTimerList; pxOverflowTimerList = pxTemp; } /*-----------------------------------------------------------*/ static void prvCheckForValidListAndQueue( void ) { /* Check that the list from which active timers are referenced, and the queue used to communicate with the timer service, have been initialised. */ taskENTER_CRITICAL(); { if( xTimerQueue == NULL ) { vListInitialise( &xActiveTimerList1 ); vListInitialise( &xActiveTimerList2 ); pxCurrentTimerList = &xActiveTimerList1; pxOverflowTimerList = &xActiveTimerList2; #if( configSUPPORT_STATIC_ALLOCATION == 1 ) { /* The timer queue is allocated statically in case configSUPPORT_DYNAMIC_ALLOCATION is 0. */ static static_queue_s_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ xTimerQueue = queue_create_static( ( uint32_t ) configTIMER_QUEUE_LENGTH, ( uint32_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); } #else { xTimerQueue = queue_create( ( uint32_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); } #endif #if ( configQUEUE_REGISTRY_SIZE > 0 ) { if( xTimerQueue != NULL ) { vQueueAddToRegistry( xTimerQueue, "TmrQ" ); } else { mtCOVERAGE_TEST_MARKER(); } } #endif /* configQUEUE_REGISTRY_SIZE */ } else { mtCOVERAGE_TEST_MARKER(); } } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ int32_t xTimerIsTimerActive( TimerHandle_t xTimer ) { int32_t xTimerIsInActiveList; Timer_t *pxTimer = ( Timer_t * ) xTimer; configASSERT( xTimer ); /* Is the timer in the list of active timers? */ taskENTER_CRITICAL(); { /* Checking to see if it is in the NULL list in effect checks to see if it is referenced from either the current or the overflow timer lists in one go, but the logic has to be reversed, hence the '!'. */ xTimerIsInActiveList = ( int32_t ) !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) ); /*lint !e961. Cast is only redundant when NULL is passed into the macro. */ } taskEXIT_CRITICAL(); return xTimerIsInActiveList; } /*lint !e818 Can't be pointer to const due to the typedef. */ /*-----------------------------------------------------------*/ void *pvTimerGetTimerID( const TimerHandle_t xTimer ) { Timer_t * const pxTimer = ( Timer_t * ) xTimer; void *pvReturn; configASSERT( xTimer ); taskENTER_CRITICAL(); { pvReturn = pxTimer->pvTimerID; } taskEXIT_CRITICAL(); return pvReturn; } /*-----------------------------------------------------------*/ void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) { Timer_t * const pxTimer = ( Timer_t * ) xTimer; configASSERT( xTimer ); taskENTER_CRITICAL(); { pxTimer->pvTimerID = pvNewID; } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ #if( INCLUDE_xTimerPendFunctionCall == 1 ) int32_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, int32_t *pxHigherPriorityTaskWoken ) { DaemonTaskMessage_t xMessage; int32_t xReturn; /* Complete the message with the function parameters and post it to the daemon task. */ xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); return xReturn; } #endif /* INCLUDE_xTimerPendFunctionCall */ /*-----------------------------------------------------------*/ #if( INCLUDE_xTimerPendFunctionCall == 1 ) int32_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, uint32_t xTicksToWait ) { DaemonTaskMessage_t xMessage; int32_t xReturn; /* This function can only be called after a timer has been created or after the scheduler has been started because, until then, the timer queue does not exist. */ configASSERT( xTimerQueue ); /* Complete the message with the function parameters and post it to the daemon task. */ xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; xReturn = queue_append( xTimerQueue, &xMessage, xTicksToWait ); tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); return xReturn; } #endif /* INCLUDE_xTimerPendFunctionCall */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) uint32_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) { return ( ( Timer_t * ) xTimer )->uxTimerNumber; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ #if ( configUSE_TRACE_FACILITY == 1 ) void vTimerSetTimerNumber( TimerHandle_t xTimer, uint32_t uxTimerNumber ) { ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; } #endif /* configUSE_TRACE_FACILITY */ /*-----------------------------------------------------------*/ /* This entire source file will be skipped if the application is not configured to include software timer functionality. If you want to include software timer functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ #endif /* configUSE_TIMERS == 1 */ ================================================ FILE: src/system/cpp_support.cpp ================================================ /** * \file system/cpp_support.cpp * * C++ support hooks * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include "rtos/FreeRTOS.h" #include "rtos/task.h" #include "v5_api.h" extern "C" void task_fn_wrapper(task_fn_t fn, void* args) { #ifdef __cpp_exceptions try { #endif fn(args); #ifdef __cpp_exceptions } catch (const std::runtime_error& re) { fprintf(stderr, "Runtime error: %s \n", re.what()); vexDisplayString(5, "A runtime error occurred:"); vexDisplayString(6, "%s", re.what()); vexDisplayString(7, "Note: open terminal for error message"); } catch (const std::exception& ex) { fprintf(stderr, "Exception occurred: %s \n", ex.what()); vexDisplayString(5, "An exception occurred:"); vexDisplayString(6, "%s", ex.what()); vexDisplayString(7, "Note: open terminal for error message"); } catch (...) { fprintf(stderr, "Unknown error occurred. \n"); vexDisplayString(5, "An unknown error occurred"); } #endif } /******************************************************************************/ /** C++ Linkages for User Tasks **/ /******************************************************************************/ __attribute__((weak)) void autonomous() {} __attribute__((weak)) void initialize() {} __attribute__((weak)) void opcontrol() {} __attribute__((weak)) void disabled() {} __attribute__((weak)) void competition_initialize() {} extern "C" void cpp_autonomous() { autonomous(); } extern "C" void cpp_initialize() { initialize(); } extern "C" void cpp_opcontrol() { opcontrol(); } extern "C" void cpp_disabled() { disabled(); } extern "C" void cpp_competition_initialize() { competition_initialize(); } ================================================ FILE: src/system/dev/dev_driver.c ================================================ /** * \file system/dev/dev_driver.c * * Generic Serial Device driver * * Contains the driver for writing to any smart port with no regard to the * device on the other end. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include #include #include "common/set.h" #include "common/string.h" #include "kapi.h" #include "system/dev/dev.h" #include "system/dev/vfs.h" #include "system/optimizers.h" #include "v5_api.h" #include "vdml/vdml.h" #define ASCII_ZERO 48 typedef struct dev_file_arg { uint32_t port; int flags; } dev_file_arg_t; /******************************************************************************/ /** newlib driver functions **/ /******************************************************************************/ int dev_read_r(struct _reent* r, void* const arg, uint8_t* buffer, const size_t len) { dev_file_arg_t* file_arg = (dev_file_arg_t*)arg; uint32_t port = file_arg->port; int32_t recv = 0; while (true) { recv = serial_read(port, (uint8_t*)(buffer + recv), len - recv); if (recv == PROS_ERR) { return 0; } if (file_arg->flags & O_NONBLOCK || recv >= 1) { break; } task_delay(2); } if (recv == 0) { errno = EAGAIN; return 0; } return recv; } int dev_write_r(struct _reent* r, void* const arg, const uint8_t* buf, const size_t len) { dev_file_arg_t* file_arg = (dev_file_arg_t*)arg; uint32_t port = file_arg->port; int32_t wrtn = 0; while (true) { int32_t w = serial_write(port, (uint8_t*)(buf + wrtn), len - wrtn); if (w == PROS_ERR) { return wrtn; } wrtn += w; if (file_arg->flags & O_NONBLOCK || wrtn >= len) { break; } task_delay(2); } if (wrtn == 0) { errno = EAGAIN; return 0; } return wrtn; } int dev_close_r(struct _reent* r, void* const arg) { return 0; } int dev_fstat_r(struct _reent* r, void* const arg, struct stat* st) { // this is a complete implementation st->st_mode = S_IFCHR; return 0; } int dev_isatty_r(struct _reent* r, void* const arg) { // this is a complete implementation return 0; } off_t dev_lseek_r(struct _reent* r, void* const arg, off_t ptr, int dir) { // lseek doesn't make sense on a serial line r->_errno = ESPIPE; return -1; } int dev_ctl(void* const arg, const uint32_t cmd, void* const extra_arg) { dev_file_arg_t* file_arg = (dev_file_arg_t*)arg; uint32_t port = file_arg->port; switch (cmd) { case DEVCTL_FIONREAD: return serial_get_read_avail(port); case DEVCTL_FIONWRITE: return serial_get_write_free(port); case DEVCTL_SET_BAUDRATE: return serial_set_baudrate(port, (int32_t)extra_arg); default: errno = EINVAL; return PROS_ERR; } } /******************************************************************************/ /** Driver description **/ /******************************************************************************/ const struct fs_driver _dev_driver = {.close_r = dev_close_r, .fstat_r = dev_fstat_r, .isatty_r = dev_isatty_r, .lseek_r = dev_lseek_r, .read_r = dev_read_r, .write_r = dev_write_r, .ctl = dev_ctl}; const struct fs_driver* const dev_driver = &_dev_driver; int dev_open_r(struct _reent* r, const char* path, int flags, int mode) { if (*path == '\0') { return STDOUT_FILENO; } if (*path == '/') { path++; } // check length of path - it MUST be at most 2 characters size_t i; for (i = 0; i < 3; i++) { if (path[i] == '\0') { break; } } int32_t port; if (path[i] != '\0') { // i will the length of the path or the third character r->_errno = ENAMETOOLONG; return -1; } if (i == 2) { // Port number is two characters port = 10 * (path[0] - ASCII_ZERO) + (path[1] - ASCII_ZERO); } else { port = path[0] - ASCII_ZERO; } serial_enable(port); dev_file_arg_t* arg = (dev_file_arg_t*)kmalloc(sizeof(dev_file_arg_t)); arg->port = port; arg->flags = flags; return vfs_add_entry_r(r, dev_driver, arg); } ================================================ FILE: src/system/dev/file_system_stubs.c ================================================ /** * \file system/dev/dev_driver.c * * Generic Serial Device driver * * Contains temporary stubs for the file system to allow compilation under gcc 9.2 * This is temporary and should be removed as part of #184 * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include int chdir(const char* path) { errno = ENOSYS; return -1; } int mkdir(const char* pathname, mode_t mode) { errno = ENOSYS; return -1; } int chmod(const char* pathname, mode_t mode) { errno = ENOSYS; return -1; } int fchmod(int fd, mode_t mode) { errno = ENOSYS; return -1; } int fchmodat(int dirfd, const char* pathname, mode_t mode, int flags) { errno = ENOSYS; return -1; } long pathconf(const char* path, int name) { errno = ENOSYS; return -1; } char* getcwd(char* buf, size_t size) { errno = ENOSYS; return NULL; } int _unlink(const char* name) { errno = ENOSYS; return -1; } int _link(const char* old, const char* new) { errno = ENOSYS; return -1; } int _stat(const char* file, struct stat* st) { errno = ENOSYS; return -1; } int symlink(const char* file, const char* linkpath) { errno = ENOSYS; return -1; } ssize_t readlink(const char* pathname, char* buf, size_t bufsiz) { errno = ENOSYS; return -1; } int truncate(const char* path, off_t length) { errno = ENOSYS; return -1; } ================================================ FILE: src/system/dev/ser_daemon.c ================================================ /** * \file system/dev/ser_daemon.c * * Serial Input Daemon * * The serial input daemon is responsible for polling the serial line for * characters and responding to any kernel commands (like printing the banner or * enabling COBS) * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "kapi.h" #include "pros/version.h" #include "system/dev/banners.h" #include "system/hot.h" #include "system/optimizers.h" #include "v5_api.h" #define MAX_COMMAND_LENGTH 32 __attribute__((weak)) char const* const _PROS_COMPILE_TIMESTAMP = "Unknown"; __attribute__((weak)) char const* const _PROS_COMPILE_DIRECTORY = "Unknown"; __attribute__((weak)) const int _PROS_COMPILE_TIMESTAMP_INT = 0; static bool banner_is_enabled = true; void enable_banner(bool enabled) { banner_is_enabled = enabled; } void print_small_banner(void) { if (!banner_is_enabled) return; uint32_t uptime = millis(); char const * const timestamp = (HOT_TABLE && HOT_TABLE->compile_timestamp) ? HOT_TABLE->compile_timestamp : _PROS_COMPILE_TIMESTAMP; char const * const directory = (HOT_TABLE && HOT_TABLE->compile_directory) ? HOT_TABLE->compile_directory : _PROS_COMPILE_DIRECTORY; iprintf(short_banner, PROS_VERSION_STRING, uptime / 1000, uptime % 1000, timestamp, directory); } void print_large_banner(void) { if (!banner_is_enabled) return; uint8_t version[4]; uint32_t* sys_ver = (uint32_t*)version; *sys_ver = vexSystemVersion(); uint32_t uptime = millis(); char const * const timestamp = (HOT_TABLE && HOT_TABLE->compile_timestamp) ? HOT_TABLE->compile_timestamp : _PROS_COMPILE_TIMESTAMP; char const * const directory = (HOT_TABLE && HOT_TABLE->compile_directory) ? HOT_TABLE->compile_directory : _PROS_COMPILE_DIRECTORY; iprintf(large_banner, PROS_VERSION_STRING, version[3], version[2], version[1], version[0], uptime / 1000, uptime % 1000, timestamp, directory); } /******************************************************************************/ /** Input buffer **/ /** **/ /** this is what read() reads from. Implemented as a ring buffer **/ /** TODO: just use a FreeRTOS queue instead of 2 semaphores **/ /******************************************************************************/ #define INP_BUFFER_SIZE 0x1000 // 4KB... which is larger than VEX's output buffer -_- static static_stream_buf_s_t inp_stream_buf; static uint8_t inp_buffer[INP_BUFFER_SIZE]; static stream_buf_t inp_stream; static inline void inp_buffer_initialize() { inp_stream = stream_buf_create_static(INP_BUFFER_SIZE, 1, inp_buffer, &inp_stream_buf); } // if you extern this function you can place characters on the rest of the // system's input buffer bool inp_buffer_post(uint8_t b) { return stream_buf_send(inp_stream, &b, 1, TIMEOUT_MAX); } int32_t inp_buffer_read(uint32_t timeout) { // polling the semaphore from a higher priority task (as would be normal) will // starve the ser_daemon_task if (timeout == 0) { timeout = 1; } uint8_t b; if (!stream_buf_recv(inp_stream, &b, 1, timeout)) { return -1; } return (int32_t)b; } // returns the number of bytes currently in the stream int32_t inp_buffer_available() { return stream_buf_get_used(inp_stream); } /******************************************************************************/ /** Serial Daemon **/ /******************************************************************************/ static task_stack_t ser_daemon_stack[TASK_STACK_DEPTH_MIN]; static static_task_s_t ser_daemon_task_buffer; static inline uint8_t vex_read_char() { int32_t b = vexSerialReadChar(1); while (b == -1L) { task_delay(1); b = vexSerialReadChar(1); } // Don't get rid of the literal type suffix, it ensures optimiziations don't // break this condition return (uint8_t)b; } static void ser_daemon_task(void* ign) { uint8_t command_stack[MAX_COMMAND_LENGTH]; size_t command_stack_idx = 0; print_large_banner(); while (1) { uint8_t b = vex_read_char(); if (b == 'p') { // TODO: make the command prefix not typeable command_stack[command_stack_idx++] = b; b = command_stack[command_stack_idx++] = vex_read_char(); if (b == 'R') { b = command_stack[command_stack_idx++] = vex_read_char(); switch (b) { case 'a': fprintf(stderr, "I'm alive!\n"); command_stack_idx = 0; break; case 'b': task_delay(20); print_small_banner(); command_stack_idx = 0; break; case 'B': task_delay(20); print_large_banner(); command_stack_idx = 0; break; case 'e': // read next 4 bytes command_stack[command_stack_idx++] = vex_read_char(); command_stack[command_stack_idx++] = vex_read_char(); command_stack[command_stack_idx++] = vex_read_char(); command_stack[command_stack_idx++] = vex_read_char(); // the parameter expected to serctl is the stream id (a uint32_t), so // we // need to cast to a uint32_t pointer, dereference it, and cast to a // void* to make the compiler happy serctl(SERCTL_ACTIVATE, (void*)(*(uint32_t*)(command_stack + 3))); // printf("enabled %s\n", command_stack + 3); command_stack_idx = 0; break; case 'd': // read next 4 bytes command_stack[command_stack_idx++] = vex_read_char(); command_stack[command_stack_idx++] = vex_read_char(); command_stack[command_stack_idx++] = vex_read_char(); command_stack[command_stack_idx++] = vex_read_char(); serctl(SERCTL_DEACTIVATE, (void*)(*(uint32_t*)(command_stack + 3))); // printf("disabled %s\n", command_stack+3); command_stack_idx = 0; break; case 'c': serctl(SERCTL_ENABLE_COBS, NULL); command_stack_idx = 0; break; case 'r': serctl(SERCTL_DISABLE_COBS, NULL); command_stack_idx = 0; break; default: command_stack_idx = 0; break; } } for (size_t i = 0; i < command_stack_idx; i++) { // empty out the command stack onto the input buffer since something // wasn't right with the command inp_buffer_post(command_stack[i]); } command_stack_idx = 0; } else { inp_buffer_post(b); } } } void ser_initialize(void) { inp_buffer_initialize(); extern void ser_driver_initialize(void); ser_driver_initialize(); task_create_static(ser_daemon_task, NULL, TASK_PRIORITY_MIN + 1, TASK_STACK_DEPTH_MIN, "Serial Daemon (PROS)", ser_daemon_stack, &ser_daemon_task_buffer); } ================================================ FILE: src/system/dev/ser_driver.c ================================================ /** * \file system/dev/ser_driver.c * * Serial Driver * * Contains the driver for communicating over the serial line. The serial driver * is responsible for shipping out all data. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "common/cobs.h" #include "common/set.h" #include "common/string.h" #include "kapi.h" #include "system/dev/ser.h" #include "system/dev/vfs.h" #include "system/optimizers.h" #include "v5_api.h" #define VEX_SERIAL_BUFFER_SIZE 2047 // ser_file_arg is 2 words (64 bits). The first word is the stream_id // (i.e. sout/serr/jinx/kdbg) and is exactly 4 characters. The second word // contains flags for serial driver operation typedef struct ser_file_arg { union { uint32_t stream_id; uint8_t stream[4]; }; enum { E_NOBLK_WRITE = 1 } flags; } ser_file_s_t; #define STDIN_STREAM_ID 0x706e6973 // 'sinp' little endian #define STDOUT_STREAM_ID 0x74756f73 // 'sout' little endian #define STDERR_STREAM_ID 0x72726573 // 'serr' little endian #define KDBG_STREAM_ID 0x6762646b // 'kdbg' little endian // This array contains the serial driver's arguments for the 4 reserved file // descriptors. The fact that this array matches the order of the 4 reserved // file descriptors is mostly irrelevant. We do need to know which one is which, // but they get mapped in ser_driver_initialize. static ser_file_s_t RESERVED_SER_FILES[] = { {.stream_id = STDIN_STREAM_ID, .flags = 0}, {.stream_id = STDOUT_STREAM_ID, .flags = 0}, {.stream_id = STDERR_STREAM_ID, .flags = 0}, {.stream_id = KDBG_STREAM_ID, .flags = 0}, }; // These mutexes are initialized in ser_driver_initialize static static_sem_s_t read_mtx_buf; static static_sem_s_t write_mtx_buf; static mutex_t read_mtx; // ensures that only one read is happening at a time static mutex_t write_mtx; // ensures that only one write is happening at a time // Write buffer as a stream buffer. Initialized below in ser_driver_initialize static static_stream_buf_s_t write_stream_buf; static uint8_t write_buf[VEX_SERIAL_BUFFER_SIZE + 1]; static uint8_t write_scratch_buf[VEX_SERIAL_BUFFER_SIZE]; // scratch buffer static stream_buf_t write_stream; // We maintain a set of streams which should actually be sent over the serial // line. This is maintained as a separate list and don't traverse through // open files b/c enabled streams is done per ID not per file (multiple // files may map to one stream ID) // Initialized below in ser_driver_initialize static struct set enabled_streams_set; // stderr is ALWAYS guaranteed to be sent over the serial line. stdout and // others may be disabled static const uint32_t guaranteed_delivery_streams[] = { // STDIN_STREAM_ID, // STDOUT_STREAM_ID, stdout isn't guaranteed delivery, but enabled by // default STDERR_STREAM_ID, // KDBG_STREAM_ID, }; #define guaranteed_delivery_streams_size (sizeof(guaranteed_delivery_streams) / sizeof(*guaranteed_delivery_streams)) // global runtime config for the serial driver static enum { E_COBS_ENABLED = 1 } ser_driver_runtime_config; // comes from ser_daemon extern int32_t inp_buffer_read(uint32_t timeout); /******************************************************************************/ /** Output queue **/ /** **/ /** vexSerialWriteBuffer doesn't seem to be very thread safe, so the system **/ /** daemon flushes an intermediary buffer once before vexBackgroundProcessing**/ /** calls to write add to the queue. Flushing is optimized because we have **/ /** underlying access to the write buffer, as opposed to calling queue_recv **/ /** a bunch of times **/ /******************************************************************************/ void ser_output_flush(void) { size_t len = stream_buf_recv(write_stream, write_scratch_buf, vexSerialWriteFree(1), 0); uint32_t ret = vexSerialWriteBuffer(1, write_scratch_buf, len); if (ret != len) { kprintf("WARNING: some serial data has been dropped"); } } bool ser_output_write(const uint8_t* buffer, size_t size, bool noblock) { return stream_buf_send(write_stream, buffer, size, noblock ? 0 : TIMEOUT_MAX); } /******************************************************************************/ /** newlib driver functions **/ /******************************************************************************/ int ser_read_r(struct _reent* r, void* const arg, uint8_t* buffer, const size_t len) { // arg isn't used since serial reads aren't stream-based size_t read = 0; int32_t c; if (!mutex_take(read_mtx, TIMEOUT_MAX)) { r->_errno = EACCES; return 0; } while (read < len) { // the logic inside this loop is a bit funky but seems to make newlib behave // properly c = inp_buffer_read(0); // Don't get rid of the literal type suffix, it ensures optimiziations don't // break this condition if (c == -1L) { if (read) { break; } else { continue; } } *(buffer++) = (uint8_t)c; read++; if (c == '\n') { break; } } mutex_give(read_mtx); *buffer = 0; return read; } int ser_write_r(struct _reent* r, void* const arg, const uint8_t* buf, const size_t len) { const ser_file_s_t file = *(ser_file_s_t*)arg; if (!list_contains(guaranteed_delivery_streams, guaranteed_delivery_streams_size, file.stream_id) && !set_contains(&enabled_streams_set, file.stream_id)) { // the stream isn't a guaranteed delivery or hasn't been enabled so just // pretend like the data was shipped just fine return len; } if (ser_driver_runtime_config &= E_COBS_ENABLED) { // allocate stack space for the buffer to be cobs encoded const size_t cobs_len = cobs_encode_measure(buf, len, file.stream_id); uint8_t cobs_buf[cobs_len + 1]; // need to guarantee writes are in order if (!mutex_take(write_mtx, (file.flags & E_NOBLK_WRITE) ? 0 : TIMEOUT_MAX)) { r->_errno = EACCES; return 0; } cobs_encode(cobs_buf, buf, len, file.stream_id); cobs_buf[cobs_len] = 0; bool ret = ser_output_write(cobs_buf, cobs_len + 1, file.flags & E_NOBLK_WRITE); mutex_give(write_mtx); if (!ret) { r->_errno = EIO; return 0; } return len; } else { // need to guarantee writes are in order if (!mutex_take(write_mtx, TIMEOUT_MAX)) { r->_errno = EACCES; return 0; } bool ret = ser_output_write(buf, len, file.flags & E_NOBLK_WRITE); mutex_give(write_mtx); if (!ret) { r->_errno = EIO; return 0; } return len; } } int ser_close_r(struct _reent* r, void* const arg) { // This does nothing for now, may be implemented later return 0; } int ser_fstat_r(struct _reent* r, void* const arg, struct stat* st) { // this is a complete implementation st->st_mode = S_IFCHR; return 0; } int ser_isatty_r(struct _reent* r, void* const arg) { // this is a complete implementation return 1; } off_t ser_lseek_r(struct _reent* r, void* const arg, off_t ptr, int dir) { // lseek doesn't make sense on a serial line r->_errno = ESPIPE; return -1; } int ser_ctl(void* const arg, const uint32_t cmd, void* const extra_arg) { ser_file_s_t file = *(ser_file_s_t*)arg; switch (cmd) { case SERCTL_ACTIVATE: if (!list_contains(guaranteed_delivery_streams, guaranteed_delivery_streams_size, (uint32_t)file.stream_id)) { set_add(&enabled_streams_set, (uint32_t)file.stream_id); } return 0; case SERCTL_DEACTIVATE: if (!list_contains(guaranteed_delivery_streams, guaranteed_delivery_streams_size, (uint32_t)file.stream_id)) { set_rm(&enabled_streams_set, (uint32_t)file.stream_id); } return 0; case SERCTL_BLKWRITE: file.flags &= ~E_NOBLK_WRITE; return 0; case SERCTL_NOBLKWRITE: file.flags |= E_NOBLK_WRITE; return 0; default: errno = EINVAL; return PROS_ERR; } } /******************************************************************************/ /** Driver description **/ /******************************************************************************/ const struct fs_driver _ser_driver = {.close_r = ser_close_r, .fstat_r = ser_fstat_r, .isatty_r = ser_isatty_r, .lseek_r = ser_lseek_r, .read_r = ser_read_r, .write_r = ser_write_r, .ctl = ser_ctl}; const struct fs_driver* const ser_driver = &_ser_driver; int ser_open_r(struct _reent* r, const char* path, int flags, int mode) { if (*path == '\0') { return STDOUT_FILENO; } if (*path == '/') { path++; } // check length of path - it MUST be at most 4 characters size_t i; for (i = 0; i < 4; i++) { if (path[i] == '\0') { break; } } if (path[i] != '\0') { // i will the length of the path or the fifth character r->_errno = ENAMETOOLONG; return -1; } if (!strcmp(path, "sout")) { return STDOUT_FILENO; } if (!strcmp(path, "sin")) { return STDIN_FILENO; } if (!strcmp(path, "serr")) { return STDERR_FILENO; } ser_file_s_t* arg = kmalloc(sizeof(*arg)); memcpy(arg->stream, path, strlen(path)); return vfs_add_entry_r(r, ser_driver, arg); } // control various components of the serial driver or a file int32_t serctl(const uint32_t action, void* const extra_arg) { switch (action) { case SERCTL_ACTIVATE: if (!list_contains(guaranteed_delivery_streams, guaranteed_delivery_streams_size, (uint32_t)extra_arg)) { set_add(&enabled_streams_set, (uint32_t)extra_arg); } else { errno = EIO; return -1; } return 0; case SERCTL_DEACTIVATE: if (!list_contains(guaranteed_delivery_streams, guaranteed_delivery_streams_size, (uint32_t)extra_arg)) { set_rm(&enabled_streams_set, (uint32_t)extra_arg); } else { errno = EIO; return -1; } return 0; case SERCTL_ENABLE_COBS: ser_driver_runtime_config |= E_COBS_ENABLED; return 0; case SERCTL_DISABLE_COBS: ser_driver_runtime_config &= ~E_COBS_ENABLED; return 0; default: errno = EINVAL; return PROS_ERR; } } // called by ser_initialize() in ser_daemon.c // vfs_initialize() calls ser_initialize() void ser_driver_initialize(void) { ser_driver_runtime_config |= E_COBS_ENABLED; // start with cobs enabled read_mtx = mutex_create_static(&read_mtx_buf); write_mtx = mutex_create_static(&write_mtx_buf); set_initialize(&enabled_streams_set); set_add(&enabled_streams_set, STDOUT_STREAM_ID); // 'sout' little endian write_stream = stream_buf_create_static(VEX_SERIAL_BUFFER_SIZE, 0, write_buf, &write_stream_buf); vfs_update_entry(STDIN_FILENO, ser_driver, &(RESERVED_SER_FILES[0])); vfs_update_entry(STDOUT_FILENO, ser_driver, &(RESERVED_SER_FILES[1])); vfs_update_entry(STDERR_FILENO, ser_driver, &(RESERVED_SER_FILES[2])); vfs_update_entry(KDBG_FILENO, ser_driver, &(RESERVED_SER_FILES[3])); } ================================================ FILE: src/system/dev/usd_driver.c ================================================ /** * \file system/dev/usd_driver.c * * Contains the driver for writing files to the microSD card. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include #include #include "common/set.h" #include "common/string.h" #include "kapi.h" #include "system/dev/usd.h" #include "system/dev/vfs.h" #include "system/optimizers.h" #include "v5_api.h" typedef struct usd_file_arg { FIL* ifi_fptr; } usd_file_arg_t; static const int FRESULTMAP[] = {0, EIO, EINVAL, EBUSY, ENOENT, ENOENT, EINVAL, EACCES, // FR_DENIED EEXIST, EINVAL, EROFS, ENXIO, ENOBUFS, ENXIO, EIO, EACCES, // FR_LOCKED ENOBUFS, ENFILE, EINVAL}; enum fa_flags { FA_READ = 1 << 0, FA_WRITE = 1 << 1, FA_CREATE_ALWAYS = 1 << 2, FA_OPEN_APPEND = 1 << 3, FA_CREATE_NEW = 1 << 4 }; /******************************************************************************/ /** newlib driver functions **/ /******************************************************************************/ int usd_read_r(struct _reent* r, void* const arg, uint8_t* buffer, const size_t len) { usd_file_arg_t* file_arg = (usd_file_arg_t*)arg; // TODO: mutex here. Global or file lock? int32_t result = vexFileRead((char*)buffer, sizeof(*buffer), len, file_arg->ifi_fptr); return result; } int usd_write_r(struct _reent* r, void* const arg, const uint8_t* buf, const size_t len) { usd_file_arg_t* file_arg = (usd_file_arg_t*)arg; // TODO: mutex here. Global or file lock? int32_t result = vexFileWrite((char*)buf, sizeof(*buf), len, file_arg->ifi_fptr); // Flush the buffer vexFileSync(file_arg->ifi_fptr); return result; } int usd_close_r(struct _reent* r, void* const arg) { usd_file_arg_t* file_arg = (usd_file_arg_t*)arg; vexFileClose(file_arg->ifi_fptr); return 0; } int usd_fstat_r(struct _reent* r, void* const arg, struct stat* st) { usd_file_arg_t* file_arg = (usd_file_arg_t*)arg; st->st_size = vexFileSize(file_arg->ifi_fptr); return 0; } int usd_isatty_r(struct _reent* r, void* const arg) { return 0; } off_t usd_lseek_r(struct _reent* r, void* const arg, off_t ptr, int dir) { usd_file_arg_t* file_arg = (usd_file_arg_t*)arg; // TODO: mutex here. Global or file lock? FRESULT result = vexFileSeek(file_arg->ifi_fptr, ptr, dir); if (result != FR_OK) { r->_errno = FRESULTMAP[result]; return (off_t)-1; } return vexFileTell(file_arg->ifi_fptr); } int usd_ctl(void* const arg, const uint32_t cmd, void* const extra_arg) { return 0; } /******************************************************************************/ /** Driver description **/ /******************************************************************************/ const struct fs_driver _usd_driver = {.close_r = usd_close_r, .fstat_r = usd_fstat_r, .isatty_r = usd_isatty_r, .lseek_r = usd_lseek_r, .read_r = usd_read_r, .write_r = usd_write_r, .ctl = usd_ctl}; const struct fs_driver* const usd_driver = &_usd_driver; int usd_open_r(struct _reent* r, const char* path, int flags, int mode) { FRESULT result = vexFileMountSD(); if (result != F_OK) { r->_errno = FRESULTMAP[result]; return -1; } usd_file_arg_t* file_arg = kmalloc(sizeof(*file_arg)); switch (flags & O_ACCMODE) { case O_RDONLY: file_arg->ifi_fptr = vexFileOpen(path, ""); // mode is ignored break; case O_WRONLY: if (flags & O_APPEND) { file_arg->ifi_fptr = vexFileOpenWrite(path); } else { file_arg->ifi_fptr = vexFileOpenCreate(path); } break; default: r->_errno = EINVAL; return -1; } if (!file_arg->ifi_fptr) { r->_errno = ENFILE; // up to 8 files max as of vexOS 0.7.4b55 return -1; } return vfs_add_entry_r(r, usd_driver, file_arg); } ================================================ FILE: src/system/dev/vfs.c ================================================ /** * \file system/dev/vfs.c * * Virtual File System * * VFS is responsible for maintaining the global file table and routing all * basic I/O to the appropriate driver. There are three drivers implemented, * ser, dev, and usd which correspond to the serial driver, generic smart port * communication, and microSD card, respectively. * * VFS implements all of the I/O newlib stubs like open/read/write and delegates * them to the file's driver. Drivers don't actually have any knowledge of the * fileno. A file number maps to a driver and driver argument, which would be * whatever metadata the driver needs to open the file * * Copyright (c) 2017-2026, Purdue University ACM SIGBots * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include "common/gid.h" #include "common/string.h" #include "kapi.h" #include "system/dev/dev.h" #include "system/dev/ser.h" #include "system/dev/usd.h" #include "system/dev/vfs.h" #include "v5_api.h" #define MAX_FILELEN 128 #define MAX_FILES_OPEN 31 #define RESERVED_FILENOS 4 // reserve stdin, stdout, stderr, kdbg // gids bitmap buffer static uint32_t file_table_bmp[gid_size_to_words(MAX_FILES_OPEN)]; // the gid structure itself static struct gid_metadata file_table_gids = {.bitmap = file_table_bmp, .max = MAX_FILES_OPEN, .reserved = RESERVED_FILENOS, .bitmap_size = gid_size_to_words(MAX_FILES_OPEN)}; // file table mapping a file descriptor number to a driver and driver argument static struct file_entry file_table[MAX_FILES_OPEN]; void vfs_initialize(void) { gid_init(&file_table_gids); ser_initialize(); // Force _GLOBAL_REENT initialization for C++ stdio to work. See D97 extern void __sinit(struct _reent * s); if (!_GLOBAL_REENT->__cleanup) __sinit(_GLOBAL_REENT); } // adds an entry to the the file system int vfs_add_entry_r(struct _reent* r, struct fs_driver const* const driver, void* arg) { uint32_t gid = gid_alloc(&file_table_gids); if (gid == 0) { r->_errno = ENFILE; return -1; } file_table[gid].driver = driver; file_table[gid].arg = arg; return gid; } // update a given fileno driver and arg. Used by ser_driver_initialize to // initialize stdout, stdin, stderr, and kdbg int vfs_update_entry(int file, struct fs_driver const* const driver, void* arg) { if (file < 0 || !gid_check(&file_table_gids, file)) { kprintf("BAD vfs update %d", file); return -1; } if (driver != NULL) { file_table[file].driver = driver; } if (arg != (void*)-1) { file_table[file].arg = arg; } return 0; } int _open(const char* file, int flags, int mode) { struct _reent* r = _REENT; // Check if the filename is too long or not NULL terminated size_t i = 0; for (i = 0; i < MAX_FILELEN; i++) { if (file[i] == '\0') { break; } } if (i == MAX_FILELEN) { r->_errno = ENAMETOOLONG; return -1; } if (strstr(file, "/ser") == file) { // is a serial pseudofile return ser_open_r(r, file + strlen("/ser"), flags, mode); } else if (strstr(file, "/usd") == file) { return usd_open_r(r, file + strlen("/usd"), flags, mode); } else if (strstr(file, "/dev") == file) { return dev_open_r(r, file + strlen("/dev"), flags, mode); } else { return usd_open_r(r, file, flags, mode); } } ssize_t _write(int file, const void* buf, size_t len) { struct _reent* r = _REENT; if (file < 0 || !gid_check(&file_table_gids, file)) { r->_errno = EBADF; kprintf("BAD write %d", file); return -1; } return file_table[file].driver->write_r(r, file_table[file].arg, buf, len); } ssize_t _read(int file, void* buf, size_t len) { struct _reent* r = _REENT; if (file < 0 || !gid_check(&file_table_gids, file)) { r->_errno = EBADF; kprintf("BAD read %d", file); return -1; } return file_table[file].driver->read_r(r, file_table[file].arg, buf, len); } int _close(int file) { struct _reent* r = _REENT; // NOTE: newlib automatically closes all open files for a given task when // the task is deleted. if (file > 0 && file < RESERVED_FILENOS) { // Do not close the reserved file handles return 0; } if (file < 0 || !gid_check(&file_table_gids, file)) { r->_errno = EBADF; kprintf("BAD close %d", file); return -1; } int ret = file_table[file].driver->close_r(r, file_table[file].arg); if (ret == 0) { gid_free(&file_table_gids, file); } return ret; } int _fstat(int file, struct stat* st) { struct _reent* r = _REENT; if (file < 0 || !gid_check(&file_table_gids, file)) { r->_errno = EBADF; kprintf("BAD fstat %d", file); return -1; } return file_table[file].driver->fstat_r(r, file_table[file].arg, st); } off_t _lseek(int file, off_t ptr, int dir) { struct _reent* r = _REENT; if (file < 0 || !gid_check(&file_table_gids, file)) { r->_errno = EBADF; kprintf("BAD lseek %d", file); return -1; } return file_table[file].driver->lseek_r(r, file_table[file].arg, ptr, dir); } int _isatty(int file) { struct _reent* r = _REENT; if (file < 0 || !gid_check(&file_table_gids, file)) { r->_errno = EBADF; kprintf("BAD isatty %d", file); return -1; } return file_table[file].driver->isatty_r(r, file_table[file].arg); } int32_t fdctl(int file, const uint32_t action, void* const extra_arg) { if (file < 0 || !gid_check(&file_table_gids, file)) { errno = EBADF; return -1; } return file_table[file].driver->ctl(file_table[file].arg, action, extra_arg); } ================================================ FILE: src/system/envlock.c ================================================ /** * \file system/envlock.c * * environment lock newlib stubs * * Contains implementations of environment-locking functions for newlib. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "rtos/task.h" void __env_lock(void) { rtos_suspend_all(); } void __env_unlock(void) { rtos_resume_all(); } ================================================ FILE: src/system/hot.c ================================================ #include "system/hot.h" #include "kapi.h" #include "v5_api.h" // stored only in cold struct hot_table __HOT_TABLE = {0}; struct hot_table* const HOT_TABLE = &__HOT_TABLE; #define MAGIC0 0x52616368 #define MAGIC1 0x8CEF7310 extern void set_get_timestamp_int_func(const int (*func)(void)); static const int get_timestamp_int(void); __attribute__((section(".hot_magic"))) uint32_t MAGIC[] = {MAGIC0, MAGIC1}; uint32_t const volatile* const MAGIC_ADDR = MAGIC; // The linker decides on these symbols in each section just as normal // When linking in hot, these pointers work just like any other weak symbol // Note: to get C++ style initialize and friends, we strip out cpp_initialize and friends so that linker // regenerates that function with the call to the correct (user-written) C++ version extern char const* _PROS_COMPILE_TIMESTAMP; extern char const* _PROS_COMPILE_DIRECTORY; extern const int _PROS_COMPILE_TIMESTAMP_INT; extern unsigned __exidx_start; extern unsigned __exidx_end; // this expands to a bunch of: // extern void autonomous(); #define FUNC(F) void F(); #include "system/user_functions/list.h" #undef FUNC __attribute__((section(".hot_init"))) void install_hot_table(struct hot_table* const tbl) { // printf("Hot initializing\n"); tbl->compile_timestamp = _PROS_COMPILE_TIMESTAMP; tbl->compile_directory = _PROS_COMPILE_DIRECTORY; tbl->__exidx_start = &__exidx_start; tbl->__exidx_end = &__exidx_end; // this expands to a bunch of: // tbl->functions.autonomous = autonomous; #define FUNC(F) tbl->functions.F = F; #include "system/user_functions/list.h" #undef FUNC // all of these weak symbols are given to us by the linker // These values should come from the hot region, since that's where this // function is linked extern __attribute__((weak)) uint8_t* __sbss_start[]; extern __attribute__((weak)) uint8_t* __sbss_end[]; memset(__sbss_start, 0, (size_t)__sbss_end - (size_t)__sbss_start); extern __attribute__((weak)) uint8_t* __bss_start[]; extern __attribute__((weak)) uint8_t* __bss_end[]; memset(__bss_start, 0, (size_t)__bss_end - (size_t)__bss_start); extern __attribute__((weak)) void (*const __preinit_array_start[])(void); extern __attribute__((weak)) void (*const __preinit_array_end[])(void); for (void (*const* ctor)() = __preinit_array_start; ctor < __preinit_array_end; ctor++) { (*ctor)(); } extern __attribute__((weak)) void (*const __init_array_start[])(void); extern __attribute__((weak)) void (*const __init_array_end[])(void); for (void (*const* ctor)() = __init_array_start; ctor < __init_array_end; ctor++) { (*ctor)(); } // Set the function pointer in newlib_stubs so that it can fetch the // timestamp in the hot package. set_get_timestamp_int_func(get_timestamp_int); } // this function really exists on the cold section! Called by pros_init // this does the check if we're running with hot/cold and invokes the hot table // installer (install_hot_table) located in hot memory void invoke_install_hot_table() { // install_hot_table is at 0x07800008 // MAGIC_ADDR is at 0x0780000 // printf("%s %p %p %x %x\n", __FUNCTION__, (void*)install_hot_table, (void*)HOT_TABLE, MAGIC_ADDR[0], MAGIC_ADDR[1]); if (vexSystemLinkAddrGet() == (uint32_t)0x03800000 && MAGIC_ADDR[0] == MAGIC0 && MAGIC_ADDR[1] == MAGIC1) { install_hot_table(HOT_TABLE); } else { memset(HOT_TABLE, 0, sizeof(*HOT_TABLE)); } } // This is a callback function used by newlib to get the unix timestamp // newlib cannot access any symbols in the hot package, so we have the hot // package pass a function pointer to this function. Newlib then uses that // function pointer. static const int get_timestamp_int(void) { return _PROS_COMPILE_TIMESTAMP_INT; } ================================================ FILE: src/system/mlock.c ================================================ /** * \file system/mlock.c * * memory lock newlib stubs * * Contains implementations of memory-locking functions for newlib. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "rtos/task.h" void __malloc_lock(void) { rtos_suspend_all(); } void __malloc_unlock(void) { rtos_resume_all(); } ================================================ FILE: src/system/newlib_stubs.c ================================================ /** * \file system/newlib_stubs.c * * Port of newlib to PROS for the V5 * * Contains the various methods needed to enable standard C library support * through the use of the Arm-distributed implementation of newlib. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include #include #include "rtos/task.h" #include "v5_api.h" #include "hot.h" #include "pros/misc.h" #define SEC_TO_MSEC 1000 #define SEC_TO_MICRO 1000000 #define MICRO_TO_NANO 1000 void _exit(int status) { extern void flush_output_streams(); flush_output_streams(); extern void ser_output_flush(); ser_output_flush(); rtos_suspend_all(); if(status != 0) dprintf(3, "Error %d\n", status); // kprintf uint32_t start_time = millis(); static const uint32_t max_flush_time = 50; while (vexSerialWriteFree(1) != 2048 || millis() - start_time > max_flush_time) { vexBackgroundProcessing(); } vexSystemExitRequest(); while (1) vexBackgroundProcessing(); } int usleep( useconds_t period ) { // Compromise: If the delay is in microsecond range, it will block threads. // if not, it will not block threads but not be accurate to the microsecond range. if(period >= 1000) { task_delay (period / SEC_TO_MSEC); return 0; } uint64_t endTime = vexSystemHighResTimeGet() + period; while(vexSystemHighResTimeGet() < endTime) asm("YIELD"); return 0; } unsigned sleep( unsigned period ) { task_delay(period * SEC_TO_MSEC); return 1; } int getentropy(void *_buffer, size_t _length) { errno = ENOSYS; return -1; } // HACK: this helps confused libc++ functions call the right instruction. for // info see https://github.com/purduesigbots/pros/issues/153#issuecomment-519335375 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winfinite-recursion" void __sync_synchronize(void) { __sync_synchronize(); } #pragma GCC diagnostic pop // These variables are used to store the user-set time. // When user_time_set is false, the realtime clock will use the timestamp as the // base time. When it is true will use user_time_spec as the base time instead. // set_microseconds stores the value of the microsecond timer when the user set // the time. static bool user_time_set = false; static struct timespec user_time_spec; static int64_t set_microseconds = 0; int clock_settime(clockid_t clock_id, const struct timespec *tp) { if(tp == NULL) { errno = EINVAL; return -1; } int retval = -1; switch(clock_id) { case CLOCK_REALTIME: user_time_set = true; user_time_spec = *tp; set_microseconds = vexSystemHighResTimeGet(); retval = 0; default: errno = EINVAL; } return retval; } int clock_gettime(clockid_t clock_id, struct timespec* tp) { if(tp == NULL) { errno = EINVAL; return -1; } struct timeval tv; int retval = -1; switch (clock_id) { case CLOCK_REALTIME: retval = gettimeofday(&tv, NULL); if (!retval) TIMEVAL_TO_TIMESPEC(&tv, tp); break; case CLOCK_MONOTONIC: { uint64_t totalTime = vexSystemHighResTimeGet(); uint64_t secs = totalTime / SEC_TO_MICRO; uint64_t micros = totalTime - secs * SEC_TO_MICRO; tp->tv_sec = secs; tp->tv_nsec = micros * MICRO_TO_NANO; break; } default: errno = EINVAL; break; } return retval; } // HACK: // // This function pointer serves as a callback so that _gettimeofday() can call // a function inside the hot package. Without this, _gettimeofday() cannot // access any symbols in the hot package (where _PROS_COMPILE_TIMESTAMP_INT // lives), and linker errors occur. // // When the hot package is initialized, it calls set_get_timestamp_int_func() // and sets the callback to a function that returns the unix timestamp. // // Essentially, when the hot process starts: // 1) Pass the get_timestamp_int_func to the cold package // 2) When the cold package (this library) needs to access the timestamp, // call the callback // 3) Then the cold package static const int (*get_timestamp_int_func)(void) = NULL; void set_get_timestamp_int_func(const int (*func)(void)) { get_timestamp_int_func = func; } int _gettimeofday(struct timeval* tp, void* tzvp) { if(get_timestamp_int_func == NULL) { return -1; } if(user_time_set) { tp->tv_sec = user_time_spec.tv_sec; tp->tv_usec = user_time_spec.tv_nsec * 1000; tp->tv_usec += vexSystemHighResTimeGet() - set_microseconds; } else if (competition_is_connected()) { // TODO: update this to get the date/time through VexOS. Apparently, // the time is kept properly only when competition controls are // connected. I haven't had time to check or confirm this. //https://github.com/purduesigbots/pros/pull/127#issuecomment-1095361338 tp->tv_sec = get_timestamp_int_func(); tp->tv_usec = vexSystemHighResTimeGet(); } else { // When competition isn't connected, the vex's date/time functions do // not work. Here we use a timestamp compiled into the program and then // add the number of microseconds the program has been running to get // the best estimate. tp->tv_sec = get_timestamp_int_func(); tp->tv_usec = vexSystemHighResTimeGet(); } return 1; } ================================================ FILE: src/system/newlib_stubs_support.cpp ================================================ #include #include // called by _exit in newlib_stubs.c extern "C" void flush_output_streams() { fflush(stdout); std::cout.flush(); } ================================================ FILE: src/system/rtos_hooks.c ================================================ /** * \file system/rtos_hooks.c * * FreeRTOS hooks for initialization and interrupts * * FreeRTOS requires some porting to each platform to handle certain tasks. This * file contains the various methods required to be implemented for FreeRTOS. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "pros/motors.h" #include "rtos/FreeRTOS.h" #include "rtos/semphr.h" #include "rtos/task.h" #include "rtos/tcb.h" #include "v5_api.h" #include "v5_color.h" // Fast interrupt handler void FIQInterrupt() { vexSystemFIQInterrupt(); } // Replacement for DataAbortInterrupt void DataAbortInterrupt() { taskDISABLE_INTERRUPTS(); register int sp; asm("add %0,sp,#8\n" : "=r"(sp)); extern void report_fatal_error(uint32_t _sp, const char* error_name); report_fatal_error(sp, "DATA ABORT EXCEPTION"); for(uint8_t i = 1; i <= 21; i++) { motor_move_voltage(i, 0); } for (;;) { vexBackgroundProcessing(); extern void ser_output_flush(); ser_output_flush(); } } // Replacement for PrefetchAbortInterrupt void PrefetchAbortInterrupt() { taskDISABLE_INTERRUPTS(); register int sp; asm("add %0,sp,#8\n" : "=r"(sp)); extern void report_fatal_error(uint32_t _sp, const char* error_name); report_fatal_error(sp, "PREFETCH ABORT EXCEPTION"); for(uint8_t i = 1; i <= 21; i++) { motor_move_voltage(i, 0); } for (;;) { vexBackgroundProcessing(); extern void ser_output_flush(); ser_output_flush(); } } void _boot() { vexSystemBoot(); } extern void vPortInstallFreeRTOSVectorTable(void); void rtos_initialize() { vexSystemTimerStop(); portDISABLE_INTERRUPTS(); vPortInstallFreeRTOSVectorTable(); void task_notify_when_deleting_init(); task_notify_when_deleting_init(); } extern void FreeRTOS_Tick_Handler(void); void rtos_tick_interrupt_config() { vexSystemTimerReinitForRtos(portLOWEST_USABLE_INTERRUPT_PRIORITY << portPRIORITY_SHIFT, (void (*)(void*))FreeRTOS_Tick_Handler); } void rtos_tick_interrupt_clear() { vexSystemTimerClearInterrupt(); } void vApplicationFPUSafeIRQHandler(uint32_t ulICCIAR) { vexSystemApplicationIRQHandler(ulICCIAR); } void vInitialiseTimerForRunTimeStats(void) { vexSystemWatchdogReinitRtos(); } void vApplicationMallocFailedHook(void) { // Called if a call to kmalloc() fails because there is insufficient free // memory available in the FreeRTOS heap. kmalloc() is called internally by // FreeRTOS API functions that create tasks, queues, software timers, and // semaphores. The size of the FreeRTOS heap is set by the // configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. taskDISABLE_INTERRUPTS(); for (;;) ; } void vApplicationStackOverflowHook(task_t pxTask, char* pcTaskName) { (void)pcTaskName; (void)pxTask; vexSerialWriteBuffer(1, (uint8_t*)"FATAL ERROR!! Task ", 19); vexSerialWriteBuffer(1, (uint8_t*)pcTaskName, 30); vexSerialWriteBuffer(1, (uint8_t*)" overflowed its stack!\n", 23); // Run time stack overflow checking is performed if // configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook function is // called if a stack overflow is detected. taskDISABLE_INTERRUPTS(); for (;;) vexBackgroundProcessing(); ; } void vApplicationIdleHook(void) { volatile size_t xFreeHeapSpace; // This is just a trivial example of an idle hook. It is called on each cycle // of the idle task. It must *NOT* attempt to block. In this case the idle // task just queries the amount of FreeRTOS heap that remains. See the memory // management section on the http://www.FreeRTOS.org web site for memory // management options. If there is a lot of heap memory free then the // configTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up // RAM. xFreeHeapSpace = xPortGetFreeHeapSize(); // Remove compiler warning about xFreeHeapSpace being set but never used. (void)xFreeHeapSpace; } void vAssertCalled(const char* pcFile, unsigned long ulLine) { volatile unsigned long ul = 0; (void)pcFile; (void)ulLine; taskENTER_CRITICAL(); { // Set ul to a non-zero value using the debugger to step out of // this function. while (ul == 0) { portNOP(); } } taskEXIT_CRITICAL(); } // FreeRTOS V9 now allows static memory allocation for tasks // the helper functions below are copied verbatim from demo code #if (configSUPPORT_STATIC_ALLOCATION == 1) // configSUPPORT_STATIC_ALLOCATION is set to 1, so the application must provide // an implementation of vApplicationGetIdleTaskMemory() to provide the memory // that is used by the Idle task. void vApplicationGetIdleTaskMemory(static_task_s_t** ppxIdleTaskTCBBuffer, task_stack_t** ppxIdleTaskStackBuffer, uint32_t* pulIdleTaskStackSize) { // If the buffers to be provided to the Idle task are declared inside this // function then they must be declared static - otherwise they will be // allocated on the stack and so not exists after this function exits. static static_task_s_t xIdleTaskTCB; static task_stack_t uxIdleTaskStack[configMINIMAL_STACK_SIZE]; // Pass out a pointer to the static_task_s_t structure in which the Idle // task's state will be stored. *ppxIdleTaskTCBBuffer = &xIdleTaskTCB; // Pass out the array that will be used as the Idle task's stack. *ppxIdleTaskStackBuffer = uxIdleTaskStack; // Pass out the size of the array pointed to by *ppxIdleTaskStackBuffer. // Note that, as the array is necessarily of type task_stack_t, // configMINIMAL_STACK_SIZE is specified in words, not bytes. *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; } // configSUPPORT_STATIC_ALLOCATION and configUSE_TIMERS are both set to 1, so // the application must provide an implementation of // vApplicationGetTimerTaskMemory() to provide the memory that is used by the // Timer service task. void vApplicationGetTimerTaskMemory(static_task_s_t** ppxTimerTaskTCBBuffer, task_stack_t** ppxTimerTaskStackBuffer, uint32_t* pulTimerTaskStackSize) { // If the buffers to be provided to the Timer task are declared inside this // function then they must be declared static - otherwise they will be // allocated on the stack and so not exists after this function exits. static static_task_s_t xTimerTaskTCB; static task_stack_t uxTimerTaskStack[configTIMER_TASK_STACK_DEPTH]; // Pass out a pointer to the static_task_s_t structure in which the Timer // task's state will be stored. *ppxTimerTaskTCBBuffer = &xTimerTaskTCB; // Pass out the array that will be used as the Timer task's stack. *ppxTimerTaskStackBuffer = uxTimerTaskStack; // Pass out the size of the array pointed to by // *ppxTimerTaskStackBuffer. Note that, as the array is necessarily of type // task_stack_t, configMINIMAL_STACK_SIZE is specified in words, not bytes. *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; } #endif /******************************************************************************/ /** Replacements for mem functions **/ /** **/ /** See https://goo.gl/cHUA9b for more details **/ /** Unsure if necessary due to Arm's newlib optimization **/ /******************************************************************************/ #if 0 #if (configUSE_TASK_FPU_SUPPORT == 2) void* memcpy(void* restrict out, void const* restrict in, size_t n) { // modified GNU algorithm to copy a word at a time uint32_t* restrict lout; uint32_t const* restrict lin; if (!((uint32_t)in & 0xFFFFFFFC) && !((uint32_t)out & 0xFFFFFFFC)) { while(n >= sizeof(unt32_t)) { *lout++ = *lin++; n -= sizeof(uint32_t); } } } void* memcpy(void *pvDest, void const *pvSource, size_t len) { long *plDst = (long *)pvDest; long const *plSrc = (long const *)pvSource; if (!((uint32_t)pvSource & 0xFFFFFFFC) && !((uint32_t)pvDest & 0xFFFFFFFC)) { while (len >= 4) { *plDst++ = *plSrc++; len -= 4; } } char *pcDst = (char *)plDst; char const *pcSrc = (char const *)plSrc; while (len--) *pcDst++ = *pcSrc++; return (pvDest); } /*-----------------------------------------------------------*/ void *memset(void *pvDest, int iValue, size_t ulBytes) { volatile unsigned char *pcDest = (unsigned char *)pvDest; if (ulBytes > 0) { do { *pcDest++ = (unsigned char)iValue; } while (--ulBytes != 0); } return pvDest; } /*-----------------------------------------------------------*/ int memcmp(const void *pvMem1, const void *pvMem2, size_t ulBytes) { const unsigned char *pucMem1 = pvMem1, *pucMem2 = pvMem2; size_t x; for (x = 0; x < ulBytes; x++) { if (pucMem1[x] != pucMem2[x]) { break; } } return ulBytes - x; } #endif #endif ================================================ FILE: src/system/startup.c ================================================ /** * \file system/startup.c * * Contains the main startup code for PROS 3.0. main is called from vexStartup * code. Our main() initializes data structures and starts the FreeRTOS * scheduler. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include "kapi.h" #include "v5_api.h" extern void rtos_initialize(); extern void vfs_initialize(); extern void system_daemon_initialize(); extern void graphical_context_daemon_initialize(void); extern __attribute__((weak)) void display_initialize(void) {} extern void rtos_sched_start(); extern void vdml_initialize(); extern void invoke_install_hot_table(); // XXX: pros_init happens inside __libc_init_array, and before any global // C++ constructors are invoked. This is accomplished by instructing // GCC to include this function in the __init_array. The 102 argument // gives the compiler instructions on the priority of the constructor, // from 0-~65k. The first 0-100 priorities are reserved for language // implementation. Priority 101 is not used to allow functions such as // banner_enable to run before PROS initializes. __attribute__((constructor(102))) static void pros_init(void) { rtos_initialize(); vfs_initialize(); vdml_initialize(); graphical_context_daemon_initialize(); display_initialize(); // NOTE: this function should be called after all other initialize // functions. for an example of what could happen if this is not // the case, see // https://github.com/purduesigbots/pros/pull/144/#issuecomment-496901942 system_daemon_initialize(); invoke_install_hot_table(); } int main() { rtos_sched_start(); vexDisplayPrintf(10, 60, 1, "failed to start scheduler\n"); printf("Failed to start Scheduler\n"); for (;;) ; } ================================================ FILE: src/system/system_daemon.c ================================================ /** * \file system/system_daemon.c * * Competition control daemon responsible for invoking the user tasks. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "kapi.h" #include "system/optimizers.h" #include "system/user_functions.h" #include "v5_api.h" extern void vdml_background_processing(); extern void port_mutex_take_all(); extern void port_mutex_give_all(); static task_stack_t competition_task_stack[TASK_STACK_DEPTH_DEFAULT]; static static_task_s_t competition_task_buffer; static task_t competition_task; static task_stack_t system_daemon_task_stack[TASK_STACK_DEPTH_DEFAULT]; static static_task_s_t system_daemon_task_buffer; static task_t system_daemon_task; static void _disabled_task(void* ign); static void _autonomous_task(void* ign); static void _opcontrol_task(void* ign); static void _competition_initialize_task(void* ign); static void _initialize_task(void* ign); static void _system_daemon_task(void* ign); enum state_task { E_OPCONTROL_TASK = 0, E_AUTON_TASK, E_DISABLED_TASK, E_COMP_INIT_TASK }; char task_names[4][32] = {"User Operator Control (PROS)", "User Autonomous (PROS)", "User Disabled (PROS)", "User Comp. Init. (PROS)"}; task_fn_t task_fns[4] = {_opcontrol_task, _autonomous_task, _disabled_task, _competition_initialize_task}; extern void ser_output_flush(void); // does the basic background operations that need to occur every 2ms static inline void do_background_operations() { port_mutex_take_all(); ser_output_flush(); rtos_suspend_all(); vexBackgroundProcessing(); rtos_resume_all(); vdml_background_processing(); port_mutex_give_all(); } static void _system_daemon_task(void* ign) { uint32_t time = millis(); // Initialize status to an invalid state to force an update the first loop uint32_t status = (uint32_t)(1 << 8); uint32_t task_state; // XXX: Delay likely necessary for shared memory to get copied over // (discovered b/c VDML would crash and burn) // Take all port mutexes to prevent user code from attempting to access VDML during this time. User code could be // running if a task is created from a global ctor port_mutex_take_all(); task_delay(2); port_mutex_give_all(); // start up user initialize task. once the user initialize function completes, // the _initialize_task will notify us and we can go into normal competition // monitoring mode competition_task = task_create_static(_initialize_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "User Initialization (PROS)", competition_task_stack, &competition_task_buffer); time = millis(); while (!task_notify_take(true, 2)) { // wait for initialize to finish do_background_operations(); } while (1) { do_background_operations(); if (unlikely(status != competition_get_status())) { // Have a new competition status, need to clean up whatever's running uint32_t old_status = status; status = competition_get_status(); enum state_task state = E_OPCONTROL_TASK; if ((status & COMPETITION_DISABLED) && (old_status & COMPETITION_DISABLED)) { // Don't restart the disabled task even if other bits have changed (e.g. auton bit) continue; } // competition initialize runs only when entering disabled and we're // connected to competition control if ((status ^ old_status) & COMPETITION_CONNECTED && (status & (COMPETITION_DISABLED | COMPETITION_CONNECTED)) == (COMPETITION_DISABLED | COMPETITION_CONNECTED)) { state = E_COMP_INIT_TASK; } else if (status & COMPETITION_DISABLED) { state = E_DISABLED_TASK; } else if (status & COMPETITION_AUTONOMOUS) { state = E_AUTON_TASK; } task_state = task_get_state(competition_task); // delete the task only if it's in normal operation (e.g. not deleted) // The valid task states AREN'T deleted, invalid, or running (running // means it's the current task, which will never be the case) if (task_state == E_TASK_STATE_READY || task_state == E_TASK_STATE_BLOCKED || task_state == E_TASK_STATE_SUSPENDED) { task_delete(competition_task); } competition_task = task_create_static(task_fns[state], NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, task_names[state], competition_task_stack, &competition_task_buffer); } task_delay_until(&time, 2); } } void system_daemon_initialize() { system_daemon_task = task_create_static(_system_daemon_task, NULL, TASK_PRIORITY_MAX - 2, TASK_STACK_DEPTH_DEFAULT, "PROS System Daemon", system_daemon_task_stack, &system_daemon_task_buffer); } // these functions are what actually get called by the system daemon, which // attempt to call whatever the user declares #define FUNC(NAME) \ static void _##NAME##_task(void* ign) { \ user_##NAME(); \ task_notify(system_daemon_task); \ } #include "system/user_functions/c_list.h" #undef FUNC ================================================ FILE: src/system/unwind.c ================================================ /** * unwind.c - Unwind functions specialized for PROS * * Unwinding is necessary in PROS because tasks containing C++ stack frames may * be arbitrarily stopped, requiring us to call all the destructors of the task * to be killed. * * \Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include #include "unwind-arm-common.h" #include "rtos/task.h" #include "rtos/tcb.h" #include "system/hot.h" #include "v5_api.h" /******************************************************************************/ /** Helpful Unwind Files **/ /******************************************************************************* https://github.com/gcc-mirror/gcc/blob/master/libgcc/unwind-arm-common.inc https://github.com/gcc-mirror/gcc/blob/master/libgcc/config/arm/unwind-arm.c https://github.com/gcc-mirror/gcc/blob/master/libgcc/config/arm/unwind-arm.h https://github.com/gcc-mirror/gcc/blob/master/gcc/ginclude/unwind-arm-common.h http://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf *******************************************************************************/ /******************************************************************************/ /** Unwind Definitions **/ /** **/ /** These structs and extern'd functions come from unwind-arm.c **/ /******************************************************************************/ #define R_SP 12 #define R_LR 13 #define R_PC 15 struct core_regs { _uw r[16]; }; struct phase2_vrs { _uw demand_save_flags; struct core_regs core; }; // from unwind-arm-common.inc extern _Unwind_Reason_Code __gnu_Unwind_Backtrace(_Unwind_Trace_Fn, void*, struct phase2_vrs*); /******************************************************************************/ /** Unwind Helpers **/ /** **/ /** These functions and definitions are helpers for supporting PROS's usage **/ /** of unwinding **/ /******************************************************************************/ static inline void print_phase2_vrs(struct phase2_vrs* vrs) { static const char registers[16][4] = {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc"}; for (size_t i = 0; i < 16; i++) { fprintf(stderr, "%3s: 0x%08x ", registers[i], vrs->core.r[i]); if (i % 8 == 7) printf("\n"); } fputs("\n", stderr); } // exidx is the table that tells the unwinder how to unwind a stack frame // for a PC. Under hot/cold, there's two tables and the unwinder was kind // enough to let us implement a function to give it a table for a PC so // support for hot/cold is as easy as it gets struct __EIT_entry { _uw fnoffset; _uw content; }; // these are all defined by the linker extern struct __EIT_entry __exidx_start; extern struct __EIT_entry __exidx_end; extern uint8_t start_of_cold_mem, end_of_cold_mem, start_of_hot_mem, end_of_hot_mem; _Unwind_Ptr __gnu_Unwind_Find_exidx(_Unwind_Ptr pc, int* nrec) { // check if pc is in the hot region if (HOT_TABLE && (void*)&start_of_hot_mem < (void*)pc && (void*)pc < (void*)&end_of_hot_mem) { *nrec = (struct __EIT_entry*)HOT_TABLE->__exidx_end - (struct __EIT_entry*)HOT_TABLE->__exidx_start; return (_Unwind_Ptr)HOT_TABLE->__exidx_start; } // otherwise, we're in a monolith build or the cold region of a hot/cold build *nrec = &__exidx_end - &__exidx_start; return (_Unwind_Ptr)&__exidx_start; } struct trace_t { uint32_t pcs[20]; size_t size; bool truncated; }; _Unwind_Reason_Code trace_fn(_Unwind_Context* unwind_ctx, void* d) { struct trace_t* trace = (struct trace_t*)d; uint32_t pc = _Unwind_GetIP(unwind_ctx); fprintf(stderr, "\t%p\n", (void*)pc); if (trace) { if (trace->size < sizeof(trace->pcs) / sizeof(trace->pcs[0])) { trace->pcs[trace->size++] = pc; } else { trace->truncated = true; } } extern void task_clean_up(); if (pc == (uint32_t)task_clean_up) { return _URC_FAILURE; } return _URC_NO_REASON; } /******************************************************************************/ /** Data Abort Handler **/ /** **/ /** These functions use the __gnu_Unwind_* functions providing our helper **/ /** functions and phase2_vrs structure based on a target task **/ /******************************************************************************/ // recover registers from a data abort. Specific knowledge about callee stack // used from FreeRTOS_DataAbortHandler and it calling DataAbortInterrupt // NOTE: this function needs to be compiled in ARM mode and not Thumb mode // (hence the attribute), due to the specific assembly used here, which is // not supported in Thumb mode. __attribute__((target("arm"))) void p2vrs_from_data_abort(_uw* sp, struct phase2_vrs* vrs) { // sp is stack pointer when FreeRTOS_DataAbortHandler invokes DataAbortInterrupt vrs->demand_save_flags = 0; // start pulling these registers off the stack // see xilinx_vectors.s:114 stmdb sp!,{r0-r3,r12,lr} vrs->core.r[0] = sp[0]; vrs->core.r[1] = sp[1]; vrs->core.r[2] = sp[2]; vrs->core.r[3] = sp[3]; vrs->core.r[4] = sp[-1]; // DataAbortInterrupt pushes this onto stack, so grab it back // r5-r11 were never touched, so we can just plop them in asm("stm %0!, {r5-r11}\n" : : "r"(vrs->core.r + 5)); vrs->core.r[12] = sp[4]; // sp/lr are in (banked) user registers. recover them from there. ref B9.3.17 of AARM for v7-a/r asm("stm %0, {r13,r14}^" : : "r"(vrs->core.r + 13)); vrs->core.r[15] = sp[5] - 8; } // called by DataAbortInterrupt and PrefetchAbortInterrupt in rtos_hooks.c //void report_data_abort(uint32_t _sp) { void report_fatal_error(uint32_t _sp, const char* error_name) { struct phase2_vrs vrs; p2vrs_from_data_abort((_uw*)_sp, &vrs); fputs("\n\n", stderr); fputs(error_name, stderr); fputs("\n\n", stderr); vexDisplayForegroundColor(ClrWhite); vexDisplayBackgroundColor(ClrRed); vexDisplayRectClear(0, 25, 480, 200); vexDisplayString(2, error_name); vexDisplayString(3, "PC: %x", vrs.core.r[R_PC]); int brain_line_no = 4; if (pxCurrentTCB) { vexDisplayString(brain_line_no++, "CURRENT TASK: %.32s\n", pxCurrentTCB->pcTaskName); fprintf(stderr, "CURRENT TASK: %.32s\n", pxCurrentTCB->pcTaskName); } fputs("REGISTERS AT ERROR\n", stderr); print_phase2_vrs(&vrs); fputs("BEGIN STACK TRACE\n", stderr); fprintf(stderr, "\t%p\n", (void*)vrs.core.r[R_PC]); struct trace_t trace = {{0}, 0, false}; __gnu_Unwind_Backtrace(trace_fn, &trace, &vrs); fputs("END OF TRACE\n", stderr); for(size_t i = 0; i < trace.size; i += 4) { switch (trace.size - i) { case 1: vexDisplayString(brain_line_no++, "TRACE: 0x%x", trace.pcs[i]); break; case 2: vexDisplayString(brain_line_no++, "TRACE: 0x%x 0x%x", trace.pcs[i], trace.pcs[i+1]); break; case 3: vexDisplayString(brain_line_no++, "TRACE: 0x%x 0x%x 0x%x", trace.pcs[i], trace.pcs[i+1], trace.pcs[i+2]); break; default: vexDisplayString(brain_line_no++, "TRACE: 0x%x 0x%x 0x%x 0x%x", trace.pcs[i], trace.pcs[i+1], trace.pcs[i+2], trace.pcs[i+3]); break; } } if (trace.truncated) { vexDisplayString(brain_line_no++, "Trace was truncated, see terminal for full trace"); } struct mallinfo info = mallinfo(); fprintf(stderr, "HEAP USED: %d bytes\n", info.uordblks); if (pxCurrentTCB) { fprintf(stderr, "STACK REMAINING AT ERROR: %lu bytes\n", vrs.core.r[R_SP] - (uint32_t)pxCurrentTCB->pxStack); } } /******************************************************************************/ /** Modified RTOS-Task Target Unwinder Functions **/ /** **/ /** These functions use the __gnu_Unwind_* functions providing our helper **/ /** functions and phase2_vrs structure based on a target task **/ /******************************************************************************/ #define REGISTER_BASE 67 static inline struct phase2_vrs p2vrs_from_task(task_t task) { // should be called with the task scheduler suspended taskENTER_CRITICAL(); TCB_t* tcb = (TCB_t*)task; size_t i; struct phase2_vrs vrs; if (tcb == NULL) { tcb = pxCurrentTCB; } vrs.demand_save_flags = 0; switch (task_get_state(task)) { case E_TASK_STATE_READY: for (i = 0; i < 12; i++) { vrs.core.r[i] = tcb->pxTopOfStack[REGISTER_BASE + i]; } vrs.core.r[13] = (_uw)(tcb->pxTopOfStack + REGISTER_BASE + 16); // r13 is sp vrs.core.r[14] = tcb->pxTopOfStack[REGISTER_BASE + 13]; // r14 is lr vrs.core.r[15] = tcb->pxTopOfStack[REGISTER_BASE + 14]; // r15 is pc break; case E_TASK_STATE_BLOCKED: // for(i = 0; i < 12; i++) { // vrs.core.r[i] = tcb->pxTopOfStack[REGISTER_BASE + i]; // } // vrs.core.r[13] = (_uw)(tcb->pxTopOfStack + REGISTER_BASE + 29); // vrs.core.r[14] = tcb->pxTopOfStack[REGISTER_BASE + ] break; case E_TASK_STATE_RUNNING: break; case E_TASK_STATE_SUSPENDED: break; case E_TASK_STATE_DELETED: // will never happen case E_TASK_STATE_INVALID: default: break; } taskEXIT_CRITICAL(); return vrs; } void backtrace_task(task_t task) { struct phase2_vrs vrs = p2vrs_from_task(task); printf("Trace:\n"); __gnu_Unwind_Backtrace(trace_fn, NULL, &vrs); printf("finished trace\n"); } ================================================ FILE: src/system/user_functions.c ================================================ #include "system/user_functions.h" #include "kapi.h" #include "system/hot.h" // how this all works... // system daemon starts an autonomous task which calls user_autonomous() // user_autonomous will invoke a hot-linked autonomous if one is available // The invoked autonomous may actually just invoke user_cpp_autonomous // which will invoke a C routine which calls C++ autonomous routine // Our weak functions call C++ links of these functions, allowing users to only optionally extern "C" the task functions // these are implemented in cpp_support.cpp // FUNC(cpp_autonomous) expands to: // extern void cpp_autonomous(); #define FUNC(NAME) extern void NAME(); #include "system/user_functions/cpp_list.h" #undef FUNC // default implementations of the different competition modes attempt to call // the C++ linkage version of the function // FUNC(autonomous) exapnds to: // __attribute__((weak)) void autonomous() { user_cpp_autonomous(); } #define FUNC(NAME) \ __attribute__((weak)) void NAME() { \ user_cpp_##NAME(); \ } #include "system/user_functions/c_list.h" #undef FUNC // FUNC(cpp_autonomous) exapnds to: // void user_cpp_autonomous() { // if(HOT_TABLE && HOT_TABLE->functions.cpp_autonomous) { // HOT_TABLE->functions.cpp_autonomous(); // } else { // cpp_autonomous(); // } // } #define FUNC(NAME) \ void user_##NAME() { \ if (HOT_TABLE && HOT_TABLE->functions.NAME) { \ HOT_TABLE->functions.NAME(); \ } else { \ NAME(); \ } \ } #include "system/user_functions/list.h" #undef FUNC ================================================ FILE: src/system/xilinx_vectors.s ================================================ /****************************************************************************** * * (c) Copyright 2009-13 Xilinx, Inc. All rights reserved. * * This file contains confidential and proprietary information of Xilinx, Inc. * and is protected under U.S. and international copyright and other * intellectual property laws. * * DISCLAIMER * This disclaimer is not a license and does not grant any rights to the * materials distributed herewith. Except as otherwise provided in a valid * license issued to you by Xilinx, and to the maximum extent permitted by * applicable law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL * FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, * IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF * MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; * and (2) Xilinx shall not be liable (whether in contract or tort, including * negligence, or under any other theory of liability) for any loss or damage * of any kind or nature related to, arising under or in connection with these * materials, including for any direct, or any indirect, special, incidental, * or consequential loss or damage (including loss of data, profits, goodwill, * or any type of loss or damage suffered as a result of any action brought by * a third party) even if such damage or loss was reasonably foreseeable or * Xilinx had been advised of the possibility of the same. * * CRITICAL APPLICATIONS * Xilinx products are not designed or intended to be fail-safe, or for use in * any application requiring fail-safe performance, such as life-support or * safety devices or systems, Class III medical devices, nuclear facilities, * applications related to the deployment of airbags, or any other applications * that could lead to death, personal injury, or severe property or * environmental damage (individually and collectively, "Critical * Applications"). Customer assumes the sole risk and liability of any use of * Xilinx products in Critical Applications, subject only to applicable laws * and regulations governing limitations on product liability. * * THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE * AT ALL TIMES. * ******************************************************************************/ /*****************************************************************************/ /** * @file asm_vectors.s * * This file contains the initial vector table for the Cortex A9 processor * *
* MODIFICATION HISTORY:
*
* Ver   Who     Date     Changes
* ----- ------- -------- ---------------------------------------------------
* 1.00a ecm/sdm 10/20/09 Initial version
* 3.05a sdm	02/02/12 Save lr when profiling is enabled
* 3.10a srt     04/18/13 Implemented ARM Erratas. Please refer to file
*			 'xil_errata.h' for errata description
* 
* * @note * * None. * ******************************************************************************/ //#include "xil_errata.h" #define CONFIG_ARM_ERRATA_775420 1 .org 0 .text .arm .global _boot .global _freertos_vector_table .global FIQInterrupt .global DataAbortInterrupt .global PrefetchAbortInterrupt .global vPortInstallFreeRTOSVectorTable .extern FreeRTOS_IRQ_Handler .extern FreeRTOS_SWI_Handler .section .freertos_vectors _freertos_vector_table: B _boot B FreeRTOS_Undefined ldr pc, _swi B FreeRTOS_PrefetchAbortHandler B FreeRTOS_DataAbortHandler NOP /* Placeholder for address exception vector*/ LDR PC, _irq B FreeRTOS_FIQHandler _irq: .word FreeRTOS_IRQ_Handler _swi: .word FreeRTOS_SWI_Handler .align 4 FreeRTOS_FIQHandler: /* FIQ vector handler */ stmdb sp!,{r0-r3,r12,lr} /* state save from compiled code */ FIQLoop: blx FIQInterrupt /* FIQ vector */ ldmia sp!,{r0-r3,r12,lr} /* state restore from compiled code */ subs pc, lr, #4 /* adjust return */ .align 4 FreeRTOS_Undefined: /* Undefined handler */ b . .align 4 FreeRTOS_DataAbortHandler: /* Data Abort handler */ #ifdef CONFIG_ARM_ERRATA_775420 dsb #endif stmdb sp!,{r0-r3,r12,lr} /* state save from compiled code */ blx DataAbortInterrupt /*DataAbortInterrupt :call C function here */ ldmia sp!,{r0-r3,r12,lr} /* state restore from compiled code */ subs pc, lr, #4 /* adjust return */ .align 4 FreeRTOS_PrefetchAbortHandler: /* Prefetch Abort handler */ #ifdef CONFIG_ARM_ERRATA_775420 dsb #endif stmdb sp!,{r0-r3,r12,lr} /* state save from compiled code */ blx PrefetchAbortInterrupt /* PrefetchAbortInterrupt: call C function here */ ldmia sp!,{r0-r3,r12,lr} /* state restore from compiled code */ subs pc, lr, #4 /* adjust return */ .align 4 .type vPortInstallFreeRTOSVectorTable, %function vPortInstallFreeRTOSVectorTable: /* Set VBAR to the vector table that contains the FreeRTOS handlers. */ ldr r0, =_freertos_vector_table mcr p15, 0, r0, c12, c0, 0 dsb isb bx lr .end ================================================ FILE: src/tests/adi.cpp ================================================ /** * \file tests/adi.cpp * * Test code for various ADI things * * NOTE: There should also be a call to the constructor for the gyroscope object * in initialize() for calibration to occur before the opcontrol code. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" void opcontrol() { pros::ADIGyro gyro ('c', 1/1.8); pros::ADIDigitalIn dig (4); pros::ADIEncoder enc (5, 6, true); uint32_t now = pros::millis(); while (true) { if (dig.get_new_press()) pros::lcd::print(4, "here"); pros::lcd::print(2, "%d", enc.get_value()); pros::lcd::print(1, "%f", gyro.get_value()); if (pros::millis() - now > 5000) { gyro.reset(); now = pros::millis(); } pros::delay(20); } } ================================================ FILE: src/tests/basic_test.c ================================================ #include "main.h" void my_task(void* ign) { while (true) { printf("There are %d objects\n", vision_get_object_count(20)); delay(20); } } void my_task2(void* ign) { while (true) { int left = controller_get_analog(CONTROLLER_MASTER, ANALOG_LEFT_Y); int right = controller_get_analog(CONTROLLER_MASTER, ANALOG_RIGHT_Y); motor_move(1, left); motor_move(11, right); delay(20); } } void opcontrol() { task_create(my_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "My Task"); // task_create(my_task2, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "my Task 2"); while (true) { int left = controller_get_analog(CONTROLLER_MASTER, ANALOG_LEFT_Y); int right = controller_get_analog(CONTROLLER_MASTER, ANALOG_RIGHT_Y); // printf("%d, %d\n", left, right); puts("Hello from opcontrol"); motor_move(11, left); motor_move(1, -right); delay(20); } } ================================================ FILE: src/tests/basic_test.cpp ================================================ #include #include "main.h" void my_task(void* str) { pros::Vision vision(20); while (true) { std::cout << (char*)str << std::endl; std::cout << vision.get_object_count() << std::endl; pros::delay(20); } } void opcontrol() { { std::string s = "Hello world"; pros::Task t(my_task, (void*)(s.c_str())); } while (true) { pros::Motor(11).move(pros::Controller(E_CONTROLLER_MASTER).get_analog(E_CONTROLLER_ANALOG_LEFT_Y)); pros::Motor(1).move(-pros::Controller(E_CONTROLLER_MASTER).get_analog(E_CONTROLLER_ANALOG_RIGHT_Y)); std::puts("Hello from opcontrol"); pros::Task::delay(20); } } ================================================ FILE: src/tests/errno_reentrancy.c ================================================ #include #include "api.h" #include "v5_api.h" void task_a_fn(void* ign) { vexDisplayString(2, "Errno from A is: %d\n", errno); task_delay(1000); errno = ENOEXEC; while (1) { vexDisplayString(2, "Errno from A is: %d\n", errno); task_delay(10); } } void task_b_fn(void* ign) { while (1) { vexDisplayString(3, "Errno from B is: %d\n", errno); task_delay(10); } } void test_errno_reentrancy() { task_create(task_a_fn, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Task A"); task_create(task_b_fn, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Task B"); } ================================================ FILE: src/tests/exceptions.cpp ================================================ #include #include #include "v5_api.h" #include "rtos/FreeRTOS.h" #include "rtos/task.h" extern "C" void throw_it() { throw std::runtime_error("RT err in function"); } extern "C" void test_exceptions() { vexDisplayErase(); vexDisplayString(0, "Starting test"); throw_it(); vexDisplayString(3, "it didn't work"); } ================================================ FILE: src/tests/ext_adi.cpp ================================================ /** * \file tests/ext_adi.cpp * * Test code for various External ADI things * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" void opcontrol() { pros::ADIUltrasonic ultra({1, 'a', 'b'}); pros::ADIButton button({1, 'c'}); pros::ADIEncoder enc({1, 5, 6}, true); uint32_t now = pros::millis(); while (true) { pros::lcd::print(3, "%d", ultra.get_value()); pros::lcd::print(2, "%d", button.get_value()); pros::lcd::print(1, "%d", enc.get_value()); pros::delay(20); } } ================================================ FILE: src/tests/generic_serial.cpp ================================================ /** * \file tests/generic_serial.cpp * * Test code for the generic serial driver * * NOTE: There should be a cable plugged into ports 1 and 2, connecting * them together * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" #include #include "pros/apix.h" pros::Serial *serial_w = nullptr, *serial_r = nullptr; constexpr bool VERBOSE_OUTPUT = false; constexpr uint32_t BUF_SIZE = 65536; uint8_t out_buf[BUF_SIZE], in_buf[BUF_SIZE]; void verbose_printf(const char *format, ...) { if (VERBOSE_OUTPUT) { va_list va; va_start(va, format); vprintf(format, va); va_end(va); } } bool test_send_recv_byte(const uint32_t interval, const uint32_t bytes) { printf("%07d Starting send/recv byte test with an interval of %dms for %d bytes...\n", pros::millis(), interval, bytes); uint8_t count = 0, expected = 0; uint32_t last_send_time = 0, cur_time, recv_count = 0; bool pass = true; do { cur_time = pros::millis(); if (cur_time - last_send_time >= interval) { int32_t w = serial_w->write_byte(count); if (w == PROS_ERR) { pass = false; printf("%07d Write failed with error %d\n", cur_time, errno); break; } else if (w) { count++; last_send_time = cur_time; } } int32_t read = serial_r->read_byte(); if (read == PROS_ERR) { pass = false; printf("%07d Read failed with error %d\n", cur_time, errno); break; } else if (read >= 0) { if (read != expected) { printf("%07d ERR Read: 0x%02x, Expt: 0x%02x\n", cur_time, read, expected); pass = false; } else { verbose_printf("%07d 0x%02x\n", cur_time, read); } expected++; recv_count++; } pros::delay(interval); } while (recv_count < bytes); if (pass) printf("%07d PASS\n", pros::millis()); else printf("%07d FAIL\n", pros::millis()); return pass; } bool test_send_recv_block() { printf("%07d Starting send/recv block test...\n", pros::millis()); uint32_t written = 0, read = 0; bool pass = true; for (uint32_t i = 0; i < BUF_SIZE; i++) { out_buf[i] = i; } while (written < BUF_SIZE || read < BUF_SIZE) { uint32_t cur_time = pros::millis(); int32_t r = serial_r->read(in_buf + read, BUF_SIZE - read); if (r == PROS_ERR) { pass = false; printf("%07d Read failed with error %d\n", cur_time, errno); break; } else if (r) { verbose_printf("%07d R %d [", cur_time, r); for (int32_t i = 0; i < r; i++) { verbose_printf("%02x", in_buf[read + i]); if (in_buf[read + i] != out_buf[read + i]) { pass = false; verbose_printf(" (%02x)", out_buf[read + i]); } if (i < r - 1) verbose_printf(", "); } verbose_printf("]\n"); read += r; } int32_t w = serial_w->write(out_buf + written, BUF_SIZE - written); if (w == PROS_ERR) { pass = false; printf("%07d Write failed with error %d\n", cur_time, errno); break; } else if (w) { verbose_printf("%07d, W %d\n", cur_time, w); written += w; } pros::delay(1); } if (pass) printf("%07d PASS\n", pros::millis()); else printf("%07d FAIL\n", pros::millis()); return pass; } void set_baudrate(const int32_t baudrate) { printf("%07d Setting baudrate to %d\n", pros::millis(), baudrate); serial_w->set_baudrate(baudrate); serial_r->set_baudrate(baudrate); } void flush() { serial_w->flush(); pros::delay(100); serial_r->flush(); } void init_ports(uint8_t write_port, uint8_t recv_port) { printf("%07d Using port %d to write and %d to recv\n", pros::millis(), write_port, recv_port); if (serial_w != nullptr) delete serial_w; serial_w = new pros::Serial(write_port); if (serial_r != nullptr) delete serial_r; serial_r = new pros::Serial(recv_port); } bool run_tests() { flush(); set_baudrate(115200); if (!test_send_recv_byte(5, 1000)) return false; flush(); set_baudrate(230400); if (!test_send_recv_byte(2, 2500)) return false; for (int i = 0; i < 5; i++) { flush(); if (!test_send_recv_block()) return false; } return true; } void opcontrol() { printf("---Generic Serial Test---\nPlease ensure a cable is plugged into port 1 and port 2, connecting them together\n\n%07d Starting serial tests...\n", pros::millis()); init_ports(1, 2); if (!run_tests()) return; init_ports(2, 1); if (!run_tests()) return; printf("%07d All tests passed!\n", pros::millis()); } ================================================ FILE: src/tests/generic_serial_file.cpp ================================================ /** * \file tests/generic_serial_file.cpp * * Test code for the generic serial filesystem driver * * NOTE: There should be a cable plugged into ports 1 and 2, connecting * them together * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" #include #include "pros/apix.h" FILE *serial_w = nullptr, *serial_r = nullptr; char serial_w_name[8], serial_r_name[8]; int serial_w_port, serial_r_port; constexpr bool VERBOSE_OUTPUT = false; constexpr uint32_t BUF_SIZE = 65536; uint8_t out_buf[BUF_SIZE], in_buf[BUF_SIZE]; void verbose_printf(const char *format, ...) { if (VERBOSE_OUTPUT) { va_list va; va_start(va, format); vprintf(format, va); va_end(va); } } bool test_send_recv_byte(const uint32_t interval, const uint32_t bytes) { printf("%07d Starting send/recv byte test with an interval of %dms for %d bytes...\n", pros::millis(), interval, bytes); uint8_t count = 0, expected = 0; uint32_t last_send_time = 0, cur_time, recv_count = 0; bool pass = true; do { cur_time = pros::millis(); if (cur_time - last_send_time >= interval) { int32_t w = fputc(count, serial_w); fflush(serial_w); if (w == EOF) { pass = false; printf("%07d Write failed with error %d\n", cur_time, errno); break; } else if (w == count) { count++; last_send_time = cur_time; } } int32_t read = fgetc(serial_r); if (read == EOF) { pass = false; printf("%07d Read failed with error %d\n", cur_time, errno); break; } else { if (read != expected) { printf("%07d ERR Read: 0x%02x, Expt: 0x%02x\n", cur_time, read, expected); pass = false; } else { verbose_printf("%07d 0x%02x\n", cur_time, read); } expected++; recv_count++; } pros::delay(interval); } while (recv_count < bytes); if (pass) printf("%07d PASS\n", pros::millis()); else printf("%07d FAIL\n", pros::millis()); return pass; } bool test_send_recv_block() { printf("%07d Starting send/recv block test...\n", pros::millis()); uint32_t written = 0, read = 0; bool pass = true; for (uint32_t i = 0; i < BUF_SIZE; i++) { out_buf[i] = i; } while (written < BUF_SIZE || read < BUF_SIZE) { uint32_t cur_time = pros::millis(); int32_t free = pros::c::fdctl(fileno(serial_w), DEVCTL_FIONWRITE, NULL); int32_t w = fwrite(out_buf + written, 1, BUF_SIZE - written > free ? free : BUF_SIZE - written, serial_w); fflush(serial_w); if (w == EOF) { pass = false; printf("%07d Write failed with error %d\n", cur_time, errno); break; } else if (w) { verbose_printf("%07d, W %d\n", cur_time, w); written += w; } int32_t avail = pros::c::fdctl(fileno(serial_r), DEVCTL_FIONREAD, NULL); int32_t r = fread(in_buf + read, 1, BUF_SIZE - read > avail ? avail : BUF_SIZE - read, serial_r); if (r == EOF) { pass = false; printf("%07d Read failed with error %d\n", cur_time, errno); break; } else if (r) { verbose_printf("%07d R %d [", cur_time, r); for (int32_t i = 0; i < r; i++) { verbose_printf("%02x", in_buf[read + i]); if (in_buf[read + i] != out_buf[read + i]) { pass = false; verbose_printf(" (%02x)", out_buf[read + i]); } if (i < r - 1) verbose_printf(", "); } verbose_printf("]\n"); read += r; } pros::delay(1); } if (pass) printf("%07d PASS\n", pros::millis()); else printf("%07d FAIL\n", pros::millis()); return pass; } void set_baudrate(const int32_t baudrate) { printf("%07d Setting baudrate to %d\n", pros::millis(), baudrate); pros::c::fdctl(fileno(serial_w), DEVCTL_SET_BAUDRATE, (void *)baudrate); pros::c::fdctl(fileno(serial_r), DEVCTL_SET_BAUDRATE, (void *)baudrate); } void flush() { pros::c::serial_flush(serial_w_port); pros::delay(100); pros::c::serial_flush(serial_r_port); } void init_ports(uint8_t write_port, uint8_t recv_port) { printf("%07d Using port %d to write and %d to recv\n", pros::millis(), write_port, recv_port); serial_w_port = write_port; if (serial_w != nullptr) fclose(serial_w); sprintf(serial_w_name, "/dev/%d", write_port); serial_w = fopen(serial_w_name, "wb"); serial_r_port = recv_port; if (serial_r != nullptr) fclose(serial_r); sprintf(serial_r_name, "/dev/%d", recv_port); serial_r = fopen(serial_r_name, "rb"); } bool run_tests() { flush(); set_baudrate(115200); if (!test_send_recv_byte(5, 1000)) return false; flush(); set_baudrate(230400); if (!test_send_recv_byte(2, 2500)) return false; for (int i = 0; i < 5; i++) { flush(); if (!test_send_recv_block()) return false; } return true; } void opcontrol() { printf("---Generic Serial Test---\nPlease ensure a cable is plugged into port 1 and port 2, connecting them together\n\n%07d Starting serial tests...\n", pros::millis()); init_ports(1, 2); if (!run_tests()) return; init_ports(2, 1); if (!run_tests()) return; printf("%07d All tests passed!\n", pros::millis()); } ================================================ FILE: src/tests/gyro.c ================================================ /** * \file tests/gyro.c * * Test code for the gyroscope driver * * NOTE: There should also be a call to the constructor for the gyroscope object * in initialize() for calibration to occur before the opcontrol code. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" void opcontrol() { motor_pid_s_t pid = motor_convert_pid(1.0, 0.0001, 1.0, 2.0); lcd_print(2, "%d %d %d %d", pid.kp, pid.ki, pid.kd, pid.kf); motor_set_vel_pid(1, pid); adi_gyro_t gyro = adi_gyro_init('c', 1 / 1.8); motor_pid_full_s_t pidf = motor_get_vel_pid(1); lcd_print(3, "%d %d %d %d", pidf.kp, pidf.ki, pidf.kd, pidf.kf); uint32_t now = millis(); while (true) { lcd_print(1, "%f", adi_gyro_get(gyro)); if (millis() - now > 5000) { adi_gyro_reset(gyro); now = millis(); } delay(20); } } ================================================ FILE: src/tests/gyro.cpp ================================================ /** * \file tests/gyro.cpp * * Test code for the gyroscope driver * * NOTE: There should also be a call to the constructor for the gyroscope object * in initialize() for calibration to occur before the opcontrol code. * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" void opcontrol() { pros::Motor left_mtr(1); pros::motor_pid_s_t pid = pros::Motor::convert_pid(1.0, 0.0001, 1.0, 2.0); pros::lcd::print(2, "%d %d %d %d", pid.kp, pid.ki, pid.kd, pid.kf); left_mtr.set_vel_pid(pid); pros::ADIGyro gyro('c', 1 / 1.8); pros::motor_pid_full_s_t pidf = left_mtr.get_vel_pid(); pros::lcd::print(3, "%d %d %d %d", pidf.kp, pidf.ki, pidf.kd, pidf.kf); uint32_t now = pros::millis(); while (true) { pros::lcd::print(1, "%f", gyro.get_value()); if (pros::millis() - now > 5000) { gyro.reset(); now = pros::millis(); } pros::delay(20); } } ================================================ FILE: src/tests/mutexes.c ================================================ void test_mutex() { mutex_t mut = mutex_create(); mutex_take(mut, TIMEOUT_MAX); mutex_give(mut); } ================================================ FILE: src/tests/pnuematics.cpp ================================================ #include "main.h" /** * A callback function for LLEMU's center button. * * When this callback is fired, it will toggle line 2 of the LCD text between * "I was pressed!" and nothing. */ void on_center_button() { static bool pressed = false; pressed = !pressed; if (pressed) { pros::lcd::set_text(2, "I was pressed!"); } else { pros::lcd::clear_line(2); } } /** * Runs initialization code. This occurs as soon as the program is started. * * All other competition modes are blocked by initialize; it is recommended * to keep execution time for this mode under a few seconds. */ void initialize() { lvgl_init(); pros::lcd::initialize(); pros::lcd::set_text(1, "Hello PROS User!"); pros::lcd::register_btn1_cb(on_center_button); } /** * Runs while the robot is in the disabled state of Field Management System or * the VEX Competition Switch, following either autonomous or opcontrol. When * the robot is enabled, this task will exit. */ void disabled() {} /** * Runs after initialize(), and before autonomous when connected to the Field * Management System or the VEX Competition Switch. This is intended for * competition-specific initialization routines, such as an autonomous selector * on the LCD. * * This task will exit when the robot is enabled and autonomous or opcontrol * starts. */ void competition_initialize() {} /** * Runs the user autonomous code. This function will be started in its own task * with the default priority and stack size whenever the robot is enabled via * the Field Management System or the VEX Competition Switch in the autonomous * mode. Alternatively, this function may be called in initialize or opcontrol * for non-competition testing purposes. * * If the robot is disabled or communications is lost, the autonomous task * will be stopped. Re-enabling the robot will restart the task, not re-start it * from where it left off. */ void autonomous() {} /** * Runs the operator control code. This function will be started in its own task * with the default priority and stack size whenever the robot is enabled via * the Field Management System or the VEX Competition Switch in the operator * control mode. * * If no competition control is connected, this function will run immediately * following initialize(). * * If the robot is disabled or communications is lost, the * operator control task will be stopped. Re-enabling the robot will restart the * task, not resume it from where it left off. */ void opcontrol() { pros::Controller master(pros::E_CONTROLLER_MASTER); pros::adi::Pneumatics n('H', true); while (true) { pros::lcd::print(0, "%d %d %d", (pros::lcd::read_buttons() & LCD_BTN_LEFT) >> 2, (pros::lcd::read_buttons() & LCD_BTN_CENTER) >> 1, (pros::lcd::read_buttons() & LCD_BTN_RIGHT) >> 0); if(master.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_A)){ printf("Toggling Pnuematic\n"); n.toggle(); } if(master.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_X)) { printf("Extending Pnuematic\n"); n.extend(); } if(master.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_B)) { printf("Retracting Pnuematic\n"); n.retract(); } if(master.get_digital_new_press(pros::E_CONTROLLER_DIGITAL_Y)) { printf("Pneumatic state is: %i\n", (int)n.get_state()); } pros::delay(20); } } ================================================ FILE: src/tests/rtos_function_linking.c ================================================ /** * \file tests/rtos_function_linking.c * * Test that all the FreeRTOS functions link correctly. * * Do not actually run this test - just make sure it compiles * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "api.h" void x(void* ign) {} void test_all() { task_delete(task_create(x, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "no name")); task_delay(1); task_delay_until(NULL, 3); task_get_priority(NULL); task_set_priority(NULL, 4); task_get_state(NULL); task_suspend(NULL); task_resume(NULL); task_get_count(); task_get_name(NULL); task_get_by_name("Hello"); task_notify(NULL); task_notify_ext(NULL, 4, E_NOTIFY_ACTION_NONE, NULL); task_notify_take(false, MAX_TIMEOUT); task_notify_clear(NULL); mutex_t mutex = mutex_create(); mutex_take(mutex, MAX_TIMEOUT); mutex_give(mutex); sem_t sem = sem_create(4, 0); sem_wait(sem, MAX_TIMEOUT); sem_post(sem); } ================================================ FILE: src/tests/segfault.cpp ================================================ #include "main.h" [[gnu::noinline]] static void thing_1(uint8_t i) { printf("thing_1(%i)\n", i); if (i == 0) { asm volatile("mov r0, #0 \n\tSTR sp, [r0]\n\t"); } else { thing_1(i - 1); printf("%s", "Never prints!"); } } /** * Runs initialization code. This occurs as soon as the program is started. * * All other competition modes are blocked by initialize; it is recommended * to keep execution time for this mode under a few seconds. */ void initialize() { printf("%s", "Hello world!"); thing_1(10); } void disabled() {} void competition_initialize() {} void autonomous() {} void opcontrol() {} ================================================ FILE: src/tests/simple_names.c ================================================ /** * \file tests/simple_names.c * * Test that all the PROS_USE_SIMPLE_NAMES definitions compile correctly * * Do not actually run this test - just make sure it compiles * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" void opcontrol() { // ADI Simple Names adi_port_set_config(1, ADI_ANALOG_IN); adi_port_set_config(1, ADI_ANALOG_OUT); adi_port_set_config(1, ADI_DIGITAL_IN); adi_port_set_config(1, ADI_DIGITAL_OUT); adi_port_set_config(1, ADI_SMART_BUTTON); adi_port_set_config(1, ADI_SMART_POT); adi_port_set_config(1, ADI_LEGACY_BUTTON); adi_port_set_config(1, ADI_LEGACY_LINE_SENSOR); adi_port_set_config(1, ADI_LEGACY_LIGHT_SENSOR); adi_port_set_config(1, ADI_LEGACY_GYRO); adi_port_set_config(1, ADI_LEGACY_ACCELEROMETER); adi_port_set_config(1, ADI_LEGACY_SERVO); adi_port_set_config(1, ADI_LEGACY_PWM); adi_port_set_config(1, ADI_LEGACY_ENCODER); adi_port_set_config(1, ADI_LEGACY_ULTRASONIC); adi_port_set_config(1, ADI_TYPE_UNDEFINED); adi_port_set_config(1, ADI_ERR); // Misc Simple Names controller_is_connected(CONTROLLER_MASTER); controller_is_connected(CONTROLLER_PARTNER); controller_get_analog(CONTROLLER_MASTER, ANALOG_LEFT_X); controller_get_analog(CONTROLLER_MASTER, ANALOG_LEFT_Y); controller_get_analog(CONTROLLER_MASTER, ANALOG_RIGHT_X); controller_get_analog(CONTROLLER_MASTER, ANALOG_RIGHT_Y); controller_get_digital(CONTROLLER_MASTER, DIGITAL_L1); controller_get_digital(CONTROLLER_MASTER, DIGITAL_L2); controller_get_digital(CONTROLLER_MASTER, DIGITAL_R1); controller_get_digital(CONTROLLER_MASTER, DIGITAL_R2); controller_get_digital(CONTROLLER_MASTER, DIGITAL_UP); controller_get_digital(CONTROLLER_MASTER, DIGITAL_DOWN); controller_get_digital(CONTROLLER_MASTER, DIGITAL_LEFT); controller_get_digital(CONTROLLER_MASTER, DIGITAL_RIGHT); controller_get_digital(CONTROLLER_MASTER, DIGITAL_X); controller_get_digital(CONTROLLER_MASTER, DIGITAL_B); controller_get_digital(CONTROLLER_MASTER, DIGITAL_Y); controller_get_digital(CONTROLLER_MASTER, DIGITAL_A); // Motors Simple Names int result = motor_get_faults(1) & MOTOR_FAULT_NO_FAULTS; result = motor_get_faults(1) & MOTOR_FAULT_MOTOR_OVER_TEMP; result = motor_get_faults(1) & MOTOR_FAULT_DRIVER_FAULT; result = motor_get_faults(1) & MOTOR_FAULT_OVER_CURRENT; result = motor_get_faults(1) & MOTOR_FAULT_DRV_OVER_CURRENT; result = motor_get_flags(1) & MOTOR_FLAGS_NONE; result = motor_get_flags(1) & MOTOR_FLAGS_BUSY; result = motor_get_flags(1) & MOTOR_FLAGS_ZERO_VELOCITY; result = motor_get_flags(1) & MOTOR_FLAGS_ZERO_POSITION; motor_set_brake_mode(1, MOTOR_BRAKE_COAST); motor_set_brake_mode(1, MOTOR_BRAKE_BRAKE); motor_set_brake_mode(1, MOTOR_BRAKE_HOLD); motor_set_brake_mode(1, MOTOR_BRAKE_INVALID); motor_set_encoder_units(1, MOTOR_ENCODER_DEGREES); motor_set_encoder_units(1, MOTOR_ENCODER_ROTATIONS); motor_set_encoder_units(1, MOTOR_ENCODER_COUNTS); motor_set_encoder_units(1, MOTOR_ENCODER_INVALID); motor_set_gearing(1, MOTOR_GEARSET_36); motor_set_gearing(1, MOTOR_GEARSET_18); motor_set_gearing(1, MOTOR_GEARSET_06); motor_set_gearing(1, MOTOR_GEARSET_6); motor_set_gearing(1, MOTOR_GEARSET_INVALID); // RTOS Simple Names int res = task_get_state(CURRENT_TASK) & TASK_STATE_RUNNING; res = task_get_state(CURRENT_TASK) & TASK_STATE_READY; res = task_get_state(CURRENT_TASK) & TASK_STATE_BLOCKED; res = task_get_state(CURRENT_TASK) & TASK_STATE_SUSPENDED; res = task_get_state(CURRENT_TASK) & TASK_STATE_DELETED; res = task_get_state(CURRENT_TASK) & TASK_STATE_INVALID; task_notify_ext(CURRENT_TASK, 0, NOTIFY_ACTION_NONE, NULL); task_notify_ext(CURRENT_TASK, 0, NOTIFY_ACTION_BITS, NULL); task_notify_ext(CURRENT_TASK, 0, NOTIFY_ACTION_INCR, NULL); task_notify_ext(CURRENT_TASK, 0, NOTIFY_ACTION_OWRITE, NULL); task_notify_ext(CURRENT_TASK, 0, NOTIFY_ACTION_NO_OWRITE, NULL); // Vision Simple Names vision_object_s_t object; bool equal = object.type == VISION_OBJECT_NORMAL; equal = object.type == VISION_OBJECT_COLOR_CODE; equal = object.type == VISION_OBJECT_LINE; vision_set_zero_point(1, VISION_ZERO_TOPLEFT); vision_set_zero_point(1, VISION_ZERO_CENTER); } ================================================ FILE: src/tests/simple_names.cpp ================================================ /** * \file tests/simple_names.cpp * * Test that all the PROS_USE_SIMPLE_NAMES definitions compile correctly * * Do not actually run this test - just make sure it compiles * * \copyright Copyright (c) 2017-2026, Purdue University ACM SIGBots. * All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "main.h" void opcontrol() { // ADI Simple Names pros::ADIPort test1 (1, ADI_ANALOG_IN); pros::ADIPort test2 (1, ADI_ANALOG_OUT); pros::ADIPort test3 (1, ADI_DIGITAL_IN); pros::ADIPort test4 (1, ADI_DIGITAL_OUT); pros::ADIPort test5 (1, ADI_SMART_BUTTON); pros::ADIPort test6 (1, ADI_SMART_POT); pros::ADIPort test7 (1, ADI_LEGACY_BUTTON); pros::ADIPort test8 (1, ADI_LEGACY_LINE_SENSOR); pros::ADIPort test9 (1, ADI_LEGACY_LIGHT_SENSOR); pros::ADIPort test10 (1, ADI_LEGACY_GYRO); pros::ADIPort test11 (1, ADI_LEGACY_ACCELEROMETER); pros::ADIPort test12 (1, ADI_LEGACY_SERVO); pros::ADIPort test13 (1, ADI_LEGACY_PWM); pros::ADIPort test14 (1, ADI_LEGACY_ENCODER); pros::ADIPort test15 (1, ADI_LEGACY_ULTRASONIC); pros::ADIPort test16 (1, ADI_TYPE_UNDEFINED); pros::ADIPort test17 (1, ADI_ERR); // Misc Simple Names pros::Controller master (CONTROLLER_MASTER); pros::Controller partner (CONTROLLER_PARTNER); master.get_analog(ANALOG_LEFT_X); master.get_analog(ANALOG_LEFT_Y); master.get_analog(ANALOG_RIGHT_X); master.get_analog(ANALOG_RIGHT_Y); master.get_digital(DIGITAL_L1); master.get_digital(DIGITAL_L2); master.get_digital(DIGITAL_R1); master.get_digital(DIGITAL_R2); master.get_digital(DIGITAL_UP); master.get_digital(DIGITAL_DOWN); master.get_digital(DIGITAL_LEFT); master.get_digital(DIGITAL_RIGHT); master.get_digital(DIGITAL_X); master.get_digital(DIGITAL_B); master.get_digital(DIGITAL_Y); master.get_digital(DIGITAL_A); // Motors Simple Names pros::Motor motor (1); int result = motor.get_faults() & MOTOR_FAULT_NO_FAULTS; result = motor.get_faults() & MOTOR_FAULT_MOTOR_OVER_TEMP; result = motor.get_faults() & MOTOR_FAULT_DRIVER_FAULT; result = motor.get_faults() & MOTOR_FAULT_OVER_CURRENT; result = motor.get_faults() & MOTOR_FAULT_DRV_OVER_CURRENT; result = motor.get_flags() & MOTOR_FLAGS_NONE; result = motor.get_flags() & MOTOR_FLAGS_BUSY; result = motor.get_flags() & MOTOR_FLAGS_ZERO_VELOCITY; result = motor.get_flags() & MOTOR_FLAGS_ZERO_POSITION; motor.set_brake_mode(MOTOR_BRAKE_COAST); motor.set_brake_mode(MOTOR_BRAKE_BRAKE); motor.set_brake_mode(MOTOR_BRAKE_HOLD); motor.set_brake_mode(MOTOR_BRAKE_INVALID); motor.set_encoder_units(MOTOR_ENCODER_DEGREES); motor.set_encoder_units(MOTOR_ENCODER_ROTATIONS); motor.set_encoder_units(MOTOR_ENCODER_COUNTS); motor.set_encoder_units(MOTOR_ENCODER_INVALID); motor.set_gearing(MOTOR_GEARSET_36); motor.set_gearing(MOTOR_GEARSET_18); motor.set_gearing(MOTOR_GEARSET_06); motor.set_gearing(MOTOR_GEARSET_6); motor.set_gearing(MOTOR_GEARSET_INVALID); // RTOS Simple Names pros::Task task (CURRENT_TASK); int res = task.get_state() & TASK_STATE_RUNNING; res = task.get_state() & TASK_STATE_READY; res = task.get_state() & TASK_STATE_BLOCKED; res = task.get_state() & TASK_STATE_SUSPENDED; res = task.get_state() & TASK_STATE_DELETED; res = task.get_state() & TASK_STATE_INVALID; task.notify_ext(0, NOTIFY_ACTION_NONE, NULL); task.notify_ext(0, NOTIFY_ACTION_BITS, NULL); task.notify_ext(0, NOTIFY_ACTION_INCR, NULL); task.notify_ext(0, NOTIFY_ACTION_OWRITE, NULL); task.notify_ext(0, NOTIFY_ACTION_NO_OWRITE, NULL); // Vision Simple Names pros::vision_object_s_t object; bool equal = object.type == VISION_OBJECT_NORMAL; equal = object.type == VISION_OBJECT_COLOR_CODE; equal = object.type == VISION_OBJECT_LINE; pros::Vision vision (1); vision.set_zero_point(VISION_ZERO_TOPLEFT); vision.set_zero_point(VISION_ZERO_CENTER); } ================================================ FILE: src/tests/static_tast_states.c ================================================ // This test is mostly verifying that the idle task isn't being starved #include #include "rtos/FreeRTOS.h" #include "rtos/task.h" #define STACK_SIZE 0x2000 task_stack_t staticTaskStack[STACK_SIZE]; static_task_s_t staticTaskTask; task_t staticTaskHandle; void myStaticTask(void*); // the task_delay(5) SHOULD NOT BE REQUIRED but FreeRTOS is buggy af void myTask(void* ign) { printf("myTask %d task_notify_take\n", __LINE__); task_delay(10); task_notify_take(true, 0xffffffffUL); printf("myTask %d task_create_static\n", __LINE__); task_delay(10); task_create_static(myStaticTask, NULL, 8, STACK_SIZE, "My Static Task", staticTaskStack, &staticTaskTask); printf("myTask %d task_delete\n", __LINE__); task_delay(10); task_delete(NULL); } void myStaticTask(void* ign) { printf("myStaticTask %d task_create\n", __LINE__); task_delay(10); task_t task = task_create(myTask, NULL, 8, STACK_SIZE, "My Task"); printf("myStaticTask %d task_notify %p\n", __LINE__, task); task_delay(10); task_notify(task); printf("myStaticTask %d task_delete\n", __LINE__); task_delay(10); task_delete(NULL); } void opcontrol() { task_create_static(myStaticTask, NULL, 8, STACK_SIZE, "My Static Task", staticTaskStack, &staticTaskTask); } ================================================ FILE: src/tests/task_notify_when_deleting.c ================================================ #include "main.h" #include "pros/apix.h" void target_task(void* ignore) { lcd_print(0, "%s says hello", task_get_name(NULL)); task_delay(1000); lcd_print(0, "I don't feel so good - %s", task_get_name(NULL)); } void notify_task(void* ignore) { lcd_set_text(2, "I don't know - I don't know what's happening"); task_notify_take(true, TIMEOUT_MAX); lcd_set_text(4, "God damn you all to hell!"); } void opcontrol() { task_t peter = task_create(target_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Peter Parker"); task_notify_when_deleting(peter, NULL, 1, E_NOTIFY_ACTION_BITS); task_notify_take(true, TIMEOUT_MAX); lcd_set_text(1, "Are you alright?"); task_t peter2 = task_create(notify_task, NULL, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "Peter Parker's Son"); // task_delay(1000); task_notify_when_deleting(NULL, peter2, 1, E_NOTIFY_ACTION_INCR); // task_delay(1000); lcd_set_text(3, "Goodbye, cruel world!"); // task_delay(1000); } ================================================ FILE: src/tests/vision_test.cpp ================================================ #include "main.h" void opcontrol() { pros::Vision vis(10); pros::delay(2000); pros::vision_color_code_t code; code = vis.create_color_code(1, 2, 3); printf("%d\n", code); while (true) { pros::vision_object_s_t obj_arr[5]; vis.read_by_size(0, 5, obj_arr); for(int i=0; i < 5; i++) { printf("%o %d %d ", obj_arr[i].signature, obj_arr[i].x_middle_coord, obj_arr[i].y_middle_coord); } printf("\n"); pros::delay(20); } } ================================================ FILE: template-Makefile ================================================ ################################################################################ ######################### User configurable parameters ######################### # filename extensions CEXTS:=c ASMEXTS:=s S CXXEXTS:=cpp c++ cc # probably shouldn't modify these, but you may need them below ROOT=. FWDIR:=$(ROOT)/firmware BINDIR=$(ROOT)/bin SRCDIR=$(ROOT)/src INCDIR=$(ROOT)/include WARNFLAGS+= EXTRA_CFLAGS= EXTRA_CXXFLAGS= # Set to 1 to enable hot/cold linking USE_PACKAGE:=1 # Add libraries you do not wish to include in the cold image here # EXCLUDE_COLD_LIBRARIES:= $(FWDIR)/your_library.a EXCLUDE_COLD_LIBRARIES:= # Set this to 1 to add additional rules to compile your project as a PROS library template IS_LIBRARY:=0 # TODO: CHANGE THIS! # Be sure that your header files are in the include directory inside of a folder with the # same name as what you set LIBNAME to below. LIBNAME:=libbest VERSION:=1.0.0 # EXCLUDE_SRC_FROM_LIB= $(SRCDIR)/unpublishedfile.c # this line excludes opcontrol.c and similar files EXCLUDE_SRC_FROM_LIB+=$(foreach file, $(SRCDIR)/main,$(foreach cext,$(CEXTS),$(file).$(cext)) $(foreach cxxext,$(CXXEXTS),$(file).$(cxxext))) # files that get distributed to every user (beyond your source archive) - add # whatever files you want here. This line is configured to add all header files # that are in the directory include/LIBNAME TEMPLATE_FILES=$(INCDIR)/$(LIBNAME)/*.h $(INCDIR)/$(LIBNAME)/*.hpp .DEFAULT_GOAL=quick ################################################################################ ################################################################################ ########## Nothing below this line should be edited by typical users ########### -include ./common.mk ================================================ FILE: template-gitignore ================================================ # Compiled Object files *.o *.obj # Executables *.bin *.elf # PROS bin/ .vscode/ .cache/ compile_commands.json temp.log temp.errors *.ini .d/ ================================================ FILE: verify-symbols.sh ================================================ #!/usr/bin/env bash # when running this script, there should be nothing red or dark blue on the right panel (what's the in header files) with the following exceptions # the pros::c::* functions. They're #ifdef __cplusplus'd out into a namespace. The C linkages demonsrtate that it's fine # Default arguments exist in the constructor in the header file, but not in the implementation shopt -s globstar # Convenience script to manually verify that all functions in the public headers exist in the source directory vimdiff <(ctags --sort=yes --c-kinds=f --extra=-f+q --fields=S -f - src/**/* | awk '{if(index($0, "signature:")) print $1, substr($0, index($0, "signature:"))}' | sort ) <(ctags --sort=yes --c-kinds=p --extra=-f+q --fields=S -f - include/pros/**/* | awk '{if(index($0, "signature:")) print $1, substr($0, index($0, "signature:"))}' | sort) ================================================ FILE: version.py ================================================ from __future__ import print_function import subprocess import io import os try: v = subprocess.check_output(['git', 'describe', '--dirty', '--abbrev']).decode().strip() if '-' in v: bv = v[:v.index('-')] bv = bv[:bv.rindex('.') + 1] + str(int(bv[bv.rindex('.') + 1:]) + 1) if os.environ.get('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER', None): # for Azure Pipelines PR builder sempre = 'pr{}'.format(os.environ.get('SYSTEM_PULLREQUEST_PULLREQUESTNUMBER')) build = os.environ.get('BUILD_BUILDID') else: sempre = 'dirty' if v.endswith('-dirty') else 'commit' # pippre = 'alpha' if v.endswith('-dirty') else 'pre' build = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode().strip() number_since = subprocess.check_output(['git', 'rev-list', v[:v.index('-')] + '..HEAD', '--count']).decode().strip() build = "{}.{}".format(number_since, build) semver = bv + '-' + sempre + '.' + build else: semver = v with open('version', 'w') as f: print('Semantic version is ' + semver) f.write(semver) assert semver.count('.') >= 2 major, minor, patch = semver.split('.', 2) patch = patch.split('-', 1)[0] with io.open('include/pros/version.h', 'r', encoding='ascii') as file: data = file.readlines() for i, line in enumerate(data): if '#define PROS_VERSION_MAJOR' in line: data[i] = u'#define PROS_VERSION_MAJOR {}\n'.format(major) if '#define PROS_VERSION_MINOR' in line: data[i] = u'#define PROS_VERSION_MINOR {}\n'.format(minor) if '#define PROS_VERSION_PATCH' in line: data[i] = u'#define PROS_VERSION_PATCH {}\n'.format(patch) if '#define PROS_VERSION_STRING ' in line: data[i] = u'#define PROS_VERSION_STRING "{}"\n'.format(semver) with io.open('include/pros/version.h', 'w', newline='\n', encoding='ascii') as file: file.writelines(data) except subprocess.CalledProcessError as e: print('Error calling git')