【用Proteus仿真Arduino】 02 -按鍵與LED燈的使用

本次實驗目的:
實現利用按鍵控制LED燈的亮滅1

2.1 創建Arduino 實驗板

參考“【用Proteus仿真Arduino】 01 - 創建Arduino UNO原理圖”文中的方法創建
在這裏插入圖片描述

2.2 添加元器件

  1. 添加“LED-YELLOW”和電阻、接地、端子元件,因爲相同標籤名稱的端子在原理圖上是連通的,因此在這裏,LED已連接到IO9。
    在這裏插入圖片描述
  2. 添加按鈕
    我們要在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 編譯程序並運行仿真

  1. 編譯程序,單擊“build”菜單中“build Project”
    在這裏插入圖片描述
  2. 運行仿真
    單擊“run the simulation”
    在這裏插入圖片描述
    當用鼠標按下按鈕時,你會發現led_yellow編程黃色,表示led已經亮起。
    在這裏插入圖片描述

文獻資料


  1. 參考:地址 ↩︎

  2. 下拉電阻:http://baike.baidu.com/view/1546676.htm ↩︎

  3. 上拉電阻:http://baike.baidu.com/view/1106477.htm ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章