51单片机P0口接8个LED发光二极管,实现8个LED从右向左循环点亮3次后,接着8个LED从左向右再循环点亮3次,最后低4位与高4位LED交替闪烁3次,周而复始。写出代码(用delay( )函数进行时间控制)
时间: 2024-03-30 13:40:47 浏览: 118
好的,以下是代码:
```c
#include <reg51.h>
#define LED_PORT P0
// 延时函数
void delay(unsigned int count) {
unsigned int i, j;
for (i = 0; i < count; i++) {
for (j = 0; j < 120; j++) {
;
}
}
}
// 向右循环移位函数
unsigned char rotate_right(unsigned char data, unsigned char bit_num) {
return (data >> bit_num) | (data << (8 - bit_num));
}
// 向左循环移位函数
unsigned char rotate_left(unsigned char data, unsigned char bit_num) {
return (data << bit_num) | (data >> (8 - bit_num));
}
void main() {
unsigned char led_data = 0x01; // 初始值,低4位亮
unsigned char i, j;
while (1) {
// 8个LED从右向左循环点亮3次
for (i = 0; i < 3; i++) {
for (j = 0; j < 8; j++) {
LED_PORT = rotate_right(led_data, j);
delay(100);
}
}
// 8个LED从左向右循环点亮3次
for (i = 0; i < 3; i++) {
for (j = 0; j < 8; j++) {
LED_PORT = rotate_left(led_data, j);
delay(100);
}
}
// 低4位与高4位LED交替闪烁3次
for (i = 0; i < 3; i++) {
LED_PORT = 0xAA; // 10101010,低4位不亮,高4位亮
delay(100);
LED_PORT = 0x55; // 01010101,低4位亮,高4位不亮
delay(100);
}
}
}
```
希望能帮到你!
阅读全文