如何让loop只执行一次?
loop函数最后执行死循环while(1):
int ledPin = 7;
int buzzer = 8;
int ledbz(int i);//
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buzzer,OUTPUT);
}
void loop()
{
int j;
ledbz(j);//
while(1);//陷入死循环
}
int ledbz(int i)//
{
for( i=0;i<10;i++)
{
digitalWrite(ledPin,HIGH);
digitalWrite(buzzer,HIGH);
delay(100);
digitalWrite(ledPin,LOW);
digitalWrite(buzzer,LOW);
delay(100);
}
return i;
}
Arduino工程源码分析
本次分析基于Arduino 1.0.6
一、我相信大家第一次打开一个Arduino例子的时候,肯定跟我一样,有一种疑惑,
按以往经验,一般会有一个main函数,可是这里却只有一个loop()函数和setup()函数,
为什么呢????????
看到这里,没有main函数怎么运行下去。。。。。。。。。。。。。。。。。。?
运行机制是怎么样??
一系列问题。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
然后咱们揭开它神秘的面纱-----
首先大家可以用代码浏览神器Source Insight来建立一个工程,方便查看
明确自己Arduino的安装目录,这里我的是D:\Program Files\Arduino
建立工程后添加源码D:\Program Files\Arduino\hardware\arduino\cores\arduino
OK!!!建立工程完成后,开始分析---------
在工程浏览搜索mian 看到出现main.cpp
看到上面代码 , 是不是恍然大悟了~_~
这里告诉大家,为什么Arduino里面的loop()函数是执行完一次,再执行,也就是无限次执行loop,for循环,大家都知道
如果大家想要只执行一次loop()的话,可以考虑来个while(1)
继续。。。。。。。。。
看到mian函数里面的init()没有,跟进去,一探究竟
里面第一句注释:这个函数必须在setup之前执行,否则很多功能将无法工作
这个初始化函数里面sei().打开所有的中断什么的,还有其他就是些寄存器初始化
回到mian函数往下看
_attribute_的weak属性,这里的作用是弱符号:若两个或两个以上全局符号(函数或变量名)名字一样,而其中之一声明为weak symbol(弱符号),则这些全局符号不会引发重定义错误。链接器会忽略弱符号,去使用普通的全局符号来解析所有对这些符号的引用,但当普通的全局符号不可用时,链接器会使用弱符号。
也就是防止定义的一样产生冲突。
继续往下是USB功能的使能USBDevice.attch()
然后是for循环里面的串口
D:\arduino IDE\Arduino\hardware\arduino\avr\cores\arduino
/*
main.cpp - Main loop for Arduino sketches
Copyright (c) 2005-2013 Arduino Team. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
// Declared weak in Arduino.h to allow user redefinitions.
int atexit(void (* /*func*/ )()) { return 0; }
// Weak empty variant initialization function.
// May be redefined by variant files.
void initVariant() __attribute__((weak));
void initVariant() { }
void setupUSB() __attribute__((weak));
void setupUSB() { }
int main(void)
{
init();
initVariant();
#if defined(USBCON)
USBDevice.attach();
#endif
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
注意:#if #endif条件注释的使用
例如:
#if defined(X)
print ("hello word!\n") ;
#endif
以上编译只与编译宏X有关,与宏定义X的条件是否成立无关。如果定义了X宏,条件即成立,下面print语句会被编译;如果宏X未定义,则print语句不会备编译(只是编译,不是执行!)。
二、看完后知道了运行机制了吧
跟进pinMode()函数,基本上都是寄存器和另一些函数的操作
跟进digitalWrite()函数,还是寄存器和另一些函数的一些操作
终于明白,原来Arduino只是把底层封装了,让新手远离寄存器的复杂操作