arduino ultra sonic tester

 

Version 1

this code test for the key r being typed into serial port and then tests uses a ultra sonic sensor to check the distance
#define trigPin 12
#define echoPin 8

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop(){

String content = “”;
char character;

while(Serial.available()) {
character = Serial.read();
content.concat(character);
}

if (content == “r”) {
readdistance();
}

}

void readdistance() {
long duration, distance;
digitalWrite(trigPin, LOW);  // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); – Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println(“Out of range”);
}
else {
Serial.print(distance);
Serial.println(” cm”);
}
delay(500);
}

 

 

 

Version 2

more advanced code type in some thing but at the end always type ; example hello;

if you type dist; it will read the distance

#define trigPin 12
#define echoPin 8
String inputString = “”;
boolean stringComplete = false;

void setup() {
Serial.begin (9600);
Serial.print (“Power on”);
Serial.println();
inputString.reserve(200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop(){

if (stringComplete) {

Serial.print(inputString);

if (inputString == “dist;”){

readdistance();

}

Serial.println();
inputString = “”;
stringComplete = false;
}

}

void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputString += inChar;

if (inChar == ‘;’) {

stringComplete = true;

}

}
}

void readdistance() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

if (distance >= 250 || distance <= 0){
Serial.println(” Out of range or 0 cm”);
}
else {
Serial.print(distance);
Serial.println(” cm”);
}
delay(500);
}