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.
Code:/* * 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); } } }







Zitieren

Lesezeichen