This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions.

If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

esp32 — functionality specific to the ESP32

Theesp32 module contains functions and classes specifically aimed atcontrolling ESP32 modules.

Functions

esp32.wake_on_touch(wake)

Configure whether or not a touch will wake the device from sleep.wake should be a boolean value.

Note

This is only available for boards that have touch sensor support.

esp32.wake_on_ulp(wake)

Configure whether or not the Ultra-Low-Power co-processor can wake thedevice from sleep.wake should be a boolean value.

Note

This is only available for boards that have ULP coprocessor support.

esp32.wake_on_ext0(pin,level)

Configure how EXT0 wakes the device from sleep.pin can beNoneor a valid Pin object.level should beesp32.WAKEUP_ALL_LOW oresp32.WAKEUP_ANY_HIGH.

Note

This is only available for boards that have ext0 support.

esp32.wake_on_ext1(pins,level)

Configure how EXT1 wakes the device from sleep.pins can beNoneor a tuple/list of valid Pin objects.level should beesp32.WAKEUP_ALL_LOWoresp32.WAKEUP_ANY_HIGH.

Note

This is only available for boards that have ext1 support.

esp32.gpio_deep_sleep_hold(enable)

Configure whether non-RTC GPIO pin configuration is retained duringdeep-sleep mode for held pads.enable should be a boolean value.

esp32.raw_temperature()

Read the raw value of the internal temperature sensor, returning an integer.

esp32.idf_heap_info(capabilities)

Returns information about the ESP-IDF heap memory regions. One of them containsthe MicroPython heap and the others are used by ESP-IDF, e.g., for networkbuffers and other data. This data is useful to get a sense of how much memoryis available to ESP-IDF and the networking stack in particular. It may shedsome light on situations where ESP-IDF operations fail due to allocation failures.

The capabilities parameter corresponds to ESP-IDF’sMALLOC_CAP_XXX values but thetwo most useful ones are predefined asesp32.HEAP_DATA for data heap regions andesp32.HEAP_EXEC for executable regions as used by the native code emitter.

The return value is a list of 4-tuples, where each 4-tuple corresponds to one heapand contains: the total bytes, the free bytes, the largest free block, andthe minimum free seen over time.

Example after booting:

>>>importesp32;esp32.idf_heap_info(esp32.HEAP_DATA)[(240, 0, 0, 0), (7288, 0, 0, 0), (16648, 4, 4, 4), (79912, 35712, 35512, 35108), (15072, 15036, 15036, 15036), (113840, 0, 0, 0)]

Note

Free IDF heap memory in theesp32.HEAP_DATA region is availableto be automatically added to the MicroPython heap to prevent aMicroPython allocation from failing. However, the information returnedhere is otherwisenot useful to troubleshoot Python allocationfailures.micropython.mem_info() andgc.mem_free() shouldbe used instead:

The “max new split” value inmicropython.mem_info() outputcorresponds to the largest free block of ESP-IDF heap that could beautomatically added on demand to the MicroPython heap.

The result ofgc.mem_free() is the total of the current “free”and “max new split” values printed bymicropython.mem_info().

esp32.idf_task_info()

Returns information about running ESP-IDF/FreeRTOS tasks, which includeMicroPython threads. This data is useful to gain insight into how much timetasks spend running or if they are blocked for significant parts of time,and to determine if allocated stacks are fully utilized or might be reduced.

CONFIG_FREERTOS_USE_TRACE_FACILITY=y must be set in the boardconfiguration to make this method available. Additionally configuringCONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y andCONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID=y is recommended to be able toretrieve the total and per-task runtime and the core ID respectively.

The return value is a 2-tuple where the first value is the total runtime,and the second a list of tasks. Each task is a 7-tuple containing: the taskID, name, current state, priority, runtime, stack high water mark, and theID of the core it is running on. Runtime and core ID will be None when therespective FreeRTOS configuration option is not enabled.

Note

For an easier to use output based on this function you can use theutop library,which implements a live overview similar to the Unixtop command.

Flash partitions

This class gives access to the partitions in the device’s flash memory and includesmethods to enable over-the-air (OTA) updates.

classesp32.Partition(id,block_size=4096,/)

Create an object representing a partition.id can be a string which is the labelof the partition to retrieve, or one of the constants:BOOT orRUNNING.block_size specifies the byte size of an individual block.

classmethodPartition.find(type=TYPE_APP,subtype=0xff,label=None,block_size=4096)

Find a partition specified bytype,subtype andlabel. Returns a(possibly empty) list of Partition objects. Note:subtype=0xff matches any subtypeandlabel=None matches any label.

block_size specifies the byte size of an individual block used by the returnedobjects.

Partition.info()

Returns a 6-tuple(type,subtype,addr,size,label,encrypted).

