Driver for HC-SR04 connected to a Microbit

MicrobitUltrasound.cpp

Committer:
isaeldiaz@developer.mbed.org
Date:
2016-08-30
Revision:
11:41b7e18b8e06
Parent:
9:d153bcba081c
Child:
12:5c8e378fb1b1

File content as of revision 11:41b7e18b8e06:

/*
   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_TRIGGER = 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_TRIGGER, P2_ECHO);
 * @endcode
 */
MicrobitUltrasound(PinName triggerPinName, PinName echoPinName, uint16_t id):
  trigger(triggerPinName), TimedInterruptIn(echoPinName)
{
  this->id                 = id;
  this->status             = 0;
  this->sampleTime         = 0;
  this->echoDuration       = 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, &MicroBitUlstrasound::onEchoRise);
  echo->rise(this, &MicroBitUlstrasound::onEchoFall);
}

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

/**
 * 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.
 */
void MicrobitUltrasound::getPeriod()
{
  return triggerPeriod_ms;
}

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

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

/**
 * 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_add_idle_component(this);
  return result;
}



/**
 * Update sample by schedulling new trigger
 *
 * @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())
  {
    result = fireTrigger();
    if (result != MICROBIT_OK)
      return result;
    // 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;
}