Skip to content

Commit 1209125

Browse files
committed
Distance measure example
1 parent 4147204 commit 1209125

File tree

2 files changed

+57
-5
lines changed

2 files changed

+57
-5
lines changed

distanceMeasure/distanceMeasure.ino

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Ultrasonic sensor Pins:
3+
VCC: +5VDC
4+
Trig : Trigger (INPUT) - Pin11
5+
Echo: Echo (OUTPUT) - Pin 12
6+
GND: GND
7+
*/
8+
9+
#define trigPin 11
10+
#define echoPin 12
11+
12+
long duration;
13+
int cm;
14+
15+
void setup() {
16+
//Serial Port begin
17+
Serial.begin (9600);
18+
//Define inputs and outputs
19+
pinMode(trigPin, OUTPUT);
20+
pinMode(echoPin, INPUT);
21+
pinMode(LED_BUILTIN, OUTPUT);
22+
digitalWrite(LED_BUILTIN, LOW);
23+
}
24+
25+
26+
void measureDistance(){
27+
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
28+
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
29+
digitalWrite(trigPin, LOW);
30+
delayMicroseconds(5);
31+
digitalWrite(trigPin, HIGH);
32+
delayMicroseconds(10);
33+
digitalWrite(trigPin, LOW);
34+
35+
// Read the signal from the sensor: a HIGH pulse whose
36+
// duration is the time (in microseconds) from the sending
37+
// of the ping to the reception of its echo off of an object.
38+
duration = pulseIn(echoPin, HIGH);
39+
40+
// Convert the time into a distance
41+
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
42+
Serial.print(cm);
43+
Serial.println();
44+
}
45+
46+
void loop() {
47+
measureDistance();
48+
delay(50);
49+
}

main.cpp

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
1-
#include<unistd.h> // Just for sleep()
1+
#include <chrono>
2+
#include <thread>
23

34
#include <iostream>
45
#include <string>
56

67
#include "arduinoSerial.h"
78

89
int main(){
9-
arduinoSerial serial("/dev/ttyACM0", true);
10+
arduinoSerial serial("/dev/ttyACM0", false);
1011
serial.begin(B9600);
11-
// ParseFloat test
1212
while(true){
13-
std::cout << serial.parseFloat() << std::endl;
14-
sleep(1);
13+
if(serial.available()){
14+
std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Wait for the data to come in, otherwise it will be incomplete
15+
std::cout << serial.parseFloat() << std::endl;
16+
serial.flush();
17+
}
1518
}
1619
return 0;
1720
}

0 commit comments

Comments
 (0)