Partition.readblocks(block_num,buf)
Partition.readblocks(block_num,buf,offset)
Partition.writeblocks(block_num,buf)
Partition.writeblocks(block_num,buf,offset)
Partition.ioctl(cmd,arg)

These methods implement the simple andextended block protocol defined byvfs.AbstractBlockDev.

Partition.set_boot()

Sets the partition as the boot partition.

Note

Do not enterdeepsleep after changingthe OTA boot partition, without first performing a hardreset or power cycle. This ensures the bootloaderwill validate the new image before booting.

Partition.get_next_update()

Gets the next update partition after this one, and returns a new Partition object.Typical usage isPartition(Partition.RUNNING).get_next_update()which returns the next partition to update given the current running one.

classmethodPartition.mark_app_valid_cancel_rollback()

Signals that the current boot is considered successful.Callingmark_app_valid_cancel_rollback is required on the first boot of a newpartition to avoid an automatic rollback at the next boot.This uses the ESP-IDF “app rollback” feature with “CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE”and anOSError(-261) is raised if called on firmware that doesn’t have thefeature enabled.It is OK to callmark_app_valid_cancel_rollback on every boot and it is notnecessary when booting firmware that was loaded using esptool.

Constants

Partition.BOOT
Partition.RUNNING

Used in thePartition constructor to fetch various partitions:BOOT is thepartition that will be booted at the next reset andRUNNING is the currentlyrunning partition.

Partition.TYPE_APP
Partition.TYPE_DATA

Used inPartition.find to specify the partition type:APP is for bootablefirmware partitions (typically labelledfactory,ota_0,ota_1), andDATA is for other partitions, e.g.nvs,otadata,phy_init,vfs.

esp32.HEAP_DATA
esp32.HEAP_EXEC

Used inidf_heap_info.

PCNT

This class provides access to the ESP32 hardware support for pulse counting.There are 8 pulse counter units, with id 0..7.

See themachine.Counter andmachine.Encoder classes for simpler and portableabstractions of common pulse counting applications. These classes areimplemented as thin Python shims aroundPCNT.

classesp32.PCNT(id,*,...)

Returns the singleton PCNT instance for the given unitid.

Keyword arguments are passed to theinit() method as describedbelow.

PCNT.init(*,...)

(Re-)initialise a pulse counter unit. Supported keyword arguments are:

  • channel: see description below

  • pin: the input Pin to monitor for pulses

  • rising: an action to take on a rising edge - one ofPCNT.INCREMENT,PCNT.DECREMENT orPCNT.IGNORE (the default)

  • falling: an action to take on a falling edge (takes the save valuesas therising argument).

  • mode_pin: ESP32 pulse counters support monitoring a second pin andaltering the behaviour of the counter based on its level - set thiskeyword to any input Pin

  • mode_low: set to eitherPCNT.HOLD orPCNT.REVERSE toeither suspend counting or reverse the direction of the counter (i.e.,PCNT.INCREMENT behaves asPCNT.DECREMENT and vice versa)whenmode_pin is low

  • mode_high: asmode_low but for the behaviour whenmode_pinis high

  • filter: set to a value 1..1023, in ticks of the 80MHz clock, toenable the pulse width filter

  • min: set to the minimum level of the counter value whendecrementing (-32768..-1) or 0 to disable

  • max: set to the maximum level of the counter value whenincrementing (1..32767) or 0 to disable

  • threshold0: sets the counter value for thePCNT.IRQ_THRESHOLD0 event (seeirq method)

  • threshold1: sets the counter value for thePCNT.IRQ_THRESHOLD1 event (seeirq method)

  • value: can be set to0 to reset the counter value

The hardware initialisation is done in stages and so some of the keywordarguments can be used in groups or in isolation to partially reconfigure aunit:

  • thepin keyword (optionally combined withmode_pin) can be usedto change just the bound pin(s)

  • rising,falling,mode_low andmode_high can be used(singly or together) to change the counting logic - omitted keywordsuse their default (PCNT.IGNORE orPCNT.NORMAL)

  • filter can be used to change only the pulse width filter (with 0disabling it)

  • each ofmin,max,threshold0 andthreshold1 canbe used to change these limit/event values individually; however,setting any will reset the counter to zero (i.e., they implyvalue=0)

Each pulse counter unit supports two channels, 0 and 1, each able tomonitor different pins with different counting logic but updating the samecounter value. Usechannel=1 with thepin,rising,falling,mode_pin,mode_low andmode_high keywords to configure thesecond channel.

The second channel can be used to configure 4X quadrature decoding with asingle counter unit:

