Simple Ultrasonic Sensor Code

181019KA

Hello!

As a note, I’m using the HC-SR04 Ultrasonic sensors; they’ve got a VIN, GND, TRIG, and ECHO pins. Also, the sensors instantiated here definitely have incorrect pin values… I’ve changed them plenty of times since this code was written, and likely will continue to as this project evolves haha :). Here it is:

class Sensor{
  private:
  int trigPin;
  int echoPin;
  long duration;
  int distance;

   void trigger(){

   //clears the trigpin
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(2);
 digitalWrite(trigPin, LOW);

   }

  public:

  Sensor(int trig, int echo){
    trigPin = trig;
    echoPin = echo;

    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
  }

  int dist() {
    trigger();

 //reads the echopin and returns the sound wave travel time in ms
 duration = pulseIn(echoPin, HIGH);

 //calculate the distance
 distance = duration/29/2;
 return distance;
   }
};
Sensor br(22, 23); //ie back right
Sensor bm(25, 24);
Sensor bl(26, 27);
Sensor fr(28, 29);
Sensor fm(31, 30);
Sensor fl(32, 33);
void setup() {
  Serial.begin(9600);
}

void loop(){

Serial.print("br: ");
  Serial.println(br.dist());
  Serial.print("bm: ");
  Serial.println(bm.dist());
  Serial.print("bl: ");
  Serial.println(bl.dist());
  Serial.print("fr: ");
  Serial.println(fr.dist());
  Serial.print("fm: ");
  Serial.println(fm.dist());
  Serial.print("fl: ");
  Serial.println(fl.dist());
  Serial.println("---------------------");
  delay(1000);

}

Leave a Reply

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