Embedded Systems Project Mateusz Loboda 200843098

Dependencies:   N5110 SRF02-Mateusz mbed

main.cpp

Committer:
el14ml
Date:
2016-05-04
Revision:
2:0dfa60f22f07
Parent:
1:32b9ad362749
Child:
3:ee005c9f0348

File content as of revision 2:0dfa60f22f07:

/*
* @file main.cpp
* @Distance Sensor Project
* @brief Main file containing functions and int main().
* @author Mateusz Loboda
* @date April 2016
*/


//sd card
//mbed leds come on sometimes;
//make 4k mid freq
//fix buzzer beeping


#include "mbed.h"
#include "main.h"


int main()

{
    init_K64F();
    lcd.init();

    initialScreen();
    out.attach(timeout_isr,4);
    lcd.refresh();
    sleep();
    lcd.clear();
    lcd.refresh();
    initialArray();
    ticker.attach(&ticker_isr,0.1);


    while(1) {
        delay = rate;

        buzzerPeriod = 1/((4000-(2*averageDistance))+200); // BUZZER, 200+200 = 400 = maximum range so freq proportional to distance, org 1/(200-avg)+200

        if (g_ticker_flag) {

            g_ticker_flag = 0;
            if ( g_button2_flag == 0) {

                buzzer = delay; // duty cycle
                buzzer.period(buzzerPeriod); //set pwm to my freq
                // average distance calculated
                get_averageDistance();
                redLedIndicator();
                drawDistanceBars();
                

            } else if (g_button2_flag == 1) {
               // lcd.clear();
                  moveArrayElements();
                  get_averageDistance();
                  adjacentArrayElements();
                  plotAxes();
                  plotDistancePoint();
              //  modeTwo();

                lcd.refresh();

            }
            lcd.refresh();
            sleep();
        }
    }
}
void init_K64F()
{
    r_led = 1;// on-board LEDs are active-low, so set pin high to turn them off.
    g_led = 1;
    b_led = 1;
    button2.fall(&mode); //under this condition call function where mode is a function that sets flag
    button2.mode(PullUp); //enable internal pull up resistor
    button1.fall(&units);  //under this condition call function where mode is a function that sets flag
    button1.mode(PullUp); //enable internal pull up resistor

}
void units()
{
    g_button1_flag =!g_button1_flag ;   // set button 1 flag in ISR
}
void mode()
{
    g_button2_flag =!g_button2_flag ;    //set button 2 flag in ISR
}
void timeout_isr()
{
}
void ticker_isr()
{
    g_ticker_flag = 1;   // set ticker flag in ISR
}
void initialScreen() // initial screen printed
{
    lcd.printString("DISTANCE",18,0);
    lcd.printString("SENSOR",22,1);
    lcd.printString("Mateusz Loboda",0,3);
    lcd.printString("200843098",16,4);
    lcd.refresh();
}
void initialArray()
{
    //graphArray[82]; //initialize graph array, 2 pixels used for y axis so not 84
    for (int i=0; i<83; i++) { // before entering the grpah mode with the button, it is alreadt plotting points but they cannot be seen as they are above max range of 200
        graphArray[i] = 201; // has to be more thn 200 so points are only plotted from the point when user presses button
    }
    lcd.clear();
}
void get_averageDistance() // to minimize error, 5 readings are taken at regular intervals and averaged out 
{
    for ( int i=0 ; i<5; i++) {
        int distance = sensor.getDistanceCm(); // obtaining sensor distance reading
        if (distance < 400) { //better averages random annomous values not even considered
            averageDistance += distance; //assignment by sum
        } else {
            i--;  //if distance > 400 do not take that reading into account go again
        }
    }
    averageDistance = averageDistance/5; //sum of 5 readings divided by 5 to get average
   lcd.clear();
}

