When we have a code like this :
main: MOV #SFE(CSTACK), SP ; set up stack
;;; some instructions .......
; load the starting address of the array1 into the register R4
MOV.W #arr1, R4
; load the starting address of the array1 into the register R5
MOV.W #arr2, R5
; Sum arr1 and display
CLR R7 ; Holds the sum
MOV #8, R10 ; number of elements in arr1
lnext1: ADD @R4+, R7 ; get next element
DEC R10
JNZ lnext1
MOV.B R7, P1OUT ; display sum of arr1
SWPB R7
MOV.B R7, P2OUT
What is the reason/meaning behind doing SWPB R7 in this example? I read the docs and understand that it exchanges low/high end bytes; in some docs it says it multiplies by 256. Is that the only reason or am I missing something deeper here? The code supposed to add the elements of a register.
MOV.B can access only the lower byte. So to be able to copy the upper byte somewhere else, it must be moved to the lower byte first. (That the previous lower byte is in the upper byte after the swap is an unimportant side effect.)
There would be other, less efficient mechanisms to get at the upper byte, such as shifting the register right eight times:
Or storing the 16-bit value into a temporary variable, and then accessing the two bytes of that variable directly:
With newer MSP430 families, the port registers are arranged so that you can access two ports with a single 16-bit access: