1、左右来回循环的流水灯的电路连接见图4-6,显示规律如图4-7。实现本任务要求,可以有多种软件实现方法。下面列出了3种,具体如下
- 数组的字节操作实现
#include <reg51.h>
#define uchar unsigned char
uchar tab[16 ]={ 0xfe , 0xfd , 0xfb , 0xf7 , 0xef , 0xdf , 0xbf , 0x7f ,0xbf ,0xdf , 0xef , 0xf7 , 0xfb , 0xfd, 0xfe,0xff};/*前8个数据为左移点亮数据,后8个为右移点亮数据*/
void delay(uchar k)
{ uchar i,j;
for(i = 0; i < k; i++);
for(j = 0; j < 110; j++);
}
void main( ) /*主函数*/
{ uchar i;
while (1)
{ for(i = 0; i < 15; i++);
{ P1=tab[i];
delay( );}}}
- 移位运算符实现
#include <reg51.h>
#define uchar unsigned char
void delay(uchar k)
{ uchar i,j;
for(i = 0; i < k; i++);
for(j = 0; j < 110; j++);
}
void main( ) /*主函数*/
{ uchar i,temp;
while (1)
{ temp=0x01; /*左移初值赋给temp*/
for(i= 0; i < 8; i++);
{P1=~temp; /* temp取反后送P1口*/
delay( );
temp=temp<<1; } /* temp 中数据左移一位,最右位用0填*/
temp=0x80; /*赋右移初值给temp*/
for(i=0; i < 8; i++);
{ P1=~temp; /* temp取反后送P1口 */
delay( );
temp=temp>>1; /* temp 中数据右移一位*/
}
}
}
- 用移位函数实现
#include <reg51.h>
#include <intrins.h> /*包含左、右移位函数的头文件*/
#define uchar unsigned char
void delay(uchar k)
{ uchar i,j;
for(i = 0; i < k; i++);
for(j = 0; j < 110; j++);
}
void main( ) /*主函数*/
{ uchar i,temp;
while (1)
{ temp=0xfe; /*初值为0x11111110*/
for(i=0; i< 7; i++);
{ P1=temp; /* temp 值送入P1口*/
delay( ); /*延时*/
temp=_crol_( temp,1) ; /*执行左移函数,temp 中的数据循环
左移1位*/
}
for(i=0; i<7; i++);
{ P1=temp; /* temp 值送入P1口*/
delay( ); /*延时*/
temp=_cror_( temp,1) ; /*执行右移函数,temp中的数据循环右
移1位*/
}
}
}
2、开关量检测指示器2,AT89S51单片机P1.0和P1.1引脚接有两只开关S0和S1,两只引脚上的高低电平共有4种组合,这4种组合分别点亮P2.0~P2.3引脚控制的4只LED:LED0~LED3 (高电平点亮),编程实现此功能
#include <reg51.h> /* 包含头文件reg51.h */
void main( ) /* 主函数main( )* /
{ char state;
While(1)
{ P1=0xff; /* P1口为输入* /