一、点亮一个灯
设备信息:
LED1 ~ LED8 依次位于单片机 P2.7 ~ P2.0
#include <reg52.h>
sbit D1 = P2^0; // 将P2.0口赋值给D1变量
void main()
{
while(1)
{
D1 = 0; // 让P2.0口输出低电平,从而点亮LED
// P2 = 0xFE; // 也可通过直接给P2口赋值实现
}
}
二、LED流水灯
将 LED1 ~ LED8 依次点亮,即为流水灯。
#include <reg52.h>
void delay(int n) // 延时函数
{
int x, y;
for(x = 0 ; x < n; x++)
{
for(y = 0 ; y < 122 ; y++); //空跑122次大概为1ms
}
}
void main()
{
int i, L1, L2;
while(1)
{
L1 = 0xfe;
L2 = 0xff;
for(i=0 ; i<8 ; i++) //八个LED灯,所以需要移位8次
{
P2 = ~(L1 ^ L2); // 点亮LED
delay(200);
L1 <<= 1; // 左移一位
L2 <<= 1;
}
}
}
三、四联数码管显示
设备信息
- P0.0 ~ P0.4为数码管位选端
- P1.0 ~ P1.7为数码管段选端
- 数码管为共阳数码管
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar code table[]={
0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e
}; // 共阳数码管码表: 0 - F
void delay(uint n) // 延时函数
{
uint x, y;
for(x = 0 ; x < n; x++)
for(y = 0 ; y < 122 ; y++); //空跑122次大概为1ms
}
uint * split_num(uint n) // 将四位数拆分为独立的四个数字
{
uint nums[4];
nums[0] = n / 1000; // 千位
nums[1] = n % 1000 / 100; // 百位
nums[2] = n % 100 / 10; // 十位
nums[3] = n % 10; // 个位
return nums;
}
void main()
{
uint i, j, x, L1, *nums;
while(1)
{
for(i=0 ; i < 10000 ; i++) // i为在数码管上显示的4位数
{
nums = split_num(i); // 拆分数字
for(x=0 ; x<100 ; x++) // 该层循环控制数字增长速率
{
L1 = 0xF7; // 初始位选
for(j=0 ; j<4 ; j++) // 该层让四个数码管循环显示数字,利用余晖效应制造出同时显示的效果
{
P1 = table[*(nums + j)]; // 段选
P0 = L1; // 位选
delay(1); // 延时
L1 >>= 1; // 右移一位数码管
P0 = 0x00; // 消影
}
}
}
}
}
四、按键检测
设备信息
KEY1 ~ P3.6; KEY2 ~ P3.7 ; KEY3 ~ P3.3(INT1) ; KEY4 ~ P4.2
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit D1 = P2^0; // LED
sbit KEY1 = P3^6; // KEY
void delay(uint n) // 延时函数
{
uint x, y;
for(x = 0 ; x < n; x++)
for(y = 0 ; y < 122 ; y++); //空跑122次大概为1ms
}
void main()
{
uint tmp;
while(1)
{
tmp = KEY1; // 读取KEY的状态
if(tmp == 0)
{
delay(1); // 延时后再次读取,目的是消除抖动
tmp = KEY1;
if(tmp == 0)
D1 = ~D1; // 反转灯的状态
}
}
}
五、外部中断按键检测
#include <reg52.h>
sbit D1 = P2^0; // LED
sbit KEY3 = P3^3; // KEY(INT1)
void EX1_KEY(void)interrupt 2 // 外部中断1中断服务程序
{
D1 = ~ D1; // 翻转LED状态
}
void main()
{
D1 = 0;
IT1 = 1; // 设定外部中断1为边沿触发方式
EX1 = 1; // 开启外部中断1的中断允许
EA = 1; // 开启系统总的中断允许
while(1);
}
六、定时器
#include<reg52.h>
sbit D1 = P2^7;
void main()
{
D1 = 0;
TMOD = 0x01; //设置定时器0位工作模式1(M1,M0位0,1)
TH0 = (65536-45872)/256; //装初值11.0592M晶振定时50ms数为45872
TL0 = (65536-45872)%256;
TR0 = 1; //启动定时器0
ET0 = 1; //开定时器0中断
EA = 1; //开总中断
while(1);
}
void T0_time()interrupt 1 // T0 中断服务程序
{
TH0 = (65536-45872)/256; //重新装载初值
TL0 = (65536-45872)%256;
D1 = ~D1;
}