header file

Dependencies:   N5110 PowerControl SRF02 beep mbed

ultrasonic.cpp

Committer:
probrania7
Date:
2015-05-11
Revision:
3:bbfabbbc4291
Parent:
2:184524f95eb1

File content as of revision 3:bbfabbbc4291:

/**
@file main.h
@brief @library for interfacing with SRF02 ultrasonic sensor in I2C
@see http://www.robot-electronics.co.uk/htm/srf02tech.htm
@Brief Nokia library provide by Dr. Craig Evans
@Brief Beep library provided by
@programmer Ibrahim H Adam
*/

/**
@brief Header files included in the project
*/
#include "mbed.h"   //mbed standared header fle
#include "PowerControl/PowerControl.h"  //power saving functions
#include "PowerControl/EthernetPowerControl.h"  //power saving functions
#include "N5110.h"  //Nokia screen library
#include "beep.h"   //beep
#include "SRF02.h"  //ultrasonic range finder
#include "timeMgr.h"    //time functions
/**
@brief pin connections to Nokia Screen
//    VCC,SCE,RST,D/C,MOSI,SCLK,LED
*/
N5110 lcd(p7,p8,p9,p10,p11,p13,p26);
/**
// Can also power (VCC) directly from VOUT (3.3 V) -
// Can give better performance due to current limitation from GPIO pin

@brief pin connection to range finder
//          SDA, SCL
*/
SRF02 sensor(p28,p27);  //
Beep beep1(p21);    //PWM pin
AnalogIn potIn (p20);   


//LEDs to indicate program execution stage
DigitalOut Led1 (p24);
DigitalOut Led2 (p14);
DigitalOut Led3 (p25);
DigitalOut Led4 (p23);
/**
@brief buffer arraey of character data type for bufferD
@brief buffer arraey of character data type for bufferE
@brief buffer arraey of character data type for bufferF

*/
char bufferD[14];   
char bufferE[14]; 
char bufferF[14]; 

/*
@brief Type local file system created for file
@brief function created to take two arguments
@param data 2
@param data1

*/
LocalFileSystem local("local"); //create local file system
void writeDataToFile(char* (data2), float data); 

/**
@briefInterript buttons created to set flags 

*/
InterruptIn button1 (p17);
InterruptIn button2 (p29);
InterruptIn button3 (p30);
   
int position = 0;   //position for select statement 
int positionB;  //first position sampled in distance measurement
int positionA;  //second position sampled in distance measurement
int movedDist;  //gap moved 
void nextPosition();    //
void calculateDist(); //distance calculculation
int nextPosFlag = 0;    //flag to capture while loop attention
void nextPos(); //
void getPointA();   
void getPointB();
  
void introMessage();    //into message
void errorHandler();    //not included
void menu();    //menu selection function
void demo();    //demo code supplied with library
void cursorSelect(int, int, int, int);  //cursor funnction accepting 4 integer agruments
void beeper(float, float);  //beeper function accepting two float arguments
void menuLevel(float);  //menu level function accepting a float variable
void startMessage();    //start message function
void displayClock();    //clock function

void distMeasure();     //distance measurement function
void saveData();        //not used
void adjustBrightness(float);   //LCD brightness
void sysClock();    //system clock - require setting with refference to EPOCH time
void startClockMsg();   //clock message warning clock need setting
void clearRow();    //clear pixels in selected rw
void proxCheck();   //proximity check function 
void dataCapture(); //distance point stamping
void clearRow2();   //clear pixels in selected row

/*
@brief functions of interrupt service routine
@brief user to set flags to 1
*/

void button1Pressed();
void button2Pressed();
void button3Pressed();

/**
@brief initially setting flags to 0
@brief to be reverted to 1 from within ISR functions
*/

int button1Flag = 0;
int button2Flag = 0;
int button3Flag = 0;
int msgFlag = 1;        //introduction message flag

/**
@brief menu level set to 0
@brief brighness flag set to 0
@brief distance flag set to 0
@brief clock flag set to 0
setting flags to 0 will cause while loop to ignore underlying programs
*/

int menuLevelFlag = 0;
int brightFlag = 0;
int distFlag = 0;
int clockFlag = 0;
int dataFlag = 0;

