Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <xc.h> //PIC hardware mapping
- #include<pic16f1829.h>
- #define _XTAL_FREQ 500000 //Used by the XC8 delay_ms(x) macro
- //totale stap cycle van 256 stappen duurt 8 seconde elke stap duurt dus 32 miliseconde elke instrucite duurt 0,008 mili seconde 32/0,008 = 4000 stappen nodig maar de timer heeft maar 255 stappen dus gebruik maken van post of pre scalar.dus een scalar van 1:16.
- #define vertraging32 60500 //= 32000 (milisec) / 16 (want prescalar = 1:2 en 65536 (2^16) - 2000 = 63536)
- //config bits that are part-specific for the PIC16F1829
- #pragma config FOSC=INTOSC, WDTE=OFF, PWRTE=OFF, MCLRE=OFF, CP=OFF, CPD=OFF, BOREN=ON, CLKOUTEN=OFF, IESO=ON, FCMEN=ON
- #pragma config WRT=OFF, PLLEN=OFF, STVREN=OFF,BORV = LO, LVP=OFF
- typedef enum {
- dim,
- fel,
- noppes
- } knop;
- unsigned int index = 0;
- volatile knop vroeger = dim;
- volatile knop nu = noppes;
- void init(void) {
- //setup clock
- OSCCON = 0b00111000; //500KHz clock speed
- //set up leds
- TRISC = 0; //all LED pins are outputs
- LATC = 0;
- //set up button
- TRISAbits.TRISA2 = 1; //switch as input
- ANSELAbits.ANSA2 = 0; //digital switch
- //setup the PWM
- CCP2CON = 0b00001100; //PWM mode single output
- PR2 = 255; //Frequency at 486Hz. Anything over ~60Hz will get rid of any flicker
- //PWM Period = [PR2 + 1]*4*Tosc*T2CKPS = [255 + 1] * 4 * (1 / 500KHz) * 1
- CCPTMRSbits.C2TSEL = 0b00; //select timer2 as PWM source
- T2CONbits.T2CKPS = 0b00; //1:1 prescaler
- T2CONbits.TMR2ON = 1; //start the PWM
- //setup TIMER1 as the delay
- T1CON = 0x10; // Fosc/4, prescaler 1:2, tmr1 of
- //1:256 prescaler for a delay of: (insruction-cycle * 256-counts)*prescaler = ((8uS * 256)*256) =~ 524mS
- TMR1IE = 1;
- PIE1bits.TMR1IE = 1; //enable the TMR4 rollover interrupt
- PIR1bits.TMR1IF = 0;
- //setup interrupt on change for the switch
- INTCONbits.IOCIE = 1; //enable interrupt on change global
- IOCANbits.IOCAN2 = 1; //when SW1 is pressed, enter the ISR
- PEIE = 1;
- GIE = 1; //enable global interupt
- }
- void __interrupt() ISR() {
- if (PORTAbits.RA2 == 0 && IOCAFbits.IOCAF2 == 1) {
- IOCAFbits.IOCAF2 = 0; //flag = clear
- if (vroeger == dim) {
- vroeger = fel;
- nu = fel;
- } else {
- vroeger = dim;
- nu = dim;
- }
- } else if (PORTAbits.RA2 == 1 && IOCAFbits.IOCAF2 == 1) {
- IOCAFbits.IOCAF2 = 0;
- nu = noppes;
- }
- if (PIR1bits.TMR1IF == 1) {
- PIR1bits.TMR1IF = 0;
- TMR1 += vertraging32;
- switch (nu) {
- case noppes:
- break;
- case dim:
- if (index > 0) {
- index--;
- }
- break;
- case fel:
- if (index < 255) {
- index++;
- }
- break;
- }
- }
- CCPR2L = ((PWM_Lookup[index] >> 2) & 0xFF);
- CCP2CONbits.DC2B = ((PWM_Lookup[index] >> 8) & 0x03);
- }
- void main() {
- init();
- while (1) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement