Code Monkey home page Code Monkey logo

khoih-prog / nrf52_mbed_timerinterrupt Goto Github PK

View Code? Open in Web Editor NEW
13.0 2.0 2.0 219 KB

This library enables you to use Interrupt from Hardware Timers on an NRF52-based board using mbed-RTOS such as Nano-33-BLE. These nRF52 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.

License: MIT License

C++ 94.01% C 5.94% Shell 0.05%
hardware-timers isr timerinterrupt-libraries arduino-libraries non-blocking mission-critical timerinterrupt timerinterrupt-library mbed accuracy

nrf52_mbed_timerinterrupt's Issues

Issue w/ AnalogRead in Interrupt

Hi Khoi,
Thanks for writing and sharing this timer interrupt library.
I am trying to implement consistently spaced sampling on a Nano33BLE, but the board seems to crash whenever I have a call to analogRead within the ISR.

Arduino IDE version: 1.8.13
Arduino mbed Nano Core Version 2.4.1
OS: Windows 10

Minimal code is below. I have also tried with an Adafruit nrf52 board and your other version of the library. This seems to work, but only if interrupts are halted before the analogRead call and enabled afterwards.

Working on native Nordic SDK firmware, but it would be great to accelerate prototyping with your library!

// test of timer ADC functionality

#include "NRF52_MBED_TimerInterrupt.h"

#define MOTOR_PIN P0_27 // 9u, D9
#define OPTO_PIN P0_21 // 8u, D8
#define FIELD_MILL_PIN P0_5 // 15u, A1

#define SAMPLE_INTERVAL 500
#define BLE_INTERVAL 10000

NRF52_MBED_Timer sample_timer(NRF_TIMER_4);
NRF52_MBED_Timer ble_timer(NRF_TIMER_3);

volatile int idx;
volatile unsigned long times[20] = {};
volatile int readings[20] = {};
volatile int fm_output = 0;

unsigned long t_now; // start time for current loop
unsigned long t_last_sample = 0;
unsigned long sample_delay = 5000;
unsigned long t_last_print = 0;
unsigned long print_delay = 500E3;

void setup() {
// put your setup code here, to run once:

Serial.begin(57600);

analogReadResolution(12);

sample_timer.attachInterruptInterval(SAMPLE_INTERVAL, SampleTimerFunc);
ble_timer.attachInterruptInterval(BLE_INTERVAL, BleTimerFunc);

}

void loop() {
// put your main code here, to run repeatedly:

t_now = micros();
// if (t_now - t_last_sample > sample_delay)
// {
// t_last_sample = t_now;
// times[idx] = micros();
// readings[idx] = analogRead(FIELD_MILL_PIN);
// idx++;
// if (idx >= 20)
// {
// idx = 0;
// }
// }

// Print debug data
if (t_now - t_last_print > print_delay)
{
t_last_print = t_now;
Serial.println(fm_output);
for (int i = 0; i < 20; i++)
{
Serial.print(times[i]);
Serial.print("\t");
}
Serial.println();
for (int i = 0; i < 20; i++)
{
Serial.print(readings[i]);
Serial.print("\t");
}
Serial.println();
}
}

void SampleTimerFunc()
{
times[idx] = micros();
// noInterrupts();
readings[idx] = analogRead(FIELD_MILL_PIN);
// interrupts();
// readings[idx] = 200;

idx++;
if (idx >= 20)
{
idx = 0;
}
}

void BleTimerFunc()
{
int total = 0;
for (int i = 0; i < 20; i++)
{
total += readings[i];
}
fm_output = (int)(76.0 * (double)total / 20.0);
}

analogRead

I tried using the Argument_None Example that you have on Ardiuno Nano 33 Sense and it worked perfectly fine.
The issue is whenever I add a analogRead within any of the Interrupt Service Routines the program will freeze after the first printResult function. To even upload a new sketch the Ardiuno Nano 33 Sense has to be but into bootloader mode.

NRF52_MBED_Timer's TimerHandler delay

// Arduino Nano 33 BLE