//more flags
int getPointAFlag = 0;
int getPointBFlag = 0;

Ticker distTimer;   //ticker time object created
int dstFlg = 0;     //distance flag initialised to 0

//distance check function to sef diatance flag
void distChk()
{
    dstFlg = 1;
}

/**
@briefclkTimer object of ticker timer
@briefclosk flag set to 0
@briefcalls fiunction clock check
@briefsets clock flag to 0
*/
Ticker clkTimer;
int clkFlg = 0;
void clkChk()
{
    clkFlg = 1;
}

/**
@briefvarying buzzer sound with reference to distance

*/
void buzzerRange();

int distance;   //distance variable, global declaration

int main()
{   
    PHY_PowerDown();    //ethernet powerdown
    // first need to initialise display
    lcd.init();
    
    serial.attach(&serialISR); // attach serial ISR
    timer2.attach(&timer2Expired,1.0); //timer 2 triggered every 2 2seconds

    set_time(1424535031); // initialise time to 1st January 1970
    //1424535031

    introMessage();
    startClockMsg();
    /**
    @brief buttons 1 triggers on rising edge
    @brief button 3 triggers on thre rising edge
    */
    button1.rise(&button1Pressed);
    button3.rise(&button3Pressed);


    while(1) 
    {  
        
        if (msgFlag)    //if message flag is set to 1
        {
            startMessage(); //while loop will allow start message to tum   
        }
        
        if (button1Flag)    // check if button flag  is set
        //the renus the following codes
        {
            msgFlag=0;  //setmsgFlag to 0
            menu();     //call menu function
            menuLevelFlag = 1; //set menuLevelFunction to 1
        }
        /**
            @brief if menu level flag is set
            @briefset button 1 flag to 0
            @brief call menu level function, 
            @brief menu level function to be controlled by potentiometer
        */
        if (menuLevelFlag) 
        {
            button1Flag =0;
            menuLevel(potIn);
        }
        /**
            @brief if distance flag is set
            @brief set menu level flag to 0
            @brief call diatance measure function, 
            @brief button 1 rising edge sets distance flag to 0
        */
        if (distFlag) 
        {
            menuLevelFlag = 0;
            distMeasure();
           
            if(button1) 
            {
                distFlag = 0;
            }
        }      
        
        /**
            @brief if data flag is set
            @brief set menu level flag to 0
            @brief call data capture function, 
            @brief button 1 rising edge sets distance flag to 0
        */
        if (dataFlag) 
        {
            menuLevelFlag = 0;
            dataCapture();
            
            if(button1) 
            {
                dataFlag = 0;
            }
        }    
        /**
            @brief if next position flag is set
            @brief if rising edge of button 3 is encountered 
            @brief call next position function, 
            
        */
        if (nextPosFlag)
        {
            if (button3)
            nextPos();
        }    
        
        /**
            @brief if brigtness flag is set
            @brief set menu level flag to 0
            @brief call adjust brightness function to be controlled by potentiometer, 
            @brief button 1 rising edge sets brightness flag to  flag to 0
        */
        if (brightFlag) 
        {
            menuLevelFlag = 0;
            adjustBrightness(potIn);
            if (button1) 
            {
                brightFlag = 0;
            }
        }
        /**
            @brief if clock flag is set
            @brief set menu level flag to 0
            @brief call displayclock function, 
            @brief button 1 rising edge sets distance flag to 0
            @brief and set timer2Flag to 0
        */
        if (clockFlag) 
        {
            menuLevelFlag = 0;
            displayClock();
            if (button1) 
            {
                clockFlag = 0;
                timer2Flag = 0;
            }
        }
       /**
            @brief if timer2 flag is set
            @brief set timer2 flag to 0
            @brief call getCurrentTime function, 
            @brief button 1 rising edge sets distance flag to 0
        */
        if (timer2Flag)
        {
            timer2Flag = 0;
            getCurrentTime();   
        }
        /**
            @brief if setTime flag is set
            @brief call chkUpdateTime function, 
            @brief button 1 rising edge sets distance flag to 0
        */
        if (setTimeFlag) 
        {  
            chkUpdateTime();
        }
         // function goes to sleep when no activity 
        sleep();   
    }
}

