Driver for HC-SR04 connected to a Microbit

MicrobitUltrasound.cpp

Committer:
isaeldiaz@developer.mbed.org
Date:
2016-08-27
Revision:
4:c67cff7b9733
Parent:
3:8a5d2e5f64fb
Child:
5:5667dcf9c45d

File content as of revision 4:c67cff7b9733:

/*
The MIT License (MIT)

Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

/**
  * Class definition for MicroBitPin.
  *
  * Commonly represents an I/O pin on the edge connector.
  */
#include "MicrobitUltrasound.h"
#include "MicroBitConfig.h"
#include "MicroBitSystemTimer.h"
#include "MicroBitFiber.h"

/**
 * Constructor.
 * Create new MicrobitUltrasound that reports distance to closest object
 *
 * @param _trigPinName Name of the MicroBitPin to be used as trigger.
 *
 * @param _echoPinName Name of the MicroBitPin to be used as response from sensor.
 *
 * @code
 * MicroBitPin P1_PING = MicroBitPin(MICROBIT_ID_IO_P1, MICROBIT_PIN_P1, PIN_CAPABILITY_DIGITAL); 
 * MicroBitPin P2_ECHO = MicroBitPin(MICROBIT_ID_IO_P2, MICROBIT_PIN_P2, PIN_CAPABILITY_DIGITAL); 
 * MicrobitUltrasound uSoundSensor(P1_PING, P2_ECHO);
 * @endcode
 */
MicrobitUltrasound(PinName pingPinName, PinName echoPinName, uint16_t id)
{
  this->id            = id;
  this->status        = 0;
  this->sampleTime    = 0;
  this->echoDuration  = 0;
  this->pingPeriod    = MICROBIT_ULTRASOUND_PERIOD_DEFAULT_MS;
  this->pingDuration  = MICROBIT_ULTRASOUND_PING_DURATION_DEFAULT_US;

  ping = new DigitalOut(pingPinName);
  echo = new TimedInterruptIn(echoPinName);
  echo->mode((PinMode)MICROBIT_ULTRASOUND_PULLMODE_DEFAULT);
  echo->rise(this, &MicrobitUlstrasound::onEchoRise);
  echo->rise(this, &MicrobitUlstrasound::onEchoFall);
}


/**
  * This member function manages the calculation of the timestamp of a pulse detected
  * on a pin whilst in IO_STATUS_EVENT_PULSE_ON_EDGE or IO_STATUS_EVENT_ON_EDGE modes.
  *
  * @param eventValue the event value to distribute onto the message bus.
  */
void MicrobitUltrasound::pulseWidthEvent(int eventValue)
{
    MicroBitEvent evt(id, eventValue, CREATE_ONLY);
    uint64_t now = evt.timestamp;
    uint64_t previous = echo.getTimestamp();

    if (previous != 0)
    {
        evt.timestamp -= previous;
        evt.fire();
    }

    echo.setTimestamp(now);
}


/**
  * Interrupt handler for when an rise interrupt is triggered.
  */
void MicrobitUltrasound::onEchoRise()
{
    if(status & IO_STATUS_EVENT_PULSE_ON_EDGE)
        pulseWidthEvent(MICROBIT_PIN_EVT_PULSE_LO);

    if(status & IO_STATUS_EVENT_ON_EDGE)
        MicroBitEvent(id, MICROBIT_PIN_EVT_RISE);
}

/**
  * Interrupt handler for when an fall interrupt is triggered.
  */
void MicrobitUltrasound::onEchoFall()
{
    if(status & IO_STATUS_EVENT_PULSE_ON_EDGE)
        pulseWidthEvent(MICROBIT_PIN_EVT_PULSE_HI);

    if(status & IO_STATUS_EVENT_ON_EDGE)
        MicroBitEvent(id, MICROBIT_PIN_EVT_FALL);
}

/**
 * Set the sample rate at which the micro:bit triggers sensor (in ms).
 *
 * The default sample period is 1 second.
 *
 * @param period the requested time between pings, in milliseconds.
 *
 * @note the micro:bit sends pings in the background.
 */
void MicrobitUltrasound::setPeriod(int period_ms)
{
  this->pingPeriod    = period_ms;
}

/**
 * Get the sample rate at which the micro:bit triggers sensor (in ms).
 *
 * @return period the requested time between pings, in milliseconds.
 */
void MicrobitUltrasound::getPeriod()
{
  return pingPeriod;
}

