Squirrels have fuzzy tails.
0 Members and 1 Guest are viewing this topic.
I already have it done! For the ATmega128. It may work with out any changes for the $50 robot. A lot of the AVR stuff is compatible.Justin
#define ULTRA_SONIC_MASK (1<<4)#define ULTRA_SONIC_OUT (DDRD|=ULTRA_SONIC_MASK)#define ULTRA_SONIC_IN (DDRD&=~ULTRA_SONIC_MASK)#define ULTRA_SONIC_SET (PORTD|=ULTRA_SONIC_MASK)#define ULTRA_SONIC_RESET (PORTD&=~ULTRA_SONIC_MASK)#define ULTRA_SONIC_CAP_RISING (TCCR1B|=(1<<ICES1))#define ULTRA_SONIC_CAP_FALLING (TCCR1B&=~(1<<ICES1))#define ULTRA_SONIC_IS_LOW (!(PIND&ULTRA_SONIC_MASK))#define ULTRA_SONIC_IS_HIGH (PIND&ULTRA_SONIC_MASK)void PINT_INIT (void)//call FIRST sets up timer 1 for capture, keeps output compare pins digital I/O{ TCCR1A=0; TCCR1B=2;}uint16_t get_ultra_sonic (void){ uint16_t fcap=0,scap=0,dist=0;//fcap stores first capture, scap stores second ULTRA_SONIC_OUT;//set pin to output ULTRA_SONIC_SET;//set pin to high _delay_us (10);//delay for a pulse ULTRA_SONIC_RESET;//set pin low ULTRA_SONIC_IN;//set pin to input Clear_ICF1;//clear the capture flag TCNT1=0;//set timer 1 to 0 to prevent overflow ULTRA_SONIC_CAP_RISING;//capture the rising edge of the pulse while (ICF1_Empty)//wait for capture { if (TCNT1>50000) return 0xFFFF; } Clear_ICF1;//clear the capture flag fcap=ICR1;//save the captured value ULTRA_SONIC_CAP_FALLING;//capture the falling edge of the pulse while (ICF1_Empty)//wait for capture { if (TCNT1>50000) return 0xFFFF; } Clear_ICF1;//clear the capture flag scap=ICR1;//save the captured value dist=scap-fcap;//subtract the timer values to find the pulse lenght dist*=0.0850725;//convert to mm return dist;}uint16_t ultra_sonic (void)//call this function for error checking!{ uint16_t dist; dist=0xFFFF; while (dist==0xFFFF) { dist=get_ultra_sonic(); _delay_ms(10);//prevent echos if there was an error. } return dist;}
Though only tested on an ATmega8 and ATmega168 is should port over to any AVR 8-bit RISC microcontroller