Driver for HC-SR04 connected to a Microbit

Revision:
5:5667dcf9c45d
Parent:
4:c67cff7b9733
Child:
6:f3780669258d
--- a/MicrobitUltrasound.cpp	Sat Aug 27 00:12:21 2016 +0200
+++ b/MicrobitUltrasound.cpp	Sat Aug 27 22:12:52 2016 +0200
@@ -1,113 +1,119 @@
 /*
-The MIT License (MIT)
+   The MIT License (MIT)
 
-Copyright (c) 2016 British Broadcasting Corporation.
-This software is provided by Lancaster University by arrangement with the BBC.
+   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:
+   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 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.
-*/
+   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"
+ * 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
+ * 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 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_PING, P2_ECHO);
+ * MicroBitUltrasound uSoundSensor(P1_TRIGGER, P2_ECHO);
  * @endcode
  */
-MicrobitUltrasound(PinName pingPinName, PinName echoPinName, uint16_t id)
+MicroBitUltrasound(PinName triggerPinName, 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;
+  this->id              = id;
+  this->status          = 0;
+  this->sampleTime      = 0;
+  this->echoDuration    = 0;
+  this->triggerPeriod   = MICROBIT_ULTRASOUND_PERIOD_DEFAULT_MS;
+  this->triggerDuration = MICROBIT_ULTRASOUND_TRIGGER_DURATION_DEFAULT_US;
 
-  ping = new DigitalOut(pingPinName);
+  trigger = new DigitalOut(triggerPinName);
   echo = new TimedInterruptIn(echoPinName);
   echo->mode((PinMode)MICROBIT_ULTRASOUND_PULLMODE_DEFAULT);
-  echo->rise(this, &MicrobitUlstrasound::onEchoRise);
-  echo->rise(this, &MicrobitUlstrasound::onEchoFall);
+  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)
+ * This member function manages the calculation of the timestamp of a pulse detected
+ * on the echo 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();
+  MicroBitEvent evt(id, eventValue, CREATE_ONLY);
+  uint64_t now      = evt.timestamp;
+  uint64_t previous = echo.getTimestamp();
 
-    if (previous != 0)
-    {
-        evt.timestamp -= previous;
-        evt.fire();
-    }
+  if (previous != 0)
+  {
+    evt.timestamp -= previous;
+    evt.fire();
+  }
 
-    echo.setTimestamp(now);
+  echo.setTimestamp(now);
 }
 
 
 /**
-  * Interrupt handler for when an rise interrupt is triggered.
-  */
-void MicrobitUltrasound::onEchoRise()
+ * 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 & ULTRASOUND_STATUS_EVENTON_PULSE)
+    pulseWidthEvent(MICROBIT_ULTRASOUND_EVT_ECHO_PULSE_LO);
 
-    if(status & IO_STATUS_EVENT_ON_EDGE)
-        MicroBitEvent(id, MICROBIT_PIN_EVT_RISE);
+  if(status & ULTRASOUND_STATUS_EVENTON_RISE)
+    MicroBitEvent(id, MICROBIT_ULTRASOUND_EVT_ECHO_RISE);
+
+  if(status & ULTRASOUND_STATUS_EVENTON_EDGE)
+    MicroBitEvent(id, MICROBIT_PIN_EVT_EDGE);
 }
 
 /**
-  * Interrupt handler for when an fall interrupt is triggered.
-  */
-void MicrobitUltrasound::onEchoFall()
+ * 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 & ULTRASOUND_STATUS_EVENTON_PULSE)
+    pulseWidthEvent(MICROBIT_ULTRASOUND_EVT_ECHO_PULSE_HI);
 
-    if(status & IO_STATUS_EVENT_ON_EDGE)
-        MicroBitEvent(id, MICROBIT_PIN_EVT_FALL);
+  if(status & ULTRASOUND_STATUS_EVENTON_FALL)
+    MicroBitEvent(id, MICROBIT_ULTRASOUND_EVT_ECHO_FALL);
+
+  if(status & ULTRASOUND_STATUS_EVENTON_EDGE)
+    MicroBitEvent(id, MICROBIT_PIN_EVT_EDGE);
 }
 
 /**
@@ -115,23 +121,23 @@
  *
  * The default sample period is 1 second.
  *
- * @param period the requested time between pings, in milliseconds.
+ * @param period the requested time between triggers, in milliseconds.
  *
- * @note the micro:bit sends pings in the background.
+ * @note the micro:bit sends triggers in the background.
  */
