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

相关推荐
鲸渔30 分钟前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
威嵌神州34 分钟前
NXP P2020核心板技术解析:PowerPC架构与VxWorks存量项目迁移指南
嵌入式硬件·微服务·云原生·架构
星恒随风37 分钟前
从0实现C++ AI大模型接入SDK(三):环境搭建与ChatSDK快速上手——实现我们的第一个AI聊天程序
linux·开发语言·c++·人工智能·笔记
风落青芜40 分钟前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z1 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
fengkai45451 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
Zwawa2 小时前
步进电机路径规划:梯形曲线与S型曲线
c语言·单片机·嵌入式
MSTcheng.3 小时前
【LinuxIO篇】Linux学习第二十三弹——fopen和open有什么区别?从 FILE* 到 fd,讲透 Linux 文件 IO
linux·运维·学习·io·系统调用·fd
ShineWinsu3 小时前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤
2501_930707783 小时前
使用C#从 PowerPoint 演示文稿中提取图片
开发语言·c#·powerpoint