Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define echoPin 10
- #define trigPin 9
- #define ledPin 4
- long duration;
- int distance;
- int flag = 0;
- //----------------------------------
- int alertDistance = 20; // 20 CM
- //----------------------------------
- void setup() {
- Serial.begin(9600);
- Serial.println("Serial COM Test");
- pinMode(ledPin, OUTPUT);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- digitalWrite(ledPin, 1);
- }
- void loop() {
- US();
- if (distance < alertDistance) {
- digitalWrite(ledPin, 0);
- }
- else {
- digitalWrite(ledPin, 1);
- }
- delay(50);
- }
- void US() {
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH);
- distance = duration * 0.034 / 2;
- Serial.print("Distance: ");
- Serial.print(distance);
- Serial.println(" cm");
- }
Advertisement
Add Comment
Please, Sign In to add comment