GitBook: [master] 331 pages modified

This commit is contained in:
Daniel Spindelbauer
2018-09-04 10:13:29 +00:00
committed by gitbook-bot
parent f179b56b33
commit 514f62ebce
169 changed files with 289 additions and 289 deletions

View File

@@ -1,106 +0,0 @@
# machine
The `machine` module contains specific functions related to the board.
### Quick Usage Example
```python
import machine
help(machine) # display all members from the machine module
machine.freq() # get the CPU frequency
machine.unique_id() # return the 6-byte unique id of the board (the LoPy's WiFi MAC address)
```
## Reset Functions
#### machine.reset\(\)
Resets the device in a manner similar to pushing the external RESET button.
#### machine.reset\_cause\(\)
Get the reset cause. See constants for the possible return values.
## Interrupt Functions
#### machine.disable\_irq\(\)
Disable interrupt requests. Returns and integer representing the previous IRQ state. This return value can be passed to `enable_irq` to restore the IRQ to its original state.
#### machine.enable\_irq\(\[state\]\)
Enable interrupt requests. The most common use of this function is to pass the value returned by `disable_irq` to exit a critical section. Another options is to enable all interrupts which can be achieved by calling the function with no parameters.
## Power Functions
#### machine.freq\(\)
Returns CPU frequency in hertz.
#### machine.idle\(\)
Gates the clock to the CPU, useful to reduce power consumption at any time during short or long periods. Peripherals continue working and execution resumes as soon as any interrupt is triggered \(on many ports this includes system timer interrupt occurring at regular intervals on the order of millisecond\).
#### machine.deepsleep\(\[time\_ms\]\)
Stops the CPU and all peripherals, including the networking interfaces \(except for LTE\). Execution is resumed from the main script, just as with a reset. If a value in milliseconds is given then the device will wake up after that period of time, otherwise it will remain in deep sleep until the reset button is pressed.
The products with LTE connectivity \(FiPy, GPy, G01\), require the LTE radio to be disabled separately via the LTE class before entering deepsleep. This is required due to the LTE radio being powered independently and allowing use cases which require the system to be taken out from deepsleep by an event from the LTE network \(data or SMS received for instance\).
#### machine.pin\_deepsleep\_wakeup\(pins, mode, enable\_pull\)
Configure pins to wake up from deep sleep mode. The pins which have this capability are: `P2, P3, P4, P6, P8 to P10 and P13 to P23`.
The arguments are:
* `pins` a list or tuple containing the `GPIO` to setup for deepsleep wakeup.
* `mode` selects the way the configure `GPIO`s can wake up the module. The possible values are: `machine.WAKEUP_ALL_LOW` and `machine.WAKEUP_ANY_HIGH`.
* `enable_pull` if set to `True` keeps the pull up or pull down resistors enabled during deep sleep. If this variable is set to `True`, then `ULP` or capacitive touch wakeup cannot be used in combination with `GPIO` wakeup.
#### machine.wake\_reason\(\)
Get the wake reason. See constants for the possible return values. Returns a tuple of the form: `(wake_reason, gpio_list)`. When the wakeup reason is either GPIO or touch pad, then the second element of the tuple is a list with GPIOs that generated the wakeup.
#### machine.remaining\_sleep\_time\(\)
Returns the remaining timer duration \(in milliseconds\) if the ESP32 is woken up from deep sleep by something other than the timer. For example, if you set the timer for 30 seconds \(30000 ms\) and it wakes up after 10 seconds then this function will return `20000`.
## Miscellaneous Functions
#### machine.main\(filename\)
Set the `filename` of the main script to run after `boot.py` is finished. If this function is not called then the default file `main.py` will be executed.
It only makes sense to call this function from within `boot.py`.
#### machine.rng\(\)
Return a 24-bit software generated random number.
#### machine.unique\_id\(\)
Returns a byte string with a unique identifier of a board/SoC. It will vary from a board/SoC instance to another, if underlying hardware allows. Length varies by hardware \(so use substring of a full value if you expect a short ID\). In some MicroPython ports, ID corresponds to the network MAC address.
{% hint style="info" %}
Use `ubinascii.hexlify()` to convert the byte string to hexadecimal form for ease of manipulation and use elsewhere.
{% endhint %}
#### machine.info\(\)
Returns the high water mark of the stack associated with various system tasks, in words \(1 word = 4 bytes on the ESP32\). If the value is zero then the task has likely overflowed its stack. If the value is close to zero then the task has come close to overflowing its stack.
## Constants
### Reset Causes
`machine.PWRON_RESET`, `machine.HARD_RESET`, `machine.WDT_RESET,` `machine.DEEPSLEEP_RESET`, `machine.SOFT_RESET`, `machine.BROWN_OUT_RESET`
### Wake Reasons
`machine.PWRON_WAKE`, `machine.PIN_WAKE`, `machine.RTC_WAKE`, `machine.ULP_WAKE`
### Pin Wakeup Modes
`machine.WAKEUP_ALL_LOW`, `machine.WAKEUP_ANY_HIGH`

View File

