in circuit u need ADC also ....and interface it to the controller ..Apply the above algorithm as given by ljcox .
from the programming angle it will be easier if you make use of the interrupts external.
---------- Post added at 23:49 ---------- Previous post was at 23:31 ----------