]> vault307.fbx.one Git - micorpython_ir.git/blob - RECEIVER.md
ESP32 TX: adapt for RMT API change.
[micorpython_ir.git] / RECEIVER.md
1 # IR Receiver
2
3 ##### [Main README](./README.md#1-ir-communication)
4
5 # 1. Hardware Requirements
6
7 The receiver is cross-platform. It requires an IR receiver chip to demodulate
8 the carrier. The chip must be selected for the frequency in use by the remote.
9 For 38KHz devices a receiver chip such as the Vishay TSOP4838 or the
10 [adafruit one](https://www.adafruit.com/products/157) is required. This
11 demodulates the 38KHz IR pulses and passes the demodulated pulse train to the
12 microcontroller. The tested chip returns a 0 level on carrier detect, but the
13 driver design ensures operation regardless of sense.
14
15 In my testing a 38KHz demodulator worked with 36KHz and 40KHz remotes, but this
16 is obviously neither guaranteed nor optimal.
17
18 The TSOP4838 can run from 3.3V or 5V supplies. The former should be used on
19 non-5V compliant hosts such as ESP32 and Raspberry Pi Pico and is fine on 5V
20 compliant hosts too.
21
22 The pin used to connect the decoder chip to the target is arbitrary. The test
23 program `acquire.py` uses the following pins by default:
24
25 | Host | Pin | Notes |
26 |:-------:|:---:|:-----:|
27 | Pyboard | X3 | |
28 | ESP32 | 23 | |
29 | ESP8266 | 13 | |
30 | D1 Mini | D7 | WeMos name for pin 13. |
31 | Pico | 16 | |
32
33 A remote using the NEC protocol is [this one](https://www.adafruit.com/products/389).
34
35 # 2. Installation and demo scripts
36
37 The receiver is a Python package. This minimises RAM usage: applications only
38 import the device driver for the protocol in use. Clone the repository to the
39 current directory of your PC with:
40 ```bash
41 $ git clone https://github.com/peterhinch/micropython_ir
42 ```
43
44 Copy the following to the target filesystem:
45 1. `ir_rx` Directory and contents.
46
47 There are no dependencies.
48
49 ## 2.1 Test scripts
50
51 The demo can be used to characterise IR remotes where the protocol is known. It
52 displays the codes returned by each button. This can aid in the design of
53 receiver applications. The demo prints "running" every 5 seconds and reports
54 any data received from the remote.
55 ```python
56 from ir_rx.test import test
57 ```
58 Instructions will be displayed at the REPL.
59
60 If the protocol in use is unknown, there are two options: trial and error with
61 the above script or run the following:
62 ```python
63 from ir_rx.acquire import test
64 test()
65 ```
66 This script waits for a single burst from the remote and prints the timing of
67 the pulses followed by its best guess at the protocol. It correctly identifies
68 supported protocols, but can wrongly identify unsupported protocols. The
69 report produced by the script exposed to an unknown protocol is unpredictable.
70 The `test()` function returns a list of the mark and space periods (in μs).
71
72 # 3. The driver
73
74 This implements a class for each supported protocol. Each class is subclassed
75 from a common abstract base class in `__init__.py`.
76
77 Applications should instantiate the appropriate class with a callback. The
78 callback will run whenever an IR pulse train is received. Example running on a
79 Pyboard:
80 ```python
81 import time
82 from machine import Pin
83 from pyb import LED
84 from ir_rx.nec import NEC_8 # NEC remote, 8 bit addresses
85
86 red = LED(1)
87
88 def callback(data, addr, ctrl):
89 if data < 0: # NEC protocol sends repeat codes.
90 print('Repeat code.')
91 else:
92 print('Data {:02x} Addr {:04x}'.format(data, addr))
93
94 ir = NEC_8(Pin('X3', Pin.IN), callback)
95 while True:
96 time.sleep_ms(500)
97 red.toggle()
98 ```
99
100 #### Common to all classes
101
102 Constructor args:
103 1. `pin` is a `machine.Pin` instance configured as an input, connected to the
104 IR decoder chip.
105 2. `callback` is the user supplied callback.
106 3. `*args` Any further args will be passed to the callback.
107
108 The user callback takes the following args:
109 1. `data` (`int`) Value from the remote. Normally in range 0-255. A value < 0
110 signifies an NEC repeat code.
111 2. `addr` (`int`) Address from the remote.
112 3. `ctrl` (`int`) The meaning of this is protocol dependent:
113 NEC: 0
114 Philips: this is toggled 1/0 on repeat button presses. If the button is held
115 down it is not toggled. The transmitter demo implements this behaviour.
116 Sony: 0 unless receiving a 20-bit stream, in which case it holds the extended
117 value.
118 4. Any args passed to the constructor.
119
120 Bound variable:
121 1. `verbose=False` If `True` emits debug output.
122
123 Methods:
124 1. `error_function` Arg: a function taking a single `int` arg. If specified
125 the function will be called if an error occurs. The arg value corresponds to
126 the error code. Typical usage might be to provide some user feedback of
127 incorrect reception although beware of occasional triggers by external events.
128 In my testing the TSOP4838 produces 200µs pulses on occasion for no obvious
129 reason. See [section 4](./RECEIVER.md#4-errors).
130 2. `close` No args. Shuts down the pin and timer interrupts.
131
132 A function is provided to print errors in human readable form. This may be
133 invoked as follows:
134
135 ```python
136 from ir_rx.print_error import print_error # Optional print of error codes
137 # Assume ir is an instance of an IR receiver class
138 ir.error_function(print_error)
139 ```
140 Class variables:
141 1. These are constants defining the NEC repeat code and the error codes sent
142 to the error function. They are discussed in [section 4](./RECEIVER.md#4-errors).
143
144 #### NEC classes
145
146 `NEC_8`, `NEC_16`
147
148 Typical invocation:
149 ```python
150 from ir_rx.nec import NEC_8
151 ```
152
153 Remotes using the NEC protocol can send 8 or 16 bit addresses. If the `NEC_16`
154 class receives an 8 bit address it will get a 16 bit value comprising the
155 address in bits 0-7 and its one's complement in bits 8-15.
156 The `NEC_8` class enables error checking for remotes that return an 8 bit
157 address: the complement is checked and the address returned as an 8-bit value.
158 A 16-bit address will result in an error.
159
160 #### Sony classes
161
162 `SONY_12`, `SONY_15`, `SONY_20`
163
164 Typical invocation:
165 ```python
166 from ir_rx.sony import SONY_15
167 ```
168
169 The SIRC protocol comes in 3 variants: 12, 15 and 20 bits. `SONY_20` handles
170 bitstreams from all three types of remote. Choosing a class matching the remote
171 improves the timing reducing the likelihood of errors when handling repeats: in
172 20-bit mode SIRC timing when a button is held down is tight. A worst-case 20
173 bit block takes 39ms nominal, yet the repeat time is 45ms nominal.
174 A single physical remote can issue more than one type of bitstream. The Sony
175 remote tested issued both 12 bit and 15 bit streams.
176
177 #### Philips classes
178
179 `RC5_IR`, `RC6_M0`
180
181 Typical invocation:
182 ```python
183 from ir_rx.philips import RC5_IR
184 ```
185
186 These support the RC-5 (including RC-5X) and RC-6 mode 0 protocols
187 respectively.
188
189 #### Microsoft MCE class
190
191 `MCE`
192
193 Typical invocation:
194 ```python
195 from ir_rx.mce import MCE
196 ```
197
198 I have been unable to locate a definitive specification: the protocol was
199 analysed by a mixture of googling and experiment. Behaviour may change if I
200 acquire new information. The protocol is known as OrtekMCE and the remote
201 control is sold on eBay as VRC-1100.
202
203 The remote was designed for Microsoft Media Center and is used to control Kodi
204 on boxes such as the Raspberry Pi. With a suitable PC driver it can emulate a
205 PC keyboard and mouse. The mouse emulation uses a different protocol: the class
206 does not currently support it. Pressing mouse buttons and pad will cause the
207 error function (if provided) to be called.
208
209 Args passed to the callback comprise 4 bit `addr`, 6 bit `data` and 2 bit `ctrl`
210 with the latter having the value 0 for the first message and 2 for the message
211 sent on key release. Intermediate messages (where the key is held down) have
212 value 1.
213
214 There is a 4-bit checksum which is used by default. The algorithm requires an
215 initial 'seed' value which my testing proved to be 4. However the only
216 [documentation](http://www.hifi-remote.com/johnsfine/DecodeIR.html#OrtekMCE) I
217 could find stated that the value should be 3. I implemented this as a class
218 variable `MCE.init_cs=4`. This enables it to be changed if some remotes use 3.
219 If the value is set to -1 the check will be skipped.
220
221 # 4. Errors
222
223 IR reception is inevitably subject to errors, notably if the remote is operated
224 near the limit of its range, if it is not pointed at the receiver or if its
225 batteries are low. The user callback is not called when an error occurs.
226
227 On ESP8266 and ESP32 there is a further source of errors. This results from the
228 large and variable interrupt latency of the device which can exceed the pulse
229 duration. This causes pulses to be missed or their timing measured incorrectly.
230 On ESP8266 some improvment may be achieved by running the chip at 160MHz.
231
232 In general applications should provide user feedback of correct reception.
233 Users tend to press the key again if the expected action is absent.
234
235 In debugging a callback can be specified for reporting errors. The value passed
236 to the error function are represented by constants indicating the cause of the
237 error. These are driver ABC class variables and are as follows:
238
239 `BADSTART` A short (<= 4ms) start pulse was received. May occur due to IR
240 interference, e.g. from fluorescent lights. The TSOP4838 is prone to producing
241 200µs pulses on occasion, especially when using the ESP8266.
242 `BADBLOCK` A normal data block: too few edges received. Occurs on the ESP8266
243 owing to high interrupt latency.
244 `BADREP` A repeat block: an incorrect number of edges were received.
245 `OVERRUN` A normal data block: too many edges received.
246 `BADDATA` Data did not match check byte.
247 `BADADDR` (`NEC_IR`) If `extended` is `False` the 8-bit address is checked
248 against the check byte. This code is returned on failure.
249
250 # 5. Receiver platforms
251
252 Currently the ESP8266 suffers from [this issue](https://github.com/micropython/micropython/issues/5714).
253 Testing was therefore done without WiFi connectivity. If the application uses
254 the WiFi regularly, or if an external process pings the board repeatedly, the
255 crash does not occur.
256
257 Philips protocols (especially RC-6) have tight timing constraints with short
258 pulses whose length must be determined with reasonable accuracy. The Sony 20
259 bit protocol also has a timing issue in that the worst case bit pattern takes
260 39ms nominal, yet the repeat time is 45ms nominal. These issues can lead to
261 errors particularly on slower targets. As discussed above, errors are to be
262 expected. It is up to the user to decide if the error rate is acceptable.
263
264 Reception was tested using Pyboard D SF2W, ESP8266 and ESP32 with signals from
265 remote controls (where available) and from the tranmitter in this repo. Issues
266 are listed below.
267
268 NEC: No issues.
269 Sony 12 and 15 bit: No issues.
270 Sony 20 bit: On ESP32 some errors occurred when repeats occurred.
271 Philips RC-5: On ESP32 with one remote control many errors occurred, but paired
272 with the transmitter in this repo it worked.
273 Philips RC-6: No issues. Only tested against the transmitter in this repo.
274
275 # 6. Principle of operation
276
277 Protocol classes inherit from the abstract base class `IR_RX`. This uses a pin
278 interrupt to store in an array the time (in μs) of each transition of the pulse
279 train from the receiver chip. Arrival of the first edge starts a software timer
280 which runs for the expected duration of an IR block (`tblock`). The use of a
281 software timer ensures that `.decode` and the user callback can allocate.
282
283 When the timer times out its callback (`.decode`) decodes the data. `.decode`
284 is a method of the protocol specific subclass; on completion it calls the
285 `do_callback` method of the ABC. This resets the edge reception and calls
286 either the user callback or the error function (if provided).
287
288 The size of the array and the duration of the timer are protocol dependent and
289 are set by the subclasses. The `.decode` method is provided in the subclass.
290
291 CPU times used by `.decode` (not including the user callback) were measured on
292 a Pyboard D SF2W at stock frequency. They were: NEC 1ms for normal data, 100μs
293 for a repeat code. Philips codes: RC-5 900μs, RC-6 mode 0 5.5ms.
294
295 # 7. Unsupported protocols
296
297 It is possible to capture an IR burst from a remote and to re-create it using
298 the transmitter. This has limitations and is discussed in detail in
299 [the transmitter doc](./TRANSMITTER.md#5-unsupported-protocols).
300
301 # Appendix 1 NEC Protocol description
302
303 A normal burst comprises exactly 68 edges, the exception being a repeat code
304 which has 4. An incorrect number of edges is treated as an error. All bursts
305 begin with a 9ms pulse. In a normal code this is followed by a 4.5ms space; a
306 repeat code is identified by a 2.25ms space. A data burst lasts for 67.5ms.
307
308 Data bits comprise a 562.5µs mark followed by a space whose length determines
309 the bit value. 562.5µs denotes 0 and 1.6875ms denotes 1.
310
311 In 8 bit address mode the complement of the address and data values is sent to
312 provide error checking. This also ensures that the number of 1's and 0's in a
313 burst is constant, giving a constant burst length of 67.5ms. In extended
314 address mode this constancy is lost. The burst length can (by my calculations)
315 run to 76.5ms.
316
317 # Appendix 2 MCE Protocol
318
319 The bitstream comprises a header (2ms mark, 1ms space) followed by 16 bits of
320 Manchester encoded data with a bit time of 500μs. Data are encoded
321 ```
322 ccccddddddppaaaa
323 ```
324 Where `aaaa` is the address, `pp` is the position (toggle) field, `dddddd` is
325 data and `cccc` is a checksum. This is calculated by counting the ones in
326 `ddddddppaaaa` and adding 4. Data are transmitted LSB first.
327
328 The only [doc](http://www.hifi-remote.com/johnsfine/DecodeIR.html#OrtekMCE) I
329 could find states that the checksum seed value is 3, but this did not match the
330 remote I have.