pin_a=Pin(2,Pin.INPUT,pull=Pin.PULL_UP)pin_b=Pin(3,Pin.INPUT,pull=Pin.PULL_UP)rotary=PCNT(0,min=-32000,max=32000)rotary.init(channel=0,pin=pin_a,falling=PCNT.INCREMENT,rising=PCNT.DECREMENT,mode_pin=pin_b,mode_low=PCNT.REVERSE)rotary.init(channel=1,pin=pin_b,falling=PCNT.DECREMENT,rising=PCNT.INCREMENT,mode_pin=pin_a,mode_low=PCNT.REVERSE)rotary.start()
PCNT.value([value])

Call this method with no arguments to return the current counter value.

If the optionalvalue argument is set to0 then the counter isreset (but the previous value is returned). Read and reset is not atomic andso it is possible for a pulse to be missed. Any value other than0 willraise an error.

PCNT.irq(handler=None,trigger=PCNT.IRQ_ZERO)

ESP32 pulse counters support interrupts on these counter events:

  • PCNT.IRQ_ZERO: the counter has reset to zero

  • PCNT.IRQ_MIN: the counter has hit themin value

  • PCNT.IRQ_MAX: the counter has hit themax value

  • PCNT.IRQ_THRESHOLD0: the counter has hit thethreshold0 value

  • PCNT.IRQ_THRESHOLD1: the counter has hit thethreshold1 value

trigger should be a bit-mask of the desired events OR’ed together. Thehandler function should take a single argument which is thePCNT instance that raised the event.

This method returns a callback object. The callback object can be used toaccess the bit-mask of events that are outstanding on the PCNT unit.:

defpcnt_irq(pcnt):flags=pcnt.irq().flags()ifflags&PCNT.IRQ_ZERO:# resetifflags&PCNT.IRQ_MAX:# overflow......etcpcnt.irq(handler=pcnt_irq,trigger=PCNT.IRQ_ZERO|PCNT.IRQ_MAX|...)

Note: Accessingirq.flags() will clear the flags, so only call itonce per invocation of the handler.

The handler is called with the MicroPython scheduler and so will run at apoint after the interrupt. If another interrupt occurs before the handlerhas been called then the events will be coalesced together into a singlecall and the bit mask will indicate all events that have occurred.

To avoid race conditions between a handler being called and retrieving thecurrent counter value, thevalue() method will force execution of anypending events before returning the current counter value (and potentiallyresetting the value).

Only one handler can be in place per-unit. Sethandler toNone todisable the event interrupt.

Note

ESP32 pulse counters reset tozero when reaching the minimum or maximumvalue. Thus theIRQ_ZERO event will also trigger when either of theseevents occurs.

See themachine.Counter andmachine.Encoder classes for simpler abstractions ofcommon pulse counting applications.

RMT

The RMT (Remote Control) module, specific to the ESP32, was originally designedto send and receive infrared remote control signals. However, due to a flexibledesign and very accurate (as low as 12.5ns) pulse generation, it can also beused to transmit or receive many other types of digital signals:

importesp32frommachineimportPinr=esp32.RMT(0,pin=Pin(18),clock_div=8)r# RMT(channel=0, pin=18, source_freq=80000000, clock_div=8, idle_level=0)# To apply a carrier frequency to the high outputr=esp32.RMT(0,pin=Pin(18),clock_div=8,tx_carrier=(38000,50,1))# The channel resolution is 100ns (1/(source_freq/clock_div)).r.write_pulses((1,20,2,40),0)# Send 0 for 100ns, 1 for 2000ns, 0 for 200ns, 1 for 4000ns

The input to the RMT module is an 80MHz clock (in the future it may be able toconfigure the input clock but, for now, it’s fixed).clock_divdividesthe clock input which determines the resolution of the RMT channel. Thenumbers specified inwrite_pulses are multiplied by the resolution todefine the pulses.

clock_div is an 8-bit divider (0-255) and each pulse can be defined bymultiplying the resolution by a 15-bit (1-PULSE_MAX) number. There are eightchannels (0-7) and each can have a different clock divider.

So, in the example above, the 80MHz clock is divided by 8. Thus theresolution is (1/(80Mhz/8)) 100ns. Since thestart level is 0 and toggleswith each number, the bitstream is0101 with durations of [100ns, 2000ns,100ns, 4000ns].

For more details see Espressif’sESP-IDF RMT documentation..

Warning

The current MicroPython RMT implementation lacks some features, most notablyreceiving pulses. RMT should be considered abeta feature and the interface may change in the future.

classesp32.RMT(channel,*,pin=None,clock_div=8,idle_level=False,tx_carrier=None)

This class provides access to one of the eight RMT channels.channel isrequired and identifies which RMT channel (0-7) will be configured.pin,also required, configures which Pin is bound to the RMT channel.clock_divis an 8-bit clock divider that divides the source clock (80MHz) to the RMTchannel allowing the resolution to be specified.idle_level specifieswhat level the output will be when no transmission is in progress and canbe any value that converts to a boolean, withTrue representing highvoltage andFalse representing low.

