]> vault307.fbx.one Git - micorpython_ir.git/commitdiff
TX and RX support NEC, RC5 and RC6 mode 0.
authorPeter Hinch <peter@hinch.me.uk>
Wed, 26 Feb 2020 13:57:15 +0000 (13:57 +0000)
committerPeter Hinch <peter@hinch.me.uk>
Wed, 26 Feb 2020 13:57:15 +0000 (13:57 +0000)
README.md
images/circuit.png [new file with mode: 0644]
images/circuit2.png [new file with mode: 0644]
images/circuits.fzz [new file with mode: 0644]
ir_rx.py
ir_rx_test.py
ir_tx.py
ir_tx_test.py

index 03e013e758efcd39a759681282f518601865b72c..3a92dce1971389e8632ef70f19d177c527d405ef 100644 (file)
--- a/README.md
+++ b/README.md
 
 This repo provides a driver to receive from IR (infra red) remote controls and
 a driver for IR "blaster" apps. The device drivers are nonblocking. They do not
 
 This repo provides a driver to receive from IR (infra red) remote controls and
 a driver for IR "blaster" apps. The device drivers are nonblocking. They do not
-require `uasyncio` but are entirely compatible with it.
+require `uasyncio` but are compatible with it.
+
+# 1. IR communication
 
 IR communication uses a carrier frequency to pulse the IR source. Modulation
 
 IR communication uses a carrier frequency to pulse the IR source. Modulation
-takes the form of OOK (on-off keying). There are a several mutually
-incompatible protocols and at least two options for carrier frequency, namely
-36KHz and 38KHz.
+takes the form of OOK (on-off keying). There are multiple protocols and at
+least two options for carrier frequency, namely 36KHz and 38KHz.
 
 The drivers support the NEC protocol and two Philips protocols, namely RC-5 and
 RC-6 mode 0. In the case of the transmitter the carrier frequency is a runtime
 
 The drivers support the NEC protocol and two Philips protocols, namely RC-5 and
 RC-6 mode 0. In the case of the transmitter the carrier frequency is a runtime
