超声波传感器测量距离,可变溢流

时间:2014-02-24 21:56:54

标签: c avr robotics

Hy,我有超声波传感器测量距离,没有其他类型是我的变量“范围”(uint8_t,uint16_t,32,64)我总是溢出,而且传感器从0再次开始..有没有办法我可以限制“范围”变量,或者我必须用脉冲宽度来限制它...谢谢

SENSOR_DDR |= (1<<TRIGGER_PIN);  
SENSOR_DDR &= ~(1<<ECHO_PIN) & ~(1<<PB3) & ~(1<<PB2) & ~(1<<PB1) & ~(1<<PB0); 
DDRD = DDRD | _BV(4); 
PORTD = PORTD | _BV(4);
ENGINE_DDR = 0xff; 
ENGINE_PORT = 0;

lcd_init(LCD_DISP_ON);
lcd_clrscr();
lcd_puts("Something wrong...");


while(1)
{

PORTB |= (1<<PB4); //Send Trigger
_delay_us(10);
PORTB &= ~(1<<PB4); //Send trigger


timer0counter=0;
TCNT0=0; //Clear timer
while(bit_is_clear(PINB,5)); //Wait for rising edge
TCCR0 |= (1<<CS02); //Select prescalar 256
TIMSK |= (1<<TOIE0) | (1<<TOIE2); //Enable timer0 overflow interrupt

lcd_clrscr();

while(bit_is_set(PINB,5) && timer0counter<9) //wait for falling edge of echo
{
_delay_us(5);
}
TCCR0 &= ~(1<<CS02); //Stop timer
TIMSK &= ~(1<<TOIE0);
if(bit_is_set(PINB,5))
{
lcd_puts("No OBSTACLE");
}
else
{
range=(256*timer0counter+TCNT0)*32*0.017; //range conversion

lcd_clrscr();
lcd_puts("Distance:");
lcd_puts(itoa(range,buffer,10));
lcd_puts_P("cm");
}
if(range<15){
...

ISR(TIMER0_OVF_vect) 
{
TIMSK &= ~(1<<TOIE0);
TCNT0=0;
timer0counter++;

TIMSK |= (1<<TOIE0);

if(timer0counter>8)
{
TCCR0 &= ~(1<<CS02);
TIMSK &= ~(1<<TOIE0);

}

1 个答案:

答案 0 :(得分:0)

计算

256*timer0counter+TCNT0

将临时值保存在'default'size int中,在AVR上为16b。因此,每当timer0counter高于256时,无论变量的最终类型如何,它都会溢出。

而不是

range=(256*timer0counter+TCNT0)*32*0.017;

试着去:

double range_real = 256.0 * (double)timer0counter + (double)TCNT0 * 32.0 * 0.017;
range = (int) range_real;

明确关于类型可以真正拯救你的皮肤。