Arduino 內(nèi)置示例——控制結(jié)構(gòu)部分示例

  • 數(shù)組:一個在For循環(huán)的變量舉例了怎樣使用一個數(shù)組。
  • For循環(huán):通過for循環(huán)來控制多個LED燈
  • If聲明條件:使用一個‘if 聲明’,通過改變輸入條件來改變輸出條件
  • Switch Case:怎樣在非連續(xù)的數(shù)值里選擇塌西。
  • Switch Case 2:第二個switch-case的例子奈偏,展示怎樣根據(jù)在串口收到的字符來采取不同的行為
  • While 聲明條件:當(dāng)一個按鍵被讀取飞几,怎樣用一個while循環(huán)來校準(zhǔn)一個傳感器后室。
image.png
數(shù)組
  • 在for循環(huán)的變量示范了怎么用一個數(shù)組缩膝。一個數(shù)組是一個含多部分的變量混狠。 如果你把一個變量理解為一個裝數(shù)據(jù)的杯岸霹,你可以把一個數(shù)組理解為制冰格。它就像一系列的粘在一起的杯将饺,上面裝著一些最大的數(shù)值贡避。

  • for循環(huán)示范了怎樣點亮連接到Arduino或Genuino開發(fā)板上pin2到pin7的一系列的LED燈,這些引腳需要連續(xù)標(biāo)記數(shù)字予弧,而LED燈需要按順序打開刮吧。

  • 該例子示范怎樣順序打開一些引腳,這些引腳的序號是不連續(xù)而且不按次序掖蛤。為了實現(xiàn)這個目的杀捻,你可以把這些引腳序號放到一個數(shù)組里,然后在循環(huán)里重申完這個數(shù)組蚓庭。

  • 這個例子充分利用了通過220 ohm電阻連接在pin2到pin7的6個LED燈致讥,就像在for循環(huán)里。然而器赞,這里L(fēng)ED燈的順序由它們在數(shù)組里的順序確定垢袱,而不是他們的物理順序。

  • 這個把引腳放到數(shù)組的方式很方便港柜。你不必把這些引腳一個接一個排好順序请契,或者同一個順序。你可以重新排列數(shù)組,按任何你想要的順序爽锥。

通過220 ohm電阻串聯(lián)涌韩,連接6個LED燈到數(shù)字引腳pin2-pin7上。


image.png

示例代碼:

int timer = 100;           // The higher the number, the slower the timing.
int ledPins[] = {
  2, 7, 4, 6, 5, 3
};       // an array of pin numbers to which LEDs are attached
int pinCount = 6;           // the number of pins (i.e. the length of the array)

void setup() {
  // the array elements are numbered from 0 to (pinCount - 1).
  // use a for loop to initialize each pin as an output:
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    pinMode(ledPins[thisPin], OUTPUT);
  }
}

void loop() {
  // loop from the lowest pin to the highest:
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    // turn the pin on:
    digitalWrite(ledPins[thisPin], HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(ledPins[thisPin], LOW);

  }

  // loop from the highest pin to the lowest:
  for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
    // turn the pin on:
    digitalWrite(ledPins[thisPin], HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(ledPins[thisPin], LOW);
  }
}
數(shù)組跑馬燈.gif

For循環(huán)
  • 通常你想循環(huán)一系列引腳救恨,然后每個引腳做一些事情贸辈。如這個例子通過for()循環(huán)來重復(fù)點亮pin2-7上的6個LED燈。這些LED燈通過digitalWrite() 和delay()按順序點亮和熄滅肠槽。

通過220 ohm電阻串聯(lián)擎淤,連接6個LED燈到數(shù)字引腳pin2-pin7上。

image.png
int timer = 100;           // The higher the number, the slower the timing.

void setup() {
  // use a for loop to initialize each pin as an output:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // loop from the lowest pin to the highest:
  for (int thisPin = 2; thisPin < 8; thisPin++) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }

  // loop from the highest pin to the lowest:
  for (int thisPin = 7; thisPin >= 2; thisPin--) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }
}
for循環(huán)跑馬燈.gif

If聲明條件

這個if()聲明是所有程序控制結(jié)構(gòu)里最基本的部分。它允許你來使有些事情是否發(fā)生校翔,取決于是否符合一些給定的條件优幸。它看起來像這樣:

if (someCondition) {
   // do stuff if the condition is true
}

有一個公共變量叫if-else,看起來像這樣:

