I was looking for a cheap way (not necessarily as accurate) to replace the Sharp GP2D12 or alike sensor that I can't find in my country. Here's what I have found:
The simplest sensor can be made using an IR LED powered by a PWM signal and a maching frequency IR decoder like the PNA4602 (38kHz).
The ATmega8 has 3 PWM signal generators, 2 of them using Timer1 and one of them using Timer2. If you use the first 2 for motor controll (to accelerate, decelerate or PID) there is only Timer2 that remains. Now this timer is only 8 bit and the highest frequency that can generate is given by the formula:
PWM_frequency = Clock_frequency / 256
That means to get a 38kHz signal you will need a crystal of 9.8MHz for your mc. OR, for 36kHz, a crystal of 9.216MHz, or for 40kHz, a crystal of 10.240MHz.
To generate the signal, you have to configure Timer2 to work as PWM generator with prescale = 1, compare pwm = clear up, pwm = on. Then you have to specify the value for the OCR2 register, which sets the duty cycle (128 for 50% duty cycle).
Here is the tricky part. The "on" time of the duty cycle will make the IR LED light up more or less, depending of the value you set. If the LED has more power, the light will reach further, so objects will be detected at a greater distance. All you have to do is set a high value for the duty cycle, take a measurement, if object found, set a lower value, take another measurement and so on, until you have no reflection. Then you can determine approximately the distance an object can be. However this is dependand on the reflecting caracteristics of the object, but in a certain environment (maze for instance) it can be enough.
I am not a programmer, so I don't know to code all this in C. I work mostly in Bascom for my needs and I didn't find the need to change it yet. But I'm sure someone will help you get the code done if needed.