arduino 程序的机制
??????? 從一個(gè)簡(jiǎn)單的 arduino 程序說(shuō)起:
/*BlinkTurns on an LED on for one second, then off for one second, repeatedly.This example code is in the public domain.*/// Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13;// the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output.pinMode(led, OUTPUT); }// the loop routine runs over and over again forever: void loop() {digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)delay(1000); // wait for a seconddigitalWrite(led, LOW); // turn the LED off by making the voltage LOWdelay(1000); // wait for a second }??????? 這個(gè)程序的主體,提供了 setup() 和 loop() 二個(gè)函數(shù)。setup 函數(shù)做一些初始化的工作,在系統(tǒng)上電或復(fù)位后,此函數(shù)只會(huì)執(zhí)行一次。???? loop 函數(shù)會(huì)在 setup 之后一直循環(huán)運(yùn)行。
??????? 在了解如何使用之后,其背后的機(jī)制是怎樣的呢,那么,可以到安裝目錄下打開(kāi)代碼文件:C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino\main.cpp ?代碼如下:
?????? 相信您看到了這段代碼,就該知道 setup 和 loop 函數(shù)的前世今生了吧。我們所寫(xiě)的setup 和 loop 函數(shù)是這兩個(gè)函數(shù)的定義。這兩個(gè)函數(shù)在 main ( )主程序中已經(jīng)預(yù)調(diào)用了。?? 在 loop 函數(shù)運(yùn)行之后,我們還會(huì)看到 serialEventRun 的函數(shù),此函數(shù)的功能是當(dāng)串口有數(shù)據(jù)過(guò)來(lái)的時(shí)候,它可以調(diào)用Arduino的另一個(gè)函數(shù)?serialEvent。
?????? 打開(kāi) Arduino IDE , 選擇菜單:文件 -> 示例 -> 04.Communication?-> SerialEvent?具體看下面的代碼:
??????? 此代碼的功能是:系統(tǒng)上電后,接收串口的輸入數(shù)據(jù)并發(fā)送回去,類似 echo。系統(tǒng)的實(shí)現(xiàn)是通過(guò)在主循環(huán)判斷全局變量 stringComplete 的狀態(tài)來(lái)決定是否發(fā)送接收到的數(shù)據(jù)。而 stringComplete 的狀態(tài)是在 serialEvent 這個(gè)函數(shù)里賦值的。根據(jù) serialEvent 函數(shù)注釋看,此函數(shù)的調(diào)用是在每次 loop 函數(shù)運(yùn)行之后才執(zhí)行的。再回到我們之前的代碼:
??????? 通過(guò)上面的代碼,可以很明確的看出 serialEventRun 函數(shù)是在 loop 函數(shù)之后執(zhí)行的。如果我們有多個(gè)串口,比如 2560 的板子提供了4個(gè)串口,那么 serialEventRun 函數(shù)又是如何處理的呢,我們打開(kāi)代碼文件:C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino\HardwareSerial.cpp 找到 serialEventRun 函數(shù)的實(shí)現(xiàn),代碼如下: void serialEventRun(void) { #ifdef serialEvent_implementedif (Serial.available()) serialEvent(); #endif #ifdef serialEvent1_implementedif (Serial1.available()) serialEvent1(); #endif #ifdef serialEvent2_implementedif (Serial2.available()) serialEvent2(); #endif #ifdef serialEvent3_implementedif (Serial3.available()) serialEvent3(); #endif }
??????? serialEventRun 的函數(shù)體中是依次的調(diào)用 serialEvent() serialEvent1() serialEvent2() serialEvent3() 函數(shù)的。如果您的應(yīng)用需要通過(guò)多個(gè)串口讀寫(xiě)數(shù)據(jù),那么在使用 serialEvent 函數(shù)的過(guò)程中,就要考慮接受的數(shù)據(jù)長(zhǎng)度以及函數(shù)的處理時(shí)間,否則極有可能會(huì)導(dǎo)致其它串口的接收緩沖區(qū)滿而影響應(yīng)用。
總結(jié)
以上是生活随笔為你收集整理的arduino 程序的机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Hadoop学习笔记
- 下一篇: 07.用户故事与敏捷方法——优秀用户故事