To enable the transmission carrier feature,tx_carrier should be a tupleof three positive integers: carrier frequency, duty percent (0 to100) and the output level to apply the carrier to (a boolean as peridle_level).

classmethodRMT.source_freq()

Returns the source clock frequency. Currently the source clock is notconfigurable so this will always return 80MHz.

RMT.clock_div()

Return the clock divider. Note that the channel resolution is1/(source_freq/clock_div).

RMT.wait_done(*,timeout=0)

ReturnsTrue if the channel is idle orFalse if a sequence ofpulses started withRMT.write_pulses is being transmitted. If thetimeout keyword argument is given then block for up to this manymilliseconds for transmission to complete.

RMT.loop(enable_loop)

Configure looping on the channel.enable_loop is bool, set toTrue toenable looping on thenext call toRMT.write_pulses. If called withFalse while a looping sequence is currently being transmitted then thecurrent loop iteration will be completed and then transmission will stop.

RMT.write_pulses(duration,data=True)

Begin transmitting a sequence. There are three ways to specify this:

Mode 1:duration is a list or tuple of durations. The optionaldataargument specifies the initial output level. The output level will toggleafter each duration.

Mode 2:duration is a positive integer anddata is a list or tupleof output levels.duration specifies a fixed duration for each.

Mode 3:duration anddata are lists or tuples of equal length,specifying individual durations and the output level for each.

Durations are in integer units of the channel resolution (asdescribed above), between 1 andPULSE_MAX units. Output levelsare any value that can be converted to a boolean, withTruerepresenting high voltage andFalse representing low.

If transmission of an earlier sequence is in progress then this method willblock until that transmission is complete before beginning the new sequence.

If looping has been enabled withRMT.loop, the sequence will berepeated indefinitely. Further calls to this method will block until theend of the current loop iteration before immediately beginning to loop thenew sequence of pulses. Looping sequences longer than 126 pulses is notsupported by the hardware.

staticRMT.bitstream_channel([value])

Select which RMT channel is used by themachine.bitstream implementation.value can beNone or a valid RMT channel number. The default RMTchannel is the highest numbered one.

Passing inNone disables the use of RMT and instead selects a bit-bangingimplementation formachine.bitstream.

Passing in no argument will not change the channel. This function returnsthe current channel number.

Constants

RMT.PULSE_MAX

Maximum integer that can be set for a pulse duration.

Ultra-Low-Power co-processor

This class gives access to the Ultra Low Power (ULP) co-processor on the ESP32,ESP32-S2 and ESP32-S3 chips.

Warning

This class does not provide access to the RISCV ULP co-processor availableon the ESP32-S2 and ESP32-S3 chips.

classesp32.ULP

This class provides access to the Ultra-Low-Power co-processor.

ULP.set_wakeup_period(period_index,period_us)

Set the wake-up period.

ULP.load_binary(load_addr,program_binary)

Load aprogram_binary into the ULP at the givenload_addr.

ULP.run(entry_point)

Start the ULP running at the givenentry_point.

Constants

esp32.WAKEUP_ALL_LOW
esp32.WAKEUP_ANY_HIGH

Selects the wake level for pins.

Non-Volatile Storage

This class gives access to the Non-Volatile storage managed by ESP-IDF. The NVS is partitionedinto namespaces and each namespace contains typed key-value pairs. The keys are strings and thevalues may be various integer types, strings, and binary blobs. The driver currently onlysupports 32-bit signed integers and blobs.

Warning

Changes to NVS need to be committed to flash by calling the commit method. Failureto call commit results in changes being lost at the next reset.

classesp32.NVS(namespace)

Create an object providing access to a namespace (which is automatically created if notpresent).

NVS.set_i32(key,value)

Sets a 32-bit signed integer value for the specified key. Remember to callcommit!

NVS.get_i32(key)

Returns the signed integer value for the specified key. Raises an OSError if the key does notexist or has a different type.

NVS.set_blob(key,value)

Sets a binary blob value for the specified key. The value passed in must support the bufferprotocol, e.g. bytes, bytearray, str. (Note that esp-idf distinguishes blobs and strings, thismethod always writes a blob even if a string is passed in as value.)Remember to callcommit!

NVS.get_blob(key,buffer)

Reads the value of the blob for the specified key into the buffer, which must be a bytearray.Returns the actual length read. Raises an OSError if the key does not exist, has a differenttype, or if the buffer is too small.

NVS.erase_key(key)

Erases a key-value pair.

NVS.commit()

Commits changes made byset_xxx methods to flash.