Reputation: 87
Feel like I've been asking a lot of these questions lately lol, but assembly is still pretty foreign to me.
Using an Arduino, I have to write a function in Atmel AVR Assembly for my computer science class that calculates the sum of the 8-bit values in an array and returns it as a 16-bit integer. The function is supposed to take in an array of bytes and a byte representing the length of the array as arguments, with those arguments stored in r24 and r22, respectively, when the function is called. I am allowed to use branching instructions and such.
The code is in this format:
.global sumArray
sumArray:
//magic happens
ret
I know how to make loops and increment the counter and things like that, but I am really lost as to how I would do this.
I am unsure as to how I would do this. Does anyone know how to write this function in Atmel AVR Assembly? Any help would be much appreciated!
Upvotes: 0
Views: 1575
Reputation: 3566
Why don't you ask the question to your compiler?
#include <stdint.h>
uint16_t sumArray(uint8_t *val, uint8_t count)
{
uint16_t sum = 0;
for (uint8_t i = 0; i < count; i++)
sum += val[i];
return sum;
}
Compiling with avr-gcc -std=c99 -mmcu=avr5 -Os -S sum8-16.c
generates
the following assembly:
.global sumArray
sumArray:
mov r19, r24
movw r30, r24
ldi r24, 0
ldi r25, 0
.L2:
mov r18, r30
sub r18, r19
cp r18, r22
brsh .L5
ld r18, Z+
add r24, r18
adc r25,__zero_reg__
rjmp .L2
.L5:
ret
This may not be the most straight-forward solution, but if you study this code, you can understand how it works and, hopefully, come with your own version.
Upvotes: 2
Reputation: 71566
with pencil and paper how do I add two two digit decimal numbers when I was only taught to add two single digit numbers at a time? 12 + 49? I can add the 2+9 = 11 then what do I do? (search for the word carry)
Upvotes: 0
Reputation: 2699
Iif you want something quick and dirty, add the two 8-bit values into an 8-bit register. If the sum is less than the inputs, then make a second 8-bit register equal to 1, otherwise 0. That's how you can do the carry.
The processor should already have something called a carry flag that you can use to this end.
Upvotes: 0