diff --git a/AGENTS.md b/AGENTS.md index 550ff12..58629fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,16 +105,16 @@ and sets the period with the prescaler, the overflow at the bottom calls the ske 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. +- **The hardware is a parameter** (CodingStyle H-3): `timer_two::Timer` in + `src/timer_two/timer.h` drives any 8-bit Timer/Counter whose registers `Registers` returns; + `src/timer_two/timer2.h` hands in Timer/Counter2 as `Timer2Registers`, and `timer2.cpp` defines + the one object a sketch uses, `timer2`, made when compiling, and the overflow interrupt that + calls it. A test makes a `Timer2` of its own, on the mock's registers set back in `SetUp()`. +- **Errors** are `timer_two::Error` in a `Status`, or a `Result` for `Read()`, as MaxMatrix has + them: no conversion to `bool`, the texts in flash. +- **The mock of the registers**, `test/mock/avr/io.h`: TCNT2 steps up to OCR2A and down again + while a clock is selected, on each read or on every n-th, so that `Start()` and `Read()`, which + wait for the counter to move, end on the host. - **The clocks**: `CMakeLists.txt` builds `test/ClockTest.cpp` at 1 and 20 MHz besides the Uno's 16, as the code computes with quotients of `F_CPU`; its expectations are computed from `F_CPU`, so that they hold at any clock. diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b88a2f..c414b89 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,10 +20,10 @@ 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) +# Recursive, as a module has a folder of its own (docs/CodingStyle.md F-12). 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_RECURSE library_sources CONFIGURE_DEPENDS src/timer_two/*.cpp) file(GLOB_RECURSE test_sources CONFIGURE_DEPENDS test/*Test.cpp test/*_test.cpp) list(FILTER test_sources EXCLUDE REGEX "/test/(mock|compile_fail)/") diff --git a/OIL.md b/OIL.md index 0b9d029..09483ed 100644 --- a/OIL.md +++ b/OIL.md @@ -12,7 +12,7 @@ Status: `open`, `in progress`, `done`, `dropped` (with the reason in the item). |---|------|------------|--------|----| | 1 | On the template embedded-cpp-template | – | in progress | #4 | | 2 | The known bugs, each shown by a test first | 1 | in progress | #5 | -| 3 | Version 2.0.0: a namespace, constants for macros, the template's checks | 2 | open | | +| 3 | Version 2.0.0: a namespace, constants for macros, the template's checks | 2 | in progress | #6 | | 4 | Release 2.0.0 and the Library Manager | 3 | open | | | 5 | SelfCheck in simavr | 1 | open | | @@ -62,14 +62,27 @@ The tests of the clocks run at 1, 16 and 20 MHz, each a build of its own. ### 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`; +`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 +no longer need a process each. `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. +Decided on 2026-11-10: + +- A refusal is a `Status` of an `enum class Error`, and `Read()` returns a `Result`, as in + MaxMatrix; not `bool`, which says not why, nor Utl's, as every error comes from the library + itself and Utl would be a dependency of every user (MaxMatrix OIL 28). +- The hardware is a parameter of a template, `Timer`, as XmegaTimer has it, with one + object for Timer/Counter2. +- The PWM takes no pin: there is only pin 3, as OCR2A is the top. +- `TimeType` stays, 16 bits from 8 MHz and 32 below. + +Found on the way, from the datasheet and the core's `init()`, and fixed with a test: the flag of +an overflow stays set while the interrupt is disabled, and `init()` runs Timer2 before `setup()`, +so the interrupt came at once when `Start()` enabled it. It is cleared first now. Not on +hardware. + ### 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, diff --git a/README.md b/README.md index d09e7ce..e8cdcfd 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,91 @@ # TimerTwo -Arduino Timer2 library. This is a simple adaption of the Arduino Timer1 library. For more information see https://playground.arduino.cc/Code/Timer1/. -Library is using the hardware timer two (Timer/Counter2) of the Arduino Uno. -## API description +A periodic interrupt, a PWM and a time readout on Timer/Counter2 of the ATmega328P, as on the +Arduino Uno and Nano: the Timer2 counterpart of the Arduino library +[TimerOne](https://playground.arduino.cc/Code/Timer1/). -### General -The most functions have parameter checks and some other checks (e. g. state checks of the library) implemented. These functions have a return value of stdReturnType. You can check the return value (E_OK or E_NOT_OK) to find out if something went wrong. +The timer runs in phase correct PWM: the period, in microseconds, sets the top and the +prescaler; the overflow at the bottom calls a function of the sketch; and pin 3 gives a PWM +whose frequency follows the period. This takes Timer2 from `analogWrite()` on pins 3 and 11 and +from `tone()`. -### init(Microseconds, OverflowCallback) -You must call this method first to use any of the other methods. You can optionally specify the timer's period here (in microseconds), by default it is set to 1 millisecond. Note that this breaks analogWrite() for digital pin 3 on Arduino. You can specify also a callback function, which will be called at the specified interval in microseconds. +```cpp +#include -### start() -Starts the timer. Note init() has to be called first. - -### stop() -Stops the timer by removing the timer clock. - -### setPeriod(Microseconds) -Sets the period in microseconds. The minimum period or highest frequency this library supports is 1 microsecond or 1 MHz. The maximum period is 32767 microseconds (can be retrieved by getPeriodMax()) or about 0.032767 seconds. Note that setting the period will change the attached interrupt and the PWM output frequency and duty cycle simultaneously. - -### enablePwm(PwmPin, DutyCycle) -Generates a PWM waveform on the specified pin. Output pins for Timer2 are PORTB pin 3 and PORTD pin 3. On Arduino, these are digital pins 11 and 3. But the library supports PWM only for pin 3 (PWM_PIN_3). Because in Timer Mode 5 (PWM, Phase Correct) the register OCRA is used to save the top value of the timer. The duty cycle is specified as a 8 bit value, so anything between 0 and 255. - -### attachInterrupt(OverflowCallback) -Calls a function at the specified interval in microseconds. Take care about the exution time of the code in the interrupt, or the CPU may never enter the main loop and your program will 'lock up'. - -### setPwmDuty(PwmPin, DutyCycle) -A fast shortcut for setting the PWM duty for a given pin if you have already set it up by calling enablePwm() earlier. This avoids the overhead of enabling PWM mode for the pin, setting the data direction register, checking for optional period adjustments etc. that are mandatory when you call enablePwm(). - -### detachInterrupt() -Disables the attached interrupt. - -### disablePwm(PwmPin) -Turns PWM off for the specified pin so you can use that pin for something else. - -### read(Microseconds) -Reads the time since last rollover in microseconds. The resolution of the time is only as high as the resolution of the timer. Means F_CPU / prescaler of the timer. The prescaler is calculated by setting the period of the timer. The accuracy of the result also depends on calculation. This is only performed as an integer division, therefore deviations can still occur due to truncation. - -## Usage -```c++ -/* - This example toggles the PIN13 cyclically all 1ms and starts the PWM for PIN3. - The frequency depends on the period of the timer. -*/ - -#define PIN_TOGGLE 13u - -void timerCallback() { - digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); -}; +void OnTick() { + // every millisecond, in the interrupt: keep it short +} 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); + timer_two::Discard(timer_two::timer2.Begin(1000, OnTick)); + timer_two::Discard(timer_two::timer2.EnablePwm(128)); // half of the period high + timer_two::Discard(timer_two::timer2.Start()); } -void loop() { - -} +void loop() {} ``` -This is [examples/Basics](examples/Basics/Basics.ino). For a more advanced usage see also -[examples/Read](examples/Read/Read.ino). +This is [examples/Basics](examples/Basics/Basics.ino). [examples/Read](examples/Read/Read.ino) +checks each call and reads the time. + +## API + +Everything lies in the namespace `timer_two`; `timer2` is the timer. A call that can refuse +returns a `Status`, and changes nothing when it refuses: `IsOk()` says whether it did what it +was asked, `GetError()` why not, and `GetErrorText()` the same in a few words for +`Serial.print()`. A `Status` must not be dropped: where a sketch does not care, `Discard()` says +so. `Read()` returns a `Result`, the time or why there is none. + +| Call | What it does | Refuses with | +|---|---|---| +| `Begin(period, callback)` | Sets the timer up with a period in microseconds, 1000 if none is given, and a function the overflow calls, or none. It does not count yet. | `kBegunAlready`, `kPeriodOutOfRange` | +| `SetPeriod(period)` | Sets the period of the interrupt and of the PWM, up to `Timer2::kPeriodMax`, 32767 at 16 MHz; at least one step of the counter, 1 from 2 MHz on. The duty keeps its share. | `kNotBegun`, `kPeriodOutOfRange` | +| `Start()` | Starts the counter at 0, and the interrupt if there is a callback. | `kNotBegun`, `kRunning` | +| `Stop()` | Stops the counter where it is. | `kNotRunning` | +| `Resume()` | Lets the counter go on from where `Stop()` stopped it. | `kNotStopped` | +| `AttachInterrupt(callback)` | Sets the function the overflow calls. | `kNoCallback` | +| `DetachInterrupt()` | Disables the interrupt and forgets the function. | – | +| `EnablePwm(duty)` | Starts the PWM on pin 3: 0 is always low, 255 always high. | `kNotBegun` | +| `SetPwmDuty(duty)` | Sets the duty. | `kNotBegun` | +| `DisablePwm()` | Stops the PWM; pin 3 is a plain output again. | – | +| `Read()` | The time since the counter was last at its bottom, in microseconds. | `kNotRunning` | +| `GetState()` | `kNotBegun`, `kIdle`, `kRunning` or `kStopped`. | – | + +The callback runs in the interrupt: it should do little, as setting a flag that `loop()` reads, +and what it shares with `loop()` is `volatile`. Below 8 MHz the times are `uint32_t`, as the +longest period does not fit 16 bits; from 8 MHz they are `uint16_t`. Both are `TimeType`. + +## From version 1 + +Version 2.0.0 breaks every name, on purpose: a sketch of version 1 does not compile until it is +changed, rather than behaving otherwise without notice. There are no aliases for the old names. + +| Version 1 | Version 2.0.0 | +|---|---| +| `Timer2.init(us, f)` | `timer_two::timer2.Begin(us, f)` | +| `Timer2.start()`, `stop()`, `resume()` | `Start()`, `Stop()`, `Resume()` | +| `Timer2.setPeriod(us)` | `SetPeriod(us)` | +| `Timer2.enablePwm(TimerTwo::PWM_PIN_3, duty)` | `EnablePwm(duty)`: there is only pin 3 | +| `Timer2.setPwmDuty(TimerTwo::PWM_PIN_3, duty)` | `SetPwmDuty(duty)` | +| `Timer2.disablePwm(TimerTwo::PWM_PIN_3)` | `DisablePwm()` | +| `Timer2.attachInterrupt(f)`, `detachInterrupt()` | `AttachInterrupt(f)`, `DetachInterrupt()` | +| `Timer2.read(us)` | `Read()`, which returns the time in a `Result` | +| `Timer2.getPeriodMax()` | `timer_two::Timer2::kPeriodMax` | +| `Timer2.getState()`, `TimerTwo::STATE_INIT` ... | `GetState()`, `timer_two::State::kNotBegun` ... | +| `StdReturnType`, `E_OK`, `E_NOT_OK` | `timer_two::Status`, `IsOk()`, `timer_two::Error` | +| `TimerTwo::TimeType` | `timer_two::TimeType` | +| `StandardTypes.h` | gone | + +What also changed: + +- The duty is a share of 255, not of 256: 255 keeps the output high, as 0 keeps it low. +- `SetPeriod()` and `SetPwmDuty()` are refused before `Begin()`, and `Stop()` returns why it + did nothing. +- The first callback comes after a period, not at once: the flag of an overflow, which the + core's `init()` leaves set, is cleared before the interrupt is enabled. +- The bugs of version 1 are fixed, among them `resume()`, which left the timer marked stopped, + and the time `read()` returned, which lost its lower steps: item 2 of + [OIL.md](https://github.com/theAndreas/TimerTwo/blob/main/OIL.md) lists them. ## Development diff --git a/examples/.clang-tidy b/examples/.clang-tidy index e4f0f03..ca49cbd 100644 --- a/examples/.clang-tidy +++ b/examples/.clang-tidy @@ -4,21 +4,7 @@ # 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-* + -cppcoreguidelines-avoid-non-const-global-variables diff --git a/examples/Basics/Basics.ino b/examples/Basics/Basics.ino index 335baa4..e4e17f8 100644 --- a/examples/Basics/Basics.ino +++ b/examples/Basics/Basics.ino @@ -1,23 +1,29 @@ // Copyright 2026 Andreas Burnickl // SPDX-License-Identifier: GPL-3.0-or-later +// +// Toggles the LED every millisecond from the overflow interrupt, and gives a +// PWM of half the period on pin 3, whose frequency follows the period. #include +#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. -*/ +namespace { -#define PIN_TOGGLE 13u +constexpr uint8_t kLedPin{LED_BUILTIN}; -void timerCallback() { digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); } +void OnTick() { + digitalWrite(kLedPin, digitalRead(kLedPin) == LOW ? HIGH : LOW); +} + +} // namespace 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); + pinMode(kLedPin, OUTPUT); + // 1000 microseconds, and the callback. Nothing to do on a refusal here: the + // period is in range, and the timer is begun once. + timer_two::Discard(timer_two::timer2.Begin(1000, OnTick)); + timer_two::Discard(timer_two::timer2.EnablePwm(128)); + timer_two::Discard(timer_two::timer2.Start()); } void loop() {} diff --git a/examples/Read/Read.ino b/examples/Read/Read.ino index 1d101af..d352ffd 100644 --- a/examples/Read/Read.ino +++ b/examples/Read/Read.ino @@ -1,50 +1,50 @@ // Copyright 2026 Andreas Burnickl // SPDX-License-Identifier: GPL-3.0-or-later +// +// Toggles the LED at the longest period of the timer, gives a PWM on pin 3, +// and prints how long ago the counter was last at its bottom: 20 ms after the +// start, as the period is about 33 ms and has not ended yet. Each call that +// can refuse is checked, and a refusal printed with its reason. #include +#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. -*/ +namespace { -#define PIN_TOGGLE 13u +constexpr uint8_t kLedPin{LED_BUILTIN}; +constexpr uint32_t kBaudRate{115200}; -void timerCallback() { digitalWrite(PIN_TOGGLE, !digitalRead(PIN_TOGGLE)); } +void OnTick() { + digitalWrite(kLedPin, digitalRead(kLedPin) == LOW ? HIGH : LOW); +} -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) { +// Prints why a call was refused and stops there, as the rest would not work. +void Check(timer_two::Status status, __FlashStringHelper const* call) { + if (!status.IsOk()) { + Serial.print(call); + Serial.print(F(": ")); + Serial.println(status.GetErrorText()); + while (true) { } } +} - // delay of 20ms - delay(20u); - TimerTwo::TimeType elapsedTime{0u}; +} // namespace - 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 setup() { + Serial.begin(kBaudRate); + pinMode(kLedPin, OUTPUT); + auto& timer = timer_two::timer2; + Check(timer.Begin(timer_two::Timer2::kPeriodMax, OnTick), F("Begin")); + Check(timer.EnablePwm(127), F("EnablePwm")); + Check(timer.Start(), F("Start")); + + delay(20); + timer_two::Result const elapsed{timer.Read()}; + Check(elapsed.GetError(), F("Read")); + Serial.print(F("Since the bottom: ")); + Serial.print(elapsed.GetValue()); + Serial.println(F(" us")); } void loop() {} diff --git a/keywords.txt b/keywords.txt index 2ed21ab..5445626 100644 --- a/keywords.txt +++ b/keywords.txt @@ -6,26 +6,41 @@ # Datatypes (KEYWORD1) ####################################### -TimerTwo KEYWORD1 +timer_two KEYWORD1 +timer2 KEYWORD1 +Timer2 KEYWORD1 +Timer KEYWORD1 +Status KEYWORD1 +Result KEYWORD1 +Error KEYWORD1 +State KEYWORD1 +TimeType KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) ####################################### -init KEYWORD2 -start KEYWORD2 -stop KEYWORD2 -resume KEYWORD2 -read KEYWORD2 -enablePwm KEYWORD2 -disablePwm KEYWORD2 -attachInterrupt KEYWORD2 -detachInterrupt KEYWORD2 -setPeriod KEYWORD2 -setPwmDuty KEYWORD2 +Begin KEYWORD2 +SetPeriod KEYWORD2 +Start KEYWORD2 +Stop KEYWORD2 +Resume KEYWORD2 +AttachInterrupt KEYWORD2 +DetachInterrupt KEYWORD2 +EnablePwm KEYWORD2 +SetPwmDuty KEYWORD2 +DisablePwm KEYWORD2 +Read KEYWORD2 +GetState KEYWORD2 +IsOk KEYWORD2 +GetError KEYWORD2 +GetErrorText KEYWORD2 +GetValue KEYWORD2 +Discard KEYWORD2 ####################################### # Constants (LITERAL1) ####################################### - +kPeriodMax LITERAL1 +kDefaultPeriod LITERAL1 diff --git a/src/.clang-tidy b/src/.clang-tidy deleted file mode 100644 index 3b6fafc..0000000 --- a/src/.clang-tidy +++ /dev/null @@ -1,17 +0,0 @@ ---- -# 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 deleted file mode 100644 index e63f9d3..0000000 --- a/src/StandardTypes.h +++ /dev/null @@ -1,66 +0,0 @@ -// 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 deleted file mode 100644 index 6efb295..0000000 --- a/src/TimerTwo.cpp +++ /dev/null @@ -1,279 +0,0 @@ -// 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; - PwmDutyCycle = 0u; -} - -TimerTwo::~TimerTwo() {} - -TimerTwo& TimerTwo::getInstance() { - static TimerTwo SingletonInstance; - return SingletonInstance; -} - -StdReturnType TimerTwo::init(TimeType Microseconds, - TimerIsrCallbackF_void sTimerOverflowCallback) { - StdReturnType ReturnValue = E_NOT_OK; - ClockSelectType ClockSelect{REG_CS_NO_CLOCK}; - - // A period setPeriod() would refuse leaves the timer as it was: started - // without a top, it would never move. - if ((STATE_INIT == State) && (Microseconds <= getPeriodMax()) && - (getTimerCycles(Microseconds, ClockSelect) != 0u)) { - 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); - - (void)setPeriod(Microseconds); - if (sTimerOverflowCallback != nullptr) { - attachInterrupt(sTimerOverflowCallback); - } - State = STATE_IDLE; - } - return ReturnValue; -} - -StdReturnType TimerTwo::setPeriod(TimeType Microseconds) { - StdReturnType ReturnValue{E_NOT_OK}; - - ClockSelectType ClockSelect{REG_CS_NO_CLOCK}; - byte const Top{(Microseconds <= getPeriodMax()) - ? getTimerCycles(Microseconds, ClockSelect) - : static_cast(0u)}; - - // A top of 0 would stop the counter at 0. - if (Top != 0u) { - ClockSelectBitGroup = ClockSelect; - /* OCR2A is TOP in phase correct PWM mode */ - OCR2A = Top; - // The duty is a share of the top. - OCR2B = getPwmCompareValue(); - - if (STATE_RUNNING == State) { - /* reset clock select register, and start the clock */ - writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, - ClockSelectBitGroup); - } - ReturnValue = 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)) { - /* set output compare register value for given Pwm pin */ - if (PWM_PIN_3 == PwmPin) { - ReturnValue = E_OK; - PwmDutyCycle = DutyCycle; - OCR2B = getPwmCompareValue(); - } - } - 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() { - // Only a timer that runs: start() takes a stopped one as initialized. - if (STATE_RUNNING == State) { - /* 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); - State = STATE_RUNNING; - return E_OK; - } - return E_NOT_OK; -} - -StdReturnType TimerTwo::attachInterrupt( - TimerIsrCallbackF_void TimerOverflowCallback) { - if (TimerOverflowCallback != nullptr) { - // The AVR writes the pointer a byte at a time: the interrupt must not call - // through half of the new one. - writeBit(TIMSK2, TOIE2, 0u); - 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); - // After the interrupt is off, which calls through it. - TimerIsrOverflowCallback = nullptr; -} - -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); - } - // The steps in clocks, then in microseconds: multiplied before divided, - // so that no step is lost. At most 2 * 255 steps of 1024 clocks, times - // 1000, fit 32 bits; the time is below getPeriodMax(), which TimeType - // holds. - uint32_t const Clocks{static_cast(counterValue) - << getPrescaleShiftScale()}; - Microseconds = static_cast((Clocks * 1000uL) / (F_CPU / 1000uL)); - 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; - } -} - -// The top for a period, and in ClockSelect the prescaler for it; 0 for a -// period too short for one step. -inline byte TimerTwo::getTimerCycles(TimeType Microseconds, - ClockSelectType& ClockSelect) { - /* calculate timer cycles to reach timer period, counter runs backwards after - * TOP, interrupt is at BOTTOM so divide microseconds by 2 */ - // Multiplied before divided, so that a clock below 2 MHz keeps its cycles; - // up to getPeriodMax() the product is below 2^29. - uint32_t TimerCycles{ - static_cast(((F_CPU / 1000uL) * Microseconds) / 2000uL)}; - /* calculate timer pre-scaler */ - if (TimerCycles < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_NO_PRESCALER; - else if ((TimerCycles >>= 3u) < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_PRESCALE_8; - else if ((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_PRESCALE_32; - else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_PRESCALE_64; - else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_PRESCALE_128; - else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_PRESCALE_256; - else if ((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) - ClockSelect = REG_CS_PRESCALE_1024; - - // Below TIMERTWO_RESOLUTION for a period up to getPeriodMax(). - return static_cast(TimerCycles); -} - -// The compare value of PwmDutyCycle at the top OCR2A, rounded: 0 is the -// bottom, which keeps the output low, and 255 the top, which keeps it high. -// In 16 bits unsigned: 255 * 255 does not fit the AVR's int. -inline byte TimerTwo::getPwmCompareValue() { - uint16_t const Product{ - static_cast(static_cast(OCR2A) * PwmDutyCycle)}; - return static_cast((Product + 127u) / 255u); -} - -ISR(TIMER2_OVF_vect) { Timer2.callTimerIsrOverflowCallback(); } diff --git a/src/TimerTwo.h b/src/TimerTwo.h index 26086f4..90ad5cf 100644 --- a/src/TimerTwo.h +++ b/src/TimerTwo.h @@ -3,211 +3,36 @@ /*! * \file - * \brief TimerTwo, a periodic interrupt, a PWM and a time readout on - * Timer/Counter2 of the ATmega328P. + * \brief The header a sketch includes, before any other of the library. * - * 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. + * It includes all of the library. arduino-cli finds a library only by a + * header that lies directly in its `src/`, not by one in a folder below, and + * it goes through a sketch's includes in order. Once this header has found + * the library, `src/` is on the include path, and a header below it can be + * included by its path in every file after it. * - * 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. + * \code{.cpp} + * #include + * + * void OnTick() { ... } // every millisecond + * + * void setup() { + * timer_two::Discard(timer_two::timer2.Begin(1000, OnTick)); + * timer_two::Discard(timer_two::timer2.Start()); + * } + * \endcode */ -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&); +// The name is the library's, as Arduino expects, not lower case as Google's. +// The export pragmas tell clang-tidy's include-cleaner that this header +// provides what it includes. - TimerIsrCallbackF_void TimerIsrOverflowCallback; - StateType State; - ClockSelectType ClockSelectBitGroup; - // The duty setPwmDuty() was given, which setPeriod() applies to a new top. - byte PwmDutyCycle; - - byte getPrescaleShiftScale(); - byte getTimerCycles(TimeType, ClockSelectType&); - byte getPwmCompareValue(); - - 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: the last one - * whose half fits 256 steps of the largest prescaler. - */ - TimeType getPeriodMax() { - return static_cast( - (TIMERTWO_RESOLUTION * TIMERTWO_MAX_PRESCALER * 2uL * 1000uL - 1uL) / - (F_CPU / 1000uL)); - } - - /*! - * \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 setPeriod() would - * refuse the period; the timer is left as it was then. - */ - 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 keeps its share. - * \param Microseconds the period, up to getPeriodMax() - * \return E_NOT_OK if the period is too long, or too short for one step of - * the counter at the CPU's clock: 0, or 1 below 2 MHz. - */ - StdReturnType setPeriod(TimeType Microseconds); - /*! - * \brief Starts the PWM on a pin, with a duty. - * \param PwmPin the pin - * \param DutyCycle the duty, 0 for always low to 255 for always high - * \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 for always low to 255 for always high - * \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, if it runs. */ - void stop(); - /*! - * \brief Lets the counter go on from where stop() stopped it, and the timer - * runs again. - * \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 and forgets its callback, so that - * start() does not enable it again. - */ - 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(); } -}; +#ifndef TIMERTWO_SRC_TIMERTWO_H_ +#define TIMERTWO_SRC_TIMERTWO_H_ -/*! \brief The one TimerTwo. */ -extern TimerTwo& Timer2; +#include "timer_two/attributes.h" // IWYU pragma: export +#include "timer_two/status.h" // IWYU pragma: export +#include "timer_two/timer.h" // IWYU pragma: export +#include "timer_two/timer2.h" // IWYU pragma: export #endif // TIMERTWO_SRC_TIMERTWO_H_ diff --git a/src/timer_two/attributes.h b/src/timer_two/attributes.h new file mode 100644 index 0000000..99c8c69 --- /dev/null +++ b/src/timer_two/attributes.h @@ -0,0 +1,57 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief Attributes of a later standard, as macros for every standard, and + * Discard() for a result one of them marks. + * + * The library is written for C++11 and later. Where a later standard has an + * attribute, the macro is that attribute; before it, the compiler's own + * where GCC and clang have one, else nothing. + */ + +#ifndef TIMERTWO_SRC_TIMER_TWO_ATTRIBUTES_H_ +#define TIMERTWO_SRC_TIMER_TWO_ATTRIBUTES_H_ + +/*! + * \def TIMER_TWO_NODISCARD + * \brief Marks a function whose result must not be ignored. + * + * Stands in front of the declaration: `TIMER_TWO_NODISCARD int Read();`. A call + * that drops the result is a warning, and an error in CI. + * + * \note For a function only. On a type, as a class whose every result must be + * used, `[[nodiscard]]` of C++17 works, GCC's attribute before it does + * not. + */ +// By __cplusplus, not by __has_cpp_attribute: GCC and clang have +// [[nodiscard]] in C++11 as well, as an extension that -Wpedantic reports. +#if __cplusplus >= 201703L +#define TIMER_TWO_NODISCARD [[nodiscard]] +#elif defined(__GNUC__) +// GCC, avr-gcc and clang, which defines __GNUC__ as well. +#define TIMER_TWO_NODISCARD __attribute__((warn_unused_result)) +#else +#define TIMER_TWO_NODISCARD +#endif + +namespace timer_two { + +/*! + * \brief Drops a result that must not be ignored, where dropping it is meant. + * + * For a result TIMER_TWO_NODISCARD marks: the call says that it is + * dropped on purpose, and a comment beside it why: + * `Discard(Send(frame)); // sent again on the next tick`. Not a cast to + * `void`: before C++17, GCC's `warn_unused_result` warns through one and clang + * does not, so a cast that passes on the host fails the build for the target. + * + * \tparam Value The type of the result. + */ +template +void Discard(Value const& /*value*/) noexcept {} + +} // namespace timer_two + +#endif // TIMERTWO_SRC_TIMER_TWO_ATTRIBUTES_H_ diff --git a/src/timer_two/status.cpp b/src/timer_two/status.cpp new file mode 100644 index 0000000..c43f0e2 --- /dev/null +++ b/src/timer_two/status.cpp @@ -0,0 +1,49 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "timer_two/status.h" + +#include +#include + +namespace timer_two { +namespace { + +// The texts and the table of them lie in flash: a switch that returned F("...") +// for each error would be turned by avr-gcc into a table of pointers that the +// Uno copies into RAM. +char const kTextOk[] PROGMEM = "ok"; +char const kTextNotBegun[] PROGMEM = "not begun"; +char const kTextBegunAlready[] PROGMEM = "begun already"; +char const kTextRunning[] PROGMEM = "running"; +char const kTextNotRunning[] PROGMEM = "not running"; +char const kTextNotStopped[] PROGMEM = "not stopped"; +char const kTextPeriodOutOfRange[] PROGMEM = "period out of range"; +char const kTextNoCallback[] PROGMEM = "no callback"; +char const kTextUnknownError[] PROGMEM = "unknown error"; + +// In the order of Error. An array, as PROGMEM takes one. +// NOLINTNEXTLINE(modernize-avoid-c-arrays) +char const* const kTexts[] PROGMEM = { + kTextOk, kTextNotBegun, kTextBegunAlready, kTextRunning, + kTextNotRunning, kTextNotStopped, kTextPeriodOutOfRange, kTextNoCallback, +}; + +constexpr uint8_t kTextCount{sizeof(kTexts) / sizeof(kTexts[0])}; + +static_assert(kTextCount == static_cast(Error::kNoCallback) + 1, + "every error has a text"); + +} // namespace + +__FlashStringHelper const* Status::GetErrorText() const { + uint8_t const index{static_cast(error_)}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) + void const* const text{index < kTextCount ? pgm_read_ptr(&kTexts[index]) + : kTextUnknownError}; + // The type Serial.print() takes for a text in flash, as F() makes it. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return reinterpret_cast<__FlashStringHelper const*>(text); +} + +} // namespace timer_two diff --git a/src/timer_two/status.h b/src/timer_two/status.h new file mode 100644 index 0000000..e21b250 --- /dev/null +++ b/src/timer_two/status.h @@ -0,0 +1,162 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief Why a call did not do what it was asked: Error, and Status and Result, + * which a function returns. + */ + +#ifndef TIMERTWO_SRC_TIMER_TWO_STATUS_H_ +#define TIMERTWO_SRC_TIMER_TWO_STATUS_H_ + +#include + +// The core's name, reserved as it is: GetErrorText() returns this very type. +class __FlashStringHelper; // NOLINT(bugprone-reserved-identifier) + +namespace timer_two { + +/*! + * \brief Why a call did not do what it was asked; one byte, so that it returns + * in a register. + */ +enum class Error : uint8_t { + kOk = 0, /*!< No error. */ + kNotBegun, /*!< Begin() has not been called. */ + kBegunAlready, /*!< Begin() has been called already. */ + kRunning, /*!< The timer runs already. */ + kNotRunning, /*!< The timer does not run. */ + kNotStopped, /*!< The timer was not stopped by Stop(). */ + kPeriodOutOfRange, /*!< The period is not in range, see SetPeriod(). */ + kNoCallback /*!< The callback is nullptr. */ +}; + +/*! + * \brief What a function that can refuse returns when it has no value to + * return. + * + * A sketch asks IsOk(), or compares with an error: + * + * \code{.cpp} + * if (timer_two::timer2.SetPeriod(50000) == + * timer_two::Error::kPeriodOutOfRange) { + * ... + * } + * \endcode + * + * \note It has no conversion to `bool`, on purpose: with `StdReturnType` of + * version 1, `E_OK` was 0, so `if (Timer2.start())` was true on an error. + */ +class Status { + public: + /*! + * \brief Makes a status of `error`, ok when none is given. + * + * Implicit, so that a function returns an error as it is. + * + * \param error the error, or Error::kOk + */ + constexpr Status( // NOLINT(google-explicit-constructor) + Error error = Error::kOk) + : error_{error} {} + + /*! \brief Why the call failed, or Error::kOk. */ + constexpr Error GetError() const { return error_; } + + /*! + * \brief The error in a few words, in flash, for `Serial.print()`: + * `"period out of range"` for Error::kPeriodOutOfRange. + * + * A sketch that never calls it pays nothing, as the linker drops it with its + * texts. + * + * \return the text; `"unknown error"` for a byte cast to Error that is none + * of its values + */ + __FlashStringHelper const* GetErrorText() const; + + /*! \brief Whether the call did what it was asked. */ + constexpr bool IsOk() const { return error_ == Error::kOk; } + + /*! + * \brief Whether the call failed for this reason. + * \param other the error to compare with + */ + constexpr bool operator==(Error other) const { return error_ == other; } + + /*! + * \brief Whether the call did not fail for this reason. + * \param other the error to compare with + */ + constexpr bool operator!=(Error other) const { return error_ != other; } + + private: + // A sketch reaches the error only through this class, so that it could carry + // more than the enum one day without a sketch changing. + Error error_; +}; + +/*! + * \brief What a function that reads a value returns: the value, or why there is + * none. + * + * After an error the value is 0, or what `Value()` is, never undefined. + * + * \tparam Value the type of the value + */ +template +class Result { + public: + /*! + * \brief Makes a result that holds `value`. + * + * Implicit, so that a function returns its value as it is. + * + * \param value the value + */ + // NOLINTNEXTLINE(google-explicit-constructor) + constexpr Result(Value value) // NOLINT(runtime/explicit) + : value_{value}, error_{Error::kOk} {} + + /*! + * \brief Makes a result that holds why there is no value. + * + * Implicit, so that a function returns its error as it is. + * + * \param error the error + */ + // NOLINTNEXTLINE(google-explicit-constructor) + constexpr Result(Error error) // NOLINT(runtime/explicit) + : value_{}, error_{error} {} + + /*! \brief The value; 0, or what `Value()` is, after an error. */ + constexpr Value GetValue() const { return value_; } + + /*! \brief Why there is no value, or Error::kOk. */ + constexpr Error GetError() const { return error_; } + + /*! \copydoc Status::GetErrorText() */ + __FlashStringHelper const* GetErrorText() const { + return Status{error_}.GetErrorText(); + } + + /*! \brief Whether there is a value. */ + constexpr bool IsOk() const { return error_ == Error::kOk; } + + /*! \copydoc Status::operator==(Error) const */ + constexpr bool operator==(Error other) const { return error_ == other; } + + /*! \copydoc Status::operator!=(Error) const */ + constexpr bool operator!=(Error other) const { return error_ != other; } + + private: + // Side by side rather than in a union: a value and its error still return in + // registers on the AVR, and the value is never left undefined. + Value value_; + Error error_; +}; + +} // namespace timer_two + +#endif // TIMERTWO_SRC_TIMER_TWO_STATUS_H_ diff --git a/src/timer_two/timer.h b/src/timer_two/timer.h new file mode 100644 index 0000000..74ecfe3 --- /dev/null +++ b/src/timer_two/timer.h @@ -0,0 +1,443 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief Timer, a periodic interrupt, a PWM and a time readout on an 8-bit + * Timer/Counter of the AVR in phase correct PWM with OCRxA as its top. + * + * The counter runs up to the top and down again in mode 5: the period sets + * the top, OCRxA, and the prescaler; the overflow at the bottom calls the + * callback; and OCxB gives the PWM, at a duty that is a share of the top. + * Which Timer/Counter it is, is a parameter of the template: timer2.h hands in + * Timer/Counter2 of the ATmega328P, the tests a mock of it. + */ + +#ifndef TIMERTWO_SRC_TIMER_TWO_TIMER_H_ +#define TIMERTWO_SRC_TIMER_TWO_TIMER_H_ + +#include +#include +#include + +#include "timer_two/attributes.h" +#include "timer_two/status.h" + +namespace timer_two { + +/*! + * \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 The function the overflow interrupt calls. */ +using Callback = void (*)(); + +/*! \brief Where a timer is in its life. */ +enum class State : uint8_t { + kNotBegun, /*!< Begin() comes first. */ + kIdle, /*!< Begun, not started. */ + kRunning, /*!< Counting. */ + kStopped /*!< Stopped by Stop(); Resume() goes on, Start() from 0. */ +}; + +namespace internal { + +/*! \cond */ +// The values of the clock select bits CSx2..CSx0, and the bits themselves. +enum class ClockSelect : uint8_t { + kNoClock = 0, + kDivide1, + kDivide8, + kDivide32, + kDivide64, + kDivide128, + kDivide256, + kDivide1024 +}; +constexpr uint8_t kClockSelectMask{0x07U}; + +// The counter has 256 values. +constexpr uint32_t kCounterValues{256U}; +constexpr uint32_t kClocksPerMillisecond{F_CPU / 1000UL}; +constexpr uint32_t kMicrosecondsPerMillisecond{1000U}; +// The duty is a share of 255 of the top, rounded. +constexpr uint16_t kDutyMax{255U}; +constexpr uint16_t kDutyRounding{kDutyMax / 2U}; + +// The prescalers as shifts: 1, 8, 32, 64, 128, 256 and 1024. +constexpr uint8_t kShiftDivide8{3U}; +constexpr uint8_t kShiftDivide32{5U}; +constexpr uint8_t kShiftDivide64{6U}; +constexpr uint8_t kShiftDivide128{7U}; +constexpr uint8_t kShiftDivide256{8U}; +constexpr uint8_t kShiftDivide1024{10U}; + +// The shift of the prescaler clock_select selects; a switch rather than a +// table, which avr-gcc would copy to RAM. +inline uint8_t ShiftOf(ClockSelect clock_select) { + switch (clock_select) { + case ClockSelect::kDivide8: + return kShiftDivide8; + case ClockSelect::kDivide32: + return kShiftDivide32; + case ClockSelect::kDivide64: + return kShiftDivide64; + case ClockSelect::kDivide128: + return kShiftDivide128; + case ClockSelect::kDivide256: + return kShiftDivide256; + case ClockSelect::kDivide1024: + return kShiftDivide1024; + case ClockSelect::kNoClock: + case ClockSelect::kDivide1: + default: + return 0U; + } +} + +// The top for a period, and in clock_select the smallest prescaler that lets +// it fit the counter; 0 for a period too short for one step, or too long. The +// counter runs up to the top and down again, so half the period is counted. +// Multiplied before divided, so that a clock below 2 MHz keeps its cycles; up +// to Timer::kPeriodMax the product is below 2^29. +inline uint8_t TopOf(TimeType period, ClockSelect& clock_select) { + uint32_t const half{(kClocksPerMillisecond * period) / + (2U * kMicrosecondsPerMillisecond)}; + for (uint8_t select{static_cast(ClockSelect::kDivide1)}; + select <= static_cast(ClockSelect::kDivide1024); ++select) { + uint32_t const top{half >> ShiftOf(static_cast(select))}; + if (top < kCounterValues) { + clock_select = static_cast(select); + return static_cast(top); + } + } + clock_select = ClockSelect::kNoClock; + return 0U; +} +/*! \endcond */ + +} // namespace internal + +/*! + * \brief A periodic interrupt, a PWM and a time readout on an 8-bit + * Timer/Counter in phase correct PWM, mode 5. + * + * Begin() first, then Start(). A function that can refuse returns a Status, + * and leaves the timer as it was when it refuses. A sketch uses the one that + * timer2.h gives, timer2. + * + * \tparam Registers the Timer/Counter: static functions `Tccra()`, `Tccrb()`, + * `Ocra()`, `Ocrb()`, `Timsk()`, `Tifr()` and `Tcnt()` that + * return its registers, and `kPwmPin`, the Arduino pin of + * OCxB. The names of the bits are those of Timer/Counter2, as + * all of the AVR's 8-bit timers share their places. + */ +template +class Timer { + public: + /*! + * \brief The longest period, in microseconds: the last whose half fits 256 + * steps of the largest prescaler. 32767 at 16 MHz. + */ + static constexpr TimeType kPeriodMax{static_cast( + (((internal::kCounterValues << internal::kShiftDivide1024) * 2U * + internal::kMicrosecondsPerMillisecond) - + 1U) / + internal::kClocksPerMillisecond)}; + + /*! \brief The period Begin() sets if none is given: 1 ms. */ + static constexpr TimeType kDefaultPeriod{1000U}; + + /*! + * \brief Sets the timer up in mode 5, with a period and a callback; it does + * not count before Start(). + * \param period the period in microseconds, up to kPeriodMax + * \param callback what the overflow interrupt calls, or nullptr for none + * \return Error::kBegunAlready, or Error::kPeriodOutOfRange as SetPeriod() + */ + TIMER_TWO_NODISCARD Status Begin(TimeType period = kDefaultPeriod, + Callback callback = nullptr) { + internal::ClockSelect clock_select{internal::ClockSelect::kNoClock}; + uint8_t const top{internal::TopOf(period, clock_select)}; + if (state_ != State::kNotBegun) { + return Error::kBegunAlready; + } + if ((period > kPeriodMax) || (top == 0U)) { + return Error::kPeriodOutOfRange; + } + // Mode 5: WGMx2 and WGMx0; no clock and no output yet. + Registers::Tccra() = static_cast(1U << WGM20); + Registers::Tccrb() = static_cast(1U << WGM22); + state_ = State::kIdle; + ApplyPeriod(top, clock_select); + if (callback != nullptr) { + Discard(AttachInterrupt(callback)); // not nullptr, so it attaches + } + return Error::kOk; + } + + /*! + * \brief Sets the period of the interrupt and of the PWM; the duty of the PWM + * keeps its share of it. + * \param period the period in microseconds, up to kPeriodMax + * \return Error::kNotBegun, or Error::kPeriodOutOfRange for a period too + * long, or too short for one step of the counter: 0, or 1 below 2 MHz + */ + TIMER_TWO_NODISCARD Status SetPeriod(TimeType period) { + internal::ClockSelect clock_select{internal::ClockSelect::kNoClock}; + uint8_t const top{internal::TopOf(period, clock_select)}; + if (state_ == State::kNotBegun) { + return Error::kNotBegun; + } + // A top of 0 would stop the counter at 0. + if ((period > kPeriodMax) || (top == 0U)) { + return Error::kPeriodOutOfRange; + } + ApplyPeriod(top, clock_select); + return Error::kOk; + } + + /*! + * \brief Starts the counter at 0, and the interrupt if a callback is set. + * \return Error::kNotBegun, or Error::kRunning + */ + TIMER_TWO_NODISCARD Status Start() { + if (state_ == State::kNotBegun) { + return Error::kNotBegun; + } + if (state_ == State::kRunning) { + return Error::kRunning; + } + Registers::Tcnt() = 0U; + SelectClock(clock_select_); + if (callback_ != nullptr) { + // Off the bottom first, as version 1 did; one step takes at most 1024 + // clocks, 64 us at 16 MHz. + while (Registers::Tcnt() == 0U) { + } + EnableOverflowInterrupt(); + } + state_ = State::kRunning; + return Error::kOk; + } + + /*! + * \brief Stops the counter where it is. + * \return Error::kNotRunning + */ + TIMER_TWO_NODISCARD Status Stop() { + if (state_ != State::kRunning) { + return Error::kNotRunning; + } + SelectClock(internal::ClockSelect::kNoClock); + state_ = State::kStopped; + return Error::kOk; + } + + /*! + * \brief Lets the counter go on from where Stop() stopped it. + * \return Error::kNotStopped + */ + TIMER_TWO_NODISCARD Status Resume() { + if (state_ != State::kStopped) { + return Error::kNotStopped; + } + SelectClock(clock_select_); + state_ = State::kRunning; + return Error::kOk; + } + + /*! + * \brief Sets the function the overflow interrupt calls, and enables the + * interrupt if the timer runs. + * \param callback the function + * \return Error::kNoCallback for nullptr + */ + TIMER_TWO_NODISCARD Status AttachInterrupt(Callback callback) { + if (callback == nullptr) { + return Error::kNoCallback; + } + // The AVR writes the pointer a byte at a time: the interrupt must not call + // through half of the new one. + ClearBit(Registers::Timsk(), TOIE2); + callback_ = callback; + if (state_ == State::kRunning) { + EnableOverflowInterrupt(); + } + return Error::kOk; + } + + /*! + * \brief Disables the overflow interrupt and forgets its callback, so that + * Start() does not enable it again. + */ + void DetachInterrupt() { + ClearBit(Registers::Timsk(), TOIE2); + // After the interrupt is off, which calls through it. + callback_ = nullptr; + } + + /*! + * \brief Starts the PWM on `Registers::kPwmPin`, pin 3 for Timer2, with a + * duty. + * + * It breaks analogWrite() on that pin. + * + * \param duty the duty, 0 for always low to 255 for always high + * \return Error::kNotBegun + */ + TIMER_TWO_NODISCARD Status EnablePwm(uint8_t duty) { + if (state_ == State::kNotBegun) { + return Error::kNotBegun; + } + pinMode(Registers::kPwmPin, OUTPUT); + SetBit(Registers::Tccra(), COM2B1); + return SetPwmDuty(duty); + } + + /*! + * \brief Sets the duty of the PWM, which EnablePwm() started or is to start. + * \param duty the duty, 0 for always low to 255 for always high + * \return Error::kNotBegun + */ + TIMER_TWO_NODISCARD Status SetPwmDuty(uint8_t duty) { + if (state_ == State::kNotBegun) { + return Error::kNotBegun; + } + duty_ = duty; + Registers::Ocrb() = CompareValue(); + return Error::kOk; + } + + /*! + * \brief Stops the PWM; the pin is a plain output again, at the level of its + * bit in its PORT register. + */ + void DisablePwm() { ClearBit(Registers::Tccra(), COM2B1); } + + /*! + * \brief The time since the counter was last at its bottom, in steps of the + * prescaled clock. + * + * Waits for one step of the counter, at most 1024 clocks, to see whether it + * counts up or down. + * + * \return the time in microseconds, or Error::kNotRunning + */ + TIMER_TWO_NODISCARD Result Read() { + if (state_ != State::kRunning) { + return Error::kNotRunning; + } + uint16_t steps{Registers::Tcnt()}; + uint8_t next{Registers::Tcnt()}; + while (next == steps) { + next = Registers::Tcnt(); + } + // Counting down: up to the top, and back to where it is. + if (next < steps) { + steps = static_cast((2U * Registers::Ocra()) - steps); + } + // In clocks, then in microseconds: multiplied before divided, so that no + // step is lost. At most 2 * 255 steps of 1024 clocks, times 1000, fit 32 + // bits; the time is below kPeriodMax, which TimeType holds. + uint32_t const clocks{static_cast(steps) + << internal::ShiftOf(clock_select_)}; + return static_cast( + (clocks * internal::kMicrosecondsPerMillisecond) / + internal::kClocksPerMillisecond); + } + + /*! \brief Where the timer is in its life. */ + State GetState() const { return state_; } + + /*! \brief The function the overflow interrupt calls, or nullptr. */ + Callback GetCallback() const { return callback_; } + + /*! + * \brief Calls the callback; for the overflow interrupt, which timer2.cpp + * defines. + */ + void OnOverflow() { + Callback const callback{callback_}; + if (callback != nullptr) { + callback(); + } + } + + private: + // The compare value of duty_ at the top, rounded: 0 is the bottom, which + // keeps the output low, and 255 the top, which keeps it high. In 16 bits + // unsigned: 255 * 255 does not fit the AVR's int. + uint8_t CompareValue() const { + // The outer cast is redundant on the AVR, where the product is unsigned + // int, but not on the host, where it is int. + // NOLINTNEXTLINE(readability-redundant-casting) + uint16_t const product{static_cast( + static_cast(Registers::Ocra()) * duty_)}; + return static_cast((product + internal::kDutyRounding) / + internal::kDutyMax); + } + + void ApplyPeriod(uint8_t top, internal::ClockSelect clock_select) { + clock_select_ = clock_select; + Registers::Ocra() = top; + Registers::Ocrb() = CompareValue(); + if (state_ == State::kRunning) { + SelectClock(clock_select_); + } + } + + // The flag of an overflow stays set until the interrupt runs, even while it + // is disabled: the core's init() runs Timer2 for analogWrite() before + // setup(), and an earlier run leaves it as well. Enabled with it set, the + // interrupt would call the callback at once rather than after a period. A + // flag is cleared by writing 1 to it, and only it: no read first. + static void EnableOverflowInterrupt() { + Registers::Tifr() = static_cast(1U << TOV2); + SetBit(Registers::Timsk(), TOIE2); + } + + static void SelectClock(internal::ClockSelect clock_select) { + Registers::Tccrb() = static_cast( + (static_cast(Registers::Tccrb()) & + ~static_cast(internal::kClockSelectMask)) | + static_cast(clock_select)); + } + + template + static void SetBit(Register& reg, uint8_t bit) { + reg = static_cast(static_cast(reg) | (1U << bit)); + } + + template + static void ClearBit(Register& reg, uint8_t bit) { + reg = static_cast(static_cast(reg) & ~(1U << bit)); + } + + // volatile, as the overflow interrupt reads it: the store must not move + // past the enabling of the interrupt. + Callback volatile callback_{nullptr}; + State state_{State::kNotBegun}; + internal::ClockSelect clock_select_{internal::ClockSelect::kNoClock}; + // The duty SetPwmDuty() was given, which a new period applies to its top. + uint8_t duty_{0}; +}; + +/*! \cond */ +// The definitions C++11 needs for a static constexpr member that is used by +// reference. +template +constexpr TimeType Timer::kPeriodMax; +template +constexpr TimeType Timer::kDefaultPeriod; +/*! \endcond */ + +} // namespace timer_two + +#endif // TIMERTWO_SRC_TIMER_TWO_TIMER_H_ diff --git a/src/timer_two/timer2.cpp b/src/timer_two/timer2.cpp new file mode 100644 index 0000000..91c7265 --- /dev/null +++ b/src/timer_two/timer2.cpp @@ -0,0 +1,16 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "timer_two/timer2.h" + +#include +#include + +namespace timer_two { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +Timer2 timer2; + +} // namespace timer_two + +ISR(TIMER2_OVF_vect) { timer_two::timer2.OnOverflow(); } diff --git a/src/timer_two/timer2.h b/src/timer_two/timer2.h new file mode 100644 index 0000000..c114d97 --- /dev/null +++ b/src/timer_two/timer2.h @@ -0,0 +1,63 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief timer2, Timer/Counter2 of the ATmega328P as a Timer. + * + * It breaks analogWrite() on pins 3 and 11, and tone(), which use Timer2 as + * well. Pin 11, OC2A, gives no PWM: OCR2A is the top of the counter. + */ + +#ifndef TIMERTWO_SRC_TIMER_TWO_TIMER2_H_ +#define TIMERTWO_SRC_TIMER_TWO_TIMER2_H_ + +#include +#include + +#include "timer_two/timer.h" + +namespace timer_two { + +/*! + * \brief The registers of Timer/Counter2, for Timer. + * + * Each returns the register as the vendor's header declares it, so that the + * compiler writes it where the datasheet says. + */ +struct Timer2Registers { + /*! \brief The Arduino pin of OC2B, PD3, which gives the PWM. */ + static constexpr uint8_t kPwmPin{3}; + + /*! \brief TCCR2A. */ + static auto Tccra() -> decltype((TCCR2A)) { return TCCR2A; } + /*! \brief TCCR2B. */ + static auto Tccrb() -> decltype((TCCR2B)) { return TCCR2B; } + /*! \brief OCR2A, the top. */ + static auto Ocra() -> decltype((OCR2A)) { return OCR2A; } + /*! \brief OCR2B, the compare value of the PWM. */ + static auto Ocrb() -> decltype((OCR2B)) { return OCR2B; } + /*! \brief TIMSK2. */ + static auto Timsk() -> decltype((TIMSK2)) { return TIMSK2; } + /*! \brief TIFR2, whose flags are cleared by writing 1. */ + static auto Tifr() -> decltype((TIFR2)) { return TIFR2; } + /*! \brief TCNT2, the counter. */ + static auto Tcnt() -> decltype((TCNT2)) { return TCNT2; } +}; + +/*! \brief The type of timer2, for its constants: `Timer2::kPeriodMax`. */ +using Timer2 = Timer; + +/*! + * \brief Timer/Counter2; its overflow interrupt calls the callback. + * + * Made when compiling, by the constexpr constructor: there is no order of + * construction to mind, and it can be used from the first line of setup(). + */ +// The one object a sketch shares with the interrupt, as Serial is. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +extern Timer2 timer2; + +} // namespace timer_two + +#endif // TIMERTWO_SRC_TIMER_TWO_TIMER2_H_ diff --git a/test/ClockTest.cpp b/test/ClockTest.cpp index 85bcf74..9d82062 100644 --- a/test/ClockTest.cpp +++ b/test/ClockTest.cpp @@ -1,10 +1,9 @@ // Copyright 2026 Andreas Burnickl // SPDX-License-Identifier: GPL-3.0-or-later // -// TimerTwo at whatever clock F_CPU is: CMakeLists.txt builds these tests at -// 1, 16 and 20 MHz. Each expectation is computed from F_CPU in 64 bits, apart -// from how TimerTwo computes it. As in TimerTwoTest.cpp, each test needs a -// process of its own. +// Timer at whatever clock F_CPU is: CMakeLists.txt builds these tests at 1, +// 16 and 20 MHz. Each expectation is computed from F_CPU in 64 bits, apart +// from how Timer computes it. #include #include @@ -12,9 +11,12 @@ #include -#include "StandardTypes.h" -#include "TimerTwo.h" +#include "test/printers.h" // IWYU pragma: keep +#include "timer_two/status.h" +#include "timer_two/timer.h" +#include "timer_two/timer2.h" +namespace timer_two { namespace { constexpr uint64_t kClock{F_CPU}; @@ -37,39 +39,45 @@ uint64_t PeriodInClocks() { return uint64_t{2} * OCR2A * Prescaler(); } class ClockTest : 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."; + TCCR2A = 0; + TCCR2B = 0; + OCR2A = 0; + TCNT2.Set(0, true); } + + Timer2& timer() { return timer_; } + + private: + Timer2 timer_; }; TEST_F(ClockTest, TheLongestPeriodIsTheLastThatFits) { uint64_t const longest{ ((kLongestPeriodInClocks * kMicrosecondsPerSecond) - 1) / kClock}; - EXPECT_EQ(Timer2.getPeriodMax(), longest); + EXPECT_EQ(Timer2::kPeriodMax, longest); } TEST_F(ClockTest, TheLongestPeriodIsTakenAndOneMoreRefused) { - ASSERT_EQ(Timer2.init(Timer2.getPeriodMax()), E_OK); - ASSERT_EQ(Timer2.start(), E_OK); + ASSERT_EQ(timer().Begin(Timer2::kPeriodMax), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); EXPECT_EQ(Prescaler(), 1024U); - EXPECT_EQ(Timer2.setPeriod( - static_cast(Timer2.getPeriodMax() + 1U)), - E_NOT_OK); + EXPECT_EQ(timer().SetPeriod(static_cast(Timer2::kPeriodMax + 1U)), + Error::kPeriodOutOfRange); } // Each period is met to less than a step of the counter up and one down, and // the two clocks that dividing by 2 and by the prescaler may cut. TEST_F(ClockTest, EachPeriodIsMetWithinAStep) { - ASSERT_EQ(Timer2.init(), E_OK); + ASSERT_EQ(timer().Begin(), Error::kOk); // The prescaler is in TCCR2B while the timer runs. - ASSERT_EQ(Timer2.start(), E_OK); + ASSERT_EQ(timer().Start(), Error::kOk); constexpr std::array kPeriods{2, 3, 10, 100, 1000, 10000, 20000, 26214}; for (uint32_t const period : kPeriods) { - ASSERT_EQ(Timer2.setPeriod(static_cast(period)), E_OK) + ASSERT_EQ(timer().SetPeriod(static_cast(period)), Error::kOk) << period << " us"; uint64_t const wanted{period * kClock / kMicrosecondsPerSecond}; @@ -83,18 +91,21 @@ TEST_F(ClockTest, APeriodShorterThanAStepIsRefused) { // One step up and one down at no prescaler: two clocks. constexpr bool kOneMicrosecondIsAStep{2 * kMicrosecondsPerSecond <= kClock}; - EXPECT_EQ(Timer2.init(1U), kOneMicrosecondIsAStep ? E_OK : E_NOT_OK); + EXPECT_EQ(timer().Begin(1U), + kOneMicrosecondIsAStep ? Error::kOk : Error::kPeriodOutOfRange); } TEST_F(ClockTest, ReadIsTheTimeOfTheStepsCounted) { - ASSERT_EQ(Timer2.init(1000U), E_OK); - ASSERT_EQ(Timer2.start(), E_OK); + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); TCNT2.Set(50, true); - TimerTwo::TimeType microseconds{0}; - ASSERT_EQ(Timer2.read(microseconds), E_OK); + Result const result{timer().Read()}; - EXPECT_EQ(microseconds, 50 * Prescaler() * kMicrosecondsPerSecond / kClock); + ASSERT_TRUE(result.IsOk()); + EXPECT_EQ(result.GetValue(), + 50 * Prescaler() * kMicrosecondsPerSecond / kClock); } } // namespace +} // namespace timer_two diff --git a/test/StatusTest.cpp b/test/StatusTest.cpp new file mode 100644 index 0000000..fb967c9 --- /dev/null +++ b/test/StatusTest.cpp @@ -0,0 +1,76 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "timer_two/status.h" + +#include +#include + +#include + +#include "test/printers.h" // IWYU pragma: keep + +namespace timer_two { +namespace { + +TEST(StatusTest, IsOkWithoutAnError) { + Status const status; + + EXPECT_TRUE(status.IsOk()); + EXPECT_EQ(status.GetError(), Error::kOk); +} + +TEST(StatusTest, CarriesItsError) { + Status const status{Error::kNotRunning}; + + EXPECT_FALSE(status.IsOk()); + EXPECT_EQ(status.GetError(), Error::kNotRunning); + EXPECT_TRUE(status == Error::kNotRunning); + EXPECT_TRUE(status != Error::kRunning); +} + +TEST(StatusTest, IsAConstantExpression) { + static_assert(!Status{Error::kNoCallback}.IsOk(), "made when compiling"); +} + +TEST(StatusTest, HasATextForEachError) { + EXPECT_EQ(std::string{TextOf(Error::kOk)}, "ok"); + EXPECT_EQ(std::string{TextOf(Error::kNotBegun)}, "not begun"); + EXPECT_EQ(std::string{TextOf(Error::kBegunAlready)}, "begun already"); + EXPECT_EQ(std::string{TextOf(Error::kRunning)}, "running"); + EXPECT_EQ(std::string{TextOf(Error::kNotRunning)}, "not running"); + EXPECT_EQ(std::string{TextOf(Error::kNotStopped)}, "not stopped"); + EXPECT_EQ(std::string{TextOf(Error::kPeriodOutOfRange)}, + "period out of range"); + EXPECT_EQ(std::string{TextOf(Error::kNoCallback)}, "no callback"); +} + +TEST(StatusTest, HasATextForAByteThatIsNoError) { + // A byte that is none of the values of Error, on purpose. + // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange) + Error const no_error{static_cast(200)}; + + EXPECT_EQ(std::string{TextOf(no_error)}, "unknown error"); +} + +TEST(ResultTest, HoldsAValue) { + Result const result{uint16_t{42}}; + + EXPECT_TRUE(result.IsOk()); + EXPECT_EQ(result.GetValue(), 42U); + EXPECT_EQ(result.GetError(), Error::kOk); +} + +TEST(ResultTest, HoldsAnErrorAndAValueOfZero) { + Result const result{Error::kNotRunning}; + + EXPECT_FALSE(result.IsOk()); + EXPECT_EQ(result.GetValue(), 0U); + EXPECT_TRUE(result == Error::kNotRunning); + EXPECT_TRUE(result != Error::kOk); + EXPECT_EQ(std::string{reinterpret_cast(result.GetErrorText())}, + "not running"); +} + +} // namespace +} // namespace timer_two diff --git a/test/Timer2Test.cpp b/test/Timer2Test.cpp new file mode 100644 index 0000000..e7107e9 --- /dev/null +++ b/test/Timer2Test.cpp @@ -0,0 +1,34 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// timer2, the one object a sketch uses, and the overflow interrupt it is +// wired to. One test only: timer2 lives as long as the program. + +#include "timer_two/timer2.h" + +#include +#include + +#include "test/printers.h" // IWYU pragma: keep +#include "timer_two/status.h" +#include "timer_two/timer.h" + +namespace timer_two { +namespace { + +int overflow_calls{0}; + +void CountOverflow() { ++overflow_calls; } + +TEST(Timer2Test, TheOverflowInterruptCallsTheCallbackOfTimer2) { + ASSERT_EQ(timer2.GetState(), State::kNotBegun); + ASSERT_EQ(timer2.Begin(1000U, CountOverflow), Error::kOk); + ASSERT_EQ(timer2.Start(), Error::kOk); + + TIMER2_OVF_vect(); + + EXPECT_EQ(overflow_calls, 1); +} + +} // namespace +} // namespace timer_two diff --git a/test/TimerTest.cpp b/test/TimerTest.cpp new file mode 100644 index 0000000..61b93f6 --- /dev/null +++ b/test/TimerTest.cpp @@ -0,0 +1,477 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Timer on the registers of Timer2 in test/mock/avr/io.h, at the Uno's 16 MHz: +// each test makes a timer of its own, on registers set back to those after a +// reset. + +#include "timer_two/timer.h" + +#include +#include +#include + +#include + +#include "Arduino.h" +#include "test/printers.h" // IWYU pragma: keep +#include "timer_two/status.h" +#include "timer_two/timer2.h" + +namespace timer_two { +namespace { + +// The bits of TCCR2B that select the clock, and their values. +constexpr uint8_t kClockSelectMask{0x07}; +constexpr uint8_t kDivide1{1}; +constexpr uint8_t kDivide8{2}; +constexpr uint8_t kDivide32{3}; +constexpr uint8_t kDivide64{4}; +constexpr uint8_t kDivide128{5}; +constexpr uint8_t kDivide256{6}; +constexpr uint8_t kDivide1024{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 TimerTest : public ::testing::Test { + protected: + void SetUp() override { + TCCR2A = 0; + TCCR2B = 0; + OCR2A = 0; + OCR2B = 0; + TIMSK2 = 0; + TIFR2 = 0; + TCNT2.Set(0, true); + mock_pin_mode.fill(INPUT); + overflow_calls = 0; + } + + Timer2& timer() { return timer_; } + + private: + Timer2 timer_; +}; + +TEST_F(TimerTest, BeginSetsPhaseCorrectPwmWithoutAClock) { + TCCR2A = 0xFF; + TCCR2B = 0xFF; + + EXPECT_EQ(timer().Begin(), Error::kOk); + + EXPECT_EQ(timer().GetState(), State::kIdle); + 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(TimerTest, BeginIsRefusedTheSecondTime) { + ASSERT_EQ(timer().Begin(), Error::kOk); + + EXPECT_EQ(timer().Begin(), Error::kBegunAlready); +} + +TEST_F(TimerTest, BeginRefusesAPeriodAboveTheLongestAndStaysNotBegun) { + EXPECT_EQ(timer().Begin(static_cast(Timer2::kPeriodMax + 1U)), + Error::kPeriodOutOfRange); + + EXPECT_EQ(timer().GetState(), State::kNotBegun); +} + +TEST_F(TimerTest, BeginRefusesAPeriodOfZeroAndStaysNotBegun) { + EXPECT_EQ(timer().Begin(0U, CountOverflow), Error::kPeriodOutOfRange); + + EXPECT_EQ(timer().GetState(), State::kNotBegun); + EXPECT_EQ(timer().GetCallback(), nullptr); + EXPECT_EQ(timer().Start(), Error::kNotBegun); +} + +TEST_F(TimerTest, TheLongestPeriodIsAbout33Milliseconds) { + // 256 steps up and down at 16 MHz / 1024. + EXPECT_EQ(Timer2::kPeriodMax, 32767U); +} + +// The period is 2 * OCR2A * prescaler / 16 MHz: up to OCR2A and down again. +TEST_F(TimerTest, APeriodSetsTheTopAndTheSmallestPrescaler) { + ASSERT_EQ(timer().Begin(10U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + EXPECT_EQ(OCR2A, 80); + EXPECT_EQ(ClockSelect(), kDivide1); + + struct Case { + TimeType period; + uint8_t top; + uint8_t clock_select; + }; + std::array const cases{{{100U, 100, kDivide8}, + {1000U, 250, kDivide32}, + {2000U, 250, kDivide64}, + {4000U, 250, kDivide128}, + {8000U, 250, kDivide256}, + {32767U, 255, kDivide1024}}}; + for (auto const& c : cases) { + EXPECT_EQ(timer().SetPeriod(c.period), Error::kOk) << c.period << " us"; + EXPECT_EQ(OCR2A, c.top) << c.period << " us"; + EXPECT_EQ(ClockSelect(), c.clock_select) << c.period << " us"; + } +} + +TEST_F(TimerTest, SetPeriodIsRefusedBeforeBegin) { + EXPECT_EQ(timer().SetPeriod(1000U), Error::kNotBegun); + + EXPECT_EQ(OCR2A, 0); +} + +TEST_F(TimerTest, SetPeriodRefusesAPeriodAboveTheLongest) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + EXPECT_EQ(timer().SetPeriod(static_cast(Timer2::kPeriodMax + 1U)), + Error::kPeriodOutOfRange); + EXPECT_EQ(OCR2A, 250); +} + +TEST_F(TimerTest, SetPeriodRefusesAPeriodOfZero) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_EQ(timer().SetPeriod(0U), Error::kPeriodOutOfRange); + + EXPECT_EQ(OCR2A, 250); + EXPECT_EQ(ClockSelect(), kDivide32); +} + +TEST_F(TimerTest, SetPeriodKeepsTheShareOfTheDuty) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().EnablePwm(255), Error::kOk); + + ASSERT_EQ(timer().SetPeriod(100U), Error::kOk); + + EXPECT_EQ(OCR2A, 100); + EXPECT_EQ(OCR2B, 100); +} + +TEST_F(TimerTest, StartSelectsTheClockFromZero) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + TCNT2.Set(42, false); + + EXPECT_EQ(timer().Start(), Error::kOk); + + EXPECT_EQ(timer().GetState(), State::kRunning); + EXPECT_EQ(ClockSelect(), kDivide32); + EXPECT_EQ(static_cast(TCNT2), 0); +} + +TEST_F(TimerTest, StartWithoutCallbackLeavesTheInterruptOff) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); +} + +TEST_F(TimerTest, StartWithCallbackEnablesTheInterrupt) { + ASSERT_EQ(timer().Begin(1000U, CountOverflow), Error::kOk); + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); + + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_TRUE(BitIsSet(TIMSK2, TOIE2)); +} + +// The core's init() runs Timer2 before setup(), so its overflow flag is set: +// enabled with it, the interrupt would come at once. +TEST_F(TimerTest, StartClearsTheOverflowFlagBeforeItEnablesTheInterrupt) { + ASSERT_EQ(timer().Begin(1000U, CountOverflow), Error::kOk); + + ASSERT_EQ(timer().Start(), Error::kOk); + + // Written with a 1, which clears it. + EXPECT_TRUE(BitIsSet(TIFR2, TOV2)); +} + +TEST_F(TimerTest, AttachInterruptWhileRunningClearsTheOverflowFlag) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + ASSERT_FALSE(BitIsSet(TIFR2, TOV2)); + + ASSERT_EQ(timer().AttachInterrupt(CountOverflow), Error::kOk); + + EXPECT_TRUE(BitIsSet(TIFR2, TOV2)); +} + +TEST_F(TimerTest, StartIsRefusedBeforeBegin) { + EXPECT_EQ(timer().Start(), Error::kNotBegun); + + EXPECT_EQ(ClockSelect(), 0); +} + +TEST_F(TimerTest, StartIsRefusedWhileRunning) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_EQ(timer().Start(), Error::kRunning); +} + +TEST_F(TimerTest, StartAfterStopBeginsFromZero) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + ASSERT_EQ(timer().Stop(), Error::kOk); + TCNT2.Set(42, true); + + EXPECT_EQ(timer().Start(), Error::kOk); + + EXPECT_EQ(static_cast(TCNT2), 0); +} + +TEST_F(TimerTest, TheOverflowCallsTheCallback) { + ASSERT_EQ(timer().Begin(1000U, CountOverflow), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + + timer().OnOverflow(); + timer().OnOverflow(); + + EXPECT_EQ(overflow_calls, 2); +} + +TEST_F(TimerTest, TheOverflowWithoutCallbackCallsNothing) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + timer().OnOverflow(); + + EXPECT_EQ(overflow_calls, 0); +} + +TEST_F(TimerTest, StopDeselectsTheClock) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_EQ(timer().Stop(), Error::kOk); + + EXPECT_EQ(timer().GetState(), State::kStopped); + EXPECT_EQ(ClockSelect(), 0); +} + +TEST_F(TimerTest, StopIsRefusedUnlessRunning) { + EXPECT_EQ(timer().Stop(), Error::kNotRunning); + EXPECT_EQ(timer().GetState(), State::kNotBegun); + + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + EXPECT_EQ(timer().Stop(), Error::kNotRunning); + EXPECT_EQ(timer().GetState(), State::kIdle); +} + +TEST_F(TimerTest, ResumeLetsTheTimerRunAgain) { + ASSERT_EQ(timer().Begin(100U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + ASSERT_EQ(timer().Stop(), Error::kOk); + + EXPECT_EQ(timer().Resume(), Error::kOk); + + EXPECT_EQ(timer().GetState(), State::kRunning); + EXPECT_EQ(ClockSelect(), kDivide8); + EXPECT_TRUE(timer().Read().IsOk()); +} + +TEST_F(TimerTest, ResumeIsRefusedUnlessStopped) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + EXPECT_EQ(timer().Resume(), Error::kNotStopped); + + ASSERT_EQ(timer().Start(), Error::kOk); + EXPECT_EQ(timer().Resume(), Error::kNotStopped); +} + +TEST_F(TimerTest, EnablePwmDrivesPin3WithTheDutyOfTheTop) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + EXPECT_EQ(timer().EnablePwm(128), Error::kOk); + + EXPECT_EQ(mock_pin_mode[3], OUTPUT); + EXPECT_TRUE(BitIsSet(TCCR2A, COM2B1)); + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B0)); + // 128 / 255 of the top, 250, rounded. + EXPECT_EQ(OCR2B, 125); +} + +TEST_F(TimerTest, EnablePwmIsRefusedBeforeBegin) { + EXPECT_EQ(timer().EnablePwm(128), Error::kNotBegun); + + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B1)); + EXPECT_EQ(mock_pin_mode[3], INPUT); +} + +TEST_F(TimerTest, AFullDutyIsTheTopAndNoDutyTheBottom) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + // OCR2B at the top keeps the output high all the time, at the bottom low. + ASSERT_EQ(timer().EnablePwm(255), Error::kOk); + EXPECT_EQ(OCR2B, OCR2A); + ASSERT_EQ(timer().SetPwmDuty(0), Error::kOk); + EXPECT_EQ(OCR2B, 0); +} + +TEST_F(TimerTest, SetPwmDutySetsTheCompareValue) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().EnablePwm(128), Error::kOk); + + EXPECT_EQ(timer().SetPwmDuty(64), Error::kOk); + + // 64 / 255 of the top, 250, rounded. + EXPECT_EQ(OCR2B, 63); +} + +TEST_F(TimerTest, SetPwmDutyIsRefusedBeforeBegin) { + OCR2B = 7; + + EXPECT_EQ(timer().SetPwmDuty(64), Error::kNotBegun); + + EXPECT_EQ(OCR2B, 7); +} + +TEST_F(TimerTest, DisablePwmDisconnectsPin3) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().EnablePwm(128), Error::kOk); + + timer().DisablePwm(); + + EXPECT_FALSE(BitIsSet(TCCR2A, COM2B1)); +} + +TEST_F(TimerTest, AttachInterruptRefusesNullptr) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + EXPECT_EQ(timer().AttachInterrupt(nullptr), Error::kNoCallback); + + EXPECT_EQ(timer().GetCallback(), nullptr); +} + +TEST_F(TimerTest, AttachInterruptWhileRunningEnablesTheInterrupt) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_EQ(timer().AttachInterrupt(CountOverflow), Error::kOk); + + EXPECT_TRUE(BitIsSet(TIMSK2, TOIE2)); + timer().OnOverflow(); + EXPECT_EQ(overflow_calls, 1); +} + +TEST_F(TimerTest, AttachInterruptBeforeStartLeavesTheInterruptOff) { + ASSERT_EQ(timer().Begin(1000U), Error::kOk); + + EXPECT_EQ(timer().AttachInterrupt(CountOverflow), Error::kOk); + + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); + EXPECT_EQ(timer().GetCallback(), &CountOverflow); +} + +TEST_F(TimerTest, DetachInterruptDisablesTheInterruptAndForgetsTheCallback) { + ASSERT_EQ(timer().Begin(1000U, CountOverflow), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + + timer().DetachInterrupt(); + + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); + EXPECT_EQ(timer().GetCallback(), nullptr); +} + +TEST_F(TimerTest, StartAfterDetachInterruptLeavesTheInterruptOff) { + ASSERT_EQ(timer().Begin(1000U, CountOverflow), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + timer().DetachInterrupt(); + ASSERT_EQ(timer().Stop(), Error::kOk); + + ASSERT_EQ(timer().Start(), Error::kOk); + + EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); +} + +TEST_F(TimerTest, ReadIsRefusedUnlessRunning) { + ASSERT_EQ(timer().Begin(100U), Error::kOk); + + Result const result{timer().Read()}; + + EXPECT_EQ(result.GetError(), Error::kNotRunning); + EXPECT_EQ(result.GetValue(), 0U); +} + +// At 100 us the prescaler is 8: a step of the counter is 0.5 us. +TEST_F(TimerTest, ReadCountsTheStepsUpwards) { + ASSERT_EQ(timer().Begin(100U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + TCNT2.Set(50, true); + + Result const result{timer().Read()}; + + ASSERT_TRUE(result.IsOk()); + EXPECT_EQ(result.GetValue(), 25U); +} + +TEST_F(TimerTest, ReadCountsTheStepsBackDownFromTheTop) { + ASSERT_EQ(timer().Begin(100U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + // 100 steps up and 92 down. + TCNT2.Set(8, false); + + Result const result{timer().Read()}; + + ASSERT_TRUE(result.IsOk()); + EXPECT_EQ(result.GetValue(), 96U); +} + +TEST_F(TimerTest, ReadWaitsForTheCounterToStep) { + ASSERT_EQ(timer().Begin(100U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + TCNT2.Set(50, false); + // The prescaler of 8 lets the CPU read each value several times. + TCNT2.SetReadsPerStep(4); + + Result const result{timer().Read()}; + + ASSERT_TRUE(result.IsOk()); + // 100 steps up and 50 down, of 0.5 us. + EXPECT_EQ(result.GetValue(), 75U); +} + +// 16 steps of the counter are as many microseconds as the prescaler divides +// by: 16 MHz / 16. +TEST_F(TimerTest, ReadScalesByEachPrescaler) { + ASSERT_EQ(timer().Begin(10U), Error::kOk); + ASSERT_EQ(timer().Start(), Error::kOk); + struct Case { + TimeType period; + 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(timer().SetPeriod(c.period), Error::kOk); + TCNT2.Set(16, true); + + Result const result{timer().Read()}; + + ASSERT_TRUE(result.IsOk()) << "period " << c.period; + EXPECT_EQ(result.GetValue(), c.sixteen_steps) << "period " << c.period; + } +} + +} // namespace +} // namespace timer_two diff --git a/test/TimerTwoTest.cpp b/test/TimerTwoTest.cpp deleted file mode 100644 index 20c8cce..0000000 --- a/test/TimerTwoTest.cpp +++ /dev/null @@ -1,439 +0,0 @@ -// 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); - - // 64 / 255 of the top, 250, rounded. - EXPECT_EQ(OCR2B, 63); -} - -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; - } -} - -// The bugs of OIL 2, each shown here before it was fixed. - -TEST_F(TimerTwoTest, ResumeLetsTheTimerRunAgain) { - ASSERT_EQ(Timer2.init(100U), E_OK); - ASSERT_EQ(Timer2.start(), E_OK); - Timer2.stop(); - - ASSERT_EQ(Timer2.resume(), E_OK); - - EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_RUNNING); - TimerTwo::TimeType microseconds{0}; - EXPECT_EQ(Timer2.read(microseconds), E_OK); - EXPECT_EQ(Timer2.start(), E_NOT_OK); -} - -TEST_F(TimerTwoTest, StopBeforeInitChangesNothing) { - Timer2.stop(); - - EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_INIT); - EXPECT_EQ(Timer2.start(), E_NOT_OK); - EXPECT_EQ(ClockSelect(), 0); -} - -TEST_F(TimerTwoTest, StartAfterDetachInterruptLeavesTheInterruptOff) { - ASSERT_EQ(Timer2.init(1000U, CountOverflow), E_OK); - ASSERT_EQ(Timer2.start(), E_OK); - Timer2.detachInterrupt(); - Timer2.stop(); - - ASSERT_EQ(Timer2.start(), E_OK); - - EXPECT_FALSE(BitIsSet(TIMSK2, TOIE2)); - EXPECT_EQ(Timer2.getTimerIsrCallbackFunction(), nullptr); -} - -TEST_F(TimerTwoTest, AFullDutyIsTheTop) { - ASSERT_EQ(Timer2.init(1000U), E_OK); - - ASSERT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 255), E_OK); - - // OCR2B at the top keeps the output high all the time. - EXPECT_EQ(OCR2B, OCR2A); -} - -TEST_F(TimerTwoTest, ANoDutyIsZero) { - ASSERT_EQ(Timer2.init(1000U), E_OK); - - ASSERT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 0), E_OK); - - // OCR2B at the bottom keeps the output low all the time. - EXPECT_EQ(OCR2B, 0); -} - -TEST_F(TimerTwoTest, SetPeriodKeepsTheDuty) { - ASSERT_EQ(Timer2.init(1000U), E_OK); - ASSERT_EQ(Timer2.enablePwm(TimerTwo::PWM_PIN_3, 255), E_OK); - - ASSERT_EQ(Timer2.setPeriod(100U), E_OK); - - EXPECT_EQ(OCR2A, 100); - EXPECT_EQ(OCR2B, 100); -} - -// At 100 us the prescaler is 8: 50 steps of 0.5 us. -TEST_F(TimerTwoTest, ReadKeepsTheStepsBelowSixteen) { - ASSERT_EQ(Timer2.init(100U), E_OK); - ASSERT_EQ(Timer2.start(), E_OK); - TCNT2.Set(50, true); - TimerTwo::TimeType microseconds{0}; - - EXPECT_EQ(Timer2.read(microseconds), E_OK); - - EXPECT_EQ(microseconds, 25U); -} - -TEST_F(TimerTwoTest, InitRefusesAPeriodOfZeroAndStaysUninitialized) { - OCR2A = 0; - - EXPECT_EQ(Timer2.init(0U, CountOverflow), E_NOT_OK); - - EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_INIT); - EXPECT_EQ(Timer2.start(), E_NOT_OK); -} - -TEST_F(TimerTwoTest, InitRefusesAPeriodAboveTheLongestAndStaysUninitialized) { - EXPECT_EQ( - Timer2.init(static_cast(Timer2.getPeriodMax() + 1U)), - E_NOT_OK); - - EXPECT_EQ(Timer2.getState(), TimerTwo::STATE_INIT); -} - -TEST_F(TimerTwoTest, SetPeriodRefusesAPeriodOfZero) { - ASSERT_EQ(Timer2.init(1000U), E_OK); - ASSERT_EQ(Timer2.start(), E_OK); - - EXPECT_EQ(Timer2.setPeriod(0U), E_NOT_OK); - - EXPECT_EQ(OCR2A, 250); - EXPECT_EQ(ClockSelect(), kPrescale32); -} - -} // namespace diff --git a/test/attributes_test.cpp b/test/attributes_test.cpp new file mode 100644 index 0000000..8a0026a --- /dev/null +++ b/test/attributes_test.cpp @@ -0,0 +1,37 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "timer_two/attributes.h" + +#include + +namespace timer_two { +namespace { + +// A result that must not be dropped, and an effect that shows the call. +class Sender { + public: + TIMER_TWO_NODISCARD bool Send() { + sent_ = true; + return true; + } + + TIMER_TWO_NODISCARD bool sent() const { return sent_; } + + private: + bool sent_{false}; +}; + +// That Discard() silences the warning is checked by the build itself, with +// warnings as errors under `make check`: before C++17 GCC warns through a +// cast to void. +TEST(DiscardTest, LeavesTheCallItsEffect) { + Sender sender; + + Discard(sender.Send()); + + EXPECT_TRUE(sender.sent()); +} + +} // namespace +} // namespace timer_two diff --git a/test/mock/Arduino.h b/test/mock/Arduino.h index 2f9445d..8de41d3 100644 --- a/test/mock/Arduino.h +++ b/test/mock/Arduino.h @@ -2,10 +2,10 @@ // 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. +// 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_ @@ -16,11 +16,8 @@ // 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); diff --git a/test/mock/avr/io.cpp b/test/mock/avr/io.cpp index 45b2e0b..47464b3 100644 --- a/test/mock/avr/io.cpp +++ b/test/mock/avr/io.cpp @@ -10,6 +10,7 @@ uint8_t volatile TCCR2B{0}; uint8_t volatile OCR2A{0}; uint8_t volatile OCR2B{0}; uint8_t volatile TIMSK2{0}; +uint8_t volatile TIFR2{0}; MockCounter TCNT2; namespace { @@ -21,7 +22,9 @@ constexpr uint8_t kClockSelectMask{0x07}; MockCounter::operator uint8_t() { uint8_t const now{value_}; - if ((TCCR2B & kClockSelectMask) != 0) { + ++reads_; + if (((TCCR2B & kClockSelectMask) != 0) && (reads_ >= reads_per_step_)) { + reads_ = 0; uint8_t const top{OCR2A}; if (counting_up_ && value_ >= top) { counting_up_ = false; @@ -44,4 +47,11 @@ MockCounter& MockCounter::operator=(uint8_t value) { void MockCounter::Set(uint8_t value, bool counting_up) { value_ = value; counting_up_ = counting_up; + reads_per_step_ = 1; + reads_ = 0; +} + +void MockCounter::SetReadsPerStep(uint8_t reads) { + reads_per_step_ = reads; + reads_ = 0; } diff --git a/test/mock/avr/io.h b/test/mock/avr/io.h index ba3e6e4..6c0b9bf 100644 --- a/test/mock/avr/io.h +++ b/test/mock/avr/io.h @@ -27,6 +27,7 @@ constexpr int CS21{1}; constexpr int CS22{2}; constexpr int WGM22{3}; constexpr int TOIE2{0}; +constexpr int TOV2{0}; // NOLINTEND(readability-identifier-naming) // TCNT2, which counts on each read while TCCR2B selects a clock. @@ -37,12 +38,18 @@ class MockCounter { // 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. + // Sets the counter and its direction, for a test; it steps on each read. void Set(uint8_t value, bool counting_up); + // Lets the counter step only on every reads-th read, as a prescaler makes + // the CPU read the same value several times. + void SetReadsPerStep(uint8_t reads); + private: uint8_t value_{0}; bool counting_up_{true}; + uint8_t reads_per_step_{1}; + uint8_t reads_{0}; }; // avr-libc's names of the registers, globals as they are on the board. @@ -52,6 +59,9 @@ extern uint8_t volatile TCCR2B; extern uint8_t volatile OCR2A; extern uint8_t volatile OCR2B; extern uint8_t volatile TIMSK2; +// What was last written to TIFR2: on the board a 1 clears its flag, so a test +// sees which flags were cleared. +extern uint8_t volatile TIFR2; extern MockCounter TCNT2; // NOLINTEND(readability-identifier-naming) diff --git a/test/mock/avr/pgmspace.h b/test/mock/avr/pgmspace.h new file mode 100644 index 0000000..f2c11bf --- /dev/null +++ b/test/mock/avr/pgmspace.h @@ -0,0 +1,55 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// avr-libc's access to flash, for the tests on the host, which has no +// separate flash: PROGMEM is nothing, and a read from flash is a read. + +#ifndef TIMERTWO_TEST_MOCK_AVR_PGMSPACE_H_ +#define TIMERTWO_TEST_MOCK_AVR_PGMSPACE_H_ + +#include +#include +#include + +#define PROGMEM +#define PGM_P const char* + +// avr-libc's names, which the library calls. +// NOLINTNEXTLINE(readability-identifier-naming) +inline uint8_t pgm_read_byte(void const* address) { + return *static_cast(address); +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline uint16_t pgm_read_word(void const* address) { + uint16_t value{0}; + memcpy(&value, address, sizeof(value)); + return value; +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline uint32_t pgm_read_dword(void const* address) { + uint32_t value{0}; + memcpy(&value, address, sizeof(value)); + return value; +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline void* memcpy_P(void* ram, void const* flash, size_t count) { + return memcpy(ram, flash, count); +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline void const* pgm_read_ptr(void const* address) { + return *static_cast(address); +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline int memcmp_P(void const* ram, void const* flash, size_t count) { + return memcmp(ram, flash, count); +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline size_t strlen_P(char const* flash) { return strlen(flash); } + +#endif // TIMERTWO_TEST_MOCK_AVR_PGMSPACE_H_ diff --git a/test/printers.h b/test/printers.h new file mode 100644 index 0000000..104b890 --- /dev/null +++ b/test/printers.h @@ -0,0 +1,55 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later +// +// How GoogleTest prints an Error, a Status and a State that an expectation +// did not meet: by name, rather than as the bytes of an object. + +#ifndef TIMERTWO_TEST_PRINTERS_H_ +#define TIMERTWO_TEST_PRINTERS_H_ + +#include + +#include + +#include "timer_two/status.h" +#include "timer_two/timer.h" + +namespace timer_two { + +// The text of an error, as the library has it in flash, which the host reads +// as RAM. +inline char const* TextOf(Error error) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return reinterpret_cast(Status{error}.GetErrorText()); +} + +// GoogleTest finds these by their name, in the namespace of the type. +// NOLINTNEXTLINE(readability-identifier-naming) +inline void PrintTo(Error error, std::ostream* out) { *out << TextOf(error); } + +// NOLINTNEXTLINE(readability-identifier-naming) +inline void PrintTo(Status const& status, std::ostream* out) { + *out << TextOf(status.GetError()); +} + +// NOLINTNEXTLINE(readability-identifier-naming) +inline void PrintTo(State state, std::ostream* out) { + switch (state) { + case State::kNotBegun: + *out << "not begun"; + break; + case State::kIdle: + *out << "idle"; + break; + case State::kRunning: + *out << "running"; + break; + case State::kStopped: + *out << "stopped"; + break; + } +} + +} // namespace timer_two + +#endif // TIMERTWO_TEST_PRINTERS_H_