Using IR as an Input

We've shown how to send and receive IR signals from Circuit Playground Express to Circuit Playground Express. You can use those signals as an input to trigger events on the receiving CPX. So, let's do something fun with it. It's time to light it up and make some noise!

You'll need two Circuit Playground Expresses for this example.

Copy the following code to code.py on the CPX currently receiving signals. The transmission code.py will remain the same from the previous page

import pulseio
import board
import adafruit_irremote
from adafruit_circuitplayground.express import cpx

# Create a 'pulseio' input, to listen to infrared signals on the IR receiver
pulsein = pulseio.PulseIn(board.IR_RX, maxlen=120, idle_state=True)
# Create a decoder that will take pulses and turn them into numbers
decoder = adafruit_irremote.GenericDecode()

while True:
    pulses = decoder.read_pulses(pulsein)
    try:
        # Attempt to convert received pulses into numbers
        received_code = decoder.decode_bits(pulses, debug=False)
    except adafruit_irremote.IRNECRepeatException:
        # We got an unusual short code, probably a 'repeat' signal
        # print("NEC repeat!")
        continue
    except adafruit_irremote.IRDecodeException as e:
        # Something got distorted or maybe its not an NEC-type remote?
        # print("Failed to decode: ", e.args)
        continue

    print("NEC Infrared code received: ", received_code)
    if received_code == [255, 2, 255, 0]:
        print("Button A signal")
        cpx.pixels.fill((130, 0, 100))
    if received_code == [255, 2, 191, 64]:
        print("Button B Signal")
        cpx.pixels.fill((0, 0, 0))
        cpx.play_tone(262, 1)

The beginning of this code is the same as the test with the remote. We create the pulsesio and decoder objects, wait to receive the signals, and attempt to decode them. Then we print the IR code received.

We check for the button presses like before as well. However, instead of simply print()ing to the serial output, we've added something more fun!

  • If we receive the IR code now associated with button A, we print Button A signal, and turn all the NeoPixel LEDs purple!
  • If we receive the IR code now associated with button B, we print Button B signal, turn all of the LEDs off, and play a 262Hz tone!

We've put the two windows together again to show the associated print statements from each board. The transmitting board output is on the left and the receiving output is on the right.

You can do all kinds of things by adding code to these if blocks, such as, move a servo, play a wave file, change LED animations, or print a special message to the serial output. The possibilities are endless. Pick something and give it a try!

This guide was first published on Jul 24, 2018. It was last updated on Jul 24, 2018. This page (Using IR as an Input) was last updated on Sep 19, 2019.