mpmcws

Radar

Jun 15th, 2018
106
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Includes the Servo library
  2. #include <Servo.h>
  3. // Defines Tirg and Echo pins of the Ultrasonic Sensor
  4. const int trigPin = 10;
  5. const int echoPin = 11;
  6. // Variables for the duration and the distance
  7. long duration;
  8. int distance;
  9. Servo myServo; // Creates a servo object for controlling the servo motor
  10. void setup() {
  11.   pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  12.   pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  13.   Serial.begin(9600);
  14.   myServo.attach(12); // Defines on which pin is the servo motor attached
  15. }
  16. void loop() {
  17.   // rotates the servo motor from 15 to 165 degrees
  18.   for(int i=15;i<=165;i++){  
  19.   myServo.write(i);
  20.   delay(30);
  21.   distance = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree
  22.  
  23.   Serial.print(i); // Sends the current degree into the Serial Port
  24.   Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  25.   Serial.print(distance); // Sends the distance value into the Serial Port
  26.   Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
  27.   }
  28.   // Repeats the previous lines from 165 to 15 degrees
  29.   for(int i=165;i>15;i--){  
  30.   myServo.write(i);
  31.   delay(30);
  32.   distance = calculateDistance();
  33.   Serial.print(i);
  34.   Serial.print(",");
  35.   Serial.print(distance);
  36.   Serial.print(".");
  37.   }
  38. }
  39. // Function for calculating the distance measured by the Ultrasonic sensor
  40. int calculateDistance(){
  41.  
  42.   digitalWrite(trigPin, LOW);
  43.   delayMicroseconds(2);
  44.   // Sets the trigPin on HIGH state for 10 micro seconds
  45.   digitalWrite(trigPin, HIGH);
  46.   delayMicroseconds(10);
  47.   digitalWrite(trigPin, LOW);
  48.   duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
  49.   distance= duration*0.034/2;
  50.   return distance;
  51. }
RAW Paste Data