1
2
3 '''
4 Class that represents an ultrasonic sensor.
5
6 This software is part of the raspibrick module.
7 It is Open Source Free Software, so you may
8 - run the code for any purpose
9 - study how the code works and adapt it to your needs
10 - integrate all or parts of the code in your own programs
11 - redistribute copies of the code777
12 - improve the code and release your improvements to the public
13 However the use of the code is entirely your responsibility.
14 '''
15
16 import SharedConstants
17 from RobotInstance import RobotInstance
18 from Tools import Tools
19 import RPi.GPIO as GPIO
20 import time
21
23 '''
24 Class that represents an ultrasonic sensor.
25 '''
27 '''
28 Creates a sensor instance.
29 '''
30 self.sensorState = "FAR"
31 self.sensorType = "UltrasonicSensor"
32 self.triggerLevel = 20
33 self.nearCallback = None
34 self.farCallback = None
35 for key in kwargs:
36 if key == "near":
37 self.nearCallback = kwargs[key]
38 elif key == "far":
39 self.farCallback = kwargs[key]
40 robot = RobotInstance.getRobot()
41 if robot == None:
42 RobotInstance._sensorsToRegister.append(self)
43 else:
44 if self.nearCallback != None or self.farCallback != None:
45 robot.registerSensor(self)
46 Tools.debug("UltrasonicSensor instance created")
47
93
95 '''
96 Returns the distance.
97 @return: Distance from target in cm formatted to two decimals, or -1 if no object or error
98 @rtype: str
99 '''
100 return format(self.getValue(), ".2f")
101
103 return self.triggerLevel
104
106 self.triggerLevel = level
107
109 return self.sensorState
110
112 self.sensorState = state
113
115 return self.sensorType
116
118 if self.nearCallback != None:
119 self.nearCallback(v)
120
122 if self.farCallback != None:
123 self.farCallback(v)
124
128