1

我正在使用 Atmega16 来控制带有超声波传感器的 LED。基本上,如果距离小于 100 厘米,则 LED 会亮起,否则会熄灭。

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
#include <stdlib.h>


#define  Trigger_pin PA0

volatile int TimerOverflow = 0;


ISR(TIMER1_OVF_vect)
{
    TimerOverflow++;
}

int main(void)
{
    char string[10];
    long count;
    double distance;
    
    DDRA = 0x01;

    DDRB = 0x01;

    sei();              
    TIMSK = (1 << TOIE1);
    TCCR1A = 0x00;              

    while(1)
    {

        PORTA |= (1 << Trigger_pin);
        _delay_us(10);
        PORTA &= (~(1 << Trigger_pin));
        
        TCNT1 = 0;          
        TCCR1B = 0x41;      
        TIFR = 1<<ICF1;     
        TIFR = 1<<TOV1;     
        
        
        while ((TIFR & (1 << ICF1)) == 0);  
        TCNT1 = 0;          
        TCCR1B = 0x01;      
        TIFR = 1<<ICF1;     
        TIFR = 1<<TOV1;     
        TimerOverflow = 0;  

        while ((TIFR & (1 << ICF1)) == 0); 
        count = ICR1 + (65535 * TimerOverflow); 
        
        distance = (double)count / 466.47;
        if (distance <= 100)
            PORTB |= (1<<0);
        else PORTB &= (~(1<<0));
        
        _delay_ms(200);
    }
}

问题是我必须为我的项目使用 Atmega328p。因为 328p 没有PORTA,所以我将代码更改为:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
#include <stdlib.h>

#define  Trigger_pin 0
volatile int TimerOverflow = 0;
ISR(TIMER1_OVF_vect)
{
    TimerOverflow++;
}

int main(void)
{
    long count;
    double distance;
    
    DDRB = 0b00000011;
    sei();
    TIMSK1 = (1 << TOIE1);
    TCCR1A = 0;

    

    while(1)
    {
        PORTB |= (1 << 0);
        _delay_us(10);
        PORTB &= (~(1 << 0));
        
        TCNT1 = 0;
        TCCR1B = 0x41;
        TIFR1 = 1<<ICF1;
        TIFR1 = 1<<TOV1;
        
        while ((TIFR1 & (1 << ICF1)) == 0);
        TCNT1 = 0;
        TCCR1B = 0x01;
        TIFR1 = 1<<ICF1;
        TIFR1 = 1<<TOV1;
        TimerOverflow = 0;


        while ((TIFR1 & (1 << ICF1)) == 0);
        count = ICR1 + (65535 * TimerOverflow);
        distance = (double)count / 466.47;
        if (distance < 100)
        PORTB |= (1<<1);
        else PORTB &= (~(1<<1));
        _delay_ms(200);
    }
}

我正在使用 Proteus 进行模拟,并且在模拟日志中获得了正确的距离,但连接到 B 端口引脚 1 的 LED 保持关闭。可能是什么问题?引脚配置看起来不错,我遵循与以前相同的逻辑。

4

0 回答 0