/**
@brief introductory message

*/

void introMessage()
{
    /**
    @brief LED flash sequence
    @brief all LEDs ON
    */
    Led1 = 1;
    Led2 = 1;
    Led3 = 1;
    Led4 = 1;
    /**
    @brief introductory text a
    @brief name of project
    @brief wait for 1.3 secs
    @brief clear screen
    */
    
    lcd.drawLine(4, 0, 79, 0, 1);
    lcd.printString("Ultrasonic",13,1);
    lcd.printString("Distance",18,2);
    lcd.printString("Sensor",23,3);
    lcd.drawLine(4, 45, 79, 45, 1);

    wait(1.3);
    lcd.clear();

    /**
    @brief introductory text b
    @brief university name
    @brief wait for 1.3 secs
    @brief clear screen
    */
    
    lcd.drawLine(4, 0, 79, 0, 1);
    lcd.printString("University",13,1);
    lcd.printString("Of",35,2);
    lcd.printString("Leeds",26,3);
    lcd.drawLine(4, 45, 79, 45, 1);

    wait(1.3);
    lcd.clear();

    /**
    @brief introductory text c
    @brief programmert's name
    @brief wait for 1.3 secs
    @brief clear screen
    */
    
    lcd.drawLine(4, 0, 79, 0, 1);
    lcd.printString("Ibrahim Adam",5,1);
    lcd.printString("200789110",10,2);
    lcd.printString("Yr2 - 2015",8,3);
    lcd.drawLine(4, 45, 79, 45, 1);

    wait(1.3);
    lcd.clear();

    /**
    @brief introductory text d
    @brief module title
    @brief wait for 1.3 secs
    @brief clear screen
    */
    
    lcd.drawLine(4, 0, 79, 0, 1);
    lcd.printString("Elec 2645",15,1);
    lcd.printString("Embedded SYS",8,2);
    lcd.printString("Project",21,3);
    lcd.drawLine(4, 45, 79, 45, 1);

    msgFlag = 1;

    wait(1.3);
    lcd.clear();
}

/**
    @brief not included at present moment
    @brief a future posibilityt
    
    */
    
void errorHandler()
{
    //end text
    lcd.drawLine(4, 0, 79, 0, 1);
    lcd.printString("Error Help",12,1);


    wait(0.2);
    lcd.clear();
}

/**
    @brief adjust brightness function
    @brief takes float argument
    @brief checks the range
    @brief clear screen
    @brief set corresponding brightness
    @brief display brightness level on screen
    */
    
void adjustBrightness(float x)
{   
    if ((x >= 0) && (x < 0.2)) 
    {
        lcd.clear();
        lcd.setBrightness(0);
        lcd.printString("Light 0%",13,1);
    }

    if ((x >= 0.2) && (x < 0.4)) 
    {
        lcd.clear();
        lcd.setBrightness(0.25);
        lcd.printString("Light 25%",13,1);
    }

    if ((x >= 0.4) && (x < 0.6)) 
    {
        lcd.clear();
        lcd.setBrightness(0.5);
        lcd.printString("Light 50%",13,1);
    }

    if ((x >= 0.6) && (x < 0.8)) 
    {
        lcd.clear();
        lcd.setBrightness(0.75);
        lcd.printString("Light 75%",13,1);
    }
    if (x >= 0.8) 
    {
        lcd.clear();
        lcd.setBrightness(1);
        lcd.printString("Light 100%",13,1);
    }
         
}

/**
    @brief data capture function
    @brief display title
    @brief call distance measure function
    @brief set next positioFlag to 1

    
    */
void dataCapture()
{
    
    lcd.printString("Store Dist",9,0);
    
    distMeasure();
    nextPosFlag = 1;         
}  

/**
    @brief set LED sequence
    @brief clear screen
    @brief display main menu title
    @brief draw line at specitied location
    @brief print further information on subsquent lines
    @brief display brightness level on screen
    */
