Wanted to share a short piece of source code, since it’s my first program for the Pololu SV-328. I’ve purchased a Parallax Ping ultrasonic range sensor–got it off the shelf from radio shack actually–and hooked its three lines directly to the corresponding pins on my controller’s C5 line.
The source code below continually reads the sensor and reports the calculated distance in feet and inches. Seems to work quite well below about 2’; anything about that registers as 6’, meaning there was no reading.
#include <avr/io.h>
#include <util/delay.h>
#include <pololu/orangutan.h>
#define TICKS_PER_MSEC 2500UL
const unsigned char pulsePins[] = { IO_C5 };
int main (void)
{
unsigned long update = 0;
for (;;) {
// Send a trigger pulse
red_led(HIGH);
set_digital_output(pulsePins[0], HIGH);
delay_us(3);
set_digital_output(pulsePins[0], LOW);
red_led(LOW);
// Read a response pulse
pulse_in_start(pulsePins, 1);
set_digital_input(pulsePins[0], PULL_UP_ENABLED);
green_led(HIGH);
struct PulseInputStruct pulse_info;
do {
get_pulse_info(0, &pulse_info);
} while (get_ticks() - pulse_info.lastPCTime < (TICKS_PER_MSEC*20));
green_led(LOW);
pulse_in_stop();
// Speed of sound at sea level is 1116 feet per second (thanks, google)
// That's 13392 inches per second, or 0.013392 inches every microsecond.
// We have a pulse width in microseconds for the full trip; divide it by
// two (since the sound went out and back), and multiply time by
// this dist-per-time and we get distance in inches.
double distance = pulse_to_microseconds(pulse_info.lastHighPulse);
distance /= 2;
distance *= .013392;
// How was that? About every tenth of a second we'll update the display.
if (get_ticks() > update + (TICKS_PER_MSEC * 100)) {
clear();
lcd_goto_xy(0,0);
print("distance");
lcd_goto_xy(0,1);
unsigned long feet = (int)(distance / 12);
distance -= feet*12;
print_unsigned_long(feet);
print("' ");
unsigned long inches = (int)distance;
distance -= inches;
print_unsigned_long(inches);
print(".");
unsigned long tenths = (int)(distance * 10);
print_unsigned_long(tenths);
print("\"");
}
}
return 0;
}