XIAO nRF52840 fast digitalRead?

Hello everyone !

Please tell me how to make a very fast reading of the pin status (fast ReadDigital) ?
I use the mbed-enabled board core.

Try this.

void setup()

  pinMode(P0_3, INPUT_PULLUP);  //D1(P0.03) connected SW

void loop()
  uint32_t REPEAT = 1000000;
  uint32_t timestamp = millis();
  int x;
  for(uint32_t i = 0; i < REPEAT; i++) {
    x = (nrf_gpio_port_in_read(NRF_P0) >> 3) & 1UL;
//    x = digitalRead(P0_3);
  Serial.println(millis() - timestamp);

Hi there,
So in an effort to understand :nerd_face: this code segment, is it the speed in between each read or the burst of reads that make it fast or is it the index or shift that does it addressing the port number? Please explain this code and logic if you can, Thank you very much
You always deliver the cleanest code, TY
GL :slight_smile: PJ :v:

Hi PJ,
I don’t know what @NRF52 means by “fast ReadDigital”, but the sketch is the result of cutting down on the overhead of resolving pin names in the digitalRead() function in order to increase throughput.
Or perhaps the @NRF52 wants a quick response (low latency) like an interrupt.

1 Like

Hi !

I need this to work with an optical incremental encoder (3600 pulses per revolution) . When digitalRead is slow, skips occur when the encoder rotates rapidly. And I need to solve this problem

I do it through an interruption ( attachInterrupt)

void encIsr()  


  curState = digitalRead(ENC_A) | digitalRead(ENC_B) << 1;  // digitalRead 

  if (resetFlag && curState == 0b11) {

    if (prevState == 0b10) {


      if (encCounter >= 250) {

        encCounter = 0;




    if (prevState == 0b01) {


      if (encCounter <= -250) {

        encCounter = 0;




    resetFlag = 0;

    flag = true;


  if (curState == 0b00) resetFlag = 1;

  prevState = curState;


If the MPU executes a lot of code in an interrupt routine, could it miss the next interrupt?
What is the maximum frequency of the pulses from the encoder? (How much time is allowed between reading the encoder status and finishing the process?)

Tell me how to rewrite this line of code using nrf_gpio_port_in_read. I use pins P0.2 and P0.3. I want to check how fast it will work.

curState = ((nrf_gpio_port_in_read(NRF_P0) >> 2) & 1UL) | ((nrf_gpio_port_in_read(NRF_P0) >> 3) & 1UL) << 1;
1 Like

Great! It works very well! Very fast!

msfujino !
Thank you so much for your help !

Can you also tell me how to manage quickly in the same way, instead of the digitalWrite(P0.2, HIGH) and digitalWrite(P0.2, LOW) command ?

Below are some functions that may be used. Please try it out.
nrf_gpio_port_out_set() or nrf_gpio_port_out_clear()

See the file below for details.

See also the following sections of the datasheet
6.9.2 Registers

The BEST !
Thanks !!!