-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpicozero.py
1969 lines (1586 loc) · 66.3 KB
/
picozero.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 machine import Pin, PWM, Timer, ADC
from micropython import schedule
from time import ticks_ms, ticks_us, sleep
###############################################################################
# EXCEPTIONS
###############################################################################
class PWMChannelAlreadyInUse(Exception):
pass
class EventFailedScheduleQueueFull(Exception):
pass
###############################################################################
# SUPPORTING CLASSES
###############################################################################
def clamp(n, low, high): return max(low, min(n, high))
def pinout(output=True):
"""
Returns a textual representation of the Raspberry Pi pico pins and functions.
:param bool output:
If :data:`True` (the default) the pinout will be "printed".
"""
pins = """ ---usb---
GP0 1 |o o| -1 VBUS
GP1 2 |o o| -2 VSYS
GND 3 |o o| -3 GND
GP2 4 |o o| -4 3V3_EN
GP3 5 |o o| -5 3V3(OUT)
GP4 6 |o o| -6 ADC_VREF
GP5 7 |o o| -7 GP28 ADC2
GND 8 |o o| -8 GND AGND
GP6 9 |o o| -9 GP27 ADC1
GP7 10 |o o| -10 GP26 ADC0
GP8 11 |o o| -11 RUN
GP9 12 |o o| -12 GP22
GND 13 |o o| -13 GND
GP10 14 |o o| -14 GP21
GP11 15 |o o| -15 GP20
GP12 16 |o o| -16 GP19
GP13 17 |o o| -17 GP18
GND 18 |o o| -18 GND
GP14 19 |o o| -19 GP17
GP15 20 |o o| -20 GP16
---------"""
if output:
print(pins)
return pins
class PinMixin:
"""
Mixin used by devices that have a single pin number.
"""
@property
def pin(self):
"""
Returns the pin number used by the device.
"""
return self._pin_num
def __str__(self):
return "{} (pin {})".format(self.__class__.__name__, self._pin_num)
class PinsMixin:
"""
Mixin used by devices that use multiple pins.
"""
@property
def pins(self):
"""
Returns a tuple of pins used by the device.
"""
return self._pin_nums
def __str__(self):
return "{} (pins - {})".format(self.__class__.__name__, self._pin_nums)
class ValueChange:
"""
Internal class to control the value of an output device.
:param OutputDevice output_device:
The OutputDevice object you wish to change the value of.
:param generator:
A generator function that yields a 2d list of
((value, seconds), *).
The output_device's value will be set for the number of
seconds.
:param int n:
The number of times to repeat the sequence. If None, the
sequence will repeat forever.
:param bool wait:
If True the ValueChange object will block (wait) until
the sequence has completed.
"""
def __init__(self, output_device, generator, n, wait):
self._output_device = output_device
self._generator = generator
self._n = n
self._gen = self._generator()
self._timer = Timer()
self._running = True
self._wait = wait
self._set_value()
def _set_value(self, timer_obj=None):
if self._wait:
# wait for the exection to end
next_seq = self._get_value()
while next_seq is not None:
value, seconds = next_seq
self._output_device._write(value)
sleep(seconds)
next_seq = self._get_value()
else:
# run the timer
next_seq = self._get_value()
if next_seq is not None:
value, seconds = next_seq
self._output_device._write(value)
self._timer.init(period=int(seconds * 1000), mode=Timer.ONE_SHOT, callback=self._set_value)
if next_seq is None:
# the sequence has finished, turn the device off
self._output_device.off()
self._running = False
def _get_value(self):
try:
return next(self._gen)
except StopIteration:
self._n = self._n - 1 if self._n is not None else None
if self._n == 0:
# it's the end, return None
return None
else:
# recreate the generator and start again
self._gen = self._generator()
return next(self._gen)
def stop(self):
"""
Stops the ValueChange object running.
"""
self._running = False
self._timer.deinit()
###############################################################################
# OUTPUT DEVICES
###############################################################################
class OutputDevice:
"""
Base class for output devices.
"""
def __init__(self, active_high=True, initial_value=False):
self.active_high = active_high
if initial_value is not None:
self._write(initial_value)
self._value_changer = None
@property
def active_high(self):
"""
Sets or returns the active_high property. If :data:`True`, the
:meth:`on` method will set the Pin to HIGH. If :data:`False`,
the :meth:`on` method will set the Pin to LOW (the :meth:`off` method
always does the opposite).
"""
return self._active_state
@active_high.setter
def active_high(self, value):
self._active_state = True if value else False
self._inactive_state = False if value else True
@property
def value(self):
"""
Sets or returns a value representing the state of the device: 1 is on, 0 is off.
"""
return self._read()
@value.setter
def value(self, value):
self._stop_change()
self._write(value)
def on(self, value=1, t=None, wait=False):
"""
Turns the device on.
:param float value:
The value to set when turning on. Defaults to 1.
:param float t:
The time in seconds that the device should be on. If None is
specified, the device will stay on. The default is None.
:param bool wait:
If True, the method will block until the time `t` has expired.
If False, the method will return and the device will turn on in
the background. Defaults to False. Only effective if `t` is not
None.
"""
if t is None:
self.value = value
else:
self._start_change(lambda : iter([(value, t), ]), 1, wait)
def off(self):
"""
Turns the device off.
"""
self.value = 0
@property
def is_active(self):
"""
Returns :data:`True` if the device is on.
"""
return bool(self.value)
def toggle(self):
"""
If the device is off, turn it on. If it is on, turn it off.
"""
if self.is_active:
self.off()
else:
self.on()
def blink(self, on_time=1, off_time=None, n=None, wait=False):
"""
Makes the device turn on and off repeatedly.
:param float on_time:
The length of time in seconds that the device will be on. Defaults to 1.
:param float off_time:
The length of time in seconds that the device will be off. If `None`,
it will be the same as ``on_time``. Defaults to `None`.
:param int n:
The number of times to repeat the blink operation. If None is
specified, the device will continue blinking forever. The default
is None.
:param bool wait:
If True, the method will block until the device stops turning on and off.
If False, the method will return and the device will turn on and off in
the background. Defaults to False.
"""
off_time = on_time if off_time is None else off_time
self.off()
# is there anything to change?
if on_time > 0 or off_time > 0:
self._start_change(lambda : iter([(1,on_time), (0,off_time)]), n, wait)
def _start_change(self, generator, n, wait):
self._value_changer = ValueChange(self, generator, n, wait)
def _stop_change(self):
if self._value_changer is not None:
self._value_changer.stop()
self._value_changer = None
def close(self):
"""
Turns the device off.
"""
self.value = 0
class DigitalOutputDevice(OutputDevice, PinMixin):
"""
Represents a device driven by a digital pin.
:param int pin:
The pin that the device is connected to.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the LED will be off initially. If
:data:`True`, the LED will be switched on initially.
"""
def __init__(self, pin, active_high=True, initial_value=False):
self._pin_num = pin
self._pin = Pin(pin, Pin.OUT)
super().__init__(active_high, initial_value)
def _value_to_state(self, value):
return int(self._active_state if value else self._inactive_state)
def _state_to_value(self, state):
return int(bool(state) == self._active_state)
def _read(self):
return self._state_to_value(self._pin.value())
def _write(self, value):
self._pin.value(self._value_to_state(value))
def close(self):
"""
Closes the device and turns the device off. Once closed, the device
can no longer be used.
"""
super().close()
self._pin = None
class DigitalLED(DigitalOutputDevice):
"""
Represents a simple LED, which can be switched on and off.
:param int pin:
The pin that the device is connected to.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the LED will be off initially. If
:data:`True`, the LED will be switched on initially.
"""
pass
DigitalLED.is_lit = DigitalLED.is_active
class Buzzer(DigitalOutputDevice):
"""
Represents an active or passive buzzer, which can be turned on or off.
:param int pin:
The pin that the device is connected to.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the Buzzer will be off initially. If
:data:`True`, the Buzzer will be switched on initially.
"""
pass
Buzzer.beep = Buzzer.blink
class PWMOutputDevice(OutputDevice, PinMixin):
"""
Represents a device driven by a PWM pin.
:param int pin:
The pin that the device is connected to.
:param int freq:
The frequency of the PWM signal in hertz. Defaults to 100.
:param int duty_factor:
The duty factor of the PWM signal. This is a value between 0 and 65535.
Defaults to 65535.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the LED will be off initially. If
:data:`True`, the LED will be switched on initially.
"""
PIN_TO_PWM_CHANNEL = ["0A","0B","1A","1B","2A","2B","3A","3B","4A","4B","5A","5B","6A","6B","7A","7B","0A","0B","1A","1B","2A","2B","3A","3B","4A","4B","5A","5B","6A","6B"]
_channels_used = {}
def __init__(self, pin, freq=100, duty_factor=65535, active_high=True, initial_value=False):
self._check_pwm_channel(pin)
self._pin_num = pin
self._duty_factor = duty_factor
self._pwm = PWM(Pin(pin))
self._pwm.freq(freq)
super().__init__(active_high, initial_value)
def _check_pwm_channel(self, pin_num):
channel = PWMOutputDevice.PIN_TO_PWM_CHANNEL[pin_num]
if channel in PWMOutputDevice._channels_used.keys():
raise PWMChannelAlreadyInUse(
"PWM channel {} is already in use by {}. Use a different pin".format(
channel,
str(PWMOutputDevice._channels_used[channel])
)
)
else:
PWMOutputDevice._channels_used[channel] = self
def _state_to_value(self, state):
return (state if self.active_high else self._duty_factor - state) / self._duty_factor
def _value_to_state(self, value):
return int(self._duty_factor * (value if self.active_high else 1 - value))
def _read(self):
return self._state_to_value(self._pwm.duty_u16())
def _write(self, value):
self._pwm.duty_u16(self._value_to_state(value))
@property
def is_active(self):
"""
Returns :data:`True` if the device is on.
"""
return self.value != 0
@property
def freq(self):
"""
Returns the current frequency of the device.
"""
return self._pwm.freq()
@freq.setter
def freq(self, freq):
"""
Sets the frequency of the device.
"""
self._pwm.freq(freq)
def blink(self, on_time=1, off_time=None, n=None, wait=False, fade_in_time=0, fade_out_time=None, fps=25):
"""
Makes the device turn on and off repeatedly.
:param float on_time:
The length of time in seconds the device will be on. Defaults to 1.
:param float off_time:
The length of time in seconds the device will be off. If `None`,
it will be the same as ``on_time``. Defaults to `None`.
:param int n:
The number of times to repeat the blink operation. If `None`, the
device will continue blinking forever. The default is `None`.
:param bool wait:
If True, the method will block until the LED stops blinking. If False,
the method will return and the LED will blink in the background.
Defaults to False.
:param float fade_in_time:
The length of time in seconds to spend fading in. Defaults to 0.
:param float fade_out_time:
The length of time in seconds to spend fading out. If `None`,
it will be the same as ``fade_in_time``. Defaults to `None`.
:param int fps:
The frames per second that will be used to calculate the number of
steps between off/on states when fading. Defaults to 25.
"""
self.off()
off_time = on_time if off_time is None else off_time
fade_out_time = fade_in_time if fade_out_time is None else fade_out_time
def blink_generator():
if fade_in_time > 0:
for s in [
(i * (1 / fps) / fade_in_time, 1 / fps)
for i in range(int(fps * fade_in_time))
]:
yield s
if on_time > 0:
yield (1, on_time)
if fade_out_time > 0:
for s in [
(1 - (i * (1 / fps) / fade_out_time), 1 / fps)
for i in range(int(fps * fade_out_time))
]:
yield s
if off_time > 0:
yield (0, off_time)
# is there anything to change?
if on_time > 0 or off_time > 0 or fade_in_time > 0 or fade_out_time > 0:
self._start_change(blink_generator, n, wait)
def pulse(self, fade_in_time=1, fade_out_time=None, n=None, wait=False, fps=25):
"""
Makes the device pulse on and off repeatedly.
:param float fade_in_time:
The length of time in seconds that the device will take to turn on.
Defaults to 1.
:param float fade_out_time:
The length of time in seconds that the device will take to turn off.
Defaults to 1.
:param int fps:
The frames per second that will be used to calculate the number of
steps between off/on states. Defaults to 25.
:param int n:
The number of times to pulse the LED. If None, the LED will pulse
forever. Defaults to None.
:param bool wait:
If True, the method will block until the LED stops pulsing. If False,
the method will return and the LED will pulse in the background.
Defaults to False.
"""
self.blink(on_time=0, off_time=0, fade_in_time=fade_in_time, fade_out_time=fade_out_time, n=n, wait=wait, fps=fps)
def close(self):
"""
Closes the device and turns the device off. Once closed, the device
can no longer be used.
"""
super().close()
del PWMOutputDevice._channels_used[
PWMOutputDevice.PIN_TO_PWM_CHANNEL[self._pin_num]
]
self._pwm.deinit()
self._pwm = None
class PWMLED(PWMOutputDevice):
"""
Represents an LED driven by a PWM pin; the brightness of the LED can be changed.
:param int pin:
The pin that the device is connected to.
:param int freq:
The frequency of the PWM signal in hertz. Defaults to 100.
:param int duty_factor:
The duty factor of the PWM signal. This is a value between 0 and 65535.
Defaults to 65535.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the LED will be off initially. If
:data:`True`, the LED will be switched on initially.
"""
PWMLED.brightness = PWMLED.value
def LED(pin, pwm=True, active_high=True, initial_value=False):
"""
Returns an instance of :class:`DigitalLED` or :class:`PWMLED` depending on
the value of the `pwm` parameter.
::
from picozero import LED
my_pwm_led = LED(1)
my_digital_led = LED(2, pwm=False)
:param int pin:
The pin that the device is connected to.
:param int pin:
If `pwm` is :data:`True` (the default), a :class:`PWMLED` will be
returned. If `pwm` is :data:`False`, a :class:`DigitalLED` will be
returned. A :class:`PWMLED` can control the brightness of the LED but
uses 1 PWM channel.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the device will be off initially. If
:data:`True`, the device will be switched on initially.
"""
if pwm:
return PWMLED(
pin=pin,
active_high=active_high,
initial_value=initial_value)
else:
return DigitalLED(
pin=pin,
active_high=active_high,
initial_value=initial_value)
try:
pico_led = LED("LED", pwm=False)
except TypeError:
# older version of micropython before "LED" was supported
pico_led = LED(25, pwm=False)
class PWMBuzzer(PWMOutputDevice):
"""
Represents a passive buzzer driven by a PWM pin; the volume of the buzzer can be changed.
:param int pin:
The pin that the buzzer is connected to.
:param int freq:
The frequency of the PWM signal in hertz. Defaults to 440.
:param int duty_factor:
The duty factor of the PWM signal. This is a value between 0 and 65535.
Defaults to 1023.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
:param bool initial_value:
If :data:`False` (the default), the buzzer will be off initially. If
:data:`True`, the buzzer will be switched on initially.
"""
def __init__(self, pin, freq=440, duty_factor=1023, active_high=True, initial_value=False):
super().__init__(pin, freq, duty_factor, active_high, initial_value)
PWMBuzzer.volume = PWMBuzzer.value
PWMBuzzer.beep = PWMBuzzer.blink
class Speaker(OutputDevice, PinMixin):
"""
Represents a speaker driven by a PWM pin.
:param int pin:
The pin that the speaker is connected to.
:param int initial_freq:
The initial frequency of the PWM signal in hertz. Defaults to 440.
:param int initial_volume:
The initial volume of the PWM signal. This is a value between 0 and
1. Defaults to 0.
:param int duty_factor:
The duty factor of the PWM signal. This is a value between 0 and 65535.
Defaults to 1023.
:param bool active_high:
If :data:`True` (the default), the :meth:`on` method will set the Pin
to HIGH. If :data:`False`, the :meth:`on` method will set the Pin to
LOW (the :meth:`off` method always does the opposite).
"""
NOTES = {
'b0': 31, 'c1': 33, 'c#1': 35, 'd1': 37, 'd#1': 39, 'e1': 41, 'f1': 44, 'f#1': 46, 'g1': 49,'g#1': 52, 'a1': 55,
'a#1': 58, 'b1': 62, 'c2': 65, 'c#2': 69, 'd2': 73, 'd#2': 78,
'e2': 82, 'f2': 87, 'f#2': 93, 'g2': 98, 'g#2': 104, 'a2': 110, 'a#2': 117, 'b2': 123,
'c3': 131, 'c#3': 139, 'd3': 147, 'd#3': 156, 'e3': 165, 'f3': 175, 'f#3': 185, 'g3': 196, 'g#3': 208, 'a3': 220, 'a#3': 233, 'b3': 247,
'c4': 262, 'c#4': 277, 'd4': 294, 'd#4': 311, 'e4': 330, 'f4': 349, 'f#4': 370, 'g4': 392, 'g#4': 415, 'a4': 440, 'a#4': 466, 'b4': 494,
'c5': 523, 'c#5': 554, 'd5': 587, 'd#5': 622, 'e5': 659, 'f5': 698, 'f#5': 740, 'g5': 784, 'g#5': 831, 'a5': 880, 'a#5': 932, 'b5': 988,
'c6': 1047, 'c#6': 1109, 'd6': 1175, 'd#6': 1245, 'e6': 1319, 'f6': 1397, 'f#6': 1480, 'g6': 1568, 'g#6': 1661, 'a6': 1760, 'a#6': 1865, 'b6': 1976,
'c7': 2093, 'c#7': 2217, 'd7': 2349, 'd#7': 2489,
'e7': 2637, 'f7': 2794, 'f#7': 2960, 'g7': 3136, 'g#7': 3322, 'a7': 3520, 'a#7': 3729, 'b7': 3951,
'c8': 4186, 'c#8': 4435, 'd8': 4699, 'd#8': 4978
}
def __init__(self, pin, initial_freq=440, initial_volume=0, duty_factor=1023, active_high=True):
self._pin_num = pin
self._pwm_buzzer = PWMBuzzer(
pin,
freq=initial_freq,
duty_factor=duty_factor,
active_high=active_high,
initial_value=None,
)
super().__init__(active_high, None)
self.volume = initial_volume
def on(self, volume=1):
self.volume = volume
def off(self):
self.volume = 0
@property
def value(self):
"""
Sets or returns the value of the speaker. The value is a tuple of (freq, volume).
"""
return tuple(self.freq, self.volume)
@value.setter
def value(self, value):
self._stop_change()
self._write(value)
@property
def volume(self):
"""
Sets or returns the volume of the speaker: 1 for maximum volume, 0 for off.
"""
return self._volume
@volume.setter
def volume(self, value):
self._volume = value
self.value = (self.freq, self.volume)
@property
def freq(self):
"""
Sets or returns the current frequency of the speaker.
"""
return self._pwm_buzzer.freq
@freq.setter
def freq(self, freq):
self.value = (freq, self.volume)
def _write(self, value):
# set the frequency
if value[0] is not None:
self._pwm_buzzer.freq = value[0]
# write the volume value
if value[1] is not None:
self._pwm_buzzer.volume = value[1]
def _to_freq(self, freq):
if freq is not None and freq != '' and freq != 0:
if type(freq) is str:
return int(self.NOTES[freq])
elif freq <= 128 and freq > 0: # MIDI
midi_factor = 2**(1/12)
return int(440 * midi_factor ** (freq - 69))
else:
return freq
else:
return None
def beep(self, on_time=1, off_time=None, n=None, wait=False, fade_in_time=0, fade_out_time=None, fps=25):
"""
Makes the buzzer turn on and off repeatedly.
:param float on_time:
The length of time in seconds that the device will be on. Defaults to 1.
:param float off_time:
The length of time in seconds that the device will be off. If `None`,
it will be the same as ``on_time``. Defaults to `None`.
:param int n:
The number of times to repeat the beep operation. If `None`, the
device will continue beeping forever. The default is `None`.
:param bool wait:
If True, the method will block until the buzzer stops beeping. If False,
the method will return and the buzzer will beep in the background.
Defaults to False.
:param float fade_in_time:
The length of time in seconds to spend fading in. Defaults to 0.
:param float fade_out_time:
The length of time in seconds to spend fading out. If `None`,
it will be the same as ``fade_in_time``. Defaults to `None`.
:param int fps:
The frames per second that will be used to calculate the number of
steps between off/on states when fading. Defaults to 25.
"""
self._pwm_buzzer.blink(on_time, off_time, n, wait, fade_in_time, fade_out_time, fps)
def play(self, tune=440, duration=1, volume=1, n=1, wait=True):
"""
Plays a tune for a given duration.
:param int tune:
The tune to play can be specified as:
+ a single "note", represented as:
+ a frequency in Hz e.g. `440`
+ a midi note e.g. `60`
+ a note name as a string e.g. `"E4"`
+ a list of notes and duration e.g. `[440, 1]` or `["E4", 2]`
+ a list of two value tuples of (note, duration) e.g. `[(440,1), (60, 2), ("e4", 3)]`
Defaults to `440`.
:param int volume:
The volume of the tune; 1 is maximum volume, 0 is mute. Defaults to 1.
:param float duration:
The duration of each note in seconds. Defaults to 1.
:param int n:
The number of times to play the tune. If None, the tune will play
forever. Defaults to 1.
:param bool wait:
If True, the method will block until the tune has finished. If False,
the method will return and the tune will play in the background.
Defaults to True.
"""
self.off()
# tune isn't a list, so it must be a single frequency or note
if not isinstance(tune, (list, tuple)):
tune = [(tune, duration)]
# if the first element isn't a list, then it must be list of a single note and duration
elif not isinstance(tune[0], (list, tuple)):
tune = [tune]
def tune_generator():
for note in tune:
# note isn't a list or tuple, it must be a single frequency or note
if not isinstance(note, (list, tuple)):
# make it into a tuple
note = (note, duration)
# turn the notes into frequencies
freq = self._to_freq(note[0])
freq_duration = note[1]
freq_volume = volume if freq is not None else 0
# if this is a tune of greater than 1 note, add gaps between notes
if len(tune) == 1:
yield ((freq, freq_volume), freq_duration)
else:
yield ((freq, freq_volume), freq_duration * 0.9)
yield ((freq, 0), freq_duration * 0.1)
self._start_change(tune_generator, n, wait)
def close(self):
self._pwm_buzzer.close()
class RGBLED(OutputDevice, PinsMixin):
"""
Extends :class:`OutputDevice` and represents a full colour LED component (composed
of red, green, and blue LEDs).
Connect the common cathode (longest leg) to a ground pin; connect each of
the other legs (representing the red, green, and blue anodes) to any GP
pins. You should use three limiting resistors (one per anode).
The following code will make the LED yellow::
from picozero import RGBLED
rgb = RGBLED(1, 2, 3)
rgb.color = (1, 1, 0)
0–255 colours are also supported::
rgb.color = (255, 255, 0)
:type red: int
:param red:
The GP pin that controls the red component of the RGB LED.
:type green: int
:param green:
The GP pin that controls the green component of the RGB LED.
:type blue: int
:param blue:
The GP pin that controls the blue component of the RGB LED.
:param bool active_high:
Set to :data:`True` (the default) for common cathode RGB LEDs. If you
are using a common anode RGB LED, set this to :data:`False`.
:type initial_value: ~colorzero.Color or tuple
:param initial_value:
The initial color for the RGB LED. Defaults to black ``(0, 0, 0)``.
:param bool pwm:
If :data:`True` (the default), construct :class:`PWMLED` instances for
each component of the RGBLED. If :data:`False`, construct
:class:`DigitalLED` instances.
"""
def __init__(self, red=None, green=None, blue=None, active_high=True,
initial_value=(0, 0, 0), pwm=True):
self._pin_nums = (red, green, blue)
self._leds = ()
self._last = initial_value
LEDClass = PWMLED if pwm else DigitalLED
self._leds = tuple(
LEDClass(pin, active_high=active_high)
for pin in (red, green, blue))
super().__init__(active_high, initial_value)
def _write(self, value):
if type(value) is not tuple:
value = (value, ) * 3
for led, v in zip(self._leds, value):
led.value = v
@property
def value(self):
"""
Represents the colour of the LED as an RGB 3-tuple of ``(red, green,
blue)`` where each value is between 0 and 1 if *pwm* was :data:`True`
when the class was constructed (but only takes values of 0 or 1 otherwise).
For example, red would be ``(1, 0, 0)`` and yellow would be ``(1, 1,
0)``, whereas orange would be ``(1, 0.5, 0)``.
"""
return tuple(led.value for led in self._leds)
@value.setter
def value(self, value):
self._stop_change()
self._write(value)
@property
def is_active(self):
"""
Returns :data:`True` if the LED is currently active (not black) and
:data:`False` otherwise.
"""
return self.value != (0, 0, 0)
is_lit = is_active
def _to_255(self, value):
return round(value * 255)
def _from_255(self, value):
return 0 if value == 0 else value / 255
@property
def color(self):
"""
Represents the colour of the LED as an RGB 3-tuple of ``(red, green,
blue)`` where each value is between 0 and 255 if *pwm* was :data:`True`
when the class was constructed (but only takes values of 0 or 255 otherwise).
For example, red would be ``(255, 0, 0)`` and yellow would be ``(255, 255,
0)``, whereas orange would be ``(255, 127, 0)``.
"""
return tuple(self._to_255(v) for v in self.value)
@color.setter
def color(self, value):
self.value = tuple(self._from_255(v) for v in value)
@property
def red(self):
"""
Represents the red component of the LED as a value between 0 and 255 if *pwm* was :data:`True`
when the class was constructed (but only takes values of 0 or 255 otherwise).
"""
return self._to_255(self.value[0])
@red.setter
def red(self, value):
r, g, b = self.value
self.value = self._from_255(value), g, b
@property
def green(self):
"""
Represents the green component of the LED as a value between 0 and 255 if *pwm* was :data:`True`
when the class was constructed (but only takes values of 0 or 255 otherwise).
"""
return self._to_255(self.value[1])
@green.setter
def green(self, value):
r, g, b = self.value
self.value = r, self._from_255(value), b
@property