Loading [MathJax]/extensions/TeX/AMSsymbols.js

Thursday, 29 November 2018

Distance Sensor


Another online purchase saw me get a set of HC-SR04 Ultrasonic sensors. These sensors contain an ultrasonic transmitter and receivers. Sound waves sent from the transmitter reflect off a distant surface and are sensed by the receiver. The time taken for the round trip can be used to calculate the distance. Details how it works are on the datasheet.
The company that sold the sensor, www.elegoo.com provided an download for Arduino, this consisted of a library and sample sketch.
The .cpp and .h files needed to be setup as an Arduino Library. To do this i needed to copy the files to ~/Arduino/Libraries/SR04/  The SR04 folder must match the library name.
The simple sketch below could then be created:
#include "SR04.h"
#define ECHO_PIN 11
#define TRIG_PIN 12

SR04 sr04 = SR04(ECHO_PIN, TRIG_PIN);
long distance;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  distance = sr04.Distance();
  Serial.print(distance);
  Serial.println("cm");
  delay(1000);
}

Unfortunately, when I tried to upload to the Arduino I got this error:

/home/jonathan/Development/Arduino/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libreadline.so.6: cannot open shared object file: No such file or directory

Looking in the /lib/x86_64-linux-gnu folder I discovered I only had libreadline.so.7.
An upgrade to Ubuntu 18.04 meant the installed version of the Arduino IDE, 1.6.7 was no longer compatible. However, simply installing the latest version 1.8.7 resolved the problem and I was able to upload the sketch.
Finally I added a piezoelectric buzzer configured to beep more rapidly the closer something got to the sensor.


The speaker was plugged into pin 8 and ground, with the code changed as below:
#define SPEAKER 8
void loop() {
  // put your main code here, to run repeatedly:
  distance = sr04.Distance();
  Serial.print(distance);
  Serial.println("cm");


  tone(SPEAKER, 550, 100);
  int delayTime = distance * 10;
  delay(delayTime);
}


This is what the setup looked like:


In practice the maximum distance reported by the sensor was around 1.25m.

No comments:

Post a Comment