Fully integrated working system

Dependencies:   Speaker mbed mbed-rtos 4DGL-uLCD-SE hcsr04

main.cpp

Committer:
fiachra
Date:
2020-12-16
Revision:
9:d1b00a2a8e25
Parent:
8:f3ab61374cd0
Child:
10:f29ed3675509

File content as of revision 9:d1b00a2a8e25:

#include "mbed.h"
#include "hcsr04.h"
#include  "Speaker.h"

HCSR04  usensor(p25,p6);
Serial pc(USBTX, USBRX);
Speaker mySpeaker(p18);

unsigned int dist;

float averageDistance();
void beeping();
float i;

int main()
{
 
    while(1) {
        usensor.start();
        
        averageDistance();
        
        beeping();
        pc.printf("cm:%ld\n",dist );
        wait_ms(50); 
    }
}
float averageDistance() /** Divide the running total by 10 to get the average distance to get more accurate readings on the sensor**/
{
        int a = usensor.get_dist_cm();
        int b = usensor.get_dist_cm();
        int c = usensor.get_dist_cm();
        int d = usensor.get_dist_cm();
        int e = usensor.get_dist_cm();
        int f = usensor.get_dist_cm();
        int g = usensor.get_dist_cm();
        int h = usensor.get_dist_cm();
        int i = usensor.get_dist_cm();
        int j = usensor.get_dist_cm();
 
        dist  = (a+b+c+d+e+f+g+h+i+j)/10;
        return dist;
}
void beeping()
/*
@Brief Function to create the effect of varying beeping sounds depending on how close the sensor is to an object interspersed with
the led changing color depending on the distance
 */
{
    int distance = averageDistance();
 
    if (distance > 2000) i=0.05; //sensor defaults to 2k+ when dist<~3cm 
    if (distance < 150) i=0.6;
    if (distance < 100) i=0.55;
    if (distance < 90) i=0.5;
    if (distance < 80) i=0.45;
    if (distance < 70) i=0.4;
    if (distance < 60) i=0.35;
    if (distance < 50) i=0.3;
    if (distance < 40) i=0.25;
    if (distance < 30) i=0.2;
    if (distance < 20) i=0.15;
    if (distance < 10) i=0.1;
    if (distance < 5) i=0.05;
    mySpeaker.PlayNote(329.63, i, 1.0);
    
}