我正在尝试了解如何在我的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处于高电平的时间,请编写一些代码来完成此操作,然后编译,将其写入微控制器并打开它。
未经测试,请尝试以下操作:
#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/