]> vault307.fbx.one Git - micorpython_ir.git/blob - ir_tx/__init__.py
Release 0.1 Various bugfixes and improvements.
[micorpython_ir.git] / ir_tx / __init__.py
1 # __init__.py Nonblocking IR blaster
2 # Runs on Pyboard D or Pyboard 1.x (not Pyboard Lite) and ESP32
3
4 # Released under the MIT License (MIT). See LICENSE.
5
6 # Copyright (c) 2020 Peter Hinch
7 from sys import platform
8 ESP32 = platform == 'esp32' # Loboris not supported owing to RMT
9 if ESP32:
10 from machine import Pin, PWM
11 from esp32 import RMT
12 else:
13 from pyb import Pin, Timer # Pyboard does not support machine.PWM
14
15 from micropython import const
16 from array import array
17 from time import ticks_us, ticks_diff
18 # import micropython
19 # micropython.alloc_emergency_exception_buf(100)
20
21 # On ESP32 gate hardware design is led_on = rmt and carrier
22
23 # Shared by NEC
24 STOP = const(0) # End of data
25
26 # IR abstract base class. Array holds periods in μs between toggling 36/38KHz
27 # carrier on or off. Physical transmission occurs in an ISR context controlled
28 # by timer 2 and timer 5. See TRANSMITTER.md for details of operation.
29 class IR:
30 _active_high = True # Hardware turns IRLED on if pin goes high.
31 _space = 0 # Duty ratio that causes IRLED to be off
32 timeit = False # Print timing info
33
34 @classmethod
35 def active_low(cls):
36 if ESP32:
37 raise ValueError('Cannot set active low on ESP32')
38 cls._active_high = False
39 cls._space = 100
40
41 def __init__(self, pin, cfreq, asize, duty, verbose):
42 if ESP32:
43 self._pwm = PWM(pin[0]) # Continuous 36/38/40KHz carrier
44 self._pwm.deinit()
45 # ESP32: 0 <= duty <= 1023
46 self._pwm.init(freq=cfreq, duty=round(duty * 10.23))
47 self._rmt = RMT(0, pin=pin[1], clock_div=80) # 1μs resolution
48 else: # Pyboard
49 if not IR._active_high:
50 duty = 100 - duty
51 tim = Timer(2, freq=cfreq) # Timer 2/pin produces 36/38/40KHz carrier
52 self._ch = tim.channel(1, Timer.PWM, pin=pin)
53 self._ch.pulse_width_percent(self._space) # Turn off IR LED
54 # Pyboard: 0 <= pulse_width_percent <= 100
55 self._duty = duty
56 self._tim = Timer(5) # Timer 5 controls carrier on/off times
57 self._tcb = self._cb # Pre-allocate
58 self._arr = array('H', 0 for _ in range(asize)) # on/off times (μs)
59 self._mva = memoryview(self._arr)
60 # Subclass interface
61 self.verbose = verbose
62 self.carrier = False # Notional carrier state while encoding biphase
63 self.aptr = 0 # Index into array
64
65 def _cb(self, t): # T5 callback, generate a carrier mark or space
66 t.deinit()
67 p = self.aptr
68 v = self._arr[p]
69 if v == STOP:
70 self._ch.pulse_width_percent(self._space) # Turn off IR LED.
71 return
72 self._ch.pulse_width_percent(self._space if p & 1 else self._duty)
73 self._tim.init(prescaler=84, period=v, callback=self._tcb)
74 self.aptr += 1
75
76 # Public interface
77 # Before populating array, zero pointer, set notional carrier state (off).
78 def transmit(self, addr, data, toggle=0, validate=False): # NEC: toggle is unused
79 t = ticks_us()
80 if validate:
81 if addr > self.valid[0] or addr < 0:
82 raise ValueError('Address out of range', addr)
83 if data > self.valid[1] or data < 0:
84 raise ValueError('Data out of range', data)
85 if toggle > self.valid[2] or toggle < 0:
86 raise ValueError('Toggle out of range', toggle)
87 self.aptr = 0 # Inital conditions for tx: index into array
88 self.carrier = False
89 self.tx(addr, data, toggle) # Subclass populates ._arr
90 self.trigger() # Initiate transmission
91 if self.timeit:
92 dt = ticks_diff(ticks_us(), t)
93 print('Time = {}μs'.format(dt))
94
95 # Subclass interface
96 def trigger(self): # Used by NEC to initiate a repeat frame
97 if ESP32:
98 self._rmt.write_pulses(tuple(self._mva[0 : self.aptr]), start = 1)
99 else:
100 self.append(STOP)
101 self.aptr = 0 # Reset pointer
102 self._cb(self._tim) # Initiate physical transmission.
103
104 def append(self, *times): # Append one or more time peiods to ._arr
105 for t in times:
106 self._arr[self.aptr] = t
107 self.aptr += 1
108 self.carrier = not self.carrier # Keep track of carrier state
109 self.verbose and print('append', t, 'carrier', self.carrier)
110
111 def add(self, t): # Increase last time value (for biphase)
112 assert t > 0
113 self.verbose and print('add', t)
114 # .carrier unaffected
115 self._arr[self.aptr - 1] += t
116
117
118 # Given an iterable (e.g. list or tuple) of times, emit it as an IR stream.
119 class Player(IR):
120
121 def __init__(self, pin, freq=38000, verbose=False): # NEC specifies 38KHz
122 super().__init__(pin, freq, 68, 33, verbose) # Measured duty ratio 33%
123
124 def play(self, lst):
125 for x, t in enumerate(lst):
126 self._arr[x] = t
127 self.aptr = x + 1
128 self.trigger()