/* ========================================================================== *//* *//* UltraSonicSensorModule.c *//* (c) 2007 Frazras *//* CHIP: ATMega8535L 8MHz clock *//* *//* Description: The following code will send a pulse to the SRF04 ultrsonic *//* Ranger(sensor) and output the range in centimeters *//* *//* This code is free software; you can redistribute it and/or *//* modify it under the terms of the GNU Library General Public *//* License as published by the Free Software Foundation; either *//* version 2 of the License, or (at your option) any later version. *//* *//* ========================================================================== */#define F_CPU 1000000UL#include <avr/interrupt.h>#include <util/delay.h>//define times for start and end of signaluint16_t rising, falling;//this function sleeps s seconds (if F_CPU is set to frequency of processor)void sleep_sec(uint8_t s){ uint8_t i; while (s--) for (i = 0; i < 100; i++) _delay_ms(10);}//Timer1 capture interrupt service subroutineISR(TIMER1_CAPT_vect){ /*This subroutine checks to see if itwas start of pulse (rising edge) or was it end (fallingedge)and performs required operations*/ //if high level detected if ((bit_is_set(PIND, 6))){ //save start time rising=ICR1; //set to trigger next on falling edge TCCR1B = _BV(CS10);}else{ //save falling time falling=ICR1; //rising edge triggers next TCCR1B = _BV(CS10)|_BV(ICES1); //variable to display values on LED int led; //calculate the pulse width led = falling - rising; //convert to centimeters (cm) led /=58; //output range on LEDs DDRB = 0xFF; PORTB = (uint8_t)led; //display for 4 seconds //sleep_sec(4); } }void pulse(){ //send pulse throught PIN 1 DDRD = 0b00000001; PORTD= 0b00000001; //12 us delay asm volatile( "ldi r16, 31\n\t" "loop: dec r16\n\t" "brne loop\n\t" ); //Set PIN1 to LOW and end pulse PORTD= 0b00000000;}int main(){ //Input Capture Interrupt Enable TIMSK = _BV(TICIE1); //Enable Global interrupt sei(); //Send pulse to SRF04 ultrasonic sensor pulse(); //Start timer counter and Enable input capture on rising edge TCCR1B = _BV(CS10)|_BV(ICES1); while(1);}