if (someCondition) {
   // do stuff if the condition is true
} else {
   // do stuff if the condition is false
}

也有else-if席吴,當(dāng)?shù)谝粭l件為真時你可以檢查第二條件:

if (someCondition) {
   // do stuff if the condition is true
} else if (anotherCondition) {
   // do stuff only if the first condition is false
   // and the second condition is true
}

你任何時候都可以用到if聲明。下面的例子如果模擬輸入引腳讀取的值超過閾值捞蛋,就會打開pin13的LED燈(內(nèi)置在很多Arduino上)孝冒。

image.png

示例代碼:

在下面的代碼里,一個叫analogValue的變量用來保存從電位計(連接到開發(fā)板的模擬引腳pin0)讀取的數(shù)據(jù)拟杉。然后對比這個數(shù)據(jù)和閾值庄涡。如果模擬值在設(shè)置的閾值上面,打開pin13的內(nèi)置LED燈搬设。如果低于閾值穴店,LED保持關(guān)閉。

// These constants won't change:
const int analogPin = A0;    // pin that the sensor is attached to
const int ledPin = 13;       // pin that the LED is attached to
const int threshold = 400;   // an arbitrary threshold level that's in the range of the analog input

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communications:
  Serial.begin(9600);
}

void loop() {
  // read the value of the potentiometer:
  int analogValue = analogRead(analogPin);

  // if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }

  // print the analog value:
  Serial.println(analogValue);
  delay(1);        // delay in between reads for stability
}
if控制led.gif

Switch Case
  • 一個if聲明允許你選擇兩個分開的選項拿穴,真或假泣洞。當(dāng)有超過2個的選項,你可以用多個if聲明默色,或者你可以用switch聲明球凰。switch允許你選擇多個選項。這個教程示范怎樣用它在四種光電阻的狀態(tài)下切換開關(guān):全黑腿宰,昏暗呕诉,中等,明亮酗失。

  • 這個程序首先讀取光敏電阻义钉。然后它用map()函數(shù)來使它的輸出值符合四個值之一:0,1规肴,2捶闸,3夜畴。最后,用switch()聲明來打印對應(yīng)的信息到電腦里删壮。

光敏電阻通過一個分壓電路連接到模擬輸入pin0贪绘。一個10k ohm電阻補充分壓器的另一部分,從模擬輸入pin0連到地央碟。analogRead()函數(shù)從這個電路返回一個0-600的范圍值税灌。

image.png

示例代碼:

// these constants won't change. They are the lowest and highest readings you
// get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}
image.png
image.png

Switch Case 2
  • 一個if聲明允許你選擇兩個分開的選項,真或假亿虽。當(dāng)有超過2個的選項菱涤,你可以用多個if聲明,或者你可以用switch聲明洛勉。switch允許你選擇多個選項粘秆。

  • 這個教程示范怎樣用switch根據(jù)收到的字節(jié)數(shù)據(jù)來打開多個LED燈中的一個。并且根據(jù)字符a,b,c,d,e來打開特定的LED燈收毫。

5個LED燈通過串聯(lián)的220 ohm電阻連接到數(shù)字引腳pin 2攻走,3,4此再,5昔搂,6。

為了使程序工作输拇,你的開發(fā)板需要連接到電腦摘符。在Arduino IDE上打開串口監(jiān)視器,并且發(fā)送字符 a,b,c,d,e來點亮相應(yīng)的LED燈淳附,或者其他東西來關(guān)閉它們议慰。

image.png

示例代碼:

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  // initialize the LED pins:
  for (int thisPin = 2; thisPin < 7; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // read the sensor:
  if (Serial.available() > 0) {
    int inByte = Serial.read();
    // do something different depending on the character received.
    // The switch statement expects single number values for each case; in this
    // example, though, you're using single quotes to tell the controller to get
    // the ASCII value for the character. For example 'a' = 97, 'b' = 98,
    // and so forth:

    switch (inByte) {
      case 'a':
        digitalWrite(2, HIGH);
        break;
      case 'b':
        digitalWrite(3, HIGH);
        break;
      case 'c':
        digitalWrite(4, HIGH);
        break;
      case 'd':
        digitalWrite(5, HIGH);
        break;
      case 'e':
        digitalWrite(6, HIGH);
        break;
      default:
        // turn all the LEDs off:
        for (int thisPin = 2; thisPin < 7; thisPin++) {
          digitalWrite(thisPin, LOW);
        }
    }
  }
}
Switch Case 2.gif