void redLedIndicator() // this function evaluates the average distance reading, displays it and controls the auditory + visual alerts 
{
    if (averageDistance<=30) {
        myled = 1;  // warning led comes on
        lcd.clear(); // clear previous distance values displayed
        lcd.printString(" ***COLLISION ",2,1); //warning text
        lcd.printString(" WARNING***   ",8,3);
        lcd.refresh();
        buzzer = delay; // duty cycle, volume of buzzer controlled with pot
        buzzer.period(0.001); //highest frequency pitch when warning message comes on
    } else {
      //  r_led = 1;
      //  g_led = 1;
      //  b_led = 1;
        myled = 0;
    }
    if (averageDistance >30) {  // above critical distance
        lcd.clear();
        char str[10]; //keep the string as character array in local stack so can be manipulated
        if (g_button1_flag == 0) {  //button 1 flag is set 0 by default so distance displayed in units of cm

            sprintf(str,"%.2f",averageDistance); // printing first 2 digits of average distance as float
            lcd.printString("cm",62,4); // printing units 

        } else  if (g_button1_flag == 1) {  //button 1 pressed, flag set 1 
            sprintf(str,"%.2f",averageDistance*0.393701); //converting from cm to inches
            lcd.printString("in",60,4); // printing the units

        }
        lcd.printString("                                  ",0,3);
        lcd.printString(str,20,4);
        lcd.refresh();
    }
}
void drawDistanceBars() // function draws bars so as to indicate the approximate distance to nearest target object
{
    if(averageDistance>380) {
        lcd.drawRect(67,2,5,16,1); //Draw 8 bars

    }
    if(averageDistance>330) {
        lcd.drawRect(59,2,5,16,1); //Draw 7 bars

    }
    if(averageDistance>280) {
        lcd.drawRect(51,2,5,16,1); //Draw 6 bars

    }
    if(averageDistance>230) {
        lcd.drawRect(43,2,5,16,1); //Draw 5 bars

    }
    if(averageDistance>180) {
        lcd.drawRect(35,2,5,16,1); //Draw 4 bars

    }
    if(averageDistance>130) {
        lcd.drawRect(27,2,5,16,1);  //Draw 3 bars

    }
    if(averageDistance>80) {
        lcd.drawRect(19,2,5,16,1); //Draw 2 Bars

    }
    if(averageDistance>30) {
        lcd.drawRect(12,2,5,16,1); //Draw one rectangle
    }
    lcd.refresh();
}
void moveArrayElements()
{

    for (int i=81 ; i>0; i--) {
        graphArray[i] = graphArray[i-1];  //moving each element of array to right
    } 
}
void adjacentArrayElements() // assigning float distance to first element of graph matrix
{

    graphArray[0]= averageDistance; //array element is average distance float
    if ((int)graphArray[0] != (int)graphArray[1]) { //if value of current array element is different to previous one, red led and buzzer comes on ie visual and auditory alerts
        myled=1; //red led comes on
        buzzer = delay; // duty cycle
        buzzer.period(buzzerPeriod); //set period of buzzer to my function 

    } else { // if no movement alerts are off
        myled=0;
        buzzer=0;
    }
}

void plotAxes() //plotting both the x and y axis which are 2 pixels thick, i represents the pixels 
{
    //i is pixel, plotting x axis
    for ( int i=0; i<84; i++) { // plotting x axis
        lcd.setPixel(i,46);
        lcd.setPixel(i,47);
    }
    //plotting y axis
    for ( int i=0; i<48; i++) { // plotting y axis 
        lcd.setPixel(0,i);
        lcd.setPixel(1,i);
    }
}
void plotDistancePoint() //function converts float distance to integer pixel
{

    // i in this loop is element of the array NOT pixel
    for (int i=0; i<82; i++) { // array is 82 elements long as 2 pixels are used for axes
        //x position + y position)
        int p = (int)(45-(graphArray[i]/(200/46))); //convert array element float distance to integer pixel
        //convert from float distance to integer pixel
        lcd.setPixel(83-i,p); // plot in pixel 84 at the right height , this pixel is then moved to right and new pixel is plotted
    }
    lcd.refresh();
}