loading
atmega128을 이용한 초음파센서 동작
본문 바로가기
IT/CodeVision atmega128

atmega128을 이용한 초음파센서 동작

by 쿠로쿠로네코 2022. 7. 17.
반응형

#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") 
        }
}

반응형

댓글