从for循环结束回到msp430的开始需要多少时间?
问题描述:
我在问这是因为下面的代码是我用来使2个两个LED完全交替闪烁。但它为什么这个工作并没有意义。这个带有2个xor的环路有2个状态,一个是pin1(红色点亮),另一个是引脚6和pin1都处于活动状态(红色和绿色点亮)。但是灯光闪烁,就像它们在彼此之间完美地交替开关一样。从for循环结束回到msp430的开始需要多少时间?
#include <msp430g2553.h>
// counter as a global variable
unsigned int i = 0;
void main(void)
{
// stop the watchdog timer
WDTCTL = WDTPW + WDTHOLD;
// set the direction register for LED1 and LED2
P1DIR |= 0x41;
// initialize LED1 and LED2 to off
P1OUT &= 0xBE;
//empty for loop is an infinite loop
for (;;)
{
P1OUT ^= 0x01;
// create a delay between toggles
for(i=0; i< 20000; i++)
{
// empty statement, do nothing
}
P1OUT ^= 0x40;
}
}
主循环的延迟是否有可能导致这种错觉?
答
答案是,回到循环的开始非常快。
这段代码看起来像应该替代我的LED。你的评论看起来好像很糟糕。
它的主要部分是在你的循环中。你首先关闭两个LED。那么做到这一点(我已经改变了意见,我认为他们这样做):
for (;;) { // infinite loop
P1OUT ^= 0x01; // toggle state of LED1
for(i=0; i< 20000; i++) // create a delay
;
P1OUT ^= 0x40; // toggle state of LED2
}
这样做什么的,不上不下的循环是:
LED1 LED2
off off
start into loop
Toggle LED1 on off
wait
wait
wait
Toggle LED2 on on { go back to start of loop - quickly }
Toggle LED1 off on
wait
wait
wait
Toggle LED2 off off
Toggle LED1 on off
wait
...
+0
是的,我很抱歉评论它是我编辑的教科书代码,但我没有修改评论。感谢你的例子确实帮助我想象它。 – Destreation
不能从您提供什么来决定。 –
为了更好地理解发生了什么,在无限循环结束之前添加延迟循环的副本。 –
如果您希望他人阅读您的代码,如果格式化为可读性,则可能更有礼貌,更吸引观众。空格和缩进也有助于你理解。为您重新格式化。 – Clifford