Monday, March 13, 2006

PIC: EXAMPLE 6

EXAMPLE 6

TMR0 as a counter, defining new variables, using relay

This time, TMR0 is used as a counter. The idea is to connect the counter input to one pushbutton so that it counts one pulse at a time upon every button press. When the number of counted pulses becomes equal to the number in register TEST, logic one voltage (5V) will be applied to the PORTD, 3 pin. Since this voltage activates an electro-mechanical relay, this bit is called the same- "Relay".
In this example, the TEST register contains number 5. Naturally, it could be any number and could be calculated or entered via the keyboard. Instead of a relay, the microcontroller can activate some other device and instead of push-buttons it can use sensors. This example illustrates one of the most common uses of the microcontroller in industry. When something is done as many times as needed, then something else should be switched on or off...
Example 6 - TMR0 as a counter, defining new variables, using relay

Source Code

;****************************************************************************
;                    Header                                            
;****************************************************************************
;************* DEFINING VARIABLES *******************************************

       TEST        equ B'00000101' ; Binary number 00000101 = TEST
       #define     RELAY PORTD,3   ; Pin PORTD,3 = RELAY
       
;************************ MAIN PROGRAM **************************************

       org         0x0000          ; Address of the first program instruction

       banksel     TRISB           ; Selects bank containing register TRISB
       clrf        TRISB           ; All port B pins are configured as outputs
       clrf        TRISD           ; All port D pins are configured as outputs
       movlw       B'00010000'     ; This number is written to W register
       movwf       TRISA           ; Only the forth pin of port A is input
       
       banksel     OPTION_REG      ; Bank containing OPTION_REG register
       bsf         OPTION_REG,T0CS ; Pin RA4 is supplied with pulses
       bsf         OPTION_REG,PSA  ; Prescaler rate is 1:1
       
       banksel     PORTB           ; Selects bank containing PORTB register
       
       clrf        TMR0            ; Clears timer register
       bcf         PORTD,3         ; Pin PORTD,3 = 0
loop
       movfw       TMR0            ; Timer register is moved to W register
       movwf       PORTB           ; W register is moved to PORTB
       xorlw       TEST            ; Operation exclusive OR between
                                   ; W register and number TEST (00000101)
       btfsc       STATUS,Z        ; If numbers are equal, result is 0 and
       bsf         PORTD,3         ; bit STATUS,Z = 1. Bit PORTD,3 is set
       goto        loop            ; and jump to label loop is executed
       
       end                         ; End of program