LED学习笔记

蓝桥杯单片机——LED学习笔记

例程一:点亮一个LED

代码:

#include  "stc15.h"//注意头文件的写法
void main(){
	P2=0xa0;	P0=0x00;	P2=0x80;	P0=0xff;//与锁存器有关,具体参见原理图
	while(1){
		P00 = 0;//这个型号的单片机可以直接写成这样,一般写为P0_0或P0^0
	}
}

例程二:单个LED闪烁

说明:这里为了实现闪烁调用了延时函数1

代码:

#include <STC15F2K60S2.H>//这里头文件直接用KEIl右键添加的IAP15f2k61s2的型号

void Delay(unsigned int time);//延时函数的参数一定注意,是int不是char

void main(){
	P2=0xa0;	P0=0x00;	P2=0x80;	P0=0xff;//初始化一定不要忘记写
	while(1){
		P02 = 0;	Delay(50);
		P02 = 1;	Delay(50);
	}
}

//1ms延时函数的写法,得背会
void Delay(unsigned int time){
	unsigned int i,j;
	for(i=0;i<time;i++)
		for(j=853;j>0;j--);
}

例程三:LED跑马灯

1.十六进制写法

代码:

 #include <STC15F2K60S2.H>
 
 void Delay(unsigned char time){
 	unsigned char i=11,j=190;
 	while(time--){
 		do{
 			while(--j);
 		}while(--i);
 	}
 }
 
 void main(){
 	P2=0xa0;	P0=0x00;	P2=0x80;	P0=0xff;
 	while(1){
 		P0=0xfe;	Delay(20);
 		P0=0xfd;	Delay(20);
 		P0=0xfb;	Delay(20);
 		P0=0xf7;	Delay(20);
 		P0=0xef;	Delay(20);
 		P0=0xdf;	Delay(20);
 		P0=0xbf;	Delay(20);
 		P0=0x7f;	Delay(20);
		
 	}
 }

2.逻辑移位

说明:参考C语言逻辑移位2

代码:

 #include "STC15.h"

 void Delay(unsigned char time){
 	unsigned char i=11,j=190;
 	while(time--){
 		do{
 			while(--j);
 		}while(--i);
 	}
 }
 
 void main(){
 	P2=0xa0;	P0=0x00;	P2=0x80;	P0=0xff;
 	while (1)
 	{
 		unsigned char i;
 		for(i=0;i<8;i++){//注意这里的循环变量i实现了流水灯的效果,而不是逻辑移位是循环的
 			P0 = ~(0x01<<i);//0点亮LED,逻辑移位空位补零,因此需要移动1,再取反
 			Delay(20);
 		}
 	}
 }

3.调用移位函数

说明:需要使用intrins.h库调用函数3

代码:

#include "stc15.h"
#include "intrins.h"

unsigned char LED = 0xfe;
unsigned int s = 500;

void Delay(unsigned int time);

void main(){
	unsigned int i=300,count=0;
	P2=0xa0;	P0=0x00;	P2=0x80;	P0=0xff;
	while (1)
	{
		LED = _crol_(LED,1);
		P0 = LED;
		Delay(s);
		
	}
}
	
void Delay(unsigned int time){
	unsigned int i,j;
	for(i=0;i<time;i++)
		for(j=853;j>0;j--);
}

  1. C语言函数及其调用_c语言函数调用-CSDN博客 ↩︎

  2. 【C语言深度剖析】深入理解C语言中的移位操作符(代码+图解)_c语言右移补0还是1-CSDN博客 ↩︎

  3. Keil C51中头文件INTRINS.H的作用_keil 8051头文件-CSDN博客 ↩︎

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值