Ultrasonic ranging

From Mech
Revision as of 16:35, 11 February 2009 by Ben Tollberg (talk | contribs) (→‎Code)
Jump to navigationJump to search

Original Assignment

In this project you will demonstrate that you can measure distances using an ultrasonic transmitter and receiver, at distances up to a few meters. While you could build from components (see, for example, this website), in this project you will use this pre-packaged PING))) ultrasonic sensor. Your results can be displayed on an LCD screen (see, e.g., C Example: Serial LCD or C Example: Parallel Interfacing with LCDs) or on a PC using the USB/RS-232 cable (see PIC RS232).

Overview

Ultrasonic Ranging.JPG

Circuit

Ultrasonic Ranging Schematic.jpg

Code

#include <18f4520.h>
#fuses HS,NOLVP,NOWDT,NOPROTECT
#use delay(clock=40000000)
#use rs232(baud=19200, UART1) // hardware UART; uses  RC6/TX and RC7/RX  

int16 timer;
float distance;

#INT_EXT             // designates that this is the routine to call when pin RB0/INTO changes state
void INT0isr() {
   SET_TIMER1(0);    // initialize timer 1 to 0
}

#INT_EXT1             // designates that this is the routine to call when pin RB1/INT1 changes state
void INT1isr() {
   timer=GET_TIMER1(); // records timer 1 value 
   distance=timer*.0000004*343; //scale timer, .0000004 represents the .8 
   //microsecond increments of Timer 1, 2 is to divide the distance by half, 343 
   //is the speed of sound in meters, which can be changed
   if(distance >.01) {
      printf("%f meters\n",distance); //print out the Value in meters
   }
}

void main() {
   enable_interrupts(INT_EXT);
   enable_interrupts(INT_EXT1);
   enable_interrupts(GLOBAL);
   ext_int_edge(0, L_TO_H);      // interrupt on INT0/RB0 pin, low to high transition
   ext_int_edge(1, H_TO_L);      // interrupt on INT1/RB1 pin, high to low transition
   
   setup_timer_1(T1_INTERNAL|T1_DIV_BY_8); // start timer T1, which counts in .8 microsecond increments
   
   while(true) {
      output_high(PIN_C5); //send signal to Ultrasonic Sensor for 5 microseconds
      delay_us(5);         
      output_low(PIN_C5);
      input(PIN_C5); // set pin to input, since the sensor has one pin for I/O, pin c5 can not be outputting a signal
      delay_ms(200); //changeable delay
}