Wednesday, July 30, 2008

LED (OIL) LAMP

This time I am using another PIC, 16F628, which is better than 16F84 in number of ways. It has internal Oscillator, more IO pins, PWM, more space (twice) etc. As my first program with 16F628, I wrote this quick and dirty code segment to simulate an oil lamp. It uses the built in PWM to change the duty cycle of the LED.

Here is the video



Here is the code in MikroC

unsigned short j, oj,i;

void InitMain() {


PORTB = 0x0; // set PORTB to 0
TRISB = 0; // designate PORTBpins as output
PWM_Init(5000); // initialize PWM module
}//~

void main() {
CMCON=7;

initMain();

j = 127; // initial value for j
oj = 0; // oj will keep the 'old j' value
PWM_Start(); // start PWM

while (1) { // endless loop

j=rand(); // Generate Random Number
if (j>=255)
j=254;

if (j==0)
j=1;

if (j>oj)
{
for (i=oj;i<=j;i++)
PWM_Change_Duty(i); //Smoothen the level change
}
else
if (j {
for (i=oj;i>=j;i--)
PWM_Change_Duty(i);
}
else
PWM_Change_Duty(j); // set new duty ratio,

oj = j; // memorize it
PORTB = oj; // and display on PORTB

Vdelay_ms(200+j); // slow down change pace a little
}
}//~!

No comments: