/* Project: Ultrasonic sensor HC SR04, 5V servo motor Function: Ultrasonic radar. Use of Processing software for visualisation */ //******************************************************************************* #include //include library code //******************************************************************************* const int trigPin = 2;//ultrasonic sensor trig pin attached to digital pin 2 of Arduino Uno const int echoPin = 3;//ultrasonic sensor trig pin attached to digital pin 3 of Arduino Uno const int servoPin = 9;//servo motor attached to digital pin 9 PWM //(you can use any PWM pin - 3, 9, 10, 6 or 11) long duration;//variable for duration int distance;//variable for distance Servo myServo; //creates servo object //******************************************************************************** void setup() { pinMode(trigPin, OUTPUT); //sets trigPin as an OUTPUT pinMode(echoPin, INPUT); //sets echoPin as an INPUT Serial.begin(9600);//initialize the serial communication at 9600 bps myServo.attach(servoPin);//attach the servo to servo object } void loop() { //rotates the servo motor from 0 to 180 degrees for(int i=0;i<=180;i++){ myServo.write(i); delay(30);//sets delay for 30 ms distance = calculateDistance();//calls the function calculateDistance() Serial.print(i); //sends the current degree into the Serial Port Serial.print(","); //sends addition character right next to the previous value needed later in the Processing IDE for indexing Serial.print(distance); //sends the distance value into the Serial Port Serial.print("."); //sends addition character right next to the previous value needed later in the Processing IDE for indexing } //repeats the previous lines from 180 to 0 degrees for(int i=180;i>0;i--){ myServo.write(i); delay(30);//sets delay for 30 ms distance = calculateDistance(); Serial.print(i); Serial.print(","); Serial.print(distance); Serial.print("."); } } //************************************************************************* // Function for calculating the distance measured by the Ultrasonic sensor int calculateDistance(){ digitalWrite(trigPin, LOW); //sets the trigPin on LOW state for 2 ms delayMicroseconds(2); digitalWrite(trigPin, HIGH); //sets the trigPin on HIGH state for 10 ms delayMicroseconds(10); digitalWrite(trigPin, LOW);//sets the trigPin on LOW state duration = pulseIn(echoPin, HIGH); //reads the echoPin, returns the sound wave travel time in microseconds distance= duration*0.034/2; return distance; }