#include <mega128.h>
#include <delay.h>
#define LCD_RS PORTA.0
#define LCD_RW PORTA.1
#define LCD_EN PORTA.2
#define LCD_Data PORTA
#define Trigger PORTD.0
unsigned int distance = 0;
unsigned int cm_count = 0;
void LCD_E(void)
{
LCD_EN = 1;
delay_us(250);
LCD_EN = 0;
}
void LCD_Command(unsigned char rs, unsigned char rw, unsigned char data)
{
LCD_RS = rs;
LCD_RW = rw;
LCD_Data = ((LCD_Data & 0x0f) | (data & 0xf0));
LCD_E();
LCD_Data = ((LCD_Data & 0x0f) | ((data<<4) & 0xf0));
LCD_E();
delay_ms(2);
}
void LCD_Init(void)
{
delay_ms(30);
LCD_Command(0,0,0x20);
delay_ms(10);
LCD_Command(0,0,0x20);
delay_us(200);
LCD_Command(0,0,0x20);
LCD_Command(0,0,0x20);
LCD_Command(0,0,0x28);
LCD_Command(0,0,0x0C);
LCD_Command(0,0,0x01);
LCD_Command(0,0,0x06);
}
void LCD_Position(unsigned char x,unsigned char y)
{
if(y==0) LCD_Command(0,0,0x80+x);
else LCD_Command(0,0,0xC0+x);
}
void LCD_string(char x, char y, char flash *str)
{
LCD_Position(x,y);
while(*str) LCD_Command(1,0,*str++);
}
unsigned int AD_CON(unsigned char CH)
{
ADMUX=CH;
delay_us(10);
ADCSRA = ADCSRA | 0x40;
while ((ADCSRA & 0x10) ==0);
ADCSRA = ADCSRA | 0x10;
return ADCW;
}
void Putchar(unsigned char data)
{
while((UCSR0A & 0x20) == 0x00);
UDR0 = data;
}
void UltraSonic_Start(void)
{
Trigger = 1;
delay_us(10);
Trigger = 0;
#asm("sei")
}
void main(void)
{
DDRC = 0xff;
PORTC = 0xff;
DDRA = 0xff;
DDRD.0 = 1;
DDRD.1 = 0;
DDRE.4 = DDRE.5 = DDRE.6 = DDRE.7 = 0;
LCD_Init();
TCCR0 = 0x03; // 64 분주
TCNT0 = 241; // 58us
TCCR0 = 0x02; // 64 분주
TCNT0 = 139; // 58us
LCD_string(0,0,"Ultra-Sonic ");
LCD_string(0,1,"Dis: cm ");
EIMSK = 0x02;
EICRA = 0xc0;
#asm("sei")
while (1){
UltraSonic_Start();
LCD_Position(4,1);
LCD_Command(1,0,distance/100+0x30);
LCD_Command(1,0,(distance%100)/10+0x30);
LCD_Command(1,0,distance%10+0x30);
delay_ms(100);
}
}
interrupt [TIM0_OVF] void timer_0 (void)
{
TCNT0 = 139;
cm_count++;
}
interrupt [EXT_INT1] void ext_int1(void)
{
if(EICRA == 0x0C) {
TIMSK = 0x01; TCCR0 = 0x02; TCNT0 = 139;
EICRA = 0x08;
}
else {
TIMSK = 0x00; TCCR0 = 0x00;
EICRA = 0x0C;
distance = cm_count;
if( cm_count >= 400 ) distance = 0;
cm_count = 0;
#asm("cli")
}
}
'IT > CodeVision atmega128' 카테고리의 다른 글
ATmega128을 이용한 문자 'C' 표시하기 (0) | 2022.07.14 |
---|---|
Atmega128을 이용한 0.5초 간격으로 : 깜빡이기 (0) | 2022.07.13 |
댓글