// PIC18 in C - Versione 0.3 - Dicembre 2014 // Copyright (c) 2014, Vincenzo Villa // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/PIC18/hello-2.htm // Reference: PIC18F2431 data sheet // [1] REGISTER 3-2: OSCCON: OSCILLATOR CONTROL REGISTER - Page 36 // [2] PORTB, TRISB and LATB Registers - Page 116 // [3] REGISTER 10-2: INTCON2: INTERRUPT CONTROL REGISTER 2 - Page 100 // [4] PORTC, TRISC and LATC Registers - Page 119 #include "configurationsbits.h" #define _XTAL_FREQ 31250 // CPU clock: 31.250 kHz [1] #define MY_DELAY 2 // Debounce time [ms] - Set as 1 or 2 ms #define KEY_RISE 2 #define KEY_FALL 3 int button_R4(void); // Return pin 25 (RB4) status - With debounce void main(void) { TRISBbits.RB4 = 1; // Set RB0 pin as input [2] INTCON2bits.nRBPU = 0; // Enable all input PORTB pullup [3] TRISC = 0; // Set all PORTC pins as output [4] PORTC = 1; // Turn on the first LED [4] while (1) { if (button_R4() == KEY_FALL) LATC <<= 1; // Shift PORTC data [4] if (LATC == 0) LATC = 1; // Reset PORTC: turn on the first LED [4] } } int button_R4(void) // Return pin 21 (RB0) status - With debounce // Return code: 0 - Pin is low // 1 - Pin is high // KEY_FALL - Pin from 1 to 0 (from the previous call) // KEY_RISE - Pin from 0 to 1 (from the previous call) { static unsigned char old_button; unsigned char new_button, status; __delay_ms(MY_DELAY); new_button = PORTBbits.RB4; // Read actual bit [2] if (new_button == old_button) // If actual bit equal old bit-> no change status = new_button; if (old_button && !new_button) // bit value changed status = KEY_FALL; if (!old_button && new_button) // bit value changed status = KEY_RISE; old_button = new_button; return (status); }