Question

I'm writing a subroutine to count the number of set bits in wreg, but on reaching the return statement at the end of the subprogram it just repeats the return statement endlessly. I'm new to PIC and assembly, so I'm sure I've just done something silly, but I haven't been able to work it out yet. Any help would be greatly appreciated.

Here is my code:

COUNT       equ 0x00

NUMBER      equ 0x01

BITS        equ 0x02

;bitcounter subprogram counts the number of set bits in a byte

BITCOUNTER:

Loop1   rlcf NUMBER,f   ;rotates one bit of number into carry flag, store rotated number

    btfsc STATUS, C     ;skips next line if carry is clear

    incf COUNT, f   ;add one to count, store in count

    bcf STATUS, C   ;clear carry flag

    decfsz BITS

    goto Loop1

    movf COUNT, 0   ; put bit count into W register
return 

START

        movlw   0x0008

        movwf   BITS

        movlw   0xF2

        movwf NUMBER    ;stores input as "number"

        call BITCOUNTER

    end
Was it helpful?

Solution

I'm new to PIC programming and haven't uploaded any codes to PICs as of yet (still waiting for programmer delivery) but I think that the "goto start" at the end fixes the problem because a PIC needs to do something. The "goto start" instruction puts the PIC in a loop so it doesn't have to try and "stop". In it's absence, I think that the PIC is trying to deal with the "not being able to stop" by simply repeating the last instruction indefinitely.

If so, you could alternatively add something like (assuming I have set it out right):

loop2 nop
      goto loop2

at the end of your code. The PIC would continue to run a no-operation until you reset it (or you could set up an interrupt, WDT or some other function as required).

OTHER TIPS

Try this...

include "p18f452.inc"  ;from dir X:\Program Files (x86)\Microchip\MPASM Suite

COUNT       equ 0x00
NUMBER      equ 0x01
BITS        equ 0x02

;bitcounter subprogram counts the number of set bits in a byte
            org 0

START
            movlw   0x0008
            movwf   BITS
            movlw   0xF2
            movwf   NUMBER    ;stores input as "number"
            call    BITCOUNTER
            goto    START

BITCOUNTER:
Loop1       rlcf   NUMBER,f   ;rotates one bit of number into carry flag, store rotated number
            btfsc  STATUS, C     ;skips next line if carry is clear
            incf   COUNT, f   ;add one to count, store in count
            bcf    STATUS, C   ;clear carry flag
            decfsz BITS
            goto   Loop1
            movf   COUNT, 0   ; put bit count into W register
            return

            end

Remember there is no MCPU configuration settings, like oscillator, watchdog... Just test code!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top