PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : HC-SR04 mit Atmega8 ansteuern



LarsMD
17.08.2014, 16:24
Hallo,

versuche leider vergebens den HC-SR04 mit dem Atmega zu verbinden bzw
anzusteuern.

Möchte eigentlich erstmal nur eine LED Leuchten lassen, wenn eine
ENtfernung unterschritten wird.
Kann sich den Code mal wer anschauen?
Wo liegt der Fehler?

Danke.




/*
* Ultraschall.c
*
* Created: 16.08.2014 17:21:46
* Author: Pi
*/
/*Sensor | MCU
_____________
Trig | PC0
Echo | PC1
*/
#include <avr/io.h>
//#include <util/delay.h>

#define US_PORT PORTC
#define US_PIN PINC
#define US_DDR DDRC

#define US_TRIG_POS PC0
#define US_ECHO_POS PC1


#define US_ERROR -1
#define US_NO_OBSTACLE -2

void HCSR04Init();
void HCSR04Trigger();

void HCSR04Init()
{
US_DDR|=(1<<US_TRIG_POS);
}

void HCSR04Trigger()
{
//Send a 10uS pulse on trigger line

US_PORT|=(1<<US_TRIG_POS); //high

//_delay_us(15); //wait 15uS

US_PORT&=~(1<<US_TRIG_POS); //low
}

uint16_t GetPulseWidth()
{
uint32_t i,result;

//Wait for the rising edge
for(i=0;i<600000;i++)
{
if(!(US_PIN & (1<<US_ECHO_POS)))
continue; //Line is still low, so wait
else
break; //High edge detected, so break.
}

if(i==600000)
return US_ERROR; //Indicates time out

//High Edge Found

//Setup Timer1
TCCR1A=0X00;
TCCR1B=(1<<CS11); //Prescaler = Fcpu/8
TCNT1=0x00; //Init counter

//Now wait for the falling edge
for(i=0;i<600000;i++)
{
if(US_PIN & (1<<US_ECHO_POS))
{
if(TCNT1 > 60000) break; else continue;
}
else
break;
}

if(i==600000)
return US_NO_OBSTACLE; //Indicates time out

//Falling edge found

result=TCNT1;

//Stop Timer
TCCR1B=0x00;

if(result > 60000)
return US_NO_OBSTACLE; //No obstacle
else
return (result>>1);
}




int main(void)
{
uint16_t r;
int d;
//_delay_ms(100);

HCSR04Init();

DDRB |= (1 << PB0);


while(1)
{
//Send a trigger pulse
HCSR04Trigger();
r=GetPulseWidth(); //Measure the width of pulse

d=(r/58.0);

if (d<5)
{
PORTB |= (1 << PB0);
}
else
{
PORTB |= (1 << PB1);
}
}
}

zschunky
18.08.2014, 08:11
Hallo,

ein paar Dinge:
- da PC0 und PC1 auch ADC Ports sind mußt Du sicherstellen dass AVCC am Atmega angeschlossen ist
- Du setzt nur PB0 als Ausgang und nicht PB1
- ob das an und sofort aus im Trigger ausreicht ist fraglich, Laut Timing Diagram sollten es schon 10us sein
- ich gehe davon aus, dass Deine Schaltung mit 16MHz läuft, sonst würde Deine Berechnung mit /58 nicht passen da der Timer Tick mit Deinem Result shift um 1 sonst nicht passt

- - - Aktualisiert - - -

ausserdem setzt du PB0 und PB1 nie zurück, werden daher dann dauerhaft an sein.