#define TIMER_INTERRUPT_DEBUG         0
#define _TIMERINTERRUPT_LOGLEVEL_     0
#define HW_TIMER_INTERVAL_MS      1

#include "NRF52_MBED_TimerInterrupt.h"
#include "NRF52_MBED_ISR_Timer.h"

NRF52_MBED_Timer ITimer(NRF_TIMER_3);

// Init NRF52 timer NRF_TIMER3
NRF52_MBED_Timer ITimer(NRF_TIMER_3);
// Init NRF52_MBED_ISRTimer
// Each NRF52_MBED_ISRTimer can service 16 different ISR-based timers
NRF52_MBED_ISRTimer ISR_Timer;

#define TIMER_INTERVAL_1s    1000L

volatile static unsigned int count = 0;
void TimerHandler() {
    count += 1;
    if (count % 100000 == 0) // **** should happen every 1 sec? - does not work
        digitalWrite(LED_PWR, !digitalRead(LED_PWR)); 
    ISR_Timer.run();
}


void onTimer1s() { // once per 1 sec. - it works
     digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
   }


void setup() {
    // Interval in microsecs
    if (ITimer.attachInterruptInterval(HW_TIMER_INTERVAL_MS * 1000/100, TimerHandler)) {  // **** every 10 us?
        // Serial.print(F("Starting ITimer OK, millis() = ")); Serial.println(millis());
    } else {
       //  Serial.println(F("Can't set ITimer. Select another freq. or timer"));
    }
    ISR_Timer.setInterval(TIMER_INTERVAL_1s, onTimer1s); 
 }


void loop() {
}

For some reason LED_PWR blink are about twice as slow... onTimer1s works as expected.

Nano 33 BLE will not run library examples using NRF_TIMER_1

Arduino IDE 1.8.15
mbed nano 2.4.1 core
Board selection "Arduino Nano 33"
NRF52_MBED_TimerInterrupt v1.2.1

Library example files (e.g. Argument_None) run as expected with the use of Timer3 and Timer4. Most of the example programs are written for these two timers,

The library states

Depending on the board, you can select NRF52 Hardware Timer from NRF_TIMER_1,NRF_TIMER_3,NRF_TIMER_4 (1,3 and 4)
//If you select the already-used NRF_TIMER_0 or NRF_TIMER_2, it'll be auto modified to use NRF_TIMER_1

In library example Argument_None, if either Timer3 or Timer4 is changed to Timer1, the led will not flash and the timer count does not increment.

Is there an issue with the implementation of Timer1 on the Nano33 Ble?

/****************************************************************************************************************************
  Argument_None.ino
  For NRF52 boards using mbed-RTOS such as Nano-33-BLE
  Written by Khoi Hoang

  Built by Khoi Hoang https://github.com/khoih-prog/NRF52_MBED_TimerInterrupt
  Licensed under MIT license

  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 NRF52 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: [email protected]
  Copyright (c) 2010 OTTOTECNICA Italy

  Based on BlynkTimer.h
  Author: Volodymyr Shymanskyy

  Version: 1.2.1

  Version Modified By   Date      Comments
  ------- -----------  ---------- -----------
  1.0.1   K Hoang      22/11/2020 Initial coding and sync with NRF52_TimerInterrupt
  1.0.2   K Hoang      23/11/2020 Add and optimize examples
  1.1.1   K.Hoang      06/12/2020 Add Change_Interval example. Bump up version to sync with other TimerInterrupt Libraries
  1.2.0   K.Hoang      11/01/2021 Add better debug feature. Optimize code and examples to reduce RAM usage
  1.2.1   K.Hoang      04/05/2021 Add mbed_nano to list of compatible architectures
*****************************************************************************************************************************/

