编写一个51单片机代码,要求:1.按下按键K1,流水灯。再次按下K1,切换为呼吸灯。 2.按下按键K2,切换为数码管计时器,当时间为2秒到4秒之间蜂鸣器响起。 3.再次按下按键K2,由数码管切换为呼吸...
时间: 2024-05-02 18:17:28 浏览: 102
很高兴为您提供51单片机代码,以下是代码:
```c
#include<reg52.h>
#include<intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit K1 = P3^0;
sbit K2 = P3^1;
sbit Beep = P3^2;
sbit LED = P2^0;
sbit SPEAKER = P2^3;
sbit SEG_A = P1^0;
sbit SEG_B = P1^1;
sbit SEG_C = P1^2;
sbit SEG_D = P1^3;
sbit SEG_E = P1^4;
sbit SEG_F = P1^5;
sbit SEG_G = P1^6;
sbit DIGIT_1 = P2^4;
sbit DIGIT_2 = P2^5;
sbit DIGIT_3 = P2^6;
sbit DIGIT_4 = P2^7;
uchar led_mode = 0; // 0: 流水灯模式 1: 呼吸灯模式
uchar timer_mode = 0; // 0: 呼吸灯模式 1: 计时器模式
uchar time_count = 0; // 计时器时间
uint count = 0; // 计时器计数器
// 数码管显示
void display(uint num) {
SEG_A = ~(num % 10 == 1 || num % 10 == 4 ? 0 : 1);
SEG_B = ~(num % 10 == 5 || num % 10 == 6 ? 0 : 1);
SEG_C = ~(num % 10 == 2 ? 0 : 1);
SEG_D = ~(num % 10 == 1 || num % 10 == 4 || num % 10 == 7 ? 0 : 1);
SEG_E = ~(num % 10 == 1 || num % 10 == 3 || num % 10 == 4 || num % 10 == 5 || num % 10 == 7 ? 0 : 1);
SEG_F = ~(num % 10 == 1 || num % 10 == 2 || num % 10 == 3 || num % 10 == 7 ? 0 : 1);
SEG_G = ~(num % 10 == 0 || num % 10 == 1 || num % 10 == 7 ? 0 : 1);
num /= 10;
DIGIT_1 = 0;
P0 = ~(num % 10);
DIGIT_1 = 1;
num /= 10;
DIGIT_2 = 0;
P0 = ~(num % 10);
DIGIT_2 = 1;
num /= 10;
DIGIT_3 = 0;
P0 = ~(num % 10);
DIGIT_3 = 1;
num /= 10;
DIGIT_4 = 0;
P0 = ~(num % 10);
DIGIT_4 = 1;
}
// 呼吸灯
void breath_led() {
uint i;
for (i = 0; i < 200; i++) {
LED = ~(i / 2);
_nop_();
_nop_();
_nop_();
_nop_();
}
for (i = 200; i > 0; i--) {
LED = ~(i / 2);
_nop_();
_nop_();
_nop_();
_nop_();
}
}
// 流水灯
void flow_led() {
uchar i;
for (i = 0; i < 8; i++) {
LED = ~(1 << i);
delay_ms(100);
}
}
// 计时器
void timer() {
display(count);
if (count >= 20 && count <= 40) {
SPEAKER = 1;
} else {
SPEAKER = 0;
}
if (count >= 50) {
count = 0;
}
}
// 延时函数
void delay_ms(uint ms) {
uint i, j;
for (i = 0; i < ms; i++) {
for (j = 0; j < 110; j++);
}
}
// 中断函数
void timer0_isr() interrupt 1 {
TH0 = (65536 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
if (timer_mode) {
count++;
timer();
}
}
// 主函数
void main() {
TMOD = 0x01;
TH0 = (65536 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
EA = 1;
ET0 = 1;
TR0 = 1;
while (1) {
if (K1 == 0) {
delay_ms(10);
if (K1 == 0) {
led_mode = !led_mode;
while (K1 == 0);
}
}
if (K2 == 0) {
delay_ms(10);
if (K2 == 0) {
timer_mode = !timer_mode;
count = 0;
while (K2 == 0);
}
}
if (led_mode) {
breath_led();
} else {
flow_led();
}
}
}
```
该代码实现了按下按键K1时,可以切换为流水灯和呼吸灯;按下按键K2时,可以切换为计时器和呼吸灯。当计时器时间为2秒到4秒之间时,蜂鸣器会响起。
注意:该代码并未进行严格的验证,若出现问题请自行进行排查。
阅读全文