Advertisement
amosmyn

Basic Ultrasonic

Feb 8th, 2019
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1.  
  2. /*
  3.  * Basic Ultrasonic
  4.  * by Tyson Moll
  5.  *
  6.  * References:
  7.  * Ultrasonic Tutorial by Rui Santos, https://randomnerdtutorials.com
  8.  *
  9.  */
  10. #include <Wire.h>
  11. #include <ArduinoJson.h>
  12.  
  13. // Ultrasonic
  14. int trigPin = 5;    // Ultrasonic Trigger
  15. int echoPin = 6;    // Ultrasonic Echo
  16. long duration, cm; // Units for Ultrasonic
  17. unsigned long lastSend, sonicCount;
  18. int sendRate = 50;
  19. int sonicRate = sendRate;
  20.  
  21. // Thermochromic Pins
  22. int ledPin = 7;
  23. int chromicPin = 4;
  24. int dist = 10; // Distance to light at
  25.  
  26. void setup() {
  27.   Serial.begin(9600);
  28.   pinMode(trigPin, OUTPUT); // Ultrasonic
  29.   pinMode(echoPin, INPUT);
  30.   pinMode(ledPin, OUTPUT); // Thermochromics
  31.   pinMode(chromicPin, OUTPUT);
  32. }
  33.  
  34. void loop() {
  35.  
  36.   // Ultrasonic
  37.   if (millis() - sonicCount >= sonicRate) {
  38.     digitalWrite(trigPin, LOW); // LOW clearing ensures clean HIGH pulse
  39.     delayMicroseconds(5); // 0.000005 seconds
  40.     digitalWrite(trigPin, HIGH); // Triggers ultrasonic signal
  41.     delayMicroseconds(10);
  42.     digitalWrite(trigPin, LOW);
  43.    
  44.     // Read the signal from the sensor: a HIGH pulse whose
  45.     // duration is the time (in microseconds) from the sending
  46.     // of the ping to the reception of its echo off of an object.
  47.     pinMode(echoPin, INPUT);
  48.     duration = pulseIn(echoPin, HIGH);
  49.    
  50.     // Convert the time into a distance
  51.     cm = (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
  52.  
  53.     Serial.print(cm); // Report unit distance
  54.     Serial.print("cm");
  55.     Serial.println();
  56.   }
  57.  
  58.   if (cm > dist) {
  59.     digitalWrite(ledPin, HIGH);
  60.     digitalWrite(chromicPin, HIGH);
  61.   } else {
  62.     digitalWrite(ledPin, LOW);
  63.     digitalWrite(chromicPin, LOW);  
  64.   }
  65.  
  66.   delay(100);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement