Social distance

Kuo, Li-Wen
1 min readFeb 15, 2021

--

/* Social Distance App
Using ultrasonic distance sensor to trigger different leds
*/

const int pingPin = 12; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 13; // Echo Pin of Ultrasonic Sensor
int redLed = 2;
int yellowLed = 3;
int greenLed = 9;

int safeLine = 20;
int dangerLine = 10;
// >= 30 is safe
// <=30 && >=20 is ok
// <=20 is danger

void setup() {
Serial.begin(9600); // Starting Serial Terminal
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}

void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print(“in, “);

if (inches >= safeLine) {
Serial.println(“safe”);
digitalWrite(greenLed, HIGH);
digitalWrite(yellowLed, LOW);
digitalWrite(redLed, LOW);
} else if (inches <= safeLine && inches >= dangerLine) {
Serial.println(“ok”);
digitalWrite(yellowLed, HIGH);
digitalWrite(greenLed, LOW);
digitalWrite(redLed, LOW);
} else if (inches <= dangerLine){
Serial.println(“dangerous”);
digitalWrite(yellowLed, LOW);
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
}
// Serial.print(cm);
// Serial.print(“cm”);
Serial.println();
delay(100);
}

long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}

--

--