@@ -1,100 +0,0 @@
---
search:
keywords:
- ADC
- Analog
- ADCChannel
---
# ADC
## class ADC Analog to Digital Conversion
### Quick Usage Example
```python
import machine
adc = machine.ADC() # create an ADC object
apin = adc.channel(pin='P16') # create an analog pin on P16
val = apin() # read an analog value
```
### Constructors
#### class machine.ADC\(id=0\)
Create an ADC object; associate a channel with a pin. For more info check the hardware section.
### Methods
#### adc.init\( \* , bits=12\)
Enable the ADC block. This method is automatically called on object creation.
* `Bits` can take values between 9 and 12 and selects the number of bits of resolution of the ADC block.
#### adc.deinit\(\)
Disable the ADC block.
#### adc.channel\(\* , pin, attn=ADC.ATTN\_0DB\)
Create an analog pin.
* `pin` is a keyword-only string argument. Valid pins are `P13` to `P20`.
* `attn` is the attenuation level. The supported values are: `ADC.ATTN_0DB`, `ADC.ATTN_2_5DB`, `ADC.ATTN_6DB`, `ADC.ATTN_11DB`
Returns an instance of `ADCChannel`. Example:
```python
# enable an ADC channel on P16
apin = adc.channel(pin='P16')
```
#### adc.vref\(vref\)
If called without any arguments, this function returns the current calibrated voltage \(in millivolts\) of the `1.1v` reference. Otherwise it will update the calibrated value \(in millivolts\) of the internal `1.1v` reference.
#### adc.vref\_to\_pin\(pin\)
Connects the internal `1.1v` to external `GPIO`. It can only be connected to `P22`, `P21` or `P6`. It is recommended to only use `P6` on the WiPy, on other modules this pin is connected to the radio.
### Constants
* ADC channel attenuation values: `ADC.ATTN_0DB`, `ADC.ATTN_2_5DB`, `ADC.ATTN_6DB`, `ADC.ATTN_11DB`
## class ADCChannel
Read analog values from internal/external sources. ADC channels can be connected to internal points of the `MCU` or to `GPIO` pins. ADC channels are created using the `ADC.channel` method.
### Methods
#### adcchannel\(\)
Fast method to read the channel value.
#### adcchannel.value\(\)
Read the channel value.
#### adcchannel.init\(\)
\(Re\)init and enable the ADC channel. This method is automatically called on object creation.
#### adcchannel.deinit\(\)
Disable the ADC channel.
#### adcchannel.voltage\(\)
Reads the channels value and converts it into a voltage \(in millivolts\)
#### adcchannel.value\_to\_voltage\(value\)
Converts the provided value into a voltage \(in millivolts\) in the same way voltage does.
{% hint style="danger" %}
ADC pin input range is `0-1.1V`. This maximum value can be increased up to `3.3V` using the highest attenuation of `11dB`. **Do not exceed the maximum of 3.3V**, to avoid damaging the device.
{% endhint %}

View File

@@ -1,132 +0,0 @@
# CAN
The CAN class supports the full CAN 2.0 specification with standard and extended frames, as well as acceptance filtering.
The ESP32 has a built-in CAN controller, but the transceiver needs to be added externally. A recommended device is the SN65HVD230.
## Quick Usage Example
```python
from machine import CAN
can = CAN(mode=CAN.NORMAL, baudrate=500000, pins=('P22', 'P23'))
can.send(id=12, data=bytes([1, 2, 3, 4, 5, 6, 7, 8]))
can.recv()
```
## Constructors
#### class machine.CAN\(bus=0, ...\)
Create an CAN object. See init for parameters of initialisation.:
```python
# only 1 CAN peripheral is available, so the bus must always be 0
can = CAN(0, mode=CAN.NORMAL, baudrate=500000, pins=('P22', 'P23')) # pin order is Tx, Rx
```
## Methods
#### can.init\(mode=CAN.NORMAL, baudrate=500000, \*, frame\_format=CAN.FORMAT\_STD, rx\_queue\_len=128, pins=\('P22', 'P23'\)\)
Initialize the CAN controller. The arguments are:
* `mode` can take either CAN.NORMAL or CAN.SILENT. Silent mode is useful for sniffing the bus.
* `baudrate` sets up the bus speed. Acceptable values are between 1 and 1000000.
* `frame_format` defines the frame format to be accepted by the receiver. Useful for filtering frames based on the identifier length. Can tale either `CAN.FORMAT_STD`, `CAN.FORMAT_EXT`, `CAN.FORMAT_BOTH`. If `CAN.FORMAT_STD` is selected, extended frames won't be received and vice-versa.
* `rx_queue_len` defines the number of messages than can be queued by the receiver. Due to CAN being a high traffic bus, large values are recommended \(>= 128\), otherwise messages will be dropped specially when no filtering is applied.
* `pins` selects the `Tx` and `Rx` pins \(in that order\).
#### can.deinit\(\)
Disables the CAN bus.
#### can.send\(id, \* , data=None, rtr=False, extended=False\)
Send a CAN frame on the bus
* `id` is the identifier of the message.
* `data` can take up to 8 bytes. It must be left empty is the message to be sent is a remote request \(rtr=True\).
* `rtr` set it to false to send a remote request.
* `extnted` specifies if the message identifier width should be 11bit \(standard\) or 29bit \(extended\).
Can be used like:
```python
can.send(id=0x0020, data=bytes([0x01, 0x02, 0x03, 0x04, 0x05]), extended=True) # sends 5 bytes with an extended identifier
can.send(id=0x010, data=bytes([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08])) # sends 8 bytes with an standard identifier
can.send(id=0x012, rtr=True) # sends a remote request for message id=0x12
```
#### can.recv\(timeout=0\)
Get a message from the receive queue, and optionally specify a timeout value in **s** \(can be a floating point value e.g. `0.2`\). This function returns `None` if no messages available. If a message is present, it will be returned as a named tuple with the following form:
`(id, data, rtr, extended)`
```python
>>> can.recv()
(id=0x012, data=b'123', rtr=False, extended=False)
```
#### can.soft\_filter\(mode, filter\_list\)
Specify a software filter accepting only the messages that pass the filter test.
There are 3 possible filter modes:
* `CAN.FILTER_LIST` allows to pass the list of IDs that should be accepted.
* `CAN.FILTER_RANGE` allows to pass a list or tuple of ID ranges that should be accepted.
* `CAN.FILTER_MASK` allows to pass a list of tuples of the form: `(filter, mask)`.
With software filters all messages in the bus are received by the CAN controller but only the matching ones are passed to the RX queue. This means that the queue won't be filled up with non relevant messages, but the interrupt overhead will remain as normal. The `filter_list` can contain up to 32 elements.
For example:
```python
can.soft_filter(CAN.FILTER_LIST, [0x100, 0x200, 0x300, 0x400]) # only accept identifiers from 0x100, 0x200, 0x300 and 0x400
can.soft_filter(CAN.FILTER_RANGE, [(0x001, 0x010), (0x020, 0x030), (0x040, 0x050)]) # only accept identifiers from 0x001 to 0x010, from 0x020 to 0x030 and from 0x040 to 0x050.
can.soft_filter(CAN.FILTER_MASK, [(0x100, 0x7FF), (0x200, 0x7FC)]) # more of the classic Filter and Mask method.
can.soft_filter(None) # disable soft filters, all messages are accepted
```
#### can.callback\(trigger, handler=None, arg=None\)
Set a callback to be triggered when any of this 3 events are present:
* trigger is the type of event that triggers the callback. Possible values are:
* `CAN.RX_FRAME` interrupt whenever a new frame is received.
* `CAN.RX_FIFO_NOT_EMPTY` interrupt when a frame is received on an empty FIFO.
* `CAN.RX_FIFO_OVERRUN` interrupt when a message is received and the FIFO is full.
The values can be OR-ed together, for instance `trigger=CAN.RX_FRAME | CAN.RX_FIFO_OVERRUN`
* handler is the function to be called when the event happens. This function will receive one argument. Set handler to None to disable the callback.
* arg is an optional argument to pass to the callback. If left empty or set to None, the function will receive the CAN object that triggered it.
It can be used like this:
```python
from machine import CAN
can = CAN(mode=CAN.NORMAL, baudrate=500000, pins=('P22', 'P23'))
def can_cb(can_o):
print('CAN Rx:', can_o.recv())
can.callback(handler=can_cb, trigger=CAN.RX_FRAME)
```
#### can.events\(\)
This method returns a value with bits sets \(if any\) indicating the events that have occurred in the bus. Please note that by calling this function the internal events registry is cleared automatically, therefore calling it immediately for a second time will most likely return a value of 0.
## Constants
`CAN.NORMAL`, `CAN.SILENT`, `CAN.FORMAT_STD`, `CAN.FORMAT_EXT`, `CAN.FORMAT_BOTH`, `CAN.RX_FRAME`, `CAN.RX_FIFO_NOT_EMPTY`, `CAN.RX_FIFO_OVERRUN`, `CAN.FILTER_LIST`, `CAN.FILTER_RANGE`, `CAN.FILTER_MASK`

