nerdegutta.no
PIC12F1822 - Fade an LED in and out
03.01.25
Embedded
This program fades an LED in and out. The LED is connected to RA4.
// INCLUDE LIBRARIES #include < xc.h > // CONFIGURATION BITS // CONFIG1 #pragma config FOSC = INTOSC // Oscillator Selection (INTOSC oscillator: I/O function on CLKIN pin) #pragma config WDTE = OFF // Watchdog Timer Enable (WDT enabled) #pragma config PWRTE = OFF // Power-up Timer Enable (PWRT disabled) #pragma config MCLRE = ON // MCLR Pin Function Select (MCLR/VPP pin function is MCLR) #pragma config CP = OFF // Flash Program Memory Code Protection (Program memory code protection is disabled) #pragma config CPD = OFF // Data Memory Code Protection (Data memory code protection is disabled) #pragma config BOREN = ON // Brown-out Reset Enable (Brown-out Reset enabled) #pragma config CLKOUTEN = OFF // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin) #pragma config IESO = ON // Internal/External Switchover (Internal/External Switchover mode is enabled) #pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is enabled) // CONFIG2 #pragma config WRT = OFF // Flash Memory Self-Write Protection (Write protection off) #pragma config PLLEN = ON // PLL Enable (4x PLL enabled) #pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset) #pragma config BORV = LO // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.) #pragma config DEBUG = OFF // In-Circuit Debugger Mode (In-Circuit Debugger disabled, ICSPCLK and ICSPDAT are general purpose I/O pins) #pragma config LVP = ON // Low-Voltage Programming Enable (Low-voltage programming enabled) #define _XTAL_FREQ 4000000 // Reference frequency for the compiler #define led PORTAbits.RA4 // Assign the LED to RA4 void main(void) { // Configure RA4 as output TRISA4 = 0; // Set RA4 as output ANSA4 = 0; // Disable analog input on RA4 led = 0; // Initialize RA4 to low OSCCONbits.IRCF = 0b1101; // Internal oscillator set to 4MHz unsigned char brightness = 0; unsigned char direction = 1; // 1 for increasing, 0 for decreasing while (1) { for (int i = 0; i < 255; i++) { if (direction) { brightness++; } else { brightness--; } // Apply PWM manually for (int j = 0; j < 255; j++) { if (j < brightness) { led = 1; } else { led = 0; } __delay_us(10); // Short delay for pseudo-PWM cycle } } // Reverse direction at max or min brightness if (brightness == 255 || brightness == 0) { direction = !direction; } } }