]> vault307.fbx.one Git - micorpython_ir.git/blob - README.md
c1635194404241aecff2af41b06d2896a1f70b8b
[micorpython_ir.git] / README.md
1 # Device drivers for IR (infra red) remote controls
2
3 This repo provides a driver to receive from IR (infra red) remote controls and
4 a driver for IR "blaster" apps. The device drivers are nonblocking. They do not
5 require `uasyncio` but are compatible with it.
6
7 # 1. IR communication
8
9 IR communication uses a carrier frequency to pulse the IR source. Modulation
10 takes the form of OOK (on-off keying). There are multiple protocols and at
11 least three options for carrier frequency, namely 36KHz, 38KHz and 40KHz.
12
13 The drivers support NEC and Sony protocols and two Philips protocols, namely
14 RC-5 and RC-6 mode 0. In the case of the transmitter the carrier frequency is a
15 runtime parameter: any value may be specified. The receiver uses a hardware
16 demodulator which should be specified for the correct frequency. The receiver
17 device driver sees the demodulated signal and is hence carrier frequency
18 agnostic.
19
20 Examining waveforms from various remote controls it is evident that numerous
21 protocols exist. Some are doubtless proprietary and undocumented. The supported
22 protocols are those for which I managed to locate documentation. My preference
23 is for the NEC version. It has conservative timing and ample scope for error
24 detection. RC-5 has limited error detection, and RC-6 mode 0 has rather fast
25 timing: I doubt that detection can be accomplished on targets slower than a
26 Pyboard.
27
28 A remote using the NEC protocol is [this one](https://www.adafruit.com/products/389).
29
30 Remotes normally transmit an address and a data byte. The address denotes the
31 physical device being controlled. The data is associated with the button on the
32 remote. Provision exists for differentiating between a button repeatedly
33 pressed and one which is held down; the mechanism is protocol dependent.
34
35 # 2. Hardware Requirements
36
37 The receiver is cross-platform. It requires an IR receiver chip to demodulate
38 the carrier. The chip must be selected for the frequency in use by the remote.
39 For 38KHz devices a receiver chip such as the Vishay TSOP4838 or the
40 [adafruit one](https://www.adafruit.com/products/157) is required. This
41 demodulates the 38KHz IR pulses and passes the demodulated pulse train to the
42 microcontroller. The tested chip returns a 0 level on carrier detect, but the
43 driver design should ensure operation regardless of sense.
44
45 In my testing a 38KHz demodulator worked with 36KHz and 40KHz remotes, but this
46 is obviously not guaranteed or optimal.
47
48 The pin used to connect the decoder chip to the target is arbitrary but the
49 test programs assume pin X3 on the Pyboard, pin 13 on the ESP8266 and pin 23 on
50 ESP32.
51
52 The transmitter requires a Pyboard 1.x (not Lite) or a Pyboard D. Output is via
53 an IR LED which will normally need a transistor to provide sufficient current.
54 Typically these need 50-100mA of drive to achieve reasonable range and data
55 integrity. A suitable LED is [this one](https://www.adafruit.com/product/387).
56
57 The transmitter test script assumes pin X1 for IR output. It can be changed,
58 but it must support Timer 2 channel 1. Pins for pushbutton inputs are
59 arbitrary: X3 and X4 are used.
60
61 # 3. Installation
62
63 On import, demos print an explanation of how to run them.
64
65 ## 3.1 Receiver
66
67 Copy the following files to the target filesystem:
68 1. `ir_rx.py` The receiver device driver.
69 2. `ir_rx_test.py` Demo of a receiver.
70
71 There are no dependencies.
72
73 The demo can be used to characterise IR remotes. It displays the codes returned
74 by each button. This can aid in the design of receiver applications. When the
75 demo runs, the REPL prompt reappears: this is because it sets up an ISR context
76 and returns. Press `ctrl-d` to cancel it. A real application would run code
77 after initialising reception so this behaviour would not occur.
78
79 ## 3.2 Transmitter
80
81 Copy the following files to the Pyboard filesystem:
82 1. `ir_tx.py` The transmitter device driver.
83 2. `ir_tx_test.py` Demo of a 2-button remote controller.
84
85 The device driver has no dependencies. The test program requires `uasyncio`
86 from the official library and `aswitch.py` from
87 [this repo](https://github.com/peterhinch/micropython-async).
88
89 # 4. Receiver
90
91 This implements a class for each supported protocol, namely `NEC_IR`,
92 `SONY_IR`, `RC5_IR` and `RC6_M0`. Applications should instantiate the
93 appropriate class with a callback. The callback will run whenever an IR pulse
94 train is received.
95
96 Constructor:
97 `NEC_IR` args: `pin`, `callback`, `extended=True`, `*args`
98 `SONY_IR` args: `pin`, `callback`, `bits=20`, `*args`
99 `RC5_IR` and `RC6_M0`: args `pin`, `callback`, `*args`
100
101 Args (all protocols):
102 1. `pin` is a `machine.Pin` instance configured as an input, connected to the
103 IR decoder chip.
104 2. `callback` is the user supplied callback (see below).
105 4. `*args` Any further args will be passed to the callback.
106
107 Protocol specific args:
108 1. `extended` is an NEC specific boolean. Remotes using the NEC protocol can
109 send 8 or 16 bit addresses. If `True` 16 bit addresses are assumed - an 8 bit
110 address will be correctly received. Set `False` to enable extra error checking
111 for remotes that return an 8 bit address.
112 2. `bits=20` Sony specific. The SIRC protocol comes in 3 variants: 12, 15 and
113 20 bits. The default will handle bitstreams from all three types of remote. A
114 value matching your remote improves the timing and reduces the likelihood of
115 errors when handling repeats: in 20-bit mode SIRC timing when a button is held
116 down is tight. A worst-case 20-bit block takes 39ms nominal, yet the repeat
117 time is 45ms nominal.
118 The Sony remote tested issues both 12 bit and 15 bit streams.
119
120 The callback takes the following args:
121 1. `data` Integer value fom the remote. A negative value indicates an error
122 except for the value of -1 which signifies an NEC repeat code (see below).
123 2. `addr` Address from the remote
124 3. `ctrl` 0 in the case of NEC. Philips protocols toggle this bit on repeat
125 button presses. If the button is held down the bit is not toggled. The
126 transmitter demo implements this behaviour.
127 In the case of Sony the value will be 0 unless receiving a 20-bit stream, in
128 which case it will hold the extended value.
129 4. Any args passed to the constructor.
130
131 Class variable:
132 1. `verbose=False` If `True` emits debug output.
133
134 # 4.1 Errors
135
136 IR reception is inevitably subject to errors, notably if the remote is operated
137 near the limit of its range, if it is not pointed at the receiver or if its
138 batteries are low. So applications must check for, and usually ignore, errors.
139 These are flagged by data values < `REPEAT` (-1).
140
141 On the ESP8266 there is a further source of errors. This results from the large
142 and variable interrupt latency of the device which can exceed the pulse
143 duration. This causes pulses to be missed. This tendency is slightly reduced by
144 running the chip at 160MHz.
145
146 In general applications should provide user feedback of correct reception.
147 Users tend to press the key again if the expected action is absent.
148
149 Data values passed to the callback are normally positive. Negative values
150 indicate a repeat code or an error.
151
152 `REPEAT` A repeat code was received.
153
154 Any data value < `REPEAT` denotes an error. In general applications do not
155 need to decode these, but they may be of use in debugging. For completeness
156 they are listed below.
157
158 `BADSTART` A short (<= 4ms) start pulse was received. May occur due to IR
159 interference, e.g. from fluorescent lights. The TSOP4838 is prone to producing
160 200µs pulses on occasion, especially when using the ESP8266.
161 `BADBLOCK` A normal data block: too few edges received. Occurs on the ESP8266
162 owing to high interrupt latency.
163 `BADREP` A repeat block: an incorrect number of edges were received.
164 `OVERRUN` A normal data block: too many edges received.
165 `BADDATA` Data did not match check byte.
166 `BADADDR` Where `extended` is `False` the 8-bit address is checked
167 against the check byte. This code is returned on failure.
168
169 # 4.2 Receiver platforms
170
171 The NEC protocol has been tested against Pyboard, ESP8266 and ESP32 targets.
172 The Philips protocols - especially RC-6 - have tighter timing constraints. I
173 have not yet tested these, but I anticipate problems.
174
175 # 4.3 Principle of operation
176
177 Protocol classes inherit from the abstract base class `IR_RX`. This uses a pin
178 interrupt to store in an array the start and end times of pulses (in μs).
179 Arrival of the first pulse triggers a software timer which runs for the
180 expected duration of an IR block (`tblock`). When it times out its callback
181 (`.decode`) decodes the data and calls the user callback. The use of a software
182 timer ensures that `.decode` and the user callback can allocate.
183
184 The size of the array and the duration of the timer are protocol dependent and
185 are set by the subclasses. The `.decode` method is provided in the subclass.
186
187 CPU times used by `.decode` (not including the user callback) were measured on
188 a Pyboard D SF2W at stock frequency. They were NEC 1ms for normal data, 100μs
189 for a repeat code. Philips codes: RC-5 900μs, RC-6 mode 0 5.5ms.
190
191 # 5 Transmitter
192
193 This is specific to Pyboard D and Pyboard 1.x (not Lite).
194
195 It implements a class for each supported protocol, namely `NEC`, `SONY`, `RC5`
196 and `RC6_M0`. The application instantiates the appropriate class and calls the
197 `transmit` method to send data.
198
199 Constructor
200 All constructors take the following args:
201 1. `pin` An initialised `pyb.Pin` instance supporting Timer 2 channel 1: `X1`
202 is employed by the test script. Must be connected to the IR diode as described
203 below.
204 2. `freq=default` The carrier frequency in Hz. The default for NEC is 38000,
205 Sony is 40000 and Philips is 36000.
206 3. `verbose=False` If `True` emits debug output.
207
208 The `SONY` constructor is of form `pin, bits=12, freq=40000, verbose=False`.
209 The `bits` value may be 12, 15 or 20 to set SIRC variant in use. Other args are
210 as above.
211
212 Method:
213 1. `transmit(addr, data, toggle=0)` Integer args. `addr` and `data` are
214 normally 8-bit values and `toggle` is normally 0 or 1.
215 In the case of NEC, if an address < 256 is passed, normal mode is assumed and
216 the complementary value is appended. 16-bit values are transmitted as extended
217 addresses.
218 In the case of NEC the `toggle` value is ignored. For Philips protocols it
219 should be toggled each time a button is pressed, and retained if the button is
220 held down. The test program illustrates a way to do this.
221 `SONY` ignores `toggle` unless in 20-bit mode, in which case it is transmitted
222 as the `extended` value and can be any integer in range 0 to 255.
223
224 The `transmit` method is synchronous with rapid return. Actual transmission
225 occurs as a background process, controlled by timers 2 and 5. Execution times
226 on a Pyboard 1.1 were 3.3ms for NEC, 1.5ms for RC5 and 2ms for RC6.
227
228 # 5.1 Wiring
229
230 I use the following circuit which delivers just under 40mA to the diode. R2 may
231 be reduced for higher current.
232 ![Image](images/circuit.png)
233
234 This alternative delivers a constant current of about 53mA if a higher voltage
235 than 5V is available. R4 determines the current value and may be reduced to
236 increase power.
237 ![Image](images/circuit2.png)
238
239 The transistor type is not critical.
240
241 The driver assumes circuits as shown. Here the carrier "off" state is 0V,
242 which is the driver default. If using a circuit where "off" is required to be
243 3.3V, the constant `_SPACE` in `ir_tx.py` should be changed to 100.
244
245 # 5.2 Principle of operation
246
247 The classes inherit from the abstract base class `IR`. This has an array `.arr`
248 to contain the duration (in μs) of each carrier on or off period. The
249 `transmit` method calls a `tx` method of the subclass which populates this
250 array. On completion `transmit` appends a special `STOP` value and initiates
251 physical transmission which occurs in an interrupt context.
252
253 This is performed by two hardware timers initiated in the constructor. Timer 2,
254 channel 1 is used to configure the output pin as a PWM channel. Its frequency
255 is set in the constructor. The OOK is performed by dynamically changing the
256 duty ratio using the timer channel's `pulse_width_percent` method: this varies
257 the pulse width from 0 to a duty ratio passed to the constructor. The NEC
258 protocol defaults to 50%, the Sony and Philips ones to 30%.
259
260 The duty ratio is changed by the Timer 5 callback `._cb`. This retrieves the
261 next duration from the array. If it is not `STOP` it toggles the duty cycle
262 and re-initialises T5 for the new duration.
263
264 The `IR.append` enables times to be added to the array, keeping track of the
265 notional carrier on/off state for biphase generation. The `IR.add` method
266 facilitates lengthening a pulse as required in the biphase sequences used in
267 Philips protocols.
268
269 # 6. References
270
271 [General information about IR](https://www.sbprojects.net/knowledge/ir/)
272
273 The NEC protocol:
274 [altium](http://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol)
275 [circuitvalley](http://www.circuitvalley.com/2013/09/nec-protocol-ir-infrared-remote-control.html)
276
277 Philips protocols:
278 [RC5](https://en.wikipedia.org/wiki/RC-5)
279 [RC6](https://www.sbprojects.net/knowledge/ir/rc6.php)
280
281 Sony protocol:
282 [SIRC](https://www.sbprojects.net/knowledge/ir/sirc.php)
283
284 # Appendix 1 NEC Protocol description
285
286 A normal burst comprises exactly 68 edges, the exception being a repeat code
287 which has 4. An incorrect number of edges is treated as an error. All bursts
288 begin with a 9ms pulse. In a normal code this is followed by a 4.5ms space; a
289 repeat code is identified by a 2.25ms space. A data burst lasts for 67.5ms.
290
291 Data bits comprise a 562.5µs mark followed by a space whose length determines
292 the bit value. 562.5µs denotes 0 and 1.6875ms denotes 1.
293
294 In 8 bit address mode the complement of the address and data values is sent to
295 provide error checking. This also ensures that the number of 1's and 0's in a
296 burst is constant, giving a constant burst length of 67.5ms. In extended
297 address mode this constancy is lost. The burst length can (by my calculations)
298 run to 76.5ms.
299
300 A pin interrupt records the time of every state change (in µs). The first
301 interrupt in a burst sets an event, passing the time of the state change. A
302 coroutine waits on the event, yields for the duration of a data burst, then
303 decodes the stored data before calling the user-specified callback.
304
305 Passing the time to the `Event` instance enables the coro to compensate for
306 any asyncio latency when setting its delay period.
307
308 The algorithm promotes interrupt handler speed over RAM use: the 276 bytes used
309 for the data array could be reduced to 69 bytes by computing and saving deltas
310 in the interrupt service routine.