单片机-LED实验
1、51工程模版
#include "reg52.h"
void main(){
while(1){
}
}
2、LED灯亮
#include "reg52.h"
sbit LED1=P2^0;
void main(){
while(1){
LED1=0;
}
}
3、LED闪烁
#include "reg52.h"
sbit LED1=P2^0; //P2大写,默认是高电平
typedef unsigned int u16; //0~65535
typedef unsigned char u8; //0~255
void delay_10us(u16 ten_us){
while(ten_us--); //当传入ten_su=1,大约延时10us
}
void main(){
while(1){
LED1=0; //灯亮
delay_10us(50000); //延时 //500ms 450-500
LED1=1; //灯灭
delay_10us(50000);
}
}
4、LED流水灯
4.1从左向右依次亮
方法一
#include "reg52.h"
#define LED_PORT P2
typedef unsigned int u16;
typedef unsigned char u8;
void delay_10us(u16 ten_us){
while(ten_us--);
}
void main(){
u16 i=0;
while(1){
for (i=0;i<8;i++){
LED_PORT=~(0X01<<i);
delay_10us(50000);
}
}
}
方法二 左移函数 _corl_
#include "reg52.h"
#include "intrins.h"
typedef unsigned int u16;
typedef unsigned char u8;
#define LED_PORT P2//宏定义
void delay_10us(u16 ten_us){
while(ten_us--);
}
void main(){
u16 i=0;
LED_PORT=0XFE; //LED_PORT=~0X01; //1111 1110
delay_10us(50000);
while(1){
for(i=0;i<7;i++){
LED_PORT=_crol_(LED_PORT,1);
delay_10us(50000);
}
}
}
4.2从右向左依次亮
#include "reg52.h"
#include "intrins.h"
typedef unsigned int u16;
typedef unsigned char u8;
#define LED_PORT P2//宏定义
void delay_10us(u16 ten_us){
while(ten_us--);
}
void main(){
u16 i=0;
LED_PORT=0X7F; //0111 1111
delay_10us(50000);
while(1){
for(i=0;i<7;i++){
LED_PORT=_cror_(LED_PORT,1);
delay_10us(50000);
}
}
}