Compare commits

..

No commits in common. "cross" and "v1.9" have entirely different histories.
cross ... v1.9

723 changed files with 3370 additions and 8932 deletions

2
.gitignore vendored
View File

@ -9,7 +9,7 @@
*.dis
*.exe
# Packages
# Packages
############
# Logs and Databases

View File

@ -40,7 +40,7 @@ script:
- make -C qemu-arm test
- make -C stmhal
- make -C stmhal BOARD=PYBV11 MICROPY_PY_WIZNET5K=1 MICROPY_PY_CC3K=1
- make -C stmhal BOARD=STM32F769DISC
- make -C stmhal BOARD=STM32F7DISC
- make -C stmhal BOARD=STM32L476DISC
- make -C teensy
- make -C cc3200 BTARGET=application BTYPE=release

View File

@ -26,27 +26,6 @@ require such detailed description.
To get good practical examples of good commits and their messages, browse
the `git log` of the project.
MicroPython doesn't require explicit sign-off for patches ("Signed-off-by"
lines and similar). Instead, the commit message, and your name and email
address on it construes your sign-off of the following:
* That you wrote the change yourself, or took it from a project with
a compatible license (in the latter case the commit message, and possibly
source code should provide reference where the implementation was taken
from and give credit to the original author, as required by the license).
* That you are allowed to release these changes to an open-source project
(for example, changes done during paid work for a third party may require
explicit approval from that third party).
* That you (or your employer) agree to release the changes under
MicroPython's license, which is the MIT license. Note that you retain
copyright for your changes (for smaller changes, the commit message
conveys your copyright; if you make significant changes to a particular
source module, you're welcome to add your name to the file header).
* Your signature for all of the above, which is the 'Author' line in
the commit message, and which should include your full real name and
a valid and active email address by which you can be contacted in the
foreseeable future.
Python code conventions
=======================
@ -73,7 +52,7 @@ White space:
keyword and the opening parenthesis.
- Put 1 space after a comma, and 1 space around operators.
Braces:
Braces:
- Use braces for all blocks, even no-line and single-line pieces of
code.
- Put opening braces on the end of the line it belongs to, not on
@ -135,76 +114,3 @@ Type declarations:
int member;
void *data;
} my_struct_t;
Documentation conventions
=========================
MicroPython generally follows CPython in documentation process and
conventions. reStructuredText syntax is used for the documention.
Specific conventions/suggestions:
* Use `*` markup to refer to arguments of a function, e.g.:
```
.. method:: poll.unregister(obj)
Unregister *obj* from polling.
```
* Use following syntax for cross-references/cross-links:
```
:func:`foo` - function foo in current module
:func:`module1.foo` - function foo in module "module1"
(similarly for other referent types)
:class:`Foo` - class Foo
:meth:`Class.method1` - method1 in Class
:meth:`~Class.method1` - method1 in Class, but rendered just as "method1()",
not "Class.method1()"
:meth:`title <method1>` - reference method1, but render as "title" (use only
if really needed)
:mod:`module1` - module module1
`symbol` - generic xref syntax which can replace any of the above in case
the xref is unambiguous. If there's ambiguity, there will be a warning
during docs generation, which need to be fixed using one of the syntaxes
above
```
* Cross-referencing arbitrary locations
~~~
.. _xref_target:
Normal non-indented text.
This is :ref:`reference <xref_target>`.
(If xref target is followed by section title, can be just
:ref:`xref_target`).
~~~
* Linking to external URL:
```
`link text <http://foo.com/...>`_
```
* Referencing builtin singleton objects:
```
``None``, ``True``, ``False``
```
* Use following syntax to create common description for more than one element:
~~~
.. function:: foo(x)
bar(y)
Description common to foo() and bar().
~~~
More detailed guides and quickrefs:
* http://www.sphinx-doc.org/en/stable/rest.html
* http://www.sphinx-doc.org/en/stable/markup/inline.html
* http://docutils.sourceforge.net/docs/user/rst/quickref.html

View File

@ -22,18 +22,12 @@ Builtin modules include `sys`, `time`, and `struct`, etc. Select ports have
support for `_thread` module (multithreading). Note that only a subset of
Python 3 functionality is implemented for the data types and modules.
MicroPython can execute scripts in textual source form or from precompiled
bytecode, in both cases either from an on-device filesystem or "frozen" into
the MicroPython executable.
See the repository http://github.com/micropython/pyboard for the MicroPython
See the repository www.github.com/micropython/pyboard for the MicroPython
board (PyBoard), the officially supported reference electronic circuit board.
Major components in this repository:
- py/ -- the core Python implementation, including compiler, runtime, and
core library.
- mpy-cross/ -- the MicroPython cross-compiler which is used to turn scripts
into precompiled bytecode.
- unix/ -- a version of MicroPython that runs on Unix.
- stmhal/ -- a version of MicroPython that runs on the PyBoard and similar
STM32 boards (using ST's Cube HAL drivers).

View File

@ -11,7 +11,7 @@ MEMORY
CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 0x010000 /* 64 KiB */
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 0x020000 /* 128 KiB */
}
/* top end of the stack */
_estack = ORIGIN(RAM) + LENGTH(RAM);
@ -30,7 +30,7 @@ SECTIONS
. = ALIGN(4);
} >FLASH_ISR
/* The program code and other data goes into FLASH */
.text :
{
@ -46,7 +46,7 @@ SECTIONS
_etext = .; /* define a global symbol at end of code */
_sidata = _etext; /* This is used by the startup in order to initialize the .data secion */
} >FLASH_TEXT
/*
.ARM.extab :
{
@ -60,7 +60,7 @@ SECTIONS
__exidx_end = .;
} >FLASH
*/
/* This is the initialized data section
The program executes knowing that the data is in the RAM
but the loader puts the initial values in the FLASH (inidata).
@ -76,7 +76,7 @@ SECTIONS
. = ALIGN(4);
_edata = .; /* define a global symbol at data end; used by startup code in order to initialise the .data section in RAM */
} >RAM
/* Uninitialized data section */
.bss :
{

View File

@ -138,7 +138,7 @@ If `WIPY_IP`, `WIPY_USER` or `WIPY_PWD` are omitted the default values (the ones
## Regarding old revisions of the CC3200-LAUNCHXL
First silicon (pre-release) revisions of the CC3200 had issues with the ram blocks, and MicroPython cannot run
there. Make sure to use a **v4.1 (or higher) LAUNCHXL board** when trying this port, otherwise it won't work.
there. Make sure to use a **v4.1 (or higer) LAUNCHXL board** when trying this port, otherwise it won't work.
### Note regarding FileZilla

View File

@ -147,12 +147,13 @@ APP_LIB_SRC_C = $(addprefix lib/,\
netutils/netutils.c \
timeutils/timeutils.c \
utils/pyexec.c \
utils/sys_stdio_mphal.c \
)
APP_STM_SRC_C = $(addprefix stmhal/,\
bufhelper.c \
input.c \
irq.c \
pybstdio.c \
)
OBJ = $(PY_O) $(addprefix $(BUILD)/, $(APP_FATFS_SRC_C:.c=.o) $(APP_RTOS_SRC_C:.c=.o) $(APP_FTP_SRC_C:.c=.o) $(APP_HAL_SRC_C:.c=.o) $(APP_MISC_SRC_C:.c=.o))

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_BOOTMGR_BOOTMGR_H
#define MICROPY_INCLUDED_CC3200_BOOTMGR_BOOTMGR_H
#ifndef __BOOTMGR_H__
#define __BOOTMGR_H__
//****************************************************************************
//
@ -65,4 +66,4 @@ extern void Run(unsigned long);
}
#endif
#endif // MICROPY_INCLUDED_CC3200_BOOTMGR_BOOTMGR_H
#endif //__BOOTMGR_H__

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_BOOTMGR_FLC_H
#define MICROPY_INCLUDED_CC3200_BOOTMGR_FLC_H
#ifndef __FLC_H__
#define __FLC_H__
/******************************************************************************
@ -92,4 +93,4 @@ typedef struct _sBootInfo_t
}
#endif
#endif // MICROPY_INCLUDED_CC3200_BOOTMGR_FLC_H
#endif /* __FLC_H__ */

View File

@ -335,7 +335,7 @@ void ftp_run (void) {
ftp_data.loggin.uservalid = false;
ftp_data.loggin.passvalid = false;
strcpy (ftp_path, "/");
ftp_send_reply (220, "MicroPython FTP Server");
ftp_send_reply (220, "Micropython FTP Server");
break;
}
}

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_FTP_FTP_H
#define MICROPY_INCLUDED_CC3200_FTP_FTP_H
#ifndef FTP_H_
#define FTP_H_
/******************************************************************************
DECLARE EXPORTED FUNCTIONS
@ -35,4 +36,4 @@ extern void ftp_enable (void);
extern void ftp_disable (void);
extern void ftp_reset (void);
#endif // MICROPY_INCLUDED_CC3200_FTP_FTP_H
#endif /* FTP_H_ */

View File

@ -23,8 +23,10 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_FTP_UPDATER_H
#define MICROPY_INCLUDED_CC3200_FTP_UPDATER_H
#ifndef UPDATER_H_
#define UPDATER_H_
extern void updater_pre_init (void);
extern bool updater_check_path (void *path);
@ -33,4 +35,4 @@ extern bool updater_write (uint8_t *buf, uint32_t len);
extern void updater_finnish (void);
extern bool updater_verify (uint8_t *rbuff, uint8_t *hasbuff);
#endif // MICROPY_INCLUDED_CC3200_FTP_UPDATER_H
#endif /* UPDATER_H_ */

View File

@ -24,6 +24,9 @@
* THE SOFTWARE.
*/
#ifndef CC3200_LAUNCHXL_HAL_CC3200_HAL_H_
#define CC3200_LAUNCHXL_HAL_CC3200_HAL_H_
#include <stdint.h>
#include <stdbool.h>
@ -66,3 +69,5 @@ extern void mp_hal_set_interrupt_char (int c);
#define mp_hal_delay_us(usec) UtilsDelay(UTILS_DELAY_US_TO_COUNT(usec))
#define mp_hal_ticks_cpu() (SysTickPeriodGet() - SysTickValueGet())
#endif /* CC3200_LAUNCHXL_HAL_CC3200_HAL_H_ */

View File

@ -89,7 +89,7 @@ int main (void) {
#ifndef DEBUG
OsiTaskHandle mpTaskHandle;
#endif
mpTaskHandle = xTaskCreateStatic(TASK_MicroPython, "MicroPy",
mpTaskHandle = xTaskCreateStatic(TASK_Micropython, "MicroPy",
MICROPY_TASK_STACK_LEN, NULL, MICROPY_TASK_PRIORITY, mpTaskStack, &mpTaskTCB);
ASSERT(mpTaskHandle != NULL);

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MISC_ANTENNA_H
#define MICROPY_INCLUDED_CC3200_MISC_ANTENNA_H
#ifndef _ANTENNA_H_
#define _ANTENNA_H_
typedef enum {
ANTENNA_TYPE_INTERNAL = 0,
@ -34,4 +35,4 @@ typedef enum {
extern void antenna_init0 (void);
extern void antenna_select (antenna_type_t antenna_type);
#endif // MICROPY_INCLUDED_CC3200_MISC_ANTENNA_H
#endif /* _ANTENNA_H_ */

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MISC_MPERROR_H
#define MICROPY_INCLUDED_CC3200_MISC_MPERROR_H
#ifndef MPERROR_H_
#define MPERROR_H_
extern void NORETURN __fatal_error(const char *msg);
@ -38,4 +39,4 @@ void mperror_heartbeat_signal (void);
void mperror_enable_heartbeat (bool enable);
bool mperror_is_heartbeat_enabled (void);
#endif // MICROPY_INCLUDED_CC3200_MISC_MPERROR_H
#endif // MPERROR_H_

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MISC_MPEXCEPTION_H
#define MICROPY_INCLUDED_CC3200_MISC_MPEXCEPTION_H
#ifndef MPEXCEPTION_H_
#define MPEXCEPTION_H_
extern const char mpexception_value_invalid_arguments[];
extern const char mpexception_num_type_invalid_arguments[];
@ -39,4 +40,4 @@ extern void mpexception_set_interrupt_char (int c);
extern void mpexception_nlr_jump (void *o);
extern void mpexception_keyboard_nlr_jump (void);
#endif // MICROPY_INCLUDED_CC3200_MISC_MPEXCEPTION_H
#endif /* MPEXCEPTION_H_ */

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MISC_MPIRQ_H
#define MICROPY_INCLUDED_CC3200_MISC_MPIRQ_H
#ifndef MPIRQ_H_
#define MPIRQ_H_
/******************************************************************************
DEFINE CONSTANTS
@ -71,4 +72,4 @@ void mp_irq_remove (const mp_obj_t parent);
void mp_irq_handler (mp_obj_t self_in);
uint mp_irq_translate_priority (uint priority);
#endif // MICROPY_INCLUDED_CC3200_MISC_MPIRQ_H
#endif /* MPIRQ_H_ */

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H
#define MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H
#ifndef MODNETWORK_H_
#define MODNETWORK_H_
/******************************************************************************
DEFINE CONSTANTS
@ -51,7 +52,7 @@ typedef struct _mod_network_socket_base_t {
} u_param;
int16_t sd;
};
uint32_t timeout_ms; // 0 for no timeout
bool has_timeout;
bool cert_req;
} mod_network_socket_base_t;
@ -70,4 +71,4 @@ extern const mod_network_nic_type_t mod_network_nic_type_wlan;
******************************************************************************/
void mod_network_init0(void);
#endif // MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H
#endif // MODNETWORK_H_

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H
#define MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H
#ifndef MODUBINASCII_H_
#define MODUBINASCII_H_
#endif // MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H
#endif /* MODUBINASCII_H_ */

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUOS_H
#define MICROPY_INCLUDED_CC3200_MODS_MODUOS_H
#ifndef MODUOS_H_
#define MODUOS_H_
#include "py/obj.h"
@ -44,4 +45,4 @@ typedef struct _os_term_dup_obj_t {
******************************************************************************/
void osmount_unmount_all (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_MODUOS_H
#endif // MODUOS_H_

View File

@ -34,7 +34,6 @@
#include "py/objstr.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/mphal.h"
#include "lib/netutils/netutils.h"
#include "modnetwork.h"
#include "modusocket.h"
@ -69,31 +68,6 @@
ip[2] = addr.sa_data[3]; \
ip[3] = addr.sa_data[2];
#define SOCKET_TIMEOUT_QUANTA_MS (20)
STATIC int convert_sl_errno(int sl_errno) {
return -sl_errno;
}
// This function is left as non-static so it's not inlined.
int check_timedout(mod_network_socket_obj_t *s, int ret, uint32_t *timeout_ms, int *_errno) {
if (*timeout_ms == 0 || ret != SL_EAGAIN) {
if (s->sock_base.timeout_ms > 0 && ret == SL_EAGAIN) {
*_errno = MP_ETIMEDOUT;
} else {
*_errno = convert_sl_errno(ret);
}
return -1;
}
mp_hal_delay_ms(SOCKET_TIMEOUT_QUANTA_MS);
if (*timeout_ms < SOCKET_TIMEOUT_QUANTA_MS) {
*timeout_ms = 0;
} else {
*timeout_ms -= SOCKET_TIMEOUT_QUANTA_MS;
}
return 0;
}
STATIC int wlan_gethostbyname(const char *name, mp_uint_t len, uint8_t *out_ip, uint8_t family) {
uint32_t ip;
int result = sl_NetAppDnsGetHostByName((_i8 *)name, (_u16)len, (_u32*)&ip, (_u8)family);
@ -148,111 +122,70 @@ STATIC int wlan_socket_accept(mod_network_socket_obj_t *s, mod_network_socket_ob
SlSockAddr_t addr;
SlSocklen_t addr_len = sizeof(addr);
uint32_t timeout_ms = s->sock_base.timeout_ms;
for (;;) {
sd = sl_Accept(s->sock_base.sd, &addr, &addr_len);
if (sd >= 0) {
// save the socket descriptor
s2->sock_base.sd = sd;
// return ip and port
UNPACK_SOCKADDR(addr, ip, *port);
return 0;
}
if (check_timedout(s, sd, &timeout_ms, _errno)) {
return -1;
}
sd = sl_Accept(s->sock_base.sd, &addr, &addr_len);
// save the socket descriptor
s2->sock_base.sd = sd;
if (sd < 0) {
*_errno = sd;
return -1;
}
// return ip and port
UNPACK_SOCKADDR(addr, ip, *port);
return 0;
}
STATIC int wlan_socket_connect(mod_network_socket_obj_t *s, byte *ip, mp_uint_t port, int *_errno) {
MAKE_SOCKADDR(addr, ip, port)
uint32_t timeout_ms = s->sock_base.timeout_ms;
// For a non-blocking connect the CC3100 will return SL_EALREADY while the
// connection is in progress.
for (;;) {
int ret = sl_Connect(s->sock_base.sd, &addr, sizeof(addr));
if (ret == 0) {
return 0;
}
// Check if we are in non-blocking mode and the connection is in progress
if (s->sock_base.timeout_ms == 0 && ret == SL_EALREADY) {
// To match BSD we return EINPROGRESS here
*_errno = MP_EINPROGRESS;
return -1;
}
// We are in blocking mode, so if the connection isn't in progress then error out
if (ret != SL_EALREADY) {
*_errno = convert_sl_errno(ret);
return -1;
}
if (check_timedout(s, SL_EAGAIN, &timeout_ms, _errno)) {
return -1;
}
int ret = sl_Connect(s->sock_base.sd, &addr, sizeof(addr));
if (ret != 0) {
*_errno = ret;
return -1;
}
return 0;
}
STATIC int wlan_socket_send(mod_network_socket_obj_t *s, const byte *buf, mp_uint_t len, int *_errno) {
if (len == 0) {
return 0;
mp_int_t bytes = 0;
if (len > 0) {
bytes = sl_Send(s->sock_base.sd, (const void *)buf, len, 0);
}
uint32_t timeout_ms = s->sock_base.timeout_ms;
for (;;) {
int ret = sl_Send(s->sock_base.sd, (const void *)buf, len, 0);
if (ret > 0) {
return ret;
}
if (check_timedout(s, ret, &timeout_ms, _errno)) {
return -1;
}
if (bytes <= 0) {
*_errno = bytes;
return -1;
}
return bytes;
}
STATIC int wlan_socket_recv(mod_network_socket_obj_t *s, byte *buf, mp_uint_t len, int *_errno) {
uint32_t timeout_ms = s->sock_base.timeout_ms;
for (;;) {
int ret = sl_Recv(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0);
if (ret >= 0) {
return ret;
}
if (check_timedout(s, ret, &timeout_ms, _errno)) {
return -1;
}
int ret = sl_Recv(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0);
if (ret < 0) {
*_errno = ret;
return -1;
}
return ret;
}
STATIC int wlan_socket_sendto( mod_network_socket_obj_t *s, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) {
MAKE_SOCKADDR(addr, ip, port)
uint32_t timeout_ms = s->sock_base.timeout_ms;
for (;;) {
int ret = sl_SendTo(s->sock_base.sd, (byte*)buf, len, 0, (SlSockAddr_t*)&addr, sizeof(addr));
if (ret >= 0) {
return ret;
}
if (check_timedout(s, ret, &timeout_ms, _errno)) {
return -1;
}
int ret = sl_SendTo(s->sock_base.sd, (byte*)buf, len, 0, (SlSockAddr_t*)&addr, sizeof(addr));
if (ret < 0) {
*_errno = ret;
return -1;
}
return ret;
}
STATIC int wlan_socket_recvfrom(mod_network_socket_obj_t *s, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) {
SlSockAddr_t addr;
SlSocklen_t addr_len = sizeof(addr);
uint32_t timeout_ms = s->sock_base.timeout_ms;
for (;;) {
int ret = sl_RecvFrom(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0, &addr, &addr_len);
if (ret >= 0) {
UNPACK_SOCKADDR(addr, ip, *port);
return ret;
}
if (check_timedout(s, ret, &timeout_ms, _errno)) {
return -1;
}
mp_int_t ret = sl_RecvFrom(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0, &addr, &addr_len);
if (ret < 0) {
*_errno = ret;
return -1;
}
UNPACK_SOCKADDR(addr, ip, *port);
return ret;
}
STATIC int wlan_socket_setsockopt(mod_network_socket_obj_t *s, mp_uint_t level, mp_uint_t opt, const void *optval, mp_uint_t optlen, int *_errno) {
@ -265,8 +198,10 @@ STATIC int wlan_socket_setsockopt(mod_network_socket_obj_t *s, mp_uint_t level,
}
STATIC int wlan_socket_settimeout(mod_network_socket_obj_t *s, mp_uint_t timeout_s, int *_errno) {
SlSockNonblocking_t option;
int ret;
bool has_timeout;
if (timeout_s == 0 || timeout_s == -1) {
SlSockNonblocking_t option;
if (timeout_s == 0) {
// set non-blocking mode
option.NonblockingEnabled = 1;
@ -274,19 +209,23 @@ STATIC int wlan_socket_settimeout(mod_network_socket_obj_t *s, mp_uint_t timeout
// set blocking mode
option.NonblockingEnabled = 0;
}
timeout_s = 0;
ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &option, sizeof(option));
has_timeout = false;
} else {
// synthesize timeout via non-blocking behaviour with a loop
option.NonblockingEnabled = 1;
// set timeout
struct SlTimeval_t timeVal;
timeVal.tv_sec = timeout_s; // seconds
timeVal.tv_usec = 0; // microseconds. 10000 microseconds resolution
ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_RCVTIMEO, &timeVal, sizeof(timeVal));
has_timeout = true;
}
int ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &option, sizeof(option));
if (ret != 0) {
*_errno = convert_sl_errno(ret);
*_errno = ret;
return -1;
}
s->sock_base.timeout_ms = timeout_s * 1000;
s->sock_base.has_timeout = has_timeout;
return 0;
}
@ -440,7 +379,7 @@ STATIC mp_obj_t socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t
s->sock_base.u_param.type = SL_SOCK_STREAM;
s->sock_base.u_param.proto = SL_IPPROTO_TCP;
s->sock_base.u_param.fileno = -1;
s->sock_base.timeout_ms = 0;
s->sock_base.has_timeout = false;
s->sock_base.cert_req = false;
if (n_args > 0) {
@ -523,7 +462,7 @@ STATIC mp_obj_t socket_accept(mp_obj_t self_in) {
mp_uint_t port = 0;
int _errno = 0;
if (wlan_socket_accept(self, socket2, ip, &port, &_errno) != 0) {
mp_raise_OSError(_errno);
mp_raise_OSError(-_errno);
}
// add the socket to the list
@ -551,7 +490,7 @@ STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) {
if (!self->sock_base.cert_req && _errno == SL_ESECSNOVERIFY) {
return mp_const_none;
}
mp_raise_OSError(_errno);
mp_raise_OSError(-_errno);
}
return mp_const_none;
}
@ -565,7 +504,7 @@ STATIC mp_obj_t socket_send(mp_obj_t self_in, mp_obj_t buf_in) {
int _errno;
mp_int_t ret = wlan_socket_send(self, bufinfo.buf, bufinfo.len, &_errno);
if (ret < 0) {
mp_raise_OSError(_errno);
mp_raise_OSError(-_errno);
}
return mp_obj_new_int_from_uint(ret);
}
@ -580,7 +519,10 @@ STATIC mp_obj_t socket_recv(mp_obj_t self_in, mp_obj_t len_in) {
int _errno;
mp_int_t ret = wlan_socket_recv(self, (byte*)vstr.buf, len, &_errno);
if (ret < 0) {
mp_raise_OSError(_errno);
if (_errno == MP_EAGAIN && self->sock_base.has_timeout) {
mp_raise_OSError(MP_ETIMEDOUT);
}
mp_raise_OSError(-_errno);
}
if (ret == 0) {
return mp_const_empty_bytes;
@ -607,7 +549,7 @@ STATIC mp_obj_t socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_
int _errno = 0;
mp_int_t ret = wlan_socket_sendto(self, bufinfo.buf, bufinfo.len, ip, port, &_errno);
if (ret < 0) {
mp_raise_OSError(_errno);
mp_raise_OSError(-_errno);
}
return mp_obj_new_int(ret);
}
@ -623,7 +565,10 @@ STATIC mp_obj_t socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) {
int _errno = 0;
mp_int_t ret = wlan_socket_recvfrom(self, (byte*)vstr.buf, vstr.len, ip, &port, &_errno);
if (ret < 0) {
mp_raise_OSError(_errno);
if (_errno == MP_EAGAIN && self->sock_base.has_timeout) {
mp_raise_OSError(MP_ETIMEDOUT);
}
mp_raise_OSError(-_errno);
}
mp_obj_t tuple[2];
if (ret == 0) {
@ -679,9 +624,9 @@ STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) {
} else {
timeout = mp_obj_get_int(timeout_in);
}
int _errno = 0;
int _errno;
if (wlan_socket_settimeout(self, timeout, &_errno) != 0) {
mp_raise_OSError(_errno);
mp_raise_OSError(-_errno);
}
return mp_const_none;
}
@ -698,8 +643,17 @@ STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t blocking) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
STATIC mp_obj_t socket_makefile(mp_uint_t n_args, const mp_obj_t *args) {
(void)n_args;
return args[0];
// TODO: CPython explicitly says that closing the returned object doesn't
// close the original socket (Python2 at all says that fd is dup()ed). But
// we save on the bloat.
mod_network_socket_obj_t *self = args[0];
if (n_args > 1) {
const char *mode = mp_obj_str_get_str(args[1]);
if (strcmp(mode, "rb") && strcmp(mode, "wb")) {
mp_raise_ValueError(mpexception_value_invalid_arguments);
}
}
return self;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 6, socket_makefile);
@ -721,7 +675,7 @@ STATIC const mp_map_elem_t socket_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR_makefile), (mp_obj_t)&socket_makefile_obj },
// stream methods
{ MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read1_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj},
{ MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj },
@ -735,8 +689,10 @@ STATIC mp_uint_t socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *e
if (ret < 0) {
// we need to ignore the socket closed error here because a read() without params
// only returns when the socket is closed by the other end
if (*errcode != -SL_ESECCLOSED) {
if (*errcode != SL_ESECCLOSED) {
ret = MP_STREAM_ERROR;
// needed to convert simplelink's negative error codes to POSIX
(*errcode) *= -1;
} else {
ret = 0;
}
@ -749,6 +705,8 @@ STATIC mp_uint_t socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size,
mp_int_t ret = wlan_socket_send(self, buf, size, errcode);
if (ret < 0) {
ret = MP_STREAM_ERROR;
// needed to convert simplelink's negative error codes to POSIX
(*errcode) *= -1;
}
return ret;
}

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H
#define MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H
#ifndef MODUSOCKET_H_
#define MODUSOCKET_H_
extern const mp_obj_dict_t socket_locals_dict;
extern const mp_stream_p_t socket_stream_p;
@ -35,4 +36,4 @@ extern void modusocket_socket_delete (int16_t sd);
extern void modusocket_enter_sleep (void);
extern void modusocket_close_all_user_sockets (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H
#endif /* MODUSOCKET_H_ */

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H
#define MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H
#ifndef MODWLAN_H_
#define MODWLAN_H_
/******************************************************************************
DEFINE CONSTANTS
@ -96,4 +97,4 @@ extern bool wlan_is_connected (void);
extern void wlan_set_current_time (uint32_t seconds_since_2000);
extern void wlan_off_on (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H
#endif /* MODWLAN_H_ */

View File

@ -24,9 +24,10 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBADC_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBADC_H
#ifndef PYBADC_H_
#define PYBADC_H_
extern const mp_obj_type_t pyb_adc_type;
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBADC_H
#endif /* PYBADC_H_ */

View File

@ -24,9 +24,10 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H
#ifndef PYBI2C_H_
#define PYBI2C_H_
extern const mp_obj_type_t pyb_i2c_type;
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H
#endif // PYBI2C_H_

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H
#ifndef PYBPIN_H_
#define PYBPIN_H_
enum {
PORT_A0 = GPIOA0_BASE,
@ -137,4 +138,4 @@ uint8_t pin_find_peripheral_unit (const mp_obj_t pin, uint8_t fn, uint8_t type);
uint8_t pin_find_peripheral_type (const mp_obj_t pin, uint8_t fn, uint8_t unit);
int8_t pin_find_af_index (const pin_obj_t* pin, uint8_t fn, uint8_t unit, uint8_t type);;
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H
#endif // PYBPIN_H_

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H
#ifndef PYBRTC_H_
#define PYBRTC_H_
// RTC triggers
#define PYB_RTC_ALARM0 (0x01)
@ -55,4 +56,4 @@ extern void pyb_rtc_calc_future_time (uint32_t a_mseconds, uint32_t *f_seconds,
extern void pyb_rtc_repeat_alarm (pyb_rtc_obj_t *self);
extern void pyb_rtc_disable_alarm (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H
#endif // PYBRTC_H_

View File

@ -23,8 +23,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBSD_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBSD_H
#ifndef PYBSD_H_
#define PYBSD_H_
/******************************************************************************
DEFINE PUBLIC TYPES
@ -41,4 +41,4 @@ typedef struct {
extern pybsd_obj_t pybsd_obj;
extern const mp_obj_type_t pyb_sd_type;
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSD_H
#endif // PYBSD_H_

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H
#ifndef PYBSLEEP_H_
#define PYBSLEEP_H_
/******************************************************************************
DEFINE CONSTANTS
@ -69,4 +70,4 @@ void pyb_sleep_deepsleep (void);
pybsleep_reset_cause_t pyb_sleep_get_reset_cause (void);
pybsleep_wake_reason_t pyb_sleep_get_wake_reason (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H
#endif /* PYBSLEEP_H_ */

View File

@ -24,9 +24,10 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H
#ifndef PYBSPI_H_
#define PYBSPI_H_
extern const mp_obj_type_t pyb_spi_type;
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H
#endif // PYBSPI_H_

View File

@ -24,8 +24,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H
/******************************************************************************
DECLARE EXPORTED DATA
@ -37,4 +35,3 @@ extern const mp_obj_type_t pyb_timer_type;
******************************************************************************/
void timer_init0 (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H

View File

@ -24,8 +24,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBUART_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBUART_H
#ifndef PYBUART_H_
#define PYBUART_H_
typedef enum {
PYB_UART_0 = 0,
@ -42,4 +43,4 @@ int uart_rx_char(pyb_uart_obj_t *uart_obj);
bool uart_tx_char(pyb_uart_obj_t *self, int c);
bool uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len);
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBUART_H
#endif // PYBUART_H_

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H
#define MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H
#ifndef PYBWDT_H_
#define PYBWDT_H_
#include "py/obj.h"
@ -35,4 +36,4 @@ void pybwdt_srv_alive (void);
void pybwdt_srv_sleeping (bool state);
void pybwdt_sl_alive (void);
#endif // MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H
#endif /* PYBWDT_H_ */

View File

@ -25,6 +25,9 @@
* THE SOFTWARE.
*/
#ifndef __INCLUDED_MPCONFIGPORT_H
#define __INCLUDED_MPCONFIGPORT_H
#include <stdint.h>
#ifndef BOOTLOADER
@ -77,7 +80,6 @@
#define MICROPY_VFS_FAT (1)
#define MICROPY_PY_ASYNC_AWAIT (0)
#define MICROPY_PY_ALL_SPECIAL_METHODS (1)
#define MICROPY_PY_BUILTINS_INPUT (1)
#define MICROPY_PY_BUILTINS_HELP (1)
#define MICROPY_PY_BUILTINS_HELP_TEXT cc3200_help_text
#ifndef DEBUG
@ -140,6 +142,7 @@
// extra built in names to add to the global namespace
#define MICROPY_PORT_BUILTINS \
{ MP_OBJ_NEW_QSTR(MP_QSTR_input), (mp_obj_t)&mp_builtin_input_obj }, \
{ MP_OBJ_NEW_QSTR(MP_QSTR_open), (mp_obj_t)&mp_builtin_open_obj }, \
// extra built in modules to add to the list of known ones
@ -232,3 +235,5 @@ typedef long mp_off_t;
#define MICROPY_PORT_WLAN_AP_KEY "www.wipy.io"
#define MICROPY_PORT_WLAN_AP_SECURITY SL_SEC_TYPE_WPA_WPA2
#define MICROPY_PORT_WLAN_AP_CHANNEL 5
#endif // __INCLUDED_MPCONFIGPORT_H

View File

@ -112,7 +112,7 @@ static const char fresh_boot_py[] = "# boot.py -- run on boot-up\r\n"
DECLARE PUBLIC FUNCTIONS
******************************************************************************/
void TASK_MicroPython (void *pvParameters) {
void TASK_Micropython (void *pvParameters) {
// get the top of the stack to initialize the garbage collector
uint32_t sp = gc_helper_get_sp();

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_MPTASK_H
#define MICROPY_INCLUDED_CC3200_MPTASK_H
#ifndef MPTASK_H_
#define MPTASK_H_
/******************************************************************************
DEFINE CONSTANTS
@ -41,6 +42,6 @@ extern StackType_t mpTaskStack[];
/******************************************************************************
DECLARE PUBLIC FUNCTIONS
******************************************************************************/
extern void TASK_MicroPython (void *pvParameters);
extern void TASK_Micropython (void *pvParameters);
#endif // MICROPY_INCLUDED_CC3200_MPTASK_H
#endif /* MPTASK_H_ */

View File

@ -23,6 +23,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __MICROPY_INCLUDED_CC3200_MPTHREADPORT_H__
#define __MICROPY_INCLUDED_CC3200_MPTHREADPORT_H__
#ifndef BOOTLOADER
#include "FreeRTOS.h"
@ -37,3 +39,5 @@ typedef struct _mp_thread_mutex_t {
void mp_thread_init(void);
void mp_thread_gc_others(void);
#endif // __MICROPY_INCLUDED_CC3200_MPTHREADPORT_H__

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_SERVERSTASK_H
#define MICROPY_INCLUDED_CC3200_SERVERSTASK_H
#ifndef SERVERSTASK_H_
#define SERVERSTASK_H_
/******************************************************************************
DEFINE CONSTANTS
@ -72,4 +73,4 @@ extern void server_sleep_sockets (void);
extern void servers_set_timeout (uint32_t timeout);
extern uint32_t servers_get_timeout (void);
#endif // MICROPY_INCLUDED_CC3200_SERVERSTASK_H
#endif /* SERVERSTASK_H_ */

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_TELNET_TELNET_H
#define MICROPY_INCLUDED_CC3200_TELNET_TELNET_H
#ifndef TELNET_H_
#define TELNET_H_
/******************************************************************************
DECLARE EXPORTED FUNCTIONS
@ -38,4 +39,4 @@ extern void telnet_enable (void);
extern void telnet_disable (void);
extern void telnet_reset (void);
#endif // MICROPY_INCLUDED_CC3200_TELNET_TELNET_H
#endif /* TELNET_H_ */

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_CRYPTOHASH_H
#define MICROPY_INCLUDED_CC3200_UTIL_CRYPTOHASH_H
#ifndef CRYPTOHASH_H_
#define CRYPTOHASH_H_
/******************************************************************************
DECLARE PUBLIC FUNCTIONS
@ -34,4 +35,4 @@ extern void CRYPTOHASH_SHAMD5Start (uint32_t algo, uint32_t blocklen);
extern void CRYPTOHASH_SHAMD5Update (uint8_t *data, uint32_t datalen);
extern void CRYPTOHASH_SHAMD5Read (uint8_t *hash);
#endif // MICROPY_INCLUDED_CC3200_UTIL_CRYPTOHASH_H
#endif /* CRYPTOHASH_H_ */

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_FIFO_H
#define MICROPY_INCLUDED_CC3200_UTIL_FIFO_H
#ifndef FIFO_H_
#define FIFO_H_
typedef struct {
void *pvElements;
@ -46,4 +47,4 @@ extern bool FIFO_IsEmpty (FIFO_t *fifo);
extern bool FIFO_IsFull (FIFO_t *fifo);
extern void FIFO_Flush (FIFO_t *fifo);
#endif // MICROPY_INCLUDED_CC3200_UTIL_FIFO_H
#endif /* FIFO_H_ */

View File

@ -24,8 +24,6 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_GCCOLLECT_H
#define MICROPY_INCLUDED_CC3200_UTIL_GCCOLLECT_H
// variables defining memory layout
extern uint32_t _etext;
@ -41,5 +39,3 @@ extern uint32_t _stack;
extern uint32_t _estack;
void gc_collect(void);
#endif // MICROPY_INCLUDED_CC3200_UTIL_GCCOLLECT_H

View File

@ -24,10 +24,11 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_GCHELPER_H
#define MICROPY_INCLUDED_CC3200_UTIL_GCHELPER_H
#ifndef GC_HELPER_H_
#define GC_HELPER_H_
extern mp_uint_t gc_helper_get_sp(void);
extern mp_uint_t gc_helper_get_regs_and_sp(mp_uint_t *regs);
#endif // MICROPY_INCLUDED_CC3200_UTIL_GCHELPER_H
#endif /* GC_HELPER_H_ */

View File

@ -23,12 +23,13 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_RANDOM_H
#define MICROPY_INCLUDED_CC3200_UTIL_RANDOM_H
#ifndef __RANDOM_H
#define __RANDOM_H
void rng_init0 (void);
uint32_t rng_get (void);
MP_DECLARE_CONST_FUN_OBJ_0(machine_rng_get_obj);
#endif // MICROPY_INCLUDED_CC3200_UTIL_RANDOM_H
#endif // __RANDOM_H

View File

@ -23,10 +23,11 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_SLEEPRESTORE_H
#define MICROPY_INCLUDED_CC3200_UTIL_SLEEPRESTORE_H
#ifndef SLEEPRESTORE_H_
#define SLEEPRESTORE_H_
extern void sleep_store(void);
extern void sleep_restore(void);
#endif // MICROPY_INCLUDED_CC3200_UTIL_SLEEPRESTORE_H
#endif /* SLEEPRESTORE_H_ */

View File

@ -23,8 +23,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_UTIL_SOCKETFIFO_H
#define MICROPY_INCLUDED_CC3200_UTIL_SOCKETFIFO_H
#ifndef SOCKETFIFO_H_
#define SOCKETFIFO_H_
/*----------------------------------------------------------------------------
** Imports
@ -59,4 +60,4 @@ extern bool SOCKETFIFO_IsFull (void);
extern void SOCKETFIFO_Flush (void);
extern unsigned int SOCKETFIFO_Count (void);
#endif // MICROPY_INCLUDED_CC3200_UTIL_SOCKETFIFO_H
#endif /* SOCKETFIFO_H_ */

View File

@ -23,9 +23,10 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_CC3200_VERSION_H
#define MICROPY_INCLUDED_CC3200_VERSION_H
#ifndef VERSION_H_
#define VERSION_H_
#define WIPY_SW_VERSION_NUMBER "1.2.0"
#endif // MICROPY_INCLUDED_CC3200_VERSION_H
#endif /* VERSION_H_ */

View File

@ -96,9 +96,10 @@ copyright = '2014-2017, Damien P. George, Paul Sokolovsky, and contributors'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags"
# breakdown, so use the same version identifier for both to avoid confusion.
version = release = '1.9.1'
# The short X.Y version.
version = '1.9'
# The full version, including alpha/beta/rc tags.
release = '1.9'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@ -112,11 +113,11 @@ version = release = '1.9.1'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['build', '.venv']
exclude_patterns = ['build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
default_role = 'any'
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
@ -138,12 +139,6 @@ pygments_style = 'sphinx'
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# Global include files. Sphinx docs suggest using rst_epilog in preference
# of rst_prolog, so we follow. Absolute paths below mean "from the base
# of the doctree".
rst_epilog = """
.. include:: /templates/replace.inc
"""
# -- Options for HTML output ----------------------------------------------
@ -251,8 +246,6 @@ latex_elements = {
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Include 3 levels of headers in PDF ToC
'preamble': '\setcounter{tocdepth}{2}',
}
# Grouping the document tree into LaTeX files. List of tuples
@ -322,7 +315,7 @@ texinfo_documents = [
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('http://docs.python.org/3', None)}
intersphinx_mapping = {'http://docs.python.org/': None}
# Append the other ports' specific folders/files to the exclude pattern
exclude_patterns.extend([port + '*' for port in ports if port != micropy_port])

View File

@ -1,6 +1,4 @@
.. _cpython_diffs:
MicroPython differences from CPython
MicroPython Differences from CPython
====================================
The operations listed in this section produce conflicting results in MicroPython when compared to standard Python.

View File

@ -116,32 +116,9 @@ Real-time clock
RTC in ESP8266 has very bad accuracy, drift may be seconds per minute. As
a workaround, to measure short enough intervals you can use
``utime.time()``, etc. functions, and for wall clock time, synchronize from
the net using included ``ntptime.py`` module.
the net using included ``ntpdate.py`` module.
Due to limitations of the ESP8266 chip the internal real-time clock (RTC)
will overflow every 7:45h. If a long-term working RTC time is required then
``time()`` or ``localtime()`` must be called at least once within 7 hours.
MicroPython will then handle the overflow.
Sockets and WiFi buffers overflow
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Socket instances remain active until they are explicitly closed. This has two
consequences. Firstly they occupy RAM, so an application which opens sockets
without closing them may eventually run out of memory. Secondly not properly
closed socket can cause the low-level part of the vendor WiFi stack to emit
``Lmac`` errors. This occurs if data comes in for a socket and is not
processed in a timely manner. This can overflow the WiFi stack input queue
and lead to a deadlock. The only recovery is by a hard reset.
The above may also happen after an application terminates and quits to the REPL
for any reason including an exception. Subsequent arrival of data provokes the
failure with the above error message repeatedly issued. So, sockets should be
closed in any case, regardless whether an application terminates successfully
or by an exeption, for example using try/finally::
sock = socket(...)
try:
# Use sock
finally:
sock.close()

View File

@ -107,9 +107,9 @@ Use the :ref:`machine.Pin <machine.Pin>` class::
from machine import Pin
p0 = Pin(0, Pin.OUT) # create output pin on GPIO0
p0.on() # set pin to "on" (high) level
p0.off() # set pin to "off" (low) level
p0.value(1) # set pin to on/high
p0.high() # set pin to high
p0.low() # set pin to low
p0.value(1) # set pin to high
p2 = Pin(2, Pin.IN) # create input pin on GPIO2
print(p2.value()) # get value, 0 or 1

View File

@ -50,16 +50,12 @@ From here, you have 3 main choices
* Daily firmware builds for 1024kb modules and above.
* Daily firmware builds for 512kb modules.
If you are just starting with MicroPython, the best bet is to go for the Stable
firmware builds. If you are an advanced, experienced MicroPython ESP8266 user
who would like to follow development closely and help with testing new
features, there are daily builds (note: you actually may need some
development experience, e.g. being ready to follow git history to know
what new changes and features were introduced).
Support for 512kb modules is provided on a feature preview basis. For end
users, it's recommended to use modules with flash of 1024kb or more. As
such, only daily builds for 512kb modules are provided.
The best bet is nearly always to go for the Stable firmware builds.
An exception to this though is if you have an ESP8266 module with only 512kb
of onboard storage. You can easily tell by trying to load a Stable firmware
build and if you get the error below, then you may have to use the Daily
firmware builds for 512kb modules.
WARNING: Unlikely to work as data goes beyond end of flash.
Deploying the firmware
----------------------
@ -165,9 +161,7 @@ after it, here are troubleshooting recommendations:
* If lower baud rate didn't help, you may want to try older version of
esptool.py, which had a different programming algorithm::
pip install esptool==1.0.1
This version doesn't support ``--flash_size=detect`` option, so you will
need to specify FlashROM size explicitly (in megabits). It also requires
Python 2.7, so you may need to use ``pip2`` instead of ``pip`` in the
@ -182,10 +176,8 @@ after it, here are troubleshooting recommendations:
* Additionally, you can check the firmware integrity from a MicroPython REPL
prompt (assuming you were able to flash it and ``--verify`` option doesn't
report errors)::
import esp
esp.check_fw()
If the last output value is True, the firmware is OK. Otherwise, it's
corrupted and need to be reflashed correctly.

View File

@ -35,8 +35,8 @@ Then set its value using::
Or::
>>> pin.off()
>>> pin.on()
>>> pin.low()
>>> pin.high()
External interrupts
-------------------

View File

@ -101,12 +101,11 @@ turn it on and off using the following code::
>>> import machine
>>> pin = machine.Pin(2, machine.Pin.OUT)
>>> pin.on()
>>> pin.off()
>>> pin.high()
>>> pin.low()
Note that ``on`` method of a Pin might turn the LED off and ``off`` might
turn it on (or vice versa), depending on how the LED is wired on your board.
To resolve this, machine.Signal class is provided.
Note that ``high`` might turn the LED off and ``low`` might turn it on (or vice
versa), depending on how the LED is wired on your board.
Line editing
~~~~~~~~~~~~

12
docs/esp8266_contents.rst Normal file
View File

@ -0,0 +1,12 @@
MicroPython documentation contents
==================================
.. toctree::
esp8266/quickref.rst
esp8266/general.rst
esp8266/tutorial/index.rst
library/index.rst
reference/index.rst
genrst/index.rst
license.rst

View File

@ -4,9 +4,14 @@ MicroPython documentation and references
.. toctree::
esp8266/quickref.rst
esp8266/general.rst
esp8266/tutorial/index.rst
library/index.rst
reference/index.rst
genrst/index.rst
license.rst
esp8266_contents.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -4,7 +4,8 @@
.. module:: array
:synopsis: efficient arrays of numeric data
|see_cpython_module| :mod:`python:array`.
See `Python array <https://docs.python.org/3/library/array.html>`_ for more
information.
Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``,
``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the