-void MicrobitUltrasound::setPeriod(int period_ms)
+void MicroBitUltrasound::setPeriod(int period_ms)
 {
-  this->pingPeriod    = period_ms;
+  this->triggerPeriod    = period_ms;
 }
 
 /**
  * Get the sample rate at which the micro:bit triggers sensor (in ms).
  *
- * @return period the requested time between pings, in milliseconds.
+ * @return period the requested time between triggers, in milliseconds.
  */
-void MicrobitUltrasound::getPeriod()
+void MicroBitUltrasound::getPeriod()
 {
-  return pingPeriod;
+  return triggerPeriod;
 }
 
 /**
@@ -146,19 +152,19 @@
 }
 
 /**
- * Send ping to start measurement in sensor
+ * 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::ping(void)
+int MicroBitUltrasound::fireTrigger(void)
 {
   int result;
   int actVal, pasVal;
-  actVal =  pingActiveValue? 1 : 0;
-  pasVal =  pingActiveValue? 0 : 1;
+  actVal =  triggerActiveValue? 1 : 0;
+  pasVal =  triggerActiveValue? 0 : 1;
   result = trigger.write(pasVal);
   if (result =! 0)
     return result;
@@ -166,18 +172,18 @@
   result = trigger.write(actVal);
   if (result =! 0)
     return result;
-  wait_us(MICROBIT_ULTRASOUND_PING_DURATION_DEFAULT_US);
+  wait_us(MICROBIT_ULTRASOUND_TRIGGER_DURATION_DEFAULT_US);
   result = trigger.write(pasVal);
   return result;
 }
 
 /**
- * Start periodic ping to sensor. This call also will add the class
+ * 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 MicroBitUltrasound::start(void)
 {
   int result;
   status |= MICROBIT_COMPONENT_RUNNING;
@@ -186,11 +192,11 @@
 }
 
 /**
- * Stop periodic ping to sensor. 
+ * Stop periodic trigger to sensor. 
  *
  * @return MICROBIT_OK on success.
  */
-int MicrobitUltrasound::stop(void)
+int MicroBitUltrasound::stop(void)
 {
   int result;
   status &= !MICROBIT_COMPONENT_RUNNING;
@@ -201,79 +207,71 @@
 
 
 /**
- * Update sample by schedulling new ping
+ * Update sample by schedulling new trigger
  *
  * @return MICROBIT_OK on success.
  */
-int MicrobitUltrasound::updateSample(void)
+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.
+    // 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 ping...
-  if (isPingNeeded())
+  // check if we need to update our trigger...
+  if (isTriggerNeeded())
   {
-    result = ping();
+    result = fireTrigger();
     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);
+    // 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 ping.
-  sampleTime = system_timer_current_time() + pingPeriod;
+  // Schedule our next trigger.
+  sampleTime = system_timer_current_time() + triggerPeriod;
 
   return MICROBIT_OK
 }
 
 /**
-  * Periodic callback from MicroBit idle thread.
-  */
-void MicrobitUltrasound::idleTick()
+ * 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()
+ * 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;
+  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)
+int MicroBitUltrasound::eventOn(int eventType)
 {
   switch(eventType)
   {
-    case MICROBIT_ULTRASOUND_EVT_PING           : status |= ULTRASOUND_STATUS_EVENTON_PING;
+    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_RISE | ULTRASOUND_STATUS_EVENTON_FALL);
+    case MICROBIT_ULTRASOUND_EVT_ECHO_EDGE      : status |= ULTRASOUND_STATUS_EVENTON_EDGE;
                                                   break;
     case MICROBIT_ULTRASOUND_EVT_ECHO_PULSE     : status |= ULTRASOUND_STATUS_EVENTON_PULSE;
                                                   break;