实验一:点亮LED灯并使其闪烁:
学习视频:8.7-点亮第一个LED--LED闪烁编程_哔哩哔哩_bilibili
#include <REGX52.H>
typedef unsigned int u16;
typedef unsigned char u8;
sbit LED1 = P2^0; //重命名:将 P2.0 命名为 LED1
void delay10us(u16 ten_us) //延时程序,输入ten_us为1,则延时10us =1e-6s
{
while(ten_us--);
}
void main()
{
while(1)
{
LED1 = 0; //点亮LED1
delay10us(50000); //延时450ms
LED1 = 1; //熄灭LED1
delay10us(50000);
}
}
实验二:流水灯,依次点亮LED1-8,完成后又继续点亮LED1-8:
学习视频:8.8-点亮第一个LED--使用左移实现流水灯编程_哔哩哔哩_bilibili
#include "reg51.h"
#include "intrins.h" // <<左移 和 >>右移 所包含的库函数
typedef unsigned int u16;
typedef unsigned char u8;
#define LED_PORT P2 // 宏定义,用LED_PORT 定义 P2(LED引脚接口)
void delay10us(u16 ten_us) // 延时程序
{
while(ten_us--);
}
void main()
{
u8 i=0; // char i
while(1)
{
for(i=0;i<8;i++)
{
LED_PORT=~(0x01<<i); // 看解析2.1
delay10us(50000); // 延时程序:50000*10us=500ms
}
}
}
解析2.1: LED_PORT=~(0x01<<i);
LED_PORT:P2接口,有8bit位,0000 0000 分别代表 P2.8—P2.0。当位置为0时,对应的LED灯被点亮。如:1111 1110 代表P2.0被点亮,1111 1101 代表P2.1被点亮,以此类推。
~ :取反操作。
0x01<<i :0000 0001 左移 i 位。
当i=0时: LED_PORT= ~(0000 0001)——> LED_PORT= 1111 1110 ——> LED只有P2.0亮
当i=1时: LED_PORT= ~(0000 0010)——> LED_PORT= 1111 1101 ——> LED只有P2.1亮
当i=8时: LED_PORT= ~(1000 0000)——> LED_PORT= 0111 1111 ——> LED只有P2.7亮
在for循环中,实现依次点亮P2.0-2.7。 在while循环中,又从P2.0开始for循环。
实验三:流水灯,使用库函数交替点亮LED1-8,完成后点亮LED8-1:
intrins.h 自带左移和右移的函数:_crol_左移 和 _cror_右移
学习视频:8.9-点亮第一个LED--使用左移右移库函数实现流水灯_哔哩哔哩_bilibili
#include "reg51.h"
#include "intrins.h" // 库函数,名字别错了,intr ins 这样好记
typedef unsigned int u16;
typedef unsigned char u8;
#define LED_PORT P2 // 宏定义
void delay10us(u16 ten_us) // 延时程序
{
while(ten_us--);
}
void main()
{
u8 i = 0;
LED_PORT = 0xfe; // 初始化,P2 = 1111 1110 先点亮P2.0
while(1)
{
for(i=0;i<7;i++)
{
LED_PORT=_crol_(LED_PORT,1); // _crol_(LED_PORT,1) 将LED_PORT左移1位
delay10us(50000);
}
// 左移结束后右移 P2.0 -> P2.8 -> P2.0
for(i=0;i<7;i++)
{
LED_PORT=_cror_(LED_PORT,1); // _cror_(LED_PORT,1) 将LED_PORT右移1位
delay10us(50000);
}
}
}
上述笔记为学习所用,如有侵权,Call我必删!