This tutorial is compatible with all Raspberry Pi models with 40 GPIO pins. It may also work with the older 26 GPIO pin models with some code modification. To complete this tutorial, you will first need to install Swift-Lite on your Raspberry Pi. Details for this are in tutorial 1.

In this tutorial, we will be using a HC-SR04 Ultrasonic unit, a 330 Ohm resistor, a 470 Ohm resistor, a breadboard and some jumpers wires to connect to the Pi's GPIO pins.

The HC-SR04

The HC-SR04 uses ultrasonic pulses to measure distance in a similar way to a bat. The unit sends out a pulse and then listens for an echo. By measuring the time taken for the echo to return, we can calculate the distance to the object that reflected the pulse.

There are 4 connections on the device.

Power - This requires 5V

Ground

Trigger - We send a signal to this pin to start the pulse

Echo - This pin outputs 5V for the duration of the pulse if detected.

Special Note

The Echo pin outputs 5V. This is higher than the 3.3V rated input of the Raspberry Pi's GPIO pins. To avoid damage to the Pi, we need to reduce the 5V to under 3.3V. This can be easily achieved by using 2 resistors as a voltage divider. By using the resistors shown in the connection diagram, we can reduce the voltage to about 3V.

Other resistors can be used to achieve the same effect by using the formula:

V out = V in * Resistor 1 / ( Resistor 1 + Resistor 2)

More info on voltage dividers here.

Connecting the Hardware

Use the attached diagram to connect all the components. Take care with the order of the resistors and placement of the echo return jumper wire.

The HC-SR04 will plug straight into the breadboard as shown in the photo.

The Swift Code

The Swift code consists of a main project file piCodeUltrasonics.swift , the GPIO module file piCodeGPIO.swift and another small module file piCodeTime.swift . The GPIO module file is the same file that we used in the previous tutorial - GPIO Getting Started.

piCodeTime.swift is a small utility file that uses DispatchTime to insert delay or pause into the program. This can be used the same way as sleep or usleep .

The Main Project File

1. Include the required module files and import main libraries.

// 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

2. Detect board type and set up 2 GPIO pins, one for the " trigger " and one for the " echo ".

// auto detect board type (detects all boards with 40 GPIO pins) let gpios = autoDetectBoardType() // 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

3. Create 2 variables to store the start and end times of the pulse and echo.

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

4. Allow the unit to stabilize for 0.5 sec. Here we will use the " wait " function from the piCodeTime module.

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

5. Next we will create a function to send a pulse, listen for an echo and calculate the distance.

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 }

6. To finish we will create a loop to call the " getDistance " function.

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 }

Change the counter var to change the number of measurements. Change the " wait " time in the loop to change the time between measurements.

Download Sample Code

Open a Terminal window and ssh to your Raspberry Pi.

ssh pi@raspberrypi3x.local

Use " wget " to download the sample code package.

wget https://s3-us-west-2.amazonaws.com/swiftpi.swiftlite.v1/ultrasonicsSampleCode.tar.gz

Unzip (tar) the package.

tar -xzpf ultrasonicsSampleCode.tar.gz

Remove package file.

rm ultrasonicsSampleCode.tar.gz

We should now have 3 files. A project file called piCodeUltrasonics.swift and a module files called piCodeGPIO.swift and piCodeTime.swift .

All the code for these tutorials is now also available on Github.

Building the Project

Change to the " swiftProjects " directory.

cd swiftProjects

Use " swift-lite-build " to build the project.

swift-lite-build piCodeUltrasonics.swift Processing Files Building! Build Finished

In our projects directory we should now have a file called piCodeUltrasonics.swapp. Because we are accessing the GPIO pins we will need to use " sudo " with the run command.

sudo ./piCodeUltrasonics.swapp

We should see a series of measurements returned.

echo time: 587862 nanoseconds Distance : 10.08cm echo time: 588123 nanoseconds Distance : 10.09cm echo time: 587498 nanoseconds Distance : 10.08cm echo time: 587966 nanoseconds Distance : 10.08cm echo time: 588123 nanoseconds Distance : 10.09cm

Hope you enjoyed this tutorial. In the next tutorial, we will be connecting and controlling a Stepper Motor.