JSN-SR04_Gen3_RK
Data Structures | Public Member Functions | Static Public Member Functions | Protected Member Functions | Protected Attributes
JSN_SR04_Gen3 Class Reference

Class for a JSN-SR04 ultrasonic distance sensor. More...

#include <JSN-SR04_Gen3_RK.h>

Data Structures

class  Distance
 Utility class for holding a distance. More...
 
class  DistanceAlarm
 Settings for use with distance alarm mode. More...
 
class  DistanceAlarmGreaterThan
 Helper class to configure a GREATER_THAN DistanceAlarm with the specified distance and default hysteresis. More...
 
class  DistanceAlarmLessThan
 Helper class to configure a LESS_THAN DistanceAlarm with the specified distance and default hysteresis. More...
 
class  DistanceCm
 Helper class for specifying a Distance in centimeters. More...
 
class  DistanceInch
 Helper class for specifying a Distance in inches. More...
 
class  DistanceResult
 Structure passed to the callback when the distance has been retrieved. More...
 

Public Member Functions

 JSN_SR04_Gen3 ()
 Construct the object. You typically instantiate one of these as a global variable. More...
 
virtual ~JSN_SR04_Gen3 ()
 Destroy the object. More...
 
JSN_SR04_Gen3withTrigPin (pin_t trigPin)
 Specifies the TRIG pin (OUTPUT) More...
 
JSN_SR04_Gen3withEchoPin (pin_t echoPin)
 Specifies the ECHO pin (INPUT) More...
 
JSN_SR04_Gen3withUnusedPins (pin_t unusedPin1, pin_t unusedPin2)
 You must specify two GPIO that are not otherwise used that will be used as outputs by this library. More...
 
JSN_SR04_Gen3withMaxLengthMeters (float maxLengthM)
 The maximum length that can be measured in meters. Default: 1 meter. More...
 
JSN_SR04_Gen3withCallback (std::function< void(DistanceResult)> callback)
 Specify a callback function to be called on samples, errors, and alarm conditions. More...
 
JSN_SR04_Gen3withSamplePeriodic (std::chrono::milliseconds period)
 Enabling periodic sampling mode. More...
 
JSN_SR04_Gen3withSamplePeriodicMs (unsigned long periodMs)
 Enabling periodic sampling mode. More...
 
JSN_SR04_Gen3withDistanceAlarm (DistanceAlarm distanceAlarm)
 Enable distance alarm mode. More...
 
bool setup ()
 You typically call this from setup() after setting all of the configuration parameters using the withXXX() methods. More...
 
void loop ()
 You must call this from loop()
 
bool sampleOnce ()
 Get a sample from the sensor. More...
 
DistanceResult sampleOnceSync ()
 Synchronous version of sampleOnce - not recommended. More...
 
DistanceResult getLastResult () const
 Gets the last result code. More...
 
unsigned long getSampleTimeMs () const
 Returns the number of milliseconds it takes to process a sample. More...
 

Static Public Member Functions

static int countOneBits (uint16_t sample)
 Utility function to count the number of one bits in a 16-bit unsigned integer. More...
 

Protected Member Functions

void idleState ()
 State handler for idle, waiting to take a sample. More...
 
void startState ()
 State handler for when ready to start taking a sample. More...
 
void sampleState ()
 State handle to wait for samples, then act on them. More...
 
void setResult (DistanceResult::Status status, double distanceM=0.0)
 Used internally to set the result of the last measurement. More...
 
void distanceAlarmCallback (DistanceResult distanceResult)
 Function to handle the distance alarm. Used internally, called from sampleState() if distanceAlarm is configured. More...
 

Protected Attributes

pin_t trigPin = PIN_INVALID
 TRIG pin (OUTPUT)
 
pin_t echoPin = PIN_INVALID
 ECHO pin (input)
 
pin_t unusedPin1 = PIN_INVALID
 SCK output (1 mHz)
 
pin_t unusedPin2 = PIN_INVALID
 LRCK output (32 kHz)
 
float maxLengthM = 1.0
 Maximum distance that can be read (affects memory and sample period)
 
std::function< void(DistanceResult)> callback = nullptr
 Callback after sample or error.
 
size_t numSamples = 0
 Number of samples, depends on maxLengthM and leadingOverhead.
 
uint16_t * rxBuffer = nullptr
 ECHO pin buffer.
 
uint16_t * txBuffer = nullptr
 TRIG pin buffer.
 
bool isIdle = true
 True if in idleState.
 
DistanceResult lastResult
 The last sample read (single, periodic, or alarm)
 
