diff --git a/AGENTS.md b/AGENTS.md index 2da9bc4..550ff12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -115,4 +115,7 @@ and why. A pull request that works on an item sets its status and links itself i - **The mock of the registers**, `test/mock/avr/io.h`: TCNT2 steps on each read while a clock is selected, up to OCR2A and down again, so that `start()` and `read()`, which wait for the counter to move, end on the host. -- **Known bugs, for OIL 2**, each to be shown by a failing test before it is fixed; see OIL.md. +- **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. +- **No self check in simavr yet** (OIL 5): simavr 1.6 does not count Timer2 in mode 5. diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f0f339..5b88a2f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,21 +28,28 @@ file(GLOB_RECURSE test_sources CONFIGURE_DEPENDS test/*Test.cpp test/*_test.cpp) list(FILTER test_sources EXCLUDE REGEX "/test/(mock|compile_fail)/") # One library and one test program per variant: a switch that changes what is compiled makes -# a build of its own. A variant is added with its defines, as add_variant(checked -# TIMERTWO_CHECK_ACCESS=1), and in tools/project.sh for the examples. +# a build of its own. A variant is added with its defines, as add_variant(checked DEFINES +# TIMERTWO_CHECK_ACCESS=1), and in tools/project.sh for the examples. CLOCK is F_CPU, the +# Uno's 16 MHz unless given; TESTS the tests it runs, all of test/ unless given. function(add_variant name) - set(defines ${ARGN}) + cmake_parse_arguments(PARSE_ARGV 1 arg "" "CLOCK" "DEFINES;TESTS") + if(NOT arg_CLOCK) + set(arg_CLOCK 16000000uL) + endif() + if(NOT arg_TESTS) + set(arg_TESTS ${test_sources}) + endif() add_library(timer_two_${name} STATIC ${library_sources} test/mock/Arduino.cpp test/mock/avr/io.cpp) target_include_directories(timer_two_${name} PUBLIC src test/mock) - # The Uno's clock, which the board's build defines. - target_compile_definitions(timer_two_${name} PUBLIC F_CPU=16000000uL ${defines}) + # The CPU's clock, which the board's build defines. + target_compile_definitions(timer_two_${name} PUBLIC F_CPU=${arg_CLOCK} ${arg_DEFINES}) target_compile_options(timer_two_${name} PRIVATE -std=gnu++11 ${CHECK_WARNINGS} ${CHECK_INSTRUMENT}) target_link_options(timer_two_${name} PUBLIC ${CHECK_INSTRUMENT}) - add_executable(timer_two_test_${name} ${test_sources}) + add_executable(timer_two_test_${name} ${arg_TESTS}) target_compile_features(timer_two_test_${name} PRIVATE cxx_std_17) # The root, so that a test includes its helpers as "test/...", as Google wants an include # to name the directory. @@ -51,10 +58,15 @@ function(add_variant name) ${CHECK_INSTRUMENT}) target_link_libraries(timer_two_test_${name} PRIVATE timer_two_${name} GTest::gtest_main) - gtest_discover_tests(timer_two_test_${name} TEST_PREFIX ${name}/) + # A test that waits for a counter that stands would hang the run: it fails after 10 s. + gtest_discover_tests(timer_two_test_${name} TEST_PREFIX ${name}/ PROPERTIES TIMEOUT 10) endfunction() add_variant(default) +# The clocks where TimerTwo computed with a quotient of F_CPU that was cut or 0 (OIL 2): the +# tests that hold at any clock, as TimeType is 32 bits below 8 MHz. +add_variant(1mhz CLOCK 1000000uL TESTS test/ClockTest.cpp) +add_variant(20mhz CLOCK 20000000uL TESTS test/ClockTest.cpp) add_compile_fail_tests(DIRECTORY ${CMAKE_SOURCE_DIR}/test/compile_fail STANDARD gnu++11 INCLUDES ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/test/mock) diff --git a/OIL.md b/OIL.md index f4e5ae7..0b9d029 100644 --- a/OIL.md +++ b/OIL.md @@ -11,9 +11,10 @@ Status: `open`, `in progress`, `done`, `dropped` (with the reason in the item). | # | Item | Depends on | Status | PR | |---|------|------------|--------|----| | 1 | On the template embedded-cpp-template | – | in progress | #4 | -| 2 | The known bugs, each shown by a test first, and SelfCheck in simavr | 1 | open | | +| 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 | | | 4 | Release 2.0.0 and the Library Manager | 3 | open | | +| 5 | SelfCheck in simavr | 1 | open | | ### 1 On the template embedded-cpp-template @@ -32,7 +33,7 @@ today; what does not is 2. *Done when* `make check` passes, and flash and RAM of the examples on the Uno are those of before, or differ by what a commit names. -### 2 The known bugs, each shown by a test first, and SelfCheck in simavr +### 2 The known bugs, each shown by a test first Found while bringing TimerTwo in. Each gets a test that fails on the code of 1, then the fix: @@ -48,11 +49,16 @@ Found while bringing TimerTwo in. Each gets a test that fails on the code of 1, - `F_CPU / 2000000uL` is 0 below 2 MHz, so every period gives a top of 0; and `F_CPU / 1000000uL` truncates at 20 MHz, where `getPeriodMax()` is 24575 for 26214. - A period of 0 sets a top of 0: the counter stands, and `start()` with a callback waits for it - forever. + forever. `init()` with a period it refuses still leaves the timer initialized. + +Found while fixing them, and fixed with them; neither can a test on the host show: + +- `attachInterrupt()` writes the pointer to the callback while the interrupt may call it, and + the AVR writes it a byte at a time. +- The duty is computed in `int`, which has 16 bits on the AVR: 255 * 255 overflows it. + +The tests of the clocks run at 1, 16 and 20 MHz, each a build of its own. -Then `examples/SelfCheck`, which tools/self_check.sh runs in simavr: the period counted in -callbacks and the PWM measured on pin 3, if simavr models mode 5 of Timer2 well enough; -`SIMAVR_MCU` in `tools/project.sh` is empty until then. ### 3 Version 2.0.0: a namespace, constants for macros, the template's checks @@ -68,3 +74,27 @@ a clean break. The README of 2.0.0 with the table of flash and RAM between `` markers, the tag, `release.yml`, and the request to the Arduino Library Manager. + +### 5 SelfCheck in simavr + +`examples/SelfCheck`, which tools/self_check.sh runs in simavr: the period counted in callbacks +and the PWM measured on pin 3. Not possible with simavr as it is, measured on 2026-11-10 with the +registers alone, without TimerTwo, in simavr 1.6 of the dev container and in 1.8, the latest +release, built from source: + +- Timer2 counts in the modes normal, CTC and fast PWM, but TCNT2 stays at 0 in both phase + correct modes, 1 and 5, though 1.8 lists them in its table of Timer2. +- In mode 5, OC2B never drives pin 3: low in 61 397 samples over 100 ms at a duty of 64. +- With the overflow interrupt on in mode 5, the sketch no longer gets through a loop of 100 ms; + the interrupt seems to fire without end. + +So `start()` waits forever in simavr, and there is nothing to measure. The cause in both +releases: modes 1 and 5 are missing from the table of Timer2's modes, so TOV2 fires without end. + +simavr's master after 1.8 fills the table (63aa5b192, 2026-08-09), and the counter moves; but it +counts one way only, so TOV2 comes twice as often as on the chip, and the duty on OC2B did not +come out the same in two programs. Reported with a program that shows it in +[simavr #442](https://github.com/buserror/simavr/issues/442#issuecomment-6779055513). + +`SIMAVR_MCU` in `tools/project.sh` stays empty, and this item waits for a simavr release that +models phase correct PWM as the chip does; the template's image would then need it too. diff --git a/src/TimerTwo.cpp b/src/TimerTwo.cpp index ab64883..6efb295 100644 --- a/src/TimerTwo.cpp +++ b/src/TimerTwo.cpp @@ -9,6 +9,7 @@ TimerTwo::TimerTwo() { State = STATE_INIT; TimerIsrOverflowCallback = nullptr; ClockSelectBitGroup = REG_CS_NO_CLOCK; + PwmDutyCycle = 0u; } TimerTwo::~TimerTwo() {} @@ -21,8 +22,12 @@ TimerTwo& TimerTwo::getInstance() { StdReturnType TimerTwo::init(TimeType Microseconds, TimerIsrCallbackF_void sTimerOverflowCallback) { StdReturnType ReturnValue = E_NOT_OK; + ClockSelectType ClockSelect{REG_CS_NO_CLOCK}; - if (STATE_INIT == State) { + // 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; @@ -33,9 +38,7 @@ StdReturnType TimerTwo::init(TimeType Microseconds, writeBit(TCCR2A, WGM21, 0u); writeBit(TCCR2B, WGM22, 1u); - if (setPeriod(Microseconds) == E_NOT_OK) { - ReturnValue = E_NOT_OK; - } + (void)setPeriod(Microseconds); if (sTimerOverflowCallback != nullptr) { attachInterrupt(sTimerOverflowCallback); } @@ -47,16 +50,25 @@ StdReturnType TimerTwo::init(TimeType Microseconds, StdReturnType TimerTwo::setPeriod(TimeType Microseconds) { StdReturnType ReturnValue{E_NOT_OK}; - if (Microseconds <= getPeriodMax()) { + 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 = getTimerCycles(Microseconds); + 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); } - return E_OK; + ReturnValue = E_OK; } return ReturnValue; } @@ -97,15 +109,11 @@ StdReturnType TimerTwo::setPwmDuty(PwmPinType PwmPin, byte DutyCycle) { if ((STATE_IDLE == State) || (STATE_RUNNING == State) || (STATE_STOPPED == State)) { - // use rule of three to calculate duty cycle related to timer top value - // OCR2A is top value of timer - uint32_t DutyCycleTrans = OCR2A * DutyCycle; - DutyCycleTrans >>= TIMERTWO_NUMBER_OF_BITS; /* set output compare register value for given Pwm pin */ if (PWM_PIN_3 == PwmPin) { ReturnValue = E_OK; - // At most 255 * 255 / 256. - OCR2B = static_cast(DutyCycleTrans); + PwmDutyCycle = DutyCycle; + OCR2B = getPwmCompareValue(); } } return ReturnValue; @@ -133,10 +141,13 @@ StdReturnType TimerTwo::start() { } void TimerTwo::stop() { - /* stop counter by clearing clock select register */ - writeBitGroup(TCCR2B, TIMERTWO_REG_CS_GM, TIMERTWO_REG_CS_GP, - REG_CS_NO_CLOCK); - State = STATE_STOPPED; + // 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() { @@ -144,6 +155,7 @@ StdReturnType TimerTwo::resume() { /* 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; @@ -152,6 +164,9 @@ StdReturnType TimerTwo::resume() { 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); @@ -163,6 +178,8 @@ StdReturnType TimerTwo::attachInterrupt( 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) { @@ -180,12 +197,13 @@ StdReturnType TimerTwo::read(TimeType& Microseconds) { // At most 2 * 255. counterValue = static_cast((OCR2A - counterValue) + OCR2A); } - /* transform counter value to microseconds in an efficient way */ - // At most 2 * 255 steps of 1024 clocks: 32640 us at 16 MHz, 65280 at 8, - // and TimeType has 32 bits below. - Microseconds = - static_cast(((counterValue * 1000uL) / (F_CPU / 1000uL)) - << getPrescaleShiftScale()); + // 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; @@ -219,28 +237,43 @@ inline byte TimerTwo::getPrescaleShiftScale() { } } -inline byte TimerTwo::getTimerCycles(TimeType Microseconds) { +// 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 */ - uint32_t TimerCycles = (F_CPU / 2000000uL) * Microseconds; + // 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) - ClockSelectBitGroup = REG_CS_NO_PRESCALER; + ClockSelect = REG_CS_NO_PRESCALER; else if ((TimerCycles >>= 3u) < TIMERTWO_RESOLUTION) - ClockSelectBitGroup = REG_CS_PRESCALE_8; + ClockSelect = REG_CS_PRESCALE_8; else if ((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) - ClockSelectBitGroup = REG_CS_PRESCALE_32; + ClockSelect = REG_CS_PRESCALE_32; else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) - ClockSelectBitGroup = REG_CS_PRESCALE_64; + ClockSelect = REG_CS_PRESCALE_64; else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) - ClockSelectBitGroup = REG_CS_PRESCALE_128; + ClockSelect = REG_CS_PRESCALE_128; else if ((TimerCycles >>= 1u) < TIMERTWO_RESOLUTION) - ClockSelectBitGroup = REG_CS_PRESCALE_256; + ClockSelect = REG_CS_PRESCALE_256; else if ((TimerCycles >>= 2u) < TIMERTWO_RESOLUTION) - ClockSelectBitGroup = REG_CS_PRESCALE_1024; + 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 6a67193..26086f4 100644 --- a/src/TimerTwo.h +++ b/src/TimerTwo.h @@ -102,9 +102,12 @@ class TimerTwo { 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); + byte getTimerCycles(TimeType, ClockSelectType&); + byte getPwmCompareValue(); public: /*! \brief The one TimerTwo, which Timer2 refers to. */ @@ -116,11 +119,14 @@ class TimerTwo { TimerIsrCallbackF_void getTimerIsrCallbackFunction() const { return TimerIsrOverflowCallback; } - /*! \brief The longest period setPeriod() takes, in microseconds. */ + /*! + * \brief The longest period setPeriod() takes, in microseconds: the last one + * whose half fits 256 steps of the largest prescaler. + */ TimeType getPeriodMax() { - return TimeType{((TIMERTWO_RESOLUTION / (F_CPU / 1000000uL)) * - TIMERTWO_MAX_PRESCALER * 2u) - - 1u}; + return static_cast( + (TIMERTWO_RESOLUTION * TIMERTWO_MAX_PRESCALER * 2uL * 1000uL - 1uL) / + (F_CPU / 1000uL)); } /*! @@ -129,24 +135,24 @@ class TimerTwo { * \param Microseconds the period, up to getPeriodMax() * \param sTimerOverflowCallback what the overflow interrupt calls, or nullptr * for none - * \return E_NOT_OK if the timer was initialized already, or the period is too - * long; the timer is initialized with a callback in the latter case. + * \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 is not set again: call - * setPwmDuty() after it. + * 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. + * \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 to 255 of 256 + * \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); @@ -160,7 +166,7 @@ class TimerTwo { /*! * \brief Sets the duty of the PWM on a pin that enablePwm() started. * \param PwmPin the pin - * \param DutyCycle the duty, 0 to 255 of 256 + * \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); @@ -169,10 +175,11 @@ class TimerTwo { * \return E_NOT_OK if the timer is not initialized, or runs already. */ StdReturnType start(); - /*! \brief Stops the counter where it is. */ + /*! \brief Stops the counter where it is, if it runs. */ void stop(); /*! - * \brief Lets the counter go on from where stop() stopped it. + * \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(); @@ -183,7 +190,10 @@ class TimerTwo { * \return E_NOT_OK for nullptr. */ StdReturnType attachInterrupt(TimerIsrCallbackF_void TimerOverflowCallback); - /*! \brief Disables the overflow interrupt. */ + /*! + * \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. diff --git a/test/ClockTest.cpp b/test/ClockTest.cpp new file mode 100644 index 0000000..85bcf74 --- /dev/null +++ b/test/ClockTest.cpp @@ -0,0 +1,100 @@ +// 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. + +#include +#include +#include + +#include + +#include "StandardTypes.h" +#include "TimerTwo.h" + +namespace { + +constexpr uint64_t kClock{F_CPU}; +constexpr uint64_t kMicrosecondsPerSecond{1000000}; + +// Mode 5 counts up to the top and down again, 2 * 256 steps at the most, of +// the largest prescaler. +constexpr uint64_t kLongestPeriodInClocks{uint64_t{2} * 256 * 1024}; + +// The prescaler TCCR2B selects, 0 while the timer does not run. +uint64_t Prescaler() { + constexpr std::array kPrescalers{0, 1, 8, 32, + 64, 128, 256, 1024}; + return kPrescalers.at(TCCR2B & 0x07U); +} + +// The period OCR2A and TCCR2B make, in clocks. +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."; + } +}; + +TEST_F(ClockTest, TheLongestPeriodIsTheLastThatFits) { + uint64_t const longest{ + ((kLongestPeriodInClocks * kMicrosecondsPerSecond) - 1) / kClock}; + + EXPECT_EQ(Timer2.getPeriodMax(), longest); +} + +TEST_F(ClockTest, TheLongestPeriodIsTakenAndOneMoreRefused) { + ASSERT_EQ(Timer2.init(Timer2.getPeriodMax()), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + EXPECT_EQ(Prescaler(), 1024U); + + EXPECT_EQ(Timer2.setPeriod( + static_cast(Timer2.getPeriodMax() + 1U)), + E_NOT_OK); +} + +// 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); + // The prescaler is in TCCR2B while the timer runs. + ASSERT_EQ(Timer2.start(), E_OK); + 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) + << period << " us"; + uint64_t const wanted{period * kClock / kMicrosecondsPerSecond}; + + EXPECT_LE(PeriodInClocks(), wanted) << period << " us"; + EXPECT_LT(wanted - PeriodInClocks(), (2 * Prescaler()) + 2) + << period << " us"; + } +} + +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); +} + +TEST_F(ClockTest, ReadIsTheTimeOfTheStepsCounted) { + ASSERT_EQ(Timer2.init(1000U), E_OK); + ASSERT_EQ(Timer2.start(), E_OK); + TCNT2.Set(50, true); + TimerTwo::TimeType microseconds{0}; + + ASSERT_EQ(Timer2.read(microseconds), E_OK); + + EXPECT_EQ(microseconds, 50 * Prescaler() * kMicrosecondsPerSecond / kClock); +} + +} // namespace diff --git a/test/TimerTwoTest.cpp b/test/TimerTwoTest.cpp index 5579401..20c8cce 100644 --- a/test/TimerTwoTest.cpp +++ b/test/TimerTwoTest.cpp @@ -225,7 +225,8 @@ TEST_F(TimerTwoTest, SetPwmDutySetsTheCompareValue) { EXPECT_EQ(Timer2.setPwmDuty(TimerTwo::PWM_PIN_3, 64), E_OK); - EXPECT_EQ(OCR2B, 62); + // 64 / 255 of the top, 250, rounded. + EXPECT_EQ(OCR2B, 63); } TEST_F(TimerTwoTest, SetPwmDutyIsRefusedBeforeInit) { @@ -333,4 +334,106 @@ TEST_F(TimerTwoTest, ReadScalesByEachPrescaler) { } } +// 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