STC51点亮LED
1.点亮LED
#include "reg52.h"
sbit LED1=P2^0; //将 P2.0 管脚定义为 LED1
void main()
{
LED1=0; //LED1 端口设置为低电平
while(1)
{
}
}
2.闪烁灯
重定义数据类型
typedef unsigned int u16; //对系统默认数据类型进行重命名
typedef unsigned char u8;
延时函数,通过 while 循环来实现。函数入口有一个形式参数 ten_us,如果 ten_us 等于 1,则 while 循环执行一次,调用该函数延时时间大 约 10us,当然使用循环来实现延时,这种延时是不精确的。
***********************************************
* 函 数 名 : delay_10us
* 函数功能 : 延时函数,ten_us=1 时,大约延时 10us
* 输 入 : ten_us
* 输 出 : 无
***********************************************
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
void main()
{
while(1)
{
LED1=0; //点亮
delay_10us(50000); //大约延时 450ms
LED1=1; //熄灭
delay_10us(50000);
}
}
3.流水灯
3.1位操作
#define LED_PORT P2 //使用宏定义 P2 端口
void main()
{
u8 i=0;
while(1)
{
for(i=0;i<8;i++)
{
LED_PORT=~(0x01<<i); //右移,然后取反赋值LED_PORT
delay_10us(50000);
}
}
}
3.2 使用左移_crol_、右移_cror_函数
除了使用 for 循环语句实现移位,KEIL C51 软件内还有对应的移位库函数,左移函数是_crol_(),右移函数是_cror_(),要使用这两个函数在我们的程序中 必须包含 intrins.h 头文件。这两个移位函数大家可以百度了解下,其内部实现 过程是看不到的,该移位函数实现的移位功能就相当于一个队列内循环移动,如果是左移,那么最高位就被移到最低位了,次高位变为最高位,依次类推。
void main()
{
u8 i=0;
LED_PORT=~0x01;
delay_10us(50000);
while(1)
{
for(i=0;i<7;i++) //将 led 左移一位
{
LED_PORT=_crol_(LED_PORT,1);
delay_10us(50000);
}
for(i=0;i<7;i++) //将 led 右移一位
{
LED_PORT=_cror_(LED_PORT,1);
delay_10us(50000);
}
}
}
本文来自博客园,作者:晚风也温柔,转载请注明原文链接:https://www.cnblogs.com/zxr-blog/p/17936848