View File

@ -22,14 +22,8 @@ Example::
# First, we need to open a stream which holds a database
# This is usually a file, but can be in-memory database
# using uio.BytesIO, a raw flash partition, etc.
# Oftentimes, you want to create a database file if it doesn't
# exist and open if it exists. Idiom below takes care of this.
# DO NOT open database with "a+b" access mode.
try:
f = open("mydb", "r+b")
except OSError:
f = open("mydb", "w+b")
# using uio.BytesIO, a raw flash section, etc.
f = open("mydb", "w+b")
# Now open a database itself
db = btree.open(f)
@ -39,11 +33,6 @@ Example::
db[b"1"] = b"one"
db[b"2"] = b"two"
# Assume that any changes are cached in memory unless
# explicitly flushed (or database closed). Flush database
# at the end of each "transaction".
db.flush()
# Prints b'two'
print(db[b"2"])
@ -80,20 +69,20 @@ Functions
Open a database from a random-access `stream` (like an open file). All
other parameters are optional and keyword-only, and allow to tweak advanced
parameters of the database operation (most users will not need them):
paramters of the database operation (most users will not need them):
* *flags* - Currently unused.
* *cachesize* - Suggested maximum memory cache size in bytes. For a
* `flags` - Currently unused.
* `cachesize` - Suggested maximum memory cache size in bytes. For a
board with enough memory using larger values may improve performance.
The value is only a recommendation, the module may use more memory if
values set too low.
* *pagesize* - Page size used for the nodes in BTree. Acceptable range
* `pagesize` - Page size used for the nodes in BTree. Acceptable range
is 512-65536. If 0, underlying I/O block size will be used (the best
compromise between memory usage and performance).
* *minkeypage* - Minimum number of keys to store per page. Default value
* `minkeypage` - Minimum number of keys to store per page. Default value
of 0 equivalent to 2.
Returns a BTree object, which implements a dictionary protocol (set
Returns a `BTree` object, which implements a dictionary protocol (set
of methods), and some additional methods described below.
Methods
@ -103,7 +92,7 @@ Methods
Close the database. It's mandatory to close the database at the end of
processing, as some unwritten data may be still in the cache. Note that
this does not close underlying stream with which the database was opened,
this does not close underlying streamw with which the database was opened,
it should be closed separately (which is also mandatory to make sure that
data flushed from buffer to the underlying storage).
@ -112,10 +101,10 @@ Methods
Flush any data in cache to the underlying stream.
.. method:: btree.__getitem__(key)
btree.get(key, default=None)
btree.__setitem__(key, val)
btree.__detitem__(key)
btree.__contains__(key)
.. method:: btree.get(key, default=None)
.. method:: btree.__setitem__(key, val)
.. method:: btree.__detitem__(key)
.. method:: btree.__contains__(key)
Standard dictionary methods.
@ -125,20 +114,20 @@ Methods
to get access to all keys in order.
.. method:: btree.keys([start_key, [end_key, [flags]]])
btree.values([start_key, [end_key, [flags]]])
btree.items([start_key, [end_key, [flags]]])
.. method:: btree.values([start_key, [end_key, [flags]]])
.. method:: btree.items([start_key, [end_key, [flags]]])
These methods are similar to standard dictionary methods, but also can
take optional parameters to iterate over a key sub-range, instead of
the entire database. Note that for all 3 methods, *start_key* and
*end_key* arguments represent key values. For example, `values()`
the entire database. Note that for all 3 methods, `start_key` and
`end_key` arguments represent key values. For example, ``values()``
method will iterate over values corresponding to they key range
given. None values for *start_key* means "from the first key", no
*end_key* or its value of None means "until the end of database".
By default, range is inclusive of *start_key* and exclusive of
*end_key*, you can include *end_key* in iteration by passing *flags*
given. None values for `start_key` means "from the first key", no
`end_key` or its value of None means "until the end of database".
By default, range is inclusive of `start_key` and exclusive of
`end_key`, you can include `end_key` in iteration by passing `flags`
of `btree.INCL`. You can iterate in descending key direction
by passing *flags* of `btree.DESC`. The flags values can be ORed
by passing `flags` of `btree.DESC`. The flags values can be ORed
together.
Constants

View File

@ -1,11 +1,8 @@
Builtin functions and exceptions
================================
Builtin Functions
=================
All builtin functions and exceptions are described here. They are also
available via ``builtins`` module.
Functions and types
-------------------
All builtin functions are described here. They are also available via
``builtins`` module.
.. function:: abs()
@ -21,8 +18,6 @@ Functions and types
.. class:: bytes()
|see_cpython| `python:bytes`.
.. function:: callable()
.. function:: chr()
@ -149,51 +144,3 @@ Functions and types
.. function:: type()
.. function:: zip()
Exceptions
----------
.. exception:: AssertionError
.. exception:: AttributeError
.. exception:: Exception
.. exception:: ImportError
.. exception:: IndexError
.. exception:: KeyboardInterrupt
.. exception:: KeyError
.. exception:: MemoryError
.. exception:: NameError
.. exception:: NotImplementedError
.. exception:: OSError
|see_cpython| `python:OSError`. MicroPython doesn't implement ``errno``
attribute, instead use the standard way to access exception arguments:
``exc.args[0]``.
.. exception:: RuntimeError
.. exception:: StopIteration
.. exception:: SyntaxError
.. exception:: SystemExit
|see_cpython| `python:SystemExit`.
.. exception:: TypeError
|see_cpython| `python:TypeError`.
.. exception:: ValueError
.. exception:: ZeroDivisionError

View File

@ -4,8 +4,6 @@
.. module:: cmath
:synopsis: mathematical functions for complex numbers
|see_cpython_module| :mod:`python:cmath`.
The ``cmath`` module provides some basic mathematical functions for
working with complex numbers.

View File

@ -14,7 +14,7 @@ Functions
Get or set the sleep type.
If the *sleep_type* parameter is provided, sets the sleep type to its
If the ``sleep_type`` parameter is provided, sets the sleep type to its
value. If the function is called without parameters, returns the current
sleep type.
@ -55,23 +55,23 @@ Functions
1MByte of flash (which is memory mapped), and this function controls the
location.
If *start* and *length* are both ``None`` then the native code location is
If `start` and `length` are both `None` then the native code location is
set to the unused portion of memory at the end of the iRAM1 region. The
size of this unused portion depends on the firmware and is typically quite
small (around 500 bytes), and is enough to store a few very small
functions. The advantage of using this iRAM1 region is that it does not
get worn out by writing to it.
If neither *start* nor *length* are ``None`` then they should be integers.
*start* should specify the byte offset from the beginning of the flash at
which native code should be stored. *length* specifies how many bytes of
flash from *start* can be used to store native code. *start* and *length*
If neither `start` nor `length` are `None` then they should be integers.
`start` should specify the byte offset from the beginning of the flash at
which native code should be stored. `length` specifies how many bytes of
flash from `start` can be used to store native code. `start` and `length`
should be multiples of the sector size (being 4096 bytes). The flash will
be automatically erased before writing to it so be sure to use a region of
flash that is not otherwise used, for example by the firmware or the
filesystem.
When using the flash to store native code *start+length* must be less
When using the flash to store native code `start+length` must be less
than or equal to 1MByte. Note that the flash can be worn out if repeated
erasures (and writes) are made so use this feature sparingly.
In particular, native code needs to be recompiled and rewritten to flash

View File

@ -32,25 +32,25 @@ Constructors
Construct a FrameBuffer object. The parameters are:
- *buffer* is an object with a buffer protocol which must be large
- `buffer` is an object with a buffer protocol which must be large
enough to contain every pixel defined by the width, height and
format of the FrameBuffer.
- *width* is the width of the FrameBuffer in pixels
- *height* is the height of the FrameBuffer in pixels
- *format* specifies the type of pixel used in the FrameBuffer;
- `width` is the width of the FrameBuffer in pixels
- `height` is the height of the FrameBuffer in pixels
- `format` specifies the type of pixel used in the FrameBuffer;
valid values are ``framebuf.MVLSB``, ``framebuf.RGB565``
and ``framebuf.GS4_HMSB``. MVLSB is monochrome 1-bit color,
RGB565 is RGB 16-bit color, and GS4_HMSB is grayscale 4-bit color.
Where a color value c is passed to a method, c is a small integer
with an encoding that is dependent on the format of the FrameBuffer.
- *stride* is the number of pixels between each horizontal line
of pixels in the FrameBuffer. This defaults to *width* but may
- `stride` is the number of pixels between each horizontal line
of pixels in the FrameBuffer. This defaults to `width` but may
need adjustments when implementing a FrameBuffer within another
larger FrameBuffer or screen. The *buffer* size must accommodate
larger FrameBuffer or screen. The `buffer` size must accommodate
an increased step size.
One must specify valid *buffer*, *width*, *height*, *format* and
optionally *stride*. Invalid *buffer* size or dimensions may lead to
One must specify valid `buffer`, `width`, `height`, `format` and
optionally `stride`. Invalid `buffer` size or dimensions may lead to
unexpected errors.
Drawing primitive shapes
@ -64,8 +64,8 @@ The following methods draw shapes onto the FrameBuffer.
.. method:: FrameBuffer.pixel(x, y[, c])
If *c* is not given, get the color value of the specified pixel.
If *c* is given, set the specified pixel to the given color.
If `c` is not given, get the color value of the specified pixel.
If `c` is given, set the specified pixel to the given color.
.. method:: FrameBuffer.hline(x, y, w, c)
.. method:: FrameBuffer.vline(x, y, h, c)
@ -106,7 +106,7 @@ Other methods
.. method:: FrameBuffer.blit(fbuf, x, y[, key])
Draw another FrameBuffer on top of the current one at the given coordinates.
If *key* is specified then it should be a color integer and the
If `key` is specified then it should be a color integer and the
corresponding color will be considered transparent: all pixels with that
color value will not be drawn.

View File

@ -4,8 +4,6 @@
.. module:: gc
:synopsis: control the garbage collector
|see_cpython_module| :mod:`python:gc`.
Functions
---------
@ -26,41 +24,6 @@ Functions
Return the number of bytes of heap RAM that are allocated.
.. admonition:: Difference to CPython
:class: attention
This function is MicroPython extension.
.. function:: mem_free()
Return the number of bytes of available heap RAM, or -1 if this amount
is not known.
.. admonition:: Difference to CPython
:class: attention
This function is MicroPython extension.
.. function:: threshold([amount])
Set or query the additional GC allocation threshold. Normally, a collection
is triggered only when a new allocation cannot be satisfied, i.e. on an
out-of-memory (OOM) condition. If this function is called, in addition to
OOM, a collection will be triggered each time after *amount* bytes have been
allocated (in total, since the previous time such an amount of bytes
have been allocated). *amount* is usually specified as less than the
full heap size, with the intention to trigger a collection earlier than when the
heap becomes exhausted, and in the hope that an early collection will prevent
excessive memory fragmentation. This is a heuristic measure, the effect
of which will vary from application to application, as well as
the optimal value of the *amount* parameter.
Calling the function without argument will return the current value of
the threshold. A value of -1 means a disabled allocation threshold.
.. admonition:: Difference to CPython
:class: attention
This function is a MicroPython extension. CPython has a similar
function - ``set_threshold()``, but due to different GC
implementations, its signature and semantics are different.
Return the number of bytes of available heap RAM.

View File

@ -1,5 +1,3 @@
.. _micropython_lib:
MicroPython libraries
=====================
@ -74,17 +72,16 @@ it will fallback to loading the built-in ``ujson`` module.
cmath.rst
gc.rst
math.rst
select.rst
sys.rst
ubinascii.rst
ucollections.rst
uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
uselect.rst
usocket.rst
ustruct.rst
utime.rst
@ -100,17 +97,16 @@ it will fallback to loading the built-in ``ujson`` module.
cmath.rst
gc.rst
math.rst
select.rst
sys.rst
ubinascii.rst
ucollections.rst
uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
uselect.rst
usocket.rst
ustruct.rst
utime.rst
@ -124,12 +120,12 @@ it will fallback to loading the built-in ``ujson`` module.
builtins.rst
array.rst
gc.rst
select.rst
sys.rst
ubinascii.rst
ujson.rst
uos.rst
ure.rst
uselect.rst
usocket.rst
ussl.rst
utime.rst
@ -146,14 +142,12 @@ it will fallback to loading the built-in ``ujson`` module.
sys.rst
ubinascii.rst
ucollections.rst
uerrno.rst
uhashlib.rst
uheapq.rst
uio.rst
ujson.rst
uos.rst
ure.rst
uselect.rst
usocket.rst
ussl.rst
ustruct.rst

View File

@ -41,21 +41,21 @@ Constructors
Construct an LCD160CR object. The parameters are:
- *connect* is a string specifying the physical connection of the LCD
- `connect` is a string specifying the physical connection of the LCD
display to the board; valid values are "X", "Y", "XY", "YX".
Use "X" when the display is connected to a pyboard in the X-skin
position, and "Y" when connected in the Y-skin position. "XY"
and "YX" are used when the display is connected to the right or
left side of the pyboard, respectively.
- *pwr* is a Pin object connected to the LCD's power/enabled pin.
- *i2c* is an I2C object connected to the LCD's I2C interface.
- *spi* is an SPI object connected to the LCD's SPI interface.
- *i2c_addr* is the I2C address of the display.
- `pwr` is a Pin object connected to the LCD's power/enabled pin.
- `i2c` is an I2C object connected to the LCD's I2C interface.
- `spi` is an SPI object connected to the LCD's SPI interface.
- `i2c_addr` is the I2C address of the display.
One must specify either a valid *connect* or all of *pwr*, *i2c* and *spi*.
If a valid *connect* is given then any of *pwr*, *i2c* or *spi* which are
not passed as parameters (i.e. they are ``None``) will be created based on the
value of *connect*. This allows to override the default interface to the
One must specify either a valid `connect` or all of `pwr`, `i2c` and `spi`.
If a valid `connect` is given then any of `pwr`, `i2c` or `spi` which are
not passed as parameters (ie they are `None`) will be created based on the
value of `connect`. This allows to override the default interface to the
display if needed.
The default values are:
@ -103,12 +103,12 @@ Setup commands
.. method:: LCD160CR.set_power(on)
Turn the display on or off, depending on the given value of *on*: 0 or ``False``
will turn the display off, and 1 or ``True`` will turn it on.
Turn the display on or off, depending on the given value of `on`: 0 or `False`
will turn the display off, and 1 or `True` will turn it on.
.. method:: LCD160CR.set_orient(orient)
Set the orientation of the display. The *orient* parameter can be one
Set the orientation of the display. The `orient` parameter can be one
of `PORTRAIT`, `LANDSCAPE`, `PORTRAIT_UPSIDEDOWN`, `LANDSCAPE_UPSIDEDOWN`.
.. method:: LCD160CR.set_brightness(value)
@ -117,7 +117,7 @@ Setup commands
.. method:: LCD160CR.set_i2c_addr(addr)
Set the I2C address of the display. The *addr* value must have the
Set the I2C address of the display. The `addr` value must have the
lower 2 bits cleared.
.. method:: LCD160CR.set_uart_baudrate(baudrate)
@ -126,7 +126,7 @@ Setup commands
.. method:: LCD160CR.set_startup_deco(value)
Set the start-up decoration of the display. The *value* parameter can be a
Set the start-up decoration of the display. The `value` parameter can be a
logical or of `STARTUP_DECO_NONE`, `STARTUP_DECO_MLOGO`, `STARTUP_DECO_INFO`.
.. method:: LCD160CR.save_to_flash()
@ -151,17 +151,17 @@ The following methods manipulate individual pixels on the display.
.. method:: LCD160CR.get_line(x, y, buf)
Low-level method to get a line of pixels into the given buffer.
To read *n* pixels *buf* should be *2*n+1* bytes in length. The first byte
To read `n` pixels `buf` should be `2*n+1` bytes in length. The first byte
is a dummy byte and should be ignored, and subsequent bytes represent the
pixels in the line starting at coordinate *(x, y)*.
pixels in the line starting at coordinate `(x, y)`.
.. method:: LCD160CR.screen_dump(buf, x=0, y=0, w=None, h=None)
Dump the contents of the screen to the given buffer. The parameters *x* and *y*
specify the starting coordinate, and *w* and *h* the size of the region. If *w*
or *h* are ``None`` then they will take on their maximum values, set by the size
of the screen minus the given *x* and *y* values. *buf* should be large enough
to hold ``2*w*h`` bytes. If it's smaller then only the initial horizontal lines
Dump the contents of the screen to the given buffer. The parameters `x` and `y`
specify the starting coordinate, and `w` and `h` the size of the region. If `w`
or `h` are `None` then they will take on their maximum values, set by the size
of the screen minus the given `x` and `y` values. `buf` should be large enough
to hold `2*w*h` bytes. If it's smaller then only the initial horizontal lines
will be stored.
.. method:: LCD160CR.screen_load(buf)
@ -188,18 +188,18 @@ To draw text one sets the position, color and font, and then uses
Set the font for the text. Subsequent calls to `write` will use the newly
configured font. The parameters are:
- *font* is the font family to use, valid values are 0, 1, 2, 3.
- *scale* is a scaling value for each character pixel, where the pixels
are drawn as a square with side length equal to *scale + 1*. The value
- `font` is the font family to use, valid values are 0, 1, 2, 3.
- `scale` is a scaling value for each character pixel, where the pixels
are drawn as a square with side length equal to `scale + 1`. The value
can be between 0 and 63.
- *bold* controls the number of pixels to overdraw each character pixel,
making a bold effect. The lower 2 bits of *bold* are the number of
- `bold` controls the number of pixels to overdraw each character pixel,
making a bold effect. The lower 2 bits of `bold` are the number of
pixels to overdraw in the horizontal direction, and the next 2 bits are
for the vertical direction. For example, a *bold* value of 5 will
for the vertical direction. For example, a `bold` value of 5 will
overdraw 1 pixel in both the horizontal and vertical directions.
- *trans* can be either 0 or 1 and if set to 1 the characters will be
- `trans` can be either 0 or 1 and if set to 1 the characters will be
drawn with a transparent background.
- *scroll* can be either 0 or 1 and if set to 1 the display will do a
- `scroll` can be either 0 or 1 and if set to 1 the display will do a
soft scroll if the text moves to the next line.
.. method:: LCD160CR.write(s)
@ -252,7 +252,7 @@ Primitive drawing commands use a foreground and background color set by the
.. method:: LCD160CR.poly_dot(data)
Draw a sequence of dots using the pen line color.
The *data* should be a buffer of bytes, with each successive pair of
The `data` should be a buffer of bytes, with each successive pair of
bytes corresponding to coordinate pairs (x, y).
.. method:: LCD160CR.poly_line(data)
@ -266,25 +266,25 @@ Touch screen methods
Configure the touch panel:
- If *calib* is ``True`` then the call will trigger a touch calibration of
- If `calib` is `True` then the call will trigger a touch calibration of
the resistive touch sensor. This requires the user to touch various
parts of the screen.
- If *save* is ``True`` then the touch parameters will be saved to NVRAM
- If `save` is `True` then the touch parameters will be saved to NVRAM
to persist across reset/power up.
- If *irq* is ``True`` then the display will be configured to pull the IRQ
line low when a touch force is detected. If *irq* is ``False`` then this
feature is disabled. If *irq* is ``None`` (the default value) then no
- If `irq` is `True` then the display will be configured to pull the IRQ
line low when a touch force is detected. If `irq` is `False` then this
feature is disabled. If `irq` is `None` (the default value) then no
change is made to this setting.
.. method:: LCD160CR.is_touched()
Returns a boolean: ``True`` if there is currently a touch force on the screen,
Returns a boolean: `True` if there is currently a touch force on the screen,
`False` otherwise.
.. method:: LCD160CR.get_touch()
Returns a 3-tuple of: *(active, x, y)*. If there is currently a touch force
on the screen then *active* is 1, otherwise it is 0. The *x* and *y* values
Returns a 3-tuple of: (active, x, y). If there is currently a touch force
on the screen then `active` is 1, otherwise it is 0. The `x` and `y` values
indicate the position of the current or most recent touch.
Advanced commands
@ -308,7 +308,7 @@ Advanced commands
.. method:: LCD160CR.show_framebuf(buf)
Show the given buffer on the display. *buf* should be an array of bytes containing
Show the given buffer on the display. `buf` should be an array of bytes containing
the 16-bit RGB values for the pixels, and they will be written to the area
specified by :meth:`LCD160CR.set_spi_win`, starting from the top-left corner.
@ -325,35 +325,35 @@ Advanced commands
Configure a window region for scrolling:
- *win* is the window id to configure. There are 0..7 standard windows for
- `win` is the window id to configure. There are 0..7 standard windows for
general purpose use. Window 8 is the text scroll window (the ticker).
- *x*, *y*, *w*, *h* specify the location of the window in the display.
- *vec* specifies the direction and speed of scroll: it is a 16-bit value
of the form ``0bF.ddSSSSSSSSSSSS``. *dd* is 0, 1, 2, 3 for +x, +y, -x,
-y scrolling. *F* sets the speed format, with 0 meaning that the window
is shifted *S % 256* pixel every frame, and 1 meaning that the window
is shifted 1 pixel every *S* frames.
- *pat* is a 16-bit pattern mask for the background.
- *fill* is the fill color.
- *color* is the extra color, either of the text or pattern foreground.
- `x`, `y`, `w`, `h` specify the location of the window in the display.
- `vec` specifies the direction and speed of scroll: it is a 16-bit value
of the form ``0bF.ddSSSSSSSSSSSS``. `dd` is 0, 1, 2, 3 for +x, +y, -x,
-y scrolling. `F` sets the speed format, with 0 meaning that the window
is shifted `S % 256` pixel every frame, and 1 meaning that the window
is shifted 1 pixel every `S` frames.
- `pat` is a 16-bit pattern mask for the background.
- `fill` is the fill color.
- `color` is the extra color, either of the text or pattern foreground.
.. method:: LCD160CR.set_scroll_win_param(win, param, value)
Set a single parameter of a scrolling window region:
- *win* is the window id, 0..8.
- *param* is the parameter number to configure, 0..7, and corresponds
- `win` is the window id, 0..8.
- `param` is the parameter number to configure, 0..7, and corresponds
to the parameters in the `set_scroll_win` method.
- *value* is the value to set.
- `value` is the value to set.
.. method:: LCD160CR.set_scroll_buf(s)
Set the string for scrolling in window 8. The parameter *s* must be a string
Set the string for scrolling in window 8. The parameter `s` must be a string
with length 32 or less.
.. method:: LCD160CR.jpeg(buf)
Display a JPEG. *buf* should contain the entire JPEG data. JPEG data should
Display a JPEG. `buf` should contain the entire JPEG data. JPEG data should
not include EXIF information. The following encodings are supported: Baseline
DCT, Huffman coding, 8 bits per sample, 3 color components, YCbCr4:2:2.
The origin of the JPEG is set by :meth:`LCD160CR.set_pos`.
@ -380,15 +380,15 @@ Constants
---------
.. data:: lcd160cr.PORTRAIT
lcd160cr.LANDSCAPE
lcd160cr.PORTRAIT_UPSIDEDOWN
lcd160cr.LANDSCAPE_UPSIDEDOWN
.. data:: lcd160cr.LANDSCAPE
.. data:: lcd160cr.PORTRAIT_UPSIDEDOWN
.. data:: lcd160cr.LANDSCAPE_UPSIDEDOWN
Orientations of the display, used by :meth:`LCD160CR.set_orient`.
orientation of the display, used by :meth:`LCD160CR.set_orient`
.. data:: lcd160cr.STARTUP_DECO_NONE
lcd160cr.STARTUP_DECO_MLOGO
lcd160cr.STARTUP_DECO_INFO
.. data:: lcd160cr.STARTUP_DECO_MLOGO
.. data:: lcd160cr.STARTUP_DECO_INFO
Types of start-up decoration, can be OR'ed together, used by
:meth:`LCD160CR.set_startup_deco`.
type of start-up decoration, can be or'd together, used by
:meth:`LCD160CR.set_startup_deco`

View File

@ -37,16 +37,16 @@ Constructors
Construct and return a new I2C object using the following parameters:
- *id* identifies a particular I2C peripheral. The default
- `id` identifies the particular I2C peripheral. The default
value of -1 selects a software implementation of I2C which can
work (in most cases) with arbitrary pins for SCL and SDA.
If *id* is -1 then *scl* and *sda* must be specified. Other
allowed values for *id* depend on the particular port/board,
and specifying *scl* and *sda* may or may not be required or
If `id` is -1 then `scl` and `sda` must be specified. Other
allowed values for `id` depend on the particular port/board,
and specifying `scl` and `sda` may or may not be required or
allowed in this case.
- *scl* should be a pin object specifying the pin to use for SCL.
- *sda* should be a pin object specifying the pin to use for SDA.
- *freq* should be an integer which sets the maximum frequency
- `scl` should be a pin object specifying the pin to use for SCL.
- `sda` should be a pin object specifying the pin to use for SDA.
- `freq` should be an integer which sets the maximum frequency
for SCL.
General Methods
@ -56,9 +56,9 @@ General Methods
Initialise the I2C bus with the given arguments:
- *scl* is a pin object for the SCL line
- *sda* is a pin object for the SDA line
- *freq* is the SCL clock rate
- `scl` is a pin object for the SCL line
- `sda` is a pin object for the SDA line
- `freq` is the SCL clock rate
.. method:: I2C.deinit()
@ -93,9 +93,9 @@ control over the bus, otherwise the standard methods (see below) can be used.
.. method:: I2C.readinto(buf, nack=True)
Reads bytes from the bus and stores them into *buf*. The number of bytes
read is the length of *buf*. An ACK will be sent on the bus after
receiving all but the last byte. After the last byte is received, if *nack*
Reads bytes from the bus and stores them into `buf`. The number of bytes
read is the length of `buf`. An ACK will be sent on the bus after
receiving all but the last byte. After the last byte is received, if `nack`
is true then a NACK will be sent, otherwise an ACK will be sent (and in this
case the slave assumes more bytes are going to be read in a later call).
@ -103,7 +103,7 @@ control over the bus, otherwise the standard methods (see below) can be used.
.. method:: I2C.write(buf)
Write the bytes from *buf* to the bus. Checks that an ACK is received
Write the bytes from `buf` to the bus. Checks that an ACK is received
after each byte and stops transmitting the remaining bytes if a NACK is
received. The function returns the number of ACKs that were received.
@ -117,23 +117,23 @@ operations that target a given slave device.
.. method:: I2C.readfrom(addr, nbytes, stop=True)
Read *nbytes* from the slave specified by *addr*.
If *stop* is true then a STOP condition is generated at the end of the transfer.
Read `nbytes` from the slave specified by `addr`.
If `stop` is true then a STOP condition is generated at the end of the transfer.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_into(addr, buf, stop=True)
Read into *buf* from the slave specified by *addr*.
The number of bytes read will be the length of *buf*.
If *stop* is true then a STOP condition is generated at the end of the transfer.
Read into `buf` from the slave specified by `addr`.
The number of bytes read will be the length of `buf`.
If `stop` is true then a STOP condition is generated at the end of the transfer.
The method returns ``None``.
The method returns `None`.
.. method:: I2C.writeto(addr, buf, stop=True)
Write the bytes from *buf* to the slave specified by *addr*. If a
NACK is received following the write of a byte from *buf* then the
remaining bytes are not sent. If *stop* is true then a STOP condition is
Write the bytes from `buf` to the slave specified by `addr`. If a
NACK is received following the write of a byte from `buf` then the
remaining bytes are not sent. If `stop` is true then a STOP condition is
generated at the end of the transfer, even if a NACK is received.
The function returns the number of ACKs that were received.
@ -147,26 +147,26 @@ methods are convenience functions to communicate with such devices.
.. method:: I2C.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8)
Read *nbytes* from the slave specified by *addr* starting from the memory
address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits.
Read `nbytes` from the slave specified by `addr` starting from the memory
address specified by `memaddr`.
The argument `addrsize` specifies the address size in bits.
Returns a `bytes` object with the data read.
.. method:: I2C.readfrom_mem_into(addr, memaddr, buf, \*, addrsize=8)
Read into *buf* from the slave specified by *addr* starting from the
memory address specified by *memaddr*. The number of bytes read is the
length of *buf*.
The argument *addrsize* specifies the address size in bits (on ESP8266
Read into `buf` from the slave specified by `addr` starting from the
memory address specified by `memaddr`. The number of bytes read is the
length of `buf`.
The argument `addrsize` specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
The method returns ``None``.
The method returns `None`.
.. method:: I2C.writeto_mem(addr, memaddr, buf, \*, addrsize=8)
Write *buf* to the slave specified by *addr* starting from the
memory address specified by *memaddr*.
The argument *addrsize* specifies the address size in bits (on ESP8266
Write `buf` to the slave specified by `addr` starting from the
memory address specified by `memaddr`.
The argument `addrsize` specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
The method returns ``None``.
The method returns `None`.

View File

@ -146,20 +146,18 @@ Methods
When setting the value this method returns ``None``.
.. method:: Pin.out_value()
Return the value stored in the output buffer of a pin, regardless of its mode.
Not all ports implement this method.
.. method:: Pin.__call__([x])
Pin objects are callable. The call method provides a (fast) shortcut to set
and get the value of the pin. It is equivalent to Pin.value([x]).
See :meth:`Pin.value` for more details.
.. method:: Pin.on()
Set pin to "1" output level.
.. method:: Pin.off()
Set pin to "0" output level.
.. method:: Pin.mode([mode])
Get or set the pin mode.

View File

@ -34,7 +34,7 @@ Methods
.. method:: SD.init(id=0, pins=('GP10', 'GP11', 'GP15'))
Enable the SD card. In order to initialize the card, give it a 3-tuple:
Enable the SD card. In order to initalize the card, give it a 3-tuple:
``(clk_pin, cmd_pin, dat0_pin)``.
.. method:: SD.deinit()

View File

@ -16,9 +16,9 @@ UART objects can be created and initialised using::
uart = UART(1, 9600) # init with given baudrate
uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters
Supported parameters differ on a board:
Supported paramters differ on a board:
Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With *parity=None*,
Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With `parity=None`,
only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits
are supported.

View File

@ -13,7 +13,7 @@ damage.
.. _machine_callbacks:
A note of callbacks used by functions and class methods of :mod:`machine` module:
A note of callbacks used by functions and class methods of ``machine`` module:
all these callbacks should be considered as executing in an interrupt context.
This is true for both physical devices with IDs >= 0 and "virtual" devices
with negative IDs like -1 (these "virtual" devices are still thin shims on
@ -38,14 +38,14 @@ Interrupt related functions
Disable interrupt requests.
Returns the previous IRQ state which should be considered an opaque value.
This return value should be passed to the `enable_irq()` function to restore
interrupts to their original state, before `disable_irq()` was called.
This return value should be passed to the ``enable_irq`` function to restore
interrupts to their original state, before ``disable_irq`` was called.
.. function:: enable_irq(state)
Re-enable interrupt requests.
The *state* parameter should be the value that was returned from the most
recent call to the `disable_irq()` function.
The ``state`` parameter should be the value that was returned from the most
recent call to the ``disable_irq`` function.
Power related functions
-----------------------
@ -71,8 +71,8 @@ Power related functions
Stops the CPU and all peripherals (including networking interfaces, if any). Execution
is resumed from the main script, just as with a reset. The reset cause can be checked
to know that we are coming from `machine.DEEPSLEEP`. For wake up to actually happen,
wake sources should be configured first, like `Pin` change or `RTC` timeout.
to know that we are coming from ``machine.DEEPSLEEP``. For wake up to actually happen,
wake sources should be configured first, like ``Pin`` change or ``RTC`` timeout.
.. only:: port_wipy
@ -98,18 +98,18 @@ Miscellaneous functions
.. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000)
Time a pulse on the given *pin*, and return the duration of the pulse in
microseconds. The *pulse_level* argument should be 0 to time a low pulse
Time a pulse on the given `pin`, and return the duration of the pulse in
microseconds. The `pulse_level` argument should be 0 to time a low pulse
or 1 to time a high pulse.
If the current input value of the pin is different to *pulse_level*,
the function first (*) waits until the pin input becomes equal to *pulse_level*,
then (**) times the duration that the pin is equal to *pulse_level*.
If the pin is already equal to *pulse_level* then timing starts straight away.
If the current input value of the pin is different to `pulse_level`,
the function first (*) waits until the pin input becomes equal to `pulse_level`,
then (**) times the duration that the pin is equal to `pulse_level`.
If the pin is already equal to `pulse_level` then timing starts straight away.
The function will return -2 if there was timeout waiting for condition marked
(*) above, and -1 if there was timeout during the main measurement, marked (**)
above. The timeout is the same for both cases and given by *timeout_us* (which
above. The timeout is the same for both cases and given by `timeout_us` (which
is in microseconds).
.. _machine_constants:
@ -145,13 +145,13 @@ Classes
.. toctree::
:maxdepth: 1
machine.I2C.rst
machine.Pin.rst
machine.Signal.rst
machine.UART.rst
machine.SPI.rst
machine.I2C.rst
machine.RTC.rst
machine.SPI.rst
machine.Timer.rst
machine.UART.rst
machine.WDT.rst
.. only:: port_wipy
@ -159,12 +159,12 @@ Classes
.. toctree::
:maxdepth: 1
machine.Pin.rst
machine.UART.rst
machine.SPI.rst
machine.I2C.rst
machine.RTC.rst
machine.Timer.rst
machine.WDT.rst
machine.ADC.rst
machine.I2C.rst
machine.Pin.rst
machine.RTC.rst
machine.SD.rst
machine.SPI.rst
machine.Timer.rst
machine.UART.rst
machine.WDT.rst

View File

@ -4,8 +4,6 @@
.. module:: math
:synopsis: mathematical functions
|see_cpython_module| :mod:`python:math`.
The ``math`` module provides some basic mathematical functions for
working with floating-point numbers.

View File

@ -23,30 +23,30 @@ Functions
variable, and does not take up any memory during execution.
This `const` function is recognised directly by the MicroPython parser and is
provided as part of the :mod:`micropython` module mainly so that scripts can be
provided as part of the `micropython` module mainly so that scripts can be
written which run under both CPython and MicroPython, by following the above
pattern.
.. function:: opt_level([level])
If *level* is given then this function sets the optimisation level for subsequent
compilation of scripts, and returns ``None``. Otherwise it returns the current
If `level` is given then this function sets the optimisation level for subsequent
compilation of scripts, and returns `None`. Otherwise it returns the current
optimisation level.
.. function:: alloc_emergency_exception_buf(size)
Allocate *size* bytes of RAM for the emergency exception buffer (a good
Allocate ``size`` bytes of RAM for the emergency exception buffer (a good
size is around 100 bytes). The buffer is used to create exceptions in cases
when normal RAM allocation would fail (eg within an interrupt handler) and
therefore give useful traceback information in these situations.
A good way to use this function is to put it at the start of your main script
(eg ``boot.py`` or ``main.py``) and then the emergency exception buffer will be active
(eg boot.py or main.py) and then the emergency exception buffer will be active
for all the code following it.
.. function:: mem_info([verbose])
Print information about currently used memory. If the *verbose`* argument
Print information about currently used memory. If the ``verbose`` argument
is given then extra information is printed.
The information that is printed is implementation dependent, but currently
@ -55,7 +55,7 @@ Functions
.. function:: qstr_info([verbose])
Print information about currently interned strings. If the *verbose*
Print information about currently interned strings. If the ``verbose``
argument is given then extra information is printed.
The information that is printed is implementation dependent, but currently
@ -89,10 +89,10 @@ Functions
incoming stream of characters that is usually used for the REPL, in case
that stream is used for other purposes.
.. function:: schedule(func, arg)
.. function:: schedule(fun, arg)
Schedule the function *func* to be executed "very soon". The function
is passed the value *arg* as its single argument. "Very soon" means that
Schedule the function `fun` to be executed "very soon". The function
is passed the value `arg` as its single argument. "very soon" means that
the MicroPython runtime will do its best to execute the function at the
earliest possible time, given that it is also trying to be efficient, and
that the following conditions hold:

View File

@ -14,20 +14,14 @@ module.
For example::
# connect/ show IP config a specific network interface
# configure a specific network interface
# see below for examples of specific drivers
import network
import utime
nic = network.Driver(...)
if not nic.isconnected():
nic.connect()
print("Waiting for connection...")
while not nic.isconnected():
utime.sleep(1)
print(nic.ifconfig())
# now use usocket as usual
import usocket as socket
# now use socket as usual
import socket
addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
s = socket.socket()
s.connect(addr)
@ -35,102 +29,51 @@ For example::
data = s.recv(1000)
s.close()
Common network adapter interface
================================
.. only:: port_wipy
This section describes an (implied) abstract base class for all network
interface classes implemented by different ports of MicroPython for
different hardware. This means that MicroPython does not actually
provide `AbstractNIC` class, but any actual NIC class, as described
in the following sections, implements methods as described here.
.. _network.Server:
.. class:: AbstractNIC(id=None, ...)
class Server
============
Instantiate a network interface object. Parameters are network interface
dependent. If there are more than one interface of the same type, the first
parameter should be `id`.
The ``Server`` class controls the behaviour and the configuration of the FTP and telnet
services running on the WiPy. Any changes performed using this class' methods will
affect both.
.. method:: active([is_active])
Example::
Activate ("up") or deactivate ("down") the network interface, if
a boolean argument is passed. Otherwise, query current state if
no argument is provided. Most other methods require an active
interface (behavior of calling them on inactive interface is
undefined).
import network
server = network.Server()
server.deinit() # disable the server
# enable the server again with new settings
server.init(login=('user', 'password'), timeout=600)
.. method:: connect([service_id, key=None, \*, ...])
Constructors
------------
Connect the interface to a network. This method is optional, and
available only for interfaces which are not "always connected".
If no parameters are given, connect to the default (or the only)
service. If a single parameter is given, it is the primary identifier
of a service to connect to. It may be accompanied by a key
(password) required to access said service. There can be further
arbitrary keyword-only parameters, depending on the networking medium
type and/or particular device. Parameters can be used to: a)
specify alternative service identifer types; b) provide additional
connection parameters. For various medium types, there are different
sets of predefined/recommended parameters, among them:
.. class:: network.Server(id, ...)
* WiFi: *bssid* keyword to connect by BSSID (MAC address) instead
of access point name
Create a server instance, see ``init`` for parameters of initialization.
.. method:: disconnect()
Methods
-------
Disconnect from network.
.. method:: server.init(\*, login=('micro', 'python'), timeout=300)
.. method:: isconnected()
Init (and effectively start the server). Optionally a new ``user``, ``password``
and ``timeout`` (in seconds) can be passed.
Returns ``True`` if connected to network, otherwise returns ``False``.
.. method:: server.deinit()
.. method:: scan(\*, ...)
Stop the server
Scan for the available network services/connections. Returns a
list of tuples with discovered service parameters. For various
network media, there are different variants of predefined/
recommended tuple formats, among them:
.. method:: server.timeout([timeout_in_seconds])
* WiFi: (ssid, bssid, channel, RSSI, authmode, hidden). There
may be further fields, specific to a particular device.
Get or set the server timeout.
The function may accept additional keyword arguments to filter scan
results (e.g. scan for a particular service, on a particular channel,
for services of a particular set, etc.), and to affect scan
duration and other parameters. Where possible, parameter names
should match those in connect().
.. method:: server.isrunning()
.. method:: status()
Return detailed status of the interface, values are dependent
on the network medium/technology.
.. method:: ifconfig([(ip, subnet, gateway, dns)])
Get/set IP-level network interface parameters: IP address, subnet mask,
gateway and DNS server. When called with no arguments, this method returns
a 4-tuple with the above information. To set the above values, pass a
4-tuple with the required information. For example::
nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
.. method:: config('param')
config(param=value, ...)
Get or set general network interface parameters. These methods allow to work
with additional parameters beyond standard IP configuration (as dealt with by
`ifconfig()`). These include network-specific and hardware-specific
parameters and status values. For setting parameters, the keyword argument
syntax should be used, and multiple parameters can be set at once. For
querying, a parameter name should be quoted as a string, and only one
parameter can be queried at a time::
# Set WiFi access point name (formally known as ESSID) and WiFi channel
ap.config(essid='My AP', channel=11)
# Query params one by one
print(ap.config('essid'))
print(ap.config('channel'))
# Extended status information also available this way
print(sta.config('rssi'))
Returns ``True`` if the server is running, ``False`` otherwise.
.. only:: port_pyboard
@ -170,11 +113,11 @@ parameter should be `id`.
Arguments are:
- *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is
- ``spi`` is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the CC3000 is
connected to (the MOSI, MISO and CLK pins).
- *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin.
- *pin_en* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin.
- *pin_irq* is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin.
- ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 CS pin.
- ``pin_en`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 VBEN pin.
- ``pin_irq`` is a :ref:`Pin object <pyb.Pin>` which is connected to the CC3000 IRQ pin.
All of these objects will be initialised by the driver, so there is no need to
initialise them yourself. For example, you can use::
@ -256,10 +199,10 @@ parameter should be `id`.
Arguments are:
- *spi* is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is
- ``spi`` is an :ref:`SPI object <pyb.SPI>` which is the SPI bus that the WIZnet5x00 is
connected to (the MOSI, MISO and SCLK pins).
- *pin_cs* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin.
- *pin_rst* is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin.
- ``pin_cs`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nSS pin.
- ``pin_rst`` is a :ref:`Pin object <pyb.Pin>` which is connected to the WIZnet5x00 nRESET pin.
All of these objects will be initialised by the driver, so there is no need to
initialise them yourself. For example, you can use::
@ -294,7 +237,7 @@ parameter should be `id`.
Get or set the PHY mode.
If the *mode* parameter is provided, sets the mode to its value. If
If the ``mode`` parameter is provided, sets the mode to its value. If
the function is called without parameters, returns the current mode.
The possible modes are defined as constants:
@ -322,7 +265,7 @@ parameter should be `id`.
``network.STA_IF`` (station aka client, connects to upstream WiFi access
points) and ``network.AP_IF`` (access point, allows other WiFi clients to
connect). Availability of the methods below depends on interface type.
For example, only STA interface may `connect()` to an access point.
For example, only STA interface may ``connect()`` to an access point.
Methods
-------
@ -350,8 +293,8 @@ parameter should be `id`.
(ssid, bssid, channel, RSSI, authmode, hidden)
*bssid* is hardware address of an access point, in binary form, returned as
bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form.
`bssid` is hardware address of an access point, in binary form, returned as
bytes object. You can use ``ubinascii.hexlify()`` to convert it to ASCII form.
There are five values for authmode:
@ -399,7 +342,7 @@ parameter should be `id`.
Get or set general network interface parameters. These methods allow to work
with additional parameters beyond standard IP configuration (as dealt with by
`wlan.ifconfig()`). These include network-specific and hardware-specific
``wlan.ifconfig()``). These include network-specific and hardware-specific
parameters. For setting parameters, keyword argument syntax should be used,
multiple parameters can be set at once. For querying, parameters name should
be quoted as a string, and only one parameter can be queries at time::
@ -450,7 +393,7 @@ parameter should be `id`.
.. class:: WLAN(id=0, ...)
Create a WLAN object, and optionally configure it. See `init()` for params of configuration.
Create a WLAN object, and optionally configure it. See ``init`` for params of configuration.
.. note::
@ -469,14 +412,14 @@ parameter should be `id`.
Arguments are:
- *mode* can be either ``WLAN.STA`` or ``WLAN.AP``.
- *ssid* is a string with the ssid name. Only needed when mode is ``WLAN.AP``.
- *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
- ``mode`` can be either ``WLAN.STA`` or ``WLAN.AP``.
- ``ssid`` is a string with the ssid name. Only needed when mode is ``WLAN.AP``.
- ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password.
If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal
values (e.g. 'ABC1DE45BF'). Only needed when mode is ``WLAN.AP``.
- *channel* a number in the range 1-11. Only needed when mode is ``WLAN.AP``.
- *antenna* selects between the internal and the external antenna. Can be either
- ``channel`` a number in the range 1-11. Only needed when mode is ``WLAN.AP``.
- ``antenna`` selects between the internal and the external antenna. Can be either
``WLAN.INT_ANT`` or ``WLAN.EXT_ANT``.
For example, you can do::
@ -494,13 +437,13 @@ parameter should be `id`.
Connect to a WiFi access point using the given SSID, and other security
parameters.
- *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
- ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``,
``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password.
If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal
values (e.g. 'ABC1DE45BF').
- *bssid* is the MAC address of the AP to connect to. Useful when there are several
- ``bssid`` is the MAC address of the AP to connect to. Useful when there are several
APs with the same ssid.
- *timeout* is the maximum time in milliseconds to wait for the connection to succeed.
- ``timeout`` is the maximum time in milliseconds to wait for the connection to succeed.
.. method:: wlan.scan()
@ -518,7 +461,7 @@ parameter should be `id`.
.. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple])
With no parameters given returns a 4-tuple of *(ip, subnet_mask, gateway, DNS_server)*.
With no parameters given returns a 4-tuple of ``(ip, subnet_mask, gateway, DNS_server)``.
if ``'dhcp'`` is passed as a parameter then the DHCP client is enabled and the IP params
are negotiated with the AP.
@ -556,8 +499,8 @@ parameter should be `id`.
Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP``
mode. Events are triggered by socket activity or by WLAN connection/disconnection.
- *handler* is the function that gets called when the IRQ is triggered.
- *wake* must be ``machine.SLEEP``.
- ``handler`` is the function that gets called when the IRQ is triggered.
- ``wake`` must be ``machine.SLEEP``.
Returns an IRQ object.

View File

@ -8,8 +8,7 @@ A Switch object is used to control a push-button switch.
Usage::
sw = pyb.Switch() # create a switch object
sw.value() # get state (True if pressed, False otherwise)
sw() # shorthand notation to get the switch state
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
@ -35,10 +34,6 @@ Methods
Call switch object directly to get its state: ``True`` if pressed down,
``False`` otherwise.
.. method:: Switch.value()
Get the switch state. Returns `True` if pressed down, otherwise `False`.
.. method:: Switch.callback(fun)
Register the given function to be called when the switch is pressed down.

View File

@ -21,7 +21,7 @@ Time related functions
Returns the number of milliseconds since the board was last reset.
The result is always a MicroPython smallint (31-bit signed number), so
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.
@ -33,7 +33,7 @@ Time related functions
Returns the number of microseconds since the board was last reset.
The result is always a MicroPython smallint (31-bit signed number), so
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.
@ -85,10 +85,10 @@ Reset related functions
Enable or disable hard-fault debugging. A hard-fault is when there is a fatal
error in the underlying system, like an invalid memory access.
If the *value* argument is ``False`` then the board will automatically reset if
If the `value` argument is `False` then the board will automatically reset if
there is a hard fault.
If *value* is ``True`` then, when the board has a hard fault, it will print the
If `value` is `True` then, when the board has a hard fault, it will print the
registers and the stack trace, and then cycle the LEDs indefinitely.
The default value is disabled, i.e. to automatically reset.

View File

@ -1,13 +1,18 @@
:mod:`uselect` -- wait for events on a set of streams
:mod:`select` -- wait for events on a set of streams
========================================================================
.. module:: uselect
.. module:: select
:synopsis: wait for events on a set of streams
|see_cpython_module| :mod:`python:select`.
This module provides functions to wait for events on streams (select streams
which are ready for operations).
This module provides functions to efficiently wait for events on multiple
streams (select streams which are ready for operations).
Pyboard specifics
-----------------
Polling is an efficient way of waiting for read/write activity on multiple
objects. Current objects that support polling are: :class:`pyb.UART`,
:class:`pyb.USB_VCP`.
Functions
---------
@ -20,8 +25,8 @@ Functions
Wait for activity on a set of objects.
This function is provided by some MicroPython ports for compatibility
and is not efficient. Usage of :class:`Poll` is recommended instead.
This function is provided for compatibility and is not efficient. Usage
of :class:`Poll` is recommended instead.
.. _class: Poll
@ -33,46 +38,30 @@ Methods
.. method:: poll.register(obj[, eventmask])
Register *obj* for polling. *eventmask* is logical OR of:
Register ``obj`` for polling. ``eventmask`` is logical OR of:
* ``select.POLLIN`` - data available for reading
* ``select.POLLOUT`` - more data can be written
* ``select.POLLERR`` - error occurred
* ``select.POLLHUP`` - end of stream/connection termination detected
*eventmask* defaults to ``select.POLLIN | select.POLLOUT``.
``eventmask`` defaults to ``select.POLLIN | select.POLLOUT``.
.. method:: poll.unregister(obj)
Unregister *obj* from polling.
Unregister ``obj`` from polling.
.. method:: poll.modify(obj, eventmask)
Modify the *eventmask* for *obj*.
Modify the ``eventmask`` for ``obj``.
.. method:: poll.poll([timeout])
Wait for at least one of the registered objects to become ready. Returns
list of (``obj``, ``event``, ...) tuples, ``event`` element specifies
which events happened with a stream and is a combination of ``select.POLL*``
which events happened with a stream and is a combination of `select.POLL*`
constants described above. There may be other elements in tuple, depending
on a platform and version, so don't assume that its size is 2. In case of
timeout, an empty list is returned.
Timeout is in milliseconds.
.. admonition:: Difference to CPython
:class: attention
Tuples returned may contain more than 2 elements as described above.
.. method:: poll.ipoll([timeout])
Like :meth:`poll.poll`, but instead returns an iterator which yields
callee-owned tuples. This function provides efficient, allocation-free
way to poll on streams.
.. admonition:: Difference to CPython
:class: attention
This function is a MicroPython extension.

View File

@ -4,21 +4,19 @@
.. module:: sys
:synopsis: system specific functions
|see_cpython_module| :mod:`python:sys`.
Functions
---------
.. function:: exit(retval=0)
Terminate current program with a given exit code. Underlyingly, this
function raise as `SystemExit` exception. If an argument is given, its
value given as an argument to `SystemExit`.
function raise as ``SystemExit`` exception. If an argument is given, its
value given as an argument to ``SystemExit``.
.. function:: print_exception(exc, file=sys.stdout)
Print exception with a traceback to a file-like object *file* (or
`sys.stdout` by default).
Print exception with a traceback to a file-like object `file` (or
``sys.stdout`` by default).
.. admonition:: Difference to CPython
:class: attention
@ -26,7 +24,7 @@ Functions
This is simplified version of a function which appears in the
``traceback`` module in CPython. Unlike ``traceback.print_exception()``,
this function takes just exception value instead of exception type,
exception value, and traceback object; *file* argument should be
exception value, and traceback object; `file` argument should be
positional; further arguments are not supported. CPython-compatible
``traceback`` module can be found in micropython-lib.
@ -39,15 +37,15 @@ Constants
.. data:: byteorder
The byte order of the system (``"little"`` or ``"big"``).
The byte order of the system ("little" or "big").
.. data:: implementation
Object with information about the current Python implementation. For
MicroPython, it has following attributes:
* *name* - string "micropython"
* *version* - tuple (major, minor, micro), e.g. (1, 7, 0)
* `name` - string "micropython"
* `version` - tuple (major, minor, micro), e.g. (1, 7, 0)
This object is the recommended way to distinguish MicroPython from other
Python implementations (note that it still may not exist in the very
@ -97,10 +95,10 @@ Constants
The platform that MicroPython is running on. For OS/RTOS ports, this is
usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it
is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython
is an identifier of a board, e.g. "pyboard" for the original MicroPython
reference board. It thus can be used to distinguish one board from another.
If you need to check whether your program runs on MicroPython (vs other
Python implementation), use `sys.implementation` instead.
Python implementation), use ``sys.implementation`` instead.
.. data:: stderr

View File

@ -4,8 +4,6 @@
.. module:: ubinascii
:synopsis: binary/ASCII conversions
|see_cpython_module| :mod:`python:binascii`.
This module implements conversions between binary data and various
encodings of it in ASCII form (in both directions).
@ -19,7 +17,7 @@ Functions
.. admonition:: Difference to CPython
:class: attention
If additional argument, *sep* is supplied, it is used as a separator
If additional argument, `sep` is supplied, it is used as a separator
between hexadecimal values.
.. function:: unhexlify(data)

View File

@ -4,8 +4,6 @@
.. module:: ucollections
:synopsis: collection and container types
|see_cpython_module| :mod:`python:collections`.
This module implements advanced collection and container types to
hold/accumulate various objects.

View File

@ -1,34 +0,0 @@
:mod:`uerrno` -- system error codes
===================================
.. module:: uerrno
:synopsis: system error codes
|see_cpython_module| :mod:`python:errno`.
This module provides access to symbolic error codes for `OSError` exception.
A particular inventory of codes depends on `MicroPython port`.
Constants
---------
.. data:: EEXIST, EAGAIN, etc.
Error codes, based on ANSI C/POSIX standard. All error codes start with
"E". As mentioned above, inventory of the codes depends on
`MicroPython port`. Errors are usually accessible as ``exc.args[0]``
where `exc` is an instance of `OSError`. Usage example::
try:
uos.mkdir("my_dir")
except OSError as exc:
if exc.args[0] == uerrno.EEXIST:
print("Directory already exists")
.. data:: errorcode
Dictionary mapping numeric error codes to strings with symbolic error
code (see above)::
>>> print(uerrno.errorcode[uerrno.EEXIST])
EEXIST

View File

@ -4,8 +4,6 @@
.. module:: uhashlib
:synopsis: hashing algorithms
|see_cpython_module| :mod:`python:hashlib`.
This module implements binary data hashing algorithms. The exact inventory
of available algorithms depends on a board. Among the algorithms which may
be implemented:
@ -17,11 +15,11 @@ be implemented:
* SHA1 - A previous generation algorithm. Not recommended for new usages,
but SHA1 is a part of number of Internet standards and existing
applications, so boards targeting network connectivity and
applications, so boards targetting network connectivity and
interoperatiability will try to provide this.
* MD5 - A legacy algorithm, not considered cryptographically secure. Only
selected boards, targeting interoperatibility with legacy applications,
selected boards, targetting interoperatibility with legacy applications,
will offer this.
Constructors

View File

@ -4,8 +4,6 @@
.. module:: uheapq
:synopsis: heap queue algorithm
|see_cpython_module| :mod:`python:heapq`.
This module implements the heap queue algorithm.
A heap queue is simply a list that has its elements stored in a certain way.

View File

@ -4,8 +4,6 @@
.. module:: uio
:synopsis: input/output streams
|see_cpython_module| :mod:`python:io`.
This module contains additional types of stream (file-like) objects
and helper functions.

View File

@ -4,8 +4,6 @@
.. module:: ujson
:synopsis: JSON encoding and decoding
|see_cpython_module| :mod:`python:json`.
This modules allows to convert between Python objects and the JSON
data format.

View File

@ -4,11 +4,28 @@
.. module:: uos
:synopsis: basic "operating system" services
|see_cpython_module| :mod:`python:os`.
The ``uos`` module contains functions for filesystem access and ``urandom``
The ``os`` module contains functions for filesystem access and ``urandom``
function.
Port specifics
--------------
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)
.. only:: port_pyboard
On boot up, the current directory is ``/flash`` if no SD card is inserted,
otherwise it is ``/sd``.
.. only:: port_wipy
On boot up, the current directory is ``/flash``.
Functions
---------
@ -24,15 +41,15 @@ Functions
This function returns an iterator which then yields 3-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*.
current directory, otherwise it lists the directory given by `dir`.
The 3-tuples have the form *(name, type, inode)*:
The 3-tuples have the form `(name, type, inode)`:
- *name* is a string (or bytes if *dir* is a bytes object) and is the name of
- `name` is a string (or bytes if `dir` is a bytes object) and is the name of
the entry;
- *type* is an integer that specifies the type of the entry, with 0x4000 for
- `type` is an integer that specifies the type of the entry, with 0x4000 for
directories and 0x8000 for regular files;
- *inode* is an integer corresponding to the inode of the file, and may be 0
- `inode` is an integer corresponding to the inode of the file, and may be 0
for filesystems that don't have such a notion.
.. function:: listdir([dir])
@ -89,8 +106,26 @@ Functions
Return a bytes object with n random bytes. Whenever possible, it is
generated by the hardware random number generator.
.. function:: dupterm(stream_object)
.. only:: port_wipy
Duplicate or switch MicroPython terminal (the REPL) on the passed stream-like
object. The given object must implement the ``readinto()`` and ``write()``
methods. If ``None`` is passed, previously set redirection is cancelled.
.. function:: mount(block_device, mount_point, \*, readonly=False)
Mounts a block device (like an ``SD`` object) in the specified mount
point. Example::
os.mount(sd, '/sd')
.. function:: unmount(path)
Unmounts a previously mounted block device from the given path.
.. function:: mkfs(block_device or path)
Formats the specified path, must be either ``/flash`` or ``/sd``.
A block device can also be passed like an ``SD`` object before
being mounted.
.. function:: dupterm(stream_object)
Duplicate the terminal (the REPL) on the passed stream-like object.
The given object must at least implement the ``.read()`` and ``.write()`` methods.

View File

@ -1,11 +1,9 @@
:mod:`ure` -- simple regular expressions
========================================
:mod:`ure` -- regular expressions
=================================
.. module:: ure
:synopsis: regular expressions
|see_cpython_module| :mod:`python:re`.
This module implements regular expression operations. Regular expression
syntax supported is a subset of CPython ``re`` module (and actually is
a subset of POSIX extended regular expressions).
@ -34,10 +32,6 @@ Supported operators are:
``'+?'``
``'()'``
Grouping. Each group is capturing (a substring it captures can be accessed
with `match.group()` method).
Counted repetitions (``{m,n}``), more advanced assertions, named groups,
etc. are not supported.
@ -45,18 +39,18 @@ etc. are not supported.
Functions
---------
.. function:: compile(regex_str)
.. function:: compile(regex)
Compile regular expression, return `regex <regex>` object.
Compile regular expression, return ``regex`` object.
.. function:: match(regex_str, string)
.. function:: match(regex, string)
Compile *regex_str* and match against *string*. Match always happens
from starting position in a string.
Match ``regex`` against ``string``. Match always happens from starting
position in a string.
.. function:: search(regex_str, string)
.. function:: search(regex, string)
Compile *regex_str* and search it in a *string*. Unlike `match`, this will search
Search ``regex`` in a ``string``. Unlike ``match``, this will search
string for first position which matches regex (which still may be
0 if regex is anchored).
@ -65,33 +59,24 @@ Functions
Flag value, display debug information about compiled expression.
.. _regex:
Regex objects
-------------
Compiled regular expression. Instances of this class are created using
`ure.compile()`.
``ure.compile()``.
.. method:: regex.match(string)
regex.search(string)
Similar to the module-level functions :meth:`match` and :meth:`search`.
Using methods is (much) more efficient if the same regex is applied to
multiple strings.
.. method:: regex.search(string)
.. method:: regex.split(string, max_split=-1)
Split a *string* using regex. If *max_split* is given, it specifies
maximum number of splits to perform. Returns list of strings (there
may be up to *max_split+1* elements if it's specified).
Match objects
-------------
Match objects as returned by `match()` and `search()` methods.
Match objects as returned by ``match()`` and ``search()`` methods.
.. method:: match.group([index])
Return matching (sub)string. *index* is 0 for entire match,
1 and above for each capturing group. Only numeric groups are supported.
Only numeric groups are supported.

View File

@ -5,22 +5,23 @@
.. module:: usocket
:synopsis: socket module
|see_cpython_module| :mod:`python:socket`.
This module provides access to the BSD socket interface.
See the corresponding `CPython module <https://docs.python.org/3/library/socket.html>`_
for comparison.
.. admonition:: Difference to CPython
:class: attention
CPython used to have a ``socket.error`` exception which is now deprecated,
and is an alias of `OSError`. In MicroPython, use `OSError` directly.
and is an alias of OSError. In MicroPython, use OSError directly.
.. admonition:: Difference to CPython
:class: attention
For efficiency and consistency, socket objects in MicroPython implement a stream
(file-like) interface directly. In CPython, you need to convert a socket to
a file-like object using `makefile()` method. This method is still supported
a file-like object using ``makefile()`` method. This method is still supported
by MicroPython (but is a no-op), so where compatibility with CPython matters,
be sure to use it.
@ -28,19 +29,19 @@ Socket address format(s)
------------------------
The functions below which expect a network address, accept it in the format of
*(ipv4_address, port)*, where *ipv4_address* is a string with dot-notation numeric
`(ipv4_address, port)`, where `ipv4_address` is a string with dot-notation numeric
IPv4 address, e.g. ``"8.8.8.8"``, and port is integer port number in the range
1-65535. Note the domain names are not accepted as *ipv4_address*, they should be
resolved first using `usocket.getaddrinfo()`.
1-65535. Note the domain names are not accepted as `ipv4_address`, they should be
resolved first using ``socket.getaddrinfo()``.
Functions
---------
.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
.. function:: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
Create a new socket using the given address family, socket type and protocol number.
.. function:: getaddrinfo(host, port)
.. function:: socket.getaddrinfo(host, port)
Translate the host/port argument into a sequence of 5-tuples that contain all the
necessary arguments for creating a socket connected to that service. The list of
@ -56,11 +57,11 @@ Functions
.. admonition:: Difference to CPython
:class: attention
CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case
CPython raises a ``socket.gaierror`` exception (OSError subclass) in case
of error in this function. MicroPython doesn't have ``socket.gaierror``
and raises OSError directly. Note that error numbers of `getaddrinfo()`
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
``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
@ -69,34 +70,32 @@ Functions
Constants
---------
.. data:: AF_INET
AF_INET6
.. data:: socket.AF_INET
socket.AF_INET6
Address family types. Availability depends on a particular board.
.. data:: SOCK_STREAM
SOCK_DGRAM
.. data:: socket.SOCK_STREAM
socket.SOCK_DGRAM
Socket types.
.. data:: IPPROTO_UDP
IPPROTO_TCP
.. data:: socket.IPPROTO_UDP
socket.IPPROTO_TCP
IP protocol numbers.
.. data:: usocket.SOL_*
.. data:: socket.SOL_*
Socket option levels (an argument to `setsockopt()`). The exact
inventory depends on a MicroPython port.
Socket option levels (an argument to ``setsockopt()``). The exact inventory depends on a board.
.. data:: usocket.SO_*
.. data:: socket.SO_*
Socket options (an argument to `setsockopt()`). The exact
inventory depends on a MicroPython port.
Socket options (an argument to ``setsockopt()``). The exact inventory depends on a board.
Constants specific to WiPy:
.. data:: IPPROTO_SEC
.. data:: socket.IPPROTO_SEC
Special protocol value to create SSL-compatible socket.
@ -106,22 +105,21 @@ class socket
Methods
-------
.. method:: socket.close()
.. method:: socket.close
Mark the socket closed and release all resources. Once that happens, all future operations
on the socket object will fail. The remote end will receive EOF indication if
supported by protocol.
Mark the socket closed. Once that happens, all future operations on the socket
object will fail. The remote end will receive no more data (after queued data is flushed).
Sockets are automatically closed when they are garbage-collected, but it is recommended
to `close()` them explicitly as soon you finished working with them.
to close() them explicitly, or to use a with statement around them.
.. method:: socket.bind(address)
Bind the socket to *address*. The socket must not already be bound.
Bind the socket to address. The socket must not already be bound.
.. method:: socket.listen([backlog])
Enable a server to accept connections. If *backlog* is specified, it must be at least 0
Enable a server to accept connections. If backlog is specified, it must be at least 0
(if it's lower, it will be set to 0); and specifies the number of unaccepted connections
that the system will allow before refusing new connections. If not specified, a default
reasonable value is chosen.
@ -135,7 +133,7 @@ Methods
.. method:: socket.connect(address)
Connect to a remote socket at *address*.
Connect to a remote socket at address.
.. method:: socket.send(bytes)
@ -146,11 +144,11 @@ Methods
.. method:: socket.sendall(bytes)
Send all data to the socket. The socket must be connected to a remote socket.
Unlike `send()`, this method will try to send all of data, by sending data
Unlike ``send()``, this method will try to send all of data, by sending data
chunk by chunk consecutively.
The behavior of this method on non-blocking sockets is undefined. Due to this,
on MicroPython, it's recommended to use `write()` method instead, which
on MicroPython, it's recommended to use ``write()`` method instead, which
has the same "no short writes" policy for blocking sockets, and will return
number of bytes sent on non-blocking sockets.
@ -162,25 +160,25 @@ Methods
.. method:: socket.sendto(bytes, address)
Send data to the socket. The socket should not be connected to a remote socket, since the
destination socket is specified by *address*.
destination socket is specified by `address`.
.. method:: socket.recvfrom(bufsize)
Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a
bytes object representing the data received and *address* is the address of the socket sending
Receive data from the socket. The return value is a pair (bytes, address) where bytes is a
bytes object representing the data received and address is the address of the socket sending
the data.
.. method:: socket.setsockopt(level, optname, value)
Set the value of the given socket option. The needed symbolic constants are defined in the
socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing
socket module (SO_* etc.). The value can be an integer or a bytes-like object representing
a buffer.
.. method:: socket.settimeout(value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative floating
point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations
will raise an `OSError` exception if the timeout period value has elapsed before the operation has
will raise an ``OSError`` exception if the timeout period value has elapsed before the operation has
completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket
is put in blocking mode.
@ -188,7 +186,7 @@ Methods
:class: attention
CPython raises a ``socket.timeout`` exception in case of timeout,
which is an `OSError` subclass. MicroPython raises an OSError directly
which is an ``OSError`` subclass. MicroPython raises an OSError directly
instead. If you use ``except OSError:`` to catch the exception,
your code will work both in MicroPython and CPython.
@ -197,7 +195,7 @@ Methods
Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking,
else to blocking mode.
This method is a shorthand for certain `settimeout()` calls:
This method is a shorthand for certain ``settimeout()`` calls:
* ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
* ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)``
@ -206,12 +204,12 @@ Methods
Return a file object associated with the socket. The exact returned type depends on the arguments
given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb').
CPython's arguments: *encoding*, *errors* and *newline* are not supported.
CPython's arguments: ``encoding``, ``errors`` and ``newline`` are not supported.
.. admonition:: Difference to CPython
:class: attention
As MicroPython doesn't support buffered streams, values of *buffering*
As MicroPython doesn't support buffered streams, values of ``buffering``
parameter is ignored and treated as if it was 0 (unbuffered).
.. admonition:: Difference to CPython
@ -222,19 +220,19 @@ Methods
.. method:: socket.read([size])
Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it
reads all data available from the socket until EOF; as such the method will not return until
Read up to size bytes from the socket. Return a bytes object. If ``size`` is not given, it
reads all data available from the socket until ``EOF``; as such the method will not return until
the socket is closed. This function tries to read as much data as
requested (no "short reads"). This may be not possible with
non-blocking socket though, and then less data will be returned.
.. method:: socket.readinto(buf[, nbytes])
Read bytes into the *buf*. If *nbytes* is specified then read at most
that many bytes. Otherwise, read at most *len(buf)* bytes. Just as
`read()`, this method follows "no short reads" policy.
Read bytes into the ``buf``. If ``nbytes`` is specified then read at most
that many bytes. Otherwise, read at most ``len(buf)`` bytes. Just as
``read()``, this method follows "no short reads" policy.
Return value: number of bytes read and stored into *buf*.
Return value: number of bytes read and stored into ``buf``.
.. method:: socket.readline()
@ -247,6 +245,6 @@ Methods
Write the buffer of bytes to the socket. This function will try to
write all data to a socket (no "short writes"). This may be not possible
with a non-blocking socket though, and returned value will be less than
the length of *buf*.
the length of ``buf``.
Return value: number of bytes written.

View File

@ -4,8 +4,6 @@
.. module:: ussl
:synopsis: TLS/SSL wrapper for socket objects
|see_cpython_module| :mod:`python:ssl`.
This module provides access to Transport Layer Security (previously and
widely known as “Secure Sockets Layer”) encryption and peer authentication
facilities for network sockets, both client-side and server-side.
@ -15,7 +13,7 @@ Functions
.. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None)
Takes a stream *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type),
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
@ -45,4 +43,4 @@ Constants
ssl.CERT_OPTIONAL
ssl.CERT_REQUIRED
Supported values for *cert_reqs* parameter.
Supported values for `cert_reqs` parameter.

View File

@ -4,7 +4,8 @@
.. module:: ustruct
:synopsis: pack and unpack primitive data types
|see_cpython_module| :mod:`python:struct`.
See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more
information.
Supported size/byte order prefixes: ``@``, ``<``, ``>``, ``!``.
@ -17,26 +18,26 @@ Functions
.. function:: calcsize(fmt)
Return the number of bytes needed to store the given *fmt*.
Return the number of bytes needed to store the given `fmt`.
.. function:: pack(fmt, v1, v2, ...)
Pack the values *v1*, *v2*, ... according to the format string *fmt*.
Pack the values `v1`, `v2`, ... according to the format string `fmt`.
The return value is a bytes object encoding the values.
.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)
Pack the values *v1*, *v2*, ... according to the format string *fmt*
into a *buffer* starting at *offset*. *offset* may be negative to count
from the end of *buffer*.
Pack the values `v1`, `v2`, ... according to the format string `fmt`
into a `buffer` starting at `offset`. `offset` may be negative to count
from the end of `buffer`.
.. function:: unpack(fmt, data)
Unpack from the *data* according to the format string *fmt*.
Unpack from the `data` according to the format string `fmt`.
The return value is a tuple of the unpacked values.
.. function:: unpack_from(fmt, data, offset=0)
Unpack from the *data* starting at *offset* according to the format string
*fmt*. *offset* may be negative to count from the end of *buffer*. The return
Unpack from the `data` starting at `offset` according to the format string
`fmt`. `offset` may be negative to count from the end of `buffer`. The return
value is a tuple of the unpacked values.

View File

@ -4,8 +4,6 @@
.. module:: utime
:synopsis: time related functions
|see_cpython_module| :mod:`python:time`.
The ``utime`` module provides functions for getting the current time and date,
measuring time intervals, and for delays.
@ -59,10 +57,10 @@ Functions
.. function:: sleep(seconds)
Sleep for the given number of seconds. Some boards may accept *seconds* as a
Sleep for the given number of seconds. Some boards may accept `seconds` as a
floating-point number to sleep for a fractional number of seconds. Note that
other boards may not accept a floating-point argument, for compatibility with
them use `sleep_ms()` and `sleep_us()` functions.
them use ``sleep_ms()`` and ``sleep_us()`` functions.
.. function:: sleep_ms(ms)
@ -75,32 +73,30 @@ Functions
.. function:: ticks_ms()
Returns an increasing millisecond counter with an arbitrary reference point, that
wraps around after some value.
The wrap-around value is not explicitly exposed, but we will
refer to it as *TICKS_MAX* to simplify discussion. Period of the values is
*TICKS_PERIOD = TICKS_MAX + 1*. *TICKS_PERIOD* is guaranteed to be a power of
wraps around after some value. This value is not explicitly exposed, but we will
refer to it as ``TICKS_MAX`` to simplify discussion. Period of the values is
``TICKS_PERIOD = TICKS_MAX + 1``. ``TICKS_PERIOD`` is guaranteed to be a power of
two, but otherwise may differ from port to port. The same period value is used
for all of `ticks_ms()`, `ticks_us()`, `ticks_cpu()` functions (for
simplicity). Thus, these functions will return a value in range [*0* ..
*TICKS_MAX*], inclusive, total *TICKS_PERIOD* values. Note that only
for all of ``ticks_ms()``, ``ticks_us()``, ``ticks_cpu()`` functions (for
simplicity). Thus, these functions will return a value in range [``0`` ..
``TICKS_MAX``], inclusive, total ``TICKS_PERIOD`` values. Note that only
non-negative values are used. For the most part, you should treat values returned
by these functions as opaque. The only operations available for them are
`ticks_diff()` and `ticks_add()` functions described below.
``ticks_diff()`` and ``ticks_add()`` functions described below.
Note: Performing standard mathematical operations (+, -) or relational
operators (<, <=, >, >=) directly on these value will lead to invalid
result. Performing mathematical operations and then passing their results
as arguments to `ticks_diff()` or `ticks_add()` will also lead to
as arguments to ``ticks_diff()`` or ``ticks_add()`` will also lead to
invalid results from the latter functions.
.. function:: ticks_us()
Just like `ticks_ms()` above, but in microseconds.
Just like ``ticks_ms()`` above, but in microseconds.
.. function:: ticks_cpu()
Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution
Similar to ``ticks_ms()`` and ``ticks_us()``, but with the highest possible resolution
in the system. This is usually CPU clocks, and that's why the function is named that
way. But it doesn't have to be a CPU clock, some other timing source available in a
system (e.g. high-resolution timer) can be used instead. The exact timing unit
@ -115,13 +111,13 @@ Functions
.. function:: ticks_add(ticks, delta)
Offset ticks value by a given number, which can be either positive or negative.
Given a *ticks* value, this function allows to calculate ticks value *delta*
Given a ``ticks`` value, this function allows to calculate ticks value ``delta``
ticks before or after it, following modular-arithmetic definition of tick values
(see `ticks_ms()` above). *ticks* parameter must be a direct result of call
to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` functions (or from previous
call to `ticks_add()`). However, *delta* can be an arbitrary integer number
or numeric expression. `ticks_add()` is useful for calculating deadlines for
events/tasks. (Note: you must use `ticks_diff()` function to work with
(see ``ticks_ms()`` above). ``ticks`` parameter must be a direct result of call
to ``ticks_ms()``, ``ticks_us()``, or ``ticks_cpu()`` functions (or from previous
call to ``ticks_add()``). However, ``delta`` can be an arbitrary integer number
or numeric expression. ``ticks_add()`` is useful for calculating deadlines for
events/tasks. (Note: you must use ``ticks_diff()`` function to work with
deadlines.)
Examples::
@ -140,25 +136,23 @@ Functions
.. function:: ticks_diff(ticks1, ticks2)
Measure ticks difference between values returned from `ticks_ms()`, `ticks_us()`,
or `ticks_cpu()` functions, as a signed value which may wrap around.
The argument order is the same as for subtraction
Measure ticks difference between values returned from ``ticks_ms()``, ``ticks_us()``,
or ``ticks_cpu()`` functions. The argument order is the same as for subtraction
operator, ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``.
However, values returned by `ticks_ms()`, etc. functions may wrap around, so
However, values returned by ``ticks_ms()``, etc. functions may wrap around, so
directly using subtraction on them will produce incorrect result. That is why
`ticks_diff()` is needed, it implements modular (or more specifically, ring)
``ticks_diff()`` is needed, it implements modular (or more specifically, ring)
arithmetics to produce correct result even for wrap-around values (as long as they not
too distant inbetween, see below). The function returns **signed** value in the range
[*-TICKS_PERIOD/2* .. *TICKS_PERIOD/2-1*] (that's a typical range definition for
[``-TICKS_PERIOD/2`` .. ``TICKS_PERIOD/2-1``] (that's a typical range definition for
two's-complement signed binary integers). If the result is negative, it means that
*ticks1* occurred earlier in time than *ticks2*. Otherwise, it means that
*ticks1* occurred after *ticks2*. This holds **only** if *ticks1* and *ticks2*
are apart from each other for no more than *TICKS_PERIOD/2-1* ticks. If that does
``ticks1`` occured earlier in time than ``ticks2``. Otherwise, it means that
``ticks1`` occured after ``ticks2``. This holds ``only`` if ``ticks1`` and ``ticks2``
are apart from each other for no more than ``TICKS_PERIOD/2-1`` ticks. If that does
not hold, incorrect result will be returned. Specifically, if two tick values are
apart for *TICKS_PERIOD/2-1* ticks, that value will be returned by the function.
However, if *TICKS_PERIOD/2* of real-time ticks has passed between them, the
function will return *-TICKS_PERIOD/2* instead, i.e. result value will wrap around
apart for ``TICKS_PERIOD/2-1`` ticks, that value will be returned by the function.
However, if ``TICKS_PERIOD/2`` of real-time ticks has passed between them, the
function will return ``-TICKS_PERIOD/2`` instead, i.e. result value will wrap around
to the negative range of possible values.
Informal rationale of the constraints above: Suppose you are locked in a room with no
@ -170,10 +164,10 @@ Functions
behavior: don't let your application run any single task for too long. Run tasks
in steps, and do time-keeping inbetween.
`ticks_diff()` is designed to accommodate various usage patterns, among them:
``ticks_diff()`` is designed to accommodate various usage patterns, among them:
* Polling with timeout. In this case, the order of events is known, and you will deal
only with positive results of `ticks_diff()`::
Polling with timeout. In this case, the order of events is known, and you will deal
only with positive results of ``ticks_diff()``::
# Wait for GPIO pin to be asserted, but at most 500us
start = time.ticks_us()
@ -181,8 +175,8 @@ Functions
if time.ticks_diff(time.ticks_us(), start) > 500:
raise TimeoutError
* Scheduling events. In this case, `ticks_diff()` result may be negative
if an event is overdue::
Scheduling events. In this case, ``ticks_diff()`` result may be negative
if an event is overdue::
# This code snippet is not optimized
now = time.ticks_ms()
@ -198,8 +192,8 @@ Functions
print("Oops, running late, tell task to run faster!")
task.run(run_faster=true)
Note: Do not pass `time()` values to `ticks_diff()`, you should use
normal mathematical operations on them. But note that `time()` may (and will)
Note: Do not pass ``time()`` values to ``ticks_diff()``, you should use
normal mathematical operations on them. But note that ``time()`` may (and will)
also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_problem .
@ -211,8 +205,8 @@ Functions
embedded boards without a battery-backed RTC, usually since power up or reset). If you
want to develop portable MicroPython application, you should not rely on this function
to provide higher than second precision. If you need higher precision, use
`ticks_ms()` and `ticks_us()` functions, if you need calendar time,
`localtime()` without an argument is a better choice.
``ticks_ms()`` and ``ticks_us()`` functions, if you need calendar time,
``localtime()`` without an argument is a better choice.
.. admonition:: Difference to CPython
:class: attention

View File

@ -4,35 +4,13 @@
.. module:: uzlib
:synopsis: zlib decompression
|see_cpython_module| :mod:`python:zlib`.
This module allows to decompress binary data compressed with
`DEFLATE algorithm <https://en.wikipedia.org/wiki/DEFLATE>`_
(commonly used in zlib library and gzip archiver). Compression
This modules allows to decompress binary data compressed with DEFLATE
algorithm (commonly used in zlib library and gzip archiver). Compression
is not yet implemented.
Functions
---------
.. function:: decompress(data, wbits=0, bufsize=0)
.. function:: decompress(data)
Return decompressed *data* as bytes. *wbits* is DEFLATE dictionary window
size used during compression (8-15, the dictionary size is power of 2 of
that value). Additionally, if value is positive, *data* is assumed to be
zlib stream (with zlib header). Otherwise, if it's negative, it's assumed
to be raw DEFLATE stream. *bufsize* parameter is for compatibility with
CPython and is ignored.
.. class:: DecompIO(stream, wbits=0)
Create a stream wrapper which allows transparent decompression of
compressed data in another *stream*. This allows to process compressed
streams with data larger than available heap size. In addition to
values described in :func:`decompress`, *wbits* may take values
24..31 (16 + 8..15), meaning that input stream has gzip header.
.. admonition:: Difference to CPython
:class: attention
This class is MicroPython extension. It's included on provisional
basis and may be changed considerably or removed in later versions.
Return decompressed data as bytes.

View File

@ -3,7 +3,7 @@ MicroPython license information
The MIT License (MIT)
Copyright (c) 2013-2017 Damien P. George, and others
Copyright (c) 2013-2015 Damien P. George, and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,8 +1,6 @@
General information about the pyboard
=====================================
.. contents::
Local filesystem and SD card
----------------------------
@ -12,9 +10,7 @@ is inserted into the slot, it is available as ``/sd``.
When the pyboard boots up, it needs to choose a filesystem to boot from. If
there is no SD card, then it uses the internal filesystem ``/flash`` as the boot
filesystem, otherwise, it uses the SD card ``/sd``. After the boot, the current
directory is set to one of the directories above.
filesystem, otherwise, it uses the SD card ``/sd``.
If needed, you can prevent the use of the SD card by creating an empty file
called ``/flash/SKIPSD``. If this file exists when the pyboard boots
up then the SD card will be skipped and the pyboard will always boot from the
@ -69,12 +65,3 @@ There are currently 2 kinds of errors that you might see:
2. If all 4 LEDs cycle on and off slowly, then there was a hard fault.
This cannot be recovered from and you need to do a hard reset.
Guide for using the pyboard with Windows
----------------------------------------
The following PDF guide gives information about using the pyboard with Windows,
including setting up the serial prompt and downloading new firmware using
DFU programming:
`PDF guide <http://micropython.org/resources/Micro-Python-Windows-setup.pdf>`__.
.. include:: hardware/index.rst

View File

@ -1,7 +1,7 @@
.. _hardware_index:
The pyboard hardware
--------------------
====================
For the pyboard:
@ -16,14 +16,14 @@ For the official skin modules:
* LCD160CRv1.0: see :mod:`lcd160cr`
Datasheets for the components on the pyboard
--------------------------------------------
============================================
* The microcontroller: `STM32F405RGT6 <http://www.st.com/web/catalog/mmc/FM141/SC1169/SS1577/LN1035/PF252144>`_ (link to manufacturer's site)
* The accelerometer: `Freescale MMA7660 <http://micropython.org/resources/datasheets/MMA7660FC.pdf>`_ (800kiB PDF)
* The LDO voltage regulator: `Microchip MCP1802 <http://micropython.org/resources/datasheets/MCP1802-22053C.pdf>`_ (400kiB PDF)
Datasheets for other components
-------------------------------
===============================
* The LCD display on the LCD touch-sensor skin: `Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3 <http://micropython.org/resources/datasheets/NHD-C12832A1Z-FSW-FBW-3V3.pdf>`_ (460KiB PDF)
* The touch sensor chip on the LCD touch-sensor skin: `Freescale MPR121 <http://micropython.org/resources/datasheets/MPR121.pdf>`_ (280KiB PDF)

View File

@ -69,30 +69,4 @@ Then you can do::
>>> f = wave.open('test.wav')
>>> dac.write_timed(f.readframes(f.getnframes()), f.getframerate())
This should play the WAV file. Note that this will read the whole file into RAM
so it has to be small enough to fit in it.
To play larger wave files you will have to use the micro-SD card to store it.
Also the file must be read and sent to the DAC in small chunks that will fit
the RAM limit of the microcontroller. Here is an example function that can
play 8-bit wave files with up to 16kHz sampling::
import wave
from pyb import DAC
from pyb import delay
dac = DAC(1)
def play(filename):
f = wave.open(filename, 'r')
total_frames = f.getnframes()
framerate = f.getframerate()
for position in range(0, total_frames, framerate):
f.setpos(position)
dac.write_timed(f.readframes(framerate), framerate)
delay(1000)
This function reads one second worth of data and sends it to DAC. It then waits
one second and moves the file cursor to the new position to read the next second
of data in the next iteration of the for-loop. It plays one second of audio at
a time every one second.
This should play the WAV file.

View File

@ -1,7 +1,7 @@
.. _tutorial-index:
MicroPython tutorial for the pyboard
====================================
MicroPython tutorial
====================
This tutorial is intended to get you started with your pyboard.
All you need is a pyboard and a micro-USB cable to connect it to

View File

@ -15,18 +15,12 @@ the name ``pyb`` does not exist.
With the switch object you can get its status::
>>> sw.value()
>>> sw()
False
This will print ``False`` if the switch is not held, or ``True`` if it is held.
Try holding the USR switch down while running the above command.
There is also a shorthand notation to get the switch status, by "calling" the
switch object::
>>> sw()
False
Switch callbacks
----------------

14
docs/pyboard_contents.rst Normal file
View File

@ -0,0 +1,14 @@
MicroPython documentation contents
==================================
.. toctree::
pyboard/quickref.rst
pyboard/general.rst
pyboard/tutorial/index.rst
library/index.rst
reference/index.rst
pyboard/hardware/index.rst
genrst/index.rst
license.rst

View File

@ -7,6 +7,14 @@ MicroPython documentation and references
pyboard/general.rst
pyboard/tutorial/index.rst
library/index.rst
reference/index.rst
pyboard/hardware/index.rst
genrst/index.rst
license.rst
pyboard_contents.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Some files were not shown because too many files have changed in this diff Show More