Skip to content
This repository has been archived by the owner on Oct 4, 2022. It is now read-only.

jasompi/HCSR04.swift

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A Swift library for the HC-SR04 (US-015 and similar) ultrasonic ranging sensors.

The project is based on SwiftyGPIO

Summary

This is library for HC-SR04 (US-015 and similar) ultrasonic ranging sensor which provide 3cm up to 500cm(depends on the used sensor) of non-contact measurement functionality with a ranging accuracy that can reach up to 3mm. Library allows to make a single or multiple sample measurement, detect timeout, hardware and measurement errors.

Supported Boards

Every board supported by SwiftyGPIO

Hardware details

The HC-SR04 (US-015 and similar) ultrasonic range sensor is very simple to use, however the signal it outputs needs to be converted from 5V to 3.3V so as not to damage your Raspberry Pi!

There are only four pins that you need to connect:

  • VCC (Power) - 5v
  • Trig (Trigger) - 3,3v signal from Raspberry is enough to trigger impulse
  • Echo (Receive) - signal need to be converted from 5V to 3.3V via voltage divider or logic level converter !!!
  • GND (Ground)

Voltage divider - look for Level Shifting section.
Logic level converter - simple to use and cheap level converter.

For more details read datasheet of your sensor.

Wiring

Installation

If your version of Swift supports the Swift Package Manager, You just need to add HCSR04 as a dependency in your Package.swift:

 .Package(url: "https://github.com/konifer44/HCSR04.swift.git", majorVersion: 1)

Swift Package Manager - look for Using the Package Manager section.

Usage

First you need to import necessary libraries.

import HCSR04
import SwiftyGPIO

Next step is initialization. Sensor is initialized by creating instance of class HCSR04 and providing:

  • Used Raspberry name.
  • GPIO which the ECHO pin is connected to.
  • GPIO which the TRIGGER pin is connected to.
  • Maximum range of your sensor in cm - check datasheet typically is 400cm.
var sensor = HCSR04.init(usedRaspberry: .RaspberryPiPlusZero, echoConnectedPin: .P21, triggerConnectedPin: .P20, maximumSensorRange: 400)

Single sample distance measurement:

You can start single sample measurement by calling measureDistance() method with no arguments. Because the measureDistance() method propagates any errors it throws, any code that calls this method must either handle the errors—using a do-catch statement, try?, or try!. In single sample measurement method measureDistance() takes sample immediately after calling it. If You want make next measurement You need to remember that producer of ultrasonic sensor suggest to use over 60ms measurement cycle, in order to prevent trigger signal to the echo signal, so You need to wait 60ms before You call measureDistance() again.

More about: Swift Error Handling

do {
  let distance = try sensor.measureDistance()
  print(distance)
} catch {
  print("Unexpected error: \(error)")   
}

Multiple samples distance measurement:

You can start multiple sample measurement which returns average distance by calling measureDistance(numberOfSamples: Int? = nil) method with an optional argument numberOfSamples
Depending on producer suggest to use over 60ms measurement cycle measureDistance(numberOfSamples: Int? = nil) method takes first sample immediately after calling it but every next sample is taken after 60ms.
In below example as You expected time of 5 sample measurement will take around 240ms and return average distance.

do {
  let distance = try sensor.measureDistance(numberOfSamples: 5)
  print(distance)
} catch {
  print("Error: \(error)")   
}

User provided timeout and errors:

In normal measurement, method measureDistance() using default timeout value to throw errors in three cases

  • echoSignalError //Disconnected echo, trigger pin or too fast measurements.
  • measuredDistanceIsOutSensorRange //Measured distance is out of sensor range.
  • userTimeout //User timeout interrupt.

Default value of timeout depends on your maximum sensor range, it's twice longer than maximum echo signal because it should't interrupt distance measurement. If You provide 400cm maximum sensor range the default timeout value will be around 45ms and after this time You can expect throwing an error. If You need change timeout value for some reasons You can provide it by calling method with optional argument measureDistance(providedTimeout: Int? = nil)
For example 40ms provided timeout:

do {
  let distance = try sensor.measureDistance(providedTimeout: 40)
  print(distance)
} catch {
  print("Error: \(error)")   
}

Remember that if You provide timeout shorter than maximum echo signal it will interrupt measurement and throw error.

If You need handle error separately, You can access enum ErrorList inside of class HCSR04

do {
  let distance = try sensor.measureDistance()
  print(distance)
} catch HCSR04.ErrorList.echoSignalError {
  //user error handling procedure
}catch HCSR04.ErrorList.measuredDistanceIsOutSensorRange {
  //user error handling procedure
}catch HCSR04.ErrorList.userTimeout {
  //user error handling procedure
}

More about: Swift Error Handling

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Swift 100.0%