PIC Microcontroller C Programming Examples
Practical 1: LED Blinking Patterns
#include <xc.h>
#define _XTAL_FREQ 20000000
#pragma config FOSC = HS, WDTE = OFF, PWRTE = ON, LVP = OFF
void delay_ms(unsigned int time) {
while(time--) __delay_ms(1);
}
void main(void) {
ANSEL = 0x00; ANSELH = 0x00;
TRISB = 0x00; PORTB = 0x00;
while(1) {
PORTB = 0xFF; delay_ms(500);
PORTB = 0x00; delay_ms(500);
PORTB = 0xAA; delay_ms(500);
PORTB = 0x55; delay_ms(500);
}
}Practical 2: DC Motor Control
#include <xc.h>
#pragma config WDTE = OFF, LVP = OFF
void myMsDelay(unsigned int time) {
unsigned int i, j;
for(i = 0; i < time; i++) for(j = 0; j < 710; j++);
}
void main() {
ANSEL = 0x00; ANSELH = 0x00;
TRISCbits.TRISC0 = 0; TRISCbits.TRISC1 = 0; TRISCbits.TRISC2 = 0;
while(1) {
PORTCbits.RC0 = 1; PORTCbits.RC1 = 0; PORTCbits.RC2 = 1; myMsDelay(2000);
PORTCbits.RC0 = 0; PORTCbits.RC1 = 0; PORTCbits.RC2 = 0; myMsDelay(2000);
PORTCbits.RC0 = 0; PORTCbits.RC1 = 1; PORTCbits.RC2 = 1; myMsDelay(2000);
PORTCbits.RC0 = 0; PORTCbits.RC1 = 0; PORTCbits.RC2 = 0; myMsDelay(2000);
}
}Practical 3: LCD Interfacing
#include <xc.h>
#define _XTAL_FREQ 8000000
#define LCD_DATA PORTD
#define rs RE0
#define rw RE1
#define en RE2
// Functions: init_LCD, LCD_command, LCD_data, LCD_write_string, msdelay
// Implementation details for 16x2 LCD in 8-bit mode provided.Practical 4: External Interrupts
void __interrupt() switch_isr(void) {
if (INTCONbits.INTF == 1) {
PORTBbits.RB2 = ~PORTBbits.RB2;
msdelay(200);
INTCONbits.INTF = 0;
}
}Practical 5 & 6: DMX Data Arrays
These headers define DMX frame data for lighting control applications.
Practical 7: 7-Segment Display Counter
unsigned char seg_code[10] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};
// Loop through array to display digits 0-9 on PORTBPractical 8: PWM Motor Speed Control
Utilizes the CCP1 module to generate Pulse Width Modulation for variable motor speed control.
