/* Ultrasonic_sensor.ino by Lucas Lim created on 22/4/2020 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 const int trigPin = 9; // Trigger pin const int echoPin = 10; // Echo pin long duration, cm; int c = 1; void setup() { //Initialising Serial Port Communication mySerial.begin (9600); //Define inputs and outputs pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // read from serial for stop character if (mySerial.available()>0){ // read from serial c = mySerial.read(); } while (c != 0){ // 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(2); // set the trip pin high high for 10 smicroseconds 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. duration = pulseIn(echoPin, HIGH); // Convert the time into a distance cm = duration *0.034/2; mySerial.print(cm); mySerial.println(); delay(100); //delay 1 tenth of a sec } }