ATMEGA168A - 使用定时器

ATMEGA168A - Using timer

我想了解如何在我的 ATMEGA168A 上使用定时器,但是我的示例 (link) 似乎不起作用,因为它一直 returns 0。

我的想法是让 HC-SR04 (link) 超声波传感器工作。

#define F_CPU   1000000UL
#include <avr/io.h>
#include <util/delay.h>

long measure(){
    //Setting up the timer
    TCCR1B |= (1 << CS12) | (1 << CS11) | (1 << CS10);

    //Setting trigger as output
    DDRD |= (1 << PD1);

    //Setting echo as input
    PORTD |= (1 << PD2);

    //Triggering the hardware
    PORTD ^= (1 << PD1);
    _delay_us(10);
    PORTD ^= (1 << PD1);

    //Waiting until echo goes low
    TCNT1 = 0;
    while(bit_is_clear(PIND, PD2));
    long timer_value = TCNT1;

    //Calculating and returning the distance
    long distance = timer_value / 58.82;
    return distance;
}

如何才能成功测量 PD2 高电平的时间?

要测量 PD2 处于高电平的时间量,请编写一些代码来执行此操作,编译,将其写入您的微控制器并打开它。

未测试,试试这个:

#define F_CPU   1000000UL
#include <avr/io.h>
#include <util/delay.h>

long measure(){
    //Setting up the timer
    TCCR1B |= (1 << CS12) | (1 << CS11) | (1 << CS10);

    //Setting trigger as output
    DDRD |= (1 << PD1);

    //Setting echo as input
    PORTD |= (1 << PD2);

    //Triggering the hardware
    PORTD ^= (1 << PD1);
    _delay_us(10);
    PORTD ^= (1 << PD1);

    //Waiting until echo goes low (after Initiate)
    while(!bit_is_clear(PIND, PD2));
    //Waiting until echo goes high (Echo back starts)
    while(bit_is_clear(PIND, PD2));
    TCNT1 = 0;
    //Waiting until echo goes low (Echo back ends)
    while(!bit_is_clear(PIND, PD2));
    long timer_value = TCNT1;

    //Calculating and returning the distance
    long distance = timer_value / 58.82;
    return distance;
}