Advertisement
igendel

Electronic Code Lock with the PIC12F675

Jul 6th, 2014
1,652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.11 KB | None | 0 0
  1. // For MPLAB X with the XC8 Compiler
  2. // by Ido Gendel (info AT idogendel.com)
  3.  
  4. // Connections : Red LED to GP4, Green LED to GP5
  5. // Three momentary buttons from GND to GP0-GP2
  6.  
  7. #define _XTAL_FREQ 4000000
  8. #include <xc.h>
  9.  
  10. #pragma config FOSC = INTRCIO   // Oscillator Selection bits (INTOSC oscillator: I/O function on GP4/OSC2/CLKOUT , GP5/OSC1/CLKIN)
  11. #pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
  12. #pragma config PWRTE = OFF      // Power-Up Timer Enable bit (PWRT disabled)
  13. #pragma config MCLRE = OFF      // GP3/MCLR pin function select (GP3/MCLR pin function is digital I/O, MCLR internally tied to VDD)
  14. #pragma config BOREN = OFF      // Brown-out Detect Enable bit (BOD disabled)
  15. #pragma config CP = OFF         // Code Protection bit (Program Memory code protection is disabled)
  16. #pragma config CPD = OFF        // Data Code Protection bit (Data memory code protection is disabled)
  17.  
  18. #define redLedIO 4
  19. #define greenLedIO 5
  20.  
  21. char buttonInput() {
  22.   // Reversed logic reversed...
  23.   return 7 - (GPIO & 7);
  24. }
  25.  
  26. int main() {
  27.  
  28.   const char secretCode[] = {1, 2, 4 ,2 ,1};
  29.   char codeIndex;
  30.  
  31.   ANSEL = 0;            // ANalog SELect; all digital
  32.   CMCON = 7;            // CoMparator CONtrol; comparator off
  33.   ADCON0 = 0;           // A/D CONtrol; A/D conversion off
  34.   TRISIO = 7;           // GP0-2 inputs
  35.   OPTION_REG &= 127;    // GPPU clear - pullups enabled
  36.   WPU = 7;              // Internal pull-up on GP0-2
  37.  
  38.   while (1) {
  39.    
  40.     GPIO = 1 << redLedIO; // Red LED pin High
  41.     codeIndex = 0;
  42.  
  43.     while (codeIndex < sizeof(secretCode)) {
  44.  
  45.       // Wait for input on any button, then debounce
  46.       while (!buttonInput()) ;
  47.       __delay_ms(10);
  48.  
  49.       // Check input
  50.       if (buttonInput() == secretCode[codeIndex]) codeIndex++;
  51.        else codeIndex = (buttonInput() == secretCode[0]) ? 1 : 0;
  52.  
  53.       // Wait for button release, then debounce
  54.       while (buttonInput()) ;
  55.       __delay_ms(10);
  56.  
  57.     } // while
  58.  
  59.     // Correct combination sequence
  60.     GPIO = 1 << greenLedIO; // Green LED pin High
  61.     __delay_ms(1000);
  62.  
  63.   } // while
  64.  
  65.   return 0;
  66.  
  67. } // main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement