docs: Import documentation from source-code inline comments.

The inline docs (prefixed with /// in .c files) have been converted to
RST format and put in the docs subdirectory.
This commit is contained in:
Damien George 2014-10-31 01:37:19 +00:00
parent 7c4445afe1
commit 88d3054ac0
39 changed files with 2350 additions and 9 deletions

View File

@ -60,7 +60,7 @@ copyright = '2014, Damien P. George'
# The short X.Y version.
version = '1.3'
# The full version, including alpha/beta/rc tags.
release = '1.3.1'
release = '1.3.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View File

@ -14,10 +14,11 @@ Software
--------
.. toctree::
:maxdepth: 2
:maxdepth: 1
general.rst
tutorial/index.rst
library/index.rst
..
.. - Reference for the [pyb module](module/pyb/ "pyb module").

60
docs/library/cmath.rst Normal file
View File

@ -0,0 +1,60 @@
:mod:`cmath` --- mathematical functions for complex numbers
===========================================================
.. module:: cmath
:synopsis: mathematical functions for complex numbers
The ``cmath`` module provides some basic mathematical funtions for
working with complex numbers.
Functions
---------
.. function:: cos(z)
Return the cosine of ``z``.
.. function:: exp(z)
Return the exponential of ``z``.
.. function:: log(z)
Return the natural logarithm of ``z``. The branch cut is along the negative real axis.
.. function:: log10(z)
Return the base-10 logarithm of ``z``. The branch cut is along the negative real axis.
.. function:: phase(z)
Returns the phase of the number ``z``, in the range (-pi, +pi].
.. function:: polar(z)
Returns, as a tuple, the polar form of ``z``.
.. function:: rect(r, phi)
Returns the complex number with modulus ``r`` and phase ``phi``.
.. function:: sin(z)
Return the sine of ``z``.
.. function:: sqrt(z)
Return the square-root of ``z``.
Constants
---------
.. data:: e
base of the natural logarithm
.. data:: pi
the ratio of a circle's circumference to its diameter

30
docs/library/gc.rst Normal file
View File

@ -0,0 +1,30 @@
:mod:`gc` --- control the garbage collector
===========================================
.. module:: gc
:synopsis: control the garbage collector
Functions
---------
.. function:: collect()
Run a garbage collection.
.. function:: disable()
Disable the garbage collector.
.. function:: enable()
Enable the garbage collector.
.. function:: mem_alloc()
Return the number of bytes of heap RAM that are allocated.
.. function:: mem_free()
Return the number of bytes of available heap RAM.

35
docs/library/index.rst Normal file
View File

@ -0,0 +1,35 @@
Micro Python libraries
======================
Python standard libraries
-------------------------
.. toctree::
:maxdepth: 1
cmath.rst
gc.rst
math.rst
os.rst
select.rst
sys.rst
time.rst
Micro Python reduced libraries
------------------------------
.. toctree::
:maxdepth: 1
usocket.rst
uheapq.rst
ujson.rst
Libraries specific to the pyboard
---------------------------------
.. toctree::
:maxdepth: 2
pyb.rst
network.rst

145
docs/library/math.rst Normal file
View File

@ -0,0 +1,145 @@
:mod:`math` --- mathematical functions
======================================
.. module:: math
:synopsis: mathematical functions
The ``math`` module provides some basic mathematical funtions for
working with floating-point numbers.
Functions
---------
.. function:: acos(x)
.. function:: acosh(x)
.. function:: asin(x)
.. function:: asinh(x)
.. function:: atan(x)
.. function:: atan2(y, x)
.. function:: atanh(x)
.. function:: ceil(x)
.. function:: copysign(x, y)
.. function:: cos(x)
.. function:: cosh(x)
.. function:: degrees(x)
.. function:: erf(x)
Return the error function of ``x``.
.. function:: erfc(x)
Return the complementary error function of ``x``.
.. function:: exp(x)
.. function:: expm1(x)
.. function:: fabs(x)
.. function:: floor(x)
.. function:: fmod(x, y)
.. function:: frexp(x)
Converts a floating-point number to fractional and integral components.
.. function:: gamma(x)
Return the gamma function of ``x``.
.. function:: isfinite(x)
.. function:: isinf(x)
.. function:: isnan(x)
.. function:: ldexp(x, exp)
.. function:: lgamma(x)
return the natural logarithm of the gamma function of ``x``.
.. function:: log(x)
.. function:: log10(x)
.. function:: log2(x)
.. function:: modf(x)
.. function:: pow(x, y)
Returns ``x`` to the power of ``y``.
.. function:: radians(x)
.. function:: sin(x)
.. function:: sinh(x)
.. function:: sqrt(x)
Returns the square root of ``x``.
.. function:: tan(x)
.. function:: tanh(x)
.. function:: trunc(x)
Constants
---------
.. data:: e
base of the natural logarithm
.. data:: pi
the ratio of a circle's circumference to its diameter

63
docs/library/network.rst Normal file
View File

@ -0,0 +1,63 @@
****************************************
:mod:`network` --- network configuration
****************************************
.. module:: network
:synopsis: network configuration
This module provides network drivers and routing configuration.
class CC3k
==========
Constructors
------------
.. class:: CC3k(spi, pin_cs, pin_en, pin_irq)
Initialise the CC3000 using the given SPI bus and pins and return a CC3k object.
Methods
-------
.. method:: cc3k.connect(ssid, key=None, \*, security=WPA2, bssid=None)
class WIZnet5k
==============
This class allows you to control WIZnet5x00 Ethernet adaptors based on
the W5200 and W5500 chipsets (only W5200 tested).
Example usage::
import wiznet5k
w = wiznet5k.WIZnet5k()
print(w.ipaddr())
w.gethostbyname('micropython.org')
s = w.socket()
s.connect(('192.168.0.2', 8080))
s.send('hello')
print(s.recv(10))
Constructors
------------
.. class:: WIZnet5k(spi, pin_cs, pin_rst)
Create and return a WIZnet5k object.
Methods
-------
.. method:: wiznet5k.ipaddr([(ip, subnet, gateway, dns)])
Get/set IP address, subnet mask, gateway and DNS.
.. method:: wiznet5k.regs()
Dump WIZnet5k registers.

65
docs/library/os.rst Normal file
View File

@ -0,0 +1,65 @@
:mod:`os` --- basic "operating system" services
===============================================
.. module:: os
:synopsis: basic "operating system" services
The ``os`` module contains functions for filesystem access and ``urandom``.
The filesystem has ``/`` as the root directory, and the available physical
drives are accessible from here. They are currently:
/flash -- the internal flash filesystem
/sd -- the SD card (if it exists)
On boot up, the current directory is ``/flash`` if no SD card is inserted,
otherwise it is ``/sd``.
Functions
---------
.. function:: chdir(path)
Change current directory.
.. function:: getcwd()
Get the current directory.
.. function:: listdir([dir])
With no argument, list the current directory. Otherwise list the given directory.
.. function:: mkdir(path)
Create a new directory.
.. function:: remove(path)
Remove a file.
.. function:: rmdir(path)
Remove a directory.
.. function:: stat(path)
Get the status of a file or directory.
.. function:: sync()
Sync all filesystems.
.. function:: urandom(n)
Return a bytes object with n random bytes, generated by the hardware
random number generator.
Constants
---------
.. data:: sep
separation character used in paths

50
docs/library/pyb.ADC.rst Normal file
View File

@ -0,0 +1,50 @@
class ADC =-- analog to digital conversion: read analog values on a pin
=======================================================================
Usage::
import pyb
adc = pyb.ADC(pin) # create an analog object from a pin
val = adc.read() # read an analog value
adc = pyb.ADCAll(resolution) # creale an ADCAll object
val = adc.read_channel(channel) # read the given channel
val = adc.read_core_temp() # read MCU temperature
val = adc.read_core_vbat() # read MCU VBAT
val = adc.read_core_vref() # read MCU VREF
Constructors
------------
.. class:: pyb.ADC(pin)
Create an ADC object associated with the given pin.
This allows you to then read analog values on that pin.
Methods
-------
.. method:: adc.read()
Read the value on the analog pin and return it. The returned value
will be between 0 and 4095.
.. method:: adc.read_timed(buf, freq)
Read analog values into the given buffer at the given frequency. Buffer
can be bytearray or array.array for example. If a buffer with 8-bit elements
is used, sample resolution will be reduced to 8 bits.
Example::
adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19
buf = bytearray(100) # create a buffer of 100 bytes
adc.read_timed(buf, 10) # read analog values into buf at 10Hz
# this will take 10 seconds to finish
for val in buf: # loop over all values
print(val) # print the value out
This function does not allocate any memory.

View File

@ -0,0 +1,51 @@
class Accel --- accelerometer control
=====================================
Accel is an object that controls the accelerometer. Example usage::
accel = pyb.Accel()
for i in range(10):
print(accel.x(), accel.y(), accel.z())
Raw values are between -32 and 31.
Constructors
------------
.. class:: pyb.Accel()
Create and return an accelerometer object.
Note: if you read accelerometer values immediately after creating this object
you will get 0. It takes around 20ms for the first sample to be ready, so,
unless you have some other code between creating this object and reading its
values, you should put a ``pyb.delay(20)`` after creating it. For example::
accel = pyb.Accel()
pyb.delay(20)
print(accel.x())
Methods
-------
.. method:: accel.filtered_xyz()
Get a 3-tuple of filtered x, y and z values.
.. method:: accel.tilt()
Get the tilt register.
.. method:: accel.x()
Get the x-axis value.
.. method:: accel.y()
Get the y-axis value.
.. method:: accel.z()
Get the z-axis value.

87
docs/library/pyb.CAN.rst Normal file
View File

@ -0,0 +1,87 @@
class CAN --- controller area network communication bus
=======================================================
CAN implements the standard CAN communications protocol. At
the physical level it consists of 2 lines: RX and TX. Note that
to connect the pyboard to a CAN bus you must use a CAN transceiver
to convert the CAN logic signals from the pyboard to the correct
voltage levels on the bus.
Note that this driver does not yet support filter configuration
(it defaults to a single filter that lets through all messages),
or bus timing configuration (except for setting the prescaler).
Example usage (works without anything connected)::
from pyb import CAN
can = pyb.CAN(1, pyb.CAN.LOOPBACK)
can.send('message!', 123) # send message to id 123
can.recv(0) # receive message on FIFO 0
Constructors
------------
.. class:: pyb.CAN(bus, ...)
Construct a CAN object on the given bus. ``bus`` can be 1-2, or 'YA' or 'YB'.
With no additional parameters, the CAN 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.
The physical pins of the CAN busses are:
- ``CAN(1)`` is on ``YA``: ``(RX, TX) = (Y3, Y4) = (PB8, PB9)``
- ``CAN(2)`` is on ``YB``: ``(RX, TX) = (Y5, Y6) = (PB12, PB13)``
Methods
-------
.. method:: can.init(mode, extframe=False, prescaler=100, \*, sjw=1, bs1=6, bs2=8)
Initialise the CAN bus with the given parameters:
- ``mode`` is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK
If ``extframe`` is True then the bus uses extended identifiers in the frames (29 bits).
Otherwise it uses standard 11 bit identifiers.
.. method:: can.deinit()
Turn off the CAN bus.
.. method:: can.any(fifo)
Return ``True`` if any message waiting on the FIFO, else ``False``.
.. method:: can.recv(fifo, \*, timeout=5000)
Receive data on the bus:
- ``fifo`` is an integer, which is the FIFO to receive on
- ``timeout`` is the timeout in milliseconds to wait for the receive.
Return value: buffer of data bytes.
.. method:: can.send(send, addr, \*, timeout=5000)
Send a message on the bus:
- ``send`` is the data to send (an integer to send, or a buffer object).
- ``addr`` is the address to send to
- ``timeout`` is the timeout in milliseconds to wait for the send.
Return value: ``None``.
Constants
---------
.. data:: CAN.NORMAL
.. data:: CAN.LOOPBACK
.. data:: CAN.SILENT
.. data:: CAN.SILENT_LOOPBACK
the mode of the CAN bus

67
docs/library/pyb.DAC.rst Normal file
View File

@ -0,0 +1,67 @@
class DAC --- digital to analog conversion
==========================================
The DAC is used to output analog values (a specific voltage) on pin X5 or pin X6.
The voltage will be between 0 and 3.3V.
*This module will undergo changes to the API.*
Example usage::
from pyb import DAC
dac = DAC(1) # create DAC 1 on pin X5
dac.write(128) # write a value to the DAC (makes X5 1.65V)
To output a continuous sine-wave::
import math
from pyb import DAC
# create a buffer containing a sine-wave
buf = bytearray(100)
for i in range(len(buf)):
buf[i] = 128 + int(127 \* math.sin(2 \* math.pi \* i / len(buf)))
# output the sine-wave at 400Hz
dac = DAC(1)
dac.write_timed(buf, 400 \* len(buf), mode=DAC.CIRCULAR)
Constructors
------------
.. class:: pyb.DAC(port)
Construct a new DAC object.
``port`` can be a pin object, or an integer (1 or 2).
DAC(1) is on pin X5 and DAC(2) is on pin X6.
Methods
-------
.. method:: dac.noise(freq)
Generate a pseudo-random noise signal. A new random sample is written
to the DAC output at the given frequency.
.. method:: dac.triangle(freq)
Generate a triangle wave. The value on the DAC output changes at
the given frequency, and the frequence of the repeating triangle wave
itself is 256 (or 1024, need to check) times smaller.
.. method:: dac.write(value)
Direct access to the DAC output (8 bit only at the moment).
.. method:: dac.write_timed(data, freq, \*, mode=DAC.NORMAL)
Initiates a burst of RAM to DAC using a DMA transfer.
The input data is treated as an array of bytes (8 bit data).
``mode`` can be ``DAC.NORMAL`` or ``DAC.CIRCULAR``.
TIM6 is used to control the frequency of the transfer.

111
docs/library/pyb.ExtInt.rst Normal file
View File

@ -0,0 +1,111 @@
class ExtInt --- configure I/O pins to interrupt on external events
===================================================================
There are a total of 22 interrupt lines. 16 of these can come from GPIO pins
and the remaining 6 are from internal sources.
For lines 0 thru 15, a given line can map to the corresponding line from an
arbitrary port. So line 0 can map to Px0 where x is A, B, C, ... and
line 1 can map to Px1 where x is A, B, C, ... ::
def callback(line):
print("line =", line)
Note: ExtInt will automatically configure the gpio line as an input. ::
extint = pyb.ExtInt(pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, callback)
Now every time a falling edge is seen on the X1 pin, the callback will be
called. Caution: mechanical pushbuttons have "bounce" and pushing or
releasing a switch will often generate multiple edges.
See: http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed
explanation, along with various techniques for debouncing.
Trying to register 2 callbacks onto the same pin will throw an exception.
If pin is passed as an integer, then it is assumed to map to one of the
internal interrupt sources, and must be in the range 16 thru 22.
All other pin objects go through the pin mapper to come up with one of the
gpio pins. ::
extint = pyb.ExtInt(pin, mode, pull, callback)
Valid modes are pyb.ExtInt.IRQ_RISING, pyb.ExtInt.IRQ_FALLING,
pyb.ExtInt.IRQ_RISING_FALLING, pyb.ExtInt.EVT_RISING,
pyb.ExtInt.EVT_FALLING, and pyb.ExtInt.EVT_RISING_FALLING.
Only the IRQ_xxx modes have been tested. The EVT_xxx modes have
something to do with sleep mode and the WFE instruction.
Valid pull values are pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN, pyb.Pin.PULL_NONE.
There is also a C API, so that drivers which require EXTI interrupt lines
can also use this code. See extint.h for the available functions and
usrsw.h for an example of using this.
Constructors
------------
.. class:: pyb.ExtInt(pin, mode, pull, callback)
Create an ExtInt object:
- ``pin`` is the pin on which to enable the interrupt (can be a pin object or any valid pin name).
- ``mode`` can be one of:
- ``ExtInt.IRQ_RISING`` - trigger on a rising edge;
- ``ExtInt.IRQ_FALLING`` - trigger on a falling edge;
- ``ExtInt.IRQ_RISING_FALLING`` - trigger on a rising or falling edge.
- ``pull`` can be one of:
- ``pyb.Pin.PULL_NONE`` - no pull up or down resistors;
- ``pyb.Pin.PULL_UP`` - enable the pull-up resistor;
- ``pyb.Pin.PULL_DOWN`` - enable the pull-down resistor.
- ``callback`` is the function to call when the interrupt triggers. The
callback function must accept exactly 1 argument, which is the line that
triggered the interrupt.
Class methods
-------------
.. method:: ExtInt.regs()
Dump the values of the EXTI registers.
Methods
-------
.. method:: extint.disable()
Disable the interrupt associated with the ExtInt object.
This could be useful for debouncing.
.. method:: extint.enable()
Enable a disabled interrupt.
.. method:: extint.line()
Return the line number that the pin is mapped to.
.. method:: extint.swint()
Trigger the callback from software.
Constants
---------
.. data:: ExtInt.IRQ_FALLING
interrupt on a falling edge
.. data:: ExtInt.IRQ_RISING
interrupt on a rising edge
.. data:: ExtInt.IRQ_RISING_FALLING
interrupt on a rising or falling edge

151
docs/library/pyb.I2C.rst Normal file
View File

@ -0,0 +1,151 @@
class I2C --- a two-wire serial protocol
========================================
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::
from pyb import I2C
i2c = I2C(1) # create on bus 1
i2c = I2C(1, I2C.MASTER) # create and init as a master
i2c.init(I2C.MASTER, baudrate=20000) # init as a master
i2c.init(I2C.SLAVE, addr=0x42) # init as a slave with given address
i2c.deinit() # turn off the peripheral
Printing the i2c object gives you information about its configuration.
Basic methods for slave are send and recv::
i2c.send('abc') # send 3 bytes
i2c.send(0x42) # send a single byte, given by the number
data = i2c.recv(3) # receive 3 bytes
To receive inplace, first create a bytearray::
data = bytearray(3) # create a buffer
i2c.recv(data) # receive 3 bytes, writing them into data
You can specify a timeout (in ms)::
i2c.send(b'123', timeout=2000) # timout after 2 seconds
A master must specify the recipient's address::
i2c.init(I2C.MASTER)
i2c.send('123', 0x42) # send 3 bytes to slave with address 0x42
i2c.send(b'456', addr=0x42) # keyword for address
Master also has other methods::
i2c.is_ready(0x42) # check if slave 0x42 is ready
i2c.scan() # scan for slaves on the bus, returning
# a list of valid addresses
i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of slave 0x42,
# starting at address 2 in the slave
i2c.mem_write('abc', 0x42, 2, timeout=1000)
Constructors
------------
.. class:: pyb.I2C(bus, ...)
Construct an I2C object on the given bus. ``bus`` can be 1 or 2.
With no additional parameters, the I2C 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.
The physical pins of the I2C busses are:
- ``I2C(1)`` is on the X position: ``(SCL, SDA) = (X9, X10) = (PB6, PB7)``
- ``I2C(2)`` is on the Y position: ``(SCL, SDA) = (Y9, Y10) = (PB10, PB11)``
Methods
-------
.. method:: i2c.deinit()
Turn off the I2C bus.
.. method:: i2c.init(mode, \*, addr=0x12, baudrate=400000, gencall=False)
Initialise the I2C bus with the given parameters:
- ``mode`` must be either ``I2C.MASTER`` or ``I2C.SLAVE``
- ``addr`` is the 7-bit address (only sensible for a slave)
- ``baudrate`` is the SCL clock rate (only sensible for a master)
- ``gencall`` is whether to support general call mode
.. method:: i2c.is_ready(addr)
Check if an I2C device responds to the given address. Only valid when in master mode.
.. method:: i2c.mem_read(data, addr, memaddr, timeout=5000, addr_size=8)
Read from the memory of an I2C device:
- ``data`` can be an integer or a buffer to read into
- ``addr`` is the I2C device address
- ``memaddr`` is the memory location within the I2C device
- ``timeout`` is the timeout in milliseconds to wait for the read
- ``addr_size`` selects width of memaddr: 8 or 16 bits
Returns the read data.
This is only valid in master mode.
.. method:: i2c.mem_write(data, addr, memaddr, timeout=5000, addr_size=8)
Write to the memory of an I2C device:
- ``data`` can be an integer or a buffer to write from
- ``addr`` is the I2C device address
- ``memaddr`` is the memory location within the I2C device
- ``timeout`` is the timeout in milliseconds to wait for the write
- ``addr_size`` selects width of memaddr: 8 or 16 bits
Returns ``None``.
This is only valid in master mode.
.. method:: i2c.recv(recv, addr=0x00, timeout=5000)
Receive data on the bus:
- ``recv`` can be an integer, which is the number of bytes to receive,
or a mutable buffer, which will be filled with received bytes
- ``addr`` is the address to receive from (only required in master mode)
- ``timeout`` is the timeout in milliseconds to wait for the receive
Return value: if ``recv`` is an integer then a new buffer of the bytes received,
otherwise the same buffer that was passed in to ``recv``.
.. method:: i2c.scan()
Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond.
Only valid when in master mode.
.. method:: i2c.send(send, addr=0x00, timeout=5000)
Send data on the bus:
- ``send`` is the data to send (an integer to send, or a buffer object)
- ``addr`` is the address to send to (only required in master mode)
- ``timeout`` is the timeout in milliseconds to wait for the send
Return value: ``None``.
Constants
---------
.. data:: I2C.MASTER
for initialising the bus to master mode
.. data:: I2C.SLAVE
for initialising the bus to slave mode

94
docs/library/pyb.LCD.rst Normal file
View File

@ -0,0 +1,94 @@
class LCD --- LCD control for the LCD touch-sensor pyskin
=========================================================
The LCD class is used to control the LCD on the LCD touch-sensor pyskin,
LCD32MKv1.0. The LCD is a 128x32 pixel monochrome screen, part NHD-C12832A1Z.
The pyskin must be connected in either the X or Y positions, and then
an LCD object is made using::
lcd = pyb.LCD('X') # if pyskin is in the X position
lcd = pyb.LCD('Y') # if pyskin is in the Y position
Then you can use::
lcd.light(True) # turn the backlight on
lcd.write('Hello world!\n') # print text to the screen
This driver implements a double buffer for setting/getting pixels.
For example, to make a bouncing dot, try::
x = y = 0
dx = dy = 1
while True:
# update the dot's position
x += dx
y += dy
# make the dot bounce of the edges of the screen
if x <= 0 or x >= 127: dx = -dx
if y <= 0 or y >= 31: dy = -dy
lcd.fill(0) # clear the buffer
lcd.pixel(x, y, 1) # draw the dot
lcd.show() # show the buffer
pyb.delay(50) # pause for 50ms
Constructors
------------
.. class:: pyb.LCD(skin_position)
Construct an LCD object in the given skin position. ``skin_position`` can be 'X' or 'Y', and
should match the position where the LCD pyskin is plugged in.
Methods
-------
.. method:: lcd.command(instr_data, buf)
Send an arbitrary command to the LCD. Pass 0 for ``instr_data`` to send an
instruction, otherwise pass 1 to send data. ``buf`` is a buffer with the
instructions/data to send.
.. method:: lcd.contrast(value)
Set the contrast of the LCD. Valid values are between 0 and 47.
.. method:: lcd.fill(colour)
Fill the screen with the given colour (0 or 1 for white or black).
This method writes to the hidden buffer. Use ``show()`` to show the buffer.
.. method:: lcd.get(x, y)
Get the pixel at the position ``(x, y)``. Returns 0 or 1.
This method reads from the visible buffer.
.. method:: lcd.light(value)
Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off.
.. method:: lcd.pixel(x, y, colour)
Set the pixel at ``(x, y)`` to the given colour (0 or 1).
This method writes to the hidden buffer. Use ``show()`` to show the buffer.
.. method:: lcd.show()
Show the hidden buffer on the screen.
.. method:: lcd.text(str, x, y, colour)
Draw the given text to the position ``(x, y)`` using the given colour (0 or 1).
This method writes to the hidden buffer. Use ``show()`` to show the buffer.
.. method:: lcd.write(str)
Write the string ``str`` to the screen. It will appear immediately.

36
docs/library/pyb.LED.rst Normal file
View File

@ -0,0 +1,36 @@
class LED --- LED object
========================
The LED object controls an individual LED (Light Emitting Diode).
Constructors
------------
.. class:: pyb.LED(id)
Create an LED object associated with the given LED:
- ``id`` is the LED number, 1-4.
Methods
-------
.. method:: led.intensity([value])
Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on).
If no argument is given, return the LED intensity.
If an argument is given, set the LED intensity and return ``None``.
.. method:: led.off()
Turn the LED off.
.. method:: led.on()
Turn the LED on.
.. method:: led.toggle()
Toggle the LED between on and off.

