]> vault307.fbx.one Git - micorpython_ir.git/blob - RECEIVER.md
Doc improvements. Add acquire script.
[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 pin used to connect the decoder chip to the target is arbitrary. The test
19 program assumes pin X3 on the Pyboard, pin 23 on ESP32 and pin 13 on ESP8266.
20 On the WeMos D1 Mini the equivalent pin is D7.
21
22 A remote using the NEC protocol is [this one](https://www.adafruit.com/products/389).
23
24 # 2. Installation and demo scripts
25
26 The receiver is a Python package. This minimises RAM usage: applications only
27 import the device driver for the protocol in use. Clone the repository to the
28 current directory of your PC with:
29 ```bash
30 $ git clone https://github.com/peterhinch/micropython_ir
31 ```
32
33 Copy the following to the target filesystem:
34 1. `ir_rx` Directory and contents.
35
36 There are no dependencies.
37
38 ## 2.1 Test scripts
39
40 The demo can be used to characterise IR remotes where the protocol is known. It
41 displays the codes returned by each button. This can aid in the design of
42 receiver applications. The demo prints "running" every 5 seconds and reports
43 any data received from the remote.
44 ```python
45 from ir_rx.test import test
46 ```
47 Instructions will be displayed at the REPL.
48
49 If the protocol in use is unknown, there are two options: trial and error with
50 the above script or run the following:
51 ```python
52 from ir_rx.acquire import test
53 test()
54 ```
55 This script is under development.
56
57 It waits for a single burst from the remote and prints the timing of the pulses
58 followed by its best guess at the protocol. It correctly identifies supported
59 protocols, but can wrongly identify some unsupported proprietary protocols.
60
61 # 3. The driver
62
63 This implements a class for each supported protocol. Each class is subclassed
64 from a common abstract base class in `__init__.py`.
65
66 Applications should instantiate the appropriate class with a callback. The
67 callback will run whenever an IR pulse train is received. Example running on a
68 Pyboard:
69 ```python
70 import time
71 from machine import Pin
72 from pyb import LED
73 from ir_rx.nec import NEC_8 # NEC remote, 8 bit addresses
74
75 red = LED(1)
76
77 def callback(data, addr, ctrl):
78 if data < 0: # NEC protocol sends repeat codes.
79 print('Repeat code.')
80 else:
81 print('Data {:02x} Addr {:04x}'.format(data, addr))
82
83 ir = NEC_8(Pin('X3', Pin.IN), callback)
84 while True:
85 time.sleep_ms(500)
86 red.toggle()
87 ```
88
89 #### Common to all classes
90
91 Constructor args:
92 1. `pin` is a `machine.Pin` instance configured as an input, connected to the
93 IR decoder chip.
94 2. `callback` is the user supplied callback.
95 3. `*args` Any further args will be passed to the callback.
96
97 The user callback takes the following args:
98 1. `data` (`int`) Value from the remote. Normally in range 0-255. A value < 0
99 signifies an NEC repeat code.
100 2. `addr` (`int`) Address from the remote.
101 3. `ctrl` (`int`) The meaning of this is protocol dependent:
102 NEC: 0
103 Philips: this is toggled 1/0 on repeat button presses. If the button is held
104 down it is not toggled. The transmitter demo implements this behaviour.
105 Sony: 0 unless receiving a 20-bit stream, in which case it holds the extended
106 value.
107 4. Any args passed to the constructor.
108
109 Bound variable:
110 1. `verbose=False` If `True` emits debug output.
111
112 Methods:
113 1. `error_function` Arg: a function taking a single `int` arg. If specified
114 the function will be called if an error occurs. The arg value corresponds to
115 the error code. Typical usage might be to provide some user feedback of
116 incorrect reception although beware of occasional triggers by external events.
117 In my testing the TSOP4838 produces 200µs pulses on occasion for no obvious
118 reason. See [section 4](./RECEIVER.md#4-errors).
119 2. `close` No args. Shuts down the pin and timer interrupts.
120
121 A function is provided to print errors in human readable form. This may be
122 invoked as follows:
123
124 ```python
125 from ir_rx.print_error import print_error # Optional print of error codes
126 # Assume ir is an instance of an IR receiver class
127 ir.error_function(print_error)
128 ```
129 Class variables:
130 1. These are constants defining the NEC repeat code and the error codes sent
131 to the error function. They are discussed in [section 4](./RECEIVER.md#4-errors).
132
133 #### NEC classes
134
135 `NEC_8`, `NEC_16`
136
137 Typical invocation:
138 ```python
139 from ir_rx.nec import NEC_8
140 ```
141
142 Remotes using the NEC protocol can send 8 or 16 bit addresses. If the `NEC_16`
143 class receives an 8 bit address it will get a 16 bit value comprising the
144 address in bits 0-7 and its one's complement in bits 8-15.
145 The `NEC_8` class enables error checking for remotes that return an 8 bit
146 address: the complement is checked and the address returned as an 8-bit value.
147 A 16-bit address will result in an error.
148
149 #### Sony classes
150
151 `SONY_12`, `SONY_15`, `SONY_20`
152
153 Typical invocation:
154 ```python
155 from ir_rx.sony import SONY_15
156 ```
157
158 The SIRC protocol comes in 3 variants: 12, 15 and 20 bits. `SONY_20` handles
159 bitstreams from all three types of remote. Choosing a class matching the remote
160 improves the timing reducing the likelihood of errors when handling repeats: in
161 20-bit mode SIRC timing when a button is held down is tight. A worst-case 20
162 bit block takes 39ms nominal, yet the repeat time is 45ms nominal.
163 A single physical remote can issue more than one type of bitstream. The Sony
164 remote tested issued both 12 bit and 15 bit streams.
165
166 #### Philips classes
167
168 `RC5_IR`, `RC6_M0`
169
170 Typical invocation:
171 ```python
172 from ir_rx.philips import RC5_IR
173 ```
174
175 These support the RC-5 and RC-6 mode 0 protocols respectively.
176
177 # 4. Errors
178
179 IR reception is inevitably subject to errors, notably if the remote is operated
180 near the limit of its range, if it is not pointed at the receiver or if its
181 batteries are low. The user callback is not called when an error occurs.
182
183 On ESP8266 and ESP32 there is a further source of errors. This results from the
184 large and variable interrupt latency of the device which can exceed the pulse
185 duration. This causes pulses to be missed or their timing measured incorrectly.
186 On ESP8266 some improvment may be achieved by running the chip at 160MHz.
187
188 In general applications should provide user feedback of correct reception.
189 Users tend to press the key again if the expected action is absent.
190
191 In debugging a callback can be specified for reporting errors. The value passed
192 to the error function are represented by constants indicating the cause of the
193 error. These are driver ABC class variables and are as follows:
194
195 `BADSTART` A short (<= 4ms) start pulse was received. May occur due to IR
196 interference, e.g. from fluorescent lights. The TSOP4838 is prone to producing
197 200µs pulses on occasion, especially when using the ESP8266.
198 `BADBLOCK` A normal data block: too few edges received. Occurs on the ESP8266
199 owing to high interrupt latency.
200 `BADREP` A repeat block: an incorrect number of edges were received.
201 `OVERRUN` A normal data block: too many edges received.
202 `BADDATA` Data did not match check byte.
203 `BADADDR` (`NEC_IR`) If `extended` is `False` the 8-bit address is checked
204 against the check byte. This code is returned on failure.
205
206 # 5. Receiver platforms
207
208 Currently the ESP8266 suffers from [this issue](https://github.com/micropython/micropython/issues/5714).
209 Testing was therefore done without WiFi connectivity. If the application uses
210 the WiFi regularly, or if an external process pings the board repeatedly, the
211 crash does not occur.
212
213 Philips protocols (especially RC-6) have tight timing constraints with short
214 pulses whose length must be determined with reasonable accuracy. The Sony 20
215 bit protocol also has a timing issue in that the worst case bit pattern takes
216 39ms nominal, yet the repeat time is 45ms nominal. These issues can lead to
217 errors particularly on slower targets. As discussed above, errors are to be
218 expected. It is up to the user to decide if the error rate is acceptable.
219
220 Reception was tested using Pyboard D SF2W, ESP8266 and ESP32 with signals from
221 remote controls (where available) and from the tranmitter in this repo. Issues
222 are listed below.
223
224 NEC: No issues.
225 Sony 12 and 15 bit: No issues.
226 Sony 20 bit: On ESP32 some errors occurred when repeats occurred.
227 Philips RC-5: On ESP32 with one remote control many errors occurred, but paired
228 with the transmitter in this repo it worked.
229 Philips RC-6: No issues. Only tested against the transmitter in this repo.
230
231 # 6. Principle of operation
232
233 Protocol classes inherit from the abstract base class `IR_RX`. This uses a pin
234 interrupt to store in an array the time (in μs) of each transition of the pulse
235 train from the receiver chip. Arrival of the first edge starts a software timer
236 which runs for the expected duration of an IR block (`tblock`). The use of a
237 software timer ensures that `.decode` and the user callback can allocate.
238
239 When the timer times out its callback (`.decode`) decodes the data. `.decode`
240 is a method of the protocol specific subclass; on completion it calls the
241 `do_callback` method of the ABC. This resets the edge reception and calls
242 either the user callback or the error function (if provided).
243
244 The size of the array and the duration of the timer are protocol dependent and
245 are set by the subclasses. The `.decode` method is provided in the subclass.
246
247 CPU times used by `.decode` (not including the user callback) were measured on
248 a Pyboard D SF2W at stock frequency. They were: NEC 1ms for normal data, 100μs
249 for a repeat code. Philips codes: RC-5 900μs, RC-6 mode 0 5.5ms.
250
251 # 7. References
252
253 [General information about IR](https://www.sbprojects.net/knowledge/ir/)
254
255 The NEC protocol:
256 [altium](http://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol)
257 [circuitvalley](http://www.circuitvalley.com/2013/09/nec-protocol-ir-infrared-remote-control.html)
258
259 Philips protocols:
260 [RC5](https://en.wikipedia.org/wiki/RC-5)
261 [RC5](https://www.sbprojects.net/knowledge/ir/rc5.php)
262 [RC6](https://www.sbprojects.net/knowledge/ir/rc6.php)
263
264 Sony protocol:
265 [SIRC](https://www.sbprojects.net/knowledge/ir/sirc.php)
266
267 # Appendix 1 NEC Protocol description
268
269 A normal burst comprises exactly 68 edges, the exception being a repeat code
270 which has 4. An incorrect number of edges is treated as an error. All bursts
271 begin with a 9ms pulse. In a normal code this is followed by a 4.5ms space; a
272 repeat code is identified by a 2.25ms space. A data burst lasts for 67.5ms.
273
274 Data bits comprise a 562.5µs mark followed by a space whose length determines
275 the bit value. 562.5µs denotes 0 and 1.6875ms denotes 1.
276
277 In 8 bit address mode the complement of the address and data values is sent to
278 provide error checking. This also ensures that the number of 1's and 0's in a
279 burst is constant, giving a constant burst length of 67.5ms. In extended
280 address mode this constancy is lost. The burst length can (by my calculations)
281 run to 76.5ms.