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
20 changes: 10 additions & 10 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Registers>` 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.
Expand Down
8 changes: 4 additions & 4 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)/")

Expand Down
23 changes: 18 additions & 5 deletions OIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | |

Expand Down Expand Up @@ -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<Registers>`, 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 `<!-- sizes -->` markers, the tag,
Expand Down
133 changes: 77 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -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 <TimerTwo.h>

### 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

Expand Down
16 changes: 1 addition & 15 deletions examples/.clang-tidy
Original file line number Diff line number Diff line change
Expand Up @@ -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
28 changes: 17 additions & 11 deletions examples/Basics/Basics.ino
Original file line number Diff line number Diff line change
@@ -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 <TimerTwo.h>
#include <stdint.h>

/*
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() {}
70 changes: 35 additions & 35 deletions examples/Read/Read.ino
Original file line number Diff line number Diff line change
@@ -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 <TimerTwo.h>
#include <stdint.h>

/*
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<timer_two::TimeType> 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() {}
Loading
Loading