void menu()
{
    Led1 = 1;
    Led2 = 0;
    Led3 = 0;
    Led4 = 0;
    lcd.clear();
    lcd.printString("-MAIN MENU-",9,0);
    lcd.drawLine(4, 7, 79, 7, 1);
    lcd.printString("Dist read",15,1);
    lcd.printString("Data",15,2);
    lcd.printString("brightness",15,3);
    lcd.printString("SYS Clock",15,4);
}
/**
    @brief cursor select definition function
    @brief vertical start point, dommension 
    @brief horizontal start point, dimmension 
    @brief in all specified point coordinates turn off pixel
    
    */
void cursorSelect(int xDimm, int xLimm, int yDimm, int yLimm)
{
    int i,j;

    //clear selecton column
    for (i = 1; i < 6; i++) 
    {
        for(j = 1; j < 46; j++) 
        {
            lcd.clearPixel(i,j);
        }
    }

    //particular selection
    for (i = xDimm; i < xLimm; i++) 
    {
        for(j = yDimm; j < yLimm; j++) 
        {
            lcd.setPixel(i,j);
        }
    }
    lcd.refresh();
}


/**
void demo()
{
    // these are default settings so not strictly needed
    lcd.normalMode();      // normal colour mode
    lcd.setBrightness(0.5); // put LED backlight on 50%

    // can directly print strings at specified co-ordinates
    lcd.printString("Hello, World!",0,0);

    char buffer[14];  // each character is 6 pixels wide, screen is 84 pixels (84/6 = 14)
    // so can display a string of a maximum 14 characters in length
    // or create formatted strings - ensure they aren't more than 14 characters long
    int temperature = 27;
    int length = sprintf(buffer,"T = %2d C",temperature); // print formatted data to buffer
    // it is important the format specifier ensures the length will fit in the buffer
    if (length <= 14)  // if string will fit on display
        lcd.printString(buffer,0,1);           // display on screen

    float pressure = 1012.3;  // same idea with floats
    length = sprintf(buffer,"P = %.2f mb",pressure);
    if (length <= 14)
        lcd.printString(buffer,0,2);

    // can also print individual characters at specified place
    lcd.printChar('X',5,3);

    // draw a line across the display at y = 40 pixels (origin top-left)
    for (int i = 0; i < WIDTH; i++) 
    {
        lcd.setPixel(i,40);
    }
    // need to refresh display after setting pixels
    lcd.refresh();

    // can also check status of pixels using getPixel(x,y)

    wait(5.0);
    lcd.clear();            // clear display
    lcd.inverseMode();      // invert colours
    lcd.setBrightness(1.0); // put LED backlight on full

    float array[84];

    for (int i = 0; i < 84; i++) 
    {
        array[i] = 0.5 + 0.5*sin(i*2*3.14/84);
    }

    // can also plot graphs - 84 elements only
    // values must be in range 0.0 - 1.0
    lcd.plotArray(array);
    wait(5.0);
    lcd.clear();
    lcd.normalMode();      // normal colour mode back
    lcd.setBrightness(0.5); // put LED backlight on 50%

    // example of drawing lines
    for (int x = 0; x < WIDTH ; x+=10) 
    {
        // x0,y0,x1,y1,type 0-white,1-black,2-dotted
        lcd.drawLine(0,0,x,HEIGHT,2);
    }

    wait(5.0);
    lcd.clear();

    // example of how to draw circles
    lcd.drawCircle(WIDTH/2,HEIGHT/2,20,1);  // x,y,radius,black fill
    lcd.drawCircle(WIDTH/2,HEIGHT/2,10,2);  // x,y,radius,white fill
    lcd.drawCircle(WIDTH/2,HEIGHT/2,30,0);  // x,y,radius,transparent with outline

    wait(5.0);
    lcd.clear();

    // example of how to draw rectangles
    //          origin x,y,width,height,type
    lcd.drawRect(10,10,50,30,1);  // filled black rectangle
    lcd.drawRect(15,15,20,10,2);  // filled white rectange (no outline)
    lcd.drawRect(2,2,70,40,0);    // transparent, just outline

    wait(5.0);
    lcd.clear();
}

*/

/**
@brief Interrupt service routines
@brief button 1
@brief button 1 flag st to 1 to get while loop attention
@brief button 2
@brief button 2 flag st to 2 to get while loop attention
@brief button 3
@brief button 3 flag st to 3 to get while loop attention
*/
void button1Pressed()
{
    button1Flag = 1;
}
void button2Pressed()
{
    button2Flag = 1;
}
void button3Pressed()
{
    button3Flag = 1;
}
/**
@brief beep sound based on beeper frequency and beeper time
@brief entered respectively
*/
void beeper(float beeperFreq, float beeperTime)
{
    beep1.beep(beeperFreq,beeperTime);
}

