...
 
Commits (100)
......@@ -16,14 +16,14 @@ Classes
.. class:: array.array(typecode, [iterable])
Create array with elements of given type. Initial contents of the
array are given by an `iterable`. If it is not provided, an empty
array are given by *iterable*. If it is not provided, an empty
array is created.
.. method:: append(val)
Append new element to the end of array, growing it.
Append new element *val* to the end of array, growing it.
.. method:: extend(iterable)
Append new elements as contained in an iterable to the end of
Append new elements as contained in *iterable* to the end of
array, growing it.
......@@ -172,7 +172,7 @@ Drawing text
------------
To draw text one sets the position, color and font, and then uses
`write` to draw the text.
`LCD160CR.write` to draw the text.
.. method:: LCD160CR.set_pos(x, y)
......@@ -279,7 +279,7 @@ Touch screen methods
.. method:: LCD160CR.is_touched()
Returns a boolean: ``True`` if there is currently a touch force on the screen,
`False` otherwise.
``False`` otherwise.
.. method:: LCD160CR.get_touch()
......
......@@ -33,6 +33,18 @@ Functions
compilation of scripts, and returns ``None``. Otherwise it returns the current
optimisation level.
The optimisation level controls the following compilation features:
- Assertions: at level 0 assertion statements are enabled and compiled into the
bytecode; at levels 1 and higher assertions are not compiled.
- Built-in ``__debug__`` variable: at level 0 this variable expands to ``True``;
at levels 1 and higher it expands to ``False``.
- Source-code line numbers: at levels 0, 1 and 2 source-code line number are
stored along with the bytecode so that exceptions can report the line number
they occurred at; at levels 3 and higher line numbers are not stored.
The default optimisation level is usually level 0.
.. function:: alloc_emergency_exception_buf(size)
Allocate *size* bytes of RAM for the emergency exception buffer (a good
......
......@@ -383,10 +383,11 @@ parameter should be `id`.
* 0 -- visible
* 1 -- hidden
.. method:: wlan.status()
.. method:: wlan.status([param])
Return the current status of the wireless connection.
When called with no argument the return value describes the network link status.
The possible statuses are defined as constants:
* ``STAT_IDLE`` -- no connection and no activity,
......@@ -396,6 +397,9 @@ parameter should be `id`.
* ``STAT_CONNECT_FAIL`` -- failed due to other problems,
* ``STAT_GOT_IP`` -- connection successful.
When called with one argument *param* should be a string naming the status
parameter to retrieve. Supported parameters in WiFI STA mode are: ``'rssi'``.
.. method:: wlan.isconnected()
In case of STA mode, returns ``True`` if connected to a WiFi access
......
This diff is collapsed.
......@@ -38,7 +38,7 @@ Methods
.. method:: Switch.value()
Get the switch state. Returns `True` if pressed down, otherwise `False`.
Get the switch state. Returns ``True`` if pressed down, otherwise ``False``.
.. method:: Switch.callback(fun)
......
......@@ -81,7 +81,7 @@ Functions
Open a file. Builtin ``open()`` function is aliased to this function.
All ports (which provide access to file system) are required to support
`mode` parameter, but support for other arguments vary by port.
*mode* parameter, but support for other arguments vary by port.
Classes
-------
......@@ -103,7 +103,7 @@ Classes
text-mode I/O (similar to a normal file opened with "t" modifier).
`BytesIO` is used for binary-mode I/O (similar to a normal file
opened with "b" modifier). Initial contents of file-like objects
can be specified with `string` parameter (should be normal string
can be specified with *string* parameter (should be normal string
for `StringIO` or bytes object for `BytesIO`). All the usual file
methods like ``read()``, ``write()``, ``seek()``, ``flush()``,
``close()`` are available on these objects, and additionally, a
......
......@@ -6,11 +6,32 @@
|see_cpython_module| :mod:`python:os`.
The ``uos`` module contains functions for filesystem access and ``urandom``
function.
The ``uos`` module contains functions for filesystem access and mounting,
terminal redirection and duplication, and the ``uname`` and ``urandom``
functions.
Functions
---------
General functions
-----------------
.. function:: uname()
Return a tuple (possibly a named tuple) containing information about the
underlying machine and/or its operating system. The tuple has five fields
in the following order, each of them being a string:
* ``sysname`` -- the name of the underlying system
* ``nodename`` -- the network name (can be the same as ``sysname``)
* ``release`` -- the version of the underlying system
* ``version`` -- the MicroPython version and build date
* ``machine`` -- an identifier for the underlying hardware (eg board, CPU)
.. function:: urandom(n)
Return a bytes object with *n* random bytes. Whenever possible, it is
generated by the hardware random number generator.
Filesystem access
-----------------
.. function:: chdir(path)
......@@ -22,11 +43,11 @@ Functions
.. function:: ilistdir([dir])
This function returns an iterator which then yields 3-tuples corresponding to
This function returns an iterator which then yields tuples corresponding to
the entries in the directory that it is listing. With no argument it lists the
current directory, otherwise it lists the directory given by *dir*.
The 3-tuples have the form *(name, type, inode)*:
The tuples have the form *(name, type, inode[, size])*:
- *name* is a string (or bytes if *dir* is a bytes object) and is the name of
the entry;
......@@ -34,6 +55,10 @@ Functions
directories and 0x8000 for regular files;
- *inode* is an integer corresponding to the inode of the file, and may be 0
for filesystems that don't have such a notion.
- Some platforms may return a 4-tuple that includes the entry's *size*. For
file entries, *size* is an integer representing the size of the file
or -1 if unknown. Its meaning is currently undefined for directory
entries.
.. function:: listdir([dir])
......@@ -84,10 +109,8 @@ Functions
Sync all filesystems.
.. function:: urandom(n)
Return a bytes object with n random bytes. Whenever possible, it is
generated by the hardware random number generator.
Terminal redirection and duplication
------------------------------------
.. function:: dupterm(stream_object, index=0)
......@@ -108,3 +131,119 @@ Functions
the slot given by *index*.
The function returns the previous stream-like object in the given slot.
Filesystem mounting
-------------------
Some ports provide a Virtual Filesystem (VFS) and the ability to mount multiple
"real" filesystems within this VFS. Filesystem objects can be mounted at either
the root of the VFS, or at a subdirectory that lives in the root. This allows
dynamic and flexible configuration of the filesystem that is seen by Python
programs. Ports that have this functionality provide the :func:`mount` and
:func:`umount` functions, and possibly various filesystem implementations
represented by VFS classes.
.. function:: mount(fsobj, mount_point, \*, readonly)
Mount the filesystem object *fsobj* at the location in the VFS given by the
*mount_point* string. *fsobj* can be a a VFS object that has a ``mount()``
method, or a block device. If it's a block device then the filesystem type
is automatically detected (an exception is raised if no filesystem was
recognised). *mount_point* may be ``'/'`` to mount *fsobj* at the root,
or ``'/<name>'`` to mount it at a subdirectory under the root.
If *readonly* is ``True`` then the filesystem is mounted read-only.
During the mount process the method ``mount()`` is called on the filesystem
object.
Will raise ``OSError(EPERM)`` if *mount_point* is already mounted.
.. function:: umount(mount_point)
Unmount a filesystem. *mount_point* can be a string naming the mount location,
or a previously-mounted filesystem object. During the unmount process the
method ``umount()`` is called on the filesystem object.
Will raise ``OSError(EINVAL)`` if *mount_point* is not found.
.. class:: VfsFat(block_dev)
Create a filesystem object that uses the FAT filesystem format. Storage of
the FAT filesystem is provided by *block_dev*.
Objects created by this constructor can be mounted using :func:`mount`.
.. staticmethod:: mkfs(block_dev)
Build a FAT filesystem on *block_dev*.
Block devices
-------------
A block device is an object which implements the block protocol, which is a set
of methods described below by the :class:`AbstractBlockDev` class. A concrete
implementation of this class will usually allow access to the memory-like
functionality a piece of hardware (like flash memory). A block device can be
used by a particular filesystem driver to store the data for its filesystem.
.. class:: AbstractBlockDev(...)
Construct a block device object. The parameters to the constructor are
dependent on the specific block device.
.. method:: readblocks(block_num, buf)
Starting at *block_num*, read blocks from the device into *buf* (an array
of bytes). The number of blocks to read is given by the length of *buf*,
which will be a multiple of the block size.
.. method:: writeblocks(block_num, buf)
Starting at *block_num*, write blocks from *buf* (an array of bytes) to
the device. The number of blocks to write is given by the length of *buf*,
which will be a multiple of the block size.
.. method:: ioctl(op, arg)
Control the block device and query its parameters. The operation to
perform is given by *op* which is one of the following integers:
- 1 -- initialise the device (*arg* is unused)
- 2 -- shutdown the device (*arg* is unused)
- 3 -- sync the device (*arg* is unused)
- 4 -- get a count of the number of blocks, should return an integer
(*arg* is unused)
- 5 -- get the number of bytes in a block, should return an integer,
or ``None`` in which case the default value of 512 is used
(*arg* is unused)
By way of example, the following class will implement a block device that stores
its data in RAM using a ``bytearray``::
class RAMBlockDev:
def __init__(self, block_size, num_blocks):
self.block_size = block_size
self.data = bytearray(block_size * num_blocks)
def readblocks(self, block_num, buf):
for i in range(len(buf)):
buf[i] = self.data[block_num * self.block_size + i]
def writeblocks(self, block_num, buf):
for i in range(len(buf)):
self.data[block_num * self.block_size + i] = buf[i]
def ioctl(self, op, arg):
if op == 4: # get number of blocks
return len(self.data) // self.block_size
if op == 5: # get block size
return self.block_size
It can be used as follows::
import uos
bdev = RAMBlockDev(512, 50)
uos.VfsFat.mkfs(bdev)
vfs = uos.VfsFat(bdev)
uos.mount(vfs, '/ramdisk')
......@@ -35,10 +35,10 @@ Methods
Register `stream` *obj* for polling. *eventmask* is logical OR of:
* `uselect.POLLIN` - data available for reading
* `uselect.POLLOUT` - more data can be written
* ``uselect.POLLIN`` - data available for reading
* ``uselect.POLLOUT`` - more data can be written
Note that flags like `uselect.POLLHUP` and `uselect.POLLERR` are
Note that flags like ``uselect.POLLHUP`` and ``uselect.POLLERR`` are
*not* valid as input eventmask (these are unsolicited events which
will be returned from `poll()` regardless of whether they are asked
for). This semantics is per POSIX.
......@@ -63,7 +63,7 @@ Methods
tuple, depending on a platform and version, so don't assume that its size is 2.
The ``event`` element specifies which events happened with a stream and
is a combination of ``uselect.POLL*`` constants described above. Note that
flags `uselect.POLLHUP` and `uselect.POLLERR` can be returned at any time
flags ``uselect.POLLHUP`` and ``uselect.POLLERR`` can be returned at any time
(even if were not asked for), and must be acted on accordingly (the
corresponding stream unregistered from poll and likely closed), because
otherwise all further invocations of `poll()` may return immediately with
......
......@@ -99,7 +99,7 @@ Functions
of error in this function. MicroPython doesn't have ``socket.gaierror``
and raises OSError directly. Note that error numbers of `getaddrinfo()`
form a separate namespace and may not match error numbers from
`uerrno` module. To distinguish `getaddrinfo()` errors, they are
the :mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are
represented by negative numbers, whereas standard system errors are
positive numbers (error numbers are accessible using ``e.args[0]`` property
from an exception object). The use of negative values is a provisional
......
......@@ -18,10 +18,10 @@ Functions
Takes a `stream` *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type),
and returns an instance of ssl.SSLSocket, which wraps the underlying stream in
an SSL context. Returned object has the usual `stream` interface methods like
`read()`, `write()`, etc. In MicroPython, the returned object does not expose
socket interface and methods like `recv()`, `send()`. In particular, a
``read()``, ``write()``, etc. In MicroPython, the returned object does not expose
socket interface and methods like ``recv()``, ``send()``. In particular, a
server-side SSL socket should be created from a normal socket returned from
`accept()` on a non-SSL listening server socket.
:meth:`~usocket.socket.accept()` on a non-SSL listening server socket.
Depending on the underlying module implementation in a particular
`MicroPython port`, some or all keyword arguments above may be not supported.
......
......@@ -185,7 +185,7 @@ a file it will save RAM if this is done in a piecemeal fashion. Rather than
creating a large string object, create a substring and feed it to the stream
before dealing with the next.
The best way to create dynamic strings is by means of the string `format`
The best way to create dynamic strings is by means of the string ``format()``
method:
.. code::
......@@ -259,7 +259,7 @@ were a string.
**Runtime compiler execution**
The Python funcitons `eval` and `exec` invoke the compiler at runtime, which
requires significant amounts of RAM. Note that the `pickle` library from
requires significant amounts of RAM. Note that the ``pickle`` library from
`micropython-lib` employs `exec`. It may be more RAM efficient to use the
`ujson` library for object serialisation.
......
......@@ -42,7 +42,7 @@ size, which means that to uncompress a compressed stream, 32KB of
contguous memory needs to be allocated. This requirement may be not
satisfiable on low-memory devices, which may have total memory available
less than that amount, and even if not, a contiguous block like that
may be hard to allocate due to `memory fragmentation`. To accommodate
may be hard to allocate due to memory fragmentation. To accommodate
these constraints, MicroPython distribution packages use Gzip compression
with the dictionary size of 4K, which should be a suitable compromise
with still achieving some compression while being able to uncompressed
......@@ -243,7 +243,7 @@ the data files as "resources", and abstracting away access to them.
Python supports resource access using its "setuptools" library, using
``pkg_resources`` module. MicroPython, following its usual approach,
implements subset of the functionality of that module, specifically
`pkg_resources.resource_stream(package, resource)` function.
``pkg_resources.resource_stream(package, resource)`` function.
The idea is that an application calls this function, passing a
resource identifier, which is a relative path to data file within
the specified package (usually top-level application package). It
......
......@@ -19,7 +19,7 @@ If your cursor is all the way back at the beginning, pressing RETURN will then
execute the code that you've entered. The following shows what you'd see
after entering a for statement (the underscore shows where the cursor winds up):
>>> for i in range(3):
>>> for i in range(30):
... _
If you then enter an if statement, an additional level of indentation will be
......@@ -58,9 +58,10 @@ Auto-completion
While typing a command at the REPL, if the line typed so far corresponds to
the beginning of the name of something, then pressing TAB will show
possible things that could be entered. For example type ``m`` and press TAB
and it should expand to ``machine``. Enter a dot ``.`` and press TAB again. You
should see something like:
possible things that could be entered. For example, first import the machine
module by entering ``import machine`` and pressing RETURN.
Then type ``m`` and press TAB and it should expand to ``machine``.
Enter a dot ``.`` and press TAB again. You should see something like:
>>> machine.
__name__ info unique_id reset
......@@ -151,7 +152,7 @@ method by which you're connected to the MicroPython board (USB-serial, or Wifi).
You can perform a soft reset from the REPL by pressing Ctrl-D, or from your python
code by executing: ::
raise SystemExit
machine.soft_reset()
For example, if you reset your MicroPython board, and you execute a dir()
command, you'd see something like this:
......
......@@ -63,8 +63,8 @@ used for communication with a device. A typical driver will create the buffer in
constructor and use it in its I/O methods which will be called repeatedly.
The MicroPython libraries typically provide support for pre-allocated buffers. For
example, objects which support stream interface (e.g., file or UART) provide `read()`
method which allocates new buffer for read data, but also a `readinto()` method
example, objects which support stream interface (e.g., file or UART) provide ``read()``
method which allocates new buffer for read data, but also a ``readinto()`` method
to read data into an existing buffer.
Floating Point
......@@ -109,10 +109,10 @@ the 10K buffer go (be ready for garbage collection), instead of making a
long-living memoryview and keeping 10K blocked for GC.
Nonetheless, `memoryview` is indispensable for advanced preallocated buffer
management. `readinto()` method discussed above puts data at the beginning
management. ``readinto()`` method discussed above puts data at the beginning
of buffer and fills in entire buffer. What if you need to put data in the
middle of existing buffer? Just create a memoryview into the needed section
of buffer and pass it to `readinto()`.
of buffer and pass it to ``readinto()``.
Identifying the slowest section of code
---------------------------------------
......@@ -326,7 +326,7 @@ standard approach would be to write
mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin
This involves the overhead of two calls to the `Pin` instance's :meth:`~machine.Pin.value()`
This involves the overhead of two calls to the :class:`~machine.Pin` instance's :meth:`~machine.Pin.value()`
method. This overhead can be eliminated by performing a read/write to the relevant bit
of the chip's GPIO port output data register (odr). To facilitate this the ``stm``
module provides a set of constants providing the addresses of the relevant registers.
......
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017-2018 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H
#define MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H
#include "py/mphal.h"
enum {
MP_QSPI_IOCTL_INIT,
MP_QSPI_IOCTL_DEINIT,
MP_QSPI_IOCTL_BUS_ACQUIRE,
MP_QSPI_IOCTL_BUS_RELEASE,
};
typedef struct _mp_qspi_proto_t {
int (*ioctl)(void *self, uint32_t cmd);
void (*write_cmd_data)(void *self, uint8_t cmd, size_t len, uint32_t data);
void (*write_cmd_addr_data)(void *self, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src);
uint32_t (*read_cmd)(void *self, uint8_t cmd, size_t len);
void (*read_cmd_qaddr_qdata)(void *self, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest);
} mp_qspi_proto_t;
typedef struct _mp_soft_qspi_obj_t {
mp_hal_pin_obj_t cs;
mp_hal_pin_obj_t clk;
mp_hal_pin_obj_t io0;
mp_hal_pin_obj_t io1;
mp_hal_pin_obj_t io2;
mp_hal_pin_obj_t io3;
} mp_soft_qspi_obj_t;
extern const mp_qspi_proto_t mp_soft_qspi_proto;
#endif // MICROPY_INCLUDED_DRIVERS_BUS_QSPI_H
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017-2018 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "drivers/bus/qspi.h"
#define CS_LOW(self) mp_hal_pin_write(self->cs, 0)
#define CS_HIGH(self) mp_hal_pin_write(self->cs, 1)
#ifdef MICROPY_HW_SOFTQSPI_SCK_LOW
// Use externally provided functions for SCK control and IO reading
#define SCK_LOW(self) MICROPY_HW_SOFTQSPI_SCK_LOW(self)
#define SCK_HIGH(self) MICROPY_HW_SOFTQSPI_SCK_HIGH(self)
#define NIBBLE_READ(self) MICROPY_HW_SOFTQSPI_NIBBLE_READ(self)
#else
// Use generic pin functions for SCK control and IO reading
#define SCK_LOW(self) mp_hal_pin_write(self->clk, 0)
#define SCK_HIGH(self) mp_hal_pin_write(self->clk, 1)
#define NIBBLE_READ(self) ( \
mp_hal_pin_read(self->io0) \
| (mp_hal_pin_read(self->io1) << 1) \
| (mp_hal_pin_read(self->io2) << 2) \
| (mp_hal_pin_read(self->io3) << 3))
#endif
STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) {
mp_hal_pin_write(self->io0, v & 1);
mp_hal_pin_write(self->io1, (v >> 1) & 1);
mp_hal_pin_write(self->io2, (v >> 2) & 1);
mp_hal_pin_write(self->io3, (v >> 3) & 1);
}
STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
switch (cmd) {
case MP_QSPI_IOCTL_INIT:
mp_hal_pin_high(self->cs);
mp_hal_pin_output(self->cs);
// Configure pins
mp_hal_pin_write(self->clk, 0);
mp_hal_pin_output(self->clk);
//mp_hal_pin_write(self->clk, 1);
mp_hal_pin_output(self->io0);
mp_hal_pin_input(self->io1);
mp_hal_pin_write(self->io2, 1);
mp_hal_pin_output(self->io2);
mp_hal_pin_write(self->io3, 1);
mp_hal_pin_output(self->io3);
break;
}
return 0; // success
}
STATIC void mp_soft_qspi_transfer(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *src, uint8_t *dest) {
// Will run as fast as possible, limited only by CPU speed and GPIO time
mp_hal_pin_input(self->io1);
mp_hal_pin_output(self->io0);
if (self->io3) {
mp_hal_pin_write(self->io2, 1);
mp_hal_pin_output(self->io2);
mp_hal_pin_write(self->io3, 1);
mp_hal_pin_output(self->io3);
}
if (src) {
for (size_t i = 0; i < len; ++i) {
uint8_t data_out = src[i];
uint8_t data_in = 0;
for (int j = 0; j < 8; ++j, data_out <<= 1) {
mp_hal_pin_write(self->io0, (data_out >> 7) & 1);
mp_hal_pin_write(self->clk, 1);
data_in = (data_in << 1) | mp_hal_pin_read(self->io1);
mp_hal_pin_write(self->clk, 0);
}
if (dest != NULL) {
dest[i] = data_in;
}
}
} else {
for (size_t i = 0; i < len; ++i) {
uint8_t data_in = 0;
for (int j = 0; j < 8; ++j) {
mp_hal_pin_write(self->clk, 1);
data_in = (data_in << 1) | mp_hal_pin_read(self->io1);
mp_hal_pin_write(self->clk, 0);
}
if (dest != NULL) {
dest[i] = data_in;
}
}
}
}
STATIC void mp_soft_qspi_qread(mp_soft_qspi_obj_t *self, size_t len, uint8_t *buf) {
// Make all IO lines input
mp_hal_pin_input(self->io2);
mp_hal_pin_input(self->io3);
mp_hal_pin_input(self->io0);
mp_hal_pin_input(self->io1);
// Will run as fast as possible, limited only by CPU speed and GPIO time
while (len--) {
SCK_HIGH(self);
uint8_t data_in = NIBBLE_READ(self);
SCK_LOW(self);
SCK_HIGH(self);
*buf++ = (data_in << 4) | NIBBLE_READ(self);
SCK_LOW(self);
}
}
STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint8_t *buf) {
// Make all IO lines output
mp_hal_pin_output(self->io2);
mp_hal_pin_output(self->io3);
mp_hal_pin_output(self->io0);
mp_hal_pin_output(self->io1);
// Will run as fast as possible, limited only by CPU speed and GPIO time
for (size_t i = 0; i < len; ++i) {
nibble_write(self, buf[i] >> 4);
SCK_HIGH(self);
SCK_LOW(self);
nibble_write(self, buf[i]);
SCK_HIGH(self);
SCK_LOW(self);
}
//mp_hal_pin_input(self->io1);
}
STATIC void mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint32_t cmd_buf = cmd | data << 8;
CS_LOW(self);
mp_soft_qspi_transfer(self, 1 + len, (uint8_t*)&cmd_buf, NULL);
CS_HIGH(self);
}
STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint8_t cmd_buf[4] = {cmd, addr >> 16, addr >> 8, addr};
CS_LOW(self);
mp_soft_qspi_transfer(self, 4, cmd_buf, NULL);
mp_soft_qspi_transfer(self, len, src, NULL);
CS_HIGH(self);
}
STATIC uint32_t mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint32_t cmd_buf = cmd;
CS_LOW(self);
mp_soft_qspi_transfer(self, 1 + len, (uint8_t*)&cmd_buf, (uint8_t*)&cmd_buf);
CS_HIGH(self);
return cmd_buf >> 8;
}
STATIC void mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) {
mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in;
uint8_t cmd_buf[7] = {cmd, addr >> 16, addr >> 8, addr};
CS_LOW(self);
mp_soft_qspi_transfer(self, 1, cmd_buf, NULL);
mp_soft_qspi_qwrite(self, 6, &cmd_buf[1]); // 3 addr bytes, 1 extra byte (0), 2 dummy bytes (4 dummy cycles)
mp_soft_qspi_qread(self, len, dest);
CS_HIGH(self);
}
const mp_qspi_proto_t mp_soft_qspi_proto = {
.ioctl = mp_soft_qspi_ioctl,
.write_cmd_data = mp_soft_qspi_write_cmd_data,
.write_cmd_addr_data = mp_soft_qspi_write_cmd_addr_data,
.read_cmd = mp_soft_qspi_read_cmd,
.read_cmd_qaddr_qdata = mp_soft_qspi_read_cmd_qaddr_qdata,
};
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "drivers/bus/spi.h"
int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) {
mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t*)self_in;
switch (cmd) {
case MP_SPI_IOCTL_INIT:
mp_hal_pin_write(self->sck, self->polarity);
mp_hal_pin_output(self->sck);
mp_hal_pin_output(self->mosi);
mp_hal_pin_input(self->miso);
break;
case MP_SPI_IOCTL_DEINIT:
break;
}
return 0;
}
void mp_soft_spi_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t*)self_in;
uint32_t delay_half = self->delay_half;
// only MSB transfer is implemented
// If a port defines MICROPY_HW_SOFTSPI_MIN_DELAY, and the configured
// delay_half is equal to this value, then the software SPI implementation
// will run as fast as possible, limited only by CPU speed and GPIO time.
#ifdef MICROPY_HW_SOFTSPI_MIN_DELAY
if (delay_half == MICROPY_HW_SOFTSPI_MIN_DELAY) {
for (size_t i = 0; i < len; ++i) {
uint8_t data_out = src[i];
uint8_t data_in = 0;
for (int j = 0; j < 8; ++j, data_out <<= 1) {
mp_hal_pin_write(self->mosi, (data_out >> 7) & 1);
mp_hal_pin_write(self->sck, 1 - self->polarity);
data_in = (data_in << 1) | mp_hal_pin_read(self->miso);
mp_hal_pin_write(self->sck, self->polarity);
}
if (dest != NULL) {
dest[i] = data_in;
}
}
return;
}
#endif
for (size_t i = 0; i < len; ++i) {
uint8_t data_out = src[i];
uint8_t data_in = 0;
for (int j = 0; j < 8; ++j, data_out <<= 1) {
mp_hal_pin_write(self->mosi, (data_out >> 7) & 1);
if (self->phase == 0) {
mp_hal_delay_us_fast(delay_half);
mp_hal_pin_write(self->sck, 1 - self->polarity);
} else {
mp_hal_pin_write(self->sck, 1 - self->polarity);
mp_hal_delay_us_fast(delay_half);
}
data_in = (data_in << 1) | mp_hal_pin_read(self->miso);
if (self->phase == 0) {
mp_hal_delay_us_fast(delay_half);
mp_hal_pin_write(self->sck, self->polarity);
} else {
mp_hal_pin_write(self->sck, self->polarity);
mp_hal_delay_us_fast(delay_half);
}
}
if (dest != NULL) {
dest[i] = data_in;
}
}
}
const mp_spi_proto_t mp_soft_spi_proto = {
.ioctl = mp_soft_spi_ioctl,
.transfer = mp_soft_spi_transfer,
};
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_DRIVERS_BUS_SPI_H
#define MICROPY_INCLUDED_DRIVERS_BUS_SPI_H
#include "py/mphal.h"
enum {
MP_SPI_IOCTL_INIT,
MP_SPI_IOCTL_DEINIT,
};
typedef struct _mp_spi_proto_t {
int (*ioctl)(void *self, uint32_t cmd);
void (*transfer)(void *self, size_t len, const uint8_t *src, uint8_t *dest);
} mp_spi_proto_t;
typedef struct _mp_soft_spi_obj_t {
uint32_t delay_half; // microsecond delay for half SCK period
uint8_t polarity;
uint8_t phase;
mp_hal_pin_obj_t sck;
mp_hal_pin_obj_t mosi;
mp_hal_pin_obj_t miso;
} mp_soft_spi_obj_t;
extern const mp_spi_proto_t mp_soft_spi_proto;
int mp_soft_spi_ioctl(void *self, uint32_t cmd);
void mp_soft_spi_transfer(void *self, size_t len, const uint8_t *src, uint8_t *dest);
#endif // MICROPY_INCLUDED_DRIVERS_BUS_SPI_H
This diff is collapsed.
......@@ -3,7 +3,7 @@
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Damien P. George
* Copyright (c) 2016-2018 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
......@@ -26,14 +26,36 @@
#ifndef MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H
#define MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H
#include "extmod/machine_spi.h"
#include "drivers/bus/spi.h"
#include "drivers/bus/qspi.h"
enum {
MP_SPIFLASH_BUS_SPI,
MP_SPIFLASH_BUS_QSPI,
};
typedef struct _mp_spiflash_config_t {
uint32_t bus_kind;
union {
struct {
mp_hal_pin_obj_t cs;
void *data;
const mp_spi_proto_t *proto;
} u_spi;
struct {
void *data;
const mp_qspi_proto_t *proto;
} u_qspi;
} bus;
} mp_spiflash_config_t;
typedef struct _mp_spiflash_t {
mp_hal_pin_obj_t cs;
mp_obj_base_t *spi; // object must have protocol pointing to mp_machine_spi_p_t struct
const mp_spiflash_config_t *config;
volatile uint32_t flags;
} mp_spiflash_t;
void mp_spiflash_init(mp_spiflash_t *self);
void mp_spiflash_flush(mp_spiflash_t *self);
void mp_spiflash_read(mp_spiflash_t *self, uint32_t addr, size_t len, uint8_t *dest);
int mp_spiflash_write(mp_spiflash_t *self, uint32_t addr, size_t len, const uint8_t *src);
......
......@@ -38,61 +38,6 @@
#define MICROPY_PY_MACHINE_SPI_LSB (1)
#endif
void mp_machine_soft_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in;
uint32_t delay_half = self->delay_half;
// only MSB transfer is implemented
// If a port defines MICROPY_PY_MACHINE_SPI_MIN_DELAY, and the configured
// delay_half is equal to this value, then the software SPI implementation
// will run as fast as possible, limited only by CPU speed and GPIO time.
#ifdef MICROPY_PY_MACHINE_SPI_MIN_DELAY
if (delay_half == MICROPY_PY_MACHINE_SPI_MIN_DELAY) {
for (size_t i = 0; i < len; ++i) {
uint8_t data_out = src[i];
uint8_t data_in = 0;
for (int j = 0; j < 8; ++j, data_out <<= 1) {
mp_hal_pin_write(self->mosi, (data_out >> 7) & 1);
mp_hal_pin_write(self->sck, 1 - self->polarity);
data_in = (data_in << 1) | mp_hal_pin_read(self->miso);
mp_hal_pin_write(self->sck, self->polarity);
}
if (dest != NULL) {
dest[i] = data_in;
}
}
return;
}
#endif
for (size_t i = 0; i < len; ++i) {
uint8_t data_out = src[i];
uint8_t data_in = 0;
for (int j = 0; j < 8; ++j, data_out <<= 1) {
mp_hal_pin_write(self->mosi, (data_out >> 7) & 1);
if (self->phase == 0) {
mp_hal_delay_us_fast(delay_half);
mp_hal_pin_write(self->sck, 1 - self->polarity);
} else {
mp_hal_pin_write(self->sck, 1 - self->polarity);
mp_hal_delay_us_fast(delay_half);
}
data_in = (data_in << 1) | mp_hal_pin_read(self->miso);
if (self->phase == 0) {
mp_hal_delay_us_fast(delay_half);
mp_hal_pin_write(self->sck, self->polarity);
} else {
mp_hal_pin_write(self->sck, self->polarity);
mp_hal_delay_us_fast(delay_half);
}
}
if (dest != NULL) {
dest[i] = data_in;
}
}
}
/******************************************************************************/
// MicroPython bindings for generic machine.SPI
......@@ -199,9 +144,9 @@ MP_DEFINE_CONST_DICT(mp_machine_spi_locals_dict, machine_spi_locals_dict_table);
// Implementation of soft SPI
STATIC uint32_t baudrate_from_delay_half(uint32_t delay_half) {
#ifdef MICROPY_PY_MACHINE_SPI_MIN_DELAY
if (delay_half == MICROPY_PY_MACHINE_SPI_MIN_DELAY) {
return MICROPY_PY_MACHINE_SPI_MAX_BAUDRATE;
#ifdef MICROPY_HW_SOFTSPI_MIN_DELAY
if (delay_half == MICROPY_HW_SOFTSPI_MIN_DELAY) {
return MICROPY_HW_SOFTSPI_MAX_BAUDRATE;
} else
#endif
{
......@@ -210,9 +155,9 @@ STATIC uint32_t baudrate_from_delay_half(uint32_t delay_half) {
}
STATIC uint32_t baudrate_to_delay_half(uint32_t baudrate) {
#ifdef MICROPY_PY_MACHINE_SPI_MIN_DELAY
if (baudrate >= MICROPY_PY_MACHINE_SPI_MAX_BAUDRATE) {
return MICROPY_PY_MACHINE_SPI_MIN_DELAY;
#ifdef MICROPY_HW_SOFTSPI_MIN_DELAY
if (baudrate >= MICROPY_HW_SOFTSPI_MAX_BAUDRATE) {
return MICROPY_HW_SOFTSPI_MIN_DELAY;
} else
#endif
{
......@@ -229,8 +174,8 @@ STATIC void mp_machine_soft_spi_print(const mp_print_t *print, mp_obj_t self_in,
mp_machine_soft_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "SoftSPI(baudrate=%u, polarity=%u, phase=%u,"
" sck=" MP_HAL_PIN_FMT ", mosi=" MP_HAL_PIN_FMT ", miso=" MP_HAL_PIN_FMT ")",
baudrate_from_delay_half(self->delay_half), self->polarity, self->phase,
mp_hal_pin_name(self->sck), mp_hal_pin_name(self->mosi), mp_hal_pin_name(self->miso));
baudrate_from_delay_half(self->spi.delay_half), self->spi.polarity, self->spi.phase,
mp_hal_pin_name(self->spi.sck), mp_hal_pin_name(self->spi.mosi), mp_hal_pin_name(self->spi.miso));
}
STATIC mp_obj_t mp_machine_soft_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
......@@ -253,9 +198,9 @@ STATIC mp_obj_t mp_machine_soft_spi_make_new(const mp_obj_type_t *type, size_t n
self->base.type = &mp_machine_soft_spi_type;
// set parameters
self->delay_half = baudrate_to_delay_half(args[ARG_baudrate].u_int);
self->polarity = args[ARG_polarity].u_int;
self->phase = args[ARG_phase].u_int;
self->spi.delay_half = baudrate_to_delay_half(args[ARG_baudrate].u_int);
self->spi.polarity = args[ARG_polarity].u_int;
self->spi.phase = args[ARG_phase].u_int;
if (args[ARG_bits].u_int != 8) {
mp_raise_ValueError("bits must be 8");
}
......@@ -267,15 +212,12 @@ STATIC mp_obj_t mp_machine_soft_spi_make_new(const mp_obj_type_t *type, size_t n
|| args[ARG_miso].u_obj == MP_OBJ_NULL) {
mp_raise_ValueError("must specify all of sck/mosi/miso");
}
self->sck = mp_hal_get_pin_obj(args[ARG_sck].u_obj);
self->mosi = mp_hal_get_pin_obj(args[ARG_mosi].u_obj);
self->miso = mp_hal_get_pin_obj(args[ARG_miso].u_obj);
self->spi.sck = mp_hal_get_pin_obj(args[ARG_sck].u_obj);
self->spi.mosi = mp_hal_get_pin_obj(args[ARG_mosi].u_obj);
self->spi.miso = mp_hal_get_pin_obj(args[ARG_miso].u_obj);
// configure pins
mp_hal_pin_write(self->sck, self->polarity);
mp_hal_pin_output(self->sck);
mp_hal_pin_output(self->mosi);
mp_hal_pin_input(self->miso);
// configure bus
mp_soft_spi_ioctl(&self->spi, MP_SPI_IOCTL_INIT);
return MP_OBJ_FROM_PTR(self);
}
......@@ -296,32 +238,34 @@ STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, cons
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
if (args[ARG_baudrate].u_int != -1) {
self->delay_half = baudrate_to_delay_half(args[ARG_baudrate].u_int);
self->spi.delay_half = baudrate_to_delay_half(args[ARG_baudrate].u_int);
}
if (args[ARG_polarity].u_int != -1) {
self->polarity = args[ARG_polarity].u_int;
self->spi.polarity = args[ARG_polarity].u_int;
}
if (args[ARG_phase].u_int != -1) {
self->phase = args[ARG_phase].u_int;
self->spi.phase = args[ARG_phase].u_int;
}
if (args[ARG_sck].u_obj != MP_OBJ_NULL) {
self->sck = mp_hal_get_pin_obj(args[ARG_sck].u_obj);
self->spi.sck = mp_hal_get_pin_obj(args[ARG_sck].u_obj);
}
if (args[ARG_mosi].u_obj != MP_OBJ_NULL) {
self->mosi = mp_hal_get_pin_obj(args[ARG_mosi].u_obj);
self->spi.mosi = mp_hal_get_pin_obj(args[ARG_mosi].u_obj);
}
if (args[ARG_miso].u_obj != MP_OBJ_NULL) {
self->miso = mp_hal_get_pin_obj(args[ARG_miso].u_obj);
self->spi.miso = mp_hal_get_pin_obj(args[ARG_miso].u_obj);
}
// configure pins
mp_hal_pin_write(self->sck, self->polarity);
mp_hal_pin_output(self->sck);
mp_hal_pin_output(self->mosi);
mp_hal_pin_input(self->miso);
// configure bus
mp_soft_spi_ioctl(&self->spi, MP_SPI_IOCTL_INIT);
}
STATIC void mp_machine_soft_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in;
mp_soft_spi_transfer(&self->spi, len, src, dest);
}
STATIC const mp_machine_spi_p_t mp_machine_soft_spi_p = {
const mp_machine_spi_p_t mp_machine_soft_spi_p = {
.init = mp_machine_soft_spi_init,
.deinit = NULL,
.transfer = mp_machine_soft_spi_transfer,
......
......@@ -28,6 +28,7 @@
#include "py/obj.h"
#include "py/mphal.h"
#include "drivers/bus/spi.h"
// SPI protocol
typedef struct _mp_machine_spi_p_t {
......@@ -38,19 +39,13 @@ typedef struct _mp_machine_spi_p_t {
typedef struct _mp_machine_soft_spi_obj_t {
mp_obj_base_t base;
uint32_t delay_half; // microsecond delay for half SCK period
uint8_t polarity;
uint8_t phase;
mp_hal_pin_obj_t sck;
mp_hal_pin_obj_t mosi;
mp_hal_pin_obj_t miso;
mp_soft_spi_obj_t spi;
} mp_machine_soft_spi_obj_t;
extern const mp_machine_spi_p_t mp_machine_soft_spi_p;
extern const mp_obj_type_t mp_machine_soft_spi_type;
extern const mp_obj_dict_t mp_machine_spi_locals_dict;
void mp_machine_soft_spi_transfer(mp_obj_base_t *self, size_t len, const uint8_t *src, uint8_t *dest);
mp_obj_t mp_machine_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_read_obj);
......
......@@ -366,9 +366,7 @@ mp_obj_t mp_vfs_listdir(size_t n_args, const mp_obj_t *args) {
mp_obj_t dir_list = mp_obj_new_list(0, NULL);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
mp_obj_t *items;
mp_obj_get_array_fixed_n(next, 3, &items);
mp_obj_list_append(dir_list, items[0]);
mp_obj_list_append(dir_list, mp_obj_subscr(next, MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_SENTINEL));
}
return dir_list;
}
......
......@@ -142,8 +142,8 @@ STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) {
// Note that FatFS already filters . and .., so we don't need to
// make 3-tuple with info about this entry
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL));
// make 4-tuple with info about this entry
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL));
if (self->is_str) {
t->items[0] = mp_obj_new_str(fn, strlen(fn));
} else {
......@@ -157,6 +157,7 @@ STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) {
t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG);
}
t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
t->items[3] = mp_obj_new_int_from_uint(fno.fsize);