unsigned long samplePeriodic = 0
 If in periodic sample mode, the number of milliseconds in period (0 = disabled)
 
DistanceAlarm distanceAlarm
 Distance alarm mode settings, if enabled. If distance == 0, then disabled.
 
bool inAlarm = false
 True if the distance alarm has been notified.
 
size_t leadingOverhead = 152
 How long in 16-bit samples from falling TRIG to rising ECHO (maximum, typical). Must be a multiple of 4.
 
unsigned long safetyTimeoutMs = 300
 Maximum amount of time to wait if sensor does not respond.
 
unsigned long sampleTime = 0
 millis value when last sample was taken, used for periodic sampling
 
std::function< void(JSN_SR04_Gen3 &)> stateHandler = &JSN_SR04_Gen3::idleState
 state handler function
 

Detailed Description

Class for a JSN-SR04 ultrasonic distance sensor.

Note: You can effectively only have one instance of this class per device, because there is only one I2S peripheral, which is what is used to implement the device driver.

Constructor & Destructor Documentation

◆ JSN_SR04_Gen3()

JSN_SR04_Gen3::JSN_SR04_Gen3 ( )

Construct the object. You typically instantiate one of these as a global variable.

Do not construct one of these objects on the stack in a function that returns. It needs to have a persistent lifetime to function correctly.

◆ ~JSN_SR04_Gen3()

JSN_SR04_Gen3::~JSN_SR04_Gen3 ( )
virtual

Destroy the object.

You typically instantiate one of these as a global variable, so it will never be deleted.

Member Function Documentation

◆ countOneBits()

int JSN_SR04_Gen3::countOneBits ( uint16_t  sample)
static

Utility function to count the number of one bits in a 16-bit unsigned integer.

Parameters
sampleThe uint16_t value to test
Returns
int A value from 0 to 16

This is optimized for the common cases of 0x0000 (0) and 0xffff (16).

◆ distanceAlarmCallback()

void JSN_SR04_Gen3::distanceAlarmCallback ( DistanceResult  distanceResult)
protected

Function to handle the distance alarm. Used internally, called from sampleState() if distanceAlarm is configured.

Parameters
distanceResult

◆ getLastResult()

DistanceResult JSN_SR04_Gen3::getLastResult ( ) const
inline

Gets the last result code.

Returns
DistanceResult

Normally you should use the callback, but if you want to poll instead of using a callback you can use this function for periodic, sample once, and alarm modes.

◆ getSampleTimeMs()

unsigned long JSN_SR04_Gen3::getSampleTimeMs ( ) const

Returns the number of milliseconds it takes to process a sample.

Returns
unsigned long number of milliseconds

In practice it might take a few milliseconds longer because of the delays in dispatching loop(). The value is calculated from the maxLengthM and leadingOverhead values.

With the default value of 1 meter maximum and 152 leadingOverhead, this returns 9 milliseconds.

In theory you could sample at around every 9 milliseconds, maybe 10, but it's probably best to limit it to 100 milliseconds, or even 500 milliseconds, to be safe. If you sample frequently, be sure to handle the case where BUSY status is returned. This means that that sensor has not yet reset the ECHO output low and a sample cannot be taken yet.

Note that the callback will not be called for at least this long, regardless of distance! The reason is that the sample buffer is not processed until the DMA engine stops writing to the entire buffer, and then it waits until in loop context again.

◆ idleState()

void JSN_SR04_Gen3::idleState ( )
protected

State handler for idle, waiting to take a sample.

Next state: startState, trigged by calling sampleOnce(). Note that periodic sampling calls sampleOnce() internally. Alarm mode automatically enables periodic sampling.

◆ sampleOnce()

bool JSN_SR04_Gen3::sampleOnce ( )

Get a sample from the sensor.

Returns
true
false

You still must configure the pins and call the setup() method. You must also call the loop() method from loop().

◆ sampleOnceSync()

JSN_SR04_Gen3::DistanceResult JSN_SR04_Gen3::sampleOnceSync ( )

Synchronous version of sampleOnce - not recommended.

Returns
DistanceResult

Using the asynchronous callback is preferable, but this call is provided to make it somewhat easier to convert code from other libraries.

◆ sampleState()

void JSN_SR04_Gen3::sampleState ( )
protected

State handle to wait for samples, then act on them.

Previous state: startState Next state: idleState

◆ setResult()

void JSN_SR04_Gen3::setResult ( DistanceResult::Status  status,
double  distanceM = 0.0 
)
protected

Used internally to set the result of the last measurement.

Parameters
statusThe status, such as SUCCESS, BUSY, ERROR, etc.
distanceMDistance in meters, optional. Usually only set for SUCCESS, ENTER_ALARM, and EXIT_ALARM.

