Speed of digitalRead

Ive got some data which is a pulsing wave of 0s and 1s at a a freq of 20khz. A time period of 50us. I want to use digital read to read each bit and process it. However it seems to be to quick the arduino cant read successfully for a time period less than about 1ms. How can I increase the speed ?

Many Thanks.

You can read the ports directly, but your code will be less portable.
Google "AVR port manipulation"

That would very much depend on what you mean by "process it".

AWOL:
You can read the ports directly, but your code will be less portable.
Google "AVR port manipulation"

Right thanks. My research tells me that means ditching the avr libraries and going into the c which is fine. But how does that mean the speed I can read the digital data will increase ?

But how does that mean the speed I can read the digital data will increase ?

Most of the time take by digitalRead/digitalWrite is taken up mapping the pin and port to a consistent Arduino scheme, but the actual eight bit wide port read or write is a single 62.5ns instruction cycle long.

const byte led = 13;
const byte button = 2;

void setup()
{                
  pinMode(led, OUTPUT);
  pinMode(button,INPUT_PULLUP);
}

void loop()
{
  PINB  = B00100000; //Toggle 13                (high)
  PINB  = B00100000; //Toggle 13  From this edge (low)
  PIND  & B00000100; //Read D2    120nS
  PINB  = B00100000; //Toggle 13  to this edge. (high)
  
  PINB  = B00100000; //Toggle 13  From this edge (low)
  digitalRead(2);    //Read D2    3.75uS
  PINB  = B00100000; //Toggle 13  to this edge. (high)
  PINB  = B00100000; //Toggle 13                (low)
  delay(100);
}

I haven't measured it in a while but the digitalRead() function is about 5us on typical 16Mhz AVR.
The 1ms time is believable if you are trying to process the bits in real time in a foreground vs using interrupts to process the transitions.

If you get a Teensy product it has a much better implementation of digitalRead() that will automatically use raw port i/o if the pin is a compile time constant so the read is 62.5ns.
This is an optimization that the Arduino Team has faught against doing for years.

The faster speed of doing raw port i/o will help but may not solve the problem depending on how you write your code to process the signal.
The best and most reliable way to process something like that will be to split the task up and use interrupts.
Use interrupts for the real time processing of the signal and then have the foreground process the status/state information from the ISR.

Given your clock speed is only 20khz you might be able to use the standard digitalRead() once you split the task between foreground and background ISR.

--- bill