While 聲明條件
  • 有時候當(dāng)給定的條件為真時蠢古,你想程序所有東西都停止奴曙。你可以用while循環(huán)來做這件事。這個例子示范怎樣用while循環(huán)來校準(zhǔn)傳感器的值草讶。

  • 在主循環(huán)里洽糟,下面程序在模擬引腳pin0里讀取光敏電阻的值,并用它來使pin9的LED燈變亮或者變暗堕战。而當(dāng)一個按鍵(連接到數(shù)字引腳pin2)被按下時坤溃,程序運行一個叫 calibrate()的函數(shù),尋找模擬傳感值的最大和最小值嘱丢。當(dāng)你放開按鍵時薪介,程序會繼續(xù)主循環(huán)。

  • 這個方法可以使你在光源環(huán)境改變的時候更新光敏電阻的最大值和最小值越驻。

把你的模擬傳感器(光敏電阻或者其他)通過10k ohm電阻下拉到地汁政,再連接到模擬輸入引腳pin0道偷。連接你的按鍵(通過10k ohm電阻下拉到地)到數(shù)字引腳pin2。把你的LED燈串聯(lián)一個220 ohm電阻連接到數(shù)字引腳pin9记劈。

image.png

示例代碼:

// These constants won't change:
const int sensorPin = A0;       // pin that the sensor is attached to
const int ledPin = 9;           // pin that the LED is attached to
const int indicatorLedPin = 13; // pin that the built-in LED is attached to
const int buttonPin = 2;        // pin that the button is attached to


// These variables will change:
int sensorMin = 1023;  // minimum sensor value
int sensorMax = 0;     // maximum sensor value
int sensorValue = 0;         // the sensor value


void setup() {
  // set the LED pins as outputs and the switch pin as input:
  pinMode(indicatorLedPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  // while the button is pressed, take calibration readings:
  while (digitalRead(buttonPin) == HIGH) {
    calibrate();
  }
  // signal the end of the calibration period
  digitalWrite(indicatorLedPin, LOW);

  // read the sensor:
  sensorValue = analogRead(sensorPin);

  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);

  // fade the LED using the calibrated value:
  analogWrite(ledPin, sensorValue);
}

void calibrate() {
  // turn on the indicator LED to indicate that calibration is happening:
  digitalWrite(indicatorLedPin, HIGH);
  // read the sensor:
  sensorValue = analogRead(sensorPin);

  // record the maximum sensor value
  if (sensorValue > sensorMax) {
    sensorMax = sensorValue;
  }

  // record the minimum sensor value
  if (sensorValue < sensorMin) {
    sensorMin = sensorValue;
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末勺鸦,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子目木,更是在濱河造成了極大的恐慌换途,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件刽射,死亡現(xiàn)場離奇詭異军拟,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)誓禁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進(jìn)店門吻谋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人现横,你說我怎么就攤上這事漓拾。” “怎么了戒祠?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵骇两,是天一觀的道長。 經(jīng)常有香客問我姜盈,道長低千,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任馏颂,我火速辦了婚禮示血,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘救拉。我一直安慰自己难审,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布亿絮。 她就那樣靜靜地躺著告喊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪派昧。 梳的紋絲不亂的頭發(fā)上黔姜,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天,我揣著相機(jī)與錄音蒂萎,去河邊找鬼秆吵。 笑死,一個胖子當(dāng)著我的面吹牛五慈,可吹牛的內(nèi)容都是我干的纳寂。 我是一名探鬼主播实苞,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼烈疚!你這毒婦竟也來了黔牵?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤爷肝,失蹤者是張志新(化名)和其女友劉穎猾浦,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體灯抛,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡金赦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了对嚼。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片夹抗。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖纵竖,靈堂內(nèi)的尸體忽然破棺而出漠烧,到底是詐尸還是另有隱情,我是刑警寧澤靡砌,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布已脓,位于F島的核電站,受9級特大地震影響通殃,放射性物質(zhì)發(fā)生泄漏度液。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一画舌、第九天 我趴在偏房一處隱蔽的房頂上張望堕担。 院中可真熱鬧,春花似錦曲聂、人聲如沸霹购。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽厕鹃。三九已至兢仰,卻和暖如春乍丈,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背把将。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工轻专, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人察蹲。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓请垛,卻偏偏與公主長得像催训,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子宗收,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容