/**
@brief menu level function, takes float argument
@brief argument checked against range 0 -1
@brief corresponding cursor position established
@brief if rising edge of button 2 encountered 
@brief clear screen
@brief set distance flag to 1
@brief set bright flag to 0
@brief set clock flag to 0
@brief set data flag to 0
*/
void menuLevel(float lvl)
{
    if ((lvl >= 0) && (lvl < 0.25)) 
    {
        cursorSelect(1, 6, 9, 14);
        if (button2) 
        {   
            lcd.clear();
            distFlag = 1;
            brightFlag = 0;
            clockFlag = 0;
            dataFlag = 0;
           
        }    
    }
    if ((lvl >= 0.25) && (lvl < 0.5))
    {
        cursorSelect(1, 6, 17, 22);
        if (button2)
        {
            lcd.clear();
            dataFlag = 1;
            brightFlag = 0;
            distFlag =0;
            clockFlag = 0;      
        }       
    }
    
    if ((lvl >= 0.5) && (lvl < 0.75)) 
    {
        cursorSelect(1, 6, 25, 30);
        if (button2) 
        {
            lcd.clear();
            brightFlag = 1;
            distFlag =0;
            clockFlag = 0;
            dataFlag = 0;
        }
    }
    if ((lvl >= 0.75) && (lvl <= 1)) 
    {
        cursorSelect(1, 6, 33, 38);
        if (button2) 
        {
            clockFlag = 1;
            distFlag = 0;
            brightFlag = 0;
            dataFlag = 0;
        }
    }
}

/**
@brief function wo return distance 
@brief distance based on speeed of sound and time travelled to and from

*/
void distMeasure()
{
    /**
    @brief print title Measure
    @brief return sensor distance in cms
    @brief do proximity check
    
    */
    lcd.printString("Measure",15,0);
    distance = sensor.getDistanceCm();
    proxCheck();
    
    /**
    @brief read sensor distance in cm and print over serial port
    @brief each character is 6 pixels wide, screen is 84 pixels (84/6 = 14)
    @brief so can display a string of a maximum 14 characters in length
    @brief or create formatted strings - ensure they aren't more than 14 characters long
     */
    char buffer[14];  
    /**
    @brief print formatted data to buffer
    @brief it is important the format specifier ensures the length will fit in the buffer
    */
    int length = sprintf(buffer,"Dist = %2d cm",distance); 
    
    if (length <= 14)
    { // if string will fit on display
        lcd.printString(buffer,0,1);           // display on screen   
    }
 
}

void saveData()
{
    lcd.printString("Save data",36,0);
}
void sysClock()
{
    lcd.printString("System test",30,0);
}
/**
@brief start message function
@brief LED session sequence
@brief display subsequent messages

*/
void startMessage()
{
    Led1 = 1;
    Led2 = 1;
    Led3 = 1;
    Led4 = 0;
    lcd.printString("Press",25,2);
    lcd.printString("Start Button",8,3);
    //displayClock();

}
/**
@brief displayClock function
@brief clear screen
@brief print title

@brief check if timer2Flag is on
@brief if yes, get current time
@brief if setTimeflag
@brief check upate time
@brief print contents of buffer to screen
*/
void displayClock()
{
   
    lcd.clear();

    lcd.printString("-SYS CLOCK-",9,0);

    if (timer2Flag) 
    {
        getCurrentTime();
    }

    if (setTimeFlag) 
    {
        chkUpdateTime();
    }

    lcd.printString(buffer2,4,2);           // display on screen
}

/*buzzer function
@brief 

*/
void buzzerRange()
{
    {
        beeper(400,distance);
    }
}

