/* ULTRASONIC SENSOR 18.02.2020 */ const int trigPin = A0; const int echoPin = A1; int out6 = 4 ; // defines variables long duration, cm, inches; void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input pinMode(out6, OUTPUT); } void loop() { // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(5); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // Calculating the distance cm = (duration/2)/29.1; Serial.println(cm); if (cm < 30) // obsticle detected { analogWrite(out6, cm); // delay(200); } else { analogWrite(out6, 0); } }