SunFounder ESP32 Starter Kit
(continued from previous page)
ir = NEC_8(pin_ir, callback) # Instantiate the NEC_8 receiver
# Show debug information
ir.error_function(print_error)
# keep the script running until interrupted by a keyboard interrupt (Ctrl+C)
try:
while True:
pass
except KeyboardInterrupt:
ir.close() # Close the receiver
When the program is running, press the key on the remote control, the value and name of the key will appear in the
Shell.
Note: The new remote control features a plastic tab at the end to insulate the battery inside. To power up the remote
when using it, simply remove this plastic piece.
How it works?
1. While this program may appear somewhat complex at first glance, it actually accomplishes the fundamental
functions of the IR receiver using just a few lines of code.
import time
from machine import Pin, freq
from ir_rx.nec import NEC_8
pin_ir = Pin(14, Pin.IN) # IR receiver
# User callback
def callback(data, addr, ctrl):
if data < 0: # NEC protocol sends repeat codes.
pass
else:
print(decodeKeyValue(data))
ir = NEC_8(pin_ir, callback) # Instantiate receiver
• In this code, an ir object is instantiated, allowing it to read the signals captured by the IR receiver
at any given moment.
• The resulting information is then stored in the data variable within the callback function.
– Callback Function - Wikipedia
• If the IR receiver receives duplicate values (e.g., when a button is pressed and held down), the
data will be less than 0, and this data needs to be filtered out.
• Otherwise, the data would be a usable value, albeit in an unreadable code. The
decodeKeyValue(data) function is then utilized to decode it into a more comprehensible for-
mat.
406 Chapter 3. For MicroPython User