-1

I'm just starting with low level assembly in an AVR microcontroller. I have allocated variables on SRAM as :

var1:   .BYTE 2
var2:   .BYTE 2

Afterwards, I'm populating the variables via SPI from a sensor. Using Indirect adressing as:

;set up Z pointer
ldi ZL, low(var1)
ldi ZH, high(var1)

...

;store the result from registers r25 and r26 into RAM
st Z+, r25
st Z+, r26

I have confirmed that var1 and var2 are stored contiguous in memory.

Now my question is, upon recieving the second 2 Bytes of var2 from the sensor, is it acceptable to just increment the Z pointer and store the result, or should I set up the Z pointer again?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Ait-Gacem Nabil
  • 165
  • 3
  • 12
  • Why would it not work by incrementing the pointer when you know the values are stored in contiguous memory? – xiver77 Jul 18 '22 at 09:08
  • @xiver77 it **_does_** work, but does it also have any unexpected side effects. I'll edit the question. But basically even when something works doesn't mean one should do it. – Ait-Gacem Nabil Jul 18 '22 at 09:10

1 Answers1

3

There's nothing wrong with doing that.

However, you should be aware of maintenance issues.  When a change in one place requires an analogous change in another place, that is a potential long-term maintenance issue — making the code error prone.  It is for this reason that we prefer to define constants with some form of name, in case it changes that will change all users of that constant, plus it makes the code more self-documenting.  It is also why we use labels, so we can insert code or data letting the assembler make all the adjustments.

So, at minimum I would add comment the data about there being an expectation in the code of these two variables are consecutive.

Alternatively, I might make var1 4 bytes long such that var1 is an array of 2 elements, if you will, and there is no var2 — that would also accomplish communicating to other programmers the way this storage is being used by the code.  (With that, then, I might add comment that this is an array of 2 elements holding a pair of sensor values.)

Erik Eidt
  • 23,049
  • 2
  • 29
  • 53