mirror of
https://github.com/micropython/micropython.git
synced 2025-12-31 09:10:11 +01:00
Compare commits
466 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe45d78b1e | ||
|
|
5ae9586541 | ||
|
|
80e3f07e7f | ||
|
|
02b4b23319 | ||
|
|
b81fbf938f | ||
|
|
4dd523adbb | ||
|
|
6fb093282b | ||
|
|
10b76a9620 | ||
|
|
74ec52d857 | ||
|
|
05a2bb888f | ||
|
|
8f9af63c20 | ||
|
|
24c8eda744 | ||
|
|
0e80f345f8 | ||
|
|
9b9dbc5815 | ||
|
|
b9923262db | ||
|
|
c64eb4f8ce | ||
|
|
a33fca99a1 | ||
|
|
d1cd533134 | ||
|
|
f36975b679 | ||
|
|
328c1e78be | ||
|
|
9a7e3469b2 | ||
|
|
f4059dcc0c | ||
|
|
cfff12612f | ||
|
|
9956fd0710 | ||
|
|
f2baa9ec24 | ||
|
|
93ce125abe | ||
|
|
d6bf3658f4 | ||
|
|
0eb333e3cf | ||
|
|
9725a654bd | ||
|
|
c53ca32561 | ||
|
|
8fa3d2996c | ||
|
|
285ac58532 | ||
|
|
d90ade5e3e | ||
|
|
06f2fdbe61 | ||
|
|
e36821a766 | ||
|
|
c0ea91bc89 | ||
|
|
73e387cff6 | ||
|
|
5c437963d7 | ||
|
|
0a30ad96c8 | ||
|
|
5d7b0b237b | ||
|
|
65ba481cb0 | ||
|
|
829c329daf | ||
|
|
37282f8fc1 | ||
|
|
e39fcda8eb | ||
|
|
7c7c7b161d | ||
|
|
c59fc1419d | ||
|
|
a3afa8cfc4 | ||
|
|
1b7d6a7951 | ||
|
|
b1457db002 | ||
|
|
69da74e538 | ||
|
|
dc948e4d54 | ||
|
|
08a196697c | ||
|
|
81a06d2c9c | ||
|
|
d8d4e4dfbe | ||
|
|
25e140652b | ||
|
|
f599a38059 | ||
|
|
dc92f1c4ee | ||
|
|
d236d0c415 | ||
|
|
933eab46fc | ||
|
|
add933feaf | ||
|
|
6db132e130 | ||
|
|
53966fd9a8 | ||
|
|
c15be989ee | ||
|
|
4514f073c1 | ||
|
|
71c1a05d88 | ||
|
|
58ea239510 | ||
|
|
6f1a615427 | ||
|
|
ca2427c313 | ||
|
|
7df4083ac6 | ||
|
|
ea6692a83e | ||
|
|
98dd126e98 | ||
|
|
8c7db42ee3 | ||
|
|
ff93fd4f50 | ||
|
|
36f7952f76 | ||
|
|
0864a6957f | ||
|
|
f869d6b2e3 | ||
|
|
23faf88cab | ||
|
|
dfa563c71f | ||
|
|
a3dc1b1957 | ||
|
|
6c82cfc089 | ||
|
|
9e0cdb22f1 | ||
|
|
3289b9b7a7 | ||
|
|
b00040c43c | ||
|
|
54acd0b0f0 | ||
|
|
1394258f37 | ||
|
|
2ac1364688 | ||
|
|
01978648fd | ||
|
|
8e0b9f495b | ||
|
|
aba1f9167a | ||
|
|
c9a0b2a818 | ||
|
|
2f7827ba8f | ||
|
|
bdc6e86e07 | ||
|
|
62849b7010 | ||
|
|
9d836fedbd | ||
|
|
f008263022 | ||
|
|
8fa03fee77 | ||
|
|
d29b709642 | ||
|
|
4a314a6f63 | ||
|
|
8edc2e4b14 | ||
|
|
d36539df06 | ||
|
|
e2ba45c35f | ||
|
|
f7f4bf0321 | ||
|
|
db7f4aa2cb | ||
|
|
dbff0164b3 | ||
|
|
0ea73d2da7 | ||
|
|
f8f17f48c5 | ||
|
|
35e3435f6e | ||
|
|
b3b922f177 | ||
|
|
e04b478050 | ||
|
|
77e1da40e2 | ||
|
|
980b33177b | ||
|
|
ede8a0235b | ||
|
|
7885a425d7 | ||
|
|
96fd80db13 | ||
|
|
347de3e218 | ||
|
|
78602a217f | ||
|
|
fc9a6dd09e | ||
|
|
44f0a4d1e7 | ||
|
|
fdb2aa81b7 | ||
|
|
9dce823cfd | ||
|
|
72491b3e40 | ||
|
|
75163325ae | ||
|
|
280fb4d928 | ||
|
|
89f657f073 | ||
|
|
aca498c2b0 | ||
|
|
d42b89bc3a | ||
|
|
d7cd1d2027 | ||
|
|
da8c4c2653 | ||
|
|
b02be234e1 | ||
|
|
52620c6b0e | ||
|
|
eea5fcc442 | ||
|
|
6e06512e0f | ||
|
|
f54b3527f2 | ||
|
|
d1f909005a | ||
|
|
c46d480adc | ||
|
|
d6f9d64d97 | ||
|
|
eb84a830df | ||
|
|
de981040b3 | ||
|
|
9355cca610 | ||
|
|
e41bc3fcbb | ||
|
|
9b4666dad5 | ||
|
|
5671a11b81 | ||
|
|
bd71b3252a | ||
|
|
e6fbee0981 | ||
|
|
da1c80d850 | ||
|
|
cc7fece309 | ||
|
|
0708dd495f | ||
|
|
19f1b39d6f | ||
|
|
b8ee7ab5b9 | ||
|
|
c460f6f15a | ||
|
|
6d4cac088e | ||
|
|
50b9329eba | ||
|
|
d4d1c45a55 | ||
|
|
5c603bd0fd | ||
|
|
beeb7483d8 | ||
|
|
68c28174d0 | ||
|
|
069fc48bf6 | ||
|
|
21c889baeb | ||
|
|
81375eb470 | ||
|
|
3101a8fe32 | ||
|
|
f1dd0fd7df | ||
|
|
4a93801c12 | ||
|
|
01dd7804b8 | ||
|
|
a9862b3006 | ||
|
|
1aaba5cabe | ||
|
|
e354b0a0cb | ||
|
|
376618cd8a | ||
|
|
60749e57f2 | ||
|
|
77a48e8cd4 | ||
|
|
98da3cf407 | ||
|
|
689dae1211 | ||
|
|
ab9d7619fc | ||
|
|
d4b75f6b68 | ||
|
|
9950865c39 | ||
|
|
dd376a239d | ||
|
|
860eeeea9b | ||
|
|
1ee6c3771f | ||
|
|
bebff0dab0 | ||
|
|
2daacc5cee | ||
|
|
79d5acbd01 | ||
|
|
793d826d9d | ||
|
|
b349479a49 | ||
|
|
ca21aed0a1 | ||
|
|
6c9fca2aa9 | ||
|
|
0e420d48ee | ||
|
|
09547f0f51 | ||
|
|
4556bd2acd | ||
|
|
35be9e805f | ||
|
|
b565c36963 | ||
|
|
df6605eaba | ||
|
|
0102ee092b | ||
|
|
71c9cfb028 | ||
|
|
784909ce16 | ||
|
|
8388ec4e35 | ||
|
|
fe6f0354f6 | ||
|
|
e30ba2f1c7 | ||
|
|
6568001c00 | ||
|
|
293e81f31e | ||
|
|
05eba60d84 | ||
|
|
904eb2d9f3 | ||
|
|
58321dd985 | ||
|
|
be8e5744e6 | ||
|
|
613510bce8 | ||
|
|
d5336ba136 | ||
|
|
37379a2974 | ||
|
|
c5c095690f | ||
|
|
358a7ba014 | ||
|
|
7e6881cf7d | ||
|
|
3e1412a1fb | ||
|
|
a8052d343c | ||
|
|
41b4686dd7 | ||
|
|
b84268d49c | ||
|
|
fc483706d3 | ||
|
|
49316b864b | ||
|
|
1f78e7a431 | ||
|
|
f9ecaa132f | ||
|
|
64a3c52f66 | ||
|
|
ab2c64cc76 | ||
|
|
1c6b442d32 | ||
|
|
f5309fc4ff | ||
|
|
103ae43f95 | ||
|
|
ad6aae13a4 | ||
|
|
4ec803a42a | ||
|
|
4c736ea8fc | ||
|
|
b16a755a0b | ||
|
|
e3383e9352 | ||
|
|
0cd9ab7755 | ||
|
|
168350cd98 | ||
|
|
387a8d26f9 | ||
|
|
46583e9057 | ||
|
|
3f91570483 | ||
|
|
ccaad53270 | ||
|
|
478887c62f | ||
|
|
394c536675 | ||
|
|
09b561f108 | ||
|
|
0aa1d3f447 | ||
|
|
c89254fd0f | ||
|
|
025e5f2b33 | ||
|
|
e4ab404780 | ||
|
|
9404093606 | ||
|
|
ad937c49aa | ||
|
|
d5191edf7f | ||
|
|
ace9fb5405 | ||
|
|
a14ce77b28 | ||
|
|
c127ace28a | ||
|
|
35a1fea90b | ||
|
|
b6a3289564 | ||
|
|
bfc2092dc5 | ||
|
|
7d4a2f773c | ||
|
|
f9dfd8aa3b | ||
|
|
63edc2e78b | ||
|
|
3d25d9c7d9 | ||
|
|
eb2784e8a2 | ||
|
|
cb7ecda9f0 | ||
|
|
675ceb2dd9 | ||
|
|
600f5afed3 | ||
|
|
6c55cdafa3 | ||
|
|
642d9fd2a5 | ||
|
|
4dc7c5649b | ||
|
|
ca582675e1 | ||
|
|
0f12082f5b | ||
|
|
ee04525097 | ||
|
|
55f33240f3 | ||
|
|
bbced3b4bb | ||
|
|
b62bb53d0e | ||
|
|
e6bb25317b | ||
|
|
e3864b5907 | ||
|
|
e280122b14 | ||
|
|
f2140f9446 | ||
|
|
036b58228c | ||
|
|
456450437f | ||
|
|
f578947ae3 | ||
|
|
a3cd349eaf | ||
|
|
653a0c2d71 | ||
|
|
6b4d4a25ce | ||
|
|
f3687109d5 | ||
|
|
0893b273b9 | ||
|
|
363087aa11 | ||
|
|
a10467b58a | ||
|
|
04552ff71b | ||
|
|
4d1fb6107f | ||
|
|
aa7be82a4d | ||
|
|
a559098fec | ||
|
|
1ed3356540 | ||
|
|
513dfcf4fe | ||
|
|
d003daee06 | ||
|
|
7901741bf1 | ||
|
|
71173cd57d | ||
|
|
a6bec53177 | ||
|
|
205c368fa1 | ||
|
|
6ede921731 | ||
|
|
8c9e22c127 | ||
|
|
6cfe737597 | ||
|
|
bb3bddabb5 | ||
|
|
6c1b7e008d | ||
|
|
4368ae3142 | ||
|
|
4662006119 | ||
|
|
761e4c7ff6 | ||
|
|
c972c60dbe | ||
|
|
cadbd7f3e6 | ||
|
|
3235b95f08 | ||
|
|
016325dd0a | ||
|
|
299bc62586 | ||
|
|
d91c1170ca | ||
|
|
c9a48eb464 | ||
|
|
4fa9d97e4d | ||
|
|
9cca14a5dc | ||
|
|
2b70757411 | ||
|
|
f1d260d878 | ||
|
|
12d4fa9b37 | ||
|
|
1e6fd9f2b4 | ||
|
|
d0db93cf1f | ||
|
|
4d55d8805a | ||
|
|
ad3abcd324 | ||
|
|
0c5369a1f0 | ||
|
|
ad5e7a0e6f | ||
|
|
5f65ad8c96 | ||
|
|
c5efb8159f | ||
|
|
b2979023ac | ||
|
|
bfa68ef6b2 | ||
|
|
0291a624cb | ||
|
|
0c75990d6e | ||
|
|
f69ab79ec8 | ||
|
|
145796f037 | ||
|
|
ed52955c6b | ||
|
|
7feb7301b2 | ||
|
|
91a385db98 | ||
|
|
a040fb89e7 | ||
|
|
f110dbd795 | ||
|
|
e66fd56852 | ||
|
|
7bd10c1ffe | ||
|
|
8b84b8ab8a | ||
|
|
d5ec46ace4 | ||
|
|
b51919f5b7 | ||
|
|
48b745cfc8 | ||
|
|
503cf3d097 | ||
|
|
6b8b56f859 | ||
|
|
9ed5e80eea | ||
|
|
9d2c72ad4f | ||
|
|
2138258fea | ||
|
|
9aeba3e41b | ||
|
|
80b31dc097 | ||
|
|
5b509dbc7b | ||
|
|
3c62577ee9 | ||
|
|
b86c65d31c | ||
|
|
45b127e7ac | ||
|
|
ffb13cc633 | ||
|
|
4f23c5d587 | ||
|
|
e467949a4a | ||
|
|
65417c5ad9 | ||
|
|
90c1d54464 | ||
|
|
a6af1a1d9c | ||
|
|
465d84b7e7 | ||
|
|
ebce7984c6 | ||
|
|
5f0c56bcf1 | ||
|
|
7e14f99c26 | ||
|
|
d0797fbc18 | ||
|
|
d80ecad03f | ||
|
|
d42bb58c33 | ||
|
|
8b7d311595 | ||
|
|
50eea26145 | ||
|
|
f585526c80 | ||
|
|
ef47dee4bf | ||
|
|
e334b6b6d2 | ||
|
|
58b7b01cb5 | ||
|
|
871a45dd0c | ||
|
|
f2babeaeda | ||
|
|
369e7fd178 | ||
|
|
adf22c19ae | ||
|
|
8f6ef8de48 | ||
|
|
265500c5c8 | ||
|
|
1942f0ceef | ||
|
|
346f5d4cce | ||
|
|
05a08506ae | ||
|
|
703370ebc5 | ||
|
|
4d47e6c0db | ||
|
|
535804a0ed | ||
|
|
d20f8fb893 | ||
|
|
ebfdd96cb2 | ||
|
|
045116551e | ||
|
|
409fc8f9c1 | ||
|
|
3a9445c6b3 | ||
|
|
2f7fad66a2 | ||
|
|
ebb9396274 | ||
|
|
cd0987f5b7 | ||
|
|
f8ac28964d | ||
|
|
3e82bedf46 | ||
|
|
fbd252b77c | ||
|
|
748f493f33 | ||
|
|
683df1c8d5 | ||
|
|
118173013f | ||
|
|
02e9337494 | ||
|
|
7a4694fc4e | ||
|
|
0a54b6dce9 | ||
|
|
caa132a236 | ||
|
|
4a6c0fda78 | ||
|
|
c408ed9fb1 | ||
|
|
a926119099 | ||
|
|
dd16e21562 | ||
|
|
7c0e1f1a08 | ||
|
|
cfce7d784e | ||
|
|
ba33c544bb | ||
|
|
6f87b03e3c | ||
|
|
1e31d4bdf6 | ||
|
|
176aa681f0 | ||
|
|
7f2bc83dbc | ||
|
|
e92602ba27 | ||
|
|
bc790b5145 | ||
|
|
602f7e2189 | ||
|
|
7455e40186 | ||
|
|
91e93a9684 | ||
|
|
c4e3a03fa5 | ||
|
|
4cdddfed8e | ||
|
|
b50659e137 | ||
|
|
beb94b6efc | ||
|
|
51668dffaa | ||
|
|
6201e84812 | ||
|
|
bc7659eb59 | ||
|
|
3f9d59c87a | ||
|
|
0fe825b89e | ||
|
|
46b849ab49 | ||
|
|
6e80f0ee90 | ||
|
|
85acf7645f | ||
|
|
a065d78675 | ||
|
|
b19138e82e | ||
|
|
8ed7155828 | ||
|
|
eeaab1897b | ||
|
|
6cc4da4cb8 | ||
|
|
0c13b95cdc | ||
|
|
68c640d7cb | ||
|
|
d94bc675e8 | ||
|
|
44922934f5 | ||
|
|
4c5f108321 | ||
|
|
458cbacb8f | ||
|
|
4caa27ae0e | ||
|
|
c06aa5be00 | ||
|
|
e6782428be | ||
|
|
1686346d53 | ||
|
|
101fc187f0 | ||
|
|
9ae0713cef | ||
|
|
b8fef67c69 | ||
|
|
94696973a0 | ||
|
|
396d6f6d4e | ||
|
|
a960d50579 | ||
|
|
4f9858e86d | ||
|
|
76ec04a6d9 | ||
|
|
a5609e1cf1 | ||
|
|
fd860dc552 | ||
|
|
4abe3731e3 | ||
|
|
e269cabe3e | ||
|
|
8c5632a869 | ||
|
|
2bf5a947b2 | ||
|
|
48d867b4a6 | ||
|
|
1e70fda69f | ||
|
|
696fcde800 | ||
|
|
3bedff0b3c | ||
|
|
c064f0a36a | ||
|
|
e374cfff80 | ||
|
|
a47b871131 | ||
|
|
82b9915b34 | ||
|
|
75c3f2a7ab | ||
|
|
f01c1c6b35 | ||
|
|
6ed4581f54 | ||
|
|
d42b80fd64 | ||
|
|
08c73d9734 | ||
|
|
6ca086a89a |
23
.gitattributes
vendored
23
.gitattributes
vendored
@@ -15,16 +15,13 @@
|
||||
# These should also not be modified by git.
|
||||
tests/basics/string_cr_conversion.py -text
|
||||
tests/basics/string_crlf_conversion.py -text
|
||||
stmhal/pybcdc.inf_template -text
|
||||
stmhal/usbd_* -text
|
||||
stmhal/boards/*/stm32f4xx_hal_conf.h -text
|
||||
stmhal/cmsis/** -text
|
||||
stmhal/hal/** -text
|
||||
stmhal/usbdev/** -text
|
||||
stmhal/usbhost/** -text
|
||||
cc3200/hal/aes.c -text
|
||||
cc3200/hal/aes.h -text
|
||||
cc3200/hal/des.c -text
|
||||
cc3200/hal/i2s.c -text
|
||||
cc3200/hal/i2s.h -text
|
||||
cc3200/version.h -text
|
||||
ports/stm32/pybcdc.inf_template -text
|
||||
ports/stm32/usbd_* -text
|
||||
ports/stm32/usbdev/** -text
|
||||
ports/stm32/usbhost/** -text
|
||||
ports/cc3200/hal/aes.c -text
|
||||
ports/cc3200/hal/aes.h -text
|
||||
ports/cc3200/hal/des.c -text
|
||||
ports/cc3200/hal/i2s.c -text
|
||||
ports/cc3200/hal/i2s.h -text
|
||||
ports/cc3200/version.h -text
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -9,7 +9,7 @@
|
||||
*.dis
|
||||
*.exe
|
||||
|
||||
# Packages
|
||||
# Packages
|
||||
############
|
||||
|
||||
# Logs and Databases
|
||||
|
||||
4
.gitmodules
vendored
4
.gitmodules
vendored
@@ -11,3 +11,7 @@
|
||||
[submodule "lib/berkeley-db-1.xx"]
|
||||
path = lib/berkeley-db-1.xx
|
||||
url = https://github.com/pfalcon/berkeley-db-1.xx
|
||||
[submodule "lib/stm32lib"]
|
||||
path = lib/stm32lib
|
||||
url = https://github.com/micropython/stm32lib
|
||||
branch = work-F4-1.13.1+F7-1.5.0+L4-1.3.0
|
||||
|
||||
50
.travis.yml
50
.travis.yml
@@ -19,48 +19,48 @@ before_script:
|
||||
- sudo apt-get install -y --force-yes gcc-arm-none-eabi
|
||||
# For teensy build
|
||||
- sudo apt-get install realpath
|
||||
# For coverage testing
|
||||
- sudo pip install cpp-coveralls
|
||||
# For coverage testing (upgrade is used to get latest urllib3 version)
|
||||
- sudo pip install --upgrade cpp-coveralls
|
||||
- gcc --version
|
||||
- arm-none-eabi-gcc --version
|
||||
- python3 --version
|
||||
|
||||
script:
|
||||
- make -C mpy-cross
|
||||
- make -C minimal CROSS=1 build/firmware.bin
|
||||
- ls -l minimal/build/firmware.bin
|
||||
- make -C ports/minimal CROSS=1 build/firmware.bin
|
||||
- ls -l ports/minimal/build/firmware.bin
|
||||
- tools/check_code_size.sh
|
||||
- mkdir -p ${HOME}/persist
|
||||
# Save new firmware for reference, but only if building a main branch, not a pull request
|
||||
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then cp minimal/build/firmware.bin ${HOME}/persist/; fi'
|
||||
- make -C unix deplibs
|
||||
- make -C unix
|
||||
- make -C unix nanbox
|
||||
- make -C bare-arm
|
||||
- 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=STM32F7DISC
|
||||
- make -C stmhal BOARD=STM32L476DISC
|
||||
- make -C teensy
|
||||
- make -C cc3200 BTARGET=application BTYPE=release
|
||||
- make -C cc3200 BTARGET=bootloader BTYPE=release
|
||||
- make -C windows CROSS_COMPILE=i686-w64-mingw32-
|
||||
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then cp ports/minimal/build/firmware.bin ${HOME}/persist/; fi'
|
||||
- make -C ports/unix deplibs
|
||||
- make -C ports/unix
|
||||
- make -C ports/unix nanbox
|
||||
- make -C ports/bare-arm
|
||||
- make -C ports/qemu-arm test
|
||||
- make -C ports/stm32
|
||||
- make -C ports/stm32 BOARD=PYBV11 MICROPY_PY_WIZNET5K=5200 MICROPY_PY_CC3K=1
|
||||
- make -C ports/stm32 BOARD=STM32F769DISC
|
||||
- make -C ports/stm32 BOARD=STM32L476DISC
|
||||
- make -C ports/teensy
|
||||
- make -C ports/cc3200 BTARGET=application BTYPE=release
|
||||
- make -C ports/cc3200 BTARGET=bootloader BTYPE=release
|
||||
- make -C ports/windows CROSS_COMPILE=i686-w64-mingw32-
|
||||
|
||||
# run tests without coverage info
|
||||
#- (cd tests && MICROPY_CPYTHON3=python3.4 ./run-tests)
|
||||
#- (cd tests && MICROPY_CPYTHON3=python3.4 ./run-tests --emit native)
|
||||
|
||||
# run tests with coverage info
|
||||
- make -C unix coverage
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests)
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests -d thread)
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests --emit native)
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../unix/micropython_coverage ./run-tests --via-mpy -d basics float)
|
||||
- make -C ports/unix coverage
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests)
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests -d thread)
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --emit native)
|
||||
- (cd tests && MICROPY_CPYTHON3=python3.4 MICROPY_MICROPYTHON=../ports/unix/micropython_coverage ./run-tests --via-mpy -d basics float)
|
||||
|
||||
# run coveralls coverage analysis (try to, even if some builds/tests failed)
|
||||
- (cd unix && coveralls --root .. --build-root . --gcov $(which gcov) --gcov-options '\-o build-coverage/' --include py --include extmod)
|
||||
- (cd ports/unix && coveralls --root ../.. --build-root . --gcov $(which gcov) --gcov-options '\-o build-coverage/' --include py --include extmod)
|
||||
|
||||
after_failure:
|
||||
- (cd tests && for exp in *.exp; do testbase=$(basename $exp .exp); echo -e "\nFAILURE $testbase"; diff -u $testbase.exp $testbase.out; done)
|
||||
- (grep "FAIL" qemu-arm/build/console.out)
|
||||
- (grep "FAIL" ports/qemu-arm/build/console.out)
|
||||
|
||||
@@ -26,6 +26,27 @@ 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
|
||||
=======================
|
||||
|
||||
@@ -52,7 +73,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
|
||||
@@ -114,3 +135,76 @@ 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
|
||||
|
||||
82
README.md
82
README.md
@@ -22,16 +22,22 @@ 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.
|
||||
|
||||
See the repository www.github.com/micropython/pyboard for the MicroPython
|
||||
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
|
||||
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.
|
||||
- unix/ -- a version of MicroPython that runs on Unix.
|
||||
- stmhal/ -- a version of MicroPython that runs on the PyBoard and similar
|
||||
- mpy-cross/ -- the MicroPython cross-compiler which is used to turn scripts
|
||||
into precompiled bytecode.
|
||||
- ports/unix/ -- a version of MicroPython that runs on Unix.
|
||||
- ports/stm32/ -- a version of MicroPython that runs on the PyBoard and similar
|
||||
STM32 boards (using ST's Cube HAL drivers).
|
||||
- minimal/ -- a minimal MicroPython port. Start with this if you want
|
||||
- ports/minimal/ -- a minimal MicroPython port. Start with this if you want
|
||||
to port MicroPython to another microcontroller.
|
||||
- tests/ -- test framework and test scripts.
|
||||
- docs/ -- user documentation in Sphinx reStructuredText format. Rendered
|
||||
@@ -39,13 +45,13 @@ Major components in this repository:
|
||||
to select needed board/port at the bottom left corner).
|
||||
|
||||
Additional components:
|
||||
- bare-arm/ -- a bare minimum version of MicroPython for ARM MCUs. Used
|
||||
- ports/bare-arm/ -- a bare minimum version of MicroPython for ARM MCUs. Used
|
||||
mostly to control code size.
|
||||
- teensy/ -- a version of MicroPython that runs on the Teensy 3.1
|
||||
- ports/teensy/ -- a version of MicroPython that runs on the Teensy 3.1
|
||||
(preliminary but functional).
|
||||
- pic16bit/ -- a version of MicroPython for 16-bit PIC microcontrollers.
|
||||
- cc3200/ -- a version of MicroPython that runs on the CC3200 from TI.
|
||||
- esp8266/ -- an experimental port for ESP8266 WiFi modules.
|
||||
- ports/pic16bit/ -- a version of MicroPython for 16-bit PIC microcontrollers.
|
||||
- ports/cc3200/ -- a version of MicroPython that runs on the CC3200 from TI.
|
||||
- ports/esp8266/ -- an experimental port for ESP8266 WiFi modules.
|
||||
- extmod/ -- additional (non-core) modules implemented in C.
|
||||
- tools/ -- various tools, including the pyboard.py module.
|
||||
- examples/ -- a few example Python scripts.
|
||||
@@ -53,7 +59,7 @@ Additional components:
|
||||
The subdirectories above may include READMEs with additional info.
|
||||
|
||||
"make" is used to build the components, or "gmake" on BSD-based systems.
|
||||
You will also need bash and Python (at least 2.7 or 3.3).
|
||||
You will also need bash, gcc, and Python (at least 2.7 or 3.3).
|
||||
|
||||
The Unix version
|
||||
----------------
|
||||
@@ -66,7 +72,8 @@ Alternatively, fallback implementation based on setjmp/longjmp can be used.
|
||||
|
||||
To build (see section below for required dependencies):
|
||||
|
||||
$ cd unix
|
||||
$ git submodule update --init
|
||||
$ cd ports/unix
|
||||
$ make axtls
|
||||
$ make
|
||||
|
||||
@@ -98,44 +105,49 @@ Standard library modules come from
|
||||
External dependencies
|
||||
---------------------
|
||||
|
||||
Building Unix version requires some dependencies installed. For
|
||||
Building MicroPython ports may require some dependencies installed.
|
||||
|
||||
For Unix port, `libffi` library and `pkg-config` tool are required. On
|
||||
Debian/Ubuntu/Mint derivative Linux distros, install `build-essential`
|
||||
(includes toolchain and make), `libffi-dev`, and `pkg-config` packages.
|
||||
|
||||
Other dependencies can be built together with MicroPython. Oftentimes,
|
||||
you need to do this to enable extra features or capabilities. To build
|
||||
Other dependencies can be built together with MicroPython. This may
|
||||
be required to enable extra features or capabilities, and in recent
|
||||
versions of MicroPython, these may be enabled by default. To build
|
||||
these additional dependencies, first fetch git submodules for them:
|
||||
|
||||
$ git submodule update --init
|
||||
|
||||
Use this same command to get the latest versions of dependencies, as
|
||||
they are updated from time to time. After that, in `unix/` dir, execute:
|
||||
Use the same command to get the latest versions of dependencies, as
|
||||
they are updated from time to time. After that, in the port directory
|
||||
(e.g. `ports/unix/`), execute:
|
||||
|
||||
$ make deplibs
|
||||
|
||||
This will build all available dependencies (regardless whether they
|
||||
are used or not). If you intend to build MicroPython with additional
|
||||
options (like cross-compiling), the same set of options should be passed
|
||||
to `make deplibs`. To actually enabled use of dependencies, edit
|
||||
`unix/mpconfigport.mk` file, which has inline descriptions of the options.
|
||||
For example, to build SSL module (required for `upip` tool described above),
|
||||
set `MICROPY_PY_USSL` to 1.
|
||||
to `make deplibs`. To actually enable/disable use of dependencies, edit
|
||||
`ports/unix/mpconfigport.mk` file, which has inline descriptions of the options.
|
||||
For example, to build SSL module (required for `upip` tool described above,
|
||||
and so enabled by dfeault), `MICROPY_PY_USSL` should be set to 1.
|
||||
|
||||
In `unix/mpconfigport.mk`, you can also disable some dependencies enabled
|
||||
by default, like FFI support, which requires libffi development files to
|
||||
be installed.
|
||||
For some ports, building required dependences is transparent, and happens
|
||||
automatically. They still need to be fetched with the git submodule command
|
||||
above.
|
||||
|
||||
The STM version
|
||||
---------------
|
||||
The STM32 version
|
||||
-----------------
|
||||
|
||||
The "stmhal" port requires an ARM compiler, arm-none-eabi-gcc, and associated
|
||||
bin-utils. For those using Arch Linux, you need arm-none-eabi-binutils and
|
||||
arm-none-eabi-gcc packages. Otherwise, try here:
|
||||
The "stm32" port requires an ARM compiler, arm-none-eabi-gcc, and associated
|
||||
bin-utils. For those using Arch Linux, you need arm-none-eabi-binutils,
|
||||
arm-none-eabi-gcc and arm-none-eabi-newlib packages. Otherwise, try here:
|
||||
https://launchpad.net/gcc-arm-embedded
|
||||
|
||||
To build:
|
||||
|
||||
$ cd stmhal
|
||||
$ git submodule update --init
|
||||
$ cd ports/stm32
|
||||
$ make
|
||||
|
||||
You then need to get your board into DFU mode. On the pyboard, connect the
|
||||
@@ -149,4 +161,14 @@ Then to flash the code via USB DFU to your device:
|
||||
This will use the included `tools/pydfu.py` script. If flashing the firmware
|
||||
does not work it may be because you don't have the correct permissions, and
|
||||
need to use `sudo make deploy`.
|
||||
See the README.md file in the stmhal/ directory for further details.
|
||||
See the README.md file in the ports/stm32/ directory for further details.
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
MicroPython is an open-source project and welcomes contributions. To be
|
||||
productive, please be sure to follow the
|
||||
[Contributors' Guidelines](https://github.com/micropython/micropython/wiki/ContributorGuidelines)
|
||||
and the [Code Conventions](https://github.com/micropython/micropython/blob/master/CODECONVENTIONS.md).
|
||||
Note that MicroPython is licenced under the MIT license, and all contributions
|
||||
should follow this license.
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
/*
|
||||
* This file is part of the Micro Python project, http://micropython.org/
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2013, 2014 Damien P. George
|
||||
* Copyright (c) 2015 Daniel Campora
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "py/mpstate.h"
|
||||
#include "mpexception.h"
|
||||
|
||||
|
||||
/******************************************************************************
|
||||
DECLARE PRIVATE FUNCTIONS
|
||||
******************************************************************************/
|
||||
STATIC void mpexception_set_user_interrupt (int chr, void *data);
|
||||
|
||||
/******************************************************************************
|
||||
DECLARE EXPORTED DATA
|
||||
******************************************************************************/
|
||||
const char mpexception_value_invalid_arguments[] = "invalid argument(s) value";
|
||||
const char mpexception_num_type_invalid_arguments[] = "invalid argument(s) num/type";
|
||||
const char mpexception_uncaught[] = "uncaught exception";
|
||||
|
||||
int user_interrupt_char = -1;
|
||||
|
||||
/******************************************************************************
|
||||
DECLARE PRIVATE DATA
|
||||
******************************************************************************/
|
||||
STATIC void *user_interrupt_data = NULL;
|
||||
|
||||
/******************************************************************************
|
||||
DEFINE PUBLIC FUNCTIONS
|
||||
******************************************************************************/
|
||||
|
||||
void mpexception_init0 (void) {
|
||||
// Create an exception object for interrupting through the stdin uart
|
||||
MP_STATE_PORT(mp_const_user_interrupt) = mp_obj_new_exception(&mp_type_KeyboardInterrupt);
|
||||
mpexception_set_user_interrupt (-1, MP_STATE_PORT(mp_const_user_interrupt));
|
||||
}
|
||||
|
||||
void mpexception_set_interrupt_char (int c) {
|
||||
if (c != -1) {
|
||||
mp_obj_exception_clear_traceback(MP_STATE_PORT(mp_const_user_interrupt));
|
||||
}
|
||||
mpexception_set_user_interrupt(c, MP_STATE_PORT(mp_const_user_interrupt));
|
||||
}
|
||||
|
||||
// Call this function to raise a pending exception during an interrupt.
|
||||
// It will try to raise the exception "softly" by setting the
|
||||
// mp_pending_exception variable hoping that the VM will notice it.
|
||||
void mpexception_nlr_jump (void *o) {
|
||||
if (MP_STATE_PORT(mp_pending_exception) == MP_OBJ_NULL) {
|
||||
MP_STATE_PORT(mp_pending_exception) = o;
|
||||
}
|
||||
}
|
||||
|
||||
void mpexception_keyboard_nlr_jump (void) {
|
||||
mpexception_nlr_jump (user_interrupt_data);
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
DEFINE PRIVATE FUNCTIONS
|
||||
******************************************************************************/
|
||||
|
||||
STATIC void mpexception_set_user_interrupt (int chr, void *data) {
|
||||
user_interrupt_char = chr;
|
||||
user_interrupt_data = data;
|
||||
}
|
||||
21
docs/conf.py
21
docs/conf.py
@@ -96,10 +96,9 @@ copyright = '2014-2017, Damien P. George, Paul Sokolovsky, and contributors'
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '1.9'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '1.9.1'
|
||||
# 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.3'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
@@ -113,11 +112,11 @@ 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']
|
||||
exclude_patterns = ['build', '.venv']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all
|
||||
# documents.
|
||||
#default_role = None
|
||||
default_role = 'any'
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
@@ -139,6 +138,12 @@ 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 ----------------------------------------------
|
||||
|
||||
@@ -246,6 +251,8 @@ 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
|
||||
@@ -315,7 +322,7 @@ texinfo_documents = [
|
||||
|
||||
|
||||
# Example configuration for intersphinx: refer to the Python standard library.
|
||||
intersphinx_mapping = {'http://docs.python.org/': None}
|
||||
intersphinx_mapping = {'python': ('http://docs.python.org/3', None)}
|
||||
|
||||
# Append the other ports' specific folders/files to the exclude pattern
|
||||
exclude_patterns.extend([port + '*' for port in ports if port != micropy_port])
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
MicroPython Differences from CPython
|
||||
.. _cpython_diffs:
|
||||
|
||||
MicroPython differences from CPython
|
||||
====================================
|
||||
|
||||
The operations listed in this section produce conflicting results in MicroPython when compared to standard Python.
|
||||
|
||||
@@ -116,9 +116,72 @@ 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 ``ntpdate.py`` module.
|
||||
the net using included ``ntptime.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()
|
||||
|
||||
|
||||
SSL/TLS limitations
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
ESP8266 uses `axTLS <http://axtls.sourceforge.net/>`_ library, which is one
|
||||
of the smallest TLS libraries with the compatible licensing. However, it
|
||||
also has some known issues/limitations:
|
||||
|
||||
1. No support for Diffie-Hellman (DH) key exchange and Elliptic-curve
|
||||
cryptography (ECC). This means it can't work with sites which force
|
||||
the use of these features (it works ok with classic RSA certifactes).
|
||||
2. Half-duplex communication nature. axTLS uses a single buffer for both
|
||||
sending and receiving, which leads to considerable memory saving and
|
||||
works well with protocols like HTTP. But there may be problems with
|
||||
protocols which don't follow classic request-response model.
|
||||
|
||||
Besides axTLS own limitations, the configuration used for MicroPython is
|
||||
highly optimized for code size, which leads to additional limitations
|
||||
(these may be lifted in the future):
|
||||
|
||||
3. Optimized RSA algorithms are not enabled, which may lead to slow
|
||||
SSL handshakes.
|
||||
4. Stored sessions are not supported (may allow faster repeated connections
|
||||
to the same site in some circumstances).
|
||||
|
||||
Besides axTLS specific limitations described above, there's another generic
|
||||
limitation with usage of TLS on the low-memory devices:
|
||||
|
||||
5. The TLS standard specifies the maximum length of the TLS record (unit
|
||||
of TLS communication, the entire record must be buffered before it can
|
||||
be processed) as 16KB. That's almost half of the available ESP8266 memory,
|
||||
and inside a more or less advanced application would be hard to allocate
|
||||
due to memory fragmentation issues. As a compromise, a smaller buffer is
|
||||
used, with the idea that the most interesting usage for SSL would be
|
||||
accessing various REST APIs, which usually require much smaller messages.
|
||||
The buffers size is on the order of 5KB, and is adjusted from time to
|
||||
time, taking as a reference being able to access https://google.com .
|
||||
The smaller buffer hower means that some sites can't be accessed using
|
||||
it, and it's not possible to stream large amounts of data.
|
||||
|
||||
@@ -223,6 +223,17 @@ and is accessed via the :ref:`machine.I2C <machine.I2C>` class::
|
||||
buf = bytearray(10) # create a buffer with 10 bytes
|
||||
i2c.writeto(0x3a, buf) # write the given buffer to the slave
|
||||
|
||||
Real time clock (RTC)
|
||||
---------------------
|
||||
|
||||
See :ref:`machine.RTC <machine.RTC>` ::
|
||||
|
||||
from machine import RTC
|
||||
|
||||
rtc = RTC()
|
||||
rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time
|
||||
rtc.datetime() # get date and time
|
||||
|
||||
Deep-sleep mode
|
||||
---------------
|
||||
|
||||
|
||||
@@ -50,12 +50,16 @@ From here, you have 3 main choices
|
||||
* Daily firmware builds for 1024kb modules and above.
|
||||
* Daily firmware builds for 512kb modules.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
Deploying the firmware
|
||||
----------------------
|
||||
@@ -161,7 +165,9 @@ 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
|
||||
@@ -176,8 +182,10 @@ 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.
|
||||
|
||||
|
||||
@@ -20,6 +20,20 @@ To set the colour of pixels use::
|
||||
>>> np[1] = (0, 128, 0) # set to green, half brightness
|
||||
>>> np[2] = (0, 0, 64) # set to blue, quarter brightness
|
||||
|
||||
For LEDs with more than 3 colours, such as RGBW pixels or RGBY pixels, the
|
||||
NeoPixel class takes a ``bpp`` parameter. To setup a NeoPixel object for an
|
||||
RGBW Pixel, do the following::
|
||||
|
||||
>>> import machine, neopixel
|
||||
>>> np = neopixel.NeoPixel(machine.Pin(4), 8, bpp=4)
|
||||
|
||||
In a 4-bpp mode, remember to use 4-tuples instead of 3-tuples to set the colour.
|
||||
For example to set the first three pixels use::
|
||||
|
||||
>>> np[0] = (255, 0, 0, 128) # Orange in an RGBY Setup
|
||||
>>> np[1] = (0, 255, 0, 128) # Yellow-green in an RGBY Setup
|
||||
>>> np[2] = (0, 0, 255, 128) # Green-blue in an RGBY Setup
|
||||
|
||||
Then use the ``write()`` method to output the colours to the LEDs::
|
||||
|
||||
>>> np.write()
|
||||
|
||||
@@ -22,7 +22,7 @@ processing power, at the expense of current consumption::
|
||||
160000000
|
||||
|
||||
You can change to the higher frequency just while your code does the heavy
|
||||
processing and then change back when its finished.
|
||||
processing and then change back when it's finished.
|
||||
|
||||
Deep-sleep mode
|
||||
---------------
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
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
|
||||
@@ -4,14 +4,9 @@ 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`
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
.. module:: array
|
||||
:synopsis: efficient arrays of numeric data
|
||||
|
||||
See `Python array <https://docs.python.org/3/library/array.html>`_ for more
|
||||
information.
|
||||
|see_cpython_module| :mod:`python:array`.
|
||||
|
||||
Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``,
|
||||
``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the
|
||||
|
||||
@@ -22,8 +22,14 @@ 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 section, etc.
|
||||
f = open("mydb", "w+b")
|
||||
# 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")
|
||||
|
||||
# Now open a database itself
|
||||
db = btree.open(f)
|
||||
@@ -33,6 +39,11 @@ 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"])
|
||||
|
||||
@@ -65,24 +76,28 @@ Example::
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. function:: open(stream, \*, flags=0, cachesize=0, pagesize=0, minkeypage=0)
|
||||
.. function:: open(stream, \*, flags=0, pagesize=0, cachesize=0, minkeypage=0)
|
||||
|
||||
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):
|
||||
|
||||
* `flags` - Currently unused.
|
||||
* `cachesize` - Suggested maximum memory cache size in bytes. For a
|
||||
* *flags* - Currently unused.
|
||||
* *pagesize* - Page size used for the nodes in BTree. Acceptable range
|
||||
is 512-65536. If 0, a port-specific default will be used, optimized for
|
||||
port's memory usage and/or performance.
|
||||
* *cachesize* - Suggested 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
|
||||
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
|
||||
Cache policy is as follows: entire cache is not allocated at once;
|
||||
instead, accessing a new page in database will allocate a memory buffer
|
||||
for it, until value specified by *cachesize* is reached. Then, these
|
||||
buffers will be managed using LRU (least recently used) policy. More
|
||||
buffers may still be allocated if needed (e.g., if a database contains
|
||||
big keys and/or values). Allocated cache buffers aren't reclaimed.
|
||||
* *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
|
||||
@@ -92,7 +107,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 streamw with which the database was opened,
|
||||
this does not close underlying stream 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).
|
||||
|
||||
@@ -101,10 +116,10 @@ Methods
|
||||
Flush any data in cache to the underlying stream.
|
||||
|
||||
.. method:: btree.__getitem__(key)
|
||||
.. method:: btree.get(key, default=None)
|
||||
.. method:: btree.__setitem__(key, val)
|
||||
.. method:: btree.__detitem__(key)
|
||||
.. method:: btree.__contains__(key)
|
||||
btree.get(key, default=None)
|
||||
btree.__setitem__(key, val)
|
||||
btree.__detitem__(key)
|
||||
btree.__contains__(key)
|
||||
|
||||
Standard dictionary methods.
|
||||
|
||||
@@ -114,20 +129,20 @@ Methods
|
||||
to get access to all keys in order.
|
||||
|
||||
.. method:: btree.keys([start_key, [end_key, [flags]]])
|
||||
.. method:: btree.values([start_key, [end_key, [flags]]])
|
||||
.. method:: btree.items([start_key, [end_key, [flags]]])
|
||||
btree.values([start_key, [end_key, [flags]]])
|
||||
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
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
Builtin Functions
|
||||
=================
|
||||
Builtin functions and exceptions
|
||||
================================
|
||||
|
||||
All builtin functions are described here. They are also available via
|
||||
``builtins`` module.
|
||||
All builtin functions and exceptions are described here. They are also
|
||||
available via ``builtins`` module.
|
||||
|
||||
Functions and types
|
||||
-------------------
|
||||
|
||||
.. function:: abs()
|
||||
|
||||
@@ -18,6 +21,8 @@ All builtin functions are described here. They are also available via
|
||||
|
||||
.. class:: bytes()
|
||||
|
||||
|see_cpython| `python:bytes`.
|
||||
|
||||
.. function:: callable()
|
||||
|
||||
.. function:: chr()
|
||||
@@ -144,3 +149,51 @@ All builtin functions are described here. They are also available via
|
||||
.. 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
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
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.
|
||||
- *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;
|
||||
permissible values are listed under Constants below. These set the
|
||||
number of bits used to encode a color value and the layout of these
|
||||
bits in *buffer*.
|
||||
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,12 +106,13 @@ 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.
|
||||
|
||||
This method works between FrameBuffer's utilising different formats, but the
|
||||
resulting colors may be unexpected due to the mismatch in color formats.
|
||||
This method works between FrameBuffer instances utilising different formats,
|
||||
but the resulting colors may be unexpected due to the mismatch in color
|
||||
formats.
|
||||
|
||||
Constants
|
||||
---------
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. module:: gc
|
||||
:synopsis: control the garbage collector
|
||||
|
||||
|see_cpython_module| :mod:`python:gc`.
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
@@ -24,6 +26,41 @@ 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.
|
||||
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.
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
.. _micropython_lib:
|
||||
|
||||
MicroPython libraries
|
||||
=====================
|
||||
|
||||
@@ -38,8 +40,7 @@ information pertaining to a specific port.
|
||||
|
||||
Beyond the built-in libraries described in this documentation, many more
|
||||
modules from the Python standard library, as well as further MicroPython
|
||||
extensions to it, can be found in the `micropython-lib repository
|
||||
<https://github.com/micropython/micropython-lib>`_.
|
||||
extensions to it, can be found in `micropython-lib`.
|
||||
|
||||
Python standard libraries and micro-libraries
|
||||
---------------------------------------------
|
||||
@@ -52,7 +53,7 @@ e.g. ``ujson`` instead of ``json``. This is to signify that such a module is
|
||||
micro-library, i.e. implements only a subset of CPython module functionality.
|
||||
By naming them differently, a user has a choice to write a Python-level module
|
||||
to extend functionality for better compatibility with CPython (indeed, this is
|
||||
what done by micropython-lib project mentioned above).
|
||||
what done by the `micropython-lib` project mentioned above).
|
||||
|
||||
On some embedded platforms, where it may be cumbersome to add Python-level
|
||||
wrapper modules to achieve naming compatibility with CPython, micro-modules
|
||||
@@ -72,16 +73,17 @@ 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
|
||||
@@ -97,16 +99,17 @@ 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
|
||||
@@ -120,12 +123,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
|
||||
@@ -142,12 +145,14 @@ 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
|
||||
|
||||
@@ -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 (ie 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 (i.e. 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
|
||||
.. data:: lcd160cr.LANDSCAPE
|
||||
.. data:: lcd160cr.PORTRAIT_UPSIDEDOWN
|
||||
.. data:: lcd160cr.LANDSCAPE_UPSIDEDOWN
|
||||
lcd160cr.LANDSCAPE
|
||||
lcd160cr.PORTRAIT_UPSIDEDOWN
|
||||
lcd160cr.LANDSCAPE_UPSIDEDOWN
|
||||
|
||||
orientation of the display, used by :meth:`LCD160CR.set_orient`
|
||||
Orientations of the display, used by :meth:`LCD160CR.set_orient`.
|
||||
|
||||
.. data:: lcd160cr.STARTUP_DECO_NONE
|
||||
.. data:: lcd160cr.STARTUP_DECO_MLOGO
|
||||
.. data:: lcd160cr.STARTUP_DECO_INFO
|
||||
lcd160cr.STARTUP_DECO_MLOGO
|
||||
lcd160cr.STARTUP_DECO_INFO
|
||||
|
||||
type of start-up decoration, can be or'd together, used by
|
||||
:meth:`LCD160CR.set_startup_deco`
|
||||
Types of start-up decoration, can be OR'ed together, used by
|
||||
:meth:`LCD160CR.set_startup_deco`.
|
||||
|
||||
@@ -37,16 +37,16 @@ Constructors
|
||||
|
||||
Construct and return a new I2C object using the following parameters:
|
||||
|
||||
- `id` identifies the particular I2C peripheral. The default
|
||||
- *id* identifies a 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``.
|
||||
|
||||
@@ -38,7 +38,7 @@ Methods
|
||||
|
||||
Resets the RTC to the time of January 1, 2015 and starts running it again.
|
||||
|
||||
.. method:: RTC.alarm(id, time, /*, repeat=False)
|
||||
.. method:: RTC.alarm(id, time, \*, repeat=False)
|
||||
|
||||
Set the RTC alarm. Time might be either a millisecond value to program the alarm to
|
||||
current time + time_in_ms in the future, or a datetimetuple. If the time passed is in
|
||||
|
||||
@@ -4,17 +4,44 @@
|
||||
class Signal -- control and sense external I/O devices
|
||||
======================================================
|
||||
|
||||
The Signal class is a simple extension of Pin class. Unlike Pin, which
|
||||
The Signal class is a simple extension of the `Pin` class. Unlike Pin, which
|
||||
can be only in "absolute" 0 and 1 states, a Signal can be in "asserted"
|
||||
(on) or "deasserted" (off) states, while being inverted (active-low) or
|
||||
not. Summing up, it adds logical inversion support to Pin functionality.
|
||||
not. In other words, it adds logical inversion support to Pin functionality.
|
||||
While this may seem a simple addition, it is exactly what is needed to
|
||||
support wide array of simple digital devices in a way portable across
|
||||
different boards, which is one of the major MicroPython goals. Regardless
|
||||
whether different users have an active-high or active-low LED, a normally
|
||||
open or normally closed relay - you can develop single, nicely looking
|
||||
of whether different users have an active-high or active-low LED, a normally
|
||||
open or normally closed relay - you can develop a single, nicely looking
|
||||
application which works with each of them, and capture hardware
|
||||
configuration differences in few lines on the config file of your app.
|
||||
configuration differences in few lines in the config file of your app.
|
||||
|
||||
Example::
|
||||
|
||||
from machine import Pin, Signal
|
||||
|
||||
# Suppose you have an active-high LED on pin 0
|
||||
led1_pin = Pin(0, Pin.OUT)
|
||||
# ... and active-low LED on pin 1
|
||||
led2_pin = Pin(1, Pin.OUT)
|
||||
|
||||
# Now to light up both of them using Pin class, you'll need to set
|
||||
# them to different values
|
||||
led1_pin.value(1)
|
||||
led2_pin.value(0)
|
||||
|
||||
# Signal class allows to abstract away active-high/active-low
|
||||
# difference
|
||||
led1 = Signal(led1_pin, invert=False)
|
||||
led2 = Signal(led2_pin, invert=True)
|
||||
|
||||
# Now lighting up them looks the same
|
||||
led1.value(1)
|
||||
led2.value(1)
|
||||
|
||||
# Even better:
|
||||
led1.on()
|
||||
led2.on()
|
||||
|
||||
Following is the guide when Signal vs Pin should be used:
|
||||
|
||||
@@ -33,11 +60,11 @@ architecture of MicroPython: Pin offers the lowest overhead, which may
|
||||
be important when bit-banging protocols. But Signal adds additional
|
||||
flexibility on top of Pin, at the cost of minor overhead (much smaller
|
||||
than if you implemented active-high vs active-low device differences in
|
||||
Python manually!). Also, Pin is low-level object which needs to be
|
||||
Python manually!). Also, Pin is a low-level object which needs to be
|
||||
implemented for each support board, while Signal is a high-level object
|
||||
which comes for free once Pin is implemented.
|
||||
|
||||
If in doubt, give the Signal a try! Once again, it is developed to save
|
||||
If in doubt, give the Signal a try! Once again, it is offered to save
|
||||
developers from the need to handle unexciting differences like active-low
|
||||
vs active-high signals, and allow other users to share and enjoy your
|
||||
application, instead of being frustrated by the fact that it doesn't
|
||||
|
||||
@@ -18,7 +18,7 @@ UART objects can be created and initialised using::
|
||||
|
||||
Supported parameters 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.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ damage.
|
||||
|
||||
.. _machine_callbacks:
|
||||
|
||||
A note of callbacks used by functions and class methods of ``machine`` module:
|
||||
A note of callbacks used by functions and class methods of :mod:`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:
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
|
||||
@@ -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 `micropython` module mainly so that scripts can be
|
||||
provided as part of the :mod:`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(fun, arg)
|
||||
.. function:: schedule(func, arg)
|
||||
|
||||
Schedule the function `fun` to be executed "very soon". The function
|
||||
is passed the value `arg` as its single argument. "very soon" means that
|
||||
Schedule the function *func* 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:
|
||||
|
||||
@@ -9,7 +9,7 @@ This module provides network drivers and routing configuration. To use this
|
||||
module, a MicroPython variant/build with network capabilities must be installed.
|
||||
Network drivers for specific hardware are available within this module and are
|
||||
used to configure hardware network interface(s). Network services provided
|
||||
by configured interfaces are then available for use via the :mod:`socket`
|
||||
by configured interfaces are then available for use via the :mod:`usocket`
|
||||
module.
|
||||
|
||||
For example::
|
||||
@@ -39,9 +39,9 @@ Common network adapter interface
|
||||
================================
|
||||
|
||||
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
|
||||
interface classes implemented by `MicroPython ports <MicroPython port>`
|
||||
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.
|
||||
|
||||
.. class:: AbstractNIC(id=None, ...)
|
||||
@@ -72,8 +72,7 @@ parameter should be `id`.
|
||||
connection parameters. For various medium types, there are different
|
||||
sets of predefined/recommended parameters, among them:
|
||||
|
||||
* WiFi: `bssid` keyword to connect by BSSID (MAC address) instead
|
||||
of access point name
|
||||
* WiFi: *bssid* keyword to connect to a specific BSSID (MAC address)
|
||||
|
||||
.. method:: disconnect()
|
||||
|
||||
@@ -118,7 +117,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
|
||||
``ifconfig()``). These include network-specific and hardware-specific
|
||||
`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
|
||||
@@ -170,11 +169,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::
|
||||
@@ -225,7 +224,9 @@ parameter should be `id`.
|
||||
==============
|
||||
|
||||
This class allows you to control WIZnet5x00 Ethernet adaptors based on
|
||||
the W5200 and W5500 chipsets (only W5200 tested).
|
||||
the W5200 and W5500 chipsets. The particular chipset that is supported
|
||||
by the firmware is selected at compile-time via the MICROPY_PY_WIZNET5K
|
||||
option.
|
||||
|
||||
Example usage::
|
||||
|
||||
@@ -256,10 +257,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::
|
||||
@@ -269,6 +270,11 @@ parameter should be `id`.
|
||||
Methods
|
||||
-------
|
||||
|
||||
.. method:: wiznet5k.isconnected()
|
||||
|
||||
Returns ``True`` if the physical Ethernet link is connected and up.
|
||||
Returns ``False`` otherwise.
|
||||
|
||||
.. method:: wiznet5k.ifconfig([(ip, subnet, gateway, dns)])
|
||||
|
||||
Get/set IP address, subnet mask, gateway and DNS.
|
||||
@@ -294,7 +300,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 +328,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
|
||||
-------
|
||||
@@ -333,9 +339,12 @@ parameter should be `id`.
|
||||
argument is passed. Otherwise, query current state if no argument is
|
||||
provided. Most other methods require active interface.
|
||||
|
||||
.. method:: wlan.connect(ssid, password)
|
||||
.. method:: wlan.connect(ssid=None, password=None, \*, bssid=None)
|
||||
|
||||
Connect to the specified wireless network, using the specified password.
|
||||
If *bssid* is given then the connection will be restricted to the
|
||||
access-point with that MAC address (the *ssid* must also be specified
|
||||
in this case).
|
||||
|
||||
.. method:: wlan.disconnect()
|
||||
|
||||
@@ -350,8 +359,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 +408,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::
|
||||
@@ -411,18 +420,19 @@ parameter should be `id`.
|
||||
print(ap.config('channel'))
|
||||
|
||||
Following are commonly supported parameters (availability of a specific parameter
|
||||
depends on network technology type, driver, and MicroPython port).
|
||||
depends on network technology type, driver, and `MicroPython port`).
|
||||
|
||||
========= ===========
|
||||
Parameter Description
|
||||
========= ===========
|
||||
mac MAC address (bytes)
|
||||
essid WiFi access point name (string)
|
||||
channel WiFi channel (integer)
|
||||
hidden Whether ESSID is hidden (boolean)
|
||||
authmode Authentication mode supported (enumeration, see module constants)
|
||||
password Access password (string)
|
||||
========= ===========
|
||||
============= ===========
|
||||
Parameter Description
|
||||
============= ===========
|
||||
mac MAC address (bytes)
|
||||
essid WiFi access point name (string)
|
||||
channel WiFi channel (integer)
|
||||
hidden Whether ESSID is hidden (boolean)
|
||||
authmode Authentication mode supported (enumeration, see module constants)
|
||||
password Access password (string)
|
||||
dhcp_hostname The DHCP hostname to use
|
||||
============= ===========
|
||||
|
||||
|
||||
|
||||
@@ -450,7 +460,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 +479,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 +504,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 +528,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 +566,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.
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.. currentmodule:: pyb
|
||||
.. _pyb.Accel:
|
||||
|
||||
class Accel -- accelerometer control
|
||||
====================================
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.. currentmodule:: pyb
|
||||
.. _pyb.CAN:
|
||||
|
||||
class CAN -- controller area network communication bus
|
||||
======================================================
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.. currentmodule:: pyb
|
||||
.. _pyb.LCD:
|
||||
|
||||
class LCD -- LCD control for the LCD touch-sensor pyskin
|
||||
========================================================
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.. currentmodule:: pyb
|
||||
.. _pyb.Switch:
|
||||
|
||||
class Switch -- switch object
|
||||
=============================
|
||||
@@ -8,7 +9,8 @@ A Switch object is used to control a push-button switch.
|
||||
Usage::
|
||||
|
||||
sw = pyb.Switch() # create a switch object
|
||||
sw() # get state (True if pressed, False otherwise)
|
||||
sw.value() # get state (True if pressed, False otherwise)
|
||||
sw() # shorthand notation to get the switch state
|
||||
sw.callback(f) # register a callback to be called when the
|
||||
# switch is pressed down
|
||||
sw.callback(None) # remove the callback
|
||||
@@ -34,6 +36,10 @@ 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.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.. currentmodule:: pyb
|
||||
.. _pyb.USB_HID:
|
||||
|
||||
class USB_HID -- USB Human Interface Device (HID)
|
||||
=================================================
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.. currentmodule:: pyb
|
||||
.. _pyb.USB_VCP:
|
||||
|
||||
class USB_VCP -- USB virtual comm port
|
||||
======================================
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
:mod:`select` -- wait for events on a set of streams
|
||||
========================================================================
|
||||
|
||||
.. module:: select
|
||||
:synopsis: wait for events on a set of streams
|
||||
|
||||
This module provides functions to wait for events on 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
|
||||
---------
|
||||
|
||||
.. function:: poll()
|
||||
|
||||
Create an instance of the Poll class.
|
||||
|
||||
.. function:: select(rlist, wlist, xlist[, timeout])
|
||||
|
||||
Wait for activity on a set of objects.
|
||||
|
||||
This function is provided for compatibility and is not efficient. Usage
|
||||
of :class:`Poll` is recommended instead.
|
||||
|
||||
.. _class: Poll
|
||||
|
||||
class ``Poll``
|
||||
--------------
|
||||
|
||||
Methods
|
||||
~~~~~~~
|
||||
|
||||
.. method:: poll.register(obj[, eventmask])
|
||||
|
||||
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``.
|
||||
|
||||
.. method:: poll.unregister(obj)
|
||||
|
||||
Unregister ``obj`` from polling.
|
||||
|
||||
.. method:: poll.modify(obj, eventmask)
|
||||
|
||||
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*`
|
||||
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.
|
||||
@@ -4,19 +4,21 @@
|
||||
.. 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
|
||||
@@ -24,9 +26,9 @@ 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.
|
||||
``traceback`` module can be found in `micropython-lib`.
|
||||
|
||||
Constants
|
||||
---------
|
||||
@@ -37,15 +39,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
|
||||
@@ -95,10 +97,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
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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).
|
||||
|
||||
@@ -17,7 +19,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)
|
||||
@@ -27,8 +29,12 @@ Functions
|
||||
|
||||
.. function:: a2b_base64(data)
|
||||
|
||||
Convert Base64-encoded data to binary representation. Returns bytes string.
|
||||
Decode base64-encoded data, ignoring invalid characters in the input.
|
||||
Conforms to `RFC 2045 s.6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_.
|
||||
Returns a bytes object.
|
||||
|
||||
.. function:: b2a_base64(data)
|
||||
|
||||
Encode binary data in Base64 format. Returns string.
|
||||
Encode binary data in base64 format, as in `RFC 3548
|
||||
<https://tools.ietf.org/html/rfc3548.html>`_. Returns the encoded data
|
||||
followed by a newline character, as a bytes object.
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
|
||||
34
docs/library/uerrno.rst
Normal file
34
docs/library/uerrno.rst
Normal file
@@ -0,0 +1,34 @@
|
||||
: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
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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:
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. module:: uos
|
||||
:synopsis: basic "operating system" services
|
||||
|
||||
|see_cpython_module| :mod:`python:os`.
|
||||
|
||||
The ``uos`` module contains functions for filesystem access and ``urandom``
|
||||
function.
|
||||
|
||||
@@ -22,15 +24,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])
|
||||
@@ -87,8 +89,22 @@ Functions
|
||||
Return a bytes object with n random bytes. Whenever possible, it is
|
||||
generated by the hardware random number generator.
|
||||
|
||||
.. function:: dupterm(stream_object)
|
||||
.. function:: dupterm(stream_object, index=0)
|
||||
|
||||
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.
|
||||
Duplicate or switch the MicroPython terminal (the REPL) on the given stream-like
|
||||
object. The *stream_object* argument must implement the ``readinto()`` and
|
||||
``write()`` methods. The stream should be in non-blocking mode and
|
||||
``readinto()`` should return ``None`` if there is no data available for reading.
|
||||
|
||||
After calling this function all terminal output is repeated on this stream,
|
||||
and any input that is available on the stream is passed on to the terminal input.
|
||||
|
||||
The *index* parameter should be a non-negative integer and specifies which
|
||||
duplication slot is set. A given port may implement more than one slot (slot 0
|
||||
will always be available) and in that case terminal input and output is
|
||||
duplicated on all the slots that are set.
|
||||
|
||||
If ``None`` is passed as the *stream_object* then duplication is cancelled on
|
||||
the slot given by *index*.
|
||||
|
||||
The function returns the previous stream-like object in the given slot.
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
:mod:`ure` -- regular expressions
|
||||
=================================
|
||||
:mod:`ure` -- simple 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).
|
||||
@@ -32,6 +34,12 @@ 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.
|
||||
|
||||
@@ -39,18 +47,18 @@ etc. are not supported.
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. function:: compile(regex)
|
||||
.. function:: compile(regex_str)
|
||||
|
||||
Compile regular expression, return ``regex`` object.
|
||||
Compile regular expression, return `regex <regex>` object.
|
||||
|
||||
.. function:: match(regex, string)
|
||||
.. function:: match(regex_str, string)
|
||||
|
||||
Match ``regex`` against ``string``. Match always happens from starting
|
||||
position in a string.
|
||||
Compile *regex_str* and match against *string*. Match always happens
|
||||
from starting position in a string.
|
||||
|
||||
.. function:: search(regex, string)
|
||||
.. function:: search(regex_str, string)
|
||||
|
||||
Search ``regex`` in a ``string``. Unlike ``match``, this will search
|
||||
Compile *regex_str* and search it in a *string*. Unlike `match`, this will search
|
||||
string for first position which matches regex (which still may be
|
||||
0 if regex is anchored).
|
||||
|
||||
@@ -59,24 +67,33 @@ 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)
|
||||
|
||||
.. method:: 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.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])
|
||||
|
||||
Only numeric groups are supported.
|
||||
Return matching (sub)string. *index* is 0 for entire match,
|
||||
1 and above for each capturing group. Only numeric groups are supported.
|
||||
|
||||
84
docs/library/uselect.rst
Normal file
84
docs/library/uselect.rst
Normal file
@@ -0,0 +1,84 @@
|
||||
:mod:`uselect` -- wait for events on a set of streams
|
||||
========================================================================
|
||||
|
||||
.. module:: uselect
|
||||
:synopsis: wait for events on a set of streams
|
||||
|
||||
|see_cpython_module| :mod:`python:select`.
|
||||
|
||||
This module provides functions to efficiently wait for events on multiple
|
||||
streams (select streams which are ready for operations).
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. function:: poll()
|
||||
|
||||
Create an instance of the Poll class.
|
||||
|
||||
.. function:: select(rlist, wlist, xlist[, timeout])
|
||||
|
||||
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.
|
||||
|
||||
.. _class: Poll
|
||||
|
||||
class ``Poll``
|
||||
--------------
|
||||
|
||||
Methods
|
||||
~~~~~~~
|
||||
|
||||
.. method:: poll.register(obj[, eventmask])
|
||||
|
||||
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``.
|
||||
|
||||
.. method:: poll.unregister(obj)
|
||||
|
||||
Unregister *obj* from polling.
|
||||
|
||||
.. method:: poll.modify(obj, eventmask)
|
||||
|
||||
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*``
|
||||
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=-1, flags=0)
|
||||
|
||||
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.
|
||||
|
||||
If *flags* is 1, one-shot behavior for events is employed: streams for
|
||||
which events happened, event mask will be automatically reset (equivalent
|
||||
to ``poll.modify(obj, 0)``), so new events for such a stream won't be
|
||||
processed until new mask is set with `poll.modify()`. This behavior is
|
||||
useful for asynchronous I/O schedulers.
|
||||
|
||||
.. admonition:: Difference to CPython
|
||||
:class: attention
|
||||
|
||||
This function is a MicroPython extension.
|
||||
@@ -5,43 +5,81 @@
|
||||
.. 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.
|
||||
|
||||
.. 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.
|
||||
|
||||
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, 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 ``socket.getaddrinfo()``.
|
||||
The native socket address format of the ``usocket`` module is an opaque data type
|
||||
returned by `getaddrinfo` function, which must be used to resolve textual address
|
||||
(including numeric addresses)::
|
||||
|
||||
sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1]
|
||||
# You must use getaddrinfo() even for numeric addresses
|
||||
sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1]
|
||||
# Now you can use that address
|
||||
sock.connect(addr)
|
||||
|
||||
Using `getaddrinfo` is the most efficient (both in terms of memory and processing
|
||||
power) and portable way to work with addresses.
|
||||
|
||||
However, ``socket`` module (note the difference with native MicroPython
|
||||
``usocket`` module described here) provides CPython-compatible way to specify
|
||||
addresses using tuples, as described below. Note that depending on a
|
||||
`MicroPython port`, ``socket`` module can be builtin or need to be
|
||||
installed from `micropython-lib` (as in the case of `MicroPython Unix port`),
|
||||
and some ports still accept only numeric addresses in the tuple format,
|
||||
and require to use `getaddrinfo` function to resolve domain names.
|
||||
|
||||
Summing up:
|
||||
|
||||
* Always use `getaddrinfo` when writing portable applications.
|
||||
* Tuple addresses described below can be used as a shortcut for
|
||||
quick hacks and interactive use, if your port supports them.
|
||||
|
||||
Tuple address format for ``socket`` module:
|
||||
|
||||
* IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with
|
||||
dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and
|
||||
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()`.
|
||||
* IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address*
|
||||
is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``,
|
||||
and *port* is an integer port number in the range 1-65535. *flowinfo*
|
||||
must be 0. *scopeid* is the interface scope identifier for link-local
|
||||
addresses. Note the domain names are not accepted as *ipv6_address*,
|
||||
they should be resolved first using `usocket.getaddrinfo()`. Availability
|
||||
of IPv6 support depends on a `MicroPython port`.
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. function:: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
|
||||
.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
|
||||
|
||||
Create a new socket using the given address family, socket type and protocol number.
|
||||
Create a new socket using the given address family, socket type and
|
||||
protocol number. Note that specifying *proto* in most cases is not
|
||||
required (and not recommended, as some MicroPython ports may omit
|
||||
``IPPROTO_*`` constants). Instead, *type* argument will select needed
|
||||
protocol automatically::
|
||||
|
||||
.. function:: socket.getaddrinfo(host, port)
|
||||
# Create STREAM TCP socket
|
||||
socket(AF_INET, SOCK_STREAM)
|
||||
# Create DGRAM UDP socket
|
||||
socket(AF_INET, SOCK_DGRAM)
|
||||
|
||||
.. function:: 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
|
||||
@@ -51,51 +89,73 @@ Functions
|
||||
|
||||
The following example shows how to connect to a given url::
|
||||
|
||||
s = socket.socket()
|
||||
s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1])
|
||||
s = usocket.socket()
|
||||
s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1])
|
||||
|
||||
.. 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
|
||||
detail which may change in the future.
|
||||
|
||||
.. function:: inet_ntop(af, bin_addr)
|
||||
|
||||
Convert a binary network address *bin_addr* of the given address family *af*
|
||||
to a textual representation::
|
||||
|
||||
>>> usocket.inet_ntop(usocket.AF_INET, b"\x7f\0\0\1")
|
||||
'127.0.0.1'
|
||||
|
||||
.. function:: inet_pton(af, txt_addr)
|
||||
|
||||
Convert a textual network address *txt_addr* of the given address family *af*
|
||||
to a binary representation::
|
||||
|
||||
>>> usocket.inet_pton(usocket.AF_INET, "1.2.3.4")
|
||||
b'\x01\x02\x03\x04'
|
||||
|
||||
Constants
|
||||
---------
|
||||
|
||||
.. data:: socket.AF_INET
|
||||
socket.AF_INET6
|
||||
.. data:: AF_INET
|
||||
AF_INET6
|
||||
|
||||
Address family types. Availability depends on a particular board.
|
||||
Address family types. Availability depends on a particular `MicroPython port`.
|
||||
|
||||
.. data:: socket.SOCK_STREAM
|
||||
socket.SOCK_DGRAM
|
||||
.. data:: SOCK_STREAM
|
||||
SOCK_DGRAM
|
||||
|
||||
Socket types.
|
||||
|
||||
.. data:: socket.IPPROTO_UDP
|
||||
socket.IPPROTO_TCP
|
||||
.. data:: IPPROTO_UDP
|
||||
IPPROTO_TCP
|
||||
|
||||
IP protocol numbers.
|
||||
IP protocol numbers. Availability depends on a particular `MicroPython port`.
|
||||
Note that you don't need to specify these in a call to `usocket.socket()`,
|
||||
because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and
|
||||
`SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants
|
||||
is as an argument to `setsockopt()`.
|
||||
|
||||
.. data:: socket.SOL_*
|
||||
.. data:: usocket.SOL_*
|
||||
|
||||
Socket option levels (an argument to ``setsockopt()``). The exact inventory depends on a board.
|
||||
Socket option levels (an argument to `setsockopt()`). The exact
|
||||
inventory depends on a `MicroPython port`.
|
||||
|
||||
.. data:: socket.SO_*
|
||||
.. data:: usocket.SO_*
|
||||
|
||||
Socket options (an argument to ``setsockopt()``). The exact inventory depends on a board.
|
||||
Socket options (an argument to `setsockopt()`). The exact
|
||||
inventory depends on a `MicroPython port`.
|
||||
|
||||
Constants specific to WiPy:
|
||||
|
||||
.. data:: socket.IPPROTO_SEC
|
||||
.. data:: IPPROTO_SEC
|
||||
|
||||
Special protocol value to create SSL-compatible socket.
|
||||
|
||||
@@ -105,21 +165,22 @@ class socket
|
||||
Methods
|
||||
-------
|
||||
|
||||
.. method:: socket.close
|
||||
.. method:: socket.close()
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
Sockets are automatically closed when they are garbage-collected, but it is recommended
|
||||
to close() them explicitly, or to use a with statement around them.
|
||||
to `close()` them explicitly as soon you finished working with 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.
|
||||
@@ -133,7 +194,7 @@ Methods
|
||||
|
||||
.. method:: socket.connect(address)
|
||||
|
||||
Connect to a remote socket at address.
|
||||
Connect to a remote socket at *address*.
|
||||
|
||||
.. method:: socket.send(bytes)
|
||||
|
||||
@@ -144,11 +205,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.
|
||||
|
||||
@@ -160,33 +221,51 @@ 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)
|
||||
|
||||
**Note**: Not every port supports this method, see below.
|
||||
|
||||
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.
|
||||
|
||||
Not every `MicroPython port` supports this method. A more portable and
|
||||
generic solution is to use `uselect.poll` object. This allows to wait on
|
||||
multiple objects at the same time (and not just on sockets, but on generic
|
||||
stream objects which support polling). Example::
|
||||
|
||||
# Instead of:
|
||||
s.settimeout(1.0) # time in seconds
|
||||
s.read(10) # may timeout
|
||||
|
||||
# Use:
|
||||
poller = uselect.poll()
|
||||
poller.register(s, uselect.POLLIN)
|
||||
res = poller.poll(1000) # time in milliseconds
|
||||
if not res:
|
||||
# s is still not ready for input, i.e. operation timed out
|
||||
|
||||
.. admonition:: Difference to CPython
|
||||
: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.
|
||||
|
||||
@@ -195,7 +274,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)``
|
||||
@@ -204,12 +283,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
|
||||
@@ -220,19 +299,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()
|
||||
|
||||
@@ -245,6 +324,16 @@ 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.
|
||||
|
||||
.. exception:: usocket.error
|
||||
|
||||
MicroPython does NOT have this exception.
|
||||
|
||||
.. 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.
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
@@ -11,9 +13,9 @@ facilities for network sockets, both client-side and server-side.
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None)
|
||||
.. function:: ussl.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
|
||||
@@ -21,12 +23,12 @@ Functions
|
||||
server-side SSL socket should be created from a normal socket returned from
|
||||
`accept()` on a non-SSL listening server socket.
|
||||
|
||||
Depending on the underlying module implementation for a particular board,
|
||||
some or all keyword arguments above may be not supported.
|
||||
Depending on the underlying module implementation in a particular
|
||||
`MicroPython port`, some or all keyword arguments above may be not supported.
|
||||
|
||||
.. warning::
|
||||
|
||||
Some implementations of ``ssl`` module do NOT validate server certificates,
|
||||
Some implementations of ``ussl`` module do NOT validate server certificates,
|
||||
which makes an SSL connection established prone to man-in-the-middle attacks.
|
||||
|
||||
Exceptions
|
||||
@@ -39,8 +41,8 @@ Exceptions
|
||||
Constants
|
||||
---------
|
||||
|
||||
.. data:: ssl.CERT_NONE
|
||||
ssl.CERT_OPTIONAL
|
||||
ssl.CERT_REQUIRED
|
||||
.. data:: ussl.CERT_NONE
|
||||
ussl.CERT_OPTIONAL
|
||||
ussl.CERT_REQUIRED
|
||||
|
||||
Supported values for `cert_reqs` parameter.
|
||||
Supported values for *cert_reqs* parameter.
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
.. module:: ustruct
|
||||
:synopsis: pack and unpack primitive data types
|
||||
|
||||
See `Python struct <https://docs.python.org/3/library/struct.html>`_ for more
|
||||
information.
|
||||
|see_cpython_module| :mod:`python:struct`.
|
||||
|
||||
Supported size/byte order prefixes: ``@``, ``<``, ``>``, ``!``.
|
||||
|
||||
@@ -18,26 +17,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.
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
.. 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.
|
||||
|
||||
@@ -57,10 +59,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)
|
||||
|
||||
@@ -73,30 +75,32 @@ Functions
|
||||
.. function:: ticks_ms()
|
||||
|
||||
Returns an increasing millisecond counter with an arbitrary reference point, that
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -111,13 +115,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::
|
||||
@@ -136,23 +140,25 @@ Functions
|
||||
|
||||
.. function:: ticks_diff(ticks1, ticks2)
|
||||
|
||||
Measure ticks difference between values returned from ``ticks_ms()``, ``ticks_us()``,
|
||||
or ``ticks_cpu()`` functions. The argument order is the same as for subtraction
|
||||
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
|
||||
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* 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
|
||||
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
|
||||
@@ -164,10 +170,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()
|
||||
@@ -175,8 +181,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()
|
||||
@@ -192,8 +198,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 .
|
||||
|
||||
|
||||
@@ -205,8 +211,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
|
||||
|
||||
@@ -4,13 +4,35 @@
|
||||
.. module:: uzlib
|
||||
:synopsis: zlib decompression
|
||||
|
||||
This modules allows to decompress binary data compressed with DEFLATE
|
||||
algorithm (commonly used in zlib library and gzip archiver). Compression
|
||||
|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
|
||||
is not yet implemented.
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. function:: decompress(data)
|
||||
.. function:: decompress(data, wbits=0, bufsize=0)
|
||||
|
||||
Return decompressed data as bytes.
|
||||
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.
|
||||
|
||||
@@ -3,7 +3,7 @@ MicroPython license information
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013-2015 Damien P. George, and others
|
||||
Copyright (c) 2013-2017 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
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
General information about the pyboard
|
||||
=====================================
|
||||
|
||||
.. contents::
|
||||
|
||||
Local filesystem and SD card
|
||||
----------------------------
|
||||
|
||||
@@ -67,3 +69,12 @@ 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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -39,17 +39,32 @@ Use the :mod:`time <utime>` module::
|
||||
start = time.ticks_ms() # get value of millisecond counter
|
||||
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
|
||||
|
||||
LEDs
|
||||
----
|
||||
Internal LEDs
|
||||
-------------
|
||||
|
||||
See :ref:`pyb.LED <pyb.LED>`. ::
|
||||
|
||||
from pyb import LED
|
||||
|
||||
led = LED(1) # red led
|
||||
led = LED(1) # 1=red, 2=green, 3=yellow, 4=blue
|
||||
led.toggle()
|
||||
led.on()
|
||||
led.off()
|
||||
|
||||
# LEDs 3 and 4 support PWM intensity (0-255)
|
||||
LED(4).intensity() # get intensity
|
||||
LED(4).intensity(128) # set intensity to half
|
||||
|
||||
Internal switch
|
||||
---------------
|
||||
|
||||
See :ref:`pyb.Switch <pyb.Switch>`. ::
|
||||
|
||||
from pyb import Switch
|
||||
|
||||
sw = Switch()
|
||||
sw.value() # returns True or False
|
||||
sw.callback(lambda: pyb.LED(1).toggle())
|
||||
|
||||
Pins and GPIO
|
||||
-------------
|
||||
@@ -99,6 +114,17 @@ See :ref:`pyb.Timer <pyb.Timer>`. ::
|
||||
tim.freq(0.5) # 0.5 Hz
|
||||
tim.callback(lambda t: pyb.LED(1).toggle())
|
||||
|
||||
RTC (real time clock)
|
||||
---------------------
|
||||
|
||||
See :ref:`pyb.RTC <pyb.RTC>` ::
|
||||
|
||||
from pyb import RTC
|
||||
|
||||
rtc = RTC()
|
||||
rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time
|
||||
rtc.datetime() # get date and time
|
||||
|
||||
PWM (pulse width modulation)
|
||||
----------------------------
|
||||
|
||||
@@ -167,3 +193,25 @@ See :ref:`pyb.I2C <pyb.I2C>`. ::
|
||||
i2c.recv(5, 0x42) # receive 5 bytes from slave
|
||||
i2c.mem_read(2, 0x42, 0x10) # read 2 bytes from slave 0x42, slave memory 0x10
|
||||
i2c.mem_write('xy', 0x42, 0x10) # write 2 bytes to slave 0x42, slave memory 0x10
|
||||
|
||||
CAN bus (controller area network)
|
||||
---------------------------------
|
||||
|
||||
See :ref:`pyb.CAN <pyb.CAN>`. ::
|
||||
|
||||
from pyb import CAN
|
||||
|
||||
can = CAN(1, CAN.LOOPBACK)
|
||||
can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126))
|
||||
can.send('message!', 123) # send a message with id 123
|
||||
can.recv(0) # receive message on FIFO 0
|
||||
|
||||
Internal accelerometer
|
||||
----------------------
|
||||
|
||||
See :ref:`pyb.Accel <pyb.Accel>`. ::
|
||||
|
||||
from pyb import Accel
|
||||
|
||||
accel = Accel()
|
||||
print(accel.x(), accel.y(), accel.z(), accel.tilt())
|
||||
|
||||
@@ -69,4 +69,30 @@ Then you can do::
|
||||
>>> f = wave.open('test.wav')
|
||||
>>> dac.write_timed(f.readframes(f.getnframes()), f.getframerate())
|
||||
|
||||
This should play the WAV file.
|
||||
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.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
.. _tutorial-index:
|
||||
|
||||
MicroPython tutorial
|
||||
====================
|
||||
MicroPython tutorial for the pyboard
|
||||
====================================
|
||||
|
||||
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
|
||||
|
||||
@@ -60,10 +60,10 @@ One problem you might find is that if you stop the script and then start it agai
|
||||
for l in leds:
|
||||
l.off()
|
||||
|
||||
The Fourth Special LED
|
||||
----------------------
|
||||
The Special LEDs
|
||||
----------------
|
||||
|
||||
The blue LED is special. As well as turning it on and off, you can control the intensity using the intensity() method. This takes a number between 0 and 255 that determines how bright it is. The following script makes the blue LED gradually brighter then turns it off again. ::
|
||||
The yellow and blue LEDs are special. As well as turning them on and off, you can control their intensity using the intensity() method. This takes a number between 0 and 255 that determines how bright it is. The following script makes the blue LED gradually brighter then turns it off again. ::
|
||||
|
||||
led = pyb.LED(4)
|
||||
intensity = 0
|
||||
@@ -72,4 +72,4 @@ The blue LED is special. As well as turning it on and off, you can control the i
|
||||
led.intensity(intensity)
|
||||
pyb.delay(20)
|
||||
|
||||
You can call intensity() on the other LEDs but they can only be off or on. 0 sets them off and any other number up to 255 turns them on.
|
||||
You can call intensity() on LEDs 1 and 2 but they can only be off or on. 0 sets them off and any other number up to 255 turns them on.
|
||||
|
||||
@@ -15,4 +15,4 @@ It's as simple as::
|
||||
if uart.any():
|
||||
usb.write(uart.read(256))
|
||||
|
||||
pass_through(pyb.USB_VCP(), pyb.UART(1, 9600))
|
||||
pass_through(pyb.USB_VCP(), pyb.UART(1, 9600, timeout=0))
|
||||
|
||||
@@ -15,12 +15,18 @@ the name ``pyb`` does not exist.
|
||||
|
||||
With the switch object you can get its status::
|
||||
|
||||
>>> sw()
|
||||
>>> sw.value()
|
||||
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
|
||||
----------------
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
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
|
||||
|
||||
@@ -7,14 +7,6 @@ MicroPython documentation and references
|
||||
pyboard/general.rst
|
||||
pyboard/tutorial/index.rst
|
||||
library/index.rst
|
||||
pyboard/hardware/index.rst
|
||||
reference/index.rst
|
||||
genrst/index.rst
|
||||
license.rst
|
||||
pyboard_contents.rst
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
||||
@@ -119,10 +119,10 @@ symbols that have already been defined, e.g. ``1 << BIT``.
|
||||
|
||||
Where there is a substantial volume of constant data and the platform supports
|
||||
execution from Flash, RAM may be saved as follows. The data should be located in
|
||||
Python modules and frozen as bytecode. The data must be defined as ``bytes``
|
||||
objects. The compiler 'knows' that ``bytes`` objects are immutable and ensures
|
||||
Python modules and frozen as bytecode. The data must be defined as `bytes`
|
||||
objects. The compiler 'knows' that `bytes` objects are immutable and ensures
|
||||
that the objects remain in flash memory rather than being copied to RAM. The
|
||||
``ustruct`` module can assist in converting between ``bytes`` types and other
|
||||
`ustruct` module can assist in converting between `bytes` types and other
|
||||
Python built-in types.
|
||||
|
||||
When considering the implications of frozen bytecode, note that in Python
|
||||
@@ -185,7 +185,7 @@ a file it will save RAM if this is done in a piecemeal fashion. Rather than
|
||||
creating a large string object, create a substring and feed it to the stream
|
||||
before dealing with the next.
|
||||
|
||||
The best way to create dynamic strings is by means of the string ``format``
|
||||
The best way to create dynamic strings is by means of the string `format`
|
||||
method:
|
||||
|
||||
.. code::
|
||||
@@ -226,26 +226,26 @@ function ``foo()``:
|
||||
foo(b'\1\2\xff')
|
||||
|
||||
In the first call a tuple of integers is created in RAM. The second efficiently
|
||||
creates a ``bytes`` object consuming the minimum amount of RAM. If the module
|
||||
were frozen as bytecode, the ``bytes`` object would reside in flash.
|
||||
creates a `bytes` object consuming the minimum amount of RAM. If the module
|
||||
were frozen as bytecode, the `bytes` object would reside in flash.
|
||||
|
||||
**Strings Versus Bytes**
|
||||
|
||||
Python3 introduced Unicode support. This introduced a distinction between a
|
||||
string and an array of bytes. MicroPython ensures that Unicode strings take no
|
||||
additional space so long as all characters in the string are ASCII (i.e. have
|
||||
a value < 126). If values in the full 8-bit range are required ``bytes`` and
|
||||
``bytearray`` objects can be used to ensure that no additional space will be
|
||||
required. Note that most string methods (e.g. ``strip()``) apply also to ``bytes``
|
||||
a value < 126). If values in the full 8-bit range are required `bytes` and
|
||||
`bytearray` objects can be used to ensure that no additional space will be
|
||||
required. Note that most string methods (e.g. :meth:`str.strip()`) apply also to `bytes`
|
||||
instances so the process of eliminating Unicode can be painless.
|
||||
|
||||
.. code::
|
||||
|
||||
s = 'the quick brown fox' # A string instance
|
||||
b = b'the quick brown fox' # a bytes instance
|
||||
s = 'the quick brown fox' # A string instance
|
||||
b = b'the quick brown fox' # A bytes instance
|
||||
|
||||
Where it is necessary to convert between strings and bytes the string ``encode``
|
||||
and the bytes ``decode`` methods can be used. Note that both strings and bytes
|
||||
Where it is necessary to convert between strings and bytes the :meth:`str.encode`
|
||||
and the :meth:`bytes.decode` methods can be used. Note that both strings and bytes
|
||||
are immutable. Any operation which takes as input such an object and produces
|
||||
another implies at least one RAM allocation to produce the result. In the
|
||||
second line below a new bytes object is allocated. This would also occur if ``foo``
|
||||
@@ -258,10 +258,10 @@ were a string.
|
||||
|
||||
**Runtime compiler execution**
|
||||
|
||||
The Python keywords ``eval`` and ``exec`` invoke the compiler at runtime, which
|
||||
requires significant amounts of RAM. Note that the ``pickle`` library employs
|
||||
``exec``. It may be more RAM efficient to use the ``json`` library for object
|
||||
serialisation.
|
||||
The Python funcitons `eval` and `exec` invoke the compiler at runtime, which
|
||||
requires significant amounts of RAM. Note that the `pickle` library from
|
||||
`micropython-lib` employs `exec`. It may be more RAM efficient to use the
|
||||
`ujson` library for object serialisation.
|
||||
|
||||
**Storing strings in flash**
|
||||
|
||||
@@ -279,7 +279,7 @@ After importing the modules, execute:
|
||||
|
||||
Then copy and paste all the Q(xxx) lines into a text editor. Check for and
|
||||
remove lines which are obviously invalid. Open the file qstrdefsport.h which
|
||||
will be found in stmhal (or the equivalent directory for the architecture in
|
||||
will be found in ports/stm32 (or the equivalent directory for the architecture in
|
||||
use). Copy and paste the corrected lines at the end of the file. Save the file,
|
||||
rebuild and flash the firmware. The outcome can be checked by importing the
|
||||
modules and again issuing:
|
||||
@@ -300,7 +300,7 @@ from a fixed size pool known as the heap. When the object goes out of scope (in
|
||||
other words becomes inaccessible to code) the redundant object is known as
|
||||
"garbage". A process known as "garbage collection" (GC) reclaims that memory,
|
||||
returning it to the free heap. This process runs automatically, however it can
|
||||
be invoked directly by issuing ``gc.collect()``.
|
||||
be invoked directly by issuing `gc.collect()`.
|
||||
|
||||
The discourse on this is somewhat involved. For a 'quick fix' issue the
|
||||
following periodically:
|
||||
@@ -332,7 +332,7 @@ Reporting
|
||||
~~~~~~~~~
|
||||
|
||||
A number of library functions are available to report on memory allocation and
|
||||
to control GC. These are to be found in the ``gc`` and ``micropython`` modules.
|
||||
to control GC. These are to be found in the `gc` and `micropython` modules.
|
||||
The following example may be pasted at the REPL (``ctrl e`` to enter paste mode,
|
||||
``ctrl d`` to run it).
|
||||
|
||||
@@ -357,17 +357,17 @@ The following example may be pasted at the REPL (``ctrl e`` to enter paste mode,
|
||||
|
||||
Methods employed above:
|
||||
|
||||
* ``gc.collect()`` Force a garbage collection. See footnote.
|
||||
* ``micropython.mem_info()`` Print a summary of RAM utilisation.
|
||||
* ``gc.mem_free()`` Return the free heap size in bytes.
|
||||
* ``gc.mem_alloc()`` Return the number of bytes currently allocated.
|
||||
* `gc.collect()` Force a garbage collection. See footnote.
|
||||
* `micropython.mem_info()` Print a summary of RAM utilisation.
|
||||
* `gc.mem_free()` Return the free heap size in bytes.
|
||||
* `gc.mem_alloc()` Return the number of bytes currently allocated.
|
||||
* ``micropython.mem_info(1)`` Print a table of heap utilisation (detailed below).
|
||||
|
||||
The numbers produced are dependent on the platform, but it can be seen that
|
||||
declaring the function uses a small amount of RAM in the form of bytecode
|
||||
emitted by the compiler (the RAM used by the compiler has been reclaimed).
|
||||
Running the function uses over 10KiB, but on return ``a`` is garbage because it
|
||||
is out of scope and cannot be referenced. The final ``gc.collect()`` recovers
|
||||
is out of scope and cannot be referenced. The final `gc.collect()` recovers
|
||||
that memory.
|
||||
|
||||
The final output produced by ``micropython.mem_info(1)`` will vary in detail but
|
||||
@@ -394,7 +394,7 @@ line of the heap dump represents 0x400 bytes or 1KiB of RAM.
|
||||
Control of Garbage Collection
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A GC can be demanded at any time by issuing ``gc.collect()``. It is advantageous
|
||||
A GC can be demanded at any time by issuing `gc.collect()`. It is advantageous
|
||||
to do this at intervals, firstly to pre-empt fragmentation and secondly for
|
||||
performance. A GC can take several milliseconds but is quicker when there is
|
||||
little work to do (about 1ms on the Pyboard). An explicit call can minimise that
|
||||
@@ -417,7 +417,7 @@ occupied.
|
||||
In general modules should instantiate data objects at runtime using constructors
|
||||
or other initialisation functions. The reason is that if this occurs on
|
||||
initialisation the compiler may be starved of RAM when subsequent modules are
|
||||
imported. If modules do instantiate data on import then ``gc.collect()`` issued
|
||||
imported. If modules do instantiate data on import then `gc.collect()` issued
|
||||
after the import will ameliorate the problem.
|
||||
|
||||
String Operations
|
||||
@@ -444,13 +444,13 @@ RAM usage and speed.
|
||||
|
||||
Where variables are required whose size is neither a byte nor a machine word
|
||||
there are standard libraries which can assist in storing these efficiently and
|
||||
in performing conversions. See the ``array``, ``ustruct`` and ``uctypes``
|
||||
in performing conversions. See the `array`, `ustruct` and `uctypes`
|
||||
modules.
|
||||
|
||||
Footnote: gc.collect() return value
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
On Unix and Windows platforms the ``gc.collect()`` method returns an integer
|
||||
On Unix and Windows platforms the `gc.collect()` method returns an integer
|
||||
which signifies the number of distinct memory regions that were reclaimed in the
|
||||
collection (more precisely, the number of heads that were turned into frees). For
|
||||
efficiency reasons bare metal ports do not return this value.
|
||||
|
||||
105
docs/reference/glossary.rst
Normal file
105
docs/reference/glossary.rst
Normal file
@@ -0,0 +1,105 @@
|
||||
Glossary
|
||||
========
|
||||
|
||||
.. glossary::
|
||||
|
||||
baremetal
|
||||
A system without (full-fledged) OS, like an :term:`MCU`. When
|
||||
running on a baremetal system, MicroPython effectively becomes
|
||||
its user-facing OS with a command interpreter (REPL).
|
||||
|
||||
board
|
||||
A PCB board. Oftentimes, the term is used to denote a particular
|
||||
model of an :term:`MCU` system. Sometimes, it is used to actually
|
||||
refer to :term:`MicroPython port` to a particular board (and then
|
||||
may also refer to "boardless" ports like
|
||||
:term:`Unix port <MicroPython Unix port>`).
|
||||
|
||||
CPython
|
||||
CPython is the reference implementation of Python programming
|
||||
language, and the most well-known one, which most of the people
|
||||
run. It is however one of many implementations (among which
|
||||
Jython, IronPython, PyPy, and many more, including MicroPython).
|
||||
As there is no formal specification of the Python language, only
|
||||
CPython documentation, it is not always easy to draw a line
|
||||
between Python the language and CPython its particular
|
||||
implementation. This however leaves more freedom for other
|
||||
implementations. For example, MicroPython does a lot of things
|
||||
differently than CPython, while still aspiring to be a Python
|
||||
language implementation.
|
||||
|
||||
GPIO
|
||||
General-purpose input/output. The simplest means to control
|
||||
electrical signals. With GPIO, user can configure hardware
|
||||
signal pin to be either input or output, and set or get
|
||||
its digital signal value (logical "0" or "1"). MicroPython
|
||||
abstracts GPIO access using :class:`machine.Pin` and :class:`machine.Signal`
|
||||
classes.
|
||||
|
||||
GPIO port
|
||||
A group of :term:`GPIO` pins, usually based on hardware
|
||||
properties of these pins (e.g. controllable by the same
|
||||
register).
|
||||
|
||||
MCU
|
||||
Microcontroller. Microcontrollers usually have much less resources
|
||||
than a full-fledged computing system, but smaller, cheaper and
|
||||
require much less power. MicroPython is designed to be small and
|
||||
optimized enough to run on an average modern microcontroller.
|
||||
|
||||
micropython-lib
|
||||
MicroPython is (usually) distributed as a single executable/binary
|
||||
file with just few builtin modules. There is no extensive standard
|
||||
library comparable with :term:`CPython`. Instead, there is a related, but
|
||||
separate project
|
||||
`micropython-lib <https://github.com/micropython/micropython-lib>`_
|
||||
which provides implementations for many modules from CPython's
|
||||
standard library. However, large subset of these modules require
|
||||
POSIX-like environment (Linux, MacOS, Windows may be partially
|
||||
supported), and thus would work or make sense only with
|
||||
`MicroPython Unix port`. Some subset of modules is however usable
|
||||
for `baremetal` ports too.
|
||||
|
||||
Unlike monolithic :term:`CPython` stdlib, micropython-lib modules
|
||||
are intended to be installed individually - either using manual
|
||||
copying or using :term:`upip`.
|
||||
|
||||
MicroPython port
|
||||
MicroPython supports different :term:`boards <board>`, RTOSes,
|
||||
and OSes, and can be relatively easily adapted to new systems.
|
||||
MicroPython with support for a particular system is called a
|
||||
"port" to that system. Different ports may have widely different
|
||||
functionality. This documentation is intended to be a reference
|
||||
of the generic APIs available across different ports ("MicroPython
|
||||
core"). Note that some ports may still omit some APIs described
|
||||
here (e.g. due to resource constraints). Any such differences,
|
||||
and port-specific extensions beyond MicroPython core functionality,
|
||||
would be described in the separate port-specific documentation.
|
||||
|
||||
MicroPython Unix port
|
||||
Unix port is one of the major :term:`MicroPython ports <MicroPython port>`.
|
||||
It is intended to run on POSIX-compatible operating systems, like
|
||||
Linux, MacOS, FreeBSD, Solaris, etc. It also serves as the basis
|
||||
of Windows port. The importance of Unix port lies in the fact
|
||||
that while there are many different :term:`boards <board>`, so
|
||||
two random users unlikely have the same board, almost all modern
|
||||
OSes have some level of POSIX compatibility, so Unix port serves
|
||||
as a kind of "common ground" to which any user can have access.
|
||||
So, Unix port is used for initial prototyping, different kinds
|
||||
of testing, development of machine-independent features, etc.
|
||||
All users of MicroPython, even those which are interested only
|
||||
in running MicroPython on :term:`MCU` systems, are recommended
|
||||
to be familiar with Unix (or Windows) port, as it is important
|
||||
productivity helper and a part of normal MicroPython workflow.
|
||||
|
||||
port
|
||||
Either :term:`MicroPython port` or :term:`GPIO port`. If not clear
|
||||
from context, it's recommended to use full specification like one
|
||||
of the above.
|
||||
|
||||
upip
|
||||
(Literally, "micro pip"). A package manage for MicroPython, inspired
|
||||
by :term:`CPython`'s pip, but much smaller and with reduced functionality.
|
||||
upip runs both on :term:`Unix port <MicroPython Unix port>` and on
|
||||
:term:`baremetal` ports (those which offer filesystem and networking
|
||||
support).
|
||||
@@ -1,17 +1,25 @@
|
||||
The MicroPython language
|
||||
========================
|
||||
|
||||
MicroPython aims to implement the Python 3.4 standard, and most of
|
||||
the features of MicroPython are identical to those described by the
|
||||
documentation at
|
||||
`docs.python.org <https://docs.python.org/3.4/reference/index.html>`_.
|
||||
MicroPython aims to implement the Python 3.4 standard (with selected
|
||||
features from later versions) with respect to language syntax, and most
|
||||
of the features of MicroPython are identical to those described by the
|
||||
"Language Reference" documentation at
|
||||
`docs.python.org <https://docs.python.org/3/reference/index.html>`_.
|
||||
|
||||
Differences to standard Python as well as additional features of
|
||||
MicroPython are described in the sections here.
|
||||
The MicroPython standard library is described in the
|
||||
:ref:`corresponding chapter <micropython_lib>`. The :ref:`cpython_diffs`
|
||||
chapter describes differences between MicroPython and CPython (which
|
||||
mostly concern standard library and types, but also some language-level
|
||||
features).
|
||||
|
||||
This chapter describes features and peculiarities of MicroPython
|
||||
implementation and the best practices to use them.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
glossary.rst
|
||||
repl.rst
|
||||
isr_rules.rst
|
||||
speed_python.rst
|
||||
|
||||
@@ -21,6 +21,7 @@ This summarises the points detailed below and lists the principal recommendation
|
||||
|
||||
* Keep the code as short and simple as possible.
|
||||
* Avoid memory allocation: no appending to lists or insertion into dictionaries, no floating point.
|
||||
* Consider using ``micropython.schedule`` to work around the above constraint.
|
||||
* Where an ISR returns multiple bytes use a pre-allocated ``bytearray``. If multiple integers are to be
|
||||
shared between an ISR and the main program consider an array (``array.array``).
|
||||
* Where data is shared between the main program and an ISR, consider disabling interrupts prior to accessing
|
||||
@@ -79,7 +80,7 @@ example causes two LED's to flash at different rates.
|
||||
self.led.toggle()
|
||||
|
||||
red = Foo(pyb.Timer(4, freq=1), pyb.LED(1))
|
||||
greeen = Foo(pyb.Timer(2, freq=0.8), pyb.LED(2))
|
||||
green = Foo(pyb.Timer(2, freq=0.8), pyb.LED(2))
|
||||
|
||||
In this example the ``red`` instance associates timer 4 with LED 1: when a timer 4 interrupt occurs ``red.cb()``
|
||||
is called causing LED 1 to change state. The ``green`` instance operates similarly: a timer 2 interrupt
|
||||
@@ -158,6 +159,26 @@ On platforms with hardware floating point (such as the Pyboard) the inline ARM T
|
||||
round this limitation. This is because the processor stores float values in a machine word; values can be shared
|
||||
between the ISR and main program code via an array of floats.
|
||||
|
||||
Using micropython.schedule
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This function enables an ISR to schedule a callback for execution "very soon". The callback is queued for
|
||||
execution which will take place at a time when the heap is not locked. Hence it can create Python objects
|
||||
and use floats. The callback is also guaranteed to run at a time when the main program has completed any
|
||||
update of Python objects, so the callback will not encounter partially updated objects.
|
||||
|
||||
Typical usage is to handle sensor hardware. The ISR acquires data from the hardware and enables it to
|
||||
issue a further interrupt. It then schedules a callback to process the data.
|
||||
|
||||
Scheduled callbacks should comply with the principles of interrupt handler design outlined below. This is to
|
||||
avoid problems resulting from I/O activity and the modification of shared data which can arise in any code
|
||||
which pre-empts the main program loop.
|
||||
|
||||
Execution time needs to be considered in relation to the frequency with which interrupts can occur. If an
|
||||
interrupt occurs while the previous callback is executing, a further instance of the callback will be queued
|
||||
for execution; this will run after the current instance has completed. A sustained high interrupt repetition
|
||||
rate therefore carries a risk of unconstrained queue growth and eventual failure with a ``RuntimeError``.
|
||||
|
||||
Exceptions
|
||||
----------
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
Maximising Python Speed
|
||||
=======================
|
||||
Maximising MicroPython Speed
|
||||
============================
|
||||
|
||||
.. contents::
|
||||
|
||||
This tutorial describes ways of improving the performance of MicroPython code.
|
||||
Optimisations involving other languages are covered elsewhere, namely the use
|
||||
of modules written in C and the MicroPython inline ARM Thumb-2 assembler.
|
||||
of modules written in C and the MicroPython inline assembler.
|
||||
|
||||
The process of developing high performance code comprises the following stages
|
||||
which should be performed in the order listed.
|
||||
@@ -17,6 +19,7 @@ Optimisation steps:
|
||||
* Improve the efficiency of the Python code.
|
||||
* Use the native code emitter.
|
||||
* Use the viper code emitter.
|
||||
* Use hardware-specific optimisations.
|
||||
|
||||
Designing for speed
|
||||
-------------------
|
||||
@@ -50,7 +53,7 @@ once only and not permitted to grow in size. This implies that the object persis
|
||||
for the duration of its use: typically it will be instantiated in a class constructor
|
||||
and used in various methods.
|
||||
|
||||
This is covered in further detail :ref:`Controlling garbage collection <gc>` below.
|
||||
This is covered in further detail :ref:`Controlling garbage collection <controlling_gc>` below.
|
||||
|
||||
Buffers
|
||||
~~~~~~~
|
||||
@@ -60,8 +63,8 @@ used for communication with a device. A typical driver will create the buffer in
|
||||
constructor and use it in its I/O methods which will be called repeatedly.
|
||||
|
||||
The MicroPython libraries typically provide support for pre-allocated buffers. For
|
||||
example, objects which support stream interface (e.g., file or UART) provide ``read()``
|
||||
method which allocate new buffer for read data, but also a ``readinto()`` method
|
||||
example, objects which support stream interface (e.g., file or UART) provide `read()`
|
||||
method which allocates new buffer for read data, but also a `readinto()` method
|
||||
to read data into an existing buffer.
|
||||
|
||||
Floating Point
|
||||
@@ -79,14 +82,14 @@ Arrays
|
||||
~~~~~~
|
||||
|
||||
Consider the use of the various types of array classes as an alternative to lists.
|
||||
The ``array`` module supports various element types with 8-bit elements supported
|
||||
by Python's built in ``bytes`` and ``bytearray`` classes. These data structures all store
|
||||
The `array` module supports various element types with 8-bit elements supported
|
||||
by Python's built in `bytes` and `bytearray` classes. These data structures all store
|
||||
elements in contiguous memory locations. Once again to avoid memory allocation in critical
|
||||
code these should be pre-allocated and passed as arguments or as bound objects.
|
||||
|
||||
When passing slices of objects such as ``bytearray`` instances, Python creates
|
||||
When passing slices of objects such as `bytearray` instances, Python creates
|
||||
a copy which involves allocation of the size proportional to the size of slice.
|
||||
This can be alleviated using a ``memoryview`` object. ``memoryview`` itself
|
||||
This can be alleviated using a `memoryview` object. `memoryview` itself
|
||||
is allocated on heap, but is a small, fixed-size object, regardless of the size
|
||||
of slice it points too.
|
||||
|
||||
@@ -97,7 +100,7 @@ of slice it points too.
|
||||
mv = memoryview(ba) # small object is allocated
|
||||
func(mv[30:2000]) # a pointer to memory is passed
|
||||
|
||||
A ``memoryview`` can only be applied to objects supporting the buffer protocol - this
|
||||
A `memoryview` can only be applied to objects supporting the buffer protocol - this
|
||||
includes arrays but not lists. Small caveat is that while memoryview object is live,
|
||||
it also keeps alive the original buffer object. So, a memoryview isn't a universal
|
||||
panacea. For instance, in the example above, if you are done with 10K buffer and
|
||||
@@ -105,11 +108,11 @@ just need those bytes 30:2000 from it, it may be better to make a slice, and let
|
||||
the 10K buffer go (be ready for garbage collection), instead of making a
|
||||
long-living memoryview and keeping 10K blocked for GC.
|
||||
|
||||
Nonetheless, ``memoryview`` is indispensable for advanced preallocated buffer
|
||||
management. ``.readinto()`` method discussed above puts data at the beginning
|
||||
Nonetheless, `memoryview` is indispensable for advanced preallocated buffer
|
||||
management. `readinto()` method discussed above puts data at the beginning
|
||||
of buffer and fills in entire buffer. What if you need to put data in the
|
||||
middle of existing buffer? Just create a memoryview into the needed section
|
||||
of buffer and pass it to ``.readinto()``.
|
||||
of buffer and pass it to `readinto()`.
|
||||
|
||||
Identifying the slowest section of code
|
||||
---------------------------------------
|
||||
@@ -118,8 +121,7 @@ This is a process known as profiling and is covered in textbooks and
|
||||
(for standard Python) supported by various software tools. For the type of
|
||||
smaller embedded application likely to be running on MicroPython platforms
|
||||
the slowest function or method can usually be established by judicious use
|
||||
of the timing ``ticks`` group of functions documented
|
||||
`here <http://docs.micropython.org/en/latest/pyboard/library/time.html>`_.
|
||||
of the timing ``ticks`` group of functions documented in `utime`.
|
||||
Code execution time can be measured in ms, us, or CPU cycles.
|
||||
|
||||
The following enables any function or method to be timed by adding an
|
||||
@@ -130,9 +132,9 @@ The following enables any function or method to be timed by adding an
|
||||
def timed_function(f, *args, **kwargs):
|
||||
myname = str(f).split(' ')[1]
|
||||
def new_func(*args, **kwargs):
|
||||
t = time.ticks_us()
|
||||
t = utime.ticks_us()
|
||||
result = f(*args, **kwargs)
|
||||
delta = time.ticks_diff(time.ticks_us(), t)
|
||||
delta = utime.ticks_diff(utime.ticks_us(), t)
|
||||
print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
|
||||
return result
|
||||
return new_func
|
||||
@@ -170,7 +172,7 @@ by caching the object in a local variable:
|
||||
This avoids the need repeatedly to look up ``self.ba`` and ``obj_display.framebuffer``
|
||||
in the body of the method ``bar()``.
|
||||
|
||||
.. _gc:
|
||||
.. _controlling_gc:
|
||||
|
||||
Controlling garbage collection
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
@@ -182,7 +184,7 @@ process known as garbage collection reclaims the memory used by these redundant
|
||||
objects and the allocation is then tried again - a process which can take several
|
||||
milliseconds.
|
||||
|
||||
There are benefits in pre-empting this by periodically issuing ``gc.collect()``.
|
||||
There may be benefits in pre-empting this by periodically issuing `gc.collect()`.
|
||||
Firstly doing a collection before it is actually required is quicker - typically on the
|
||||
order of 1ms if done frequently. Secondly you can determine the point in code
|
||||
where this time is used rather than have a longer delay occur at random points,
|
||||
@@ -190,34 +192,11 @@ possibly in a speed critical section. Finally performing collections regularly
|
||||
can reduce fragmentation in the heap. Severe fragmentation can lead to
|
||||
non-recoverable allocation failures.
|
||||
|
||||
Accessing hardware directly
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
This comes into the category of more advanced programming and involves some knowledge
|
||||
of the target MCU. Consider the example of toggling an output pin on the Pyboard. The
|
||||
standard approach would be to write
|
||||
|
||||
.. code:: python
|
||||
|
||||
mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin
|
||||
|
||||
This involves the overhead of two calls to the ``Pin`` instance's ``value()``
|
||||
method. This overhead can be eliminated by performing a read/write to the relevant bit
|
||||
of the chip's GPIO port output data register (odr). To facilitate this the ``stm``
|
||||
module provides a set of constants providing the addresses of the relevant registers.
|
||||
A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED -
|
||||
can be performed as follows:
|
||||
|
||||
.. code:: python
|
||||
|
||||
BIT14 = const(1 << 14)
|
||||
stm.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14
|
||||
|
||||
The Native code emitter
|
||||
-----------------------
|
||||
|
||||
This causes the MicroPython compiler to emit ARM native opcodes rather than
|
||||
bytecode. It covers the bulk of the Python language so most functions will require
|
||||
This causes the MicroPython compiler to emit native CPU opcodes rather than
|
||||
bytecode. It covers the bulk of the MicroPython functionality, so most functions will require
|
||||
no adaptation (but see below). It is invoked by means of a function decorator:
|
||||
|
||||
.. code:: python
|
||||
@@ -276,7 +255,7 @@ Viper provides pointer types to assist the optimiser. These comprise
|
||||
* ``ptr32`` Points to a 32 bit machine word.
|
||||
|
||||
The concept of a pointer may be unfamiliar to Python programmers. It has similarities
|
||||
to a Python ``memoryview`` object in that it provides direct access to data stored in memory.
|
||||
to a Python `memoryview` object in that it provides direct access to data stored in memory.
|
||||
Items are accessed using subscript notation, but slices are not supported: a pointer can return
|
||||
a single item only. Its purpose is to provide fast random access to data stored in contiguous
|
||||
memory locations - such as data stored in objects which support the buffer protocol, and
|
||||
@@ -330,3 +309,34 @@ The following example illustrates the use of a ``ptr16`` cast to toggle pin X1 `
|
||||
A detailed technical description of the three code emitters may be found
|
||||
on Kickstarter here `Note 1 <https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/664832>`_
|
||||
and here `Note 2 <https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/665145>`_
|
||||
|
||||
Accessing hardware directly
|
||||
---------------------------
|
||||
|
||||
.. note::
|
||||
|
||||
Code examples in this section are given for the Pyboard. The techniques
|
||||
described however may be applied to other MicroPython ports too.
|
||||
|
||||
This comes into the category of more advanced programming and involves some knowledge
|
||||
of the target MCU. Consider the example of toggling an output pin on the Pyboard. The
|
||||
standard approach would be to write
|
||||
|
||||
.. code:: python
|
||||
|
||||
mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin
|
||||
|
||||
This involves the overhead of two calls to the `Pin` instance's :meth:`~machine.Pin.value()`
|
||||
method. This overhead can be eliminated by performing a read/write to the relevant bit
|
||||
of the chip's GPIO port output data register (odr). To facilitate this the ``stm``
|
||||
module provides a set of constants providing the addresses of the relevant registers.
|
||||
A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED -
|
||||
can be performed as follows:
|
||||
|
||||
.. code:: python
|
||||
|
||||
import machine
|
||||
import stm
|
||||
|
||||
BIT14 = const(1 << 14)
|
||||
machine.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14
|
||||
|
||||
9
docs/templates/replace.inc
vendored
Normal file
9
docs/templates/replace.inc
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
.. comment: This file is intended for global "replace" definitions.
|
||||
|
||||
.. |see_cpython| replace:: See CPython documentation:
|
||||
|
||||
.. |see_cpython_module| replace::
|
||||
|
||||
*This module implements a subset of the corresponding* `CPython` *module,
|
||||
as described below. For more information, refer to the original
|
||||
CPython documentation:*
|
||||
@@ -57,16 +57,6 @@
|
||||
<a class="biglink" href="{{ pathto("reference/index") }}">Language Reference</a><br/>
|
||||
<span class="linkdescr">information about MicroPython specific language features</span>
|
||||
</p>
|
||||
{% if port == "pyboard" %}
|
||||
<p class="biglink">
|
||||
<a class="biglink" href="{{ pathto(port + "/hardware/index") }}">The {{ port }} hardware</a><br/>
|
||||
<span class="linkdescr">schematics, dimensions and component datasheets</span>
|
||||
</p>
|
||||
<p class="biglink">
|
||||
<a class="biglink" href="http://micropython.org/resources/Micro-Python-Windows-setup.pdf">Guide for {{ port_name }} on Windows (PDF)</a><br/>
|
||||
<span class="linkdescr">including DFU programming</span>
|
||||
</p>
|
||||
{% endif %}
|
||||
<p class="biglink">
|
||||
<a class="biglink" href="{{ pathto("license") }}">License</a><br/>
|
||||
<span class="linkdescr">MicroPython license information</span>
|
||||
@@ -88,7 +78,11 @@
|
||||
</td>
|
||||
<td width="40%" style="padding-left:2em;">
|
||||
<p class="biglink">
|
||||
<a class="biglink" href="{{ pathto(port + "_contents") }}">Table of contents</a><br/>
|
||||
<a class="biglink" href="{{ pathto("reference/glossary") }}">Glossary</a><br/>
|
||||
<span class="linkdescr">MicroPython terms explained</span>
|
||||
</p>
|
||||
<p class="biglink">
|
||||
<a class="biglink" href="{{ pathto(port + "_index") }}">Table of contents</a><br/>
|
||||
<span class="linkdescr">a list of all sections and subsections</span>
|
||||
</p>
|
||||
</td></tr>
|
||||
@@ -112,12 +106,6 @@
|
||||
<a class="biglink" href="https://github.com/micropython">MicroPython on GitHub</a><br/>
|
||||
<span class="linkdescr">contribute to the source code on GitHub</span>
|
||||
</p>
|
||||
{% if port == "wipy" %}
|
||||
<p class="biglink">
|
||||
<a class="biglink" href="http://wipy.io">The WiPy homepage</a><br/>
|
||||
<span class="linkdescr">the official WiPy site</span>
|
||||
</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr></table>
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
MicroPython documentation contents
|
||||
==================================
|
||||
|
||||
.. toctree::
|
||||
|
||||
library/index.rst
|
||||
reference/index.rst
|
||||
genrst/index.rst
|
||||
license.rst
|
||||
@@ -4,13 +4,6 @@ MicroPython documentation and references
|
||||
.. toctree::
|
||||
|
||||
library/index.rst
|
||||
reference/index.rst
|
||||
genrst/index.rst
|
||||
license.rst
|
||||
unix_contents.rst
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
MicroPython documentation contents
|
||||
==================================
|
||||
|
||||
.. toctree::
|
||||
|
||||
wipy/quickref.rst
|
||||
wipy/general.rst
|
||||
wipy/tutorial/index.rst
|
||||
library/index.rst
|
||||
reference/index.rst
|
||||
genrst/index.rst
|
||||
license.rst
|
||||
@@ -7,13 +7,6 @@ MicroPython documentation and references
|
||||
wipy/general.rst
|
||||
wipy/tutorial/index.rst
|
||||
library/index.rst
|
||||
reference/index.rst
|
||||
genrst/index.rst
|
||||
license.rst
|
||||
wipy_contents.rst
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
||||
@@ -34,8 +34,6 @@
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "py/nlr.h"
|
||||
#include "py/obj.h"
|
||||
#include "py/runtime.h"
|
||||
#include "pin.h"
|
||||
#include "led.h"
|
||||
|
||||
@@ -40,7 +40,7 @@ STATIC mp_obj_t dht_readinto(mp_obj_t pin_in, mp_obj_t buf_in) {
|
||||
mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE);
|
||||
|
||||
if (bufinfo.len < 5) {
|
||||
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "buffer too small"));
|
||||
mp_raise_ValueError("buffer too small");
|
||||
}
|
||||
|
||||
// issue start command
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
#ifndef MICROPY_INCLUDED_DRIVERS_DHT_DHT_H
|
||||
#define MICROPY_INCLUDED_DRIVERS_DHT_DHT_H
|
||||
|
||||
#include "py/obj.h"
|
||||
|
||||
MP_DECLARE_CONST_FUN_OBJ_2(dht_readinto_obj);
|
||||
|
||||
#endif // MICROPY_INCLUDED_DRIVERS_DHT_DHT_H
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
|
||||
|
||||
from micropython import const
|
||||
import time
|
||||
import framebuf
|
||||
|
||||
|
||||
@@ -32,8 +31,21 @@ class SSD1306:
|
||||
self.external_vcc = external_vcc
|
||||
self.pages = self.height // 8
|
||||
self.buffer = bytearray(self.pages * self.width)
|
||||
self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MVLSB)
|
||||
self.poweron()
|
||||
fb = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)
|
||||
self.framebuf = fb
|
||||
# Provide methods for accessing FrameBuffer graphics primitives. This is a
|
||||
# workround because inheritance from a native class is currently unsupported.
|
||||
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
|
||||
self.fill = fb.fill
|
||||
self.pixel = fb.pixel
|
||||
self.hline = fb.hline
|
||||
self.vline = fb.vline
|
||||
self.line = fb.line
|
||||
self.rect = fb.rect
|
||||
self.fill_rect = fb.fill_rect
|
||||
self.text = fb.text
|
||||
self.scroll = fb.scroll
|
||||
self.blit = fb.blit
|
||||
self.init_display()
|
||||
|
||||
def init_display(self):
|
||||
@@ -66,6 +78,9 @@ class SSD1306:
|
||||
def poweroff(self):
|
||||
self.write_cmd(SET_DISP | 0x00)
|
||||
|
||||
def poweron(self):
|
||||
self.write_cmd(SET_DISP | 0x01)
|
||||
|
||||
def contrast(self, contrast):
|
||||
self.write_cmd(SET_CONTRAST)
|
||||
self.write_cmd(contrast)
|
||||
@@ -88,18 +103,6 @@ class SSD1306:
|
||||
self.write_cmd(self.pages - 1)
|
||||
self.write_data(self.buffer)
|
||||
|
||||
def fill(self, col):
|
||||
self.framebuf.fill(col)
|
||||
|
||||
def pixel(self, x, y, col):
|
||||
self.framebuf.pixel(x, y, col)
|
||||
|
||||
def scroll(self, dx, dy):
|
||||
self.framebuf.scroll(dx, dy)
|
||||
|
||||
def text(self, string, x, y, col=1):
|
||||
self.framebuf.text(string, x, y, col)
|
||||
|
||||
|
||||
class SSD1306_I2C(SSD1306):
|
||||
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
|
||||
@@ -121,9 +124,6 @@ class SSD1306_I2C(SSD1306):
|
||||
self.i2c.write(buf)
|
||||
self.i2c.stop()
|
||||
|
||||
def poweron(self):
|
||||
pass
|
||||
|
||||
|
||||
class SSD1306_SPI(SSD1306):
|
||||
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
|
||||
@@ -135,6 +135,12 @@ class SSD1306_SPI(SSD1306):
|
||||
self.dc = dc
|
||||
self.res = res
|
||||
self.cs = cs
|
||||
import time
|
||||
self.res(1)
|
||||
time.sleep_ms(1)
|
||||
self.res(0)
|
||||
time.sleep_ms(10)
|
||||
self.res(1)
|
||||
super().__init__(width, height, external_vcc)
|
||||
|
||||
def write_cmd(self, cmd):
|
||||
@@ -152,10 +158,3 @@ class SSD1306_SPI(SSD1306):
|
||||
self.cs(0)
|
||||
self.spi.write(buf)
|
||||
self.cs(1)
|
||||
|
||||
def poweron(self):
|
||||
self.res(1)
|
||||
time.sleep_ms(1)
|
||||
self.res(0)
|
||||
time.sleep_ms(10)
|
||||
self.res(1)
|
||||
|
||||
@@ -49,10 +49,8 @@ STATIC uint8_t buf[SECTOR_SIZE];
|
||||
void mp_spiflash_init(mp_spiflash_t *self) {
|
||||
mp_hal_pin_write(self->cs, 1);
|
||||
mp_hal_pin_output(self->cs);
|
||||
mp_hal_pin_write(self->spi.sck, 0);
|
||||
mp_hal_pin_output(self->spi.sck);
|
||||
mp_hal_pin_output(self->spi.mosi);
|
||||
mp_hal_pin_input(self->spi.miso);
|
||||
const mp_machine_spi_p_t *protocol = self->spi->type->protocol;
|
||||
protocol->init(self->spi, 0, NULL, (mp_map_t*)&mp_const_empty_map);
|
||||
}
|
||||
|
||||
STATIC void mp_spiflash_acquire_bus(mp_spiflash_t *self) {
|
||||
@@ -66,7 +64,8 @@ STATIC void mp_spiflash_release_bus(mp_spiflash_t *self) {
|
||||
}
|
||||
|
||||
STATIC void mp_spiflash_transfer(mp_spiflash_t *self, size_t len, const uint8_t *src, uint8_t *dest) {
|
||||
mp_machine_soft_spi_transfer(&self->spi.base, len, src, dest);
|
||||
const mp_machine_spi_p_t *protocol = self->spi->type->protocol;
|
||||
protocol->transfer(self->spi, len, src, dest);
|
||||
}
|
||||
|
||||
STATIC int mp_spiflash_wait_sr(mp_spiflash_t *self, uint8_t mask, uint8_t val, uint32_t timeout) {
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H
|
||||
#define MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H
|
||||
|
||||
@@ -31,8 +30,7 @@
|
||||
|
||||
typedef struct _mp_spiflash_t {
|
||||
mp_hal_pin_obj_t cs;
|
||||
// TODO replace with generic SPI object
|
||||
mp_machine_soft_spi_obj_t spi;
|
||||
mp_obj_base_t *spi; // object must have protocol pointing to mp_machine_spi_p_t struct
|
||||
} mp_spiflash_t;
|
||||
|
||||
void mp_spiflash_init(mp_spiflash_t *self);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""NRF24L01 driver for Micro Python
|
||||
"""NRF24L01 driver for MicroPython
|
||||
"""
|
||||
|
||||
from micropython import const
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Test for nrf24l01 module."""
|
||||
|
||||
import struct
|
||||
import pyb
|
||||
from pyb import Pin, SPI
|
||||
import utime
|
||||
from machine import Pin, SPI
|
||||
from nrf24l01 import NRF24L01
|
||||
|
||||
pipes = (b'\xf0\xf0\xf0\xf0\xe1', b'\xf0\xf0\xf0\xf0\xd2')
|
||||
@@ -24,7 +24,7 @@ def master():
|
||||
while num_successes < num_needed and num_failures < num_needed:
|
||||
# stop listening and send packet
|
||||
nrf.stop_listening()
|
||||
millis = pyb.millis()
|
||||
millis = utime.ticks_ms()
|
||||
led_state = max(1, (led_state << 1) & 0x0f)
|
||||
print('sending:', millis, led_state)
|
||||
try:
|
||||
@@ -36,10 +36,10 @@ def master():
|
||||
nrf.start_listening()
|
||||
|
||||
# wait for response, with 250ms timeout
|
||||
start_time = pyb.millis()
|
||||
start_time = utime.ticks_ms()
|
||||
timeout = False
|
||||
while not nrf.any() and not timeout:
|
||||
if pyb.elapsed_millis(start_time) > 250:
|
||||
if utime.ticks_diff(utime.ticks_ms(), start_time) > 250:
|
||||
timeout = True
|
||||
|
||||
if timeout:
|
||||
@@ -51,11 +51,11 @@ def master():
|
||||
got_millis, = struct.unpack('i', nrf.recv())
|
||||
|
||||
# print response and round-trip delay
|
||||
print('got response:', got_millis, '(delay', pyb.millis() - got_millis, 'ms)')
|
||||
print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)')
|
||||
num_successes += 1
|
||||
|
||||
# delay then loop
|
||||
pyb.delay(250)
|
||||
utime.sleep_ms(250)
|
||||
|
||||
print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
|
||||
|
||||
@@ -69,18 +69,19 @@ def slave():
|
||||
print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')
|
||||
|
||||
while True:
|
||||
pyb.wfi()
|
||||
machine.idle()
|
||||
if nrf.any():
|
||||
while nrf.any():
|
||||
buf = nrf.recv()
|
||||
millis, led_state = struct.unpack('ii', buf)
|
||||
print('received:', millis, led_state)
|
||||
for i in range(4):
|
||||
if led_state & (1 << i):
|
||||
pyb.LED(i + 1).on()
|
||||
for led in leds:
|
||||
if led_state & 1:
|
||||
led.on()
|
||||
else:
|
||||
pyb.LED(i + 1).off()
|
||||
pyb.delay(15)
|
||||
led.off()
|
||||
led_state >>= 1
|
||||
utime.sleep_ms(15)
|
||||
|
||||
nrf.stop_listening()
|
||||
try:
|
||||
@@ -90,6 +91,12 @@ def slave():
|
||||
print('sent response')
|
||||
nrf.start_listening()
|
||||
|
||||
try:
|
||||
import pyb
|
||||
leds = [pyb.LED(i + 1) for i in range(4)]
|
||||
except:
|
||||
leds = []
|
||||
|
||||
print('NRF24L01 test module loaded')
|
||||
print('NRF24L01 pinout for test:')
|
||||
print(' CE on Y4')
|
||||
|
||||
@@ -1,101 +1,51 @@
|
||||
"""
|
||||
DS18x20 temperature sensor driver for MicroPython.
|
||||
# DS18x20 temperature sensor driver for MicroPython.
|
||||
# MIT license; Copyright (c) 2016 Damien P. George
|
||||
|
||||
This driver uses the OneWire driver to control DS18S20 and DS18B20
|
||||
temperature sensors. It supports multiple devices on the same 1-wire bus.
|
||||
from micropython import const
|
||||
|
||||
The following example assumes the ground of your DS18x20 is connected to
|
||||
Y11, vcc is connected to Y9 and the data pin is connected to Y10.
|
||||
_CONVERT = const(0x44)
|
||||
_RD_SCRATCH = const(0xbe)
|
||||
_WR_SCRATCH = const(0x4e)
|
||||
|
||||
>>> from machine import Pin
|
||||
>>> gnd = Pin('Y11', Pin.OUT_PP)
|
||||
>>> gnd.off()
|
||||
>>> vcc = Pin('Y9', Pin.OUT_PP)
|
||||
>>> vcc.on()
|
||||
class DS18X20:
|
||||
def __init__(self, onewire):
|
||||
self.ow = onewire
|
||||
self.buf = bytearray(9)
|
||||
|
||||
>>> from ds18x20 import DS18X20
|
||||
>>> d = DS18X20(Pin('Y10'))
|
||||
def scan(self):
|
||||
return [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]
|
||||
|
||||
Call read_temps to read all sensors:
|
||||
def convert_temp(self):
|
||||
self.ow.reset(True)
|
||||
self.ow.writebyte(self.ow.SKIP_ROM)
|
||||
self.ow.writebyte(_CONVERT)
|
||||
|
||||
>>> result = d.read_temps()
|
||||
>>> print(result)
|
||||
[20.875, 20.8125]
|
||||
def read_scratch(self, rom):
|
||||
self.ow.reset(True)
|
||||
self.ow.select_rom(rom)
|
||||
self.ow.writebyte(_RD_SCRATCH)
|
||||
self.ow.readinto(self.buf)
|
||||
if self.ow.crc8(self.buf):
|
||||
raise Exception('CRC error')
|
||||
return self.buf
|
||||
|
||||
Call read_temp to read the temperature of a specific sensor:
|
||||
def write_scratch(self, rom, buf):
|
||||
self.ow.reset(True)
|
||||
self.ow.select_rom(rom)
|
||||
self.ow.writebyte(_WR_SCRATCH)
|
||||
self.ow.write(buf)
|
||||
|
||||
>>> result = d.read_temp(d.roms[0])
|
||||
>>> print(result)
|
||||
20.25
|
||||
|
||||
If only one DS18x20 is attached to the bus, then you don't need to
|
||||
pass a ROM to read_temp:
|
||||
|
||||
>>> result = d.read_temp()
|
||||
>>> print(result)
|
||||
20.25
|
||||
|
||||
"""
|
||||
|
||||
from onewire import OneWire
|
||||
|
||||
class DS18X20(object):
|
||||
def __init__(self, pin):
|
||||
self.ow = OneWire(pin)
|
||||
# Scan the 1-wire devices, but only keep those which have the
|
||||
# correct # first byte in their rom for a DS18x20 device.
|
||||
self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]
|
||||
|
||||
def read_temp(self, rom=None):
|
||||
"""
|
||||
Read and return the temperature of one DS18x20 device.
|
||||
Pass the 8-byte bytes object with the ROM of the specific device you want to read.
|
||||
If only one DS18x20 device is attached to the bus you may omit the rom parameter.
|
||||
"""
|
||||
rom = rom or self.roms[0]
|
||||
ow = self.ow
|
||||
ow.reset()
|
||||
ow.select_rom(rom)
|
||||
ow.write_byte(0x44) # Convert Temp
|
||||
while True:
|
||||
if ow.read_bit():
|
||||
break
|
||||
ow.reset()
|
||||
ow.select_rom(rom)
|
||||
ow.write_byte(0xbe) # Read scratch
|
||||
data = ow.read_bytes(9)
|
||||
return self.convert_temp(rom[0], data)
|
||||
|
||||
def read_temps(self):
|
||||
"""
|
||||
Read and return the temperatures of all attached DS18x20 devices.
|
||||
"""
|
||||
temps = []
|
||||
for rom in self.roms:
|
||||
temps.append(self.read_temp(rom))
|
||||
return temps
|
||||
|
||||
def convert_temp(self, rom0, data):
|
||||
"""
|
||||
Convert the raw temperature data into degrees celsius and return as a float.
|
||||
"""
|
||||
temp_lsb = data[0]
|
||||
temp_msb = data[1]
|
||||
if rom0 == 0x10:
|
||||
if temp_msb != 0:
|
||||
# convert negative number
|
||||
temp_read = temp_lsb >> 1 | 0x80 # truncate bit 0 by shifting, fill high bit with 1.
|
||||
temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement
|
||||
def read_temp(self, rom):
|
||||
buf = self.read_scratch(rom)
|
||||
if rom[0] == 0x10:
|
||||
if buf[1]:
|
||||
t = buf[0] >> 1 | 0x80
|
||||
t = -((~t + 1) & 0xff)
|
||||
else:
|
||||
temp_read = temp_lsb >> 1 # truncate bit 0 by shifting
|
||||
count_remain = data[6]
|
||||
count_per_c = data[7]
|
||||
temp = temp_read - 0.25 + (count_per_c - count_remain) / count_per_c
|
||||
return temp
|
||||
elif rom0 == 0x28:
|
||||
temp = (temp_msb << 8 | temp_lsb) / 16
|
||||
if (temp_msb & 0xf8) == 0xf8: # for negative temperature
|
||||
temp -= 0x1000
|
||||
return temp
|
||||
t = buf[0] >> 1
|
||||
return t - 0.25 + (buf[7] - buf[6]) / buf[7]
|
||||
else:
|
||||
assert False
|
||||
t = buf[1] << 8 | buf[0]
|
||||
if t & 0x8000: # sign bit set
|
||||
t = -((t ^ 0xffff) + 1)
|
||||
return t / 16
|
||||
|
||||
@@ -1,336 +1,91 @@
|
||||
"""
|
||||
OneWire library ported to MicroPython by Jason Hildebrand.
|
||||
# 1-Wire driver for MicroPython
|
||||
# MIT license; Copyright (c) 2016 Damien P. George
|
||||
|
||||
from micropython import const
|
||||
import _onewire as _ow
|
||||
|
||||
TODO:
|
||||
* implement and test parasite-power mode (as an init option)
|
||||
* port the crc checks
|
||||
|
||||
The original upstream copyright and terms follow.
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
Copyright (c) 2007, Jim Studt (original old version - many contributors since)
|
||||
|
||||
OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since
|
||||
January 2010.
|
||||
|
||||
26 Sept 2008 -- Robin James
|
||||
|
||||
Jim Studt's original library was modified by Josh Larios.
|
||||
|
||||
Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
Much of the code was inspired by Derek Yerger's code, though I don't
|
||||
think much of that remains. In any event that was..
|
||||
(copyleft) 2006 by Derek Yerger - Free to distribute freely.
|
||||
"""
|
||||
|
||||
import pyb
|
||||
from pyb import disable_irq
|
||||
from pyb import enable_irq
|
||||
class OneWireError(Exception):
|
||||
pass
|
||||
|
||||
class OneWire:
|
||||
SEARCH_ROM = const(0xf0)
|
||||
MATCH_ROM = const(0x55)
|
||||
SKIP_ROM = const(0xcc)
|
||||
|
||||
def __init__(self, pin):
|
||||
"""
|
||||
Pass the data pin connected to your one-wire device(s), for example Pin('X1').
|
||||
The one-wire protocol allows for multiple devices to be attached.
|
||||
"""
|
||||
self.data_pin = pin
|
||||
self.write_delays = (1, 40, 40, 1)
|
||||
self.read_delays = (1, 1, 40)
|
||||
self.pin = pin
|
||||
self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP)
|
||||
|
||||
# cache a bunch of methods and attributes. This is necessary in _write_bit and
|
||||
# _read_bit to achieve the timing required by the OneWire protocol.
|
||||
self.cache = (pin.init, pin.value, pin.OUT_PP, pin.IN, pin.PULL_UP)
|
||||
def reset(self, required=False):
|
||||
reset = _ow.reset(self.pin)
|
||||
if required and not reset:
|
||||
raise OneWireError
|
||||
return reset
|
||||
|
||||
pin.init(pin.IN, pin.PULL_UP)
|
||||
def readbit(self):
|
||||
return _ow.readbit(self.pin)
|
||||
|
||||
def reset(self):
|
||||
"""
|
||||
Perform the onewire reset function.
|
||||
Returns 1 if a device asserted a presence pulse, 0 otherwise.
|
||||
def readbyte(self):
|
||||
return _ow.readbyte(self.pin)
|
||||
|
||||
If you receive 0, then check your wiring and make sure you are providing
|
||||
power and ground to your devices.
|
||||
"""
|
||||
retries = 25
|
||||
self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP)
|
||||
def readinto(self, buf):
|
||||
for i in range(len(buf)):
|
||||
buf[i] = _ow.readbyte(self.pin)
|
||||
|
||||
# We will wait up to 250uS for
|
||||
# the bus to come high, if it doesn't then it is broken or shorted
|
||||
# and we return a 0;
|
||||
def writebit(self, value):
|
||||
return _ow.writebit(self.pin, value)
|
||||
|
||||
# wait until the wire is high... just in case
|
||||
while True:
|
||||
if self.data_pin.value():
|
||||
break
|
||||
retries -= 1
|
||||
if retries == 0:
|
||||
raise OSError("OneWire pin didn't go high")
|
||||
pyb.udelay(10)
|
||||
def writebyte(self, value):
|
||||
return _ow.writebyte(self.pin, value)
|
||||
|
||||
# pull the bus low for at least 480us
|
||||
self.data_pin.low()
|
||||
self.data_pin.init(self.data_pin.OUT_PP)
|
||||
pyb.udelay(480)
|
||||
|
||||
# If there is a slave present, it should pull the bus low within 60us
|
||||
i = pyb.disable_irq()
|
||||
self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP)
|
||||
pyb.udelay(70)
|
||||
presence = not self.data_pin.value()
|
||||
pyb.enable_irq(i)
|
||||
pyb.udelay(410)
|
||||
return presence
|
||||
|
||||
def write_bit(self, value):
|
||||
"""
|
||||
Write a single bit.
|
||||
"""
|
||||
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
|
||||
self._write_bit(value, pin_init, pin_value, Pin_OUT_PP)
|
||||
|
||||
def _write_bit(self, value, pin_init, pin_value, Pin_OUT_PP):
|
||||
"""
|
||||
Write a single bit - requires cached methods/attributes be passed as arguments.
|
||||
See also write_bit()
|
||||
"""
|
||||
d0, d1, d2, d3 = self.write_delays
|
||||
udelay = pyb.udelay
|
||||
if value:
|
||||
# write 1
|
||||
i = disable_irq()
|
||||
pin_value(0)
|
||||
pin_init(Pin_OUT_PP)
|
||||
udelay(d0)
|
||||
pin_value(1)
|
||||
enable_irq(i)
|
||||
udelay(d1)
|
||||
else:
|
||||
# write 0
|
||||
i = disable_irq()
|
||||
pin_value(0)
|
||||
pin_init(Pin_OUT_PP)
|
||||
udelay(d2)
|
||||
pin_value(1)
|
||||
enable_irq(i)
|
||||
udelay(d3)
|
||||
|
||||
def write_byte(self, value):
|
||||
"""
|
||||
Write a byte. The pin will go tri-state at the end of the write to avoid
|
||||
heating in a short or other mishap.
|
||||
"""
|
||||
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
|
||||
for i in range(8):
|
||||
self._write_bit(value & 1, pin_init, pin_value, Pin_OUT_PP)
|
||||
value >>= 1
|
||||
pin_init(Pin_IN, Pin_PULL_UP)
|
||||
|
||||
def write_bytes(self, bytestring):
|
||||
"""
|
||||
Write a sequence of bytes.
|
||||
"""
|
||||
for byte in bytestring:
|
||||
self.write_byte(byte)
|
||||
|
||||
def _read_bit(self, pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP):
|
||||
"""
|
||||
Read a single bit - requires cached methods/attributes be passed as arguments.
|
||||
See also read_bit()
|
||||
"""
|
||||
d0, d1, d2 = self.read_delays
|
||||
udelay = pyb.udelay
|
||||
pin_init(Pin_IN, Pin_PULL_UP) # TODO why do we need this?
|
||||
i = disable_irq()
|
||||
pin_value(0)
|
||||
pin_init(Pin_OUT_PP)
|
||||
udelay(d0)
|
||||
pin_init(Pin_IN, Pin_PULL_UP)
|
||||
udelay(d1)
|
||||
value = pin_value()
|
||||
enable_irq(i)
|
||||
udelay(d2)
|
||||
return value
|
||||
|
||||
def read_bit(self):
|
||||
"""
|
||||
Read a single bit.
|
||||
"""
|
||||
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
|
||||
return self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
|
||||
|
||||
def read_byte(self):
|
||||
"""
|
||||
Read a single byte and return the value as an integer.
|
||||
See also read_bytes()
|
||||
"""
|
||||
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
|
||||
value = 0
|
||||
for i in range(8):
|
||||
bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
|
||||
value |= bit << i
|
||||
return value
|
||||
|
||||
def read_bytes(self, count):
|
||||
"""
|
||||
Read a sequence of N bytes.
|
||||
The bytes are returned as a bytearray.
|
||||
"""
|
||||
s = bytearray(count)
|
||||
for i in range(count):
|
||||
s[i] = self.read_byte()
|
||||
return s
|
||||
def write(self, buf):
|
||||
for b in buf:
|
||||
_ow.writebyte(self.pin, b)
|
||||
|
||||
def select_rom(self, rom):
|
||||
"""
|
||||
Select a specific device to talk to. Pass in rom as a bytearray (8 bytes).
|
||||
"""
|
||||
assert len(rom) == 8, "ROM must be 8 bytes"
|
||||
self.reset()
|
||||
self.write_byte(0x55) # ROM MATCH
|
||||
self.write_bytes(rom)
|
||||
|
||||
def read_rom(self):
|
||||
"""
|
||||
Read the ROM - this works if there is only a single device attached.
|
||||
"""
|
||||
self.reset()
|
||||
self.write_byte(0x33) # READ ROM
|
||||
rom = self.read_bytes(8)
|
||||
# TODO: check CRC of the ROM
|
||||
return rom
|
||||
|
||||
def skip_rom(self):
|
||||
"""
|
||||
Send skip-rom command - this works if there is only one device attached.
|
||||
"""
|
||||
self.write_byte(0xCC) # SKIP ROM
|
||||
|
||||
def depower(self):
|
||||
self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_NONE)
|
||||
self.writebyte(MATCH_ROM)
|
||||
self.write(rom)
|
||||
|
||||
def scan(self):
|
||||
"""
|
||||
Return a list of ROMs for all attached devices.
|
||||
Each ROM is returned as a bytes object of 8 bytes.
|
||||
"""
|
||||
devices = []
|
||||
self._reset_search()
|
||||
while True:
|
||||
rom = self._search()
|
||||
if not rom:
|
||||
return devices
|
||||
devices.append(rom)
|
||||
diff = 65
|
||||
rom = False
|
||||
for i in range(0xff):
|
||||
rom, diff = self._search_rom(rom, diff)
|
||||
if rom:
|
||||
devices += [rom]
|
||||
if diff == 0:
|
||||
break
|
||||
return devices
|
||||
|
||||
def _reset_search(self):
|
||||
self.last_discrepancy = 0
|
||||
self.last_device_flag = False
|
||||
self.last_family_discrepancy = 0
|
||||
self.rom = bytearray(8)
|
||||
|
||||
def _search(self):
|
||||
# initialize for search
|
||||
id_bit_number = 1
|
||||
last_zero = 0
|
||||
rom_byte_number = 0
|
||||
rom_byte_mask = 1
|
||||
search_result = 0
|
||||
pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache
|
||||
|
||||
# if the last call was not the last one
|
||||
if not self.last_device_flag:
|
||||
# 1-Wire reset
|
||||
if not self.reset():
|
||||
self._reset_search()
|
||||
return None
|
||||
|
||||
# issue the search command
|
||||
self.write_byte(0xF0)
|
||||
|
||||
# loop to do the search
|
||||
while rom_byte_number < 8: # loop until through all ROM bytes 0-7
|
||||
# read a bit and its complement
|
||||
id_bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
|
||||
cmp_id_bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP)
|
||||
|
||||
# check for no devices on 1-wire
|
||||
if (id_bit == 1) and (cmp_id_bit == 1):
|
||||
break
|
||||
def _search_rom(self, l_rom, diff):
|
||||
if not self.reset():
|
||||
return None, 0
|
||||
self.writebyte(SEARCH_ROM)
|
||||
if not l_rom:
|
||||
l_rom = bytearray(8)
|
||||
rom = bytearray(8)
|
||||
next_diff = 0
|
||||
i = 64
|
||||
for byte in range(8):
|
||||
r_b = 0
|
||||
for bit in range(8):
|
||||
b = self.readbit()
|
||||
if self.readbit():
|
||||
if b: # there are no devices or there is an error on the bus
|
||||
return None, 0
|
||||
else:
|
||||
# all devices coupled have 0 or 1
|
||||
if (id_bit != cmp_id_bit):
|
||||
search_direction = id_bit # bit write value for search
|
||||
else:
|
||||
# if this discrepancy if before the Last Discrepancy
|
||||
# on a previous next then pick the same as last time
|
||||
if (id_bit_number < self.last_discrepancy):
|
||||
search_direction = (self.rom[rom_byte_number] & rom_byte_mask) > 0
|
||||
else:
|
||||
# if equal to last pick 1, if not then pick 0
|
||||
search_direction = (id_bit_number == self.last_discrepancy)
|
||||
|
||||
# if 0 was picked then record its position in LastZero
|
||||
if search_direction == 0:
|
||||
last_zero = id_bit_number
|
||||
|
||||
# check for Last discrepancy in family
|
||||
if last_zero < 9:
|
||||
self.last_family_discrepancy = last_zero
|
||||
if not b: # collision, two devices with different bit meaning
|
||||
if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i):
|
||||
b = 1
|
||||
next_diff = i
|
||||
self.writebit(b)
|
||||
if b:
|
||||
r_b |= 1 << bit
|
||||
i -= 1
|
||||
rom[byte] = r_b
|
||||
return rom, next_diff
|
||||
|
||||
# set or clear the bit in the ROM byte rom_byte_number
|
||||
# with mask rom_byte_mask
|
||||
if search_direction == 1:
|
||||
self.rom[rom_byte_number] |= rom_byte_mask
|
||||
else:
|
||||
self.rom[rom_byte_number] &= ~rom_byte_mask
|
||||
|
||||
# serial number search direction write bit
|
||||
#print('sd', search_direction)
|
||||
self.write_bit(search_direction)
|
||||
|
||||
# increment the byte counter id_bit_number
|
||||
# and shift the mask rom_byte_mask
|
||||
id_bit_number += 1
|
||||
rom_byte_mask <<= 1
|
||||
|
||||
# if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask
|
||||
if rom_byte_mask == 0x100:
|
||||
rom_byte_number += 1
|
||||
rom_byte_mask = 1
|
||||
|
||||
# if the search was successful then
|
||||
if not (id_bit_number < 65):
|
||||
# search successful so set last_discrepancy,last_device_flag,search_result
|
||||
self.last_discrepancy = last_zero
|
||||
|
||||
# check for last device
|
||||
if self.last_discrepancy == 0:
|
||||
self.last_device_flag = True
|
||||
search_result = True
|
||||
|
||||
# if no device found then reset counters so next 'search' will be like a first
|
||||
if not search_result or not self.rom[0]:
|
||||
self._reset_search()
|
||||
return None
|
||||
else:
|
||||
return bytes(self.rom)
|
||||
def crc8(self, data):
|
||||
return _ow.crc8(data)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
Micro Python driver for SD cards using SPI bus.
|
||||
MicroPython driver for SD cards using SPI bus.
|
||||
|
||||
Requires an SPI bus and a CS pin. Provides readblocks and writeblocks
|
||||
methods so the device can be mounted as a filesystem.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
This is the driver for the WIZnet5x00 series of Ethernet controllers.
|
||||
|
||||
Adapted for Micro Python.
|
||||
Adapted for MicroPython.
|
||||
|
||||
Original source: https://github.com/Wiznet/W5500_EVB/tree/master/ioLibrary
|
||||
Taken on: 30 August 2014
|
||||
|
||||
@@ -52,10 +52,9 @@
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "py/mpthread.h"
|
||||
#include "socket.h"
|
||||
|
||||
extern void HAL_Delay(uint32_t);
|
||||
|
||||
#define SOCK_ANY_PORT_NUM 0xC000;
|
||||
|
||||
static uint16_t sock_any_port = SOCK_ANY_PORT_NUM;
|
||||
@@ -242,7 +241,7 @@ int8_t WIZCHIP_EXPORT(connect)(uint8_t sn, uint8_t * addr, uint16_t port)
|
||||
#endif
|
||||
return SOCKERR_TIMEOUT;
|
||||
}
|
||||
HAL_Delay(1);
|
||||
MICROPY_THREAD_YIELD();
|
||||
}
|
||||
#if _WIZCHIP_ == 5200 // for W5200 ARP errata
|
||||
setSUBR((uint8_t*)"\x00\x00\x00\x00");
|
||||
@@ -317,6 +316,7 @@ int32_t WIZCHIP_EXPORT(send)(uint8_t sn, uint8_t * buf, uint16_t len)
|
||||
}
|
||||
if( (sock_io_mode & (1<<sn)) && (len > freesize) ) return SOCK_BUSY;
|
||||
if(len <= freesize) break;
|
||||
MICROPY_THREAD_YIELD();
|
||||
}
|
||||
wiz_send_data(sn, buf, len);
|
||||
#if _WIZCHIP_ == 5200
|
||||
@@ -368,7 +368,7 @@ int32_t WIZCHIP_EXPORT(recv)(uint8_t sn, uint8_t * buf, uint16_t len)
|
||||
}
|
||||
if((sock_io_mode & (1<<sn)) && (recvsize == 0)) return SOCK_BUSY;
|
||||
if(recvsize != 0) break;
|
||||
HAL_Delay(1);
|
||||
MICROPY_THREAD_YIELD();
|
||||
};
|
||||
if(recvsize < len) len = recvsize;
|
||||
wiz_recv_data(sn, buf, len);
|
||||
@@ -416,7 +416,7 @@ int32_t WIZCHIP_EXPORT(sendto)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t
|
||||
if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED;
|
||||
if( (sock_io_mode & (1<<sn)) && (len > freesize) ) return SOCK_BUSY;
|
||||
if(len <= freesize) break;
|
||||
HAL_Delay(1);
|
||||
MICROPY_THREAD_YIELD();
|
||||
};
|
||||
wiz_send_data(sn, buf, len);
|
||||
|
||||
@@ -446,7 +446,7 @@ int32_t WIZCHIP_EXPORT(sendto)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_t
|
||||
return SOCKERR_TIMEOUT;
|
||||
}
|
||||
////////////
|
||||
HAL_Delay(1);
|
||||
MICROPY_THREAD_YIELD();
|
||||
}
|
||||
#if _WIZCHIP_ == 5200 // for W5200 ARP errata
|
||||
setSUBR((uint8_t*)"\x00\x00\x00\x00");
|
||||
@@ -486,6 +486,7 @@ int32_t WIZCHIP_EXPORT(recvfrom)(uint8_t sn, uint8_t * buf, uint16_t len, uint8_
|
||||
if(getSn_SR(sn) == SOCK_CLOSED) return SOCKERR_SOCKCLOSED;
|
||||
if( (sock_io_mode & (1<<sn)) && (pack_len == 0) ) return SOCK_BUSY;
|
||||
if(pack_len != 0) break;
|
||||
MICROPY_THREAD_YIELD();
|
||||
};
|
||||
}
|
||||
sock_pack_info[sn] = PACK_COMPLETED;
|
||||
|
||||
@@ -57,6 +57,16 @@
|
||||
|
||||
////////////////////////////////////////////////////
|
||||
|
||||
#define LPC_SSP0 (0)
|
||||
|
||||
static void Chip_SSP_ReadFrames_Blocking(int dummy, uint8_t *buf, uint32_t len) {
|
||||
WIZCHIP.IF.SPI._read_bytes(buf, len);
|
||||
}
|
||||
|
||||
static void Chip_SSP_WriteFrames_Blocking(int dummy, const uint8_t *buf, uint32_t len) {
|
||||
WIZCHIP.IF.SPI._write_bytes(buf, len);
|
||||
}
|
||||
|
||||
uint8_t WIZCHIP_READ(uint32_t AddrSel)
|
||||
{
|
||||
uint8_t ret;
|
||||
|
||||
@@ -44,7 +44,6 @@
|
||||
|
||||
#include <stdint.h>
|
||||
#include "../wizchip_conf.h"
|
||||
#include "board.h"
|
||||
|
||||
#define _W5500_IO_BASE_ 0x00000000
|
||||
|
||||
|
||||
@@ -56,7 +56,9 @@
|
||||
* @todo You should select one, \b 5100, \b 5200 ,\b 5500 or etc. \n\n
|
||||
* ex> <code> #define \_WIZCHIP_ 5500 </code>
|
||||
*/
|
||||
#ifndef _WIZCHIP_
|
||||
#define _WIZCHIP_ 5200 // 5100, 5200, 5500
|
||||
#endif
|
||||
|
||||
#define _WIZCHIP_IO_MODE_NONE_ 0x0000
|
||||
#define _WIZCHIP_IO_MODE_BUS_ 0x0100 /**< Bus interface mode */
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
void esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz);
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* This file is part of the MicroPython project, http://micropython.org/
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2015-2016 Damien P. George
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "etshal.h"
|
||||
#include "user_interface.h"
|
||||
#include "modmachine.h"
|
||||
#include "esponewire.h"
|
||||
|
||||
#define TIMING_RESET1 (0)
|
||||
#define TIMING_RESET2 (1)
|
||||
#define TIMING_RESET3 (2)
|
||||
#define TIMING_READ1 (3)
|
||||
#define TIMING_READ2 (4)
|
||||
#define TIMING_READ3 (5)
|
||||
#define TIMING_WRITE1 (6)
|
||||
#define TIMING_WRITE2 (7)
|
||||
#define TIMING_WRITE3 (8)
|
||||
|
||||
uint16_t esp_onewire_timings[9] = {480, 40, 420, 5, 5, 40, 10, 50, 10};
|
||||
|
||||
static uint32_t disable_irq(void) {
|
||||
ets_intr_lock();
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void enable_irq(uint32_t i) {
|
||||
ets_intr_unlock();
|
||||
}
|
||||
|
||||
static void mp_hal_delay_us_no_irq(uint32_t us) {
|
||||
uint32_t start = system_get_time();
|
||||
while (system_get_time() - start < us) {
|
||||
}
|
||||
}
|
||||
|
||||
#define DELAY_US mp_hal_delay_us_no_irq
|
||||
|
||||
int esp_onewire_reset(uint pin) {
|
||||
pin_set(pin, 0);
|
||||
DELAY_US(esp_onewire_timings[TIMING_RESET1]);
|
||||
uint32_t i = disable_irq();
|
||||
pin_set(pin, 1);
|
||||
DELAY_US(esp_onewire_timings[TIMING_RESET2]);
|
||||
int status = !pin_get(pin);
|
||||
enable_irq(i);
|
||||
DELAY_US(esp_onewire_timings[TIMING_RESET3]);
|
||||
return status;
|
||||
}
|
||||
|
||||
int esp_onewire_readbit(uint pin) {
|
||||
pin_set(pin, 1);
|
||||
uint32_t i = disable_irq();
|
||||
pin_set(pin, 0);
|
||||
DELAY_US(esp_onewire_timings[TIMING_READ1]);
|
||||
pin_set(pin, 1);
|
||||
DELAY_US(esp_onewire_timings[TIMING_READ2]);
|
||||
int value = pin_get(pin);
|
||||
enable_irq(i);
|
||||
DELAY_US(esp_onewire_timings[TIMING_READ3]);
|
||||
return value;
|
||||
}
|
||||
|
||||
void esp_onewire_writebit(uint pin, int value) {
|
||||
uint32_t i = disable_irq();
|
||||
pin_set(pin, 0);
|
||||
DELAY_US(esp_onewire_timings[TIMING_WRITE1]);
|
||||
if (value) {
|
||||
pin_set(pin, 1);
|
||||
}
|
||||
DELAY_US(esp_onewire_timings[TIMING_WRITE2]);
|
||||
pin_set(pin, 1);
|
||||
DELAY_US(esp_onewire_timings[TIMING_WRITE3]);
|
||||
enable_irq(i);
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* This file is part of the MicroPython project, http://micropython.org/
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2016 Damien P. George
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef __MICROPY_INCLUDED_ESP8266_ESPONEWIRE_H__
|
||||
#define __MICROPY_INCLUDED_ESP8266_ESPONEWIRE_H__
|
||||
|
||||
extern uint16_t esp_onewire_timings[9];
|
||||
|
||||
int esp_onewire_reset(uint pin);
|
||||
int esp_onewire_readbit(uint pin);
|
||||
void esp_onewire_writebit(uint pin, int value);
|
||||
|
||||
#endif // __MICROPY_INCLUDED_ESP8266_ESPONEWIRE_H__
|
||||
@@ -1,4 +0,0 @@
|
||||
extern int ets_loop_iter_disable;
|
||||
extern uint32_t system_time_high_word;
|
||||
|
||||
bool ets_loop_iter(void);
|
||||
@@ -1,51 +0,0 @@
|
||||
# DS18x20 temperature sensor driver for MicroPython.
|
||||
# MIT license; Copyright (c) 2016 Damien P. George
|
||||
|
||||
from micropython import const
|
||||
|
||||
_CONVERT = const(0x44)
|
||||
_RD_SCRATCH = const(0xbe)
|
||||
_WR_SCRATCH = const(0x4e)
|
||||
|
||||
class DS18X20:
|
||||
def __init__(self, onewire):
|
||||
self.ow = onewire
|
||||
self.buf = bytearray(9)
|
||||
|
||||
def scan(self):
|
||||
return [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]
|
||||
|
||||
def convert_temp(self):
|
||||
self.ow.reset(True)
|
||||
self.ow.writebyte(self.ow.SKIP_ROM)
|
||||
self.ow.writebyte(_CONVERT)
|
||||
|
||||
def read_scratch(self, rom):
|
||||
self.ow.reset(True)
|
||||
self.ow.select_rom(rom)
|
||||
self.ow.writebyte(_RD_SCRATCH)
|
||||
self.ow.readinto(self.buf)
|
||||
if self.ow.crc8(self.buf):
|
||||
raise Exception('CRC error')
|
||||
return self.buf
|
||||
|
||||
def write_scratch(self, rom, buf):
|
||||
self.ow.reset(True)
|
||||
self.ow.select_rom(rom)
|
||||
self.ow.writebyte(_WR_SCRATCH)
|
||||
self.ow.write(buf)
|
||||
|
||||
def read_temp(self, rom):
|
||||
buf = self.read_scratch(rom)
|
||||
if rom[0] == 0x10:
|
||||
if buf[1]:
|
||||
t = buf[0] >> 1 | 0x80
|
||||
t = -((~t + 1) & 0xff)
|
||||
else:
|
||||
t = buf[0] >> 1
|
||||
return t - 0.25 + (buf[7] - buf[6]) / buf[7]
|
||||
else:
|
||||
t = buf[1] << 8 | buf[0]
|
||||
if t & 0x8000: # sign bit set
|
||||
t = -((t ^ 0xffff) + 1)
|
||||
return t / 16
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user