◆ setup()

bool JSN_SR04_Gen3::setup ( )

You typically call this from setup() after setting all of the configuration parameters using the withXXX() methods.

You must call setup() before any samples can be taken.

◆ startState()

void JSN_SR04_Gen3::startState ( )
protected

State handler for when ready to start taking a sample.

Once the I2S peripheral has been initialized, goes into sampleState to wait for samples.

Previous state: idleState Next state: sampleState

◆ withCallback()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withCallback ( std::function< void(DistanceResult)>  callback)
inline

Specify a callback function to be called on samples, errors, and alarm conditions.

Parameters
callbackThe callback function
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

The callback function has the prototype;

void callback(DistanceResult distanceResult)

It can be a C++11 lambda, if desired, to call a class member function.

◆ withDistanceAlarm()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withDistanceAlarm ( DistanceAlarm  distanceAlarm)

Enable distance alarm mode.

Parameters
distanceAlarmThe distance alarm configuration
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

◆ withEchoPin()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withEchoPin ( pin_t  echoPin)
inline

Specifies the ECHO pin (INPUT)

Parameters
echoPinA pin, such as D2 or A0, or another port that is not being used, such as TX, RX, DAC, etc.
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

The ECHO pin is typically a 5V logic level. You MUST add a level shifter before connecting it to a Particle Gen 3 device GPIO because GPIO are not 5V tolerant on the nRF52!

The ECHO pin on a JSN-SR04 is driven by a push-pull driver so you can only connect a single sensor to a single GPIO.

◆ withMaxLengthMeters()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withMaxLengthMeters ( float  maxLengthM)
inline

The maximum length that can be measured in meters. Default: 1 meter.

Parameters
maxLengthMDistance in meters
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

This affects the amount of memory that is used, and also the amount of time a sampling takes. See the README for more information.

At the default is 1 meter, the memory is 2,080 bytes and the time is 9 milliseconds.

◆ withSamplePeriodic()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withSamplePeriodic ( std::chrono::milliseconds  period)
inline

Enabling periodic sampling mode.

Parameters
periodThe sampling period as a chrono literal, such as 500ms, 10s, etc.
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

It's recommended to specify a sampling period greater than safetyTimeoutMs milliseconds (currently 300). However, in practice you can specify a much faster sampling period, as low as getSampleTimeMs() milliseconds. The latter varies depending on the max length meters. At the default value of 1 meter, you can use a periodic sample rate at low as 10 milliseconds, however you might not get every sample. The sensor may not always reset in time an the BUSY error will be called on the callback.

◆ withSamplePeriodicMs()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withSamplePeriodicMs ( unsigned long  periodMs)
inline

Enabling periodic sampling mode.

Parameters
periodMsThe sampling period in milliseconds
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

It's recommended to specify a sampling period greater than safetyTimeoutMs milliseconds (currently 300). However, in practice you can specify a much faster sampling period, as low as getSampleTimeMs() milliseconds. The latter varies depending on the max length meters. At the default value of 1 meter, you can use a periodic sample rate at low as 10 milliseconds, however you might not get every sample. The sensor may not always reset in time an the BUSY error will be called on the callback.

◆ withTrigPin()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withTrigPin ( pin_t  trigPin)
inline

Specifies the TRIG pin (OUTPUT)

Parameters
trigPinA pin, such as D2 or A0, or another port that is not being used, such as TX, RX, DAC, etc.
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

◆ withUnusedPins()

JSN_SR04_Gen3 & JSN_SR04_Gen3::withUnusedPins ( pin_t  unusedPin1,
pin_t  unusedPin2 
)
inline

You must specify two GPIO that are not otherwise used that will be used as outputs by this library.

Parameters
unusedPin1A pin, such as D2 or A0, or another port that is not being used, such as TX, RX, DAC, etc.
unusedPin2A pin, such as D2 or A0, or another port that is not being used, such as TX, RX, DAC, etc. Must be different than unusedPin1.
Returns
JSN_SR04_Gen3& This object, for chaining options, fluent-style

You need to dedicate two other pins, unusedPin1 and unusedPin2. These must not be the same pin, and can't be used for anything else for all practical purposes. This is due to how the I2S peripheral works. You have to assign the I2S LRCK and SCK to pins or the nRF52 I2S peripheral won't initialize. You won't need these outputs for anything, but they do need to be assigned GPIOs. The signals happen to be 32 kHz for the LRCK and 1 MHz for SCK while getting a distance sample.


The documentation for this class was generated from the following files: