使用汇编语言不使用定时器Arduino的乌诺创建延迟 [英] Create Delay in Arduino Uno using Assembly language without using timer
问题描述
我刚开始学习微控制器和我是不是能够理解我们如何能够引进在code拖延不使用定时器。
我的主板有16MHZ的时钟。比方说,我想介绍延时5ms我检查前如果按钮pressed。我将如何确定我需要多少执行的指令得到5毫秒的延迟,我将如何编程呢?
是否有这样做的一个标准化的方式?它看起来像一个非常标准的东西,但我不能够理解它是如何做。
I just started learning about micro controllers and I was not able to understand how we could introduce delays in the code without using timers. My board has a clock of 16MHZ. Let's say I want to introduce 5ms delay before I check if a button is pressed. How would I identify how many instructions I need to execute to get 5 ms delay and how would I program it? Is there a standardized way of doing this? It looks like a very standard thing but I am not able to understand how it is done.
我使用的Atmega 328的Arduino UNO汇编语言编程。
I am programming using Assembly language on Atmega 328 Arduino uno.
推荐答案
一般来说,你弄清楚你需要燃烧多少个时钟周期,然后写一个循环。请咨询您的数据表,以确定您的循环多少次需要并计算你有多少次迭代需要。
Generally you figure out how many clock cycles you need to burn, then write a loop. Consult your datasheet to determine how many cycles your loop takes and calculate how many iterations you need.
ldi r16, x ; 1 cycle
loop: nop ; 1 cycle
dec r16 ; 1 cycle
brne loop1 ; 2 cycles when jumping, 1 otherwise
根据 X
,这个循环将采取 X * 4
周期的价值。用16MHz的板1ms的是16000个周期,所以5ms的将是80000次。这是比这8位循环更可以管理,所以我们需要做一个16位的计数器。
Depending on the value of x
, this loop will take x * 4
cycles. With a 16MHz board 1ms is 16000 cycles, so 5ms would be 80000 cycles. That's more than this 8 bit loop can manage so we need to make a 16 bit counter.
ldi r16, x ; 1 cycle
ldi r17, y ; 1 cycle
loop: nop ; 1 cycle
dec r16 ; 1 cycle
brne skip ; 2 cycles when jumping, 1 otherwise
dec r17 ; 1 cycle
skip: brne loop ; 2 cycles when jumping, 1 otherwise
好了,所以我们的循环体现在只需每次迭代6个周期。请注意,这是6个周期不管 R16
被包装与否。安装需要2个周期,但最终 brne
为我们提供了1个循环回来,我们得到了1个周期的开销。这意味着我们需要79999个周期是13333迭代,一个周期去浪费。因此, X =低(13333)= 21
和 Y =高(13333)= 52
并添加 NOP
。
Okay so our loop body now takes 6 cycles per iteration. Notice that it's 6 cycles no matter if r16
is wrapping or not. The setup takes 2 cycles but the final brne
gives us 1 cycle back so we got 1 cycle overhead. That means we need 79999 cycles which is 13333 iterations and one more cycle to waste. Thus x=low(13333)=21
and y=high(13333)=52
and add a nop
.
这是一般的想法,我希望我没有算错什么。如果你打算让这个功能,要素在调用和返回的开销。此外,你可以把它参数化。
That's the general idea, I hope I have not miscalculated anything. If you intend to make a function of this, factor in the overhead of the call and return. Also, you can make it parametrized.
这篇关于使用汇编语言不使用定时器Arduino的乌诺创建延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!