Rotary encoder with R4 using timer

I played a little bit with the timer on an Arduino Uno R4 Minima and created this little example on how to use GPT162 with a rotary encoder:

/**
 * Example for using a rotary encoder with a timer.
 * 
 * This works with an Arduino Uno R4 Minima
 * 
 * Pin connections:
 * Encoder    Arduino Uno R4 Minima
 *   A          P102 (D5)
 *   B          P103 (D4)
 *   com        GND
 */


#include "FspTimer.h"

FspTimer timer{};

int event = -1;

void isr_GPT162(timer_callback_args_t *p_args) {
  event = static_cast<int>(p_args->event);
}

void setup() {
  //configure P102
  R_PFS->PORT[1].PIN[2].PmnPFS_b.PCR  = 0b1;     // enable pull-up
  R_PFS->PORT[1].PIN[2].PmnPFS_b.PSEL = 0b00011; // pin function GTIOC2B
  R_PFS->PORT[1].PIN[2].PmnPFS_b.PMR  = 0b1;     // use as PSEL

  //configure P103
  R_PFS->PORT[1].PIN[3].PmnPFS_b.PCR  = 0b1;     // enable pull-up
  R_PFS->PORT[1].PIN[3].PmnPFS_b.PSEL = 0b00011; // pin function GTIOC2A
  R_PFS->PORT[1].PIN[3].PmnPFS_b.PMR  = 0b1;     // use as PSEL

  const auto GPT162 = 2;

  timer.force_use_of_pwm_reserved_timer();
  timer.begin(TIMER_MODE_PERIODIC, GPT_TIMER, GPT162, 0x10000, 0, TIMER_SOURCE_DIV_1, isr_GPT162);
  timer.setup_overflow_irq();
  timer.setup_underflow_irq();
  timer.open();

  // configure count up
  R_GPT2->GTUPSR_b.USCAFBL = 0b1;
  R_GPT2->GTUPSR_b.USCARBH = 0b1;
  R_GPT2->GTUPSR_b.USCBRAL = 0b1;
  R_GPT2->GTUPSR_b.USCBFAH = 0b1;

  // configure count down
  R_GPT2->GTDNSR_b.DSCAFBH = 0b1;
  R_GPT2->GTDNSR_b.DSCARBL = 0b1;
  R_GPT2->GTDNSR_b.DSCBRAH = 0b1;
  R_GPT2->GTDNSR_b.DSCBFAL = 0b1;

  timer.start();

  Serial.begin(115200);
}

void loop() {
  if(event != -1){
    Serial.print("Event: ");
    Serial.println(event);
    event = -1;
  }
  auto value = timer.get_counter();
  Serial.println(value);
  delay(1000);
}

For register names and functions take a look at the datasheet:

3 Likes

is there a problem with the code? What is it that needs help?

It works for me.

But when there is something that can be improved, I'd like to hear.

ah ok. I thought that something was amiss somewhere. Your code looks fine to me, but that's not saying much :wink:

I started a library for this:

Any ideas how to get rid of channel2GPT?

1 Like