Monitoring pins internally

I am using the PWM to generate a 40kHz signal for an ultrasonic application like this -

TCCR2A = _BV (WGM20) | _BV (WGM21) | _BV (COM2B1); // fast PWM, clear OC2B on compare
  TCCR2B = _BV (WGM22) | _BV (CS21);         // fast PWM, prescaler of 8
  OCR2A =  ((F_CPU / 8) / frequency) - 1;    // zero relative  
  OCR2B = ((OCR2A + 1) / 2) - 1;             // 50% duty cycle

I want to detect the phase shift between the transmitted and received signal, so I want to be able to detect the state of the PWM pin. Is there any way of doing this internally? It seems a bit daft to have to connect the PWM pin to another pin just to know the state of the PWM pulse (and I’m running out of pins and I have a 328 based board and for various reasons I don’t want to go up to a 1280 or whatever)

(PIND & (1 << PIND3))

Thanks, never thought of trying that

You are welcome.

The first diagram under the Ports as General Digital I/O shows why it will work. The input synchronizer is connected to the world side of the pin after the output driver. An AVR processor is able to read a pin's state regardless of what's driving the pin.

That's good to know, thanks again