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

Dependencies:   mbed HCSR04 AutomationElements

Committer:
jakobhz
Date:
Tue Dec 15 18:14:00 2020 +0000
Revision:
7:667133e8fb42
Parent:
6:bca0839e8295
ultrasonic sensor alarm system

Who changed what in which revision?

UserRevisionLine numberNew 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
jakobhz 7:667133e8fb42 5 DigitalIn mypin(D4);
jakobhz 7:667133e8fb42 6 PwmOut Buzzer(D5);
jakobhz 7:667133e8fb42 7 DigitalOut myled(D7);
tbjazic 3:3297ea6e3ae1 8 Serial pc(USBTX, USBRX);
jakobhz 7:667133e8fb42 9 HCSR04 sensor(D8, D9);
tbjazic 6:bca0839e8295 10 float sampleTime = 0.5;
tbjazic 4:052ac3f5c938 11 PT1 filter(1, 2, sampleTime);
tbjazic 4:052ac3f5c938 12 Ticker ticker;
tbjazic 4:052ac3f5c938 13 float distance;
tbjazic 4:052ac3f5c938 14 float filteredDistance;
tbjazic 4:052ac3f5c938 15
tbjazic 4:052ac3f5c938 16 void calc() {
tbjazic 6:bca0839e8295 17 sensor.startMeasurement();
tbjazic 4:052ac3f5c938 18 }
tbjazic 0:ebee649c5b1b 19
tbjazic 0:ebee649c5b1b 20 int main() {
tbjazic 6:bca0839e8295 21 sensor.setRanges(2, 400);
tbjazic 4:052ac3f5c938 22 pc.printf("Minimum sensor range = %g cm\n\rMaximum sensor range = %g cm\n\r", sensor.getMinRange(), sensor.getMaxRange());
tbjazic 4:052ac3f5c938 23 pc.printf("Sensor: Filtered:\n\r");
tbjazic 4:052ac3f5c938 24 ticker.attach(&calc, sampleTime);
tbjazic 6:bca0839e8295 25 while(true) {
tbjazic 6:bca0839e8295 26 while(!sensor.isNewDataReady()) {
tbjazic 6:bca0839e8295 27 // wait for new data
tbjazic 6:bca0839e8295 28 }
jakobhz 7:667133e8fb42 29 float distance = sensor.getDistance_cm();
tbjazic 6:bca0839e8295 30 filter.in(distance);
tbjazic 6:bca0839e8295 31 filteredDistance = filter.out();
tbjazic 6:bca0839e8295 32 pc.printf("%7.1f cm %7.1f cm\n\r", distance, filteredDistance);
jakobhz 7:667133e8fb42 33
jakobhz 7:667133e8fb42 34 if(distance<10 && mypin == 1){
jakobhz 7:667133e8fb42 35 pc.printf("intruder alert");
jakobhz 7:667133e8fb42 36 myled = 1;
jakobhz 7:667133e8fb42 37 Buzzer = 1;
jakobhz 7:667133e8fb42 38 }
jakobhz 7:667133e8fb42 39 else{
jakobhz 7:667133e8fb42 40 myled = 0;
jakobhz 7:667133e8fb42 41 Buzzer = 0;
jakobhz 7:667133e8fb42 42 }
tbjazic 0:ebee649c5b1b 43 }
tbjazic 0:ebee649c5b1b 44 }