My second project using a Pic microcontroller was controlling the brightness of a LED using an ultrasonic range sensor. when an object was close to the sensor the LED was dimly lit and as the object moved away the LED got brighter.
Link to code: Sensor
For this project I learned how pulse width modulation worked and how to operate the SRF05 ultrasonic range sensor. I decided that since the pic18F1220 had a built in PWM module, I would learn how to use that.
In order to generate a pulse width modulation the pic microcontroller uses a timer and compares the timer value to two other registers. One of the registers (PR2 in the 18F1220) is the value at which the timer resets. This value is related to the period of the pwm waveform. The other register (CCPR1L in the 18F1220) is the duty cycle. When the timer is less than this value, the waveform is high. Otherwise the waveform is low. When CCPR1L is equal to PR2 the duty cycle is 100%.
The SRF05 creates a pulse who’s length is proportional to the distance an object is from the sensor. In order to begin the distance measurement the SRF05 needs a 10us trigger pulse. The SRF05 then measures the distance and outputs a pulse that is between 100us and 25ms. Measuring the pulse can be done by waiting for the output line of the SRF05 to go high, then setting up a timer with an appropriate prescaler to run until the line goes low. Once the pulse is over the timer value is read and can be mathematically manipulated to get the distance. The SRF05 recommends waiting 50ms before getting another measurement so the previous ultrasonic pulse doesn’t interfere. Documentation on the SRF05 can be found here
For this project I used a simple loop where I got the distance from the SRF05 then moved the timer value into CCPR1L. I then waited for 50ms before getting the distance again. The led was hooked up to the output of the pwm wave. The pulse widht modulation controlled the brightness of the led.