-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_core.py
More file actions
1174 lines (946 loc) · 39.5 KB
/
_core.py
File metadata and controls
1174 lines (946 loc) · 39.5 KB
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
# This file is part of espzero, automatically synced from
# https://github.com/roboticsware/espzero at revision 24cae2bc1c028458052675181e95f2a08fdf7481.
# Do not edit this file directly — run update_user_libs.py espzero instead.
"""espzero/_core.py — ESP32 port of the picozero core logic."""
from machine import Pin, Timer
from micropython import schedule
from time import ticks_ms, ticks_us, ticks_diff, ticks_add, sleep
from . import _hal
class PWMChannelAlreadyInUse(Exception):
pass
class EventFailedScheduleQueueFull(Exception):
pass
def clamp(n, low, high):
return max(low, min(n, high))
class PinMixin:
@property
def pin(self):
return self._pin_num
def __str__(self):
return "{} (pin {})".format(self.__class__.__name__, self._pin_num)
class PinsMixin:
@property
def pins(self):
return self._pin_nums
def __str__(self):
return "{} (pins - {})".format(self.__class__.__name__, self._pin_nums)
# ── Software Timer Implementation ──────────────────────────────
# ESP32 MicroPython doesn't support Timer(-1). We implement a simple
# software scheduler using one hardware timer (Timer 3) to allow
# unlimited concurrent blinks/pulses.
class _SoftwareTimer:
def __init__(self):
self._callback = None
self._period = 0
self._next_tick = 0
self._active = False
def init(self, mode=None, period=0, callback=None):
self._callback = callback
self._period = period
self._next_tick = ticks_add(ticks_ms(), period)
self._active = True
_scheduler.register(self)
def deinit(self):
self._active = False
_scheduler.unregister(self)
class _Scheduler:
def __init__(self):
self._tasks = []
self._hw_timer = None
def register(self, task):
if task not in self._tasks:
self._tasks.append(task)
if self._hw_timer is None:
# Start hardware timer when first task is added
try:
self._hw_timer = Timer(3) # Use the last hardware timer
self._hw_timer.init(period=10, mode=Timer.PERIODIC, callback=self._tick)
except Exception:
pass # Fallback or silent fail if T3 unavailable
def unregister(self, task):
if task in self._tasks:
self._tasks.remove(task)
if not self._tasks and self._hw_timer:
self._hw_timer.deinit()
self._hw_timer = None
def _tick(self, timer_obj):
now = ticks_ms()
for task in self._tasks[:]:
# Use ticks_diff for wraparound-safe comparison
if task._active and ticks_diff(task._next_tick, now) <= 0:
task._active = False
if task._callback:
# Execute directly. ESP32 Timer callbacks are Soft-IRQs,
# so they can allocate memory and run normal Python code.
# This avoids micropython.schedule dropping tasks.
try:
task._callback(None)
except Exception as e:
print("[espzero] Timer callback error:", e)
_scheduler = _Scheduler()
class ValueChange:
def __init__(self, output_device, sequence, n, wait):
self._output_device = output_device
self._sequence = sequence # List of (value, duration) tuples
self._n = n
self._index = 0
self._timer = _SoftwareTimer()
self._running = True
if wait:
self._run_sync()
else:
self._step_async()
def _run_sync(self):
# Synchronous execution using a while loop to avoid recursion limit
while self._running:
if self._index >= len(self._sequence):
self._index = 0
if self._n is not None:
self._n -= 1
if self._n <= 0:
self._output_device.off()
self._running = False
break
value, seconds = self._sequence[self._index]
self._index += 1
self._output_device._write(value)
sleep(seconds)
def _step_async(self, timer_obj=None):
# Asynchronous execution triggered by hardware timer Soft-IRQ
if not self._running:
return
if self._index >= len(self._sequence):
self._index = 0
if self._n is not None:
self._n -= 1
if self._n <= 0:
self._output_device.off()
self._running = False
return
value, seconds = self._sequence[self._index]
self._index += 1
self._output_device._write(value)
self._timer.init(period=int(seconds * 1000), callback=self._step_async)
def stop(self):
self._running = False
self._timer.deinit()
class OutputDevice:
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):
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):
return self._read()
@value.setter
def value(self, value):
self._stop_change()
self._write(value)
def on(self, value=1, t=None, wait=False):
if t is None:
self.value = value
else:
self._start_change([(value, t)], 1, wait)
def off(self):
self.value = 0
@property
def is_active(self):
return bool(self.value)
def toggle(self):
if self.is_active:
self.off()
else:
self.on()
def blink(self, on_time=1, off_time=None, n=None, wait=False):
off_time = on_time if off_time is None else off_time
self._stop_change()
if on_time > 0 or off_time > 0:
self._start_change([(1, on_time), (0, off_time)], n, wait)
def _start_change(self, sequence, n, wait):
self._value_changer = ValueChange(self, sequence, n, wait)
def _stop_change(self):
if self._value_changer is not None:
self._value_changer.stop()
self._value_changer = None
def close(self):
self.value = 0
class DigitalOutputDevice(OutputDevice, PinMixin):
def __init__(self, pin, active_high=True, initial_value=False):
self._pin_num = pin
self._pin = _hal.make_digital_out(pin)
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):
super().close()
self._pin = None
class DigitalLED(DigitalOutputDevice):
pass
DigitalLED.is_lit = DigitalLED.is_active
class Buzzer(DigitalOutputDevice):
pass
Buzzer.beep = Buzzer.blink
class PWMOutputDevice(OutputDevice, PinMixin):
# ESP32 LEDC: any pin can use any channel — no channel-collision table needed
def __init__(self, pin, freq=None, duty_factor=65535,
active_high=True, initial_value=False):
self._pin_num = pin
self._duty_factor = duty_factor
self._pwm = _hal.make_pwm(pin, freq)
super().__init__(active_high, initial_value)
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(_hal.get_duty_u16(self._pwm))
def _write(self, value):
_hal.set_duty_u16(self._pwm, self._value_to_state(value))
@property
def is_active(self):
return self.value != 0
@property
def freq(self):
return self._pwm.freq()
@freq.setter
def freq(self, freq):
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):
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)
if on_time > 0 or off_time > 0 or fade_in_time > 0 or fade_out_time > 0:
# Convert generator to a list for the state-machine ValueChange
self._start_change(list(blink_generator()), n, wait)
def pulse(self, fade_in_time=1, fade_out_time=None, n=None, wait=False, fps=25):
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):
super().close()
self._pwm.deinit()
self._pwm = None
class PWMLED(PWMOutputDevice):
pass
PWMLED.brightness = PWMLED.value
def LED(pin, pwm=True, active_high=True, initial_value=False):
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)
class NeoPixelLED(OutputDevice):
"""WS2812 single-pixel wrapper for boards with a built-in RGB LED.
Automatically used when INTERNAL_LED_TYPE == 'neopixel'.
"""
def __init__(self, pin, color=(255, 255, 255), active_high=True, initial_value=False):
import neopixel
self._np = neopixel.NeoPixel(Pin(pin), 1)
self._color = color
self._pin_num = pin
super().__init__(active_high, initial_value)
def _write(self, value):
self._np[0] = self._color if self._value_to_state(value) else (0, 0, 0)
self._np.write()
def close(self):
super().close()
self.off()
class PWMBuzzer(PWMOutputDevice):
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):
NOTES = {
"c4":262,"d4":294,"e4":330,"f4":349,"g4":392,"a4":440,"b4":494,
"c5":523,"d5":587,"e5":659,"f5":698,"g5":784,"a5":880,"b5":988,
"c6":1047,"d6":1175,"e6":1319,"f6":1397,"g6":1568,"a6":1760,"b6":1976,
}
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):
return (self.freq, self.volume)
@value.setter
def value(self, value):
self._stop_change()
self._write(value)
@property
def volume(self):
return self._volume
@volume.setter
def volume(self, value):
self._volume = value
self.value = (self.freq, self.volume)
@property
def freq(self):
return self._pwm_buzzer.freq
@freq.setter
def freq(self, freq):
self.value = (freq, self.volume)
def _write(self, value):
if value[0] is not None:
self._pwm_buzzer.freq = value[0]
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.get(freq.lower(), 440))
elif 0 < freq <= 128:
return int(440 * (2 ** (1/12)) ** (freq - 69))
else:
return freq
return None
def play(self, tune=440, duration=1, volume=1, n=1, wait=True):
self.off()
if not isinstance(tune, (list, tuple)):
tune = [(tune, duration)]
elif not isinstance(tune[0], (list, tuple)):
tune = [tune]
def tune_generator():
for note in tune:
if not isinstance(note, (list, tuple)):
note = (note, duration)
freq = self._to_freq(note[0])
freq_duration = note[1]
freq_volume = volume if freq is not None else 0
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)
# Convert generator to list for state-machine compatibility
self._start_change(list(tune_generator()), n, wait)
def close(self):
self._pwm_buzzer.close()
class RGBLED(OutputDevice, PinsMixin):
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)
LEDClass = PWMLED if pwm else DigitalLED
self._leds = tuple(LEDClass(p, active_high=active_high) for p in (red, green, blue))
self._last = initial_value
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):
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):
return self.value != (0, 0, 0)
is_lit = is_active
def _to_255(self, v): return round(v * 255)
def _from_255(self, v): return 0 if v == 0 else v / 255
@property
def color(self):
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)
def on(self): self.value = (1, 1, 1)
def toggle(self):
if self.value == (0,0,0):
self.value = self._last or (1,1,1)
else:
self._last = self.value
self.value = (0,0,0)
def close(self):
super().close()
for led in self._leds:
led.close()
RGBLED.colour = RGBLED.color
class Motor(PinsMixin):
def __init__(self, forward, backward, pwm=True):
self._pin_nums = (forward, backward)
self._forward = PWMOutputDevice(forward) if pwm else DigitalOutputDevice(forward)
self._backward = PWMOutputDevice(backward) if pwm else DigitalOutputDevice(backward)
def on(self, speed=1, t=None, wait=False):
if speed > 0:
self._backward.off(); self._forward.on(speed, t, wait)
elif speed < 0:
self._forward.off(); self._backward.on(-speed, t, wait)
else:
self.off()
def off(self):
self._backward.off(); self._forward.off()
@property
def value(self):
return self._forward.value + (-self._backward.value)
@value.setter
def value(self, value):
self.on(value) if value != 0 else self.off()
def forward(self, speed=1, t=None, wait=False): self.on(speed, t, wait)
def backward(self, speed=1, t=None, wait=False): self.on(-speed, t, wait)
def close(self): self._forward.close(); self._backward.close()
Motor.start = Motor.on
Motor.stop = Motor.off
class Robot:
def __init__(self, left, right, pwm=True):
self._left = Motor(left[0], left[1], pwm)
self._right = Motor(right[0], right[1], pwm)
@property
def value(self): return (self._left.value, self._right.value)
@value.setter
def value(self, v): self._left.value, self._right.value = v
def forward(self, speed=1, t=None, wait=False):
self._left.forward(speed, t, False); self._right.forward(speed, t, wait)
def backward(self, speed=1, t=None, wait=False):
self._left.backward(speed, t, False); self._right.backward(speed, t, wait)
def left(self, speed=1, t=None, wait=False):
self._left.backward(speed, t, False); self._right.forward(speed, t, wait)
def right(self, speed=1, t=None, wait=False):
self._left.forward(speed, t, False); self._right.backward(speed, t, wait)
def stop(self): self._left.stop(); self._right.stop()
def close(self): self._left.close(); self._right.close()
Rover = Robot
class Servo(PWMOutputDevice):
def __init__(self, pin, initial_value=None,
min_pulse_width=1/1000, max_pulse_width=2/1000,
frame_width=20/1000, duty_factor=65535):
self._min_duty = int((min_pulse_width / frame_width) * duty_factor)
self._max_duty = int((max_pulse_width / frame_width) * duty_factor)
super().__init__(pin, freq=int(1/frame_width),
duty_factor=duty_factor, initial_value=initial_value)
def _state_to_value(self, state):
return (None if state == 0 else
clamp((state - self._min_duty) / (self._max_duty - self._min_duty), 0, 1))
def _value_to_state(self, value):
return (0 if value is None else
int(self._min_duty + (self._max_duty - self._min_duty) * value))
def min(self): self.value = 0
def mid(self): self.value = 0.5
def max(self): self.value = 1
def off(self): self.value = None
class InputDevice:
def __init__(self, active_state=None):
self._active_state = active_state
@property
def active_state(self): return self._active_state
@active_state.setter
def active_state(self, value):
self._active_state = True if value else False
self._inactive_state = False if value else True
@property
def value(self): return self._read()
class DigitalInputDevice(InputDevice, PinMixin):
def __init__(self, pin, pull_up=False, active_state=None, bounce_time=None):
super().__init__(active_state)
self._pin_num = pin
self._pin = _hal.make_digital_in(pin, pull_up)
self._bounce_time = bounce_time
self._last_callback_ms = None
if active_state is None:
self._active_state = False if pull_up else True
else:
self._active_state = active_state
self._state = self._pin.value()
self._when_activated = None
self._when_deactivated = None
self._pin.irq(self._pin_change, Pin.IRQ_RISING | Pin.IRQ_FALLING)
def _state_to_value(self, state):
return int(bool(state) == self._active_state)
def _read(self):
return self._state_to_value(self._state)
def _pin_change(self, p):
new_state = p.value()
if self._state != new_state:
current_ms = ticks_ms()
elapsed = (current_ms - self._last_callback_ms
if self._last_callback_ms is not None else float("inf"))
bounce_ms = self._bounce_time * 1000 if self._bounce_time else None
if bounce_ms is None or elapsed >= bounce_ms:
self._state = new_state
self._last_callback_ms = current_ms
cb = None
if self.value and self._when_activated:
cb = self._when_activated
elif not self.value and self._when_deactivated:
cb = self._when_deactivated
if cb is not None:
try:
schedule(lambda c: c(), cb)
except RuntimeError:
raise EventFailedScheduleQueueFull(
"{} callback not scheduled: queue full".format(str(self)))
else:
self._state = new_state
@property
def is_active(self): return bool(self.value)
@property
def is_inactive(self): return not bool(self.value)
@property
def when_activated(self): return self._when_activated
@when_activated.setter
def when_activated(self, value): self._when_activated = value
@property
def when_deactivated(self): return self._when_deactivated
@when_deactivated.setter
def when_deactivated(self, value): self._when_deactivated = value
def close(self):
self._pin.irq(handler=None)
self._pin = None
class Switch(DigitalInputDevice):
def __init__(self, pin, pull_up=True, bounce_time=0.02):
super().__init__(pin=pin, pull_up=pull_up, bounce_time=bounce_time)
Switch.is_closed = Switch.is_active
Switch.is_open = Switch.is_inactive
Switch.when_closed = Switch.when_activated
Switch.when_opened = Switch.when_deactivated
class Button(Switch):
pass
Button.is_pressed = Button.is_active
Button.is_released = Button.is_inactive
Button.when_pressed = Button.when_activated
Button.when_released = Button.when_deactivated
class MotionSensor(DigitalInputDevice):
def __init__(self, pin, pull_up=False, bounce_time=1.0):
super().__init__(pin=pin, pull_up=pull_up, bounce_time=bounce_time)
MotionSensor.motion_detected = MotionSensor.is_active
MotionSensor.motion_not_detected = MotionSensor.is_inactive
MotionSensor.when_motion = MotionSensor.when_activated
MotionSensor.when_no_motion = MotionSensor.when_deactivated
class TouchSensor(Button):
def __init__(self, pin, pull_up=False, bounce_time=0.02):
super().__init__(pin=pin, pull_up=pull_up, bounce_time=bounce_time)
TouchSensor.is_touched = TouchSensor.is_active
TouchSensor.is_not_touched = TouchSensor.is_inactive
TouchSensor.when_touch_starts = TouchSensor.when_activated
TouchSensor.when_touch_ends = TouchSensor.when_deactivated
class AnalogInputDevice(InputDevice, PinMixin):
def __init__(self, pin, active_state=True, threshold=0.5):
self._pin_num = pin
super().__init__(active_state)
self._adc = _hal.make_adc(pin)
self._threshold = float(threshold)
def _state_to_value(self, state):
return (state if self.active_state else 65535 - state) / 65535
def _read(self):
return self._state_to_value(_hal.adc_read_u16(self._adc))
@property
def threshold(self): return self._threshold
@threshold.setter
def threshold(self, value): self._threshold = float(value)
@property
def is_active(self): return self.value > self.threshold
@property
def voltage(self):
return self.value * _hal.get_profile().ADC_VREF
def close(self): self._adc = None
class Potentiometer(AnalogInputDevice):
pass
Pot = Potentiometer
class TemperatureSensor(AnalogInputDevice):
def __init__(self, pin, active_state=True, threshold=0.5, conversion=None):
self._conversion = conversion
super().__init__(pin, active_state, threshold)
@property
def temp(self):
return self._conversion(self.voltage) if self._conversion else None
@property
def conversion(self): return self._conversion
@conversion.setter
def conversion(self, value): self._conversion = value
TempSensor = TemperatureSensor
Thermistor = TemperatureSensor
class ESPTemperatureSensor:
"""Reads the ESP32 built-in temperature sensor via the esp32 module."""
@property
def temp(self):
try:
import esp32
return esp32.raw_temperature() / 100.0
except Exception:
return None
class DistanceSensor(PinsMixin):
def __init__(self, echo, trigger, max_distance=400):
self._pin_nums = (echo, trigger)
self._max_distance = max_distance
self._echo = Pin(echo, mode=Pin.IN, pull=Pin.PULL_DOWN)
self._trigger = Pin(trigger, mode=Pin.OUT, value=0)
def _read(self):
echo_on = echo_off = None
self._trigger.off(); sleep(0.000005)
self._trigger.on(); sleep(0.00001)
self._trigger.off()
stop = ticks_ms() + 100
while echo_off is None and ticks_ms() < stop:
if self._echo.value() == 1 and echo_on is None:
echo_on = ticks_us()
if echo_on and self._echo.value() == 0:
echo_off = ticks_us()
if echo_off is None:
return None
# Use 0.0343 for centimeters (matches picozero 0.6.2)
dist = ((echo_off - echo_on) * 0.0343) / 2
return min(dist, self._max_distance)
@property
def distance(self): return self._read()
@property
def value(self):
d = self.distance
return d / self._max_distance if d is not None else None
@property
def max_distance(self): return self._max_distance
class Stepper(PinsMixin):
STEP_SEQUENCES = {
"wave": [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],
"full": [[1,1,0,0],[0,1,1,0],[0,0,1,1],[1,0,0,1]],
"half": [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,0],
[0,0,1,0],[0,0,1,1],[0,0,0,1],[1,0,0,1]],
}
def __init__(self, pins, step_sequence="full", step_delay=0.002, steps_per_rotation=2048):
if len(pins) != 4:
raise ValueError("Stepper requires exactly 4 pins")
self._pin_nums = tuple(pins)
self._pins = tuple(DigitalOutputDevice(p) for p in pins)
self._step_delay = step_delay
self._steps_per_rotation = steps_per_rotation
self._current_step = 0
self._step_count = 0
if step_sequence not in self.STEP_SEQUENCES:
raise ValueError(f"Invalid step_sequence. Must be one of: {list(self.STEP_SEQUENCES.keys())}")
self._step_sequence = step_sequence
self._sequence = self.STEP_SEQUENCES[step_sequence]
self._set_step([0,0,0,0])
def _normalise_direction(self, direction):
if isinstance(direction, str):
direction_lower = direction.lower().strip()
if direction_lower in ("cw", "clockwise"): return 1
elif direction_lower in ("ccw", "counter-clockwise", "counterclockwise"): return -1
else: raise ValueError(f"Invalid direction string: '{direction}'.")
else:
return 1 if direction >= 0 else -1
def _set_step(self, pattern):
for pin, state in zip(self._pins, pattern):
pin.value = state
def _single_step(self, direction=1):
normalised_direction = self._normalise_direction(direction)
if normalised_direction > 0:
self._current_step = (self._current_step + 1) % len(self._sequence)
self._step_count += 1
else:
self._current_step = (self._current_step - 1) % len(self._sequence)
self._step_count -= 1
self._set_step(self._sequence[self._current_step])
sleep(self._step_delay)
def step(self, steps, direction=1):
for _ in range(abs(int(steps))):
self._single_step(direction)
def step_to(self, steps, direction):
target_steps = int(steps)
current_steps = self._step_count
normalised_dir = self._normalise_direction(direction)
if normalised_dir > 0:
distance = target_steps - current_steps
if distance > 0: self.step(distance, direction)
elif distance < 0: self.step(self._steps_per_rotation + distance, direction)
else:
if target_steps > 0: self.step(target_steps, direction)
def turn(self, angle, direction):
angle = abs(float(angle))
steps = int((angle / 360.0) * self._steps_per_rotation)
self.step(steps, direction)
def rotate(self, rotations, direction):
rotations = abs(float(rotations))
steps = int(rotations * self._steps_per_rotation)
self.step(steps, direction)
def turn_to(self, angle, direction):
target_angle = abs(float(angle)) % 360.0
current_angle = self.angle
if self._normalise_direction(direction) > 0:
if target_angle >= current_angle: rotation_angle = target_angle - current_angle
else: rotation_angle = 360.0 - current_angle + target_angle
else:
if target_angle <= current_angle: rotation_angle = current_angle - target_angle
else: rotation_angle = current_angle + (360.0 - target_angle)
steps = int((rotation_angle / 360.0) * self._steps_per_rotation)
if steps > 0: self.step(steps, direction)
def reset_position(self): self._step_count = 0
def off(self): self._set_step([0,0,0,0])
def set_speed(self, rpm):
rpm = float(rpm)
if rpm <= 0: raise ValueError("RPM must be positive")
self._step_delay = 60.0 / (rpm * self._steps_per_rotation)
def run_continuous(self, seconds=None, direction=1):
if seconds is None:
try:
while True: self._single_step(direction)
except KeyboardInterrupt:
self.off()
else:
seconds = abs(float(seconds))
end_time = ticks_ms() + int(seconds * 1000)
while ticks_ms() < end_time: self._single_step(direction)
self.off()
@property
def step_delay(self): return self._step_delay
@step_delay.setter
def step_delay(self, value): self._step_delay = float(value)
@property
def step_count(self): return self._step_count
@property
def angle(self): return ((self._step_count / self._steps_per_rotation) * 360.0) % 360.0
@property
def steps_per_rotation(self): return self._steps_per_rotation
def close(self):
self.off()
for p in self._pins: p.close()
# --- LCD Display Classes ---
MASK_RS = 0x01
MASK_RW = 0x02
MASK_E = 0x04
SHIFT_BACKLIGHT = 3
SHIFT_DATA = 4
class LcdApi:
LCD_CLR = 0x01
LCD_HOME = 0x02
LCD_ENTRY_MODE = 0x04
LCD_ENTRY_INC = 0x02
LCD_ENTRY_SHIFT = 0x01
LCD_ON_CTRL = 0x08
LCD_ON_DISPLAY = 0x04
LCD_ON_CURSOR = 0x02
LCD_ON_BLINK = 0x01
LCD_MOVE = 0x10
LCD_MOVE_DISP = 0x08
LCD_MOVE_RIGHT = 0x04
LCD_FUNCTION = 0x20
LCD_FUNCTION_8BIT = 0x10
LCD_FUNCTION_2LINES = 0x08
LCD_FUNCTION_10DOTS = 0x04
LCD_FUNCTION_RESET = 0x30
LCD_CGRAM = 0x40
LCD_DDRAM = 0x80
def __init__(self, num_lines, num_columns):
self.num_lines = min(num_lines, 4)
self.num_columns = min(num_columns, 40)
self.cursor_x = 0
self.cursor_y = 0
self.implied_newline = False
self.backlight = True
self.display_off()
self.backlight_on()
self.clear()
self.hal_write_command(self.LCD_ENTRY_MODE | self.LCD_ENTRY_INC)
self.hide_cursor()
self.display_on()
def clear(self):
self.hal_write_command(self.LCD_CLR)
self.hal_write_command(self.LCD_HOME)
self.cursor_x = 0
self.cursor_y = 0
def show_cursor(self): self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | self.LCD_ON_CURSOR)
def hide_cursor(self): self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)
def blink_cursor_on(self): self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | self.LCD_ON_CURSOR | self.LCD_ON_BLINK)
def blink_cursor_off(self): self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | self.LCD_ON_CURSOR)
def display_on(self): self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)
def display_off(self): self.hal_write_command(self.LCD_ON_CTRL)
def backlight_on(self):
self.backlight = True
self.hal_backlight_on()
def backlight_off(self):
self.backlight = False
self.hal_backlight_off()
def move_to(self, cursor_x, cursor_y):
self.cursor_x = cursor_x
self.cursor_y = cursor_y
addr = cursor_x & 0x3f