208
docs/library/pyb.Pin.rst Normal file
View File

@ -0,0 +1,208 @@
class Pin --- control I/O pins
==============================
A pin is the basic object to control I/O pins. 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.
Usage Model:
All Board Pins are predefined as pyb.Pin.board.Name ::
x1_pin = pyb.Pin.board.X1
g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN)
CPU pins which correspond to the board pins are available
as ``pyb.cpu.Name``. For the CPU pins, the names are the port letter
followed by the pin number. On the PYBv1.0, ``pyb.Pin.board.X1`` and
``pyb.Pin.cpu.B6`` are the same pin.
You can also use strings::
g = pyb.Pin('X1', pyb.Pin.OUT_PP)
Users can add their own names::
MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 }
pyb.Pin.dict(MyMapperDict)
g = pyb.Pin("LeftMotorDir", pyb.Pin.OUT_OD)
and can query mappings ::
pin = pyb.Pin("LeftMotorDir")
Users can also add their own mapping function::
def MyMapper(pin_name):
if pin_name == "LeftMotorDir":
return pyb.Pin.cpu.A0
pyb.Pin.mapper(MyMapper)
So, if you were to call: ``pyb.Pin("LeftMotorDir", pyb.Pin.OUT_PP)``
then ``"LeftMotorDir"`` is passed directly to the mapper function.
To summarise, the following order determines how things get mapped into
an ordinal pin number:
1. Directly specify a pin object
2. User supplied mapping function
3. User supplied mapping (object must be usable as a dictionary key)
4. Supply a string which matches a board pin
5. Supply a string which matches a CPU port/pin
You can set ``pyb.Pin.debug(True)`` to get some debug information about
how a particular object gets mapped to a pin.
Constructors
------------
.. class:: pyb.Pin(id, ...)
Create a new Pin object associated with the id. If additional arguments are given,
they are used to initialise the pin. See ``init``.
Class methods
-------------
.. method:: Pin.af_list()
Returns an array of alternate functions available for this pin.
.. method:: Pin.debug([state])
Get or set the debugging state (``True`` or ``False`` for on or off).
.. method:: Pin.dict([dict])
Get or set the pin mapper dictionary.
.. method:: Pin.mapper([fun])
Get or set the pin mapper function.
Methods
-------
.. method:: pin.__str__()
Return a string describing the pin object.
.. method:: pin.af()
Returns the currently configured alternate-function of the pin. The
integer returned will match one of the allowed constants for the af
argument to the init function.
.. method:: pin.gpio()
Returns the base address of the GPIO block associated with this pin.
.. method:: pin.high()
Set the pin to a high logic level.
.. method:: pin.init(mode, pull=Pin.PULL_NONE, af=-1)
Initialise the pin:
- ``mode`` can be one of:
- ``Pin.IN`` - configure the pin for input;
- ``Pin.OUT_PP`` - configure the pin for output, with push-pull control;
- ``Pin.OUT_OD`` - configure the pin for output, with open-drain control;
- ``Pin.AF_PP`` - configure the pin for alternate function, pull-pull;
- ``Pin.AF_OD`` - configure the pin for alternate function, open-drain;
- ``Pin.ANALOG`` - configure the pin for analog.
- ``pull`` can be one of:
- ``Pin.PULL_NONE`` - no pull up or down resistors;
- ``Pin.PULL_UP`` - enable the pull-up resistor;
- ``Pin.PULL_DOWN`` - enable the pull-down resistor.
- when mode is Pin.AF_PP or Pin.AF_OD, then af can be the index or name
of one of the alternate functions associated with a pin.
Returns: ``None``.
.. method:: pin.low()
Set the pin to a low logic level.
.. method:: pin.mode()
Returns the currently configured mode of the pin. The integer returned
will match one of the allowed constants for the mode argument to the init
function.
.. method:: pin.name()
Get the pin name.
.. method:: pin.names()
Returns the cpu and board names for this pin.
.. method:: pin.pin()
Get the pin number.
.. method:: pin.port()
Get the pin port.
.. method:: pin.pull()
Returns the currently configured pull of the pin. The integer returned
will match one of the allowed constants for the pull argument to the init
function.
.. method:: 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.
Constants
---------
.. data:: Pin.AF_OD
initialise the pin to alternate-function mode with an open-drain drive
.. data:: Pin.AF_PP
initialise the pin to alternate-function mode with a push-pull drive
.. data:: Pin.ANALOG
initialise the pin to analog mode
.. data:: Pin.IN
initialise the pin to input mode
.. data:: Pin.OUT_OD
initialise the pin to output mode with an open-drain drive
.. data:: Pin.OUT_PP
initialise the pin to output mode with a push-pull drive
.. data:: Pin.PULL_DOWN
enable the pull-down resistor on the pin
.. data:: Pin.PULL_NONE
don't enable any pull up or down resistors on the pin
.. data:: Pin.PULL_UP
enable the pull-up resistor on the pin

