A program that demonstrates the development of library, using as an example an ultrasonic distance sensor HC-SR04.

Dependencies:   mbed HCSR04 AutomationElements

The purpose of this program is to encourage students to develope their own classes. Instructions how to follow the development of this program and class HCSR04 for ultrasonic distance measurement are given here.

main.cpp

Committer:
tbjazic
Date:
2016-12-10
Revision:
6:bca0839e8295
Parent:
4:052ac3f5c938

File content as of revision 6:bca0839e8295:

#include "mbed.h"
#include "HCSR04.h"
#include "AutomationElements.h"

Serial pc(USBTX, USBRX);
HCSR04 sensor(p5, p7);
float sampleTime = 0.5;
PT1 filter(1, 2, sampleTime);
Ticker ticker;
float distance;
float filteredDistance; 

void calc() {
    sensor.startMeasurement();
}

int main() {
    sensor.setRanges(2, 400);
    pc.printf("Minimum sensor range = %g cm\n\rMaximum sensor range = %g cm\n\r", sensor.getMinRange(), sensor.getMaxRange());
    pc.printf("Sensor:       Filtered:\n\r");
    ticker.attach(&calc, sampleTime);
    while(true) {
        while(!sensor.isNewDataReady()) {
        // wait for new data
        }
        distance = sensor.getDistance_cm();
        filter.in(distance);
        filteredDistance = filter.out();
        pc.printf("%7.1f cm  %7.1f cm\n\r", distance, filteredDistance);
    }
}