-
Notifications
You must be signed in to change notification settings - Fork 1
/
LIDARcontrol.py
51 lines (37 loc) · 1.53 KB
/
LIDARcontrol.py
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
#!/usr/bin/env python
# Read LIDAR sensor data on Raspberry Pi from Arduino through serial
#-------------------------------------------------------------------------------
#### Imports ####
import serial
from pprint import pprint
import re
#### Objects ####
#-------------------------------------------------------------------------------
# Open serial port
ser = serial.Serial('/dev/ttyACM0', 115200)
# Set number of readings to take, a higher value provides more precise readings
ACCURACY = 10
class LIDARControl(object):
# Make sure there is only one instance of LIDARControl
_instances=[]
# Initialize the object
def __init__(self):
if (len(self._instances) > 1):
print("ERROR: One instance of LIDARControl is running already.")
exit(1)
self._instances.append(self)
# Reads the serial port for LIDAR sensor reading from Arduino
def distance(self):
total = 0
# Poll the sensor and average out the readings according to the desired precision
for num in range(ACCURACY):
# Read serial port and extract only digits
sensor_reading = str(ser.readline())
clean_sensor_reading = re.findall(r'\d+', sensor_reading)
# Ensure reading is valid
if len(clean_sensor_reading) is 1:
if str(clean_sensor_reading[0]).isdigit():
total += int(clean_sensor_reading[0])
# Average the readings
total = total/ACCURACY
return total