首页 > 解决方案 > 使用两个超声波传感器测量距离

问题描述

我有 2 个超声波传感器,每个传感器在液晶显示器上显示测量距离,一个传感器(US1)由定时器 1 的输入捕获模式操作,并且工作正常,另一个(US2)使用中断操作,该中断检测回波中的任何逻辑变化传感器的引脚然后 timer0 开始计数,但它总是为零,任何人都可以帮助我,我正在使用 atmega32。

#include "LCD.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define  Trigger_pin    PA0    /* sensor 1 trig pin*/
int TimerOverflow = 0;
long TimerOverflow1 = 0;
long pulse = 0;
static volatile int i = 0;
void US1();
void US2();
ISR(TIMER1_OVF_vect)
{
    TimerOverflow++;    /* Increment Timer Overflow count */
}
ISR(INT0_vect)
 {
     if (i==1)
     {
         TCCR0=0;
         pulse=TCNT0;
         TCNT0=0;
         i=0;
     }
     if (i==0)
     {
         TCCR0|=(1<<CS00);
         TCNT0=0;
         i=1;
     }
 }
int main(void)
{
    DIO_init();
    LCD_init();
    DDRC=0xff;
    DDRA |= (1<<PINA0);    
    PORTC=0x00;    
    DDRD = 0b10111011;
    PORTD=0xff;
    sei();            /* Enable global interrupt */
    TIMSK |= (1 << TOIE1);    /* Enable Timer1 overflow interrupts */
    TCCR1A = 0;
    TCCR0 = 0;        
    GICR|=(1<<INT0);
    MCUCR|=(1<<ISC00);
     
    LCD_StringPos(2,10,"A5");
    
    while (1) 
    {
        US1();
        US2();
    }
}
void US1()
{
    long count;
    int distance;
    char st_lcd[10];
    /* Give 10us trigger pulse on trig. pin to HC-SR04 */
    PORTA |= (1 << Trigger_pin);
    _delay_us(15);
    PORTA &= (~(1 << Trigger_pin));
    _delay_us(15);
    TCNT1 = 0;    /* Clear Timer counter */
    TCCR1B = 0x41;    /* Capture on rising edge, No prescaler*/
    TIFR = 1<<ICF1;    /* Clear ICP flag (Input Capture flag) */
    TIFR = 1<<TOV1;    /* Clear Timer Overflow flag */
    /*Calculate width of Echo by Input Capture (ICP) */
    
    while ((TIFR & (1 << ICF1)) == 0);/* Wait for rising edge */
    TCNT1 = 0;    /* Clear Timer counter */
    TCCR1B = 0x01;    /* Capture on falling edge, No prescaler */
    TIFR = 1<<ICF1;    /* Clear ICP flag (Input Capture flag) */
    TIFR = 1<<TOV1;    /* Clear Timer Overflow flag */
    TimerOverflow = 0;/* Clear Timer overflow count */
    while ((TIFR & (1 << ICF1)) == 0);/* Wait for falling edge */
    count = ICR1 + (65535 * TimerOverflow);    /* Take count */
    //freq=count/F_CPU;      //freq =
    /* 8MHz Timer freq, sound speed =343 m/s */
    distance=count/933;
    itoa(distance,st_lcd, 10);
    LCD_StringPos(2,5,st_lcd);
    _delay_ms(1000);
}
void US2()
{
        long count=0;
        int dist=0;
       PORTD|=(1<<PIND0);
       _delay_us(15);
       PORTD &=~(1<<PIND0);
       char st_lcd2[10];
       count=pulse;
       dist=count/933;
       itoa(dist,st_lcd2, 10);
       LCD_StringPos(1,5,st_lcd2);
       _delay_ms(900);
}

标签: atmega

解决方案


推荐阅读