Releases v1.0.0 to support RP2040-based boards

### Initial Releases v1.0.0

1. Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc. using [Earle Philhower's arduino-pico core](https://github.com/earlephilhower/arduino-pico)
This commit is contained in:
Khoi Hoang
2021-05-11 20:58:08 -04:00
committed by GitHub
commit 5e6d0251b3
28 changed files with 5027 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
+53
View File
@@ -0,0 +1,53 @@
## Contributing to RPI_PICO_TimerInterrupt
### Reporting Bugs
Please report bugs in [RPI_PICO_TimerInterrupt Issues](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/issues) if you find them.
However, before reporting a bug please check through the following:
* [Existing Open Issues](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/issues) - someone might have already encountered this.
If you don't find anything, please [open a new issue](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/issues/new).
### How to submit a bug report
Please ensure to specify the following:
* Arduino IDE version (e.g. 1.8.13) or Platform.io version
* `RP2040` Core Version (e.g. RP2040 core v1.2.1)
* `RP2040` Board type (e.g. RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040, GENERIC_RP2040, etc.)
* Contextual information (e.g. what you were trying to achieve)
* Simplest possible steps to reproduce
* Anything that might be relevant in your opinion, such as:
* Operating system (Windows, Ubuntu, etc.) and the output of `uname -a`
* Network configuration
### Example
```
Arduino IDE version: 1.8.13
RP2040 core v1.2.1
RASPBERRY_PI_PICO Module
OS: Ubuntu 20.04 LTS
Linux xy-Inspiron-3593 5.4.0-72-generic #80-Ubuntu SMP Mon Apr 12 17:35:00 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
Context:
I encountered a crash while using TimerInterrupt.
Steps to reproduce:
1. ...
2. ...
3. ...
4. ...
```
### Sending Feature Requests
Feel free to post feature requests. It's helpful if you can explain exactly why the feature would be useful.
There are usually some outstanding feature requests in the [existing issues list](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement), feel free to add comments to them.
### Sending Pull Requests
Pull Requests with changes and fixes are also welcome!
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Khoi Hoang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,146 @@
# Copyright (c) 2021 Earle F. Philhower, III
#
# Raspberry Pi RP2040 Core platform file
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# For more info:
# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification
name=Raspberry Pi RP2040 Boards(1.2.1)
version=1.2.1
compiler.path={runtime.tools.pqt-gcc.path}/bin/
# Compile variables
# -----------------
compiler.warning_flags=-w
compiler.warning_flags.none=-w
compiler.warning_flags.default=
compiler.warning_flags.more=-Wall
compiler.warning_flags.all=-Wall -Wextra
compiler.defines={build.led}
compiler.includes="-I{runtime.platform.path}/pico_base/" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_unique_id/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_platform/include/" "-I{runtime.platform.path}/pico-sdk/src/common/pico_base/include/" "-I{runtime.platform.path}/pico-sdk/src/rp2040/hardware_regs/include/" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_timer/include/" "-I{runtime.platform.path}/pico-sdk/src/common/pico_stdlib/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_gpio/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_i2c/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_flash/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_base/include" "-I{runtime.platform.path}/pico-examples/build/generated/pico_base" "-I{runtime.platform.path}/pico-sdk/src/boards/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_platform/include" "-I{runtime.platform.path}/pico-sdk/src/rp2040/hardware_regs/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_base/include" "-I{runtime.platform.path}/pico-sdk/src/rp2040/hardware_structs/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_claim/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_sync/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_uart/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_divider/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_time/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_timer/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_sync/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_util/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_runtime/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_clocks/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_resets/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_watchdog/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_xosc/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_pll/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_vreg/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_irq/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_printf/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_bootrom/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_bit_ops/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_divider/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_double/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_int64_ops/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_float/include" "-I{runtime.platform.path}/pico-sdk/src/common/pico_binary_info/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_pio/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_stdio/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_dma/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_stdio_uart/include" "-I{runtime.platform.path}/pico-sdk/src/rp2040/hardware_regs/include/" "-I{runtime.platform.path}/pico-sdk/lib/tinyusb/src/" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_stdio_usb/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_spi/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_pwm/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/hardware_adc/include" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_multicore/include" "-I{runtime.platform.path}/cores/rp2040/api/deprecated-avr-comp/" "-I{runtime.platform.path}/pico-sdk/src/rp2_common/pico_multicore/include" "-I{runtime.platform.path}/pico-extras/src/rp2_common/pico_audio_i2s/include" "-I{runtime.platform.path}/pico-extras/src/common/pico_audio/include" "-I{runtime.platform.path}/pico-extras/src/common/pico_util_buffer/include"
compiler.flags=-Os -march=armv6-m -mcpu=cortex-m0plus -mthumb -ffunction-sections -fdata-sections
compiler.wrap=-Wl,--wrap=acos -Wl,--wrap=acosf -Wl,--wrap=acosh -Wl,--wrap=acoshf -Wl,--wrap=__aeabi_cdcmpeq -Wl,--wrap=__aeabi_cdcmple -Wl,--wrap=__aeabi_cdrcmple -Wl,--wrap=__aeabi_cfcmpeq -Wl,--wrap=__aeabi_cfcmple -Wl,--wrap=__aeabi_cfrcmple -Wl,--wrap=__aeabi_d2f -Wl,--wrap=__aeabi_d2iz -Wl,--wrap=__aeabi_d2lz -Wl,--wrap=__aeabi_d2uiz -Wl,--wrap=__aeabi_d2ulz -Wl,--wrap=__aeabi_dadd -Wl,--wrap=__aeabi_dcmpeq -Wl,--wrap=__aeabi_dcmpge -Wl,--wrap=__aeabi_dcmpgt -Wl,--wrap=__aeabi_dcmple -Wl,--wrap=__aeabi_dcmplt -Wl,--wrap=__aeabi_dcmpun -Wl,--wrap=__aeabi_ddiv -Wl,--wrap=__aeabi_dmul -Wl,--wrap=__aeabi_drsub -Wl,--wrap=__aeabi_dsub -Wl,--wrap=__aeabi_f2d -Wl,--wrap=__aeabi_f2iz -Wl,--wrap=__aeabi_f2lz -Wl,--wrap=__aeabi_f2uiz -Wl,--wrap=__aeabi_f2ulz -Wl,--wrap=__aeabi_fadd -Wl,--wrap=__aeabi_fcmpeq -Wl,--wrap=__aeabi_fcmpge -Wl,--wrap=__aeabi_fcmpgt -Wl,--wrap=__aeabi_fcmple -Wl,--wrap=__aeabi_fcmplt -Wl,--wrap=__aeabi_fcmpun -Wl,--wrap=__aeabi_fdiv -Wl,--wrap=__aeabi_fmul -Wl,--wrap=__aeabi_frsub -Wl,--wrap=__aeabi_fsub -Wl,--wrap=__aeabi_i2d -Wl,--wrap=__aeabi_i2f -Wl,--wrap=__aeabi_idiv -Wl,--wrap=__aeabi_idivmod -Wl,--wrap=__aeabi_l2d -Wl,--wrap=__aeabi_l2f -Wl,--wrap=__aeabi_ldivmod -Wl,--wrap=__aeabi_lmul -Wl,--wrap=__aeabi_memcpy -Wl,--wrap=__aeabi_memcpy4 -Wl,--wrap=__aeabi_memcpy8 -Wl,--wrap=__aeabi_memset -Wl,--wrap=__aeabi_memset4 -Wl,--wrap=__aeabi_memset8 -Wl,--wrap=__aeabi_ui2d -Wl,--wrap=__aeabi_ui2f -Wl,--wrap=__aeabi_uidiv -Wl,--wrap=__aeabi_uidivmod -Wl,--wrap=__aeabi_ul2d -Wl,--wrap=__aeabi_ul2f -Wl,--wrap=__aeabi_uldivmod -Wl,--wrap=asin -Wl,--wrap=asinf -Wl,--wrap=asinh -Wl,--wrap=asinhf -Wl,--wrap=atan -Wl,--wrap=atan2 -Wl,--wrap=atan2f -Wl,--wrap=atanf -Wl,--wrap=atanh -Wl,--wrap=atanhf -Wl,--wrap=calloc -Wl,--wrap=cbrt -Wl,--wrap=cbrtf -Wl,--wrap=ceil -Wl,--wrap=ceilf -Wl,--wrap=__clz -Wl,--wrap=__clzdi2 -Wl,--wrap=__clzl -Wl,--wrap=__clzll -Wl,--wrap=__clzsi2 -Wl,--wrap=copysign -Wl,--wrap=copysignf -Wl,--wrap=cos -Wl,--wrap=cosf -Wl,--wrap=cosh -Wl,--wrap=coshf -Wl,--wrap=__ctzdi2 -Wl,--wrap=__ctzsi2 -Wl,--wrap=drem -Wl,--wrap=dremf -Wl,--wrap=exp -Wl,--wrap=exp10 -Wl,--wrap=exp10f -Wl,--wrap=exp2 -Wl,--wrap=exp2f -Wl,--wrap=expf -Wl,--wrap=expm1 -Wl,--wrap=expm1f -Wl,--wrap=floor -Wl,--wrap=floorf -Wl,--wrap=fma -Wl,--wrap=fmaf -Wl,--wrap=fmod -Wl,--wrap=fmodf -Wl,--wrap=free -Wl,--wrap=hypot -Wl,--wrap=hypotf -Wl,--wrap=ldexp -Wl,--wrap=ldexpf -Wl,--wrap=log -Wl,--wrap=log10 -Wl,--wrap=log10f -Wl,--wrap=log1p -Wl,--wrap=log1pf -Wl,--wrap=log2 -Wl,--wrap=log2f -Wl,--wrap=logf -Wl,--wrap=malloc -Wl,--wrap=memcpy -Wl,--wrap=memset -Wl,--wrap=__popcountdi2 -Wl,--wrap=__popcountsi2 -Wl,--wrap=pow -Wl,--wrap=powf -Wl,--wrap=powint -Wl,--wrap=powintf -Wl,--wrap=remainder -Wl,--wrap=remainderf -Wl,--wrap=remquo -Wl,--wrap=remquof -Wl,--wrap=round -Wl,--wrap=roundf -Wl,--wrap=sin -Wl,--wrap=sincos -Wl,--wrap=sincosf -Wl,--wrap=sinf -Wl,--wrap=sinh -Wl,--wrap=sinhf -Wl,--wrap=sqrt -Wl,--wrap=sqrtf -Wl,--wrap=tan -Wl,--wrap=tanf -Wl,--wrap=tanh -Wl,--wrap=tanhf -Wl,--wrap=trunc -Wl,--wrap=truncf
compiler.c.cmd=arm-none-eabi-gcc
compiler.c.flags=-c {compiler.defines} {compiler.flags} {compiler.includes} -std=gnu17 -g
compiler.c.elf.cmd=arm-none-eabi-g++
compiler.c.elf.flags={compiler.defines} {compiler.flags} -Wl,--gc-sections -u _printf_float -u _scanf_float
compiler.S.cmd=arm-none-eabi-gcc
compiler.S.flags=-c -g -x assembler-with-cpp -MMD {compiler.includes} -g
compiler.cpp.cmd=arm-none-eabi-g++
compiler.cpp.flags=-c {compiler.defines} {compiler.flags} {compiler.includes} -std=gnu++17 -g
compiler.ar.cmd=arm-none-eabi-ar
compiler.ar.flags=rcs
compiler.objcopy.cmd=arm-none-eabi-objcopy
compiler.objcopy.eep.flags=-O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0
compiler.elf2hex.bin.flags=-O binary
compiler.elf2hex.hex.flags=-O ihex -R .eeprom
compiler.elf2hex.cmd=arm-none-eabi-objcopy
compiler.ldflags={compiler.wrap} -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--unresolved-symbols=report-all -Wl,--warn-common
compiler.size.cmd=arm-none-eabi-size
compiler.define=-DARDUINO=
compiler.readelf.cmd=arm-none-eabi-readelf
# this can be overriden in boards.txt
build.extra_flags=
# These can be overridden in platform.local.txt
compiler.c.extra_flags=
compiler.c.elf.extra_flags=
compiler.cpp.extra_flags=
compiler.S.extra_flags=
compiler.ar.extra_flags=
compiler.elf2hex.extra_flags=
# Board configuration, set in boards.txt. Present here to ensure substitution works
build.flash_length=
build.eeprom_start=
build.fs_start=
build.fs_end=
build.boot2=boot2_generic_03h_4_padded_checksum
# Allow Pico boards do be auto-discovered by the IDE
discovery.rp2040.pattern="{runtime.tools.pqt-python3.path}/python3" "{runtime.platform.path}/tools/discovery.py"
# Compile patterns
# ----------------
## Compile c files
## KH Add -DBOARD_NAME="{build.board}"
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} {build.usbpid} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DBOARD_NAME="{build.board}" -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {build.debug_port} {build.debug_level} {includes} "{source_file}" -o "{object_file}"
## Compile c++ files
## KH Add -DBOARD_NAME="{build.board}"
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {build.usbpid} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DBOARD_NAME="{build.board}" -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {build.debug_port} {build.debug_level} {includes} "{source_file}" -o "{object_file}"
## Compile S files
## KH Add -DBOARD_NAME="{build.board}"
recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} {build.usbpid} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DBOARD_NAME="{build.board}" -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {build.debug_port} {build.debug_level} {includes} "{source_file}" -o "{object_file}"
## Create archives
# archive_file_path is needed for backwards compatibility with IDE 1.6.5 or older, IDE 1.6.6 or newer overrides this value
archive_file_path={build.path}/{archive_file}
recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}"
## Combine gc-sections, archives, and objects
recipe.hooks.linking.prelink.1.pattern="{runtime.tools.pqt-python3.path}/python3" "{runtime.platform.path}/tools/simplesub.py" --input "{runtime.platform.path}/lib/memmap_default.ld" --out "{build.path}/memmap_default.ld" --sub __FLASH_LENGTH__ {build.flash_length} --sub __EEPROM_START__ {build.eeprom_start} --sub __FS_START__ {build.fs_start} --sub __FS_END__ {build.fs_end}
recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-Wl,--script={build.path}/memmap_default.ld" "-Wl,-Map,{build.path}/{build.project_name}.map" --specs=nosys.specs -Wl,--start-group {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} "{build.path}/{archive_file}" "{runtime.platform.path}/lib/libpico.a" -lm "-I{runtime.platform.path}/pico-sdk/src/rp2040/hardware_regs/include/" "-I{runtime.platform.path}/pico-sdk/src/common/pico_binary_info/include" "{runtime.platform.path}/assembly/{build.boot2}.S" -lc -lstdc++ -Wl,--end-group
## Create output (UF2 file)
recipe.objcopy.uf2.pattern="{runtime.tools.pqt-elf2uf2.path}/elf2uf2" "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.uf2"
build.preferred_out_format=uf2
## Save hex
recipe.output.tmp_file={build.project_name}.{build.preferred_out_format}
recipe.output.save_file={build.project_name}.{build.variant}.{build.preferred_out_format}
## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.boot2|\.text|\.rodata|\.ARM\.extab|\.ARM\.exidx)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.bss|\.ram_vector_table|\.uninitialized_data)\s+([0-9]+).*
tools.uf2conv.path=
# Because the variable expansion doesn't allow one tool to find another, the following lines
# will point to "{runtime.platform.path}/tools/python3/python3" in GIT and
# "{runtime.tools.pqt-python3.path}/python3" for JSON board manager releases.
tools.uf2conv.cmd={runtime.tools.pqt-python3.path}/python3
tools.uf2conv.upload.protocol=uf2
tools.uf2conv.upload.params.verbose=
tools.uf2conv.upload.params.quiet=
tools.uf2conv.upload.pattern="{cmd}" "{runtime.platform.path}/tools/uf2conv.py" --serial "{serial.port}" --family RP2040 --deploy "{build.path}/{build.project_name}.uf2"
tools.picoprobe.cmd={runtime.tools.pqt-openocd.path}
tools.picoprobe.upload.protocol=picoprobe
tools.picoprobe.upload.params.verbose=
tools.picoprobe.upload.params.quiet=
tools.picoprobe.upload.pattern="{cmd}/bin/openocd" -f "interface/picoprobe.cfg" -f "target/rp2040.cfg" -s "{cmd}/share/openocd/scripts" -c "program {build.path}/{build.project_name}.elf verify reset exit"
+819
View File
@@ -0,0 +1,819 @@
# RPI_PICO_TimerInterrupt Library
[![arduino-library-badge](https://www.ardu-badge.com/badge/RPI_PICO_TimerInterrupt.svg?)](https://www.ardu-badge.com/RPI_PICO_TimerInterrupt)
[![GitHub release](https://img.shields.io/github/release/khoih-prog/RPI_PICO_TimerInterrupt.svg)](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/releases)
[![GitHub](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/blob/master/LICENSE)
[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](#Contributing)
[![GitHub issues](https://img.shields.io/github/issues/khoih-prog/RPI_PICO_TimerInterrupt.svg)](http://github.com/khoih-prog/RPI_PICO_TimerInterrupt/issues)
---
---
## Table of Contents
* [Why do we need this RPI_PICO_TimerInterrupt library](#why-do-we-need-this-rpi_pico_timerinterrupt-library)
* [Features](#features)
* [Why using ISR-based Hardware Timer Interrupt is better](#why-using-isr-based-hardware-timer-interrupt-is-better)
* [Currently supported Boards](#currently-supported-boards)
* [Important Notes about ISR](#important-notes-about-isr)
* [Changelog](#changelog)
* [Initial Releases v1.0.0](#initial-releases-v100)
* [Prerequisites](#prerequisites)
* [Installation](#installation)
* [Use Arduino Library Manager](#use-arduino-library-manager)
* [Manual Install](#manual-install)
* [VS Code & PlatformIO](#vs-code--platformio)
* [HOWTO Fix `Multiple Definitions` Linker Error](#howto-fix-multiple-definitions-linker-error)
* [More useful Information](#more-useful-information)
* [Usage](#usage)
* [1. Using only Hardware Timer directly](#1-using-only-hardware-timer-directly)
* [1.1 Init Hardware Timer](#11-init-hardware-timer)
* [1.2 Set Hardware Timer Interval and attach Timer Interrupt Handler function](#12-set-hardware-timer-interval-and-attach-timer-interrupt-handler-function)
* [1.3 Set Hardware Timer Frequency and attach Timer Interrupt Handler function](#13-set-hardware-timer-frequency-and-attach-timer-interrupt-handler-function)
* [2. Using 16 ISR_based Timers from 1 Hardware Timer](#2-using-16-isr_based-timers-from-1-hardware-timer)
* [2.1 Important Note](#21-important-note)
* [2.2 Init Hardware Timer and ISR-based Timer](#22-init-hardware-timer-and-isr-based-timer)
* [2.3 Set Hardware Timer Interval and attach Timer Interrupt Handler functions](#23-set-hardware-timer-interval-and-attach-timer-interrupt-handler-functions)
* [Examples](#examples)
* [ 1. Argument_Complex](examples/Argument_Complex)
* [ 2. Argument_None](examples/Argument_None)
* [ 3. Argument_Simple](examples/Argument_Simple)
* [ 4. Change_Interval](examples/Change_Interval).
* [ 5. ISR_Timers_Array_Simple](examples/ISR_Timers_Array_Simple)
* [ 6. RPM_Measure](examples/RPM_Measure)
* [ 7. SwitchDebounce](examples/SwitchDebounce)
* [ 8. TimerInterruptTest](examples/TimerInterruptTest)
* [Example ISR_Timers_Array_Simple](#example-isr_timer_array_simple)
* [Debug Terminal Output Samples](#debug-terminal-output-samples)
* [1. ISR_Timers_Array_Simple on RASPBERRY_PI_PICO](#1-isr_timers_array_simple-on-raspberry_pi_pico)
* [2. TimerInterruptTest on RASPBERRY_PI_PICO](#2-timerinterrupttest-on-raspberry_pi_pico)
* [3. Change_Interval on RASPBERRY_PI_PICO](#3-change_interval-on-raspberry_pi_pico)
* [4. SwitchDebounce on RASPBERRY_PI_PICO](#4-switchdebounce-on-raspberry_pi_pico)
* [Debug](#debug)
* [Troubleshooting](#troubleshooting)
* [Releases](#releases)
* [Issues](#issues)
* [TO DO](#to-do)
* [DONE](#done)
* [Contributions and Thanks](#contributions-and-thanks)
* [Contributing](#contributing)
* [License](#license)
* [Copyright](#copyright)
---
---
### Why do we need this [RPI_PICO_TimerInterrupt library](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt)
## Features
This library enables you to use Interrupt from Hardware Timers on on RP2040-based boards such as RASPBERRY_PI_PICO, using [Earle Philhower's arduino-pico core](https://github.com/earlephilhower/arduino-pico). Support to [**Arduino-mbed RP2040** core](https://github.com/arduino/ArduinoCore-mbed) will be added in future releases.
As **Hardware Timers are rare, and very precious assets** of any board, this library now enables you to use up to **16 ISR-based Timers, while consuming only 1 Hardware Timer**. Timers' interval is very long (**ulong millisecs**).
Now with these new **16 ISR-based timers**, the maximum interval is **practically unlimited** (limited only by unsigned long miliseconds) while **the accuracy is nearly perfect** compared to software timers.
The most important feature is they're ISR-based timers. Therefore, their executions are **not blocked by bad-behaving functions / tasks**. This important feature is absolutely necessary for mission-critical tasks.
The [**ISR_Timers_Array_Simple**](examples/ISR_Timers_Array_Simple) example will demonstrate the nearly perfect accuracy compared to software timers by printing the actual elapsed millisecs of each type of timers.
Being ISR-based timers, their executions are not blocked by bad-behaving functions / tasks, such as connecting to WiFi, Internet and Blynk services. You can also have many `(up to 16)` timers to use.
This non-being-blocked important feature is absolutely necessary for mission-critical tasks.
You'll see blynkTimer Software is blocked while system is connecting to WiFi / Internet / Blynk, as well as by blocking task
in loop(), using delay() function as an example. The elapsed time then is very unaccurate
### Why using ISR-based Hardware Timer Interrupt is better
Imagine you have a system with a **mission-critical** function, measuring water level and control the sump pump or doing something much more important. You normally use a software timer to poll, or even place the function in loop(). But what if another function is **blocking** the loop() or setup().
So your function **might not be executed, and the result would be disastrous.**
You'd prefer to have your function called, no matter what happening with other functions (busy loop, bug, etc.).
The correct choice is to use a Hardware Timer with **Interrupt** to call your function.
These hardware timers, using interrupt, still work even if other functions are blocking. Moreover, they are much more **precise** (certainly depending on clock frequency accuracy) than other software timers using millis() or micros(). That's necessary if you need to measure some data requiring better accuracy.
Functions using normal software timers, relying on loop() and calling millis(), won't work if the loop() or setup() is blocked by certain operation. For example, certain function is blocking while it's connecting to WiFi or some services.
The catch is **your function is now part of an ISR (Interrupt Service Routine), and must be lean / mean, and follow certain rules.** More to read on:
[**HOWTO Attach Interrupt**](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/)
---
### Currently supported Boards
1. RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040, etc.
---
### Important Notes about ISR
1. Inside the attached function, **delay() wont work and the value returned by millis() will not increment.** Serial data received while in the function may be lost. You should declare as **volatile any variables that you modify within the attached function.**
2. Typically global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile.
---
---
## Changelog
### Initial Releases v1.0.0
1. Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc. using [Earle Philhower's arduino-pico core](https://github.com/earlephilhower/arduino-pico)
---
---
## Prerequisites
1. [`Arduino IDE 1.8.13+` for Arduino](https://www.arduino.cc/en/Main/Software)
2. [`Earle Philhower's arduino-pico core v1.2.1+`](https://github.com/earlephilhower/arduino-pico) for RP2040-based boards such as **RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040**, etc. [![GitHub release](https://img.shields.io/github/release/earlephilhower/arduino-pico.svg)](https://github.com/earlephilhower/arduino-pico/releases/latest)
---
---
## Installation
### Use Arduino Library Manager
The best and easiest way is to use `Arduino Library Manager`. Search for [**RPI_PICO_TimerInterrupt**](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt), then select / install the latest version.
You can also use this link [![arduino-library-badge](https://www.ardu-badge.com/badge/RPI_PICO_TimerInterrupt.svg?)](https://www.ardu-badge.com/RPI_PICO_TimerInterrupt) for more detailed instructions.
### Manual Install
Another way to install is to:
1. Navigate to [**RPI_PICO_TimerInterrupt**](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt) page.
2. Download the latest release `RPI_PICO_TimerInterrupt-master.zip`.
3. Extract the zip file to `RPI_PICO_TimerInterrupt-master` directory
4. Copy whole `RPI_PICO_TimerInterrupt-master` folder to Arduino libraries' directory such as `~/Arduino/libraries/`.
### VS Code & PlatformIO
1. Install [VS Code](https://code.visualstudio.com/)
2. Install [PlatformIO](https://platformio.org/platformio-ide)
3. Install [**RPI_PICO_TimerInterrupt** library](https://platformio.org/lib/show/xxxxx/RPI_PICO_TimerInterrupt) by using [Library Manager](https://platformio.org/lib/show/xxxxx/RPI_PICO_TimerInterrupt/installation). Search for **RPI_PICO_TimerInterrupt** in [Platform.io Author's Libraries](https://platformio.org/lib/search?query=author:%22Khoi%20Hoang%22)
4. Use included [platformio.ini](platformio/platformio.ini) file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples at [Project Configuration File](https://docs.platformio.org/page/projectconf.html)
---
---
### HOWTO Fix `Multiple Definitions` Linker Error
The current library implementation, using **xyz-Impl.h instead of standard xyz.cpp**, possibly creates certain `Multiple Definitions` Linker error in certain use cases. Although it's simple to just modify several lines of code, either in the library or in the application, the library is adding 2 more source directories
1. **scr_h** for new h-only files
2. **src_cpp** for standard h/cpp files
besides the standard **src** directory.
To use the **old standard cpp** way, locate this library' directory, then just
1. **Delete the all the files in src directory.**
2. **Copy all the files in src_cpp directory into src.**
3. Close then reopen the application code in Arduino IDE, etc. to recompile from scratch.
To re-use the **new h-only** way, just
1. **Delete the all the files in src directory.**
2. **Copy the files in src_h directory into src.**
3. Close then reopen the application code in Arduino IDE, etc. to recompile from scratch.
---
---
## More useful Information
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
---
Now with these new `16 ISR-based timers` (while consuming only **1 hardware timer**), the maximum interval is practically unlimited (limited only by unsigned long miliseconds). The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
The `ISR_Timer_Complex` example will demonstrate the nearly perfect accuracy compared to software timers by printing the actual elapsed millisecs of each type of timers.
Being ISR-based timers, their executions are not blocked by bad-behaving functions / tasks, such as connecting to WiFi, Internet and Blynk services. You can also have many `(up to 16)` timers to use.
This non-being-blocked important feature is absolutely necessary for mission-critical tasks.
You'll see blynkTimer Software is blocked while system is connecting to WiFi / Internet / Blynk, as well as by blocking task in loop(), using delay() function as an example. The elapsed time then is very unaccurate
---
---
## Usage
Before using any Timer, you have to make sure the Timer has not been used by any other purpose.
`Timer0, Timer1, Timer2 and Timer3` are supported for RP2040-based boards.
### 1. Using only Hardware Timer directly
### 1.1 Init Hardware Timer
```
// Select the timer you're using, from ITimer0(0)-ITimer3(3)
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer1(1);
```
### 1.2 Set Hardware Timer Interval and attach Timer Interrupt Handler function
Use one of these functions with **interval in unsigned long microseconds**
```
// interval (in us), callback is ISR
bool setInterval(unsigned long interval, pico_timer_callback callback);
// interval (in us), callback is ISR
bool attachInterruptInterval(unsigned long interval, pico_timer_callback callback)
```
as follows
```
void TimerHandler()
{
// Doing something here inside ISR
}
#define TIMER_INTERVAL_MS 5000L
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer(0);
void setup()
{
....
// Interval in unsigned long microseconds
if (ITimer.attachInterruptInterval(TIMER_INTERVAL_MS * 1000, TimerHandler))
Serial.println("Starting ITimer OK, millis() = " + String(millis()));
else
Serial.println("Can't set ITimer. Select another freq. or timer");
}
```
### 1.3 Set Hardware Timer Frequency and attach Timer Interrupt Handler function
Use one of these functions with **frequency in float Hz**
```
// frequency (in Hz), callback is ISR
bool setFrequency(float frequency, pico_timer_callback callback)
// frequency (in Hz), callback is ISR
bool attachInterrupt(float frequency, timer_callback callback);
```
as follows
```
void TimerHandler()
{
// Doing something here inside ISR
}
#define TIMER_FREQ_HZ 5555.555
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer(0);
void setup()
{
....
// Frequency in float Hz
if (ITimer.attachInterrupt(TIMER_FREQ_HZ, TimerHandler))
Serial.println("Starting ITimer OK, millis() = " + String(millis()));
else
Serial.println("Can't set ITimer. Select another freq. or timer");
}
```
### 2. Using 16 ISR_based Timers from 1 Hardware Timer
### 2.1 Important Note
The 16 ISR_based Timers, designed for long timer intervals, only support using **unsigned long millisec intervals**. If you have to use much higher frequency or sub-millisecond interval, you have to use the Hardware Timers directly as in [1.3 Set Hardware Timer Frequency and attach Timer Interrupt Handler function](#13-set-hardware-timer-frequency-and-attach-timer-interrupt-handler-function)
### 2.2 Init Hardware Timer and ISR-based Timer
```
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer1(1);
// Init ISR_Timer
// Each ISR_Timer can service 16 different ISR-based timers
RPI_PICO_ISR_Timer ISR_timer;
```
### 2.3 Set Hardware Timer Interval and attach Timer Interrupt Handler functions
```
void TimerHandler()
{
ISR_timer.run();
}
#define HW_TIMER_INTERVAL_MS 50L
#define TIMER_INTERVAL_2S 2000L
#define TIMER_INTERVAL_5S 5000L
#define TIMER_INTERVAL_11S 11000L
#define TIMER_INTERVAL_101S 101000L
// In AVR, avoid doing something fancy in ISR, for example complex Serial.print with String() argument
// The pure simple Serial.prints here are just for demonstration and testing. Must be eliminate in working environment
// Or you can get this run-time error / crash
void doingSomething2s()
{
// Doing something here inside ISR every 2 seconds
}
void doingSomething5s()
{
// Doing something here inside ISR every 5 seconds
}
void doingSomething11s()
{
// Doing something here inside ISR every 11 seconds
}
void doingSomething101s()
{
// Doing something here inside ISR every 101 seconds
}
void setup()
{
....
if (ITimer1.attachInterruptInterval(HW_TIMER_INTERVAL_MS * 1000, TimerHandler))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
// Just to demonstrate, don't use too many ISR Timers if not absolutely necessary
// You can use up to 16 timer for each ISR_Timer
ISR_timer.setInterval(TIMER_INTERVAL_2S, doingSomething2s);
ISR_timer.setInterval(TIMER_INTERVAL_5S, doingSomething5s);
ISR_timer.setInterval(TIMER_INTERVAL_11S, doingSomething11s);
ISR_timer.setInterval(TIMER_INTERVAL_101S, doingSomething101s);
}
```
---
---
### Examples
1. [Argument_Complex](examples/Argument_Complex)
2. [Argument_None](examples/Argument_None)
3. [Argument_Simple](examples/Argument_Simple)
4. [Change_Interval](examples/Change_Interval)
5. [ISR_Timers_Array_Simple](examples/ISR_Timers_Array_Simple)
6. [RPM_Measure](examples/RPM_Measure)
7. [SwitchDebounce](examples/SwitchDebounce)
8. [TimerInterruptTest](examples/TimerInterruptTest)
---
---
### Example [ISR_Timers_Array_Simple](examples/ISR_Timers_Array_Simple)
```
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#include "RPi_Pico_ISR_Timer.h"
#include <SimpleTimer.h> // https://github.com/schinken/SimpleTimer
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer1(1);
RPI_PICO_ISR_Timer ISR_timer;
#ifndef LED_BUILTIN
#define LED_BUILTIN 25
#endif
#define LED_TOGGLE_INTERVAL_MS 1000L
// You have to use longer time here if having problem because Arduino AVR clock is low, 16MHz => lower accuracy.
// Tested OK with 1ms when not much load => higher accuracy.
#define TIMER_INTERVAL_MS 1L
volatile uint32_t startMillis = 0;
volatile uint32_t deltaMillis2s = 0;
volatile uint32_t deltaMillis5s = 0;
volatile uint32_t previousMillis2s = 0;
volatile uint32_t previousMillis5s = 0;
bool TimerHandler(struct repeating_timer *t)
{
static bool toggle = false;
static int timeRun = 0;
ISR_timer.run();
// Toggle LED every LED_TOGGLE_INTERVAL_MS = 2000ms = 2s
if (++timeRun == ((LED_TOGGLE_INTERVAL_MS) / TIMER_INTERVAL_MS) )
{
timeRun = 0;
//timer interrupt toggles pin LED_BUILTIN
digitalWrite(LED_BUILTIN, toggle);
toggle = !toggle;
}
return true;
}
void doingSomething2s()
{
unsigned long currentMillis = millis();
deltaMillis2s = currentMillis - previousMillis2s;
previousMillis2s = currentMillis;
}
void doingSomething5s()
{
unsigned long currentMillis = millis();
deltaMillis5s = currentMillis - previousMillis5s;
previousMillis5s = currentMillis;
}
/////////////////////////////////////////////////
#define SIMPLE_TIMER_MS 2000L
// Init SimpleTimer
SimpleTimer simpleTimer;
// Here is software Timer, you can do somewhat fancy stuffs without many issues.
// But always avoid
// 1. Long delay() it just doing nothing and pain-without-gain wasting CPU power.Plan and design your code / strategy ahead
// 2. Very long "do", "while", "for" loops without predetermined exit time.
void simpleTimerDoingSomething2s()
{
static unsigned long previousMillis = startMillis;
unsigned long currMillis = millis();
Serial.print(F("SimpleTimer : programmed ")); Serial.print(SIMPLE_TIMER_MS);
Serial.print(F("ms, current time ms : ")); Serial.print(currMillis);
Serial.print(F(", Delta ms : ")); Serial.println(currMillis - previousMillis);
Serial.print(F("Timer2s actual : ")); Serial.println(deltaMillis2s);
Serial.print(F("Timer5s actual : ")); Serial.println(deltaMillis5s);
previousMillis = currMillis;
}
////////////////////////////////////////////////
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
while (!Serial);
Serial.print(F("\nStarting ISR_Timers_Array_Simple on "));
Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
if (ITimer1.attachInterruptInterval(TIMER_INTERVAL_MS *1000, TimerHandler))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
ISR_timer.setInterval(2000L, doingSomething2s);
ISR_timer.setInterval(5000L, doingSomething5s);
// You need this timer for non-critical tasks. Avoid abusing ISR if not absolutely necessary.
simpleTimer.setInterval(SIMPLE_TIMER_MS, simpleTimerDoingSomething2s);
}
#define BLOCKING_TIME_MS 10000L
void loop()
{
// This unadvised blocking task is used to demonstrate the blocking effects onto the execution and accuracy to Software timer
// You see the time elapse of ISR_Timer still accurate, whereas very unaccurate for Software Timer
// The time elapse for 2000ms software timer now becomes 3000ms (BLOCKING_TIME_MS)
// While that of ISR_Timer is still prefect.
delay(BLOCKING_TIME_MS);
// You need this Software timer for non-critical tasks. Avoid abusing ISR if not absolutely necessary
// You don't need to and never call ISR_Timer.run() here in the loop(). It's already handled by ISR timer.
simpleTimer.run();
}
```
---
---
### Debug Terminal Output Samples
### 1. ISR_Timers_Array_Simple on RASPBERRY_PI_PICO
The following is the sample terminal output when running example [ISR_Timers_Array_Simple](examples/ISR_Timers_Array_Simple) to demonstrate the accuracy of ISR Hardware Timer, **especially when system is very busy**. The ISR timer is **programmed for 2s, is activated exactly after 2.000s !!!**
While software timer, **programmed for 2s, is activated after more than 10.000s !!!**
```
Starting ISR_Timers_Array_Simple on RASPBERRY_PI_PICO
RPi_Pico_TimerInterrupt v1.0.0
CPU Frequency = 125 MHz
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 1 , _fre = 1000000.00
[TISR] _count = 0 - 1000
[TISR] add_repeating_timer_us = 1000
Starting ITimer1 OK, millis() = 1707
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 3 , _fre = 1000000.00
[TISR] _count = 0 - 1000
[TISR] add_repeating_timer_us = 1000
Starting ITimer3 OK, millis() = 1707
SimpleTimer : programmed 2000ms, current time ms : 11707, Delta ms : 11707
Timer2s actual : 2000
Timer5s actual : 5000
SimpleTimer : programmed 2000ms, current time ms : 21708, Delta ms : 10001
Timer2s actual : 2000
Timer5s actual : 5000
SimpleTimer : programmed 2000ms, current time ms : 31708, Delta ms : 10000
Timer2s actual : 2000
Timer5s actual : 5000
```
---
### 2. TimerInterruptTest on RASPBERRY_PI_PICO
The following is the sample terminal output when running example [TimerInterruptTest](examples/TimerInterruptTest) to demonstrate how to start/stop Hardware Timers on RP2040-based boards.
```
Starting TimerInterruptTest on RASPBERRY_PI_PICO
RPi_Pico_TimerInterrupt v1.0.0
CPU Frequency = 125 MHz
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 1000000
[TISR] timer_set_alarm_value (us) = 1000000
Starting ITimer0 OK, millis() = 1781
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 3000000
[TISR] timer_set_alarm_value (us) = 3000000
Starting ITimer1 OK, millis() = 1782
ITimer0 called, millis() = 2781
ITimer0 called, millis() = 3781
ITimer0 called, millis() = 4781
ITimer1 called, millis() = 4782
Stop ITimer0, millis() = 5001
ITimer1 called, millis() = 7782
Start ITimer0, millis() = 10002
ITimer1 called, millis() = 10782
ITimer0 called, millis() = 11002
ITimer0 called, millis() = 12002
ITimer0 called, millis() = 13002
ITimer1 called, millis() = 13782
ITimer0 called, millis() = 14002
Stop ITimer1, millis() = 15001
ITimer0 called, millis() = 15002
Stop ITimer0, millis() = 15003
Start ITimer0, millis() = 20004
ITimer0 called, millis() = 21004
ITimer0 called, millis() = 22004
ITimer0 called, millis() = 23004
ITimer0 called, millis() = 24004
ITimer0 called, millis() = 25004
Stop ITimer0, millis() = 25005
```
---
### 3. Change_Interval on RASPBERRY_PI_PICO
The following is the sample terminal output when running example [Change_Interval](examples/Change_Interval) to demonstrate how to change Timer Interval on-the-fly on RP2040-based boards.
```
Starting Change_Interval on RASPBERRY_PI_PICO
RPi_Pico_TimerInterrupt v1.0.0
CPU Frequency = 125 MHz
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 2000000
[TISR] add_repeating_timer_us = 2000000
Starting ITimer0 OK, millis() = 1544
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 1 , _fre = 1000000.00
[TISR] _count = 0 - 5000000
[TISR] add_repeating_timer_us = 5000000
Starting ITimer1 OK, millis() = 1544
ITimer0: millis() = 3544
ITimer0: millis() = 5544
ITimer1: millis() = 6544
ITimer0: millis() = 7544
ITimer0: millis() = 9544
Time = 10001, Timer0Count = 4, Timer1Count = 1
ITimer0: millis() = 11544
ITimer1: millis() = 11544
ITimer0: millis() = 13544
ITimer0: millis() = 15544
ITimer1: millis() = 16544
ITimer0: millis() = 17544
ITimer0: millis() = 19544
Time = 20002, Timer0Count = 9, Timer1Count = 3
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 4000000
[TISR] add_repeating_timer_us = 4000000
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 1 , _fre = 1000000.00
[TISR] _count = 0 - 10000000
[TISR] add_repeating_timer_us = 10000000
Changing Interval, Timer0 = 4000, Timer1 = 10000
ITimer0: millis() = 24002
ITimer0: millis() = 28002
ITimer1: millis() = 30003
Time = 30003, Timer0Count = 11, Timer1Count = 4
ITimer0: millis() = 32002
ITimer0: millis() = 36002
ITimer0: millis() = 40002
ITimer1: millis() = 40003
Time = 40004, Timer0Count = 14, Timer1Count = 5
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 2000000
[TISR] add_repeating_timer_us = 2000000
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 1 , _fre = 1000000.00
[TISR] _count = 0 - 5000000
[TISR] add_repeating_timer_us = 5000000
Changing Interval, Timer0 = 2000, Timer1 = 5000
ITimer0: millis() = 42004
ITimer0: millis() = 44004
ITimer1: millis() = 45004
ITimer0: millis() = 46004
ITimer0: millis() = 48004
ITimer0: millis() = 50004
ITimer1: millis() = 50004
Time = 50005, Timer0Count = 19, Timer1Count = 7
ITimer0: millis() = 52004
ITimer0: millis() = 54004
ITimer1: millis() = 55005
ITimer0: millis() = 56004
ITimer0: millis() = 58004
ITimer0: millis() = 60004
ITimer1: millis() = 60005
Time = 60006, Timer0Count = 24, Timer1Count = 9
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 4000000
[TISR] add_repeating_timer_us = 4000000
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 1 , _fre = 1000000.00
[TISR] _count = 0 - 10000000
[TISR] add_repeating_timer_us = 10000000
Changing Interval, Timer0 = 4000, Timer1 = 10000
ITimer0: millis() = 64006
```
---
### 4. SwitchDebounce on RASPBERRY_PI_PICO
The following is the sample terminal output when running example [SwitchDebounce](examples/SwitchDebounce)
```
Starting SwitchDebounce on RASPBERRY_PI_PICO
RPi_Pico_TimerInterrupt v1.0.0
CPU Frequency = 125 MHz
[TISR] RPI_PICO_TimerInterrupt: _timerNo = 0 , _fre = 1000000.00
[TISR] _count = 0 - 20000
[TISR] add_repeating_timer_us = 20000
Starting ITimer1 OK, millis() = 1302
SW Press, from millis() = 77377
SW Released, from millis() = 78077
SW Pressed total time ms = 700
SW Press, from millis() = 78257
SW Released, from millis() = 78577
SW Pressed total time ms = 320
SW Press, from millis() = 79057
SW Released, from millis() = 80238
SW Pressed total time ms = 1181
```
---
---
### Debug
Debug is enabled by default on Serial.
You can also change the debugging level (_TIMERINTERRUPT_LOGLEVEL_) from 0 to 4
```cpp
// These define's must be placed at the beginning before #include "RPI_PICO_TimerInterrupt.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 0
#define _TIMERINTERRUPT_LOGLEVEL_ 0
```
---
### Troubleshooting
If you get compilation errors, more often than not, you may need to install a newer version of the core for Arduino boards.
Sometimes, the library will only work if you update the board core to the latest version because I am using newly added functions.
---
---
## Releases
### Initial Releases v1.0.0
1. Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc. using [Earle Philhower's arduino-pico core](https://github.com/earlephilhower/arduino-pico)
---
---
### Issues
Submit issues to: [RPI_PICO_TimerInterrupt issues](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/issues)
---
## TO DO
1. Search for bug and improvement.
2. Add support to RP2040-based boards such as RASPBERRY_PI_PICO, using [**Arduino-mbed RP2040** core](https://github.com/arduino/ArduinoCore-mbed)
---
## DONE
1. Basic hardware timers for **RP2040-based boards such as RASPBERRY_PI_PICO**, using [Earle Philhower's arduino-pico core](https://github.com/earlephilhower/arduino-pico)
2. More hardware-initiated software-enabled timers
3. Longer time interval
4. Add Version String
5. Add Table of Contents
---
---
### Contributions and Thanks
Many thanks for everyone for bug reporting, new feature suggesting, testing and contributing to the development of this library.
---
## Contributing
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell other people about this library
---
### License
- The library is licensed under [MIT](https://github.com/khoih-prog/RPI_PICO_TimerInterrupt/blob/master/LICENSE)
---
## Copyright
Copyright 2021- Khoi Hoang
@@ -0,0 +1,117 @@
/****************************************************************************************************************************
Argument_Complex.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#if !defined(LED_BUILTIN)
#define LED_BUILTIN 25
#endif
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer1(1);
struct pinStruct
{
unsigned int Pin1;
unsigned int Pin2;
unsigned int Pin3;
};
volatile pinStruct myOutputPins = { LED_BUILTIN, 0, 1 };
bool TimerHandler(struct repeating_timer *t)
{
static bool toggle = false;
//timer interrupt toggles pins
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("Toggle pin1 = "); Serial.println( myOutputPins.Pin1 );
#endif
digitalWrite(myOutputPins.Pin1, toggle);
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("Read pin2 ("); Serial.print( myOutputPins.Pin2 );
Serial.print(") = ");
Serial.println(digitalRead(myOutputPins.Pin2) ? "HIGH" : "LOW" );
Serial.print("Read pin3 ("); Serial.print( myOutputPins.Pin1 );
Serial.print(") = ");
Serial.println(digitalRead(myOutputPins.Pin3) ? "HIGH" : "LOW" );
#endif
toggle = !toggle;
return true;
}
#define TIMER_INTERVAL_MS 1000
void setup()
{
pinMode(myOutputPins.Pin1, OUTPUT);
pinMode(myOutputPins.Pin2, OUTPUT);
pinMode(myOutputPins.Pin3, OUTPUT);
Serial.begin(115200);
while (!Serial);
Serial.print(F("\nStarting Argument_Complex on "));
Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
// Interval in microsecs
if (ITimer1.attachInterruptInterval(TIMER_INTERVAL_MS * 1000, TimerHandler))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
}
void loop()
{
}
+139
View File
@@ -0,0 +1,139 @@
/****************************************************************************************************************************
Argument_None.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
/*
Notes:
Special design is necessary to share data between interrupt code and the rest of your program.
Variables usually need to be "volatile" types. Volatile tells the compiler to avoid optimizations that assume
variable can not spontaneously change. Because your function may change variables while your program is using them,
the compiler needs this hint. But volatile alone is often not enough.
When accessing shared variables, usually interrupts must be disabled. Even with volatile,
if the interrupt changes a multi-byte variable between a sequence of instructions, it can be read incorrectly.
If your data is multiple variables, such as an array and a count, usually interrupts need to be disabled
or the entire sequence of your code which accesses the data.
*/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#ifndef LED_BUILTIN
#define LED_BUILTIN 25 // Pin LED_BUILTIN mapped to pin GPIO25 of RPI_PICO, control on-board LED
#endif
#define PIN_D1 1 // Pin D1 mapped to pin GPIO1 of RPI_PICO
bool TimerHandler0(struct repeating_timer *t)
{
static bool toggle0 = false;
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("ITimer0: millis() = "); Serial.println(millis());
#endif
//timer interrupt toggles pin LED_BUILTIN
digitalWrite(LED_BUILTIN, toggle0);
toggle0 = !toggle0;
return true;
}
bool TimerHandler1(struct repeating_timer *t)
{
static bool toggle1 = false;
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("ITimer1: millis() = "); Serial.println(millis());
#endif
//timer interrupt toggles outputPin
digitalWrite(PIN_D1, toggle1);
toggle1 = !toggle1;
return true;
}
#define TIMER0_INTERVAL_MS 1000
#define TIMER1_INTERVAL_MS 5000
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer0(0);
RPI_PICO_Timer ITimer1(1);
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(PIN_D1, OUTPUT);
Serial.begin(115200);
while (!Serial);
delay(100);
Serial.print(F("\nStarting Argument_None on ")); Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
// Interval in microsecs
if (ITimer0.attachInterruptInterval(TIMER0_INTERVAL_MS * 1000, TimerHandler0))
{
Serial.print(F("Starting ITimer0 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer0. Select another Timer, freq. or timer"));
// Interval in microsecs
if (ITimer1.attachInterruptInterval(TIMER1_INTERVAL_MS * 1000, TimerHandler1))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another Timer, freq. or timer"));
}
void loop()
{
}
@@ -0,0 +1,133 @@
/****************************************************************************************************************************
Argument_Simple.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#if !defined(LED_BUILTIN)
#define LED_BUILTIN 25
#endif
unsigned int outputPin1 = LED_BUILTIN;
unsigned int outputPin2 = 1;
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer1(1);
RPI_PICO_Timer ITimer2(2);
#define TIMER1_INTERVAL_MS 1000
bool TimerHandler1(struct repeating_timer *t)
{
static bool toggle1 = false;
#if (TIMER_INTERRUPT_DEBUG > 0)
//timer interrupt toggles pin outputPin1
Serial.print("Pin"); Serial.print(outputPin1); Serial.println(toggle1 ? F(" ON") : F(" OFF"));
#endif
digitalWrite(outputPin1, toggle1);
toggle1 = !toggle1;
return true;
}
#define TIMER2_INTERVAL_MS 2000
bool TimerHandler2(struct repeating_timer *t)
{
static bool toggle2 = false;
#if (TIMER_INTERRUPT_DEBUG > 0)
//timer interrupt toggles pin outputPin2
Serial.print("Pin"); Serial.print(outputPin2); Serial.println(toggle2 ? F(" ON") : F(" OFF"));
#endif
//timer interrupt toggles pin outputPin2
digitalWrite(outputPin2, toggle2);
toggle2 = !toggle2;
return true;
}
void setup()
{
pinMode(outputPin1, OUTPUT);
pinMode(outputPin2, OUTPUT);
Serial.begin(115200);
while (!Serial);
Serial.print(F("\nStarting Argument_Simple on "));
Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
if (ITimer1.attachInterruptInterval(TIMER1_INTERVAL_MS * 1000, TimerHandler1))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
#if (TIMER_INTERRUPT_DEBUG > 1)
Serial.print(F("OutputPin1 = ")); Serial.print(outputPin1);
#endif
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
if (ITimer2.attachInterruptInterval(TIMER2_INTERVAL_MS * 1000, TimerHandler2))
{
Serial.print(F("Starting ITimer2 OK, millis() = ")); Serial.println(millis());
#if (TIMER_INTERRUPT_DEBUG > 1)
Serial.print(F("OutputPin2 = ")); Serial.print(outputPin2);
#endif
}
else
Serial.println(F("Can't set ITimer2. Select another freq. or timer"));
}
void loop()
{
}
@@ -0,0 +1,182 @@
/****************************************************************************************************************************
Change_Interval.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
/*
Notes:
Special design is necessary to share data between interrupt code and the rest of your program.
Variables usually need to be "volatile" types. Volatile tells the compiler to avoid optimizations that assume
variable can not spontaneously change. Because your function may change variables while your program is using them,
the compiler needs this hint. But volatile alone is often not enough.
When accessing shared variables, usually interrupts must be disabled. Even with volatile,
if the interrupt changes a multi-byte variable between a sequence of instructions, it can be read incorrectly.
If your data is multiple variables, such as an array and a count, usually interrupts need to be disabled
or the entire sequence of your code which accesses the data.
*/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#ifndef LED_BUILTIN
#define LED_BUILTIN 25 // Pin D2 mapped to pin GPIO2/ADC12 of ESP32, control on-board LED
#endif
#define PIN_D1 1 // Pin D1 mapped to pin GPIO1 of RPI_PICO
volatile uint32_t Timer0Count = 0;
volatile uint32_t Timer1Count = 0;
bool TimerHandler0(struct repeating_timer *t)
{
static bool toggle0 = false;
// Flag for checking to be sure ISR is working as Serial.print is not OK here in ISR
Timer0Count++;
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("ITimer0: millis() = "); Serial.println(millis());
#endif
//timer interrupt toggles pin LED_BUILTIN
digitalWrite(LED_BUILTIN, toggle0);
toggle0 = !toggle0;
return true;
}
bool TimerHandler1(struct repeating_timer *t)
{
static bool toggle1 = false;
// Flag for checking to be sure ISR is working as Serial.print is not OK here in ISR
Timer1Count++;
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("ITimer1: millis() = "); Serial.println(millis());
#endif
//timer interrupt toggles PIN_D1
digitalWrite(PIN_D1, toggle1);
toggle1 = !toggle1;
return true;
}
void printResult(uint32_t currTime)
{
Serial.print(F("Time = ")); Serial.print(currTime);
Serial.print(F(", Timer0Count = ")); Serial.print(Timer0Count);
Serial.print(F(", Timer1Count = ")); Serial.println(Timer1Count);
}
#define TIMER0_INTERVAL_MS 2000
#define TIMER1_INTERVAL_MS 5000
// Init ESP32 timer 0
RPI_PICO_Timer ITimer0(0);
RPI_PICO_Timer ITimer1(1);
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(PIN_D1, OUTPUT);
Serial.begin(115200);
while (!Serial);
delay(100);
Serial.print(F("\nStarting Change_Interval on ")); Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
// Interval in microsecs
if (ITimer0.attachInterruptInterval(TIMER0_INTERVAL_MS * 1000, TimerHandler0))
{
Serial.print(F("Starting ITimer0 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer0. Select another freq. or timer"));
// Interval in microsecs
if (ITimer1.attachInterruptInterval(TIMER1_INTERVAL_MS * 1000, TimerHandler1))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
}
#define CHECK_INTERVAL_MS 10000L
#define CHANGE_INTERVAL_MS 20000L
void loop()
{
static uint32_t lastTime = 0;
static uint32_t lastChangeTime = 0;
static uint32_t currTime;
static uint32_t multFactor = 0;
currTime = millis();
if (currTime - lastTime > CHECK_INTERVAL_MS)
{
printResult(currTime);
lastTime = currTime;
if (currTime - lastChangeTime > CHANGE_INTERVAL_MS)
{
//setInterval(unsigned long interval, timerCallback callback)
multFactor = (multFactor + 1) % 2;
ITimer0.setInterval(TIMER0_INTERVAL_MS * 1000 * (multFactor + 1), TimerHandler0);
ITimer1.setInterval(TIMER1_INTERVAL_MS * 1000 * (multFactor + 1), TimerHandler1);
Serial.print(F("Changing Interval, Timer0 = ")); Serial.print(TIMER0_INTERVAL_MS * (multFactor + 1));
Serial.print(F(", Timer1 = ")); Serial.println(TIMER1_INTERVAL_MS * (multFactor + 1));
lastChangeTime = currTime;
}
}
}
@@ -0,0 +1,179 @@
/****************************************************************************************************************************
ISR_Timers_Array_Simple.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#include "RPi_Pico_ISR_Timer.h"
#include <SimpleTimer.h> // https://github.com/schinken/SimpleTimer
// Init RPI_PICO_Timer
RPI_PICO_Timer ITimer1(1);
RPI_PICO_ISR_Timer ISR_timer;
#ifndef LED_BUILTIN
#define LED_BUILTIN 25
#endif
#define LED_TOGGLE_INTERVAL_MS 1000L
// You have to use longer time here if having problem because Arduino AVR clock is low, 16MHz => lower accuracy.
// Tested OK with 1ms when not much load => higher accuracy.
#define TIMER_INTERVAL_MS 1L
volatile uint32_t startMillis = 0;
volatile uint32_t deltaMillis2s = 0;
volatile uint32_t deltaMillis5s = 0;
volatile uint32_t previousMillis2s = 0;
volatile uint32_t previousMillis5s = 0;
bool TimerHandler(struct repeating_timer *t)
{
static bool toggle = false;
static int timeRun = 0;
ISR_timer.run();
// Toggle LED every LED_TOGGLE_INTERVAL_MS = 2000ms = 2s
if (++timeRun == ((LED_TOGGLE_INTERVAL_MS) / TIMER_INTERVAL_MS) )
{
timeRun = 0;
//timer interrupt toggles pin LED_BUILTIN
digitalWrite(LED_BUILTIN, toggle);
toggle = !toggle;
}
return true;
}
void doingSomething2s()
{
unsigned long currentMillis = millis();
deltaMillis2s = currentMillis - previousMillis2s;
previousMillis2s = currentMillis;
}
void doingSomething5s()
{
unsigned long currentMillis = millis();
deltaMillis5s = currentMillis - previousMillis5s;
previousMillis5s = currentMillis;
}
/////////////////////////////////////////////////
#define SIMPLE_TIMER_MS 2000L
// Init SimpleTimer
SimpleTimer simpleTimer;
// Here is software Timer, you can do somewhat fancy stuffs without many issues.
// But always avoid
// 1. Long delay() it just doing nothing and pain-without-gain wasting CPU power.Plan and design your code / strategy ahead
// 2. Very long "do", "while", "for" loops without predetermined exit time.
void simpleTimerDoingSomething2s()
{
static unsigned long previousMillis = startMillis;
unsigned long currMillis = millis();
Serial.print(F("SimpleTimer : programmed ")); Serial.print(SIMPLE_TIMER_MS);
Serial.print(F("ms, current time ms : ")); Serial.print(currMillis);
Serial.print(F(", Delta ms : ")); Serial.println(currMillis - previousMillis);
Serial.print(F("Timer2s actual : ")); Serial.println(deltaMillis2s);
Serial.print(F("Timer5s actual : ")); Serial.println(deltaMillis5s);
previousMillis = currMillis;
}
////////////////////////////////////////////////
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
while (!Serial);
Serial.print(F("\nStarting ISR_Timers_Array_Simple on "));
Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
if (ITimer1.attachInterruptInterval(TIMER_INTERVAL_MS * 1000, TimerHandler))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
ISR_timer.setInterval(2000L, doingSomething2s);
ISR_timer.setInterval(5000L, doingSomething5s);
// You need this timer for non-critical tasks. Avoid abusing ISR if not absolutely necessary.
simpleTimer.setInterval(SIMPLE_TIMER_MS, simpleTimerDoingSomething2s);
}
#define BLOCKING_TIME_MS 10000L
void loop()
{
// This unadvised blocking task is used to demonstrate the blocking effects onto the execution and accuracy to Software timer
// You see the time elapse of ISR_Timer still accurate, whereas very unaccurate for Software Timer
// The time elapse for 2000ms software timer now becomes 3000ms (BLOCKING_TIME_MS)
// While that of ISR_Timer is still prefect.
delay(BLOCKING_TIME_MS);
// You need this Software timer for non-critical tasks. Avoid abusing ISR if not absolutely necessary
// You don't need to and never call ISR_Timer.run() here in the loop(). It's already handled by ISR timer.
simpleTimer.run();
}
+158
View File
@@ -0,0 +1,158 @@
/****************************************************************************************************************************
RPM_Measure.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
/*
Notes:
Special design is necessary to share data between interrupt code and the rest of your program.
Variables usually need to be "volatile" types. Volatile tells the compiler to avoid optimizations that assume
variable can not spontaneously change. Because your function may change variables while your program is using them,
the compiler needs this hint. But volatile alone is often not enough.
When accessing shared variables, usually interrupts must be disabled. Even with volatile,
if the interrupt changes a multi-byte variable between a sequence of instructions, it can be read incorrectly.
If your data is multiple variables, such as an array and a count, usually interrupts need to be disabled
or the entire sequence of your code which accesses the data.
RPM Measuring uses high frequency hardware timer 1Hz == 1ms) to measure the time from of one rotation, in ms
then convert to RPM. One rotation is detected by reading the state of a magnetic REED SW or IR LED Sensor
Asssuming LOW is active.
For example: Max speed is 600RPM => 10 RPS => minimum 100ms a rotation. We'll use 80ms for debouncing
If the time between active state is less than 8ms => consider noise.
RPM = 60000 / (rotation time in ms)
You can also use interrupt to detect whenever the SW is active, set a flag then use timer to count the time between active state
*/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#define PIN_D1 1 // Pin D1 mapped to pin GPIO1 of RPI_PICO
unsigned int SWPin = PIN_D1;
#define TIMER0_INTERVAL_MS 1
#define DEBOUNCING_INTERVAL_MS 80
#define LOCAL_DEBUG 1
// Init RPI_PICO_Timer, can use any from 0-15 pseudo-hardware timers
RPI_PICO_Timer ITimer0(0);
volatile unsigned long rotationTime = 0;
float RPM = 0.00;
float avgRPM = 0.00;
volatile int debounceCounter;
bool TimerHandler0(struct repeating_timer *t)
{
if ( !digitalRead(SWPin) && (debounceCounter >= DEBOUNCING_INTERVAL_MS / TIMER0_INTERVAL_MS ) )
{
//min time between pulses has passed
RPM = (float) ( 60000.0f / ( rotationTime * TIMER0_INTERVAL_MS ) );
avgRPM = ( 2 * avgRPM + RPM) / 3,
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("RPM = "); Serial.print(avgRPM);
Serial.print(", rotationTime ms = "); Serial.println(rotationTime * TIMER0_INTERVAL_MS);
#endif
rotationTime = 0;
debounceCounter = 0;
}
else
{
debounceCounter++;
}
if (rotationTime >= 5000)
{
// If idle, set RPM to 0, don't increase rotationTime
RPM = 0;
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("RPM = "); Serial.print(RPM); Serial.print(", rotationTime = "); Serial.println(rotationTime);
#endif
rotationTime = 0;
}
else
{
rotationTime++;
}
return true;
}
void setup()
{
pinMode(SWPin, INPUT_PULLUP);
Serial.begin(115200);
while (!Serial);
delay(100);
Serial.print(F("\nStarting RPM_Measure on ")); Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
// Using ESP32 => 80 / 160 / 240MHz CPU clock ,
// For 64-bit timer counter
// For 16-bit timer prescaler up to 1024
// Interval in microsecs
if (ITimer0.attachInterruptInterval(TIMER0_INTERVAL_MS * 1000, TimerHandler0))
{
Serial.print(F("Starting ITimer0 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer0. Select another freq. or timer"));
Serial.flush();
}
void loop()
{
}
+191
View File
@@ -0,0 +1,191 @@
/****************************************************************************************************************************
SwitchDebounce.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
/*
Notes:
Special design is necessary to share data between interrupt code and the rest of your program.
Variables usually need to be "volatile" types. Volatile tells the compiler to avoid optimizations that assume
variable can not spontaneously change. Because your function may change variables while your program is using them,
the compiler needs this hint. But volatile alone is often not enough.
When accessing shared variables, usually interrupts must be disabled. Even with volatile,
if the interrupt changes a multi-byte variable between a sequence of instructions, it can be read incorrectly.
If your data is multiple variables, such as an array and a count, usually interrupts need to be disabled
or the entire sequence of your code which accesses the data.
Switch Debouncing uses high frequency hardware timer 50Hz == 20ms) to measure the time from the SW is pressed,
debouncing time is 100ms => SW is considered pressed if timer count is > 5, then call / flag SW is pressed
When the SW is released, timer will count (debounce) until more than 50ms until consider SW is released.
We can set to flag or call a function whenever SW is pressed more than certain predetermined time, even before
SW is released.
*/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#define PIN_D1 1 // Pin D1 mapped to pin GPIO1 of RPI_PICO
unsigned int SWPin = PIN_D1;
#define TIMER1_INTERVAL_MS 20
#define DEBOUNCING_INTERVAL_MS 100
#define LONG_PRESS_INTERVAL_MS 5000
#define LOCAL_DEBUG 2
// Init RPI_PICO_Timer, can use any from 0-15 pseudo-hardware timers
RPI_PICO_Timer ITimer1(1);
volatile bool SWPressed = false;
volatile bool SWLongPressed = false;
bool TimerHandler1(struct repeating_timer *t)
{
static unsigned int debounceCountSWPressed = 0;
static unsigned int debounceCountSWReleased = 0;
#if (LOCAL_DEBUG > 1)
static unsigned long SWPressedTime;
static unsigned long SWReleasedTime;
unsigned long currentMillis = millis();
#endif
if ( (!digitalRead(SWPin)) )
{
// Start debouncing counting debounceCountSWPressed and clear debounceCountSWReleased
debounceCountSWReleased = 0;
if (++debounceCountSWPressed >= DEBOUNCING_INTERVAL_MS / TIMER1_INTERVAL_MS)
{
// Call and flag SWPressed
if (!SWPressed)
{
#if (LOCAL_DEBUG > 1)
SWPressedTime = currentMillis;
Serial.print("SW Press, from millis() = "); Serial.println(SWPressedTime);
#endif
SWPressed = true;
// Do something for SWPressed here in ISR
// But it's better to use outside software timer to do your job instead of inside ISR
//Your_Response_To_Press();
}
if (debounceCountSWPressed >= LONG_PRESS_INTERVAL_MS / TIMER1_INTERVAL_MS)
{
// Call and flag SWLongPressed
if (!SWLongPressed)
{
#if (LOCAL_DEBUG > 1)
Serial.print("SW Long Pressed, total time ms = "); Serial.print(currentMillis);
Serial.print(" - "); Serial.print(SWPressedTime);
Serial.print(" = "); Serial.println(currentMillis - SWPressedTime);
#endif
SWLongPressed = true;
// Do something for SWLongPressed here in ISR
// But it's better to use outside software timer to do your job instead of inside ISR
//Your_Response_To_Long_Press();
}
}
}
}
else
{
// Start debouncing counting debounceCountSWReleased and clear debounceCountSWPressed
if ( SWPressed && (++debounceCountSWReleased >= DEBOUNCING_INTERVAL_MS / TIMER1_INTERVAL_MS))
{
#if (LOCAL_DEBUG > 1)
SWReleasedTime = currentMillis;
// Call and flag SWPressed
Serial.print("SW Released, from millis() = "); Serial.println(SWReleasedTime);
#endif
SWPressed = false;
SWLongPressed = false;
// Do something for !SWPressed here in ISR
// But it's better to use outside software timer to do your job instead of inside ISR
//Your_Response_To_Release();
// Call and flag SWPressed
#if (LOCAL_DEBUG > 1)
Serial.print("SW Pressed total time ms = ");
Serial.println(SWReleasedTime - SWPressedTime);
#endif
debounceCountSWPressed = 0;
}
}
return true;
}
void setup()
{
pinMode(SWPin, INPUT_PULLUP);
Serial.begin(115200);
while (!Serial);
delay(100);
Serial.print(F("\nStarting SwitchDebounce on ")); Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
// Interval in microsecs
if (ITimer1.attachInterruptInterval(TIMER1_INTERVAL_MS * 1000, TimerHandler1))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
}
void loop()
{
}
@@ -0,0 +1,191 @@
/****************************************************************************************************************************
TimerInterruptTest.ino
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
/*
Notes:
Special design is necessary to share data between interrupt code and the rest of your program.
Variables usually need to be "volatile" types. Volatile tells the compiler to avoid optimizations that assume
variable can not spontaneously change. Because your function may change variables while your program is using them,
the compiler needs this hint. But volatile alone is often not enough.
When accessing shared variables, usually interrupts must be disabled. Even with volatile,
if the interrupt changes a multi-byte variable between a sequence of instructions, it can be read incorrectly.
If your data is multiple variables, such as an array and a count, usually interrupts need to be disabled
or the entire sequence of your code which accesses the data.
*/
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
// These define's must be placed at the beginning before #include "TimerInterrupt_Generic.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG 1
#define _TIMERINTERRUPT_LOGLEVEL_ 4
#include "RPi_Pico_TimerInterrupt.h"
#ifndef LED_BUILTIN
#define LED_BUILTIN 25 // Pin D2 mapped to pin GPIO2/ADC12 of ESP32, control on-board LED
#endif
#define PIN_D1 1 // Pin D1 mapped to pin GPIO1 of RPI_PICO
bool TimerHandler0(struct repeating_timer *t)
{
static bool toggle0 = false;
static bool started = false;
if (!started)
{
started = true;
pinMode(LED_BUILTIN, OUTPUT);
}
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("ITimer0 called, millis() = "); Serial.println(millis());
#endif
//timer interrupt toggles pin LED_BUILTIN
digitalWrite(LED_BUILTIN, toggle0);
toggle0 = !toggle0;
return true;
}
bool TimerHandler1(struct repeating_timer *t)
{
static bool toggle1 = false;
static bool started = false;
if (!started)
{
started = true;
pinMode(PIN_D1, OUTPUT);
}
#if (TIMER_INTERRUPT_DEBUG > 0)
Serial.print("ITimer1 called, millis() = "); Serial.println(millis());
#endif
//timer interrupt toggles outputPin
digitalWrite(PIN_D1, toggle1);
toggle1 = !toggle1;
return true;
}
#define TIMER0_INTERVAL_MS 1000
#define TIMER0_DURATION_MS 5000
#define TIMER1_INTERVAL_MS 3000
#define TIMER1_DURATION_MS 15000
// Init RPI_PICO_Timer, can use any from 0-15 pseudo-hardware timers
RPI_PICO_Timer ITimer0(0);
RPI_PICO_Timer ITimer1(1);
void setup()
{
Serial.begin(115200);
while (!Serial);
delay(100);
Serial.print(F("\nStarting TimerInterruptTest on ")); Serial.println(BOARD_NAME);
Serial.println(RPI_PICO_TIMER_INTERRUPT_VERSION);
Serial.print(F("CPU Frequency = ")); Serial.print(F_CPU / 1000000); Serial.println(F(" MHz"));
// Interval in microsecs
if (ITimer0.attachInterruptInterval(TIMER0_INTERVAL_MS * 1000, TimerHandler0))
{
Serial.print(F("Starting ITimer0 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer0. Select another freq. or timer"));
// Interval in microsecs
if (ITimer1.attachInterruptInterval(TIMER1_INTERVAL_MS * 1000, TimerHandler1))
{
Serial.print(F("Starting ITimer1 OK, millis() = ")); Serial.println(millis());
}
else
Serial.println(F("Can't set ITimer1. Select another freq. or timer"));
Serial.flush();
}
void loop()
{
static unsigned long lastTimer0 = 0;
static unsigned long lastTimer1 = 0;
static bool timer0Stopped = false;
static bool timer1Stopped = false;
if (millis() - lastTimer0 > TIMER0_DURATION_MS)
{
lastTimer0 = millis();
if (timer0Stopped)
{
Serial.print(F("Start ITimer0, millis() = ")); Serial.println(millis());
ITimer0.restartTimer();
}
else
{
Serial.print(F("Stop ITimer0, millis() = ")); Serial.println(millis());
ITimer0.stopTimer();
}
timer0Stopped = !timer0Stopped;
}
if (millis() - lastTimer1 > TIMER1_DURATION_MS)
{
lastTimer1 = millis();
if (timer1Stopped)
{
Serial.print(F("Start ITimer1, millis() = ")); Serial.println(millis());
ITimer1.restartTimer();
}
else
{
Serial.print(F("Stop ITimer1, millis() = ")); Serial.println(millis());
ITimer1.stopTimer();
}
timer1Stopped = !timer1Stopped;
}
}
+50
View File
@@ -0,0 +1,50 @@
#######################################
# Datatypes (KEYWORD1)
#######################################
RPI_PICO_TimerInterrupt KEYWORD1
RPI_PICO_Timer KEYWORD1
RPI_PICO_ISR_Timer KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
###########################
# RPi_Pico_TimerInterrupt
###########################
setFrequency KEYWORD2
setInterval KEYWORD2
attachInterrupt KEYWORD2
attachInterruptInterval KEYWORD2
detachInterrupt KEYWORD2
disableTimer KEYWORD2
reattachInterrupt KEYWORD2
enableTimer KEYWORD2
stopTimer KEYWORD2
restartTimer KEYWORD2
###########################
# RPi_Pico_ISR_Timer
###########################
init KEYWORD2
run KEYWORD2
setTimeout KEYWORD2
setTimer KEYWORD2
changeInterval KEYWORD2
deleteTimer KEYWORD2
restartTimer KEYWORD2
isEnabled KEYWORD2
enable KEYWORD2
disable KEYWORD2
enableAll KEYWORD2
disableAll KEYWORD2
toggle KEYWORD2
getNumTimers KEYWORD2
getNumAvailableTimers KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+29
View File
@@ -0,0 +1,29 @@
{
"name": "RPI_PICO_TimerInterrupt",
"version": "1.0.0",
"keywords": "timing, device, control, timer, interrupt, hardware, isr, isr-based, hardware-timer, mission-critical, accuracy, precise, non-blocking, raspberry-pico, rpi-pico, pico, rp2040",
"description": "This library enables you to use Interrupt from Hardware Timers on RP2040-based boards such as RASPBERRY_PI_PICO. It now supports 16 ISR-based timers, while consuming only 1 Hardware Timer. Timers' interval is very long (ulong millisecs). The most important feature is they're ISR-based timers. Therefore, their executions are not blocked by bad-behaving functions or tasks. This important feature is absolutely necessary for mission-critical tasks. These hardware timers, using interrupt, still work even if other functions are blocking. Moreover, they are much more precise (certainly depending on clock frequency accuracy) than other software timers using millis() or micros(). That's necessary if you need to measure some data requiring better accuracy.",
"authors":
{
"name": "Khoi Hoang",
"url": "https://github.com/khoih-prog",
"maintainer": true
},
"repository":
{
"type": "git",
"url": "//https://github.com/khoih-prog/RPI_PICO_TimerInterrupt"
},
"homepage": "https://github.com/khoih-prog/RPI_PICO_TimerInterrupt",
"export": {
"exclude": [
"linux",
"extras",
"tests"
]
},
"frameworks": "*",
"platforms": "rp2040",
"examples": "examples/*/*/*.ino",
"license": "MIT"
}
+12
View File
@@ -0,0 +1,12 @@
name=RPI_PICO_TimerInterrupt
version=1.0.0
author=Khoi Hoang <khoih.prog@gmail.com>
maintainer=Khoi Hoang <khoih.prog@gmail.com>
sentence=This library enables you to use Interrupt from Hardware Timers on RP2040-based boards such as RASPBERRY_PI_PICO
paragraph=These RPI_PICO_TimerInterrupt Hardware Timers, using Interrupt, still work even if other functions are blocking. Moreover, they are much more precise (certainly depending on clock frequency accuracy) than other software timers using millis() or micros(). That's mandatory if you need to measure some data requiring better accuracy. It now supports 16 ISR-based Timers, while consuming only 1 Hardware Timer. Timers' interval is very long (ulong millisecs). The most important feature is they're ISR-based Timers. Therefore, their executions are not blocked by bad-behaving functions or tasks. This important feature is absolutely necessary for mission-critical tasks.
category=Timing, Control, Device, Time, Timer, rp2040, raspberry-pico
url=https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
architectures=rp2040
repository=https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
license=MIT
includes=RPi_Pico_TimerInterrupt.h,RPi_Pico_ISR_Timer.h
+391
View File
@@ -0,0 +1,391 @@
/****************************************************************************************************************************
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef ISR_TIMER_GENERIC_IMPL_H
#define ISR_TIMER_GENERIC_IMPL_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
#include <string.h>
RPI_PICO_ISR_Timer::RPI_PICO_ISR_Timer()
: numTimers (-1)
{
}
void RPI_PICO_ISR_Timer::init()
{
unsigned long current_millis = millis(); //elapsed();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
memset((void*) &timer[i], 0, sizeof (timer_t));
timer[i].prev_millis = current_millis;
}
numTimers = 0;
}
void RPI_PICO_ISR_Timer::run()
{
uint8_t i;
unsigned long current_millis;
// get current time
current_millis = millis(); //elapsed();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during ISR
rp2040.idleOtherCore();
for (i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_DONTRUN;
// no callback == no timer, i.e. jump over empty slots
if (timer[i].callback != NULL)
{
// is it time to process this timer ?
// see http://arduino.cc/forum/index.php/topic,124048.msg932592.html#msg932592
if ((current_millis - timer[i].prev_millis) >= timer[i].delay)
{
unsigned long skipTimes = (current_millis - timer[i].prev_millis) / timer[i].delay;
// update time
timer[i].prev_millis += timer[i].delay * skipTimes;
// check if the timer callback has to be executed
if (timer[i].enabled)
{
// "run forever" timers must always be executed
if (timer[i].maxNumRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNONLY;
}
// other timers get executed the specified number of times
else if (timer[i].numRuns < timer[i].maxNumRuns)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNONLY;
timer[i].numRuns++;
// after the last run, delete the timer
if (timer[i].numRuns >= timer[i].maxNumRuns)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNANDDEL;
}
}
}
}
}
}
for (i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].toBeCalled == RPI_PICO_DEFCALL_DONTRUN)
continue;
if (timer[i].hasParam)
(*(timer_callback_p)timer[i].callback)(timer[i].param);
else
(*(timer_callback)timer[i].callback)();
if (timer[i].toBeCalled == RPI_PICO_DEFCALL_RUNANDDEL)
deleteTimer(i);
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during ISR
rp2040.resumeOtherCore();
}
// find the first available slot
// return -1 if none found
int RPI_PICO_ISR_Timer::findFirstFreeSlot()
{
// all slots are used
if (numTimers >= RPI_PICO_MAX_TIMERS)
{
return -1;
}
// return the first slot with no callback (i.e. free)
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback == NULL)
{
return i;
}
}
// no free slots found
return -1;
}
int RPI_PICO_ISR_Timer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n)
{
int freeTimer;
if (numTimers < 0)
{
init();
}
freeTimer = findFirstFreeSlot();
if (freeTimer < 0)
{
return -1;
}
if (f == NULL)
{
return -1;
}
timer[freeTimer].delay = d;
timer[freeTimer].callback = f;
timer[freeTimer].param = p;
timer[freeTimer].hasParam = h;
timer[freeTimer].maxNumRuns = n;
timer[freeTimer].enabled = true;
timer[freeTimer].prev_millis = millis();
numTimers++;
return freeTimer;
}
int RPI_PICO_ISR_Timer::setTimer(unsigned long d, timer_callback f, unsigned n)
{
return setupTimer(d, (void *)f, NULL, false, n);
}
int RPI_PICO_ISR_Timer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n)
{
return setupTimer(d, (void *)f, p, true, n);
}
int RPI_PICO_ISR_Timer::setInterval(unsigned long d, timer_callback f)
{
return setupTimer(d, (void *)f, NULL, false, RPI_PICO_RUN_FOREVER);
}
int RPI_PICO_ISR_Timer::setInterval(unsigned long d, timer_callback_p f, void* p)
{
return setupTimer(d, (void *)f, p, true, RPI_PICO_RUN_FOREVER);
}
int RPI_PICO_ISR_Timer::setTimeout(unsigned long d, timer_callback f)
{
return setupTimer(d, (void *)f, NULL, false, RPI_PICO_RUN_ONCE);
}
int RPI_PICO_ISR_Timer::setTimeout(unsigned long d, timer_callback_p f, void* p)
{
return setupTimer(d, (void *)f, p, true, RPI_PICO_RUN_ONCE);
}
bool RPI_PICO_ISR_Timer::changeInterval(unsigned numTimer, unsigned long d)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return false;
}
// Updates interval of existing specified timer
if (timer[numTimer].callback != NULL)
{
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
timer[numTimer].delay = d;
timer[numTimer].prev_millis = millis();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
return true;
}
// false return for non-used numTimer, no callback
return false;
}
void RPI_PICO_ISR_Timer::deleteTimer(unsigned timerId)
{
if (timerId >= RPI_PICO_MAX_TIMERS)
{
return;
}
// nothing to delete if no timers are in use
if (numTimers == 0)
{
return;
}
// don't decrease the number of timers if the specified slot is already empty
if (timer[timerId].callback != NULL)
{
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
memset((void*) &timer[timerId], 0, sizeof (timer_t));
timer[timerId].prev_millis = millis();
// update number of timers
numTimers--;
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
}
// function contributed by code@rowansimms.com
void RPI_PICO_ISR_Timer::restartTimer(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
timer[numTimer].prev_millis = millis();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
bool RPI_PICO_ISR_Timer::isEnabled(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return false;
}
return timer[numTimer].enabled;
}
void RPI_PICO_ISR_Timer::enable(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = true;
}
void RPI_PICO_ISR_Timer::disable(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = false;
}
void RPI_PICO_ISR_Timer::enableAll()
{
// Enable all timers with a callback assigned (used)
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback != NULL && timer[i].numRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].enabled = true;
}
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
void RPI_PICO_ISR_Timer::disableAll()
{
// Disable all timers with a callback assigned (used)
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback != NULL && timer[i].numRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].enabled = false;
}
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
void RPI_PICO_ISR_Timer::toggle(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = !timer[numTimer].enabled;
}
unsigned RPI_PICO_ISR_Timer::getNumTimers()
{
return numTimers;
}
#endif // ISR_TIMER_GENERIC_IMPL_H
+192
View File
@@ -0,0 +1,192 @@
/****************************************************************************************************************************
RPi_Pico_ISR_Timer.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef ISR_TIMER_GENERIC_H
#define ISR_TIMER_GENERIC_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
#ifndef RPI_PICO_TIMER_INTERRUPT_VERSION
#define RPI_PICO_TIMER_INTERRUPT_VERSION "RPi_Pico_TimerInterrupt v1.0.0"
#endif
#include "TimerInterrupt_Generic_Debug.h"
#include <stddef.h>
#include <inttypes.h>
#include "pico/multicore.h"
#if defined(ARDUINO)
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#endif
#define FLAG_VALUE 0xDEADBEEF
#define RPI_PICO_ISR_Timer RPI_PICO_ISRTimer
typedef void (*timer_callback)();
typedef void (*timer_callback_p)(void *);
class RPI_PICO_ISR_Timer
{
public:
// maximum number of timers
#define RPI_PICO_MAX_TIMERS 16
#define RPI_PICO_RUN_FOREVER 0
#define RPI_PICO_RUN_ONCE 1
// constructor
RPI_PICO_ISR_Timer();
void init();
// this function must be called inside loop()
void run();
// Timer will call function 'f' every 'd' milliseconds forever
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setInterval(unsigned long d, timer_callback f);
// Timer will call function 'f' with parameter 'p' every 'd' milliseconds forever
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setInterval(unsigned long d, timer_callback_p f, void* p);
// Timer will call function 'f' after 'd' milliseconds one time
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimeout(unsigned long d, timer_callback f);
// Timer will call function 'f' with parameter 'p' after 'd' milliseconds one time
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimeout(unsigned long d, timer_callback_p f, void* p);
// Timer will call function 'f' every 'd' milliseconds 'n' times
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimer(unsigned long d, timer_callback f, unsigned n);
// Timer will call function 'f' with parameter 'p' every 'd' milliseconds 'n' times
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n);
// updates interval of the specified timer
bool changeInterval(unsigned numTimer, unsigned long d);
// destroy the specified timer
void deleteTimer(unsigned numTimer);
// restart the specified timer
void restartTimer(unsigned numTimer);
// returns true if the specified timer is enabled
bool isEnabled(unsigned numTimer);
// enables the specified timer
void enable(unsigned numTimer);
// disables the specified timer
void disable(unsigned numTimer);
// enables all timers
void enableAll();
// disables all timers
void disableAll();
// enables the specified timer if it's currently disabled, and vice-versa
void toggle(unsigned numTimer);
// returns the number of used timers
unsigned getNumTimers();
// returns the number of available timers
unsigned getNumAvailableTimers()
{
return RPI_PICO_MAX_TIMERS - numTimers;
};
private:
// deferred call constants
#define RPI_PICO_DEFCALL_DONTRUN 0 // don't call the callback function
#define RPI_PICO_DEFCALL_RUNONLY 1 // call the callback function but don't delete the timer
#define RPI_PICO_DEFCALL_RUNANDDEL 2 // call the callback function and delete the timer
// low level function to initialize and enable a new timer
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n);
// find the first available slot
int findFirstFreeSlot();
typedef struct
{
unsigned long prev_millis; // value returned by the millis() function in the previous run() call
void* callback; // pointer to the callback function
void* param; // function parameter
bool hasParam; // true if callback takes a parameter
unsigned long delay; // delay value
unsigned maxNumRuns; // number of runs to be executed
unsigned numRuns; // number of executed runs
bool enabled; // true if enabled
unsigned toBeCalled; // deferred function call (sort of) - N.B.: only used in run()
} timer_t;
volatile timer_t timer[RPI_PICO_MAX_TIMERS];
// actual number of timers in use (-1 means uninitialized)
volatile int numTimers;
};
#include "RPi_Pico_ISR_Timer-Impl.h"
#endif // ISR_TIMER_GENERIC_H
+198
View File
@@ -0,0 +1,198 @@
/****************************************************************************************************************************
RPi_Pico_TimerInterrupt.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef RPI_PICO_TIMERINTERRUPT_H
#define RPI_PICO_TIMERINTERRUPT_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#else
#define USING_RPI_PICO_TIMER_INTERRUPT true
#endif
#ifndef RPI_PICO_TIMER_INTERRUPT_VERSION
#define RPI_PICO_TIMER_INTERRUPT_VERSION "RPi_Pico_TimerInterrupt v1.0.0"
#endif
#ifndef TIMER_INTERRUPT_DEBUG
#define TIMER_INTERRUPT_DEBUG 0
#endif
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/timer.h"
#include "hardware/irq.h"
#include "TimerInterrupt_Generic_Debug.h"
/*
To enable an alarm:
• Enable the interrupt at the timer with a write to the appropriate alarm bit in INTE: i.e. (1 << 0) for ALARM0
• Enable the appropriate timer interrupt at the processor (see Section 2.3.2)
• Write the time you would like the interrupt to fire to ALARM0 (i.e. the current value in TIMERAWL plus your desired
alarm time in microseconds). Writing the time to the ALARM register sets the ARMED bit as a side effect.
Once the alarm has fired, the ARMED bit will be set to 0 . To clear the latched interrupt, write a 1 to the appropriate bit in
INTR.
*/
class RPI_PICO_TimerInterrupt;
typedef RPI_PICO_TimerInterrupt RPI_PICO_Timer;
// We can use many timers here
#define MAX_RPI_PICO_NUM_TIMERS 4
typedef bool (*pico_timer_callback) (struct repeating_timer *t);
class RPI_PICO_TimerInterrupt
{
private:
uint8_t _timerNo;
pico_timer_callback _callback; // pointer to the callback function
float _frequency; // Timer frequency
uint64_t _timerCount; // count to activate timer, in us
struct repeating_timer _timer;
public:
RPI_PICO_TimerInterrupt(uint8_t timerNo)
{
_timerNo = timerNo;
_callback = NULL;
};
// frequency (in hertz) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool setFrequency(float frequency, pico_timer_callback callback)
{
if (_timerNo < MAX_RPI_PICO_NUM_TIMERS)
{
// select timer frequency is 1MHz for better accuracy. We don't use 16-bit prescaler for now.
// Will use later if very low frequency is needed.
_frequency = (float) 1000000;
_timerCount = (uint64_t) _frequency / frequency;
TISR_LOGWARN3(F("RPI_PICO_TimerInterrupt: _timerNo ="), _timerNo, F(", _fre ="), _frequency);
TISR_LOGWARN3(F("_count ="), (uint32_t) (_timerCount >> 32) , F("-"), (uint32_t) (_timerCount));
_callback = callback;
// static bool add_repeating_timer_us(int64_t delay_us, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
// static bool add_repeating_timer_ms(int64_t delay_ms, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
// bool cancel_repeating_timer (repeating_timer_t *timer);
cancel_repeating_timer(&_timer);
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
TISR_LOGWARN1(F("add_repeating_timer_us ="), _timerCount);
return true;
}
else
{
TISR_LOGERROR(F("Error. Timer must be 0-3"));
return false;
}
}
// interval (in microseconds) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool setInterval(unsigned long interval, pico_timer_callback callback)
{
return setFrequency((float) (1000000.0f / interval), callback);
}
bool attachInterrupt(float frequency, pico_timer_callback callback)
{
return setFrequency(frequency, callback);
}
// interval (in microseconds) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool attachInterruptInterval(unsigned long interval, pico_timer_callback callback)
{
return setFrequency( (float) ( 1000000.0f / interval), callback);
}
void detachInterrupt()
{
cancel_repeating_timer(&_timer);
}
void disableTimer()
{
cancel_repeating_timer(&_timer);
}
// Duration (in milliseconds). Duration = 0 or not specified => run indefinitely
void reattachInterrupt()
{
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
// Duration (in milliseconds). Duration = 0 or not specified => run indefinitely
void enableTimer()
{
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
// Just stop clock source, clear the count
void stopTimer()
{
cancel_repeating_timer(&_timer);
}
// Just reconnect clock source, start current count from 0
void restartTimer()
{
cancel_repeating_timer(&_timer);
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
int8_t getTimer() __attribute__((always_inline))
{
return _timerNo;
};
}; // class RPI_PICO_TimerInterrupt
#endif // RPI_PICO_TIMERINTERRUPT_H
+81
View File
@@ -0,0 +1,81 @@
/****************************************************************************************************************************
TimerInterrupt_Generic_Debug.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef TIMERINTERRUPT_GENERIC_DEBUG_H
#define TIMERINTERRUPT_GENERIC_DEBUG_H
#ifdef TIMERINTERRUPT_DEBUG_PORT
#define TISR_DBG_PORT TIMERINTERRUPT_DEBUG_PORT
#else
#define TISR_DBG_PORT Serial
#endif
// Change _TIMERINTERRUPT_LOGLEVEL_ to set tracing and logging verbosity
// 0: DISABLED: no logging
// 1: ERROR: errors
// 2: WARN: errors and warnings
// 3: INFO: errors, warnings and informational (default)
// 4: DEBUG: errors, warnings, informational and debug
#ifndef _TIMERINTERRUPT_LOGLEVEL_
#define _TIMERINTERRUPT_LOGLEVEL_ 1
#endif
#define TISR_LOGERROR(x) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGERROR0(x) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print(x); }
#define TISR_LOGERROR1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGERROR2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGERROR3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGWARN(x) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGWARN0(x) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print(x); }
#define TISR_LOGWARN1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGWARN2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGWARN3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGINFO(x) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGINFO0(x) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print(x); }
#define TISR_LOGINFO1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGINFO2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGINFO3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGDEBUG(x) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGDEBUG0(x) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print(x); }
#define TISR_LOGDEBUG1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGDEBUG2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGDEBUG3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#endif //TIMERINTERRUPT_GENERIC_DEBUG_H
+383
View File
@@ -0,0 +1,383 @@
/****************************************************************************************************************************
RPi_Pico_ISR_Timer.cpp
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#include <string.h>
#include "RPi_Pico_ISR_Timer.h"
RPI_PICO_ISR_Timer::RPI_PICO_ISR_Timer()
: numTimers (-1)
{
}
void RPI_PICO_ISR_Timer::init()
{
unsigned long current_millis = millis(); //elapsed();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
memset((void*) &timer[i], 0, sizeof (timer_t));
timer[i].prev_millis = current_millis;
}
numTimers = 0;
}
void RPI_PICO_ISR_Timer::run()
{
uint8_t i;
unsigned long current_millis;
// get current time
current_millis = millis(); //elapsed();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during ISR
rp2040.idleOtherCore();
for (i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_DONTRUN;
// no callback == no timer, i.e. jump over empty slots
if (timer[i].callback != NULL)
{
// is it time to process this timer ?
// see http://arduino.cc/forum/index.php/topic,124048.msg932592.html#msg932592
if ((current_millis - timer[i].prev_millis) >= timer[i].delay)
{
unsigned long skipTimes = (current_millis - timer[i].prev_millis) / timer[i].delay;
// update time
timer[i].prev_millis += timer[i].delay * skipTimes;
// check if the timer callback has to be executed
if (timer[i].enabled)
{
// "run forever" timers must always be executed
if (timer[i].maxNumRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNONLY;
}
// other timers get executed the specified number of times
else if (timer[i].numRuns < timer[i].maxNumRuns)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNONLY;
timer[i].numRuns++;
// after the last run, delete the timer
if (timer[i].numRuns >= timer[i].maxNumRuns)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNANDDEL;
}
}
}
}
}
}
for (i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].toBeCalled == RPI_PICO_DEFCALL_DONTRUN)
continue;
if (timer[i].hasParam)
(*(timer_callback_p)timer[i].callback)(timer[i].param);
else
(*(timer_callback)timer[i].callback)();
if (timer[i].toBeCalled == RPI_PICO_DEFCALL_RUNANDDEL)
deleteTimer(i);
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during ISR
rp2040.resumeOtherCore();
}
// find the first available slot
// return -1 if none found
int RPI_PICO_ISR_Timer::findFirstFreeSlot()
{
// all slots are used
if (numTimers >= RPI_PICO_MAX_TIMERS)
{
return -1;
}
// return the first slot with no callback (i.e. free)
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback == NULL)
{
return i;
}
}
// no free slots found
return -1;
}
int RPI_PICO_ISR_Timer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n)
{
int freeTimer;
if (numTimers < 0)
{
init();
}
freeTimer = findFirstFreeSlot();
if (freeTimer < 0)
{
return -1;
}
if (f == NULL)
{
return -1;
}
timer[freeTimer].delay = d;
timer[freeTimer].callback = f;
timer[freeTimer].param = p;
timer[freeTimer].hasParam = h;
timer[freeTimer].maxNumRuns = n;
timer[freeTimer].enabled = true;
timer[freeTimer].prev_millis = millis();
numTimers++;
return freeTimer;
}
int RPI_PICO_ISR_Timer::setTimer(unsigned long d, timer_callback f, unsigned n)
{
return setupTimer(d, (void *)f, NULL, false, n);
}
int RPI_PICO_ISR_Timer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n)
{
return setupTimer(d, (void *)f, p, true, n);
}
int RPI_PICO_ISR_Timer::setInterval(unsigned long d, timer_callback f)
{
return setupTimer(d, (void *)f, NULL, false, RPI_PICO_RUN_FOREVER);
}
int RPI_PICO_ISR_Timer::setInterval(unsigned long d, timer_callback_p f, void* p)
{
return setupTimer(d, (void *)f, p, true, RPI_PICO_RUN_FOREVER);
}
int RPI_PICO_ISR_Timer::setTimeout(unsigned long d, timer_callback f)
{
return setupTimer(d, (void *)f, NULL, false, RPI_PICO_RUN_ONCE);
}
int RPI_PICO_ISR_Timer::setTimeout(unsigned long d, timer_callback_p f, void* p)
{
return setupTimer(d, (void *)f, p, true, RPI_PICO_RUN_ONCE);
}
bool RPI_PICO_ISR_Timer::changeInterval(unsigned numTimer, unsigned long d)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return false;
}
// Updates interval of existing specified timer
if (timer[numTimer].callback != NULL)
{
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
timer[numTimer].delay = d;
timer[numTimer].prev_millis = millis();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
return true;
}
// false return for non-used numTimer, no callback
return false;
}
void RPI_PICO_ISR_Timer::deleteTimer(unsigned timerId)
{
if (timerId >= RPI_PICO_MAX_TIMERS)
{
return;
}
// nothing to delete if no timers are in use
if (numTimers == 0)
{
return;
}
// don't decrease the number of timers if the specified slot is already empty
if (timer[timerId].callback != NULL)
{
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
memset((void*) &timer[timerId], 0, sizeof (timer_t));
timer[timerId].prev_millis = millis();
// update number of timers
numTimers--;
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
}
// function contributed by code@rowansimms.com
void RPI_PICO_ISR_Timer::restartTimer(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
timer[numTimer].prev_millis = millis();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
bool RPI_PICO_ISR_Timer::isEnabled(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return false;
}
return timer[numTimer].enabled;
}
void RPI_PICO_ISR_Timer::enable(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = true;
}
void RPI_PICO_ISR_Timer::disable(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = false;
}
void RPI_PICO_ISR_Timer::enableAll()
{
// Enable all timers with a callback assigned (used)
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback != NULL && timer[i].numRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].enabled = true;
}
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
void RPI_PICO_ISR_Timer::disableAll()
{
// Disable all timers with a callback assigned (used)
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback != NULL && timer[i].numRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].enabled = false;
}
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
void RPI_PICO_ISR_Timer::toggle(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = !timer[numTimer].enabled;
}
unsigned RPI_PICO_ISR_Timer::getNumTimers()
{
return numTimers;
}
+189
View File
@@ -0,0 +1,189 @@
/****************************************************************************************************************************
RPi_Pico_ISR_Timer.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef ISR_TIMER_GENERIC_H
#define ISR_TIMER_GENERIC_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
#ifndef RPI_PICO_TIMER_INTERRUPT_VERSION
#define RPI_PICO_TIMER_INTERRUPT_VERSION "RPi_Pico_TimerInterrupt v1.0.0"
#endif
#include "TimerInterrupt_Generic_Debug.h"
#include <stddef.h>
#include <inttypes.h>
#include "pico/multicore.h"
#if defined(ARDUINO)
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#endif
#define FLAG_VALUE 0xDEADBEEF
#define RPI_PICO_ISR_Timer RPI_PICO_ISRTimer
typedef void (*timer_callback)();
typedef void (*timer_callback_p)(void *);
class RPI_PICO_ISR_Timer
{
public:
// maximum number of timers
#define RPI_PICO_MAX_TIMERS 16
#define RPI_PICO_RUN_FOREVER 0
#define RPI_PICO_RUN_ONCE 1
// constructor
RPI_PICO_ISR_Timer();
void init();
// this function must be called inside loop()
void run();
// Timer will call function 'f' every 'd' milliseconds forever
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setInterval(unsigned long d, timer_callback f);
// Timer will call function 'f' with parameter 'p' every 'd' milliseconds forever
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setInterval(unsigned long d, timer_callback_p f, void* p);
// Timer will call function 'f' after 'd' milliseconds one time
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimeout(unsigned long d, timer_callback f);
// Timer will call function 'f' with parameter 'p' after 'd' milliseconds one time
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimeout(unsigned long d, timer_callback_p f, void* p);
// Timer will call function 'f' every 'd' milliseconds 'n' times
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimer(unsigned long d, timer_callback f, unsigned n);
// Timer will call function 'f' with parameter 'p' every 'd' milliseconds 'n' times
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n);
// updates interval of the specified timer
bool changeInterval(unsigned numTimer, unsigned long d);
// destroy the specified timer
void deleteTimer(unsigned numTimer);
// restart the specified timer
void restartTimer(unsigned numTimer);
// returns true if the specified timer is enabled
bool isEnabled(unsigned numTimer);
// enables the specified timer
void enable(unsigned numTimer);
// disables the specified timer
void disable(unsigned numTimer);
// enables all timers
void enableAll();
// disables all timers
void disableAll();
// enables the specified timer if it's currently disabled, and vice-versa
void toggle(unsigned numTimer);
// returns the number of used timers
unsigned getNumTimers();
// returns the number of available timers
unsigned getNumAvailableTimers()
{
return RPI_PICO_MAX_TIMERS - numTimers;
};
private:
// deferred call constants
#define RPI_PICO_DEFCALL_DONTRUN 0 // don't call the callback function
#define RPI_PICO_DEFCALL_RUNONLY 1 // call the callback function but don't delete the timer
#define RPI_PICO_DEFCALL_RUNANDDEL 2 // call the callback function and delete the timer
// low level function to initialize and enable a new timer
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n);
// find the first available slot
int findFirstFreeSlot();
typedef struct
{
unsigned long prev_millis; // value returned by the millis() function in the previous run() call
void* callback; // pointer to the callback function
void* param; // function parameter
bool hasParam; // true if callback takes a parameter
unsigned long delay; // delay value
unsigned maxNumRuns; // number of runs to be executed
unsigned numRuns; // number of executed runs
bool enabled; // true if enabled
unsigned toBeCalled; // deferred function call (sort of) - N.B.: only used in run()
} timer_t;
volatile timer_t timer[RPI_PICO_MAX_TIMERS];
// actual number of timers in use (-1 means uninitialized)
volatile int numTimers;
};
#endif // ISR_TIMER_GENERIC_H
+198
View File
@@ -0,0 +1,198 @@
/****************************************************************************************************************************
RPi_Pico_TimerInterrupt.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef RPI_PICO_TIMERINTERRUPT_H
#define RPI_PICO_TIMERINTERRUPT_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#else
#define USING_RPI_PICO_TIMER_INTERRUPT true
#endif
#ifndef RPI_PICO_TIMER_INTERRUPT_VERSION
#define RPI_PICO_TIMER_INTERRUPT_VERSION "RPi_Pico_TimerInterrupt v1.0.0"
#endif
#ifndef TIMER_INTERRUPT_DEBUG
#define TIMER_INTERRUPT_DEBUG 0
#endif
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/timer.h"
#include "hardware/irq.h"
#include "TimerInterrupt_Generic_Debug.h"
/*
To enable an alarm:
• Enable the interrupt at the timer with a write to the appropriate alarm bit in INTE: i.e. (1 << 0) for ALARM0
• Enable the appropriate timer interrupt at the processor (see Section 2.3.2)
• Write the time you would like the interrupt to fire to ALARM0 (i.e. the current value in TIMERAWL plus your desired
alarm time in microseconds). Writing the time to the ALARM register sets the ARMED bit as a side effect.
Once the alarm has fired, the ARMED bit will be set to 0 . To clear the latched interrupt, write a 1 to the appropriate bit in
INTR.
*/
class RPI_PICO_TimerInterrupt;
typedef RPI_PICO_TimerInterrupt RPI_PICO_Timer;
// We can use many timers here
#define MAX_RPI_PICO_NUM_TIMERS 4
typedef bool (*pico_timer_callback) (struct repeating_timer *t);
class RPI_PICO_TimerInterrupt
{
private:
uint8_t _timerNo;
pico_timer_callback _callback; // pointer to the callback function
float _frequency; // Timer frequency
uint64_t _timerCount; // count to activate timer, in us
struct repeating_timer _timer;
public:
RPI_PICO_TimerInterrupt(uint8_t timerNo)
{
_timerNo = timerNo;
_callback = NULL;
};
// frequency (in hertz) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool setFrequency(float frequency, pico_timer_callback callback)
{
if (_timerNo < MAX_RPI_PICO_NUM_TIMERS)
{
// select timer frequency is 1MHz for better accuracy. We don't use 16-bit prescaler for now.
// Will use later if very low frequency is needed.
_frequency = (float) 1000000;
_timerCount = (uint64_t) _frequency / frequency;
TISR_LOGWARN3(F("RPI_PICO_TimerInterrupt: _timerNo ="), _timerNo, F(", _fre ="), _frequency);
TISR_LOGWARN3(F("_count ="), (uint32_t) (_timerCount >> 32) , F("-"), (uint32_t) (_timerCount));
_callback = callback;
// static bool add_repeating_timer_us(int64_t delay_us, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
// static bool add_repeating_timer_ms(int64_t delay_ms, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
// bool cancel_repeating_timer (repeating_timer_t *timer);
cancel_repeating_timer(&_timer);
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
TISR_LOGWARN1(F("add_repeating_timer_us ="), _timerCount);
return true;
}
else
{
TISR_LOGERROR(F("Error. Timer must be 0-3"));
return false;
}
}
// interval (in microseconds) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool setInterval(unsigned long interval, pico_timer_callback callback)
{
return setFrequency((float) (1000000.0f / interval), callback);
}
bool attachInterrupt(float frequency, pico_timer_callback callback)
{
return setFrequency(frequency, callback);
}
// interval (in microseconds) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool attachInterruptInterval(unsigned long interval, pico_timer_callback callback)
{
return setFrequency( (float) ( 1000000.0f / interval), callback);
}
void detachInterrupt()
{
cancel_repeating_timer(&_timer);
}
void disableTimer()
{
cancel_repeating_timer(&_timer);
}
// Duration (in milliseconds). Duration = 0 or not specified => run indefinitely
void reattachInterrupt()
{
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
// Duration (in milliseconds). Duration = 0 or not specified => run indefinitely
void enableTimer()
{
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
// Just stop clock source, clear the count
void stopTimer()
{
cancel_repeating_timer(&_timer);
}
// Just reconnect clock source, start current count from 0
void restartTimer()
{
cancel_repeating_timer(&_timer);
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
int8_t getTimer() __attribute__((always_inline))
{
return _timerNo;
};
}; // class RPI_PICO_TimerInterrupt
#endif // RPI_PICO_TIMERINTERRUPT_H
+81
View File
@@ -0,0 +1,81 @@
/****************************************************************************************************************************
TimerInterrupt_Generic_Debug.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef TIMERINTERRUPT_GENERIC_DEBUG_H
#define TIMERINTERRUPT_GENERIC_DEBUG_H
#ifdef TIMERINTERRUPT_DEBUG_PORT
#define TISR_DBG_PORT TIMERINTERRUPT_DEBUG_PORT
#else
#define TISR_DBG_PORT Serial
#endif
// Change _TIMERINTERRUPT_LOGLEVEL_ to set tracing and logging verbosity
// 0: DISABLED: no logging
// 1: ERROR: errors
// 2: WARN: errors and warnings
// 3: INFO: errors, warnings and informational (default)
// 4: DEBUG: errors, warnings, informational and debug
#ifndef _TIMERINTERRUPT_LOGLEVEL_
#define _TIMERINTERRUPT_LOGLEVEL_ 1
#endif
#define TISR_LOGERROR(x) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGERROR0(x) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print(x); }
#define TISR_LOGERROR1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGERROR2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGERROR3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGWARN(x) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGWARN0(x) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print(x); }
#define TISR_LOGWARN1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGWARN2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGWARN3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGINFO(x) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGINFO0(x) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print(x); }
#define TISR_LOGINFO1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGINFO2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGINFO3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGDEBUG(x) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGDEBUG0(x) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print(x); }
#define TISR_LOGDEBUG1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGDEBUG2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGDEBUG3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#endif //TIMERINTERRUPT_GENERIC_DEBUG_H
+391
View File
@@ -0,0 +1,391 @@
/****************************************************************************************************************************
RPi_Pico_ISR_Timer-Impl.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef ISR_TIMER_GENERIC_IMPL_H
#define ISR_TIMER_GENERIC_IMPL_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
#include <string.h>
RPI_PICO_ISR_Timer::RPI_PICO_ISR_Timer()
: numTimers (-1)
{
}
void RPI_PICO_ISR_Timer::init()
{
unsigned long current_millis = millis(); //elapsed();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
memset((void*) &timer[i], 0, sizeof (timer_t));
timer[i].prev_millis = current_millis;
}
numTimers = 0;
}
void RPI_PICO_ISR_Timer::run()
{
uint8_t i;
unsigned long current_millis;
// get current time
current_millis = millis(); //elapsed();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during ISR
rp2040.idleOtherCore();
for (i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_DONTRUN;
// no callback == no timer, i.e. jump over empty slots
if (timer[i].callback != NULL)
{
// is it time to process this timer ?
// see http://arduino.cc/forum/index.php/topic,124048.msg932592.html#msg932592
if ((current_millis - timer[i].prev_millis) >= timer[i].delay)
{
unsigned long skipTimes = (current_millis - timer[i].prev_millis) / timer[i].delay;
// update time
timer[i].prev_millis += timer[i].delay * skipTimes;
// check if the timer callback has to be executed
if (timer[i].enabled)
{
// "run forever" timers must always be executed
if (timer[i].maxNumRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNONLY;
}
// other timers get executed the specified number of times
else if (timer[i].numRuns < timer[i].maxNumRuns)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNONLY;
timer[i].numRuns++;
// after the last run, delete the timer
if (timer[i].numRuns >= timer[i].maxNumRuns)
{
timer[i].toBeCalled = RPI_PICO_DEFCALL_RUNANDDEL;
}
}
}
}
}
}
for (i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].toBeCalled == RPI_PICO_DEFCALL_DONTRUN)
continue;
if (timer[i].hasParam)
(*(timer_callback_p)timer[i].callback)(timer[i].param);
else
(*(timer_callback)timer[i].callback)();
if (timer[i].toBeCalled == RPI_PICO_DEFCALL_RUNANDDEL)
deleteTimer(i);
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during ISR
rp2040.resumeOtherCore();
}
// find the first available slot
// return -1 if none found
int RPI_PICO_ISR_Timer::findFirstFreeSlot()
{
// all slots are used
if (numTimers >= RPI_PICO_MAX_TIMERS)
{
return -1;
}
// return the first slot with no callback (i.e. free)
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback == NULL)
{
return i;
}
}
// no free slots found
return -1;
}
int RPI_PICO_ISR_Timer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n)
{
int freeTimer;
if (numTimers < 0)
{
init();
}
freeTimer = findFirstFreeSlot();
if (freeTimer < 0)
{
return -1;
}
if (f == NULL)
{
return -1;
}
timer[freeTimer].delay = d;
timer[freeTimer].callback = f;
timer[freeTimer].param = p;
timer[freeTimer].hasParam = h;
timer[freeTimer].maxNumRuns = n;
timer[freeTimer].enabled = true;
timer[freeTimer].prev_millis = millis();
numTimers++;
return freeTimer;
}
int RPI_PICO_ISR_Timer::setTimer(unsigned long d, timer_callback f, unsigned n)
{
return setupTimer(d, (void *)f, NULL, false, n);
}
int RPI_PICO_ISR_Timer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n)
{
return setupTimer(d, (void *)f, p, true, n);
}
int RPI_PICO_ISR_Timer::setInterval(unsigned long d, timer_callback f)
{
return setupTimer(d, (void *)f, NULL, false, RPI_PICO_RUN_FOREVER);
}
int RPI_PICO_ISR_Timer::setInterval(unsigned long d, timer_callback_p f, void* p)
{
return setupTimer(d, (void *)f, p, true, RPI_PICO_RUN_FOREVER);
}
int RPI_PICO_ISR_Timer::setTimeout(unsigned long d, timer_callback f)
{
return setupTimer(d, (void *)f, NULL, false, RPI_PICO_RUN_ONCE);
}
int RPI_PICO_ISR_Timer::setTimeout(unsigned long d, timer_callback_p f, void* p)
{
return setupTimer(d, (void *)f, p, true, RPI_PICO_RUN_ONCE);
}
bool RPI_PICO_ISR_Timer::changeInterval(unsigned numTimer, unsigned long d)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return false;
}
// Updates interval of existing specified timer
if (timer[numTimer].callback != NULL)
{
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
timer[numTimer].delay = d;
timer[numTimer].prev_millis = millis();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
return true;
}
// false return for non-used numTimer, no callback
return false;
}
void RPI_PICO_ISR_Timer::deleteTimer(unsigned timerId)
{
if (timerId >= RPI_PICO_MAX_TIMERS)
{
return;
}
// nothing to delete if no timers are in use
if (numTimers == 0)
{
return;
}
// don't decrease the number of timers if the specified slot is already empty
if (timer[timerId].callback != NULL)
{
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
memset((void*) &timer[timerId], 0, sizeof (timer_t));
timer[timerId].prev_millis = millis();
// update number of timers
numTimers--;
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
}
// function contributed by code@rowansimms.com
void RPI_PICO_ISR_Timer::restartTimer(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
timer[numTimer].prev_millis = millis();
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
bool RPI_PICO_ISR_Timer::isEnabled(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return false;
}
return timer[numTimer].enabled;
}
void RPI_PICO_ISR_Timer::enable(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = true;
}
void RPI_PICO_ISR_Timer::disable(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = false;
}
void RPI_PICO_ISR_Timer::enableAll()
{
// Enable all timers with a callback assigned (used)
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback != NULL && timer[i].numRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].enabled = true;
}
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
void RPI_PICO_ISR_Timer::disableAll()
{
// Disable all timers with a callback assigned (used)
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.idleOtherCore();
for (uint8_t i = 0; i < RPI_PICO_MAX_TIMERS; i++)
{
if (timer[i].callback != NULL && timer[i].numRuns == RPI_PICO_RUN_FOREVER)
{
timer[i].enabled = false;
}
}
// RPI_PICO is a multi core / multi processing chip. It is mandatory to disable task switches during modifying shared vars
rp2040.resumeOtherCore();
}
void RPI_PICO_ISR_Timer::toggle(unsigned numTimer)
{
if (numTimer >= RPI_PICO_MAX_TIMERS)
{
return;
}
timer[numTimer].enabled = !timer[numTimer].enabled;
}
unsigned RPI_PICO_ISR_Timer::getNumTimers()
{
return numTimers;
}
#endif // ISR_TIMER_GENERIC_IMPL_H
+192
View File
@@ -0,0 +1,192 @@
/****************************************************************************************************************************
RPi_Pico_ISR_Timer.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef ISR_TIMER_GENERIC_H
#define ISR_TIMER_GENERIC_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#endif
#ifndef RPI_PICO_TIMER_INTERRUPT_VERSION
#define RPI_PICO_TIMER_INTERRUPT_VERSION "RPi_Pico_TimerInterrupt v1.0.0"
#endif
#include "TimerInterrupt_Generic_Debug.h"
#include <stddef.h>
#include <inttypes.h>
#include "pico/multicore.h"
#if defined(ARDUINO)
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#endif
#define FLAG_VALUE 0xDEADBEEF
#define RPI_PICO_ISR_Timer RPI_PICO_ISRTimer
typedef void (*timer_callback)();
typedef void (*timer_callback_p)(void *);
class RPI_PICO_ISR_Timer
{
public:
// maximum number of timers
#define RPI_PICO_MAX_TIMERS 16
#define RPI_PICO_RUN_FOREVER 0
#define RPI_PICO_RUN_ONCE 1
// constructor
RPI_PICO_ISR_Timer();
void init();
// this function must be called inside loop()
void run();
// Timer will call function 'f' every 'd' milliseconds forever
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setInterval(unsigned long d, timer_callback f);
// Timer will call function 'f' with parameter 'p' every 'd' milliseconds forever
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setInterval(unsigned long d, timer_callback_p f, void* p);
// Timer will call function 'f' after 'd' milliseconds one time
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimeout(unsigned long d, timer_callback f);
// Timer will call function 'f' with parameter 'p' after 'd' milliseconds one time
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimeout(unsigned long d, timer_callback_p f, void* p);
// Timer will call function 'f' every 'd' milliseconds 'n' times
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimer(unsigned long d, timer_callback f, unsigned n);
// Timer will call function 'f' with parameter 'p' every 'd' milliseconds 'n' times
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n);
// updates interval of the specified timer
bool changeInterval(unsigned numTimer, unsigned long d);
// destroy the specified timer
void deleteTimer(unsigned numTimer);
// restart the specified timer
void restartTimer(unsigned numTimer);
// returns true if the specified timer is enabled
bool isEnabled(unsigned numTimer);
// enables the specified timer
void enable(unsigned numTimer);
// disables the specified timer
void disable(unsigned numTimer);
// enables all timers
void enableAll();
// disables all timers
void disableAll();
// enables the specified timer if it's currently disabled, and vice-versa
void toggle(unsigned numTimer);
// returns the number of used timers
unsigned getNumTimers();
// returns the number of available timers
unsigned getNumAvailableTimers()
{
return RPI_PICO_MAX_TIMERS - numTimers;
};
private:
// deferred call constants
#define RPI_PICO_DEFCALL_DONTRUN 0 // don't call the callback function
#define RPI_PICO_DEFCALL_RUNONLY 1 // call the callback function but don't delete the timer
#define RPI_PICO_DEFCALL_RUNANDDEL 2 // call the callback function and delete the timer
// low level function to initialize and enable a new timer
// returns the timer number (numTimer) on success or
// -1 on failure (f == NULL) or no free timers
int setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n);
// find the first available slot
int findFirstFreeSlot();
typedef struct
{
unsigned long prev_millis; // value returned by the millis() function in the previous run() call
void* callback; // pointer to the callback function
void* param; // function parameter
bool hasParam; // true if callback takes a parameter
unsigned long delay; // delay value
unsigned maxNumRuns; // number of runs to be executed
unsigned numRuns; // number of executed runs
bool enabled; // true if enabled
unsigned toBeCalled; // deferred function call (sort of) - N.B.: only used in run()
} timer_t;
volatile timer_t timer[RPI_PICO_MAX_TIMERS];
// actual number of timers in use (-1 means uninitialized)
volatile int numTimers;
};
#include "RPi_Pico_ISR_Timer-Impl.h"
#endif // ISR_TIMER_GENERIC_H
+198
View File
@@ -0,0 +1,198 @@
/****************************************************************************************************************************
RPi_Pico_TimerInterrupt.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef RPI_PICO_TIMERINTERRUPT_H
#define RPI_PICO_TIMERINTERRUPT_H
#if !( defined(ARDUINO_RASPBERRY_PI_PICO) || defined(ARDUINO_ADAFRUIT_FEATHER_RP2040) || defined(ARDUINO_GENERIC_RP2040) )
#error This code is intended to run on the RASPBERRY_PI_PICO platform! Please check your Tools->Board setting.
#else
#define USING_RPI_PICO_TIMER_INTERRUPT true
#endif
#ifndef RPI_PICO_TIMER_INTERRUPT_VERSION
#define RPI_PICO_TIMER_INTERRUPT_VERSION "RPi_Pico_TimerInterrupt v1.0.0"
#endif
#ifndef TIMER_INTERRUPT_DEBUG
#define TIMER_INTERRUPT_DEBUG 0
#endif
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/timer.h"
#include "hardware/irq.h"
#include "TimerInterrupt_Generic_Debug.h"
/*
To enable an alarm:
• Enable the interrupt at the timer with a write to the appropriate alarm bit in INTE: i.e. (1 << 0) for ALARM0
• Enable the appropriate timer interrupt at the processor (see Section 2.3.2)
• Write the time you would like the interrupt to fire to ALARM0 (i.e. the current value in TIMERAWL plus your desired
alarm time in microseconds). Writing the time to the ALARM register sets the ARMED bit as a side effect.
Once the alarm has fired, the ARMED bit will be set to 0 . To clear the latched interrupt, write a 1 to the appropriate bit in
INTR.
*/
class RPI_PICO_TimerInterrupt;
typedef RPI_PICO_TimerInterrupt RPI_PICO_Timer;
// We can use many timers here
#define MAX_RPI_PICO_NUM_TIMERS 4
typedef bool (*pico_timer_callback) (struct repeating_timer *t);
class RPI_PICO_TimerInterrupt
{
private:
uint8_t _timerNo;
pico_timer_callback _callback; // pointer to the callback function
float _frequency; // Timer frequency
uint64_t _timerCount; // count to activate timer, in us
struct repeating_timer _timer;
public:
RPI_PICO_TimerInterrupt(uint8_t timerNo)
{
_timerNo = timerNo;
_callback = NULL;
};
// frequency (in hertz) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool setFrequency(float frequency, pico_timer_callback callback)
{
if (_timerNo < MAX_RPI_PICO_NUM_TIMERS)
{
// select timer frequency is 1MHz for better accuracy. We don't use 16-bit prescaler for now.
// Will use later if very low frequency is needed.
_frequency = (float) 1000000;
_timerCount = (uint64_t) _frequency / frequency;
TISR_LOGWARN3(F("RPI_PICO_TimerInterrupt: _timerNo ="), _timerNo, F(", _fre ="), _frequency);
TISR_LOGWARN3(F("_count ="), (uint32_t) (_timerCount >> 32) , F("-"), (uint32_t) (_timerCount));
_callback = callback;
// static bool add_repeating_timer_us(int64_t delay_us, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
// static bool add_repeating_timer_ms(int64_t delay_ms, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
// bool cancel_repeating_timer (repeating_timer_t *timer);
cancel_repeating_timer(&_timer);
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
TISR_LOGWARN1(F("add_repeating_timer_us ="), _timerCount);
return true;
}
else
{
TISR_LOGERROR(F("Error. Timer must be 0-3"));
return false;
}
}
// interval (in microseconds) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool setInterval(unsigned long interval, pico_timer_callback callback)
{
return setFrequency((float) (1000000.0f / interval), callback);
}
bool attachInterrupt(float frequency, pico_timer_callback callback)
{
return setFrequency(frequency, callback);
}
// interval (in microseconds) and duration (in milliseconds). Duration = 0 or not specified => run indefinitely
// No params and duration now. To be added in the future by adding similar functions here
bool attachInterruptInterval(unsigned long interval, pico_timer_callback callback)
{
return setFrequency( (float) ( 1000000.0f / interval), callback);
}
void detachInterrupt()
{
cancel_repeating_timer(&_timer);
}
void disableTimer()
{
cancel_repeating_timer(&_timer);
}
// Duration (in milliseconds). Duration = 0 or not specified => run indefinitely
void reattachInterrupt()
{
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
// Duration (in milliseconds). Duration = 0 or not specified => run indefinitely
void enableTimer()
{
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
// Just stop clock source, clear the count
void stopTimer()
{
cancel_repeating_timer(&_timer);
}
// Just reconnect clock source, start current count from 0
void restartTimer()
{
cancel_repeating_timer(&_timer);
add_repeating_timer_us(_timerCount, _callback, NULL, &_timer);
}
int8_t getTimer() __attribute__((always_inline))
{
return _timerNo;
};
}; // class RPI_PICO_TimerInterrupt
#endif // RPI_PICO_TIMERINTERRUPT_H
+81
View File
@@ -0,0 +1,81 @@
/****************************************************************************************************************************
TimerInterrupt_Generic_Debug.h
For RP2040-based boards such as RASPBERRY_PI_PICO, ADAFRUIT_FEATHER_RP2040 and GENERIC_RP2040.
Written by Khoi Hoang
Built by Khoi Hoang https://github.com/khoih-prog/RPI_PICO_TimerInterrupt
Licensed under MIT license
The RPI_PICO system timer peripheral provides a global microsecond timebase for the system, and generates
interrupts based on this timebase. It supports the following features:
• A single 64-bit counter, incrementing once per microsecond
• This counter can be read from a pair of latching registers, for race-free reads over a 32-bit bus.
• Four alarms: match on the lower 32 bits of counter, IRQ on match: TIMER_IRQ_0-TIMER_IRQ_3
Now even you use all these new 16 ISR-based timers,with their maximum interval practically unlimited (limited only by
unsigned long miliseconds), you just consume only one RPI_PICO timer and avoid conflicting with other cores' tasks.
The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timers
Therefore, their executions are not blocked by bad-behaving functions / tasks.
This important feature is absolutely necessary for mission-critical tasks.
Based on SimpleTimer - A timer library for Arduino.
Author: mromani@ottotecnica.com
Copyright (c) 2010 OTTOTECNICA Italy
Based on BlynkTimer.h
Author: Volodymyr Shymanskyy
Version: 1.0.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 11/05/2021 Initial coding to support RP2040-based boards such as RASPBERRY_PI_PICO. etc.
*****************************************************************************************************************************/
#pragma once
#ifndef TIMERINTERRUPT_GENERIC_DEBUG_H
#define TIMERINTERRUPT_GENERIC_DEBUG_H
#ifdef TIMERINTERRUPT_DEBUG_PORT
#define TISR_DBG_PORT TIMERINTERRUPT_DEBUG_PORT
#else
#define TISR_DBG_PORT Serial
#endif
// Change _TIMERINTERRUPT_LOGLEVEL_ to set tracing and logging verbosity
// 0: DISABLED: no logging
// 1: ERROR: errors
// 2: WARN: errors and warnings
// 3: INFO: errors, warnings and informational (default)
// 4: DEBUG: errors, warnings, informational and debug
#ifndef _TIMERINTERRUPT_LOGLEVEL_
#define _TIMERINTERRUPT_LOGLEVEL_ 1
#endif
#define TISR_LOGERROR(x) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGERROR0(x) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print(x); }
#define TISR_LOGERROR1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGERROR2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGERROR3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>0) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGWARN(x) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGWARN0(x) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print(x); }
#define TISR_LOGWARN1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGWARN2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGWARN3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>1) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGINFO(x) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGINFO0(x) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print(x); }
#define TISR_LOGINFO1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGINFO2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGINFO3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>2) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#define TISR_LOGDEBUG(x) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.println(x); }
#define TISR_LOGDEBUG0(x) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print(x); }
#define TISR_LOGDEBUG1(x,y) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(y); }
#define TISR_LOGDEBUG2(x,y,z) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(z); }
#define TISR_LOGDEBUG3(x,y,z,w) if(_TIMERINTERRUPT_LOGLEVEL_>3) { TISR_DBG_PORT.print("[TISR] "); TISR_DBG_PORT.print(x); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(y); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.print(z); TISR_DBG_PORT.print(" "); TISR_DBG_PORT.println(w); }
#endif //TIMERINTERRUPT_GENERIC_DEBUG_H