Hi all,
i am trying to use PWM to fade one or mode RGB leds using a PIC 16F648A. I use SDCC and PikLab. Here's the code:
PWM code seems to work (it' in an embrional stage) *but* the interrupt is too slow, so i can see leds blink instead of stable color. Maybe i have to use Timer1 or Timer2 ?
Thanks, O-Zone
i am trying to use PWM to fade one or mode RGB leds using a PIC 16F648A. I use SDCC and PikLab. Here's the code:
Code:
#include <pic16f648a.h>
/* ----------------------------------------------------------------------- */
/* Configuration bits: adapt to your setup and needs */
typedef unsigned int word;
word at 0x2007 CONFIG = _WDT_OFF & _PWRTE_OFF & _INTOSC_OSC_NOCLKOUT & _MCLRE_ON & _BOREN_ON & _LVP_OFF & _DATA_CP_OFF & _CP_OFF;
#define setBit(var, bitnum) (var)|=(1<<(bitnum))
#define resBit(var, bitnum) (var)&=~(1<<(bitnum))
#define clearBit(var, bitnum) (var)&=~(1<<(bitnum))
#define testBit(var, bitnum) (var)&(1<<(bitnum))
void delay(long ms) {
long i;
while (ms--) {
for (i=0; i < 230; i++) {
__asm nop __endasm;
}
}
}
#define LEDA RB3
#define LEDA_TRIS TRISB3
#define LEDA_RED RB0
#define LEDA_RED_TRIS TRISB0
#define LEDA_GREEN RB1
#define LEDA_GREEN_TRIS TRISB1
#define LEDA_BLUE RB2
#define LEDA_BLUE_TRIS TRISB2
/* RGB PWM Channels */
unsigned short pwmChans[3] = {1,80,160}, pwmState[3], pwmPin[3]={0,1,2};
char *pwmPort;
unsigned short timerTick=0,portShadow=0;
void doPwm() {
unsigned short i;
for(i=0;i<3;i++) {
if(timerTick == 0 && pwmChans[i] != 0) { // reset at start.
setBit(portShadow, pwmPin[i]);
*pwmPort=portShadow;
pwmState[i] = 0;
} else if(timerTick == pwmChans[i] && pwmChans[i] != 255) { // set at duty.
resBit(portShadow, pwmPin[i]);
*pwmPort=portShadow;
pwmState[i] = 1;
}
}
}
static void Intr(void) interrupt 0 { /* interrupt service routine */
timerTick++;
if(timerTick >= 254) timerTick=0;
doPwm();
T0IF = 0;
}
void main() {
OSCF=1; /* 4 MHz CLock */
CMCON = 0x07;
CCP1CON=0x00;
/* Set LED driver's line as OUT */
LEDA_TRIS = 0;
LEDA_RED_TRIS = 0;
LEDA_GREEN_TRIS = 0;
LEDA_BLUE_TRIS = 0;
/* Turn all LEDs OFF */
LEDA_RED = 1;
LEDA_GREEN = 1;
LEDA_BLUE = 1;
/* Setup PWM */
pwmPort = (char *)&PORTB;
portShadow = PORTB;
/* Enable Timer0 */
T0CS = 0; // Clear to enable timer mode.
PSA = 0; // Clear to assign prescaler to Timer 0.
PS2 = 0; // Set up prescaler to 1:256.
PS1 = 0;
PS0 = 0;
INTCON = 0; // Clear interrupt flag bits.
GIE = 1; // Enable all interrupts.
T0IE = 1; // Set Timer 0 to 0.
TMR0 = 0; // Enable peripheral interrupts.
while(1) {
}
}
PWM code seems to work (it' in an embrional stage) *but* the interrupt is too slow, so i can see leds blink instead of stable color. Maybe i have to use Timer1 or Timer2 ?
Thanks, O-Zone