Kaguei Nakueka
Kaguei Nakueka

Reputation: 1128

ATMEGA168A - Using timer

I am trying to understand how to use timers with my ATMEGA168A, however the example I have (link) doesn't seem to work since it returns 0 all the time.

My idea is to make a HC-SR04 (link) ultra sound sensor work.

#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;
}

How can I successfully measure the amount of time the PD2 was high?

Upvotes: 0

Views: 97

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

To measure the amount of time the PD2 was high, write some code to do so, compile, write it to your microcontroller and turn on it.

Not tested, try this:

#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;
}

Upvotes: 1

Related Questions