View File

@ -0,0 +1,51 @@
class PinAF --- Pin Alternate Functions
=======================================
A Pin represents a physical pin on the microcprocessor. Each pin
can have a variety of functions (GPIO, I2C SDA, etc). Each PinAF
object represents a particular function for a pin.
Usage Model::
x3 = pyb.Pin.board.X3
x3_af = x3.af_list()
x3_af will now contain an array of PinAF objects which are availble on
pin X3.
For the pyboard, x3_af would contain:
[Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
Normally, each peripheral would configure the af automatically, but sometimes
the same function is available on multiple pins, and having more control
is desired.
To configure X3 to expose TIM2_CH3, you could use::
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2)
or::
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1)
Methods
-------
.. method:: pinaf.__str__()
Return a string describing the alternate function.
.. method:: pinaf.index()
Return the alternate function index.
.. method:: pinaf.name()
Return the name of the alternate function.
.. method:: pinaf.reg()
Return the base register associated with the peripheral assigned to this
alternate function. For example, if the alternate function were TIM2_CH3
this would return stm.TIM2

48
docs/library/pyb.RTC.rst Normal file
View File

@ -0,0 +1,48 @@
class RTC --- real time clock
=============================
The RTC is and independent clock that keeps track of the date
and time.
Example usage::
rtc = pyb.RTC()
rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.datetime())
Constructors
------------
.. class:: pyb.RTC()
Create an RTC object.
Methods
-------
.. method:: rtc.datetime([datetimetuple])
Get or set the date and time of the RTC.
With no arguments, this method returns an 8-tuple with the current
date and time. With 1 argument (being an 8-tuple) it sets the date
and time.
The 8-tuple has the following format:
(year, month, day, weekday, hours, minutes, seconds, subseconds)
``weekday`` is 1-7 for Monday through Sunday.
``subseconds`` counts down from 255 to 0
.. method:: rtc.info()
Get information about the startup time and reset source.
- The lower 0xffff are the number of milliseconds the RTC took to
start up.
- Bit 0x10000 is set if a power-on reset occurred.
- Bit 0x20000 is set if an external reset occurred