/**
@brief start clock message function
@brief LED session sequence
@brief if no time displayed
@brief display clock
@brief print title on screen
@brief clear and print in succession
*/
void startClockMsg()
{
    Led1 = 1;
    Led2 = 1;
    Led3 = 0;
    Led4 = 0;
    if(time(NULL)) {
        displayClock();
        lcd.printString("Set Clock",15,0);
        wait(0.3);
        clearRow();
        wait(0.3);
        lcd.printString("Set Clock",15,0);
        wait(0.3);
        clearRow();
        wait(0.3);
        lcd.printString("Set Clock",15,0);
        wait(0.3);
        clearRow();
        wait(0.3);
        lcd.printString("Set Clock",15,0);
        wait(1.3);
        
    } 
    else 
    {
        //diplay clock 
        displayClock();
        lcd.printString("Clock Set",15,0);
        wait(1.3); 
    }
    lcd.clear();
}

//clear selected row
void clearRow()
{
    for (int j = 0; j <8; j++)
    {
        for(int i = 0; i < 84; i++)
        {
            lcd.clearPixel(i,j);   
        }       
    } 
}   

/**
@brief check range of distance
@brief assign a particular buzzing frequency

*/ 
void proxCheck()
{
    if ((distance>=20) && (distance <50)) 
    {
        beeper(1000, 0.2);
         
    }       
 
    if ((distance >= 10) && (distance < 20))
    {
        beeper(3000, 0.2);
       
    }
 
    if (distance < 10)
    {
        beeper(4000, 0.2);      
    }    

}

/**
@brief next position function
@brief if position is greater than3 default to 0
@brief switch statement uses position value
@brief getPointA - first sampled distance
@brief getPointB - second sampled distance
@brief calculate dist  subtract to get difference
*/
void nextPos()
{
        
        if (position > 3)
        {
            position = 0;   
        } 
        switch (position)
        {
            case 0:
            //lcd.clear();
            //lcd.printString("Point A",9,1);
            getPointA();
            //wait(1);
            break;
            
            case 1:
            //lcd.clear();
            //lcd.printString("Point B",9,1);
            getPointB();
            //wait(1);
            break;
            
            case 2:
            //lcd.clear();
            lcd.printString("Dist   ",9,1);
            calculateDist();
            //wait(1);
            break;
            case 3:
            
            //
           // writeDataToFile(bufferE, positionA);
            //writeDataToFile(bufferF, positionB);
            
            //lcd.printString(bufferC,0,2); 
            
            positionA = 0;
            positionB = 0;
            lcd.clear();
            break;   
        }
        //clearRow2();
        position = position + 1;          
              
}    
/**
@brief point A is assigned value from distance returned value
*/
void getPointA()
{
    //positionA = 0;
    positionA = distance;
    
     
    int lengthE = sprintf(bufferE,"Org = %2d cm",positionA); 
    if (lengthE <= 14)
    { 
        lcd.printString(bufferE,0,2);                 
    }  
} 
/**
@brief point B is assigned value from distance returned value
*/     
void getPointB()
{
   // positionB = 0;
    positionB = distance;
    
    
    int lengthF = sprintf(bufferF,"Dest = %2d cm",positionB); 
    if (lengthF <= 14)
    { 
        lcd.printString(bufferF,0,3);                 
    } 
} 
/**
@brief calculate seperation distance
*/
void calculateDist()
{
    movedDist = positionB - positionA; 
      
    int lengthD = sprintf(bufferD,"Dist = %2d cm",movedDist); 
    if (lengthD <= 14)
    { 
        lcd.printString(bufferD,0,4); 
        //writeDataToFile(bufferD, movedDist);        
    }
} 
//clears specific row 
void clearRow2()
{
    for(int ir = 0; ir < 84; ir ++)
    {
        for(int jr = 8; jr < 16; jr ++)
        {
            lcd.clear();
        } 
    }           
}   
/**
@brief writing to flash memory
@brief opening file, type FILE , 
@brief print string to file
@brief close file
*/
void writeDataToFile(char* (data2), float data)
{
    //leds = 15; //turn on leds for feedback
    FILE *fp = fopen("/local/log.csv", "a"); //open 'log.csv' for apending
    
    //if the file doesnt exist it is created, if it exists, data is apended to the end
    fprintf(fp, "%s, %0.2f C\n", data2, data); //print string to file
    
    fclose(fp); //close file
    
   // leds = 0; //turn off leds to signify file access has finished     
    
}