Using digitalRead() for checking when PWM is HIGH or LOW

PaulS:
A PWM pin toggles between HIGH and LOW faster than digitalRead() can react. Even if it didn't, what do you think you will learn from knowing whether the pin is HIGH or LOW at the moment you read it?

Paul, a PWM pin toggles at about 490Hz unless you change the PWM frequency, which means you can read its state many times in a single cycle.

The reason that the OP wants to read the state (as described in a thread elsewhere on the forum) is that he is using the PWM pin to generate a square wave, and he wants to measure the amplitude of a square wave derived from it. So he wants to synchronize analogRead calls to the state changes.

Peter, I'm seeing the same problem. Reading the datasheet, it looks like the data in buffers are disabled when certain pins are used for alternate functions such as PWM. I can think of a few ways round this:

  1. If you have a spare pin, connect it to the PWM pin and digitalRead the value from that pin.

  2. Configure the timer/counter that generates the PWM signal to generate an interrupt on the state change, and synchronize the analogRead calls to that interrupt.

  3. Don't bother synchronizing the analogRead calls, just take a number of readings (say over 100ms), and take the difference between the highest and lowest as the signal amplitude.