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@6:bca0839e8295, 2016-12-10 (annotated)
- Committer:
- tbjazic
- Date:
- Sat Dec 10 08:28:06 2016 +0000
- Revision:
- 6:bca0839e8295
- Parent:
- 4:052ac3f5c938
Filtering with Ticker object corrected.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
tbjazic | 0:ebee649c5b1b | 1 | #include "mbed.h" |
tbjazic | 2:f86b1e3609b3 | 2 | #include "HCSR04.h" |
tbjazic | 4:052ac3f5c938 | 3 | #include "AutomationElements.h" |
tbjazic | 0:ebee649c5b1b | 4 | |
tbjazic | 3:3297ea6e3ae1 | 5 | Serial pc(USBTX, USBRX); |
tbjazic | 4:052ac3f5c938 | 6 | HCSR04 sensor(p5, p7); |
tbjazic | 6:bca0839e8295 | 7 | float sampleTime = 0.5; |
tbjazic | 4:052ac3f5c938 | 8 | PT1 filter(1, 2, sampleTime); |
tbjazic | 4:052ac3f5c938 | 9 | Ticker ticker; |
tbjazic | 4:052ac3f5c938 | 10 | float distance; |
tbjazic | 4:052ac3f5c938 | 11 | float filteredDistance; |
tbjazic | 4:052ac3f5c938 | 12 | |
tbjazic | 4:052ac3f5c938 | 13 | void calc() { |
tbjazic | 6:bca0839e8295 | 14 | sensor.startMeasurement(); |
tbjazic | 4:052ac3f5c938 | 15 | } |
tbjazic | 0:ebee649c5b1b | 16 | |
tbjazic | 0:ebee649c5b1b | 17 | int main() { |
tbjazic | 6:bca0839e8295 | 18 | sensor.setRanges(2, 400); |
tbjazic | 4:052ac3f5c938 | 19 | pc.printf("Minimum sensor range = %g cm\n\rMaximum sensor range = %g cm\n\r", sensor.getMinRange(), sensor.getMaxRange()); |
tbjazic | 4:052ac3f5c938 | 20 | pc.printf("Sensor: Filtered:\n\r"); |
tbjazic | 4:052ac3f5c938 | 21 | ticker.attach(&calc, sampleTime); |
tbjazic | 6:bca0839e8295 | 22 | while(true) { |
tbjazic | 6:bca0839e8295 | 23 | while(!sensor.isNewDataReady()) { |
tbjazic | 6:bca0839e8295 | 24 | // wait for new data |
tbjazic | 6:bca0839e8295 | 25 | } |
tbjazic | 6:bca0839e8295 | 26 | distance = sensor.getDistance_cm(); |
tbjazic | 6:bca0839e8295 | 27 | filter.in(distance); |
tbjazic | 6:bca0839e8295 | 28 | filteredDistance = filter.out(); |
tbjazic | 6:bca0839e8295 | 29 | pc.printf("%7.1f cm %7.1f cm\n\r", distance, filteredDistance); |
tbjazic | 0:ebee649c5b1b | 30 | } |
tbjazic | 0:ebee649c5b1b | 31 | } |