Digital input

Dear All,

I am trying to read a digital input and I want to read it at 1000 Hz.

Is it feasible? Can anyone share a sample code to do that?

Thanks a lot,
Samuele

Have you wanted to say that you wish to read 1-bit data from an input digital line at 1000 times in one second time period? If so, there are complexities:

If you read an input-pin and find it at Logic-High state, you must wait until the port-pin assumes Logic-Low state. You must have provision to measure the duration times of the High and Low states of the port-pin. This way, you can determine the frequency at which the port-pin is changing its states. To say in other words – you can measure the frequency of an unknown signal present at the said port-pin.

I am trying to read a digital input and I want to read it at 1000 Hz.

Yes, absolutely no problem. It might get a problem if you need to do more than just reading it but that wasn't your question.

Can anyone share a sample code to do that?

void setup() {
  pinMode(2, INPUT);
}

void loop() {
  uint8_t value = digitalRead(2);
}

“I am trying to read a digital input and I want to read it at 1000 Hz.”
Why?

You may start reading bounces.

pylon:

void setup() {

pinMode(2, INPUT);
}

void loop() {
  uint8_t value = digitalRead(2);
}

This code will read the pin at a far greater frequency than OP asked for (I guess it’ll get to a frequency of 0.1-1 MHz), and that is assuming the line doesn’t get optimised out for not doing anything useful.

This is more what OP is asking for, it will read the pin 1,000 times per second:

void loop() {
  static uint32_t latestRead;
  if (micros() - latestRead > 1000) {
    uint8_t value = digitalRead(2);
    latestRead += 1000;
  }
}