Driver for HC-SR04 connected to a Microbit

MicrobitUltrasound.cpp

Committer:
isaeldiaz@developer.mbed.org
Date:
2016-10-04
Revision:
18:c425443e177c
Parent:
17:a82fb8fc4ca3

File content as of revision 18:c425443e177c:

/*
   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 "MicroBitSystemTimer.h"
#include "MicroBitFiber.h"

  /**
   * Constructor.
   * Create new MicrobitUltrasound that reports distance to closest object
   *
   * @param triggerPinName Name of the MicroBitPin to be used as trigger.
   *
   * @param echoPinName Name of the MicroBitPin to be used as response from sensor.
   *
   * @code
   * MicrobitUltrasound uSoundSensor(MICROBIT_PIN_P1, 100, true, MICROBIT_PIN_P2, PullUp);
   * @endcode
   */
MicrobitUltrasound::MicrobitUltrasound(PinName triggerPinName, int _triggerPeriod_ms, bool _triggerActiveValue, 
    PinName echoPinName, PinMode echoPinMode, uint16_t id):
  trigger(triggerPinName), echo(echoPinName)
{
  this->id                 = id;
  this->status             = 0;
  this->sampleTime         = 0;
  this->triggerDuration_us = MICROBIT_ULTRASOUND_TRIGGER_DURATION_DEFAULT_US;
  this->triggerPeriod_ms   = (uint16_t)_triggerPeriod_ms;
  this->triggerActiveValue = _triggerActiveValue;

  echo.mode(echoPinMode);
  echo.rise(this, &MicrobitUltrasound::onEchoRise);
  echo.fall(this, &MicrobitUltrasound::onEchoFall);
}

  /**
   * Constructor.
   * Create new MicrobitUltrasound that reports distance to closest object
   *
   * @param triggerPinName Name of the MicroBitPin to be used as trigger.
   *
   * @param echoPinName Name of the MicroBitPin to be used as response from sensor.
   *
   * @code
   * MicrobitUltrasound uSoundSensor(MICROBIT_PIN_P1, MICROBIT_PIN_P2);
   * @endcode
   */
MicrobitUltrasound::MicrobitUltrasound(PinName triggerPinName, PinName echoPinName, uint16_t id):
  trigger(triggerPinName), echo(echoPinName)
{
  this->id                 = id;
  this->status             = 0;
  this->sampleTime         = 0;
  this->triggerPeriod_ms   = MICROBIT_ULTRASOUND_PERIOD_DEFAULT_MS;
  this->triggerDuration_us = MICROBIT_ULTRASOUND_TRIGGER_DURATION_DEFAULT_US;
  this->triggerActiveValue = TRIGGER_ACTIVE_VALUE;

  //echo.mode((PinMode)MICROBIT_ULTRASOUND_PULLMODE_DEFAULT);
  echo.rise(this, &MicrobitUltrasound::onEchoRise);
  echo.fall(this, &MicrobitUltrasound::onEchoFall);
}

/**
  * Destructor for MicrobitUltrasound, where we deregister from the array of fiber components.
  */
MicrobitUltrasound::~MicrobitUltrasound()
{
    fiber_remove_idle_component(this);
}

/**
 * Set Echo PinMode
 */
void MicrobitUltrasound::setEchoPinMode(PinMode echoPinMode)
{
  echo.mode(echoPinMode);
}

/**
 * This member function manages the calculation of the timestamp of a pulse detected
 * on the echo pin.
 *
 * @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 & ULTRASOUND_STATUS_EVENTON_PULSE)
    pulseWidthEvent(MICROBIT_ULTRASOUND_EVT_ECHO_PULSE_LO);

  if(status & ULTRASOUND_STATUS_EVENTON_RISE)
    MicroBitEvent(id, MICROBIT_ULTRASOUND_EVT_ECHO_RISE);

  if(status & ULTRASOUND_STATUS_EVENTON_EDGE)
    MicroBitEvent(id, MICROBIT_ULTRASOUND_EVT_ECHO_EDGE);
}

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

  if(status & ULTRASOUND_STATUS_EVENTON_FALL)
    MicroBitEvent(id, MICROBIT_ULTRASOUND_EVT_ECHO_FALL);

  if(status & ULTRASOUND_STATUS_EVENTON_EDGE)
    MicroBitEvent(id, MICROBIT_ULTRASOUND_EVT_ECHO_EDGE);
}

/**
 * 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 triggers, in milliseconds.
 *
 * @note the micro:bit sends triggers in the background.
 */
void MicrobitUltrasound::setPeriod(int period_ms)
{
  this->triggerPeriod_ms    = period_ms;
}

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

/**
 * Send trigger 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.
 */
void MicrobitUltrasound::fireTrigger(void)
{
  int actVal, pasVal;
  actVal =  triggerActiveValue? 1 : 0;
  pasVal =  triggerActiveValue? 0 : 1;
  trigger.write(pasVal);
  wait_us(MICROBIT_ULTRASOUND_IDLE_DURATION_DEFAULT_US);
  trigger.write(actVal);
  wait_us(triggerDuration_us);
  trigger.write(pasVal);
}

/**
 * Start periodic trigger 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 trigger to sensor. 
 *
 * @return MICROBIT_OK on success.
 */
int MicrobitUltrasound::stop(void)
{
  int result;
  status &= !MICROBIT_COMPONENT_RUNNING;
  result = fiber_remove_idle_component(this);
  return result;
}



/**
 * Update Sensor measurement
 *
 * @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 trigger 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 trigger...
  if (isTriggerNeeded())
  {
    fireTrigger();
    // Send an event to indicate that we just sent a new trigger.
    if (status & ULTRASOUND_STATUS_EVENTON_TRIGGER)
      MicroBitEvent e(id, MICROBIT_ULTRASOUND_EVT_TRIGGER);

    // Schedule our next trigger.
    sampleTime = system_timer_current_time() + triggerPeriod_ms;
  }

  return MICROBIT_OK;
}

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

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


/**
 * Enables a particular event for the current module
 *
 * @return 1 if we're due to take a new trigger, 0 otherwise.
 */
int MicrobitUltrasound::eventOn(int eventType)
{
  switch(eventType)
  {
    case MICROBIT_ULTRASOUND_EVT_ECHO_PULSE_HI  : status |= ULTRASOUND_STATUS_EVENTON_PULSE;
                                                  break;
    case MICROBIT_ULTRASOUND_EVT_ECHO_PULSE_LO  : status |= ULTRASOUND_STATUS_EVENTON_PULSE;
                                                  break;
    case MICROBIT_ULTRASOUND_EVT_TRIGGER        : status |= ULTRASOUND_STATUS_EVENTON_TRIGGER;
                                                  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_EDGE;
                                                  break;
    default                                     : return MICROBIT_INVALID_PARAMETER;
                                                  break;
  }
  return MICROBIT_OK;
}