嵌入式学习——51单片机——(按键、中断)day17

  1. 按键程序

1.1 主函数

cpp 复制代码
#include <reg51.h>
#include "digit.h"
#include "key.h"

void delay(int n)
{
	while (n--);
}

int main(void)
{
	int cnt = 0;

	init_digit();
	init_key();

	while (1)
	{	
	  	if (2 == key_pressed())
		{
			cnt++;
			delay(0x5fff);
		}
		show_number(cnt);
	}
	
	return 0;
}

1.2 头文件

cpp 复制代码
#ifndef _KEY_H_
#define _KEY_H_

extern void init_key(void);
extern int key_pressed(void);

#endif 

1.3 源文件

cpp 复制代码
#include <reg51.h>
#include "digit.h"
#include "key.h"

void init_key(void)
{
	P1 |= ((1 << 4) | (1 << 5) | (1 << 6) | (1 << 7));
	P3 |= (1 << 5);
}

int key_pressed(void)
{
	int ret = 0;

	if (0 == (P1 & (1 << 4)))
	{
		ret = 1;
	}
	else if (0 == (P1 & (1 << 5)))
	{
		ret = 2;
	}
	else if (0 == (P1 & (1 << 6)))
	{
		ret = 3;
	}
	else if (0 == (P1 & (1 << 7)))
	{
		ret = 4;
	}
	else if (0 == (P3 & (1 << 5)))
	{
		ret = 5;
	}
	
	return ret;	
}
  1. 中断

2.1 中断的定义

当CPU正在处理某件事情的时候外界发生了紧急事件请求,要求CPU暂停当前的工作,转而去处理这个紧急事件,处理完后,再回到原来中断的地方继续原来的工作。

2.2 中断源的定义

可以引发中断是事件、条件或者硬件模块

常见的中断源

  1. 外部中断源

  2. 定时器、计数器中断源

  3. 串口中断源

  4. ADC中断源

  5. 比较器中断源

  6. 看门狗定时器中断源

2.3 中断执行流程

  1. 中断源发出中断请求

  2. CPU查询中断是否被运行、以及中断是否被屏蔽

  3. CPU考察中断优先级

  4. CPU保护现场

  5. 执行中断服务函数

  6. 恢复现场

2.4 外部中断的初始化函数

cpp 复制代码
void init_eint(void)   
{
	P3 |= ((1 << 2) | (1 << 3) );
	IE |= ((1 << 7) | (1 << 2) | (1 << 0));
	TCON |= ((1 << 0) | (1 << 2));

}

2.5 外部中断的的作用函数

cpp 复制代码
void eint0_handeler(void) interrupt 0
{
	delay(0x1fff);
	cnt++;
}

void eint1_handeler(void) interrupt 2
{
	delay(0xfff);
	cnt--;
}

3.定时器

相关推荐
GFCGUO13 分钟前
ubuntu18.04运行OpenPCDet出现的问题
linux·python·学习·ubuntu·conda·pip
快乐就好ya39 分钟前
Java多线程
java·开发语言
CS_GaoMing1 小时前
Centos7 JDK 多版本管理与 Maven 构建问题和注意!
java·开发语言·maven·centos7·java多版本
丝丝不是土豆丝2 小时前
学习 CSS 新的属性 conic-gradient 实现环形进度条
学习
2401_858120532 小时前
Spring Boot框架下的大学生就业招聘平台
java·开发语言
S hh2 小时前
【Linux】进程地址空间
java·linux·运维·服务器·学习
转调2 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
Java探秘者2 小时前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea
wusam2 小时前
螺蛳壳里做道场:老破机搭建的私人数据中心---Centos下Docker学习04(环境准备)
学习·docker·centos
攸攸太上2 小时前
Spring Gateway学习
java·后端·学习·spring·微服务·gateway