MENU

4 LED流水灯

July 4, 2020 • 51单片机

--- 当前时间: ---

4 LED流水灯

4.1 C语言常用预处理命令

#define的使用:

#define A P0    // Macro definition

4.2 循环左移右移函数

以下两个函数包含在库函数intrins.h里面(注意in后面没有s哦

_crol_(a, b);循环左移函数,a是左移的值,b是左移的位数

_cror_(a, b);循环右移函数,a是右移的值,b是右移的位数

4.3 实例代码

main.c

#include "reg52.h"
#include "intrins.h"

typedef unsigned char u8;            // 1 byte: 0 ~ 255
typedef unsigned int u16;            // 2 byte: 0 ~ 65535

#define LED P0                        // Macro definition of ports P0

void delay(u16 i)                    // The delay is about 10 us when i = 1
{
    while(i--);
}

void main()
{
    u8 i = 0;                        // Default is 0 in keil
    LED = 0x01;                        // The first port of P0: P0.0
    delay(50000);                    // Delay 450 ms
    while(1)
    {
        /****************** Method 1 ******************/
        /*
        for(i = 0; i < 8; i++)
        {
            LED = (0x01 << i);        // (0x01)16 = (0000 0001)2 => (0000 0010)2 => (0000 0100)2 => ...
            delay(50000);            // Delay 450 ms
        }
        */

        /****************** Method 2 ******************/

        /** Shift to the left **/

        for(i = 0; i < 7; i++)        // Why 7?
        {
            // To keep the cycle going, keep all lights from going out the 8th time
            LED = _crol_(LED, 1);    // REMEMBER to import its header file
            delay(50000);            // Delay 450 ms
        }


        /** Shift to the right **/

        for(i = 0; i < 7; i++)
        {
            LED = _cror_(LED, 1);
            delay(50000);            // Delay 450 ms
        }

    }
}
Last Modified: August 21, 2020
Archives QR Code
QR Code for this page
Tipping QR Code