8.1_GPIO简介
电源引脚 VCC GND
晶振引脚 XTAL1(Crystal 1)
XTAL2
复位引脚 RST(Reset)
下载引脚 RxD (Receive Data,即串行数据接收引脚)
TxD (Transmit Data,即串行数据发送引脚)
管脚图查询---中文开发手册
8.2_P0结构框图
需要外接上拉电阻,才能输出高电平
P0.x 代表P0 ~ P7
三态门:输出端口三种状态
-
高电平
-
低电平
-
高阻态
8.3_P1&p2&p3结构框图
P1端口
准双向口
P2端口
内置上拉电阻
输出高电平不需要外接上拉电阻
弱上拉,可以外接上拉电阻,增强输出功能
P3端口
8.4_LED介绍
单向导电性(注意不要接反)
通常为:3mA ~ 20mA
导通压降:1.7V
通常长的脚为正极,短的为负极
8.5_硬件介绍和管脚介绍
硬件设计
RP9:排阻
P20是指P2管脚的第0脚
管脚定义介绍
sfr P2 = 0xA0; // P2管脚的第一个端口,即P20端口
sbit P2^0; // 与上一行等价,P20端口(0 XOR 任何数 == 任何数本身)
P2^1; // 0xA1, P21端口
P2^2; // 0xA2, P22端口
P2^3; // 0xA3, P23端口
P2^4; // 0xA4, P24端口
8.6_点亮第一个LED编程
#include "reg52.h"
sbit LED1 = P2^0; // 定义控制管脚
void main()
{
LED1 = 0; // 点亮
while(1)
{
}
}
8.7_LED闪烁编程
#include "reg52.h"
#include "intrins.h" // 左移,右移头文件
typedef unsigned char u8;//u8代表该变量是8位的无符号字符型数据
typedef unsigned int u16;//u16即代表该变量是16位的无符号整型数据
sbit LED1 = P2^0;
void delay_10us(u16 ten_us) // 当传入Ten_us=1时,大约延时10us
{
while(ten_us--);
}
void main()
{
while(1)
{
LED1 = 0; //点亮
delay_10us(50000); // 大约延时450ms
LED1 = 1; //熄灭
delay_10us(50000);
}
}
查看延时,软件模拟步骤:
-
点击魔术棒,点project,设置晶振为12或11.0952
-
点击debug按钮进行软件仿真(放大镜图标)
-
点击reset进行复位
-
设置断点
-
点击run进行运行
8.8_使用左移实现流水灯编程
#include "reg52.h"
typedef unsigned char u8;
typedef unsigned int u16;
#define LED_PORT P2 // 使用宏定义将p2端口定义
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
void main()
{
u8 i = 0;
while(1)
{
for(i = 0; i < 8; i++)
{
LED_PORT = ~(0x01<<i); //i=0,D1亮; i=1,
delay_10us(50000);
}
}
}
8.9_使用左移右移库函数实现流水灯编程
头文件
#include "intrins.h"
函数声明
左移: extern unsigned char _crol_ (unsigned char, unsigned char);
右移:extern unsigned char _cror_ (unsigned char, unsigned char);
参数说明
_crol_(a, b)
第一个参数为值,第二个参数为位数
注意
与<<(右补0)不同,库函数为循环左移右移
#include "reg52.h"
#include "intrins.h"
typedef unsigned char u8;
typedef unsigned int u16;
#define LED_PORT P2 // 使用宏定义将p2端口定义
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
void main()
{
u8 i = 0;
LED_PORT = ~0x01;
while(1)
{
for(i = 0; i < 7; i++) // 这里为<7
{
LED_PORT = _crol_(LED_PORT, 1);
delay_10us(50000);
}
for(i = 0; i < 7; i++) // 这里为<7
{
LED_PORT = _cror_(LED_PORT, 1);
delay_10us(50000);
}
}
}