110
docs/library/pyb.SPI.rst Normal file
View File

@ -0,0 +1,110 @@
class SPI --- a master-driven serial protocol
=============================================
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::
from pyb import SPI
spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7)
Only required parameter is mode, SPI.MASTER or SPI.SLAVE. 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. Crc can be
None for no CRC, or a polynomial specifier.
Additional method for SPI::
data = spi.send_recv(b'1234') # send 4 bytes and receive 4 bytes
buf = bytearray(4)
spi.send_recv(b'1234', buf) # send 4 bytes and receive 4 into buf
spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf
Constructors
------------
.. class:: pyb.SPI(bus, ...)
Construct an SPI object on the given bus. ``bus`` can be 1 or 2.
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.
The physical pins of the SPI busses are:
- ``SPI(1)`` is on the X position: ``(NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4, PA5, PA6, PA7)``
- ``SPI(2)`` is on the Y position: ``(NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12, PB13, PB14, PB15)``
At the moment, the NSS pin is not used by the SPI driver and is free
for other use.
Methods
-------
.. method:: spi.deinit()
Turn off the SPI bus.
.. method:: spi.init(mode, baudrate=328125, \*, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)
Initialise the SPI bus with the given parameters:
- ``mode`` must be either ``SPI.MASTER`` or ``SPI.SLAVE``.
- ``baudrate`` is the SCK clock rate (only sensible for a master).
.. method:: spi.recv(recv, \*, timeout=5000)
Receive data on the bus:
- ``recv`` can be an integer, which is the number of bytes to receive,
or a mutable buffer, which will be filled with received bytes.
- ``timeout`` is the timeout in milliseconds to wait for the receive.
Return value: if ``recv`` is an integer then a new buffer of the bytes received,
otherwise the same buffer that was passed in to ``recv``.
.. method:: spi.send(send, \*, timeout=5000)
Send data on the bus:
- ``send`` is the data to send (an integer to send, or a buffer object).
- ``timeout`` is the timeout in milliseconds to wait for the send.
Return value: ``None``.
.. method:: spi.send_recv(send, recv=None, \*, timeout=5000)
Send and receive data on the bus at the same time:
- ``send`` is the data to send (an integer to send, or a buffer object).
- ``recv`` is a mutable buffer which will be filled with received bytes.
It can be the same as ``send``, or omitted. If omitted, a new buffer will
be created.
- ``timeout`` is the timeout in milliseconds to wait for the receive.
Return value: the buffer with the received bytes.
Constants
---------
.. data:: LSB
set the first bit to LSB
.. data:: MASTER
for initialising the bus to master mode
.. data:: MSB
set the first bit to MSB
.. data:: SLAVE
for initialising the bus to slave mode

