You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.1 KiB
41 lines
1.1 KiB
6 years ago
|
/*
|
||
|
* Simple code to test the distance sensor function and electrical connections.
|
||
|
*/
|
||
|
int DIST_ECHO_PIN = 10;
|
||
|
int DIST_TRIG_PIN = 11;
|
||
|
long duration, cm;
|
||
|
|
||
|
void setup() {
|
||
|
// Starts the serial com with PC
|
||
|
Serial.begin(9600);
|
||
|
Serial.println("Running setup function");
|
||
|
|
||
|
//Defines inputs and outputs
|
||
|
pinMode(DIST_TRIG_PIN, OUTPUT);
|
||
|
pinMode(DIST_ECHO_PIN, INPUT);
|
||
|
}
|
||
|
|
||
|
void loop() {
|
||
|
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
|
||
|
// Gives a short LOW pulse beforehand to ensure a clean HIGH pulse:
|
||
|
digitalWrite(DIST_TRIG_PIN, LOW);
|
||
|
delayMicroseconds(5);
|
||
|
digitalWrite(DIST_TRIG_PIN, HIGH);
|
||
|
delayMicroseconds(10);
|
||
|
digitalWrite(DIST_TRIG_PIN, LOW);
|
||
|
|
||
|
// Reads 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(DIST_ECHO_PIN, INPUT);
|
||
|
duration = pulseIn(DIST_ECHO_PIN, HIGH);
|
||
|
|
||
|
// Converts the time into a distance
|
||
|
cm = (duration/2) / 29.1;
|
||
|
|
||
|
Serial.print(cm);
|
||
|
Serial.print("cm");
|
||
|
Serial.println();
|
||
|
|
||
|
delay(1000);
|
||
|
}
|