c - ATMEGA168A - 使用定时器

标签 c timer embedded atmega

我试图了解如何在我的 ATMEGA168A 上使用定时器,但是我有 (link) 的示例似乎不起作用,因为它总是返回 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 处于高电平的时间,请编写一些代码来执行此操作,编译,将其写入微 Controller 并打开它。

未经测试,试试这个:

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

关于c - ATMEGA168A - 使用定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34471193/

相关文章:

embedded - cortex a9 开机和内存

linux - 对硬件抽象层的说明

编译器错误 : cannot convert char* to char

c - 将 C 脚本迁移到 GoDaddy 托管帐户的最简单方法

c# - 具有类似于 Timer.Tick 的事件的精确计时器

c++ - QT,运行特定时间的功能

将 unix 时间戳转换为 YYYY-MM-DD HH :MM:SS

c - 如何仅使用标准库分配对齐的内存?

java - 可在 JVM Scala 和 Scala.js 中使用的计时器

linux - 从嵌入式 Linux 上的 shell 控制多个后台进程