/
LRF50M3PS-samplecode.py
74 lines (64 loc) · 1.99 KB
/
LRF50M3PS-samplecode.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# =============================================================================
# The sample code will use the pyserial lib. Please use the following command to install the required packages.
# $ sudo pip install pyserial
# =============================================================================
import serial.tools.list_ports
import sys
#List available COMport
ports = serial.tools.list_ports.comports()
portlist=[]
index=0
for port, desc, hwid in ports:
portlist.append(port)
print(str(index)+") "+desc+"|"+port)
index+=1
if portlist == []:
print("No serial ports detected")
sys.exit()
#Select COMport
portname=input("Please input the number of the desired port: \n")
try:
ser = serial.Serial(
port=portlist[int(portname)],\
baudrate=115200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=3)
except Exception as e:
print(str(e))
sys.exit()
#Laser OFF (Confirm LRF is in default off state)
cmd=b'$0003260029&'
ser.write(cmd)
#Select functions
while True:
key=input("\nPlease enter the operation command:\n -s single measurement\n -o Laser ON\n -f Laser OFF\n -q Exit\n")
#Single measurement
if key=='s':
ser.reset_input_buffer()
cmd=b'$00022123&'
ser.write(cmd)
#The confirmation response will be discard
data=ser.read_until(b'&')
#The second response includes the measurement
data=ser.read_until(b'&')
if(len(data)==18):
print('Module response: '+str(data))
distance = int(data[7:15])
print(str(distance)+'mm\n')
#Laser ON
elif key=='o':
cmd=b'$0003260130&'
ser.write(cmd)
#Laser OFF
elif key=='f':
cmd=b'$0003260029&'
ser.write(cmd)
#Exit
elif key=='q':
ser.close()
sys.exit()
#Incorrect Input
else:
print("Invalid option. Please enter one of the above options.")