// barbara's code zur led-steuerung via ultraschallsensor
// define arduino pins
const int trigPin = 9;
const int echoPin = 10;
//ledPin is connected to an LED
//inside a ping-pong ball
const int ledPin = 13;
// define variables
long duration;
int distance;
int safetyDistance;
void setup() {
pinMode(trigPin, OUTPUT); // sets the trigPin as output
pinMode(echoPin, INPUT); // sets the echoPin as input
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // starts serial communication
}
void loop() {
digitalWrite(trigPin, LOW); // clears the trigPin
delayMicroseconds(2); // sets delay
digitalWrite(trigPin, HIGH); // sets the trigPin on HIGH
delayMicroseconds(14); // sets delay
digitalWrite(trigPin, LOW); // sets the trigPin on LOW
duration = pulseIn(echoPin, HIGH); // reads the echoPin
// returns the transmission speed
// of the sound waves in microseconds
distance= duration*0.034/2;
// calculating the distance (centimetres)
safetyDistance = distance;
if (safetyDistance <= 5){ // value <= 5cm
digitalWrite(ledPin, HIGH);// led on
}
else{
digitalWrite(ledPin, LOW); // else: led off
}
}