View File

@@ -1,46 +0,0 @@
# DAC
The DAC is used to output analog values \(a specific voltage\) on pin `P22` or pin `P21`. The voltage will be between `0` and `3.3V`.
## Quick Usage Example
```python
import machine
dac = machine.DAC('P22') # create a DAC object
dac.write(0.5) # set output to 50%
dac_tone = machine.DAC('P21') # create a DAC object
dac_tone.tone(1000, 0) # set tone output to 1kHz
```
## Constructors
#### class class machine.DAC\(pin\)
Create a DAC object, that will let you associate a channel with a `pin`. `pin` can be a string argument.
## Methods
#### dac.init\(\)
Enable the DAC block. This method is automatically called on object creation.
#### dac.deinit\(\)
Disable the DAC block.
#### dac.write\(value\)
Set the DC level for a DAC pin. `value` is a float argument, with values between 0 and 1.
#### dac.tone\(frequency, amplitude\)
Sets up tone signal to the specified `frequency` at `amplitude` scale. `frequency` can be from `125Hz` to `20kHz` in steps of `122Hz`. `amplitude` is an integer specifying the tone amplitude to write the DAC pin. Amplitude value represents:
* `0` is 0dBV \(~ 3Vpp at 600 Ohm load\)
* `1` is -6dBV \(~1.5 Vpp\), `2` is -12dBV \(~0.8 Vpp\)
* `3` is -18dBV \(~0.4 Vpp\).
The generated signal is a sine wave with an DC offset of VDD/2.

View File

@@ -1,128 +0,0 @@
# I2C
I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on.
## Example using default Pins
```python
from machine import I2C
i2c = I2C(0) # create on bus 0
i2c = I2C(0, I2C.MASTER) # create and init as a master
i2c = I2C(0, pins=('P10','P11')) # create and use non-default PIN assignments (P10=SDA, P11=SCL)
i2c.init(I2C.MASTER, baudrate=20000) # init as a master
i2c.deinit() # turn off the peripheral
```
## Example using non-default Pins
```python
from machine import I2C
i2c = I2C(0, pins=('P10','P11')) # create and use non-default PIN assignments (P10=SDA, P11=SCL)
i2c.init(I2C.MASTER, baudrate=20000) # init as a master
i2c.deinit() # turn off the peripheral
```
Printing the `i2c` object gives you information about its configuration.
A master must specify the recipients address:
```python
i2c.init(I2C.MASTER)
i2c.writeto(0x42, '123') # send 3 bytes to slave with address 0x42
i2c.writeto(addr=0x42, b'456') # keyword for address
```
Master also has other methods:
```python
i2c.scan() # scan for slaves on the bus, returning
# a list of valid addresses
i2c.readfrom_mem(0x42, 2, 3) # read 3 bytes from memory of slave 0x42,
# starting at address 2 in the slave
i2c.writeto_mem(0x42, 2, 'abc') # write 'abc' (3 bytes) to memory of slave 0x42
# starting at address 2 in the slave, timeout after 1 second
```
## Quick Usage Example
```python
from machine import I2C
# configure the I2C bus
i2c = I2C(0, I2C.MASTER, baudrate=100000)
i2c.scan() # returns list of slave addresses
i2c.writeto(0x42, 'hello') # send 5 bytes to slave with address 0x42
i2c.readfrom(0x42, 5) # receive 5 bytes from slave
i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from slave 0x42, slave memory 0x10
i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to slave 0x42, slave memory 0x10
```
## Constructors
#### class machine.I2C\(bus, ...\)
Construct an I2C object on the given `bus`. `bus` can only be `0, 1, 2`. If the `bus` is not given, the default one will be selected \(`0`\). Buses `0` and `1` use the ESP32 I2C hardware peripheral while bus `2` is implemented with a bit-banged software driver.
## Methods
### General Methods
#### i2c.init\(mode, \* , baudrate=100000, pins=\(SDA, SCL\)\)
Initialise the I2C bus with the given parameters:
* `mode` must be I2C.MASTER
* `baudrate` is the SCL clock rate
* pins is an optional tuple with the pins to assign to the I2C bus. The default I2C pins are `P9` \(SDA\) and `P10` \(SCL\)
#### i2c.scan\(\)
Scan all I2C addresses between `0x08` and `0x77` inclusive and return a list of those that respond. A device responds if it pulls the SDA line low after its address \(including a read bit\) is sent on the bus.
### Standard Bus Operations
The following methods implement the standard I2C master read and write operations that target a given slave device.
#### i2c.readfrom\(addr, nbytes\)
Read `nbytes` from the slave specified by `addr`. Returns a bytes object with the data read.
#### i2c.readfrom\_into\(addr, buf\)
Read into `buf` from the slave specified by `addr`. The number of bytes read will be the length of `buf`.
Return value is the number of bytes read.
#### i2c.writeto\(addr, buf, \* , stop=True\)
Write the bytes from `buf` to the slave specified by `addr`. The argument `buf` can also be an integer which will be treated as a single byte. If `stop` is set to `False` then the stop condition wont be sent and the I2C operation may be continued \(typically with a read transaction\).
Return value is the number of bytes written.
### Memory Operations
Some I2C devices act as a memory device \(or set of registers\) that can be read from and written to. In this case there are two addresses associated with an I2C transaction: the slave address and the memory address. The following methods are convenience functions to communicate with such devices.
#### i2c.readfrom\_mem\(addr, memaddr, nbytes, \*, addrsize=8\)
Read `nbytes` from the slave specified by `addr` starting from the memory address specified by `memaddr`. The `addrsize` argument is specified in bits and it can only take 8 or 16.
#### i2c.readfrom\_mem\_into\(addr, memaddr, buf, \*, addrsize=8\)
Read into `buf` from the slave specified by `addr` starting from the memory address specified by `memaddr`. The number of bytes read is the length of `buf`. The `addrsize` argument is specified in bits and it can only take 8 or 16.
The return value is the number of bytes read.
#### i2c.writeto\_mem\(addr, memaddr, buf \*, addrsize=8\)
Write `buf` to the slave specified by `addr` starting from the memory address specified by `memaddr`. The argument `buf` can also be an integer which will be treated as a single byte. The `addrsize` argument is specified in bits and it can only take 8 or 16.
The return value is the number of bytes written.
## Constants
* `I2C.MASTER`: Used to initialise the bus to master mode.

