帮我写一份基于AT89C51型号共阴极的单片机代码,效果要求为利用定时/计数器T1产生定时时钟,由P1口控制8个发光二极管,使8个指示灯依次一个一个闪动,闪动频率为10次/(8个灯依次亮一遍为一个周期),循环。设晶振频率为12MHz。
时间: 2024-03-26 11:38:32 浏览: 77
89C51单片机定时/计数器0
好的,以下是基于AT89C51型号共阴极的单片机代码,实现8个指示灯依次闪动的效果:
```
#include <reg52.h>
#define FREQ 12000000UL // 晶振频率
sbit LED_1 = P1 ^ 0; // 指示灯1
sbit LED_2 = P1 ^ 1; // 指示灯2
sbit LED_3 = P1 ^ 2; // 指示灯3
sbit LED_4 = P1 ^ 3; // 指示灯4
sbit LED_5 = P1 ^ 4; // 指示灯5
sbit LED_6 = P1 ^ 5; // 指示灯6
sbit LED_7 = P1 ^ 6; // 指示灯7
sbit LED_8 = P1 ^ 7; // 指示灯8
void init_timer1() // 初始化定时/计数器 T1
{
TMOD |= 0x10; // T1 工作在模式1:16位定时器
TH1 = 0x00; // 高字节初始值为0
TL1 = 0x00; // 低字节初始值为0
TR1 = 1; // 启动 T1
}
void delay(uint16_t count) // 延时函数
{
uint16_t i, j;
for (i = 0; i < count; i++)
{
for (j = 0; j < 1000; j++);
}
}
void main()
{
uint8_t led_count = 0; // 记录当前亮灯的编号
uint16_t timer_count = 0; // 记录定时器计数器的值
init_timer1(); // 初始化定时/计数器 T1
while (1)
{
if (TF1) // T1 溢出中断
{
TF1 = 0; // 清除 T1 溢出中断标志
timer_count++; // 定时器计数器加1
if (timer_count == FREQ / 10 / 8) // 闪动频率为10次/(8个灯依次亮一遍为一个周期)
{
timer_count = 0; // 重置定时器计数器
led_count++; // 亮灯编号加1
if (led_count == 1) // 依次亮灯
{
LED_1 = 1; LED_2 = 0; LED_3 = 0; LED_4 = 0; LED_5 = 0; LED_6 = 0; LED_7 = 0; LED_8 = 0;
}
else if (led_count == 2)
{
LED_1 = 0; LED_2 = 1; LED_3 = 0; LED_4 = 0; LED_5 = 0; LED_6 = 0; LED_7 = 0; LED_8 = 0;
}
else if (led_count == 3)
{
LED_1 = 0; LED_2 = 0; LED_3 = 1; LED_4 = 0; LED_5 = 0; LED_6 = 0; LED_7 = 0; LED_8 = 0;
}
else if (led_count == 4)
{
LED_1 = 0; LED_2 = 0; LED_3 = 0; LED_4 = 1; LED_5 = 0; LED_6 = 0; LED_7 = 0; LED_8 = 0;
}
else if (led_count == 5)
{
LED_1 = 0; LED_2 = 0; LED_3 = 0; LED_4 = 0; LED_5 = 1; LED_6 = 0; LED_7 = 0; LED_8 = 0;
}
else if (led_count == 6)
{
LED_1 = 0; LED_2 = 0; LED_3 = 0; LED_4 = 0; LED_5 = 0; LED_6 = 1; LED_7 = 0; LED_8 = 0;
}
else if (led_count == 7)
{
LED_1 = 0; LED_2 = 0; LED_3 = 0; LED_4 = 0; LED_5 = 0; LED_6 = 0; LED_7 = 1; LED_8 = 0;
}
else if (led_count == 8)
{
LED_1 = 0; LED_2 = 0; LED_3 = 0; LED_4 = 0; LED_5 = 0; LED_6 = 0; LED_7 = 0; LED_8 = 1;
led_count = 0; // 重置亮灯编号
}
}
}
}
}
```
希望能够帮到你!
阅读全文