Range Finder (Version 2) - Below 50cm, buzzer sounds, LED flashes for 5s, then alarm sounds until interrupted

Dependencies:   mbed

Fork of range_finder_2 by Arthur Spencer

main.cpp

Committer:
wadh4587
Date:
2016-06-14
Revision:
2:fe61a5e4cdf5
Parent:
1:b3590ab2a8ae

File content as of revision 2:fe61a5e4cdf5:

/* Arthur Spencer 14/06/16
LV-MaxSonar-EZ1 Range Finder
When someone comes within 50cm, LED flashes for 5s, then buzzer sounds until interupted.
*/
#include "mbed.h"

AnalogIn ain(A0);           //Receives analogue signal from range finder
Serial pc(USBTX, USBRX);

PwmOut buzz(D2);
DigitalOut timer(D1);
int stop;

void press_x()      //Interrupt sequence
{
    char c = pc.getc();
    if(c == 'x') {
        stop = 1;
        pc.printf("Interrupt\n\r");
    }
}

int main()
{
    float  volts, distance, p, q;
    buzz.period_ms(2);
    timer = 0;
    buzz = 0;
    stop = 0;
    pc.attach(&press_x);
    while (1) {
        if (stop == 0) {
            volts = ain.read();
            distance = volts*1000;        //cm
            wait(0.5);
            if (distance > 50) {
                timer = 0;
                buzz = 0;
                wait(0.2);
            } else {
                for( p = 0.0f; p < 0.4; p += 0.1) {       //Initial buzz
                    if(p<0.2) {
                        buzz = 0.5;
                        wait(0.1);
                    } else {
                        buzz = 0;
                        wait(0.1);
                    }
                }
                for( p = 0; p < 10; p++) {              //5s LED timer
                    timer = !timer;
                    wait(0.5);
                }
                for( q = 0; q < 60; q += 1) {       //Alarm
                    if (stop == 0) {
                        for( p = 0.0f; p < 0.5; p += 0.1) {
                            if(p<0.25) {
                                buzz = 0.5;
                                wait(0.05);
                            } else {
                                buzz = 0;
                                wait(0.05);
                            }
                        }
                    } else {
                        buzz = 0, timer = 0;
                    }
                }
            }
        } else {
        }
    }
}