【用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 ↩︎

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