/*
   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 !( ARDUINO_ARCH_NRF52840 && TARGET_NAME == ARDUINO_NANO33BLE )
  #error This code is designed to run on nRF52-based Nano-33-BLE boards using mbed-RTOS platform! Please check your Tools->Board setting.
#endif

// These define's must be placed at the beginning before #include "NRF52TimerInterrupt.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
// For Nano33-BLE, don't use Serial.print() in ISR as system will definitely hang.
#define TIMER_INTERRUPT_DEBUG         1
#define _TIMERINTERRUPT_LOGLEVEL_     0

#include "NRF52_MBED_TimerInterrupt.h"

//#ifndef LED_BUILTIN
//  #define LED_BUILTIN         D13
//#endif

#ifndef LED_BLUE_PIN
  #define LED_BLUE_PIN          D7
#endif

#ifndef LED_RED_PIN
  #define LED_RED_PIN           D8
#endif

#define TIMER0_INTERVAL_MS        500   //1000
#define TIMER1_INTERVAL_MS        2000

volatile uint32_t Timer0Count = 0;
volatile uint32_t Timer1Count = 0;

// Depending on the board, you can select NRF52 Hardware Timer from NRF_TIMER_1,NRF_TIMER_3,NRF_TIMER_4 (1,3 and 4)
// If you select the already-used NRF_TIMER_0 or NRF_TIMER_2, it'll be auto modified to use NRF_TIMER_1

// Init NRF52 timer NRF_TIMER1
//NRF52_MBED_Timer ITimer0(NRF_TIMER_4);
NRF52_MBED_Timer ITimer0(NRF_TIMER_1);

// Init NRF52 timer NRF_TIMER3
NRF52_MBED_Timer ITimer1(NRF_TIMER_3);
//NRF52_MBED_Timer ITimer1(NRF_TIMER_1);

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);
}

void TimerHandler0()
{
  static bool toggle0 = false;

  // Flag for checking to be sure ISR is working as SErial.print is not OK here in ISR
  Timer0Count++;

  //timer interrupt toggles pin LED_BUILTIN
  digitalWrite(LED_BUILTIN, toggle0);
  toggle0 = !toggle0;
}

void TimerHandler1()
{
  static bool toggle1 = false;

  // Flag for checking to be sure ISR is working as Serial.print is not OK here in ISR
  Timer1Count++;
  
  //timer interrupt toggles outputPin
  digitalWrite(LED_BLUE_PIN, toggle1);
  toggle1 = !toggle1;
}

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(LED_BLUE_PIN, OUTPUT);
  
  Serial.begin(115200);
  while (!Serial);

  delay(100);

  Serial.print(F("\nStarting Argument_None on ")); Serial.println(BOARD_NAME);
  Serial.println(NRF52_MBED_TIMER_INTERRUPT_VERSION);
 
  // 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

void loop()
{
  static uint32_t lastTime = 0;
  static uint32_t currTime;

  currTime = millis();

  if (currTime - lastTime > CHECK_INTERVAL_MS)
  {
    printResult(currTime);
    lastTime = currTime;
  }
}

Procedure For Installing MBED 1.3.2

I'm using a Nano 33 BLE, and the Arduino IDE.

I know that Timer 1 doesn't work for the latest MBED versions, which I discovered myself before reading other peoples reports.

Therefore, I have two questions...

  1. Please describe the procedure for installing MBED 1.3.2 (and will this then mean that timer 1 will work after doing this?)

  2. Does this library make use of all 16 bit timers, e.g., will 10 micro seconds (or even lower, perhaps 1) be accurate? like when setting registers directly, as demonstrated in various AVR examples.

Thank you, Gary.

Edit 1: ah! so for micro second precision we need the following maybe...

#include <hal/nrf_timer.h>
#include <hal/nrf_gpiote.h>
#include <hal/nrf_gpio.h>
#include <hal/nrf_ppi.h>

Please kindly confirm if this library uses the above for the Nano 33 BLE?

Edit 2: my sincere apologies for editing again, but I'm trying to understand the fundamentals...

NRF52840 Timers... "5ร—32 bit 16MHz Timer"

So for the Nano 33 BLE... is this correct? so potentially extremely accurate via using the GPIOTE.

Edit 3: the timers are listed in the 1st table on this page as well Nordic's NRF52 Timer Info

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.