嵌入式学习——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.定时器

相关推荐
踏着七彩祥云的小丑17 分钟前
Go学习第1天:入门
开发语言·学习·golang·go
2023自学中26 分钟前
Linux虚拟机 CMakeLists.txt:x86 与 ARM 双架构编译脚本
linux·c语言·c++·嵌入式
憧憬成为web高手35 分钟前
[0CTF 2016]piapiapia
学习
眠りたいです44 分钟前
现代C++:C++17中的新库特性
开发语言·c++·c++20·c++17
devnullcoffee1 小时前
亚马逊 Buy Box 数据采集完全指南(2026):Python 实战 + Pangolinfo API
开发语言·python·亚马逊数据采集·亚马逊数据 api·pangolinfo api·亚马逊 buy box 数据·亚马逊数据采集软件
imDwAaY1 小时前
贝叶斯网络到粒子滤波Python算法实现 CS188 Proj4 学习笔记
网络·人工智能·笔记·python·学习·算法
sleven fung1 小时前
Whisper库
开发语言·人工智能·python·算法·ai·whisper
天若有情6731 小时前
【C++趣味实战】仿写Burp代理逻辑!自定义可控迭代器:拦截Intercept/放行Forward/重放Repeater全实现
java·开发语言·c++
l1t1 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程37-38
开发语言·python
迷藏4941 小时前
Python+DuckDB:轻量级BI流水线实战
java·开发语言·python·原型模式