-parameter so any value may be used. The receiver uses a hardware demodulator
-which must be specified for the correct frequency. The device driver is carrier
-frequency agnostic.
+parameter: any value may be specified. The receiver uses a hardware demodulator
+which must be specified for the correct frequency. The receiver device driver
+sees the demodulated signal and is hence carrier frequency agnostic.
+
+Examining waveforms from various remote controls it is evident that numerous
+protocols exist. Some are doubtless proprietary and undocumented. The supported
+protocols are those for which I managed to locate documentation. My preference
+is for the NEC version. It has conservative timing and ample scope for error
+detection. RC-5 has limited error detection, and RC-6 mode 0 has rather fast
+timing: I doubt that detection can be accomplished on targets slower than a
+Pyboard.
+
+A remote using the NEC protocol is [this one](https://www.adafruit.com/products/389).
 
 
-# Hardware Requirements
+Remotes normally transmit an address and a data byte. The address denotes the
+physical device being controlled. The data is associated with the button on the
+remote. Provision exists for differentiating between a button repeatedly
+pressed and one which is held down; the mechanism is protocol dependent.
+
+# 2. Hardware Requirements
 
 The receiver is cross-platform. It requires an IR receiver chip to demodulate
 
 The receiver is cross-platform. It requires an IR receiver chip to demodulate
-the carrier. There are two options for carrier frequency: 36KHz and 38KHz. The
-chip must be selected for the frequency in use by the remote. 
+the carrier. The chip must be selected for the frequency in use by the remote.
+For 38KHz devices a receiver chip such as the Vishay TSOP4838 or the
+[adafruit one](https://www.adafruit.com/products/157) is required. This
+demodulates the 38KHz IR pulses and passes the demodulated pulse train to the
+microcontroller. The tested chip returns a 0 level on carrier detect, but the
+driver design should ensure operation regardless of sense.
+
+The pin used to connect the decoder chip to the target is arbitrary but the
+test programs assume pin X3 on the Pyboard, pin 13 on the ESP8266 and pin 23 on
+ESP32.
 
 The transmitter requires a Pyboard 1.x (not Lite) or a Pyboard D. Output is via
 an IR LED which will normally need a transistor to provide sufficient current.
 
 The transmitter requires a Pyboard 1.x (not Lite) or a Pyboard D. Output is via
 an IR LED which will normally need a transistor to provide sufficient current.
+Typically these need 50-100mA of drive to achieve reasonable range and data
+integrity. A suitable LED is [this one](https://www.adafruit.com/product/387).
 
 
-# Decoder for IR Remote Controls using the NEC protocol
+The transmitter test script assumes pin X1 for IR output. It can be changed,
+but it must support Timer 2 channel 1. Pins for pushbutton inputs are
+arbitrary: X3 and X4 are used.
 
 
-This protocol is widely used. An example remote is [this one](https://www.adafruit.com/products/389).
-To interface the device a receiver chip such as the Vishay TSOP4838 or the
-[adafruit one](https://www.adafruit.com/products/157) is required. This
-demodulates the 38KHz IR pulses and passes the demodulated pulse train to the
-microcontroller.
+# 3. Installation
 
 
-The driver and test programs run on the Pyboard and ESP8266.
+On import, demos print an explanation of how to run them.
 
 
-# Files
+## 3.1 Receiver
 
 
- 1. `aremote.py` The device driver.
- 2. `art.py` A test program to characterise a remote.
- 3. `art1.py` Control an onboard LED using a remote. The data and addresss
- values need changing to match your characterised remote.
+Copy the following files to the target filesystem:
+ 1. `ir_rx.py` The receiver device driver.
+ 2. `ir_rx_test.py` Demo of a receiver.
 
 
-# Dependencies
+There are no dependencies.
 
 
-The driver requires the `uasyncio` library and the file `asyn.py` from this
-repository.
+The demo can be used to characterise IR remotes. It displays the codes returned
+by each button. This can aid in the design of receiver applications. When the
+demo runs, the REPL prompt reappears: this is because it sets up an ISR context
+and returns. Press `ctrl-d` to cancel it. A real application would run code
+after initialising reception so this behaviour would not occur.
 
 
-# Usage
+## 3.2 Transmitter
 
 
-The pin used to connect the decoder chip to the target is arbitrary but the
-test programs assume pin X3 on the Pyboard and pin 13 on the ESP8266.
+Copy the following files to the Pyboard filesystem:
+ 1. `ir_tx.py` The transmitter device driver.
+ 2. `ir_tx_test.py` Demo of a 2-button remote controller.
+
+The device driver has no dependencies. The test program requires `uasyncio`
+from the official library and `aswitch.py` from
+[this repo](https://github.com/peterhinch/micropython-async).
 
 
-The driver is event driven. Pressing a button on the remote causes a user
-defined callback to be run. The NEC protocol returns a data value and an
-address. These are passed to the callback as the first two arguments (further
-user defined arguments may be supplied). The address is normally constant for a
-given remote, with the data corresponding to the button. Applications should
-check the address to ensure that they only respond to the correct remote.
+# 4. Receiver
 
 
-Data values are 8 bit. Addresses may be 8 or 16 bit depending on whether the
-remote uses extended addressing.
+This implements a class for each supported protocol, namely `NEC_IR`, `RC5_IR`
+and `RC6_M0`. Applications should instantiate the appropriate class with a
+callback. The callback will run whenever an IR pulsetrain is received.
 
 
-If a button is held down a repeat code is sent. In this event the driver
-returns a data value of `REPEAT` and the address associated with the last
-valid data block.
+Constructor:  
+`NEC_IR` args: `pin`, `callback`, `extended=True`, `*args`  
+`RC5_IR` and `RC6_M0`: args `pin`, `callback`, `*args`  
+Args:  
+ 1. `pin` is a `machine.Pin` instance configured as an input, connected to the
+ IR decoder chip.  
+ 2. `callback` is the user supplied callback (see below).
+ 3. `extended` is an NEC specific boolean. Remotes using the NEC protocol can
+ send 8 or 16 bit addresses. If `True` 16 bit addresses are assumed - an 8 bit
+ address will be correctly received. Set `False` to enable extra error checking
+ for remotes that return an 8 bit address.
+ 4. `*args` Any further args will be passed to the callback.  
 
 
-To characterise a remote run `art.py` and note the data value for each button
-which is to be used. If the address is less than 256, extended addressing is
-not in use.
+The callback takes the following args:  
+ 1. `data` Integer value fom the remote. A negative value indicates an error
+ except for the value of -1 which signifies an NEC repeat code (see below).
+ 2. `addr` Address from the remote
+ 3. `ctrl` 0 in the case of NEC. Philips protocols toggle this bit on repeat
+ button presses. If the button is held down the bit is not toggled. The
+ transmitter demo implements this behaviour.
+ 4. Any args passed to the constructor.
 
 
-# Reliability
+Class variable:  
+ 1. `verbose=False` If `True` emits debug output.
+
+# 4.1 Errors
 
 IR reception is inevitably subject to errors, notably if the remote is operated
 near the limit of its range, if it is not pointed at the receiver or if its
 batteries are low. So applications must check for, and usually ignore, errors.
 
 IR reception is inevitably subject to errors, notably if the remote is operated
 near the limit of its range, if it is not pointed at the receiver or if its
 batteries are low. So applications must check for, and usually ignore, errors.
-These are flagged by data values < `REPEAT`.
+These are flagged by data values < `REPEAT` (-1).
 
 On the ESP8266 there is a further source of errors. This results from the large
 and variable interrupt latency of the device which can exceed the pulse
 
 On the ESP8266 there is a further source of errors. This results from the large
 and variable interrupt latency of the device which can exceed the pulse
@@ -82,34 +126,134 @@ duration. This causes pulses to be missed. This tendency is slightly reduced by
 running the chip at 160MHz.
 
 In general applications should provide user feedback of correct reception.
 running the chip at 160MHz.
 
 In general applications should provide user feedback of correct reception.
-Users tend to press the key again if no acknowledgement is received.
+Users tend to press the key again if the expected action is absent.
+
+Data values passed to the callback are normally positive. Negative values
+indicate a repeat code or an error.
+
+`REPEAT` A repeat code was received.
+
+Any data value < `REPEAT` denotes an error. In general applications do not
+need to decode these, but they may be of use in debugging. For completeness
+they are listed below.
+
+`BADSTART` A short (<= 4ms) start pulse was received. May occur due to IR
+interference, e.g. from fluorescent lights. The TSOP4838 is prone to producing
+200µs pulses on occasion, especially when using the ESP8266.  
+`BADBLOCK` A normal data block: too few edges received. Occurs on the ESP8266
+owing to high interrupt latency.  
+`BADREP` A repeat block: an incorrect number of edges were received.  
+`OVERRUN` A normal data block: too many edges received.  
+`BADDATA` Data did not match check byte.  
+`BADADDR` Where `extended` is `False` the 8-bit address is checked
+against the check byte. This code is returned on failure.  
+
+# 4.2 Receiver platforms
+
+The NEC protocol has been tested against Pyboard, ESP8266 and ESP32 targets.
+The Philips protocols - especially RC-6 - have tighter timing constraints. I
+have not yet tested these, but I anticipate problems.
+
+# 4.3 Principle of operation
 
 
-# The NEC_IR class
+Protocol classes inherit from the abstract base class `IR_RX`. This uses a pin
+interrupt to store in an array the start and end times of pulses (in μs).
+Arrival of the first pulse triggers a software timer which runs for the
+expected duration of an IR block (`tblock`). When it times out its callback
+(`.decode`) decodes the data and calls the user callback. The use of a software
+timer ensures that `.decode` and the user callback can allocate.
 
 
-The constructor takes the following positional arguments.
+The size of the array and the duration of the timer are protocol dependent and
+are set by the subclasses. The `.decode` method is provided in the subclass.
 
 
- 1. `pin` A `Pin` instance for the decoder chip.
- 2. `cb` The user callback function.
- 3. `extended` Set `False` to enable extra error checking if the remote
- returns an 8 bit address.
- 4. Further arguments, if provided, are passed to the callback.
+CPU times used by `.decode` (not including the user callback) were measured on
+a Pyboard D SF2W at stock frequency. They were NEC 1ms for normal data, 100μs
+for a repeat code. Philips codes: RC-5 900μs, RC-6 mode 0 5.5ms.
 
 
-The callback receives the following positional arguments:
+# 5 Transmitter
 
 
- 1. The data value returned from the remote.
- 2. The address value returned from the remote.
- 3. Any further arguments provided to the `NEC_IR` constructor.
+This is specific to Pyboard D and Pyboard 1.x (not Lite).
 
 
-Negative data values are used to signal repeat codes and transmission errors.
+It implements a class for each supported protocol, namely `NEC`, `RC5` and
+`RC6_M0`. The application instantiates the appropriate class and calls the
+`transmit` method to send data.
 
 
-The test program `art1.py` provides an example of a minimal application.
+Constructor  
+All constructors take the following args:  
+ 1. `pin` An initialised `pyb.Pin` instance supporting Timer 2 channel 1: `X1`
+ is employed by the test script. Must be connected to the IR diode as described
+ below.
+ 2. `freq=default` The carrier frequency in Hz. The default for NEC is 38000,
+ and for Philips is 36000.
+ 3. `verbose=False` If `True` emits debug output.
 
 
-# How it works
+Method:
+ 1. `transmit(addr, data, toggle=0)` Integer args. `addr` and `data` are
+ normally 8-bit values and `toggle` is 0 or 1.  
+ In the case of NEC, if an address < 256 is passed, normal mode is assumed and
+ the complementary value is appended. 16-bit values are transmitted as extended
+ addresses.  
+ In the case of NEC the `toggle` value is ignored. For Philips protocols it
+ should be toggled each time a button is pressed, and retained if the button is
+ held down. The test program illustrates a way to do this.
 
 
-The NEC protocol is described in these references.  
+The `transmit` method is synchronous with rapid return. Actual transmission
+occurs as a background process, controlled by timers 2 and 5. Execution times
+on a Pyboard 1.1 were 3.3ms for NEC, 1.5ms for RC5 and 2ms for RC6.
+
+# 5.1 Wiring
+
+I use the following circuit which delivers just under 40mA to the diode. R2 may
+be reduced for higher current.  
+![Image](images/circuit.png)
+
+This alternative delivers a constant current of about 53mA if a higher voltage
+than 5V is available. R4 determines the current value and may be reduced to
+increase power.  
+![Image](images/circuit2.png)
+
+The transistor type is not critical.
+
+These circuits assume circuits as shown. Here the carrier "off" state is 0V,
+which is the driver default. If using a circuit where "off" is required to be
+3.3V, the constant `_SPACE` in `ir_tx.py` should be changed to 100.
+
+# 5.2 Principle of operation
+
+The classes inherit from the abstract base class `IR`. This has an array `.arr`
+to contain the duration (in μs) of each carrier on or off period. The
+`transmit` method calls a `tx` method in the subclass which populates this
+array. On completion `transmit` appends a special `STOP` value and initiates
+physical transmission which occurs in an interrupt context.
+
+This is performed by two hardware timers initiated in the constructor. Timer 2,
+channel 1 is used to configure the output pin as a PWM channel. Its frequency
+is set in the constructor. The OOK is performed by dynamically changing the
+duty ratio using the timer channel's `pulse_width_percent` method: this varies
+the pulse width from 0 to a duty ratio passed to the constructor. The NEC
+protocol defaults to 50%, the Philips ones to 30%.
+
+The duty ratio is changed by the Timer 5 callback `._cb`. This retrieves the
+next duration from the array. If it is not `STOP` it toggles the duty cycle
+and re-initialises T5 for the new duration.
+
+The `IR.append` enables times to be added to the array, keeping track of the
+notional carrier on/off state for biphase generation. The `IR.add` method
+facilitates lengthening a pulse as required in the biphase sequences used in
+Philips protocols.
+
+# 6. References
+
+The NEC protocol is described in these references:  
 [altium](http://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol)  
 [circuitvalley](http://www.circuitvalley.com/2013/09/nec-protocol-ir-infrared-remote-control.html)
 
 [altium](http://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol)  
 [circuitvalley](http://www.circuitvalley.com/2013/09/nec-protocol-ir-infrared-remote-control.html)
 
+The Philips protocols may be found in these refs:  
+[RC5](https://en.wikipedia.org/wiki/RC-5)  
+[RC6](https://www.sbprojects.net/knowledge/ir/rc6.php)
+
+# Appendix 1 NEC Protocol description
+
 A normal burst comprises exactly 68 edges, the exception being a repeat code
 which has 4. An incorrect number of edges is treated as an error. All bursts
 begin with a 9ms pulse. In a normal code this is followed by a 4.5ms space; a
 A normal burst comprises exactly 68 edges, the exception being a repeat code
 which has 4. An incorrect number of edges is treated as an error. All bursts
 begin with a 9ms pulse. In a normal code this is followed by a 4.5ms space; a
@@ -135,25 +279,3 @@ any asyncio latency when setting its delay period.
 The algorithm promotes interrupt handler speed over RAM use: the 276 bytes used
 for the data array could be reduced to 69 bytes by computing and saving deltas
 in the interrupt service routine.
 The algorithm promotes interrupt handler speed over RAM use: the 276 bytes used
 for the data array could be reduced to 69 bytes by computing and saving deltas
 in the interrupt service routine.
-
-# Error returns
-
-Data values passed to the callback are normally positive. Negative values
-indicate a repeat code or an error.
-
-`REPEAT` A repeat code was received.
-
-Any data value < `REPEAT` denotes an error. In general applications do not
-need to decode these, but they may be of use in debugging. For completeness
-they are listed below.
-
-`BADSTART` A short (<= 4ms) start pulse was received. May occur due to IR
-interference, e.g. from fluorescent lights. The TSOP4838 is prone to producing
-200µs pulses on occasion, especially when using the ESP8266.  
-`BADBLOCK` A normal data block: too few edges received. Occurs on the ESP8266
-owing to high interrupt latency.  
-`BADREP` A repeat block: an incorrect number of edges were received.  
-`OVERRUN` A normal data block: too many edges received.  
-`BADDATA` Data did not match check byte.  
-`BADADDR` Where `extended` is `False` the 8-bit address is checked
-against the check byte. This code is returned on failure.  
diff --git a/images/circuit.png b/images/circuit.png
new file mode 100644 (file)
index 0000000..132f939
Binary files /dev/null and b/images/circuit.png differ
diff --git a/images/circuit2.png b/images/circuit2.png
new file mode 100644 (file)
index 0000000..de65dc6
Binary files /dev/null and b/images/circuit2.png differ
diff --git a/images/circuits.fzz b/images/circuits.fzz
new file mode 100644 (file)
index 0000000..9ad4333
Binary files /dev/null and b/images/circuits.fzz differ
index 896d9cdb4c5269931d90e77baf040dae509a1102..6c484bc26c100cf0d9958e331af1aecba74d59e3 100644 (file)
--- a/ir_rx.py
+++ b/ir_rx.py
@@ -40,6 +40,7 @@ BADADDR = -7
 # a block start and a repeat code start (~108ms depending on protocol)
 
 class IR_RX():
 # a block start and a repeat code start (~108ms depending on protocol)
 
 class IR_RX():
+    verbose = False
     def __init__(self, pin, nedges, tblock, callback, *args):  # Optional args for callback
         self._nedges = nedges
         self._tblock = tblock
     def __init__(self, pin, nedges, tblock, callback, *args):  # Optional args for callback
         self._nedges = nedges
         self._tblock = tblock
@@ -55,7 +56,7 @@ class IR_RX():
             pin.irq(handler = self._cb_pin, trigger = (Pin.IRQ_FALLING | Pin.IRQ_RISING), hard = True)
         self.edge = 0
         self.tim = Timer(-1)  # Sofware timer
             pin.irq(handler = self._cb_pin, trigger = (Pin.IRQ_FALLING | Pin.IRQ_RISING), hard = True)
         self.edge = 0
         self.tim = Timer(-1)  # Sofware timer
-        self.cb = self._decode
+        self.cb = self.decode
 
 
     # Pin interrupt. Save time of each edge for later decode.
 
 
     # Pin interrupt. Save time of each edge for later decode.
@@ -69,60 +70,57 @@ class IR_RX():
             self.edge += 1
 
 class NEC_IR(IR_RX):
             self.edge += 1
 
 class NEC_IR(IR_RX):
-    def __init__(self, pin, callback, extended, *args):
+    def __init__(self, pin, callback, extended=True, *args):
         # Block lasts <= 80ms and has 68 edges
         tblock = 80 if extended else 73  # Allow for some tx tolerance (?)
         super().__init__(pin, 68, tblock, callback, *args)
         self._extended = extended
         self._addr = 0
 
         # Block lasts <= 80ms and has 68 edges
         tblock = 80 if extended else 73  # Allow for some tx tolerance (?)
         super().__init__(pin, 68, tblock, callback, *args)
         self._extended = extended
         self._addr = 0
 
-    def _decode(self, _):
-        overrun = self.edge > 68
-        val = OVERRUN if overrun else BADSTART
-        if not overrun:
+    def decode(self, _):
+        try:
+            if self.edge > 68:
+                raise RuntimeError(OVERRUN)
             width = ticks_diff(self._times[1], self._times[0])
             width = ticks_diff(self._times[1], self._times[0])
-            if width > 4000:  # 9ms leading mark for all valid data
-                width = ticks_diff(self._times[2], self._times[1])
-                if width > 3000: # 4.5ms space for normal data
-                    if self.edge < 68:
-                        # Haven't received the correct number of edges
-                        val = BADBLOCK
-                    else:
-                        # Time spaces only (marks are always 562.5µs)
-                        # Space is 1.6875ms (1) or 562.5µs (0)
-                        # Skip last bit which is always 1
-                        val = 0
-                        for edge in range(3, 68 - 2, 2):
-                            val >>= 1
-                            if ticks_diff(self._times[edge + 1], self._times[edge]) > 1120:
-                                val |= 0x80000000
-                elif width > 1700: # 2.5ms space for a repeat code. Should have exactly 4 edges.
-                    val = REPEAT if self.edge == 4 else BADREP
-        addr = 0
-        if val >= 0:  # validate. Byte layout of val ~cmd cmd ~addr addr
-            addr = val & 0xff
-            cmd = (val >> 16) & 0xff
-            if addr == ((val >> 8) ^ 0xff) & 0xff:  # 8 bit address OK
-                val = cmd if cmd == (val >> 24) ^ 0xff else BADDATA
-                self._addr = addr
+            if width < 4000:  # 9ms leading mark for all valid data
+                raise RuntimeError(BADSTART)
+            width = ticks_diff(self._times[2], self._times[1])
+            if width > 3000:  # 4.5ms space for normal data
+                if self.edge < 68:  # Haven't received the correct number of edges
+                    raise RuntimeError(BADBLOCK)
+                # Time spaces only (marks are always 562.5µs)
+                # Space is 1.6875ms (1) or 562.5µs (0)
+                # Skip last bit which is always 1
+                val = 0
+                for edge in range(3, 68 - 2, 2):
+                    val >>= 1
+                    if ticks_diff(self._times[edge + 1], self._times[edge]) > 1120:
+                        val |= 0x80000000
+            elif width > 1700: # 2.5ms space for a repeat code. Should have exactly 4 edges.
+                raise RuntimeError(REPEAT if self.edge == 4 else BADREP)  # Treat REPEAT as error.
             else:
             else:
+                raise RuntimeError(BADSTART)
+            addr = val & 0xff  # 8 bit addr
+            cmd = (val >> 16) & 0xff
+            if cmd != (val >> 24) ^ 0xff:
+                raise RuntimeError(BADDATA)
+            if addr != ((val >> 8) ^ 0xff) & 0xff:  # 8 bit addr doesn't match check
+                if not self._extended:
+                    raise RuntimeError(BADADDR)
                 addr |= val & 0xff00  # pass assumed 16 bit address to callback
                 addr |= val & 0xff00  # pass assumed 16 bit address to callback
-                if self._extended:
-                    val = cmd if cmd == (val >> 24) ^ 0xff else BADDATA
-                    self._addr = addr
-                else:
-                    val = BADADDR
-        if val == REPEAT:
-            addr = self._addr  # Last valid addresss
+            self._addr = addr
+        except RuntimeError as e:
+            cmd = e.args[0]
+            addr = self._addr if cmd == REPEAT else 0  # REPEAT uses last address
         self.edge = 0  # Set up for new data burst and run user callback
         self.edge = 0  # Set up for new data burst and run user callback
-        self.callback(val, addr, *self.args)
+        self.callback(cmd, addr, 0, *self.args)
 
 class RC5_IR(IR_RX):
     def __init__(self, pin, callback, *args):
         # Block lasts <= 30ms and has <= 28 edges
         super().__init__(pin, 28, 30, callback, *args)
 
 
 class RC5_IR(IR_RX):
     def __init__(self, pin, callback, *args):
         # Block lasts <= 30ms and has <= 28 edges
         super().__init__(pin, 28, 30, callback, *args)
 
-    def _decode(self, _):
+    def decode(self, _):
         try:
             nedges = self.edge  # No. of edges detected
             if not 14 <= nedges <= 28:
         try:
             nedges = self.edge  # No. of edges detected
             if not 14 <= nedges <= 28:
@@ -138,7 +136,7 @@ class RC5_IR(IR_RX):
                     bits <<= 1
                     bits |= bit
                 bit ^= 1
                     bits <<= 1
                     bits |= bit
                 bit ^= 1
-            #print(bin(bits))  # Matches inverted scope waveform
+            self.verbose and print(bin(bits))  # Matches inverted scope waveform
             # Decode Manchester code
             x = 30
             while not bits >> x:
             # Decode Manchester code
             x = 30
             while not bits >> x:
@@ -174,60 +172,63 @@ class RC6_M0(IR_RX):
         # Block lasts 23ms nominal and has <=44 edges
         super().__init__(pin, 44, 30, callback, *args)
 
         # Block lasts 23ms nominal and has <=44 edges
         super().__init__(pin, 44, 30, callback, *args)
 
-    def _decode(self, _):
+    def decode(self, _):
         try:
             nedges = self.edge  # No. of edges detected
             if not 22 <= nedges <= 44:
                 raise RuntimeError(OVERRUN if nedges > 28 else BADSTART)
             for x, lims in enumerate(self.hdr):
                 width = ticks_diff(self._times[x + 1], self._times[x])
         try:
             nedges = self.edge  # No. of edges detected
             if not 22 <= nedges <= 44:
                 raise RuntimeError(OVERRUN if nedges > 28 else BADSTART)
             for x, lims in enumerate(self.hdr):
                 width = ticks_diff(self._times[x + 1], self._times[x])
-                #print('x = {}, width = {}, lims = {}'.format(x, width, lims))
                 if not (lims[0] < width < lims[1]):
                 if not (lims[0] < width < lims[1]):
-                    #print('Bad start', x, width, lims)
+                    self.verbose and print('Bad start', x, width, lims)
                     raise RuntimeError(BADSTART)
             x += 1
             width = ticks_diff(self._times[x + 1], self._times[x])
                     raise RuntimeError(BADSTART)
             x += 1
             width = ticks_diff(self._times[x + 1], self._times[x])
-            # Long bit is 889μs (0) or 1333μs (1)
-            ctrl = width > 1111  # If 1333, ctrl == True and carrier is off
-            start = x + 2 if ctrl else x + 3 # Skip 2nd long bit
-
-            # Regenerate bitstream
-            bits = 1  # MSB is a dummy 1 to mark start of bitstream
-            bit = int(ctrl)
-            for x in range(start, nedges - 1):
+            # 2nd bit of last 0 is 444μs (0) or 1333μs (1)
+            if not 222 < width < 1555:
+                self.verbose and print('Bad block 1 Width', width, 'x', x)
+                raise RuntimeError(BADBLOCK)
+            short = width < 889
+            v = int(not short)
+            bit = v
+            bits = 1  # Bits decoded
+            x += 1 + int(short)
+            width = ticks_diff(self._times[x + 1], self._times[x])
+            if not 222 < width < 1555:
+                self.verbose and print('Bad block 2 Width', width, 'x', x)
+                raise RuntimeError(BADBLOCK)
+            short = width < 1111
+            if not short:
+                bit ^= 1
+            x += 1 + int(short)  # If it's short, we know width of next
+            v <<= 1
+            v |= bit  # MSB of result
+            bits += 1
+            # Decode bitstream
+            while bits < 17:
+                # -1 convert count to index, -1 because we look ahead
+                if x > nedges - 2:
+                    raise RuntimeError(BADBLOCK)
+                # width is 444/889 nominal
                 width = ticks_diff(self._times[x + 1], self._times[x])
                 width = ticks_diff(self._times[x + 1], self._times[x])
-                if not 222 < width < 1333:
-                    #print('Width', width, 'x', x)
+                if not 222 < width < 1111:
+                    self.verbose and print('Bad block 3 Width', width, 'x', x)
                     raise RuntimeError(BADBLOCK)
                     raise RuntimeError(BADBLOCK)
-                for _ in range(1 if width < 666 else 2):
-                    bits <<= 1
-                    bits |= bit
-                bit ^= 1
-            print('36-bit format {:036b} x={} nedges={}'.format(bits, x, nedges))
-
-            # Decode Manchester code. Bitstream varies in length: find MS 1.
-            x = 36
-            while not bits >> x:
-                x -= 1
-            # Now points to dummy 1
-            x -= 2  # Point to MS biphase pair
-            m0 = 1 << x
-            m1 = m0 << 1  # MSB of pair
-            v = 0  # 16 bit bitstream
-            for _ in range(16):
+                short = width < 666
+                if not short:
+                    bit ^= 1
                 v <<= 1
                 v <<= 1
-                b0 = (bits & m0) > 0
-                b1 = (bits & m1) > 0
-                print(int(b1), int(b0))
-                if b0 == b1:
-                    raise RuntimeError(BADBLOCK)
-                v |= b1
-                m0 >>= 2
-                m1 >>= 2
-            # Split into fields (val, addr)
+                v |= bit
+                bits += 1
+                x += 1 + int(short)
+
+            if self.verbose:
+                 ss = '20-bit format {:020b} x={} nedges={} bits={}'
+                 print(ss.format(v, x, nedges, bits))
+
             val = v & 0xff
             addr = (v >> 8) & 0xff
             val = v & 0xff
             addr = (v >> 8) & 0xff
-
+            ctrl = (v >> 16) & 1
         except RuntimeError as e:
             val, addr, ctrl = e.args[0], 0, 0
         self.edge = 0  # Set up for new data burst and run user callback
         except RuntimeError as e:
             val, addr, ctrl = e.args[0], 0, 0
         self.edge = 0  # Set up for new data burst and run user callback
index 401c077eae6d5ec3e4a90f55770f9be5906e0b03..82f97dd0862cedbdbc265f1ad04a215bdc0e1932 100644 (file)
@@ -46,11 +46,12 @@ print(s)
 
 def test(proto=0):
     if proto == 0:
 
 def test(proto=0):
     if proto == 0:
-        ir = NEC_IR(p, cb, True, 0)  # Extended mode, dummy ctrl arg for callback
+        ir = NEC_IR(p, cb)  # Extended mode
     elif proto == 5:
         ir = RC5_IR(p, cb)
     elif proto == 6:
         ir = RC6_M0(p, cb)
     elif proto == 5:
         ir = RC5_IR(p, cb)
     elif proto == 6:
         ir = RC6_M0(p, cb)
+        ir.verbose = True
     # A real application would do something here...
     #while True:
         #time.sleep(5)
     # A real application would do something here...
     #while True:
         #time.sleep(5)
index 0697d9a1cdd9a6541f70dc0d8881501fe4158f3e..a1cc9e9859d03a4d2d64b1b7da711f8eb7f79ceb 100644 (file)
--- a/ir_tx.py
+++ b/ir_tx.py
@@ -6,7 +6,6 @@
 # Copyright (c) 2020 Peter Hinch
 
 from pyb import Pin, Timer
 # Copyright (c) 2020 Peter Hinch
 
 from pyb import Pin, Timer
-from time import sleep_us, sleep
 from micropython import const
 from array import array
 import micropython
 from micropython import const
 from array import array
 import micropython
@@ -27,18 +26,16 @@ _T2_RC6 = const(889)
 
 # IR abstract base class. Array holds periods in μs between toggling 36/38KHz
 # carrier on or off. Physical transmission occurs in an ISR context controlled
 
 # IR abstract base class. Array holds periods in μs between toggling 36/38KHz
 # carrier on or off. Physical transmission occurs in an ISR context controlled
-# by timer 2 and timer 5.
-# Operation is in two phases: .transmit populates .arr with times in μs (via
-# subclass), then initiates physical transmission.
+# by timer 2 and timer 5. See README.md for details of operation.
 class IR:
 
     def __init__(self, pin, freq, asize, duty, verbose):
         tim = Timer(2, freq=freq)  # Timer 2/pin produces 36/38KHz carrier
         self._ch = tim.channel(1, Timer.PWM, pin=pin)
         self._ch.pulse_width_percent(_SPACE)  # Turn off IR LED
 class IR:
 
     def __init__(self, pin, freq, asize, duty, verbose):
         tim = Timer(2, freq=freq)  # Timer 2/pin produces 36/38KHz carrier
         self._ch = tim.channel(1, Timer.PWM, pin=pin)
         self._ch.pulse_width_percent(_SPACE)  # Turn off IR LED
-        self._duty = duty
+        self._duty = duty if not _SPACE else (100 - duty)
         self._tim = Timer(5)  # Timer 5 controls carrier on/off times
         self._tim = Timer(5)  # Timer 5 controls carrier on/off times
-        self._tcb = self._cb
+        self._tcb = self.cb  # Pre-allocate
         self.verbose = verbose
         self.arr = array('H', 0 for _ in range(asize))  # on/off times (μs)
         self.carrier = False  # Notional carrier state while encoding biphase
         self.verbose = verbose
         self.arr = array('H', 0 for _ in range(asize))  # on/off times (μs)
         self.carrier = False  # Notional carrier state while encoding biphase
@@ -51,9 +48,9 @@ class IR:
         self.tx(addr, data, toggle)
         self.append(_STOP)
         self.aptr = 0  # Reset pointer
         self.tx(addr, data, toggle)
         self.append(_STOP)
         self.aptr = 0  # Reset pointer
-        self._cb(self._tim)  # Initiate physical transmission.
+        self.cb(self._tim)  # Initiate physical transmission.
 
 
-    def _cb(self, t):  # T5 callback, generate a carrier mark or space
+    def cb(self, t):  # T5 callback, generate a carrier mark or space
         t.deinit()
         p = self.aptr
         v = self.arr[p]
         t.deinit()
         p = self.aptr
         v = self.arr[p]
@@ -88,18 +85,20 @@ class NEC(IR):
         self.append(9000, 4500)
         if addr < 256:  # Short address: append complement
             addr |= ((addr ^ 0xff) << 8)
         self.append(9000, 4500)
         if addr < 256:  # Short address: append complement
             addr |= ((addr ^ 0xff) << 8)
-        for x in range(16):
+        for _ in range(16):
             self._bit(addr & 1)
             addr >>= 1
         data |= ((data ^ 0xff) << 8)
             self._bit(addr & 1)
             addr >>= 1
         data |= ((data ^ 0xff) << 8)
-        for x in range(16):
+        for _ in range(16):
             self._bit(data & 1)
             data >>= 1
             self._bit(data & 1)
             data >>= 1
-        self.append(_TBURST,)
+        self.append(_TBURST)
 
     def repeat(self):
         self.aptr = 0
 
     def repeat(self):
         self.aptr = 0
-        self.append(9000, 2250, _TBURST)
+        self.append(9000, 2250, _TBURST, _STOP)
+        self.aptr = 0  # Reset pointer
+        self.cb(self._tim)  # Initiate physical transmission.
 
 
 # Philips RC5 protocol
 
 
 # Philips RC5 protocol
index 0220c7b894f4aa6618ee802f5d7dd8e05976d44b..08230a38f8cbcbe29d88ca496a6e76ddff7e0d13 100644 (file)
@@ -46,8 +46,8 @@ class Rbutton:
 async def main(proto):
     # Test uses a 38KHz carrier. Some Philips systems use 36KHz.
     # If button is held down normal behaviour is to retransmit
 async def main(proto):
     # Test uses a 38KHz carrier. Some Philips systems use 36KHz.
     # If button is held down normal behaviour is to retransmit
-    # but most NEC models send a RPEAT code
-    rep_code = False  # Don't care for RC-X. NEC protocol only.
+    # but most NEC models send a REPEAT code
+    rep_code = False  # Rbutton constructor requires False for RC-X. NEC protocol only.
     pin = Pin('X1')
     if not proto:
         irb = NEC(pin)  # Default NEC freq == 38KHz
     pin = Pin('X1')
     if not proto:
         irb = NEC(pin)  # Default NEC freq == 38KHz
@@ -56,11 +56,11 @@ async def main(proto):
     elif proto == 5:
         irb = RC5(pin, 38000)  # My decoder chip is 38KHz
     elif proto == 6:
     elif proto == 5:
         irb = RC5(pin, 38000)  # My decoder chip is 38KHz
     elif proto == 6:
-        irb = RC6_M0(pin, 38000, True)  # Verbose
+        irb = RC6_M0(pin, 38000)
 
     b = []  # Rbutton instances
     b.append(Rbutton(irb, Pin('X3', Pin.IN, Pin.PULL_UP), 0x1, 0x7, rep_code))
 
     b = []  # Rbutton instances
     b.append(Rbutton(irb, Pin('X3', Pin.IN, Pin.PULL_UP), 0x1, 0x7, rep_code))
-    b.append(Rbutton(irb, Pin('X4', Pin.IN, Pin.PULL_UP), 0xfa, 0xb, rep_code))
+    b.append(Rbutton(irb, Pin('X4', Pin.IN, Pin.PULL_UP), 0x10, 0xb, rep_code))
     led = LED(1)
     while True:
         await asyncio.sleep_ms(500)  # Obligatory flashing LED.
     led = LED(1)
     while True:
         await asyncio.sleep_ms(500)  # Obligatory flashing LED.