Arduino Range Finder

I’ve been working w/ the LiquidCrystal library (which rocks), and the MaxSonar EZ4 (MB1040).  Same LCD as I used in previous posts.

Only reading one range finder so far, but this is a start. 

The LCD is set up in 4 bit mode – digital pins 12, 11, 5, 4, 3 and 2. 

PWM pin from the EZ4 is in digital 7.

Enough of that, here’s the code!


#include <LiquidCrystal.h>

 // these constants won't change.  But you can change the size of
 // your LCD using them:
 const int numRows = 2;
 const int numCols = 16;
 // initialize the library with the numbers of the interface pins
 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
 // pin hooked up to PWM from the ez4
 const int pwPin = 7;

 //variables needed to store values
 long pulse, inches, cm;

void setup() {
  // set up the LCD's number of rows and columns: 
  lcd.begin(numRows, numCols);
  // throw up a shameless banner
  writeLcd("Manatee Software", 0, 0, true);
  writeLcd("", 1, 0, false);  

// Main loop
void loop() { 

// update display
// the main process that loops
void updateDisplay()
    pinMode(pwPin, INPUT);

    //Used to read in the pulse that is being sent by the MaxSonar device.
  //Pulse Width representation with a scale factor of 147 uS per Inch.
  pulse = pulseIn(pwPin, HIGH);

  //147uS per inch
  inches = pulse/147;

// put in the label.  doesn't seem to hurt anything to clear here, but it's
// counter-intuitive.  Probably bad practice...
  writeLcd("Inches: ", 0, 0, true);

// set and print the inches from the calculation  
  lcd.setCursor(9, 0);

// write to the LCD at a defined position
void writeLcd(char data[], int line, int pos, bool clear)
  // clear if desired
  if(clear == true)

  lcd.setCursor(pos, line);

Leave a Reply

Your email address will not be published. Required fields are marked *