srf05_ultraschall.c


1
// Atmega 48 mit 16Mhz
2
#include <avr/io.h>
3
#include <util/delay.h>
4
#include <stdlib.h>
5
6
#define SIMULATION 1
7
8
#define trigger()      DDRD  |=  (1<<PD0);
9
#define trigger_high() PORTD |=  (1<<PD0);
10
#define trigger_low()  PORTD &= ~(1<<PD0);
11
12
#define TICKS_PRO_US  2
13
#define NUM_MESSUNGEN 6
14
#define MM_PRO_US     5.8
15
16
// Max. Abstand wg. uint16_t: 5649/NUM_MESSUNGEN mm
17
uint16_t abstand;
18
uint8_t ergebnis[6];
19
20
uint16_t echoticks(void)
21
{
22
   // Timer vorbereiten
23
   TCCR1A = 0x00;
24
   TCNT1 = 0;
25
26
   // Ultraschallimpuls senden
27
   trigger_high();
28
   _delay_us(20); // Mindestlänge eines Ultraschall-Sendepulses
29
   trigger_low();
30
31
   // LOW-Phase abwarten bis Echo kommt (ca. 700µs)
32
#if (SIMULATION == 1)
33
   _delay_us(700);
34
#else
35
   while(!(PIND & (1<<PD1))){}
36
#endif
37
38
   // HIGH auf PD1 = Echolänge in Timerticks messen
39
   // 16 MHz / 8 => 2 Ticks/µs
40
   TCCR1B = (1<<CS11); // Timer starten, CS11: Prescaler /8
41
#if (SIMULATION == 1)
42
   _delay_us(1682);
43
#else
44
   while(PIND & (1<<PD1)){}
45
#endif
46
   TCCR1B = 0x00;      // Timer stoppen
47
   
48
   // Ergebnis zurückgeben
49
   return TCNT1;
50
}
51
52
int main(void)
53
{
54
  // IO einstellen
55
  trigger(); 
56
57
  while ( 1 ) {
58
    abstand = 0;
59
    for ( uint8_t i = 0; i < NUM_MESSUNGEN; i++) {
60
#if (SIMULATION == 0)
61
      _delay_ms(50); // Mindestzeit bis SRF05 wieder bereit ist
62
#endif
63
      abstand += echoticks();
64
    }
65
    abstand /= TICKS_PRO_US * NUM_MESSUNGEN * MM_PRO_US;
66
    utoa(abstand, ergebnis, 10);
67
  }
68
}