BUS4TN007-3 / tehtävä 4 (assignment 4)

In this weeks assignment I had HC-SR04 Ultrasonic sensor that measures distance (Pictures below). I am sorry for the quality of the photos but it is something that we have to live with since I try to use as much as my own material as possible instead of using outside sources because a lot of the background information that I use in my assignments are from online sources and the coursebook that I have mentioned in the sources.

Anyway lets start with the assignment. Again I encourage you to see my older assignments for some background information. So when I started this assignment the very first problem that I encountered again was not being able to find the datasheet for this particular sensor but in the end I did manage to find the datasheet. Click this link to read the datasheet.


Note in the above picture that there is 4 pins and above the pins there is descriptions that mean the following:

VCC  = 5 volt supply
trig    = Trigger pulse input
echo = Echo pulse output
GND = Ground




So this sensor is all about using ultrasound to measure the distance of the object. The mechanism is close to how bats locate their food, other bats and objects. Basically it sends signal and the input comes when it bounces back from nearby objects. This way the sensor is able to calculate how far the object is. Please do note that it’s not easy to explain how sound moves from someone like me but I do know (Thanks to the internet) some basic things about it.The speed of sound = 343 seconds per meter or c = 343 m/s depending on the temperature of the air among other things. The sensor thus sends ultrasound (The speed depends) “where the measuring angle is 15 degrees”. Other things you should note are

– You should not worry about any health effects for small projects like this

– The sensor sends pulses (Look below and click on it to go to the original source)


Before I start with the assignment I must admit that I heavily borrowed code from other people because the test code looks pure evil but here is the link. I think that you can calculate the distance of the object by taking humidity into account also, but that is a bit more complicated code and I do not have time to go into that area.

The example code that I will be using is not mine so here is the link to the authors page, because why to invent something that was already invented. I just modified it a little bit, where Arduini will switch on the red LED when the object/s is out of range and when to switch the green LED on when the object is not out of range. The serial monitor print would be something like in the picture below.


Where the object for example your hand is moving either closer or farther away from the sensor. You can also place an object like cardboard box in front of the sensor and move it slowly away from it. Here is the code bit to calculate the distance of the object.

distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
  Serial.println(“Out of range”);
  digitalWrite(greenPin, LOW);
  digitalWrite(redPin, HIGH);
else {
  digitalWrite(redPin, LOW);
  digitalWrite(greenPin, HIGH);
  Serial.println(” cm”);

Here is few pictures of the wiring itself and again I did the wiring like it is for testing purposes so it was meant to be messy and sorry for the quality of the photo.




And lastly here is the code. I will probably try to decipher the test code and come up with my own code or just make my own functions later but for now this is the loaned code to show the functionality of the HC-SR04 sensor.

#define trigPin 12
#define echoPin 13
const int redPin = 7;
const int greenPin = 8;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);

void loop() {
int duration, distance; // creating variables
digitalWrite(trigPin, HIGH); // pin ON
delayMicroseconds(1000); //delay
digitalWrite(trigPin, LOW); // pin OFF
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println(“Out of range”);
digitalWrite(greenPin, LOW);
digitalWrite(redPin, HIGH);
else {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
Serial.println(” cm”);


In the setup method we start the serial port for displaying the status of the sensor. We also define the bits per second.

“Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. You can, however, specify other rates – for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate.

An optional second argument configures the data, parity, and stop bits. The default is 8 data bits, no parity, one stop bit.”

Where the sensor pins are given constant values with defined names.

"#define is a useful C component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don’t take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time.

This can have some unwanted side effects though, if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text).

In general, the const keyword is preferred for defining constants and should be used instead of #define.”

pinIn() means according to arduino website.

“Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds. Gives up and returns 0 if no pulse starts within a specified time out.

The timing of this function has been determined empirically and will probably show errors in longer pulses. Works on pulses from 10 microseconds to 3 minutes in length.”

With the digitalWrite() we either give the pin values HIGH (On) or LOW (Off).








Make: Arduino Bots and Gadgets by Tero and Kimmo Karvinen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s