Reputation: 9
I will calculate the time delay so I need clock cycle number. What is the clock cycle in this code total?
.ORG 0
LDI R20, 200 ; Load immediate value 200 into register R20
BACK:
LDI R25, 120 ; Load immediate value 120 into register R25
NOP ; No operation
NOP ; No operation
NOP ; No operation
HERE:
DEC R25 ; Decrement R25
BRNE HERE ; Branch to HERE if R25 is not zero
DEC R20 ; Decrement R20
BRNE BACK ; Branch to BACK if R20 is not zero
LDI R22, 0xFF ; Load immediate value 0xFF into register R22
I understand the LDI, NOP,DEC instructions have 1 clock cycle each time and depend on their loops, but I confused BRNE instructions.
Upvotes: 0
Views: 68
Reputation: 3918
All instructions in the example take 1 cycle, except taken branches which take 2 cycles.
Upvotes: 0
Reputation: 819
AVR has RISC architecture. Instruction execution consists of two phases: fetch the instruction from memory, decoding and execution. But these two phases are pipelined because they are performed by two independent parts of the hardware. So executing an instruction and fetching the next instruction from memory can be done at the same time. Therefore, the execution of an instruction usually takes only one clock cycle. If it is necessary to jump to a different place in the program than the following instruction, it is necessary to first fetch this instruction from memory. Therefore, for conditional jumps, if their result needs to jump to a new address, another clock cycle is needed to fetch the next instruction. AVR is a very simple core and does not have speculative instruction execution like more powerful architectures.
In your case:
.ORG 0
LDI R20, 200 ; 2 (first instruction pipeline is empty)
BACK:
LDI R25, 120 ; 1
NOP ; 1
NOP ; 1
NOP ; 1
HERE:
DEC R25 ; 1
BRNE HERE ; 2 or 1
DEC R20 ; 1
BRNE BACK ; 2 or 1
LDI R22, 0xFF ; 1
2+(1+1+1+1+(1+2)*120-1+1+2)*200-1+1
Upvotes: 0
Reputation: 324
Jump instructions do two things :
It takes one cycle to test the condition. In your case, brne
tests the 'Zero Flag'.
Then, if the test is true, it takes one more cycle to jump to the label. Otherwise, the program continues to the next instruction.
Example from the AVR Instruction Set Manual :
eor r27,r27 ; Clear r27
loop: inc r27 ; Increase r27
...
cpi r27,5 ; Compare r27 to 5
brne loop ; Branch if r27<>5
nop ; Loop exit (do nothing)
brne
will need 2 cycles the 5 first iterations because r27
is not equal to 5, and only one on the 6th, when r27
is equal to 5
Upvotes: 0