View File

@ -0,0 +1,38 @@
class Servo --- 3-wire hobby servo driver
=========================================
Servo controls standard hobby servos with 3-wires (ground, power, signal).
Constructors
------------
.. class:: pyb.Servo(id)
Create a servo object. ``id`` is 1-4.
Methods
-------
.. method:: servo.angle([angle, time=0])
Get or set the angle of the servo.
- ``angle`` is the angle to move to in degrees.
- ``time`` is the number of milliseconds to take to get to the specified angle.
.. method:: servo.calibration([pulse_min, pulse_max, pulse_centre, [pulse_angle_90, pulse_speed_100]])
Get or set the calibration of the servo timing.
.. method:: servo.pulse_width([value])
Get or set the pulse width in milliseconds.
.. method:: servo.speed([speed, time=0])
Get or set the speed of a continuous rotation servo.
- ``speed`` is the speed to move to change to, between -100 and 100.
- ``time`` is the number of milliseconds to take to get to the specified speed.

View File

@ -0,0 +1,37 @@
class Switch --- switch object
==============================
A Switch object is used to control a push-button switch.
Usage::
sw = pyb.Switch() # create a switch object
sw() # get state (True if pressed, False otherwise)
sw.callback(f) # register a callback to be called when the
# switch is pressed down
sw.callback(None) # remove the callback
Example::
pyb.Switch().callback(lambda: pyb.LED(1).toggle())
Constructors
------------
.. class:: pyb.Switch()
Create and return a switch object.
Methods
-------
.. method:: switch()
Return the switch state: ``True`` if pressed down, ``False`` otherwise.
.. method:: switch.callback(fun)
Register the given function to be called when the switch is pressed down.
If ``fun`` is ``None``, then it disables the callback.

232
docs/library/pyb.Timer.rst Normal file
View File

