/* Title: Ultrasonic_sensor.ino Author: Lucas Lim Date Created: 2/4/2019 Last Modified: 4/4/2019 Purpose: To activate Ultrasonic sensor and send data to computer Ultrasonic sensor Pins: VCC: +5V DC Trig : Trigger (INPUT) - Arduino Pin9 (PB1) Echo: Echo (OUTPUT) - Arduino Pin10 (PB0) GND: GND Original code created by Rui Santos, https://randomnerdtutorials.com */ #include SoftwareSerial mySerial(1, 0); // RX, TX int trigPin = 9; // Trigger int echoPin = 10; // Echo long duration, cm, inches; void setup() { //Serial Port begin mySerial.begin (9600); //Define inputs and outputs pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor: a HIGH pulse whose // duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // Convert the time into a distance cm = duration/58; // uS divide by 58 to give cm inches = duration/148; // uS divide by 148 to give inches mySerial.print(inches); mySerial.print("in, "); mySerial.print(cm); mySerial.print("cm"); mySerial.println(); delay(250); }