A program designed to get the distance from an SRF02 distance sensor and create an audible and visual indication of that distance with data logging capabilities.
Dependencies: N5110 PowerControl SRF02 mbed
Diff: main.cpp
- Revision:
- 0:7d01de89a1ff
- Child:
- 1:387d5e6fa05f
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Wed Apr 08 16:57:08 2015 +0000 @@ -0,0 +1,90 @@ +// Distance Sensor Project +// Main File "main.cpp" +// Designed By Sam Russell (200773195) +// Date: 07/04/2015 || Version: 0.1 + +#include "mbed.h" + +DigitalOut myled(LED1); + +int main() { + pc.baud(9600); //setting the baud rate + timer.attach(&timerExpired,1); + display.init(); // Initialise the display. + display.clear(); // Clears the starting pattern from the screen. + display.printString("--++--++--++--",0,0); //Print string of "" at x,y locations. + display.printString("Distance",18,1); + display.printString("Sensor",22,2); + display.printString("--++--++--++--",0,3); + display.printString("Sam Russell",10,4); + display.printString("--++--++--++--",0,5); + wait(2); //Delay between the introduction and the begining of the game. + display.clear(); //Clears the display. + drawRect(int 0,int 0,int 80,int 20,int 0) + } +} + +while(1) { + if(timerflag) { + timerflag = 0; + ///Read sensor distance in cm and print to the serial port. + distance = avgDist(); + pc.printf("Distance = %.2f cm\n",distance); + if(distance<75) { + leds = 15; + } else if(distance<150) { + leds = 7; + } else if(distance<275) { + leds = 3; + } else { + leds = 1; + } + } + + } +} + +//When timer expires set flag to equal 1. +void timerExpired() +{ + timerflag = 1; +} + +void error(int code) +//ERROR CODE +{ + while(1) { + leds = 0; + wait(0.25); + leds = code; + wait(0.25); + } +} + +float avgDist() +//Read the distance from the sensor every 10ms. +//After 10 readings calculate the average and define that as the total distance. +{ + float d1 = SRF02.getDistanceCm(); + wait(0.01); + float d2 = SRF02.getDistanceCm(); + wait(0.01); + float d3 = SRF02.getDistanceCm(); + wait(0.01); + float d4 = SRF02.getDistanceCm(); + wait(0.01); + float d5 = SRF02.getDistanceCm(); + wait(0.01); + float d6 = SRF02.getDistanceCm(); + wait(0.01); + float d7 = SRF02.getDistanceCm(); + wait(0.01); + float d8 = SRF02.getDistanceCm(); + wait(0.01); + float d9 = SRF02.getDistanceCm(); + wait(0.01); + float d10 = SRF02.getDistanceCm(); + float distance = (d1+d2+d3+d4+d5+d6+d7+d8+d9+d10)/10; + return distance; +} +