@ -0,0 +1,232 @@
class Timer --- control internal timers
=======================================
Timers can be used for a great variety of tasks. At the moment, only
the simplest case is implemented: that of calling a function periodically.
Each timer consists of a counter that counts up at a certain rate. The rate
at which it counts is the peripheral clock frequency (in Hz) divided by the
timer prescaler. When the counter reaches the timer period it triggers an
event, and the counter resets back to zero. By using the callback method,
the timer event can call a Python function.
Example usage to toggle an LED at a fixed frequency::
tim = pyb.Timer(4) # create a timer object using timer 4
tim.init(freq=2) # trigger at 2Hz
tim.callback(lambda t:pyb.LED(1).toggle())
Further examples::
tim = pyb.Timer(4, freq=100) # freq in Hz
tim = pyb.Timer(4, prescaler=0, period=99)
tim.counter() # get counter (can also set)
tim.prescaler(2) # set prescaler (can also get)
tim.period(199) # set period (can also get)
tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
tim.callback(None) # clear callback
*Note:* Timer 3 is reserved for internal use. Timer 5 controls
the servo driver, and Timer 6 is used for timed ADC/DAC reading/writing.
It is recommended to use the other timers in your programs.
Constructors
------------
.. class:: pyb.Timer(id, ...)
Construct a new timer object of the given id. If additional
arguments are given, then the timer is initialised by ``init(...)``.
``id`` can be 1 to 14, excluding 3.
Methods
-------
.. method:: timer.callback(fun)
Set the function to be called when the timer triggers.
``fun`` is passed 1 argument, the timer object.
If ``fun`` is ``None`` then the callback will be disabled.
.. method:: timer.channel(channel, mode, ...)
If only a channel number is passed, then a previously initialized channel
object is returned (or ``None`` if there is no previous channel).
Othwerwise, a TimerChannel object is initialized and returned.
Each channel can be configured to perform pwm, output compare, or
input capture. All channels share the same underlying timer, which means
that they share the same timer clock.
Keyword arguments:
- ``mode`` can be one of:
- ``Timer.PWM`` --- configure the timer in PWM mode (active high).
- ``Timer.PWM_INVERTED`` --- configure the timer in PWM mode (active low).
- ``Timer.OC_TIMING`` --- indicates that no pin is driven.
- ``Timer.OC_ACTIVE`` --- the pin will be made active when a compare match occurs (active is determined by polarity)
- ``Timer.OC_INACTIVE`` --- the pin will be made inactive when a compare match occurs.
- ``Timer.OC_TOGGLE`` --- the pin will be toggled when an compare match occurs.
- ``Timer.OC_FORCED_ACTIVE`` --- the pin is forced active (compare match is ignored).
- ``Timer.OC_FORCED_INACTIVE`` --- the pin is forced inactive (compare match is ignored).
- ``Timer.IC`` --- configure the timer in Input Capture mode.
- ``callback`` - as per TimerChannel.callback()
- ``pin`` None (the default) or a Pin object. If specified (and not None)
this will cause the alternate function of the the indicated pin
to be configured for this timer channel. An error will be raised if
the pin doesn't support any alternate functions for this timer channel.
Keyword arguments for Timer.PWM modes:
- ``pulse_width`` - determines the initial pulse width value to use.
- ``pulse_width_percent`` - determines the initial pulse width percentage to use.
Keyword arguments for Timer.OC modes:
- ``compare`` - determines the initial value of the compare register.
- ``polarity`` can be one of:
- ``Timer.HIGH`` - output is active high
- ``Timer.LOW`` - output is acive low
Optional keyword arguments for Timer.IC modes:
- ``polarity`` can be one of:
- ``Timer.RISING`` - captures on rising edge.
- ``Timer.FALLING`` - captures on falling edge.
- ``Timer.BOTH`` - captures on both edges.
Note that capture only works on the primary channel, and not on the
complimentary channels.
PWM Example::
timer = pyb.Timer(2, freq=1000)
ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
.. method:: timer.counter([value])
Get or set the timer counter.
.. method:: timer.deinit()
Deinitialises the timer.
Disables the callback (and the associated irq).
Disables any channel callbacks (and the associated irq).
Stops the timer, and disables the timer peripheral.
.. method:: timer.freq([value])
Get or set the frequency for the timer (changes prescaler and period if set).
.. method:: timer.init(\*, freq, prescaler, period)
Initialise the timer. Initialisation must be either by frequency (in Hz)
or by prescaler and period::
tim.init(freq=100) # set the timer to trigger at 100Hz
tim.init(prescaler=83, period=999) # set the prescaler and period directly
Keyword arguments:
- ``freq`` --- specifies the periodic frequency of the timer. You migh also
view this as the frequency with which the timer goes through one complete cycle.
- ``prescaler`` [0-0xffff] - specifies the value to be loaded into the
timer's Prescaler Register (PSC). The timer clock source is divided by
(``prescaler + 1``) to arrive at the timer clock. Timers 2-7 and 12-14
have a clock source of 84 MHz (pyb.freq()[2] \* 2), and Timers 1, and 8-11
have a clock source of 168 MHz (pyb.freq()[3] \* 2).
- ``period`` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
Specifies the value to be loaded into the timer's AutoReload
Register (ARR). This determines the period of the timer (i.e. when the
counter cycles). The timer counter will roll-over after ``period + 1``
timer clock cycles.
- ``mode`` can be one of:
- ``Timer.UP`` - configures the timer to count from 0 to ARR (default)
- ``Timer.DOWN`` - configures the timer to count from ARR down to 0.
- ``Timer.CENTER`` - confgures the timer to count from 0 to ARR and
then back down to 0.
- ``div`` can be one of 1, 2, or 4. Divides the timer clock to determine
the sampling clock used by the digital filters.
- ``callback`` - as per Timer.callback()
- ``deadtime`` - specifies the amount of "dead" or inactive time between
transitions on complimentary channels (both channels will be inactive)
for this time). ``deadtime`` may be an integer between 0 and 1008, with
the following restrictions: 0-128 in steps of 1. 128-256 in steps of
2, 256-512 in steps of 8, and 512-1008 in steps of 16. ``deadime``
measures ticks of ``source_freq`` divided by ``div`` clock ticks.
``deadtime`` is only available on timers 1 and 8.
You must either specify freq or both of period and prescaler.
.. method:: timer.period([value])
Get or set the period of the timer.
.. method:: timer.prescaler([value])
Get or set the prescaler for the timer.
.. method:: timer.source_freq()
Get the frequency of the source of the timer.
class TimerChannel --- setup a channel for a timer
==================================================
Timer channels are used to generate/capture a signal using a timer.
TimerChannel objects are created using the Timer.channel() method.
Methods
-------
.. method:: timerchannel.callback(fun)
Set the function to be called when the timer channel triggers.
``fun`` is passed 1 argument, the timer object.
If ``fun`` is ``None`` then the callback will be disabled.
.. method:: timerchannel.capture([value])
Get or set the capture value associated with a channel.
capture, compare, and pulse_width are all aliases for the same function.
capture is the logical name to use when the channel is in input capture mode.
.. method:: timerchannel.compare([value])
Get or set the compare value associated with a channel.
capture, compare, and pulse_width are all aliases for the same function.
compare is the logical name to use when the channel is in output compare mode.
.. method:: timerchannel.pulse_width([value])
Get or set the pulse width value associated with a channel.
capture, compare, and pulse_width are all aliases for the same function.
pulse_width is the logical name to use when the channel is in PWM mode.
In edge aligned mode, a pulse_width of ``period + 1`` corresponds to a duty cycle of 100%
In center aligned mode, a pulse width of ``period`` corresponds to a duty cycle of 100%
.. method:: timerchannel.pulse_width_percent([value])
Get or set the pulse width percentage associated with a channel. The value
is a number between 0 and 100 and sets the percentage of the timer period
for which the pulse is active. The value can be an integer or
floating-point number for more accuracy. For example, a value of 25 gives
a duty cycle of 25%.

103
docs/library/pyb.UART.rst Normal file
View File

