Distance grapher

From ShawnReevesWiki
Revision as of 15:09, 16 June 2024 by Shawn (talk | contribs) (Categorizing in PT)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Arduino and HC-SR04 distance grapher

We use any Arduino connected to a computer running the Arduino Integrated Development Environment, and an HC-SR04, a very inexpensive ultrasonic distance sensor. The program periodically sends a trigger signal to the sensor, which in turn emits a series of eight blips in ultrasonic sound. The sensor listens for the blips to return, all the while keeping the "echo" signal pin high. Meanwhile, as soon as the trigger signal is sent, the Arduino keeps track of how long the echo signal pin is high. When the echo signal pin returns to low, the Arduino calculates how long the time of flight was, divides by two, and multiplies by the speed of sound to get the distance measured.

Circuit

It's always smart to make connections while Arduino is not powered, connected to USB or otherwise. You can choose any input-output pin, but avoid the ones labeled RX and TX, 0 and 1, if you are using UNO or similar non-native-USB board. Here we use 4 and 5. Arduino label <> HC-SR04 label:

  • GND <> GND
  • 5V <> VCC
  • 4 <> TRIG
  • 5 <> ECHO

Arduino code

const int soundMicrosecondsPerCentimeter = 29;
const int TRIG = 3;
const int ECHO = 5;
const unsigned long measurementPeriod = 100;//ms
unsigned long lastMeasurementTime = 0;
long duration, cm;


void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  pinMode(ECHO, INPUT);
  pinMode(TRIG, OUTPUT);
  digitalWrite(TRIG, LOW);
}

void loop()
{
  if(millis()-lastMeasurementTime > measurementPeriod){
    lastMeasurementTime = millis();
    digitalWrite(TRIG, LOW);
    delayMicroseconds(2);
    digitalWrite(TRIG, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIG, LOW);
    duration = pulseIn(ECHO, HIGH);
    cm = duration/soundMicrosecondsPerCentimeter/2;
    Serial.print(cm);
    Serial.println("cm");
  }
}

Graphing

Once the circuit is set up, the HC-SR04 is pointing where you want it, the Arduino is connected to power, and the code is uploaded to the Arduino, turn on "Serial Plotter" from the Tools menu of the Arduino IDE. It will plot numbers it sees coming in the same serial port used to upload the code. Be sure the baud rate in Serial Plotter matches that in the code.