-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlasersensor_v2.ino
87 lines (74 loc) · 2.24 KB
/
lasersensor_v2.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <SoftwareSerial.h>
// common variables for TOF10120 UART reading and parsing
String rx_tof = "";
char rx_char;
uint8_t double_m = 0;
bool newLine_tof = false;
// total distance value
uint8_t distance = 0;
// Average filter variables, because of noise of raw sensor values from UART
uint8_t counter = 0;
int commulative = 0;
const uint8_t koeff = 5; // average coefficient
// software serial #1: RX = digital pin 10, TX = digital pin 11
SoftwareSerial portOne(10, 11);
void setup() {
// Open serial communications (monitoring port)
Serial.begin(9600);
// Start software serial port (TOF10120 port)
portOne.begin(9600);
Serial.println("TOF10120 Laser Distance Metering Sensor start...");
portOne.write("s2-20#"); // not realy sure that this line is neccesary, taken from https://github.com/SoyM/TOF10120 example
// I don't speak Chinese (datasheet only in Chinese language), that's why i doesn't really know what this command do with sensor
// if look for answer - it just unswering "OK"
// and you can try this example without this line - it working well too.
}
void loop() {
// Getting values from sensor procedure
measure();
}
void measure()
{
rx_tof = "";
// Values parsing from TOF10120 UART
while (1) {
if (portOne.available()) {
rx_char = portOne.read();
if (rx_char == 10) {
newLine_tof = true;
continue;
}
if (newLine_tof == true) {
if (rx_char == 'm') {
double_m = double_m + 1;
}
else {
rx_tof.concat(rx_char);
}
if (double_m == 2) {
newLine_tof = false;
break;
}
}
}
}
newLine_tof = false;
double_m = 0;
// average sensor values and print to Serial
if (rx_tof != "") {
if (counter < koeff)
{
commulative = commulative + (rx_tof.toInt() / 10);
counter = counter + 1;
}
else
{
distance = commulative / counter;
commulative = 0;
counter = 0;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm.");
}
}
}