@ -0,0 +1,103 @@
class UART --- duplex serial communication bus
==============================================
UART implements the standard UART/USART duplex serial communications protocol. At
the physical level it consists of 2 lines: RX and TX. The unit of communication
is a character (not to be confused with a string character) which can be 8 or 9
bits wide.
UART objects can be created and initialised using::
from pyb 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 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2.
A UART object acts like a stream object and reading and writing is done
using the standard stream methods::
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
Individual characters can be read/written using::
uart.readchar() # read 1 character and returns it as an integer
uart.writechar(42) # write 1 character
To check if there is anything to be read, use::
uart.any() # returns True if any characters waiting
Constructors
------------
.. class:: pyb.UART(bus, ...)
Construct a UART object on the given bus. ``bus`` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'.
With no additional parameters, the UART 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.
The physical pins of the UART busses are:
- ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)``
- ``UART(1)`` is on ``XB``: ``(TX, RX) = (X9, X10) = (PB6, PB7)``
- ``UART(6)`` is on ``YA``: ``(TX, RX) = (Y1, Y2) = (PC6, PC7)``
- ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)``
- ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)``
Methods
-------
.. method:: uart.any()
Return ``True`` if any characters waiting, else ``False``.
.. method:: uart.deinit()
Turn off the UART bus.
.. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, timeout_char=0, read_buf_len=64)
Initialise the UART bus with the given parameters:
- ``baudrate`` is the clock rate.
- ``bits`` is the number of bits per byte, 8 or 9.
- ``parity`` is the parity, ``None``, 0 (even) or 1 (odd).
- ``stop`` is the number of stop bits, 1 or 2.
- ``timeout`` is the timeout in milliseconds to wait for the first character.
- ``timeout_char`` is the timeout in milliseconds to wait between characters.
- ``read_buf_len`` is the character length of the read buffer (0 to disable).
.. method:: uart.read([nbytes])
.. method:: uart.readall()
.. method:: uart.readchar()
Receive a single character on the bus.
Return value: The character read, as an integer. Returns -1 on timeout.
.. method:: uart.readinto(buf[, nbytes])
.. method:: uart.readline()
.. method:: uart.write(buf)
.. method:: uart.writechar(char)
Write a single character on the bus. ``char`` is an integer to write.
Return value: ``None``.

View File

@ -0,0 +1,57 @@
class USB_VCP --- USB virtual comm port
=======================================
The USB_VCP class allows creation of an object representing the USB
virtual comm port. It can be used to read and write data over USB to
the connected host.
Constructors
------------
.. class:: pyb.USB_VCP()
Create a new USB_VCP object.
Methods
-------
.. method:: usb_vcp.any()
Return ``True`` if any characters waiting, else ``False``.
.. method:: usb_vcp.close()
.. method:: usb_vcp.read([nbytes])
.. method:: usb_vcp.readall()
.. method:: usb_vcp.readline()
.. method:: usb_vcp.recv(data, \*, timeout=5000)
Receive data on the bus:
- ``data`` can be an integer, which is the number of bytes to receive,
or a mutable buffer, which will be filled with received bytes.
- ``timeout`` is the timeout in milliseconds to wait for the receive.
Return value: if ``data`` is an integer then a new buffer of the bytes received,
otherwise the number of bytes read into ``data`` is returned.
.. method:: usb_vcp.send(data, \*, timeout=5000)
Send data over the USB VCP:
- ``data`` is the data to send (an integer to send, or a buffer object).
- ``timeout`` is the timeout in milliseconds to wait for the send.
Return value: number of bytes sent.
.. method:: usb_vcp.write(buf)

171
docs/library/pyb.rst Normal file
View File

@ -0,0 +1,171 @@
:mod:`pyb` --- functions related to the pyboard
===============================================
.. module:: pyb
:synopsis: functions related to the pyboard
The ``pyb`` module contains specific functions related to the pyboard.
Time related functions
----------------------
.. function:: delay(ms)
Delay for the given number of milliseconds.
.. function:: udelay(us)
Delay for the given number of microseconds.
.. function:: millis()
Returns the number of milliseconds since the board was last reset.
The result is always a micropython smallint (31-bit signed number), so
after 2^30 milliseconds (about 12.4 days) this will start to return
negative numbers.
.. function:: micros()
Returns the number of microseconds since the board was last reset.
The result is always a micropython smallint (31-bit signed number), so
after 2^30 microseconds (about 17.8 minutes) this will start to return
negative numbers.
.. function:: elapsed_millis(start)
Returns the number of milliseconds which have elapsed since ``start``.
This function takes care of counter wrap, and always returns a positive
number. This means it can be used to measure periods upto about 12.4 days.
Example::
start = pyb.millis()
while pyb.elapsed_millis(start) < 1000:
# Perform some operation
.. function:: elapsed_micros(start)
Returns the number of microseconds which have elapsed since ``start``.
This function takes care of counter wrap, and always returns a positive
number. This means it can be used to measure periods upto about 17.8 minutes.
Example::
start = pyb.micros()
while pyb.elapsed_micros(start) < 1000:
# Perform some operation
pass
Reset related functions
-----------------------
.. function:: hard_reset()
Resets the pyboard in a manner similar to pushing the external RESET
button.
.. function:: bootloader()
Activate the bootloader without BOOT\* pins.
Interrupt related functions
---------------------------
.. function:: disable_irq()
Disable interrupt requests.
Returns the previous IRQ state: ``False``/``True`` for disabled/enabled IRQs
respectively. This return value can be passed to enable_irq to restore
the IRQ to its original state.
.. function:: enable_irq(state=True)
Enable interrupt requests.
If ``state`` is ``True`` (the default value) then IRQs are enabled.
If ``state`` is ``False`` then IRQs are disabled. The most common use of
this function is to pass it the value returned by ``disable_irq`` to
exit a critical section.
Power related functions
-----------------------
.. function:: freq([sys_freq])
If given no arguments, returns a tuple of clock frequencies:
(SYSCLK, HCLK, PCLK1, PCLK2).
If given an argument, sets the system frequency to that value in Hz.
Eg freq(120000000) gives 120MHz. Note that not all values are
supported and the largest supported frequency not greater than
the given sys_freq will be selected.
.. function:: wfi()
Wait for an interrupt.
This executies a ``wfi`` instruction which reduces power consumption
of the MCU until an interrupt occurs, at which point execution continues.
.. function:: standby()
.. function:: stop()
Miscellaneous functions
-----------------------
.. function:: have_cdc()
Return True if USB is connected as a serial device, False otherwise.
.. function:: hid((buttons, x, y, z))
Takes a 4-tuple (or list) and sends it to the USB host (the PC) to
signal a HID mouse-motion event.
.. function:: info([dump_alloc_table])
Print out lots of information about the board.
.. function:: repl_uart(uart)
Get or set the UART object that the REPL is repeated on.
.. function:: rng()
Return a 30-bit hardware generated random number.
.. function:: sync()
Sync all file systems.
.. function:: unique_id()
Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
Classes
-------
.. toctree::
:maxdepth: 1
pyb.Accel.rst
pyb.ADC.rst
pyb.CAN.rst
pyb.DAC.rst
pyb.ExtInt.rst
pyb.I2C.rst
pyb.LCD.rst
pyb.LED.rst
pyb.PinAF.rst
pyb.Pin.rst
pyb.RTC.rst
pyb.Servo.rst
pyb.SPI.rst
pyb.Switch.rst
pyb.Timer.rst
pyb.UART.rst
pyb.USB_VCP.rst

37
docs/library/select.rst Normal file
View File

@ -0,0 +1,37 @@
:mod:`select` --- Provides select function to wait for events on a stream
=========================================================================
.. module:: select
:synopsis: Provides select function to wait for events on a stream
This module provides the select function.
Functions
---------
.. function:: poll()
.. function:: select(rlist, wlist, xlist[, timeout])
class Poll
----------
Methods
-------
.. method:: poll.modify(obj, eventmask)
.. method:: poll.poll([timeout])
Timeout is in milliseconds.
.. method:: poll.register(obj[, eventmask])
.. method:: poll.unregister(obj)

55
docs/library/sys.rst Normal file
View File

@ -0,0 +1,55 @@
:mod:`sys` --- system specific functions
========================================
.. module:: sys
:synopsis: system specific functions
Functions
---------
.. function:: exit([retval])
Raise a ``SystemExit`` exception. If an argument is given, it is the
value given to ``SystemExit``.
Constants
---------
.. data:: argv
a mutable list of arguments this program started with
.. data:: byteorder
the byte order of the system ("little" or "big")
.. data:: path
a mutable list of directories to search for imported modules
.. data:: platform
the platform that Micro Python is running on
.. data:: stderr
standard error (connected to USB VCP, and optional UART object)
.. data:: stdin
standard input (connected to USB VCP, and optional UART object)
.. data:: stdout
standard output (connected to USB VCP, and optional UART object)
.. data:: version
Python language version that this implementation conforms to, as a string
.. data:: version_info
Python language version that this implementation conforms to, as a tuple of ints

