forked from DexterInd/GoPiGo3
/
easysensors.py
1957 lines (1412 loc) · 70 KB
/
easysensors.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from I2C_mutex import Mutex
import time
# needed for duck typing
import gopigo3
import operator
mutex = Mutex()
def _ifMutexAcquire(mutex_enabled=False):
"""
Acquires the I2C if the ``use_mutex`` parameter of the constructor was set to ``True``.
Always acquires if system-wide mutex has been set.
"""
if mutex_enabled or mutex.overall_mutex()==True:
mutex.acquire()
def _ifMutexRelease(mutex_enabled=False):
"""
Releases the I2C if the ``use_mutex`` parameter of the constructor was set to ``True``.
"""
if mutex_enabled or mutex.overall_mutex()==True:
mutex.release()
def debug(in_str):
if False:
print(in_str)
try:
from line_follower import line_sensor
# is_line_follower_accessible not really used, just in case
is_line_follower_accessible = True
except:
try:
sys.path.insert(0, '/home/pi/GoPiGo/Software/Python/line_follower')
import line_sensor
is_line_follower_accessible = True
except:
is_line_follower_accessible = False
#############################################################
# SENSORS
#############################################################
class Sensor(object):
"""
Base class for all sensors. Can only be instantiated through the use of an :py:class:`~easygopigo3.EasyGoPiGo3` object.
It *should* only be used as a base class for any type of sensor. Since it contains methods for setting / getting the ports or the pinmode,
it's basically useless unless a derived class comes in and adds functionalities.
:var str port: There're 4 types of ports - analog, digital, I2C and serial ports. The string identifiers are mapped in the following graphical representation - :ref:`hardware-ports-section`.
:var str pinmode: Represents the mode of operation of a pin - can be a digital input/output, an analog input/output or even a custom mode which must defined in the `GoPiGo3`_'s firmware.
:var int pin: Each grove connector has 4 pins: GND, VCC and 2 signal pins that can be user-defined. This variable specifies which pin of these 2 signal pins is used.
:var int portID: Depending on ``ports``'s value, an ID is given to each port. This variable is not important to us.
:var str descriptor: Represents the "informal" string representation of an instantiated object of this class.
:var EasyGoPiGo3 gpg: Object instance of the :py:class:`~easygopigo3.EasyGoPiGo3` class.
.. note::
The classes which derive from this class are the following:
* :py:class:`~easysensors.DigitalSensor`
* :py:class:`~easysensors.AnalogSensor`
* :py:class:`~easysensors.Servo`
* :py:class:`~easysensors.DHTSensor`
And the classes which are found at 2nd level of inheritance from this class are:
* :py:class:`~easysensors.LightSensor`
* :py:class:`~easysensors.SoundSensor`
* :py:class:`~easysensors.LoudnessSensor`
* :py:class:`~easysensors.UltraSonicSensor`
* :py:class:`~easysensors.Buzzer`
* :py:class:`~easysensors.Led`
* :py:class:`~easysensors.ButtonSensor`
.. warning::
1. This class should only be used by the developers of the `GoPiGo3`_ platform.
2. The name of this class isn't representative of the devices we connect to the `GoPiGo3`_ robot - we don't only use this class for sensors, but for any kind of device that we can connect to the `GoPiGo3`_ robot.
"""
PORTS = {}
def __init__(self, port, pinmode, gpg, use_mutex=False):
"""
Constructor for creating a connection to one of the available grove ports on the `GoPIGo3`_.
:param str port: Specifies the port with which we want to communicate / interact with. The string literals we can use for identifying a port are found in the following graphical drawing : :ref:`hardware-ports-section`.
:param str pinmode: The mode of operation of the pin we're selecting.
:param easygopigo3.EasyGoPiGo3 gpg: An instantiated object of the :py:class:`~easygopigo3.EasyGoPiGo3` class. We need this :py:class:`~easygopigo3.EasyGoPiGo3` class for setting up the `GoPiGo3`_ robot's pins.
:raises TypeError: If the ``gpg`` parameter is not a :py:class:`~easygopigo3.EasyGoPiGo3` object.
The ``port`` parameter can take the following string values:
* ``"AD1"`` - for digital and analog ``pinmode``'s.
* ``"AD2"`` - for digital and analog ``pinmode``'s.
* ``"SERVO1"`` - for ``"OUTPUT"`` ``pinmode``.
* ``"SERVO2"`` - for ``"OUTPUT"`` ``pinmode``.
* ``"I2C"`` - the ``pinmode`` is irrelevant here.
* ``"SERIAL"`` - the ``pinmode`` is irrelevant here.
These ports' locations can be seen in the following graphical representation - :ref:`hardware-ports-section`.
The ``pinmode`` parameter can take the following string values:
* ``"INPUT"`` - for general purpose inputs. The `GoPiGo3`_ has 12-bit ADCs.
* ``"DIGITAL_INPUT"`` - for digital inputs. The port can detect either **0** or **1**.
* ``"OUTPUT"`` - for general purpose outputs.
* ``"DIGITAL_OUTPUT"`` - for digital outputs. The port can only be set to **0** or **1**.
* ``"US"`` - that's for the :py:class:`~easysensors.UltraSonicSensor` which can be bought from our `shop`_. Can only be used with ports ``"AD1"`` and ``"AD2"``.
* ``"IR"`` - that's for the `infrared receiver`_. Can only be used with ports ``"AD1"`` and ``"AD2"``.
.. warning::
At the moment, there's no class for interfacing with the `infrared receiver`_.
"""
debug("Sensor init")
if not isinstance(gpg, gopigo3.GoPiGo3):
raise TypeError("Use a GoPiGo3 object for the gpg parameter.")
self.gpg = gpg
debug(pinmode)
self.set_port(port)
self.set_pin_mode(pinmode)
self.use_mutex = use_mutex
self.reconfig_bus()
def reconfig_bus(self):
"""
Sets the bus properly. Sometimes this needs to be done even after instantiation when two processes are
trying to connect to the GoPiGo and one re-initialises the ports.
"""
pinmode = self.get_pin_mode()
try:
# I2C sensors don't need a valid gpg
if pinmode == "INPUT":
self.gpg.set_grove_type(self.portID,
self.gpg.GROVE_TYPE.CUSTOM)
self.gpg.set_grove_mode(self.portID,
self.gpg.GROVE_INPUT_ANALOG)
if pinmode == "DIGITAL_INPUT":
self.gpg.set_grove_type(self.portID,
self.gpg.GROVE_TYPE.CUSTOM)
self.gpg.set_grove_mode(self.portID,
self.gpg.GROVE_INPUT_DIGITAL)
if pinmode == "OUTPUT":
self.gpg.set_grove_type(self.portID,
self.gpg.GROVE_TYPE.CUSTOM)
self.gpg.set_grove_mode(self.portID,
self.gpg.GROVE_OUTPUT_PWM)
if pinmode == "DIGITAL_OUTPUT":
self.gpg.set_grove_type(self.portID,
self.gpg.GROVE_TYPE.CUSTOM)
self.gpg.set_grove_mode(self.portID,
self.gpg.GROVE_OUTPUT_DIGITAL)
if pinmode == "US":
self.gpg.set_grove_type(self.portID,
self.gpg.GROVE_TYPE.US)
if pinmode == "IR":
self.gpg.set_grove_type(self.portID,
self.gpg.GROVE_TYPE.IR_DI_REMOTE)
except:
pass
def __str__(self):
"""
Prints out a short summary of the class-instantiated object's attributes.
:returns: A string with a short summary of the object's attributes.
:rtype: str
The returned string is made of the following components:
* the :py:attr:`~easysensors.Sensor.descriptor`'s description
* the :py:attr:`~easysensors.Sensor.port` name
* the :py:attr:`~easysensors.Sensor.pin` identifier
* the :py:attr:`~easysensors.Sensor.portID` - see :py:meth:`~easysensors.Sensor.set_port` method.
Sample of returned string as shown in a terminal:
.. code-block:: console
$ ultrasonic sensor on port AD1
$ pinmode OUTPUT
$ portID 3
"""
return ("{} on port {} \npinmode {}\nportID {}".format(self.descriptor,
self.get_port(), self.get_pin_mode(), self.portID))
def set_pin(self, pin):
"""
Selects one of the 2 available pins of the grove connector.
:param int pin: **1** for the exterior pin of the grove connector (aka SIG) or anything else for the interior one.
"""
if self.port == "AD1":
if pin == 1:
self.pin = self.gpg.GROVE_1_1
else:
self.pin = self.gpg.GROVE_1_2
elif self.port == "AD2":
if pin == 1:
self.pin = self.gpg.GROVE_2_1
else:
self.pin = self.gpg.GROVE_2_2
debug("setting pin to {}".format(self.pin))
def get_pin(self):
"""
Tells us which pin of the grove connector is used.
:returns: For exterior pins (aka SIG) it returns :py:data:`gopigo3.GROVE_2_1` or :py:data:`gopigo3.GROVE_2_2` and for interior pins (aka NC) it returns :py:data:`gopigo3.GROVE_1_2` or :py:data:`gopigo3.GROVE_1_2`.
:rtype: int
"""
return self.pin
def set_port(self, port):
"""
Sets the port that's going to be used by our new device. Again, we can't communicate with our
device, because the class doesn't have any methods for interfacing with it, so we need to create
a derived class that does this.
:param str port: The port we're connecting the device to. Take a look at the :ref:`hardware-ports-section`' locations.
Apart from this graphical representation of the ports' locations (:ref:`hardware-ports-section` locations),
take a look at the list of ports in :py:meth:`~easysensors.Sensor.__init__`'s description.
"""
debug(port)
self.port = port
debug(self.port)
debug("self.gpg is {}".format(self.gpg))
if port == "AD1":
self.portID = self.gpg.GROVE_1
elif port == "AD2":
self.portID = self.gpg.GROVE_2
elif port == "SERIAL":
self.portID = -1
elif port == "I2C":
self.portID = -2
elif port == "SERVO1":
self.portID = self.gpg.SERVO_1
elif port == "SERVO2":
self.portID = self.gpg.SERVO_2
else:
self.portID = -5
debug(self.portID)
def get_port(self):
"""
Gets the current port our device is connected to.
:returns: The current set port.
:rtype: str
Apart from this graphical representation of the ports' locations (:ref:`hardware-ports-section` locations),
take a look at the list of ports in :py:meth:`~easysensors.Sensor.__init__`'s description.
"""
return (self.port)
def get_port_ID(self):
"""
Gets the ID of the port we're set to.
:returns: The ID of the port we're set to.
:rtype: int
See more about port IDs in :py:class:`~easysensors.Sensor`'s description.
"""
return (self.portID)
def set_pin_mode(self, pinmode):
"""
Sets the pin mode of the port we're set to.
:param str pinmode: The pin mode of the port.
See more about pin modes in :py:meth:`~easysensors.Sensor.__init__`'s description.
"""
self.pinmode = pinmode
def get_pin_mode(self):
"""
Gets the pin mode of the port we're set to.
:returns: The pin mode of the port.
:rtype: str
See more about pin modes in :py:meth:`~easysensors.Sensor.__init__`'s description.
"""
return (self.pinmode)
# def is_analog(self):
# return (self.pin == ANALOG)
# def is_digital(self):
# return (self.pin == DIGITAL)
def set_descriptor(self, descriptor):
"""
Sets the object's description.
:param str descriptor: The object's description.
See more about class descriptors in :py:class:`~easysensors.Sensor`'s description.
"""
self.descriptor = descriptor
##########################
class DigitalSensor(Sensor):
def __init__(self, port, pinmode, gpg, use_mutex = False):
debug("DigitalSensor init")
try:
Sensor.__init__(self, port, pinmode, gpg, use_mutex)
except:
raise("Digital Sensor Init")
def read(self):
'''
Return values:
0 or 1 are valid values
-1 may occur when there's a reading error
On a reading error, a second attempt will be made before
returning a -1 value
'''
try:
self.value = self.gpg.get_grove_state(self.get_pin())
except gopigo3.ValueError:
try:
self.value = self.gpg.get_grove_state(self.get_pin())
except Exception:
return -1
return self.value
def write(self, power):
self.value = power
# not ported to GPG3 yet
return -1
# return gopigo.digitalWrite(self.get_port_ID(), power)
##########################
class AnalogSensor(Sensor):
"""
Class for analog devices with input/output capabilities on the `GoPiGo3`_ robot.
This class is derived from :py:class:`~easysensors.Sensor` class, so this means this class inherits all attributes and methods.
For creating an :py:class:`~easysensors.AnalogSensor` object an :py:class:`~easygopigo3.EasyGoPiGo3` object is needed like in the following example.
.. code-block:: python
# initialize an EasyGoPiGo3 object first
gpg3_obj = EasyGoPiGo3()
# let's have an analog input sensor on "AD1" port
port = "AD1"
pinmode = "INPUT"
# instantiate an AnalogSensor object
# pay attention that we need the gpg3_obj
analogsensor_obj = AnalogSensor(port, pinmode, gpg3_obj)
# for example
# read the sensor's value as we have an analog sensor connected to "AD1" port
analogsensor_obj.read()
.. warning::
The name of this class isn't representative of the type of devices we connect to the `GoPiGo3`_ robot.
With this class, both analog sensors and actuators (output devices such as LEDs which may require controlled output voltages) can be connected.
"""
def __init__(self, port, pinmode, gpg, use_mutex = False):
"""
Binds an analog device to the specified ``port`` with the appropriate ``pinmode`` mode.
:param str port: The port to which the sensor/actuator is connected.
:param str pinmode: The pin mode of the device that's connected to the `GoPiGo3`_.
:param easygopigo3.EasyGoPiGo3 gpg: Required object for instantiating an :py:class:`~easysensors.AnalogSensor` object.
:param bool use_mutex = False: When using multiple threads/processes that access the same resource/device, mutexes should be enabled.
:raises TypeError: If the ``gpg`` parameter is not a :py:class:`~easygopigo3.EasyGoPiGo3` object.
The available ``port``'s for use are the following:
* ``"AD1"`` - general purpose input/output port.
* ``"AD2"`` - general purpose input/output port.
The ports' locations can be seen in the following graphical representation: :ref:`hardware-ports-section`.
.. important::
Since the grove connector allows 2 signals to pass through 2 pins (not concurently), we can select which pin to go with by using the :py:meth:`~easysensors.Sensor.set_pin` method.
By default, we're using pin **1**, which corresponds to the exterior pin of the grove connector (aka SIG) and the wire is yellow.
"""
debug("AnalogSensor init")
self.value = 0
self.freq = 24000
self._max_value = 4096
try:
Sensor.__init__(self, port, pinmode, gpg, use_mutex)
except:
raise("AnalogSensor Init")
# select the outwards pin of the grove connector
self.set_pin(1)
# this delay is at least needed by the Light sensor
time.sleep(0.01)
def read(self):
"""
Reads analog value of the sensor that's connected to our `GoPiGo3`_ robot.
:returns: 12-bit number representing the voltage we get from the sensor. Range goes from 0V-5V.
:rtype: int
:raises gopigo3.ValueError: If an invalid value was read.
:raises Exception: If any other errors happens.
"""
try:
self.value = self.gpg.get_grove_analog(self.get_pin())
except gopigo3.ValueError as e:
try:
self.value = self.gpg.get_grove_analog(self.get_pin())
except Exception as e:
print("Value Error: {}".format(e))
return 0
except Exception as e:
print("Analog Read fail-all: {}".format(e))
print("Analog Read: {}".format(self.value))
return self.value
def percent_read(self):
"""
Reads analog value of the sensor that's connected to our `GoPiGo3`_ robot as a percentage.
:returns: Percentage mapped to 0V-5V range.
:rtype: int
"""
reading_percent = round(self.read() * 100 // self._max_value)
# Some sensors - like the loudness_sensor -
# can actually return higher than 100% so let's clip it
# and keep classrooms within an acceptable noise level
if reading_percent > 100:
reading_percent = 100
return reading_percent
def write(self, power):
"""
Generates a PWM signal on the selected port.
Good for simulating an DAC convertor - for instance an LED is a good candidate.
:param int power: Number from **0** to **100** that represents the duty cycle as a percentage of the frequency's period.
.. tip::
If the ``power`` parameter is out of the given range, the most close and valid value will be selected.
"""
self.value = power
return_value = self.gpg.set_grove_pwm_duty(self.get_pin(),
power)
return return_value
def write_freq(self, freq):
"""
Sets the frequency of the PWM signal.
The frequency range goes from 3Hz up to 48000Hz. Default value is set to 24000Hz (24kHz).
:param int freq: Frequency of the PWM signal.
.. seealso::
Read more about this in :py:meth:`gopigo3.GoPiGo3.set_grove_pwm_frequency`'s description.
"""
self.freq = freq
# debug("write_freq: {}".format(self.freq))
return_value = self.gpg.set_grove_pwm_frequency(
self.get_port_ID(),
self.freq)
debug ("Analog Write on {} at {}".format(self.get_port_ID(),
self.freq))
return return_value
##########################
class LightSensor(AnalogSensor):
"""
Class for the `Grove Light Sensor`_.
This class derives from :py:class:`~easysensors.AnalogSensor` class, so all of its attributes and methods are inherited.
For creating a :py:class:`~easysensors.LightSensor` object we need to call :py:meth:`~easygopigo3.EasyGoPiGo3.init_light_sensor` method like in the following examples.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# and now instantiate a LightSensor object through the gpg3_obj object
light_sensor = gpg3_obj.init_light_sensor()
# do the usual stuff, like read the data of the sensor
value = light_sensor.read()
value_percentage = light_sensor.percent_read()
# take a look at AnalogSensor class for more methods and attributes
Or if we need to specify the port we want to use, we might do it like in the following example.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# variable for holding the port to which we have the Light Sensor connected to
port = "AD2"
light_sensor = gpg3_obj.init_light_sensor(port)
# read the sensor the same way as in the previous example
.. seealso::
For more sensors, please see our Dexter Industries `shop`_.
"""
def __init__(self, port="AD1", gpg=None, use_mutex = False):
"""
Constructor for initializing a :py:class:`~easysensors.LightSensor` object for the `Grove Light Sensor`_.
:param str port = "AD1": Port to which we have the `Grove Light Sensor`_ connected to.
:param easygopigo3.EasyGoPiGo3 gpg = None: :py:class:`~easygopigo3.EasyGoPiGo3` object used for instantiating a :py:class:`~easysensors.LightSensor` object.
:param bool use_mutex = False: When using multiple threads/processes that access the same resource/device, mutexes should be enabled.
:raises TypeError: If the ``gpg`` parameter is not a :py:class:`~easygopigo3.EasyGoPiGo3` object.
The ``port`` parameter can take the following values:
* ``"AD1"`` - general purpose input/output port.
* ``"AD2"`` - general purpose input/output port.
The ports' locations can be seen in the following graphical representation: :ref:`hardware-ports-section`.
"""
debug("LightSensor init")
self.set_descriptor("Light sensor")
try:
AnalogSensor.__init__(self, port, "INPUT", gpg, use_mutex)
except:
raise
self.set_pin(1)
##########################
class SoundSensor(AnalogSensor):
"""
Class for the `Grove Sound Sensor`_.
This class derives from :py:class:`~easysensors.AnalogSensor` class, so all of its attributes and methods are inherited.
For creating a :py:class:`~easysensors.SoundSensor` object we need to call :py:meth:`~easygopigo3.EasyGoPiGo3.init_sound_sensor` method like in the following examples.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# and now instantiate a SoundSensor object through the gpg3_obj object
sound_sensor = gpg3_obj.init_sound_sensor()
# do the usual stuff, like read the data of the sensor
value = sound_sensor.read()
value_percentage = sound_sensor.percent_read()
# take a look at AnalogSensor class for more methods and attributes
| Or if we need to specify the port we want to use, we might do it like in the following example.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# variable for holding the port to which we have the sound sensor connected to
port = "AD1"
sound_sensor = gpg3_obj.init_sound_sensor(port)
# read the sensor the same way as in the previous example
.. seealso::
For more sensors, please see our Dexter Industries `shop`_.
"""
def __init__(self, port="AD1", gpg=None, use_mutex=False):
"""
Constructor for initializing a :py:class:`~easysensors.SoundSensor` object for the `Grove Sound Sensor`_.
:param str port = "AD1": Port to which we have the `Grove Sound Sensor`_ connected to.
:param easygopigo3.EasyGoPiGo3 gpg = None: :py:class:`~easygopigo3.EasyGoPiGo3` object used for instantiating a :py:class:`~easysensors.SoundSensor` object.
:param bool use_mutex = False: When using multiple threads/processes that access the same resource/device, mutexes should be enabled.
:raises TypeError: If the ``gpg`` parameter is not a :py:class:`~easygopigo3.EasyGoPiGo3` object.
The ``port`` parameter can take the following values:
* ``"AD1"`` - general purpose input/output port.
* ``"AD2"`` - general purpose input/output port.
The ports' locations can be seen in the following graphical representation: :ref:`hardware-ports-section`.
"""
debug("Sound Sensor on port " + port)
self.set_descriptor("Sound sensor")
try:
AnalogSensor.__init__(self, port, "INPUT", gpg, use_mutex)
except:
raise
self.set_pin(1)
##########################
class LoudnessSensor(AnalogSensor):
"""
Class for the `Grove Loudness Sensor`_.
This class derives from :py:class:`~easysensors.AnalogSensor` class, so all of their attributes and methods are inherited.
For creating a :py:class:`~easysensors.LoudnessSensor` object we need to call :py:meth:`~easygopigo3.EasyGoPiGo3.init_loudness_sensor` method like in the following examples.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# and now instantiate a LoudnessSensor object through the gpg3_obj object
loudness_sensor = gpg3_obj.init_loudness_sensor()
# do the usual stuff, like read the data of the sensor
value = loudness_sensor.read()
value_percentage = loudness_sensor.percent_read()
# take a look at AnalogSensor class and Sensor class for more methods and attributes
Or if we need to specify the port we want to use, we might do it like in the following example.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# variable for holding the port to which we have the sound sensor connected to
port = "AD1"
loudness_sensor = gpg3_obj.init_loudness_sensor(port)
# read the sensor the same way as in the previous example
.. seealso::
For more sensors, please see our Dexter Industries `shop`_.
"""
def __init__(self, port="AD1", gpg=None, use_mutex=False):
"""
Constructor for initializing a :py:class:`~easysensors.LoudnessSensor` object for the `Grove Loudness Sensor`_.
:param str port = "AD1": Port to which we have the `Grove Loudness Sensor`_ connected to.
:param easygopigo3.EasyGoPiGo3 gpg = None: :py:class:`~easygopigo3.EasyGoPiGo3` object used for instantiating a :py:class:`~easysensors.LoudnessSensor` object.
:param bool use_mutex = False: When using multiple threads/processes that access the same resource/device, mutexes should be enabled.
:raises TypeError: If the ``gpg`` parameter is not a :py:class:`~easygopigo3.EasyGoPiGo3` object.
The ``port`` parameter can take the following values:
* ``"AD1"`` - general purpose input/output port.
* ``"AD2"`` - general purpose input/output port.
The ports' locations can be seen in the following graphical representation: :ref:`hardware-ports-section`.
"""
debug("Loudness Sensor on port " + port)
self.set_descriptor("Loudness sensor")
try:
AnalogSensor.__init__(self, port, "INPUT", gpg, use_mutex)
except:
raise
# time.sleep(0.2)
self.set_pin(1)
self._max_value = 1024 # based on empirical tests
##########################
class UltraSonicSensor(AnalogSensor):
"""
Class for the `Grove Ultrasonic Sensor`_.
This class derives from :py:class:`~easysensors.AnalogSensor` class, so all of its attributes and methods are inherited.
For creating a :py:class:`~easysensors.UltraSonicSensor` object we need to call :py:meth:`~easygopigo3.EasyGoPiGo3.init_ultrasonic_sensor` method like in the following examples.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# and now instantiate a UltraSonicSensor object through the gpg3_obj object
ultrasonic_sensor = gpg3_obj.init_ultrasonic_sensor()
# do the usual stuff, like read the distance the sensor is measuring
distance_cm = ultrasonic_sensor.read()
distance_inches = ultrasonic_sensor.read_inches()
# take a look at AnalogSensor class for more methods and attributes
Or if we need to specify the port we want to use, we might do it like in the following example.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# variable for holding the port to which we have the ultrasonic sensor connected to
port = "AD1"
ultrasonic_sensor = gpg3_obj.init_ultrasonic_sensor(port)
# read the sensor's measured distance as in the previous example
.. seealso::
For more sensors, please see our Dexter Industries `shop`_.
"""
def __init__(self, port="AD1", gpg=None, use_mutex = False):
"""
Constructor for initializing a :py:class:`~easysensors.UltraSonicSensor` object for the `Grove Ultrasonic Sensor`_.
:param str port = "AD1": Port to which we have the `Grove Ultrasonic Sensor`_ connected to.
:param easygopigo3.EasyGoPiGo3 gpg = None: :py:class:`~easygopigo3.EasyGoPiGo3` object used for instantiating a :py:class:`~easysensors.UltraSonicSensor` object.
:param bool use_mutex = False: When using multiple threads/processes that access the same resource/device, mutexes should be enabled.
:raises TypeError: If the ``gpg`` parameter is not a :py:class:`~easygopigo3.EasyGoPiGo3` object.
The ``port`` parameter can take the following values:
* ``"AD1"`` - general purpose input/output port.
* ``"AD2"`` - general purpose input/output port.
The ports' locations can be seen in the following graphical representation: :ref:`hardware-ports-section`.
"""
try:
debug("Ultrasonic Sensor on port " + port)
AnalogSensor.__init__(self, port, "US", gpg, use_mutex)
self.set_descriptor("Ultrasonic sensor")
self.safe_distance = 500
self.set_pin(1)
except:
raise
def is_too_close(self):
"""
Checks whether the `Grove Ultrasonic Sensor`_ measures a distance that's too close to a target than
what we consider a *safe distance*.
:returns: Whether the `Grove Ultrasonic Sensor`_ is too close from a target.
:rtype: bool
:raises gopigo3.SensorError: If a sensor is not yet configured when trying to read it.
A *safe distance* can be set with the :py:meth:`~easysensors.UltraSonicSensor.set_safe_distance` method.
.. note::
The default *safe distance* is set at 50 cm.
"""
try:
val = self.gpg.get_grove_value(self.get_port_ID())
except gopigo3.SensorError as e:
print("Invalid Reading")
print(e)
return False
if val < self.get_safe_distance():
return True
return False
def set_safe_distance(self, dist):
"""
Sets a *safe distance* for the `Grove Ultrasonic Sensor`_.
:param int dist: Minimum distance from a target that we can call a *safe distance*.
To check whether the robot is too close from a target, please check the :py:meth:`~easysensors.UltraSonicSensor.is_too_close` method.
.. note::
The default *safe distance* is set at 50 cm.
"""
self.safe_distance = int(dist)
def get_safe_distance(self):
"""
Gets what we call the *safe distance* for the `Grove Ultrasonic Sensor`_.
:returns: The minimum distance from a target that can be considered a *safe distance*.
:rtype: int
.. note::
The default *safe distance* is set at 50 cm.
"""
return self.safe_distance
def read_mm(self):
"""
Measures the distance from a target in millimeters.
:returns: The distance from a target in millimeters.
:rtype: int
:raises gopigo3.ValueError: If trying to read an invalid value.
:raises Exception: If any other error occurs.
.. important::
* This method can read distances between **15-4300** millimeters.
* This method will read the data for 3 times and it'll discard anything that's smaller than 15 millimeters and bigger than 4300 millimeters.
* If data is discarded 5 times (due to a communication error with the sensor), then the method returns **5010**.
"""
return_reading = 0
readings = []
skip = 0
value=0
while len(readings) < 3 and skip < 5:
try:
value = self.gpg.get_grove_value(self.get_port_ID())
print ("raw {}".format(value))
except gopigo3.ValueError as e:
# print("Value Error")
# print(e)
value = 5010 # assume open road ahead
time.sleep(0.05)
except Exception as e:
print(e)
skip += 1
time.sleep(0.05)
continue
if value <= 4300 and value >= 15:
readings.append(value)
# debug (readings)
else:
skip += 1
if skip >= 5:
# if value = 0 it means Ultrasonic Sensor wasn't found
if value == 0:
return(0)
# no special meaning to the number 5010
return(5010)
for reading in readings:
return_reading += reading
return_reading = int(return_reading / len(readings))
return (return_reading)
def read(self):
"""
Measures the distance from a target in centimeters.
:returns: The distance from a target in centimeters.
:rtype: int
.. important::
* This method can read distances between **2-430** centimeters.
* If data is discarded 5 times (due to a communication error with the sensor), then the method returns **501**.
"""
# returns value in cm
value = self.read_mm()
if value >= 15 and value <= 5010:
return int(round(value / 10.0))
return value
def read_inches(self):
"""
Measures the distance from a target in inches.
:returns: The distance from a target in inches.
:rtype: float (one decimal)
.. important::
* This method can read distances of up to **169** inches.
* If data is discarded 5 times (due to a communication error with the sensor), then the method returns **501**.
"""
value = self.read() # cm reading
if value == 501:
return 501
return (round(value / 2.54, 1))
##########################
class Buzzer(AnalogSensor):
"""
Class for the `Grove Buzzer`_.
This class derives from :py:class:`~easysensors.AnalogSensor` class, so all of its attributes and methods are inherited.
For creating a :py:class:`~easysensors.Buzzer` object we need to call :py:meth:`~easygopigo3.EasyGoPiGo3.init_buzzer` method like in the following examples.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# and now instantiate a UltraSonicSensor object through the gpg3_obj object
buzzer = gpg3_obj.init_buzzer()
# turn on and off the buzzer
buzzer.sound_on()
sleep(1)
buzzer.sound_off()
# take a look at AnalogSensor class for more methods and attributes
If we need to specify the port we want to use, we might do it like in the following example.
.. code-block:: python
# create an EasyGoPiGo3 object
gpg3_obj = EasyGoPiGo3()
# variable for holding the port to which we have the ultrasonic sensor connected to
port = "AD1"
buzzer = gpg3_obj.init_buzzer(port)
.. seealso::
For more sensors, please see our Dexter Industries `shop`_.
"""
#:Dictionary of frequencies for each musical note.
#:For instance, ``scale["A3"]`` instruction is equal to 220 Hz (that's the A3 musical note's frequency).
#:This dictionary is useful when we want to make the buzzer ring at certain frequencies (aka musical notes).
scale = {"A3": 220,
"A3#": 233,
"B3": 247,
"C4": 261,
"C4#": 277,
"D4": 293,
"D4#": 311,
"E4": 329,
"F4": 349,
"F4#": 370,
"G4": 392,
"G4#": 415,