Line sensor code (untested).

But at least it properly measures how long pin is held high for.