41
docs/library/time.rst Normal file
View File

@ -0,0 +1,41 @@
:mod:`time` --- time related functions
======================================
.. module:: time
:synopsis: time related functions
The ``time`` module provides functions for getting the current time and date,
and for sleeping.
Functions
---------
.. function:: localtime([secs])
Convert a time expressed in seconds since Jan 1, 2000 into an 8-tuple which
contains: (year, month, mday, hour, minute, second, weekday, yearday)
If secs is not provided or None, then the current time from the RTC is used.
year includes the century (for example 2014)
month is 1-12
mday is 1-31
hour is 0-23
minute is 0-59
second is 0-59
weekday is 0-6 for Mon-Sun.
yearday is 1-366
.. function:: mktime()
This is inverse function of localtime. It's argument is a full 8-tuple
which expresses a time as per localtime. It returns an integer which is
the number of seconds since Jan 1, 2000.
.. function:: sleep(seconds)
Sleep for the given number of seconds. Seconds can be a floating-point number to
sleep for a fractional number of seconds.
.. function:: time()
Returns the number of seconds, as an integer, since 1/1/2000.

25
docs/library/uheapq.rst Normal file
View File

@ -0,0 +1,25 @@
:mod:`uheapq` --- heap queue algorithm
======================================
.. module:: uheapq
:synopsis: heap queue algorithm
This module implements the heap queue algorithm.
A heap queue is simply a list that has its elements stored in a certain way.
Functions
---------
.. function:: heappush(heap, item)
Push the ``item`` onto the ``heap``.
.. function:: heappop(heap)
Pop the first item froh the ``heap``, and return it. Raises IndexError if
heap is empty.
.. function:: heapify(x)
Convert the list ``x`` into a heap. This is an in-place operation.

20
docs/library/ujson.rst Normal file
View File

@ -0,0 +1,20 @@
:mod:`ujson` --- JSON encoding and decoding
===========================================
.. module:: ujson
:synopsis: JSON encoding and decoding
This modules allows to convert between Python objects and the JSON
data format.
Functions
---------
.. function:: dumps(obj)
Return ``obj`` represented as a JSON string.
.. function:: loads(str)
Parse the JSON ``str`` and return an object. Raises ValueError if the
string is not correctly formed.

18
docs/library/usocket.rst Normal file
View File

@ -0,0 +1,18 @@
:mod:`usocket` --- socket module
================================
.. module:: usocket
:synopsis: socket module
Socket functionality.
Functions
---------
.. function:: getaddrinfo(host, port)
.. function:: socket(family=AF_INET, type=SOCK_STREAM, fileno=-1)
Create a socket.

View File

@ -26,6 +26,7 @@ potentiometer, which is an I2C device with address 46 on the ``IC2(1)`` bus.
To set the volume, define the following function::
import pyb
def volume(val):
pyb.I2C(1, pyb.I2C.MASTER).mem_write(val, 46, 0)

View File

@ -6,7 +6,7 @@ In addition to turning LEDs on and off, it is also possible to control the brigh
.. image:: http://upload.wikimedia.org/wikipedia/commons/a/a9/Fade.gif
Components
==========
----------
You will need:
@ -16,14 +16,14 @@ You will need:
- `Breadboard <http://en.wikipedia.org/wiki/Breadboard>`_ (optional, but makes things easier)
Connecting Things Up
====================
--------------------
For this tutorial, we will use the ``X1`` pin. Connect one end of the resistor to ``X1``, and the other end to the **anode** of the LED, which is the longer leg. Connect the **cathode** of the LED to ground.
.. image:: img/fading_leds_breadboard_fritzing.png
Code
====
----
By examining the :ref:`quickref`, we see that ``X1`` is connected to channel 1 of timer 5 (``TIM5 CH1``). Therefore we will first create a ``Timer`` object for timer 5, then create a ``TimerChannel`` object for channel 1::
from pyb import Timer
@ -59,7 +59,7 @@ To achieve the fading effect shown at the beginning of this tutorial, we want to
cur_width = min_width
Breathing Effect
================
----------------
If we want to have a breathing effect, where the LED fades from dim to bright then bright to dim, then we simply need to reverse the sign of ``wstep`` when we reach maximum brightness, and reverse it again at minimum brightness. To do this we modify the ``while`` loop to be::
@ -78,12 +78,12 @@ If we want to have a breathing effect, where the LED fades from dim to bright th
wstep *= -1
Advanced Exercise
==================
-----------------
You may have noticed that the LED brightness seems to fade slowly, but increases quickly. This is because our eyes interprets brightness logarithmically (`Weber's Law <http://www.telescope-optics.net/eye_intensity_response.htm>`_
), while the LED's brightness changes linearly, that is by the same amount each time. How do you solve this problem? (Hint: what is the opposite of the logarithmic function?)
Addendum
========
--------
We could have also used the digital-to-analog converter (DAC) to achieve the same effect. The PWM method has the advantage that it drives the LED with the same current each time, but for different lengths of time. This allows better control over the brightness, because LEDs do not necessarily exhibit a linear relationship between the driving current and brightness.

View File

@ -22,6 +22,16 @@ the tutorial through in the order below.
usb_mouse.rst
timer.rst
assembler.rst
power_ctrl.rst
Tips, tricks and useful things to know
--------------------------------------
.. toctree::
:maxdepth: 1
:numbered:
pass_through.rst
Tutorials requiring extra components
------------------------------------

View File

@ -24,12 +24,14 @@ Using the LCD
To get started using the LCD, try the following at the Micro Python prompt.
Make sure the LCD skin is attached to the pyboard as pictured at the top of this page. ::
>>> import pyb
>>> lcd = pyb.LCD('X')
>>> lcd.light(True)
>>> lcd.write('Hello uPy!\n')
You can make a simple animation using the code::
import pyb
lcd = pyb.LCD('X')
lcd.light(True)
for x in range(-80, 128):
@ -46,6 +48,7 @@ MPR121 capacitive touch sensor has address 90.
To get started, try::
>>> import pyb
>>> i2c = pyb.I2C(1, pyb.I2C.MASTER)
>>> i2c.mem_write(4, 90, 0x5e)
>>> touch = i2c.mem_read(1, 90, 0)[0]

View File

@ -0,0 +1,17 @@
Making a UART - USB pass through
================================
It's as simple as::
import pyb
import select
def pass_through(usb, uart):
while True:
select.select([usb, uart], [], [])
if usb.any():
uart.write(usb.read(256))
if uart.any():
usb.write(uart.read(256))
pass_through(pyb.USB_VCP(), pyb.UART(1, 9600))

View File

@ -0,0 +1,13 @@
Power control
=============
:meth:`pyb.wfi` is used to reduce power consumption while waiting for an
event such as an interrupt. You would use it in the following situation::
while True:
do_some_processing()
pyb.wfi()
Control the frequency using :meth:`pyb.freq`::
pyb.freq(30000000) # set CPU frequency to 30MHz

View File

@ -39,7 +39,7 @@ Open a terminal and run::
screen /dev/tty.usbmodem*
When you are finishend and want to exit screen, type CTRL-A CTRL-\\.
When you are finished and want to exit screen, type CTRL-A CTRL-\\.
Linux
-----