Arduino与Proteus仿真实例-按键与中断仿真

按键与中断仿真

1、Arduino的中断介绍

常见的中断类型有两种:

  • 硬件中断:它发生在外部事件发生时,例如外部中断引脚将其状态从低电平变为高电平或从高电平变为低电平。
  • 软件中断:它根据软件的说明发生。 例如定时器中断是软件中断。

Arduino支持两种中断类型:

  • 外部中断:这些中断由硬件解释并且非常快。 这些中断可以设置为在 RISING 或 FALLING 或低电平事件时触发。如下表所示,不同版本的Arduino支持的外部中断如下:
Arduino Board External Interrupt pins:
UNO , NANO 2,3
Mega 2,3,18,19,20,21
  • 引脚变化中断:Arduinos 可以通过使用引脚更改中断来启用更多中断引脚。 在基于 ATmega168/328 的 Arduino 板中,任何引脚或所有 20 个信号引脚都可以用作中断引脚。 它们也可以使用上升沿或下降沿触发。

2、仿真电路原理图

在这里插入图片描述

3、代码实现

为了在 Arduino 中使用中断,需要了解以下概念。

1)中断服务程序(Interrupt Service Routine (ISR))

中断服务程序或中断处理程序是一个包含一小组指令的事件。 当外部中断发生时,处理器首先执行 ISR 中存在的这些代码,然后返回到它离开正常执行的状态。

Arduino提供了中断服务程序的绑定和解除绑定API:

1
2
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

digitalPinToInterrupt(pin):用于此指定用于外部中断的输入引脚。

ISR:一个在外部中断完成时调用的函数。

mode:要触发的转换类型,例如 下降、上升等。包含如下几种类型:

  • RISING:当引脚从低电平变为高电平时触发中断。
  • FALLING:当引脚从高电平转换为低电平时触发中断。
  • CHANGE:当引脚从 LOW 转换为 HIGH 或 HIGH 转换为 LOW 时(即,当引脚状态改变时)触发中断。

注意:使用中断时的一些条件

  • 中断服务程序功能 (ISR) 必须尽可能短。
  • Delay() 函数在 ISR 内部不起作用,应避免使用。

仿真代码实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int ledPin = 10; // LED引脚
int buttonPin = 3; // 按键引脚
static bool ledState = false; // LED状态
// 按键外部中断程序
void button\_pressed(){

if(ledState){
ledState = false;
}else{
ledState = true;
}
Serial.print("button pressed:");
Serial.println(ledState);

}

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledPin,OUTPUT);// 设置LED引脚为输出模式
pinMode(buttonPin,INPUT);// 设置按键引脚为输入模式

// 绑定中断
attachInterrupt(digitalPinToInterrupt(buttonPin),button_pressed,FALLING);
}

void loop() {
// put your main code here, to run repeatedly:
if(ledState){
digitalWrite(ledPin,HIGH);
}else{
digitalWrite(ledPin,LOW);
}
}

4、仿真结果

在这里插入图片描述

文章来源: https://iotsmart.blog.csdn.net/article/details/120841973