FutureJones
Published © MIT

HC-SR04 Ultrasonic Measurement with Swift

In this tutorial, we will learn how to measure distance using the HC-SR04 Ultrasonic unit and Swift code.

EasyProtip1 hour3,806
HC-SR04 Ultrasonic Measurement with Swift

Things used in this project

Hardware components

Raspberry Pi 3 Model B
Raspberry Pi 3 Model B
×1
Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
×1
Raspberry Pi Zero
Raspberry Pi Zero
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Solderless Breadboard Half Size
Solderless Breadboard Half Size
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Resistor 330 ohm
Resistor 330 ohm
×1
Resistor 470 ohm
×1

Software apps and online services

Raspbian
Raspberry Pi Raspbian
Swift-Lite

Story

Read more

Schematics

HC-SR04 Wiring Setup

How to connect the HC-SR04 to Raspberry Pi.

Ultrasonic ranging module HC - SR04

Technical notes for the Ultrasonic ranging module HC - SR04

Code

piCodeUltrasonics.swift

Swift
This is the main project file for control of the HC-SR04 Ultrasonics unit.
// Created with PiCode for Swift 3.0
// A Swift-Lite project file
// type:project
// name:piCodeUltrasonics
// include:piCodeTime.swift
// include:piCodeGPIO.swift

import Glibc
import Foundation
import Dispatch

// auto detect board type (detects all boards with 40 GPIO pins)
let gpios = autoDetectBoardType()

// for older boards with 26 GPIO pins please set board type manually
//let gpios = PiCodeGPIO.RPIPlusZERO
//let gpios = PiCodeGPIO.RPIRev2

// set trigger pin
var gp_trigger = gpios[.P9]!
gp_trigger.direction = .OUT
gp_trigger.value = 0

// set echo pin
var gp_echo = gpios[.P11]!
gp_echo.direction = .IN
gp_echo.value = 0

// set echo time start/end variables
var startTime = DispatchTime.now()
var endTime = DispatchTime.now()

// Allow unit to stabilize for 0.5sec
wait(time: 0.5)

func getDistance() -> String {
    
    // Send a 10 micro second pulse to trigger
    gp_trigger.value = 1
    wait(time: 0.00001) // wait for 10 microseconds
    gp_trigger.value = 0
    
    // listen for echo return
    while (gp_echo.value == 0) {
        startTime = DispatchTime.now()
    }
    while (gp_echo.value == 1) {
        endTime = DispatchTime.now()
    }
    
    // Caculate echo time
    let timeInterval = endTime.uptimeNanoseconds - startTime.uptimeNanoseconds
    print("echo time: \(timeInterval) nanoseconds")
    // multiplied by the speed of sound (cm/nanoseconds)
    var distance:Double = Double(timeInterval) * 0.000034300
    // Divide by 2 as it was a return distance
    distance = distance / 2
    // limit result to 2 decimal places
    let cm = String(format: "%0.2fcm", distance)
    
    return cm
}

var counter = 5  // set number of measurments

while (counter > 0) {
    let measurment = getDistance()
    print ("Distance : \(measurment)")
    counter -= 1
    
    wait(time: 1)  // allow 1 second between measurments
}

piCodeTime.swift

Swift
A Swift-Lite module file. Used to insert wait time (delay).
// Created with PiCode for Swift 3.0
// A Swift-Lite module file
// type:module
// name:piCodeTime

import Glibc
import Foundation
import Dispatch

// function for inserting wait time in seconds
func wait(time: Double) {
    let nanoTime = time * 1000000000  // convert to nanoseconds
    let UI64Time = UInt64(nanoTime)  // convert to UInt64
    let pauseTime = DispatchTime.now().uptimeNanoseconds
    while (DispatchTime.now().uptimeNanoseconds <= pauseTime + UI64Time) {
        // wait time
    }   
}

Swift-Lite Sample Files.

Swift-Lite Project and Module sample files used with Hackster tutorials.

Credits

FutureJones

FutureJones

4 projects • 30 followers
Development Engineer at Swift-Arm - Bringing Swift to the Raspberry Pi and other Arm SBC's. Designer and creator of Swift-Lite.

Comments