/**
 * Get the pulse's duration from sensor, last updated sample
 *
 * @return the latest updated pulse duration.
 *
 */
int getEchoDuration()
{
  return echoDuration;
}

/**
 * Send ping to start measurement in sensor
 *
 * This call also will add the class to fiber components to receive
 * one callback only.
 *
 * @return MICROBIT_OK on success.
 */
int MicrobitUltrasound::ping(void)
{
  int result;
  int actVal, pasVal;
  actVal =  pingActiveValue? 1 : 0;
  pasVal =  pingActiveValue? 0 : 1;
  result = trigger.write(pasVal);
  if (result =! 0)
    return result;
  wait_us(MICROBIT_ULTRASOUND_IDLE_DURATION_DEFAULT_US);
  result = trigger.write(actVal);
  if (result =! 0)
    return result;
  wait_us(MICROBIT_ULTRASOUND_PING_DURATION_DEFAULT_US);
  result = trigger.write(pasVal);
  return result;
}

/**
 * Start periodic ping to sensor. This call also will add the class
 * to fiber components for periodic callbacks.
 *
 * @return MICROBIT_OK on success.
 */
int MicrobitUltrasound::start(void)
{
  int result;
  status |= MICROBIT_COMPONENT_RUNNING;
  result = updateSample();
  return result;
}

/**
 * Stop periodic ping to sensor. 
 *
 * @return MICROBIT_OK on success.
 */
int MicrobitUltrasound::stop(void)
{
  int result;
  status &= !MICROBIT_COMPONENT_RUNNING;
  result = fiber_add_idle_component(this);
  return result;
}



/**
 * Update sample by schedulling new ping
 *
 * @return MICROBIT_OK on success.
 */
int MicrobitUltrasound::updateSample(void)
{
  int result;
  if(!(status & ULTRASOUND_STATUS_ADDED_TO_IDLE))
  {
    // If we're running under a fiber scheduer, register ourselves for a periodic callback to keep our data up to date.
    // Otherwise, we do just do this on demand with the ping function.
    result = fiber_add_idle_component(this);
    if (result != MICROBIT_OK)
      return result;
    status |= ULTRASOUND_STATUS_ADDED_TO_IDLE;
  }

  // check if we need to update our ping...
  if (isPingNeeded())
  {
    result = ping();
    if (result != MICROBIT_OK)
      return result;
    // Send an event to indicate that we just sent a new ping.
    if (status & ULTRASOUND_STATUS_EVENTON_PING)
      MicroBitEvent e(id, MICROBIT_ULTRASOUND_EVT_PING);
  }


  // Schedule our next ping.
  sampleTime = system_timer_current_time() + pingPeriod;

  return MICROBIT_OK
}

/**
  * Periodic callback from MicroBit idle thread.
  */
void MicrobitUltrasound::idleTick()
{
  updateSample();
}

/**
  * Determines if we're due to take another ping
  *
  * @return 1 if we're due to take a new ping, 0 otherwise.
  */
int MicrobitUltrasound::isPingNeeded()
{
    return  system_timer_current_time() >= sampleTime;
}

/**
 *  Echo event catcher function
 */
void MicrobitUltrasound::onEchoPulse(MicroBitEvent eIn)
{
  echoDuration = eIn.timestamp;
  MicroBitEvent eOut(id, MICROBIT_ULTRASOUND_ECHO_RECEIVED);
}

int MicrobitUltrasound::eventOn(int eventType)
{
  switch(eventType)
  {
    case MICROBIT_ULTRASOUND_EVT_PING           : status |= ULTRASOUND_STATUS_EVENTON_PING;
                                                  break;
    case MICROBIT_ULTRASOUND_EVT_ECHO_RISE      : status |= ULTRASOUND_STATUS_EVENTON_RISE;
                                                  break;
    case MICROBIT_ULTRASOUND_EVT_ECHO_FALL      : status |= ULTRASOUND_STATUS_EVENTON_FALL;
                                                  break;
    case MICROBIT_ULTRASOUND_EVT_ECHO_EDGE      : status |= (ULTRASOUND_STATUS_EVENTON_RISE | ULTRASOUND_STATUS_EVENTON_FALL);
                                                  break;
    case MICROBIT_ULTRASOUND_EVT_ECHO_PULSE     : status |= ULTRASOUND_STATUS_EVENTON_PULSE;
                                                  break;
    default                                     : return MICROBIT_INVALID_PARAMETER;
                                                  break;
  }
  return MICROBIT_OK;
}