Things used in this project

Hardware components:
Pi 3 02
Raspberry Pi 3 Model B
×1
R8326274 01
Raspberry Pi 2 Model B
×1
Raspberry pi zero
Raspberry Pi Zero
×1
51gzz5eu9pl. sx425
HC-SR04
×1
Adafruit industries ada64 image 75px
Solderless Breadboard Half Size
×1
11026 02
Jumper wires (generic)
×1
08377 02 l
Resistor 330 ohm
×1
Resistor 470 ohm
×1
Software apps and online services:
Raspberry Pi Raspbian
Swift-Lite

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.swiftSwift
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.swiftSwift
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

Oeq87mf14w7ffi52nxro
FutureJones

Development Engineer at SwiftPi - Bringing Swift to the Raspberry Pi. Designer and creator of Swift-Lite.

Contact

Replications

Did you replicate this project? Share it!

I made one

Love this project? Think it could be improved? Tell us what you think!

Give feedback

Comments

Similar projects you might like

Setting Up Your Pi Cap on the Raspberry Pi 1, 2 or 3
Easy
  • 64
  • 2

Protip

Follow this tutorial to set up your Pi Cap with a Raspberry Pi 1 A+/B+, Raspberry Pi 2 or Raspberry Pi 3.

Setting Up Your Pi Cap on the Raspberry Pi Zero
Easy
  • 72
  • 2

Protip

Follow this tutorial to set up your Pi Cap with a Raspberry Pi Zero.

Secure Simple Remote Access for Camera Viewing
Easy
  • 2,001
  • 8

Full instructions

Turn your RPi into a full featured camera with remote access, end2end encryption, and easy user enrollment.

PiCorder
Easy
  • 3,606
  • 14

Full instructions

A simple Pi-based camcorder using the very nice HyperPixel touchscreen from Pimoroni.

RPi Serial Console Automation using Arduino
Easy
  • 234
  • 3

Full instructions

A follow-up article to "One Button Restart of a Stalled Raspberry Pi": 3 digital pins provide 8 separate functions that can be called.

Run uTorrent on Raspberry Pi
Easy
  • 467
  • 2

Protip

Step-by-step instruction of running uTorrent on Raspberry Pi 2 using ExaGear Desktop.

ProjectsCommunitiesTopicsContestsLiveAppsBetaFree StoreBlogAdd projectSign up / Login