diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..1e6af5c --- /dev/null +++ b/.clang-format @@ -0,0 +1,11 @@ +--- +BasedOnStyle: Google +# const right of what it qualifies: char const*, Status const&. Google +# encourages const first but does not require it, and asks to be consistent with the code +# around; this is the one place the library departs from its preference. volatile moves +# with it. clang-format --dry-run in tools/lint.sh fails on a const on the left. +QualifierAlignment: Right +# A test of RingBuffer.h is RingBufferTest.cpp (docs/Testing.md TS-5), and includes the header +# it tests first, as a source does its own. Google's regex knows only the endings _test and +# _unittest; Test is added to them. +IncludeIsMainRegex: '(Test|[-_](test|unittest))?$' diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..aa4cfed --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,188 @@ +# Broad groups, and out of them what contradicts the Google style, what cannot be had on the +# AVR, and the aliases of checks that are on already. Each exception says why. This file comes +# from the template and is brought up to date with `copier update`; a project adds its own +# exceptions at the end of a list, with its reason, and the update keeps them. +Checks: > + bugprone-*, + cert-*, + clang-analyzer-*, + cppcoreguidelines-*, + google-*, + house-*, + misc-*, + modernize-*, + performance-*, + portability-*, + readability-*, + -bugprone-dynamic-static-initializers, + -cert-dcl37-c, + -cert-dcl51-cpp, + -cert-dcl58-cpp, + -cppcoreguidelines-avoid-c-arrays, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-c-copy-assignment-signature, + -cppcoreguidelines-explicit-constructor, + -cppcoreguidelines-explicit-virtual-functions, + -cppcoreguidelines-macro-to-enum, + -cppcoreguidelines-missing-std-forward, + -cppcoreguidelines-narrowing-conversions, + -cppcoreguidelines-noexcept-destructor, + -cppcoreguidelines-noexcept-move-operations, + -cppcoreguidelines-noexcept-swap, + -cppcoreguidelines-non-private-member-variables-in-classes, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-avoid-unchecked-container-access, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-rvalue-reference-param-not-moved, + -cppcoreguidelines-use-default-member-init, + -google-explicit-constructor, + -misc-explicit-constructor, + -modernize-deprecated-headers, + -modernize-return-braced-init-list, + -modernize-use-trailing-return-type, + -readability-identifier-length, + -readability-named-parameter +# house-*: the checks of our own, in tools/lib/tidy_module/; tools/tidy.sh loads them. Without +# the module, as in clangd, the name matches nothing. +# bugprone-dynamic-static-initializers: it reports the extern declaration of a constant whose +# constexpr definition lies in a .cpp it cannot see, as an object identified by its address +# has to be. +# cert-dcl37-c, cert-dcl51-cpp, cert-dcl58-cpp: aliases of bugprone-reserved-identifier and +# bugprone-std-namespace-modification, which are on; two names would want two NOLINTs. +# cppcoreguidelines-avoid-c-arrays, -avoid-magic-numbers, -c-copy-assignment-signature, +# -explicit-virtual-functions, -macro-to-enum, -narrowing-conversions, -noexcept-destructor, +# -noexcept-move-operations, -noexcept-swap, -non-private-member-variables-in-classes, +# -use-default-member-init: aliases of the modernize-, readability-, misc-, bugprone- and +# performance- checks that are on, with defaults of their own; the options below are set for +# those. +# cppcoreguidelines-explicit-constructor, google-explicit-constructor, +# misc-explicit-constructor: cpplint checks the same rule as runtime/explicit, and the +# implicit constructors that are meant carry their NOLINT there; two tools would want two +# per line. +# cppcoreguidelines-missing-std-forward, -rvalue-reference-param-not-moved: they want +# std::forward and std::move, which avr-gcc does not have without a standard library; a +# static_cast is what both are, and the checks do not know it. +# cppcoreguidelines-pro-bounds-array-to-pointer-decay, -pro-bounds-avoid-unchecked-container- +# access, -pro-bounds-constant-array-index: the bounds profile wants gsl::span and gsl::at, +# which the AVR does not have; F(), PROGMEM tables and the core take arrays as pointers, and +# operator[] is the unchecked access the standard gives. cppcoreguidelines-pro-bounds- +# pointer-arithmetic stays on: a project built on pointers, as a container, turns it off +# below, with its reason. +# modernize-deprecated-headers: avr-gcc comes without a C++ standard library, so there is no +# , only . +# modernize-return-braced-init-list: `return Error();` says what is returned, `return {};` +# hides it. +# modernize-use-trailing-return-type: Google puts the return type in front. +# readability-identifier-length: Google allows `f` or `a` and `b` where the scope is a few +# lines. +# readability-named-parameter: Google leaves out the name of a parameter that is unused where +# the context explains it, as a tag type that only picks an overload. +WarningsAsErrors: '*' +# clang's warnings beyond -Wall -Wextra, which tools/tidy.sh passes: what an IDE such as CLion +# finds with its own analysis of the code, reported here by clang-tidy as clang-diagnostic-* +# and failing as any check does. Code that cannot be reached, a macro or a member function +# that is never used, an #if on a macro that is not defined (a switch spelled wrong is off +# without a word), a C cast, 0 as a null pointer, a shadowed name, a float promoted to double +# (which the AVR computes in software). Not -Wdeprecated-redundant-constexpr-static-def: a +# library for gnu++11 needs the definition of a constexpr static member outside its class, which +# C++17, as the tests are compiled, calls redundant. +# +# And the Doxygen blocks, checked against the declaration they stand at: a \param whose name +# the function does not have, a \return on a function that returns nothing, an unknown +# command. \stddiff is the alias of the Doxyfile. See docs/Documentation.md. +# +# .clangd adds the same, so that the editor shows them. +ExtraArgs: + - -Wcast-qual + - -Wcomma + - -Wconditional-uninitialized + - -Wdeprecated + - -Wno-deprecated-redundant-constexpr-static-def + - -Wdouble-promotion + - -Wextra-semi + - -Wformat=2 + - -Wimplicit-fallthrough + - -Wloop-analysis + - -Wmissing-noreturn + - -Wnon-virtual-dtor + - -Wnull-dereference + - -Wold-style-cast + - -Wshadow-all + - -Wundef + - -Wunreachable-code-aggressive + - -Wunused-exception-parameter + - -Wunused-macros + - -Wunused-member-function + - -Wunused-template + - -Wzero-as-null-pointer-constant + - -Wdocumentation + - -Wdocumentation-unknown-command + - -fcomment-block-commands=stddiff +# (^|/), as tools/tidy.sh names the files relative to the repository, and a +# header beside an example is found as examples/.../font_error.h. +HeaderFilterRegex: '(^|/)(src|examples)/' +CheckOptions: + # The size of a function, docs/CodingStyle.md FN-2 to FN-5: 40 lines of body, + # 4 parameters, 3 levels within the body (the body itself is level 1 to the + # check), a cognitive complexity of 15. Without a threshold the check + # reports nothing. + readability-function-size.LineThreshold: 40 + readability-function-size.ParameterThreshold: 4 + readability-function-size.NestingThreshold: 4 + readability-function-cognitive-complexity.Threshold: 15 + # A text in PROGMEM is a char array, as F() and a table of texts need one. + modernize-avoid-c-arrays.AllowStringArrays: true + # A list over several lines ends in a comma, unless it is one value whose + # expression wraps, as in Result<...> const end{ReadDigits(...)}: there a + # comma would read as the start of a second value. + readability-trailing-comma.MultiLineCommaPolicy: Ignore + # A struct with only public members is what Google calls a struct, and an + # array type has to be one to stay an aggregate. + misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic: true + # The do { ... } while (0) of a macro is how a macro becomes one statement. + cppcoreguidelines-avoid-do-while.IgnoreMacros: true + # A class that deletes its copy has no move either, as the language has it; + # the rule of five does not ask to say so twice. + cppcoreguidelines-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted: true + # Google's "include what you use", with Arduino.h as what provides the + # core and the board's pins: F(), __FlashStringHelper and A0 come through it, + # from the core's folder and from the variant's. + misc-include-cleaner.IgnoreHeaders: '.*/cores/arduino/.*;.*/variants/.*' + # Google's names, which readability-identifier-naming checks only once it is told them; the + # same block in every project, so that every project names alike. Two exceptions Google + # makes itself are general: an accessor is named like the variable it gives (group(), + # size()), as are the aliases of a type that mimics the standard (value_type); and an include + # guard ends in an underscore. The third, an entity that mimics one of the standard library + # and takes its names (array, span, make_array), is the project's: it lists them below, as + # ClassIgnoredRegexp, StructIgnoredRegexp, FunctionIgnoredRegexp and + # ConstexprVariableIgnoredRegexp. + readability-identifier-naming.NamespaceCase: lower_case + readability-identifier-naming.ClassCase: CamelCase + readability-identifier-naming.StructCase: CamelCase + readability-identifier-naming.EnumCase: CamelCase + readability-identifier-naming.UnionCase: CamelCase + readability-identifier-naming.TypeAliasCase: CamelCase + readability-identifier-naming.TypeAliasIgnoredRegexp: '^[a-z][a-z0-9_]*$' + readability-identifier-naming.TypedefCase: CamelCase + readability-identifier-naming.TypedefIgnoredRegexp: '^[a-z][a-z0-9_]*$' + readability-identifier-naming.TemplateParameterCase: CamelCase + readability-identifier-naming.FunctionCase: CamelCase + readability-identifier-naming.MethodCase: CamelCase + readability-identifier-naming.MethodIgnoredRegexp: '^[a-z][a-z0-9_]*$' + readability-identifier-naming.VariableCase: lower_case + readability-identifier-naming.ParameterCase: lower_case + readability-identifier-naming.MemberCase: lower_case + readability-identifier-naming.PrivateMemberCase: lower_case + readability-identifier-naming.PrivateMemberSuffix: _ + readability-identifier-naming.ProtectedMemberCase: lower_case + readability-identifier-naming.ProtectedMemberSuffix: _ + readability-identifier-naming.ConstexprVariableCase: CamelCase + readability-identifier-naming.ConstexprVariablePrefix: k + readability-identifier-naming.GlobalConstantCase: CamelCase + readability-identifier-naming.GlobalConstantPrefix: k + readability-identifier-naming.StaticConstantCase: CamelCase + readability-identifier-naming.StaticConstantPrefix: k + readability-identifier-naming.EnumConstantCase: CamelCase + readability-identifier-naming.EnumConstantPrefix: k + readability-identifier-naming.MacroDefinitionCase: UPPER_CASE + readability-identifier-naming.MacroDefinitionIgnoredRegexp: '^[A-Z][A-Z0-9_]*_$' diff --git a/.clangd b/.clangd new file mode 100644 index 0000000..04dfcaf --- /dev/null +++ b/.clangd @@ -0,0 +1,45 @@ +# Which compilation database clangd reads, by path. src/ and test/ come from +# CMake, against the mock of the core (cmake --preset default writes it); +# examples/ from tools/tidy.sh --database-only, with the flags the board is +# compiled with, as only that one has the sketches, an .ino as C++ with +# Arduino.h included first. Both add the warnings that .clang-tidy passes as +# ExtraArgs, the checks of the Doxygen blocks among them, as clangd does not +# read ExtraArgs. +CompileFlags: + CompilationDatabase: build/host + Add: [-Wcast-qual, -Wcomma, -Wconditional-uninitialized, -Wdeprecated, + -Wno-deprecated-redundant-constexpr-static-def, -Wdouble-promotion, + -Wextra-semi, -Wformat=2, -Wimplicit-fallthrough, -Wloop-analysis, + -Wmissing-noreturn, -Wnon-virtual-dtor, -Wnull-dereference, + -Wold-style-cast, -Wshadow-all, -Wundef, -Wunreachable-code-aggressive, + -Wunused-exception-parameter, -Wunused-macros, -Wunused-member-function, + -Wunused-template, -Wzero-as-null-pointer-constant, + -Wdocumentation, -Wdocumentation-unknown-command, + -fcomment-block-commands=stddiff] +--- +If: + PathMatch: examples/.* +CompileFlags: + CompilationDatabase: build/tidy/default + Add: [-Wcast-qual, -Wcomma, -Wconditional-uninitialized, -Wdeprecated, + -Wno-deprecated-redundant-constexpr-static-def, -Wdouble-promotion, + -Wextra-semi, -Wformat=2, -Wimplicit-fallthrough, -Wloop-analysis, + -Wmissing-noreturn, -Wnon-virtual-dtor, -Wnull-dereference, + -Wold-style-cast, -Wshadow-all, -Wundef, -Wunreachable-code-aggressive, + -Wunused-exception-parameter, -Wunused-macros, -Wunused-member-function, + -Wunused-template, -Wzero-as-null-pointer-constant, + -Wdocumentation, -Wdocumentation-unknown-command, + -fcomment-block-commands=stddiff] +--- +# The clang-tidy module of our own, against the headers of LLVM the dev container keeps for it +# (tools/lib/tidy_module.sh); the major version follows ARG LLVM_MAJOR of .devcontainer/Dockerfile. +# It is written to LLVM's API, not to the library's rules, so the checks of .clang-tidy are +# not applied to it. +If: + PathMatch: tools/lib/tidy_module/.* +CompileFlags: + CompilationDatabase: None + Add: [-xc++, -std=c++17, -isystem/opt/llvm-23/include] +Diagnostics: + ClangTidy: + Remove: ['*'] diff --git a/.copier-answers.yml b/.copier-answers.yml new file mode 100644 index 0000000..e4e5918 --- /dev/null +++ b/.copier-answers.yml @@ -0,0 +1,18 @@ +# The answers this project was made from, which `copier update` reads. Change one with +# `copier update --data name=value`, not here. +_commit: v0.5.0 +_src_path: gh:theAndreas/embedded-cpp-template +arduino_core: arduino:avr@1.8.8 +author: Andreas Burnickl +copyright_year: 2026 +description: Periodic interrupt, PWM and time readout on Timer2 of the ATmega328P. +fqbn: arduino:avr:uno +github_owner: theAndreas +license: GPL-3.0-or-later +macro_prefix: TIMERTWO +namespace: timer_two +project_name: TimerTwo +simavr_frequency: 16000000 +simavr_mcu: atmega328p +skeleton: false +url: https://github.com/theAndreas/TimerTwo diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..741469a --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,193 @@ +# Base image, overridable via build.args in a devcontainer.json variant so that +# site-specific base images can be used without touching this file. +# +# The tag has no hyphen. devcontainers/cpp publishes ubuntu-24.04 and ubuntu24.04 both, +# but from 26.04 only the unhyphenated form exists, so the older spelling looks like the +# newest release when it is not. The base image carries build-essential and gdb: the host +# g++ builds the tests against the mock of the core, and whatever tools/project.sh prepares +# for the build, such as a GCC plugin against the plugin headers of the AVR core's avr-gcc. +ARG BASE_IMAGE=mcr.microsoft.com/devcontainers/cpp:ubuntu26.04 +FROM ${BASE_IMAGE} + +# CMake, Ninja and GoogleTest build and run the tests on the host, clang a second time beside +# the base image's g++ (make clang); simavr runs examples/SelfCheck as the board would +# (tools/self_check.sh); jq writes the compilation database of tools/tidy.sh; Doxygen builds +# the reference (tools/docs.sh), and cppcheck reads the library beside clang-tidy +# (tools/cppcheck.sh); neither of the two is on PyPI. From apt +# rather than pinned like the tools below: the distribution's versions are what CI installs +# as well, and none of them has a bug that forces a newer release. +RUN apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + cmake ninja-build libgtest-dev clang simavr jq doxygen cppcheck && \ + rm -rf /var/lib/apt/lists/* + +# arduino-cli compiles the library and its examples with the real Arduino AVR core, which +# is the one check the tests on the host cannot replace: they build against a mock of +# Arduino.h, not against avr-gcc, and flash is RAM there. Not gcc-avr from apt - the AVR +# core brings its own toolchain, and that one is what the Arduino IDE compiles a user's +# sketch with. +# A pinned release tarball with its published checksum, for the same reason as gh below: +# the trust stays anchored to something visible in this file, at the cost of bumping the +# version by hand. +ARG ARDUINO_CLI_VERSION=1.5.1 +ARG ARDUINO_CLI_SHA256_AMD64=28a8e119c498a25607821c36cb2dc49e8463941b261a0d99091baa7bc692dd2b +ARG ARDUINO_CLI_SHA256_ARM64=1e69e077479f300614d4551334e0a33f08ee40b04315d83b8e7e0e94f0d0ee62 +RUN ARCH="$(dpkg --print-architecture)" && \ + case "${ARCH}" in \ + amd64) ASSET=64bit; SHA256="${ARDUINO_CLI_SHA256_AMD64}" ;; \ + arm64) ASSET=ARM64; SHA256="${ARDUINO_CLI_SHA256_ARM64}" ;; \ + *) echo "arduino-cli: no pinned checksum for ${ARCH}; add one or drop arduino-cli" >&2; exit 1 ;; \ + esac && \ + curl -fsSL -o /tmp/arduino-cli.tar.gz \ + "https://github.com/arduino/arduino-cli/releases/download/v${ARDUINO_CLI_VERSION}/arduino-cli_${ARDUINO_CLI_VERSION}_Linux_${ASSET}.tar.gz" && \ + echo "${SHA256} /tmp/arduino-cli.tar.gz" | sha256sum -c - && \ + tar -xzf /tmp/arduino-cli.tar.gz -C /usr/local/bin arduino-cli && \ + rm /tmp/arduino-cli.tar.gz + +# arduino-lint checks library.properties, keywords.txt and the folder layout against the +# rules the Arduino Library Manager applies, so a broken library is found here rather than +# when the registry rejects it. Pinned the same way as arduino-cli. +ARG ARDUINO_LINT_VERSION=1.3.0 +ARG ARDUINO_LINT_SHA256_AMD64=181671ca174988f2601e1cdf2b40a552682db8eaa047de33117e67e70338b63e +ARG ARDUINO_LINT_SHA256_ARM64=d886fd734762f43b90990ff0ec12d65e088f74516db1a1a9c3c2de6b7fffdada +RUN ARCH="$(dpkg --print-architecture)" && \ + case "${ARCH}" in \ + amd64) ASSET=64bit; SHA256="${ARDUINO_LINT_SHA256_AMD64}" ;; \ + arm64) ASSET=ARM64; SHA256="${ARDUINO_LINT_SHA256_ARM64}" ;; \ + *) echo "arduino-lint: no pinned checksum for ${ARCH}; add one or drop arduino-lint" >&2; exit 1 ;; \ + esac && \ + curl -fsSL -o /tmp/arduino-lint.tar.gz \ + "https://github.com/arduino/arduino-lint/releases/download/${ARDUINO_LINT_VERSION}/arduino-lint_${ARDUINO_LINT_VERSION}_Linux_${ASSET}.tar.gz" && \ + echo "${SHA256} /tmp/arduino-lint.tar.gz" | sha256sum -c - && \ + tar -xzf /tmp/arduino-lint.tar.gz -C /usr/local/bin arduino-lint && \ + rm /tmp/arduino-lint.tar.gz + +# gh turns branch and pull request housekeeping into something doable from the container +# rather than by hand in a browser. +# A pinned release .deb, not the universe package - that one is 2.46, whose `gh pr edit` +# still asks for the retired Projects-classic `projectCards` field and therefore fails +# outright. dpkg rather than apt because the package Depends on git alone, which the base +# image carries - so this needs no package lists. +ARG GH_VERSION=2.97.0 +ARG GH_SHA256_AMD64=7c7fa3bb890db0934baf65910d97b8c0fa437b2e590f7f7daf6bdf82c5c486d7 +ARG GH_SHA256_ARM64=0ba7a76739c865d82ebde24667d875d9b8caa55db47c7597c24accdd4defd2bb +RUN ARCH="$(dpkg --print-architecture)" && \ + case "${ARCH}" in \ + amd64) SHA256="${GH_SHA256_AMD64}" ;; \ + arm64) SHA256="${GH_SHA256_ARM64}" ;; \ + *) echo "gh: no pinned checksum for ${ARCH}; add one or drop gh" >&2; exit 1 ;; \ + esac && \ + curl -fsSL -o /tmp/gh.deb \ + "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_${ARCH}.deb" && \ + echo "${SHA256} /tmp/gh.deb" | sha256sum -c - && \ + dpkg -i /tmp/gh.deb && \ + rm /tmp/gh.deb + +# uv makes the environment of the Python tools from pyproject.toml and uv.lock, in the +# workspace's .venv, on the first `uv run` or with `uv sync --frozen` when the container is +# created: clang-format, clang-tidy, cpplint, gcovr, shellcheck, actionlint, ruff and copier, +# at the versions CI checks with. This ARG is the one place uv's version is written: +# .github/actions/uv-sync reads it for CI. Pinned with its published checksum, as the tools +# above. +ARG UV_VERSION=0.12.0 +ARG UV_SHA256_AMD64=eaf842262aa1c418d8ecc5605f02ee1ebfd369124fa48548e85f9481a47831a9 +ARG UV_SHA256_ARM64=2c5d6e3092cc5223b10ff403880cc75121bf64e84644e7a0c69f643b0d89ac95 +RUN ARCH="$(dpkg --print-architecture)" && \ + case "${ARCH}" in \ + amd64) TRIPLE=x86_64-unknown-linux-gnu; SHA256="${UV_SHA256_AMD64}" ;; \ + arm64) TRIPLE=aarch64-unknown-linux-gnu; SHA256="${UV_SHA256_ARM64}" ;; \ + *) echo "uv: no pinned checksum for ${ARCH}; add one or drop uv" >&2; exit 1 ;; \ + esac && \ + curl -fsSL -o /tmp/uv.tar.gz \ + "https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/uv-${TRIPLE}.tar.gz" && \ + echo "${SHA256} /tmp/uv.tar.gz" | sha256sum -c - && \ + tar -xzf /tmp/uv.tar.gz -C /usr/local/bin --strip-components=1 \ + "uv-${TRIPLE}/uv" "uv-${TRIPLE}/uvx" && \ + rm /tmp/uv.tar.gz + +# clangd gives the editor completion, navigation and the findings of clang-tidy, with the +# .clang-tidy of the repository, reading the compilation databases that .clangd names. +# From PyPI through uv, pinned, as clang-tidy in tools/tidy.sh; 22 is the newest there, one +# behind the clang-tidy 23 of CI, which stays the measure. The package wraps the binary in +# a Python script whose interpreter would lie in root's home, out of the remote user's +# reach, so the link goes to the binary itself, which finds its headers next to it. +ARG CLANGD_VERSION=22.1.1 +RUN UV_TOOL_DIR=/opt/uv/tools UV_PYTHON_INSTALL_DIR=/opt/uv/python \ + UV_TOOL_BIN_DIR=/opt/uv/bin \ + uv tool install --no-cache "clangd==${CLANGD_VERSION}" && \ + ln -s "$(find /opt/uv/tools/clangd -path '*/clangd/data/bin/clangd' -type f)" \ + /usr/local/bin/clangd && \ + clangd --version + +# The headers of LLVM, clang and clang-tidy that tools/lib/tidy_module.sh compiles the checks of +# our own against, as a module that the clang-tidy of uv.lock loads. LLVM_MAJOR is that +# clang-tidy's major version: tools/lib/tidy_module.sh fails, saying so, when uv.lock moves on and +# this does not. CI's action llvm-headers reads it from here, so there is one place that says +# which LLVM. llvm-headers.sh says where they come from, and why not pinned closer. +ARG LLVM_MAJOR=23 +COPY llvm-headers.sh /tmp/llvm-headers.sh +RUN /tmp/llvm-headers.sh "${LLVM_MAJOR}" "/opt/llvm-${LLVM_MAJOR}/include" && \ + rm /tmp/llvm-headers.sh + +# The Arduino data directory and uv's cache are named volumes: the AVR core and its +# toolchain, and the checkers from PyPI, are downloaded on first use, and the volumes are +# what keep a rebuild from fetching them again. An empty named volume takes its ownership +# from the path it covers, so the path has to exist and belong to the remote user first, +# or nothing can write into it. `install -d` gives only the last component to the owner and +# creates missing parents as root, so ~/.cache is named on its own: a base image without it +# would otherwise leave it to root, and arduino-cli could not put its build cache there. +RUN install -d -o vscode -g vscode -m 0755 /home/vscode/.arduino15 && \ + install -d -o vscode -g vscode -m 0755 /home/vscode/.cache /home/vscode/.cache/uv + +# The same arrangement for the logins a rebuild would otherwise throw away: Codex and Claude +# Code, whose extensions the shared feature installs, and gh, which every push and every pull request +# goes through. Mode 0700 rather than 0755, because what these hold is a credential and not +# a cache - and gh refuses to read a config directory others can enter. ~/.config is +# named on its own, as ~/.cache above, so that it does not fall to root. +RUN install -d -o vscode -g vscode -m 0700 /home/vscode/.codex && \ + install -d -o vscode -g vscode -m 0700 /home/vscode/.claude && \ + install -d -o vscode -g vscode -m 0755 /home/vscode/.config && \ + install -d -o vscode -g vscode -m 0700 /home/vscode/.config/gh + +# The shell history, a volume as well, so that a rebuild keeps it. 0700 too: a command line +# can carry a token. +RUN install -d -o vscode -g vscode -m 0700 /home/vscode/.commandhistory + +# GitHub's SSH host key, so that the first git operation in a fresh container verifies +# against something rather than failing with "Host key verification failed", because +# ~/.ssh belongs to the container and is empty after every rebuild. +# +# Written out rather than fetched with ssh-keyscan at build time: a scan believes whatever +# answers it, which is precisely what a known host key is there to prevent. The fingerprint +# below is the one GitHub publishes under "GitHub's SSH key fingerprints", and +# `ssh-keygen -lf /etc/ssh/ssh_known_hosts` prints it back out of the file. +# +# Three names for one key: github.com, ssh.github.com for SSH on port 443 in networks that +# block 22, and the bracketed form, because an entry is keyed by host *and* port. +ARG GITHUB_HOST_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" +RUN printf '# SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU\n%s %s\n%s %s\n%s %s\n' \ + 'github.com' "${GITHUB_HOST_KEY}" \ + 'ssh.github.com' "${GITHUB_HOST_KEY}" \ + '[ssh.github.com]:443' "${GITHUB_HOST_KEY}" \ + >> /etc/ssh/ssh_known_hosts && \ + chmod 0644 /etc/ssh/ssh_known_hosts + +# The project's own packages, from apt-packages.txt beside this file, which the project's +# workflows install as well. Last, so that a change to the list builds this layer alone and none +# of the downloads above. Nothing to do for an empty list. +COPY apt-packages.txt /tmp/apt-packages.txt +RUN packages="$(sed -e 's/#.*//' /tmp/apt-packages.txt | xargs)" && \ + if [ -n "${packages}" ]; then \ + apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ${packages} && \ + rm -rf /var/lib/apt/lists/*; \ + fi && \ + rm /tmp/apt-packages.txt + +ENV TZ=Europe/Berlin + +# Extensions, editor settings and lifecycle commands live in the local feature +# in shared/, which every devcontainer.json variant references. A +# devcontainer.metadata label set here would not work: clients read image +# metadata from the image the final FROM points at, then overwrite the label on +# the image they build from this file. diff --git a/.devcontainer/README.md b/.devcontainer/README.md new file mode 100644 index 0000000..67a6f3a --- /dev/null +++ b/.devcontainer/README.md @@ -0,0 +1,132 @@ +# TimerTwo development containers + +VS Code offers two configurations when running **Dev Containers: Reopen in Container**: + +- **TimerTwo (Linux)** for native Linux and remote environments. It mounts the host's SSH agent. +- **TimerTwo (WSL2)** when VS Code runs in WSL2. It relies on VS Code's own SSH-agent forwarding and + mounts nothing. + +Open the repository from a checkout on the host, in WSL2 the Linux side of it: a folder inside +another container is lost with that container. + +## What the container carries + +| Tool | What for | +|---|---| +| `arduino-cli` with the core of `tools/project.sh` | the library and its examples with the real toolchain, pinned as in CI | +| `simavr` | `examples/SelfCheck` as the board runs it: `tools/self_check.sh` | +| `g++`, `gdb` (from the base image) | the tests on the host, and what `tools/project.sh` prepares | +| `cmake`, `ninja`, GoogleTest | the tests on the host: `cmake --workflow --preset default` | +| `uv` | the Python tools that `uv.lock` pins, in `.venv`: clang-format, clang-tidy, cpplint, gcovr, shellcheck, actionlint, ruff, copier | +| `clang` | the tests a second time, by another compiler: `make clang` | +| `clangd` | IntelliSense, see below | +| LLVM's headers, in `/opt/llvm-23/include` | the checks of our own, `house-*`, a module that `tools/lib/tidy_module.sh` builds and `tools/tidy.sh` loads | +| `jq` | the compilation database of `tools/tidy.sh` | +| `cppcheck` | a second analyser beside clang-tidy: `tools/cppcheck.sh` | +| `arduino-lint` | the rules of the Arduino Library Manager | +| `gh` | branches and pull requests from the container | +| what `apt-packages.txt` lists | the project's own, as a simulator's libraries | + +`apt-packages.txt` is the project's: the Dockerfile installs what it lists, last, so that a +change to it rebuilds that layer alone, and a workflow of the project's installs the same with +the action `apt-install` and `file: .devcontainer/apt-packages.txt`, as the jobs of `ci.yml` and +`static-analysis.yml` that build with CMake do. `copier update` leaves it alone. + +The `postCreateCommand` runs `tools/setup.sh`, which installs the core and builds what +`tools/project.sh` prepares, configures CMake and writes the compilation databases, so that a new container can build, check and complete code at once. + +**Flashing is not covered.** The container builds; getting a USB serial adapter into it is another +matter, and under WSL2 it needs `usbipd-win` on the Windows side first. Build here, flash from the +host. + +## IntelliSense: clangd + +clangd does completion, navigation and the findings of clang-tidy, with the repository's +`.clang-tidy`, so the editor shows what CI would. cpptools stays installed for debugging, with its +IntelliSense off, so that the two do not answer twice. + +clangd reads the compilation database that `.clangd` names for a path, as no single one covers +everything: + +- `src/` and `test/` from CMake, against the mock of the core, in `build/host/`. +- `examples/` from `tools/tidy.sh --database-only`, in `build/tidy/default/`, with the flags the + board is compiled with: only that one has the sketches, an `.ino` as C++ with `Arduino.h` included + first. + +Both are written when the container is created. After adding a file, run `cmake --preset default` +or `tools/tidy.sh --database-only` again. clangd inserts no includes: a sketch includes +`` first, which an include put in by the editor would not know. + +clangd does not load the module of the checks of our own, `house-*`: those findings come from +`make tidy` alone. The module's own sources in `tools/lib/tidy_module/` are read against LLVM's +headers, without the checks of `.clang-tidy`, which are the library's rules and not LLVM's. + +clangd comes from PyPI at 22.1.1, the newest there, one behind the clang-tidy 23 of CI, which stays +the measure. The package wraps the binary in a Python script whose interpreter would lie in root's +home; `/usr/local/bin/clangd` links to the binary itself. + +## Volumes + +The Arduino core and its toolchain, and the checkers uv fetches, are not part of the image. They live +in the named volumes `timer_two-arduino15` and `timer_two-uv-cache`, so that a rebuild does not download them +again. Three more carry a login across a rebuild: `timer_two-codex` at `/home/vscode/.codex`, +`timer_two-claude` at `/home/vscode/.claude` (with `CLAUDE_CONFIG_DIR` pointing there, so that +Claude Code's `.claude.json` lands in it too) and `timer_two-gh` at `/home/vscode/.config/gh`, all at +mode 0700, as `gh` refuses a config directory others can enter. Those three hold credentials: do not share, export or remove one unless the login should go. +The shell history lives in `timer_two-history` at `/home/vscode/.commandhistory`, written after every +command (`HISTFILE` and `PROMPT_COMMAND` in `shared/devcontainer-feature.json`); remove the volume to +forget it. + +The `Dockerfile` creates each path as the remote user first: an empty named volume takes its +ownership from the path it covers, and one that does not exist in the image gives a volume owned by +root that nothing can write into. + +## SSH agent on Linux + +The Linux variant mounts the host's `SSH_AUTH_SOCK` at the fixed path `/tmp/ssh-agent`, as the host +socket carries a random name. An `initializeCommand` checks that the agent runs first, so that a +missing one is reported as such rather than as a docker error about an empty `source=`: + +```sh +ssh-add -l +``` + +GitHub's SSH host key is written into `/etc/ssh/ssh_known_hosts` by the `Dockerfile`, as published +by GitHub, so the first SSH operation does not fail with `Host key verification failed`. + +## Pinned tools + +`arduino-cli`, `arduino-lint`, `gh` and `uv` are pinned release downloads, each verified against its +published SHA-256 in the `Dockerfile`; `clangd` is pinned on PyPI. Bumping a version means bumping +its checksums as well. `gh auth login` has to run in a terminal, once, as its login stays in its +volume. The shared feature's `postAttachCommand` then runs `gh auth setup-git` on every attach, so +that `git push` over HTTPS uses the same token instead of VS Code's helper, which opens a window +on the host; on every attach, as VS Code copies the host's `.gitconfig` into a new container. + +LLVM's headers are not pinned closer than their major version, `ARG LLVM_MAJOR`: `llvm-headers.sh` +takes them from apt.llvm.org, which keeps only the newest build of a release branch, and checks the +archive's signature against the fingerprint in the script. Within a major version LLVM keeps its +ABI. When `uv.lock` moves clang-tidy to the next major version, `make tidy` says so, and +`LLVM_MAJOR` follows it, as does the path in `.clangd`. + +`gh` is pointed at `github.com` by the shared feature's `containerEnv`. A base image that sets +`GH_HOST` to a company GitHub needs `"remoteEnv": {"GH_HOST": "github.com"}` in its +`devcontainer.json` as well: the VS Code server starts with the image's value, and `remoteEnv` is +applied last. + +## Shared configuration + +Extensions, settings, volumes, the `postCreateCommand` and the `postAttachCommand` live in the +local feature in `shared/`, which every configuration references with +`"features": { "./../shared": {} }`. A variant can add extensions of its own on top. Feature metadata is baked into the image, so a change to +`shared/devcontainer-feature.json` needs **Dev Containers: Rebuild Container**. + +## Site-specific variants + +Another directory beside `linux/` and `wsl2/` shows up as another entry in the same picker: the +place for what must not be committed, such as an internal base image through the `BASE_IMAGE` +build argument. `/.devcontainer/vector/` is listed in `.gitignore` for that. + +Behind a TLS-intercepting proxy the public base image cannot build, as it does not trust the proxy's +certificate and the first download fails with `curl` exit code 60. A base image that carries the +proxy's CA, set through `BASE_IMAGE`, fixes that. diff --git a/.devcontainer/apt-packages.txt b/.devcontainer/apt-packages.txt new file mode 100644 index 0000000..bada23b --- /dev/null +++ b/.devcontainer/apt-packages.txt @@ -0,0 +1,9 @@ +# The project's own Ubuntu packages, beside those the Dockerfile installs for every project: one +# or more per line, # for a comment. The Dockerfile installs them into the dev container, and a +# workflow of the project's installs the same with the action apt-install and its input file: +# +# - uses: ./.github/actions/apt-install +# with: +# file: .devcontainer/apt-packages.txt +# +# The template wrote this file once; it is the project's, and `copier update` leaves it alone. diff --git a/.devcontainer/linux/devcontainer.json b/.devcontainer/linux/devcontainer.json new file mode 100644 index 0000000..0b4e232 --- /dev/null +++ b/.devcontainer/linux/devcontainer.json @@ -0,0 +1,31 @@ +{ + "name": "TimerTwo (Linux)", + "build": { + "dockerfile": "../Dockerfile", + "context": ".." + }, + // Extensions, the Arduino core and the volumes live in ../shared. + "features": { + "./../shared": {} + }, + // Podman's generated feature build can leave /tmp at 0755 even after chmod + // in the Dockerfile. Set its permissions at runtime, before VS Code attaches. + "runArgs": ["--tmpfs", "/tmp:rw,mode=1777"], + // X11 works on native Linux without requiring the WSL-only /mnt/wslg path. + "containerEnv": { + "DISPLAY": "${localEnv:DISPLAY}" + }, + // The agent socket lands on a fixed path, because the host one carries a random + // name that would change under the container on every host login. + "remoteEnv": { + "SSH_AUTH_SOCK": "/tmp/ssh-agent" + }, + // A missing SSH_AUTH_SOCK would leave the mount below with an empty "source=", + // and container creation then fails on a docker error that never mentions SSH. + // Fail here instead, where the message can say what to do about it. + "initializeCommand": "bash -c 'test -S \"$SSH_AUTH_SOCK\" || { echo \"TimerTwo devcontainer: no SSH agent on the host (SSH_AUTH_SOCK is unset or not a socket). Start one and add the key, or use the WSL2 variant, which relies on VS Codes own agent forwarding. See .devcontainer/README.md.\" >&2; exit 1; }'", + "mounts": [ + "source=/tmp/.X11-unix,target=/tmp/.X11-unix,type=bind", + "source=${localEnv:SSH_AUTH_SOCK},target=/tmp/ssh-agent,type=bind" + ] +} diff --git a/.devcontainer/llvm-headers.sh b/.devcontainer/llvm-headers.sh new file mode 100755 index 0000000..893e04d --- /dev/null +++ b/.devcontainer/llvm-headers.sh @@ -0,0 +1,92 @@ +#!/bin/bash +# +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Puts the headers of LLVM, clang and clang-tidy of one major version into a folder: what the +# clang-tidy module in tools/lib/tidy_module/ is compiled against. The clang-tidy from PyPI loads a +# module (--load) and exports the symbols one needs, but comes without headers. The Dockerfile +# runs this, and the action llvm-headers in CI, so that both have the same. +# +# Usage: +# llvm-headers.sh MAJOR DEST +# +# The headers come from apt.llvm.org, from llvm-MAJOR-dev and libclang-MAJOR-dev, unpacked and +# not installed: they depend on all of LLVM, and only the headers are wanted. apt reads the +# archive with a state and a configuration of its own in a temporary folder, so the system's +# sources, lists and hooks are left as they are, and no root is needed but to write DEST. Its +# signature is checked against the key whose fingerprint is below, the trust anchored in this +# file as the Dockerfile anchors its downloads. +# +# Not pinned to a patch release: apt.llvm.org keeps only the newest build of a release branch, +# and an older one is gone the day a newer comes. Within a major version LLVM keeps its ABI, so +# headers of 23.1.6 build a module that the clang-tidy 23.1.4 of uv.lock loads. +# tools/lib/tidy_module.sh checks the major version. + +set -euo pipefail + +# Sylvestre Ledru's key, which signs apt.llvm.org. +readonly KEY_URL="https://apt.llvm.org/llvm-snapshot.gpg.key" +readonly KEY_FINGERPRINT="6084F3CF814B57C1CF12EFD515CF4D18AF4F7421" + +main() { + if [[ $# -ne 2 ]]; then + echo "Usage: $0 MAJOR DEST" >&2 + exit 2 + fi + local major="$1" + local dest="$2" + local codename + codename="$(sed -n 's/^VERSION_CODENAME=//p' /etc/os-release)" + + local tmp + tmp="$(mktemp -d)" + # shellcheck disable=SC2064 # expanded now, as tmp is local + trap "rm -rf '${tmp}'" EXIT + + # gpg's home in the temporary folder as well, so that none is left in the image. + export GNUPGHOME="${tmp}/gnupg" + mkdir -m 0700 "${GNUPGHOME}" + curl -fsSL "${KEY_URL}" | gpg --quiet --dearmor > "${tmp}/llvm.gpg" + local fingerprint + fingerprint="$(gpg --quiet --show-keys --with-colons "${tmp}/llvm.gpg" \ + | awk -F: '$1 == "fpr" { print $10; exit }')" + if [[ "${fingerprint}" != "${KEY_FINGERPRINT}" ]]; then + echo "llvm-headers: the key at ${KEY_URL} is ${fingerprint}, not ${KEY_FINGERPRINT}" >&2 + exit 1 + fi + + echo "deb [signed-by=${tmp}/llvm.gpg] https://apt.llvm.org/${codename}/" \ + "llvm-toolchain-${codename}-${major} main" > "${tmp}/sources.list" + mkdir -p "${tmp}/lists/partial" "${tmp}/cache/archives/partial" "${tmp}/debs" \ + "${tmp}/apt.conf.d" + # Through APT_CONFIG, which apt reads before /etc/apt/apt.conf.d: on the command line, the + # parts would be read already, and with them the docker-clean of an Ubuntu image, whose hook + # empties the system's cache after an update. + cat > "${tmp}/apt.conf" </dev/null + (cd "${tmp}/debs" && apt-get -q download "llvm-${major}-dev" "libclang-${major}-dev" >/dev/null) + + local deb + for deb in "${tmp}"/debs/*.deb; do + dpkg-deb -x "${deb}" "${tmp}/root" + done + # usr/lib/llvm-MAJOR/include links to usr/include/llvm-MAJOR for llvm and llvm-c: -L copies what + # the links point to. + rm -rf "${dest}" + mkdir -p "${dest}" + cp -RL "${tmp}/root/usr/lib/llvm-${major}/include/." "${dest}/" + echo "llvm-headers: $(sed -n 's/^#define LLVM_VERSION_STRING "\(.*\)"/\1/p' \ + "${dest}/llvm/Config/llvm-config.h") in ${dest}" +} + +main "$@" diff --git a/.devcontainer/shared/devcontainer-feature.json b/.devcontainer/shared/devcontainer-feature.json new file mode 100644 index 0000000..46d3b31 --- /dev/null +++ b/.devcontainer/shared/devcontainer-feature.json @@ -0,0 +1,94 @@ +{ + "id": "shared", + "version": "1.0.0", + "name": "TimerTwo shared editor configuration", + "description": "Extensions, the Arduino core, the CMake build of the tests and the volumes for the Arduino data directory, uv's cache and logins shared by every devcontainer.json variant.", + "customizations": { + "vscode": { + "extensions": [ + "llvm-vs-code-extensions.vscode-clangd", + "ms-vscode.cpptools", + "eamodio.gitlens", + "cschlosser.doxdocgen", + "openai.chatgpt", + "anthropic.claude-code" + ], + // clangd for IntelliSense, with the databases .clangd names; cpptools only + // for debugging, its IntelliSense off so that the two do not answer twice. + // doxdocgen writes the skeleton of a Doxygen block, see the settings below. + // No header insertion: a sketch includes first, and an + // include put in by the editor would not know that. An .ino is C++. + "settings": { + "C_Cpp.intelliSenseEngine": "disabled", + "clangd.path": "/usr/local/bin/clangd", + "clangd.arguments": ["--header-insertion=never"], + "files.associations": { "*.ino": "cpp" }, + // The skeleton of a Doxygen block in the style of docs/Documentation.md: + // /*! and Enter above a declaration. + "doxdocgen.c.triggerSequence": "/*!", + "doxdocgen.c.firstLine": "/*!", + "doxdocgen.c.commentPrefix": " * ", + "doxdocgen.c.lastLine": " */", + "doxdocgen.generic.briefTemplate": "\\brief {text}", + "doxdocgen.generic.paramTemplate": "\\param[in] {param} ", + "doxdocgen.cpp.tparamTemplate": "\\tparam {param} ", + "doxdocgen.generic.returnTemplate": "\\return ", + "doxdocgen.generic.includeTypeAtReturn": false, + "doxdocgen.generic.order": ["brief", "empty", "tparam", "param", "return"] + } + } + }, + // uv's cache is a volume of its own, another file system than the workspace's .venv, so it + // copies rather than failing to link and saying so on every sync. + "containerEnv": { + "GH_HOST": "github.com", + "UV_LINK_MODE": "copy", + // Claude Code keeps .claude.json beside ~/.claude rather than in it; this puts both + // into the volume below, so that a rebuild keeps the login and the settings. + "CLAUDE_CONFIG_DIR": "/home/vscode/.claude", + // The shell history in the volume below, written after every command rather than + // when the shell exits, as a terminal that a rebuild closes never exits cleanly. + // ~/.bashrc appends its own hook to PROMPT_COMMAND, so this one stays. + "HISTFILE": "/home/vscode/.commandhistory/.bash_history", + "PROMPT_COMMAND": "history -a" + }, + // The Python tools of uv.lock, the core of tools/project.sh, pinned as in CI, and what + // prepare() there builds; then the compilation databases clangd reads, see .clangd. + "postCreateCommand": "uv sync --frozen && make setup && cmake --preset default && tools/tidy.sh --database-only && arduino-cli version && arduino-lint --version && gh --version && uv --version && clangd --version && command -v simavr && doxygen --version && cppcheck --version && clang++ --version", + // git signs in to GitHub through gh, whose login is in the volume below, rather than + // through VS Code's helper, which opens a window on the host. On every attach, after VS Code + // has copied the host's .gitconfig in; nothing without a login. + "postAttachCommand": "gh auth status --hostname github.com >/dev/null 2>&1 && gh auth setup-git --hostname github.com || true", + "mounts": [ + { + "source": "timer_two-arduino15", + "target": "/home/vscode/.arduino15", + "type": "volume" + }, + { + "source": "timer_two-uv-cache", + "target": "/home/vscode/.cache/uv", + "type": "volume" + }, + { + "source": "timer_two-codex", + "target": "/home/vscode/.codex", + "type": "volume" + }, + { + "source": "timer_two-claude", + "target": "/home/vscode/.claude", + "type": "volume" + }, + { + "source": "timer_two-gh", + "target": "/home/vscode/.config/gh", + "type": "volume" + }, + { + "source": "timer_two-history", + "target": "/home/vscode/.commandhistory", + "type": "volume" + } + ] +} diff --git a/.devcontainer/shared/install.sh b/.devcontainer/shared/install.sh new file mode 100644 index 0000000..4bddead --- /dev/null +++ b/.devcontainer/shared/install.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The editor metadata in devcontainer-feature.json is the whole of this feature; +# the tools are installed by ../Dockerfile, and the Arduino AVR core by the +# postCreateCommand, as it lives in a volume rather than in the image. + +set -e + +echo "TimerTwo shared configuration: nothing to install." diff --git a/.devcontainer/wsl2/devcontainer.json b/.devcontainer/wsl2/devcontainer.json new file mode 100644 index 0000000..2c40869 --- /dev/null +++ b/.devcontainer/wsl2/devcontainer.json @@ -0,0 +1,12 @@ +{ + "name": "TimerTwo (WSL2)", + "build": { + "dockerfile": "../Dockerfile", + "context": ".." + }, + // Extensions, the Arduino core and the volumes live in ../shared. + // Nothing is mounted: this variant relies on VS Code's own SSH-agent forwarding. + "features": { + "./../shared": {} + } +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..5631df7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +# What an editor that reads EditorConfig keeps to before clang-format sees a file, in every +# file of the repository, scripts and Markdown among them. +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..783395b --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,5 @@ +self-hosted-runner: + # GitHub's own runner, which CI uses, but newer than the list of labels in + # the actionlint that tools/lint.sh pins. + labels: + - ubuntu-26.04 diff --git a/.github/actions/apt-install/action.yml b/.github/actions/apt-install/action.yml new file mode 100644 index 0000000..c523b49 --- /dev/null +++ b/.github/actions/apt-install/action.yml @@ -0,0 +1,117 @@ +# apt-get install for a CI job, made to survive the Ubuntu mirror having a bad hour. +# +# What it guards against was read out of a job that sat in its install step until the job's +# timeout cancelled it: apt-get update fetched its indices at 13 MB/s, and then the package +# downloads crawled - cmake's 14 MB took five minutes, and gcc-avr's 57 MB was still coming +# thirteen minutes later. A connection that trickles is not a connection that has died, so +# apt never gives up on it, and the step ran into the job's timeout-minutes, which reports as +# a cancellation and says nothing about why. +# +# So, in that order: +# +# - The .deb files are cached, keyed by exactly the versions this run would fetch. A run whose +# packages have not changed downloads nothing from the mirror at all; a new version in the +# archive is a new key, so the cache follows the archive by itself instead of going stale. +# - What is still missing is downloaded with --download-only under a timeout, generous next +# to a normal run, which fetches all of it in seconds. A retry goes to a different mirror: +# the first version of this retried on a new connection, and all four attempts met the same +# crawl on the same file - the runner's apt-mirrors.txt lists Azure's mirror first and +# archive.ubuntu.com second, but apt moves down that list on an error, never on slowness. +# So from the second attempt on, Azure's line is taken out of the list. +# - Only then is it installed, from the cache and with no timeout: the downloading is over by +# then, and a timeout that killed dpkg halfway through unpacking would leave the runner +# broken rather than slow. +name: Install Ubuntu packages +description: apt-get install with the downloads cached, and a stalled mirror retried rather than waited out + +inputs: + packages: + description: The packages to install, separated by spaces + required: false + default: "" + file: + description: A file of more packages, one or more per line, # for a comment, as .devcontainer/apt-packages.txt + required: false + default: "" + +runs: + using: composite + steps: + # The packages given and those of the file, so that a job installs what the project's dev + # container has, from the one list both read. + - name: Collect the packages + id: collect + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + LIST: ${{ inputs.file }} + run: | + if [ -n "$LIST" ]; then + PACKAGES="$PACKAGES $(sed -e 's/#.*//' "$LIST" | xargs)" + fi + PACKAGES=$(xargs <<< "$PACKAGES") + if [ -z "$PACKAGES" ]; then + echo "::error::no packages: neither packages nor file names one" + exit 1 + fi + echo "packages=$PACKAGES" >> "$GITHUB_OUTPUT" + + # The index is normally fast even when the archive is not, and the key below needs it. It + # gets the same timeout and retry all the same: ci.yml records an apt-get update that hung. + # --print-uris lists every .deb the install would fetch. Only the file name goes into the + # key: it carries the version, so the key changes exactly when a download would, while the + # URL in front of it names whichever mirror this runner was given. + - name: Work out what would be downloaded + id: plan + shell: bash + run: | + for Attempt in 1 2 3; do + if sudo timeout 120 apt-get update -q; then break; fi + if [ "$Attempt" -eq 3 ]; then + echo "::error::apt-get update did not finish in three attempts" + exit 1 + fi + echo "::warning::apt-get update attempt $Attempt stalled or failed; retrying" + done + KEY=$(apt-get install --print-uris -qq --no-install-recommends ${{ steps.collect.outputs.packages }} | cut -d' ' -f2 | sha256sum | cut -c1-16) + echo "key=$KEY" >> "$GITHUB_OUTPUT" + + - name: Restore the downloaded packages + uses: actions/cache@v6 + with: + path: ~/apt-archives + key: apt-${{ runner.os }}-${{ steps.plan.outputs.key }} + # An older set still holds most of the files; apt fetches only what differs. + restore-keys: apt-${{ runner.os }}- + + # apt downloads into ~/apt-archives as root and warns that it cannot hand the job to its + # _apt sandbox user there. That is a warning, the download is the same; the chown + # afterwards is what lets the cache step read the files back to save them. + # timeout runs under sudo rather than around it, so that its signal reaches apt itself. + - name: Download, retrying a stalled mirror + shell: bash + run: | + mkdir -p ~/apt-archives/partial + for Attempt in 1 2 3 4; do + if [ "$Attempt" -eq 2 ] && grep -q 'azure\.archive\.ubuntu\.com' /etc/apt/apt-mirrors.txt 2>/dev/null; then + echo "::warning::moving off azure.archive.ubuntu.com to the next mirror in /etc/apt/apt-mirrors.txt" + sudo sed -i '/azure\.archive\.ubuntu\.com/d' /etc/apt/apt-mirrors.txt + fi + if sudo timeout 240 apt-get -q -o Dir::Cache::Archives="$HOME/apt-archives" -o APT::Keep-Downloaded-Packages=true \ + install -y --no-install-recommends --download-only ${{ steps.collect.outputs.packages }}; then + break + fi + if [ "$Attempt" -eq 4 ]; then + echo "::error::apt could not download the packages in four attempts" + exit 1 + fi + echo "::warning::apt download attempt $Attempt stalled or failed; retrying" + done + sudo chown -R "$(id -u):$(id -g)" ~/apt-archives + + - name: Install + shell: bash + run: | + sudo apt-get -q -o Dir::Cache::Archives="$HOME/apt-archives" -o APT::Keep-Downloaded-Packages=true \ + install -y --no-install-recommends ${{ steps.collect.outputs.packages }} + sudo chown -R "$(id -u):$(id -g)" ~/apt-archives diff --git a/.github/actions/arduino-setup/action.yml b/.github/actions/arduino-setup/action.yml new file mode 100644 index 0000000..0e84aa8 --- /dev/null +++ b/.github/actions/arduino-setup/action.yml @@ -0,0 +1,38 @@ +# arduino-cli for a CI job, at the dev container's version, and the core tools/project.sh pins, +# with what its prepare() builds beyond it. +# +# The version is read from the ARG ARDUINO_CLI_VERSION line of .devcontainer/Dockerfile, as +# uv-sync reads uv's, so there is one place that says which arduino-cli. The core, its toolchain +# among it, is kept between runs, keyed by tools/project.sh, which names it: a run whose core +# has not changed fetches nothing. +name: Set up arduino-cli +description: arduino-cli at the dev container's version, and the pinned core through make setup + +runs: + using: composite + steps: + - name: Read the version + id: version + shell: bash + run: | + version=$(sed -n 's/^ARG ARDUINO_CLI_VERSION=//p' .devcontainer/Dockerfile) + if [ -z "$version" ]; then + echo "::error::.devcontainer/Dockerfile names no ARG ARDUINO_CLI_VERSION" + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + + - uses: arduino/setup-arduino-cli@v2 + with: + version: ${{ steps.version.outputs.version }} + + - name: Cache the core + uses: actions/cache@v6 + with: + path: ~/.arduino15 + key: arduino-${{ runner.os }}-${{ hashFiles('tools/project.sh') }} + restore-keys: arduino-${{ runner.os }}- + + - name: Install the core + shell: bash + run: make setup diff --git a/.github/actions/llvm-headers/action.yml b/.github/actions/llvm-headers/action.yml new file mode 100644 index 0000000..95eb419 --- /dev/null +++ b/.github/actions/llvm-headers/action.yml @@ -0,0 +1,44 @@ +# The headers of LLVM, clang and clang-tidy for a CI job that runs tools/tidy.sh: the checks of +# our own, house-*, are a module that tools/lib/tidy_module.sh compiles against them. +# +# The major version is ARG LLVM_MAJOR of .devcontainer/Dockerfile, read from there as uv-sync +# reads uv's, so that the dev container and CI have the same; .devcontainer/llvm-headers.sh +# fetches them, the script the Dockerfile runs. They are kept between runs, keyed by the major +# version alone: within one, LLVM keeps its ABI, and a newer patch release changes nothing a +# module sees. After this action LLVM_INCLUDE_DIR names the folder. +name: LLVM headers +description: The headers of LLVM, clang and clang-tidy at the dev container's major version + +inputs: + root: + description: The folder that holds .devcontainer, the repository's if not given + default: . + +runs: + using: composite + steps: + - name: Read the major version + id: version + shell: bash + run: | + major=$(sed -n 's/^ARG LLVM_MAJOR=//p' "${{ inputs.root }}/.devcontainer/Dockerfile") + if [ -z "$major" ]; then + echo "::error::${{ inputs.root }}/.devcontainer/Dockerfile names no ARG LLVM_MAJOR" + exit 1 + fi + echo "major=$major" >> "$GITHUB_OUTPUT" + echo "LLVM_INCLUDE_DIR=$RUNNER_TEMP/llvm-$major/include" >> "$GITHUB_ENV" + + - name: Restore the headers + id: cache + uses: actions/cache@v6 + with: + path: ${{ runner.temp }}/llvm-${{ steps.version.outputs.major }}/include + key: llvm-headers-${{ runner.os }}-${{ runner.arch }}-${{ steps.version.outputs.major }} + + - name: Fetch the headers + if: steps.cache.outputs.cache-hit != 'true' + shell: bash + run: | + "${{ inputs.root }}/.devcontainer/llvm-headers.sh" "${{ steps.version.outputs.major }}" \ + "$LLVM_INCLUDE_DIR" diff --git a/.github/actions/uv-sync/action.yml b/.github/actions/uv-sync/action.yml new file mode 100644 index 0000000..2c7a8ea --- /dev/null +++ b/.github/actions/uv-sync/action.yml @@ -0,0 +1,46 @@ +# The repository's Python tools for a CI job - clang-format, clang-tidy, cpplint, gcovr, +# shellcheck, actionlint, ruff - at the versions uv.lock pins. +# +# uv itself comes from PyPI at the version the dev container installs, read from the ARG +# UV_VERSION line of .devcontainer/Dockerfile, so there is one place that says which uv. It goes +# into a virtual environment of its own, because the runner's Python will not let pip write into +# the system one. +# Python is 3.14, the dev container's. +# +# uv's download cache is kept between runs, keyed by the lockfile, so a run whose lock has not +# changed fetches nothing. After this action the environment's bin directory is on PATH, and +# `uv run --frozen` in the steps after it finds the environment in .venv. +name: Sync the Python tools +description: uv at the dev container's version, and uv sync --frozen + +runs: + using: composite + steps: + - uses: actions/setup-python@v7 + with: + python-version: '3.14' + + - name: Install uv + shell: bash + run: | + version=$(sed -n 's/^ARG UV_VERSION=//p' .devcontainer/Dockerfile) + if [ -z "$version" ]; then + echo "::error::.devcontainer/Dockerfile names no ARG UV_VERSION" + exit 1 + fi + python -m venv "$RUNNER_TEMP/uv" + "$RUNNER_TEMP/uv/bin/pip" install --quiet "uv==$version" + echo "$RUNNER_TEMP/uv/bin" >> "$GITHUB_PATH" + + - name: Cache uv's downloads + uses: actions/cache@v6 + with: + path: ~/.cache/uv + key: uv-${{ runner.os }}-${{ hashFiles('uv.lock') }} + restore-keys: uv-${{ runner.os }}- + + - name: Sync + shell: bash + run: | + uv sync --frozen + echo "$GITHUB_WORKSPACE/.venv/bin" >> "$GITHUB_PATH" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..26838e4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,138 @@ +# What a pull request is built and tested with. Every step that builds or checks something is a +# target of the Makefile, the same a developer runs; under CI it takes the ci- presets, warnings +# as errors, as GitHub sets CI=true. What reads the code is static-analysis.yml beside this one, +# so that each has a badge of its own. +# +# lint clang-format, cpplint, shellcheck, actionlint, ruff +# tests the tests on the host, by GCC, also under ASan and UBSan, and what they reach +# of src/ into the job's summary +# clang the same tests by clang, which warns about other things than GCC +# examples SelfCheck in simavr, and every example in every variant, without a warning; +# flash and RAM into the job's summary +# arduino-lint the rules of the Arduino Library Manager +# +# Every job carries a timeout-minutes well above what it takes, for a job that has stopped +# making progress; the apt installs go through .github/actions/apt-install, which caches the +# packages and retries a mirror that has slowed to a trickle. This file comes from the template; +# a job of the project's own goes into a workflow of its own, so that `copier update` merges +# nothing into it. +name: CI + +on: + pull_request: + push: + branches: [main, master] + # So that release.yml runs this file rather than repeat it: a release is then something the + # whole of CI has passed. + workflow_call: + +# Read the repository and nothing else: no job here writes to it, and a token that could would be +# handed to every action each job runs. +permissions: + contents: read + +# A second push to the same branch makes the first answer worthless. +concurrency: + # The file's own name in the group: called by release.yml, both this and its sibling run as + # the workflow "Release", and one would cancel the other. + group: ${{ github.workflow }}-ci-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + lint: + name: Lint + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + # cpplint derives the header guards from the path below the parent of the checkout, which + # GitHub names after the repository. + - uses: actions/checkout@v7 + + - uses: ./.github/actions/uv-sync + + - name: Lint + run: make lint + + tests: + name: Host tests + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + + - name: Install the toolchain + uses: ./.github/actions/apt-install + with: + packages: cmake ninja-build libgtest-dev + # And the project's own, as its dev container has them. + file: .devcontainer/apt-packages.txt + + # gcovr, for the coverage. + - uses: ./.github/actions/uv-sync + + - name: Tests + run: make tests + + - name: Tests under ASan and UBSan + run: make sanitize + + - name: Coverage + run: make coverage + + clang: + name: Host tests by clang + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + + - name: Install the toolchain + uses: ./.github/actions/apt-install + with: + packages: cmake ninja-build libgtest-dev clang + # And the project's own, as its dev container has them. + file: .devcontainer/apt-packages.txt + + - name: Tests + run: make clang + + examples: + name: Examples + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + + - name: Install simavr + uses: ./.github/actions/apt-install + with: + packages: simavr + + - uses: ./.github/actions/arduino-setup + + - name: SelfCheck in simavr + run: make self-check + + - name: Compile + run: make examples + + - name: The sizes in the README + run: make sizes + + arduino-lint: + name: arduino-lint + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + + # "submit" while the library is not in the Library Manager; once it is, "update" adds the + # checks for a new release. + - uses: arduino/arduino-lint-action@v3 + with: + project-type: library + library-manager: submit diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..6b61d25 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,62 @@ +# The reference from the Doxygen blocks, on GitHub Pages. Every pull request builds it and fails +# on a warning, so that a block Doxygen cannot read, or an entity of the API without one, is +# found before the merge; only main publishes it. Which warnings count is in tools/docs.sh, +# what Doxygen reads in the Doxyfile, how a block is written in docs/Documentation.md. +name: docs + +on: + pull_request: + push: + branches: [main, master] + +# A second push to the same branch makes the first answer worthless. On main, a deployment that +# runs is left to finish, rather than cut off halfway, and the next one waits for it. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/master' }} + +defaults: + run: + shell: bash + +jobs: + build: + name: Doxygen + runs-on: ubuntu-26.04 + timeout-minutes: 10 + # Read the repository; the deploy job below asks for what publishing needs. + permissions: + contents: read + steps: + - uses: actions/checkout@v7 + + # From apt, as in the Dockerfile, so that CI and the container warn alike. + - name: Install Doxygen + uses: ./.github/actions/apt-install + with: + packages: doxygen + + - name: Build and check + run: make docs + + - name: Hand the pages over + if: github.event_name == 'push' + uses: actions/upload-pages-artifact@v5 + with: + path: build/docs/html + + deploy: + name: GitHub Pages + if: github.event_name == 'push' + needs: build + runs-on: ubuntu-26.04 + timeout-minutes: 10 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..0e6a835 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,71 @@ +# What turns a tag into a release. Triggered by the tag, as the tag is +# the decision: pushing v1.2.0 is releasing 1.2.0. +# +# The checks are not repeated here: this workflow calls ci.yml and static-analysis.yml and +# publishes only once every job of both has passed, so a tag whose checks are red produces no +# release at all. The Arduino Library Manager takes a library from its tags itself; the release +# page is for a person, with the library as a .zip that the Arduino IDE installs with "Add .ZIP +# Library", and the notes GitHub writes from the merged pull requests. +name: Release + +on: + push: + tags: ['v*'] + +# Only the publishing job writes: creating a release and attaching a file to it. Declared at the +# top, as a called workflow cannot be granted more than its caller has. +permissions: + contents: write + +jobs: + checks: + name: Checks + uses: ./.github/workflows/ci.yml + + analysis: + name: Analysis + uses: ./.github/workflows/static-analysis.yml + + # library.properties says the version, and the Arduino IDE shows it; a tag v0.2.0 on a commit + # whose library.properties still says 0.1.0 would publish a release that names itself otherwise. + # Asked here, before anything is published. + version: + name: The tag matches library.properties + runs-on: ubuntu-26.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + + - name: Compare + run: | + tag="${GITHUB_REF_NAME#v}" + library=$(sed -n 's/^version=//p' library.properties) + if [ "$tag" != "$library" ]; then + echo "::error::The tag says $tag, library.properties says ${library:-nothing}" + exit 1 + fi + echo "Version $library" + + publish: + name: Publish the release + needs: [checks, analysis, version] + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + + # The library as the Arduino IDE installs it, in a folder named after it: what git tracks, + # without the dev container, CI and the tools, which a sketch does not need. + - name: Pack the library + run: | + name=$(sed -n 's/^name=//p' library.properties) + git archive --format=zip --prefix="${name}/" \ + --output="${name}-${GITHUB_REF_NAME}.zip" HEAD \ + -- library.properties LICENSE README.md src examples + + - name: Publish + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --generate-notes \ + ./*.zip diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml new file mode 100644 index 0000000..5c88133 --- /dev/null +++ b/.github/workflows/static-analysis.yml @@ -0,0 +1,95 @@ +# What a pull request is read with, next to what it is built with in ci.yml: a workflow of its +# own, as a badge reports a workflow and not a job, so that the README says separately that the +# builds pass and that the analysers are quiet. Each step is a target of the Makefile. +# +# clang-tidy the library and the examples with the board's flags, once per variant whose +# defines differ, and the tests on the host; which checks, and why the rest are +# off, is in .clang-tidy; with the checks of our own, built against LLVM's headers +# cppcheck the library, parsed by cppcheck itself, which reaches what clang does not +# headers every header of src/ compiled on its own, for the host and for the board +# +# Every job carries a timeout-minutes well above what it takes, for one that has stopped making +# progress. This file comes from the template. +name: static-analysis + +on: + pull_request: + push: + branches: [main, master] + workflow_call: + +# Read the repository and nothing else. +permissions: + contents: read + +concurrency: + # The file's own name in the group: called by release.yml, both this and its sibling run as + # the workflow "Release", and one would cancel the other. + group: ${{ github.workflow }}-analysis-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + clang-tidy: + name: clang-tidy + runs-on: ubuntu-26.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + + # CMake and GoogleTest for the database of the tests, jq for the board's. + - name: Install the toolchain + uses: ./.github/actions/apt-install + with: + packages: cmake ninja-build libgtest-dev jq + # And the project's own, as its dev container has them. + file: .devcontainer/apt-packages.txt + + - uses: ./.github/actions/uv-sync + + # The headers the module of the checks of our own is compiled against. + - uses: ./.github/actions/llvm-headers + + # The board's flags come from arduino-cli's compilation database. + - uses: ./.github/actions/arduino-setup + + - name: Analyse + run: make tidy + + cppcheck: + name: cppcheck + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + + - name: Install cppcheck + uses: ./.github/actions/apt-install + with: + packages: cppcheck + + - name: Analyse + run: make cppcheck + + headers: + name: Headers on their own + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + + - name: Install the toolchain + uses: ./.github/actions/apt-install + with: + packages: cmake ninja-build libgtest-dev jq + # And the project's own, as its dev container has them. + file: .devcontainer/apt-packages.txt + + # avr-g++ and the core, which the board's database names. + - uses: ./.github/actions/arduino-setup + + - name: Compile each header alone + run: make headers diff --git a/.gitignore b/.gitignore index 7b7e2bb..955bf4c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,9 @@ -/AtmelStudio/TimerTwo/TimerTwo/Debug -/AtmelStudio/TimerTwo/ArduinoCore/Debug +build/ +# The Python tools' environment, which uv makes from uv.lock. +.venv/ +# A dev container variant of the site, such as one on an internal base image, see +# .devcontainer/README.md. +/.devcontainer/vector/ +# The lock file VS Code writes beside a devcontainer.json; the shared feature is local and +# has no version to pin. +/.devcontainer/*/devcontainer-lock.json diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 0000000..ded272e --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1,8 @@ +# The checks shellcheck makes beyond its defaults, in tools/lint.sh and in an editor alike. This +# file comes from the template and is brought up to date with `copier update`. +# +# check-extra-masked-returns (SC2312): the status of a command whose output another one reads, +# as in `mapfile -t files < <(git ls-files ...)` or `diff "$(expected_of ...)" ...`, is lost, and +# set -e never sees it fail. A git or a find that failed left an empty list, and the check over +# it passed. Such output goes into a variable first, whose assignment fails with the command. +enable=check-extra-masked-returns diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2da9bc4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,118 @@ +# TimerTwo: for a coding agent + +Periodic interrupt, PWM and time readout on Timer2 of the ATmega328P. An embedded C++ library for targets from an 8-bit microcontroller to the host: +C++11 as the least standard, without the standard library. This project builds and checks it on +the host by GCC and clang, and on the AVR through arduino-cli and simavr. + +## Before writing code, read + +- [docs/CodingStyle.md](docs/CodingStyle.md): how the code is written. Every rule has an id; + name it where you deviate, in the `NOLINT` or in the comment that gives the reason. +- [docs/Documentation.md](docs/Documentation.md): how a comment and a Doxygen block are written. + Everything a sketch can use is documented. +- [docs/Testing.md](docs/Testing.md): which kind of test proves what, and how a test is named + and written. +- [docs/targets/avr.md](docs/targets/avr.md): what holds on the AVR only, beyond the rules + that hold for every target. + +They hold without exception. Where they and your habits differ, they win. + +## How to work + +**Quality before speed.** A change that is right and small is worth more than one that is +large and quick. Read the code you change and what calls it before you write; check what you +assume, as an API, a signature or a size, instead of guessing; run every check, not the first; +and where a decision is not yours to make, or the rules leave it open, ask rather than pick. + +1. **A test first.** Write the test of the behaviour, see it fail, then write the code. +2. **Small steps.** One concern per change; what you find on the way is a note in your answer, + not a change of its own. + A commit holds one concern, and its message says what changed and why. + A pull request's description says what changes for a user of the library, why, and how it + was checked; not the code: no function names, no walk through the files, no snippets. The + diff shows those. +3. **Only what was asked.** No refactoring, renaming or reformatting of code you were not asked + to touch. + +After every step: + +```bash +make lint # clang-format, cpplint, shellcheck, actionlint, ruff: seconds +make tidy # clang-tidy, for the host and the board +make tests # GoogleTest on the host +``` + +`make fmt` formats the code and the Doxygen blocks in place. + +## Never + +- **Nothing written anew that exists already**: look in the project first, then the standard + library where every target has it, then the library like it that the project uses, as the + ETL or Utl (M-3). Only what none has is written, once and for reuse, in a module folder of its + own with its test; say in your answer what you wrote and why nothing existing would do. +- **No heap, no exceptions, no RTTI**: no `new`, `malloc`, `throw`, `try`, `dynamic_cast`, + `typeid` (M-1, M-2). +- **No blocking and no `float` without its reason**: no busy wait in the library, no `double` + at all (H-1, H-7). An interrupt's shared data is read atomically (H-6). +- **No long expressions**: split a computation or a condition into named steps (T-18). +- **No invented API.** A function of the Arduino core or of a library is used only if you have + seen its declaration; `test/mock/` shows what the tests can call. +- **No code for later**: no unused parameter, function, overload or option "in case", no + `TODO`, no commented-out code. +- **No comment that repeats the code.** A comment says why, Documentation.md says how. +- **No test weakened to pass**: a failing test is fixed in the code, unless the test is wrong, + and then you say why in your answer. +- **No check silenced to pass**: no `NOLINT`, `#pragma` or change of `.clang-tidy`, + `.clang-format`, `CPPLINT.cfg`, the `Makefile` or the CMake files to make a finding go away. + Where a finding is wrong, suppress it for the one line, naming the check, the rule of + CodingStyle.md and the reason (S-1), and say so in your answer. +- **No change to the template's files** (below) unless asked. + +## Done + +A change is done when all of these hold, not when it compiles: + +- `make check` passes: it is what CI runs, all of it. +- Every line and branch the change adds is reached by a test: `make coverage` lists the lines + missed per file. +- What a sketch can use is documented (Documentation.md), and `make docs` passes. +- The README's table of flash and RAM, if it has one, is what the build measures: after a change + that moves them, `make examples` and `make sizes FIX=1`. +- What a user of the library notices is in `CHANGELOG.md`, if the project keeps one. +- Your answer names every rule you deviated from, and why. + +## Where things are + +| What | Where | +|---|---| +| The library | `src/`, the header a sketch includes is `src/TimerTwo.h` | +| Tests | `test/`, GoogleTest against a mock of the Arduino core in `test/mock/` | +| Examples | `examples/`; `SelfCheck` runs on the board in simavr | +| The project's settings | `tools/project.sh` (board, variants, hooks), `tools/project.mk` (own targets) | +| The scripts behind `make` | `tools/`; `tools/README.md` says what each is, and when a script is shell or Python | + +`.clang-tidy`, `.clang-format`, `CPPLINT.cfg`, the `Makefile`, `tools/` and `.github/` come from +the template and are updated by `copier update`. Change them only when asked; a project's own +exception goes at the end of a list, with its reason. + +## The project's own notes + + + +TimerTwo drives Timer/Counter2 of the ATmega328P in mode 5, phase correct PWM: OCR2A is the top +and sets the period with the prescaler, the overflow at the bottom calls the sketch's callback, +and OC2B on pin 3 gives the PWM. `OIL.md` is the open issue list: what is planned, in which order, +and why. A pull request that works on an item sets its status and links itself in the same PR. + +- **The code is of 2023, until version 2.0.0** (OIL 3): one singleton class `TimerTwo` and + `Timer2`, `StdReturnType` from `src/StandardTypes.h`, constants as `#define`. `src/.clang-tidy` + and `examples/.clang-tidy` turn off the groups it fails until then; new code, the tests and the + mock, keeps every check. +- **The tests need a process each**: `init()` takes the singleton once, and no test can begin + from a new one. ctest runs each test on its own, as `gtest_discover_tests()` adds them; the + fixture fails in `SetUp()` otherwise. +- **The mock of the registers**, `test/mock/avr/io.h`: TCNT2 steps on each read while a clock is + selected, up to OCR2A and down again, so that `start()` and `read()`, which wait for the counter + to move, end on the host. +- **Known bugs, for OIL 2**, each to be shown by a failing test before it is fixed; see OIL.md. diff --git a/AtmelStudio/.vs/TimerTwo/v14/.atsuo b/AtmelStudio/.vs/TimerTwo/v14/.atsuo deleted file mode 100644 index 9ccc00e..0000000 Binary files a/AtmelStudio/.vs/TimerTwo/v14/.atsuo and /dev/null differ diff --git a/AtmelStudio/README.md b/AtmelStudio/README.md deleted file mode 100644 index 0333943..0000000 --- a/AtmelStudio/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Atmel Studio project - -Here you find a complete working atmel studio project. With the simulator you can debug the TimerTwo library. - diff --git a/AtmelStudio/TimerTwo.atsln b/AtmelStudio/TimerTwo.atsln deleted file mode 100644 index 8eb3960..0000000 --- a/AtmelStudio/TimerTwo.atsln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Atmel Studio Solution File, Format Version 11.00 -VisualStudioVersion = 14.0.23107.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{E66E83B9-2572-4076-B26E-6BE79FF3018A}") = "TimerTwo", "TimerTwo\TimerTwo\TimerTwo.cppproj", "{DCE6C7E3-EE26-4D79-826B-08594B9AD897}" -EndProject -Project("{E66E83B9-2572-4076-B26E-6BE79FF3018A}") = "ArduinoCore", "TimerTwo\ArduinoCore\ArduinoCore.cppproj", "{B8B61B52-8E26-4022-A4C5-68291647B272}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|AVR = Debug|AVR - Release|AVR = Release|AVR - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DCE6C7E3-EE26-4D79-826B-08594B9AD897}.Debug|AVR.ActiveCfg = Debug|AVR - {DCE6C7E3-EE26-4D79-826B-08594B9AD897}.Debug|AVR.Build.0 = Debug|AVR - {DCE6C7E3-EE26-4D79-826B-08594B9AD897}.Release|AVR.ActiveCfg = Release|AVR - {DCE6C7E3-EE26-4D79-826B-08594B9AD897}.Release|AVR.Build.0 = Release|AVR - {B8B61B52-8E26-4022-A4C5-68291647B272}.Debug|AVR.ActiveCfg = Debug|AVR - {B8B61B52-8E26-4022-A4C5-68291647B272}.Debug|AVR.Build.0 = Debug|AVR - {B8B61B52-8E26-4022-A4C5-68291647B272}.Release|AVR.ActiveCfg = Release|AVR - {B8B61B52-8E26-4022-A4C5-68291647B272}.Release|AVR.Build.0 = Release|AVR - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/AtmelStudio/TimerTwo/.vs/TimerTwo/v14/.atsuo b/AtmelStudio/TimerTwo/.vs/TimerTwo/v14/.atsuo deleted file mode 100644 index a4041f5..0000000 Binary files a/AtmelStudio/TimerTwo/.vs/TimerTwo/v14/.atsuo and /dev/null differ diff --git a/AtmelStudio/TimerTwo/ArduinoCore/ArduinoCore.componentinfo.xml b/AtmelStudio/TimerTwo/ArduinoCore/ArduinoCore.componentinfo.xml deleted file mode 100644 index a44f5cf..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/ArduinoCore.componentinfo.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - Device - Startup - - - Atmel - 1.3.0 - C:/Program Files (x86)\Atmel\Studio\7.0\Packs - - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\include - - include - C - - - include - - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\include\avr\iom328p.h - - header - C - UMk4QUzkkuShabuoYtNl/Q== - - include/avr/iom328p.h - - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\templates\library.c - template - source - C Lib - 2/NZD/YM3hWVTzqme3bDXw== - - templates/library.c - Main file (.c) - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\templates\library.cpp - template - source - C Lib - rp0h0QZxgsOWeJw3b8sAIw== - - templates/library.cpp - Main file (.cpp) - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\gcc\dev\atmega328p - - libraryPrefix - GCC - - - gcc/dev/atmega328p - - - - - ATmega_DFP - C:/Program Files (x86)/Atmel/Studio/7.0/Packs/atmel/ATmega_DFP/1.3.300/Atmel.ATmega_DFP.pdsc - 1.3.300 - true - ATmega328P - - - - Resolved - Fixed - true - - - \ No newline at end of file diff --git a/AtmelStudio/TimerTwo/ArduinoCore/ArduinoCore.cppproj b/AtmelStudio/TimerTwo/ArduinoCore/ArduinoCore.cppproj deleted file mode 100644 index dce44cd..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/ArduinoCore.cppproj +++ /dev/null @@ -1,356 +0,0 @@ - - - - 2.0 - 7.0 - com.Atmel.AVRGCC8.CPP - b8b61b52-8e26-4022-a4c5-68291647b272 - atmega328p - none - StaticLibrary - CPP - lib$(MSBuildProjectName) - .a - $(MSBuildProjectDirectory)\$(Configuration) - ArduinoCore - C:\Program Files (x86)\Arduino - Core - Native - ArduinoCore - ArduinoCore - true - false - true - true - 0x20000000 - - true - exception_table - 2 - 0 - 0 - - - - - - - - - - - - - - - - - - -mmcu=atmega328p -B "%24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\gcc\dev\atmega328p" - True - True - True - True - False - True - True - - - NDEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - ..\include\core - ..\include\variants\standard - - - Optimize for size (-Os) - -fno-threadsafe-statics - True - True - Default (-g2) - True - -std=gnu99 -std=gnu11 - True - True - - - NDEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - ..\include\core - ..\include\variants\standard - - - Optimize for size (-Os) - -fno-threadsafe-statics - True - True - Default (-g2) - True - -std=gnu++11 - - - libm - - - -Os - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - - - Default (-Wa,-g) - - - - - - - -mmcu=atmega328p -B "%24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\gcc\dev\atmega328p" - True - True - True - True - False - True - True - - - DEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - ..\include\core - ..\include\variants\standard - - - Optimize for size (-Os) - -fno-threadsafe-statics - True - True - Default (-g2) - True - True - -std=gnu99 -std=gnu11 - True - True - - - DEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - ..\include\core - ..\include\variants\standard - - - Optimize for size (-Os) - -fno-threadsafe-statics - True - True - Default (-g2) - True - True - True - -std=gnu++11 - - - libm - - - -Os - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - - - Default (-Wa,-g) - - - - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - compile - - - - - - - - - - - - - \ No newline at end of file diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Arduino.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Arduino.h deleted file mode 100644 index 91eeb16..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Arduino.h +++ /dev/null @@ -1,260 +0,0 @@ -/* - Arduino.h - Main include file for the Arduino SDK - Copyright (c) 2005-2013 Arduino Team. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef Arduino_h -#define Arduino_h - -#include -#include -#include -#include - -#include -#include -#include - -#include "binary.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -void yield(void); - -#define HIGH 0x1 -#define LOW 0x0 - -#define INPUT 0x0 -#define OUTPUT 0x1 -#define INPUT_PULLUP 0x2 - -#define PI 3.1415926535897932384626433832795 -#define HALF_PI 1.5707963267948966192313216916398 -#define TWO_PI 6.283185307179586476925286766559 -#define DEG_TO_RAD 0.017453292519943295769236907684886 -#define RAD_TO_DEG 57.295779513082320876798154814105 -#define EULER 2.718281828459045235360287471352 - -#define SERIAL 0x0 -#define DISPLAY 0x1 - -#define LSBFIRST 0 -#define MSBFIRST 1 - -#define CHANGE 1 -#define FALLING 2 -#define RISING 3 - -#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) - #define DEFAULT 0 - #define EXTERNAL 1 - #define INTERNAL1V1 2 - #define INTERNAL INTERNAL1V1 -#elif defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) - #define DEFAULT 0 - #define EXTERNAL 4 - #define INTERNAL1V1 8 - #define INTERNAL INTERNAL1V1 - #define INTERNAL2V56 9 - #define INTERNAL2V56_EXTCAP 13 -#else -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) -#define INTERNAL1V1 2 -#define INTERNAL2V56 3 -#else -#define INTERNAL 3 -#endif -#define DEFAULT 1 -#define EXTERNAL 0 -#endif - -// undefine stdlib's abs if encountered -#ifdef abs -#undef abs -#endif - -#define min(a,b) ((a)<(b)?(a):(b)) -#define max(a,b) ((a)>(b)?(a):(b)) -#define abs(x) ((x)>0?(x):-(x)) -#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt))) -#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) -#define radians(deg) ((deg)*DEG_TO_RAD) -#define degrees(rad) ((rad)*RAD_TO_DEG) -#define sq(x) ((x)*(x)) - -#define interrupts() sei() -#define noInterrupts() cli() - -#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L ) -#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() ) -#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() ) - -#define lowByte(w) ((uint8_t) ((w) & 0xff)) -#define highByte(w) ((uint8_t) ((w) >> 8)) - -#define bitRead(value, bit) (((value) >> (bit)) & 0x01) -#define bitSet(value, bit) ((value) |= (1UL << (bit))) -#define bitClear(value, bit) ((value) &= ~(1UL << (bit))) -#define bitToggle(value, bit) ((value) ^= (1UL << (bit))) -#define bitWrite(value, bit, bitvalue) ((bitvalue) ? bitSet(value, bit) : bitClear(value, bit)) - -// avr-libc defines _NOP() since 1.6.2 -#ifndef _NOP -#define _NOP() do { __asm__ volatile ("nop"); } while (0) -#endif - -typedef unsigned int word; - -#define bit(b) (1UL << (b)) - -typedef bool boolean; -typedef uint8_t byte; - -void init(void); -void initVariant(void); - -int atexit(void (*func)()) __attribute__((weak)); - -void pinMode(uint8_t pin, uint8_t mode); -void digitalWrite(uint8_t pin, uint8_t val); -int digitalRead(uint8_t pin); -int analogRead(uint8_t pin); -void analogReference(uint8_t mode); -void analogWrite(uint8_t pin, int val); - -unsigned long millis(void); -unsigned long micros(void); -void delay(unsigned long ms); -void delayMicroseconds(unsigned int us); -unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout); -unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout); - -void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val); -uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder); - -void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode); -void detachInterrupt(uint8_t interruptNum); - -void setup(void); -void loop(void); - -// Get the bit location within the hardware port of the given virtual pin. -// This comes from the pins_*.c file for the active board configuration. - -#define analogInPinToBit(P) (P) - -// On the ATmega1280, the addresses of some of the port registers are -// greater than 255, so we can't store them in uint8_t's. -extern const uint16_t PROGMEM port_to_mode_PGM[]; -extern const uint16_t PROGMEM port_to_input_PGM[]; -extern const uint16_t PROGMEM port_to_output_PGM[]; - -extern const uint8_t PROGMEM digital_pin_to_port_PGM[]; -// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[]; -extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[]; -extern const uint8_t PROGMEM digital_pin_to_timer_PGM[]; - -// Get the bit location within the hardware port of the given virtual pin. -// This comes from the pins_*.c file for the active board configuration. -// -// These perform slightly better as macros compared to inline functions -// -#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) ) -#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) ) -#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) ) -#define analogInPinToBit(P) (P) -#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) ) -#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) ) -#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) ) - -#define NOT_A_PIN 0 -#define NOT_A_PORT 0 - -#define NOT_AN_INTERRUPT -1 - -#ifdef ARDUINO_MAIN -#define PA 1 -#define PB 2 -#define PC 3 -#define PD 4 -#define PE 5 -#define PF 6 -#define PG 7 -#define PH 8 -#define PJ 10 -#define PK 11 -#define PL 12 -#endif - -#define NOT_ON_TIMER 0 -#define TIMER0A 1 -#define TIMER0B 2 -#define TIMER1A 3 -#define TIMER1B 4 -#define TIMER1C 5 -#define TIMER2 6 -#define TIMER2A 7 -#define TIMER2B 8 - -#define TIMER3A 9 -#define TIMER3B 10 -#define TIMER3C 11 -#define TIMER4A 12 -#define TIMER4B 13 -#define TIMER4C 14 -#define TIMER4D 15 -#define TIMER5A 16 -#define TIMER5B 17 -#define TIMER5C 18 - -#ifdef __cplusplus -} // extern "C" -#endif - -#ifdef __cplusplus -#include "WCharacter.h" -#include "WString.h" -#include "HardwareSerial.h" -#include "USBAPI.h" -#if defined(HAVE_HWSERIAL0) && defined(HAVE_CDCSERIAL) -#error "Targets with both UART0 and CDC serial not supported" -#endif - -uint16_t makeWord(uint16_t w); -uint16_t makeWord(byte h, byte l); - -#define word(...) makeWord(__VA_ARGS__) - -unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L); -unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L); - -void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0); -void noTone(uint8_t _pin); - -// WMath prototypes -long random(long); -long random(long, long); -void randomSeed(unsigned long); -long map(long, long, long, long, long); - -#endif - -#include "pins_arduino.h" - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Client.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Client.h deleted file mode 100644 index b8e5d93..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Client.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - Client.h - Base class that provides Client - Copyright (c) 2011 Adrian McEwen. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef client_h -#define client_h -#include "Print.h" -#include "Stream.h" -#include "IPAddress.h" - -class Client : public Stream { - -public: - virtual int connect(IPAddress ip, uint16_t port) =0; - virtual int connect(const char *host, uint16_t port) =0; - virtual size_t write(uint8_t) =0; - virtual size_t write(const uint8_t *buf, size_t size) =0; - virtual int available() = 0; - virtual int read() = 0; - virtual int read(uint8_t *buf, size_t size) = 0; - virtual int peek() = 0; - virtual void flush() = 0; - virtual void stop() = 0; - virtual uint8_t connected() = 0; - virtual operator bool() = 0; -protected: - uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); }; -}; - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/HardwareSerial.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/HardwareSerial.h deleted file mode 100644 index 17000c2..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/HardwareSerial.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - HardwareSerial.h - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus - Modified 3 December 2013 by Matthijs Kooijman -*/ - -#ifndef HardwareSerial_h -#define HardwareSerial_h - -#include - -#include "Stream.h" - -// Define constants and variables for buffering incoming serial data. We're -// using a ring buffer (I think), in which head is the index of the location -// to which to write the next incoming character and tail is the index of the -// location from which to read. -// NOTE: a "power of 2" buffer size is reccomended to dramatically -// optimize all the modulo operations for ring buffers. -// WARNING: When buffer sizes are increased to > 256, the buffer index -// variables are automatically increased in size, but the extra -// atomicity guards needed for that are not implemented. This will -// often work, but occasionally a race condition can occur that makes -// Serial behave erratically. See https://github.com/arduino/Arduino/issues/2405 -#if !defined(SERIAL_TX_BUFFER_SIZE) -#if ((RAMEND - RAMSTART) < 1023) -#define SERIAL_TX_BUFFER_SIZE 16 -#else -#define SERIAL_TX_BUFFER_SIZE 64 -#endif -#endif -#if !defined(SERIAL_RX_BUFFER_SIZE) -#if ((RAMEND - RAMSTART) < 1023) -#define SERIAL_RX_BUFFER_SIZE 16 -#else -#define SERIAL_RX_BUFFER_SIZE 64 -#endif -#endif -#if (SERIAL_TX_BUFFER_SIZE>256) -typedef uint16_t tx_buffer_index_t; -#else -typedef uint8_t tx_buffer_index_t; -#endif -#if (SERIAL_RX_BUFFER_SIZE>256) -typedef uint16_t rx_buffer_index_t; -#else -typedef uint8_t rx_buffer_index_t; -#endif - -// Define config for Serial.begin(baud, config); -#define SERIAL_5N1 0x00 -#define SERIAL_6N1 0x02 -#define SERIAL_7N1 0x04 -#define SERIAL_8N1 0x06 -#define SERIAL_5N2 0x08 -#define SERIAL_6N2 0x0A -#define SERIAL_7N2 0x0C -#define SERIAL_8N2 0x0E -#define SERIAL_5E1 0x20 -#define SERIAL_6E1 0x22 -#define SERIAL_7E1 0x24 -#define SERIAL_8E1 0x26 -#define SERIAL_5E2 0x28 -#define SERIAL_6E2 0x2A -#define SERIAL_7E2 0x2C -#define SERIAL_8E2 0x2E -#define SERIAL_5O1 0x30 -#define SERIAL_6O1 0x32 -#define SERIAL_7O1 0x34 -#define SERIAL_8O1 0x36 -#define SERIAL_5O2 0x38 -#define SERIAL_6O2 0x3A -#define SERIAL_7O2 0x3C -#define SERIAL_8O2 0x3E - -class HardwareSerial : public Stream -{ - protected: - volatile uint8_t * const _ubrrh; - volatile uint8_t * const _ubrrl; - volatile uint8_t * const _ucsra; - volatile uint8_t * const _ucsrb; - volatile uint8_t * const _ucsrc; - volatile uint8_t * const _udr; - // Has any byte been written to the UART since begin() - bool _written; - - volatile rx_buffer_index_t _rx_buffer_head; - volatile rx_buffer_index_t _rx_buffer_tail; - volatile tx_buffer_index_t _tx_buffer_head; - volatile tx_buffer_index_t _tx_buffer_tail; - - // Don't put any members after these buffers, since only the first - // 32 bytes of this struct can be accessed quickly using the ldd - // instruction. - unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE]; - unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE]; - - public: - inline HardwareSerial( - volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, - volatile uint8_t *ucsra, volatile uint8_t *ucsrb, - volatile uint8_t *ucsrc, volatile uint8_t *udr); - void begin(unsigned long baud) { begin(baud, SERIAL_8N1); } - void begin(unsigned long, uint8_t); - void end(); - virtual int available(void); - virtual int peek(void); - virtual int read(void); - virtual int availableForWrite(void); - virtual void flush(void); - virtual size_t write(uint8_t); - inline size_t write(unsigned long n) { return write((uint8_t)n); } - inline size_t write(long n) { return write((uint8_t)n); } - inline size_t write(unsigned int n) { return write((uint8_t)n); } - inline size_t write(int n) { return write((uint8_t)n); } - using Print::write; // pull in write(str) and write(buf, size) from Print - operator bool() { return true; } - - // Interrupt handlers - Not intended to be called externally - inline void _rx_complete_irq(void); - void _tx_udr_empty_irq(void); -}; - -#if defined(UBRRH) || defined(UBRR0H) - extern HardwareSerial Serial; - #define HAVE_HWSERIAL0 -#endif -#if defined(UBRR1H) - extern HardwareSerial Serial1; - #define HAVE_HWSERIAL1 -#endif -#if defined(UBRR2H) - extern HardwareSerial Serial2; - #define HAVE_HWSERIAL2 -#endif -#if defined(UBRR3H) - extern HardwareSerial Serial3; - #define HAVE_HWSERIAL3 -#endif - -extern void serialEventRun(void) __attribute__((weak)); - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/HardwareSerial_private.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/HardwareSerial_private.h deleted file mode 100644 index 761a5e5..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/HardwareSerial_private.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - HardwareSerial_private.h - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus -*/ - -#include "wiring_private.h" - -// this next line disables the entire HardwareSerial.cpp, -// this is so I can support Attiny series and any other chip without a uart -#if defined(HAVE_HWSERIAL0) || defined(HAVE_HWSERIAL1) || defined(HAVE_HWSERIAL2) || defined(HAVE_HWSERIAL3) - -// Ensure that the various bit positions we use are available with a 0 -// postfix, so we can always use the values for UART0 for all UARTs. The -// alternative, passing the various values for each UART to the -// HardwareSerial constructor also works, but makes the code bigger and -// slower. -#if !defined(TXC0) -#if defined(TXC) -// Some chips like ATmega8 don't have UPE, only PE. The other bits are -// named as expected. -#if !defined(UPE) && defined(PE) -#define UPE PE -#endif -// On ATmega8, the uart and its bits are not numbered, so there is no TXC0 etc. -#define TXC0 TXC -#define RXEN0 RXEN -#define TXEN0 TXEN -#define RXCIE0 RXCIE -#define UDRIE0 UDRIE -#define U2X0 U2X -#define UPE0 UPE -#define UDRE0 UDRE -#elif defined(TXC1) -// Some devices have uart1 but no uart0 -#define TXC0 TXC1 -#define RXEN0 RXEN1 -#define TXEN0 TXEN1 -#define RXCIE0 RXCIE1 -#define UDRIE0 UDRIE1 -#define U2X0 U2X1 -#define UPE0 UPE1 -#define UDRE0 UDRE1 -#else -#error No UART found in HardwareSerial.cpp -#endif -#endif // !defined TXC0 - -// Check at compiletime that it is really ok to use the bit positions of -// UART0 for the other UARTs as well, in case these values ever get -// changed for future hardware. -#if defined(TXC1) && (TXC1 != TXC0 || RXEN1 != RXEN0 || RXCIE1 != RXCIE0 || \ - UDRIE1 != UDRIE0 || U2X1 != U2X0 || UPE1 != UPE0 || \ - UDRE1 != UDRE0) -#error "Not all bit positions for UART1 are the same as for UART0" -#endif -#if defined(TXC2) && (TXC2 != TXC0 || RXEN2 != RXEN0 || RXCIE2 != RXCIE0 || \ - UDRIE2 != UDRIE0 || U2X2 != U2X0 || UPE2 != UPE0 || \ - UDRE2 != UDRE0) -#error "Not all bit positions for UART2 are the same as for UART0" -#endif -#if defined(TXC3) && (TXC3 != TXC0 || RXEN3 != RXEN0 || RXCIE3 != RXCIE0 || \ - UDRIE3 != UDRIE0 || U3X3 != U3X0 || UPE3 != UPE0 || \ - UDRE3 != UDRE0) -#error "Not all bit positions for UART3 are the same as for UART0" -#endif - -// Constructors //////////////////////////////////////////////////////////////// - -HardwareSerial::HardwareSerial( - volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, - volatile uint8_t *ucsra, volatile uint8_t *ucsrb, - volatile uint8_t *ucsrc, volatile uint8_t *udr) : - _ubrrh(ubrrh), _ubrrl(ubrrl), - _ucsra(ucsra), _ucsrb(ucsrb), _ucsrc(ucsrc), - _udr(udr), - _rx_buffer_head(0), _rx_buffer_tail(0), - _tx_buffer_head(0), _tx_buffer_tail(0) -{ -} - -// Actual interrupt handlers ////////////////////////////////////////////////////////////// - -void HardwareSerial::_rx_complete_irq(void) -{ - if (bit_is_clear(*_ucsra, UPE0)) { - // No Parity error, read byte and store it in the buffer if there is - // room - unsigned char c = *_udr; - rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE; - - // if we should be storing the received character into the location - // just before the tail (meaning that the head would advance to the - // current location of the tail), we're about to overflow the buffer - // and so we don't write the character or advance the head. - if (i != _rx_buffer_tail) { - _rx_buffer[_rx_buffer_head] = c; - _rx_buffer_head = i; - } - } else { - // Parity error, read byte but discard it - *_udr; - }; -} - -#endif // whole file diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/IPAddress.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/IPAddress.h deleted file mode 100644 index d762f2c..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/IPAddress.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - IPAddress.h - Base class that provides IPAddress - Copyright (c) 2011 Adrian McEwen. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef IPAddress_h -#define IPAddress_h - -#include -#include "Printable.h" -#include "WString.h" - -// A class to make it easier to handle and pass around IP addresses - -class IPAddress : public Printable { -private: - union { - uint8_t bytes[4]; // IPv4 address - uint32_t dword; - } _address; - - // Access the raw byte array containing the address. Because this returns a pointer - // to the internal structure rather than a copy of the address this function should only - // be used when you know that the usage of the returned uint8_t* will be transient and not - // stored. - uint8_t* raw_address() { return _address.bytes; }; - -public: - // Constructors - IPAddress(); - IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); - IPAddress(uint32_t address); - IPAddress(const uint8_t *address); - - bool fromString(const char *address); - bool fromString(const String &address) { return fromString(address.c_str()); } - - // Overloaded cast operator to allow IPAddress objects to be used where a pointer - // to a four-byte uint8_t array is expected - operator uint32_t() const { return _address.dword; }; - bool operator==(const IPAddress& addr) const { return _address.dword == addr._address.dword; }; - bool operator==(const uint8_t* addr) const; - - // Overloaded index operator to allow getting and setting individual octets of the address - uint8_t operator[](int index) const { return _address.bytes[index]; }; - uint8_t& operator[](int index) { return _address.bytes[index]; }; - - // Overloaded copy operators to allow initialisation of IPAddress objects from other types - IPAddress& operator=(const uint8_t *address); - IPAddress& operator=(uint32_t address); - - virtual size_t printTo(Print& p) const; - - friend class EthernetClass; - friend class UDP; - friend class Client; - friend class Server; - friend class DhcpClass; - friend class DNSClient; -}; - -const IPAddress INADDR_NONE(0,0,0,0); - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/PluggableUSB.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/PluggableUSB.h deleted file mode 100644 index 507f0df..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/PluggableUSB.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - PluggableUSB.h - Copyright (c) 2015 Arduino LLC - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef PUSB_h -#define PUSB_h - -#include "USBAPI.h" -#include - -#if defined(USBCON) - -class PluggableUSBModule { -public: - PluggableUSBModule(uint8_t numEps, uint8_t numIfs, uint8_t *epType) : - numEndpoints(numEps), numInterfaces(numIfs), endpointType(epType) - { } - -protected: - virtual bool setup(USBSetup& setup) = 0; - virtual int getInterface(uint8_t* interfaceCount) = 0; - virtual int getDescriptor(USBSetup& setup) = 0; - virtual uint8_t getShortName(char *name) { name[0] = 'A'+pluggedInterface; return 1; } - - uint8_t pluggedInterface; - uint8_t pluggedEndpoint; - - const uint8_t numEndpoints; - const uint8_t numInterfaces; - const uint8_t *endpointType; - - PluggableUSBModule *next = NULL; - - friend class PluggableUSB_; -}; - -class PluggableUSB_ { -public: - PluggableUSB_(); - bool plug(PluggableUSBModule *node); - int getInterface(uint8_t* interfaceCount); - int getDescriptor(USBSetup& setup); - bool setup(USBSetup& setup); - void getShortName(char *iSerialNum); - -private: - uint8_t lastIf; - uint8_t lastEp; - PluggableUSBModule* rootNode; -}; - -// Replacement for global singleton. -// This function prevents static-initialization-order-fiasco -// https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use -PluggableUSB_& PluggableUSB(); - -#endif - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Print.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Print.h deleted file mode 100644 index 058a2ab..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Print.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - Print.h - Base class that provides print() and println() - Copyright (c) 2008 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef Print_h -#define Print_h - -#include -#include // for size_t - -#include "WString.h" -#include "Printable.h" - -#define DEC 10 -#define HEX 16 -#define OCT 8 -#ifdef BIN // Prevent warnings if BIN is previously defined in "iotnx4.h" or similar -#undef BIN -#endif -#define BIN 2 - -class Print -{ - private: - int write_error; - size_t printNumber(unsigned long, uint8_t); - size_t printFloat(double, uint8_t); - protected: - void setWriteError(int err = 1) { write_error = err; } - public: - Print() : write_error(0) {} - - int getWriteError() { return write_error; } - void clearWriteError() { setWriteError(0); } - - virtual size_t write(uint8_t) = 0; - size_t write(const char *str) { - if (str == NULL) return 0; - return write((const uint8_t *)str, strlen(str)); - } - virtual size_t write(const uint8_t *buffer, size_t size); - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - // default to zero, meaning "a single write may block" - // should be overriden by subclasses with buffering - virtual int availableForWrite() { return 0; } - - size_t print(const __FlashStringHelper *); - size_t print(const String &); - size_t print(const char[]); - size_t print(char); - size_t print(unsigned char, int = DEC); - size_t print(int, int = DEC); - size_t print(unsigned int, int = DEC); - size_t print(long, int = DEC); - size_t print(unsigned long, int = DEC); - size_t print(double, int = 2); - size_t print(const Printable&); - - size_t println(const __FlashStringHelper *); - size_t println(const String &s); - size_t println(const char[]); - size_t println(char); - size_t println(unsigned char, int = DEC); - size_t println(int, int = DEC); - size_t println(unsigned int, int = DEC); - size_t println(long, int = DEC); - size_t println(unsigned long, int = DEC); - size_t println(double, int = 2); - size_t println(const Printable&); - size_t println(void); - - virtual void flush() { /* Empty implementation for backward compatibility */ } -}; - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Printable.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Printable.h deleted file mode 100644 index 2a1b2e9..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Printable.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - Printable.h - Interface class that allows printing of complex types - Copyright (c) 2011 Adrian McEwen. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef Printable_h -#define Printable_h - -#include - -class Print; - -/** The Printable class provides a way for new classes to allow themselves to be printed. - By deriving from Printable and implementing the printTo method, it will then be possible - for users to print out instances of this class by passing them into the usual - Print::print and Print::println methods. -*/ - -class Printable -{ - public: - virtual size_t printTo(Print& p) const = 0; -}; - -#endif - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Server.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Server.h deleted file mode 100644 index 69e3e39..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Server.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - Server.h - Base class that provides Server - Copyright (c) 2011 Adrian McEwen. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef server_h -#define server_h - -#include "Print.h" - -class Server : public Print { -public: - virtual void begin() =0; -}; - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Stream.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Stream.h deleted file mode 100644 index 8e950c7..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Stream.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - Stream.h - base class for character-based streams. - Copyright (c) 2010 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - parsing functions based on TextFinder library by Michael Margolis -*/ - -#ifndef Stream_h -#define Stream_h - -#include -#include "Print.h" - -// compatability macros for testing -/* -#define getInt() parseInt() -#define getInt(ignore) parseInt(ignore) -#define getFloat() parseFloat() -#define getFloat(ignore) parseFloat(ignore) -#define getString( pre_string, post_string, buffer, length) -readBytesBetween( pre_string, terminator, buffer, length) -*/ - -// This enumeration provides the lookahead options for parseInt(), parseFloat() -// The rules set out here are used until either the first valid character is found -// or a time out occurs due to lack of input. -enum LookaheadMode{ - SKIP_ALL, // All invalid characters are ignored. - SKIP_NONE, // Nothing is skipped, and the stream is not touched unless the first waiting character is valid. - SKIP_WHITESPACE // Only tabs, spaces, line feeds & carriage returns are skipped. -}; - -#define NO_IGNORE_CHAR '\x01' // a char not found in a valid ASCII numeric field - -class Stream : public Print -{ - protected: - unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read - unsigned long _startMillis; // used for timeout measurement - int timedRead(); // read stream with timeout - int timedPeek(); // peek stream with timeout - int peekNextDigit(LookaheadMode lookahead, bool detectDecimal); // returns the next numeric digit in the stream or -1 if timeout - - public: - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - - Stream() {_timeout=1000;} - -// parsing methods - - void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second - unsigned long getTimeout(void) { return _timeout; } - - bool find(char *target); // reads data from the stream until the target string is found - bool find(uint8_t *target) { return find ((char *)target); } - // returns true if target string is found, false if timed out (see setTimeout) - - bool find(char *target, size_t length); // reads data from the stream until the target string of given length is found - bool find(uint8_t *target, size_t length) { return find ((char *)target, length); } - // returns true if target string is found, false if timed out - - bool find(char target) { return find (&target, 1); } - - bool findUntil(char *target, char *terminator); // as find but search ends if the terminator string is found - bool findUntil(uint8_t *target, char *terminator) { return findUntil((char *)target, terminator); } - - bool findUntil(char *target, size_t targetLen, char *terminate, size_t termLen); // as above but search ends if the terminate string is found - bool findUntil(uint8_t *target, size_t targetLen, char *terminate, size_t termLen) {return findUntil((char *)target, targetLen, terminate, termLen); } - - long parseInt(LookaheadMode lookahead = SKIP_ALL, char ignore = NO_IGNORE_CHAR); - // returns the first valid (long) integer value from the current position. - // lookahead determines how parseInt looks ahead in the stream. - // See LookaheadMode enumeration at the top of the file. - // Lookahead is terminated by the first character that is not a valid part of an integer. - // Once parsing commences, 'ignore' will be skipped in the stream. - - float parseFloat(LookaheadMode lookahead = SKIP_ALL, char ignore = NO_IGNORE_CHAR); - // float version of parseInt - - size_t readBytes( char *buffer, size_t length); // read chars from stream into buffer - size_t readBytes( uint8_t *buffer, size_t length) { return readBytes((char *)buffer, length); } - // terminates if length characters have been read or timeout (see setTimeout) - // returns the number of characters placed in the buffer (0 means no valid data found) - - size_t readBytesUntil( char terminator, char *buffer, size_t length); // as readBytes with terminator character - size_t readBytesUntil( char terminator, uint8_t *buffer, size_t length) { return readBytesUntil(terminator, (char *)buffer, length); } - // terminates if length characters have been read, timeout, or if the terminator character detected - // returns the number of characters placed in the buffer (0 means no valid data found) - - // Arduino String functions to be added here - String readString(); - String readStringUntil(char terminator); - - protected: - long parseInt(char ignore) { return parseInt(SKIP_ALL, ignore); } - float parseFloat(char ignore) { return parseFloat(SKIP_ALL, ignore); } - // These overload exists for compatibility with any class that has derived - // Stream and used parseFloat/Int with a custom ignore character. To keep - // the public API simple, these overload remains protected. - - struct MultiTarget { - const char *str; // string you're searching for - size_t len; // length of string you're searching for - size_t index; // index used by the search routine. - }; - - // This allows you to search for an arbitrary number of strings. - // Returns index of the target that is found first or -1 if timeout occurs. - int findMulti(struct MultiTarget *targets, int tCount); -}; - -#undef NO_IGNORE_CHAR -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBAPI.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBAPI.h deleted file mode 100644 index 701a14f..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBAPI.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - USBAPI.h - Copyright (c) 2005-2014 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef __USBAPI__ -#define __USBAPI__ - -#include -#include -#include -#include -#include - -typedef unsigned char u8; -typedef unsigned short u16; -typedef unsigned long u32; - -#include "Arduino.h" - -// This definitions is usefull if you want to reduce the EP_SIZE to 16 -// at the moment only 64 and 16 as EP_SIZE for all EPs are supported except the control endpoint -#ifndef USB_EP_SIZE -#define USB_EP_SIZE 64 -#endif - -#if defined(USBCON) - -#include "USBDesc.h" -#include "USBCore.h" - -//================================================================================ -//================================================================================ -// USB - -#define EP_TYPE_CONTROL (0x00) -#define EP_TYPE_BULK_IN ((1<256) -#error Please lower the CDC Buffer size -#endif - -class Serial_ : public Stream -{ -private: - int peek_buffer; -public: - Serial_() { peek_buffer = -1; }; - void begin(unsigned long); - void begin(unsigned long, uint8_t); - void end(void); - - virtual int available(void); - virtual int peek(void); - virtual int read(void); - virtual int availableForWrite(void); - virtual void flush(void); - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t*, size_t); - using Print::write; // pull in write(str) and write(buf, size) from Print - operator bool(); - - volatile uint8_t _rx_buffer_head; - volatile uint8_t _rx_buffer_tail; - unsigned char _rx_buffer[SERIAL_BUFFER_SIZE]; - - // This method allows processing "SEND_BREAK" requests sent by - // the USB host. Those requests indicate that the host wants to - // send a BREAK signal and are accompanied by a single uint16_t - // value, specifying the duration of the break. The value 0 - // means to end any current break, while the value 0xffff means - // to start an indefinite break. - // readBreak() will return the value of the most recent break - // request, but will return it at most once, returning -1 when - // readBreak() is called again (until another break request is - // received, which is again returned once). - // This also mean that if two break requests are received - // without readBreak() being called in between, the value of the - // first request is lost. - // Note that the value returned is a long, so it can return - // 0-0xffff as well as -1. - int32_t readBreak(); - - // These return the settings specified by the USB host for the - // serial port. These aren't really used, but are offered here - // in case a sketch wants to act on these settings. - uint32_t baud(); - uint8_t stopbits(); - uint8_t paritytype(); - uint8_t numbits(); - bool dtr(); - bool rts(); - enum { - ONE_STOP_BIT = 0, - ONE_AND_HALF_STOP_BIT = 1, - TWO_STOP_BITS = 2, - }; - enum { - NO_PARITY = 0, - ODD_PARITY = 1, - EVEN_PARITY = 2, - MARK_PARITY = 3, - SPACE_PARITY = 4, - }; - -}; -extern Serial_ Serial; - -#define HAVE_CDCSERIAL - -//================================================================================ -//================================================================================ -// Low level API - -typedef struct -{ - uint8_t bmRequestType; - uint8_t bRequest; - uint8_t wValueL; - uint8_t wValueH; - uint16_t wIndex; - uint16_t wLength; -} USBSetup; - -//================================================================================ -//================================================================================ -// MSC 'Driver' - -int MSC_GetInterface(uint8_t* interfaceNum); -int MSC_GetDescriptor(int i); -bool MSC_Setup(USBSetup& setup); -bool MSC_Data(uint8_t rx,uint8_t tx); - -//================================================================================ -//================================================================================ -// CSC 'Driver' - -int CDC_GetInterface(uint8_t* interfaceNum); -int CDC_GetDescriptor(int i); -bool CDC_Setup(USBSetup& setup); - -//================================================================================ -//================================================================================ - -#define TRANSFER_PGM 0x80 -#define TRANSFER_RELEASE 0x40 -#define TRANSFER_ZERO 0x20 - -int USB_SendControl(uint8_t flags, const void* d, int len); -int USB_RecvControl(void* d, int len); -int USB_RecvControlLong(void* d, int len); - -uint8_t USB_Available(uint8_t ep); -uint8_t USB_SendSpace(uint8_t ep); -int USB_Send(uint8_t ep, const void* data, int len); // blocking -int USB_Recv(uint8_t ep, void* data, int len); // non-blocking -int USB_Recv(uint8_t ep); // non-blocking -void USB_Flush(uint8_t ep); - -#endif - -#endif /* if defined(USBCON) */ diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBCore.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBCore.h deleted file mode 100644 index 0c63c2b..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBCore.h +++ /dev/null @@ -1,304 +0,0 @@ - -// Copyright (c) 2010, Peter Barrett -/* -** Permission to use, copy, modify, and/or distribute this software for -** any purpose with or without fee is hereby granted, provided that the -** above copyright notice and this permission notice appear in all copies. -** -** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL -** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR -** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS -** SOFTWARE. -*/ - -#ifndef __USBCORE_H__ -#define __USBCORE_H__ - -#include "USBAPI.h" - -// Standard requests -#define GET_STATUS 0 -#define CLEAR_FEATURE 1 -#define SET_FEATURE 3 -#define SET_ADDRESS 5 -#define GET_DESCRIPTOR 6 -#define SET_DESCRIPTOR 7 -#define GET_CONFIGURATION 8 -#define SET_CONFIGURATION 9 -#define GET_INTERFACE 10 -#define SET_INTERFACE 11 - - -// bmRequestType -#define REQUEST_HOSTTODEVICE 0x00 -#define REQUEST_DEVICETOHOST 0x80 -#define REQUEST_DIRECTION 0x80 - -#define REQUEST_STANDARD 0x00 -#define REQUEST_CLASS 0x20 -#define REQUEST_VENDOR 0x40 -#define REQUEST_TYPE 0x60 - -#define REQUEST_DEVICE 0x00 -#define REQUEST_INTERFACE 0x01 -#define REQUEST_ENDPOINT 0x02 -#define REQUEST_OTHER 0x03 -#define REQUEST_RECIPIENT 0x03 - -#define REQUEST_DEVICETOHOST_CLASS_INTERFACE (REQUEST_DEVICETOHOST | REQUEST_CLASS | REQUEST_INTERFACE) -#define REQUEST_HOSTTODEVICE_CLASS_INTERFACE (REQUEST_HOSTTODEVICE | REQUEST_CLASS | REQUEST_INTERFACE) -#define REQUEST_DEVICETOHOST_STANDARD_INTERFACE (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_INTERFACE) - -// Class requests - -#define CDC_SET_LINE_CODING 0x20 -#define CDC_GET_LINE_CODING 0x21 -#define CDC_SET_CONTROL_LINE_STATE 0x22 -#define CDC_SEND_BREAK 0x23 - -#define MSC_RESET 0xFF -#define MSC_GET_MAX_LUN 0xFE - -// Descriptors - -#define USB_DEVICE_DESC_SIZE 18 -#define USB_CONFIGUARTION_DESC_SIZE 9 -#define USB_INTERFACE_DESC_SIZE 9 -#define USB_ENDPOINT_DESC_SIZE 7 - -#define USB_DEVICE_DESCRIPTOR_TYPE 1 -#define USB_CONFIGURATION_DESCRIPTOR_TYPE 2 -#define USB_STRING_DESCRIPTOR_TYPE 3 -#define USB_INTERFACE_DESCRIPTOR_TYPE 4 -#define USB_ENDPOINT_DESCRIPTOR_TYPE 5 - -// usb_20.pdf Table 9.6 Standard Feature Selectors -#define DEVICE_REMOTE_WAKEUP 1 -#define ENDPOINT_HALT 2 -#define TEST_MODE 3 - -// usb_20.pdf Figure 9-4. Information Returned by a GetStatus() Request to a Device -#define FEATURE_SELFPOWERED_ENABLED (1 << 0) -#define FEATURE_REMOTE_WAKEUP_ENABLED (1 << 1) - -#define USB_DEVICE_CLASS_COMMUNICATIONS 0x02 -#define USB_DEVICE_CLASS_HUMAN_INTERFACE 0x03 -#define USB_DEVICE_CLASS_STORAGE 0x08 -#define USB_DEVICE_CLASS_VENDOR_SPECIFIC 0xFF - -#define USB_CONFIG_POWERED_MASK 0x40 -#define USB_CONFIG_BUS_POWERED 0x80 -#define USB_CONFIG_SELF_POWERED 0xC0 -#define USB_CONFIG_REMOTE_WAKEUP 0x20 - -// bMaxPower in Configuration Descriptor -#define USB_CONFIG_POWER_MA(mA) ((mA)/2) -#ifndef USB_CONFIG_POWER - #define USB_CONFIG_POWER (500) -#endif - -// bEndpointAddress in Endpoint Descriptor -#define USB_ENDPOINT_DIRECTION_MASK 0x80 -#define USB_ENDPOINT_OUT(addr) (lowByte((addr) | 0x00)) -#define USB_ENDPOINT_IN(addr) (lowByte((addr) | 0x80)) - -#define USB_ENDPOINT_TYPE_MASK 0x03 -#define USB_ENDPOINT_TYPE_CONTROL 0x00 -#define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01 -#define USB_ENDPOINT_TYPE_BULK 0x02 -#define USB_ENDPOINT_TYPE_INTERRUPT 0x03 - -#define TOBYTES(x) ((x) & 0xFF),(((x) >> 8) & 0xFF) - -#define CDC_V1_10 0x0110 -#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02 - -#define CDC_CALL_MANAGEMENT 0x01 -#define CDC_ABSTRACT_CONTROL_MODEL 0x02 -#define CDC_HEADER 0x00 -#define CDC_ABSTRACT_CONTROL_MANAGEMENT 0x02 -#define CDC_UNION 0x06 -#define CDC_CS_INTERFACE 0x24 -#define CDC_CS_ENDPOINT 0x25 -#define CDC_DATA_INTERFACE_CLASS 0x0A - -#define MSC_SUBCLASS_SCSI 0x06 -#define MSC_PROTOCOL_BULK_ONLY 0x50 - -#ifndef USB_VERSION -#define USB_VERSION 0x200 -#endif - -// Device -typedef struct { - u8 len; // 18 - u8 dtype; // 1 USB_DEVICE_DESCRIPTOR_TYPE - u16 usbVersion; // 0x200 or 0x210 - u8 deviceClass; - u8 deviceSubClass; - u8 deviceProtocol; - u8 packetSize0; // Packet 0 - u16 idVendor; - u16 idProduct; - u16 deviceVersion; // 0x100 - u8 iManufacturer; - u8 iProduct; - u8 iSerialNumber; - u8 bNumConfigurations; -} DeviceDescriptor; - -// Config -typedef struct { - u8 len; // 9 - u8 dtype; // 2 - u16 clen; // total length - u8 numInterfaces; - u8 config; - u8 iconfig; - u8 attributes; - u8 maxPower; -} ConfigDescriptor; - -// String - -// Interface -typedef struct -{ - u8 len; // 9 - u8 dtype; // 4 - u8 number; - u8 alternate; - u8 numEndpoints; - u8 interfaceClass; - u8 interfaceSubClass; - u8 protocol; - u8 iInterface; -} InterfaceDescriptor; - -// Endpoint -typedef struct -{ - u8 len; // 7 - u8 dtype; // 5 - u8 addr; - u8 attr; - u16 packetSize; - u8 interval; -} EndpointDescriptor; - -// Interface Association Descriptor -// Used to bind 2 interfaces together in CDC compostite device -typedef struct -{ - u8 len; // 8 - u8 dtype; // 11 - u8 firstInterface; - u8 interfaceCount; - u8 functionClass; - u8 funtionSubClass; - u8 functionProtocol; - u8 iInterface; -} IADDescriptor; - -// CDC CS interface descriptor -typedef struct -{ - u8 len; // 5 - u8 dtype; // 0x24 - u8 subtype; - u8 d0; - u8 d1; -} CDCCSInterfaceDescriptor; - -typedef struct -{ - u8 len; // 4 - u8 dtype; // 0x24 - u8 subtype; - u8 d0; -} CDCCSInterfaceDescriptor4; - -typedef struct -{ - u8 len; - u8 dtype; // 0x24 - u8 subtype; // 1 - u8 bmCapabilities; - u8 bDataInterface; -} CMFunctionalDescriptor; - -typedef struct -{ - u8 len; - u8 dtype; // 0x24 - u8 subtype; // 1 - u8 bmCapabilities; -} ACMFunctionalDescriptor; - -typedef struct -{ - // IAD - IADDescriptor iad; // Only needed on compound device - - // Control - InterfaceDescriptor cif; // - CDCCSInterfaceDescriptor header; - CMFunctionalDescriptor callManagement; // Call Management - ACMFunctionalDescriptor controlManagement; // ACM - CDCCSInterfaceDescriptor functionalDescriptor; // CDC_UNION - EndpointDescriptor cifin; - - // Data - InterfaceDescriptor dif; - EndpointDescriptor in; - EndpointDescriptor out; -} CDCDescriptor; - -typedef struct -{ - InterfaceDescriptor msc; - EndpointDescriptor in; - EndpointDescriptor out; -} MSCDescriptor; - - -#define D_DEVICE(_class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs) \ - { 18, 1, USB_VERSION, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs } - -#define D_CONFIG(_totalLength,_interfaces) \ - { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(USB_CONFIG_POWER) } - -#define D_INTERFACE(_n,_numEndpoints,_class,_subClass,_protocol) \ - { 9, 4, _n, 0, _numEndpoints, _class,_subClass, _protocol, 0 } - -#define D_ENDPOINT(_addr,_attr,_packetSize, _interval) \ - { 7, 5, _addr,_attr,_packetSize, _interval } - -#define D_IAD(_firstInterface, _count, _class, _subClass, _protocol) \ - { 8, 11, _firstInterface, _count, _class, _subClass, _protocol, 0 } - -#define D_CDCCS(_subtype,_d0,_d1) { 5, 0x24, _subtype, _d0, _d1 } -#define D_CDCCS4(_subtype,_d0) { 4, 0x24, _subtype, _d0 } - -// Bootloader related fields -// Old Caterina bootloader places the MAGIC key into unsafe RAM locations (it can be rewritten -// by the running sketch before to actual reboot). -// Newer bootloaders, recognizable by the LUFA "signature" at the end of the flash, can handle both -// the usafe and the safe location. -#ifndef MAGIC_KEY -#define MAGIC_KEY 0x7777 -#endif - -#ifndef MAGIC_KEY_POS -#define MAGIC_KEY_POS 0x0800 -#endif - -#ifndef NEW_LUFA_SIGNATURE -#define NEW_LUFA_SIGNATURE 0xDCFB -#endif - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBDesc.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBDesc.h deleted file mode 100644 index c0dce07..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/USBDesc.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright (c) 2011, Peter Barrett - Copyright (c) 2015, Arduino LLC - - Permission to use, copy, modify, and/or distribute this software for - any purpose with or without fee is hereby granted, provided that the - above copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL - WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR - BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES - OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, - WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, - ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS - SOFTWARE. - */ - -#define PLUGGABLE_USB_ENABLED - -#if defined(EPRST6) -#define USB_ENDPOINTS 7 // AtMegaxxU4 -#else -#define USB_ENDPOINTS 5 // AtMegaxxU2 -#endif - -#define ISERIAL_MAX_LEN 20 - -#define CDC_INTERFACE_COUNT 2 -#define CDC_ENPOINT_COUNT 3 - -#define CDC_ACM_INTERFACE 0 // CDC ACM -#define CDC_DATA_INTERFACE 1 // CDC Data -#define CDC_FIRST_ENDPOINT 1 -#define CDC_ENDPOINT_ACM (CDC_FIRST_ENDPOINT) // CDC First -#define CDC_ENDPOINT_OUT (CDC_FIRST_ENDPOINT+1) -#define CDC_ENDPOINT_IN (CDC_FIRST_ENDPOINT+2) - -#define INTERFACE_COUNT (MSC_INTERFACE + MSC_INTERFACE_COUNT) - -#define CDC_RX CDC_ENDPOINT_OUT -#define CDC_TX CDC_ENDPOINT_IN - -#define IMANUFACTURER 1 -#define IPRODUCT 2 -#define ISERIAL 3 \ No newline at end of file diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Udp.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/Udp.h deleted file mode 100644 index 89f31c6..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/Udp.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Udp.cpp: Library to send/receive UDP packets. - * - * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these) - * 1) UDP does not guarantee the order in which assembled UDP packets are received. This - * might not happen often in practice, but in larger network topologies, a UDP - * packet can be received out of sequence. - * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being - * aware of it. Again, this may not be a concern in practice on small local networks. - * For more information, see http://www.cafeaulait.org/course/week12/35.html - * - * MIT License: - * Copyright (c) 2008 Bjoern Hartmann - * 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. - * - * bjoern@cs.stanford.edu 12/30/2008 - */ - -#ifndef udp_h -#define udp_h - -#include -#include - -class UDP : public Stream { - -public: - virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulticast(IPAddress, uint16_t) { return 0; } // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 on failure - virtual void stop() =0; // Finish with the UDP socket - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port) =0; - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char *host, uint16_t port) =0; - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket() =0; - // Write a single byte into the packet - virtual size_t write(uint8_t) =0; - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t *buffer, size_t size) =0; - - // Start processing the next available incoming packet - // Returns the size of the packet in bytes, or 0 if no packets are available - virtual int parsePacket() =0; - // Number of bytes remaining in the current packet - virtual int available() =0; - // Read a single byte from the current packet - virtual int read() =0; - // Read up to len bytes from the current packet and place them into buffer - // Returns the number of bytes read, or 0 if none are available - virtual int read(unsigned char* buffer, size_t len) =0; - // Read up to len characters from the current packet and place them into buffer - // Returns the number of characters read, or 0 if none are available - virtual int read(char* buffer, size_t len) =0; - // Return the next byte from the current packet without moving on to the next byte - virtual int peek() =0; - virtual void flush() =0; // Finish reading the current packet - - // Return the IP address of the host who sent the current incoming packet - virtual IPAddress remoteIP() =0; - // Return the port of the host who sent the current incoming packet - virtual uint16_t remotePort() =0; -protected: - uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); }; -}; - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/WCharacter.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/WCharacter.h deleted file mode 100644 index 79733b5..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/WCharacter.h +++ /dev/null @@ -1,168 +0,0 @@ -/* - WCharacter.h - Character utility functions for Wiring & Arduino - Copyright (c) 2010 Hernando Barragan. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef Character_h -#define Character_h - -#include - -// WCharacter.h prototypes -inline boolean isAlphaNumeric(int c) __attribute__((always_inline)); -inline boolean isAlpha(int c) __attribute__((always_inline)); -inline boolean isAscii(int c) __attribute__((always_inline)); -inline boolean isWhitespace(int c) __attribute__((always_inline)); -inline boolean isControl(int c) __attribute__((always_inline)); -inline boolean isDigit(int c) __attribute__((always_inline)); -inline boolean isGraph(int c) __attribute__((always_inline)); -inline boolean isLowerCase(int c) __attribute__((always_inline)); -inline boolean isPrintable(int c) __attribute__((always_inline)); -inline boolean isPunct(int c) __attribute__((always_inline)); -inline boolean isSpace(int c) __attribute__((always_inline)); -inline boolean isUpperCase(int c) __attribute__((always_inline)); -inline boolean isHexadecimalDigit(int c) __attribute__((always_inline)); -inline int toAscii(int c) __attribute__((always_inline)); -inline int toLowerCase(int c) __attribute__((always_inline)); -inline int toUpperCase(int c)__attribute__((always_inline)); - - -// Checks for an alphanumeric character. -// It is equivalent to (isalpha(c) || isdigit(c)). -inline boolean isAlphaNumeric(int c) -{ - return ( isalnum(c) == 0 ? false : true); -} - - -// Checks for an alphabetic character. -// It is equivalent to (isupper(c) || islower(c)). -inline boolean isAlpha(int c) -{ - return ( isalpha(c) == 0 ? false : true); -} - - -// Checks whether c is a 7-bit unsigned char value -// that fits into the ASCII character set. -inline boolean isAscii(int c) -{ - return ( isascii (c) == 0 ? false : true); -} - - -// Checks for a blank character, that is, a space or a tab. -inline boolean isWhitespace(int c) -{ - return ( isblank (c) == 0 ? false : true); -} - - -// Checks for a control character. -inline boolean isControl(int c) -{ - return ( iscntrl (c) == 0 ? false : true); -} - - -// Checks for a digit (0 through 9). -inline boolean isDigit(int c) -{ - return ( isdigit (c) == 0 ? false : true); -} - - -// Checks for any printable character except space. -inline boolean isGraph(int c) -{ - return ( isgraph (c) == 0 ? false : true); -} - - -// Checks for a lower-case character. -inline boolean isLowerCase(int c) -{ - return (islower (c) == 0 ? false : true); -} - - -// Checks for any printable character including space. -inline boolean isPrintable(int c) -{ - return ( isprint (c) == 0 ? false : true); -} - - -// Checks for any printable character which is not a space -// or an alphanumeric character. -inline boolean isPunct(int c) -{ - return ( ispunct (c) == 0 ? false : true); -} - - -// Checks for white-space characters. For the avr-libc library, -// these are: space, formfeed ('\f'), newline ('\n'), carriage -// return ('\r'), horizontal tab ('\t'), and vertical tab ('\v'). -inline boolean isSpace(int c) -{ - return ( isspace (c) == 0 ? false : true); -} - - -// Checks for an uppercase letter. -inline boolean isUpperCase(int c) -{ - return ( isupper (c) == 0 ? false : true); -} - - -// Checks for a hexadecimal digits, i.e. one of 0 1 2 3 4 5 6 7 -// 8 9 a b c d e f A B C D E F. -inline boolean isHexadecimalDigit(int c) -{ - return ( isxdigit (c) == 0 ? false : true); -} - - -// Converts c to a 7-bit unsigned char value that fits into the -// ASCII character set, by clearing the high-order bits. -inline int toAscii(int c) -{ - return toascii (c); -} - - -// Warning: -// Many people will be unhappy if you use this function. -// This function will convert accented letters into random -// characters. - -// Converts the letter c to lower case, if possible. -inline int toLowerCase(int c) -{ - return tolower (c); -} - - -// Converts the letter c to upper case, if possible. -inline int toUpperCase(int c) -{ - return toupper (c); -} - -#endif \ No newline at end of file diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/WString.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/WString.h deleted file mode 100644 index 77709c3..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/WString.h +++ /dev/null @@ -1,229 +0,0 @@ -/* - WString.h - String library for Wiring & Arduino - ...mostly rewritten by Paul Stoffregen... - Copyright (c) 2009-10 Hernando Barragan. All right reserved. - Copyright 2011, Paul Stoffregen, paul@pjrc.com - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef String_class_h -#define String_class_h -#ifdef __cplusplus - -#include -#include -#include -#include - -// When compiling programs with this class, the following gcc parameters -// dramatically increase performance and memory (RAM) efficiency, typically -// with little or no increase in code size. -// -felide-constructors -// -std=c++0x - -class __FlashStringHelper; -#define F(string_literal) (reinterpret_cast(PSTR(string_literal))) - -// An inherited class for holding the result of a concatenation. These -// result objects are assumed to be writable by subsequent concatenations. -class StringSumHelper; - -// The string class -class String -{ - // use a function pointer to allow for "if (s)" without the - // complications of an operator bool(). for more information, see: - // http://www.artima.com/cppsource/safebool.html - typedef void (String::*StringIfHelperType)() const; - void StringIfHelper() const {} - -public: - // constructors - // creates a copy of the initial value. - // if the initial value is null or invalid, or if memory allocation - // fails, the string will be marked as invalid (i.e. "if (s)" will - // be false). - String(const char *cstr = ""); - String(const String &str); - String(const __FlashStringHelper *str); - #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) - String(String &&rval); - String(StringSumHelper &&rval); - #endif - explicit String(char c); - explicit String(unsigned char, unsigned char base=10); - explicit String(int, unsigned char base=10); - explicit String(unsigned int, unsigned char base=10); - explicit String(long, unsigned char base=10); - explicit String(unsigned long, unsigned char base=10); - explicit String(float, unsigned char decimalPlaces=2); - explicit String(double, unsigned char decimalPlaces=2); - ~String(void); - - // memory management - // return true on success, false on failure (in which case, the string - // is left unchanged). reserve(0), if successful, will validate an - // invalid string (i.e., "if (s)" will be true afterwards) - unsigned char reserve(unsigned int size); - inline unsigned int length(void) const {return len;} - - // creates a copy of the assigned value. if the value is null or - // invalid, or if the memory allocation fails, the string will be - // marked as invalid ("if (s)" will be false). - String & operator = (const String &rhs); - String & operator = (const char *cstr); - String & operator = (const __FlashStringHelper *str); - #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) - String & operator = (String &&rval); - String & operator = (StringSumHelper &&rval); - #endif - - // concatenate (works w/ built-in types) - - // returns true on success, false on failure (in which case, the string - // is left unchanged). if the argument is null or invalid, the - // concatenation is considered unsucessful. - unsigned char concat(const String &str); - unsigned char concat(const char *cstr); - unsigned char concat(char c); - unsigned char concat(unsigned char c); - unsigned char concat(int num); - unsigned char concat(unsigned int num); - unsigned char concat(long num); - unsigned char concat(unsigned long num); - unsigned char concat(float num); - unsigned char concat(double num); - unsigned char concat(const __FlashStringHelper * str); - - // if there's not enough memory for the concatenated value, the string - // will be left unchanged (but this isn't signalled in any way) - String & operator += (const String &rhs) {concat(rhs); return (*this);} - String & operator += (const char *cstr) {concat(cstr); return (*this);} - String & operator += (char c) {concat(c); return (*this);} - String & operator += (unsigned char num) {concat(num); return (*this);} - String & operator += (int num) {concat(num); return (*this);} - String & operator += (unsigned int num) {concat(num); return (*this);} - String & operator += (long num) {concat(num); return (*this);} - String & operator += (unsigned long num) {concat(num); return (*this);} - String & operator += (float num) {concat(num); return (*this);} - String & operator += (double num) {concat(num); return (*this);} - String & operator += (const __FlashStringHelper *str){concat(str); return (*this);} - - friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs); - friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr); - friend StringSumHelper & operator + (const StringSumHelper &lhs, char c); - friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, int num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, long num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, float num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, double num); - friend StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs); - - // comparison (only works w/ Strings and "strings") - operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; } - int compareTo(const String &s) const; - unsigned char equals(const String &s) const; - unsigned char equals(const char *cstr) const; - unsigned char operator == (const String &rhs) const {return equals(rhs);} - unsigned char operator == (const char *cstr) const {return equals(cstr);} - unsigned char operator != (const String &rhs) const {return !equals(rhs);} - unsigned char operator != (const char *cstr) const {return !equals(cstr);} - unsigned char operator < (const String &rhs) const; - unsigned char operator > (const String &rhs) const; - unsigned char operator <= (const String &rhs) const; - unsigned char operator >= (const String &rhs) const; - unsigned char equalsIgnoreCase(const String &s) const; - unsigned char startsWith( const String &prefix) const; - unsigned char startsWith(const String &prefix, unsigned int offset) const; - unsigned char endsWith(const String &suffix) const; - - // character acccess - char charAt(unsigned int index) const; - void setCharAt(unsigned int index, char c); - char operator [] (unsigned int index) const; - char& operator [] (unsigned int index); - void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const; - void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const - { getBytes((unsigned char *)buf, bufsize, index); } - const char* c_str() const { return buffer; } - char* begin() { return buffer; } - char* end() { return buffer + length(); } - const char* begin() const { return c_str(); } - const char* end() const { return c_str() + length(); } - - // search - int indexOf( char ch ) const; - int indexOf( char ch, unsigned int fromIndex ) const; - int indexOf( const String &str ) const; - int indexOf( const String &str, unsigned int fromIndex ) const; - int lastIndexOf( char ch ) const; - int lastIndexOf( char ch, unsigned int fromIndex ) const; - int lastIndexOf( const String &str ) const; - int lastIndexOf( const String &str, unsigned int fromIndex ) const; - String substring( unsigned int beginIndex ) const { return substring(beginIndex, len); }; - String substring( unsigned int beginIndex, unsigned int endIndex ) const; - - // modification - void replace(char find, char replace); - void replace(const String& find, const String& replace); - void remove(unsigned int index); - void remove(unsigned int index, unsigned int count); - void toLowerCase(void); - void toUpperCase(void); - void trim(void); - - // parsing/conversion - long toInt(void) const; - float toFloat(void) const; - double toDouble(void) const; - -protected: - char *buffer; // the actual char array - unsigned int capacity; // the array length minus one (for the '\0') - unsigned int len; // the String length (not counting the '\0') -protected: - void init(void); - void invalidate(void); - unsigned char changeBuffer(unsigned int maxStrLen); - unsigned char concat(const char *cstr, unsigned int length); - - // copy and move - String & copy(const char *cstr, unsigned int length); - String & copy(const __FlashStringHelper *pstr, unsigned int length); - #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) - void move(String &rhs); - #endif -}; - -class StringSumHelper : public String -{ -public: - StringSumHelper(const String &s) : String(s) {} - StringSumHelper(const char *p) : String(p) {} - StringSumHelper(char c) : String(c) {} - StringSumHelper(unsigned char num) : String(num) {} - StringSumHelper(int num) : String(num) {} - StringSumHelper(unsigned int num) : String(num) {} - StringSumHelper(long num) : String(num) {} - StringSumHelper(unsigned long num) : String(num) {} - StringSumHelper(float num) : String(num) {} - StringSumHelper(double num) : String(num) {} -}; - -#endif // __cplusplus -#endif // String_class_h diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/binary.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/binary.h deleted file mode 100644 index aec4c73..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/binary.h +++ /dev/null @@ -1,534 +0,0 @@ -/* - binary.h - Definitions for binary constants - Copyright (c) 2006 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef Binary_h -#define Binary_h - -#define B0 0 -#define B00 0 -#define B000 0 -#define B0000 0 -#define B00000 0 -#define B000000 0 -#define B0000000 0 -#define B00000000 0 -#define B1 1 -#define B01 1 -#define B001 1 -#define B0001 1 -#define B00001 1 -#define B000001 1 -#define B0000001 1 -#define B00000001 1 -#define B10 2 -#define B010 2 -#define B0010 2 -#define B00010 2 -#define B000010 2 -#define B0000010 2 -#define B00000010 2 -#define B11 3 -#define B011 3 -#define B0011 3 -#define B00011 3 -#define B000011 3 -#define B0000011 3 -#define B00000011 3 -#define B100 4 -#define B0100 4 -#define B00100 4 -#define B000100 4 -#define B0000100 4 -#define B00000100 4 -#define B101 5 -#define B0101 5 -#define B00101 5 -#define B000101 5 -#define B0000101 5 -#define B00000101 5 -#define B110 6 -#define B0110 6 -#define B00110 6 -#define B000110 6 -#define B0000110 6 -#define B00000110 6 -#define B111 7 -#define B0111 7 -#define B00111 7 -#define B000111 7 -#define B0000111 7 -#define B00000111 7 -#define B1000 8 -#define B01000 8 -#define B001000 8 -#define B0001000 8 -#define B00001000 8 -#define B1001 9 -#define B01001 9 -#define B001001 9 -#define B0001001 9 -#define B00001001 9 -#define B1010 10 -#define B01010 10 -#define B001010 10 -#define B0001010 10 -#define B00001010 10 -#define B1011 11 -#define B01011 11 -#define B001011 11 -#define B0001011 11 -#define B00001011 11 -#define B1100 12 -#define B01100 12 -#define B001100 12 -#define B0001100 12 -#define B00001100 12 -#define B1101 13 -#define B01101 13 -#define B001101 13 -#define B0001101 13 -#define B00001101 13 -#define B1110 14 -#define B01110 14 -#define B001110 14 -#define B0001110 14 -#define B00001110 14 -#define B1111 15 -#define B01111 15 -#define B001111 15 -#define B0001111 15 -#define B00001111 15 -#define B10000 16 -#define B010000 16 -#define B0010000 16 -#define B00010000 16 -#define B10001 17 -#define B010001 17 -#define B0010001 17 -#define B00010001 17 -#define B10010 18 -#define B010010 18 -#define B0010010 18 -#define B00010010 18 -#define B10011 19 -#define B010011 19 -#define B0010011 19 -#define B00010011 19 -#define B10100 20 -#define B010100 20 -#define B0010100 20 -#define B00010100 20 -#define B10101 21 -#define B010101 21 -#define B0010101 21 -#define B00010101 21 -#define B10110 22 -#define B010110 22 -#define B0010110 22 -#define B00010110 22 -#define B10111 23 -#define B010111 23 -#define B0010111 23 -#define B00010111 23 -#define B11000 24 -#define B011000 24 -#define B0011000 24 -#define B00011000 24 -#define B11001 25 -#define B011001 25 -#define B0011001 25 -#define B00011001 25 -#define B11010 26 -#define B011010 26 -#define B0011010 26 -#define B00011010 26 -#define B11011 27 -#define B011011 27 -#define B0011011 27 -#define B00011011 27 -#define B11100 28 -#define B011100 28 -#define B0011100 28 -#define B00011100 28 -#define B11101 29 -#define B011101 29 -#define B0011101 29 -#define B00011101 29 -#define B11110 30 -#define B011110 30 -#define B0011110 30 -#define B00011110 30 -#define B11111 31 -#define B011111 31 -#define B0011111 31 -#define B00011111 31 -#define B100000 32 -#define B0100000 32 -#define B00100000 32 -#define B100001 33 -#define B0100001 33 -#define B00100001 33 -#define B100010 34 -#define B0100010 34 -#define B00100010 34 -#define B100011 35 -#define B0100011 35 -#define B00100011 35 -#define B100100 36 -#define B0100100 36 -#define B00100100 36 -#define B100101 37 -#define B0100101 37 -#define B00100101 37 -#define B100110 38 -#define B0100110 38 -#define B00100110 38 -#define B100111 39 -#define B0100111 39 -#define B00100111 39 -#define B101000 40 -#define B0101000 40 -#define B00101000 40 -#define B101001 41 -#define B0101001 41 -#define B00101001 41 -#define B101010 42 -#define B0101010 42 -#define B00101010 42 -#define B101011 43 -#define B0101011 43 -#define B00101011 43 -#define B101100 44 -#define B0101100 44 -#define B00101100 44 -#define B101101 45 -#define B0101101 45 -#define B00101101 45 -#define B101110 46 -#define B0101110 46 -#define B00101110 46 -#define B101111 47 -#define B0101111 47 -#define B00101111 47 -#define B110000 48 -#define B0110000 48 -#define B00110000 48 -#define B110001 49 -#define B0110001 49 -#define B00110001 49 -#define B110010 50 -#define B0110010 50 -#define B00110010 50 -#define B110011 51 -#define B0110011 51 -#define B00110011 51 -#define B110100 52 -#define B0110100 52 -#define B00110100 52 -#define B110101 53 -#define B0110101 53 -#define B00110101 53 -#define B110110 54 -#define B0110110 54 -#define B00110110 54 -#define B110111 55 -#define B0110111 55 -#define B00110111 55 -#define B111000 56 -#define B0111000 56 -#define B00111000 56 -#define B111001 57 -#define B0111001 57 -#define B00111001 57 -#define B111010 58 -#define B0111010 58 -#define B00111010 58 -#define B111011 59 -#define B0111011 59 -#define B00111011 59 -#define B111100 60 -#define B0111100 60 -#define B00111100 60 -#define B111101 61 -#define B0111101 61 -#define B00111101 61 -#define B111110 62 -#define B0111110 62 -#define B00111110 62 -#define B111111 63 -#define B0111111 63 -#define B00111111 63 -#define B1000000 64 -#define B01000000 64 -#define B1000001 65 -#define B01000001 65 -#define B1000010 66 -#define B01000010 66 -#define B1000011 67 -#define B01000011 67 -#define B1000100 68 -#define B01000100 68 -#define B1000101 69 -#define B01000101 69 -#define B1000110 70 -#define B01000110 70 -#define B1000111 71 -#define B01000111 71 -#define B1001000 72 -#define B01001000 72 -#define B1001001 73 -#define B01001001 73 -#define B1001010 74 -#define B01001010 74 -#define B1001011 75 -#define B01001011 75 -#define B1001100 76 -#define B01001100 76 -#define B1001101 77 -#define B01001101 77 -#define B1001110 78 -#define B01001110 78 -#define B1001111 79 -#define B01001111 79 -#define B1010000 80 -#define B01010000 80 -#define B1010001 81 -#define B01010001 81 -#define B1010010 82 -#define B01010010 82 -#define B1010011 83 -#define B01010011 83 -#define B1010100 84 -#define B01010100 84 -#define B1010101 85 -#define B01010101 85 -#define B1010110 86 -#define B01010110 86 -#define B1010111 87 -#define B01010111 87 -#define B1011000 88 -#define B01011000 88 -#define B1011001 89 -#define B01011001 89 -#define B1011010 90 -#define B01011010 90 -#define B1011011 91 -#define B01011011 91 -#define B1011100 92 -#define B01011100 92 -#define B1011101 93 -#define B01011101 93 -#define B1011110 94 -#define B01011110 94 -#define B1011111 95 -#define B01011111 95 -#define B1100000 96 -#define B01100000 96 -#define B1100001 97 -#define B01100001 97 -#define B1100010 98 -#define B01100010 98 -#define B1100011 99 -#define B01100011 99 -#define B1100100 100 -#define B01100100 100 -#define B1100101 101 -#define B01100101 101 -#define B1100110 102 -#define B01100110 102 -#define B1100111 103 -#define B01100111 103 -#define B1101000 104 -#define B01101000 104 -#define B1101001 105 -#define B01101001 105 -#define B1101010 106 -#define B01101010 106 -#define B1101011 107 -#define B01101011 107 -#define B1101100 108 -#define B01101100 108 -#define B1101101 109 -#define B01101101 109 -#define B1101110 110 -#define B01101110 110 -#define B1101111 111 -#define B01101111 111 -#define B1110000 112 -#define B01110000 112 -#define B1110001 113 -#define B01110001 113 -#define B1110010 114 -#define B01110010 114 -#define B1110011 115 -#define B01110011 115 -#define B1110100 116 -#define B01110100 116 -#define B1110101 117 -#define B01110101 117 -#define B1110110 118 -#define B01110110 118 -#define B1110111 119 -#define B01110111 119 -#define B1111000 120 -#define B01111000 120 -#define B1111001 121 -#define B01111001 121 -#define B1111010 122 -#define B01111010 122 -#define B1111011 123 -#define B01111011 123 -#define B1111100 124 -#define B01111100 124 -#define B1111101 125 -#define B01111101 125 -#define B1111110 126 -#define B01111110 126 -#define B1111111 127 -#define B01111111 127 -#define B10000000 128 -#define B10000001 129 -#define B10000010 130 -#define B10000011 131 -#define B10000100 132 -#define B10000101 133 -#define B10000110 134 -#define B10000111 135 -#define B10001000 136 -#define B10001001 137 -#define B10001010 138 -#define B10001011 139 -#define B10001100 140 -#define B10001101 141 -#define B10001110 142 -#define B10001111 143 -#define B10010000 144 -#define B10010001 145 -#define B10010010 146 -#define B10010011 147 -#define B10010100 148 -#define B10010101 149 -#define B10010110 150 -#define B10010111 151 -#define B10011000 152 -#define B10011001 153 -#define B10011010 154 -#define B10011011 155 -#define B10011100 156 -#define B10011101 157 -#define B10011110 158 -#define B10011111 159 -#define B10100000 160 -#define B10100001 161 -#define B10100010 162 -#define B10100011 163 -#define B10100100 164 -#define B10100101 165 -#define B10100110 166 -#define B10100111 167 -#define B10101000 168 -#define B10101001 169 -#define B10101010 170 -#define B10101011 171 -#define B10101100 172 -#define B10101101 173 -#define B10101110 174 -#define B10101111 175 -#define B10110000 176 -#define B10110001 177 -#define B10110010 178 -#define B10110011 179 -#define B10110100 180 -#define B10110101 181 -#define B10110110 182 -#define B10110111 183 -#define B10111000 184 -#define B10111001 185 -#define B10111010 186 -#define B10111011 187 -#define B10111100 188 -#define B10111101 189 -#define B10111110 190 -#define B10111111 191 -#define B11000000 192 -#define B11000001 193 -#define B11000010 194 -#define B11000011 195 -#define B11000100 196 -#define B11000101 197 -#define B11000110 198 -#define B11000111 199 -#define B11001000 200 -#define B11001001 201 -#define B11001010 202 -#define B11001011 203 -#define B11001100 204 -#define B11001101 205 -#define B11001110 206 -#define B11001111 207 -#define B11010000 208 -#define B11010001 209 -#define B11010010 210 -#define B11010011 211 -#define B11010100 212 -#define B11010101 213 -#define B11010110 214 -#define B11010111 215 -#define B11011000 216 -#define B11011001 217 -#define B11011010 218 -#define B11011011 219 -#define B11011100 220 -#define B11011101 221 -#define B11011110 222 -#define B11011111 223 -#define B11100000 224 -#define B11100001 225 -#define B11100010 226 -#define B11100011 227 -#define B11100100 228 -#define B11100101 229 -#define B11100110 230 -#define B11100111 231 -#define B11101000 232 -#define B11101001 233 -#define B11101010 234 -#define B11101011 235 -#define B11101100 236 -#define B11101101 237 -#define B11101110 238 -#define B11101111 239 -#define B11110000 240 -#define B11110001 241 -#define B11110010 242 -#define B11110011 243 -#define B11110100 244 -#define B11110101 245 -#define B11110110 246 -#define B11110111 247 -#define B11111000 248 -#define B11111001 249 -#define B11111010 250 -#define B11111011 251 -#define B11111100 252 -#define B11111101 253 -#define B11111110 254 -#define B11111111 255 - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/new.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/new.h deleted file mode 100644 index 763f5cc..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/new.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (c) 2014 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef NEW_H -#define NEW_H - -#include - -void * operator new(size_t size); -void * operator new[](size_t size); -void * operator new(size_t size, void * ptr) noexcept; -void operator delete(void * ptr); -void operator delete[](void * ptr); - -#endif - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/core/wiring_private.h b/AtmelStudio/TimerTwo/ArduinoCore/include/core/wiring_private.h deleted file mode 100644 index a277b14..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/core/wiring_private.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - wiring_private.h - Internal header file. - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2005-2006 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA -*/ - -#ifndef WiringPrivate_h -#define WiringPrivate_h - -#include -#include -#include -#include - -#include "Arduino.h" - -#ifdef __cplusplus -extern "C"{ -#endif - -#ifndef cbi -#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) -#endif -#ifndef sbi -#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) -#endif - -uint32_t countPulseASM(volatile uint8_t *port, uint8_t bit, uint8_t stateMask, unsigned long maxloops); - -#define EXTERNAL_INT_0 0 -#define EXTERNAL_INT_1 1 -#define EXTERNAL_INT_2 2 -#define EXTERNAL_INT_3 3 -#define EXTERNAL_INT_4 4 -#define EXTERNAL_INT_5 5 -#define EXTERNAL_INT_6 6 -#define EXTERNAL_INT_7 7 - -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega128RFA1__) || defined(__AVR_ATmega256RFR2__) || \ - defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__) || defined(__AVR_ATmega32U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega8U2__) -#define EXTERNAL_NUM_INTERRUPTS 8 -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) -#define EXTERNAL_NUM_INTERRUPTS 3 -#elif defined(__AVR_ATmega32U4__) -#define EXTERNAL_NUM_INTERRUPTS 5 -#else -#define EXTERNAL_NUM_INTERRUPTS 2 -#endif - -typedef void (*voidFuncPtr)(void); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/include/variants/standard/pins_arduino.h b/AtmelStudio/TimerTwo/ArduinoCore/include/variants/standard/pins_arduino.h deleted file mode 100644 index 2ea0190..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/include/variants/standard/pins_arduino.h +++ /dev/null @@ -1,254 +0,0 @@ -/* - pins_arduino.h - Pin definition functions for Arduino - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2007 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA -*/ - -#ifndef Pins_Arduino_h -#define Pins_Arduino_h - -#include - -#define NUM_DIGITAL_PINS 20 -#define NUM_ANALOG_INPUTS 6 -#define analogInputToDigitalPin(p) ((p < 6) ? (p) + 14 : -1) - -#if defined(__AVR_ATmega8__) -#define digitalPinHasPWM(p) ((p) == 9 || (p) == 10 || (p) == 11) -#else -#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11) -#endif - -#define PIN_SPI_SS (10) -#define PIN_SPI_MOSI (11) -#define PIN_SPI_MISO (12) -#define PIN_SPI_SCK (13) - -static const uint8_t SS = PIN_SPI_SS; -static const uint8_t MOSI = PIN_SPI_MOSI; -static const uint8_t MISO = PIN_SPI_MISO; -static const uint8_t SCK = PIN_SPI_SCK; - -#define PIN_WIRE_SDA (18) -#define PIN_WIRE_SCL (19) - -static const uint8_t SDA = PIN_WIRE_SDA; -static const uint8_t SCL = PIN_WIRE_SCL; - -#define LED_BUILTIN 13 - -#define PIN_A0 (14) -#define PIN_A1 (15) -#define PIN_A2 (16) -#define PIN_A3 (17) -#define PIN_A4 (18) -#define PIN_A5 (19) -#define PIN_A6 (20) -#define PIN_A7 (21) - -static const uint8_t A0 = PIN_A0; -static const uint8_t A1 = PIN_A1; -static const uint8_t A2 = PIN_A2; -static const uint8_t A3 = PIN_A3; -static const uint8_t A4 = PIN_A4; -static const uint8_t A5 = PIN_A5; -static const uint8_t A6 = PIN_A6; -static const uint8_t A7 = PIN_A7; - -#define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0)) -#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1)) -#define digitalPinToPCMSK(p) (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0)))) -#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14))) - -#define digitalPinToInterrupt(p) ((p) == 2 ? 0 : ((p) == 3 ? 1 : NOT_AN_INTERRUPT)) - -#ifdef ARDUINO_MAIN - -// On the Arduino board, digital pins are also used -// for the analog output (software PWM). Analog input -// pins are a separate set. - -// ATMEL ATMEGA8 & 168 / ARDUINO -// -// +-\/-+ -// PC6 1| |28 PC5 (AI 5) -// (D 0) PD0 2| |27 PC4 (AI 4) -// (D 1) PD1 3| |26 PC3 (AI 3) -// (D 2) PD2 4| |25 PC2 (AI 2) -// PWM+ (D 3) PD3 5| |24 PC1 (AI 1) -// (D 4) PD4 6| |23 PC0 (AI 0) -// VCC 7| |22 GND -// GND 8| |21 AREF -// PB6 9| |20 AVCC -// PB7 10| |19 PB5 (D 13) -// PWM+ (D 5) PD5 11| |18 PB4 (D 12) -// PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM -// (D 7) PD7 13| |16 PB2 (D 10) PWM -// (D 8) PB0 14| |15 PB1 (D 9) PWM -// +----+ -// -// (PWM+ indicates the additional PWM pins on the ATmega168.) - -// ATMEL ATMEGA1280 / ARDUINO -// -// 0-7 PE0-PE7 works -// 8-13 PB0-PB5 works -// 14-21 PA0-PA7 works -// 22-29 PH0-PH7 works -// 30-35 PG5-PG0 works -// 36-43 PC7-PC0 works -// 44-51 PJ7-PJ0 works -// 52-59 PL7-PL0 works -// 60-67 PD7-PD0 works -// A0-A7 PF0-PF7 -// A8-A15 PK0-PK7 - - -// these arrays map port names (e.g. port B) to the -// appropriate addresses for various functions (e.g. reading -// and writing) -const uint16_t PROGMEM port_to_mode_PGM[] = { - NOT_A_PORT, - NOT_A_PORT, - (uint16_t) &DDRB, - (uint16_t) &DDRC, - (uint16_t) &DDRD, -}; - -const uint16_t PROGMEM port_to_output_PGM[] = { - NOT_A_PORT, - NOT_A_PORT, - (uint16_t) &PORTB, - (uint16_t) &PORTC, - (uint16_t) &PORTD, -}; - -const uint16_t PROGMEM port_to_input_PGM[] = { - NOT_A_PORT, - NOT_A_PORT, - (uint16_t) &PINB, - (uint16_t) &PINC, - (uint16_t) &PIND, -}; - -const uint8_t PROGMEM digital_pin_to_port_PGM[] = { - PD, /* 0 */ - PD, - PD, - PD, - PD, - PD, - PD, - PD, - PB, /* 8 */ - PB, - PB, - PB, - PB, - PB, - PC, /* 14 */ - PC, - PC, - PC, - PC, - PC, -}; - -const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { - _BV(0), /* 0, port D */ - _BV(1), - _BV(2), - _BV(3), - _BV(4), - _BV(5), - _BV(6), - _BV(7), - _BV(0), /* 8, port B */ - _BV(1), - _BV(2), - _BV(3), - _BV(4), - _BV(5), - _BV(0), /* 14, port C */ - _BV(1), - _BV(2), - _BV(3), - _BV(4), - _BV(5), -}; - -const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { - NOT_ON_TIMER, /* 0 - port D */ - NOT_ON_TIMER, - NOT_ON_TIMER, - // on the ATmega168, digital pin 3 has hardware pwm -#if defined(__AVR_ATmega8__) - NOT_ON_TIMER, -#else - TIMER2B, -#endif - NOT_ON_TIMER, - // on the ATmega168, digital pins 5 and 6 have hardware pwm -#if defined(__AVR_ATmega8__) - NOT_ON_TIMER, - NOT_ON_TIMER, -#else - TIMER0B, - TIMER0A, -#endif - NOT_ON_TIMER, - NOT_ON_TIMER, /* 8 - port B */ - TIMER1A, - TIMER1B, -#if defined(__AVR_ATmega8__) - TIMER2, -#else - TIMER2A, -#endif - NOT_ON_TIMER, - NOT_ON_TIMER, - NOT_ON_TIMER, - NOT_ON_TIMER, /* 14 - port C */ - NOT_ON_TIMER, - NOT_ON_TIMER, - NOT_ON_TIMER, - NOT_ON_TIMER, -}; - -#endif - -// These serial port names are intended to allow libraries and architecture-neutral -// sketches to automatically default to the correct port name for a particular type -// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN, -// the first hardware serial port whose RX/TX pins are not dedicated to another use. -// -// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor -// -// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial -// -// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library -// -// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins. -// -// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX -// pins are NOT connected to anything by default. -#define SERIAL_PORT_MONITOR Serial -#define SERIAL_PORT_HARDWARE Serial - -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/library.cpp b/AtmelStudio/TimerTwo/ArduinoCore/library.cpp deleted file mode 100644 index 3b4d5a0..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/library.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* - * ArduinoCore.cpp - * - * Created: 24.11.2020 20:49:10 - * Author : aburn - */ - -#include - - -/* Replace with your library code */ -int myfunc(void) -{ - return 0; -} - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/CDC.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/CDC.cpp deleted file mode 100644 index 4ff6b9b..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/CDC.cpp +++ /dev/null @@ -1,302 +0,0 @@ - - -/* Copyright (c) 2011, Peter Barrett -** -** Permission to use, copy, modify, and/or distribute this software for -** any purpose with or without fee is hereby granted, provided that the -** above copyright notice and this permission notice appear in all copies. -** -** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL -** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR -** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS -** SOFTWARE. -*/ - -#include "USBAPI.h" -#include -#include - -#if defined(USBCON) - -typedef struct -{ - u32 dwDTERate; - u8 bCharFormat; - u8 bParityType; - u8 bDataBits; - u8 lineState; -} LineInfo; - -static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 }; -static volatile int32_t breakValue = -1; - -static u8 wdtcsr_save; - -#define WEAK __attribute__ ((weak)) - -extern const CDCDescriptor _cdcInterface PROGMEM; -const CDCDescriptor _cdcInterface = -{ - D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0), - - // CDC communication interface - D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0), - D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd) - D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not) - D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported - D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0 - D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40), - - // CDC data interface - D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0), - D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,USB_EP_SIZE,0), - D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,USB_EP_SIZE,0) -}; - -bool isLUFAbootloader() -{ - return pgm_read_word(FLASHEND - 1) == NEW_LUFA_SIGNATURE; -} - -int CDC_GetInterface(u8* interfaceNum) -{ - interfaceNum[0] += 2; // uses 2 - return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface)); -} - -bool CDC_Setup(USBSetup& setup) -{ - u8 r = setup.bRequest; - u8 requestType = setup.bmRequestType; - - if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType) - { - if (CDC_GET_LINE_CODING == r) - { - USB_SendControl(0,(void*)&_usbLineInfo,7); - return true; - } - } - - if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType) - { - if (CDC_SEND_BREAK == r) - { - breakValue = ((uint16_t)setup.wValueH << 8) | setup.wValueL; - } - - if (CDC_SET_LINE_CODING == r) - { - USB_RecvControl((void*)&_usbLineInfo,7); - } - - if (CDC_SET_CONTROL_LINE_STATE == r) - { - _usbLineInfo.lineState = setup.wValueL; - - // auto-reset into the bootloader is triggered when the port, already - // open at 1200 bps, is closed. this is the signal to start the watchdog - // with a relatively long period so it can finish housekeeping tasks - // like servicing endpoints before the sketch ends - - uint16_t magic_key_pos = MAGIC_KEY_POS; - -// If we don't use the new RAMEND directly, check manually if we have a newer bootloader. -// This is used to keep compatible with the old leonardo bootloaders. -// You are still able to set the magic key position manually to RAMEND-1 to save a few bytes for this check. -#if MAGIC_KEY_POS != (RAMEND-1) - // For future boards save the key in the inproblematic RAMEND - // Which is reserved for the main() return value (which will never return) - if (isLUFAbootloader()) { - // horray, we got a new bootloader! - magic_key_pos = (RAMEND-1); - } -#endif - - // We check DTR state to determine if host port is open (bit 0 of lineState). - if (1200 == _usbLineInfo.dwDTERate && (_usbLineInfo.lineState & 0x01) == 0) - { -#if MAGIC_KEY_POS != (RAMEND-1) - // Backup ram value if its not a newer bootloader and it hasn't already been saved. - // This should avoid memory corruption at least a bit, not fully - if (magic_key_pos != (RAMEND-1) && *(uint16_t *)magic_key_pos != MAGIC_KEY) { - *(uint16_t *)(RAMEND-1) = *(uint16_t *)magic_key_pos; - } -#endif - // Store boot key - *(uint16_t *)magic_key_pos = MAGIC_KEY; - // Save the watchdog state in case the reset is aborted. - wdtcsr_save = WDTCSR; - wdt_enable(WDTO_120MS); - } - else if (*(uint16_t *)magic_key_pos == MAGIC_KEY) - { - // Most OSs do some intermediate steps when configuring ports and DTR can - // twiggle more than once before stabilizing. - // To avoid spurious resets we set the watchdog to 120ms and eventually - // cancel if DTR goes back high. - // Cancellation is only done if an auto-reset was started, which is - // indicated by the magic key having been set. - - wdt_reset(); - // Restore the watchdog state in case the sketch was using it. - WDTCSR |= (1<= 0) { - return 1 + USB_Available(CDC_RX); - } - return USB_Available(CDC_RX); -} - -int Serial_::peek(void) -{ - if (peek_buffer < 0) - peek_buffer = USB_Recv(CDC_RX); - return peek_buffer; -} - -int Serial_::read(void) -{ - if (peek_buffer >= 0) { - int c = peek_buffer; - peek_buffer = -1; - return c; - } - return USB_Recv(CDC_RX); -} - -int Serial_::availableForWrite(void) -{ - return USB_SendSpace(CDC_TX); -} - -void Serial_::flush(void) -{ - USB_Flush(CDC_TX); -} - -size_t Serial_::write(uint8_t c) -{ - return write(&c, 1); -} - -size_t Serial_::write(const uint8_t *buffer, size_t size) -{ - /* only try to send bytes if the high-level CDC connection itself - is open (not just the pipe) - the OS should set lineState when the port - is opened and clear lineState when the port is closed. - bytes sent before the user opens the connection or after - the connection is closed are lost - just like with a UART. */ - - // TODO - ZE - check behavior on different OSes and test what happens if an - // open connection isn't broken cleanly (cable is yanked out, host dies - // or locks up, or host virtual serial port hangs) - if (_usbLineInfo.lineState > 0) { - int r = USB_Send(CDC_TX,buffer,size); - if (r > 0) { - return r; - } else { - setWriteError(); - return 0; - } - } - setWriteError(); - return 0; -} - -// This operator is a convenient way for a sketch to check whether the -// port has actually been configured and opened by the host (as opposed -// to just being connected to the host). It can be used, for example, in -// setup() before printing to ensure that an application on the host is -// actually ready to receive and display the data. -// We add a short delay before returning to fix a bug observed by Federico -// where the port is configured (lineState != 0) but not quite opened. -Serial_::operator bool() { - bool result = false; - if (_usbLineInfo.lineState > 0) - result = true; - delay(10); - return result; -} - -unsigned long Serial_::baud() { - // Disable interrupts while reading a multi-byte value - uint32_t baudrate; - ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { - baudrate = _usbLineInfo.dwDTERate; - } - return baudrate; -} - -uint8_t Serial_::stopbits() { - return _usbLineInfo.bCharFormat; -} - -uint8_t Serial_::paritytype() { - return _usbLineInfo.bParityType; -} - -uint8_t Serial_::numbits() { - return _usbLineInfo.bDataBits; -} - -bool Serial_::dtr() { - return _usbLineInfo.lineState & 0x1; -} - -bool Serial_::rts() { - return _usbLineInfo.lineState & 0x2; -} - -int32_t Serial_::readBreak() { - int32_t ret; - // Disable IRQs while reading and clearing breakValue to make - // sure we don't overwrite a value just set by the ISR. - ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { - ret = breakValue; - breakValue = -1; - } - return ret; -} - -Serial_ Serial; - -#endif /* if defined(USBCON) */ diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial.cpp deleted file mode 100644 index e99d503..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* - HardwareSerial.cpp - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus - Modified 3 December 2013 by Matthijs Kooijman -*/ - -#include -#include -#include -#include -#include -#include "Arduino.h" - -#include "HardwareSerial.h" -#include "HardwareSerial_private.h" - -// this next line disables the entire HardwareSerial.cpp, -// this is so I can support Attiny series and any other chip without a uart -#if defined(HAVE_HWSERIAL0) || defined(HAVE_HWSERIAL1) || defined(HAVE_HWSERIAL2) || defined(HAVE_HWSERIAL3) - -// SerialEvent functions are weak, so when the user doesn't define them, -// the linker just sets their address to 0 (which is checked below). -// The Serialx_available is just a wrapper around Serialx.available(), -// but we can refer to it weakly so we don't pull in the entire -// HardwareSerial instance if the user doesn't also refer to it. -#if defined(HAVE_HWSERIAL0) - void serialEvent() __attribute__((weak)); - bool Serial0_available() __attribute__((weak)); -#endif - -#if defined(HAVE_HWSERIAL1) - void serialEvent1() __attribute__((weak)); - bool Serial1_available() __attribute__((weak)); -#endif - -#if defined(HAVE_HWSERIAL2) - void serialEvent2() __attribute__((weak)); - bool Serial2_available() __attribute__((weak)); -#endif - -#if defined(HAVE_HWSERIAL3) - void serialEvent3() __attribute__((weak)); - bool Serial3_available() __attribute__((weak)); -#endif - -void serialEventRun(void) -{ -#if defined(HAVE_HWSERIAL0) - if (Serial0_available && serialEvent && Serial0_available()) serialEvent(); -#endif -#if defined(HAVE_HWSERIAL1) - if (Serial1_available && serialEvent1 && Serial1_available()) serialEvent1(); -#endif -#if defined(HAVE_HWSERIAL2) - if (Serial2_available && serialEvent2 && Serial2_available()) serialEvent2(); -#endif -#if defined(HAVE_HWSERIAL3) - if (Serial3_available && serialEvent3 && Serial3_available()) serialEvent3(); -#endif -} - -// macro to guard critical sections when needed for large TX buffer sizes -#if (SERIAL_TX_BUFFER_SIZE>256) -#define TX_BUFFER_ATOMIC ATOMIC_BLOCK(ATOMIC_RESTORESTATE) -#else -#define TX_BUFFER_ATOMIC -#endif - -// Actual interrupt handlers ////////////////////////////////////////////////////////////// - -void HardwareSerial::_tx_udr_empty_irq(void) -{ - // If interrupts are enabled, there must be more data in the output - // buffer. Send the next byte - unsigned char c = _tx_buffer[_tx_buffer_tail]; - _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_TX_BUFFER_SIZE; - - *_udr = c; - - // clear the TXC bit -- "can be cleared by writing a one to its bit - // location". This makes sure flush() won't return until the bytes - // actually got written. Other r/w bits are preserved, and zeroes - // written to the rest. - -#ifdef MPCM0 - *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0); -#else - *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0))); -#endif - - if (_tx_buffer_head == _tx_buffer_tail) { - // Buffer empty, so disable interrupts - cbi(*_ucsrb, UDRIE0); - } -} - -// Public Methods ////////////////////////////////////////////////////////////// - -void HardwareSerial::begin(unsigned long baud, byte config) -{ - // Try u2x mode first - uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2; - *_ucsra = 1 << U2X0; - - // hardcoded exception for 57600 for compatibility with the bootloader - // shipped with the Duemilanove and previous boards and the firmware - // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot - // be > 4095, so switch back to non-u2x mode if the baud rate is too - // low. - if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095)) - { - *_ucsra = 0; - baud_setting = (F_CPU / 8 / baud - 1) / 2; - } - - // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register) - *_ubrrh = baud_setting >> 8; - *_ubrrl = baud_setting; - - _written = false; - - //set the data bits, parity, and stop bits -#if defined(__AVR_ATmega8__) - config |= 0x80; // select UCSRC register (shared with UBRRH) -#endif - *_ucsrc = config; - - sbi(*_ucsrb, RXEN0); - sbi(*_ucsrb, TXEN0); - sbi(*_ucsrb, RXCIE0); - cbi(*_ucsrb, UDRIE0); -} - -void HardwareSerial::end() -{ - // wait for transmission of outgoing data - flush(); - - cbi(*_ucsrb, RXEN0); - cbi(*_ucsrb, TXEN0); - cbi(*_ucsrb, RXCIE0); - cbi(*_ucsrb, UDRIE0); - - // clear any received data - _rx_buffer_head = _rx_buffer_tail; -} - -int HardwareSerial::available(void) -{ - return ((unsigned int)(SERIAL_RX_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail)) % SERIAL_RX_BUFFER_SIZE; -} - -int HardwareSerial::peek(void) -{ - if (_rx_buffer_head == _rx_buffer_tail) { - return -1; - } else { - return _rx_buffer[_rx_buffer_tail]; - } -} - -int HardwareSerial::read(void) -{ - // if the head isn't ahead of the tail, we don't have any characters - if (_rx_buffer_head == _rx_buffer_tail) { - return -1; - } else { - unsigned char c = _rx_buffer[_rx_buffer_tail]; - _rx_buffer_tail = (rx_buffer_index_t)(_rx_buffer_tail + 1) % SERIAL_RX_BUFFER_SIZE; - return c; - } -} - -int HardwareSerial::availableForWrite(void) -{ - tx_buffer_index_t head; - tx_buffer_index_t tail; - - TX_BUFFER_ATOMIC { - head = _tx_buffer_head; - tail = _tx_buffer_tail; - } - if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail; - return tail - head - 1; -} - -void HardwareSerial::flush() -{ - // If we have never written a byte, no need to flush. This special - // case is needed since there is no way to force the TXC (transmit - // complete) bit to 1 during initialization - if (!_written) - return; - - while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0)) { - if (bit_is_clear(SREG, SREG_I) && bit_is_set(*_ucsrb, UDRIE0)) - // Interrupts are globally disabled, but the DR empty - // interrupt should be enabled, so poll the DR empty flag to - // prevent deadlock - if (bit_is_set(*_ucsra, UDRE0)) - _tx_udr_empty_irq(); - } - // If we get here, nothing is queued anymore (DRIE is disabled) and - // the hardware finished tranmission (TXC is set). -} - -size_t HardwareSerial::write(uint8_t c) -{ - _written = true; - // If the buffer and the data register is empty, just write the byte - // to the data register and be done. This shortcut helps - // significantly improve the effective datarate at high (> - // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown. - if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) { - // If TXC is cleared before writing UDR and the previous byte - // completes before writing to UDR, TXC will be set but a byte - // is still being transmitted causing flush() to return too soon. - // So writing UDR must happen first. - // Writing UDR and clearing TC must be done atomically, otherwise - // interrupts might delay the TXC clear so the byte written to UDR - // is transmitted (setting TXC) before clearing TXC. Then TXC will - // be cleared when no bytes are left, causing flush() to hang - ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { - *_udr = c; -#ifdef MPCM0 - *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0); -#else - *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0))); -#endif - } - return 1; - } - tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE; - - // If the output buffer is full, there's nothing for it other than to - // wait for the interrupt handler to empty it a bit - while (i == _tx_buffer_tail) { - if (bit_is_clear(SREG, SREG_I)) { - // Interrupts are disabled, so we'll have to poll the data - // register empty flag ourselves. If it is set, pretend an - // interrupt has happened and call the handler to free up - // space for us. - if(bit_is_set(*_ucsra, UDRE0)) - _tx_udr_empty_irq(); - } else { - // nop, the interrupt handler will free up space for us - } - } - - _tx_buffer[_tx_buffer_head] = c; - - // make atomic to prevent execution of ISR between setting the - // head pointer and setting the interrupt flag resulting in buffer - // retransmission - ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { - _tx_buffer_head = i; - sbi(*_ucsrb, UDRIE0); - } - - return 1; -} - -#endif // whole file diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial0.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial0.cpp deleted file mode 100644 index 7d47ed2..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial0.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - HardwareSerial0.cpp - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus - Modified 3 December 2013 by Matthijs Kooijman -*/ - -#include "Arduino.h" -#include "HardwareSerial.h" -#include "HardwareSerial_private.h" - -// Each HardwareSerial is defined in its own file, since the linker pulls -// in the entire file when any element inside is used. --gc-sections can -// additionally cause unused symbols to be dropped, but ISRs have the -// "used" attribute so are never dropped and they keep the -// HardwareSerial instance in as well. Putting each instance in its own -// file prevents the linker from pulling in any unused instances in the -// first place. - -#if defined(HAVE_HWSERIAL0) - -#if defined(USART_RX_vect) - ISR(USART_RX_vect) -#elif defined(USART0_RX_vect) - ISR(USART0_RX_vect) -#elif defined(USART_RXC_vect) - ISR(USART_RXC_vect) // ATmega8 -#else - #error "Don't know what the Data Received vector is called for Serial" -#endif - { - Serial._rx_complete_irq(); - } - -#if defined(UART0_UDRE_vect) -ISR(UART0_UDRE_vect) -#elif defined(UART_UDRE_vect) -ISR(UART_UDRE_vect) -#elif defined(USART0_UDRE_vect) -ISR(USART0_UDRE_vect) -#elif defined(USART_UDRE_vect) -ISR(USART_UDRE_vect) -#else - #error "Don't know what the Data Register Empty vector is called for Serial" -#endif -{ - Serial._tx_udr_empty_irq(); -} - -#if defined(UBRRH) && defined(UBRRL) - HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR); -#else - HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0); -#endif - -// Function that can be weakly referenced by serialEventRun to prevent -// pulling in this file if it's not otherwise used. -bool Serial0_available() { - return Serial.available(); -} - -#endif // HAVE_HWSERIAL0 diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial1.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial1.cpp deleted file mode 100644 index a345cdb..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial1.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - HardwareSerial1.cpp - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus - Modified 3 December 2013 by Matthijs Kooijman -*/ - -#include "Arduino.h" -#include "HardwareSerial.h" -#include "HardwareSerial_private.h" - -// Each HardwareSerial is defined in its own file, since the linker pulls -// in the entire file when any element inside is used. --gc-sections can -// additionally cause unused symbols to be dropped, but ISRs have the -// "used" attribute so are never dropped and they keep the -// HardwareSerial instance in as well. Putting each instance in its own -// file prevents the linker from pulling in any unused instances in the -// first place. - -#if defined(HAVE_HWSERIAL1) - -#if defined(UART1_RX_vect) -ISR(UART1_RX_vect) -#elif defined(USART1_RX_vect) -ISR(USART1_RX_vect) -#else -#error "Don't know what the Data Register Empty vector is called for Serial1" -#endif -{ - Serial1._rx_complete_irq(); -} - -#if defined(UART1_UDRE_vect) -ISR(UART1_UDRE_vect) -#elif defined(USART1_UDRE_vect) -ISR(USART1_UDRE_vect) -#else -#error "Don't know what the Data Register Empty vector is called for Serial1" -#endif -{ - Serial1._tx_udr_empty_irq(); -} - -HardwareSerial Serial1(&UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1); - -// Function that can be weakly referenced by serialEventRun to prevent -// pulling in this file if it's not otherwise used. -bool Serial1_available() { - return Serial1.available(); -} - -#endif // HAVE_HWSERIAL1 diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial2.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial2.cpp deleted file mode 100644 index 8e433b6..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial2.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - HardwareSerial2.cpp - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus - Modified 3 December 2013 by Matthijs Kooijman -*/ - -#include "Arduino.h" -#include "HardwareSerial.h" -#include "HardwareSerial_private.h" - -// Each HardwareSerial is defined in its own file, since the linker pulls -// in the entire file when any element inside is used. --gc-sections can -// additionally cause unused symbols to be dropped, but ISRs have the -// "used" attribute so are never dropped and they keep the -// HardwareSerial instance in as well. Putting each instance in its own -// file prevents the linker from pulling in any unused instances in the -// first place. - -#if defined(HAVE_HWSERIAL2) - -ISR(USART2_RX_vect) -{ - Serial2._rx_complete_irq(); -} - -ISR(USART2_UDRE_vect) -{ - Serial2._tx_udr_empty_irq(); -} - -HardwareSerial Serial2(&UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UCSR2C, &UDR2); - -// Function that can be weakly referenced by serialEventRun to prevent -// pulling in this file if it's not otherwise used. -bool Serial2_available() { - return Serial2.available(); -} - -#endif // HAVE_HWSERIAL2 diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial3.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial3.cpp deleted file mode 100644 index 26aaee8..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/HardwareSerial3.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - HardwareSerial3.cpp - Hardware serial library for Wiring - Copyright (c) 2006 Nicholas Zambetti. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 28 September 2010 by Mark Sproul - Modified 14 August 2012 by Alarus - Modified 3 December 2013 by Matthijs Kooijman -*/ - -#include "Arduino.h" -#include "HardwareSerial.h" -#include "HardwareSerial_private.h" - -// Each HardwareSerial is defined in its own file, since the linker pulls -// in the entire file when any element inside is used. --gc-sections can -// additionally cause unused symbols to be dropped, but ISRs have the -// "used" attribute so are never dropped and they keep the -// HardwareSerial instance in as well. Putting each instance in its own -// file prevents the linker from pulling in any unused instances in the -// first place. - -#if defined(HAVE_HWSERIAL3) - -ISR(USART3_RX_vect) -{ - Serial3._rx_complete_irq(); -} - -ISR(USART3_UDRE_vect) -{ - Serial3._tx_udr_empty_irq(); -} - -HardwareSerial Serial3(&UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UCSR3C, &UDR3); - -// Function that can be weakly referenced by serialEventRun to prevent -// pulling in this file if it's not otherwise used. -bool Serial3_available() { - return Serial3.available(); -} - -#endif // HAVE_HWSERIAL3 diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/IPAddress.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/IPAddress.cpp deleted file mode 100644 index d9fe5be..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/IPAddress.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* - IPAddress.cpp - Base class that provides IPAddress - Copyright (c) 2011 Adrian McEwen. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include -#include - -IPAddress::IPAddress() -{ - _address.dword = 0; -} - -IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) -{ - _address.bytes[0] = first_octet; - _address.bytes[1] = second_octet; - _address.bytes[2] = third_octet; - _address.bytes[3] = fourth_octet; -} - -IPAddress::IPAddress(uint32_t address) -{ - _address.dword = address; -} - -IPAddress::IPAddress(const uint8_t *address) -{ - memcpy(_address.bytes, address, sizeof(_address.bytes)); -} - -bool IPAddress::fromString(const char *address) -{ - uint16_t acc = 0; // Accumulator - uint8_t dots = 0; - - while (*address) - { - char c = *address++; - if (c >= '0' && c <= '9') - { - acc = acc * 10 + (c - '0'); - if (acc > 255) { - // Value out of [0..255] range - return false; - } - } - else if (c == '.') - { - if (dots == 3) { - // Too much dots (there must be 3 dots) - return false; - } - _address.bytes[dots++] = acc; - acc = 0; - } - else - { - // Invalid char - return false; - } - } - - if (dots != 3) { - // Too few dots (there must be 3 dots) - return false; - } - _address.bytes[3] = acc; - return true; -} - -IPAddress& IPAddress::operator=(const uint8_t *address) -{ - memcpy(_address.bytes, address, sizeof(_address.bytes)); - return *this; -} - -IPAddress& IPAddress::operator=(uint32_t address) -{ - _address.dword = address; - return *this; -} - -bool IPAddress::operator==(const uint8_t* addr) const -{ - return memcmp(addr, _address.bytes, sizeof(_address.bytes)) == 0; -} - -size_t IPAddress::printTo(Print& p) const -{ - size_t n = 0; - for (int i =0; i < 3; i++) - { - n += p.print(_address.bytes[i], DEC); - n += p.print('.'); - } - n += p.print(_address.bytes[3], DEC); - return n; -} - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/PluggableUSB.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/PluggableUSB.cpp deleted file mode 100644 index c489d9f..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/PluggableUSB.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - PluggableUSB.cpp - Copyright (c) 2015 Arduino LLC - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "USBAPI.h" -#include "PluggableUSB.h" - -#if defined(USBCON) -#ifdef PLUGGABLE_USB_ENABLED - -extern uint8_t _initEndpoints[]; - -int PluggableUSB_::getInterface(uint8_t* interfaceCount) -{ - int sent = 0; - PluggableUSBModule* node; - for (node = rootNode; node; node = node->next) { - int res = node->getInterface(interfaceCount); - if (res < 0) - return -1; - sent += res; - } - return sent; -} - -int PluggableUSB_::getDescriptor(USBSetup& setup) -{ - PluggableUSBModule* node; - for (node = rootNode; node; node = node->next) { - int ret = node->getDescriptor(setup); - // ret!=0 -> request has been processed - if (ret) - return ret; - } - return 0; -} - -void PluggableUSB_::getShortName(char *iSerialNum) -{ - PluggableUSBModule* node; - for (node = rootNode; node; node = node->next) { - iSerialNum += node->getShortName(iSerialNum); - } - *iSerialNum = 0; -} - -bool PluggableUSB_::setup(USBSetup& setup) -{ - PluggableUSBModule* node; - for (node = rootNode; node; node = node->next) { - if (node->setup(setup)) { - return true; - } - } - return false; -} - -bool PluggableUSB_::plug(PluggableUSBModule *node) -{ - if ((lastEp + node->numEndpoints) > USB_ENDPOINTS) { - return false; - } - - if (!rootNode) { - rootNode = node; - } else { - PluggableUSBModule *current = rootNode; - while (current->next) { - current = current->next; - } - current->next = node; - } - - node->pluggedInterface = lastIf; - node->pluggedEndpoint = lastEp; - lastIf += node->numInterfaces; - for (uint8_t i = 0; i < node->numEndpoints; i++) { - _initEndpoints[lastEp] = node->endpointType[i]; - lastEp++; - } - return true; - // restart USB layer??? -} - -PluggableUSB_& PluggableUSB() -{ - static PluggableUSB_ obj; - return obj; -} - -PluggableUSB_::PluggableUSB_() : lastIf(CDC_ACM_INTERFACE + CDC_INTERFACE_COUNT), - lastEp(CDC_FIRST_ENDPOINT + CDC_ENPOINT_COUNT), - rootNode(NULL) -{ - // Empty -} - -#endif - -#endif /* if defined(USBCON) */ diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/PreprocessingAssembly/wiring_pulse.S b/AtmelStudio/TimerTwo/ArduinoCore/src/core/PreprocessingAssembly/wiring_pulse.S deleted file mode 100644 index 1dd22e6..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/PreprocessingAssembly/wiring_pulse.S +++ /dev/null @@ -1,178 +0,0 @@ -/* - wiring_pulse.s - pulseInASM() function in different flavours - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2014 Martino Facchin - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA -*/ - -/* - * The following routine was generated by avr-gcc 4.8.3 with the following parameters - * -gstabs -Wa,-ahlmsd=output.lst -dp -fverbose-asm -O2 - * on the original C function - * - * unsigned long pulseInSimpl(volatile uint8_t *port, uint8_t bit, uint8_t stateMask, unsigned long maxloops) - * { - * unsigned long width = 0; - * // wait for any previous pulse to end - * while ((*port & bit) == stateMask) - * if (--maxloops == 0) - * return 0; - * - * // wait for the pulse to start - * while ((*port & bit) != stateMask) - * if (--maxloops == 0) - * return 0; - * - * // wait for the pulse to stop - * while ((*port & bit) == stateMask) { - * if (++width == maxloops) - * return 0; - * } - * return width; - * } - * - * some compiler outputs were removed but the rest of the code is untouched - */ - -#include - -.section .text - -.global countPulseASM - -countPulseASM: - -.LM0: -.LFBB1: - push r12 ; ; 130 pushqi1/1 [length = 1] - push r13 ; ; 131 pushqi1/1 [length = 1] - push r14 ; ; 132 pushqi1/1 [length = 1] - push r15 ; ; 133 pushqi1/1 [length = 1] - push r16 ; ; 134 pushqi1/1 [length = 1] - push r17 ; ; 135 pushqi1/1 [length = 1] -/* prologue: function */ -/* frame size = 0 */ -/* stack size = 6 */ -.L__stack_usage = 6 - mov r30,r24 ; port, port ; 2 *movhi/1 [length = 2] - mov r31,r25 ; port, port -/* unsigned long width = 0; -*** // wait for any previous pulse to end -*** while ((*port & bit) == stateMask) -*/ -.LM1: - rjmp .L2 ; ; 181 jump [length = 1] -.L4: -/* if (--maxloops == 0) */ -.LM2: - subi r16,1 ; maxloops, ; 17 addsi3/2 [length = 4] - sbc r17, r1 ; maxloops - sbc r18, r1 ; maxloops - sbc r19, r1 ; maxloops - breq .L13 ; , ; 19 branch [length = 1] -.L2: -/* if (--maxloops == 0) */ -.LM3: - ld r25,Z ; D.1554, *port_7(D) ; 22 movqi_insn/4 [length = 1] - and r25,r22 ; D.1554, bit ; 24 andqi3/1 [length = 1] - cp r25,r20 ; D.1554, stateMask ; 25 *cmpqi/2 [length = 1] - breq .L4 ; , ; 26 branch [length = 1] - rjmp .L6 ; ; 184 jump [length = 1] -.L7: -/* return 0; -*** -*** // wait for the pulse to start -*** while ((*port & bit) != stateMask) -*** if (--maxloops == 0) -*/ -.LM4: - subi r16,1 ; maxloops, ; 31 addsi3/2 [length = 4] - sbc r17, r1 ; maxloops - sbc r18, r1 ; maxloops - sbc r19, r1 ; maxloops - breq .L13 ; , ; 33 branch [length = 1] -.L6: -/* if (--maxloops == 0) */ -.LM5: - ld r25,Z ; D.1554, *port_7(D) ; 41 movqi_insn/4 [length = 1] - and r25,r22 ; D.1554, bit ; 43 andqi3/1 [length = 1] - cpse r25,r20 ; D.1554, stateMask ; 44 enable_interrupt-3 [length = 1] - rjmp .L7 ; - mov r12, r1 ; width ; 7 *movsi/2 [length = 4] - mov r13, r1 ; width - mov r14, r1 ; width - mov r15, r1 ; width - rjmp .L9 ; ; 186 jump [length = 1] -.L10: -/* return 0; -*** -*** // wait for the pulse to stop -*** while ((*port & bit) == stateMask) { -*** if (++width == maxloops) -*/ -.LM6: - ldi r24,-1 ; , ; 50 addsi3/3 [length = 5] - sub r12,r24 ; width, - sbc r13,r24 ; width, - sbc r14,r24 ; width, - sbc r15,r24 ; width, - cp r16,r12 ; maxloops, width ; 51 *cmpsi/2 [length = 4] - cpc r17,r13 ; maxloops, width - cpc r18,r14 ; maxloops, width - cpc r19,r15 ; maxloops, width - breq .L13 ; , ; 52 branch [length = 1] -.L9: -/* if (++width == maxloops) */ -.LM7: - ld r24,Z ; D.1554, *port_7(D) ; 60 movqi_insn/4 [length = 1] - and r24,r22 ; D.1554, bit ; 62 andqi3/1 [length = 1] - cp r24,r20 ; D.1554, stateMask ; 63 *cmpqi/2 [length = 1] - breq .L10 ; , ; 64 branch [length = 1] -/* return 0; -*** } -*** return width; -*/ -.LM8: - mov r22,r12 ; D.1553, width ; 108 movqi_insn/1 [length = 1] - mov r23,r13 ; D.1553, width ; 109 movqi_insn/1 [length = 1] - mov r24,r14 ; D.1553, width ; 110 movqi_insn/1 [length = 1] - mov r25,r15 ; D.1553, width ; 111 movqi_insn/1 [length = 1] -/* epilogue start */ -.LM9: - pop r17 ; ; 171 popqi [length = 1] - pop r16 ; ; 172 popqi [length = 1] - pop r15 ; ; 173 popqi [length = 1] - pop r14 ; ; 174 popqi [length = 1] - pop r13 ; ; 175 popqi [length = 1] - pop r12 ; ; 176 popqi [length = 1] - ret ; 177 return_from_epilogue [length = 1] -.L13: -.LM10: - ldi r22,0 ; D.1553 ; 120 movqi_insn/1 [length = 1] - ldi r23,0 ; D.1553 ; 121 movqi_insn/1 [length = 1] - ldi r24,0 ; D.1553 ; 122 movqi_insn/1 [length = 1] - ldi r25,0 ; D.1553 ; 123 movqi_insn/1 [length = 1] -/* epilogue start */ -.LM11: - pop r17 ; ; 138 popqi [length = 1] - pop r16 ; ; 139 popqi [length = 1] - pop r15 ; ; 140 popqi [length = 1] - pop r14 ; ; 141 popqi [length = 1] - pop r13 ; ; 142 popqi [length = 1] - pop r12 ; ; 143 popqi [length = 1] - ret ; 144 return_from_epilogue [length = 1] diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/Print.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/Print.cpp deleted file mode 100644 index 1e4c99a..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/Print.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* - Print.cpp - Base class that provides print() and println() - Copyright (c) 2008 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Modified 23 November 2006 by David A. Mellis - Modified 03 August 2015 by Chuck Todd - */ - -#include -#include -#include -#include -#include "Arduino.h" - -#include "Print.h" - -// Public Methods ////////////////////////////////////////////////////////////// - -/* default implementation: may be overridden */ -size_t Print::write(const uint8_t *buffer, size_t size) -{ - size_t n = 0; - while (size--) { - if (write(*buffer++)) n++; - else break; - } - return n; -} - -size_t Print::print(const __FlashStringHelper *ifsh) -{ - PGM_P p = reinterpret_cast(ifsh); - size_t n = 0; - while (1) { - unsigned char c = pgm_read_byte(p++); - if (c == 0) break; - if (write(c)) n++; - else break; - } - return n; -} - -size_t Print::print(const String &s) -{ - return write(s.c_str(), s.length()); -} - -size_t Print::print(const char str[]) -{ - return write(str); -} - -size_t Print::print(char c) -{ - return write(c); -} - -size_t Print::print(unsigned char b, int base) -{ - return print((unsigned long) b, base); -} - -size_t Print::print(int n, int base) -{ - return print((long) n, base); -} - -size_t Print::print(unsigned int n, int base) -{ - return print((unsigned long) n, base); -} - -size_t Print::print(long n, int base) -{ - if (base == 0) { - return write(n); - } else if (base == 10) { - if (n < 0) { - int t = print('-'); - n = -n; - return printNumber(n, 10) + t; - } - return printNumber(n, 10); - } else { - return printNumber(n, base); - } -} - -size_t Print::print(unsigned long n, int base) -{ - if (base == 0) return write(n); - else return printNumber(n, base); -} - -size_t Print::print(double n, int digits) -{ - return printFloat(n, digits); -} - -size_t Print::println(const __FlashStringHelper *ifsh) -{ - size_t n = print(ifsh); - n += println(); - return n; -} - -size_t Print::print(const Printable& x) -{ - return x.printTo(*this); -} - -size_t Print::println(void) -{ - return write("\r\n"); -} - -size_t Print::println(const String &s) -{ - size_t n = print(s); - n += println(); - return n; -} - -size_t Print::println(const char c[]) -{ - size_t n = print(c); - n += println(); - return n; -} - -size_t Print::println(char c) -{ - size_t n = print(c); - n += println(); - return n; -} - -size_t Print::println(unsigned char b, int base) -{ - size_t n = print(b, base); - n += println(); - return n; -} - -size_t Print::println(int num, int base) -{ - size_t n = print(num, base); - n += println(); - return n; -} - -size_t Print::println(unsigned int num, int base) -{ - size_t n = print(num, base); - n += println(); - return n; -} - -size_t Print::println(long num, int base) -{ - size_t n = print(num, base); - n += println(); - return n; -} - -size_t Print::println(unsigned long num, int base) -{ - size_t n = print(num, base); - n += println(); - return n; -} - -size_t Print::println(double num, int digits) -{ - size_t n = print(num, digits); - n += println(); - return n; -} - -size_t Print::println(const Printable& x) -{ - size_t n = print(x); - n += println(); - return n; -} - -// Private Methods ///////////////////////////////////////////////////////////// - -size_t Print::printNumber(unsigned long n, uint8_t base) -{ - char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. - char *str = &buf[sizeof(buf) - 1]; - - *str = '\0'; - - // prevent crash if called with base == 1 - if (base < 2) base = 10; - - do { - char c = n % base; - n /= base; - - *--str = c < 10 ? c + '0' : c + 'A' - 10; - } while(n); - - return write(str); -} - -size_t Print::printFloat(double number, uint8_t digits) -{ - size_t n = 0; - - if (isnan(number)) return print("nan"); - if (isinf(number)) return print("inf"); - if (number > 4294967040.0) return print ("ovf"); // constant determined empirically - if (number <-4294967040.0) return print ("ovf"); // constant determined empirically - - // Handle negative numbers - if (number < 0.0) - { - n += print('-'); - number = -number; - } - - // Round correctly so that print(1.999, 2) prints as "2.00" - double rounding = 0.5; - for (uint8_t i=0; i 0) { - n += print('.'); - } - - // Extract digits from the remainder one at a time - while (digits-- > 0) - { - remainder *= 10.0; - unsigned int toPrint = (unsigned int)(remainder); - n += print(toPrint); - remainder -= toPrint; - } - - return n; -} diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/Stream.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/Stream.cpp deleted file mode 100644 index 9eff663..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/Stream.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/* - Stream.cpp - adds parsing methods to Stream class - Copyright (c) 2008 David A. Mellis. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - Created July 2011 - parsing functions based on TextFinder library by Michael Margolis - - findMulti/findUntil routines written by Jim Leonard/Xuth - */ - -#include "Arduino.h" -#include "Stream.h" - -#define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait - -// protected method to read stream with timeout -int Stream::timedRead() -{ - int c; - _startMillis = millis(); - do { - c = read(); - if (c >= 0) return c; - } while(millis() - _startMillis < _timeout); - return -1; // -1 indicates timeout -} - -// protected method to peek stream with timeout -int Stream::timedPeek() -{ - int c; - _startMillis = millis(); - do { - c = peek(); - if (c >= 0) return c; - } while(millis() - _startMillis < _timeout); - return -1; // -1 indicates timeout -} - -// returns peek of the next digit in the stream or -1 if timeout -// discards non-numeric characters -int Stream::peekNextDigit(LookaheadMode lookahead, bool detectDecimal) -{ - int c; - while (1) { - c = timedPeek(); - - if( c < 0 || - c == '-' || - (c >= '0' && c <= '9') || - (detectDecimal && c == '.')) return c; - - switch( lookahead ){ - case SKIP_NONE: return -1; // Fail code. - case SKIP_WHITESPACE: - switch( c ){ - case ' ': - case '\t': - case '\r': - case '\n': break; - default: return -1; // Fail code. - } - case SKIP_ALL: - break; - } - read(); // discard non-numeric - } -} - -// Public Methods -////////////////////////////////////////////////////////////// - -void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait -{ - _timeout = timeout; -} - - // find returns true if the target string is found -bool Stream::find(char *target) -{ - return findUntil(target, strlen(target), NULL, 0); -} - -// reads data from the stream until the target string of given length is found -// returns true if target string is found, false if timed out -bool Stream::find(char *target, size_t length) -{ - return findUntil(target, length, NULL, 0); -} - -// as find but search ends if the terminator string is found -bool Stream::findUntil(char *target, char *terminator) -{ - return findUntil(target, strlen(target), terminator, strlen(terminator)); -} - -// reads data from the stream until the target string of the given length is found -// search terminated if the terminator string is found -// returns true if target string is found, false if terminated or timed out -bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen) -{ - if (terminator == NULL) { - MultiTarget t[1] = {{target, targetLen, 0}}; - return findMulti(t, 1) == 0 ? true : false; - } else { - MultiTarget t[2] = {{target, targetLen, 0}, {terminator, termLen, 0}}; - return findMulti(t, 2) == 0 ? true : false; - } -} - -// returns the first valid (long) integer value from the current position. -// lookahead determines how parseInt looks ahead in the stream. -// See LookaheadMode enumeration at the top of the file. -// Lookahead is terminated by the first character that is not a valid part of an integer. -// Once parsing commences, 'ignore' will be skipped in the stream. -long Stream::parseInt(LookaheadMode lookahead, char ignore) -{ - bool isNegative = false; - long value = 0; - int c; - - c = peekNextDigit(lookahead, false); - // ignore non numeric leading characters - if(c < 0) - return 0; // zero returned if timeout - - do{ - if(c == ignore) - ; // ignore this character - else if(c == '-') - isNegative = true; - else if(c >= '0' && c <= '9') // is c a digit? - value = value * 10 + c - '0'; - read(); // consume the character we got with peek - c = timedPeek(); - } - while( (c >= '0' && c <= '9') || c == ignore ); - - if(isNegative) - value = -value; - return value; -} - -// as parseInt but returns a floating point value -float Stream::parseFloat(LookaheadMode lookahead, char ignore) -{ - bool isNegative = false; - bool isFraction = false; - long value = 0; - int c; - float fraction = 1.0; - - c = peekNextDigit(lookahead, true); - // ignore non numeric leading characters - if(c < 0) - return 0; // zero returned if timeout - - do{ - if(c == ignore) - ; // ignore - else if(c == '-') - isNegative = true; - else if (c == '.') - isFraction = true; - else if(c >= '0' && c <= '9') { // is c a digit? - value = value * 10 + c - '0'; - if(isFraction) - fraction *= 0.1; - } - read(); // consume the character we got with peek - c = timedPeek(); - } - while( (c >= '0' && c <= '9') || (c == '.' && !isFraction) || c == ignore ); - - if(isNegative) - value = -value; - if(isFraction) - return value * fraction; - else - return value; -} - -// read characters from stream into buffer -// terminates if length characters have been read, or timeout (see setTimeout) -// returns the number of characters placed in the buffer -// the buffer is NOT null terminated. -// -size_t Stream::readBytes(char *buffer, size_t length) -{ - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) break; - *buffer++ = (char)c; - count++; - } - return count; -} - - -// as readBytes with terminator character -// terminates if length characters have been read, timeout, or if the terminator character detected -// returns the number of characters placed in the buffer (0 means no valid data found) - -size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) -{ - size_t index = 0; - while (index < length) { - int c = timedRead(); - if (c < 0 || c == terminator) break; - *buffer++ = (char)c; - index++; - } - return index; // return number of characters, not including null terminator -} - -String Stream::readString() -{ - String ret; - int c = timedRead(); - while (c >= 0) - { - ret += (char)c; - c = timedRead(); - } - return ret; -} - -String Stream::readStringUntil(char terminator) -{ - String ret; - int c = timedRead(); - while (c >= 0 && c != terminator) - { - ret += (char)c; - c = timedRead(); - } - return ret; -} - -int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) { - // any zero length target string automatically matches and would make - // a mess of the rest of the algorithm. - for (struct MultiTarget *t = targets; t < targets+tCount; ++t) { - if (t->len <= 0) - return t - targets; - } - - while (1) { - int c = timedRead(); - if (c < 0) - return -1; - - for (struct MultiTarget *t = targets; t < targets+tCount; ++t) { - // the simple case is if we match, deal with that first. - if (c == t->str[t->index]) { - if (++t->index == t->len) - return t - targets; - else - continue; - } - - // if not we need to walk back and see if we could have matched further - // down the stream (ie '1112' doesn't match the first position in '11112' - // but it will match the second position so we can't just reset the current - // index to 0 when we find a mismatch. - if (t->index == 0) - continue; - - int origIndex = t->index; - do { - --t->index; - // first check if current char works against the new current index - if (c != t->str[t->index]) - continue; - - // if it's the only char then we're good, nothing more to check - if (t->index == 0) { - t->index++; - break; - } - - // otherwise we need to check the rest of the found string - int diff = origIndex - t->index; - size_t i; - for (i = 0; i < t->index; ++i) { - if (t->str[i] != t->str[i + diff]) - break; - } - - // if we successfully got through the previous loop then our current - // index is good. - if (i == t->index) { - t->index++; - break; - } - - // otherwise we just try the next index - } while (t->index); - } - } - // unreachable - return -1; -} diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/Tone.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/Tone.cpp deleted file mode 100644 index 1bfb3e3..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/Tone.cpp +++ /dev/null @@ -1,619 +0,0 @@ -/* Tone.cpp - - A Tone Generator Library - - Written by Brett Hagman - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -Version Modified By Date Comments -------- ----------- -------- -------- -0001 B Hagman 09/08/02 Initial coding -0002 B Hagman 09/08/18 Multiple pins -0003 B Hagman 09/08/18 Moved initialization from constructor to begin() -0004 B Hagman 09/09/26 Fixed problems with ATmega8 -0005 B Hagman 09/11/23 Scanned prescalars for best fit on 8 bit timers - 09/11/25 Changed pin toggle method to XOR - 09/11/25 Fixed timer0 from being excluded -0006 D Mellis 09/12/29 Replaced objects with functions -0007 M Sproul 10/08/29 Changed #ifdefs from cpu to register -0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY -0009 J Reucker 15/04/10 Issue #292 Fixed problems with ATmega8 (thanks to Pete62) -0010 jipp 15/04/13 added additional define check #2923 -*************************************************/ - -#include -#include -#include "Arduino.h" -#include "pins_arduino.h" - -#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__) -#define TCCR2A TCCR2 -#define TCCR2B TCCR2 -#define COM2A1 COM21 -#define COM2A0 COM20 -#define OCR2A OCR2 -#define TIMSK2 TIMSK -#define OCIE2A OCIE2 -#define TIMER2_COMPA_vect TIMER2_COMP_vect -#define TIMSK1 TIMSK -#endif - -// timerx_toggle_count: -// > 0 - duration specified -// = 0 - stopped -// < 0 - infinitely (until stop() method called, or new play() called) - -#if !defined(__AVR_ATmega8__) -volatile long timer0_toggle_count; -volatile uint8_t *timer0_pin_port; -volatile uint8_t timer0_pin_mask; -#endif - -volatile long timer1_toggle_count; -volatile uint8_t *timer1_pin_port; -volatile uint8_t timer1_pin_mask; -volatile long timer2_toggle_count; -volatile uint8_t *timer2_pin_port; -volatile uint8_t timer2_pin_mask; - -#if defined(TIMSK3) -volatile long timer3_toggle_count; -volatile uint8_t *timer3_pin_port; -volatile uint8_t timer3_pin_mask; -#endif - -#if defined(TIMSK4) -volatile long timer4_toggle_count; -volatile uint8_t *timer4_pin_port; -volatile uint8_t timer4_pin_mask; -#endif - -#if defined(TIMSK5) -volatile long timer5_toggle_count; -volatile uint8_t *timer5_pin_port; -volatile uint8_t timer5_pin_mask; -#endif - - -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - -#define AVAILABLE_TONE_PINS 1 -#define USE_TIMER2 - -const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 3, 4, 5, 1, 0 */ }; -static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255, 255, 255, 255 */ }; - -#elif defined(__AVR_ATmega8__) - -#define AVAILABLE_TONE_PINS 1 -#define USE_TIMER2 - -const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1 */ }; -static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; - -#elif defined(__AVR_ATmega32U4__) - -#define AVAILABLE_TONE_PINS 1 -#define USE_TIMER3 - -const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ }; -static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; - -#else - -#define AVAILABLE_TONE_PINS 1 -#define USE_TIMER2 - -// Leave timer 0 to last. -const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ }; -static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ }; - -#endif - - - -static int8_t toneBegin(uint8_t _pin) -{ - int8_t _timer = -1; - - // if we're already using the pin, the timer should be configured. - for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { - if (tone_pins[i] == _pin) { - return pgm_read_byte(tone_pin_to_timer_PGM + i); - } - } - - // search for an unused timer. - for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { - if (tone_pins[i] == 255) { - tone_pins[i] = _pin; - _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); - break; - } - } - - if (_timer != -1) - { - // Set timer specific stuff - // All timers in CTC mode - // 8 bit timers will require changing prescalar values, - // whereas 16 bit timers are set to either ck/1 or ck/64 prescalar - switch (_timer) - { - #if defined(TCCR0A) && defined(TCCR0B) && defined(WGM01) - case 0: - // 8 bit timer - TCCR0A = 0; - TCCR0B = 0; - bitWrite(TCCR0A, WGM01, 1); - bitWrite(TCCR0B, CS00, 1); - timer0_pin_port = portOutputRegister(digitalPinToPort(_pin)); - timer0_pin_mask = digitalPinToBitMask(_pin); - break; - #endif - - #if defined(TCCR1A) && defined(TCCR1B) && defined(WGM12) - case 1: - // 16 bit timer - TCCR1A = 0; - TCCR1B = 0; - bitWrite(TCCR1B, WGM12, 1); - bitWrite(TCCR1B, CS10, 1); - timer1_pin_port = portOutputRegister(digitalPinToPort(_pin)); - timer1_pin_mask = digitalPinToBitMask(_pin); - break; - #endif - - #if defined(TCCR2A) && defined(TCCR2B) - case 2: - // 8 bit timer - TCCR2A = 0; - TCCR2B = 0; - bitWrite(TCCR2A, WGM21, 1); - bitWrite(TCCR2B, CS20, 1); - timer2_pin_port = portOutputRegister(digitalPinToPort(_pin)); - timer2_pin_mask = digitalPinToBitMask(_pin); - break; - #endif - - #if defined(TCCR3A) && defined(TCCR3B) && defined(TIMSK3) - case 3: - // 16 bit timer - TCCR3A = 0; - TCCR3B = 0; - bitWrite(TCCR3B, WGM32, 1); - bitWrite(TCCR3B, CS30, 1); - timer3_pin_port = portOutputRegister(digitalPinToPort(_pin)); - timer3_pin_mask = digitalPinToBitMask(_pin); - break; - #endif - - #if defined(TCCR4A) && defined(TCCR4B) && defined(TIMSK4) - case 4: - // 16 bit timer - TCCR4A = 0; - TCCR4B = 0; - #if defined(WGM42) - bitWrite(TCCR4B, WGM42, 1); - #elif defined(CS43) - // TODO this may not be correct - // atmega32u4 - bitWrite(TCCR4B, CS43, 1); - #endif - bitWrite(TCCR4B, CS40, 1); - timer4_pin_port = portOutputRegister(digitalPinToPort(_pin)); - timer4_pin_mask = digitalPinToBitMask(_pin); - break; - #endif - - #if defined(TCCR5A) && defined(TCCR5B) && defined(TIMSK5) - case 5: - // 16 bit timer - TCCR5A = 0; - TCCR5B = 0; - bitWrite(TCCR5B, WGM52, 1); - bitWrite(TCCR5B, CS50, 1); - timer5_pin_port = portOutputRegister(digitalPinToPort(_pin)); - timer5_pin_mask = digitalPinToBitMask(_pin); - break; - #endif - } - } - - return _timer; -} - - - -// frequency (in hertz) and duration (in milliseconds). - -void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) -{ - uint8_t prescalarbits = 0b001; - long toggle_count = 0; - uint32_t ocr = 0; - int8_t _timer; - - _timer = toneBegin(_pin); - - if (_timer >= 0) - { - // Set the pinMode as OUTPUT - pinMode(_pin, OUTPUT); - - // if we are using an 8 bit timer, scan through prescalars to find the best fit - if (_timer == 0 || _timer == 2) - { - ocr = F_CPU / frequency / 2 - 1; - prescalarbits = 0b001; // ck/1: same for both timers - if (ocr > 255) - { - ocr = F_CPU / frequency / 2 / 8 - 1; - prescalarbits = 0b010; // ck/8: same for both timers - - if (_timer == 2 && ocr > 255) - { - ocr = F_CPU / frequency / 2 / 32 - 1; - prescalarbits = 0b011; - } - - if (ocr > 255) - { - ocr = F_CPU / frequency / 2 / 64 - 1; - prescalarbits = _timer == 0 ? 0b011 : 0b100; - - if (_timer == 2 && ocr > 255) - { - ocr = F_CPU / frequency / 2 / 128 - 1; - prescalarbits = 0b101; - } - - if (ocr > 255) - { - ocr = F_CPU / frequency / 2 / 256 - 1; - prescalarbits = _timer == 0 ? 0b100 : 0b110; - if (ocr > 255) - { - // can't do any better than /1024 - ocr = F_CPU / frequency / 2 / 1024 - 1; - prescalarbits = _timer == 0 ? 0b101 : 0b111; - } - } - } - } - -#if defined(TCCR0B) - if (_timer == 0) - { - TCCR0B = (TCCR0B & 0b11111000) | prescalarbits; - } - else -#endif -#if defined(TCCR2B) - { - TCCR2B = (TCCR2B & 0b11111000) | prescalarbits; - } -#else - { - // dummy place holder to make the above ifdefs work - } -#endif - } - else - { - // two choices for the 16 bit timers: ck/1 or ck/64 - ocr = F_CPU / frequency / 2 - 1; - - prescalarbits = 0b001; - if (ocr > 0xffff) - { - ocr = F_CPU / frequency / 2 / 64 - 1; - prescalarbits = 0b011; - } - - if (_timer == 1) - { -#if defined(TCCR1B) - TCCR1B = (TCCR1B & 0b11111000) | prescalarbits; -#endif - } -#if defined(TCCR3B) - else if (_timer == 3) - TCCR3B = (TCCR3B & 0b11111000) | prescalarbits; -#endif -#if defined(TCCR4B) - else if (_timer == 4) - TCCR4B = (TCCR4B & 0b11111000) | prescalarbits; -#endif -#if defined(TCCR5B) - else if (_timer == 5) - TCCR5B = (TCCR5B & 0b11111000) | prescalarbits; -#endif - - } - - - // Calculate the toggle count - if (duration > 0) - { - toggle_count = 2 * frequency * duration / 1000; - } - else - { - toggle_count = -1; - } - - // Set the OCR for the given timer, - // set the toggle count, - // then turn on the interrupts - switch (_timer) - { - -#if defined(OCR0A) && defined(TIMSK0) && defined(OCIE0A) - case 0: - OCR0A = ocr; - timer0_toggle_count = toggle_count; - bitWrite(TIMSK0, OCIE0A, 1); - break; -#endif - - case 1: -#if defined(OCR1A) && defined(TIMSK1) && defined(OCIE1A) - OCR1A = ocr; - timer1_toggle_count = toggle_count; - bitWrite(TIMSK1, OCIE1A, 1); -#elif defined(OCR1A) && defined(TIMSK) && defined(OCIE1A) - // this combination is for at least the ATmega32 - OCR1A = ocr; - timer1_toggle_count = toggle_count; - bitWrite(TIMSK, OCIE1A, 1); -#endif - break; - -#if defined(OCR2A) && defined(TIMSK2) && defined(OCIE2A) - case 2: - OCR2A = ocr; - timer2_toggle_count = toggle_count; - bitWrite(TIMSK2, OCIE2A, 1); - break; -#endif - -#if defined(OCR3A) && defined(TIMSK3) && defined(OCIE3A) - case 3: - OCR3A = ocr; - timer3_toggle_count = toggle_count; - bitWrite(TIMSK3, OCIE3A, 1); - break; -#endif - -#if defined(OCR4A) && defined(TIMSK4) && defined(OCIE4A) - case 4: - OCR4A = ocr; - timer4_toggle_count = toggle_count; - bitWrite(TIMSK4, OCIE4A, 1); - break; -#endif - -#if defined(OCR5A) && defined(TIMSK5) && defined(OCIE5A) - case 5: - OCR5A = ocr; - timer5_toggle_count = toggle_count; - bitWrite(TIMSK5, OCIE5A, 1); - break; -#endif - - } - } -} - - -// XXX: this function only works properly for timer 2 (the only one we use -// currently). for the others, it should end the tone, but won't restore -// proper PWM functionality for the timer. -void disableTimer(uint8_t _timer) -{ - switch (_timer) - { - case 0: - #if defined(TIMSK0) - TIMSK0 = 0; - #elif defined(TIMSK) - TIMSK = 0; // atmega32 - #endif - break; - -#if defined(TIMSK1) && defined(OCIE1A) - case 1: - bitWrite(TIMSK1, OCIE1A, 0); - break; -#endif - - case 2: - #if defined(TIMSK2) && defined(OCIE2A) - bitWrite(TIMSK2, OCIE2A, 0); // disable interrupt - #endif - #if defined(TCCR2A) && defined(WGM20) - TCCR2A = (1 << WGM20); - #endif - #if defined(TCCR2B) && defined(CS22) - TCCR2B = (TCCR2B & 0b11111000) | (1 << CS22); - #endif - #if defined(OCR2A) - OCR2A = 0; - #endif - break; - -#if defined(TIMSK3) && defined(OCIE3A) - case 3: - bitWrite(TIMSK3, OCIE3A, 0); - break; -#endif - -#if defined(TIMSK4) && defined(OCIE4A) - case 4: - bitWrite(TIMSK4, OCIE4A, 0); - break; -#endif - -#if defined(TIMSK5) && defined(OCIE5A) - case 5: - bitWrite(TIMSK5, OCIE5A, 0); - break; -#endif - } -} - - -void noTone(uint8_t _pin) -{ - int8_t _timer = -1; - - for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { - if (tone_pins[i] == _pin) { - _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); - tone_pins[i] = 255; - break; - } - } - - disableTimer(_timer); - - digitalWrite(_pin, 0); -} - -#ifdef USE_TIMER0 -ISR(TIMER0_COMPA_vect) -{ - if (timer0_toggle_count != 0) - { - // toggle the pin - *timer0_pin_port ^= timer0_pin_mask; - - if (timer0_toggle_count > 0) - timer0_toggle_count--; - } - else - { - disableTimer(0); - *timer0_pin_port &= ~(timer0_pin_mask); // keep pin low after stop - } -} -#endif - - -#ifdef USE_TIMER1 -ISR(TIMER1_COMPA_vect) -{ - if (timer1_toggle_count != 0) - { - // toggle the pin - *timer1_pin_port ^= timer1_pin_mask; - - if (timer1_toggle_count > 0) - timer1_toggle_count--; - } - else - { - disableTimer(1); - *timer1_pin_port &= ~(timer1_pin_mask); // keep pin low after stop - } -} -#endif - - -#ifdef USE_TIMER2 -ISR(TIMER2_COMPA_vect) -{ - - if (timer2_toggle_count != 0) - { - // toggle the pin - *timer2_pin_port ^= timer2_pin_mask; - - if (timer2_toggle_count > 0) - timer2_toggle_count--; - } - else - { - // need to call noTone() so that the tone_pins[] entry is reset, so the - // timer gets initialized next time we call tone(). - // XXX: this assumes timer 2 is always the first one used. - noTone(tone_pins[0]); -// disableTimer(2); -// *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop - } -} -#endif - - -#ifdef USE_TIMER3 -ISR(TIMER3_COMPA_vect) -{ - if (timer3_toggle_count != 0) - { - // toggle the pin - *timer3_pin_port ^= timer3_pin_mask; - - if (timer3_toggle_count > 0) - timer3_toggle_count--; - } - else - { - disableTimer(3); - *timer3_pin_port &= ~(timer3_pin_mask); // keep pin low after stop - } -} -#endif - - -#ifdef USE_TIMER4 -ISR(TIMER4_COMPA_vect) -{ - if (timer4_toggle_count != 0) - { - // toggle the pin - *timer4_pin_port ^= timer4_pin_mask; - - if (timer4_toggle_count > 0) - timer4_toggle_count--; - } - else - { - disableTimer(4); - *timer4_pin_port &= ~(timer4_pin_mask); // keep pin low after stop - } -} -#endif - - -#ifdef USE_TIMER5 -ISR(TIMER5_COMPA_vect) -{ - if (timer5_toggle_count != 0) - { - // toggle the pin - *timer5_pin_port ^= timer5_pin_mask; - - if (timer5_toggle_count > 0) - timer5_toggle_count--; - } - else - { - disableTimer(5); - *timer5_pin_port &= ~(timer5_pin_mask); // keep pin low after stop - } -} -#endif diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/USBCore.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/USBCore.cpp deleted file mode 100644 index dc6bc38..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/USBCore.cpp +++ /dev/null @@ -1,863 +0,0 @@ - - -/* Copyright (c) 2010, Peter Barrett -** Sleep/Wakeup support added by Michael Dreher -** -** Permission to use, copy, modify, and/or distribute this software for -** any purpose with or without fee is hereby granted, provided that the -** above copyright notice and this permission notice appear in all copies. -** -** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL -** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR -** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS -** SOFTWARE. -*/ - -#include "USBAPI.h" -#include "PluggableUSB.h" -#include - -#if defined(USBCON) - -/** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */ -#define TX_RX_LED_PULSE_MS 100 -volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */ -volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */ - -//================================================================== -//================================================================== - -extern const u16 STRING_LANGUAGE[] PROGMEM; -extern const u8 STRING_PRODUCT[] PROGMEM; -extern const u8 STRING_MANUFACTURER[] PROGMEM; -extern const DeviceDescriptor USB_DeviceDescriptorIAD PROGMEM; - -const u16 STRING_LANGUAGE[2] = { - (3<<8) | (2+2), - 0x0409 // English -}; - -#ifndef USB_PRODUCT -// If no product is provided, use USB IO Board -#define USB_PRODUCT "USB IO Board" -#endif - -const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT; - -#if USB_VID == 0x2341 -# if defined(USB_MANUFACTURER) -# undef USB_MANUFACTURER -# endif -# define USB_MANUFACTURER "Arduino LLC" -#elif USB_VID == 0x1b4f -# if defined(USB_MANUFACTURER) -# undef USB_MANUFACTURER -# endif -# define USB_MANUFACTURER "SparkFun" -#elif !defined(USB_MANUFACTURER) -// Fall through to unknown if no manufacturer name was provided in a macro -# define USB_MANUFACTURER "Unknown" -#endif - -const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER; - - -#define DEVICE_CLASS 0x02 - -// DEVICE DESCRIPTOR -const DeviceDescriptor USB_DeviceDescriptorIAD = - D_DEVICE(0xEF,0x02,0x01,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,ISERIAL,1); - -//================================================================== -//================================================================== - -volatile u8 _usbConfiguration = 0; -volatile u8 _usbCurrentStatus = 0; // meaning of bits see usb_20.pdf, Figure 9-4. Information Returned by a GetStatus() Request to a Device -volatile u8 _usbSuspendState = 0; // copy of UDINT to check SUSPI and WAKEUPI bits - -static inline void WaitIN(void) -{ - while (!(UEINTX & (1< len) { - n = len; - } - - { - LockEP lock(ep); - // Frame may have been released by the SOF interrupt handler - if (!ReadWriteAllowed()) - continue; - - len -= n; - if (ep & TRANSFER_ZERO) - { - while (n--) - Send8(0); - } - else if (ep & TRANSFER_PGM) - { - while (n--) - Send8(pgm_read_byte(data++)); - } - else - { - while (n--) - Send8(*data++); - } - - if (sendZlp) { - ReleaseTX(); - sendZlp = false; - } else if (!ReadWriteAllowed()) { // ...release if buffer is full... - ReleaseTX(); - if (len == 0) sendZlp = true; - } else if ((len == 0) && (ep & TRANSFER_RELEASE)) { // ...or if forced with TRANSFER_RELEASE - // XXX: TRANSFER_RELEASE is never used can be removed? - ReleaseTX(); - } - } - } - TXLED1; // light the TX LED - TxLEDPulse = TX_RX_LED_PULSE_MS; - return r; -} - -u8 _initEndpoints[USB_ENDPOINTS] = -{ - 0, // Control Endpoint - - EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM - EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT - EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN - - // Following endpoints are automatically initialized to 0 -}; - -#define EP_SINGLE_64 0x32 // EP0 -#define EP_DOUBLE_64 0x36 // Other endpoints -#define EP_SINGLE_16 0x12 - -static -void InitEP(u8 index, u8 type, u8 size) -{ - UENUM = index; - UECONX = (1< 64){ - recvLength = 64; - } - - // Write data to fit to the end (not the beginning) of the array - WaitOUT(); - Recv((u8*)d + len - length, recvLength); - ClearOUT(); - length -= recvLength; - } - return len; -} - -static u8 SendInterfaces() -{ - u8 interfaces = 0; - - CDC_GetInterface(&interfaces); - -#ifdef PLUGGABLE_USB_ENABLED - PluggableUSB().getInterface(&interfaces); -#endif - - return interfaces; -} - -// Construct a dynamic configuration descriptor -// This really needs dynamic endpoint allocation etc -// TODO -static -bool SendConfiguration(int maxlen) -{ - // Count and measure interfaces - InitControl(0); - u8 interfaces = SendInterfaces(); - ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces); - - // Now send them - InitControl(maxlen); - USB_SendControl(0,&config,sizeof(ConfigDescriptor)); - SendInterfaces(); - return true; -} - -static -bool SendDescriptor(USBSetup& setup) -{ - u8 t = setup.wValueH; - if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t) - return SendConfiguration(setup.wLength); - - InitControl(setup.wLength); -#ifdef PLUGGABLE_USB_ENABLED - int ret = PluggableUSB().getDescriptor(setup); - if (ret != 0) { - return (ret > 0 ? true : false); - } -#endif - - const u8* desc_addr = 0; - if (USB_DEVICE_DESCRIPTOR_TYPE == t) - { - desc_addr = (const u8*)&USB_DeviceDescriptorIAD; - } - else if (USB_STRING_DESCRIPTOR_TYPE == t) - { - if (setup.wValueL == 0) { - desc_addr = (const u8*)&STRING_LANGUAGE; - } - else if (setup.wValueL == IPRODUCT) { - return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT), TRANSFER_PGM); - } - else if (setup.wValueL == IMANUFACTURER) { - return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER), TRANSFER_PGM); - } - else if (setup.wValueL == ISERIAL) { -#ifdef PLUGGABLE_USB_ENABLED - char name[ISERIAL_MAX_LEN]; - PluggableUSB().getShortName(name); - return USB_SendStringDescriptor((uint8_t*)name, strlen(name), 0); -#endif - } - else - return false; - } - - if (desc_addr == 0) - return false; - u8 desc_length = pgm_read_byte(desc_addr); - - USB_SendControl(TRANSFER_PGM,desc_addr,desc_length); - return true; -} - -// Endpoint 0 interrupt -ISR(USB_COM_vect) -{ - SetEP(0); - if (!ReceivedSetupInt()) - return; - - USBSetup setup; - Recv((u8*)&setup,8); - ClearSetupInt(); - - u8 requestType = setup.bmRequestType; - if (requestType & REQUEST_DEVICETOHOST) - WaitIN(); - else - ClearIN(); - - bool ok = true; - if (REQUEST_STANDARD == (requestType & REQUEST_TYPE)) - { - // Standard Requests - u8 r = setup.bRequest; - u16 wValue = setup.wValueL | (setup.wValueH << 8); - if (GET_STATUS == r) - { - if (requestType == (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_DEVICE)) - { - Send8(_usbCurrentStatus); - Send8(0); - } - else - { - // TODO: handle the HALT state of an endpoint here - // see "Figure 9-6. Information Returned by a GetStatus() Request to an Endpoint" in usb_20.pdf for more information - Send8(0); - Send8(0); - } - } - else if (CLEAR_FEATURE == r) - { - if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE)) - && (wValue == DEVICE_REMOTE_WAKEUP)) - { - _usbCurrentStatus &= ~FEATURE_REMOTE_WAKEUP_ENABLED; - } - } - else if (SET_FEATURE == r) - { - if((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE)) - && (wValue == DEVICE_REMOTE_WAKEUP)) - { - _usbCurrentStatus |= FEATURE_REMOTE_WAKEUP_ENABLED; - } - } - else if (SET_ADDRESS == r) - { - WaitIN(); - UDADDR = setup.wValueL | (1< -#include -#include -#include -#include - -#include "wiring_private.h" - -static void nothing(void) { -} - -static volatile voidFuncPtr intFunc[EXTERNAL_NUM_INTERRUPTS] = { -#if EXTERNAL_NUM_INTERRUPTS > 8 - #warning There are more than 8 external interrupts. Some callbacks may not be initialized. - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 7 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 6 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 5 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 4 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 3 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 2 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 1 - nothing, -#endif -#if EXTERNAL_NUM_INTERRUPTS > 0 - nothing, -#endif -}; - -void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode) { - if(interruptNum < EXTERNAL_NUM_INTERRUPTS) { - intFunc[interruptNum] = userFunc; - - // Configure the interrupt mode (trigger on low input, any change, rising - // edge, or falling edge). The mode constants were chosen to correspond - // to the configuration bits in the hardware register, so we simply shift - // the mode into place. - - // Enable the interrupt. - - switch (interruptNum) { -#if defined(__AVR_ATmega32U4__) - // I hate doing this, but the register assignment differs between the 1280/2560 - // and the 32U4. Since avrlib defines registers PCMSK1 and PCMSK2 that aren't - // even present on the 32U4 this is the only way to distinguish between them. - case 0: - EICRA = (EICRA & ~((1<= howbig) { - return howsmall; - } - long diff = howbig - howsmall; - return random(diff) + howsmall; -} - -long map(long x, long in_min, long in_max, long out_min, long out_max) -{ - return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; -} - -unsigned int makeWord(unsigned int w) { return w; } -unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; } diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/WString.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/WString.cpp deleted file mode 100644 index 043fda7..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/WString.cpp +++ /dev/null @@ -1,750 +0,0 @@ -/* - WString.cpp - String library for Wiring & Arduino - ...mostly rewritten by Paul Stoffregen... - Copyright (c) 2009-10 Hernando Barragan. All rights reserved. - Copyright 2011, Paul Stoffregen, paul@pjrc.com - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "WString.h" - -/*********************************************/ -/* Constructors */ -/*********************************************/ - -String::String(const char *cstr) -{ - init(); - if (cstr) copy(cstr, strlen(cstr)); -} - -String::String(const String &value) -{ - init(); - *this = value; -} - -String::String(const __FlashStringHelper *pstr) -{ - init(); - *this = pstr; -} - -#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) -String::String(String &&rval) -{ - init(); - move(rval); -} -String::String(StringSumHelper &&rval) -{ - init(); - move(rval); -} -#endif - -String::String(char c) -{ - init(); - char buf[2]; - buf[0] = c; - buf[1] = 0; - *this = buf; -} - -String::String(unsigned char value, unsigned char base) -{ - init(); - char buf[1 + 8 * sizeof(unsigned char)]; - utoa(value, buf, base); - *this = buf; -} - -String::String(int value, unsigned char base) -{ - init(); - char buf[2 + 8 * sizeof(int)]; - itoa(value, buf, base); - *this = buf; -} - -String::String(unsigned int value, unsigned char base) -{ - init(); - char buf[1 + 8 * sizeof(unsigned int)]; - utoa(value, buf, base); - *this = buf; -} - -String::String(long value, unsigned char base) -{ - init(); - char buf[2 + 8 * sizeof(long)]; - ltoa(value, buf, base); - *this = buf; -} - -String::String(unsigned long value, unsigned char base) -{ - init(); - char buf[1 + 8 * sizeof(unsigned long)]; - ultoa(value, buf, base); - *this = buf; -} - -String::String(float value, unsigned char decimalPlaces) -{ - init(); - char buf[33]; - *this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf); -} - -String::String(double value, unsigned char decimalPlaces) -{ - init(); - char buf[33]; - *this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf); -} - -String::~String() -{ - if (buffer) free(buffer); -} - -/*********************************************/ -/* Memory Management */ -/*********************************************/ - -inline void String::init(void) -{ - buffer = NULL; - capacity = 0; - len = 0; -} - -void String::invalidate(void) -{ - if (buffer) free(buffer); - buffer = NULL; - capacity = len = 0; -} - -unsigned char String::reserve(unsigned int size) -{ - if (buffer && capacity >= size) return 1; - if (changeBuffer(size)) { - if (len == 0) buffer[0] = 0; - return 1; - } - return 0; -} - -unsigned char String::changeBuffer(unsigned int maxStrLen) -{ - char *newbuffer = (char *)realloc(buffer, maxStrLen + 1); - if (newbuffer) { - buffer = newbuffer; - capacity = maxStrLen; - return 1; - } - return 0; -} - -/*********************************************/ -/* Copy and Move */ -/*********************************************/ - -String & String::copy(const char *cstr, unsigned int length) -{ - if (!reserve(length)) { - invalidate(); - return *this; - } - len = length; - strcpy(buffer, cstr); - return *this; -} - -String & String::copy(const __FlashStringHelper *pstr, unsigned int length) -{ - if (!reserve(length)) { - invalidate(); - return *this; - } - len = length; - strcpy_P(buffer, (PGM_P)pstr); - return *this; -} - -#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) -void String::move(String &rhs) -{ - if (buffer) { - if (rhs && capacity >= rhs.len) { - strcpy(buffer, rhs.buffer); - len = rhs.len; - rhs.len = 0; - return; - } else { - free(buffer); - } - } - buffer = rhs.buffer; - capacity = rhs.capacity; - len = rhs.len; - rhs.buffer = NULL; - rhs.capacity = 0; - rhs.len = 0; -} -#endif - -String & String::operator = (const String &rhs) -{ - if (this == &rhs) return *this; - - if (rhs.buffer) copy(rhs.buffer, rhs.len); - else invalidate(); - - return *this; -} - -#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) -String & String::operator = (String &&rval) -{ - if (this != &rval) move(rval); - return *this; -} - -String & String::operator = (StringSumHelper &&rval) -{ - if (this != &rval) move(rval); - return *this; -} -#endif - -String & String::operator = (const char *cstr) -{ - if (cstr) copy(cstr, strlen(cstr)); - else invalidate(); - - return *this; -} - -String & String::operator = (const __FlashStringHelper *pstr) -{ - if (pstr) copy(pstr, strlen_P((PGM_P)pstr)); - else invalidate(); - - return *this; -} - -/*********************************************/ -/* concat */ -/*********************************************/ - -unsigned char String::concat(const String &s) -{ - return concat(s.buffer, s.len); -} - -unsigned char String::concat(const char *cstr, unsigned int length) -{ - unsigned int newlen = len + length; - if (!cstr) return 0; - if (length == 0) return 1; - if (!reserve(newlen)) return 0; - strcpy(buffer + len, cstr); - len = newlen; - return 1; -} - -unsigned char String::concat(const char *cstr) -{ - if (!cstr) return 0; - return concat(cstr, strlen(cstr)); -} - -unsigned char String::concat(char c) -{ - char buf[2]; - buf[0] = c; - buf[1] = 0; - return concat(buf, 1); -} - -unsigned char String::concat(unsigned char num) -{ - char buf[1 + 3 * sizeof(unsigned char)]; - itoa(num, buf, 10); - return concat(buf, strlen(buf)); -} - -unsigned char String::concat(int num) -{ - char buf[2 + 3 * sizeof(int)]; - itoa(num, buf, 10); - return concat(buf, strlen(buf)); -} - -unsigned char String::concat(unsigned int num) -{ - char buf[1 + 3 * sizeof(unsigned int)]; - utoa(num, buf, 10); - return concat(buf, strlen(buf)); -} - -unsigned char String::concat(long num) -{ - char buf[2 + 3 * sizeof(long)]; - ltoa(num, buf, 10); - return concat(buf, strlen(buf)); -} - -unsigned char String::concat(unsigned long num) -{ - char buf[1 + 3 * sizeof(unsigned long)]; - ultoa(num, buf, 10); - return concat(buf, strlen(buf)); -} - -unsigned char String::concat(float num) -{ - char buf[20]; - char* string = dtostrf(num, 4, 2, buf); - return concat(string, strlen(string)); -} - -unsigned char String::concat(double num) -{ - char buf[20]; - char* string = dtostrf(num, 4, 2, buf); - return concat(string, strlen(string)); -} - -unsigned char String::concat(const __FlashStringHelper * str) -{ - if (!str) return 0; - int length = strlen_P((const char *) str); - if (length == 0) return 1; - unsigned int newlen = len + length; - if (!reserve(newlen)) return 0; - strcpy_P(buffer + len, (const char *) str); - len = newlen; - return 1; -} - -/*********************************************/ -/* Concatenate */ -/*********************************************/ - -StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(rhs.buffer, rhs.len)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr) -{ - StringSumHelper &a = const_cast(lhs); - if (!cstr || !a.concat(cstr, strlen(cstr))) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, char c) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(c)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, int num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, long num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, float num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, double num) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(num)) a.invalidate(); - return a; -} - -StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs) -{ - StringSumHelper &a = const_cast(lhs); - if (!a.concat(rhs)) a.invalidate(); - return a; -} - -/*********************************************/ -/* Comparison */ -/*********************************************/ - -int String::compareTo(const String &s) const -{ - if (!buffer || !s.buffer) { - if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer; - if (buffer && len > 0) return *(unsigned char *)buffer; - return 0; - } - return strcmp(buffer, s.buffer); -} - -unsigned char String::equals(const String &s2) const -{ - return (len == s2.len && compareTo(s2) == 0); -} - -unsigned char String::equals(const char *cstr) const -{ - if (len == 0) return (cstr == NULL || *cstr == 0); - if (cstr == NULL) return buffer[0] == 0; - return strcmp(buffer, cstr) == 0; -} - -unsigned char String::operator<(const String &rhs) const -{ - return compareTo(rhs) < 0; -} - -unsigned char String::operator>(const String &rhs) const -{ - return compareTo(rhs) > 0; -} - -unsigned char String::operator<=(const String &rhs) const -{ - return compareTo(rhs) <= 0; -} - -unsigned char String::operator>=(const String &rhs) const -{ - return compareTo(rhs) >= 0; -} - -unsigned char String::equalsIgnoreCase( const String &s2 ) const -{ - if (this == &s2) return 1; - if (len != s2.len) return 0; - if (len == 0) return 1; - const char *p1 = buffer; - const char *p2 = s2.buffer; - while (*p1) { - if (tolower(*p1++) != tolower(*p2++)) return 0; - } - return 1; -} - -unsigned char String::startsWith( const String &s2 ) const -{ - if (len < s2.len) return 0; - return startsWith(s2, 0); -} - -unsigned char String::startsWith( const String &s2, unsigned int offset ) const -{ - if (offset > len - s2.len || !buffer || !s2.buffer) return 0; - return strncmp( &buffer[offset], s2.buffer, s2.len ) == 0; -} - -unsigned char String::endsWith( const String &s2 ) const -{ - if ( len < s2.len || !buffer || !s2.buffer) return 0; - return strcmp(&buffer[len - s2.len], s2.buffer) == 0; -} - -/*********************************************/ -/* Character Access */ -/*********************************************/ - -char String::charAt(unsigned int loc) const -{ - return operator[](loc); -} - -void String::setCharAt(unsigned int loc, char c) -{ - if (loc < len) buffer[loc] = c; -} - -char & String::operator[](unsigned int index) -{ - static char dummy_writable_char; - if (index >= len || !buffer) { - dummy_writable_char = 0; - return dummy_writable_char; - } - return buffer[index]; -} - -char String::operator[]( unsigned int index ) const -{ - if (index >= len || !buffer) return 0; - return buffer[index]; -} - -void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const -{ - if (!bufsize || !buf) return; - if (index >= len) { - buf[0] = 0; - return; - } - unsigned int n = bufsize - 1; - if (n > len - index) n = len - index; - strncpy((char *)buf, buffer + index, n); - buf[n] = 0; -} - -/*********************************************/ -/* Search */ -/*********************************************/ - -int String::indexOf(char c) const -{ - return indexOf(c, 0); -} - -int String::indexOf( char ch, unsigned int fromIndex ) const -{ - if (fromIndex >= len) return -1; - const char* temp = strchr(buffer + fromIndex, ch); - if (temp == NULL) return -1; - return temp - buffer; -} - -int String::indexOf(const String &s2) const -{ - return indexOf(s2, 0); -} - -int String::indexOf(const String &s2, unsigned int fromIndex) const -{ - if (fromIndex >= len) return -1; - const char *found = strstr(buffer + fromIndex, s2.buffer); - if (found == NULL) return -1; - return found - buffer; -} - -int String::lastIndexOf( char theChar ) const -{ - return lastIndexOf(theChar, len - 1); -} - -int String::lastIndexOf(char ch, unsigned int fromIndex) const -{ - if (fromIndex >= len) return -1; - char tempchar = buffer[fromIndex + 1]; - buffer[fromIndex + 1] = '\0'; - char* temp = strrchr( buffer, ch ); - buffer[fromIndex + 1] = tempchar; - if (temp == NULL) return -1; - return temp - buffer; -} - -int String::lastIndexOf(const String &s2) const -{ - return lastIndexOf(s2, len - s2.len); -} - -int String::lastIndexOf(const String &s2, unsigned int fromIndex) const -{ - if (s2.len == 0 || len == 0 || s2.len > len) return -1; - if (fromIndex >= len) fromIndex = len - 1; - int found = -1; - for (char *p = buffer; p <= buffer + fromIndex; p++) { - p = strstr(p, s2.buffer); - if (!p) break; - if ((unsigned int)(p - buffer) <= fromIndex) found = p - buffer; - } - return found; -} - -String String::substring(unsigned int left, unsigned int right) const -{ - if (left > right) { - unsigned int temp = right; - right = left; - left = temp; - } - String out; - if (left >= len) return out; - if (right > len) right = len; - char temp = buffer[right]; // save the replaced character - buffer[right] = '\0'; - out = buffer + left; // pointer arithmetic - buffer[right] = temp; //restore character - return out; -} - -/*********************************************/ -/* Modification */ -/*********************************************/ - -void String::replace(char find, char replace) -{ - if (!buffer) return; - for (char *p = buffer; *p; p++) { - if (*p == find) *p = replace; - } -} - -void String::replace(const String& find, const String& replace) -{ - if (len == 0 || find.len == 0) return; - int diff = replace.len - find.len; - char *readFrom = buffer; - char *foundAt; - if (diff == 0) { - while ((foundAt = strstr(readFrom, find.buffer)) != NULL) { - memcpy(foundAt, replace.buffer, replace.len); - readFrom = foundAt + replace.len; - } - } else if (diff < 0) { - char *writeTo = buffer; - while ((foundAt = strstr(readFrom, find.buffer)) != NULL) { - unsigned int n = foundAt - readFrom; - memcpy(writeTo, readFrom, n); - writeTo += n; - memcpy(writeTo, replace.buffer, replace.len); - writeTo += replace.len; - readFrom = foundAt + find.len; - len += diff; - } - strcpy(writeTo, readFrom); - } else { - unsigned int size = len; // compute size needed for result - while ((foundAt = strstr(readFrom, find.buffer)) != NULL) { - readFrom = foundAt + find.len; - size += diff; - } - if (size == len) return; - if (size > capacity && !changeBuffer(size)) return; // XXX: tell user! - int index = len - 1; - while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) { - readFrom = buffer + index + find.len; - memmove(readFrom + diff, readFrom, len - (readFrom - buffer)); - len += diff; - buffer[len] = 0; - memcpy(buffer + index, replace.buffer, replace.len); - index--; - } - } -} - -void String::remove(unsigned int index){ - // Pass the biggest integer as the count. The remove method - // below will take care of truncating it at the end of the - // string. - remove(index, (unsigned int)-1); -} - -void String::remove(unsigned int index, unsigned int count){ - if (index >= len) { return; } - if (count <= 0) { return; } - if (count > len - index) { count = len - index; } - char *writeTo = buffer + index; - len = len - count; - strncpy(writeTo, buffer + index + count,len - index); - buffer[len] = 0; -} - -void String::toLowerCase(void) -{ - if (!buffer) return; - for (char *p = buffer; *p; p++) { - *p = tolower(*p); - } -} - -void String::toUpperCase(void) -{ - if (!buffer) return; - for (char *p = buffer; *p; p++) { - *p = toupper(*p); - } -} - -void String::trim(void) -{ - if (!buffer || len == 0) return; - char *begin = buffer; - while (isspace(*begin)) begin++; - char *end = buffer + len - 1; - while (isspace(*end) && end >= begin) end--; - len = end + 1 - begin; - if (begin > buffer) memcpy(buffer, begin, len); - buffer[len] = 0; -} - -/*********************************************/ -/* Parsing / Conversion */ -/*********************************************/ - -long String::toInt(void) const -{ - if (buffer) return atol(buffer); - return 0; -} - -float String::toFloat(void) const -{ - return float(toDouble()); -} - -double String::toDouble(void) const -{ - if (buffer) return atof(buffer); - return 0; -} diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/abi.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/abi.cpp deleted file mode 100644 index 8d719b8..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/abi.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright (c) 2014 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -extern "C" void __cxa_pure_virtual(void) __attribute__ ((__noreturn__)); -extern "C" void __cxa_deleted_virtual(void) __attribute__ ((__noreturn__)); - -void __cxa_pure_virtual(void) { - // We might want to write some diagnostics to uart in this case - //std::terminate(); - abort(); -} - -void __cxa_deleted_virtual(void) { - // We might want to write some diagnostics to uart in this case - //std::terminate(); - abort(); -} - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/hooks.c b/AtmelStudio/TimerTwo/ArduinoCore/src/core/hooks.c deleted file mode 100644 index 641eabc..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/hooks.c +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -/** - * Empty yield() hook. - * - * This function is intended to be used by library writers to build - * libraries or sketches that supports cooperative threads. - * - * Its defined as a weak symbol and it can be redefined to implement a - * real cooperative scheduler. - */ -static void __empty() { - // Empty -} -void yield(void) __attribute__ ((weak, alias("__empty"))); diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/main.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/main.cpp deleted file mode 100644 index 434cd40..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - main.cpp - Main loop for Arduino sketches - Copyright (c) 2005-2013 Arduino Team. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -// Declared weak in Arduino.h to allow user redefinitions. -int atexit(void (* /*func*/ )()) { return 0; } - -// Weak empty variant initialization function. -// May be redefined by variant files. -void initVariant() __attribute__((weak)); -void initVariant() { } - -void setupUSB() __attribute__((weak)); -void setupUSB() { } - -int main(void) -{ - init(); - - initVariant(); - -#if defined(USBCON) - USBDevice.attach(); -#endif - - setup(); - - for (;;) { - loop(); - if (serialEventRun) serialEventRun(); - } - - return 0; -} - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/new.cpp b/AtmelStudio/TimerTwo/ArduinoCore/src/core/new.cpp deleted file mode 100644 index fc30cf8..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/new.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (c) 2014 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -void *operator new(size_t size) { - return malloc(size); -} - -void *operator new[](size_t size) { - return malloc(size); -} - -void * operator new(size_t size, void * ptr) noexcept { - (void)size; - return ptr; -} - -void operator delete(void * ptr) { - free(ptr); -} - -void operator delete[](void * ptr) { - free(ptr); -} - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring.c b/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring.c deleted file mode 100644 index 9727135..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring.c +++ /dev/null @@ -1,392 +0,0 @@ -/* - wiring.c - Partial implementation of the Wiring API for the ATmega8. - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2005-2006 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA -*/ - -#include "wiring_private.h" - -// the prescaler is set so that timer0 ticks every 64 clock cycles, and the -// the overflow handler is called every 256 ticks. -#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256)) - -// the whole number of milliseconds per timer0 overflow -#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000) - -// the fractional number of milliseconds per timer0 overflow. we shift right -// by three to fit these numbers into a byte. (for the clock speeds we care -// about - 8 and 16 MHz - this doesn't lose precision.) -#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3) -#define FRACT_MAX (1000 >> 3) - -volatile unsigned long timer0_overflow_count = 0; -volatile unsigned long timer0_millis = 0; -static unsigned char timer0_fract = 0; - -#if defined(TIM0_OVF_vect) -ISR(TIM0_OVF_vect) -#else -ISR(TIMER0_OVF_vect) -#endif -{ - // copy these to local variables so they can be stored in registers - // (volatile variables must be read from memory on every access) - unsigned long m = timer0_millis; - unsigned char f = timer0_fract; - - m += MILLIS_INC; - f += FRACT_INC; - if (f >= FRACT_MAX) { - f -= FRACT_MAX; - m += 1; - } - - timer0_fract = f; - timer0_millis = m; - timer0_overflow_count++; -} - -unsigned long millis() -{ - unsigned long m; - uint8_t oldSREG = SREG; - - // disable interrupts while we read timer0_millis or we might get an - // inconsistent value (e.g. in the middle of a write to timer0_millis) - cli(); - m = timer0_millis; - SREG = oldSREG; - - return m; -} - -unsigned long micros() { - unsigned long m; - uint8_t oldSREG = SREG, t; - - cli(); - m = timer0_overflow_count; -#if defined(TCNT0) - t = TCNT0; -#elif defined(TCNT0L) - t = TCNT0L; -#else - #error TIMER 0 not defined -#endif - -#ifdef TIFR0 - if ((TIFR0 & _BV(TOV0)) && (t < 255)) - m++; -#else - if ((TIFR & _BV(TOV0)) && (t < 255)) - m++; -#endif - - SREG = oldSREG; - - return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond()); -} - -void delay(unsigned long ms) -{ - uint32_t start = micros(); - - while (ms > 0) { - yield(); - while ( ms > 0 && (micros() - start) >= 1000) { - ms--; - start += 1000; - } - } -} - -/* Delay for the given number of microseconds. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */ -void delayMicroseconds(unsigned int us) -{ - // call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable) - - // calling avrlib's delay_us() function with low values (e.g. 1 or - // 2 microseconds) gives delays longer than desired. - //delay_us(us); -#if F_CPU >= 24000000L - // for the 24 MHz clock for the aventurous ones, trying to overclock - - // zero delay fix - if (!us) return; // = 3 cycles, (4 when true) - - // the following loop takes a 1/6 of a microsecond (4 cycles) - // per iteration, so execute it six times for each microsecond of - // delay requested. - us *= 6; // x6 us, = 7 cycles - - // account for the time taken in the preceeding commands. - // we just burned 22 (24) cycles above, remove 5, (5*4=20) - // us is at least 6 so we can substract 5 - us -= 5; //=2 cycles - -#elif F_CPU >= 20000000L - // for the 20 MHz clock on rare Arduino boards - - // for a one-microsecond delay, simply return. the overhead - // of the function call takes 18 (20) cycles, which is 1us - __asm__ __volatile__ ( - "nop" "\n\t" - "nop" "\n\t" - "nop" "\n\t" - "nop"); //just waiting 4 cycles - if (us <= 1) return; // = 3 cycles, (4 when true) - - // the following loop takes a 1/5 of a microsecond (4 cycles) - // per iteration, so execute it five times for each microsecond of - // delay requested. - us = (us << 2) + us; // x5 us, = 7 cycles - - // account for the time taken in the preceeding commands. - // we just burned 26 (28) cycles above, remove 7, (7*4=28) - // us is at least 10 so we can substract 7 - us -= 7; // 2 cycles - -#elif F_CPU >= 16000000L - // for the 16 MHz clock on most Arduino boards - - // for a one-microsecond delay, simply return. the overhead - // of the function call takes 14 (16) cycles, which is 1us - if (us <= 1) return; // = 3 cycles, (4 when true) - - // the following loop takes 1/4 of a microsecond (4 cycles) - // per iteration, so execute it four times for each microsecond of - // delay requested. - us <<= 2; // x4 us, = 4 cycles - - // account for the time taken in the preceeding commands. - // we just burned 19 (21) cycles above, remove 5, (5*4=20) - // us is at least 8 so we can substract 5 - us -= 5; // = 2 cycles, - -#elif F_CPU >= 12000000L - // for the 12 MHz clock if somebody is working with USB - - // for a 1 microsecond delay, simply return. the overhead - // of the function call takes 14 (16) cycles, which is 1.5us - if (us <= 1) return; // = 3 cycles, (4 when true) - - // the following loop takes 1/3 of a microsecond (4 cycles) - // per iteration, so execute it three times for each microsecond of - // delay requested. - us = (us << 1) + us; // x3 us, = 5 cycles - - // account for the time taken in the preceeding commands. - // we just burned 20 (22) cycles above, remove 5, (5*4=20) - // us is at least 6 so we can substract 5 - us -= 5; //2 cycles - -#elif F_CPU >= 8000000L - // for the 8 MHz internal clock - - // for a 1 and 2 microsecond delay, simply return. the overhead - // of the function call takes 14 (16) cycles, which is 2us - if (us <= 2) return; // = 3 cycles, (4 when true) - - // the following loop takes 1/2 of a microsecond (4 cycles) - // per iteration, so execute it twice for each microsecond of - // delay requested. - us <<= 1; //x2 us, = 2 cycles - - // account for the time taken in the preceeding commands. - // we just burned 17 (19) cycles above, remove 4, (4*4=16) - // us is at least 6 so we can substract 4 - us -= 4; // = 2 cycles - -#else - // for the 1 MHz internal clock (default settings for common Atmega microcontrollers) - - // the overhead of the function calls is 14 (16) cycles - if (us <= 16) return; //= 3 cycles, (4 when true) - if (us <= 25) return; //= 3 cycles, (4 when true), (must be at least 25 if we want to substract 22) - - // compensate for the time taken by the preceeding and next commands (about 22 cycles) - us -= 22; // = 2 cycles - // the following loop takes 4 microseconds (4 cycles) - // per iteration, so execute it us/4 times - // us is at least 4, divided by 4 gives us 1 (no zero delay bug) - us >>= 2; // us div 4, = 4 cycles - - -#endif - - // busy wait - __asm__ __volatile__ ( - "1: sbiw %0,1" "\n\t" // 2 cycles - "brne 1b" : "=w" (us) : "0" (us) // 2 cycles - ); - // return = 4 cycles -} - -void init() -{ - // this needs to be called before setup() or some functions won't - // work there - sei(); - - // on the ATmega168, timer 0 is also used for fast hardware pwm - // (using phase-correct PWM would mean that timer 0 overflowed half as often - // resulting in different millis() behavior on the ATmega8 and ATmega168) -#if defined(TCCR0A) && defined(WGM01) - sbi(TCCR0A, WGM01); - sbi(TCCR0A, WGM00); -#endif - - // set timer 0 prescale factor to 64 -#if defined(__AVR_ATmega128__) - // CPU specific: different values for the ATmega128 - sbi(TCCR0, CS02); -#elif defined(TCCR0) && defined(CS01) && defined(CS00) - // this combination is for the standard atmega8 - sbi(TCCR0, CS01); - sbi(TCCR0, CS00); -#elif defined(TCCR0B) && defined(CS01) && defined(CS00) - // this combination is for the standard 168/328/1280/2560 - sbi(TCCR0B, CS01); - sbi(TCCR0B, CS00); -#elif defined(TCCR0A) && defined(CS01) && defined(CS00) - // this combination is for the __AVR_ATmega645__ series - sbi(TCCR0A, CS01); - sbi(TCCR0A, CS00); -#else - #error Timer 0 prescale factor 64 not set correctly -#endif - - // enable timer 0 overflow interrupt -#if defined(TIMSK) && defined(TOIE0) - sbi(TIMSK, TOIE0); -#elif defined(TIMSK0) && defined(TOIE0) - sbi(TIMSK0, TOIE0); -#else - #error Timer 0 overflow interrupt not set correctly -#endif - - // timers 1 and 2 are used for phase-correct hardware pwm - // this is better for motors as it ensures an even waveform - // note, however, that fast pwm mode can achieve a frequency of up - // 8 MHz (with a 16 MHz clock) at 50% duty cycle - -#if defined(TCCR1B) && defined(CS11) && defined(CS10) - TCCR1B = 0; - - // set timer 1 prescale factor to 64 - sbi(TCCR1B, CS11); -#if F_CPU >= 8000000L - sbi(TCCR1B, CS10); -#endif -#elif defined(TCCR1) && defined(CS11) && defined(CS10) - sbi(TCCR1, CS11); -#if F_CPU >= 8000000L - sbi(TCCR1, CS10); -#endif -#endif - // put timer 1 in 8-bit phase correct pwm mode -#if defined(TCCR1A) && defined(WGM10) - sbi(TCCR1A, WGM10); -#endif - - // set timer 2 prescale factor to 64 -#if defined(TCCR2) && defined(CS22) - sbi(TCCR2, CS22); -#elif defined(TCCR2B) && defined(CS22) - sbi(TCCR2B, CS22); -//#else - // Timer 2 not finished (may not be present on this CPU) -#endif - - // configure timer 2 for phase correct pwm (8-bit) -#if defined(TCCR2) && defined(WGM20) - sbi(TCCR2, WGM20); -#elif defined(TCCR2A) && defined(WGM20) - sbi(TCCR2A, WGM20); -//#else - // Timer 2 not finished (may not be present on this CPU) -#endif - -#if defined(TCCR3B) && defined(CS31) && defined(WGM30) - sbi(TCCR3B, CS31); // set timer 3 prescale factor to 64 - sbi(TCCR3B, CS30); - sbi(TCCR3A, WGM30); // put timer 3 in 8-bit phase correct pwm mode -#endif - -#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */ - sbi(TCCR4B, CS42); // set timer4 prescale factor to 64 - sbi(TCCR4B, CS41); - sbi(TCCR4B, CS40); - sbi(TCCR4D, WGM40); // put timer 4 in phase- and frequency-correct PWM mode - sbi(TCCR4A, PWM4A); // enable PWM mode for comparator OCR4A - sbi(TCCR4C, PWM4D); // enable PWM mode for comparator OCR4D -#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */ -#if defined(TCCR4B) && defined(CS41) && defined(WGM40) - sbi(TCCR4B, CS41); // set timer 4 prescale factor to 64 - sbi(TCCR4B, CS40); - sbi(TCCR4A, WGM40); // put timer 4 in 8-bit phase correct pwm mode -#endif -#endif /* end timer4 block for ATMEGA1280/2560 and similar */ - -#if defined(TCCR5B) && defined(CS51) && defined(WGM50) - sbi(TCCR5B, CS51); // set timer 5 prescale factor to 64 - sbi(TCCR5B, CS50); - sbi(TCCR5A, WGM50); // put timer 5 in 8-bit phase correct pwm mode -#endif - -#if defined(ADCSRA) - // set a2d prescaler so we are inside the desired 50-200 KHz range. - #if F_CPU >= 16000000 // 16 MHz / 128 = 125 KHz - sbi(ADCSRA, ADPS2); - sbi(ADCSRA, ADPS1); - sbi(ADCSRA, ADPS0); - #elif F_CPU >= 8000000 // 8 MHz / 64 = 125 KHz - sbi(ADCSRA, ADPS2); - sbi(ADCSRA, ADPS1); - cbi(ADCSRA, ADPS0); - #elif F_CPU >= 4000000 // 4 MHz / 32 = 125 KHz - sbi(ADCSRA, ADPS2); - cbi(ADCSRA, ADPS1); - sbi(ADCSRA, ADPS0); - #elif F_CPU >= 2000000 // 2 MHz / 16 = 125 KHz - sbi(ADCSRA, ADPS2); - cbi(ADCSRA, ADPS1); - cbi(ADCSRA, ADPS0); - #elif F_CPU >= 1000000 // 1 MHz / 8 = 125 KHz - cbi(ADCSRA, ADPS2); - sbi(ADCSRA, ADPS1); - sbi(ADCSRA, ADPS0); - #else // 128 kHz / 2 = 64 KHz -> This is the closest you can get, the prescaler is 2 - cbi(ADCSRA, ADPS2); - cbi(ADCSRA, ADPS1); - sbi(ADCSRA, ADPS0); - #endif - // enable a2d conversions - sbi(ADCSRA, ADEN); -#endif - - // the bootloader connects pins 0 and 1 to the USART; disconnect them - // here so they can be used as normal digital i/o; they will be - // reconnected in Serial.begin() -#if defined(UCSRB) - UCSRB = 0; -#elif defined(UCSR0B) - UCSR0B = 0; -#endif -} diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_analog.c b/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_analog.c deleted file mode 100644 index e237d6d..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_analog.c +++ /dev/null @@ -1,294 +0,0 @@ -/* - wiring_analog.c - analog input and output - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2005-2006 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA - - Modified 28 September 2010 by Mark Sproul -*/ - -#include "wiring_private.h" -#include "pins_arduino.h" - -uint8_t analog_reference = DEFAULT; - -void analogReference(uint8_t mode) -{ - // can't actually set the register here because the default setting - // will connect AVCC and the AREF pin, which would cause a short if - // there's something connected to AREF. - analog_reference = mode; -} - -int analogRead(uint8_t pin) -{ - uint8_t low, high; - -#if defined(analogPinToChannel) -#if defined(__AVR_ATmega32U4__) - if (pin >= 18) pin -= 18; // allow for channel or pin numbers -#endif - pin = analogPinToChannel(pin); -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - if (pin >= 54) pin -= 54; // allow for channel or pin numbers -#elif defined(__AVR_ATmega32U4__) - if (pin >= 18) pin -= 18; // allow for channel or pin numbers -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) - if (pin >= 24) pin -= 24; // allow for channel or pin numbers -#else - if (pin >= 14) pin -= 14; // allow for channel or pin numbers -#endif - -#if defined(ADCSRB) && defined(MUX5) - // the MUX5 bit of ADCSRB selects whether we're reading from channels - // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high). - ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5); -#endif - - // set the analog reference (high two bits of ADMUX) and select the - // channel (low 4 bits). this also sets ADLAR (left-adjust result) - // to 0 (the default). -#if defined(ADMUX) -#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) - ADMUX = (analog_reference << 4) | (pin & 0x07); -#else - ADMUX = (analog_reference << 6) | (pin & 0x07); -#endif -#endif - - // without a delay, we seem to read from the wrong channel - //delay(1); - -#if defined(ADCSRA) && defined(ADCL) - // start the conversion - sbi(ADCSRA, ADSC); - - // ADSC is cleared when the conversion finishes - while (bit_is_set(ADCSRA, ADSC)); - - // we have to read ADCL first; doing so locks both ADCL - // and ADCH until ADCH is read. reading ADCL second would - // cause the results of each conversion to be discarded, - // as ADCL and ADCH would be locked when it completed. - low = ADCL; - high = ADCH; -#else - // we dont have an ADC, return 0 - low = 0; - high = 0; -#endif - - // combine the two bytes - return (high << 8) | low; -} - -// Right now, PWM output only works on the pins with -// hardware support. These are defined in the appropriate -// pins_*.c file. For the rest of the pins, we default -// to digital output. -void analogWrite(uint8_t pin, int val) -{ - // We need to make sure the PWM output is enabled for those pins - // that support it, as we turn it off when digitally reading or - // writing with them. Also, make sure the pin is in output mode - // for consistenty with Wiring, which doesn't require a pinMode - // call for the analog output pins. - pinMode(pin, OUTPUT); - if (val == 0) - { - digitalWrite(pin, LOW); - } - else if (val == 255) - { - digitalWrite(pin, HIGH); - } - else - { - switch(digitalPinToTimer(pin)) - { - // XXX fix needed for atmega8 - #if defined(TCCR0) && defined(COM00) && !defined(__AVR_ATmega8__) - case TIMER0A: - // connect pwm to pin on timer 0 - sbi(TCCR0, COM00); - OCR0 = val; // set pwm duty - break; - #endif - - #if defined(TCCR0A) && defined(COM0A1) - case TIMER0A: - // connect pwm to pin on timer 0, channel A - sbi(TCCR0A, COM0A1); - OCR0A = val; // set pwm duty - break; - #endif - - #if defined(TCCR0A) && defined(COM0B1) - case TIMER0B: - // connect pwm to pin on timer 0, channel B - sbi(TCCR0A, COM0B1); - OCR0B = val; // set pwm duty - break; - #endif - - #if defined(TCCR1A) && defined(COM1A1) - case TIMER1A: - // connect pwm to pin on timer 1, channel A - sbi(TCCR1A, COM1A1); - OCR1A = val; // set pwm duty - break; - #endif - - #if defined(TCCR1A) && defined(COM1B1) - case TIMER1B: - // connect pwm to pin on timer 1, channel B - sbi(TCCR1A, COM1B1); - OCR1B = val; // set pwm duty - break; - #endif - - #if defined(TCCR1A) && defined(COM1C1) - case TIMER1C: - // connect pwm to pin on timer 1, channel C - sbi(TCCR1A, COM1C1); - OCR1C = val; // set pwm duty - break; - #endif - - #if defined(TCCR2) && defined(COM21) - case TIMER2: - // connect pwm to pin on timer 2 - sbi(TCCR2, COM21); - OCR2 = val; // set pwm duty - break; - #endif - - #if defined(TCCR2A) && defined(COM2A1) - case TIMER2A: - // connect pwm to pin on timer 2, channel A - sbi(TCCR2A, COM2A1); - OCR2A = val; // set pwm duty - break; - #endif - - #if defined(TCCR2A) && defined(COM2B1) - case TIMER2B: - // connect pwm to pin on timer 2, channel B - sbi(TCCR2A, COM2B1); - OCR2B = val; // set pwm duty - break; - #endif - - #if defined(TCCR3A) && defined(COM3A1) - case TIMER3A: - // connect pwm to pin on timer 3, channel A - sbi(TCCR3A, COM3A1); - OCR3A = val; // set pwm duty - break; - #endif - - #if defined(TCCR3A) && defined(COM3B1) - case TIMER3B: - // connect pwm to pin on timer 3, channel B - sbi(TCCR3A, COM3B1); - OCR3B = val; // set pwm duty - break; - #endif - - #if defined(TCCR3A) && defined(COM3C1) - case TIMER3C: - // connect pwm to pin on timer 3, channel C - sbi(TCCR3A, COM3C1); - OCR3C = val; // set pwm duty - break; - #endif - - #if defined(TCCR4A) - case TIMER4A: - //connect pwm to pin on timer 4, channel A - sbi(TCCR4A, COM4A1); - #if defined(COM4A0) // only used on 32U4 - cbi(TCCR4A, COM4A0); - #endif - OCR4A = val; // set pwm duty - break; - #endif - - #if defined(TCCR4A) && defined(COM4B1) - case TIMER4B: - // connect pwm to pin on timer 4, channel B - sbi(TCCR4A, COM4B1); - OCR4B = val; // set pwm duty - break; - #endif - - #if defined(TCCR4A) && defined(COM4C1) - case TIMER4C: - // connect pwm to pin on timer 4, channel C - sbi(TCCR4A, COM4C1); - OCR4C = val; // set pwm duty - break; - #endif - - #if defined(TCCR4C) && defined(COM4D1) - case TIMER4D: - // connect pwm to pin on timer 4, channel D - sbi(TCCR4C, COM4D1); - #if defined(COM4D0) // only used on 32U4 - cbi(TCCR4C, COM4D0); - #endif - OCR4D = val; // set pwm duty - break; - #endif - - - #if defined(TCCR5A) && defined(COM5A1) - case TIMER5A: - // connect pwm to pin on timer 5, channel A - sbi(TCCR5A, COM5A1); - OCR5A = val; // set pwm duty - break; - #endif - - #if defined(TCCR5A) && defined(COM5B1) - case TIMER5B: - // connect pwm to pin on timer 5, channel B - sbi(TCCR5A, COM5B1); - OCR5B = val; // set pwm duty - break; - #endif - - #if defined(TCCR5A) && defined(COM5C1) - case TIMER5C: - // connect pwm to pin on timer 5, channel C - sbi(TCCR5A, COM5C1); - OCR5C = val; // set pwm duty - break; - #endif - - case NOT_ON_TIMER: - default: - if (val < 128) { - digitalWrite(pin, LOW); - } else { - digitalWrite(pin, HIGH); - } - } - } -} - diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_digital.c b/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_digital.c deleted file mode 100644 index 27a62fc..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_digital.c +++ /dev/null @@ -1,179 +0,0 @@ -/* - wiring_digital.c - digital input and output functions - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2005-2006 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA - - Modified 28 September 2010 by Mark Sproul -*/ - -#define ARDUINO_MAIN -#include "wiring_private.h" -#include "pins_arduino.h" - -void pinMode(uint8_t pin, uint8_t mode) -{ - uint8_t bit = digitalPinToBitMask(pin); - uint8_t port = digitalPinToPort(pin); - volatile uint8_t *reg, *out; - - if (port == NOT_A_PIN) return; - - // JWS: can I let the optimizer do this? - reg = portModeRegister(port); - out = portOutputRegister(port); - - if (mode == INPUT) { - uint8_t oldSREG = SREG; - cli(); - *reg &= ~bit; - *out &= ~bit; - SREG = oldSREG; - } else if (mode == INPUT_PULLUP) { - uint8_t oldSREG = SREG; - cli(); - *reg &= ~bit; - *out |= bit; - SREG = oldSREG; - } else { - uint8_t oldSREG = SREG; - cli(); - *reg |= bit; - SREG = oldSREG; - } -} - -// Forcing this inline keeps the callers from having to push their own stuff -// on the stack. It is a good performance win and only takes 1 more byte per -// user than calling. (It will take more bytes on the 168.) -// -// But shouldn't this be moved into pinMode? Seems silly to check and do on -// each digitalread or write. -// -// Mark Sproul: -// - Removed inline. Save 170 bytes on atmega1280 -// - changed to a switch statment; added 32 bytes but much easier to read and maintain. -// - Added more #ifdefs, now compiles for atmega645 -// -//static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline)); -//static inline void turnOffPWM(uint8_t timer) -static void turnOffPWM(uint8_t timer) -{ - switch (timer) - { - #if defined(TCCR1A) && defined(COM1A1) - case TIMER1A: cbi(TCCR1A, COM1A1); break; - #endif - #if defined(TCCR1A) && defined(COM1B1) - case TIMER1B: cbi(TCCR1A, COM1B1); break; - #endif - #if defined(TCCR1A) && defined(COM1C1) - case TIMER1C: cbi(TCCR1A, COM1C1); break; - #endif - - #if defined(TCCR2) && defined(COM21) - case TIMER2: cbi(TCCR2, COM21); break; - #endif - - #if defined(TCCR0A) && defined(COM0A1) - case TIMER0A: cbi(TCCR0A, COM0A1); break; - #endif - - #if defined(TCCR0A) && defined(COM0B1) - case TIMER0B: cbi(TCCR0A, COM0B1); break; - #endif - #if defined(TCCR2A) && defined(COM2A1) - case TIMER2A: cbi(TCCR2A, COM2A1); break; - #endif - #if defined(TCCR2A) && defined(COM2B1) - case TIMER2B: cbi(TCCR2A, COM2B1); break; - #endif - - #if defined(TCCR3A) && defined(COM3A1) - case TIMER3A: cbi(TCCR3A, COM3A1); break; - #endif - #if defined(TCCR3A) && defined(COM3B1) - case TIMER3B: cbi(TCCR3A, COM3B1); break; - #endif - #if defined(TCCR3A) && defined(COM3C1) - case TIMER3C: cbi(TCCR3A, COM3C1); break; - #endif - - #if defined(TCCR4A) && defined(COM4A1) - case TIMER4A: cbi(TCCR4A, COM4A1); break; - #endif - #if defined(TCCR4A) && defined(COM4B1) - case TIMER4B: cbi(TCCR4A, COM4B1); break; - #endif - #if defined(TCCR4A) && defined(COM4C1) - case TIMER4C: cbi(TCCR4A, COM4C1); break; - #endif - #if defined(TCCR4C) && defined(COM4D1) - case TIMER4D: cbi(TCCR4C, COM4D1); break; - #endif - - #if defined(TCCR5A) - case TIMER5A: cbi(TCCR5A, COM5A1); break; - case TIMER5B: cbi(TCCR5A, COM5B1); break; - case TIMER5C: cbi(TCCR5A, COM5C1); break; - #endif - } -} - -void digitalWrite(uint8_t pin, uint8_t val) -{ - uint8_t timer = digitalPinToTimer(pin); - uint8_t bit = digitalPinToBitMask(pin); - uint8_t port = digitalPinToPort(pin); - volatile uint8_t *out; - - if (port == NOT_A_PIN) return; - - // If the pin that support PWM output, we need to turn it off - // before doing a digital write. - if (timer != NOT_ON_TIMER) turnOffPWM(timer); - - out = portOutputRegister(port); - - uint8_t oldSREG = SREG; - cli(); - - if (val == LOW) { - *out &= ~bit; - } else { - *out |= bit; - } - - SREG = oldSREG; -} - -int digitalRead(uint8_t pin) -{ - uint8_t timer = digitalPinToTimer(pin); - uint8_t bit = digitalPinToBitMask(pin); - uint8_t port = digitalPinToPort(pin); - - if (port == NOT_A_PIN) return LOW; - - // If the pin that support PWM output, we need to turn it off - // before getting a digital reading. - if (timer != NOT_ON_TIMER) turnOffPWM(timer); - - if (*portInputRegister(port) & bit) return HIGH; - return LOW; -} diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_pulse.c b/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_pulse.c deleted file mode 100644 index d6e0434..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_pulse.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - wiring_pulse.c - pulseIn() function - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2005-2006 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA -*/ - -#include "wiring_private.h" -#include "pins_arduino.h" - -/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH - * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds - * to 3 minutes in length, but must be called at least a few dozen microseconds - * before the start of the pulse. - * - * This function performs better with short pulses in noInterrupt() context - */ -unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) -{ - // cache the port and bit of the pin in order to speed up the - // pulse width measuring loop and achieve finer resolution. calling - // digitalRead() instead yields much coarser resolution. - uint8_t bit = digitalPinToBitMask(pin); - uint8_t port = digitalPinToPort(pin); - uint8_t stateMask = (state ? bit : 0); - - // convert the timeout from microseconds to a number of times through - // the initial loop; it takes approximately 16 clock cycles per iteration - unsigned long maxloops = microsecondsToClockCycles(timeout)/16; - - unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops); - - // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out - if (width) - return clockCyclesToMicroseconds(width * 16 + 16); - else - return 0; -} - -/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH - * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds - * to 3 minutes in length, but must be called at least a few dozen microseconds - * before the start of the pulse. - * - * ATTENTION: - * this function relies on micros() so cannot be used in noInterrupt() context - */ -unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout) -{ - // cache the port and bit of the pin in order to speed up the - // pulse width measuring loop and achieve finer resolution. calling - // digitalRead() instead yields much coarser resolution. - uint8_t bit = digitalPinToBitMask(pin); - uint8_t port = digitalPinToPort(pin); - uint8_t stateMask = (state ? bit : 0); - - unsigned long startMicros = micros(); - - // wait for any previous pulse to end - while ((*portInputRegister(port) & bit) == stateMask) { - if (micros() - startMicros > timeout) - return 0; - } - - // wait for the pulse to start - while ((*portInputRegister(port) & bit) != stateMask) { - if (micros() - startMicros > timeout) - return 0; - } - - unsigned long start = micros(); - // wait for the pulse to stop - while ((*portInputRegister(port) & bit) == stateMask) { - if (micros() - startMicros > timeout) - return 0; - } - return micros() - start; -} diff --git a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_shift.c b/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_shift.c deleted file mode 100644 index a9b3be5..0000000 --- a/AtmelStudio/TimerTwo/ArduinoCore/src/core/wiring_shift.c +++ /dev/null @@ -1,56 +0,0 @@ -/* - wiring_shift.c - shiftOut() function - Part of Arduino - http://www.arduino.cc/ - - Copyright (c) 2005-2006 David A. Mellis - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General - Public License along with this library; if not, write to the - Free Software Foundation, Inc., 59 Temple Place, Suite 330, - Boston, MA 02111-1307 USA -*/ - -#include "wiring_private.h" - -uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) { - uint8_t value = 0; - uint8_t i; - - for (i = 0; i < 8; ++i) { - digitalWrite(clockPin, HIGH); - if (bitOrder == LSBFIRST) - value |= digitalRead(dataPin) << i; - else - value |= digitalRead(dataPin) << (7 - i); - digitalWrite(clockPin, LOW); - } - return value; -} - -void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) -{ - uint8_t i; - - for (i = 0; i < 8; i++) { - if (bitOrder == LSBFIRST) { - digitalWrite(dataPin, val & 1); - val >>= 1; - } else { - digitalWrite(dataPin, (val & 128) != 0); - val <<= 1; - } - - digitalWrite(clockPin, HIGH); - digitalWrite(clockPin, LOW); - } -} diff --git a/AtmelStudio/TimerTwo/TimerTwo/Sketch.cpp b/AtmelStudio/TimerTwo/TimerTwo/Sketch.cpp deleted file mode 100644 index df89db1..0000000 --- a/AtmelStudio/TimerTwo/TimerTwo/Sketch.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include -/* - This example toggles the PIN13 cyclically all 1ms and starts the PWM for PIN11. - The frequency of the PWM depends on the period of the timer. Furthermore the - use of the read function is demonstrated. -*/ - -#define PIN_TOGGLE 13u - - -void timerCallback() { - digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); -} - -void setup() { - pinMode(PIN_TOGGLE, OUTPUT); - if(Timer2.init(Timer2.getPeriodMax(), timerCallback) == E_NOT_OK) { - // Something went wrong, check your parameters - while(1); - } - if(Timer2.enablePwm(TimerTwo::PWM_PIN_11, 127) == E_NOT_OK) { - // Something went wrong, has init function already been called? - while(1); - } - if(Timer2.start() == E_NOT_OK) { - // Something went wrong, has init function already been called? - while(1); - } - - // delay of 20ms - delay(20u); - TimerTwo::TimeType elapsedTime{0u}; - - if(Timer2.read(elapsedTime) == E_NOT_OK) { - // Something went wrong, has init function already been called? - while(1); - } - - // Prints the measured time in µs since the last rollover of the timer. - // In this example the timer had no rollover until now. - Serial.println(elapsedTime); -} - -void loop() { - -} diff --git a/AtmelStudio/TimerTwo/TimerTwo/TimerTwo.componentinfo.xml b/AtmelStudio/TimerTwo/TimerTwo/TimerTwo.componentinfo.xml deleted file mode 100644 index b2f7f48..0000000 --- a/AtmelStudio/TimerTwo/TimerTwo/TimerTwo.componentinfo.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - Device - Startup - - - Atmel - 1.3.0 - C:/Program Files (x86)\Atmel\Studio\7.0\Packs - - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\include - - include - C - - - include - - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\include\avr\iom328p.h - - header - C - UMk4QUzkkuShabuoYtNl/Q== - - include/avr/iom328p.h - - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\templates\main.c - template - source - C Exe - GD1k8YYhulqRs6FD1B2Hog== - - templates/main.c - Main file (.c) - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\templates\main.cpp - template - source - C Exe - xPE+BgNkitxrGCml8ZjWRg== - - templates/main.cpp - Main file (.cpp) - - - - C:/Program Files (x86)\Atmel\Studio\7.0\Packs\atmel\ATmega_DFP\1.3.300\gcc\dev\atmega328p - - libraryPrefix - GCC - - - gcc/dev/atmega328p - - - - - ATmega_DFP - C:/Program Files (x86)/Atmel/Studio/7.0/Packs/atmel/ATmega_DFP/1.3.300/Atmel.ATmega_DFP.pdsc - 1.3.300 - true - ATmega328P - - - - Resolved - Fixed - true - - - \ No newline at end of file diff --git a/AtmelStudio/TimerTwo/TimerTwo/TimerTwo.cppproj b/AtmelStudio/TimerTwo/TimerTwo/TimerTwo.cppproj deleted file mode 100644 index f39a610..0000000 --- a/AtmelStudio/TimerTwo/TimerTwo/TimerTwo.cppproj +++ /dev/null @@ -1,252 +0,0 @@ - - - - 2.0 - 7.0 - com.Atmel.AVRGCC8.CPP - dce6c7e3-ee26-4d79-826b-08594b9ad897 - atmega328p - none - Executable - CPP - $(MSBuildProjectName) - Sketch - .elf - $(MSBuildProjectDirectory)\$(Configuration) - TimerTwo - TimerTwo - C:\Program Files (x86)\Arduino - Native - true - false - true - true - 0x20000000 - - true - exception_table - 2 - 0 - TimerTwo - 0 - - - - - - - - - - - - - - com.atmel.avrdbg.tool.simulator - - 0x1E950F - - - - - - com.atmel.avrdbg.tool.simulator - - - Simulator - - - - - - -mmcu=atmega328p -B "%24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\gcc\dev\atmega328p" - True - True - True - True - False - True - True - - - NDEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - %24(ProjectDir)\..\ArduinoCore\include\core - %24(ProjectDir)\..\ArduinoCore\include\variants\standard - - - Optimize for size (-Os) - -fno-threadsafe-statics - True - True - Default (-g2) - True - -std=gnu99 -std=gnu11 - True - True - - - NDEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - %24(ProjectDir)\..\ArduinoCore\include\core - %24(ProjectDir)\..\ArduinoCore\include\variants\standard - - - Optimize for size (-Os) - -fno-threadsafe-statics - True - True - Default (-g2) - True - -std=gnu++11 - - - libm - - - -Os - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - - - Default (-Wa,-g) - - - - - - - -mmcu=atmega328p -B "%24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\gcc\dev\atmega328p" - True - True - True - True - False - True - True - - - DEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - %24(ProjectDir)\..\ArduinoCore\include\core - %24(ProjectDir)\..\ArduinoCore\include\variants\standard - - - -fno-threadsafe-statics - True - True - Default (-g2) - True - True - True - -std=gnu99 -std=gnu11 - True - True - - - DEBUG - F_CPU=16000000L - ARDUINO=108013 - ARDUINO_AVR_UNO - ARDUINO_ARCH_AVR - USB_VID=0x2341 - USB_PID=0x0043 - USB_MANUFACTURER="\"Arduino LLC\"" - - - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - %24(ProjectDir)\..\ArduinoCore\include\core - %24(ProjectDir)\..\ArduinoCore\include\variants\standard - ../../../.. - - - -fno-threadsafe-statics - True - True - Default (-g2) - True - True - True - -std=gnu++11 - - - libm - - - -Os - - - %24(PackRepoDir)\atmel\ATmega_DFP\1.3.300\include - - - Default (-Wa,-g) - - - - - - compile - TimerTwo\StandardTypes.h - - - compile - TimerTwo\TimerTwo.cpp - - - compile - TimerTwo\TimerTwo.h - - - compile - - - - - - - ArduinoCore - b8b61b52-8e26-4022-a4c5-68291647b272 - True - - - - - - - \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..6f0f339 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,60 @@ +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# The tests on the host: the library against a mock of the Arduino core, on GoogleTest. The +# library is built as gnu++11, as avr-gcc builds it for Arduino; only the tests are C++17, +# which GoogleTest needs. The warnings and the presets' instrumentation come from +# cmake/checks.cmake. +# +# cmake --workflow --preset default # the tests +# cmake --workflow --preset sanitize # under ASan and UBSan +# tools/coverage.sh # the tests, and what they reach + +cmake_minimum_required(VERSION 3.25) +project(TimerTwo LANGUAGES CXX) +enable_testing() +# For clangd, which reads it through .clangd. +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +include(cmake/checks.cmake) +find_package(GTest REQUIRED) +include(GoogleTest) + +# TimerTwo lies in src/ itself until version 2.0.0 moves it into src/timer_two/ (OIL 3). A test +# is named as the class it tests and Test, or a family of functions and _test (Testing.md +# TS-5); the mock and the cases of what must not compile are no tests of their own. +file(GLOB library_sources CONFIGURE_DEPENDS src/*.cpp) +file(GLOB_RECURSE test_sources CONFIGURE_DEPENDS test/*Test.cpp test/*_test.cpp) +list(FILTER test_sources EXCLUDE REGEX "/test/(mock|compile_fail)/") + +# One library and one test program per variant: a switch that changes what is compiled makes +# a build of its own. A variant is added with its defines, as add_variant(checked +# TIMERTWO_CHECK_ACCESS=1), and in tools/project.sh for the examples. +function(add_variant name) + set(defines ${ARGN}) + + add_library(timer_two_${name} STATIC ${library_sources} test/mock/Arduino.cpp + test/mock/avr/io.cpp) + target_include_directories(timer_two_${name} PUBLIC src test/mock) + # The Uno's clock, which the board's build defines. + target_compile_definitions(timer_two_${name} PUBLIC F_CPU=16000000uL ${defines}) + target_compile_options(timer_two_${name} PRIVATE -std=gnu++11 ${CHECK_WARNINGS} + ${CHECK_INSTRUMENT}) + target_link_options(timer_two_${name} PUBLIC ${CHECK_INSTRUMENT}) + + add_executable(timer_two_test_${name} ${test_sources}) + target_compile_features(timer_two_test_${name} PRIVATE cxx_std_17) + # The root, so that a test includes its helpers as "test/...", as Google wants an include + # to name the directory. + target_include_directories(timer_two_test_${name} PRIVATE ${CMAKE_SOURCE_DIR}) + target_compile_options(timer_two_test_${name} PRIVATE ${CHECK_WARNINGS} + ${CHECK_INSTRUMENT}) + target_link_libraries(timer_two_test_${name} PRIVATE timer_two_${name} + GTest::gtest_main) + gtest_discover_tests(timer_two_test_${name} TEST_PREFIX ${name}/) +endfunction() + +add_variant(default) + +add_compile_fail_tests(DIRECTORY ${CMAKE_SOURCE_DIR}/test/compile_fail STANDARD gnu++11 + INCLUDES ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/test/mock) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..d351724 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,150 @@ +{ + "version": 6, + "configurePresets": [ + { + "name": "base", + "hidden": true, + "description": "Ninja, a compile database for clangd and clang-tidy, and warnings that do not stop a build here: a warning stops a merge in CI, and nobody in the middle of debugging.", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "CMAKE_COMPILE_WARNING_AS_ERROR": "OFF" + } + }, + { + "name": "warnings-as-errors", + "hidden": true, + "description": "What the ci- presets add: every warning of cmake/checks.cmake fails the build.", + "cacheVariables": { "CMAKE_COMPILE_WARNING_AS_ERROR": "ON" } + }, + { + "name": "default", + "displayName": "Tests", + "description": "The tests on the host, by GCC, into build/host, where clangd looks. GCC named, so that a directory an editor once configured with another compiler does not quietly stay so: the clang preset is the clang build.", + "inherits": "base", + "binaryDir": "${sourceDir}/build/host", + "cacheVariables": { "CMAKE_CXX_COMPILER": "g++" } + }, + { + "name": "clang", + "displayName": "Tests by clang", + "description": "The same tests by clang: two compilers disagree about what deserves a warning.", + "inherits": "base", + "binaryDir": "${sourceDir}/build/clang", + "cacheVariables": { "CMAKE_CXX_COMPILER": "clang++" } + }, + { + "name": "sanitize", + "displayName": "Tests under ASan and UBSan", + "inherits": "default", + "binaryDir": "${sourceDir}/build/sanitize", + "cacheVariables": { "TIMERTWO_SANITIZE": "ON" } + }, + { + "name": "coverage", + "displayName": "Tests with coverage", + "inherits": "default", + "binaryDir": "${sourceDir}/build/coverage", + "cacheVariables": { "TIMERTWO_COVERAGE": "ON" } + }, + { + "name": "ci-default", + "inherits": ["warnings-as-errors", "default"] + }, + { + "name": "ci-clang", + "inherits": ["warnings-as-errors", "clang"] + } + ], + "buildPresets": [ + { "name": "default", "configurePreset": "default" }, + { "name": "clang", "configurePreset": "clang" }, + { "name": "sanitize", "configurePreset": "sanitize" }, + { "name": "coverage", "configurePreset": "coverage" }, + { "name": "ci-default", "configurePreset": "ci-default" }, + { "name": "ci-clang", "configurePreset": "ci-clang" } + ], + "testPresets": [ + { + "name": "default", + "configurePreset": "default", + "output": { "outputOnFailure": true } + }, + { + "name": "clang", + "configurePreset": "clang", + "output": { "outputOnFailure": true } + }, + { + "name": "sanitize", + "configurePreset": "sanitize", + "output": { "outputOnFailure": true } + }, + { + "name": "coverage", + "configurePreset": "coverage", + "output": { "outputOnFailure": true } + }, + { + "name": "ci-default", + "configurePreset": "ci-default", + "output": { "outputOnFailure": true } + }, + { + "name": "ci-clang", + "configurePreset": "ci-clang", + "output": { "outputOnFailure": true } + } + ], + "workflowPresets": [ + { + "name": "default", + "steps": [ + { "type": "configure", "name": "default" }, + { "type": "build", "name": "default" }, + { "type": "test", "name": "default" } + ] + }, + { + "name": "clang", + "steps": [ + { "type": "configure", "name": "clang" }, + { "type": "build", "name": "clang" }, + { "type": "test", "name": "clang" } + ] + }, + { + "name": "sanitize", + "steps": [ + { "type": "configure", "name": "sanitize" }, + { "type": "build", "name": "sanitize" }, + { "type": "test", "name": "sanitize" } + ] + }, + { + "name": "coverage", + "steps": [ + { "type": "configure", "name": "coverage" }, + { "type": "build", "name": "coverage" }, + { "type": "test", "name": "coverage" } + ] + }, + { + "name": "ci-default", + "steps": [ + { "type": "configure", "name": "ci-default" }, + { "type": "build", "name": "ci-default" }, + { "type": "test", "name": "ci-default" } + ] + }, + { + "name": "ci-clang", + "steps": [ + { "type": "configure", "name": "ci-clang" }, + { "type": "build", "name": "ci-clang" }, + { "type": "test", "name": "ci-clang" } + ] + } + ] +} diff --git a/CPPLINT.cfg b/CPPLINT.cfg new file mode 100644 index 0000000..d1cb0d6 --- /dev/null +++ b/CPPLINT.cfg @@ -0,0 +1,11 @@ +set noparent +# Google puts the project in front of the path in a header guard, as in +# LIB_SRC_LIB_ERROR_H_. cpplint derives the guard from the path below +# root, so root is the parent of the checkout, and the checkout has to be +# named as the library, as Arduino names the folder of the library anyway. +root=.. +extensions=h,cpp,ino +# clang-format, with the Google style, sets the indentation within a +# namespace already, and cpplint takes the lines it wraps there, a trailing +# return type or a long initializer, for indented ones. +filter=-whitespace/indent_namespace diff --git a/Doxyfile b/Doxyfile new file mode 100644 index 0000000..ba2bc59 --- /dev/null +++ b/Doxyfile @@ -0,0 +1,47 @@ +# The reference on GitHub Pages, from the Doxygen blocks of src/ and the README as its main +# page. Only what differs from Doxygen's defaults is set. Built and checked by tools/docs.sh, +# which fails on a warning, see there which; published by .github/workflows/docs.yml. How a +# block is written is in docs/Documentation.md. + +PROJECT_NAME = TimerTwo +PROJECT_BRIEF = "Periodic interrupt, PWM and time readout on Timer2 of the ATmega328P." +OUTPUT_DIRECTORY = build/docs + +# The examples are not read: they are sketches, not reference, and the README links them. The +# style guide and the dev container's README are pages, as the README links them too. +INPUT = README.md docs/Documentation.md .devcontainer/README.md src +RECURSIVE = YES +FILE_PATTERNS = *.h *.md +USE_MDFILE_AS_MAINPAGE = README.md +# So that the README's links to its own headings, written for GitHub, find them here as well. +MARKDOWN_ID_STYLE = GITHUB + +# \stddiff opens the paragraph that says where an entity differs from the standard it follows, +# so that every such difference reads alike. clang knows it from -fcomment-block-commands in +# .clang-tidy and .clangd, or -Wdocumentation-unknown-command would take it for a typo. +ALIASES = "stddiff=\par Differs from the standard:^^" + +# PROGMEM and the attributes mean nothing to Doxygen; read as they are, a name in flash would +# be a symbol "not declared". A switch of the library is left to its header, so that it is in +# the reference with its default. +MACRO_EXPANSION = YES +EXPAND_ONLY_PREDEF = YES +PREDEFINED = PROGMEM= "__attribute__(x)=" + +# A class shows the members it takes from a base in the namespace internal on its own page. +INLINE_INHERITED_MEMB = YES + +# No graphs: they need Graphviz, and the parts are few enough to read from the README. +HAVE_DOT = NO +DIRECTORY_GRAPH = NO +GENERATE_LATEX = NO + +QUIET = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_INCOMPLETE_DOC = YES +WARN_NO_PARAMDOC = YES +WARN_LOGFILE = build/docs/warnings.log + +# The project's own settings, last, so that += adds to the lists above and a plain = replaces +# one: Doxyfile.project, which the template writes once and `copier update` leaves alone. +@INCLUDE = Doxyfile.project diff --git a/Doxyfile.project b/Doxyfile.project new file mode 100644 index 0000000..da0f3b6 --- /dev/null +++ b/Doxyfile.project @@ -0,0 +1,7 @@ +# The project's own settings of the reference, which Doxyfile includes at its end: Doxyfile is +# the template's and `copier update` brings it up to date, this file is the project's and the +# update leaves it alone. += adds to a list of Doxyfile, = replaces a setting: +# +# INPUT += docs/Wiring.md +# IMAGE_PATH = docs +# PREDEFINED += PREFIX_CHECK_ACCESS=1 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a4a5051 --- /dev/null +++ b/Makefile @@ -0,0 +1,113 @@ +# The index of what builds and checks this repository. +# +# Nothing is decided here: the CMake builds are presets in CMakePresets.json, the Python tools +# are pinned in uv.lock, and each check is a script in tools/. This file only names them, so +# that a developer and CI type the same: every step of the workflows that builds or checks +# something is one of these targets. `make` alone lists them. +# +# Warnings are errors in CI and under `make check`, and not otherwise: the ci- presets, chosen +# by STRICT. GitHub Actions sets CI=true in every job, which is where the default comes from. +# The other checks fail on a finding always: clang-tidy, cppcheck and the compiled examples. +# +# This file comes from the template and is brought up to date with `copier update`. A target of +# the project's own goes into tools/project.mk, included at the top; added to PROJECT_CHECKS, it +# is part of `make check` as well. + +SHELL := bash +.SHELLFLAGS := -e -o pipefail -c +.DEFAULT_GOAL := help +# One tool at a time: several of them configure the same build directory, and each runs its +# compiler or analyser on every core already. +.NOTPARALLEL: + +STRICT ?= $(CI) +PRESET = $(if $(STRICT),ci-) +PROJECT_CHECKS := + +# Before the rules, as `check` reads PROJECT_CHECKS when it is read; its targets are listed after +# these all the same, as `make help` reads the files in turn. +-include tools/project.mk + +.PHONY: help check lint fmt setup tests clang sanitize coverage examples sizes self-check \ + tidy cppcheck headers docs arduino-lint clean + +help: ## This list + @awk 'BEGIN { FS = ":.*## " } /^## / { printf "\n%s\n", substr($$0, 4) } \ + /^[a-z0-9-]+:.*## / { printf " make %-12s %s\n", $$1, $$2 }' $(MAKEFILE_LIST) + @echo + @echo ' STRICT=1 for warnings as errors, as in CI.' + +## Everything at once + +# Cheap first, so that a typo fails in seconds rather than after the analysers. +check: STRICT := 1 +check: ## What CI runs, all of it +check: lint arduino-lint tests clang tidy cppcheck headers docs sanitize coverage examples \ + sizes self-check $(PROJECT_CHECKS) + +lint: ## The checks of seconds: clang-format, cpplint, shellcheck, actionlint, ruff + tools/lint.sh + +fmt: ## Format the C++ sources and the Doxygen blocks in place + tools/lint.sh --fix + +setup: ## The pinned Arduino core, and what tools/project.sh prepares beyond it + tools/setup.sh + +## Builds, each with its tests + +tests: ## The tests on the host, by GCC + cmake --workflow --preset $(PRESET)default + +clang: ## The same tests by clang, which warns about other things + cmake --workflow --preset $(PRESET)clang + +sanitize: ## The tests under AddressSanitizer and UBSan + cmake --workflow --preset sanitize + +# Into the job's summary as well when there is one, which is CI's. +coverage: ## The tests with --coverage, and what they reach of src/ + tools/coverage.sh + if [[ -n "$${GITHUB_STEP_SUMMARY:-}" ]]; then \ + { echo '```text'; cat build/coverage/coverage.txt; echo '```'; } >> "$$GITHUB_STEP_SUMMARY"; \ + fi + +examples: ## Every example in each variant, failing on a warning; flash and RAM as a table + tools/compile_examples.sh | tee -a "$${GITHUB_STEP_SUMMARY:-/dev/null}" + +# The table of the last `make examples`, not a build of its own, so that `make check` compiles +# the examples once; FIX=1 writes it into the README. +sizes: ## The table of flash and RAM in README.md against the last make examples + python3 tools/documented_sizes.py $(if $(FIX),--fix) + +self-check: ## examples/SelfCheck in simavr, in each variant + tools/self_check.sh + +## Analysers + +tidy: ## clang-tidy: the library and the examples with the board's flags, and the tests + tools/tidy.sh + +cppcheck: ## cppcheck over the library + tools/cppcheck.sh + +# The host's database from CMake, the board's from tools/tidy.sh: each header is compiled by +# the compiler that database names, so an #if only the board takes is compiled for the board. +headers: ## Every header of src/ compiled on its own, for the host and for the board + cmake --preset default >/dev/null + tools/tidy.sh --database-only >/dev/null + python3 tools/self_contained_headers.py build/host build/tidy/default + +docs: ## The reference from the Doxygen blocks, failing on a gap + tools/docs.sh + +# What git has, tracked or new, copied into build/arduino-lint/: the Library Manager sees +# the repository, not the working tree with its build/ and .venv, whose links arduino-lint would +# report. +arduino-lint: ## The rules of the Arduino Library Manager + tools/arduino_lint.sh + +## Housekeeping + +clean: ## Every build directory + rm -rf build diff --git a/OIL.md b/OIL.md new file mode 100644 index 0000000..f4e5ae7 --- /dev/null +++ b/OIL.md @@ -0,0 +1,70 @@ +# Open Issue List + +What is planned for TimerTwo, in the order it can be done. A pull request that works on an item +sets its status and links itself in the same PR; an item is `done` once that PR is merged. New +items go at the end with the next free number, so a number never changes meaning. + +Status: `open`, `in progress`, `done`, `dropped` (with the reason in the item). + +## Items + +| # | Item | Depends on | Status | PR | +|---|------|------------|--------|----| +| 1 | On the template embedded-cpp-template | – | in progress | #4 | +| 2 | The known bugs, each shown by a test first, and SelfCheck in simavr | 1 | open | | +| 3 | Version 2.0.0: a namespace, constants for macros, the template's checks | 2 | open | | +| 4 | Release 2.0.0 and the Library Manager | 3 | open | | + +### 1 On the template embedded-cpp-template + +The checks, CI and the dev container from the copier template +[embedded-cpp-template](https://github.com/theAndreas/embedded-cpp-template), which Utl and +MaxMatrix share, so that a change to one reaches the others with `copier update`; the template's +roadmap names it R-3. The library layout 1.5, `src/` and `examples/`, in place of the AtmelStudio +project; GPL-3.0-or-later as the licence, which TimerTwo had none of; the default branch `main`. + +The code keeps its API and its behaviour: clang-format once, the warnings of `-Wconversion` and +`-Wsign-conversion`, the documentation of the API, and what cpplint finds. The groups of +clang-tidy that the code of 2023 fails wait for 3, in `src/.clang-tidy` and +`examples/.clang-tidy`. Tests on the host against a mock of Timer2's registers hold what works +today; what does not is 2. + +*Done when* `make check` passes, and flash and RAM of the examples on the Uno are those of +before, or differ by what a commit names. + +### 2 The known bugs, each shown by a test first, and SelfCheck in simavr + +Found while bringing TimerTwo in. Each gets a test that fails on the code of 1, then the fix: + +- `resume()` lets the counter go on, but leaves the state `STATE_STOPPED`: `read()` refuses, and + `start()` starts again from 0. +- `stop()` before `init()` sets `STATE_STOPPED`, and `start()` then starts a timer that was + never set up. +- `start()` enables the interrupt again after `detachInterrupt()`, as the callback stays set. +- A duty of 255 sets OCR2B below OCR2A, 249 of 250 at 1 ms: the output is never high all the + time. And the duty is a share of OCR2A that `setPeriod()` does not set again. +- `read()` divides before it multiplies by the prescaler: at 16 MHz the steps below 16 are lost, + so it reads 24 us for 25. +- `F_CPU / 2000000uL` is 0 below 2 MHz, so every period gives a top of 0; and + `F_CPU / 1000000uL` truncates at 20 MHz, where `getPeriodMax()` is 24575 for 26214. +- A period of 0 sets a top of 0: the counter stands, and `start()` with a callback waits for it + forever. + +Then `examples/SelfCheck`, which tools/self_check.sh runs in simavr: the period counted in +callbacks and the PWM measured on pin 3, if simavr models mode 5 of Timer2 well enough; +`SIMAVR_MCU` in `tools/project.sh` is empty until then. + +### 3 Version 2.0.0: a namespace, constants for macros, the template's checks + +`timer_two::Timer2` with Google's names, in `src/timer_two/`, without `StandardTypes.h`; +`constexpr` for the macros that are constants. A class a test can construct, so that the tests +no longer need a process each. What a function returns when it refuses is decided then: an +`enum class` of TimerTwo's own, `bool`, or Utl's `Status`. XmegaTimer, the same API on the +ATxmega E5, is the model where it fits. `src/.clang-tidy` goes, and the groups in +`examples/.clang-tidy` with it. A sketch has to change its names: no aliases for the old ones, +a clean break. + +### 4 Release 2.0.0 and the Library Manager + +The README of 2.0.0 with the table of flash and RAM between `` markers, the tag, +`release.yml`, and the request to the Arduino Library Manager. diff --git a/README.md b/README.md index b2f3bbe..d09e7ce 100644 --- a/README.md +++ b/README.md @@ -63,4 +63,16 @@ void loop() { } ``` -For a more advanced usage see also *Sketch.ino* file. +This is [examples/Basics](examples/Basics/Basics.ino). For a more advanced usage see also +[examples/Read](examples/Read/Read.ino). + +## Development + +TimerTwo is built and checked as the projects made from +[embedded-cpp-template](https://github.com/theAndreas/embedded-cpp-template) are: `make` lists +every build and check, `make check` is what CI runs. [OIL.md](https://github.com/theAndreas/TimerTwo/blob/main/OIL.md) is what is planned, and +[AGENTS.md](https://github.com/theAndreas/TimerTwo/blob/main/AGENTS.md) what a contributor has to know. + +## Licence + +GPL-3.0-or-later, see [LICENSE](LICENSE). diff --git a/Sketch.ino b/Sketch.ino deleted file mode 100644 index 44feaea..0000000 --- a/Sketch.ino +++ /dev/null @@ -1,48 +0,0 @@ -#include - -/* -/* - This example toggles the PIN13 cyclically all 1ms and starts the PWM for PIN11. - The frequency of the PWM depends on the period of the timer. Furthermore the - use of the read method is demonstrated. -*/ - -#define PIN_TOGGLE 13u - - -void timerCallback() { - digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); -} - -void setup() { - pinMode(PIN_TOGGLE, OUTPUT); - if(Timer2.init(Timer2.getPeriodMax(), timerCallback) == E_NOT_OK) { - // Something went wrong, check your parameters - while(1); - } - if(Timer2.enablePwm(TimerTwo::PWM_PIN_11, 127) == E_NOT_OK) { - // Something went wrong, has init function already been called? - while(1); - } - if(Timer2.start() == E_NOT_OK) { - // Something went wrong, has init function already been called? - while(1); - } - - // delay of 20ms - delay(20u); - TimerTwo::TimeType elapsedTime{0u}; - - if(Timer2.read(elapsedTime) == E_NOT_OK) { - // Something went wrong, has init function already been called? - while(1); - } - - // Prints the measured time in µs since the last rollover of the timer. - // In this example the timer had no rollover until now. - Serial.println(elapsedTime); -} - -void loop() { - -} diff --git a/StandardTypes.h b/StandardTypes.h deleted file mode 100644 index a372e1d..0000000 --- a/StandardTypes.h +++ /dev/null @@ -1,64 +0,0 @@ -/****************************************************************************************************************************************************** - * COPYRIGHT - * --------------------------------------------------------------------------------------------------------------------------------------------------- - * \verbatim - * Copyright (c) Andreas Burnickl All rights reserved. - * - * \endverbatim - * --------------------------------------------------------------------------------------------------------------------------------------------------- - * FILE DESCRIPTION - * -------------------------------------------------------------------------------------------------------------------------------------------------*/ -/** \file StandardTypes.h - * \brief Main header file of standard types library - * - * \details Library with standard types - * - * - *****************************************************************************************************************************************************/ -#ifndef _STANDARD_TYPES_H_ -#define _STANDARD_TYPES_H_ - -/****************************************************************************************************************************************************** - * INCLUDES - *****************************************************************************************************************************************************/ - - -/****************************************************************************************************************************************************** - * GLOBAL CONSTANT MACROS - *****************************************************************************************************************************************************/ - /* standard type for configuration */ -#define STD_ON 1u -#define STD_OFF 0u - -#define STD_NULL_CHARACTER '\0' - - -/****************************************************************************************************************************************************** - * GLOBAL FUNCTION MACROS - *****************************************************************************************************************************************************/ -#define writeBit(Var, Bit, Value) \ -(Var = (Var & ~(1 << Bit)) | (Value << Bit)) - -/* read Bit Group */ -#define readBitGroup(Var, BitGroupMask, BitGroupPosition) \ -(Var = ((Var & ((uint8_t)BitGroupMask)) >> BitGroupPosition)) - -/* write Bit Group */ -#define writeBitGroup(Var, BitGroupMask, BitGroupPosition, Value) \ -(Var = ((Var & ~((uint8_t)BitGroupMask)) | ((Value << BitGroupPosition) & ((uint8_t)BitGroupMask)))) - - -/****************************************************************************************************************************************************** - * GLOBAL DATA TYPES AND STRUCTURES - *****************************************************************************************************************************************************/ - /* standard return type for functions */ -typedef enum { - E_OK = 0, - E_NOT_OK = 1 -} StdReturnType; - -#endif - -/****************************************************************************************************************************************************** - * E N D O F F I L E - *****************************************************************************************************************************************************/ \ No newline at end of file diff --git a/TimerTwo.cpp b/TimerTwo.cpp deleted file mode 100644 index 87ff147..0000000 --- a/TimerTwo.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/****************************************************************************************************************************************************** - * COPYRIGHT - * --------------------------------------------------------------------------------------------------------------------------------------------------- - * \verbatim - * Copyright (c) Andreas Burnickl All rights reserved. - * - * \endverbatim - * --------------------------------------------------------------------------------------------------------------------------------------------------- - * FILE DESCRIPTION - * -------------------------------------------------------------------------------------------------------------------------------------------------*/ -/** \file TimerTwo.c - * \brief Main file of TimerTwo library - * - * \details Arduino library to use Timer 2 - * - * - *****************************************************************************************************************************************************/ -#define _TIMERTWO_SOURCE_ - -/****************************************************************************************************************************************************** - * INCLUDES - *****************************************************************************************************************************************************/ -#include "TimerTwo.h" - - -/****************************************************************************************************************************************************** - * GLOBAL DATA - *****************************************************************************************************************************************************/ -TimerTwo& Timer2 = TimerTwo::getInstance(); // pre-instantiate TimerTwo - - -/****************************************************************************************************************************************************** - * C O N S T R U C T O R S - *****************************************************************************************************************************************************/ - -/****************************************************************************************************************************************************** - CONSTRUCTOR OF TimerTwo -******************************************************************************************************************************************************/ -/*! \brief TimerTwo constructor - * \details Instantiation of the TimerTwo library - * - * \return - - *****************************************************************************************************************************************************/ -TimerTwo::TimerTwo() -{ - State = STATE_INIT; - TimerIsrOverflowCallback = nullptr; - ClockSelectBitGroup = REG_CS_NO_CLOCK; -} /* TimerTwo */ - - -/****************************************************************************************************************************************************** - DESTRUCTOR OF TimerTwo -******************************************************************************************************************************************************/ -TimerTwo::~TimerTwo() -{ - -} /* ~TimerTwo */ - - -/****************************************************************************************************************************************************** - COPY CONSTRUCTOR OF TimerTwo -******************************************************************************************************************************************************/ -TimerTwo& TimerTwo::getInstance() -{ - static TimerTwo SingletonInstance; - return SingletonInstance; -} /* getInstance */ - - -/****************************************************************************************************************************************************** - * P U B L I C F U N C T I O N S - *****************************************************************************************************************************************************/ - -/****************************************************************************************************************************************************** - init() -******************************************************************************************************************************************************/ -/*! \brief initialization of the Timer2 hardware - * \details this functions initializes the Timer2 hardware - * - * \param[in] Microseconds period of the timer overflow interrupt - * \param[in] sTimerOverflowCallback Callback function which should be called when timer overflow interrupt occurs - * \return E_OK - * E_NOT_OK - TimerTwo is already initialized or given period is out of bounds - * \pre Timer has to be in NONE state - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::init(TimeType Microseconds, TimerIsrCallbackF_void sTimerOverflowCallback) -{ - StdReturnType ReturnValue = E_NOT_OK; - - if(STATE_INIT == State) { - ReturnValue = E_OK; - /* clear control register */ - TCCR2A = 0u; - TCCR2B = 0u; - - /* set mode 5: phase correct PWM */ - writeBit(TCCR2A, WGM20, 1u); - writeBit(TCCR2A, WGM21, 0u); - writeBit(TCCR2B, WGM22, 1u); - - if(setPeriod(Microseconds) == E_NOT_OK) { ReturnValue = E_NOT_OK; } - if(sTimerOverflowCallback != nullptr) { attachInterrupt(sTimerOverflowCallback); } - State = STATE_IDLE; - } - return ReturnValue; -} /* init */ - - -/****************************************************************************************************************************************************** - setPeriod() -******************************************************************************************************************************************************/ -/*! \brief set period of Timer2 overflow interrupt - * \details this functions sets the period of the Timer2 overflow interrupt therefore - * prescaler and timer top value will be calculated - * \param[in] Microseconds period of the timer overflow interrupt - * \return E_OK - * E_NOT_OK - Given period is out of bound - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::setPeriod(TimeType Microseconds) -{ - StdReturnType ReturnValue{E_NOT_OK}; - - if(Microseconds <= getPeriodMax()) { - /* OCR2A is TOP in phase correct PWM mode */ - OCR2A = getTimerCycles(Microseconds); - - if(STATE_RUNNING == State) { - /* reset clock select register, and start the clock */ - writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, ClockSelectBitGroup); - } - return E_OK; - } - return ReturnValue; -} /* setPeriod */ - - -/****************************************************************************************************************************************************** - enablePwm() -******************************************************************************************************************************************************/ -/*! \brief enable Pwm on given Pin - * \details this function enables Pwm on given Pin with given duty cycle - * - * \param[in] PwmPin pin where pwm should be enabled - * \param[in] DutyCycle duty cycle of pwm - * \return E_OK - * E_NOT_OK - TimerTwo is not initialized or wrong PwmPin was given - * \pre Timer has to be in READY, RUNNING or STOPPED state - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::enablePwm(PwmPinType PwmPin, byte DutyCycle) -{ - StdReturnType ReturnValue{E_NOT_OK}; - - if((STATE_IDLE == State) || (STATE_RUNNING == State) || (STATE_STOPPED == State)) - { - if(PWM_PIN_3 == PwmPin) { - ReturnValue = E_OK; - pinMode(PWM_PIN_3, OUTPUT); - /* activate compare output mode in timer control register */ - writeBit(TCCR2A, COM2B1, 1u); - } - - if(setPwmDuty(PwmPin, DutyCycle) == E_NOT_OK) { ReturnValue = E_NOT_OK; } - } - return ReturnValue; -} /* enablePwm */ - - -/****************************************************************************************************************************************************** - disablePwm() -******************************************************************************************************************************************************/ -/*! \brief disable Pwm on given Pin - * \details - * \param[in] PwmPin pin where pwm should be disabled - * \return E_OK - * E_NOT_OK - Wrong PwmPin was given - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::disablePwm(PwmPinType PwmPin) -{ - StdReturnType returnValue{E_NOT_OK}; - - if(PWM_PIN_3 == PwmPin) { - returnValue = E_OK; - /* deactivate compare output mode in timer control register */ - writeBit(TCCR2A, COM2B1, 0u); - } - - return returnValue; -} /* disablePwm */ - - -/****************************************************************************************************************************************************** - setPwmDuty() -******************************************************************************************************************************************************/ -/*! \brief set pwm duty cycle on given pin - * \details - * - * \param[in] PwmPin pin where pwm duty cycle should be set - * \param[in] DutyCycle duty cycle of pwm - * \return E_OK - * E_NOT_OK - TimerTwo is not initialized or wrong PwmPin was given - * \pre Timer has to be in READY, RUNNING or STOPPED STATE - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::setPwmDuty(PwmPinType PwmPin, byte DutyCycle) -{ - StdReturnType ReturnValue{E_NOT_OK}; - - if((STATE_IDLE == State) || (STATE_RUNNING == State) || (STATE_STOPPED == State)) { - /* duty cycle out of bound? */ - if(DutyCycle <= TIMERTWO_RESOLUTION) { - // use rule of three to calculate duty cycle related to timer top value - // OCR2A is top value of timer - uint32_t DutyCycleTrans = OCR2A * DutyCycle; - DutyCycleTrans >>= TIMERTWO_NUMBER_OF_BITS; - /* set output compare register value for given Pwm pin */ - if(PWM_PIN_3 == PwmPin) { - ReturnValue = E_OK; - OCR2B = DutyCycleTrans; - } - } - } - return ReturnValue; -} /* setPwmDuty */ - - -/****************************************************************************************************************************************************** - start() -******************************************************************************************************************************************************/ -/*! \brief start timer - * \details - * - * \return E_OK - * E_NOT_OK - TimerTwo is not in correct state - * \pre Timer has to be in READY or STOPPED STATE - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::start() -{ - if((STATE_IDLE == State) || (STATE_STOPPED == State)) { - /* reset counter value */ - TCNT2 = 0u; - /* start counter by setting clock select register */ - writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, ClockSelectBitGroup); - /* set overflow interrupt, if callback is set */ - if(TimerIsrOverflowCallback != nullptr) { - /* wait until timer moved on from zero, otherwise get phantom interrupt */ - while (TCNT2 == 0u); - /* enable timer overflow interrupt */ - writeBit(TIMSK2, TOIE2, 1u); - } - State = STATE_RUNNING; - return E_OK; - } - return E_NOT_OK; -} /* start */ - - -/****************************************************************************************************************************************************** - stop() -******************************************************************************************************************************************************/ -/*! \brief stop timer - * \details - * - * \return - - *****************************************************************************************************************************************************/ -void TimerTwo::stop() -{ - /* stop counter by clearing clock select register */ - writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, REG_CS_NO_CLOCK); - State = STATE_STOPPED; -} /* stop */ - - -/****************************************************************************************************************************************************** - resume() -******************************************************************************************************************************************************/ -/*! \brief resume timer - * \details - * - * \return E_OK - * E_NOT_OK - TimerTwo is not in stopped state - * \pre Timer has to be in STOPPED STATE - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::resume() -{ - if(STATE_STOPPED == State) { - /* resume counter by setting clock select register */ - writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, ClockSelectBitGroup); - return E_OK; - } - return E_NOT_OK; -} /* resume */ - - -/****************************************************************************************************************************************************** - attachInterrupt() -******************************************************************************************************************************************************/ -/*! \brief set timer overflow interrupt callback - * \details - * - * \param[in] TimerOverflowCallback timer overflow callback function - * \return E_OK - * E_NOT_OK - Callback function is nullptr - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::attachInterrupt(TimerIsrCallbackF_void TimerOverflowCallback) -{ - if(TimerOverflowCallback != nullptr) { - TimerIsrOverflowCallback = TimerOverflowCallback; - /* enable timer overflow interrupt */ - if(State == STATE_RUNNING) writeBit(TIMSK2, TOIE2, 1u); - return E_OK; - } - return E_NOT_OK; -} /* attachInterrupt */ - - -/****************************************************************************************************************************************************** - detachInterrupt() -******************************************************************************************************************************************************/ -/*! \brief clear timer overflow interrupt callback - * \details - * - * \return - - *****************************************************************************************************************************************************/ -void TimerTwo::detachInterrupt() -{ - /* clears the timer overflow interrupt enable bit */ - writeBit(TIMSK2, TOIE2, 0u); -} /* detachInterrupt */ - - -/****************************************************************************************************************************************************** - read() -******************************************************************************************************************************************************/ -/*! \brief read current timer value in microseconds - * \details this function returns the current timer value in microseconds - * - * \param[out] Microseconds current timer value - * \return E_OK - * E_NOT_OK - TimerTwo is not in running state - * \pre Timer has to be in RUNNING STATE - *****************************************************************************************************************************************************/ -StdReturnType TimerTwo::read(TimeType& Microseconds) -{ - if(STATE_RUNNING == State) { - /* save current timer value */ - uint16_t counterValue{TCNT2}; - byte TCNT2_tmp{TCNT2}; - - /* wait one counter tick, needed to find out counter counting up or down */ - do { TCNT2_tmp = TCNT2; } while (counterValue == TCNT2_tmp); - /* if counter counting down, add top value to current value */ - if(TCNT2_tmp < counterValue) { counterValue = (OCR2A - counterValue) + OCR2A; } - /* transform counter value to microseconds in an efficient way */ - Microseconds = ((counterValue * 1000uL) / (F_CPU / 1000uL)) << getPrescaleShiftScale(); - return E_OK; - } - return E_NOT_OK; -} /* read */ - - -/****************************************************************************************************************************************************** - * P R I V A T E F U N C T I O N S -******************************************************************************************************************************************************/ - -/****************************************************************************************************************************************************** - getPrescaleShiftScale() -******************************************************************************************************************************************************/ -inline byte TimerTwo::getPrescaleShiftScale() -{ - switch (ClockSelectBitGroup) - { - case REG_CS_NO_PRESCALER: - return 0u; - break; - case REG_CS_PRESCALE_8: - return 3u; - break; - case REG_CS_PRESCALE_32: - return 5u; - break; - case REG_CS_PRESCALE_64: - return 6u; - break; - case REG_CS_PRESCALE_128: - return 7u; - break; - case REG_CS_PRESCALE_256: - return 8u; - break; - case REG_CS_PRESCALE_1024: - return 10u; - break; - default: - return 0u; - } -} - -/****************************************************************************************************************************************************** - getPrescaleShiftScale() -******************************************************************************************************************************************************/ -inline byte TimerTwo::getTimerCycles(TimeType Microseconds) -{ - /* calculate timer cycles to reach timer period, counter runs backwards after TOP, interrupt is at BOTTOM so divide microseconds by 2 */ - uint32_t TimerCycles = (F_CPU / 2000000uL) * Microseconds; - /* calculate timer pre-scaler */ - if(TimerCycles < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_NO_PRESCALER; - else if((TimerCycles >>= 3u) < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_PRESCALE_8; - else if((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_PRESCALE_32; - else if((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_PRESCALE_64; - else if((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_PRESCALE_128; - else if((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_PRESCALE_256; - else if((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) ClockSelectBitGroup = REG_CS_PRESCALE_1024; - - return TimerCycles; -} - -/****************************************************************************************************************************************************** - I S R F U N C T I O N S -******************************************************************************************************************************************************/ -ISR(TIMER2_OVF_vect) -{ - Timer2.callTimerIsrOverflowCallback(); -} - - -/****************************************************************************************************************************************************** - * E N D O F F I L E - *****************************************************************************************************************************************************/ diff --git a/TimerTwo.h b/TimerTwo.h deleted file mode 100644 index f7c834b..0000000 --- a/TimerTwo.h +++ /dev/null @@ -1,164 +0,0 @@ -/****************************************************************************************************************************************************** - * COPYRIGHT - * --------------------------------------------------------------------------------------------------------------------------------------------------- - * \verbatim - * Copyright (c) Andreas Burnickl All rights reserved. - * - * \endverbatim - * --------------------------------------------------------------------------------------------------------------------------------------------------- - * FILE DESCRIPTION - * -------------------------------------------------------------------------------------------------------------------------------------------------*/ -/** \file TimerTwo.h - * \brief Main header file of TimerTwo library - * - * \details Arduino library to use Timer two - * - * - *****************************************************************************************************************************************************/ -#ifndef _TIMERTWO_H_ -#define _TIMERTWO_H_ - -/****************************************************************************************************************************************************** - * INCLUDES - *****************************************************************************************************************************************************/ -#include "Arduino.h" -#include -#include -#include - - -/****************************************************************************************************************************************************** - * LOCAL CONSTANT MACROS - *****************************************************************************************************************************************************/ -/* Timer2 is 8 bit */ -#define TIMERTWO_NUMBER_OF_BITS 8u -#define TIMERTWO_RESOLUTION (1uL << TIMERTWO_NUMBER_OF_BITS) - -/* OC2A Chip Pin 17, Pin name PB3 */ -#define TIMERTWO_A_ARDUINO_PIN 11u -//#define TIMERTWO_A_PORT_PIN PORTB3 -/* OC2B Chip Pin 5, Pin name PD3 */ -#define TIMERTWO_B_ARDUINO_PIN 3u -//#define TIMERTWO_A_PORT_PIN PORTD3 - -#define TIMERTWO_REG_CS_GP 0u -#define TIMERTWO_REG_CS_GM B111 - -#define TIMERTWO_MAX_PRESCALER 1024u - -#if __cplusplus < 201103L -# define nullptr NULL -#endif - -/****************************************************************************************************************************************************** - * LOCAL FUNCTION MACROS - *****************************************************************************************************************************************************/ - - -/****************************************************************************************************************************************************** - * GLOBAL DATA TYPES AND STRUCTURES - *****************************************************************************************************************************************************/ - - -/****************************************************************************************************************************************************** - * CLASS TimerTwo - *****************************************************************************************************************************************************/ -class TimerTwo -{ -/****************************************************************************************************************************************************** - * P U B L I C D A T A T Y P E S A N D S T R U C T U R E S -******************************************************************************************************************************************************/ - public: - /* Timer ISR callback function */ - typedef void (*TimerIsrCallbackF_void)(void); - -#if F_CPU < 8000000uL - using TimeType = uint32_t; -#else - using TimeType = uint16_t; -#endif - - /* Type which describes the internal state of the TimerTwo */ - enum StateType { - STATE_INIT, - STATE_IDLE, - STATE_RUNNING, - STATE_STOPPED - }; - - /* Type which includes the values of the Clock Select Bit Group */ - enum ClockSelectType { - REG_CS_NO_CLOCK, - REG_CS_NO_PRESCALER, - REG_CS_PRESCALE_8, - REG_CS_PRESCALE_32, - REG_CS_PRESCALE_64, - REG_CS_PRESCALE_128, - REG_CS_PRESCALE_256, - REG_CS_PRESCALE_1024 - }; - - /* - Info: PWM for Pin 11 can not be used because in Mode 5 (PWM, Phase Correct) - OCRA is TOP value of the Timer/Counter. So Duty Cycle for OC2A Pin 11 - can not be set, otherwise counter top value will be overwritten. - */ - - /* Type which includes the Pwm Pins */ - enum PwmPinType { - //PWM_PIN_11 = TIMERTWO_A_ARDUINO_PIN, - PWM_PIN_3 = TIMERTWO_B_ARDUINO_PIN - }; - -/****************************************************************************************************************************************************** - * P R I V A T E D A T A A N D F U N C T I N O N S -******************************************************************************************************************************************************/ - private: - TimerTwo(); - ~TimerTwo(); - TimerTwo(const TimerTwo&); - - TimerIsrCallbackF_void TimerIsrOverflowCallback; - StateType State; - ClockSelectType ClockSelectBitGroup; - - // methods - byte getPrescaleShiftScale(); - byte getTimerCycles(TimeType); - -/****************************************************************************************************************************************************** - * P U B L I C F U N C T I O N S -******************************************************************************************************************************************************/ - public: - static TimerTwo& getInstance(); - - // get methods - StateType getState() const { return State; } - TimerIsrCallbackF_void getTimerIsrCallbackFunction() const { return TimerIsrOverflowCallback; } - TimeType getPeriodMax() { return TimeType{((TIMERTWO_RESOLUTION / (F_CPU / 1000000uL)) * TIMERTWO_MAX_PRESCALER * 2u) - 1u}; } - // set methods - - // methods - StdReturnType init(TimeType = 1000uL, TimerIsrCallbackF_void = nullptr); - StdReturnType setPeriod(TimeType); - StdReturnType enablePwm(PwmPinType, byte); - StdReturnType disablePwm(PwmPinType); - StdReturnType setPwmDuty(PwmPinType, byte); - StdReturnType start(); - void stop(); - StdReturnType resume(); - StdReturnType attachInterrupt(TimerIsrCallbackF_void); - void detachInterrupt(); - StdReturnType read(TimeType&); - void callTimerIsrOverflowCallback() { TimerIsrOverflowCallback(); } - -}; - -/* TimerTwo will be pre-instantiated in TimerTwo source file */ -extern TimerTwo& Timer2; - -#endif - -/****************************************************************************************************************************************************** - * E N D O F F I L E - *****************************************************************************************************************************************************/ diff --git a/cmake/checks.cmake b/cmake/checks.cmake new file mode 100644 index 0000000..66e9770 --- /dev/null +++ b/cmake/checks.cmake @@ -0,0 +1,62 @@ +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# What every build on the host is checked with, for CMakeLists.txt to include: the warnings, +# the instrumentation of the presets sanitize and coverage, and the tests of what must not +# compile. This file comes from the template and is brought up to date with `copier update`; +# what the project builds is in CMakeLists.txt. +# +# CHECK_WARNINGS the warnings, for target_compile_options(); errors only where +# CMAKE_COMPILE_WARNING_AS_ERROR is on, as the ci- presets set it +# CHECK_INSTRUMENT --coverage, or the sanitizers, for the compile and the link options +# add_compile_fail_tests(DIRECTORY dir STANDARD std INCLUDES dir...) + +option(TIMERTWO_COVERAGE "Build with --coverage, for gcovr" OFF) +option(TIMERTWO_SANITIZE "Build with AddressSanitizer and UBSan" OFF) + +# -Wconversion and -Wsign-conversion above all: an int has 16 bits on the AVR, and a +# conversion that is harmless on the host can lose a value there. Braced initialization finds +# a narrowing only where a variable is initialized, not in the arithmetic after it. -Wshadow, +# as a name that hides another is read as the other. No -Werror: CMAKE_COMPILE_WARNING_AS_ERROR +# decides, on in CI and under `make check`, off while somebody is in the middle of debugging. +set(CHECK_WARNINGS -Wall -Wextra -Wconversion -Wsign-conversion -Wshadow) + +set(CHECK_INSTRUMENT) +if(TIMERTWO_COVERAGE) + list(APPEND CHECK_INSTRUMENT --coverage) +endif() +if(TIMERTWO_SANITIZE) + list(APPEND CHECK_INSTRUMENT -fsanitize=address,undefined + -fno-sanitize-recover=all -fno-omit-frame-pointer) +endif() + +# What must not compile: each .cpp file in DIRECTORY uses the library wrongly, and its test +# passes only if the compiler stops it with the message of the static_assert that its line +# "// Expected: ..." names. A static_assert that went missing, or another error, fails it. The +# compiler is called directly, with -fsyntax-only and in STANDARD, as avr-gcc builds a sketch: +# no target, so that tests run in parallel never build in the same tree at once. +function(add_compile_fail_tests) + cmake_parse_arguments(PARSE_ARGV 0 arg "" "DIRECTORY;STANDARD" "INCLUDES") + set(includes) + foreach(dir IN LISTS arg_INCLUDES) + list(APPEND includes -I${dir}) + endforeach() + file(GLOB cases CONFIGURE_DEPENDS ${arg_DIRECTORY}/*.cpp) + foreach(case IN LISTS cases) + get_filename_component(name ${case} NAME_WE) + file(STRINGS ${case} expected REGEX "^// Expected: " LIMIT_COUNT 1) + string(REGEX REPLACE "^// Expected: " "" expected "${expected}") + if(expected STREQUAL "") + message(FATAL_ERROR "${case} names no message: a line \"// Expected: \".") + endif() + add_test(NAME compile_fail/${name} + COMMAND ${CMAKE_CXX_COMPILER} -std=${arg_STANDARD} -fsyntax-only + ${includes} ${case}) + # GCC says "static assertion failed: ", Clang "static assertion failed due to + # requirement '...': "; both on one line. + set_tests_properties( + compile_fail/${name} + PROPERTIES PASS_REGULAR_EXPRESSION + "static assertion failed[^\n]*${expected}") + endforeach() +endfunction() diff --git a/docs/CodingStyle.md b/docs/CodingStyle.md new file mode 100644 index 0000000..27e0e2f --- /dev/null +++ b/docs/CodingStyle.md @@ -0,0 +1,228 @@ +# Writing the code + +How the code of TimerTwo is written: how a file is split, how large a function may be, +which parts of C++ are used on a microcontroller and which are not. It holds for `src/`; the +tests and the examples follow it where a rule does not say otherwise. How a comment and a +Doxygen block are written is in [Documentation.md](Documentation.md), how the code is tested in +[Testing.md](Testing.md). + +The rules hold for every target. What holds for one target only, as its way to put text into +flash or to turn interrupts off, is in its profile in [targets/](targets/): for this project +[targets/avr.md](targets/avr.md). + +This file is for a person and for a coding agent alike. `AGENTS.md` points every agent here. + +## How to read a rule + +Each rule has an id, so that a review, a commit or a `NOLINT` can name it, and says what checks +it: + +- **A tool**, as clang-tidy, clang-format or cpplint: the rule is enforced by `make lint` and + `make tidy`, and its configuration is the authority; this file only says why. +- **Review**: no tool can check it. The author checks it, and the reviewer, human or agent. + +## Principles + +- **P-1 The smallest target is the measure.** The code runs on targets from an 8-bit + microcontroller with 2 KiB of RAM to a host with gigabytes: an `int` may have 16 bits, there + may be no floating point unit, no heap, no exceptions and no standard library. Code that is + right on the host but costly or wrong on the smallest target is wrong. Its profile in + `targets/` says what that target lacks. +- **P-2 The compiler and the tools decide what they can.** A rule a tool can check is a setting + of the tool, not a paragraph here. A rule here that a tool could check is a gap to close. +- **P-3 Three standards, in this order:** the C++ Core Guidelines, MISRA C++:2023 + ([Misra.md](Misra.md) says rule by rule how far), and the + [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) for everything they + leave open, as names and layout. Where they differ, the first wins, and P-1 over all three; + the departures from Google are listed below. +- **P-4 Clear before clever.** The next reader is a stranger, or an agent with no context. + +## Files + +| Id | Rule | Checked by | +|---|---|---| +| F-1 | A header holds the declarations a user needs, documented; a `.cpp` holds the definitions. | Review | +| F-2 | A header includes what its declarations need, not what its bodies need. In the class body stay only a template, which every caller has to see, a `constexpr` function, and an accessor of one statement; anything more, a state machine, an `#if` ladder, a body that would pull in a header for itself, is defined in the `.cpp`. Inlining is no reason to keep a body in the header: with `-flto` the compiler inlines across sources as readily as within one, and what a header costs is every file that includes it. A header that one source alone includes may keep its bodies, until a second one includes it. | Review, `make headers` | +| F-3 | One class, or one family of functions, per header and source. A file is named exactly as the class it holds: `RingBuffer.h` and `RingBuffer.cpp` for `RingBuffer`, `array.h` for a class that mimics the standard's `array`; a family of functions after the family, in lower case: `clamp.h`. | Review | +| F-4 | Every header compiles as the only include of an empty file. | `make headers` | +| F-5 | A file includes what it uses, and nothing it does not ("include what you use"). | `misc-include-cleaner` | +| F-6 | Header guards as `PROJECT_PATH_FILE_H_`, from the path. | cpplint | +| F-7 | Includes in Google's order, each group sorted. | clang-format | +| F-8 | Every file starts with the copyright and the SPDX licence as `//` lines. | Review | +| F-9 | A library lies in its own namespace, so that its names cannot meet those of its user; an application may stay in the global one. What is not part of a library's API lies in its namespace `internal`. No `static` and no anonymous namespace in a header. | `google-build-namespaces`, Review | +| F-10 | A source file is ASCII, with LF line ends: a display on the device may show no umlaut, and a byte that is not ASCII in a string is a byte more than its character. | `.editorconfig`, Review | +| F-11 | A `.cpp` defines its functions in the order the header declares them. | Review | +| F-12 | A header and its source lie side by side in one folder, a folder per module: `src/Text/MaxMatrixText.h` beside `src/Text/MaxMatrixText.cpp`. No tree of headers apart from the tree of sources, as `inc/` and `src/`: what is not part of the API is told by the namespace `internal` (F-9), not by a folder, and an Arduino library has everything below `src/` anyway. | Review | +| F-13 | Files are grouped in folders, not left to pile up in one: a folder holds what belongs together, and when it holds more than about a dozen files, or files of more than one module, it is split by module. The same for `test/`, which mirrors `src/`, for `tools/`, `docs/` and `examples/`. | Review | +| F-14 | No cycle of includes: two headers that need each other are one, or a third holds what both need. | Review | +| F-15 | An example is copied into a sketch as it stands, so it is code to ship: complete, checking the results it gets, and with what a user has to adapt, as a pin, named at its top. | Review, `make examples` | + +## Functions + +| Id | Rule | Checked by | +|---|---|---| +| FN-1 | A function does one thing, and its name says which. If the name needs an "and", it is two. | Review | +| FN-2 | At most 40 lines in its body. A test has no limit of lines, as many cases make it long but flat, and SelfCheck is a test; the other limits hold for it. | `readability-function-size` | +| FN-3 | At most 4 parameters; more are a struct. | `readability-function-size` | +| FN-4 | At most 3 levels of nesting within the body; an early return over an `else`. | `readability-function-size`, `readability-else-after-return` | +| FN-5 | A cognitive complexity of at most 15. In a test, what GoogleTest's macros expand to does not count, its own branches do. | `readability-function-cognitive-complexity` | +| FN-6 | No recursion: the depth of the stack cannot be known when compiling, and on a small target the stack is what is left of the RAM. | `misc-no-recursion` | +| FN-7 | A parameter that is cheap to copy (up to two pointers in size) is passed by value, any other by `T const&`; one the function writes by pointer or by `T&` only where a return value cannot carry it (F.16, F.20). | `performance-unnecessary-value-param`, Review | +| FN-8 | A result is returned, not written into a parameter (F.20). Several results are a struct. | Review | +| FN-9 | A function that can be `constexpr` is. In C++11 it is one `return`. | Review | +| FN-10 | A result that must not be ignored, as an error, is marked so with `TIMERTWO_NODISCARD` from `timer_two/attributes.h`: `[[nodiscard]]` from C++17, GCC's `warn_unused_result` before it. An attribute of a later standard is a macro so, chosen by `__cplusplus`. A result dropped on purpose goes to `Discard()` of the same header, with the reason in a comment: `Discard(Send(frame)); // sent again on the next tick`. Never `(void)` or `static_cast`: before C++17 GCC warns through both, clang does not, so a cast that passes on the host fails the build for the target. | `-Wunused-result`; the reason by review | +| FN-11 | A function is `const` when it leaves unchanged what a user sees of the object: its value, and what it controls through a pointer, as a pin, a register or a buffer it does not own. Constness is logical, not what the compiler allows: a function that writes a register through a member pointer is not `const`, though it compiles as one; a cache it updates is `mutable` (C-11). | `readability-make-member-function-const`; what is written through a pointer by review | +| FN-12 | A default argument only where its value is self-evident, and never on a `virtual` function. | `google-default-arguments`, Review | +| FN-13 | No code copied and changed a little: what two places do alike is one function. | Review | +| FN-14 | A loop that only looks for something is a function of its own, named as a question, with early returns: `bool ContainsPin(...)`, not a flag set inside a loop. | Review | +| FN-15 | A parameter that may be absent is a pointer, and its block says that it may be null; any other the function reads or writes is a reference. A member that refers to an object the class does not own, and that may be absent, is a pointer. One that must exist is a `reference_wrapper`, taken by reference in the constructor, so that it is never null and the class stays assignable: `explicit Display(Spi& spi) : spi_{spi} {}`. Which one, by M-3: `std::reference_wrapper` where every target has ``, else the counterpart of the ETL or Utl, else one of the project's own with its interface. Where an object of the class is made when compiling, as a global one (M-5), the wrapper's constructor has to be `constexpr` as well: the standard's is so only from C++20. Never a reference or a `const` member, which take the assignment from the class. What the class changes through the member counts for FN-11. | `cppcoreguidelines-avoid-const-or-ref-data-members`, Review | +| FN-16 | Two parameters of the same type whose order means something and that a caller can swap unnoticed, as a pin and a count, take a type each: a small `struct` or an `enum class`, which costs nothing once optimized. A `using` makes no type of its own (T-16). | `bugprone-easily-swappable-parameters`, Review | + +## Types and values + +| Id | Rule | Checked by | +|---|---|---| +| T-1 | Integers of fixed width, `uint8_t` to `int32_t`, in `src/`, a loop counter among them: the width of `int` depends on the target, 16 bits on an 8-bit microcontroller and 32 on the host, so a test on the host misses an overflow on the device. A counter takes the type of what it is compared with, `size_t` for a size, `uint8_t` for a small range. `bool`, `char` for text and `size_t` stay; so does `int` where an API of the platform gives it. | Review, until a check of our own (ROADMAP C-5) | +| T-2 | No implicit conversion that can change a value. | `-Wconversion`, `-Wsign-conversion` | +| T-3 | Braced initialization: `int count{0};`, `Point p{1, 2};`, and in a member initializer list. | `house-braced-member-init` in the initializer list, Review elsewhere | +| T-4 | `const` to the right of what it makes constant: `char const*`, `T const&`. | clang-format | +| T-5 | Everything that does not change is `const`; a value known when compiling is `constexpr`. | `misc-const-correctness` | +| T-6 | `constexpr` before `const` before a macro. A macro only where nothing else will do, as for a conditional build or a macro the platform requires. | `cppcoreguidelines-macro-usage` | +| T-7 | `enum class`, with its underlying type: `enum class Mode : uint8_t`. | `cppcoreguidelines-use-enum-class`,`performance-enum-size` | +| T-8 | `auto` only where the type stands in the same line already, as in a cast, or cannot be written, as of a lambda. | `modernize-use-auto`, Review | +| T-9 | No C-style cast. `static_cast`; `reinterpret_cast` and `const_cast` only with a `NOLINT` and its reason. Where a pointer is cast, two things differ by target: its width, 16 bits on an 8-bit microcontroller and 64 on the host, so that an address as a number is a `uintptr_t`; and the alignment, so that a pointer is not cast to a type that needs a stricter one. No cast through `void*` to hide a change of type. | `cppcoreguidelines-pro-type-*`, `google-readability-casting`, `bugprone-casting-through-void` | +| T-10 | `nullptr`, never `NULL` or `0`. | `modernize-use-nullptr` | +| T-11 | No magic number: a value with a meaning has a name. Without one pass only what `readability-magic-numbers` lets pass, 0 to 4 and the floating point values 1.0 and 100.0. Tests and examples are exempt: their numbers are their data. | `readability-magic-numbers` | +| T-12 | A range-based `for` where the index is not needed, taking each element by `const&` unless a copy is meant: `for (uint8_t const pin : pins)`, `for (Led const& led : leds)`. | `modernize-loop-convert`, `performance-for-range-copy` | +| T-13 | A variable is declared where it is first needed, initialized, one per declaration, in the smallest scope; a new value that means something else is a new variable, not the old one reused. A data member is initialized too (C-5). | `cppcoreguidelines-init-variables`, `cppcoreguidelines-pro-type-member-init`, `readability-isolate-declaration`, Review | +| T-14 | One side effect per statement: no `++` in a condition, no assignment inside an expression, and none in the argument of `assert` or another macro, which a build may drop or evaluate twice. | `bugprone-inc-dec-in-conditions`, `bugprone-assignment-in-if-condition`, `bugprone-assert-side-effect`, `bugprone-macro-repeated-side-effects`, Review | +| T-15 | A `switch` over an `enum class` names every value and has no `default`, so that the compiler reports a value added later; any other `switch` has a `default`. Where the value may be one the `enum` does not name, as one cast from a number or read from memory, the function handles it after the `switch`, as an error it returns: the compiler's report stays, and so does the way out. A test reaches it with `static_cast()` of an unnamed value, which is valid, as the `enum` has its underlying type (T-7). | `-Wswitch`, `bugprone-switch-missing-default-case` | +| T-16 | `using` for an alias, never `typedef`: `using Callback = void (*)(uint8_t);`. | `modernize-use-using` | +| T-17 | Never Arduino's `byte`, which is an `unsigned char` that says nothing of what it holds. A byte that is a number, a level or a count, is `uint8_t`. A byte that is raw data, as of a buffer, a register or a frame on a bus, is a type that is no number, by M-3: `std::byte` where every target has C++17, else `etl::byte` or Utl's counterpart, else one of the project's own after the same pattern, an `enum class` of `unsigned char` with `to_integer()`. Raw data then takes only bitwise operators, and is a number only through `to_integer()`. | Review | +| T-18 | An expression does one thing. A computation of several steps, or a condition of several parts, is split into named steps: a `const` local for each value with a meaning, a small function for a step that needs explaining or recurs, so that each line reads as what it computes. A step whose name explains it is worth a function even when called once. Named functions called one in the argument of the next read as a pipeline and stay, as long as they fit on a line: `ToLevel(GetWeightedIntensity(GetIntensity(pixel)))`. | Review (ROADMAP C-3) | +| T-19 | Arithmetic on a type narrower than `int` is done in `int`, after the promotion, and `int` has a sign and on an 8-bit microcontroller 16 bits: there `uint8_t * uint8_t` overflows from 182 * 182 on, on the host `uint16_t * uint16_t` from 46341 * 46341, and the overflow of a signed type is undefined. An operand is widened before the operation, to the least unsigned width that holds the result: `uint32_t const area{static_cast(width) * height};`. Not wider: on an 8-bit target an operation of 32 bits costs several of 16 (P-1). `~` of a `uint8_t` is a negative `int`, cast back before it is compared or shifted. | `-Wconversion` for the narrowing back, `make sanitize` for the widths of the host, Review | +| T-20 | An array is a class that knows its size, `std::array` or its counterpart by M-3, which does not decay to a pointer; a C array only for a string literal: `char const kName[] = "font";`. An element is reached by index, not by arithmetic on a pointer. | `modernize-avoid-c-arrays`, `cppcoreguidelines-pro-bounds-pointer-arithmetic` | +| T-21 | A `char` is widened to a number through `unsigned char`: whether `char` has a sign depends on the target, and where it has one, a character above 127 turns negative. | `bugprone-signed-char-misuse` | + +T-18 in an example: + +```cpp +// Not: +if ((now - start_ >= kInterval) && (state_ == State::kOn) && !paused_) { +// But: +bool const elapsed{now - start_ >= kInterval}; +bool const running{state_ == State::kOn && !paused_}; +if (elapsed && running) { +``` + +## Classes + +| Id | Rule | Checked by | +|---|---|---| +| C-1 | `struct` for data with public members only and no invariant, `class` for everything else. | `misc-non-private-member-variables-in-classes` | +| C-2 | The order in a class: `public`, `protected`, `private`; in each, types and constants, constructors and destructor, functions, data members. | Review | +| C-3 | The rule of zero first. Else the rule of six: a class that declares a special member declares all six, the default constructor among them; `= default` and `= delete` count. | `cppcoreguidelines-special-member-functions` for five; the default constructor by review, until a check of our own (ROADMAP C-4) | +| C-4 | A constructor with one argument is `explicit`, unless the conversion is meant; then a `NOLINT` says why. | cpplint `runtime/explicit` | +| C-5 | A default the same for every constructor is a member initializer (C.48); the rest is in the initializer list (C.49), never assigned in the body. | `modernize-use-default-member-init`, `cppcoreguidelines-prefer-member-initializer` | +| C-6 | `virtual` only with its reason in a comment at the class: each class with a `virtual` function has a table, which takes RAM on some targets (see the profile), and a call through it cannot be inlined. A template, or a function reference, often does the same at no cost; the reason says why it does not here. That a test wants to replace the class is no reason: the test is handed the hardware (H-3), or the class is a parameter of a template. | Review | +| C-7 | A base class with a `virtual` function has a public virtual or protected non-virtual destructor. | `cppcoreguidelines-virtual-class-destructor` | +| C-8 | Inheritance is public and of an interface; a class is reused by holding it, not by deriving from it. | Review | +| C-9 | Data members are `private` and end in `_`. | `readability-identifier-naming` | +| C-10 | A function that overrides says `override`, or `final`, and not `virtual` again. | `modernize-use-override` | +| C-11 | `mutable` only for what is not part of the state a user sees, as a cache (FN-11). | Review | +| C-12 | `friend` only where nothing else will do, as an operator that needs the members; with its reason. | Review | +| C-13 | An operator is overloaded only where its meaning is obvious: `Point + Point`, not `Point * Point`. | `misc-unconventional-assign-operator`, Review | +| C-14 | A special member that does what the compiler's would is `= default`, not written out: `Sensor() = default;`, not `Sensor() {}`. | `modernize-use-equals-default` | + +## Memory and the microcontroller + +| Id | Rule | Checked by | +|---|---|---| +| M-1 | No heap: no `new`, `delete`, `malloc` or `free`, not even in `setup()`. The size of everything is known when compiling, and the RAM a build takes is the RAM it needs. | `cppcoreguidelines-no-malloc`, `cppcoreguidelines-owning-memory` | +| M-2 | No exceptions and no RTTI: no `throw`, `try`, `dynamic_cast` or `typeid`. Small targets have neither, and on the others they cost flash and time that cannot be bounded. Nor a `static_cast` from a base down to a derived class in its place: where a design needs one, the base lacks a function. | the target's build, `cppcoreguidelines-pro-type-static-cast-downcast`, Review | +| M-3 | Reuse before writing, in this order: (1) what the project has already, a function or class that does it; (2) the standard library, where every target of the project has it, and only its parts that need neither heap nor exceptions (M-1, M-2), as `std::array`, ``, ``; where a target lacks it, `std::` stands only in the code of the targets that have it; (3) a library in the style of the standard library that the project uses, as the [ETL](https://github.com/ETLCPP/etl) or Utl; (4) only where none has it, it is written: once, for reuse, with the interface of the standard library's counterpart, so that it can give way to `std::` or `etl::` later, in a module folder of its own, as `src/timer_two/Utility/`, with its test. The tests on the host may use the standard library. | Review | +| M-4 | Constant data, as text and tables, is `constexpr` or `const`, so that it can lie in flash. Where a target needs more to put it there and read it, its profile says how. A constant in a header whose address is taken, as a table read by an index known only at run time, is declared `extern` there and defined once in a `.cpp`: a `constexpr` at namespace scope gives every file that takes its address a copy of its own. A value used as a value may stay `constexpr` in the header; from C++17, `inline constexpr` does both. | Review, the profile | +| M-5 | No global object with a constructor that does work: the order of initialization across files is not defined. An object of static storage is initialized when compiling, by a `constexpr` constructor, and has no destructor of its own, which would cost flash for an end the device never reaches. What has to start with work gets a `Begin()` that the application calls in `setup()`. | `cppcoreguidelines-avoid-non-const-global-variables`, `cert-err58-cpp` | +| M-7 | The cost of an entity in flash and RAM, where it matters, is stated in its Doxygen block. | Review | + +## Time, hardware and interrupts + +| Id | Rule | Checked by | +|---|---|---| +| H-1 | The library does not block. Work that takes time is spread over an `Update()` that the application calls in its main loop; a busy wait only for the microseconds a datasheet asks between two steps of the hardware, with the datasheet's figure in a comment. | Review | +| H-2 | Time is an unsigned count of a fixed width from a clock the library is given, as a millisecond counter, and a span is measured as the difference: `now - start >= interval`, never `now >= start + interval`. The difference is right across the overflow of the counter, the sum is not. | Review, a test across the overflow | +| H-3 | The hardware is handed in, not written into the library: pins, ports and peripherals as parameters of the constructor or of a template. The library is then tested on the host against the mock, and runs on another board. | Review | +| H-4 | A register and its bits by the names of the vendor's header, or by a named `constexpr`, never by a number. The profile names the header. | `readability-magic-numbers`, Review | +| H-5 | An interrupt routine does the least it can: it copies a value or sets a flag, and returns. No output, no wait, no floating point, no call that takes long. | Review | +| H-6 | What an interrupt routine and the rest share is `volatile`. The rest reads or changes it in a critical section, with the interrupts off, where it is wider than what the target reads in one access or is read and written in one step, as `++count`. The profile says how a critical section is written. | Review | +| H-7 | Fixed point before `float` where the smallest target has no floating point unit, as the profile says: there the first `float` brings the soft-float routines and their flash. A `float` takes its reason in a comment. No `double`: its width differs between targets, 32 bits on some and 64 on the host, so that a test on the host does not compute what the device does. | `-Wdouble-promotion`, Review | +| H-8 | Bitwise operators on unsigned types only, the masks named: `constexpr uint8_t kReadyBit{0x04U};`. A shift is by less than the width of its type, after the promotion to `int` that a `uint8_t` takes. | `-Wshift-count-overflow`, Review | + +## Errors + +| Id | Rule | Checked by | +|---|---|---| +| E-1 | An error is returned, as a `Result` or an `enum class` of errors, and never ignored silently (FN-10). Each project defines its own error type; the template brings none. | Review | +| E-2 | What the caller must ensure is a precondition: a `static_assert` where the compiler can check it, a `\pre` in the block otherwise. | Review | +| E-3 | Misuse that can be found when compiling fails when compiling, and a test of what must not compile proves it: `add_compile_fail_tests()`. | `test/` | + +## Names + +A name says what the entity is or does, in the terms of its domain: `brightness`, not `val`; +`ReadTemperature()`, not `Process()`. No abbreviation but the common ones (`i` for an index, +`n` for a count) and those of the domain (`pwm`, `adc`). A short name is fine where its scope is +a few lines, as Google allows; the further a name is seen, the more it says. Checked by review: +`readability-identifier-length` is off for that reason. + +A template parameter is named for its role, as any other name, never by a single letter, not +even where the scope is short: `template class Result`, +`\tparam Element`, not `T` and `E`. A pack is plural: `typename... Args`. Checked by review; no +check of clang-tidy asks for a length of a template parameter alone, a candidate for a check of +our own (ROADMAP C-3). + +As Google names, enforced by `readability-identifier-naming`; `.clang-tidy` is the authority. + +| What | How | Example | +|---|---|---| +| Namespace | `lower_case` | `timer_two` | +| File | as the class it holds (F-3) | `RingBuffer.h`, `array.h`, `clamp.h` | +| Type, function | `CamelCase` | `RingBuffer`, `PushBack()` | +| Accessor | like the member it gives | `size()` | +| Variable, parameter | `lower_case` | `byte_count` | +| Private member | `lower_case_` | `head_` | +| Constant, enum value | `kCamelCase` | `kMaxSize` | +| Macro | `TIMERTWO_UPPER_CASE` | `TIMERTWO_NODISCARD` | + +A type that mimics one of the standard library takes its names, as `array`, `size_type`; the +project lists it in `.clang-tidy`. + +No name belongs to the compiler and its library: none with two underscores in a row, none that +begins with an underscore and a capital letter, and none at namespace scope that begins with an +underscore. The headers of a vendor are full of them. Checked by `bugprone-reserved-identifier`. + +## Where we depart from Google + +Google's guide is written for large programs on servers, with the standard library. Where it +does not fit a microcontroller, or MISRA asks for more, this file wins: + +| Google says | Here | Why | +|---|---|---| +| `.cc` files | `.cpp` | Arduino compiles only `.cpp` from `src/`, and most embedded toolchains expect it | +| File names in lower case | Named as the class (F-3) | A file is found by the name of what it holds; Arduino names a library's header after the library anyway | +| `int` is the integer to use | Fixed width (T-1) | The width of `int` differs between targets; MISRA 6.9.2 | +| Braces around a one-line body are optional | Always braces | MISRA 9.3.1 | +| The standard library, `std::unique_ptr` for ownership | Its parts without heap and exceptions where every target has it, else a library like it (M-3); no ownership by pointer (M-1) | A small target may have no standard library, and there is no heap | +| Comments in `//`, any style | Doxygen blocks `/*! */` for the API | The reference is built from them (Documentation.md) | +| `const int` or `int const`, consistently | `int const` (T-4) | Read from right to left, as the rest of a type | +| Brace or `=` initialization | Braced (T-3) | It refuses a narrowing conversion | +| No exceptions | No exceptions | The same, for another reason: a small target has none (M-2) | + +## Suppressing a check + +| Id | Rule | Checked by | +|---|---|---| +| S-1 | A `NOLINT` names every check it suppresses, never none and never a pattern as `*`, and says why, on the same line or the one above: `// NOLINT(runtime/explicit): a Result is made from its value`. | Review (ROADMAP C-3) | +| S-2 | `NOLINTNEXTLINE` over `NOLINT` where the reason does not fit behind the code; never `NOLINTBEGIN` around more than one entity. | Review | +| S-3 | A check that is wrong for the whole project is turned off in `.clang-tidy`, with the reason, not suppressed line by line. | Review | +| S-4 | The code is changed first; a suppression is the last way, not the shortest. Its reason answers three questions: why the check reports the line, why the line stays as it is, and what keeps it from doing harm, as a test, a `static_assert` or a bound. "Intended" answers none. | Review | +| S-5 | A suppression of a report the tool gets wrong says so, with the tool's issue where there is one, and is looked at again when the tool is updated: once the tool is right, it goes. | Review | diff --git a/docs/Documentation.md b/docs/Documentation.md new file mode 100644 index 0000000..df2117e --- /dev/null +++ b/docs/Documentation.md @@ -0,0 +1,154 @@ +# Documenting the code + +How the code of TimerTwo is documented: which comments are Doxygen blocks, what each block says, and how +the style is checked. The reference built from the blocks is published on GitHub Pages; the style +holds for every header in `src/`. + +## Two kinds of comment + +- **A Doxygen block `/*! ... */`** documents an entity for its user: what it is, how to use it, + what it costs. It stands right above the declaration, in the header, and ends up in the + reference. +- **A comment on the implementation** explains it to the next person who changes it: why it is + written this way, which alternative was rejected and why. It is not in the reference. + - One or two lines, it is a `//` comment. + - Three lines or more, or more than one paragraph, it is a block `/* ... */`, each line + starting with ` * `, without the `!` that would make it Doxygen's. + +A comment says what the code cannot say for itself. It does not repeat the code. + +### Where a comment on the implementation stands + +Where the code it explains is, never between a Doxygen block and its declaration, where it would +read as a second comment of no one: + +- **In the body** of the function it explains, as why a constructor is implicit, or why + `__builtin_addressof` and not `&`. +- **Above the private member** whose layout it explains, as why a value and a flag lie side by + side rather than in a union. +- **At the definition in the `.cpp`**, when it explains that. +- **In the Doxygen block** instead, when the user should know it after all: that + `reference_wrapper r = 5` does not compile is for the user, as a `\note`. + +Only a `NOLINTNEXTLINE` stands between a block and its declaration, as it has to stand right above +the line it is for. + +## The block + +```cpp +/*! + * \brief Returns the element at `index`, or IndexError::kOutOfRange. + * + * A copy, as a Result holds a value. To write, check the index and use + * operator[]. + * + * \param[in] index The position, from 0. + * \return The element, or IndexError::kOutOfRange if `index` >= size(). + * + * \stddiff Returns a Result where std::span::at() throws std::out_of_range. + */ +Result at(size_type index) const; +``` + +- `/*!` on a line of its own, each further line starting with ` * `, and ` */` on a line of its + own. A block that holds only a brief is one line: `/*! \brief The width, in columns. */`. +- An enum value, a member or a struct field is documented behind it, with `/*!< ... */`, when the + brief is all it needs and fits on the line. If it does not, a one-line block + `/*! \brief ... */` stands above it, as a comment wrapped behind code is what cpplint calls a + "complex multi-line comment". +- Commands start with a backslash, `\brief`, never with `@`. +- A line that continues a command starts where the text after the command starts: + + ```cpp + * \return The view of them, or IndexError::kOutOfRange if `position` lies + * beyond the end. + ``` + + `tools/lint.sh --fix` indents it so, with `tools/lib/doc_indent.py` after clang-format, which + keeps such a line but starts one it breaks at the margin again; `tools/lint.sh` fails where a + line is not indented so. + +### The parts, in this order + +| Part | Says | +|---|---| +| `\brief` | One sentence, ending in a full stop. Always written out. | +| Description | After an empty line: what the user has to know beyond the brief, in a few short paragraphs. | +| `\tparam` | Each template parameter that the user chooses. | +| `\param[in]`, `[out]`, `[in,out]` | Each parameter, with its direction. | +| `\return` | What comes back. For a `Result`, the value and each error, with when. A one-line block whose brief already says it, "Returns the number of elements.", leaves it out. | +| `\pre` | What the caller must ensure, and what happens if not: undefined, or reported by a check the library makes on request. | +| `\note`, `\warning` | What is easy to miss. `\warning` only where a mistake is costly. | +| `\stddiff` | Where it differs from the entity of the standard it follows, and why. | +| `\see` | A related entity, where the link helps. | + +A function that returns nothing has no `\return`. Every parameter has its `\param`, even the only one. A part that has nothing to say is left out. + +### The brief + +- A function: a verb in the third person, saying what it does. "Returns the element at + `index`.", "Writes `value` into `buffer`.", "Turns on the texts of the group." +- A type: a noun phrase, saying what it is. "A view of chars in RAM.", "A value of T, or none." +- A value or a member: what it holds or means. "The base, 2 to 36." + +### The description + +- Plain, complete sentences. Present tense, active voice, no "we". +- What the user needs to choose and to use the entity correctly: its cost on the AVR in flash and + RAM where it matters, its limits, what it does at the edges. +- An example in `\code{.cpp} ... \endcode` where a call is clearer than a sentence. Keep it short + and make it compile. +- Names in backticks: parameters as `index`, entities as `Result` or `std::span`. Doxygen links + an entity of TimerTwo by its name; write `Result::Map()` to link a member. + +### What is documented + +- **Everything a sketch can use** in `src/`: every class, function, member function, data + member, enum and enum value, type alias, constant and macro, and each header with `\file`. +- **Overloads** that differ only in their parameters share one text: the first is documented, + the others take it with `\copydoc`, or are grouped with `\overload` and their own `\param`s. +- **`timer_two::internal`** is not part of the API. A block is welcome but not required. The + exception is a file whose functions a public class gives a sketch, as a base it inherits + from: it is documented as the API, and `DOCS_INTERNAL_API` in `tools/project.sh` names it. +- **Helpers a sketch never sees**, in a file that is otherwise documented as the API, are put + between `/*! \cond */` and `/*! \endcond */`: Doxygen leaves them out, and they keep their + `//` comments. +- **Source files, tests and examples** keep `//` comments. + +### A file + +Every header starts with the licence, as `//` lines that tools such as REUSE read, and then a +block for the file: + +```cpp +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief std::span, from C++20, for gnu++11. + * + * What can go out of range returns a Result instead of being undefined. + */ +``` + +## Checking + +- **`tools/docs.sh`** builds the reference with Doxygen and fails on every warning: a block + Doxygen cannot read, a parameter without `\param` or a `\param` without parameter, an entity + of the API without a block. It lets two pass: a gap in `timer_two::internal`, except in + the files `DOCS_INTERNAL_API` names, and a missing `\return`, which a one-line block needs not + have. +- **clang's `-Wdocumentation`**, through clang-tidy and clangd, checks each block against the + declaration it stands at: a `\param` whose name the function does not have, a `\return` on a + function that returns nothing, an unknown command. clangd shows these in the editor as you + type. +- **clang-format** aligns the blocks; `tools/lint.sh --fix` applies it. + +CI runs `tools/docs.sh` on every pull request and publishes the reference from `main`. + +## Writing a block + +The dev container has the extension "Doxygen Documentation Generator". Type `/*!` above a +declaration and press Enter: it writes the skeleton of this style, with a `\param` for each +parameter and a `\return` for a function that returns a value. The text is yours to write. diff --git a/docs/Misra.md b/docs/Misra.md new file mode 100644 index 0000000..505dcb7 --- /dev/null +++ b/docs/Misra.md @@ -0,0 +1,341 @@ +# MISRA C++:2023 + +How far the code of TimerTwo keeps to MISRA C++:2023, rule by rule, and where it +deviates. The C++ Core Guidelines and MISRA C++ are the standards the code follows; +[CodingStyle.md](CodingStyle.md) makes them concrete. + +## How to read the matrix + +The ids of the 4 directives and 175 rules of MISRA C++:2023 are those MathWorks lists for +Polyspace Bug Finder, the categories those Cppcheck lists (`lib/checkers.cpp`). The texts of +the rules are MISRA's and licensed; the topic below is a short note of our own, not the rule. +Read the rule in the standard. + +- **Covered by**: the check that enforces the rule, the compiler's warning, a test, a rule of + CodingStyle.md, or *Review*. Empty means not yet assessed; *n/a* means it cannot occur in this + code, with the reason. +- **Deviation**: where the project departs from the rule, as a whole, with its reason. A + deviation at one place is a `NOLINT` that names the check and the rule + (`// NOLINT(cppcoreguidelines-pro-type-reinterpret-cast): MISRA 8.2.5, F() of the core`). +- **Mandatory** rules allow no deviation, **Required** ones a documented deviation, + **Advisory** ones may be left out with a reason. + +No free tool checks MISRA C++ as a whole: clang-tidy has no MISRA module, Cppcheck's free addon +knows MISRA C only. Where a project needs evidence of compliance, a checker such as Cppcheck +Premium or PC-lint Plus fills the rows marked *Review* (ROADMAP I-4). + +> **To be checked against the standard.** What covers a rule is assigned from the topic of the +> rule, not from its full text: a check named may cover a rule only in part, and *Review* is +> where no tool is known to check it. The category of Rule 16.5.1, missing in Cppcheck's list, +> is to be looked up. + +## The matrix + +### Directives + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Dir 0.3.1 | Advisory | Floating-point arithmetic used appropriately | CodingStyle H-7 | | +| Dir 0.3.2 | Required | Calls meet the preconditions of the callee | CodingStyle E-2, Review | | +| Dir 5.7.2 | Advisory | No commented-out code | AGENTS.md, Review | | +| Dir 15.8.1 | Required | Assignment handles self-assignment | `bugprone-unhandled-self-assignment` | | + +### Rules of chapter 0 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 0.0.1 | Required | Unreachable statements | `-Wunreachable-code-aggressive` | | +| Rule 0.0.2 | Advisory | Invariant controlling expressions | `-Wtautological-compare`, `clang-analyzer-*`, in part | | +| Rule 0.1.1 | Advisory | Redundant writes to local objects | `clang-analyzer-deadcode.DeadStores` | | +| Rule 0.1.2 | Required | Return values used | `-Wunused-result`, CodingStyle FN-10 | | +| Rule 0.2.1 | Advisory | Variables of limited visibility are used | `-Wunused-variable` | | +| Rule 0.2.2 | Required | Named parameters are used | `-Wunused-parameter` | | +| Rule 0.2.3 | Advisory | Types of limited visibility are used | `-Wunused-local-typedef` | | +| Rule 0.2.4 | Advisory | Functions of limited visibility are used | `-Wunused-function`, `-Wunused-member-function`, `-Wunused-template` | | + +### Rules of chapter 4 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 4.1.1 | Required | Conforms to C++17 | Review | C++11 as the least standard, and every standard to C++20; `gnu++11` on the AVR (targets/avr.md); the tests C++17 | +| Rule 4.1.2 | Advisory | No deprecated features | `-Wdeprecated` | | +| Rule 4.1.3 | Required | No undefined or critical unspecified behaviour | `make sanitize`, `clang-analyzer-*` | | +| Rule 4.6.1 | Required | Memory operations sequenced | `-Wunsequenced`, `-Wsequence-point` | | + +### Rules of chapter 5 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 5.0.1 | Advisory | No trigraph-like sequences | `-Wtrigraphs` | | +| Rule 5.7.1 | Required | No `/*` inside a C comment | `-Wcomment` | | +| Rule 5.7.3 | Required | No line splicing in a `//` comment | `-Wcomment` | | +| Rule 5.10.1 | Required | Form of identifiers | `readability-identifier-naming`, `bugprone-reserved-identifier` | | +| Rule 5.13.1 | Required | Backslash only in defined escapes | `-Wunknown-escape-sequence` | | +| Rule 5.13.2 | Required | Escape sequences terminated | Review | | +| Rule 5.13.3 | Required | No octal constants | Review | | +| Rule 5.13.4 | Required | Unsigned literals with a suffix | Review | | +| Rule 5.13.5 | Required | No lower-case `l` first in a suffix | `readability-uppercase-literal-suffix` | | +| Rule 5.13.6 | Required | No single `L` in a `long long` suffix | `readability-uppercase-literal-suffix` | | +| Rule 5.13.7 | Required | No mixed string prefixes | Review | | + +### Rules of chapter 6 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 6.0.1 | Required | Block declarations not ambiguous | `-Wvexing-parse` | | +| Rule 6.0.2 | Advisory | External arrays with a size | Review | | +| Rule 6.0.3 | Advisory | Few declarations in the global namespace | CodingStyle F-9 | | +| Rule 6.0.4 | Required | `main` only as the global function | n/a: a sketch has no `main`, the library none either | | +| Rule 6.2.1 | Required | One definition rule | Review | | +| Rule 6.2.2 | Required | Same types across declarations | the compiler and linker | | +| Rule 6.2.3 | Required | An entity defined once | Review | | +| Rule 6.2.4 | Required | No non-inline definitions in headers | `misc-definitions-in-headers` | | +| Rule 6.4.1 | Required | No name hides another | `-Wshadow-all` | | +| Rule 6.4.2 | Required | No derived function hides a base one | `-Woverloaded-virtual` | | +| Rule 6.4.3 | Required | No unqualified lookup into a dependent base | Review | | +| Rule 6.5.1 | Advisory | External entities declared in a header | `misc-use-internal-linkage` | | +| Rule 6.5.2 | Advisory | Internal linkage where it fits | `misc-use-internal-linkage` | | +| Rule 6.7.1 | Required | No static local variables | Review | | +| Rule 6.7.2 | Required | No global variables | `cppcoreguidelines-avoid-non-const-global-variables` | | +| Rule 6.8.1 | Required | No access outside an object's lifetime | `make sanitize`, `clang-analyzer-*` | | +| Rule 6.8.2 | Mandatory | No reference or pointer to a local returned | `-Wreturn-stack-address` | | +| Rule 6.8.3 | Required | No local address kept longer | `clang-analyzer-core.StackAddressEscape` | | +| Rule 6.8.4 | Advisory | Members returning `*this` ref-qualified | Review | | +| Rule 6.9.1 | Required | Same type aliases in all declarations | Review | | +| Rule 6.9.2 | Advisory | No standard integer type names | CodingStyle T-1, Review | | + +### Rules of chapter 7 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 7.0.1 | Required | No conversion from `bool` | `readability-implicit-bool-conversion` | | +| Rule 7.0.2 | Required | No conversion to `bool` | `readability-implicit-bool-conversion` | | +| Rule 7.0.3 | Required | No numeric value of a character | Review | | +| Rule 7.0.4 | Required | Operands of bitwise and shift operators | CodingStyle H-8, Review | | +| Rule 7.0.5 | Required | Promotions keep signedness | `-Wconversion`, `-Wsign-conversion`, CodingStyle T-19 | | +| Rule 7.0.6 | Required | Numeric assignments appropriate | `-Wconversion`, `bugprone-narrowing-conversions` | | +| Rule 7.11.1 | Required | `nullptr` the only null pointer | `modernize-use-nullptr`, `-Wzero-as-null-pointer-constant` | | +| Rule 7.11.2 | Required | No array decaying as an argument | Review | An array passed as a pointer and a size, as C APIs of the platforms take it; `cppcoreguidelines-pro-bounds-array-to-pointer-decay` is off, see `.clang-tidy` | +| Rule 7.11.3 | Required | Function-to-pointer conversion limited | Review | | + +### Rules of chapter 8 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 8.0.1 | Advisory | Parentheses make the meaning clear | `readability-math-missing-parentheses`, `-Wparentheses` | | +| Rule 8.1.1 | Required | No implicit capture of `this` | Review | | +| Rule 8.1.2 | Advisory | Lambda captures explicit | Review | | +| Rule 8.2.1 | Required | Virtual bases cast by `dynamic_cast` only | n/a: no virtual base (13.1.1), no RTTI | | +| Rule 8.2.2 | Required | No C-style or functional cast | `google-readability-casting`, `cppcoreguidelines-pro-type-cstyle-cast`, `-Wold-style-cast` | | +| Rule 8.2.3 | Required | No cast removing `const` or `volatile` | `cppcoreguidelines-pro-type-const-cast`, `-Wcast-qual` | | +| Rule 8.2.4 | Required | No cast of function pointers | Review | | +| Rule 8.2.5 | Required | No `reinterpret_cast` | `cppcoreguidelines-pro-type-reinterpret-cast` | | +| Rule 8.2.6 | Required | No integer or `void*` cast to a pointer | `cppcoreguidelines-pro-type-reinterpret-cast`, in part | | +| Rule 8.2.7 | Advisory | No pointer cast to an integer | `cppcoreguidelines-pro-type-reinterpret-cast`, in part | | +| Rule 8.2.8 | Required | Pointer to integer via `intptr_t` only | CodingStyle T-9, Review | | +| Rule 8.2.9 | Required | No polymorphic operand of `typeid` | n/a: no RTTI (CodingStyle M-2) | | +| Rule 8.2.10 | Required | No recursion | `misc-no-recursion` | | +| Rule 8.2.11 | Required | Arguments to an ellipsis of fitting types | `cppcoreguidelines-pro-type-vararg` | | +| Rule 8.3.1 | Advisory | No unary minus on unsigned | Review | | +| Rule 8.3.2 | Advisory | No unary plus | Review | | +| Rule 8.7.1 | Required | Pointer arithmetic stays valid | `cppcoreguidelines-pro-bounds-pointer-arithmetic` | | +| Rule 8.7.2 | Required | Pointer subtraction within one array | `cppcoreguidelines-pro-bounds-pointer-arithmetic` | | +| Rule 8.9.1 | Required | Pointer comparison within one array | `cppcoreguidelines-pro-bounds-pointer-arithmetic` | | +| Rule 8.14.1 | Advisory | No side effect in the right operand of `&&`, `\|\|` | Review | | +| Rule 8.18.1 | Mandatory | No copy into an overlapping object | Review | | +| Rule 8.18.2 | Advisory | Result of an assignment not used | `bugprone-assignment-in-if-condition`, CodingStyle T-14 | | +| Rule 8.19.1 | Advisory | No comma operator | `-Wcomma` | | +| Rule 8.20.1 | Advisory | Constant unsigned arithmetic does not wrap | Review | | + +### Rules of chapter 9 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 9.2.1 | Required | No explicit conversion as a statement | Review | | +| Rule 9.3.1 | Required | Bodies are compound statements | `readability-braces-around-statements` | | +| Rule 9.4.1 | Required | `if … else if` ends with `else` | Review (ROADMAP C-3) | | +| Rule 9.4.2 | Required | Structure of a `switch` | `bugprone-switch-missing-default-case`, `-Wswitch`, `-Wimplicit-fallthrough`, CodingStyle T-15 | | +| Rule 9.5.1 | Required | Simple counting `for` loops | Review | | +| Rule 9.5.2 | Advisory | Range-for initializer with one call at most | Review | | +| Rule 9.6.1 | Advisory | No `goto` | `cppcoreguidelines-avoid-goto` | | +| Rule 9.6.2 | Required | `goto` to a label in an enclosing block | n/a: no `goto` (9.6.1) | | +| Rule 9.6.3 | Required | `goto` jumps forward | n/a: no `goto` (9.6.1) | | +| Rule 9.6.4 | Required | `noreturn` functions do not return | `-Winvalid-noreturn` | | +| Rule 9.6.5 | Required | Every path of a non-void function returns | `-Wreturn-type` | | + +### Rules of chapter 10 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 10.0.1 | Advisory | One variable per declaration | `readability-isolate-declaration` | | +| Rule 10.1.1 | Advisory | `const` on pointer and reference parameters | `misc-const-correctness`, `readability-non-const-parameter` | | +| Rule 10.1.2 | Required | `volatile` where it fits | CodingStyle H-6, Review | | +| Rule 10.2.1 | Required | Enumerations with an underlying type | `performance-enum-size`, CodingStyle T-7 | | +| Rule 10.2.2 | Advisory | No unscoped enumerations | `cppcoreguidelines-use-enum-class` | | +| Rule 10.2.3 | Required | No numeric use of an unscoped enumeration | `cppcoreguidelines-use-enum-class` | | +| Rule 10.3.1 | Advisory | No unnamed namespace in a header | `google-build-namespaces` | | +| Rule 10.4.1 | Required | No `asm` | Review | Where a target needs it, with its reason (targets/avr.md AVR-7) | + +### Rules of chapter 11 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 11.3.1 | Advisory | No variables of array type | `modernize-avoid-c-arrays` | A text in flash is a `char` array, as a target may need one (targets/avr.md AVR-1) (`modernize-avoid-c-arrays.AllowStringArrays`) | +| Rule 11.3.2 | Advisory | At most two levels of pointer indirection | Review | | +| Rule 11.6.1 | Advisory | Every variable initialized | `cppcoreguidelines-init-variables` | | +| Rule 11.6.2 | Mandatory | No read before an assignment | `-Wuninitialized`, `-Wconditional-uninitialized`, `clang-analyzer-core.uninitialized.*` | | +| Rule 11.6.3 | Required | Implicit enumerator values unique | Review | | + +### Rules of chapter 12 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 12.2.1 | Advisory | No bit-fields | Review | | +| Rule 12.2.2 | Required | Bit-fields of fitting types | Review | | +| Rule 12.2.3 | Required | No named one-bit signed bit-field | Review | | +| Rule 12.3.1 | Required | No `union` | `cppcoreguidelines-pro-type-union-access`, in part | | + +### Rules of chapter 13 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 13.1.1 | Advisory | No virtual inheritance | Review | | +| Rule 13.1.2 | Required | No base both virtual and non-virtual | Review | | +| Rule 13.3.1 | Required | `virtual`, `override`, `final` as fits | `modernize-use-override`, CodingStyle C-10 | | +| Rule 13.3.2 | Required | Overrides keep the default arguments | `google-default-arguments`, in part | | +| Rule 13.3.3 | Required | Same parameter names in all declarations | `readability-inconsistent-declaration-parameter-name` | | +| Rule 13.3.4 | Required | Virtual member pointers compared with `nullptr` only | Review | | + +### Rules of chapter 14 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 14.1.1 | Advisory | Data members all private or all public | `misc-non-private-member-variables-in-classes`, CodingStyle C-1 | | + +### Rules of chapter 15 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 15.0.1 | Required | Special member functions as needed | `cppcoreguidelines-special-member-functions`, CodingStyle C-3 | | +| Rule 15.0.2 | Advisory | Signatures of copy and move functions | `misc-unconventional-assign-operator` | | +| Rule 15.1.1 | Required | No dynamic type used in a constructor or destructor | `clang-analyzer-optin.cplusplus.VirtualCall` | | +| Rule 15.1.2 | Advisory | Constructors initialize every base | Review | | +| Rule 15.1.3 | Required | Conversions by one argument explicit | cpplint `runtime/explicit`, CodingStyle C-4 | | +| Rule 15.1.4 | Advisory | Members initialized before use | `cppcoreguidelines-pro-type-member-init` | | +| Rule 15.1.5 | Required | Initializer-list constructor only as the only one | Review | | + +### Rules of chapter 16 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 16.5.1 | Required? | No overloaded `&&` or `\|\|` | `google-runtime-operator`, in part | | +| Rule 16.5.2 | Required | No overloaded address-of | `google-runtime-operator` | | +| Rule 16.6.1 | Advisory | Symmetric operators as non-members | Review | | + +### Rules of chapter 17 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 17.8.1 | Required | No explicit specialization of a function template | Review | | + +### Rules of chapter 18 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 18.1.1 | Required | No pointer as an exception | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.1.2 | Required | Empty `throw` only in a handler | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.3.1 | Advisory | A catch-all handler | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.3.2 | Required | Class exceptions caught by reference | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.3.3 | Required | Handlers of constructors without non-static members | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.4.1 | Required | Functions that must not throw are `noexcept` | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.5.1 | Advisory | A `noexcept` function does not throw | n/a: no exceptions (CodingStyle M-2) | | +| Rule 18.5.2 | Advisory | No functions that end the program | Review | | + +### Rules of chapter 19 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 19.0.1 | Required | Lines with `#` are directives | Review | | +| Rule 19.0.2 | Required | No function-like macros | `cppcoreguidelines-macro-usage` | | +| Rule 19.0.3 | Advisory | `#include` only after directives or comments | Review | | +| Rule 19.0.4 | Advisory | `#undef` only of the file's own macros | Review | | +| Rule 19.1.1 | Required | `defined` used properly | Review | | +| Rule 19.1.2 | Required | Conditional directives in one file | Review | | +| Rule 19.1.3 | Required | Identifiers in `#if` defined | `-Wundef` | | +| Rule 19.2.1 | Required | Header guarded against a second inclusion | cpplint `build/header_guard` | | +| Rule 19.2.2 | Required | `#include` of a proper file name | Review | | +| Rule 19.2.3 | Required | No special characters in header names | Review | | +| Rule 19.3.1 | Advisory | No `#` and `##` operators | Review | | +| Rule 19.3.2 | Required | No `##` after a `#` parameter | Review | | +| Rule 19.3.3 | Required | Mixed-use macro argument not expanded | Review | | +| Rule 19.3.4 | Required | Macro arguments in parentheses | `bugprone-macro-parentheses` | | +| Rule 19.3.5 | Required | No directive-like tokens in macro arguments | Review | | +| Rule 19.6.1 | Advisory | No `#pragma` | Review | | + +### Rules of chapter 21 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 21.2.1 | Required | No `atof`, `atoi`, `atol`, `atoll` | Review | | +| Rule 21.2.2 | Required | No unsafe string functions | Review | | +| Rule 21.2.3 | Required | No `system()` | Review | | +| Rule 21.2.4 | Required | No `offsetof` | Review | | +| Rule 21.6.1 | Advisory | No dynamic memory | `cppcoreguidelines-no-malloc`, `cppcoreguidelines-owning-memory`, CodingStyle M-1 | | +| Rule 21.6.2 | Required | Dynamic memory managed automatically | n/a: no heap (21.6.1) | | +| Rule 21.6.3 | Required | No advanced memory management | n/a: no heap (21.6.1) | | +| Rule 21.6.4 | Required | Sized and unsized `operator delete` | n/a: no heap (21.6.1) | | +| Rule 21.6.5 | Required | No `delete` of an incomplete type | n/a: no heap (21.6.1) | | +| Rule 21.10.1 | Required | No `` | `cppcoreguidelines-pro-type-vararg` | | +| Rule 21.10.2 | Required | No `` | Review | | +| Rule 21.10.3 | Required | No `` | Review | | + +### Rules of chapter 22 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 22.3.1 | Required | `assert` not of a constant | Review | | +| Rule 22.4.1 | Required | Only zero assigned to `errno` | Review | | + +### Rules of chapter 23 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 23.11.1 | Advisory | No smart pointer made from a raw pointer | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | + +### Rules of chapter 24 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 24.5.1 | Required | No `` functions | Review | | +| Rule 24.5.2 | Required | No `memcpy`, `memmove`, `memcmp` | Review | | + +### Rules of chapter 25 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 25.5.1 | Required | No `setlocale` | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | +| Rule 25.5.2 | Mandatory | Pointers from the locale as `const` | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | +| Rule 25.5.3 | Mandatory | No pointer used after the next call | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | + +### Rules of chapter 26 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 26.3.1 | Advisory | No `std::vector` | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | + +### Rules of chapter 28 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 28.3.1 | Required | Predicates without side effects | Review | | +| Rule 28.6.1 | Required | `std::move` of a non-const lvalue | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | +| Rule 28.6.2 | Required | Forwarding references with `std::forward` | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | +| Rule 28.6.3 | Required | No moved-from object used | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | +| Rule 28.6.4 | Required | Results of `remove`, `unique`, `empty` used | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | + +### Rules of chapter 30 + +| Id | Category | Topic | Covered by | Deviation | +|---|---|---|---|---| +| Rule 30.0.1 | Required | No C library I/O | Review | | +| Rule 30.0.2 | Required | Reads and writes on a stream separated | Review where `src/` uses the standard library, which it may where every target has it (CodingStyle M-3); n/a otherwise | | diff --git a/docs/Testing.md b/docs/Testing.md new file mode 100644 index 0000000..0ae5422 --- /dev/null +++ b/docs/Testing.md @@ -0,0 +1,74 @@ +# Testing the code + +How TimerTwo is tested: which kind of test proves what, how a test is named and +written, and what the mock of the Arduino core may do. The code of a test follows +[CodingStyle.md](CodingStyle.md), but for the exceptions `test/.clang-tidy` makes and gives its +reasons for. Like CodingStyle.md, each rule has an id and says what checks it. + +## Three kinds of test + +| Kind | Where | Proves | Run by | +|---|---|---|---| +| **On the host** | `test/*_test.cpp`, GoogleTest against the mock in `test/mock/` | What the library computes: every function, every branch, every edge | `make tests`, `make clang`, `make sanitize`, `make coverage` | +| **What must not compile** | `test/compile_fail/*.cpp` | That a misuse is stopped by the compiler, with the message it names | `make tests` | +| **On the target** | `examples/SelfCheck`, in simavr for the AVR | What only the target shows: the width of its `int`, text in its flash, the variants as its compiler builds them | `make self-check` | + +Where host and target differ, a test on the host passes and the device fails. What differs, and +what catches it: + +| Difference | Host | Smallest target | Caught by | +|---|---|---|---| +| Width of `int` | 32 bits | 16 bits | CodingStyle T-1 and T-19, a check in SelfCheck where it matters | +| Width of a pointer | 64 bits | 16 bits | CodingStyle T-9 | +| Width of `double` | 64 bits | 32 bits | CodingStyle H-7 | +| Constant data | in RAM | in flash, read by its own functions | the profile, SelfCheck | +| Compiler and standard | a recent GCC and clang | the target's, as avr-gcc 7 in C++11 | `make examples`, which alone sees what that compiler reports, as `warn_unused_result` through a cast (CodingStyle FN-10) | + +| Id | Rule | Checked by | +|---|---|---| +| TS-1 | Every behaviour is tested on the host; the target checks only what the host cannot show. A check in SelfCheck that the host could make is a test on the host instead. | Review | +| TS-2 | A misuse that a `static_assert` stops has a case in `test/compile_fail/`, whose line `// Expected: ...` names the message. | `add_compile_fail_tests()` | +| TS-3 | A bug is fixed after a test that shows it fails, and the test stays. | Review | +| TS-4 | Every line and every branch of `src/` is reached by a test on the host. The tests follow what the documentation promises, not what the code does; a line they miss is first a question whether the promise is complete, then one for a test. A branch no test can reach is a question about the code, not about the test; where the code keeps it, as a way out the hardware may take, it is excluded with `GCOVR_EXCL_LINE: ` and the reason, and an exclusion without one fails. | `make coverage` | +| TS-24 | Every test on the host passes under AddressSanitizer and UBSan as well, which find what a test passes by chance: a read beyond an array, an overflow of a signed type. | `make sanitize` | + +## Files and names + +| Id | Rule | Checked by | +|---|---|---| +| TS-5 | One test file per header, in the folder of `test/` that mirrors the header's in `src/`, named as the class it tests and `Test`: `src/Text/MaxMatrixText.h` is tested in `test/Text/MaxMatrixTextTest.cpp`, as its suite is `MaxMatrixTextTest`. A family of functions in lower case takes `_test`: `clamp.h` in `clamp_test.cpp`. CMake takes every such file below `test/`. | Review | +| TS-6 | A test lies in the library's namespace and an anonymous one inside it, as the skeleton's does. | Review | +| TS-7 | The suite is the entity and `Test`, the test is what it does, as a sentence in the third person: `TEST(ClampTest, LimitsAValueBelow)` reads "Clamp limits a value below". No underscore, which GoogleTest reserves; no "Test", "Works" or "Correct" in the name of a test. | Review | +| TS-8 | A test reaches the library through its API only, as a sketch does: no `friend`, no `#define private public`, no header of `internal` unless the test is of `internal`. | Review | + +## A test + +| Id | Rule | Checked by | +|---|---|---| +| TS-9 | One behaviour per test. A test may check it with several expectations, but a second behaviour is a second test. | Review | +| TS-10 | Arrange, act, assert, in that order, each a paragraph of its own; no comment names them. | Review | +| TS-11 | `EXPECT_*` by default; `ASSERT_*` only where the rest of the test would make no sense, as an index after a size that is wrong. | Review | +| TS-12 | The value under test first, the expected second: `EXPECT_EQ(Clamp(42, 0, 10), 10)`. | Review | +| TS-13 | The expected value is written down, not computed: a test that computes it as the code does repeats the code's mistake. | Review | +| TS-14 | No logic in a test: no `if`, no loop over cases. A table of cases is a parameterized test, `TEST_P` with `INSTANTIATE_TEST_SUITE_P`, each case with a name. | Review | +| TS-15 | The edges are tested, each on its own: the least and the greatest value, one beyond each, empty and full, and an overflow where one can happen, as of the clock (H-2). | Review, `make coverage` | +| TS-16 | A `constexpr` function is also tested where the compiler computes it, with a `static_assert` in a test. | Review | +| TS-17 | A fixture only for what two tests or more set up alike. No state shared between tests: each test can run alone and in any order. | `gtest_discover_tests`, Review | +| TS-18 | Deterministic: no real time, no random number, no `sleep`. Time comes from the mock, set by the test. | Review | +| TS-25 | Each function of the API has a test with an argument outside its contract as well as one inside, where the contract says what happens then: the error it returns, the value it clamps to, the call it ignores. | Review | +| TS-26 | Calls with an order, as `Begin()` before `Update()`, are tested in the wrong one too: no `Begin()`, `Begin()` twice, `Update()` after `End()`. A state machine has a test for each transition, and one for each event that must change nothing. | Review | + +## The mock of the Arduino core + +| Id | Rule | Checked by | +|---|---|---| +| TS-19 | `test/mock/` gives what the library uses of the core, with the core's signatures and nothing more; it grows as the library comes to use more. | `make tests`, `make examples` | +| TS-20 | The mock records what the library does, as `Serial` its output, and lets the test set what the library reads, as the time of the clock or the level of a pin. It has no behaviour of its own beyond the core's. | Review | +| TS-21 | A test resets what it set in the mock, or the fixture does: the next test starts from the core's state after reset. | Review | + +## On the target + +| Id | Rule | Checked by | +|---|---|---| +| TS-22 | A check of SelfCheck prints one line, `pass` or `FAIL` and what it checks, and the run ends with the number that failed; `SelfCheck.expected` is what a correct run prints. | `make self-check` | +| TS-23 | The input of a check is `volatile`, so that the target computes it and not the compiler. | Review | diff --git a/docs/targets/avr.md b/docs/targets/avr.md new file mode 100644 index 0000000..710f5ab --- /dev/null +++ b/docs/targets/avr.md @@ -0,0 +1,31 @@ +# Target profile: AVR through Arduino + +What holds for TimerTwo on the AVR, built by avr-gcc through arduino-cli, beyond the +rules of [CodingStyle.md](../CodingStyle.md) that hold for every target. The rules there name +this profile where a target decides; the ids here start with `AVR-`. + +## What the target is + +| What | On the AVR (ATmega328P as the measure) | Consequence | +|---|---|---| +| `int` | 16 bits | Fixed widths (T-1); an overflow the host does not show | +| RAM, flash | 2 KiB, 32 KiB | No recursion (FN-6), the cost of an entity in its block (M-7) | +| Floating point | No unit; `float` in software | Fixed point first (H-7) | +| `double` | 32 bits, the same as `float` | No `double` (H-7) | +| Standard library | None | A library like it, as the ETL or Utl, or written for reuse (M-3) | +| Exceptions, RTTI | None; a sketch is built with `-fno-exceptions -fno-rtti` | M-2 | +| Heap | `malloc` exists, but fragments 2 KiB | M-1 | +| The table of `virtual` functions | Copied from flash into RAM at start, per class | C-6 | +| Compiler | avr-gcc 7.3, `gnu++11` | The least standard; `[[nodiscard]]` as `TIMERTWO_NODISCARD` (FN-10) | + +## Rules + +| Id | Rule | Checked by | +|---|---|---| +| AVR-1 | Constant text and tables lie in flash, as `PROGMEM`, and are read with `pgm_read_*`; a text handed to `Print` is `F("...")`. Flash and RAM are two address spaces: a pointer into flash read as if into RAM reads wrong data, and only SelfCheck shows it. | Review, `make self-check` | +| AVR-2 | A critical section is `ATOMIC_BLOCK(ATOMIC_RESTORESTATE)` from ``, which restores the interrupt flag as it was. The AVR reads 8 bits in one access: a shared `uint16_t` or wider is read in one (H-6). | Review | +| AVR-3 | Registers and bits by the names of ``: `TIMSK1 \|= _BV(TOIE1)` (H-4). | Review | +| AVR-4 | Time from the core's `millis()` and `micros()`, handed to the library as its clock (H-2, H-3); `millis()` overflows after 49 days, `micros()` after 71 minutes. | Review, a test across the overflow | +| AVR-5 | An interrupt routine is `ISR(vector)` of ``; it does not call `Serial`, `delay()` or `millis()`-based waits (H-5). | Review | +| AVR-6 | `delay()` and `delayMicroseconds()` only for the wait a datasheet asks (H-1). | Review | +| AVR-7 | `asm` only where the AVR needs it, as for a delay exact to the cycle, with its reason (MISRA 10.4.1). | Review | diff --git a/examples/.clang-tidy b/examples/.clang-tidy new file mode 100644 index 0000000..e4f0f03 --- /dev/null +++ b/examples/.clang-tidy @@ -0,0 +1,24 @@ +--- +# readability-magic-numbers: a sketch's pins, baud rate and test values read +# better as the numbers they are than behind names used once. +# cppcoreguidelines-avoid-non-const-global-variables: a sketch shares its +# state between setup(), loop() and its interrupts through globals; the +# Arduino core gives it no other place. +# TimerTwo's own, for now: the groups that src/.clang-tidy turns off, until +# version 2.0.0 (OIL 3). clang-tidy holds a header to the checks of the file +# that includes it, so the examples would report the headers of src/ with +# every check; and they use the API of before. +InheritParentConfig: true +Checks: > + -readability-magic-numbers, + -cppcoreguidelines-avoid-non-const-global-variables, + -bugprone-assignment-in-if-condition, + -bugprone-macro-parentheses, + -bugprone-signed-bitwise, + -clang-diagnostic-unreachable-code-break, + -cppcoreguidelines-*, + -google-*, + -misc-*, + -modernize-*, + -performance-enum-size, + -readability-* diff --git a/examples/Basics/Basics.ino b/examples/Basics/Basics.ino new file mode 100644 index 0000000..335baa4 --- /dev/null +++ b/examples/Basics/Basics.ino @@ -0,0 +1,23 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include + +/* + This example toggles PIN13 every 1 ms and starts the PWM for PIN3. + The frequency of the PWM depends on the period of the timer. +*/ + +#define PIN_TOGGLE 13u + +void timerCallback() { digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); } + +void setup() { + pinMode(PIN_TOGGLE, OUTPUT); + // Initialize timer with a period of 1000 microseconds. + Timer2.init(1000u, timerCallback); + Timer2.start(); + Timer2.enablePwm(TimerTwo::PWM_PIN_3, 127); +} + +void loop() {} diff --git a/examples/CPPLINT.cfg b/examples/CPPLINT.cfg new file mode 100644 index 0000000..dbaed63 --- /dev/null +++ b/examples/CPPLINT.cfg @@ -0,0 +1,3 @@ +# A sketch includes its own headers by name: arduino-cli puts no directory of +# the sketch on the include path that a longer name could start from. +filter=-build/include_subdir diff --git a/examples/Read/Read.ino b/examples/Read/Read.ino new file mode 100644 index 0000000..1d101af --- /dev/null +++ b/examples/Read/Read.ino @@ -0,0 +1,50 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include + +/* + This example toggles PIN13 at the longest period of the timer and starts the + PWM for PIN3. The frequency of the PWM depends on the period of the timer. + Furthermore the use of the read method is demonstrated. +*/ + +#define PIN_TOGGLE 13u + +void timerCallback() { digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); } + +void setup() { + Serial.begin(115200); + pinMode(PIN_TOGGLE, OUTPUT); + if (Timer2.init(Timer2.getPeriodMax(), timerCallback) == E_NOT_OK) { + // Something went wrong, check your parameters + while (1) { + } + } + if (Timer2.enablePwm(TimerTwo::PWM_PIN_3, 127) == E_NOT_OK) { + // Something went wrong, has init function already been called? + while (1) { + } + } + if (Timer2.start() == E_NOT_OK) { + // Something went wrong, has init function already been called? + while (1) { + } + } + + // delay of 20ms + delay(20u); + TimerTwo::TimeType elapsedTime{0u}; + + if (Timer2.read(elapsedTime) == E_NOT_OK) { + // Something went wrong, has init function already been called? + while (1) { + } + } + + // Prints the measured time in µs since the last rollover of the timer. + // In this example the timer had no rollover until now. + Serial.println(elapsedTime); +} + +void loop() {} diff --git a/library.properties b/library.properties new file mode 100644 index 0000000..dd13598 --- /dev/null +++ b/library.properties @@ -0,0 +1,10 @@ +name=TimerTwo +version=0.1.0 +author=Andreas Burnickl +maintainer=Andreas Burnickl +sentence=Periodic interrupt, PWM and time readout on Timer2 of the ATmega328P. +paragraph=Sets the period in microseconds, calls a function on each overflow, and gives a PWM on pin 3 whose frequency follows the period. +category=Timing +url=https://github.com/theAndreas/TimerTwo +architectures=avr +includes=TimerTwo.h diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8822ce6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,55 @@ +# The tools this repository checks with, pinned by uv.lock: one environment for all of them, the +# same in the dev container and in CI. `uv run --frozen` runs each from it, as the Makefile does; +# --frozen so that a run never relocks, which is the business of the change to this file. +# +# This file and uv.lock come from the template, whose Dependabot keeps them current; `copier +# update` brings them, and so they name no project: `tools` is every project's. A tool of the +# project's own is added here, with `uv add --dev`, and the update keeps it. +# +# The repository's own scripts in tools/ use the standard library only and are not a package: +# nothing here is installed from this directory. + +[project] +name = "tools" +version = "0" +requires-python = ">=3.12" +dependencies = [] + +[dependency-groups] +dev = [ + # The C++ style and its analysis, at the versions CI checks with. + "clang-format==23.1.3", + "clang-tidy==23.1.4", + "cpplint==2.0.2", + # What the tests reach of src/. + "gcovr==8.8", + # The shell scripts and the workflows; the binaries, shipped as wheels so that this lock pins + # them. + "shellcheck-py==0.11.0.1", + "actionlint-py==1.7.12.25", + # The Python scripts, read with the checks [tool.ruff.lint] selects. + "ruff==0.17.3", + # The template itself, for `uv run copier update`. + "copier==9.19.1", +] + +[tool.uv] +package = false +default-groups = ["dev"] +# A floor, not a pin: the uv that syncs this project is pinned where it is installed, the +# ARG UV_VERSION of .devcontainer/Dockerfile, which .github/actions/uv-sync reads as well. +required-version = ">=0.12.0" + +# PyPI, named here so that the lockfile names it whatever machine writes it. A uv configured to +# replace the default index, a company mirror in /etc/uv/uv.toml, otherwise writes that mirror's +# addresses into uv.lock, and CI, which cannot reach them, installs nothing. +[[tool.uv.index]] +name = "pypi" +url = "https://pypi.org/simple" +default = true + +# The same rule as .clang-tidy: the checks that answer "is this wrong", none that argue with how +# the code is written. F is pyflakes, an undefined name or an import nobody uses; E9 a file +# Python cannot parse. +[tool.ruff.lint] +select = ["F", "E9"] diff --git a/src/.clang-tidy b/src/.clang-tidy new file mode 100644 index 0000000..3b6fafc --- /dev/null +++ b/src/.clang-tidy @@ -0,0 +1,17 @@ +--- +# TimerTwo's code of 2023, until version 2.0.0 rewrites it in the namespace timer_two (OIL 3): +# its names, macros, typedefs and unsuffixed C enums are what these groups report, some 450 +# places in src/ alone. They come on with 2.0.0, each with what it finds fixed, and this file +# goes then. The tests and the mock are new and keep every check. +InheritParentConfig: true +Checks: > + -bugprone-assignment-in-if-condition, + -bugprone-macro-parentheses, + -bugprone-signed-bitwise, + -clang-diagnostic-unreachable-code-break, + -cppcoreguidelines-*, + -google-*, + -misc-*, + -modernize-*, + -performance-enum-size, + -readability-* diff --git a/src/StandardTypes.h b/src/StandardTypes.h new file mode 100644 index 0000000..e63f9d3 --- /dev/null +++ b/src/StandardTypes.h @@ -0,0 +1,66 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief The return type and the bit macros that TimerTwo shares with the + * author's older libraries. + * + * The same file comes with those libraries, under the same guard, so that a + * sketch that includes two of them gets its definitions once. Version 2.0.0 + * replaces it by types of the namespace timer_two. + */ + +// The guard the other copies of this file have; renamed, a sketch with one of +// them would define E_OK twice. +#ifndef _STANDARD_TYPES_H_ // NOLINT(build/header_guard) +// NOLINTNEXTLINE(bugprone-reserved-identifier) +#define _STANDARD_TYPES_H_ + +/*! \brief A switch of the configuration that is on. */ +#define STD_ON 1u +/*! \brief A switch of the configuration that is off. */ +#define STD_OFF 0u + +/*! \brief The character that ends a string. */ +#define STD_NULL_CHARACTER '\0' + +/*! + * \brief Sets bit `Bit` of `Var` to `Value`, 0 or 1. + * \param Var the variable or register + * \param Bit the number of the bit + * \param Value 0 or 1 + */ +#define writeBit(Var, Bit, Value) \ + ((Var) = static_cast(((Var) & ~(1u << (Bit))) | ((Value) << (Bit)))) + +/*! + * \brief Reads the group of bits `BitGroupMask` of `Var`, shifted down by + * `BitGroupPosition`, and stores it in `Var`. + * \param Var the variable or register + * \param BitGroupMask the bits of the group, in place + * \param BitGroupPosition the number of the group's lowest bit + */ +#define readBitGroup(Var, BitGroupMask, BitGroupPosition) \ + (Var = ((Var & ((uint8_t)BitGroupMask)) >> BitGroupPosition)) + +/*! + * \brief Sets the group of bits `BitGroupMask` of `Var` to `Value`. + * \param Var the variable or register + * \param BitGroupMask the bits of the group, in place + * \param BitGroupPosition the number of the group's lowest bit + * \param Value the value of the group, not shifted + */ +#define writeBitGroup(Var, BitGroupMask, BitGroupPosition, Value) \ + ((Var) = static_cast( \ + ((Var) & ~static_cast(BitGroupMask)) | \ + ((static_cast(Value) << (BitGroupPosition)) & \ + static_cast(BitGroupMask)))) + +/*! \brief Whether a function did what it was asked. */ +typedef enum { + E_OK = 0, /*!< It did. */ + E_NOT_OK = 1 /*!< It did not, and changed nothing or not all. */ +} StdReturnType; + +#endif // _STANDARD_TYPES_H_ NOLINT(build/header_guard) diff --git a/src/TimerTwo.cpp b/src/TimerTwo.cpp new file mode 100644 index 0000000..ab64883 --- /dev/null +++ b/src/TimerTwo.cpp @@ -0,0 +1,246 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "TimerTwo.h" + +TimerTwo& Timer2 = TimerTwo::getInstance(); // pre-instantiate TimerTwo + +TimerTwo::TimerTwo() { + State = STATE_INIT; + TimerIsrOverflowCallback = nullptr; + ClockSelectBitGroup = REG_CS_NO_CLOCK; +} + +TimerTwo::~TimerTwo() {} + +TimerTwo& TimerTwo::getInstance() { + static TimerTwo SingletonInstance; + return SingletonInstance; +} + +StdReturnType TimerTwo::init(TimeType Microseconds, + TimerIsrCallbackF_void sTimerOverflowCallback) { + StdReturnType ReturnValue = E_NOT_OK; + + if (STATE_INIT == State) { + ReturnValue = E_OK; + /* clear control register */ + TCCR2A = 0u; + TCCR2B = 0u; + + /* set mode 5: phase correct PWM */ + writeBit(TCCR2A, WGM20, 1u); + writeBit(TCCR2A, WGM21, 0u); + writeBit(TCCR2B, WGM22, 1u); + + if (setPeriod(Microseconds) == E_NOT_OK) { + ReturnValue = E_NOT_OK; + } + if (sTimerOverflowCallback != nullptr) { + attachInterrupt(sTimerOverflowCallback); + } + State = STATE_IDLE; + } + return ReturnValue; +} + +StdReturnType TimerTwo::setPeriod(TimeType Microseconds) { + StdReturnType ReturnValue{E_NOT_OK}; + + if (Microseconds <= getPeriodMax()) { + /* OCR2A is TOP in phase correct PWM mode */ + OCR2A = getTimerCycles(Microseconds); + + if (STATE_RUNNING == State) { + /* reset clock select register, and start the clock */ + writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, + ClockSelectBitGroup); + } + return E_OK; + } + return ReturnValue; +} + +StdReturnType TimerTwo::enablePwm(PwmPinType PwmPin, byte DutyCycle) { + StdReturnType ReturnValue{E_NOT_OK}; + + if ((STATE_IDLE == State) || (STATE_RUNNING == State) || + (STATE_STOPPED == State)) { + if (PWM_PIN_3 == PwmPin) { + ReturnValue = E_OK; + pinMode(PWM_PIN_3, OUTPUT); + /* activate compare output mode in timer control register */ + writeBit(TCCR2A, COM2B1, 1u); + } + + if (setPwmDuty(PwmPin, DutyCycle) == E_NOT_OK) { + ReturnValue = E_NOT_OK; + } + } + return ReturnValue; +} + +StdReturnType TimerTwo::disablePwm(PwmPinType PwmPin) { + StdReturnType returnValue{E_NOT_OK}; + + if (PWM_PIN_3 == PwmPin) { + returnValue = E_OK; + /* deactivate compare output mode in timer control register */ + writeBit(TCCR2A, COM2B1, 0u); + } + + return returnValue; +} + +StdReturnType TimerTwo::setPwmDuty(PwmPinType PwmPin, byte DutyCycle) { + StdReturnType ReturnValue{E_NOT_OK}; + + if ((STATE_IDLE == State) || (STATE_RUNNING == State) || + (STATE_STOPPED == State)) { + // use rule of three to calculate duty cycle related to timer top value + // OCR2A is top value of timer + uint32_t DutyCycleTrans = OCR2A * DutyCycle; + DutyCycleTrans >>= TIMERTWO_NUMBER_OF_BITS; + /* set output compare register value for given Pwm pin */ + if (PWM_PIN_3 == PwmPin) { + ReturnValue = E_OK; + // At most 255 * 255 / 256. + OCR2B = static_cast(DutyCycleTrans); + } + } + return ReturnValue; +} + +StdReturnType TimerTwo::start() { + if ((STATE_IDLE == State) || (STATE_STOPPED == State)) { + /* reset counter value */ + TCNT2 = 0u; + /* start counter by setting clock select register */ + writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, + ClockSelectBitGroup); + /* set overflow interrupt, if callback is set */ + if (TimerIsrOverflowCallback != nullptr) { + /* wait until timer moved on from zero, otherwise get phantom interrupt */ + while (TCNT2 == 0u) { + } + /* enable timer overflow interrupt */ + writeBit(TIMSK2, TOIE2, 1u); + } + State = STATE_RUNNING; + return E_OK; + } + return E_NOT_OK; +} + +void TimerTwo::stop() { + /* stop counter by clearing clock select register */ + writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, + REG_CS_NO_CLOCK); + State = STATE_STOPPED; +} + +StdReturnType TimerTwo::resume() { + if (STATE_STOPPED == State) { + /* resume counter by setting clock select register */ + writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, + ClockSelectBitGroup); + return E_OK; + } + return E_NOT_OK; +} + +StdReturnType TimerTwo::attachInterrupt( + TimerIsrCallbackF_void TimerOverflowCallback) { + if (TimerOverflowCallback != nullptr) { + TimerIsrOverflowCallback = TimerOverflowCallback; + /* enable timer overflow interrupt */ + if (State == STATE_RUNNING) writeBit(TIMSK2, TOIE2, 1u); + return E_OK; + } + return E_NOT_OK; +} + +void TimerTwo::detachInterrupt() { + /* clears the timer overflow interrupt enable bit */ + writeBit(TIMSK2, TOIE2, 0u); +} + +StdReturnType TimerTwo::read(TimeType& Microseconds) { + if (STATE_RUNNING == State) { + /* save current timer value */ + uint16_t counterValue{TCNT2}; + byte TCNT2_tmp{}; + + /* wait one counter tick, needed to find out counter counting up or down */ + do { + TCNT2_tmp = TCNT2; + } while (counterValue == TCNT2_tmp); + /* if counter counting down, add top value to current value */ + if (TCNT2_tmp < counterValue) { + // At most 2 * 255. + counterValue = static_cast((OCR2A - counterValue) + OCR2A); + } + /* transform counter value to microseconds in an efficient way */ + // At most 2 * 255 steps of 1024 clocks: 32640 us at 16 MHz, 65280 at 8, + // and TimeType has 32 bits below. + Microseconds = + static_cast(((counterValue * 1000uL) / (F_CPU / 1000uL)) + << getPrescaleShiftScale()); + return E_OK; + } + return E_NOT_OK; +} + +inline byte TimerTwo::getPrescaleShiftScale() { + switch (ClockSelectBitGroup) { + case REG_CS_NO_PRESCALER: + return 0u; + break; + case REG_CS_PRESCALE_8: + return 3u; + break; + case REG_CS_PRESCALE_32: + return 5u; + break; + case REG_CS_PRESCALE_64: + return 6u; + break; + case REG_CS_PRESCALE_128: + return 7u; + break; + case REG_CS_PRESCALE_256: + return 8u; + break; + case REG_CS_PRESCALE_1024: + return 10u; + break; + default: + return 0u; + } +} + +inline byte TimerTwo::getTimerCycles(TimeType Microseconds) { + /* calculate timer cycles to reach timer period, counter runs backwards after + * TOP, interrupt is at BOTTOM so divide microseconds by 2 */ + uint32_t TimerCycles = (F_CPU / 2000000uL) * Microseconds; + /* calculate timer pre-scaler */ + if (TimerCycles < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_NO_PRESCALER; + else if ((TimerCycles >>= 3u) < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_PRESCALE_8; + else if ((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_PRESCALE_32; + else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_PRESCALE_64; + else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_PRESCALE_128; + else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_PRESCALE_256; + else if ((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) + ClockSelectBitGroup = REG_CS_PRESCALE_1024; + + // Below TIMERTWO_RESOLUTION for a period up to getPeriodMax(). + return static_cast(TimerCycles); +} + +ISR(TIMER2_OVF_vect) { Timer2.callTimerIsrOverflowCallback(); } diff --git a/src/TimerTwo.h b/src/TimerTwo.h new file mode 100644 index 0000000..6a67193 --- /dev/null +++ b/src/TimerTwo.h @@ -0,0 +1,203 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief TimerTwo, a periodic interrupt, a PWM and a time readout on + * Timer/Counter2 of the ATmega328P. + * + * An adaption of the Arduino library TimerOne to the 8-bit Timer2. The timer + * runs in mode 5, phase correct PWM, with OCR2A as its top: the period sets + * OCR2A and the prescaler, the overflow at the bottom calls the callback, and + * OC2B on Arduino pin 3 gives the PWM. This breaks analogWrite() on pin 3, and + * tone(), which uses Timer2 as well. + */ + +#ifndef TIMERTWO_SRC_TIMERTWO_H_ +#define TIMERTWO_SRC_TIMERTWO_H_ + +#include +#include + +#include "Arduino.h" +#include "StandardTypes.h" + +/*! \brief The width of Timer2's counter, in bits. */ +#define TIMERTWO_NUMBER_OF_BITS 8u +/*! \brief The number of values of Timer2's counter. */ +#define TIMERTWO_RESOLUTION (1uL << TIMERTWO_NUMBER_OF_BITS) + +/*! \brief The Arduino pin of OC2A, PB3, which is not offered: see PwmPinType. + */ +#define TIMERTWO_A_ARDUINO_PIN 11u +/*! \brief The Arduino pin of OC2B, PD3. */ +#define TIMERTWO_B_ARDUINO_PIN 3u + +/*! \brief The position of the clock select bits CS22..CS20 in TCCR2B. */ +#define TIMERTWO_REG_CS_GP 0u +/*! \brief The mask of the clock select bits CS22..CS20 in TCCR2B. */ +#define TIMERTWO_REG_CS_GM B111 + +/*! \brief The largest prescaler of Timer2. */ +#define TIMERTWO_MAX_PRESCALER 1024u + +/*! + * \brief Timer/Counter2 as a periodic interrupt, a PWM on pin 3 and a time + * readout. + * + * There is one, Timer2; init() first, then start(). A function that can + * refuse returns E_NOT_OK, and leaves the timer as it was, unless it says + * otherwise. + */ +class TimerTwo { + public: + /*! \brief The function the overflow interrupt calls. */ + typedef void (*TimerIsrCallbackF_void)(void); + + /*! + * \brief A time in microseconds: 32 bits below 8 MHz, where the longest + * period does not fit into 16. + */ +#if F_CPU < 8000000uL + using TimeType = uint32_t; +#else + using TimeType = uint16_t; +#endif + + /*! \brief Where the timer is in its life. */ + enum StateType { + STATE_INIT, /*!< Not initialized: init() comes first. */ + STATE_IDLE, /*!< Initialized, not started. */ + STATE_RUNNING, /*!< Counting. */ + STATE_STOPPED /*!< Stopped by stop(). */ + }; + + /*! \brief The values of the clock select bits CS22..CS20 of TCCR2B. */ + enum ClockSelectType { + REG_CS_NO_CLOCK, /*!< No clock: the counter stands. */ + REG_CS_NO_PRESCALER, /*!< The CPU's clock. */ + REG_CS_PRESCALE_8, /*!< The CPU's clock / 8. */ + REG_CS_PRESCALE_32, /*!< The CPU's clock / 32. */ + REG_CS_PRESCALE_64, /*!< The CPU's clock / 64. */ + REG_CS_PRESCALE_128, /*!< The CPU's clock / 128. */ + REG_CS_PRESCALE_256, /*!< The CPU's clock / 256. */ + REG_CS_PRESCALE_1024 /*!< The CPU's clock / 1024. */ + }; + + /*! + * \brief The pins TimerTwo gives a PWM on. + * + * Only pin 3, OC2B: in mode 5 OCR2A is the top of the counter, so the duty + * of OC2A on pin 11 cannot be set without changing the period. + */ + enum PwmPinType { + PWM_PIN_3 = TIMERTWO_B_ARDUINO_PIN /*!< Arduino pin 3, OC2B, PD3. */ + }; + + private: + TimerTwo(); + ~TimerTwo(); + TimerTwo(TimerTwo const&); + + TimerIsrCallbackF_void TimerIsrOverflowCallback; + StateType State; + ClockSelectType ClockSelectBitGroup; + + byte getPrescaleShiftScale(); + byte getTimerCycles(TimeType); + + public: + /*! \brief The one TimerTwo, which Timer2 refers to. */ + static TimerTwo& getInstance(); + + /*! \brief Where the timer is in its life. */ + StateType getState() const { return State; } + /*! \brief The function the overflow interrupt calls, or nullptr. */ + TimerIsrCallbackF_void getTimerIsrCallbackFunction() const { + return TimerIsrOverflowCallback; + } + /*! \brief The longest period setPeriod() takes, in microseconds. */ + TimeType getPeriodMax() { + return TimeType{((TIMERTWO_RESOLUTION / (F_CPU / 1000000uL)) * + TIMERTWO_MAX_PRESCALER * 2u) - + 1u}; + } + + /*! + * \brief Sets the timer up in mode 5, with a period and a callback; the timer + * does not count before start(). + * \param Microseconds the period, up to getPeriodMax() + * \param sTimerOverflowCallback what the overflow interrupt calls, or nullptr + * for none + * \return E_NOT_OK if the timer was initialized already, or the period is too + * long; the timer is initialized with a callback in the latter case. + */ + StdReturnType init(TimeType Microseconds = 1000uL, + TimerIsrCallbackF_void sTimerOverflowCallback = nullptr); + /*! + * \brief Sets the period of the interrupt and of the PWM. + * + * The duty of the PWM is a share of the period, and is not set again: call + * setPwmDuty() after it. + * \param Microseconds the period, up to getPeriodMax() + * \return E_NOT_OK if the period is too long. + */ + StdReturnType setPeriod(TimeType Microseconds); + /*! + * \brief Starts the PWM on a pin, with a duty. + * \param PwmPin the pin + * \param DutyCycle the duty, 0 to 255 of 256 + * \return E_NOT_OK if the timer is not initialized. + */ + StdReturnType enablePwm(PwmPinType PwmPin, byte DutyCycle); + /*! + * \brief Stops the PWM on a pin; the pin is a plain output again, at the + * level of its bit in PORTD. + * \param PwmPin the pin + * \return E_NOT_OK for a pin TimerTwo has no PWM on. + */ + StdReturnType disablePwm(PwmPinType PwmPin); + /*! + * \brief Sets the duty of the PWM on a pin that enablePwm() started. + * \param PwmPin the pin + * \param DutyCycle the duty, 0 to 255 of 256 + * \return E_NOT_OK if the timer is not initialized. + */ + StdReturnType setPwmDuty(PwmPinType PwmPin, byte DutyCycle); + /*! + * \brief Starts the counter at 0, and the interrupt if a callback is set. + * \return E_NOT_OK if the timer is not initialized, or runs already. + */ + StdReturnType start(); + /*! \brief Stops the counter where it is. */ + void stop(); + /*! + * \brief Lets the counter go on from where stop() stopped it. + * \return E_NOT_OK if the timer was not stopped. + */ + StdReturnType resume(); + /*! + * \brief Sets the function the overflow interrupt calls, and enables the + * interrupt if the timer runs. + * \param TimerOverflowCallback the function + * \return E_NOT_OK for nullptr. + */ + StdReturnType attachInterrupt(TimerIsrCallbackF_void TimerOverflowCallback); + /*! \brief Disables the overflow interrupt. */ + void detachInterrupt(); + /*! + * \brief The time since the counter was last at its bottom. + * + * Waits for one tick of the counter, to see whether it counts up or down. + * \param[out] Microseconds the time, in steps of the prescaled clock + * \return E_NOT_OK if the timer does not run. + */ + StdReturnType read(TimeType& Microseconds); + /*! \brief Calls the callback; for the interrupt. */ + void callTimerIsrOverflowCallback() { TimerIsrOverflowCallback(); } +}; + +/*! \brief The one TimerTwo. */ +extern TimerTwo& Timer2; + +#endif // TIMERTWO_SRC_TIMERTWO_H_ diff --git a/test/.clang-tidy b/test/.clang-tidy new file mode 100644 index 0000000..84cc6b1 --- /dev/null +++ b/test/.clang-tidy @@ -0,0 +1,21 @@ +--- +# What a test does that the library must not, each the same in every test: +# readability-magic-numbers: a test's numbers are its data, 7 or 20, which +# read better as the numbers they are than behind names used once. +# cppcoreguidelines-pro-type-reinterpret-cast: a test makes chars in flash as +# F() of the core does, by a cast, to hand them to the library. +# cppcoreguidelines-avoid-non-const-global-variables: a free function that a +# test binds reaches what it counts or changes only through a global. +# readability-function-size.LineThreshold: a test of many cases is long but +# flat; its parameters, nesting and complexity keep the library's limits. +# readability-function-cognitive-complexity.IgnoreMacros: GoogleTest's +# EXPECT_ and ASSERT_ expand to an if and an else each, so a test without a +# branch of its own counted 20; its own branches still count. +InheritParentConfig: true +Checks: > + -readability-magic-numbers, + -cppcoreguidelines-pro-type-reinterpret-cast, + -cppcoreguidelines-avoid-non-const-global-variables +CheckOptions: + readability-function-size.LineThreshold: none + readability-function-cognitive-complexity.IgnoreMacros: true diff --git a/test/CPPLINT.cfg b/test/CPPLINT.cfg new file mode 100644 index 0000000..31d7679 --- /dev/null +++ b/test/CPPLINT.cfg @@ -0,0 +1,5 @@ +# cpplint takes a file for the test of a header only by the endings _test and _unittest, and +# reads RingBufferTest.cpp, which includes RingBuffer.h first (docs/Testing.md TS-5), as a file +# with an unrelated header before the system headers. clang-format orders the includes of a +# test instead, as .clang-format tells it which header is the test's own. +filter=-build/include_order diff --git a/test/TimerTwoTest.cpp b/test/TimerTwoTest.cpp new file mode 100644 index 0000000..5579401 --- /dev/null +++ b/test/TimerTwoTest.cpp @@ -0,0 +1,336 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// TimerTwo against the registers of test/mock/avr/io.h, at the Uno's 16 MHz. +// +// Timer2 is the one TimerTwo, and init() takes it only once: a test cannot +// begin from a new one. ctest runs each test in a process of its own, as +// gtest_discover_tests() adds them, so each begins from the state after a +// reset; run as one program, all but the first fail in SetUp(). Version 2.0.0 +// makes the timer a class a test can construct (OIL 3). + +#include "TimerTwo.h" + +#include +#include +#include +#include + +#include + +#include "Arduino.h" +#include "StandardTypes.h" + +namespace { + +// The bits of TCCR2B that select the clock, and their values. +constexpr uint8_t kClockSelectMask{0x07}; +constexpr uint8_t kNoPrescaler{1}; +constexpr uint8_t kPrescale8{2}; +constexpr uint8_t kPrescale32{3}; +constexpr uint8_t kPrescale64{4}; +constexpr uint8_t kPrescale128{5}; +constexpr uint8_t kPrescale256{6}; +constexpr uint8_t kPrescale1024{7}; + +int overflow_calls{0}; + +void CountOverflow() { ++overflow_calls; } + +bool BitIsSet(uint8_t reg, unsigned bit) { + return ((static_cast(reg) >> bit) & 1U) != 0; +} + +uint8_t ClockSelect() { + return static_cast(TCCR2B & kClockSelectMask); +} + +class TimerTwoTest : public ::testing::Test { + protected: + void SetUp() override { + ASSERT_EQ(Timer2.getState(), TimerTwo::STATE_INIT) + << "Each test needs a process of its own; run them through ctest."; + } +}; + +TEST_F(TimerTwoTest, InitSetsPhaseCorrectPwmWithoutAClock) { + TCCR2A = 0xFF; + TCCR2B = 0xFF; + + EXPECT_EQ(Timer2.init(), E_OK); + + EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_IDLE); + EXPECT_TRUE(BitIsSet(TCCR2A, WGM20)); + EXPECT_FALSE(BitIsSet(TCCR2A, WGM21)); + EXPECT_TRUE(BitIsSet(TCCR2B, WGM22)); + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B1)); + EXPECT_EQ(ClockSelect(), 0); +} + +TEST_F(TimerTwoTest, InitIsRefusedTheSecondTime) { + ASSERT_EQ(Timer2.init(), E_OK); + + EXPECT_EQ(Timer2.init(), E_NOT_OK); +} + +TEST_F(TimerTwoTest, InitRefusesAPeriodAboveTheLongest) { + EXPECT_EQ( + Timer2.init(static_cast(Timer2.getPeriodMax() + 1U)), + E_NOT_OK); +} + +TEST_F(TimerTwoTest, TheLongestPeriodIsAbout33Milliseconds) { + // 256 steps up and down at 16 MHz / 1024. + EXPECT_EQ(Timer2.getPeriodMax(), 32767U); +} + +// The period is 2 * OCR2A * prescaler / 16 MHz: up to OCR2A and down again. +TEST_F(TimerTwoTest, APeriodSetsTheTopAndTheSmallestPrescaler) { + ASSERT_EQ(Timer2.init(10U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + EXPECT_EQ(OCR2A, 80); + EXPECT_EQ(ClockSelect(), kNoPrescaler); + + EXPECT_EQ(Timer2.setPeriod(100U), E_OK); + EXPECT_EQ(OCR2A, 100); + EXPECT_EQ(ClockSelect(), kPrescale8); + + EXPECT_EQ(Timer2.setPeriod(1000U), E_OK); + EXPECT_EQ(OCR2A, 250); + EXPECT_EQ(ClockSelect(), kPrescale32); + + EXPECT_EQ(Timer2.setPeriod(2000U), E_OK); + EXPECT_EQ(OCR2A, 250); + EXPECT_EQ(ClockSelect(), kPrescale64); + + EXPECT_EQ(Timer2.setPeriod(4000U), E_OK); + EXPECT_EQ(OCR2A, 250); + EXPECT_EQ(ClockSelect(), kPrescale128); + + EXPECT_EQ(Timer2.setPeriod(8000U), E_OK); + EXPECT_EQ(OCR2A, 250); + EXPECT_EQ(ClockSelect(), kPrescale256); + + EXPECT_EQ(Timer2.setPeriod(Timer2.getPeriodMax()), E_OK); + EXPECT_EQ(OCR2A, 255); + EXPECT_EQ(ClockSelect(), kPrescale1024); +} + +TEST_F(TimerTwoTest, SetPeriodRefusesAPeriodAboveTheLongest) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + + EXPECT_EQ(Timer2.setPeriod( + static_cast(Timer2.getPeriodMax() + 1U)), + E_NOT_OK); + EXPECT_EQ(OCR2A, 250); +} + +TEST_F(TimerTwoTest, StartSelectsTheClockFromZero) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + TCNT2.Set(42, false); + + EXPECT_EQ(Timer2.start(), E_OK); + + EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_RUNNING); + EXPECT_EQ(ClockSelect(), kPrescale32); + EXPECT_EQ(static_cast(TCNT2), 0); +} + +TEST_F(TimerTwoTest, StartWithoutCallbackLeavesTheInterruptOff) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + + ASSERT_EQ(Timer2.start(), E_OK); + + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); +} + +TEST_F(TimerTwoTest, StartWithCallbackEnablesTheInterrupt) { + ASSERT_EQ(Timer2.init(1000U, CountOverflow), E_OK); + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); + + ASSERT_EQ(Timer2.start(), E_OK); + + EXPECT_TRUE(BitIsSet(TIMSK2, TOIE2)); +} + +TEST_F(TimerTwoTest, StartIsRefusedBeforeInit) { + EXPECT_EQ(Timer2.start(), E_NOT_OK); + EXPECT_EQ(ClockSelect(), 0); +} + +TEST_F(TimerTwoTest, StartIsRefusedWhileRunning) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + + EXPECT_EQ(Timer2.start(), E_NOT_OK); +} + +TEST_F(TimerTwoTest, TheOverflowCallsTheCallback) { + ASSERT_EQ(Timer2.init(1000U, CountOverflow), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + + TIMER2_OVF_vect(); + TIMER2_OVF_vect(); + + EXPECT_EQ(overflow_calls, 2); +} + +TEST_F(TimerTwoTest, StopDeselectsTheClock) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + + Timer2.stop(); + + EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_STOPPED); + EXPECT_EQ(ClockSelect(), 0); +} + +TEST_F(TimerTwoTest, ResumeSelectsTheClockAgain) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + Timer2.stop(); + + EXPECT_EQ(Timer2.resume(), E_OK); + + EXPECT_EQ(ClockSelect(), kPrescale32); +} + +TEST_F(TimerTwoTest, ResumeIsRefusedUnlessStopped) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + + EXPECT_EQ(Timer2.resume(), E_NOT_OK); +} + +TEST_F(TimerTwoTest, EnablePwmDrivesPin3WithTheDutyOfTheTop) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + + EXPECT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 128), E_OK); + + EXPECT_EQ(mock_pin_mode[3], OUTPUT); + EXPECT_TRUE(BitIsSet(TCCR2A, COM2B1)); + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B0)); + // Half of the top, 250. + EXPECT_EQ(OCR2B, 125); +} + +TEST_F(TimerTwoTest, EnablePwmIsRefusedBeforeInit) { + EXPECT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 128), E_NOT_OK); + + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B1)); +} + +TEST_F(TimerTwoTest, SetPwmDutySetsTheCompareValue) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 128), E_OK); + + EXPECT_EQ(Timer2.setPwmDuty(TimerTwo::PWM_PIN_3, 64), E_OK); + + EXPECT_EQ(OCR2B, 62); +} + +TEST_F(TimerTwoTest, SetPwmDutyIsRefusedBeforeInit) { + OCR2B = 7; + + EXPECT_EQ(Timer2.setPwmDuty(TimerTwo::PWM_PIN_3, 64), E_NOT_OK); + + EXPECT_EQ(OCR2B, 7); +} + +TEST_F(TimerTwoTest, DisablePwmDisconnectsPin3) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 128), E_OK); + + EXPECT_EQ(Timer2.disablePwm(TimerTwo::PWM_PIN_3), E_OK); + + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B1)); +} + +TEST_F(TimerTwoTest, AttachInterruptRefusesNullptr) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + + EXPECT_EQ(Timer2.attachInterrupt(nullptr), E_NOT_OK); + EXPECT_EQ(Timer2.getTimerIsrCallbackFunction(), nullptr); +} + +TEST_F(TimerTwoTest, AttachInterruptWhileRunningEnablesTheInterrupt) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + + EXPECT_EQ(Timer2.attachInterrupt(CountOverflow), E_OK); + + EXPECT_TRUE(BitIsSet(TIMSK2, TOIE2)); + TIMER2_OVF_vect(); + EXPECT_EQ(overflow_calls, 1); +} + +TEST_F(TimerTwoTest, DetachInterruptDisablesTheInterrupt) { + ASSERT_EQ(Timer2.init(1000U, CountOverflow), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + + Timer2.detachInterrupt(); + + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); +} + +TEST_F(TimerTwoTest, ReadIsRefusedUnlessRunning) { + ASSERT_EQ(Timer2.init(100U), E_OK); + TimerTwo::TimeType microseconds{7}; + + EXPECT_EQ(Timer2.read(microseconds), E_NOT_OK); + + EXPECT_EQ(microseconds, 7U); +} + +// At 100 us the prescaler is 8: a step of the counter is 0.5 us. +TEST_F(TimerTwoTest, ReadCountsTheStepsUpwards) { + ASSERT_EQ(Timer2.init(100U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + TCNT2.Set(64, true); + TimerTwo::TimeType microseconds{0}; + + EXPECT_EQ(Timer2.read(microseconds), E_OK); + + EXPECT_EQ(microseconds, 32U); +} + +TEST_F(TimerTwoTest, ReadCountsTheStepsBackDownFromTheTop) { + ASSERT_EQ(Timer2.init(100U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + // 100 steps up and 92 down. + TCNT2.Set(8, false); + TimerTwo::TimeType microseconds{0}; + + EXPECT_EQ(Timer2.read(microseconds), E_OK); + + EXPECT_EQ(microseconds, 96U); +} + +// 16 steps of the counter are as many microseconds as the prescaler divides +// by: 16 MHz / 16. +TEST_F(TimerTwoTest, ReadScalesByEachPrescaler) { + ASSERT_EQ(Timer2.init(10U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + struct Case { + TimerTwo::TimeType period; + TimerTwo::TimeType sixteen_steps; + }; + std::array const cases{{{10U, 1U}, + {100U, 8U}, + {1000U, 32U}, + {2000U, 64U}, + {4000U, 128U}, + {8000U, 256U}, + {32767U, 1024U}}}; + + for (auto const& c : cases) { + ASSERT_EQ(Timer2.setPeriod(c.period), E_OK); + TCNT2.Set(16, true); + TimerTwo::TimeType microseconds{0}; + + EXPECT_EQ(Timer2.read(microseconds), E_OK); + + EXPECT_EQ(microseconds, c.sixteen_steps) << "period " << c.period; + } +} + +} // namespace diff --git a/test/mock/Arduino.cpp b/test/mock/Arduino.cpp new file mode 100644 index 0000000..4790d36 --- /dev/null +++ b/test/mock/Arduino.cpp @@ -0,0 +1,16 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "Arduino.h" + +#include + +#include + +std::array mock_pin_mode{}; + +void pinMode(uint8_t pin, uint8_t mode) { + if (pin < mock_pin_mode.size()) { + mock_pin_mode[pin] = mode; + } +} diff --git a/test/mock/Arduino.h b/test/mock/Arduino.h new file mode 100644 index 0000000..2f9445d --- /dev/null +++ b/test/mock/Arduino.h @@ -0,0 +1,33 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// The part of the Arduino core that TimerTwo uses, for the tests on the host: +// byte, the binary constant B111, and pinMode(), which records the mode of +// each pin for the tests to read. The core's constants are macros; here they +// are constants by the same names, which is all the library needs. Extend it +// as the library comes to use more of the core. + +#ifndef TIMERTWO_TEST_MOCK_ARDUINO_H_ +#define TIMERTWO_TEST_MOCK_ARDUINO_H_ + +#include + +#include + +// The core's names. +// NOLINTBEGIN(readability-identifier-naming) +using byte = uint8_t; + +constexpr uint8_t INPUT{0x0}; +constexpr uint8_t OUTPUT{0x1}; +constexpr uint8_t B111{7}; + +// The core's function, which records the mode. +void pinMode(uint8_t pin, uint8_t mode); +// NOLINTEND(readability-identifier-naming) + +// The mode pinMode() last set for each of the Uno's 20 pins, INPUT after a +// reset. +extern std::array mock_pin_mode; + +#endif // TIMERTWO_TEST_MOCK_ARDUINO_H_ diff --git a/test/mock/CPPLINT.cfg b/test/mock/CPPLINT.cfg new file mode 100644 index 0000000..6261ebd --- /dev/null +++ b/test/mock/CPPLINT.cfg @@ -0,0 +1,5 @@ +# The mock stands in for the Arduino core and avr-libc, and follows their names rather than the +# Google style, which is why tools/tidy.sh leaves it out as well. +# readability/nolint: cpplint 2.0.2 takes a NOLINTBEGIN of clang-tidy's checks for no block of +# its own and then reports the NOLINTEND as outside one; clang-tidy reads both. +filter=-readability/nolint diff --git a/test/mock/avr/interrupt.h b/test/mock/avr/interrupt.h new file mode 100644 index 0000000..414fe39 --- /dev/null +++ b/test/mock/avr/interrupt.h @@ -0,0 +1,17 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// avr-libc's ISR(), for the tests on the host: the handler is a function of C +// linkage by the vector's name, which a test calls in place of the +// interrupt. + +#ifndef TIMERTWO_TEST_MOCK_AVR_INTERRUPT_H_ +#define TIMERTWO_TEST_MOCK_AVR_INTERRUPT_H_ + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define ISR(vector) extern "C" void vector() + +// The handler of Timer2's overflow, which a test calls. +extern "C" void TIMER2_OVF_vect(); // NOLINT(readability-identifier-naming) + +#endif // TIMERTWO_TEST_MOCK_AVR_INTERRUPT_H_ diff --git a/test/mock/avr/io.cpp b/test/mock/avr/io.cpp new file mode 100644 index 0000000..45b2e0b --- /dev/null +++ b/test/mock/avr/io.cpp @@ -0,0 +1,47 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "avr/io.h" + +#include + +uint8_t volatile TCCR2A{0}; +uint8_t volatile TCCR2B{0}; +uint8_t volatile OCR2A{0}; +uint8_t volatile OCR2B{0}; +uint8_t volatile TIMSK2{0}; +MockCounter TCNT2; + +namespace { + +// The clock select bits CS22..CS20 of TCCR2B. +constexpr uint8_t kClockSelectMask{0x07}; + +} // namespace + +MockCounter::operator uint8_t() { + uint8_t const now{value_}; + if ((TCCR2B & kClockSelectMask) != 0) { + uint8_t const top{OCR2A}; + if (counting_up_ && value_ >= top) { + counting_up_ = false; + } else if (!counting_up_ && value_ == 0) { + counting_up_ = true; + } + if (top != 0) { + value_ = counting_up_ ? static_cast(value_ + 1) + : static_cast(value_ - 1); + } + } + return now; +} + +MockCounter& MockCounter::operator=(uint8_t value) { + Set(value, true); + return *this; +} + +void MockCounter::Set(uint8_t value, bool counting_up) { + value_ = value; + counting_up_ = counting_up; +} diff --git a/test/mock/avr/io.h b/test/mock/avr/io.h new file mode 100644 index 0000000..ba3e6e4 --- /dev/null +++ b/test/mock/avr/io.h @@ -0,0 +1,58 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// The registers of Timer/Counter2 of the ATmega328P, for the tests on the +// host: each a byte the tests read and set, with the numbers of its bits as +// avr-libc names them. TCNT2 counts as the timer does in mode 5, phase +// correct PWM: one step on each read while a clock is selected, up from 0 to +// OCR2A and down again, so that what waits for the counter to move sees it +// move. + +#ifndef TIMERTWO_TEST_MOCK_AVR_IO_H_ +#define TIMERTWO_TEST_MOCK_AVR_IO_H_ + +#include + +// avr-libc's names of the bits, which are macros there; constants by the same +// names are all the library needs. +// NOLINTBEGIN(readability-identifier-naming) +constexpr int WGM20{0}; +constexpr int WGM21{1}; +constexpr int COM2B0{4}; +constexpr int COM2B1{5}; +constexpr int COM2A0{6}; +constexpr int COM2A1{7}; +constexpr int CS20{0}; +constexpr int CS21{1}; +constexpr int CS22{2}; +constexpr int WGM22{3}; +constexpr int TOIE2{0}; +// NOLINTEND(readability-identifier-naming) + +// TCNT2, which counts on each read while TCCR2B selects a clock. +class MockCounter { + public: + // The value the counter has now, after which it steps. + operator uint8_t(); // NOLINT(google-explicit-constructor) + // Sets the counter, as a write to TCNT2 does; it goes on upwards. + MockCounter& operator=(uint8_t value); + + // Sets the counter and its direction, for a test. + void Set(uint8_t value, bool counting_up); + + private: + uint8_t value_{0}; + bool counting_up_{true}; +}; + +// avr-libc's names of the registers, globals as they are on the board. +// NOLINTBEGIN(readability-identifier-naming) +extern uint8_t volatile TCCR2A; +extern uint8_t volatile TCCR2B; +extern uint8_t volatile OCR2A; +extern uint8_t volatile OCR2B; +extern uint8_t volatile TIMSK2; +extern MockCounter TCNT2; +// NOLINTEND(readability-identifier-naming) + +#endif // TIMERTWO_TEST_MOCK_AVR_IO_H_ diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..c91a947 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,41 @@ +# tools/ + +The scripts behind the targets of the `Makefile`, which a developer and CI alike call them +through. + +## What lies where + +| File | What it is | +|---|---| +| `setup.sh` | `make setup`: the pinned Arduino core, and what `prepare()` of `project.sh` builds | +| `lint.sh` | `make lint` and `make fmt`: clang-format, cpplint, the Doxygen indent, shellcheck, actionlint, ruff | +| `compile_examples.sh` | `make examples`: every example in each variant; the table of flash and RAM | +| `documented_sizes.py` | `make sizes`: the README's table against the last `make examples` | +| `self_check.sh` | `make self-check`: examples/SelfCheck in simavr | +| `coverage.sh` | `make coverage`: the tests with --coverage | +| `tidy.sh` | `make tidy`: clang-tidy, and the board's compilation database | +| `cppcheck.sh` | `make cppcheck` | +| `self_contained_headers.py` | `make headers`: every header compiled on its own | +| `docs.sh` | `make docs`: Doxygen, failing on a gap | +| `arduino_lint.sh` | `make arduino-lint` | +| `common.sh` | What the shell scripts share: the paths, the defaults of `project.sh`, compiling an example. A script of the project's own sources it as well | +| `project.sh` | The project's: the board, the core, the variants and the hooks | +| `project.mk` | The project's: its own targets of the `Makefile` | +| `lib/` | What the scripts above call, a target of none: `doc_indent.py` for `lint.sh`, `tidy_module.sh` and the clang-tidy module in `tidy_module/` for `tidy.sh` | + +`project.sh` and `project.mk` are the project's own: the template wrote them once, and +`copier update` leaves them alone. Everything else here comes from the template and is brought up +to date with `copier update`; a change of the project's own goes into `project.sh`, `project.mk` +or a script of its own beside them. + +## Shell or Python + +- **Shell drives the tools:** a script that calls arduino-cli, cmake, clang-tidy or simavr, + passes their flags on and reports their status. Bash, with `set -euo pipefail`; it sources + `common.sh`. +- **Python reads and writes data:** a compilation database, a table, the text of a source. The + standard library only, so that it runs without `uv sync`. + +shellcheck reads every `.sh` here, with the checks `.shellcheckrc` turns on: the output of a +command goes into a variable before it is used, as `mapfile < <(...)` never sees the command +fail; a list of files comes from `list_files` in `common.sh`. ruff reads every `.py`. diff --git a/tools/arduino_lint.sh b/tools/arduino_lint.sh new file mode 100755 index 0000000..54c1d99 --- /dev/null +++ b/tools/arduino_lint.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Checks the library against the rules of the Arduino Library Manager, as arduino-lint does in +# CI. Not the working tree: the Library Manager sees the repository, and the working tree has +# build/ and .venv beside it, whose links arduino-lint reports as a library's. So what git has, +# tracked or new and not ignored, is copied into a folder of the library's name in build/, and +# that is checked. With --copy-only it makes the copy, prints its path and stops, for a workflow +# that checks it with arduino-lint's action. + +set -euo pipefail + +# shellcheck source=tools/common.sh +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +main() { + local copy_only=0 + if [[ "${1:-}" == "--copy-only" ]]; then + copy_only=1 + elif [[ $# -gt 0 ]]; then + err "Usage: $0 [--copy-only]" + exit 2 + fi + + cd "${ROOT_DIR}" + local name + name="$(sed -n 's/^name=//p' library.properties)" + if [[ -z "${name}" ]]; then + err "library.properties names no library." + exit 1 + fi + local copy="${BUILD_DIR}/arduino-lint/${name}" + rm -rf "${BUILD_DIR}/arduino-lint" + mkdir -p "${copy}" + git ls-files -z --cached --others --exclude-standard \ + | tar --null --files-from=- --create --file=- \ + | tar --extract --file=- --directory="${copy}" + if ((copy_only)); then + echo "${copy}" + exit 0 + fi + arduino-lint --library-manager submit --compliance strict "${copy}" +} + +main "$@" diff --git a/tools/common.sh b/tools/common.sh new file mode 100755 index 0000000..97afb34 --- /dev/null +++ b/tools/common.sh @@ -0,0 +1,143 @@ +#!/bin/bash +# +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Shared by the scripts in tools/: where things lie, and how an example is compiled in each +# variant. The defaults below are what a project gets that says nothing else; tools/project.sh, +# sourced after them, is where it says otherwise. This file comes from the template and is +# brought up to date with `copier update`; what is the project's goes into tools/project.sh. + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +readonly ROOT_DIR +readonly BUILD_DIR="${ROOT_DIR}/build" + +# The defaults, each described in tools/project.sh. +# shellcheck disable=SC2034 # used by the scripts that source this file +{ + NAMESPACE="" + FQBN="arduino:avr:uno" + ARDUINO_CORE="arduino:avr" + ARDUINO_BOARD_URLS="" + SIMAVR_MCU="atmega328p" + SIMAVR_FREQUENCY=16000000 + DATABASE_EXAMPLE="Basics" + SELF_CHECK_EXAMPLE="SelfCheck" + VARIANTS=(default) + TIDY_VARIANTS=(default) + DOCS_INTERNAL_API="" + CPPCHECK=1 + HOST_CODE=() +} + +# The hooks, which do nothing unless tools/project.sh defines them again, and +# then are never called: SC2329. +# shellcheck disable=SC2329 +{ + variant_flags() { + : + } + + prepare() { + : + } + + check_elf() { + : + } +} + +# shellcheck source=tools/project.sh +source "${ROOT_DIR}/tools/project.sh" + +err() { + echo "$*" >&2 +} + +# Prints the name of every example, one per line. +list_examples() { + local dir + for dir in "${ROOT_DIR}"/examples/*/; do + basename "${dir}" + done +} + +# Prints the bin directory of the avr-gcc that arduino-cli uses for FQBN. +avr_gcc_bin_dir() { + local properties + properties="$(arduino-cli compile --fqbn "${FQBN}" --show-properties \ + "${ROOT_DIR}/examples/${DATABASE_EXAMPLE}" 2>/dev/null)" + sed -n 's/^compiler\.path=//p' <<< "${properties}" +} + +# Fills the array named first with the files git has below the pathspecs whose paths match the +# regex: tracked ones and new ones not yet added, but not what .gitignore names, so that a file +# is checked before its first commit. Fails where git fails or no file matches, as a check over +# no file would pass. +# Arguments: +# array: the name of the array to fill +# regex: an extended regular expression, such as '\.(cpp|h)$' +# pathspec...: what git lists, such as 'src/*' +list_files() { + local -n list_files_into="$1" + local regex="$2" + shift 2 + local listed + listed="$(git ls-files --cached --others --exclude-standard -- "$@")" + if ! listed="$(grep -E "${regex}" <<< "${listed}")"; then + err "No file in $* matches ${regex}." + return 1 + fi + # shellcheck disable=SC2034 # a nameref: what it fills is the caller's array + mapfile -t list_files_into <<< "${listed}" +} + +# Fills the array named first with the folders of HOST_CODE, each without the / at its end. Fails +# where one is no folder, as a misspelt one would be checked by nothing, without a word. +# Arguments: +# array: the name of the array to fill +host_code_dirs() { + local -n host_code_dirs_into="$1" + host_code_dirs_into=() + local dir + for dir in "${HOST_CODE[@]}"; do + dir="${dir%/}" + if [[ ! -d "${ROOT_DIR}/${dir}" ]]; then + err "HOST_CODE in tools/project.sh names ${dir}, which is no folder of the project." + return 1 + fi + host_code_dirs_into+=("${dir}") + done +} + +# Compiles an example in a variant into BUILD_DIR// and prints what +# arduino-cli prints. The flags of the variant go into compiler.cpp.extra_flags, which reaches +# every C++ file of the build, the core's as well. Its callers test its status, which turns off +# set -e within it, so it returns on a failure itself. +# Arguments: +# variant: one of VARIANTS +# example: the name of a folder in examples/ +compile_example() { + local variant="$1" + local example="$2" + local args=( + --fqbn "${FQBN}" + --library "${ROOT_DIR}" + --warnings all + --build-path "${BUILD_DIR}/${variant}/${example}" + ) + local flags + flags="$(variant_flags "${variant}")" || return + flags="${flags//$'\n'/ }" + if [[ -n "${flags}" ]]; then + args+=(--build-property "compiler.cpp.extra_flags=${flags}") + fi + arduino-cli compile "${args[@]}" "${ROOT_DIR}/examples/${example}" 2>&1 +} + +# Prints the path of the ELF file that compile_example made. +elf_of() { + local variant="$1" + local example="$2" + echo "${BUILD_DIR}/${variant}/${example}/${example}.ino.elf" +} diff --git a/tools/compile_examples.sh b/tools/compile_examples.sh new file mode 100755 index 0000000..248d56a --- /dev/null +++ b/tools/compile_examples.sh @@ -0,0 +1,97 @@ +#!/bin/bash +# +# Copyright 2026 Andreas Burnickl +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Compiles every example in each variant and prints flash and RAM of each, as a Markdown table. +# Fails on a warning outside the Arduino core, and where check_elf() of tools/project.sh fails +# on what was built. When every example compiles, the table goes to build/sizes.md as well, which +# tools/documented_sizes.py compares with the README's (`make sizes`); else that file is removed, +# so that no table of an older build is taken for this one's. + +set -euo pipefail + +# shellcheck source=tools/common.sh +source "$(dirname "${BASH_SOURCE[0]}")/common.sh" + +# Prints the number after "