nowornever
LED Shift ~ 본문
자, 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);
}
}
다음과 같이 되네요
'Study' 카테고리의 다른 글
Firefox 주소검색창 검색엔진 변경 (0) | 2013.05.14 |
---|---|
Excel 에서 문자 카운트 ! (콤마로 구분 되어있을 경우) (0) | 2013.05.11 |
2013 Quadcopter project (0) | 2013.05.08 |
CRC (Cyclic Redundancy Check) 32 program (0) | 2013.05.06 |
LED 연습 문제 스스로 만들고 실험해보기 (0) | 2013.04.30 |