ultrasonic.c

gehe zur Dokumentation dieser Datei
00001 /*
00002  * 
00003  * code needs to be moved in asuro.c to be compilable
00004  */
00005 
00006 #include <util/delay.h>
00007 #include "asuro.h"
00008 #include "ultrasonic.h"
00009 
00010 int count40kHz;
00011 
00015 ISR(TIMER2_COMP_vect)
00016 {
00017         count40kHz++;
00018 }
00019 
00024 void InitUltrasonics(void)
00025 {
00026         // Change Oscillator-frequency of Timer 2
00027         // to 40kHz, no toggling of IO-pin:
00028   cli();
00029   TCCR2  = (1 << WGM21) | (1 << CS20);
00030         OCR2   = 100;              // 40kHz @8MHz crystal
00031         TIMSK  = (1 << OCIE2);     // OCIE2:  Timer/Counter2 Output Compare Match Interrupt Enable
00032         
00033         ADCSRA = (0 << ADEN);      // deactivate ADC
00034         ACSR  |= (1 << ACIS1);     // Comparator Interrupt on Falling Output Edge
00035 
00036         ADMUX  = 0x03;             // connect ADC3-input with comparator
00037         SFIOR |= (1 << ACME);      // connect ADC multiplexer to comparator
00038         DDRD  &= ~(1 << 6);        // use Port D Pin 6 as input (AIN0)
00039   sei();
00040 }
00041 
00046 void RestoreAsuro(void)
00047 {
00048   cli();
00049   TCCR2 = (1 << WGM20) | (1 << WGM21) | (1 << COM20) | (1 << COM21) | (1 << CS20);
00050         OCR2  = 0x91;              // duty cycle for 36kHz
00051         TIMSK &= ~(1 << OCIE2);     // OCIE2:  Timer/Counter2 Output Compare Match Interrupt Disable
00052 
00053         ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1); // clk/64
00054         ACSR  |= (0 << ACIS1);
00055 
00056         if(autoencode) {
00057                 EncoderInit();
00058         }
00059         sei();
00060         _delay_us(1);
00061 }
00062 
00066 int Chirp(void)
00067 {
00068         unsigned int sleeptime = 0, dist = 0;
00069 
00070         InitUltrasonics();
00071 
00072         // chripen:
00073         count40kHz = 0;
00074 
00075         while(count40kHz != 20) {
00076                 OCR2 = 100 + 20 / 2 - count40kHz;
00077         }
00078 
00079         TCCR2   = (1 << WGM21) | (1 << CS20);
00080         OCR2    = 100;
00081 
00082         // analyse echoes:
00083         while(TRUE) {
00084                 _delay_us(1);
00085                 sleeptime++;
00086 
00087                 if((ACSR & (1 << ACI))) {
00088                         dist = (unsigned int) ((long) ((344L * ((sleeptime * 1000L) / 72L) / 10000L) / 2L));
00089                         ACSR |= (1 << ACI);
00090                         break;
00091                 }
00092                 
00093                 ACSR |= (1 << ACI);
00094                 
00095                 if(sleeptime > 3500) {
00096                         return -1;
00097                 }
00098         }
00099         
00100         RestoreAsuro();
00101         return dist;
00102 }

Erzeugt am Sun Nov 18 18:24:52 2007 für ASURO Library von  doxygen 1.5.1-p1