51单片机入门class1.2

    xiaoxiao2023-06-01  170

    高电平点亮流水灯

    流水灯的电路图

    #include<reg51.h> void delay(unsigned int time) { unsigned char t; for(; time > 0;time--) for(t = 125; t > 0; t--); } void main(void) { unsigned char a = 0x01; while(1) { if( a == 0x00) a = 0x01; //注意高位溢出情况,若溢出则恢复 P2 = a; a = a << 1; //循环点亮 delay(1000); } }

    将流水灯逆序反复点亮

    #include<reg51.h> void delay(unsigned int time) { unsigned char t; for(; time > 0;time--) for(t = 125; t > 0; t--); } void main() { unsigned char a = 0x01; unsigned char true = 1; while(1) { while(true) { P2 = a; a = a << 1; delay(1000); if(a == 0x00) { a = 0x80; true = 0; } } true = 1; while(true) { P2 = a; a = a >> 1; delay(1000); if(a == 0x00) { a = 0x01; true = 0; } } true = 1; } }

    (优化过后)

    #include<reg51.h> void delay(unsigned int time) { unsigned char t; for(; time > 0;time--) for(t = 125; t > 0; t--); } void main(void) { unsigned char t; while(1) { P2 = 0x01; for(t = 0;t < 8;t++) { delay(1000); P2 = P2 << 1; } P2 = 0x80; for(t = 0;t < 8;t++) { delay(1000); P2 = P2 >> 1; } } }
    最新回复(0)