nowornever

LED Shift ~ 본문

Study

LED Shift ~

JohnnyKoo 2013. 5. 8. 19:55

자, Atmega128 로 LED를 shift 해 봅시다. 키 입력으로 해볼게요. 저도 아직 배우는 중이라, 버튼을 이용한 하드웨어 인터럽트로 LED shift  하는 것은 다음에 ㅎㅎ

자 일단 첫번째!, 버튼을 입력하면 LED 가 한칸씩 오른쪽으로 이동하는 코드입니다. 

코드를 보시면 아시다 시피, 핀 입력은 저항으로 풀업(pull-up) 이 되어있습니다.

따라서 버튼을 누르게 되면 전압이 저항을 타고 바로 GND 로 흘러버리게 되죠. 그렇게 되면 AVR 에서는 0, LOW 를 읽게 됩니다. 그 LOW 를 ~ 0x01, 즉 1 과 & 조건을 걸면 0이 되겠지요? 거기에 ! 반전, 참(TRUE)로 바꾸어버리면 그 안의 코드를 실행하게 됩니다.

그냥 버튼 이 HW 적으로 (외부) 풀업이 되어있다고 말하면 되는게 괜히 길게 말했네요. 

If 문은 그 안이 거짓이면 지나가거 참이면 실행을 하는 녀석입니다.

#include <AVR/io.h>
#include <util/delay.h>

// LED shifts when release the button

void delay(int n) // dealy func
{
    int i;
    for(i=0;i<=n;i++)
    {
        _delay_ms(1);
    }
}

void main(void)
{
    int i= 1;
    DDRE=0xFF; //set PORT E as output
    DDRD=0x00; //set PORT D as input
   
    PORTE = 0x01;

    while(1)
    { 
       if(!(PIND & 0x01))     // run this when PIND.1 is ON
            {
           while(~PIND & 0x01); // wait until relase the button 
           delay(20);
           PORTE = PORTE << i; // LED shifts
          
          
           if(PORTE == 0x00) // when shfts over the 8th LED then do as follows
          {
            PORTE = 0x01; //initialize the PORTE
             }
         }   
    }
}

코드를 실행하면 이렇게 됩니다


둘째! 이번에는 두개의 버튼 입력을 통해서 LED 를 좌,우로 shift 해 봅시다.

source code 는 다음과 같습니다.

#include <AVR/io.h>
#include <util/delay.h>

// LED shifts left and right with two tact switch

void delay(int n)
{
    int i;
    for(i=0;i<=n;i++)
    {
        _delay_ms(1);
    }
}

void main(void)
{
    int i= 1;
    DDRE=0xFF;
    DDRD=0x00;
   
    PORTE = 0x01;

    while(1)
    {
        if(!(PIND & 0x01))       // run below when push PIND.1
            {
       
           PORTE = PORTE << i; //LED shifts to the right
          
          
           if(PORTE == 0x00) //when it passes the 8th LED then initialize
          {
            PORTE = 0x01;
             }
         }
        else if(!(PIND & 0x02)) // run below when push PIND.2
        {
           
            PORTE = PORTE >> i; // LED shifts to the left

            if(PORTE == 0x00) //when it passes backward, 0th LED, then initialize
            {
                PORTE = 0x80;
            }
        }       
         while(~PIND & 0x01); // wait until release PIND.1
         while(~PIND & 0x02); // wait until release PIND.2
         delay(20);
           
    }   
}

다음과 같이 되네요