Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
26 changes: 19 additions & 7 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
42 changes: 36 additions & 6 deletions OIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:

Expand All @@ -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

Expand All @@ -68,3 +74,27 @@ a clean break.

The README of 2.0.0 with the table of flash and RAM between `<!-- sizes -->` 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.
97 changes: 65 additions & 32 deletions src/TimerTwo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ TimerTwo::TimerTwo() {
State = STATE_INIT;
TimerIsrOverflowCallback = nullptr;
ClockSelectBitGroup = REG_CS_NO_CLOCK;
PwmDutyCycle = 0u;
}

TimerTwo::~TimerTwo() {}
Expand All @@ -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;
Expand All @@ -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);
}
Expand All @@ -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<byte>(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;
}
Expand Down Expand Up @@ -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<uint8_t>(DutyCycleTrans);
PwmDutyCycle = DutyCycle;
OCR2B = getPwmCompareValue();
}
}
return ReturnValue;
Expand Down Expand Up @@ -133,17 +141,21 @@ 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() {
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;
Expand All @@ -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);
Expand All @@ -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) {
Expand All @@ -180,12 +197,13 @@ StdReturnType TimerTwo::read(TimeType& Microseconds) {
// At most 2 * 255.
counterValue = static_cast<uint16_t>((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<TimeType>(((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<uint32_t>(counterValue)
<< getPrescaleShiftScale()};
Microseconds = static_cast<TimeType>((Clocks * 1000uL) / (F_CPU / 1000uL));
return E_OK;
}
return E_NOT_OK;
Expand Down Expand Up @@ -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<uint32_t>(((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<byte>(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<uint16_t>(static_cast<uint16_t>(OCR2A) * PwmDutyCycle)};
return static_cast<byte>((Product + 127u) / 255u);
}

ISR(TIMER2_OVF_vect) { Timer2.callTimerIsrOverflowCallback(); }
Loading
Loading