8051 Assembly code to find average of all numbers stored in array


           We use Indirect addressing mode to access arrays in 8051, because it is efficient and has advantage of accessing adjacent address locations with one base address. So, lets see how to find average of all numbers stored in an array.
 ALGORITHM:
  1. Start
  2. Initialize a register with base address of memory location where array is stored
  3. Initialize counter register with number of elements in array
  4. Enter the loop and add all the numbers in array
  5. Divide the sum stored by number of elements and store the result
  6. Stop

Here is example code to find average of numbers in array with 10 elements stored in internal memory location with starting address 0xA0
Note: Make sure you initialize array in memory location 0xA0, use "i:0x00A0" to access 0xA0 location in memory window.

 CODE:

ORG 0000h
        LJMP main
 ORG 0040h
 main: MOV R0,#0A0h             ; Initializing base address location where array is stored
  MOV R1,#0Ah              ; Number of elements in array
  MOV R2,#00h
  MOV A,R1                 ; Storing number of elements in array
  MOV R3,A
  loop: MOV A,@ R0       ; Coping value from memory location at which R0 is pointing
   ADD A,R2         
   MOV R2,A         ; Sum is stored in R2 register
   INC R0
   DJNZ R1, loop    
  MOV B,R3                 ; Moving number of elements to register B 
  MOV A,R2                 ; Moving Sum all elements to register A
  DIV AB                   ; Finding average
  MOV R4,A                 ; Storing the result in R4 register
END

No comments:

Powered by Blogger.