View File

@@ -1,153 +0,0 @@
# Pin
A pin is the basic object to control I/O pins \(also known as GPIO - general-purpose input/output\). It has methods to set the mode of the pin \(input, output, etc\) and methods to get and set the digital logic level. For analog control of a pin, see the ADC class.
## Quick Usage Example
```python
from machine import Pin
# initialize `P9` in gpio mode and make it an output
p_out = Pin('P9', mode=Pin.OUT)
p_out.value(1)
p_out.value(0)
p_out.toggle()
p_out(True)
# make `P10` an input with the pull-up enabled
p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP)
p_in() # get value, 0 or 1
```
## Constructors
#### class machine.Pin\(id, ...\)
Create a new Pin object associated with the string `id`. If additional arguments are given, they are used to initialise the pin. [See pin.init\(\)](pin.md#pin-init-mode-pull-alt)
```python
from machine import Pin
p = Pin('P10', mode=Pin.OUT, pull=None, alt=-1)
```
## Methods
#### pin.init\(mode, pull, \* , alt\)
Initialise the pin:
* `mode` can be one of:
* `Pin.IN` - input pin.
* `Pin.OUT` - output pin in push-pull mode.
* `Pin.OPEN_DRAIN` - input or output pin in open-drain mode.
* `pull` can be one of:
* `None` - no pull up or down resistor.
* `Pin.PULL_UP` - pull up resistor enabled.
* `Pin.PULL_DOWN` - pull down resistor enabled.
* `alt` is the id of the alternate function.
Returns: `None`.
#### pin.id\(\)
Get the pin id.
#### pin.value\(\[value\]\)
Get or set the digital logic level of the pin:
* With no argument, return 0 or 1 depending on the logic level of the pin.
* With value given, set the logic level of the pin. value can be anything that converts to a boolean. If it converts to True, the pin is set high, otherwise it is set low.
#### pin\(\[value\]\)
Pin objects are callable. The call method provides a \(fast\) shortcut to set and get the value of the pin.
Example:
```python
from machine import Pin
pin = Pin('P12', mode=Pin.IN, pull=Pin.PULL_UP)
pin() # fast method to get the value
```
See `pin.value()` for more details.
#### pin.toggle\(\)
Toggle the value of the pin.
#### pin.mode\(\[mode\]\)
Get or set the pin mode.
#### pin.pull\(\[pull\]\)
Get or set the pin pull.
#### pin.hold\(\[hold\]\)
Get or set the pin hold. You can apply a hold to a pin by passing `True` \(or clear it by passing `False`\). When a pin is held, its value cannot be changed by using `Pin.value()` or `Pin.toggle()` until the hold is released. This Can be used to retain the pin state through a core reset and system reset triggered by watchdog time-out or Deep-sleep events. Only pins in the RTC power domain can retain their value through deep sleep or reset.
These are: `P2, P3, P4, P6, P8, P9, P10, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23`
#### pin.callback\(trigger, handler=None, arg=None\)
Set a callback to be triggered when the input level at the pin changes.
* `trigger` is the type of event that triggers the callback. Possible values are:
* `Pin.IRQ_FALLING` interrupt on falling edge.
* `Pin.IRQ_RISING` interrupt on rising edge.
* `Pin.IRQ_LOW_LEVEL` interrupt on low level.
* `Pin.IRQ_HIGH_LEVEL` interrupt on high level.
The values can be OR-ed together, for instance `trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING`
* `handler` is the function to be called when the event happens. This function will receive one argument. Set `handler` to `None` to disable it.
* `arg` is an optional argument to pass to the callback. If left empty or set to `None`, the function will receive the Pin object that triggered it.
Example:
```python
from machine import Pin
def pin_handler(arg):
print("got an interrupt in pin %s" % (arg.id()))
p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP)
p_in.callback(Pin.IRQ_FALLING | Pin.IRQ_RISING, pin_handler)
```
{% hint style="info" %}
For more information on how Pycoms products handle interrupts, see [here](../../notes.md#interrupt-handling).
{% endhint %}
## Attributes
#### class pin.exp\_board
Contains all Pin objects supported by the expansion board. Examples:
```python
Pin.exp_board.G16
led = Pin(Pin.exp_board.G16, mode=Pin.OUT)
Pin.exp_board.G16.id()
```
#### class pin.module
Contains all `Pin` objects supported by the module. Examples:
```python
Pin.module.P9
led = Pin(Pin.module.P9, mode=Pin.OUT)
Pin.module.P9.id()
```
## Constants
The following constants are used to configure the pin objects. Note that not all constants are available on all ports.
* Selects the pin mode: `Pin.IN`, `Pin.OUT`, `Pin.OPEN_DRAIN`
* Enables the pull up or pull down resistor: `Pin.PULL_UP`, `Pin.PULL_DOWN`

View File

@@ -1,34 +0,0 @@
# PWM
## class PWM Pulse Width Modulation
### Quick Usage Example
```python
from machine import PWM
pwm = PWM(0, frequency=5000) # use PWM timer 0, with a frequency of 5KHz
# create pwm channel on pin P12 with a duty cycle of 50%
pwm_c = pwm.channel(0, pin='P12', duty_cycle=0.5)
pwm_c.duty_cycle(0.3) # change the duty cycle to 30%
```
### Constructors
#### class machine.PWM\(timer, frequency\)
Create a PWM object. This sets up the `timer` to oscillate at the specified `frequency`. `timer` is an integer from 0 to 3. `frequency` is an integer from 1 Hz to 78 KHz \(this values can change in future upgrades\).
### Methods
#### pwm.channel\(id, pin \* , duty\_cycle=0.5\)
Connect a PWM channel to a pin, setting the initial duty cycle. `id` is an integer from 0 to 7. `pin` is a string argument. `duty_cycle` is a keyword-only float argument, with values between 0 and 1. Returns an instance of `PWMChannel`.
## class PWMChannel — PWM channel
### Methods
#### pwmchannel.duty\_cycle\(value\)
Set the duty cycle for a PWM channel. `value` is a float argument, with values between 0 and 1.

View File

@@ -1,134 +0,0 @@
---
search:
keywords:
- RMT
- Remote
- Remote Controller
- Pulse
---
# RMT
The RMT \(Remote Control\) module is primarily designed to send and receive infrared remote control signals that use on-off-keying of a carrier frequency, but due to its design it can be used to generate various types of signals.
## Quick Usage Example: sending
```python
import machine
# create a RMT object for transmission
rmt = machine.RMT(channel=3, gpio="P20", tx_idle_level=0)
# create series of bits to send
data = (1,0,1,0,1,0,1,0,1)
# define duration of the bits, time unit depends on the selected RMT channel
duration = 10000
# send the signal
rmt.send_pulses(duration, data)
```
## Quick Usage Example: receiving
```python
import machine
# create a RMT object
rmt = machine.RMT(channel=3)
# Configure RTM for receiving
rmt.init(gpio="P20", rx_idle_threshold=12000)
# wait for any number of pulses until one longer than rx_idle_threshold
data = rmt.recv_pulses()
```
## Constructors
#### class machine.RMT\(channel,...\)
Construct an RMT object on the given channel. `channel` can be 2-7. With no additional parameters, the RMT object is created but not initialised. If extra arguments are given, the RMT is initialised for transmission or reception. See `init` for parameters of initialisation. The resolution which a pulse can be sent/received depends on the selected channel:
| Channel | Resolution | Maximum Pulse Width |
| :--- | :--- | :--- |
| 0 | Used by on-board LED | |
| 1 | Used by `pycom.pulses_get()` | |
| 2 | 100nS | 3.2768 ms |
| 3 | 100nS | 3.2768 ms |
| 4 | 1000nS | 32.768 ms |
| 5 | 1000nS | 32.768 ms |
| 6 | 3125nS | 102.4 ms |
| 7 | 3125nS | 102.4 ms |
## Methods
#### rmt.init\(gpio, rx\_idle\_threshold, rx\_filter\_threshold, tx\_idle\_level, tx\_carrier\)
Initialise the RMT peripheral with the given parameters:
* `gpio` is the GPIO Pin to use.
* `rx_idle_threshold` is the maximum duration of a valid pulse. The represented time unit \(resolution\) depends on the selected channel, value can be 0-65535.
* `rx_filter_threshold` is the minimum duration of a valid pulse. The represented time unit \(resolution\) depends on the selected channel, value can be 0-31.
* `tx_idle_level` is the output signal's level after the transmission is finished, can be RMT.HIGH or RMT.LOW.
* `tx_carrier` is the modulation of the pulses to send.
Either `rx_idle_threshold` or `tx_idle_level` must be defined, both cannot be given at the same time because a channel can be configured in RX or TX mode only. `rx_filter_threshold` is not mandatory parameter. If not given then all pulses are accepted with duration less than `rx_idle_threshold`. `tx_carrier` is not mandatory parameters. If not given no modulation is used on the sent pulses.
The `tx_carrier` parameter is a tuple with the following structure:
* `carrier_freq_hz` is the carrier's frequency in Hz.
* `carrier_duty_percent` is the duty percent of the carrier's signal, can be 0%-100%.
* `carrier_level` is the level of the pulse to modulate, can be RMT.HIGH or RMT.LOW.
#### rmt.deinit\(\)
Deinitialise the RMT object.
{% hint style="info" %}
If an RMT object needs to be reconfigured from RX/TX to TX/RX, then either first `deinit()` must be called or the `init()` again with the desired configuration.
{% endhint %}
#### rmt.pulses\_get\(pulses, timeout\)
Reads in pulses from the GPIO pin.
* `pulses` if not specified, this function will keep reading pulses until the
`rx_idle_threshold` is exceeded. If it is specified this function will return
the exactly that number of pulses, ignoring anything shorter than
`rx_filter_threshold` or longer than `rx_idle_threshold`.
* `timeout` is specified, this function will return if the first pulse does
not occur within `timeout` microseconds. If not specified, it will wait
indefinitely.
Return value: Tuple of items with the following structure: `(level, duration)`:
* `level` represents the level of the received bit/pulse, can be 0 or 1.
* `duration` represents the duration of the received pulse, the time unit \(resolution\) depends on the selected channel.
{% hint style="info" %}
Maximum of 128 pulses can be received in a row without receiving "idle" signal. If the incoming pulse sequence contains more than 128 pulses the rest is dropped and the receiver waits for another sequence of pulses. The `pulses_get` function can be called to receive more than 128 pulses, however the above mentioned limitation should be kept in mind when evaluating the received data.
{% endhint %}
#### rmt.pulses\_send\(duration, data, start\_level\)
Generates pulses as defined by the parameters below
* `duration` represents the duration of the pulses to be sent,
the time unit \(resolution\) depends on the selected channel.
* `data` Tuple that represents the sequence of pulses to be sent, must be
composed of 0 or 1 elements.
* `start_level` defines the state \(HIGH/LOW\) of the first pulse given by
`duration` if `data` is not given.
`data` must be a tuple and `duration` can be a tuple or a single number, with `data` being optional. In the case that only `duration` is provided, it must be a tuple and you must also provide `start_level` which will dictate the level of the first duration, the signal level then toggles between each duration value. If `data` is provided and `duration` is a single number, each pulse in `data` will have have an equal length as set by `duration`. If `data` and `duration` are provided as tuples, they must be of the same number of elements, with each pulse lasting its matching duration.
## Constants
* Define the level of the pulse: `RMT.LOW`, `RMT.HIGH`

View File

@@ -1,79 +0,0 @@
# RTC
The RTC is used to keep track of the date and time.
## Quick Usage Example
```python
from machine import RTC
rtc = RTC()
rtc.init((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.now())
```
## Constructors
#### class machine.RTC\(id=0, ...\)
Create an RTC object. See init for parameters of initialisation.
```python
# id of the RTC may be set if multiple are connected. Defaults to id = 0.
rtc = RTC(id=0)
```
## Methods
#### rtc.init\(datetime=None, source=RTC.INTERNAL\_RC\)
Initialise the RTC. The arguments are:
* `datetime` when passed it sets the current time. It is a tuple of the form: `(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])`
* `source` selects the oscillator that drives the RTC. The options are RTC.INTERNAL\_RC and RTC.XTAL\_32KHZ
For example:
```python
# for 2nd of February 2017 at 10:30am (TZ 0)
rtc.init((2017, 2, 28, 10, 30, 0, 0, 0))
```
{% hint style="info" %}
`tzinfo` is ignored by this method. Use `time.timezone` to achieve similar results.
{% endhint %}
#### rtc.now\(\)
Get get the current `datetime` tuple:
```python
# returns datetime tuple
rtc.now()
```
#### rtc.ntp\_sync\(server, \* , update\_period=3600\)
Set up automatic fetch and update the time using NTP \(SNTP\).
* `server` is the URL of the NTP server. Can be set to `None` to disable the periodic updates.
* `update_period` is the number of seconds between updates. Shortest period is 15 seconds.
Can be used like:
```python
rtc.ntp_sync("pool.ntp.org") # this is an example. You can select a more specific server according to your geographical location
```
#### rtc.synced\(\)
Returns `True` if the last `ntp_sync` has been completed, `False` otherwise:
```python
rtc.synced()
```
## Constants
* Clock source: `RTC.INTERNAL_RC`, `RTC.XTAL_32KHZ`

View File

@@ -1,53 +0,0 @@
# SD
The SD card class allows to configure and enable the memory card module of your Pycom module and automatically mount it as `/sd` as part of the file system. There is a single pin combination that can be used for the SD card, and the current implementation only works in 1-bit mode. The pin connections are as follows:
`P8: DAT0`, `P23: SCLK` and `P4: CMD` \(no external pull-up resistors are needed\)
If you have one of the Pycom expansion boards, then simply insert the card into the micro SD socket and run your script.
{% hint style="info" %}
Make sure your SD card is formatted either as FAT16 or FAT32.
{% endhint %}
## Quick Example Usage:
```python
from machine import SD
import os
sd = SD()
os.mount(sd, '/sd')
# check the content
os.listdir('/sd')
# try some standard file operations
f = open('/sd/test.txt', 'w')
f.write('Testing SD card write operations')
f.close()
f = open('/sd/test.txt', 'r')
f.readall()
f.close()
```
## Constructors
#### class machine.SD\(id, ...\)
Create a SD card object. See [`sd.init()`](sd.md#sd-init-id-0) for parameters if initialisation.
## Methods
#### sd.init\(id=0\)
Enable the SD card.
#### sd.deinit\(\)
Disable the SD card.
{% hint style="info" %}
Please note that the SD card library currently supports FAT16/32 formatted SD cards up to 32 GB. Future firmware updates will increase compatibility with additional formats and sizes.
{% endhint %}

View File

@@ -1,87 +0,0 @@
# SPI
SPI is a serial protocol that is driven by a master. At the physical level there are 3 lines: SCK, MOSI, MISO.
See usage model of I2C; SPI is very similar. Main difference is parameters to init the SPI bus:
```python
from machine import SPI
spi = SPI(0, mode=SPI.MASTER, baudrate=1000000, polarity=0, phase=0, firstbit=SPI.MSB)
```
Only required parameter is mode, must be SPI.MASTER. Polarity can be 0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1 to sample data on the first or second clock edge respectively.
## Quick Usage Example
```python
from machine import SPI
# configure the SPI master @ 2MHz
# this uses the SPI default pins for CLK, MOSI and MISO (``P10``, ``P11`` and ``P14``)
spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=0, phase=0)
spi.write(bytes([0x01, 0x02, 0x03, 0x04, 0x05])) # send 5 bytes on the bus
spi.read(5) # receive 5 bytes on the bus
rbuf = bytearray(5)
spi.write_readinto(bytes([0x01, 0x02, 0x03, 0x04, 0x05]), rbuf) # send a receive 5 bytes
```
## Quick Usage Example using non-default pins
```python
from machine import SPI
# configure the SPI master @ 2MHz
# this uses the SPI non-default pins for CLK, MOSI and MISO (``P19``, ``P20`` and ``P21``)
spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=0, phase=0, pins=('P19','P20','P21'))
spi.write(bytes([0x01, 0x02, 0x03, 0x04, 0x05])) # send 5 bytes on the bus
spi.read(5) # receive 5 bytes on the bus
rbuf = bytearray(5)
spi.write_readinto(bytes([0x01, 0x02, 0x03, 0x04, 0x05]), rbuf) # send a receive 5 bytes
```
## Constructors
#### class machine.SPI\(id, ...\)
Construct an SPI object on the given bus. `id` can be only 0. With no additional parameters, the SPI object is created but not initialised \(it has the settings from the last initialisation of the bus, if any\). If extra arguments are given, the bus is initialised. See init for parameters of initialisation.
## Methods
#### spi.init\(mode, baudrate=1000000, \* , polarity=0, phase=0, bits=8, firstbit=SPI.MSB, pins=\(CLK, MOSI, MISO\)\)
Initialise the SPI bus with the given parameters:
* `mode` must be SPI.MASTER.
* `baudrate` is the SCK clock rate.
* `polarity` can be 0 or 1, and is the level the idle clock line sits at.
* `phase` can be 0 or 1 to sample data on the first or second clock edge respectively.
* `bits` is the width of each transfer, accepted values are 8, 16 and 32.
* `firstbit` can be SPI.MSB or SPI.LSB.
* `pins` is an optional tuple with the pins to assign to the SPI bus. If the pins argument is not given the default pins will be selected \(`P10` as CLK,`P11` as MOSI and `P14` as MISO\). If pins is passed as None then no pin assignment will be made.
#### spi.deinit\(\)
Turn off the SPI bus.
#### spi.write\(buf\)
Write the data contained in `buf`. Returns the number of bytes written.
#### spi.read\(nbytes, \* , write=0x00\)
Read the `nbytes` while writing the data specified by `write`. Returns the bytes read.
#### spi.readinto\(buf, \* , write=0x00\)
Read into the buffer specified by `buf` while writing the data specified by `write`. Return the number of bytes read.
#### spi.write\_readinto\(write\_buf, read\_buf\)
Write from `write_buf` and read into `read_buf`. Both buffers must have the same length. Returns the number of bytes written
## Constants
* For initialising the SPI bus to master: `SPI.MASTER`
* Set the first bit to be the most significant bit: `SPI.MSB`
* Set the first bit to be the least significant bit: `SPI.LSB`

View File

@@ -1,127 +0,0 @@
# Timer
## class Timer Measure Time and Set Alarms
Timers can be used for a great variety of tasks, like measuring time spans or being notified that a specific interval has elapsed.
These two concepts are grouped into two different subclasses:
`Chrono`: used to measure time spans. `Alarm`: to get interrupted after a specific interval.
{% hint style="info" %}
You can create as many of these objects as needed.
{% endhint %}
### Constructors
#### class Timer.Chrono\(\)
Create a chronometer object.
#### class Timer.Alarm\(handler=None, s, \* , ms, us, arg=None, periodic=False\)
Create an Alarm object.
* `handler`: will be called after the interval has elapsed. If set to `None`, the alarm will be disabled after creation.
* `arg`: an optional argument can be passed to the callback handler function. If `None` is specified, the function will receive the object that triggered the alarm.
* `s, ms, us`: the interval can be specified in seconds \(float\), miliseconds \(integer\) or microseconds \(integer\). Only one at a time can be specified.
* `periodic`: an alarm can be set to trigger repeatedly by setting this parameter to `True`.
### Methods
#### Timer.sleep\_us\(\)
Delay for a given number of microseconds, should be positive or 0 \(for speed, the condition is not enforced\). Internally it uses the same timer as the other elements of the `Timer` class. It compensates for the calling overhead, so for example, 100us should be really close to 100us. For times bigger than 10,000us it releases the GIL to let other threads run, so exactitude is not guaranteed for delays longer than that.
## class Chrono
Can be used to measure time spans.
### Methods
#### chrono.start\(\)
Start the chronometer.
#### chrono.stop\(\)
Stop the chronometer.
#### chrono.reset\(\)
Reset the time count to 0.
#### chrono.read\(\)
Get the elapsed time in seconds.
#### chrono.read\_ms\(\)
Get the elapsed time in milliseconds.
#### chrono.read\_us\(\)
Get the elapsed time in microseconds.
Example:
```python
from machine import Timer
import time
chrono = Timer.Chrono()
chrono.start()
time.sleep(1.25) # simulate the first lap took 1.25 seconds
lap = chrono.read() # read elapsed time without stopping
time.sleep(1.5)
chrono.stop()
total = chrono.read()
print()
print("\nthe racer took %f seconds to finish the race" % total)
print(" %f seconds in the first lap" % lap)
print(" %f seconds in the last lap" % (total - lap))
class Alarm get interrupted after a specific interval
```
## class Alarm
Used to get interrupted after a specific interval.
### Methods
#### alarm.callback\(handler, \* , arg=None\)
Specify a callback handler for the alarm. If set to `None`, the alarm will be disabled.
An optional argument `arg` can be passed to the callback handler function. If `None` is specified, the function will receive the object that triggered the alarm.
#### alarm.cancel\(\)
Disables the alarm.
Example:
```python
from machine import Timer
class Clock:
def __init__(self):
self.seconds = 0
self.__alarm = Timer.Alarm(self._seconds_handler, 1, periodic=True)
def _seconds_handler(self, alarm):
self.seconds += 1
print("%02d seconds have passed" % self.seconds)
if self.seconds == 10:
alarm.cancel() # stop counting after 10 seconds
clock = Clock()
```
{% hint style="info" %}
For more information on how Pycoms products handle interrupts, see [notes](../../notes.md#interrupt-handling).
{% endhint %}

View File

@@ -1,135 +0,0 @@
# UART
UART implements the standard UART/USART duplex serial communications protocol. At the physical level it consists of 2 lines: RXD and TXD. The unit of communication is a character \(not to be confused with a string character\) which can be 5, 6, 7 or 8 bits wide.
UART objects can be created and initialised using:
```python
from machine import UART
uart = UART(1, 9600) # init with given baudrate
uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
```
Bits can be `5, 6, 7, 8`. Parity can be `None`, `UART.EVEN` or `UART.ODD`. Stop can be `1, 1.5 or 2`.
A UART object acts like a stream object therefore reading and writing is done using the standard stream methods:
```python
uart.read(10) # read 10 characters, returns a bytes object
uart.readall() # read all available characters
uart.readline() # read a line
uart.readinto(buf) # read and store into the given buffer
uart.write('abc') # write the 3 characters
```
To check if there is anything to be read, use:
```python
uart.any() # returns the number of characters available for reading
```
## Quick Usage Example
```python
from machine import UART
# this uses the UART_1 default pins for TXD and RXD (``P3`` and ``P4``)
uart = UART(1, baudrate=9600)
uart.write('hello')
uart.read(5) # read up to 5 bytes
```
## Quick Usage Example using non-default pins \(TXD/RXD only\)
```python
from machine import UART
# this uses the UART_1 non-default pins for TXD and RXD (``P20`` and ``P21``)
uart = UART(1, baudrate=9600, pins=('P20','P21'))
uart.write('hello')
uart.read(5) # read up to 5 bytes
```
## Quick Usage Example using non-default pins \(TXD/RXD and flow control\)
```python
from machine import UART
# this uses the UART_1 non-default pins for TXD, RXD, RTS and CTS (``P20``, ``P21``, ``P22``and ``P23``)
uart = UART(1, baudrate=9600, pins=('P20', 'P21', 'P22', 'P23'))
uart.write('hello')
uart.read(5) # read up to 5 bytes
```
## Constructors
#### class machine.UART\(bus, ...\)
Construct a UART object on the given `bus`. `bus` can be `0, 1 or 2`. If the `bus` is not given, the default one will be selected \(`0`\) or the selection will be made based on the given pins.
{% hint style="danger" %}
On the GPy/FiPy UART2 is unavailable because it is used to communicate with the cellular radio.
{% endhint %}
## Methods
#### uart.init\(baudrate=9600, bits=8, parity=None, stop=1, \* , timeout\_chars=2, pins=\(TXD, RXD, RTS, CTS\)\)
Initialise the UART bus with the given parameters:
* `baudrate` is the clock rate.
* `bits` is the number of bits per character. Can be `5, 6, 7 or 8`.
* `parity` is the parity, `None`, UART.EVEN or UART.ODD.
* `stop` is the number of stop bits, `1 or 2`.
* `timeout_chars` Rx timeout defined in number of characters. The value given here will be multiplied by the time a characters takes to be transmitted at the configured `baudrate`.
* `pins` is a 4 or 2 item list indicating the TXD, RXD, RTS and CTS pins \(in that order\). Any of the pins can be `None` if one wants the UART to operate with limited functionality. If the RTS pin is given the the RX pin must be given as well. The same applies to CTS. When no pins are given, then the default set of TXD \(P1\) and RXD \(P0\) pins is taken, and hardware flow control will be disabled. If `pins=None`, no pin assignment will be made.
#### uart.deinit\(\)
Turn off the UART bus.
#### uart.any\(\)
Return the number of characters available for reading.
#### uart.read\(\[nbytes\]\)
Read characters. If `nbytes` is specified then read at most that many bytes.
Return value: a bytes object containing the bytes read in. Returns `None` on timeout.
#### uart.readall\(\)
Read as much data as possible.
Return value: a bytes object or `None` on timeout.
#### uart.readinto\(buf\[, nbytes\]\)
Read bytes into the `buf`. If `nbytes` is specified then read at most that many bytes. Otherwise, read at most `len(buf)` bytes.
Return value: number of bytes read and stored into `buf` or `None` on timeout.
#### uart.readline\(\)
Read a line, ending in a newline character. If such a line exists, return is immediate. If the timeout elapses, all available data is returned regardless of whether a newline exists.
Return value: the line read or `None` on timeout if no data is available.
#### uart.write\(buf\)
Write the buffer of bytes to the bus.
Return value: number of bytes written or None on timeout.
#### uart.sendbreak\(\)
Send a break condition on the bus. This drives the bus low for a duration of 13 bits. Return value: `None`.
#### uart.wait\_tx\_done\(timeout\_ms\)
Waits at most `timeout_ms` for the last Tx transaction to complete. Returns `True` if all data has been sent and the TX buffer has no data in it, otherwise returns `False`.
## Constants
* Parity types \(along with `None`\): `UART.EVEN`, `UART.ODD`
* IRQ trigger sources: `UART.RX_ANY`

View File

@@ -1,28 +0,0 @@
# WDT
The WDT is used to restart the system when the application crashes and ends up into a non recoverable state. After enabling, the application must "feed" the watchdog periodically to prevent it from expiring and resetting the system.
## Quick Usage Example
```python
from machine import WDT
wdt = WDT(timeout=2000) # enable it with a timeout of 2 seconds
wdt.feed()
```
## Constructors
#### class machine.WDT\(id=0, timeout\)
Create a WDT object and start it. The `id` can only be `0`. See the init method for the parameters of initialisation.
## Methods
#### wdt.init\(timeout\)
Initialises the watchdog timer. The timeout must be given in milliseconds. Once it is running the WDT cannot be stopped but the timeout can be re-configured at any point in time.
#### wdt.feed\(\)
Feed the WDT to prevent it from resetting the system. The application should place this call in a sensible place ensuring that the WDT is only fed after verifying that everything is functioning correctly.