本次實驗目的:
實現利用按鍵控制LED燈的亮滅1。
2.1 創建Arduino 實驗板
參考“【用Proteus仿真Arduino】 01 - 創建Arduino UNO原理圖”文中的方法創建
2.2 添加元器件
- 添加“LED-YELLOW”和電阻、接地、端子元件,因爲相同標籤名稱的端子在原理圖上是連通的,因此在這裏,LED已連接到IO9。
- 添加按鈕
我們要在Arduino UNO實驗板上添加按鍵,在元器件選擇框中輸入“BUTTON”,如圖所示。選擇上面一個按鍵,並點擊確定將其添加至元器件欄中。
2.3 繪製原理圖
從元器件欄中將按鍵放置到Arduino UNO實驗板的合適位置,並放置一個10KΩ的電阻,將按鍵的一端連接至數字口8,一端連接至+5V電源端,電阻的一端連接至數字口8,一端接至低端,構成一個下拉電阻2(上拉電阻3),如圖所示。
最終原理圖:
2.4 編寫代碼
切換到“Source Code”選項卡,完善其中的代碼,
/* Main.ino file generated by New Project wizard
*
* Created: 週五 3月 27 2020
* Processor: Arduino Uno
* Compiler: Arduino AVR (Proteus)
*/
// Peripheral Configuration Code (do not edit)
//---CONFIG_BEGIN---
#pragma GCC push_options
#pragma GCC optimize ("Os")
#include <core.h> // Required by cpu
#include <cpu.h>
#pragma GCC pop_options
// Peripheral Constructors
CPU &cpu = Cpu;
void peripheral_setup () {
}
void peripheral_loop() {
}
//---CONFIG_END---
const int buttonPin = 8; // the number of the pushbutton pin
const int ledPin = 9; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status
void setup () {
peripheral_setup();
// TODO: put your setup code here, to run once:
pinMode(ledPin,OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
peripheral_loop();
// TODO: put your main code here, to run repeatedly
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // turn LED on:
}
else {
digitalWrite(ledPin, LOW); // turn LED off:
}
}
提醒
//---CONFIG_BEGIN---
//---CONFIG_END---
這兩行之間的代碼是系統爲添加外設需要,而自動添加的,不要修改。peripheral_setup()
和peripheral_loop()
也是系統自動添加的。
2.5 編譯程序並運行仿真
- 編譯程序,單擊“build”菜單中“build Project”
- 運行仿真
單擊“run the simulation”
當用鼠標按下按鈕時,你會發現led_yellow編程黃色,表示led已經亮起。