Use this repository for pilot an ultrasonic sensor

Fork of UltrasonicSensor by Daniele Briguglio

UltrasonicSensor.cpp

Committer:
danky02
Date:
2018-01-15
Revision:
1:9d56714c1119
Parent:
0:8ca9f71b386d

File content as of revision 1:9d56714c1119:

/*
  UltrasonicSensor.cpp - drive a distance sensor- Version 1.0.0
  Copyright (c) 2018 Daniele Briguglio.  All right reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.
*/

/*
  The methods are:

   UltrasonicSensor - Class for manipulating Ultrasonic Sensor

   attach(echo, trigger)  - Attaches a Ultrasonic Sensor to an i/o pin,
   default pins are D9 for echo and D8 for trigger.
 
   read()  - Read distance measured by the sensor. 
 */

#include <mbed.h>
#include <UltrasonicSensor.h>

UltrasonicSensor::UltrasonicSensor(PinName echo, PinName trigger) : _echo(echo), _trigger(trigger) {  // _pin(pin) means pass pin to the DigitalOut constructor
    _echo = D9;                                    // default the output to LED2
    _trigger = D8;
    corr = 0;
}

void UltrasonicSensor::begin(float correction = 0){
    corr = correction;
    UltrasonicSensor::begin2();
}

void UltrasonicSensor::begin(void){
    corr = 0;
    UltrasonicSensor::begin2();
}

void UltrasonicSensor::begin2(void){
    distance = 0;
    sonar.reset();
    sonar.start();
    while (_echo == 2){};
    sonar.stop();
    corr = sonar.read_us();
}

float UltrasonicSensor::read(void){
    _trigger = 1;
    sonar.reset();
    wait_us(10.0);
    _trigger = 0;
    while(_echo == 0){};
    sonar.start();
    while(_echo ==1 ){};
    sonar.stop();
    return (sonar.read_us()-corr)/58.0;
    //distance = (sonar.read_us()-corr)/58.0;
    //return distance;
}