(PIC16F877A) How to put a 5-second delay routine ?

Thread Starter

Dragnovith

Joined Apr 16, 2021
22
Hi, I'm starting to learn how to use assembly. This code refers to a presence sensor, I would like to put a 5 second timer/delay on it. When to open or close the door. I'm programming in mplab and using proteus to simulate the electrical part.
Code:
PROCESSOR 16F877A
#include<p16f877a.inc>

    __CONFIG _CP_OFF & _WDT_OFF & _PWRTE_ON & _HS_OSC
    
    org 0x00
    goto Main
    
    org 0x04
    goto Main
    
Main

    BSF STATUS,5
    
    MOVLW B'11111111'
    MOVWF TRISB            ;
    
    MOVLW B'11110000'    ;
    MOVWF TRISD
    
    BCF STATUS,5
    CLRF PORTD

Loop

    BTFSS PORTB,2
    GOTO open
    GOTO close
    
close
    BCF PORTD,0            ; Close door
    BCF PORTD,2            ; LED red on
    BSF    PORTD,3            ; LED green off

    GOTO Loop
    
open
    BSF PORTD,0            ; Open door
    BCF    PORTD,3            ; LED green on
    BSF    PORTD,2            ; LED red off
    
    GOTO Loop

    END
1624975957814.png
 

MrSalts

Joined Apr 2, 2020
2,767
Make a loop within a loop (decrement and skip if zero) and No Op commands inside the loop (use if there is nothing else for the micro to do during the delay)

Or you can use interrupts in case the micro must be doing something else in the mean time.
 

sagor

Joined Mar 10, 2019
903
One option is to set up a timer and ise a timer interrupt, with a known period, like 1ms or 10ms. In the interrupt routine, count the number of passes (5000 for 1ms, 500 for 10ms) and set a flag/variable that time is up. In main routine, you loop until that flag is set, then clear it and the counter and continue with the code. Timer interrupt will continue to count. Other option is to simply look at the counter and branch once it flows over the expected count (zero it before branching)
In interrupt routine, check for counter overflow in case main program fails to clear the flag. Some code will simply overflow, other code may cause some mysterious crash, depending on how you write the code.
 

JohnInTX

Joined Jun 26, 2012
4,787
Question: Does RB2 have an internal pull-down resistor?
That^^ Also for a real chip, you must use series resistors on the LEDs to avoid overloading the port pins AND reduce the chance of read-modify-write problems when using bsf/bcf on a PORT. Try 1K. Proteus probably lets you get away with it but a real chip will not.
 
Top