PIC16F628A connected to 4 LEDs and 4 switches.
Fig. 1

Programming PIC16F84A-PIC16F628A Pull Up Resistors with Interrupts

by Lewis Loflin

  
  

The PIC16F628A and PIC16F84A are versatile microcontrollers with easy to use hardware interrupts. By configuring a few register bits we can take advantage of easy switch interfacing. Here we concentrate on the PORTB pull up resistors, how to set them up, then how to use interrupts to detect a switch closure.

Fig. 1 illustrates four switches connected to PB4-PB7 and four LEDs on PB0-PB3. There are no external pull up resistors needed as we use internal pull ups. See Fig. 1. We will configure the PB4-PB7 "interrupt on change function" to avoid "polling" as the controller concentrates on other functions.

To fully understand PIC16FXX interrupts see Programming PIC16F84A-PIC16F628A Interrupts by Example.


	ORG     0x004  ; interrupt vector location
	; save STATUS, W
	; isr code 

	MOVLW   0x01 ; PORTB bit to change
	XORWF   PORTB, F ; change LED state

	BTFSS PORTB, SW1
	GOTO $-1 ; wait for release

	BTFSS PORTB, SW2
	GOTO $-1 ; wait for release

	CALL DELAY_100mS
	BCF INTCON, RBIF ; CLR IRQ flag

		; restore STATUS, W
	retfie  ; return from interrupt
	

SETUP		
	BSF	STATUS, RP0 ; BANK1
	BCF OPTION_REG, NOT_RBPU ; enable PORTB pull ups
	MOVLW	B'11110000'	;Config Port B PB3-PB7 INPUT PB0-PB3 OUTPUT
	MOVWF	TRISB	;Set I/O configuration for PORTB
	BCF	STATUS, RP0  ;Jump back to bank 0 of PIC.

	CLRF PORTB 
	BSF PORTB, SW1 ; pull up on
	BSF PORTB, SW2 ; pull up on

	; interrupt setup
	BSF INTCON, GIE ; global INT enable bit 7
	BSF INTCON, RBIE ; bit 3 ; enable RBPU interrupt
	BCF INTCON, RBIF ; bit 0 ; CLR IRQ flag

	GOTO LOOP ; to main program

LOOP ;Loop starts here !!!
	BSF PORTB, 3
	CALL DELAY_500mS
	BCF PORTB, 3
	CALL DELAY_500mS
GOTO  LOOP

The steps are as follows: activate PORTB pull ups (BCF OPTION_REG, 7), set PB3-PB7 as inputs, then set each desired pin to HIGH (BSF PORTB, SW1 etc.)



The main part of the program is LOOP that spends most of its time with delay routines and would miss a switch closure most of the time. When a switch is closed the logic change (HIGH to LOW) halts execution of the LOOP program, saves the program counter (PC) on the STACK, then executes the ISR code at 0x04 the system interrupt vector.

The ISR toggles the state of a LED on PB0, waits for a switch release, waits a while, the CLEARS PORTB pull up interrupt flag. (BCF INTCON, 0) If that bit is not cleared to zero no further interrupt can occur. The ISR is exited and the program continues from where it stopped.

Note this in "interrupt on change" which means the ISR is called the switch is closed, then called again when released. That's why I we have to monitor the switch openings.


Loading



PIC16F628A connected to 4 LEDs and 4 switches.

 


donate