├── .github └── workflows │ └── build.yml ├── .gitignore ├── .readthedocs.yaml ├── AUTHORS ├── LICENSE ├── Makefile ├── README.md ├── config.json ├── docs ├── Makefile ├── accelerometer.rst ├── audio.rst ├── ble.rst ├── button.rst ├── comic.png ├── compass.rst ├── conf.py ├── devguide │ ├── contributing.rst │ ├── flashfirmware.rst │ ├── hexformat.rst │ └── repl.rst ├── display.rst ├── filesystem.rst ├── i2c.rst ├── image-smile.png ├── image.rst ├── index.rst ├── machine.rst ├── make.bat ├── microbit.rst ├── microbit_micropython_api.rst ├── micropython.rst ├── music-pins.png ├── music.rst ├── neopixel-croc.png ├── neopixel-croc.svg ├── neopixel.gif ├── neopixel.rst ├── os.rst ├── pin.rst ├── pinout.png ├── pwm.png ├── radio.rst ├── random.rst ├── requirements.txt ├── scroll-hello.gif ├── speech-pitch.png ├── speech.png ├── speech.rst ├── spi.rst ├── tutorials │ ├── binary_count.gif │ ├── blue-microbit.png │ ├── buttons.rst │ ├── dalek.jpg │ ├── direction.rst │ ├── files.jpg │ ├── fireflies.gif │ ├── firefly.gif │ ├── gestures.rst │ ├── happy.png │ ├── hello.rst │ ├── images.rst │ ├── introduction.rst │ ├── io.rst │ ├── matrioshka.jpg │ ├── mb-firefly.gif │ ├── movement.rst │ ├── music.rst │ ├── network.png │ ├── network.rst │ ├── next.rst │ ├── piezo_buzzer.jpg │ ├── pin0-gnd.png │ ├── queen.jpg │ ├── radio.rst │ ├── random.rst │ ├── speech.rst │ └── storage.rst ├── uart.rst └── utime.rst ├── examples ├── analog_watch.py ├── asmleds.py ├── bubble_level_2d.py ├── compass.py ├── conway.py ├── counter.py ├── die20.py ├── digital_water.py ├── dodge_game.py ├── fallingblocks.py ├── flame_simulation.py ├── flappybit.py ├── four_buttons.py ├── friend.py ├── i_feel_today.py ├── led_dance.py ├── led_hunt.py ├── magic8.py ├── maze.py ├── music.py ├── neopixel_random.py ├── play_file.py ├── pomodoro.py ├── radio.py ├── reaction_game.py ├── red_rain.py ├── reverb.py ├── simple_slalom.py ├── speech.py ├── tiltmusic.py ├── watch.py └── waveforms.py ├── inc ├── extmod │ ├── machine_mem.h │ ├── machine_pulse.h │ └── utime_mphal.h ├── genhdr │ ├── mpversion.h │ └── qstrdefs.generated.h ├── lib │ ├── iters.h │ ├── mp-readline │ │ └── readline.h │ ├── pwm.h │ ├── ticker.h │ └── utils │ │ ├── interrupt_char.h │ │ └── pyexec.h ├── microbit │ ├── MicroBitCustomConfig.h │ ├── filesystem.h │ ├── memory.h │ ├── microbit_image.h │ ├── microbitdal.h │ ├── modaudio.h │ ├── modmicrobit.h │ ├── modmusic.h │ ├── mpconfigport.h │ ├── mphalport.h │ └── qstrdefsport.h └── py │ ├── asmarm.h │ ├── asmbase.h │ ├── asmthumb.h │ ├── asmx64.h │ ├── asmx86.h │ ├── asmxtensa.h │ ├── bc.h │ ├── bc0.h │ ├── binary.h │ ├── builtin.h │ ├── compile.h │ ├── emit.h │ ├── emitglue.h │ ├── formatfloat.h │ ├── frozenmod.h │ ├── gc.h │ ├── grammar.h │ ├── lexer.h │ ├── misc.h │ ├── mpconfig.h │ ├── mperrno.h │ ├── mphal.h │ ├── mpprint.h │ ├── mpstate.h │ ├── mpthread.h │ ├── mpz.h │ ├── nlr.h │ ├── obj.h │ ├── objarray.h │ ├── objexcept.h │ ├── objfun.h │ ├── objgenerator.h │ ├── objint.h │ ├── objlist.h │ ├── objmodule.h │ ├── objstr.h │ ├── objstringio.h │ ├── objtuple.h │ ├── objtype.h │ ├── parse.h │ ├── parse2.h │ ├── parsenum.h │ ├── parsenumbase.h │ ├── persistentcode.h │ ├── qstr.h │ ├── qstrdefs.h │ ├── reader.h │ ├── repl.h │ ├── ringbuf.h │ ├── runtime.h │ ├── runtime0.h │ ├── scope.h │ ├── smallint.h │ ├── stackctrl.h │ ├── stream.h │ ├── unicode.h │ └── vmentrytable.h ├── module.json ├── source ├── extmod │ ├── machine_mem.c │ ├── machine_pulse.c │ └── utime_mphal.c ├── lib │ ├── iters.c │ ├── mp-readline │ │ └── readline.c │ ├── neopixelsend.s │ ├── pwm.c │ ├── sam │ │ ├── ReciterTabs.h │ │ ├── RenderTabs.h │ │ ├── SamTabs.h │ │ ├── debug.c │ │ ├── debug.h │ │ ├── main.c │ │ ├── reciter.c │ │ ├── reciter.h │ │ ├── render.c │ │ ├── render.h │ │ ├── sam.c │ │ └── sam.h │ ├── ticker.c │ └── utils │ │ ├── interrupt_char.c │ │ └── pyexec.c ├── microbit │ ├── display_readme.md │ ├── events.cpp │ ├── fileobj.c │ ├── filesystem.c │ ├── gccollect.c │ ├── help.c │ ├── main.cpp │ ├── microbitaccelerometer.cpp │ ├── microbitbutton.cpp │ ├── microbitcompass.cpp │ ├── microbitconstimage.cpp │ ├── microbitconstimagetuples.c │ ├── microbitdisplay.cpp │ ├── microbiti2c.cpp │ ├── microbitimage.cpp │ ├── microbitpin.cpp │ ├── microbitpinmode.c │ ├── microbitspi.cpp │ ├── microbituart.cpp │ ├── modantigravity.cpp │ ├── modaudio.cpp │ ├── modlove.cpp │ ├── modmachine.c │ ├── modmicrobit.cpp │ ├── modmusic.cpp │ ├── modmusictunes.c │ ├── modneopixel.cpp │ ├── modos.c │ ├── modradio.cpp │ ├── modrandom.cpp │ ├── modspeech.c │ ├── modthis.cpp │ ├── modutime.c │ ├── mphalport.cpp │ └── persistent.c └── py │ ├── argcheck.c │ ├── asmarm.c │ ├── asmbase.c │ ├── asmthumb.c │ ├── asmx64.c │ ├── asmx86.c │ ├── asmxtensa.c │ ├── bc.c │ ├── binary.c │ ├── builtinevex.c │ ├── builtinhelp.c │ ├── builtinimport.c │ ├── compile.c │ ├── compile2.c │ ├── emitbc.c │ ├── emitcommon.c │ ├── emitglue.c │ ├── emitinlinethumb.c │ ├── emitinlinextensa.c │ ├── emitnative.c │ ├── formatfloat.c │ ├── frozenmod.c │ ├── gc.c │ ├── lexer.c │ ├── makeqstrdata.py │ ├── makeqstrdefs.py │ ├── makeversionhdr.py │ ├── malloc.c │ ├── map.c │ ├── modarray.c │ ├── modbuiltins.c │ ├── modcmath.c │ ├── modcollections.c │ ├── modgc.c │ ├── modio.c │ ├── modmath.c │ ├── modmicropython.c │ ├── modstruct.c │ ├── modsys.c │ ├── modthread.c │ ├── moduerrno.c │ ├── mpprint.c │ ├── mpstate.c │ ├── mpz.c │ ├── nativeglue.c │ ├── nlrsetjmp.c │ ├── nlrthumb.c │ ├── nlrx64.c │ ├── nlrx86.c │ ├── nlrxtensa.c │ ├── obj.c │ ├── objarray.c │ ├── objattrtuple.c │ ├── objbool.c │ ├── objboundmeth.c │ ├── objcell.c │ ├── objclosure.c │ ├── objcomplex.c │ ├── objdict.c │ ├── objenumerate.c │ ├── objexcept.c │ ├── objfilter.c │ ├── objfloat.c │ ├── objfun.c │ ├── objgenerator.c │ ├── objgetitemiter.c │ ├── objint.c │ ├── objint_longlong.c │ ├── objint_mpz.c │ ├── objlist.c │ ├── objmap.c │ ├── objmodule.c │ ├── objnamedtuple.c │ ├── objnone.c │ ├── objobject.c │ ├── objpolyiter.c │ ├── objproperty.c │ ├── objrange.c │ ├── objreversed.c │ ├── objset.c │ ├── objsingleton.c │ ├── objslice.c │ ├── objstr.c │ ├── objstringio.c │ ├── objstrunicode.c │ ├── objtuple.c │ ├── objtype.c │ ├── objzip.c │ ├── opmethods.c │ ├── parse.c │ ├── parse2.c │ ├── parsenum.c │ ├── parsenumbase.c │ ├── persistentcode.c │ ├── qstr.c │ ├── reader.c │ ├── repl.c │ ├── runtime.c │ ├── runtime_utils.c │ ├── scheduler.c │ ├── scope.c │ ├── sequence.c │ ├── showbc.c │ ├── smallint.c │ ├── stackctrl.c │ ├── stream.c │ ├── unicode.c │ ├── vm.c │ ├── vstr.c │ └── warning.c ├── tests ├── README.md ├── exercise.py ├── radio_audio.py ├── sample.raw ├── test_files.py ├── test_files2.py ├── test_files3.py ├── test_image.py ├── test_music.py ├── test_pins.py ├── test_pwm.py ├── test_random.py └── test_speech.py └── tools ├── adduicr.py ├── hexlifyscript.js ├── hexlifyscript.py ├── makecombinedhex.py ├── makeqstrhdr.sh ├── makeversionhdr.py ├── pyboard.py └── upload.py /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build MicroPython 2 | 3 | on: 4 | push: 5 | branches: '*' 6 | pull_request: 7 | branches: '*' 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-20.04 12 | name: Build MicroPython 13 | steps: 14 | - uses: actions/checkout@v4 15 | # Yotta has some issues with Python 3.7+ 16 | - name: Install Python 3.6 17 | uses: actions/setup-python@v5 18 | with: 19 | python-version: 3.6 20 | - name: Install GNU Arm Embedded Toolchain (arm-none-eabi-gcc) 21 | uses: carlosperate/arm-none-eabi-gcc-action@v1 22 | with: 23 | release: "10.3-2021.10" 24 | - name: Install CMake, Ninja & Yotta 25 | run: pip install cmake==3.22.3 ninja==1.10.2.3 yotta==0.20.5 26 | - name: Install srecord 27 | run: sudo apt-get install -y srecord 28 | - name: Check Versions 29 | run: | 30 | arm-none-eabi-gcc --version 31 | cmake --version 32 | ninja --version 33 | python --version 34 | yotta --version 35 | - name: Set up the Yotta target from GitHub 36 | run: | 37 | yotta target bbc-microbit-classic-gcc-nosd@https://github.com/lancaster-university/yotta-target-bbc-microbit-classic-gcc-nosd 38 | yotta up 39 | - run: make qstrs 40 | - run: git diff 41 | - run: make all 42 | - name: Process date for artifact filename 43 | id: date 44 | run: echo "BUILD_DATE=$(date +'%Y-%m-%d')" >> $GITHUB_ENV 45 | - name: Upload hex file 46 | uses: actions/upload-artifact@v4 47 | with: 48 | name: microbitv1-micropython-${{ env.BUILD_DATE }}-${{ github.sha }}.hex 49 | path: build/firmware.hex 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .yotta.json 2 | build/* 3 | yotta_modules/* 4 | yotta_targets/* 5 | *.swp 6 | __pycache__ 7 | 8 | # This file is generated by the build process 9 | inc/genhdr/microbitversion.h 10 | 11 | # Sphinx build directory 12 | docs/_build/ 13 | 14 | # MacOS desktop metadata files 15 | .DS_Store 16 | 17 | # Common virtual environment directories 18 | .venv/ 19 | venv/ 20 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 2 | version: 2 3 | 4 | build: 5 | os: ubuntu-lts-latest 6 | tools: 7 | python: "3.11" 8 | 9 | sphinx: 10 | configuration: docs/conf.py 11 | 12 | python: 13 | install: 14 | - requirements: docs/requirements.txt 15 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Damien P. George (@dpgeorge) 2 | Nicholas H. Tollervey (@ntoll) 3 | Matthew Else (@matthewelse) 4 | Alan M. Jackson (@alanmjackson) 5 | Mark Shannon (@markshannon) 6 | Larry Hastings (@larryhastings) 7 | Mariia Koroliuk (@marichkakorolyuk) 8 | Andrew Mulholland (@gbaman) 9 | Joe Glancy (@JoeGlancy) 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013-2016 The MicroPython-on-micro:bit Developers, as listed 4 | in the accompanying AUTHORS file 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ECHO = @echo 2 | 3 | HEX_SRC = build/bbc-microbit-classic-gcc-nosd/source/microbit-micropython.hex 4 | HEX_FINAL = build/firmware.hex 5 | MBIT_VER_FILE = inc/genhdr/microbitversion.h 6 | VER_ADDR_FILE = build/veraddr.txt 7 | 8 | all: $(HEX_FINAL) 9 | 10 | # Anything that depends on FORCE will be considered out-of-date 11 | FORCE: 12 | .PHONY: FORCE 13 | 14 | $(HEX_FINAL): yotta $(VER_ADDR_FILE) 15 | tools/adduicr.py $(HEX_SRC) 0x$$(cat $(VER_ADDR_FILE)) -o $(HEX_FINAL) 16 | @arm-none-eabi-size $(HEX_SRC:.hex=) 17 | 18 | .PHONY: qstrs 19 | qstrs: $(MBIT_VER_FILE) 20 | ./tools/makeqstrhdr.sh 21 | 22 | yotta: $(MBIT_VER_FILE) 23 | @yotta build 24 | 25 | $(MBIT_VER_FILE): FORCE 26 | python tools/makeversionhdr.py $(MBIT_VER_FILE) 27 | 28 | $(VER_ADDR_FILE): yotta 29 | @arm-none-eabi-objdump -x $(HEX_SRC:.hex=) | grep microbit_version_string | cut -f 1 -d' ' > $(VER_ADDR_FILE) 30 | 31 | deploy: $(HEX_FINAL) 32 | $(ECHO) "Deploying $<" 33 | @mount /dev/sdb 34 | @sleep 1s 35 | @cp $< /mnt/ 36 | @sleep 1s 37 | @umount /mnt 38 | 39 | serial: 40 | @picocom /dev/ttyACM0 -b 115200 41 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "microbit" : { 3 | "configfile" : "inc/microbit/MicroBitCustomConfig.h" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /docs/ble.rst: -------------------------------------------------------------------------------- 1 | Bluetooth 2 | ********* 3 | 4 | While the BBC micro:bit has hardware capable of allowing the device to work as 5 | a Bluetooth Low Energy (BLE) device, it only has 16k of RAM. The BLE stack 6 | alone takes up 12k RAM which means there's not enough memory for MicroPython 7 | to support Bluetooth. 8 | 9 | .. note:: 10 | MicroPython uses the radio hardware with the :mod:`radio` module. This 11 | allows users to create simple yet effective wireless networks of micro:bit 12 | devices. 13 | 14 | Furthermore, the protocol used in the :mod:`radio` module is a lot simpler 15 | than BLE, making it far easier to use in an educational context. 16 | -------------------------------------------------------------------------------- /docs/button.rst: -------------------------------------------------------------------------------- 1 | Buttons 2 | ******* 3 | 4 | .. py::module:: microbit 5 | 6 | There are two buttons on the board, called ``button_a`` and ``button_b``. 7 | 8 | Attributes 9 | ========== 10 | 11 | 12 | .. py:attribute:: button_a 13 | 14 | A ``Button`` instance (see below) representing the left button. 15 | 16 | 17 | .. py:attribute:: button_b 18 | 19 | Represents the right button. 20 | 21 | 22 | Classes 23 | ======= 24 | 25 | .. py:class:: Button() 26 | 27 | Represents a button. 28 | 29 | .. note:: 30 | This class is not actually available to the user, it is only used by 31 | the two button instances, which are provided already initialized. 32 | 33 | 34 | .. py:method:: is_pressed() 35 | 36 | Returns ``True`` if the specified button ``button`` is currently being 37 | held down, and ``False`` otherwise. 38 | 39 | .. py:method:: was_pressed() 40 | 41 | Returns ``True`` or ``False`` to indicate if the button was pressed 42 | (went from up to down) since the device started or the last time this 43 | method was called. Calling this method will clear the press state so 44 | that the button must be pressed again before this method will return 45 | ``True`` again. 46 | 47 | .. py:method:: get_presses() 48 | 49 | Returns the running total of button presses, and resets this total 50 | to zero before returning. 51 | 52 | Example 53 | ======= 54 | 55 | .. code:: 56 | 57 | import microbit 58 | 59 | while True: 60 | if microbit.button_a.is_pressed() and microbit.button_b.is_pressed(): 61 | microbit.display.scroll("AB") 62 | break 63 | elif microbit.button_a.is_pressed(): 64 | microbit.display.scroll("A") 65 | elif microbit.button_b.is_pressed(): 66 | microbit.display.scroll("B") 67 | microbit.sleep(100) 68 | -------------------------------------------------------------------------------- /docs/comic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/comic.png -------------------------------------------------------------------------------- /docs/compass.rst: -------------------------------------------------------------------------------- 1 | Compass 2 | ******* 3 | 4 | .. py:module:: microbit.compass 5 | 6 | This module lets you access the built-in electronic compass. Before using, 7 | the compass should be calibrated, otherwise the readings may be wrong. 8 | 9 | .. warning:: 10 | 11 | Calibrating the compass will cause your program to pause until calibration 12 | is complete. Calibration consists of a little game to draw a circle on the 13 | LED display by rotating the device. 14 | 15 | 16 | Functions 17 | ========= 18 | 19 | .. py:function:: calibrate() 20 | 21 | Starts the calibration process. An instructive message will be scrolled 22 | to the user after which they will need to rotate the device in order to 23 | draw a circle on the LED display. 24 | 25 | .. py:function:: is_calibrated() 26 | 27 | Returns ``True`` if the compass has been successfully calibrated, and 28 | returns ``False`` otherwise. 29 | 30 | 31 | .. py:function:: clear_calibration() 32 | 33 | Undoes the calibration, making the compass uncalibrated again. 34 | 35 | 36 | .. py:function:: get_x() 37 | 38 | Gives the reading of the magnetic field strength on the ``x`` axis in nano 39 | tesla, as a positive or negative integer, depending on the direction of the 40 | field. 41 | 42 | 43 | .. py:function:: get_y() 44 | 45 | Gives the reading of the magnetic field strength on the ``y`` axis in nano 46 | tesla, as a positive or negative integer, depending on the direction of the 47 | field. 48 | 49 | 50 | .. py:function:: get_z() 51 | 52 | Gives the reading of the magnetic field strength on the ``z`` axis in nano 53 | tesla, as a positive or negative integer, depending on the direction of the 54 | field. 55 | 56 | 57 | .. py:function:: heading() 58 | 59 | Gives the compass heading, calculated from the above readings, as an 60 | integer in the range from 0 to 360, representing the angle in degrees, 61 | clockwise, with north as 0. 62 | 63 | 64 | .. py:function:: get_field_strength() 65 | 66 | Returns an integer indication of the magnitude of the magnetic field around 67 | the device in nano tesla. 68 | 69 | 70 | Example 71 | ======= 72 | 73 | .. include:: ../examples/compass.py 74 | :code: python 75 | -------------------------------------------------------------------------------- /docs/devguide/contributing.rst: -------------------------------------------------------------------------------- 1 | Contributing 2 | ------------ 3 | 4 | Hey! Many thanks for wanting to improve MicroPython on the micro:bit. 5 | 6 | Contributions are welcome without prejudice from *anyone* irrespective of 7 | age, gender, religion, race or sexuality. Good quality code and engagement 8 | with respect, humour and intelligence wins every time. 9 | 10 | * If you're from a background which isn't well-represented in most geeky groups, get involved - *we want to help you make a difference*. 11 | * If you're from a background which *is* well-represented in most geeky groups, get involved - *we want your help making a difference*. 12 | * If you're worried about not being technical enough, get involved - *your fresh perspective will be invaluable*. 13 | * If you think you're an imposter, get involved. 14 | * If your day job isn't code, get involved. 15 | * This isn't a group of experts, just people. Get involved! 16 | * This is a new community, so, get involved. 17 | 18 | We expect contributors to follow the Python Software Foundation's Code of 19 | Conduct: https://www.python.org/psf/codeofconduct/ 20 | 21 | Feedback may be given for contributions and, where necessary, changes will 22 | be politely requested and discussed with the originating author. Respectful 23 | yet robust argument is most welcome. 24 | 25 | Checklist 26 | +++++++++ 27 | 28 | * Your code should be commented in *plain English* (British spelling). 29 | * If your contribution is for a major block of work and you've not done so 30 | already, add yourself to the AUTHORS file following the convention found 31 | therein. 32 | * If in doubt, ask a question. The only stupid question is the one that's never asked. 33 | * Have fun! 34 | -------------------------------------------------------------------------------- /docs/devguide/flashfirmware.rst: -------------------------------------------------------------------------------- 1 | .. _flashfirmware: 2 | 3 | =========================== 4 | Build and Flash MicroPython 5 | =========================== 6 | 7 | Dependencies 8 | ------------ 9 | 10 | - `CMake `_ 11 | - `Arm GCC `_ 12 | - `git `_ 13 | - `ninja `_ 14 | - `python `_ 15 | - `srecord `_ 16 | - `yotta `_ 17 | 18 | Build MicroPython 19 | ----------------- 20 | 21 | The `yotta `_ tool is used to build MicroPython, 22 | but before that takes place additional files have to be generated by the 23 | Makefile in preparation for the build, and additional data is added to the 24 | hex file after. 25 | 26 | Clone the repository and change directory to it:: 27 | 28 | $ git clone https://github.com/bbcmicrobit/micropython 29 | 30 | $ cd micropython 31 | 32 | Configure yotta to use the micro:bit target:: 33 | 34 | yotta target bbc-microbit-classic-gcc-nosd@https://github.com/lancaster-university/yotta-target-bbc-microbit-classic-gcc-nosd 35 | 36 | Run yotta update to fetch remote assets:: 37 | 38 | yotta up 39 | 40 | Start the build using the makefile:: 41 | 42 | make all 43 | 44 | The resulting ``firmware.hex`` can be found in the ``build/`` 45 | directory which can then be copied to the micro:bit. 46 | 47 | The Makefile does some extra preprocessing of the source, which is needed only 48 | if you add new interned strings to ``qstrdefsport.h``. The Makefile also puts 49 | the resulting firmware at build/firmware.hex, and includes some convenience 50 | targets. 51 | 52 | Preparing MicroPython with a Python program 53 | ------------------------------------------- 54 | 55 | Using ``tools/makecombinedhex.py`` you can combine the MicroPython firmware 56 | with a Python script and produce a hex file ready for uploading to the 57 | micro:bit.:: 58 | 59 | ./makecombinedhex.py [-o ] 60 | 61 | The script will output to ``stdout`` if no output option (``-o``) is provided. 62 | 63 | Using ``tools/hexlify.py`` you can turn a Python script into Intel HEX format 64 | to be concatenated at the end of the MicroPython firmware.hex. A simple header 65 | is added to the script.:: 66 | 67 | ./hexlifyscript.py 68 | 69 | It also accepts data on standard input. 70 | 71 | Flashing the micro:bit 72 | ---------------------- 73 | 74 | The micro:bit mounts itself as a USB mass storage device named ``MICROBIT``. 75 | When it detects that a .hex file has been copied to the USB drive, it will 76 | flash it, and start running the program. 77 | -------------------------------------------------------------------------------- /docs/i2c.rst: -------------------------------------------------------------------------------- 1 | I²C 2 | *** 3 | 4 | .. py:module:: microbit.i2c 5 | 6 | The ``i2c`` module lets you communicate with devices connected to your board 7 | using the I²C bus protocol. There can be multiple slave devices connected at 8 | the same time, and each one has its own unique address, that is either fixed 9 | for the device or configured on it. Your board acts as the I²C master. 10 | 11 | We use 7-bit addressing for devices because of the reasons stated 12 | `here `_. 13 | 14 | This may be different to other micro:bit related solutions. 15 | 16 | How exactly you should communicate with the devices, that is, what bytes to 17 | send and how to interpret the responses, depends on the device in question and 18 | should be described separately in that device's documentation. 19 | 20 | 21 | Functions 22 | ========= 23 | 24 | .. py:function:: init(freq=100000, sda=pin20, scl=pin19) 25 | 26 | Re-initialize peripheral with the specified clock frequency ``freq`` on the 27 | specified ``sda`` and ``scl`` pins. 28 | 29 | .. warning:: 30 | 31 | Changing the I²C pins from defaults will make the accelerometer and 32 | compass stop working, as they are connected internally to those pins. 33 | 34 | 35 | .. py:function:: scan() 36 | 37 | Scan the bus for devices. Returns a list of 7-bit addresses corresponding 38 | to those devices that responded to the scan. 39 | 40 | 41 | .. py:function:: read(addr, n, repeat=False) 42 | 43 | Read ``n`` bytes from the device with 7-bit address ``addr``. If ``repeat`` 44 | is ``True``, no stop bit will be sent. 45 | 46 | 47 | .. py:function:: write(addr, buf, repeat=False) 48 | 49 | Write bytes from ``buf`` to the device with 7-bit address ``addr``. If 50 | ``repeat`` is ``True``, no stop bit will be sent. 51 | 52 | 53 | Connecting 54 | ========== 55 | 56 | You should connect the device's ``SCL`` pin to micro:bit pin 19, and the 57 | device's ``SDA`` pin to micro:bit pin 20. You also must connect the device's 58 | ground to the micro:bit ground (pin ``GND``). You may need to power the device 59 | using an external power supply or the micro:bit. 60 | 61 | There are internal pull-up resistors on the I²C lines of the board, but with 62 | particularly long wires or large number of devices you may need to add 63 | additional pull-up resistors, to ensure noise-free communication. 64 | -------------------------------------------------------------------------------- /docs/image-smile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/image-smile.png -------------------------------------------------------------------------------- /docs/music-pins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/music-pins.png -------------------------------------------------------------------------------- /docs/neopixel-croc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/neopixel-croc.png -------------------------------------------------------------------------------- /docs/neopixel.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/neopixel.gif -------------------------------------------------------------------------------- /docs/os.rst: -------------------------------------------------------------------------------- 1 | The ``os`` Module 2 | ****************** 3 | 4 | .. py:module:: os 5 | 6 | MicroPython contains an ``os`` module based upon the ``os`` module in the 7 | Python standard library. It's used for accessing what would traditionally be 8 | termed as operating system dependent functionality. Since there is no operating 9 | system in MicroPython the module provides functions relating to the management 10 | of the simple on-device persistent file system and information about the 11 | current system. 12 | 13 | To access this module you need to:: 14 | 15 | import os 16 | 17 | We assume you have done this for the examples below. 18 | 19 | Functions 20 | ========= 21 | 22 | .. py:function:: listdir() 23 | 24 | Returns a list of the names of all the files contained within the local 25 | persistent on-device file system. 26 | 27 | .. py:function:: remove(filename) 28 | 29 | Removes (deletes) the file named in the argument ``filename``. If the file 30 | does not exist an ``OSError`` exception will occur. 31 | 32 | .. py:function:: size(filename) 33 | 34 | Returns the size, in bytes, of the file named in the argument ``filename``. 35 | If the file does not exist an ``OSError`` exception will occur. 36 | 37 | .. py:function:: uname() 38 | 39 | Returns information identifying the current operating system. The return 40 | value is an object with five attributes: 41 | 42 | * ``sysname`` - operating system name 43 | * ``nodename`` - name of machine on network (implementation-defined) 44 | * ``release`` - operating system release 45 | * ``version`` - operating system version 46 | * ``machine`` - hardware identifier 47 | 48 | 49 | .. note:: 50 | 51 | There is no underlying operating system in MicroPython. As a result the 52 | information returned by the ``uname`` function is mostly useful for 53 | versioning details. 54 | -------------------------------------------------------------------------------- /docs/pinout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/pinout.png -------------------------------------------------------------------------------- /docs/pwm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/pwm.png -------------------------------------------------------------------------------- /docs/random.rst: -------------------------------------------------------------------------------- 1 | Random Number Generation 2 | ************************ 3 | 4 | .. py:module:: random 5 | 6 | This module is based upon the ``random`` module in the Python standard library. 7 | It contains functions for generating random behaviour. 8 | 9 | To access this module you need to:: 10 | 11 | import random 12 | 13 | We assume you have done this for the examples below. 14 | 15 | Functions 16 | ========= 17 | 18 | .. py:function:: getrandbits(n) 19 | 20 | Returns an integer with ``n`` random bits. 21 | 22 | .. warning:: 23 | 24 | Because the underlying generator function returns at most 30 bits, ``n`` 25 | may only be a value between 1-30 (inclusive). 26 | 27 | .. py:function:: seed(n) 28 | 29 | Initialize the random number generator with a known integer ``n``. This 30 | will give you reproducibly deterministic randomness from a given starting 31 | state (``n``). 32 | 33 | 34 | .. py:function:: randint(a, b) 35 | 36 | Return a random integer ``N`` such that ``a <= N <= b``. Alias for 37 | ``randrange(a, b+1)``. 38 | 39 | 40 | .. py:function:: randrange(stop) 41 | 42 | Return a randomly selected integer between zero and up to (but not 43 | including) ``stop``. 44 | 45 | .. py:function:: randrange(start, stop) 46 | 47 | Return a randomly selected integer from ``range(start, stop)``. 48 | 49 | .. py:function:: randrange(start, stop, step) 50 | 51 | Return a randomly selected element from ``range(start, stop, step)``. 52 | 53 | 54 | .. py:function:: choice(seq) 55 | 56 | Return a random element from the non-empty sequence ``seq``. If ``seq`` is 57 | empty, raises ``IndexError``. 58 | 59 | 60 | .. py:function:: random() 61 | 62 | Return the next random floating point number in the range [0.0, 1.0) 63 | 64 | 65 | .. py:function:: uniform(a, b) 66 | 67 | Return a random floating point number ``N`` such that ``a <= N <= b`` 68 | for ``a <= b`` and ``b <= N <= a`` for ``b < a``. 69 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx<8 2 | sphinx_rtd_theme>=1,<2 3 | -------------------------------------------------------------------------------- /docs/scroll-hello.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/scroll-hello.gif -------------------------------------------------------------------------------- /docs/speech-pitch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/speech-pitch.png -------------------------------------------------------------------------------- /docs/speech.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/speech.png -------------------------------------------------------------------------------- /docs/tutorials/binary_count.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/binary_count.gif -------------------------------------------------------------------------------- /docs/tutorials/blue-microbit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/blue-microbit.png -------------------------------------------------------------------------------- /docs/tutorials/dalek.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/dalek.jpg -------------------------------------------------------------------------------- /docs/tutorials/direction.rst: -------------------------------------------------------------------------------- 1 | Direction 2 | --------- 3 | 4 | There is a compass on the BBC micro:bit. If you ever make a weather station 5 | use the device to work out the wind direction. 6 | 7 | Compass 8 | +++++++ 9 | 10 | It can also tell you the direction of North like this:: 11 | 12 | from microbit import * 13 | 14 | compass.calibrate() 15 | 16 | while True: 17 | needle = ((15 - compass.heading()) // 30) % 12 18 | display.show(Image.ALL_CLOCKS[needle]) 19 | 20 | .. note:: 21 | 22 | **You must calibrate the compass before taking readings.** Failure to do so 23 | will produce garbage results. The ``calibration`` method runs a fun little 24 | game to help the device work out where it is in relation to the Earth's 25 | magnetic field. 26 | 27 | To calibrate the compass, tilt the micro:bit around until a circle of pixels is 28 | drawn on the outside edges of the display. 29 | 30 | The program takes the ``compass.heading`` and, using some simple yet 31 | cunning maths, `floor division `_ ``//`` and `modulo `_ ``%``, works out the number of the clock hand to use to display on the screen 32 | so that it is pointing roughly North. 33 | -------------------------------------------------------------------------------- /docs/tutorials/files.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/files.jpg -------------------------------------------------------------------------------- /docs/tutorials/fireflies.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/fireflies.gif -------------------------------------------------------------------------------- /docs/tutorials/firefly.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/firefly.gif -------------------------------------------------------------------------------- /docs/tutorials/happy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/happy.png -------------------------------------------------------------------------------- /docs/tutorials/matrioshka.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/matrioshka.jpg -------------------------------------------------------------------------------- /docs/tutorials/mb-firefly.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/mb-firefly.gif -------------------------------------------------------------------------------- /docs/tutorials/network.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/network.png -------------------------------------------------------------------------------- /docs/tutorials/next.rst: -------------------------------------------------------------------------------- 1 | Next Steps 2 | ---------- 3 | 4 | These tutorials are only the first steps in using MicroPython with the 5 | BBC micro:bit. A musical analogy: you've got a basic understanding of 6 | a very simple instrument and confidently play "Three Blind Mice". 7 | 8 | This is an achievement to build upon. 9 | 10 | Ahead of you is an exciting journey to becoming a virtuoso coder. 11 | 12 | You will encounter frustration, failure and foolishness. When you do please 13 | remember that you're not alone. Python has a secret weapon: the most amazing 14 | community of programmers on the planet. Connect with this community and you 15 | will make friends, find mentors, support each other and share resources. 16 | 17 | The examples in the tutorials are simple to explain but may not be the simplest 18 | or most efficient implementations. We've left out lots of *really fun stuff* so 19 | we could concentrate on arming you with the basics. If you *really* want to 20 | know how to make MicroPython fly on the BBC micro:bit then read the API 21 | reference documentation. It contains information about *all* the capabilities 22 | available to you. 23 | 24 | Explore, experiment and be fearless trying things out ~ for these are the 25 | attributes of a virtuoso coder. To encourage you we have hidden a number of 26 | `Easter eggs `_ in MicroPython 27 | and the Python code editors. They're fun rewards for looking "under the hood" and 28 | "poking with a stick". 29 | 30 | Such skill in Python is valuable: it's one of the world's most popular 31 | professional programming languages. 32 | 33 | Amaze us with your code! Make things that delight us! Most of all, have fun! 34 | 35 | Happy hacking! 36 | -------------------------------------------------------------------------------- /docs/tutorials/piezo_buzzer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/piezo_buzzer.jpg -------------------------------------------------------------------------------- /docs/tutorials/pin0-gnd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/pin0-gnd.png -------------------------------------------------------------------------------- /docs/tutorials/queen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/docs/tutorials/queen.jpg -------------------------------------------------------------------------------- /examples/analog_watch.py: -------------------------------------------------------------------------------- 1 | from microbit import * 2 | 3 | hands = Image.ALL_CLOCKS 4 | 5 | #A centre dot of brightness 2. 6 | ticker_image = Image("2\n").crop(-2,-2,5,5) 7 | 8 | #Adjust these to taste 9 | MINUTE_BRIGHT = 0.1111 10 | HOUR_BRIGHT = 0.55555 11 | 12 | #Generate hands for 5 minute intervals 13 | def fiveticks(): 14 | fivemins = 0 15 | hours = 0 16 | while True: 17 | yield hands[fivemins]*MINUTE_BRIGHT + hands[hours]*HOUR_BRIGHT 18 | fivemins = (fivemins+1)%12 19 | hours = (hours + (fivemins == 0))%12 20 | 21 | #Generate hands with ticker superimposed for 1 minute intervals. 22 | def ticks(): 23 | on = True 24 | for face in fiveticks(): 25 | for i in range(5): 26 | if on: 27 | yield face + ticker_image 28 | else: 29 | yield face - ticker_image 30 | on = not on 31 | 32 | #Run a clock speeded up 60 times, so we can watch the animation. 33 | for tick in ticks(): 34 | display.show(tick) 35 | sleep(1000) 36 | -------------------------------------------------------------------------------- /examples/asmleds.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script uses the inline assembler to make the LEDs light up 3 | in a pattern based on how they are multiplexed in rows/cols. 4 | """ 5 | 6 | # row pins: 13, 14, 15 7 | # col pins: 4..12 inclusive 8 | # GPIO words starting at 0x50000500: 9 | # RESERVED, OUT, OUTSET, OUTCLR, IN, DIR, DIRSET, DIRCLR 10 | 11 | @micropython.asm_thumb 12 | def led_cycle(): 13 | b(START) 14 | 15 | # DELAY routine 16 | label(DELAY) 17 | mov(r3, 0xa0) 18 | lsl(r3, r3, 11) 19 | label(delay_loop) 20 | sub(r3, 1) 21 | bne(delay_loop) 22 | bx(lr) 23 | 24 | label(START) 25 | 26 | cpsid('i') # disable interrupts so we control the display 27 | 28 | mov(r0, 0x50) # r0=0x50 29 | lsl(r0, r0, 16) # r0=0x500000 30 | add(r0, 0x05) # r0=0x500005 31 | lsl(r0, r0, 8) # r0=0x50000500 -- this points to GPIO registers 32 | mov(r1, 0b111) 33 | lsl(r1, r1, 13) # r1=0xe000 34 | str(r1, [r0, 8]) # pull all rows high 35 | 36 | mov(r1, 1 << 4) # r1 holds current col bit 37 | mov(r2, 9) # r2 holds number of cols left 38 | label(loop_on) 39 | str(r1, [r0, 12]) # pull col low to turn LEDs on 40 | bl(DELAY) # wait 41 | lsl(r1, r1, 1) # shift to next col 42 | sub(r2, 1) # decrease col counter 43 | bne(loop_on) # loop while there are still cols left 44 | 45 | mov(r1, 1 << 4) # r1 holds current col bit 46 | mov(r2, 9) # r2 holds number of cols left 47 | label(loop_off) 48 | str(r1, [r0, 8]) # pull col high to turn LEDs off 49 | bl(DELAY) # wait 50 | lsl(r1, r1, 1) # shift to next col 51 | sub(r2, 1) # decrease col counter 52 | bne(loop_off) # loop while there are still cols left 53 | 54 | cpsie('i') # enable interrupts 55 | 56 | for i in range(4): 57 | led_cycle() 58 | -------------------------------------------------------------------------------- /examples/bubble_level_2d.py: -------------------------------------------------------------------------------- 1 | """ 2 | Two-dimensional bubble level which uses the accelerometer. 3 | """ 4 | 5 | from microbit import * 6 | 7 | sensitivity = 'medium' # Change to 'low', 'medium', or 'high' to adjust 8 | divisors = {'low':64, 'medium':32, 'high':16} 9 | 10 | def clamp(number, min, max): 11 | """Returns number limited to range specified by min and max, inclusive""" 12 | if number < min: 13 | return min 14 | elif number > max: 15 | return max 16 | else: 17 | return number 18 | 19 | while True: 20 | x_grav, y_grav, _ = accelerometer.get_values() 21 | # Map raw values from accelerometer to pixels on display 22 | x_pixel = 4 - clamp(2 + x_grav // divisors.get(sensitivity), 0, 4) 23 | y_pixel = 4 - clamp(2 + y_grav // divisors.get(sensitivity), 0, 4) 24 | display.clear() 25 | display.set_pixel(x_pixel, y_pixel, 9) 26 | sleep(100) -------------------------------------------------------------------------------- /examples/compass.py: -------------------------------------------------------------------------------- 1 | """ 2 | compass.py 3 | ~~~~~~~~~~ 4 | 5 | Creates a compass. 6 | 7 | The user will need to calibrate the compass first. The compass uses the 8 | built-in clock images to display the position of the needle. 9 | 10 | """ 11 | from microbit import * 12 | 13 | 14 | # Start calibrating 15 | compass.calibrate() 16 | 17 | # Try to keep the needle pointed in (roughly) the correct direction 18 | while True: 19 | sleep(100) 20 | needle = ((15 - compass.heading()) // 30) % 12 21 | display.show(Image.ALL_CLOCKS[needle]) 22 | -------------------------------------------------------------------------------- /examples/conway.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Conway's Game Of Life for the micro:bit 3 | 4 | Press button A or tap the micro:bit to generate a fresh layout. 5 | ''' 6 | 7 | import microbit 8 | import random 9 | 10 | arena1 = bytearray(7 * 7) 11 | arena2 = bytearray(7 * 7) 12 | 13 | def show(): 14 | img = microbit.Image(5,5) 15 | for y in range(5): 16 | for x in range(5): 17 | img.set_pixel(x, y, arena1[8 + y * 7 + x]*9) 18 | microbit.display.show(img) 19 | 20 | # do 1 iteration of Conway's Game of Life 21 | def conway_step(): 22 | global arena1, arena2 23 | for i in range(5 * 5): # loop over pixels 24 | i = 8 + (i // 5) * 7 + i % 5 25 | # count number of neighbours 26 | num_neighbours = (arena1[i - 8] + 27 | arena1[i - 7] + 28 | arena1[i - 6] + 29 | arena1[i - 1] + 30 | arena1[i + 1] + 31 | arena1[i + 6] + 32 | arena1[i + 7] + 33 | arena1[i + 8]) 34 | # check if the centre cell is alive or not 35 | self = arena1[i] 36 | # apply the rules of life 37 | if self and not (2 <= num_neighbours <= 3): 38 | arena2[i] = 0 # not enough, or too many neighbours: cell dies 39 | elif not self and num_neighbours == 3: 40 | arena2[i] = 1 # exactly 3 neighbours around an empty cell: cell is born 41 | else: 42 | arena2[i] = self # stay as-is 43 | # swap the buffers (arena1 is now the new one to display) 44 | arena1, arena2 = arena2, arena1 45 | 46 | while True: 47 | # randomise the start 48 | for i in range(5 * 5): # loop over pixels 49 | i = 8 + (i // 5) * 7 + i % 5 50 | arena1[i] = random.randrange(2) # set the pixel randomly 51 | show() 52 | microbit.sleep(1) # need to yield to update accelerometer (not ideal...) 53 | 54 | # loop while button a is not pressed 55 | while not microbit.button_a.is_pressed() and microbit.accelerometer.get_z() < -800: 56 | conway_step() 57 | show() 58 | microbit.sleep(150) 59 | -------------------------------------------------------------------------------- /examples/counter.py: -------------------------------------------------------------------------------- 1 | """ 2 | counter.py 3 | ~~~~~~~~~~ 4 | Creates a counter that increments on pressing button a. 5 | Scrolls the current count on the led display. 6 | """ 7 | 8 | import microbit 9 | ctr = 0 # Initialize counter 10 | while True: # Loop forever 11 | ctr = ctr + microbit.button_a.get_presses() # Count the amount of presses 12 | if ctr > 0: # Only execute if not zero 13 | microbit.display.scroll(str(ctr)) # Display the counter 14 | microbit.sleep(100) # Sleep for 100ms 15 | -------------------------------------------------------------------------------- /examples/die20.py: -------------------------------------------------------------------------------- 1 | """ 2 | die20.py 3 | ~~~~~~~~ 4 | Rolls a 20-sided die. If a 20 is rolled, display a short series of images and 5 | play some music. The skull image represents 20. If a 1 is rolled, display a sad 6 | face and play some music. 7 | The music isn't required, but if you want to hear it, you'll need a 8 | speaker/buzzer/headphones connected to P0 and GND. 9 | """ 10 | 11 | from microbit import * 12 | import random 13 | import music 14 | 15 | # A list of images to display if 20 (crit) is rolled 16 | critimages = [Image.HEART, Image.HEART_SMALL, Image.SKULL] 17 | 18 | # Loop forever 19 | while True: 20 | # User can press button A or shake the microbit to "roll" 21 | if button_a.was_pressed() or accelerometer.was_gesture("shake"): 22 | dice = random.randint(1, 20) 23 | if dice == 20: 24 | # Set wait to False to that it's not blocking. 25 | # Music will play while images are cycled through. 26 | music.play(music.POWER_UP, wait=False) 27 | display.show(critimages, delay=1400) 28 | elif dice == 1: 29 | music.play(music.WAWAWAWAA, wait=False) 30 | display.show(Image.SAD) 31 | # For single digit numbers, show the number. Scroll for double-digits. 32 | elif 10 > dice > 1: 33 | display.show(str(dice)) 34 | else: 35 | display.scroll(str(dice), wait=False, loop=True) 36 | -------------------------------------------------------------------------------- /examples/fallingblocks.py: -------------------------------------------------------------------------------- 1 | from microbit import * 2 | import random 3 | 4 | 5 | class FallingBlocks: 6 | def __init__(self): 7 | self.screen = Image(5, 5) 8 | self.movingDot = None 9 | self.points = 0 10 | self.gameOver = False 11 | 12 | def addDot(self, i): 13 | if self.screen.get_pixel(i, 0) == 9: 14 | self.gameOver = True 15 | else: 16 | self.movingDot = (i, 0) 17 | self.screen.set_pixel(i, 0, 9) 18 | 19 | def stepDown(self): 20 | x, y = self.movingDot 21 | if y + 1 < 5 and self.screen.get_pixel(x, y + 1) == 0: 22 | self.screen.set_pixel(x, y, 0) 23 | self.screen.set_pixel(x, y + 1, 9) 24 | self.movingDot = (x, y + 1) 25 | else: 26 | self.movingDot = None 27 | 28 | def move(self, v): 29 | x, y = self.movingDot 30 | if x + v >= 0 and x + v < 5 and self.screen.get_pixel(x + v, y) == 0: 31 | self.screen.set_pixel(x, y, 0) 32 | self.screen.set_pixel(x + v, y, 9) 33 | self.movingDot = (x + v, y) 34 | 35 | def hasMovingDot(self): 36 | return self.movingDot != None 37 | 38 | def screenDown(self): 39 | self.screen = self.screen.shift_down(1) 40 | 41 | def checkLine(self): 42 | if all(self.screen.get_pixel(i, 4) == 9 for i in range(5)): 43 | self.points += 1 44 | self.screenDown() 45 | return True 46 | return False 47 | 48 | 49 | while True: 50 | SPEED = 500 51 | SPEED2 = 200 52 | STEP = 10 53 | game = FallingBlocks() 54 | while not game.gameOver: 55 | if not game.hasMovingDot(): 56 | game.addDot(random.randint(0, 4)) 57 | display.show(game.screen) 58 | if not game.gameOver: 59 | t0 = running_time() 60 | while running_time() - t0 < SPEED: 61 | reading = accelerometer.get_x() 62 | if reading > 20: 63 | game.move(1) 64 | elif reading < -20: 65 | game.move(-1) 66 | display.show(game.screen) 67 | sleep(SPEED2) 68 | game.stepDown() 69 | if game.checkLine(): 70 | if SPEED >= STEP: 71 | SPEED -= STEP 72 | if SPEED2 >= STEP: 73 | SPEED2 -= STEP 74 | 75 | while True: 76 | display.scroll("Game Over !") 77 | display.scroll(str(game.points) + " points") 78 | if button_a.was_pressed(): 79 | break 80 | -------------------------------------------------------------------------------- /examples/flappybit.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Flappy Bit 3 | 4 | Control the bit by tilting the micro:bit 5 | 6 | Avoid the obstacles 7 | 8 | Create your own terrain by editing the terrain list below: 9 | ''' 10 | 11 | import music 12 | from microbit import (accelerometer, 13 | display, 14 | sleep, 15 | Image, 16 | reset, 17 | ) 18 | 19 | display.scroll('Flappy Bit') 20 | 21 | bird = 2 22 | terrain = [ 23 | (0, 0), 24 | (0, 0), 25 | (0, 0), 26 | (0, 0), 27 | (0, 2), 28 | (0, 0), 29 | (0, 0), 30 | (3, 0), 31 | (3, 0), 32 | (4, 0), 33 | (3, 0), 34 | (0, 0), 35 | (0, 0), 36 | (0, 1), 37 | (2, 0), 38 | (3, 0), 39 | (4, 0), 40 | (3, 0), 41 | (0, 0), 42 | (0, 1), 43 | (2, 0), 44 | ] 45 | 46 | terrain_multiplier = 5 47 | pos = 0 48 | 49 | while True: 50 | sleep(100) 51 | if -256 < accelerometer.get_y() < 450: 52 | bird = max(0, bird - 1) 53 | elif 568 < accelerometer.get_y() < 1024: 54 | bird = min(4, bird + 1) 55 | 56 | display.clear() 57 | display.set_pixel(0, bird, 9) 58 | 59 | pos_terrain = pos // terrain_multiplier 60 | lost_status = False 61 | for column, (top, bottom) in enumerate( 62 | terrain[pos_terrain:pos_terrain + 5]): 63 | for y in range(top): 64 | display.set_pixel(column, y, 4) 65 | if column == 0 and bird == y: 66 | lost_status = True 67 | for y in range(bottom): 68 | display.set_pixel(column, 4 - y, 4) 69 | if column == 0 and bird == (4 - y): 70 | lost_status = True 71 | if lost_status: 72 | display.show(Image.SAD) 73 | music.play(music.FUNERAL) 74 | reset() 75 | pos += 1 76 | if pos_terrain > len(terrain): 77 | pos = 0 78 | -------------------------------------------------------------------------------- /examples/i_feel_today.py: -------------------------------------------------------------------------------- 1 | """ 2 | Program that shows different emotions. 3 | Push button "A" to become sadder and "B" to become happier. 4 | """ 5 | 6 | from microbit import * 7 | 8 | horror = Image("09090:00000:09990:90009:99999") 9 | better_meh = Image("00000:09090:00000:99999:00000") 10 | joy = Image("09090:00000:99999:90009:09990") 11 | 12 | emotions = [horror, Image.SAD, better_meh, Image.HAPPY, joy] 13 | current_emotion = 2 14 | 15 | while True: 16 | if button_a.get_presses(): 17 | current_emotion = max(current_emotion - 1, 0) 18 | elif button_b.get_presses(): 19 | current_emotion = min(current_emotion + 1, 4) 20 | display.show(emotions[current_emotion]) -------------------------------------------------------------------------------- /examples/led_dance.py: -------------------------------------------------------------------------------- 1 | # Light LEDs at random and make them fade over time 2 | # 3 | # Usage: 4 | # 5 | # led_dance(delay) 6 | # 7 | # 'delay' is the time between each new LED being turned on. 8 | # 9 | # TODO The random number generator is not great. Perhaps the accelerometer 10 | # or compass could be used to add entropy. 11 | 12 | import microbit 13 | import random 14 | 15 | def led_dance(delay): 16 | dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ] 17 | while True: 18 | dots[random.randrange(5)][random.randrange(5)] = 8 19 | for i in range(5): 20 | for j in range(5): 21 | microbit.display.set_pixel(i, j, dots[i][j]) 22 | dots[i][j] = max(dots[i][j] - 1, 0) 23 | microbit.sleep(delay) 24 | 25 | led_dance(100) 26 | -------------------------------------------------------------------------------- /examples/magic8.py: -------------------------------------------------------------------------------- 1 | # Magic 8 ball by Nicholas Tollervey. February 2016. 2 | # 3 | # Ask a question then shake. 4 | # 5 | # This program has been placed into the public domain. 6 | from microbit import * 7 | import random 8 | 9 | answers = [ 10 | "It is certain", 11 | "It is decidedly so", 12 | "Without a doubt", 13 | "Yes, definitely", 14 | "You may rely on it", 15 | "As I see it, yes", 16 | "Most likely", 17 | "Outlook good", 18 | "Yes", 19 | "Signs point to yes", 20 | "Reply hazy try again", 21 | "Ask again later", 22 | "Better not tell you now", 23 | "Cannot predict now", 24 | "Concentrate and ask again", 25 | "Don't count on it", 26 | "My reply is no", 27 | "My sources say no", 28 | "Outlook not so good", 29 | "Very doubtful", 30 | ] 31 | 32 | while True: 33 | display.show('8') 34 | if accelerometer.was_gesture('shake'): 35 | display.clear() 36 | sleep(1000) 37 | display.scroll(random.choice(answers)) 38 | sleep(10) 39 | -------------------------------------------------------------------------------- /examples/maze.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple maze program. You are the flashing dot and can walk around 3 | using the accelerometer. 4 | """ 5 | 6 | import microbit 7 | 8 | d = microbit.display 9 | ac = microbit.accelerometer 10 | 11 | # the maze data, as binary numbers (outside walls are added automatically) 12 | maze = [ 13 | 0b0000000000000000, 14 | 0b0100010101011110, 15 | 0b0100010101010010, 16 | 0b0111110100000000, 17 | 0b0000000111111110, 18 | 0b0111111101000000, 19 | 0b0101010001011100, 20 | 0b0101000100000100, 21 | 0b0100011111111100, 22 | 0b0101010001000110, 23 | 0b0101000100010010, 24 | 0b0101010111010110, 25 | 0b0111010101010010, 26 | 0b0000010100010010, 27 | 0b0111110111111110, 28 | 0b0000000000000000, 29 | ] 30 | 31 | def get_maze(x, y): 32 | if 0 <= x < 16 and 0 <= y < 16: 33 | return (maze[y] >> (15 - x)) & 1 34 | else: 35 | return 1 36 | 37 | def draw(x, y, tick): 38 | img = microbit.Image(5,5) 39 | for j in range(5): 40 | for i in range(5): 41 | img.set_pixel(i, j, get_maze(x + i - 2, y + j - 2)*5) 42 | 43 | # draw the player, flashing 44 | img.set_pixel(2, 2, (tick & 1)*4+5) 45 | d.show(img) 46 | 47 | def main(): 48 | x = 0 49 | y = 0 50 | tick = 0 51 | while True: 52 | tick += 1 53 | if tick == 4: 54 | # walk around, with collision detection 55 | tick = 0 56 | if ac.get_x() > 200 and get_maze(x + 1, y) == 0: 57 | x += 1 58 | elif ac.get_x() < -200 and get_maze(x - 1, y) == 0: 59 | x -= 1 60 | elif ac.get_y() > 200 and get_maze(x, y + 1) == 0: 61 | y += 1 62 | elif ac.get_y() < -200 and get_maze(x, y - 1) == 0: 63 | y -= 1 64 | x = min(15, max(0, x)) 65 | y = min(15, max(0, y)) 66 | 67 | # draw the maze 68 | draw(x, y, tick) 69 | 70 | 71 | microbit.sleep(50) 72 | 73 | main() 74 | -------------------------------------------------------------------------------- /examples/music.py: -------------------------------------------------------------------------------- 1 | """ 2 | music.py 3 | ~~~~~~~~ 4 | 5 | Plays a simple tune using the Micropython music module. 6 | This example requires a speaker/buzzer/headphones connected to P0 and GND. 7 | """ 8 | from microbit import * 9 | import music 10 | 11 | # play Prelude in C. 12 | notes = [ 13 | 'c4:1', 'e', 'g', 'c5', 'e5', 'g4', 'c5', 'e5', 'c4', 'e', 'g', 'c5', 'e5', 'g4', 'c5', 'e5', 14 | 'c4', 'd', 'a', 'd5', 'f5', 'a4', 'd5', 'f5', 'c4', 'd', 'a', 'd5', 'f5', 'a4', 'd5', 'f5', 15 | 'b3', 'd4', 'g', 'd5', 'f5', 'g4', 'd5', 'f5', 'b3', 'd4', 'g', 'd5', 'f5', 'g4', 'd5', 'f5', 16 | 'c4', 'e', 'g', 'c5', 'e5', 'g4', 'c5', 'e5', 'c4', 'e', 'g', 'c5', 'e5', 'g4', 'c5', 'e5', 17 | 'c4', 'e', 'a', 'e5', 'a5', 'a4', 'e5', 'a5', 'c4', 'e', 'a', 'e5', 'a5', 'a4', 'e5', 'a5', 18 | 'c4', 'd', 'f#', 'a', 'd5', 'f#4', 'a', 'd5', 'c4', 'd', 'f#', 'a', 'd5', 'f#4', 'a', 'd5', 19 | 'b3', 'd4', 'g', 'd5', 'g5', 'g4', 'd5', 'g5', 'b3', 'd4', 'g', 'd5', 'g5', 'g4', 'd5', 'g5', 20 | 'b3', 'c4', 'e', 'g', 'c5', 'e4', 'g', 'c5', 'b3', 'c4', 'e', 'g', 'c5', 'e4', 'g', 'c5', 21 | 'a3', 'c4', 'e', 'g', 'c5', 'e4', 'g', 'c5', 'a3', 'c4', 'e', 'g', 'c5', 'e4', 'g', 'c5', 22 | 'd3', 'a', 'd4', 'f#', 'c5', 'd4', 'f#', 'c5', 'd3', 'a', 'd4', 'f#', 'c5', 'd4', 'f#', 'c5', 23 | 'g3', 'b', 'd4', 'g', 'b', 'd', 'g', 'b', 'g3', 'b3', 'd4', 'g', 'b', 'd', 'g', 'b' 24 | ] 25 | 26 | music.play(notes) 27 | -------------------------------------------------------------------------------- /examples/neopixel_random.py: -------------------------------------------------------------------------------- 1 | """ 2 | neopixel_random.py 3 | 4 | Repeatedly displays random colours onto the LED strip. 5 | This example requires a strip of 8 Neopixels (WS2812) connected to pin0. 6 | 7 | """ 8 | from microbit import * 9 | import neopixel 10 | from random import randint 11 | 12 | # Setup the Neopixel strip on pin0 with a length of 8 pixels 13 | np = neopixel.NeoPixel(pin0, 8) 14 | 15 | while True: 16 | #Iterate over each LED in the strip 17 | 18 | for pixel_id in range(0, len(np)): 19 | red = randint(0, 60) 20 | green = randint(0, 60) 21 | blue = randint(0, 60) 22 | 23 | # Assign the current LED a random red, green and blue value between 0 and 60 24 | np[pixel_id] = (red, green, blue) 25 | 26 | # Display the current pixel data on the Neopixel strip 27 | np.show() 28 | sleep(100) 29 | -------------------------------------------------------------------------------- /examples/play_file.py: -------------------------------------------------------------------------------- 1 | #Plays a file on the specified pins. 2 | import audio 3 | 4 | def audio_generator(file, frame): 5 | ln = -1 6 | while ln: 7 | ln = file.readinto(frame) 8 | yield frame 9 | 10 | def play_file(name, pin=None, return_pin=None): 11 | #Do allocation here, as we can't do it in an interrupt. 12 | frame = audio.AudioFrame() 13 | with open(name) as file: 14 | audio.play(audio_generator(file, frame), pin=pin, return_pin=return_pin) 15 | -------------------------------------------------------------------------------- /examples/pomodoro.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple pomodoro timer. 3 | It times a 25 minute work session then 5 minutes rest. 4 | Press the reset button to restart the timer. 5 | """ 6 | 7 | from microbit import * 8 | 9 | # Tweak CLOCK_ADJUST to make your system clock more accurate. 10 | # My clock is too fast by 4 seconds every minute so I use 4/60. 11 | # If your clock is too slow by 3 seconds every minute use -3/60. 12 | 13 | CLOCK_ADJUST = 4/60 14 | 15 | ALL_LEDS_ON = Image('99999:'*5) 16 | 17 | 18 | def index_to_xy(i): 19 | x = i % 5 20 | y = int(i / 5) 21 | return x, y 22 | 23 | 24 | def show_alarm(): 25 | for i in range(10): 26 | display.show(ALL_LEDS_ON) 27 | sleep(250) 28 | display.clear() 29 | sleep(250) 30 | 31 | 32 | def run_timer(seconds, LED_state): 33 | interval = int(seconds * 1000 / 25 * (1 + CLOCK_ADJUST)) 34 | intervals_remaining = 25 35 | timer = running_time() 36 | 37 | while intervals_remaining > 0: 38 | 39 | # Every interval set a pixel to LED_state 40 | time = running_time() 41 | if time - timer >= interval: 42 | timer = time 43 | x, y = index_to_xy(intervals_remaining - 1) 44 | display.set_pixel(x, y, LED_state) 45 | intervals_remaining -= 1 46 | 47 | 48 | print("pomodoro timer") 49 | 50 | 51 | # time the pomodoro work session, 25 minutes 52 | display.scroll("Go!") 53 | display.show(ALL_LEDS_ON) 54 | run_timer(25 * 60, 0) 55 | show_alarm() 56 | 57 | 58 | # time the pomodoro break, 5 minutes 59 | display.scroll("break") 60 | display.clear() 61 | run_timer(5 * 60, 1) 62 | show_alarm() 63 | 64 | display.show(Image.NO) 65 | 66 | print("finished\n") 67 | print("Press the reset button to restart timer.") 68 | -------------------------------------------------------------------------------- /examples/radio.py: -------------------------------------------------------------------------------- 1 | # A micro:bit Firefly. 2 | # By Nicholas H.Tollervey. Released to the public domain. 3 | import radio 4 | import random 5 | from microbit import display, Image, button_a, sleep 6 | 7 | # Create the "flash" animation frames. Can you work out how it's done? 8 | flash = [Image().invert()*(i/9) for i in range(9, -1, -1)] 9 | 10 | # Event loop. 11 | while True: 12 | # Button A sends a "flash" message. 13 | if button_a.was_pressed(): 14 | radio.send('flash') # a-ha 15 | # Read any incoming messages. 16 | incoming = radio.receive() 17 | if incoming == 'flash': 18 | # If there's an incoming "flash" message display 19 | # the firefly flash animation after a random short 20 | # pause. 21 | sleep(random.randint(50, 350)) 22 | display.show(flash, delay=100, wait=False) 23 | # Randomly re-broadcast the flash message after a 24 | # slight delay. 25 | if random.randint(0, 9) == 0: 26 | sleep(500) 27 | radio.send('flash') # a-ha 28 | -------------------------------------------------------------------------------- /examples/reaction_game.py: -------------------------------------------------------------------------------- 1 | from microbit import * 2 | import random 3 | 4 | clockwise_images = [ 5 | Image.ARROW_W, 6 | Image.ARROW_NW, 7 | Image.ARROW_N, 8 | Image.ARROW_NE, 9 | Image.ARROW_E, 10 | Image.ARROW_SE, 11 | Image.ARROW_S, 12 | Image.ARROW_SW, 13 | Image.ARROW_W, 14 | Image.ARROW_NW, 15 | Image.ARROW_N, 16 | Image.ARROW_NE, 17 | Image.ARROW_E, 18 | ] 19 | 20 | anti_clockwise_images = reversed(clockwise_images) 21 | 22 | 23 | def countDown(x): 24 | while x > 0: 25 | msg = "%d" % (x) 26 | display.show(msg) 27 | sleep(500) 28 | x = x - 1 29 | display.clear() 30 | 31 | 32 | def spin(direction): 33 | if direction is "b": 34 | display.show(clockwise_images, 100) 35 | if direction is "a": 36 | display.show(anti_clockwise_images, 100) 37 | flash(direction) 38 | 39 | 40 | def flash(direction): 41 | number_of_flashes = 10 42 | direction_image = Image.ARROW_N 43 | if direction is "b": 44 | direction_image = Image.ARROW_E 45 | if direction is "a": 46 | direction_image = Image.ARROW_W 47 | while number_of_flashes > 0: 48 | display.show(direction_image) 49 | sleep(200) 50 | display.clear() 51 | sleep(200) 52 | number_of_flashes = number_of_flashes - 1 53 | 54 | 55 | countDown(5) 56 | howLong = random.randrange(7000) 57 | display.show(Image.SAD) 58 | sleep(howLong) 59 | 60 | while (not button_a.is_pressed()) and (not button_b.is_pressed()): 61 | display.show(Image.HAPPY) 62 | sleep(1) 63 | 64 | if button_a.is_pressed(): 65 | spin("a") 66 | else: 67 | spin("b") 68 | 69 | sleep(1000) 70 | display.clear() 71 | -------------------------------------------------------------------------------- /examples/reverb.py: -------------------------------------------------------------------------------- 1 | import audio 2 | 3 | def from_file(file, frame): 4 | ln = -1 5 | while ln: 6 | ln = file.readinto(frame) 7 | yield frame 8 | 9 | def reverb_gen(src, buckets, reflect, fadeout): 10 | bucket_count = len(buckets) 11 | bucket = 0 12 | for frame in src: 13 | echo = buckets[bucket] 14 | echo *= reflect 15 | echo += frame 16 | yield echo 17 | buckets[bucket] = echo 18 | bucket += 1 19 | if bucket == bucket_count: 20 | bucket = 0 21 | while fadeout: 22 | fadeout -= 1 23 | echo = buckets[bucket] 24 | echo *= reflect 25 | yield echo 26 | buckets[bucket] = echo 27 | bucket += 1 28 | if bucket == bucket_count: 29 | bucket = 0 30 | 31 | def reverb(src, delay, reflect): 32 | #Do all allocation up front, so we don't need to do any in the generator. 33 | bucket_count = delay>>2 34 | buckets = [ None ] * bucket_count 35 | for i in range(bucket_count): 36 | buckets[i] = audio.AudioFrame() 37 | vol = 1.0 38 | fadeout = 0 39 | while vol > 0.05: 40 | fadeout += bucket_count 41 | vol *= reflect 42 | return reverb_gen(src, buckets, reflect, fadeout) 43 | 44 | def play_file(name, delay=80, reflect=0.5): 45 | #Do allocation here, as we can't do it in an interrupt. 46 | frame = audio.AudioFrame() 47 | with open(name) as file: 48 | gen = from_file(file, frame) 49 | r = reverb(gen, delay, reflect) 50 | audio.play(r) 51 | -------------------------------------------------------------------------------- /examples/speech.py: -------------------------------------------------------------------------------- 1 | """ 2 | speech.py 3 | ~~~~~~~~ 4 | Simple speech example to make the micro:bit say, pronounce and sing 5 | something. This example requires a speaker/buzzer/headphones connected 6 | to P0 and GND,or the latest micro:bit device with built-in speaker. 7 | """ 8 | import speech 9 | from microbit import sleep 10 | 11 | # The say method attempts to convert English into phonemes. 12 | speech.say("I can sing!") 13 | sleep(1000) 14 | speech.say("Listen to me!") 15 | sleep(1000) 16 | 17 | # Clearing the throat requires the use of phonemes. Changing 18 | # the pitch and speed also helps create the right effect. 19 | speech.pronounce("AEAE/HAEMM", pitch=200, speed=100) # Ahem 20 | sleep(1000) 21 | 22 | # Singing requires a phoneme with an annotated pitch for each syllable. 23 | solfa = [ 24 | "#115DOWWWWWW", # Doh 25 | "#103REYYYYYY", # Re 26 | "#94MIYYYYYY", # Mi 27 | "#88FAOAOAOAOR", # Fa 28 | "#78SOHWWWWW", # Soh 29 | "#70LAOAOAOAOR", # La 30 | "#62TIYYYYYY", # Ti 31 | "#58DOWWWWWW", # Doh 32 | ] 33 | 34 | # Sing the scale ascending in pitch. 35 | song = ''.join(solfa) 36 | speech.sing(song, speed=100) 37 | # Reverse the list of syllables. 38 | solfa.reverse() 39 | song = ''.join(solfa) 40 | # Sing the scale descending in pitch. 41 | speech.sing(song, speed=100) 42 | -------------------------------------------------------------------------------- /examples/tiltmusic.py: -------------------------------------------------------------------------------- 1 | # TiltMusic by Alex "Chozabu" P-B. September 2016. 2 | # 3 | # Tilt Y to change Pitch 4 | # press A to turn sound on or off 5 | # hold B and tilt X to change the note length 6 | # 7 | # A quick demo can be found at https://youtu.be/vvECQTDiWxQ 8 | # 9 | # This program has been placed into the public domain. 10 | 11 | from microbit import * 12 | import music 13 | 14 | #A selection of sharp notes 15 | notes = [233.08, 277.18, 311.13, 369.99, 415.30, 16 | 466.16, 554.37, 622.25, 739.99, 830.61, 932.33, 17 | 1108.73, 1244.51, 1479.98, 1661.22, 1864.66, 18 | 2217.46, 2489.02, 2959.96, 3322.44, 3729.31, 19 | 4434.92, 4978.03, 5919.91, 6644.88, 7458.62] 20 | 21 | #note lengths 22 | note_durations = [ 23 | 50, 100, 200, 400, 800 24 | ] 25 | durationlen = len(note_durations) 26 | notelen = len(notes) 27 | 28 | duration = 100 29 | 30 | play_music = True 31 | 32 | while True: 33 | #get accelerometer readings 34 | xreading = abs(accelerometer.get_x()) 35 | yreading = abs(accelerometer.get_y()) 36 | 37 | #use a to toggle music 38 | if button_a.was_pressed(): 39 | play_music = not play_music 40 | if not play_music: 41 | continue 42 | 43 | #get a note based on tilt 44 | note = xreading*.01 45 | pitch = notes[int(note)%notelen] 46 | 47 | #if b is pressed, alter the length based on tilt 48 | if button_b.is_pressed() == 1: 49 | #pitch *= .5 50 | duration = note_durations[int(yreading*0.01)%durationlen] 51 | 52 | #play our sound! 53 | music.pitch(int(pitch), duration) 54 | 55 | -------------------------------------------------------------------------------- /examples/waveforms.py: -------------------------------------------------------------------------------- 1 | from microbit import display, sleep, button_a 2 | import audio 3 | import math 4 | 5 | def repeated_frame(frame, count): 6 | for i in range(count): 7 | yield frame 8 | 9 | # Press button A to skip to next wave. 10 | def show_wave(name, frame, duration=1500): 11 | display.scroll(name + " wave", wait=False,delay=100) 12 | audio.play(repeated_frame(frame, duration),wait=False) 13 | for i in range(75): 14 | sleep(100) 15 | if button_a.is_pressed(): 16 | display.clear() 17 | audio.stop() 18 | break 19 | 20 | frame = audio.AudioFrame() 21 | 22 | for i in range(len(frame)): 23 | frame[i] = int(math.sin(math.pi*i/16)*124+128.5) 24 | show_wave("Sine", frame) 25 | 26 | triangle = audio.AudioFrame() 27 | 28 | QUARTER = len(triangle)//4 29 | for i in range(QUARTER): 30 | triangle[i] = i*15 31 | triangle[i+QUARTER] = 248-i*15 32 | triangle[i+QUARTER*2] = 128-i*15 33 | triangle[i+QUARTER*3] = i*15+8 34 | show_wave("Triangle", triangle) 35 | 36 | square = audio.AudioFrame() 37 | 38 | HALF = len(square)//2 39 | for i in range(HALF): 40 | square[i] = 8 41 | square[i+HALF] = 248 42 | show_wave("Square", square) 43 | sleep(1000) 44 | 45 | for i in range(len(frame)): 46 | frame[i] = 252-i*8 47 | show_wave("Sawtooth", frame) 48 | 49 | del frame 50 | 51 | #Generate a waveform that goes from triangle to square wave, reasonably smoothly. 52 | frames = [ None ] * 32 53 | for i in range(32): 54 | frames[i] = frame = audio.AudioFrame() 55 | for j in range(len(triangle)): 56 | frame[j] = (triangle[j]*(32-i) + square[j]*i)>>5 57 | 58 | def repeated_frames(frames, count): 59 | for frame in frames: 60 | for i in range(count): 61 | yield frame 62 | 63 | 64 | display.scroll("Ascending wave", wait=False) 65 | audio.play(repeated_frames(frames, 60)) 66 | -------------------------------------------------------------------------------- /inc/extmod/machine_mem.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2015 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H 27 | #define MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H 28 | 29 | #include "py/obj.h" 30 | 31 | typedef struct _machine_mem_obj_t { 32 | mp_obj_base_t base; 33 | unsigned elem_size; // in bytes 34 | } machine_mem_obj_t; 35 | 36 | extern const mp_obj_type_t machine_mem_type; 37 | 38 | extern const machine_mem_obj_t machine_mem8_obj; 39 | extern const machine_mem_obj_t machine_mem16_obj; 40 | extern const machine_mem_obj_t machine_mem32_obj; 41 | 42 | #if defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) 43 | uintptr_t MICROPY_MACHINE_MEM_GET_READ_ADDR(mp_obj_t addr_o, uint align); 44 | #endif 45 | #if defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR) 46 | uintptr_t MICROPY_MACHINE_MEM_GET_WRITE_ADDR(mp_obj_t addr_o, uint align); 47 | #endif 48 | 49 | #endif // MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H 50 | -------------------------------------------------------------------------------- /inc/extmod/machine_pulse.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H 27 | #define MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H 28 | 29 | #include "py/obj.h" 30 | #include "py/mphal.h" 31 | 32 | mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us); 33 | 34 | MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj); 35 | 36 | #endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H 37 | -------------------------------------------------------------------------------- /inc/extmod/utime_mphal.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013-2016 Damien P. George 7 | * Copyright (c) 2016 Paul Sokolovsky 8 | * 9 | * Permission is hereby granted, free of charge, to any person obtaining a copy 10 | * of this software and associated documentation files (the "Software"), to deal 11 | * in the Software without restriction, including without limitation the rights 12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | * copies of the Software, and to permit persons to whom the Software is 14 | * furnished to do so, subject to the following conditions: 15 | * 16 | * The above copyright notice and this permission notice shall be included in 17 | * all copies or substantial portions of the Software. 18 | * 19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | * THE SOFTWARE. 26 | */ 27 | #ifndef MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H 28 | #define MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H 29 | 30 | #include "py/obj.h" 31 | 32 | MP_DECLARE_CONST_FUN_OBJ_1(mp_utime_sleep_obj); 33 | MP_DECLARE_CONST_FUN_OBJ_1(mp_utime_sleep_ms_obj); 34 | MP_DECLARE_CONST_FUN_OBJ_1(mp_utime_sleep_us_obj); 35 | MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_ms_obj); 36 | MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_us_obj); 37 | MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_cpu_obj); 38 | MP_DECLARE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj); 39 | MP_DECLARE_CONST_FUN_OBJ_2(mp_utime_ticks_add_obj); 40 | 41 | #endif // MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H 42 | -------------------------------------------------------------------------------- /inc/genhdr/mpversion.h: -------------------------------------------------------------------------------- 1 | // This file was generated by py/makeversionhdr.py 2 | #define MICROPY_GIT_TAG "v1.9.2-34-gd64154c73" 3 | #define MICROPY_GIT_HASH "d64154c73" 4 | #define MICROPY_BUILD_DATE "2017-09-01" 5 | #define MICROPY_VERSION_MAJOR (1) 6 | #define MICROPY_VERSION_MINOR (9) 7 | #define MICROPY_VERSION_MICRO (2) 8 | #define MICROPY_VERSION_STRING "1.9.2" 9 | -------------------------------------------------------------------------------- /inc/lib/iters.h: -------------------------------------------------------------------------------- 1 | 2 | #include "py/runtime.h" 3 | 4 | mp_obj_t microbit_repeat_iterator(mp_obj_t iterable); 5 | -------------------------------------------------------------------------------- /inc/lib/mp-readline/readline.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H 27 | #define MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H 28 | 29 | #define CHAR_CTRL_A (1) 30 | #define CHAR_CTRL_B (2) 31 | #define CHAR_CTRL_C (3) 32 | #define CHAR_CTRL_D (4) 33 | #define CHAR_CTRL_E (5) 34 | #define CHAR_CTRL_F (6) 35 | #define CHAR_CTRL_K (11) 36 | #define CHAR_CTRL_N (14) 37 | #define CHAR_CTRL_P (16) 38 | #define CHAR_CTRL_U (21) 39 | 40 | void readline_init0(void); 41 | int readline(vstr_t *line, const char *prompt); 42 | void readline_push_history(const char *line); 43 | 44 | void readline_init(vstr_t *line, const char *prompt); 45 | void readline_note_newline(const char *prompt); 46 | int readline_process_char(int c); 47 | 48 | #endif // MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H 49 | -------------------------------------------------------------------------------- /inc/lib/pwm.h: -------------------------------------------------------------------------------- 1 | #ifndef __MICROPY_INCLUDED_LIB_PWM_H__ 2 | #define __MICROPY_INCLUDED_LIB_PWM_H__ 3 | 4 | #ifdef __cplusplus 5 | extern "C" { 6 | #endif 7 | 8 | void pwm_init(void); 9 | void pwm_start(void); 10 | void pwm_stop(void); 11 | 12 | int pwm_set_period_us(int32_t us); 13 | int32_t pwm_get_period_us(void); 14 | void pwm_set_duty_cycle(int32_t pin, int32_t value); 15 | void pwm_release(int32_t pin); 16 | 17 | #ifdef __cplusplus 18 | } 19 | #endif 20 | 21 | #endif // __MICROPY_INCLUDED_LIB_PWM_H__ 22 | -------------------------------------------------------------------------------- /inc/lib/ticker.h: -------------------------------------------------------------------------------- 1 | #ifndef __MICROPY_INCLUDED_LIB_TICKER_H__ 2 | #define __MICROPY_INCLUDED_LIB_TICKER_H__ 3 | 4 | /************************************* 5 | * 62.5kHz (16µs cycle time) ticker. 6 | ************************************/ 7 | 8 | #ifdef __cplusplus 9 | extern "C" { 10 | #endif 11 | 12 | #include "nrf.h" 13 | 14 | typedef void (*callback_ptr)(void); 15 | typedef int32_t (*ticker_callback_ptr)(void); 16 | 17 | extern volatile uint32_t ticker_ticks_ms; 18 | 19 | void ticker_init(callback_ptr slow_ticker_callback); 20 | void ticker_start(void); 21 | void ticker_stop(void); 22 | 23 | int clear_ticker_callback(uint32_t index); 24 | int set_ticker_callback(uint32_t index, ticker_callback_ptr func, int32_t initial_delay_us); 25 | 26 | int set_low_priority_callback(callback_ptr callback, int id); 27 | 28 | #define CYCLES_PER_MICROSECONDS 16 29 | 30 | #define MICROSECONDS_PER_TICK 16 31 | #define CYCLES_PER_TICK (CYCLES_PER_MICROSECONDS*MICROSECONDS_PER_TICK) 32 | // This must be an integer multiple of MICROSECONDS_PER_TICK 33 | #define MICROSECONDS_PER_MACRO_TICK 6000 34 | #define MILLISECONDS_PER_MACRO_TICK 6 35 | 36 | #ifdef __cplusplus 37 | } 38 | #endif 39 | 40 | #endif // __MICROPY_INCLUDED_LIB_TICKER_H__ 41 | -------------------------------------------------------------------------------- /inc/lib/utils/interrupt_char.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013-2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H 27 | #define MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H 28 | 29 | extern int mp_interrupt_char; 30 | void mp_hal_set_interrupt_char(int c); 31 | void mp_keyboard_interrupt(void); 32 | 33 | #endif // MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H 34 | -------------------------------------------------------------------------------- /inc/lib/utils/pyexec.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H 27 | #define MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H 28 | 29 | typedef enum { 30 | PYEXEC_MODE_RAW_REPL, 31 | PYEXEC_MODE_FRIENDLY_REPL, 32 | } pyexec_mode_kind_t; 33 | 34 | extern pyexec_mode_kind_t pyexec_mode_kind; 35 | 36 | // Set this to the value (eg PYEXEC_FORCED_EXIT) that will be propagated through 37 | // the pyexec functions if a SystemExit exception is raised by the running code. 38 | // It will reset to 0 at the start of each execution (eg each REPL entry). 39 | extern int pyexec_system_exit; 40 | 41 | #define PYEXEC_FORCED_EXIT (0x100) 42 | #define PYEXEC_SWITCH_MODE (0x200) 43 | 44 | int pyexec_raw_repl(void); 45 | int pyexec_friendly_repl(void); 46 | int pyexec_file(const char *filename); 47 | int pyexec_frozen_module(const char *name); 48 | void pyexec_event_repl_init(void); 49 | int pyexec_event_repl_process_char(int c); 50 | extern uint8_t pyexec_repl_active; 51 | 52 | MP_DECLARE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj); 53 | 54 | #endif // MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H 55 | -------------------------------------------------------------------------------- /inc/microbit/MicroBitCustomConfig.h: -------------------------------------------------------------------------------- 1 | /** 2 | * MicroBitCustomConfig.h 3 | * 4 | * This file is automatically included by the microbit DAL compilation 5 | * process. Use this to define any custom configration options needed 6 | * for your build of the micro:bit runtime. 7 | * 8 | * See microbit-dal/inc/MicroBitConfig.h for a complete list of options. 9 | * Any options you define here will take prescedence over those defined there. 10 | */ 11 | 12 | #ifndef MICROBIT_CUSTOM_CONFIG_H 13 | #define MICROBIT_CUSTOM_CONFIG_H 14 | 15 | #define MICROBIT_HEAP_REUSE_SD 0 16 | #define MICROBIT_BLE_ENABLED 0 17 | #define MICROBIT_BLE_BLUEZONE 0 18 | #define MICROBIT_BLE_DFU_SERVICE 0 19 | #define MICROBIT_BLE_EVENT_SERVICE 0 20 | #define MICROBIT_BLE_DEVICE_INFORMATION_SERVICE 0 21 | #define MICROBIT_BLE_PAIRING_MODE 0 22 | #define MICROBIT_RADIO_ENABLED 0 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /inc/microbit/memory.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2016 Mark Shannon 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #ifndef __MICROPY_INCLUDED_MEMORY_H__ 28 | #define __MICROPY_INCLUDED_MEMORY_H__ 29 | 30 | #include "microbit/filesystem.h" 31 | 32 | extern uint32_t __data_end__; 33 | extern uint32_t __data_start__; 34 | extern uint32_t __etext; 35 | 36 | static inline char *rounddown(char *addr, uint32_t align) { 37 | return (char *)(((uint32_t)addr)&(-align)); 38 | } 39 | 40 | static inline char *roundup(char *addr, uint32_t align) { 41 | return (char *)((((uint32_t)addr)+align-1)&(-align)); 42 | } 43 | 44 | /** The end of the code area in flash ROM (text plus read-only copy of data area) */ 45 | static inline char *microbit_end_of_code() { 46 | return (char *)(&__etext + (&__data_end__ - &__data_start__)); 47 | } 48 | 49 | static inline char *microbit_end_of_rom() { 50 | return (char *)0x40000; 51 | } 52 | 53 | static inline char *microbit_mp_appended_script() { 54 | return (char *)0x3e000; 55 | } 56 | 57 | static inline void *microbit_compass_calibration_page(void) { 58 | if (microbit_mp_appended_script()[0] == 'M') { 59 | return microbit_mp_appended_script() - persistent_page_size(); 60 | } else { 61 | return microbit_end_of_rom() - persistent_page_size(); 62 | } 63 | } 64 | 65 | #endif // __MICROPY_INCLUDED_MEMORY_H__ 66 | -------------------------------------------------------------------------------- /inc/microbit/microbitdal.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2017 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_MICROBIT_MICROBITDAL_H 27 | #define MICROPY_INCLUDED_MICROBIT_MICROBITDAL_H 28 | 29 | #include "MicroBitDisplay.h" 30 | #include "MicroBitCompass.h" 31 | #include "MicroBitCompassCalibrator.h" 32 | 33 | class MicroPythonI2C : public MicroBitI2C { 34 | public: 35 | MicroPythonI2C(PinName sda, PinName scl) 36 | : MicroBitI2C(sda, scl) { 37 | } 38 | void set_pins(PinName sda, PinName scl) { 39 | _i2c.sda = sda; 40 | _i2c.scl = scl; 41 | } 42 | i2c_t *get_i2c_obj() { 43 | return &_i2c; 44 | } 45 | }; 46 | 47 | extern MicroPythonI2C ubit_i2c; 48 | extern MicroBitAccelerometer *ubit_accelerometer; 49 | extern MicroBitDisplay ubit_display; 50 | extern MicroBitCompass *ubit_compass; 51 | extern MicroBitCompassCalibrator *ubit_compass_calibrator; 52 | 53 | #endif // MICROPY_INCLUDED_MICROBIT_MICROBITDAL_H 54 | -------------------------------------------------------------------------------- /inc/microbit/modaudio.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __MICROPY_INCLUDED_MICROBIT_AUDIO_H__ 3 | #define __MICROPY_INCLUDED_MICROBIT_AUDIO_H__ 4 | 5 | #include "nrf.h" 6 | #include "py/obj.h" 7 | #include "py/runtime.h" 8 | 9 | void audio_play_source(mp_obj_t src, mp_obj_t pin1, mp_obj_t pin2, bool wait); 10 | void audio_stop(void); 11 | 12 | #define LOG_AUDIO_CHUNK_SIZE 5 13 | #define AUDIO_CHUNK_SIZE (1< 30 | #include 31 | 32 | #define MP_ASM_PASS_COMPUTE (1) 33 | #define MP_ASM_PASS_EMIT (2) 34 | 35 | typedef struct _mp_asm_base_t { 36 | int pass; 37 | size_t code_offset; 38 | size_t code_size; 39 | uint8_t *code_base; 40 | 41 | size_t max_num_labels; 42 | size_t *label_offsets; 43 | } mp_asm_base_t; 44 | 45 | void mp_asm_base_init(mp_asm_base_t *as, size_t max_num_labels); 46 | void mp_asm_base_deinit(mp_asm_base_t *as, bool free_code); 47 | void mp_asm_base_start_pass(mp_asm_base_t *as, int pass); 48 | uint8_t *mp_asm_base_get_cur_to_write_bytes(mp_asm_base_t *as, size_t num_bytes_to_write); 49 | void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label); 50 | void mp_asm_base_align(mp_asm_base_t* as, unsigned int align); 51 | void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val); 52 | 53 | static inline size_t mp_asm_base_get_code_pos(mp_asm_base_t *as) { 54 | return as->code_offset; 55 | } 56 | 57 | static inline size_t mp_asm_base_get_code_size(mp_asm_base_t *as) { 58 | return as->code_size; 59 | } 60 | 61 | static inline void *mp_asm_base_get_code(mp_asm_base_t *as) { 62 | #if defined(MP_PLAT_COMMIT_EXEC) 63 | return MP_PLAT_COMMIT_EXEC(as->code_base, as->code_size); 64 | #else 65 | return as->code_base; 66 | #endif 67 | } 68 | 69 | #endif // MICROPY_INCLUDED_PY_ASMBASE_H 70 | -------------------------------------------------------------------------------- /inc/py/binary.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_BINARY_H 27 | #define MICROPY_INCLUDED_PY_BINARY_H 28 | 29 | #include "py/obj.h" 30 | 31 | // Use special typecode to differentiate repr() of bytearray vs array.array('B') 32 | // (underlyingly they're same). Can't use 0 here because that's used to detect 33 | // type-specification errors due to end-of-string. 34 | #define BYTEARRAY_TYPECODE 1 35 | 36 | size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign); 37 | mp_obj_t mp_binary_get_val_array(char typecode, void *p, mp_uint_t index); 38 | void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t val_in); 39 | void mp_binary_set_val_array_from_int(char typecode, void *p, mp_uint_t index, mp_int_t val); 40 | mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr); 41 | void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte **ptr); 42 | long long mp_binary_get_int(mp_uint_t size, bool is_signed, bool big_endian, const byte *src); 43 | void mp_binary_set_int(mp_uint_t val_sz, bool big_endian, byte *dest, mp_uint_t val); 44 | 45 | #endif // MICROPY_INCLUDED_PY_BINARY_H 46 | -------------------------------------------------------------------------------- /inc/py/compile.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_COMPILE_H 27 | #define MICROPY_INCLUDED_PY_COMPILE_H 28 | 29 | #include "py/lexer.h" 30 | #include "py/parse.h" 31 | #include "py/emitglue.h" 32 | 33 | // These must fit in 8 bits; see scope.h 34 | enum { 35 | MP_EMIT_OPT_NONE, 36 | MP_EMIT_OPT_BYTECODE, 37 | MP_EMIT_OPT_NATIVE_PYTHON, 38 | MP_EMIT_OPT_VIPER, 39 | MP_EMIT_OPT_ASM, 40 | }; 41 | 42 | // the compiler will raise an exception if an error occurred 43 | // the compiler will clear the parse tree before it returns 44 | mp_obj_t mp_compile(mp_parse_tree_t *parse_tree, qstr source_file, uint emit_opt, bool is_repl); 45 | 46 | #if MICROPY_PERSISTENT_CODE_SAVE 47 | // this has the same semantics as mp_compile 48 | mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, uint emit_opt, bool is_repl); 49 | #endif 50 | 51 | // this is implemented in runtime.c 52 | mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_input_kind, mp_obj_dict_t *globals, mp_obj_dict_t *locals); 53 | 54 | #endif // MICROPY_INCLUDED_PY_COMPILE_H 55 | -------------------------------------------------------------------------------- /inc/py/formatfloat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_FORMATFLOAT_H 27 | #define MICROPY_INCLUDED_PY_FORMATFLOAT_H 28 | 29 | #include "py/mpconfig.h" 30 | 31 | #if MICROPY_PY_BUILTINS_FLOAT 32 | int mp_format_float(mp_float_t f, char *buf, size_t bufSize, char fmt, int prec, char sign); 33 | #endif 34 | 35 | #endif // MICROPY_INCLUDED_PY_FORMATFLOAT_H 36 | -------------------------------------------------------------------------------- /inc/py/frozenmod.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_FROZENMOD_H 27 | #define MICROPY_INCLUDED_PY_FROZENMOD_H 28 | 29 | #include "py/lexer.h" 30 | 31 | enum { 32 | MP_FROZEN_NONE, 33 | MP_FROZEN_STR, 34 | MP_FROZEN_MPY, 35 | }; 36 | 37 | int mp_find_frozen_module(const char *str, size_t len, void **data); 38 | const char *mp_find_frozen_str(const char *str, size_t *len); 39 | mp_import_stat_t mp_frozen_stat(const char *str); 40 | 41 | #endif // MICROPY_INCLUDED_PY_FROZENMOD_H 42 | -------------------------------------------------------------------------------- /inc/py/gc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_GC_H 27 | #define MICROPY_INCLUDED_PY_GC_H 28 | 29 | #include 30 | 31 | #include "py/mpconfig.h" 32 | #include "py/misc.h" 33 | 34 | void gc_init(void *start, void *end); 35 | 36 | // These lock/unlock functions can be nested. 37 | // They can be used to prevent the GC from allocating/freeing. 38 | void gc_lock(void); 39 | void gc_unlock(void); 40 | bool gc_is_locked(void); 41 | 42 | // A given port must implement gc_collect by using the other collect functions. 43 | void gc_collect(void); 44 | void gc_collect_start(void); 45 | void gc_collect_root(void **ptrs, size_t len); 46 | void gc_collect_end(void); 47 | 48 | void *gc_alloc(size_t n_bytes, bool has_finaliser); 49 | void gc_free(void *ptr); // does not call finaliser 50 | size_t gc_nbytes(const void *ptr); 51 | void *gc_realloc(void *ptr, size_t n_bytes, bool allow_move); 52 | 53 | typedef struct _gc_info_t { 54 | size_t total; 55 | size_t used; 56 | size_t free; 57 | size_t max_free; 58 | size_t num_1block; 59 | size_t num_2block; 60 | size_t max_block; 61 | } gc_info_t; 62 | 63 | void gc_info(gc_info_t *info); 64 | void gc_dump_info(void); 65 | void gc_dump_alloc_table(void); 66 | 67 | #endif // MICROPY_INCLUDED_PY_GC_H 68 | -------------------------------------------------------------------------------- /inc/py/mpthread.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_MPTHREAD_H 27 | #define MICROPY_INCLUDED_PY_MPTHREAD_H 28 | 29 | #include "py/mpconfig.h" 30 | 31 | #if MICROPY_PY_THREAD 32 | 33 | #ifdef MICROPY_MPTHREADPORT_H 34 | #include MICROPY_MPTHREADPORT_H 35 | #else 36 | #include 37 | #endif 38 | 39 | struct _mp_state_thread_t; 40 | 41 | struct _mp_state_thread_t *mp_thread_get_state(void); 42 | void mp_thread_set_state(void *state); 43 | void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size); 44 | void mp_thread_start(void); 45 | void mp_thread_finish(void); 46 | void mp_thread_mutex_init(mp_thread_mutex_t *mutex); 47 | int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait); 48 | void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex); 49 | 50 | #endif // MICROPY_PY_THREAD 51 | 52 | #if MICROPY_PY_THREAD && MICROPY_PY_THREAD_GIL 53 | #include "py/mpstate.h" 54 | #define MP_THREAD_GIL_ENTER() mp_thread_mutex_lock(&MP_STATE_VM(gil_mutex), 1) 55 | #define MP_THREAD_GIL_EXIT() mp_thread_mutex_unlock(&MP_STATE_VM(gil_mutex)) 56 | #else 57 | #define MP_THREAD_GIL_ENTER() 58 | #define MP_THREAD_GIL_EXIT() 59 | #endif 60 | 61 | #endif // MICROPY_INCLUDED_PY_MPTHREAD_H 62 | -------------------------------------------------------------------------------- /inc/py/objarray.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * Copyright (c) 2014 Paul Sokolovsky 8 | * 9 | * Permission is hereby granted, free of charge, to any person obtaining a copy 10 | * of this software and associated documentation files (the "Software"), to deal 11 | * in the Software without restriction, including without limitation the rights 12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | * copies of the Software, and to permit persons to whom the Software is 14 | * furnished to do so, subject to the following conditions: 15 | * 16 | * The above copyright notice and this permission notice shall be included in 17 | * all copies or substantial portions of the Software. 18 | * 19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | * THE SOFTWARE. 26 | */ 27 | #ifndef MICROPY_INCLUDED_PY_OBJARRAY_H 28 | #define MICROPY_INCLUDED_PY_OBJARRAY_H 29 | 30 | #include "py/obj.h" 31 | 32 | typedef struct _mp_obj_array_t { 33 | mp_obj_base_t base; 34 | size_t typecode : 8; 35 | // free is number of unused elements after len used elements 36 | // alloc size = len + free 37 | size_t free : (8 * sizeof(size_t) - 8); 38 | size_t len; // in elements 39 | void *items; 40 | } mp_obj_array_t; 41 | 42 | #endif // MICROPY_INCLUDED_PY_OBJARRAY_H 43 | -------------------------------------------------------------------------------- /inc/py/objexcept.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJEXCEPT_H 27 | #define MICROPY_INCLUDED_PY_OBJEXCEPT_H 28 | 29 | #include "py/obj.h" 30 | #include "py/objtuple.h" 31 | 32 | typedef struct _mp_obj_exception_t { 33 | mp_obj_base_t base; 34 | size_t traceback_alloc : (8 * sizeof(size_t) / 2); 35 | size_t traceback_len : (8 * sizeof(size_t) / 2); 36 | size_t *traceback_data; 37 | mp_obj_tuple_t *args; 38 | } mp_obj_exception_t; 39 | 40 | #endif // MICROPY_INCLUDED_PY_OBJEXCEPT_H 41 | -------------------------------------------------------------------------------- /inc/py/objfun.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJFUN_H 27 | #define MICROPY_INCLUDED_PY_OBJFUN_H 28 | 29 | #include "py/obj.h" 30 | 31 | typedef struct _mp_obj_fun_bc_t { 32 | mp_obj_base_t base; 33 | mp_obj_dict_t *globals; // the context within which this function was defined 34 | const byte *bytecode; // bytecode for the function 35 | const mp_uint_t *const_table; // constant table 36 | // the following extra_args array is allocated space to take (in order): 37 | // - values of positional default args (if any) 38 | // - a single slot for default kw args dict (if it has them) 39 | // - a single slot for var args tuple (if it takes them) 40 | // - a single slot for kw args dict (if it takes them) 41 | mp_obj_t extra_args[]; 42 | } mp_obj_fun_bc_t; 43 | 44 | #endif // MICROPY_INCLUDED_PY_OBJFUN_H 45 | -------------------------------------------------------------------------------- /inc/py/objgenerator.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJGENERATOR_H 27 | #define MICROPY_INCLUDED_PY_OBJGENERATOR_H 28 | 29 | #include "py/obj.h" 30 | #include "py/runtime.h" 31 | 32 | mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_val, mp_obj_t throw_val, mp_obj_t *ret_val); 33 | 34 | #endif // MICROPY_INCLUDED_PY_OBJGENERATOR_H 35 | -------------------------------------------------------------------------------- /inc/py/objlist.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJLIST_H 27 | #define MICROPY_INCLUDED_PY_OBJLIST_H 28 | 29 | #include "py/obj.h" 30 | 31 | typedef struct _mp_obj_list_t { 32 | mp_obj_base_t base; 33 | size_t alloc; 34 | size_t len; 35 | mp_obj_t *items; 36 | } mp_obj_list_t; 37 | 38 | #endif // MICROPY_INCLUDED_PY_OBJLIST_H 39 | -------------------------------------------------------------------------------- /inc/py/objmodule.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJMODULE_H 27 | #define MICROPY_INCLUDED_PY_OBJMODULE_H 28 | 29 | #include "py/obj.h" 30 | 31 | extern const mp_map_t mp_builtin_module_map; 32 | extern const mp_map_t mp_builtin_module_weak_links_map; 33 | 34 | mp_obj_t mp_module_get(qstr module_name); 35 | void mp_module_register(qstr qstr, mp_obj_t module); 36 | 37 | #endif // MICROPY_INCLUDED_PY_OBJMODULE_H 38 | -------------------------------------------------------------------------------- /inc/py/objstringio.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJSTRINGIO_H 27 | #define MICROPY_INCLUDED_PY_OBJSTRINGIO_H 28 | 29 | #include "py/obj.h" 30 | 31 | typedef struct _mp_obj_stringio_t { 32 | mp_obj_base_t base; 33 | vstr_t *vstr; 34 | // StringIO has single pointer used for both reading and writing 35 | mp_uint_t pos; 36 | // Underlying object buffered by this StringIO 37 | mp_obj_t ref_obj; 38 | } mp_obj_stringio_t; 39 | 40 | #endif // MICROPY_INCLUDED_PY_OBJSTRINGIO_H 41 | -------------------------------------------------------------------------------- /inc/py/objtuple.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJTUPLE_H 27 | #define MICROPY_INCLUDED_PY_OBJTUPLE_H 28 | 29 | #include "py/obj.h" 30 | 31 | typedef struct _mp_obj_tuple_t { 32 | mp_obj_base_t base; 33 | size_t len; 34 | mp_obj_t items[]; 35 | } mp_obj_tuple_t; 36 | 37 | typedef struct _mp_rom_obj_tuple_t { 38 | mp_obj_base_t base; 39 | size_t len; 40 | mp_rom_obj_t items[]; 41 | } mp_rom_obj_tuple_t; 42 | 43 | void mp_obj_tuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind); 44 | mp_obj_t mp_obj_tuple_unary_op(mp_uint_t op, mp_obj_t self_in); 45 | mp_obj_t mp_obj_tuple_binary_op(mp_uint_t op, mp_obj_t lhs, mp_obj_t rhs); 46 | mp_obj_t mp_obj_tuple_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value); 47 | mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf); 48 | 49 | extern const mp_obj_type_t mp_type_attrtuple; 50 | 51 | #define MP_DEFINE_ATTRTUPLE(tuple_obj_name, fields, nitems, ...) \ 52 | const mp_rom_obj_tuple_t tuple_obj_name = { \ 53 | .base = {&mp_type_attrtuple}, \ 54 | .len = nitems, \ 55 | .items = { __VA_ARGS__ , MP_ROM_PTR((void*)fields) } \ 56 | } 57 | 58 | #if MICROPY_PY_COLLECTIONS 59 | void mp_obj_attrtuple_print_helper(const mp_print_t *print, const qstr *fields, mp_obj_tuple_t *o); 60 | #endif 61 | 62 | mp_obj_t mp_obj_new_attrtuple(const qstr *fields, size_t n, const mp_obj_t *items); 63 | 64 | #endif // MICROPY_INCLUDED_PY_OBJTUPLE_H 65 | -------------------------------------------------------------------------------- /inc/py/objtype.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_OBJTYPE_H 27 | #define MICROPY_INCLUDED_PY_OBJTYPE_H 28 | 29 | #include "py/obj.h" 30 | 31 | // instance object 32 | // creating an instance of a class makes one of these objects 33 | typedef struct _mp_obj_instance_t { 34 | mp_obj_base_t base; 35 | mp_map_t members; 36 | mp_obj_t subobj[]; 37 | // TODO maybe cache __getattr__ and __setattr__ for efficient lookup of them 38 | } mp_obj_instance_t; 39 | 40 | // this needs to be exposed for MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE to work 41 | void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); 42 | 43 | // these need to be exposed so mp_obj_is_callable can work correctly 44 | bool mp_obj_instance_is_callable(mp_obj_t self_in); 45 | mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args); 46 | 47 | #define mp_obj_is_instance_type(type) ((type)->make_new == mp_obj_instance_make_new) 48 | #define mp_obj_is_native_type(type) ((type)->make_new != mp_obj_instance_make_new) 49 | // this needs to be exposed for the above macros to work correctly 50 | mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args); 51 | 52 | #endif // MICROPY_INCLUDED_PY_OBJTYPE_H 53 | -------------------------------------------------------------------------------- /inc/py/parsenum.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_PARSENUM_H 27 | #define MICROPY_INCLUDED_PY_PARSENUM_H 28 | 29 | #include "py/mpconfig.h" 30 | #include "py/lexer.h" 31 | #include "py/obj.h" 32 | 33 | // these functions raise a SyntaxError if lex!=NULL, else a ValueError 34 | mp_obj_t mp_parse_num_integer(const char *restrict str, size_t len, int base, mp_lexer_t *lex); 35 | mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex); 36 | 37 | #endif // MICROPY_INCLUDED_PY_PARSENUM_H 38 | -------------------------------------------------------------------------------- /inc/py/parsenumbase.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_PARSENUMBASE_H 27 | #define MICROPY_INCLUDED_PY_PARSENUMBASE_H 28 | 29 | #include "py/mpconfig.h" 30 | 31 | size_t mp_parse_num_base(const char *str, size_t len, int *base); 32 | 33 | #endif // MICROPY_INCLUDED_PY_PARSENUMBASE_H 34 | -------------------------------------------------------------------------------- /inc/py/persistentcode.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013-2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_PERSISTENTCODE_H 27 | #define MICROPY_INCLUDED_PY_PERSISTENTCODE_H 28 | 29 | #include "py/mpprint.h" 30 | #include "py/reader.h" 31 | #include "py/emitglue.h" 32 | 33 | mp_raw_code_t *mp_raw_code_load(mp_reader_t *reader); 34 | mp_raw_code_t *mp_raw_code_load_mem(const byte *buf, size_t len); 35 | mp_raw_code_t *mp_raw_code_load_file(const char *filename); 36 | 37 | void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print); 38 | void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename); 39 | 40 | #endif // MICROPY_INCLUDED_PY_PERSISTENTCODE_H 41 | -------------------------------------------------------------------------------- /inc/py/qstrdefs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/mpconfig.h" 28 | 29 | // All the qstr definitions in this file are available as constants. 30 | // That is, they are in ROM and you can reference them simply as MP_QSTR_xxxx. 31 | 32 | // qstr configuration passed to makeqstrdata.py of the form QCFG(key, value) 33 | QCFG(BYTES_IN_LEN, MICROPY_QSTR_BYTES_IN_LEN) 34 | QCFG(BYTES_IN_HASH, MICROPY_QSTR_BYTES_IN_HASH) 35 | 36 | Q() 37 | Q(*) 38 | Q(_) 39 | Q(/) 40 | Q(%#o) 41 | Q(%#x) 42 | Q({:#b}) 43 | Q(\n) 44 | Q(maximum recursion depth exceeded) 45 | Q() 46 | Q() 47 | Q() 48 | Q() 49 | Q() 50 | Q() 51 | Q() 52 | Q() 53 | Q(utf-8) 54 | -------------------------------------------------------------------------------- /inc/py/reader.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013-2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_READER_H 27 | #define MICROPY_INCLUDED_PY_READER_H 28 | 29 | #include "py/obj.h" 30 | 31 | // the readbyte function must return the next byte in the input stream 32 | // it must return MP_READER_EOF if end of stream 33 | // it can be called again after returning MP_READER_EOF, and in that case must return MP_READER_EOF 34 | #define MP_READER_EOF ((mp_uint_t)(-1)) 35 | 36 | typedef struct _mp_reader_t { 37 | void *data; 38 | mp_uint_t (*readbyte)(void *data); 39 | void (*close)(void *data); 40 | } mp_reader_t; 41 | 42 | void mp_reader_new_mem(mp_reader_t *reader, const byte *buf, size_t len, size_t free_len); 43 | void mp_reader_new_file(mp_reader_t *reader, const char *filename); 44 | void mp_reader_new_file_from_fd(mp_reader_t *reader, int fd, bool close_fd); 45 | 46 | #endif // MICROPY_INCLUDED_PY_READER_H 47 | -------------------------------------------------------------------------------- /inc/py/repl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_REPL_H 27 | #define MICROPY_INCLUDED_PY_REPL_H 28 | 29 | #include "py/mpconfig.h" 30 | #include "py/misc.h" 31 | #include "py/mpprint.h" 32 | 33 | #if MICROPY_HELPER_REPL 34 | bool mp_repl_continue_with_input(const char *input); 35 | size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str); 36 | #endif 37 | 38 | #endif // MICROPY_INCLUDED_PY_REPL_H 39 | -------------------------------------------------------------------------------- /inc/py/ringbuf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2016 Paul Sokolovsky 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_RINGBUF_H 27 | #define MICROPY_INCLUDED_PY_RINGBUF_H 28 | 29 | typedef struct _ringbuf_t { 30 | uint8_t *buf; 31 | uint16_t size; 32 | uint16_t iget; 33 | uint16_t iput; 34 | } ringbuf_t; 35 | 36 | // Static initialization: 37 | // byte buf_array[N]; 38 | // ringbuf_t buf = {buf_array, sizeof(buf_array)}; 39 | 40 | // Dynamic initialization. This creates root pointer! 41 | #define ringbuf_alloc(r, sz) \ 42 | { \ 43 | (r)->buf = m_new(uint8_t, sz); \ 44 | (r)->size = sz; \ 45 | (r)->iget = (r)->iput = 0; \ 46 | } 47 | 48 | static inline int ringbuf_get(ringbuf_t *r) { 49 | if (r->iget == r->iput) { 50 | return -1; 51 | } 52 | uint8_t v = r->buf[r->iget++]; 53 | if (r->iget >= r->size) { 54 | r->iget = 0; 55 | } 56 | return v; 57 | } 58 | 59 | static inline int ringbuf_put(ringbuf_t *r, uint8_t v) { 60 | uint32_t iput_new = r->iput + 1; 61 | if (iput_new >= r->size) { 62 | iput_new = 0; 63 | } 64 | if (iput_new == r->iget) { 65 | return -1; 66 | } 67 | r->buf[r->iput] = v; 68 | r->iput = iput_new; 69 | return 0; 70 | } 71 | 72 | #endif // MICROPY_INCLUDED_PY_RINGBUF_H 73 | -------------------------------------------------------------------------------- /inc/py/stackctrl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Paul Sokolovsky 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_STACKCTRL_H 27 | #define MICROPY_INCLUDED_PY_STACKCTRL_H 28 | 29 | #include "py/mpconfig.h" 30 | 31 | void mp_stack_ctrl_init(void); 32 | void mp_stack_set_top(void *top); 33 | mp_uint_t mp_stack_usage(void); 34 | 35 | #if MICROPY_STACK_CHECK 36 | 37 | void mp_stack_set_limit(mp_uint_t limit); 38 | void mp_stack_check(void); 39 | #define MP_STACK_CHECK() mp_stack_check() 40 | 41 | #else 42 | 43 | #define mp_stack_set_limit(limit) 44 | #define MP_STACK_CHECK() 45 | 46 | #endif 47 | 48 | #endif // MICROPY_INCLUDED_PY_STACKCTRL_H 49 | -------------------------------------------------------------------------------- /inc/py/unicode.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | #ifndef MICROPY_INCLUDED_PY_UNICODE_H 27 | #define MICROPY_INCLUDED_PY_UNICODE_H 28 | 29 | #include "py/mpconfig.h" 30 | #include "py/misc.h" 31 | 32 | mp_uint_t utf8_ptr_to_index(const byte *s, const byte *ptr); 33 | 34 | #endif // MICROPY_INCLUDED_PY_UNICODE_H 35 | -------------------------------------------------------------------------------- /module.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "microbit-micropython", 3 | "version": "1.1.1", 4 | "license": "MIT", 5 | "description": "MicroPython port to the BBC micro:bit", 6 | "keywords": ["mbed-classic", "microbit", "runtime", "library", "micropython"], 7 | "author": "Damien P George ", 8 | "homepage": "http://micropython.org", 9 | "dependencies":{ 10 | "microbit-dal":"lancaster-university/microbit-dal#v2.1.1" 11 | }, 12 | "extraIncludes":[ 13 | "inc", 14 | "inc/microbit" 15 | ], 16 | "bin": "./source" 17 | } 18 | -------------------------------------------------------------------------------- /source/extmod/machine_pulse.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/runtime.h" 28 | #include "py/mperrno.h" 29 | #include "extmod/machine_pulse.h" 30 | 31 | #if MICROPY_PY_MACHINE_PULSE 32 | 33 | mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us) { 34 | mp_uint_t start = mp_hal_ticks_us(); 35 | while (mp_hal_pin_read(pin) != pulse_level) { 36 | if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { 37 | return (mp_uint_t)-2; 38 | } 39 | } 40 | start = mp_hal_ticks_us(); 41 | while (mp_hal_pin_read(pin) == pulse_level) { 42 | if ((mp_uint_t)(mp_hal_ticks_us() - start) >= timeout_us) { 43 | return (mp_uint_t)-1; 44 | } 45 | } 46 | return mp_hal_ticks_us() - start; 47 | } 48 | 49 | STATIC mp_obj_t machine_time_pulse_us_(size_t n_args, const mp_obj_t *args) { 50 | mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(args[0]); 51 | int level = 0; 52 | if (mp_obj_is_true(args[1])) { 53 | level = 1; 54 | } 55 | mp_uint_t timeout_us = 1000000; 56 | if (n_args > 2) { 57 | timeout_us = mp_obj_get_int(args[2]); 58 | } 59 | mp_uint_t us = machine_time_pulse_us(pin, level, timeout_us); 60 | // May return -1 or -2 in case of timeout 61 | return mp_obj_new_int(us); 62 | } 63 | MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj, 2, 3, machine_time_pulse_us_); 64 | 65 | #endif 66 | -------------------------------------------------------------------------------- /source/lib/iters.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2015/6 Mark Shannon 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/runtime.h" 28 | #include "lib/iters.h" 29 | 30 | 31 | typedef struct _repeat_iterator_t { 32 | mp_obj_base_t base; 33 | mp_obj_t iterable; 34 | mp_int_t index; 35 | } repeat_iterator_t; 36 | 37 | static mp_obj_t microbit_repeat_iter_next(mp_obj_t iter_in) { 38 | repeat_iterator_t *iter = (repeat_iterator_t *)iter_in; 39 | iter->index++; 40 | if (iter->index >= mp_obj_get_int(mp_obj_len(iter->iterable))) { 41 | iter->index = 0; 42 | } 43 | return mp_obj_subscr(iter->iterable, MP_OBJ_NEW_SMALL_INT(iter->index), MP_OBJ_SENTINEL); 44 | } 45 | 46 | const mp_obj_type_t microbit_repeat_iterator_type = { 47 | { &mp_type_type }, 48 | .name = MP_QSTR_iterator, 49 | .print = NULL, 50 | .make_new = NULL, 51 | .call = NULL, 52 | .unary_op = NULL, 53 | .binary_op = NULL, 54 | .attr = NULL, 55 | .subscr = NULL, 56 | .getiter = mp_identity_getiter, 57 | .iternext = microbit_repeat_iter_next, 58 | }; 59 | 60 | mp_obj_t microbit_repeat_iterator(mp_obj_t iterable) { 61 | repeat_iterator_t *result = m_new_obj(repeat_iterator_t); 62 | result->base.type = µbit_repeat_iterator_type; 63 | result->iterable = iterable; 64 | result->index = -1; 65 | return result; 66 | } 67 | -------------------------------------------------------------------------------- /source/lib/sam/debug.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "sam.h" 3 | 4 | extern unsigned char signInputTable1[]; 5 | extern unsigned char signInputTable2[]; 6 | 7 | void PrintPhonemes(char* title, phoneme_t *phonemes) 8 | { 9 | int i = 0; 10 | printf("===========================================\r\n"); 11 | 12 | printf("%s:\r\n\r\n", title); 13 | printf(" idx phoneme length stress\r\n"); 14 | printf("------------------------------\r\n"); 15 | 16 | while((phonemes[i].index != PHONEME_END) && (i < 255)) 17 | { 18 | if (phonemes[i].index < 81) 19 | { 20 | printf(" %3i %c%c %3i %i\r\n", 21 | phonemes[i].index, 22 | signInputTable1[phonemes[i].index], 23 | signInputTable2[phonemes[i].index], 24 | phonemes[i].length, 25 | phonemes[i].stress 26 | ); 27 | } else 28 | { 29 | printf(" %3i ?? %3i %i\r\n", phonemes[i].index, phonemes[i].length, phonemes[i].stress); 30 | } 31 | i++; 32 | } 33 | printf("===========================================\r\n"); 34 | printf("\r\n"); 35 | } 36 | 37 | void PrintOutput(unsigned char *flags, render_freq_amp_t *frames, unsigned char *pitches, unsigned char count) 38 | { 39 | printf("===========================================\r\n"); 40 | printf("Final data for speech output. %i frames:\r\n\r\n", count); 41 | int i = 0; 42 | printf(" flags ampl1 freq1 ampl2 freq2 ampl3 freq3 pitch\r\n"); 43 | printf("------------------------------------------------\r\n"); 44 | while(i < count) 45 | { 46 | render_freq_amp_t frame = frames[i]; 47 | printf("%5i %5i %5i %5i %5i %5i %5i %5i\r\n", flags[i], frame.amp1, frame.freq1, frame.amp2, frame.freq2, frame.amp3, frame.freq3, pitches[i]); 48 | i++; 49 | } 50 | printf("===========================================\r\n"); 51 | 52 | } 53 | 54 | /* For debugging or modifying reciter rules ... 55 | 56 | extern unsigned char GetRuleByte(unsigned short mem62, unsigned char Y); 57 | 58 | void PrintRule(int offset) 59 | { 60 | int i = 1; 61 | unsigned char A = 0; 62 | printf("Applying rule: "); 63 | do 64 | { 65 | A = GetRuleByte(offset, i); 66 | if ((A&127) == '=') printf(" -> "); else printf("%c", A&127); 67 | i++; 68 | } while ((A&128)==0); 69 | printf("\r\n"); 70 | } 71 | */ 72 | -------------------------------------------------------------------------------- /source/lib/sam/debug.h: -------------------------------------------------------------------------------- 1 | #ifndef DEBUG_H 2 | #define DEBUG_H 3 | 4 | #include "sam.h" 5 | 6 | void PrintPhonemes(char* title, phoneme_t *phonemes); 7 | void PrintOutput(unsigned char *flags, render_freq_amp_t *frames, unsigned char *pitches, unsigned char count); 8 | 9 | void PrintRule(int offset); 10 | 11 | #endif -------------------------------------------------------------------------------- /source/lib/sam/reciter.h: -------------------------------------------------------------------------------- 1 | #ifndef RECITER_C 2 | #define RECITER_C 3 | 4 | //int TextToPhonemes(char *input, char *output); 5 | 6 | typedef struct _reciter_memory { 7 | char input[128]; 8 | unsigned char inputtemp[128]; // secure copy of input tab36096 9 | } reciter_memory; 10 | 11 | int TextToPhonemes(reciter_memory *mem); 12 | 13 | #endif 14 | 15 | -------------------------------------------------------------------------------- /source/lib/sam/render.h: -------------------------------------------------------------------------------- 1 | #ifndef RENDER_H 2 | #define RENDER_H 3 | 4 | #include "sam.h" 5 | 6 | void Render(sam_memory* sam); 7 | void SetMouthThroat(unsigned char mouth, unsigned char throat); 8 | void OutputFrames(sam_memory *sam, unsigned char frame_count); 9 | 10 | /** Scaling c64 rate to sample rate */ 11 | // Rate for 22.05kHz 12 | // #define SCALE_RATE(x) (((x)*1310)>>16) 13 | // Rate for 7.8125KHz 14 | #define SCALE_RATE(x) (((x)*420)>>16) 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /source/lib/sam/sam.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/source/lib/sam/sam.c -------------------------------------------------------------------------------- /source/lib/utils/interrupt_char.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013-2016 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/obj.h" 28 | #include "py/mpstate.h" 29 | 30 | #if MICROPY_KBD_EXCEPTION 31 | 32 | int mp_interrupt_char; 33 | 34 | void mp_hal_set_interrupt_char(int c) { 35 | if (c != -1) { 36 | mp_obj_exception_clear_traceback(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception))); 37 | } 38 | mp_interrupt_char = c; 39 | } 40 | 41 | void mp_keyboard_interrupt(void) { 42 | MP_STATE_VM(mp_pending_exception) = MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception)); 43 | #if MICROPY_ENABLE_SCHEDULER 44 | if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) { 45 | MP_STATE_VM(sched_state) = MP_SCHED_PENDING; 46 | } 47 | #endif 48 | } 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /source/microbit/display_readme.md: -------------------------------------------------------------------------------- 1 | # Notes on the Display 2 | 3 | Rendering of images to the display is now done entirely within MicroPython 4 | without using the DAL's rendering logic. 5 | 6 | This achieves the following: 7 | 8 | 1. It gives more obviously distinct brightness levels on the scale of 1 to 9 9 | 2. Most obviously, the dimmest level is dimmer. Level 1 is clearly dimmer than level 2 10 | 3. It is possible to support sophisticated animations asynchronously. 11 | 12 | ## How rendering works 13 | 14 | Rendering on the microbit display works by using pulse width modulation implemented 15 | in software. A render cycle consists of: 16 | 17 | * Render each display row (which does not correspond to the image row) 18 | * Turn off all LEDs in the previous row. 19 | * Turn on all LEDs that are maximum brightness 20 | * Do any computation required to update the image 21 | * Turn on all LEDs with non-zero brightness 22 | * In exponentially increasing time steps: 23 | * Turn off LEDs in increasing order of brightness. 24 | 25 | This means that each LEDs is turned on for a period of time approximately proportional 26 | to 2**brightness. 27 | By turning on maximum brightness LEDs before updating the image, and performing the 28 | increasing time steps after the update, image is rendering is smooth even with complex 29 | image iterators. 30 | 31 | Provided that the display update step takes no more that about 2.2ms then 32 | there will no effect on the rendering of the image. 33 | Even if it takes up to 4ms (which a lot of computation to yield just a single image) 34 | then only effect is that level 8 brightness will be dimmed toward the level 7 brightness. 35 | 36 | ## How this differs from the DAL. 37 | The DAL updates the image before turning on any pixels. 38 | DAL rendering timings assume that the full 6ms cycle duration can be divided 39 | up evenly. This does not reflect the underlying clock speed and may be the cause 40 | of the unevenness in brightness levels. 41 | The DAL supports 255 brightness levels as well as rotation in the rendering ticker function, 42 | which adds quite a lot of overhead to a function that is called more than 1000 times a second. -------------------------------------------------------------------------------- /source/microbit/events.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2017 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "EventModel.h" 28 | #include "microbit/microbitdal.h" 29 | #include "microbit/modmicrobit.h" 30 | 31 | extern "C" { 32 | extern void microbit_accelerometer_event_handler(const MicroBitEvent*); 33 | } 34 | 35 | class MicroPythonEventHandler : public EventModel { 36 | public: 37 | MicroPythonEventHandler(); 38 | 39 | virtual int send(MicroBitEvent evt); 40 | }; 41 | 42 | // Create a static instance of our custom event handler 43 | static MicroPythonEventHandler event_handler; 44 | 45 | MicroPythonEventHandler::MicroPythonEventHandler() { 46 | // We take full control of the event bus 47 | EventModel::defaultEventBus = this; 48 | } 49 | 50 | int MicroPythonEventHandler::send(MicroBitEvent evt) { 51 | // Dispatch the event to the relevant component 52 | switch (evt.source) { 53 | case MICROBIT_ID_GESTURE: 54 | microbit_accelerometer_event_handler(&evt); 55 | break; 56 | 57 | case MICROBIT_ID_COMPASS: 58 | if (evt.value == MICROBIT_COMPASS_EVT_CALIBRATE) { 59 | ubit_compass_calibrator->calibrateUX(evt); 60 | } 61 | break; 62 | 63 | default: 64 | // Ignore this event 65 | break; 66 | } 67 | 68 | return MICROBIT_OK; 69 | } 70 | -------------------------------------------------------------------------------- /source/microbit/gccollect.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2015-2017 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/mpstate.h" 28 | #include "py/gc.h" 29 | 30 | __attribute__((naked)) uint32_t gc_helper_get_regs_and_sp(uint32_t *regs) { 31 | (void)regs; 32 | 33 | // store registers into given array and return the stack pointer 34 | __asm volatile ( 35 | "str r4, [r0, #0]\n" 36 | "str r5, [r0, #4]\n" 37 | "str r6, [r0, #8]\n" 38 | "str r7, [r0, #12]\n" 39 | "mov r1, r8\n" 40 | "str r1, [r0, #16]\n" 41 | "mov r1, r9\n" 42 | "str r1, [r0, #20]\n" 43 | "mov r1, r10\n" 44 | "str r1, [r0, #24]\n" 45 | "mov r1, r11\n" 46 | "str r1, [r0, #28]\n" 47 | "mov r1, r12\n" 48 | "str r1, [r0, #32]\n" 49 | "mov r1, r13\n" 50 | "str r1, [r0, #36]\n" 51 | "mov r0, sp\n" 52 | "bx lr\n" 53 | ); 54 | } 55 | 56 | void gc_collect(void) { 57 | gc_collect_start(); 58 | 59 | // get the registers and the sp 60 | uint32_t regs[10]; 61 | uint32_t sp = gc_helper_get_regs_and_sp(regs); 62 | 63 | // trace the stack, including the registers (since they live on the stack in this function) 64 | gc_collect_root((void**)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t)); 65 | 66 | gc_collect_end(); 67 | } 68 | -------------------------------------------------------------------------------- /source/microbit/microbitconstimagetuples.c: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * 4 | * Copyright (c) 2015 Mark Shannon 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | * THE SOFTWARE. 23 | */ 24 | 25 | #include "py/runtime.h" 26 | #include "microbit/modmicrobit.h" 27 | 28 | const mp_obj_tuple_t microbit_const_image_all_clocks_tuple_obj = { 29 | {&mp_type_tuple}, 30 | .len = 12, 31 | .items = { 32 | (mp_obj_t)µbit_const_image_clock12_obj, 33 | (mp_obj_t)µbit_const_image_clock1_obj, 34 | (mp_obj_t)µbit_const_image_clock2_obj, 35 | (mp_obj_t)µbit_const_image_clock3_obj, 36 | (mp_obj_t)µbit_const_image_clock4_obj, 37 | (mp_obj_t)µbit_const_image_clock5_obj, 38 | (mp_obj_t)µbit_const_image_clock6_obj, 39 | (mp_obj_t)µbit_const_image_clock7_obj, 40 | (mp_obj_t)µbit_const_image_clock8_obj, 41 | (mp_obj_t)µbit_const_image_clock9_obj, 42 | (mp_obj_t)µbit_const_image_clock10_obj, 43 | (mp_obj_t)µbit_const_image_clock11_obj 44 | } 45 | }; 46 | 47 | const mp_obj_tuple_t microbit_const_image_all_arrows_tuple_obj = { 48 | {&mp_type_tuple}, 49 | .len = 8, 50 | .items = { 51 | (mp_obj_t)µbit_const_image_arrow_n_obj, 52 | (mp_obj_t)µbit_const_image_arrow_ne_obj, 53 | (mp_obj_t)µbit_const_image_arrow_e_obj, 54 | (mp_obj_t)µbit_const_image_arrow_se_obj, 55 | (mp_obj_t)µbit_const_image_arrow_s_obj, 56 | (mp_obj_t)µbit_const_image_arrow_sw_obj, 57 | (mp_obj_t)µbit_const_image_arrow_w_obj, 58 | (mp_obj_t)µbit_const_image_arrow_nw_obj 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /source/microbit/modutime.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013-2017 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "extmod/utime_mphal.h" 28 | 29 | STATIC const mp_rom_map_elem_t utime_module_globals_table[] = { 30 | { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_utime) }, 31 | 32 | { MP_ROM_QSTR(MP_QSTR_sleep), MP_ROM_PTR(&mp_utime_sleep_obj) }, 33 | { MP_ROM_QSTR(MP_QSTR_sleep_ms), MP_ROM_PTR(&mp_utime_sleep_ms_obj) }, 34 | { MP_ROM_QSTR(MP_QSTR_sleep_us), MP_ROM_PTR(&mp_utime_sleep_us_obj) }, 35 | { MP_ROM_QSTR(MP_QSTR_ticks_ms), MP_ROM_PTR(&mp_utime_ticks_ms_obj) }, 36 | { MP_ROM_QSTR(MP_QSTR_ticks_us), MP_ROM_PTR(&mp_utime_ticks_us_obj) }, 37 | { MP_ROM_QSTR(MP_QSTR_ticks_add), MP_ROM_PTR(&mp_utime_ticks_add_obj) }, 38 | { MP_ROM_QSTR(MP_QSTR_ticks_diff), MP_ROM_PTR(&mp_utime_ticks_diff_obj) }, 39 | }; 40 | 41 | STATIC MP_DEFINE_CONST_DICT(utime_module_globals, utime_module_globals_table); 42 | 43 | const mp_obj_module_t utime_module = { 44 | .base = { &mp_type_module }, 45 | .globals = (mp_obj_dict_t*)&utime_module_globals, 46 | }; 47 | -------------------------------------------------------------------------------- /source/py/modarray.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/builtin.h" 28 | 29 | #if MICROPY_PY_ARRAY 30 | 31 | STATIC const mp_rom_map_elem_t mp_module_array_globals_table[] = { 32 | { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_array) }, 33 | { MP_ROM_QSTR(MP_QSTR_array), MP_ROM_PTR(&mp_type_array) }, 34 | }; 35 | 36 | STATIC MP_DEFINE_CONST_DICT(mp_module_array_globals, mp_module_array_globals_table); 37 | 38 | const mp_obj_module_t mp_module_array = { 39 | .base = { &mp_type_module }, 40 | .globals = (mp_obj_dict_t*)&mp_module_array_globals, 41 | }; 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /source/py/modcollections.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/builtin.h" 28 | 29 | #if MICROPY_PY_COLLECTIONS 30 | 31 | STATIC const mp_rom_map_elem_t mp_module_collections_globals_table[] = { 32 | { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucollections) }, 33 | { MP_ROM_QSTR(MP_QSTR_namedtuple), MP_ROM_PTR(&mp_namedtuple_obj) }, 34 | #if MICROPY_PY_COLLECTIONS_ORDEREDDICT 35 | { MP_ROM_QSTR(MP_QSTR_OrderedDict), MP_ROM_PTR(&mp_type_ordereddict) }, 36 | #endif 37 | }; 38 | 39 | STATIC MP_DEFINE_CONST_DICT(mp_module_collections_globals, mp_module_collections_globals_table); 40 | 41 | const mp_obj_module_t mp_module_collections = { 42 | .base = { &mp_type_module }, 43 | .globals = (mp_obj_dict_t*)&mp_module_collections_globals, 44 | }; 45 | 46 | #endif // MICROPY_PY_COLLECTIONS 47 | -------------------------------------------------------------------------------- /source/py/mpstate.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/mpstate.h" 28 | 29 | #if MICROPY_DYNAMIC_COMPILER 30 | mp_dynamic_compiler_t mp_dynamic_compiler = {0}; 31 | #endif 32 | 33 | mp_state_ctx_t mp_state_ctx; 34 | -------------------------------------------------------------------------------- /source/py/nlrsetjmp.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/nlr.h" 28 | 29 | #if MICROPY_NLR_SETJMP 30 | 31 | void nlr_setjmp_jump(void *val) { 32 | nlr_buf_t **top_ptr = &MP_STATE_THREAD(nlr_top); 33 | nlr_buf_t *top = *top_ptr; 34 | if (top == NULL) { 35 | nlr_jump_fail(val); 36 | } 37 | top->ret_val = val; 38 | *top_ptr = top->prev; 39 | longjmp(top->jmpbuf, 1); 40 | } 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /source/py/objcell.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/obj.h" 28 | 29 | typedef struct _mp_obj_cell_t { 30 | mp_obj_base_t base; 31 | mp_obj_t obj; 32 | } mp_obj_cell_t; 33 | 34 | mp_obj_t mp_obj_cell_get(mp_obj_t self_in) { 35 | mp_obj_cell_t *self = MP_OBJ_TO_PTR(self_in); 36 | return self->obj; 37 | } 38 | 39 | void mp_obj_cell_set(mp_obj_t self_in, mp_obj_t obj) { 40 | mp_obj_cell_t *self = MP_OBJ_TO_PTR(self_in); 41 | self->obj = obj; 42 | } 43 | 44 | #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED 45 | STATIC void cell_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { 46 | (void)kind; 47 | mp_obj_cell_t *o = MP_OBJ_TO_PTR(o_in); 48 | mp_printf(print, "obj); 49 | if (o->obj == MP_OBJ_NULL) { 50 | mp_print_str(print, "(nil)"); 51 | } else { 52 | mp_obj_print_helper(print, o->obj, PRINT_REPR); 53 | } 54 | mp_print_str(print, ">"); 55 | } 56 | #endif 57 | 58 | STATIC const mp_obj_type_t mp_type_cell = { 59 | { &mp_type_type }, 60 | .name = MP_QSTR_, // cell representation is just value in < > 61 | #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED 62 | .print = cell_print, 63 | #endif 64 | }; 65 | 66 | mp_obj_t mp_obj_new_cell(mp_obj_t obj) { 67 | mp_obj_cell_t *o = m_new_obj(mp_obj_cell_t); 68 | o->base.type = &mp_type_cell; 69 | o->obj = obj; 70 | return MP_OBJ_FROM_PTR(o); 71 | } 72 | -------------------------------------------------------------------------------- /source/py/objfilter.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/runtime.h" 28 | 29 | #if MICROPY_PY_BUILTINS_FILTER 30 | 31 | typedef struct _mp_obj_filter_t { 32 | mp_obj_base_t base; 33 | mp_obj_t fun; 34 | mp_obj_t iter; 35 | } mp_obj_filter_t; 36 | 37 | STATIC mp_obj_t filter_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { 38 | mp_arg_check_num(n_args, n_kw, 2, 2, false); 39 | mp_obj_filter_t *o = m_new_obj(mp_obj_filter_t); 40 | o->base.type = type; 41 | o->fun = args[0]; 42 | o->iter = mp_getiter(args[1], NULL); 43 | return MP_OBJ_FROM_PTR(o); 44 | } 45 | 46 | STATIC mp_obj_t filter_iternext(mp_obj_t self_in) { 47 | mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_filter)); 48 | mp_obj_filter_t *self = MP_OBJ_TO_PTR(self_in); 49 | mp_obj_t next; 50 | while ((next = mp_iternext(self->iter)) != MP_OBJ_STOP_ITERATION) { 51 | mp_obj_t val; 52 | if (self->fun != mp_const_none) { 53 | val = mp_call_function_n_kw(self->fun, 1, 0, &next); 54 | } else { 55 | val = next; 56 | } 57 | if (mp_obj_is_true(val)) { 58 | return next; 59 | } 60 | } 61 | return MP_OBJ_STOP_ITERATION; 62 | } 63 | 64 | const mp_obj_type_t mp_type_filter = { 65 | { &mp_type_type }, 66 | .name = MP_QSTR_filter, 67 | .make_new = filter_make_new, 68 | .getiter = mp_identity_getiter, 69 | .iternext = filter_iternext, 70 | }; 71 | 72 | #endif // MICROPY_PY_BUILTINS_FILTER 73 | -------------------------------------------------------------------------------- /source/py/objnone.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include 28 | 29 | #include "py/nlr.h" 30 | #include "py/obj.h" 31 | #include "py/runtime0.h" 32 | 33 | typedef struct _mp_obj_none_t { 34 | mp_obj_base_t base; 35 | } mp_obj_none_t; 36 | 37 | STATIC void none_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { 38 | (void)self_in; 39 | if (MICROPY_PY_UJSON && kind == PRINT_JSON) { 40 | mp_print_str(print, "null"); 41 | } else { 42 | mp_print_str(print, "None"); 43 | } 44 | } 45 | 46 | const mp_obj_type_t mp_type_NoneType = { 47 | { &mp_type_type }, 48 | .name = MP_QSTR_NoneType, 49 | .print = none_print, 50 | .unary_op = mp_generic_unary_op, 51 | }; 52 | 53 | const mp_obj_none_t mp_const_none_obj = {{&mp_type_NoneType}}; 54 | -------------------------------------------------------------------------------- /source/py/objpolyiter.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2015 Paul Sokolovsky 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include 28 | 29 | #include "py/nlr.h" 30 | #include "py/runtime.h" 31 | 32 | // This is universal iterator type which calls "iternext" method stored in 33 | // particular object instance. (So, each instance of this time can have its 34 | // own iteration behavior.) Having this type saves to define type objects 35 | // for various internal iterator objects. 36 | 37 | // Any instance should have these 2 fields at the beginning 38 | typedef struct _mp_obj_polymorph_iter_t { 39 | mp_obj_base_t base; 40 | mp_fun_1_t iternext; 41 | } mp_obj_polymorph_iter_t; 42 | 43 | STATIC mp_obj_t polymorph_it_iternext(mp_obj_t self_in) { 44 | mp_obj_polymorph_iter_t *self = MP_OBJ_TO_PTR(self_in); 45 | // Redirect call to object instance's iternext method 46 | return self->iternext(self_in); 47 | } 48 | 49 | const mp_obj_type_t mp_type_polymorph_iter = { 50 | { &mp_type_type }, 51 | .name = MP_QSTR_iterator, 52 | .getiter = mp_identity_getiter, 53 | .iternext = polymorph_it_iternext, 54 | }; 55 | -------------------------------------------------------------------------------- /source/py/objsingleton.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #include "py/nlr.h" 31 | #include "py/obj.h" 32 | #include "py/runtime0.h" 33 | 34 | /******************************************************************************/ 35 | /* singleton objects defined by Python */ 36 | 37 | typedef struct _mp_obj_singleton_t { 38 | mp_obj_base_t base; 39 | qstr name; 40 | } mp_obj_singleton_t; 41 | 42 | STATIC void singleton_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { 43 | (void)kind; 44 | mp_obj_singleton_t *self = MP_OBJ_TO_PTR(self_in); 45 | mp_printf(print, "%q", self->name); 46 | } 47 | 48 | const mp_obj_type_t mp_type_singleton = { 49 | { &mp_type_type }, 50 | .name = MP_QSTR_, 51 | .print = singleton_print, 52 | }; 53 | 54 | const mp_obj_singleton_t mp_const_ellipsis_obj = {{&mp_type_singleton}, MP_QSTR_Ellipsis}; 55 | #if MICROPY_PY_BUILTINS_NOTIMPLEMENTED 56 | const mp_obj_singleton_t mp_const_notimplemented_obj = {{&mp_type_singleton}, MP_QSTR_NotImplemented}; 57 | #endif 58 | -------------------------------------------------------------------------------- /source/py/opmethods.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/runtime0.h" 28 | #include "py/builtin.h" 29 | 30 | STATIC mp_obj_t op_getitem(mp_obj_t self_in, mp_obj_t key_in) { 31 | mp_obj_type_t *type = mp_obj_get_type(self_in); 32 | return type->subscr(self_in, key_in, MP_OBJ_SENTINEL); 33 | } 34 | MP_DEFINE_CONST_FUN_OBJ_2(mp_op_getitem_obj, op_getitem); 35 | 36 | STATIC mp_obj_t op_setitem(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) { 37 | mp_obj_type_t *type = mp_obj_get_type(self_in); 38 | return type->subscr(self_in, key_in, value_in); 39 | } 40 | MP_DEFINE_CONST_FUN_OBJ_3(mp_op_setitem_obj, op_setitem); 41 | 42 | STATIC mp_obj_t op_delitem(mp_obj_t self_in, mp_obj_t key_in) { 43 | mp_obj_type_t *type = mp_obj_get_type(self_in); 44 | return type->subscr(self_in, key_in, MP_OBJ_NULL); 45 | } 46 | MP_DEFINE_CONST_FUN_OBJ_2(mp_op_delitem_obj, op_delitem); 47 | 48 | STATIC mp_obj_t op_contains(mp_obj_t lhs_in, mp_obj_t rhs_in) { 49 | mp_obj_type_t *type = mp_obj_get_type(lhs_in); 50 | return type->binary_op(MP_BINARY_OP_IN, lhs_in, rhs_in); 51 | } 52 | MP_DEFINE_CONST_FUN_OBJ_2(mp_op_contains_obj, op_contains); 53 | -------------------------------------------------------------------------------- /source/py/parsenumbase.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2013, 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/mpconfig.h" 28 | #include "py/misc.h" 29 | #include "py/parsenumbase.h" 30 | 31 | // find real radix base, and strip preceding '0x', '0o' and '0b' 32 | // puts base in *base, and returns number of bytes to skip the prefix 33 | size_t mp_parse_num_base(const char *str, size_t len, int *base) { 34 | const byte *p = (const byte*)str; 35 | if (len <= 1) { 36 | goto no_prefix; 37 | } 38 | unichar c = *(p++); 39 | if ((*base == 0 || *base == 16) && c == '0') { 40 | c = *(p++); 41 | if ((c | 32) == 'x') { 42 | *base = 16; 43 | } else if (*base == 0 && (c | 32) == 'o') { 44 | *base = 8; 45 | } else if (*base == 0 && (c | 32) == 'b') { 46 | *base = 2; 47 | } else { 48 | if (*base == 0) { 49 | *base = 10; 50 | } 51 | p -= 2; 52 | } 53 | } else if (*base == 8 && c == '0') { 54 | c = *(p++); 55 | if ((c | 32) != 'o') { 56 | p -= 2; 57 | } 58 | } else if (*base == 2 && c == '0') { 59 | c = *(p++); 60 | if ((c | 32) != 'b') { 61 | p -= 2; 62 | } 63 | } else { 64 | p--; 65 | no_prefix: 66 | if (*base == 0) { 67 | *base = 10; 68 | } 69 | } 70 | return p - (const byte*)str; 71 | } 72 | -------------------------------------------------------------------------------- /source/py/runtime_utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2015 Josef Gajdusek 7 | * Copyright (c) 2015 Paul Sokolovsky 8 | * 9 | * Permission is hereby granted, free of charge, to any person obtaining a copy 10 | * of this software and associated documentation files (the "Software"), to deal 11 | * in the Software without restriction, including without limitation the rights 12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | * copies of the Software, and to permit persons to whom the Software is 14 | * furnished to do so, subject to the following conditions: 15 | * 16 | * The above copyright notice and this permission notice shall be included in 17 | * all copies or substantial portions of the Software. 18 | * 19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 25 | * THE SOFTWARE. 26 | */ 27 | 28 | #include "py/runtime.h" 29 | #include "py/obj.h" 30 | #include "py/nlr.h" 31 | 32 | void mp_call_function_1_protected(mp_obj_t fun, mp_obj_t arg) { 33 | nlr_buf_t nlr; 34 | if (nlr_push(&nlr) == 0) { 35 | mp_call_function_1(fun, arg); 36 | nlr_pop(); 37 | } else { 38 | mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); 39 | } 40 | } 41 | 42 | void mp_call_function_2_protected(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) { 43 | nlr_buf_t nlr; 44 | if (nlr_push(&nlr) == 0) { 45 | mp_call_function_2(fun, arg1, arg2); 46 | nlr_pop(); 47 | } else { 48 | mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /source/py/stackctrl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Paul Sokolovsky 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include "py/mpstate.h" 28 | #include "py/nlr.h" 29 | #include "py/obj.h" 30 | #include "py/runtime.h" 31 | #include "py/stackctrl.h" 32 | 33 | void mp_stack_ctrl_init(void) { 34 | volatile int stack_dummy; 35 | MP_STATE_THREAD(stack_top) = (char*)&stack_dummy; 36 | } 37 | 38 | void mp_stack_set_top(void *top) { 39 | MP_STATE_THREAD(stack_top) = top; 40 | } 41 | 42 | mp_uint_t mp_stack_usage(void) { 43 | // Assumes descending stack 44 | volatile int stack_dummy; 45 | return MP_STATE_THREAD(stack_top) - (char*)&stack_dummy; 46 | } 47 | 48 | #if MICROPY_STACK_CHECK 49 | 50 | void mp_stack_set_limit(mp_uint_t limit) { 51 | MP_STATE_THREAD(stack_limit) = limit; 52 | } 53 | 54 | void mp_exc_recursion_depth(void) { 55 | nlr_raise(mp_obj_new_exception_arg1(&mp_type_RuntimeError, 56 | MP_OBJ_NEW_QSTR(MP_QSTR_maximum_space_recursion_space_depth_space_exceeded))); 57 | } 58 | 59 | void mp_stack_check(void) { 60 | if (mp_stack_usage() >= MP_STATE_THREAD(stack_limit)) { 61 | mp_exc_recursion_depth(); 62 | } 63 | } 64 | 65 | #endif // MICROPY_STACK_CHECK 66 | -------------------------------------------------------------------------------- /source/py/warning.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the MicroPython project, http://micropython.org/ 3 | * 4 | * The MIT License (MIT) 5 | * 6 | * Copyright (c) 2014 Damien P. George 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in 16 | * all copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | * THE SOFTWARE. 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #include "py/emit.h" 31 | #include "py/runtime.h" 32 | 33 | #if MICROPY_WARNINGS 34 | 35 | void mp_warning(const char *msg, ...) { 36 | va_list args; 37 | va_start(args, msg); 38 | mp_print_str(&mp_plat_print, "Warning: "); 39 | mp_vprintf(&mp_plat_print, msg, args); 40 | mp_print_str(&mp_plat_print, "\n"); 41 | va_end(args); 42 | } 43 | 44 | void mp_emitter_warning(pass_kind_t pass, const char *msg) { 45 | if (pass == MP_PASS_CODE_SIZE) { 46 | mp_warning(msg, NULL); 47 | } 48 | } 49 | 50 | #endif // MICROPY_WARNINGS 51 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | Tests 2 | ===== 3 | 4 | This directory contains script[s] that can be used to confirm various features 5 | of the micro:bit are working. They are as follows: 6 | 7 | * `exercise.py` - a general exercise of various aspects of the hardware. Not exhaustive and requires the user to press buttons A or B to move forward in the tests. Completes with a smile. 8 | * ??? - TBC 9 | 10 | -------------------------------------------------------------------------------- /tests/exercise.py: -------------------------------------------------------------------------------- 1 | # Exercises the micro:bit - NOT EXHAUSTIVE! 2 | from microbit import * 3 | import music 4 | import random 5 | 6 | 7 | # Press A to start. 8 | while True: 9 | if button_a.was_pressed(): 10 | break 11 | else: 12 | display.show(Image.ARROW_W) 13 | sleep(200) 14 | display.clear() 15 | sleep(200) 16 | 17 | 18 | # Asyncronously play a jolly little tune (connect speaker to pin0 and GND) 19 | music.play(music.NYAN, wait=False) 20 | 21 | 22 | # Grab all the built in images. 23 | images = [getattr(Image, img) for img in dir(Image) 24 | if type(getattr(Image, img)) == Image] 25 | # ... and cycle through them on the display. 26 | pause = 1000 27 | for img in images: 28 | display.show(img) 29 | sleep(pause) 30 | pause -= 50 31 | if pause < 100: 32 | pause = 100 33 | display.clear() 34 | 35 | 36 | # Aural testing of the accelerometer. 37 | display.scroll("Accelerometer") 38 | display.show("X") 39 | while not button_a.is_pressed(): 40 | music.pitch(abs(accelerometer.get_x()), 20) 41 | sleep(500) 42 | display.show("Y") 43 | while not button_a.is_pressed(): 44 | music.pitch(abs(accelerometer.get_y()), 20) 45 | sleep(500) 46 | display.show("Z") 47 | while not button_a.is_pressed(): 48 | music.pitch(abs(accelerometer.get_z()), 20) 49 | 50 | 51 | # Aural testing of the compass. 52 | display.scroll("Compass") 53 | compass.calibrate() 54 | while not button_b.is_pressed(): 55 | music.pitch(abs(compass.heading()), 20) 56 | 57 | 58 | # Pixel brightness. 59 | display.scroll("Display") 60 | dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ] 61 | while not button_a.is_pressed(): 62 | dots[random.randrange(5)][random.randrange(5)] = 9 63 | for i in range(5): 64 | for j in range(5): 65 | display.set_pixel(i, j, dots[i][j]) 66 | dots[i][j] = max(dots[i][j] - 1, 0) 67 | sleep(50) 68 | 69 | 70 | # ??? Add further tests here... 71 | 72 | 73 | # Finished! 74 | display.scroll("Finished!") 75 | display.show(Image.HAPPY) 76 | -------------------------------------------------------------------------------- /tests/radio_audio.py: -------------------------------------------------------------------------------- 1 | 2 | import audio 3 | import radio 4 | from microbit import button_a, button_b, display, running_time, sleep 5 | import os 6 | 7 | def sample_generator(filename): 8 | buf = audio.AudioFrame() 9 | with open(filename, "rb") as file: 10 | ln = -1 11 | while ln: 12 | ln = file.readinto(buf) 13 | yield buf 14 | 15 | # 1 second of 128Hz sawtooth wave. 16 | def sawtooth_generator(): 17 | sawtooth = audio.AudioFrame() 18 | for i in range(32): 19 | sawtooth[i] = i*8+4 20 | for i in range(256): 21 | yield sawtooth 22 | 23 | 24 | def send(): 25 | display.clear() 26 | radio.on() 27 | radio.config(channel=90, power=4) 28 | if "sample.raw" in os.listdir(): 29 | gen = sample_generator("sample.raw") 30 | else: 31 | gen = sawtooth_generator() 32 | start = running_time() 33 | sent = 0 34 | for f in gen: 35 | # One frame every 4ms = 8kHz 36 | while sent > ((running_time() - start) >> 2) + 3: 37 | sleep(1) 38 | radio.send_bytes(f) 39 | sent += 1 40 | print(sent) 41 | 42 | def play(): 43 | display.clear() 44 | radio.on() 45 | radio.config(channel=90, queue=12) 46 | count = -1 47 | def gen(): 48 | recvd = audio.AudioFrame() 49 | empty = audio.AudioFrame() 50 | while True: 51 | if radio.receive_bytes_into(recvd) == 32: 52 | yield recvd 53 | else: 54 | yield empty 55 | if button_a.is_pressed() and button_b.is_pressed(): 56 | return 57 | audio.play(gen()) 58 | 59 | while True: 60 | message = "Press button a to send 'sample.raw' or sawtooth wave. Press button b to play received waveform. Press both buttons to stop." 61 | display.scroll(message, delay=100, wait=False) 62 | message_end = running_time() + len(message)*600 63 | if button_a.is_pressed() and button_b.is_pressed(): 64 | break 65 | while True: 66 | sleep(50) 67 | if button_a.is_pressed(): 68 | send() 69 | break 70 | if button_b.is_pressed(): 71 | play() 72 | break 73 | if running_time() > message_end: 74 | break 75 | -------------------------------------------------------------------------------- /tests/sample.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bbcmicrobit/micropython/359fd6bffd6d57bed3a11b1acb2ebb0f9f9494c8/tests/sample.raw -------------------------------------------------------------------------------- /tests/test_files3.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | from microbit import display, Image 4 | 5 | #We don't have space for Beowolf, so here's the next best thing... 6 | text = """ 7 | ’Twas brillig, and the slithy toves 8 | Did gyre and gimble in the wabe: 9 | All mimsy were the borogoves, 10 | And the mome raths outgrabe. 11 | 12 | “Beware the Jabberwock, my son! 13 | The jaws that bite, the claws that catch! 14 | Beware the Jubjub bird, and shun 15 | The frumious Bandersnatch!” 16 | 17 | He took his vorpal sword in hand; 18 | Long time the manxome foe he sought— 19 | So rested he by the Tumtum tree 20 | And stood awhile in thought. 21 | 22 | And, as in uffish thought he stood, 23 | The Jabberwock, with eyes of flame, 24 | Came whiffling through the tulgey wood, 25 | And burbled as it came! 26 | 27 | One, two! One, two! And through and through 28 | The vorpal blade went snicker-snack! 29 | He left it dead, and with its head 30 | He went galumphing back. 31 | 32 | “And hast thou slain the Jabberwock? 33 | Come to my arms, my beamish boy! 34 | O frabjous day! Callooh! Callay!” 35 | He chortled in his joy. 36 | 37 | ’Twas brillig, and the slithy toves 38 | Did gyre and gimble in the wabe: 39 | All mimsy were the borogoves, 40 | And the mome raths outgrabe. 41 | """ 42 | 43 | def test_read_while_writing(): 44 | j1 = open("jabbawocky.txt", "w") 45 | j1.write(text) 46 | j2 = open("jabbawocky.txt") 47 | short = j2.read() 48 | assert text.startswith(short) 49 | del j2 50 | j1.close() 51 | j2 = open("jabbawocky.txt") 52 | assert j2.read() == text 53 | j2.close() 54 | os.remove("jabbawocky.txt") 55 | 56 | def test_removing_mid_read(): 57 | with open("jabbawocky.txt", "w") as j: 58 | j.write(text) 59 | j = open("jabbawocky.txt") 60 | os.remove("jabbawocky.txt") 61 | try: 62 | j.read() 63 | assert False, "Shouldn't reach here" 64 | except OSError: 65 | pass 66 | 67 | def test_removing_mid_write(): 68 | j = open("jabbawocky.txt", "w") 69 | os.remove("jabbawocky.txt") 70 | try: 71 | j.write(text) 72 | assert False, "Shouldn't reach here" 73 | except OSError: 74 | pass 75 | 76 | def test_repeated_write(): 77 | for i in range(40): 78 | with open("jabbawocky.txt", "w") as j: 79 | j.write(text) 80 | 81 | display.clear() 82 | try: 83 | test_read_while_writing() 84 | test_removing_mid_read() 85 | test_removing_mid_write() 86 | test_repeated_write() 87 | print("File test: PASS") 88 | display.show(Image.HAPPY) 89 | except Exception as ae: 90 | display.show(Image.SAD) 91 | raise 92 | 93 | -------------------------------------------------------------------------------- /tests/test_image.py: -------------------------------------------------------------------------------- 1 | 2 | from microbit import display, Image 3 | 4 | def eq(i, j): 5 | w = i.width() 6 | h = i.height() 7 | if w != j.width(): 8 | return False 9 | if h != j.height(): 10 | return False 11 | for x in range(w): 12 | for y in range(h): 13 | if i.get_pixel(x,y) != j.get_pixel(x,y): 14 | return False 15 | return True 16 | 17 | TEST = Image("44444:45554:45654:45554:44444") 18 | 19 | def test_blit(): 20 | assert eq(TEST, TEST) 21 | i = Image(4, 4) 22 | i.blit(TEST, 1, 1, 5, 5) 23 | assert eq(i, Image("5554:5654:5554:4444")) 24 | i.fill(2) 25 | i.blit(TEST, -2, -2, 3, 3) 26 | assert eq(i, Image('0002:0002:0042:2222')) 27 | i.fill(2) 28 | i.blit(TEST, 2, 2, 3, 3) 29 | assert eq(i, Image('6542:5542:4442:2222')) 30 | i.fill(2) 31 | i.blit(TEST, 0, 0, 5, 5, -3, -3) 32 | assert eq(i, Image('5422:4422:2222:2222')) 33 | i.fill(2) 34 | i.blit(TEST, 2, 2, 2, 2, 1, 1) 35 | assert eq(i, Image('2222:2652:2552:2222')) 36 | i = TEST.copy() 37 | i.blit(i, 2, 2, 3, 3) 38 | assert eq(i, Image('65444:55454:44454:45554:44444')) 39 | i = TEST.copy() 40 | i.blit(i, -2, -2, 5, 5) 41 | assert eq(i, Image('00000:00000:00444:00455:00456')) 42 | i = TEST.copy() 43 | i.blit(i, 0, 0, 3, 3, 2, 2) 44 | assert eq(i, Image('44444:45554:45444:45455:44456')) 45 | i = Image(2, 7) 46 | i.fill(2) 47 | i.blit(TEST, -100, -100, 50, 50, 1, 1) 48 | assert eq(i, Image('22:20:20:20:20:20:20')) 49 | 50 | def test_crop(): 51 | assert eq(TEST.crop(-1, -1, 2, 2), Image('00:04')) 52 | assert eq(TEST.crop(1, 1, 2, 2), Image('55:56')) 53 | assert eq(TEST.crop(4, 4, 3, 3), Image('400:000:000')) 54 | 55 | def test_shift(): 56 | assert eq(TEST, TEST.shift_left(0)) 57 | assert eq(TEST, TEST.shift_up(0)) 58 | for n in range(-6, 7): 59 | assert eq(TEST.shift_left(n), TEST.shift_right(-n)) 60 | assert eq(TEST.shift_up(n), TEST.shift_down(-n)) 61 | assert eq(TEST.shift_left(1), Image('44440:55540:56540:55540:44440')) 62 | assert eq(TEST.shift_down(1), Image('00000:44444:45554:45654:45554')) 63 | 64 | try: 65 | display.scroll("blit") 66 | test_blit() 67 | display.scroll("crop") 68 | test_crop() 69 | display.scroll("shift") 70 | test_shift() 71 | print("Image test: PASS") 72 | display.show(Image.HAPPY) 73 | except Exception as ae: 74 | display.show(Image.SAD) 75 | raise 76 | -------------------------------------------------------------------------------- /tests/test_music.py: -------------------------------------------------------------------------------- 1 | 2 | from microbit import display, Image, pin0, pin1, pin2, pin8 3 | import music 4 | 5 | PINS = pin0, pin1, pin2, pin8 6 | FREQS = 400, 500, 600, 700, 800, 900 7 | 8 | def test_rapid_pin_switch(): 9 | for i in range(20): 10 | for pin in PINS: 11 | music.play(music.NYAN, pin, wait=False) 12 | 13 | def test_rapid_pitch_switch(): 14 | for i in range(20): 15 | for freq in FREQS: 16 | music.pitch(freq, wait=False) 17 | 18 | def test_repeated_stop(): 19 | for i in range(20): 20 | music.stop() 21 | 22 | def test_repeated_reset(): 23 | for i in range(20): 24 | music.reset() 25 | 26 | def test_repeated_set_tempo(): 27 | for i in range(20): 28 | music.set_tempo(ticks=i%4+1, bpm=i+100) 29 | 30 | def test_all_pins_free(): 31 | for pin in PINS: 32 | pin.read_digital() 33 | 34 | display.clear() 35 | try: 36 | test_rapid_pin_switch() 37 | test_rapid_pitch_switch() 38 | test_repeated_stop() 39 | test_repeated_reset() 40 | test_repeated_set_tempo() 41 | test_all_pins_free() 42 | print("File test: PASS") 43 | display.show(Image.HAPPY) 44 | except Exception as ae: 45 | display.show(Image.SAD) 46 | raise 47 | -------------------------------------------------------------------------------- /tests/test_pins.py: -------------------------------------------------------------------------------- 1 | #This tests that the mode of pins can be configured properly and that pull works OK. 2 | 3 | from microbit import * 4 | import music 5 | 6 | BIG_PINS = pin0, pin1, pin2 7 | DISPLAY_PINS = pin3, pin4, pin6, pin7, pin9, pin10 8 | 9 | def test_mode_switching(): 10 | print ("Switching mode from analog to digital on big pins") 11 | for p0 in BIG_PINS: 12 | p0.write_analog(100) 13 | for p1 in BIG_PINS: 14 | p1.write_digital(0) 15 | p0.write_analog(0) 16 | for p in BIG_PINS: 17 | p.write_analog(100) 18 | assert p.get_mode() == "write_analog" 19 | p.read_digital() 20 | assert p.get_mode() == "read_digital" 21 | p.write_analog(0) 22 | assert p.get_mode() == "unused" 23 | p.write_digital(1) 24 | assert p.get_mode() == "write_digital" 25 | p.read_analog() 26 | assert p.get_mode() == "unused" 27 | 28 | def test_display_pins(): 29 | print ("Switching mode to digital for display pins") 30 | for p0 in DISPLAY_PINS: 31 | try: 32 | p0.write_digital(0) 33 | except ValueError: 34 | pass 35 | try: 36 | p0.write_analog(0) 37 | except ValueError: 38 | pass 39 | display.off() 40 | for p0 in DISPLAY_PINS: 41 | p0.write_digital(0) 42 | display.on() 43 | display.off() 44 | for p0 in DISPLAY_PINS: 45 | p0.write_analog(200) 46 | display.on() 47 | 48 | def test_music(): 49 | print ("Switching mode to digital for music pins") 50 | music.play(music.DADADADUM,pin=pin0,wait=False) 51 | try: 52 | pin0.write_digital(0) 53 | except ValueError: 54 | pass 55 | music.stop() 56 | pin0.write_digital(0) 57 | 58 | def test_pull(): 59 | print ("Setting pull on big pins") 60 | for p in BIG_PINS: 61 | p.read_digital() 62 | p.set_pull(p.PULL_UP) 63 | assert p.get_pull() == p.PULL_UP 64 | assert p.read_digital() 65 | p.set_pull(p.PULL_DOWN) 66 | assert p.get_pull() == p.PULL_DOWN 67 | assert p.read_digital() == 0 68 | p.set_pull(p.NO_PULL) 69 | assert p.get_pull() == p.NO_PULL 70 | print ("Setting pull on display pins") 71 | display.off() 72 | for p in DISPLAY_PINS: 73 | p.read_digital() 74 | p.set_pull(p.PULL_UP) 75 | assert p.read_digital() 76 | p.set_pull(p.PULL_DOWN) 77 | assert p.read_digital() == 0 78 | display.on() 79 | 80 | try: 81 | test_mode_switching() 82 | test_display_pins() 83 | test_music() 84 | test_pull() 85 | print("Pin test: PASS") 86 | display.show(Image.HAPPY) 87 | except Exception as ae: 88 | display.show(Image.SAD) 89 | raise 90 | 91 | -------------------------------------------------------------------------------- /tests/test_pwm.py: -------------------------------------------------------------------------------- 1 | #This tests that the duty cycle of PWM is (approximately) correct. 2 | 3 | from microbit import * 4 | 5 | def pins_connected(p0, p1): 6 | for i in 0,1,0,1,0,1,0,1: 7 | p0.write_digital(i) 8 | if p1.read_digital() != i: 9 | return False 10 | p1.write_digital(i) 11 | if p0.read_digital() != i: 12 | return False 13 | return True 14 | 15 | def test_pwm(p0, p1): 16 | #Flip between modes many times 17 | for i in range(100): 18 | pin0.write_digital(i & 1) 19 | pin0.write_analog(i*10) 20 | #Now make sure it is still working. 21 | p0.write_digital(0) 22 | for val in 100, 200, 300, 500, 800, 900: 23 | print("Testing duty cycle", val) 24 | p0.write_analog(val) 25 | sleep(20) 26 | count = 0 27 | for i in range(10*1024): 28 | count += p1.read_digital() 29 | print("%+0.2f%%" % ((count-val*10)/val*10)) 30 | # Allow +- 5% 31 | assert abs(count - val*10) < val//2 32 | 33 | try: 34 | if pins_connected(pin0, pin1): 35 | test_pwm(pin0, pin1) 36 | print("PWM test: PASS") 37 | display.show(Image.HAPPY) 38 | else: 39 | print("Connect pin0 to pin1") 40 | display.show("?") 41 | except Exception as ae: 42 | display.show(Image.SAD) 43 | raise 44 | 45 | -------------------------------------------------------------------------------- /tests/test_random.py: -------------------------------------------------------------------------------- 1 | # test the random module 2 | 3 | import random 4 | 5 | result = ('FAIL', 'PASS') 6 | 7 | # test getrandbits 8 | hist = 8 * [0] 9 | for i in range(300): 10 | r = random.getrandbits(3) 11 | hist[r] += 1 12 | ok = all(h >= 10 for h in hist) 13 | print('getrandbits:', result[ok]) 14 | 15 | # test seed 16 | random.seed(0x1234567) 17 | r1 = random.getrandbits(10) 18 | random.seed(0x1234567) 19 | r2 = random.getrandbits(10) 20 | print('seed: ', result[r1 == r2]) 21 | 22 | # test randint is within the given range 23 | ok = True 24 | for i in range(100): 25 | if not 0 <= random.randint(0, 9) <= 9: 26 | ok = False 27 | print('randint: ', result[ok]) 28 | -------------------------------------------------------------------------------- /tests/test_speech.py: -------------------------------------------------------------------------------- 1 | # test speech module 2 | 3 | import microbit 4 | import speech 5 | 6 | def test_funcs(): 7 | print('Testing basic functions') 8 | ph = speech.translate('hello world') 9 | assert ph == ' /HEHLOW WERLD' 10 | speech.pronounce('PIHTHUN', pitch=32, speed=60, mouth=100, throat=150) 11 | speech.say('hello') 12 | speech.sing('YEHSTERDEY5') 13 | 14 | def test_sleep(): 15 | # check that sleep works ok with speech because they both use low-level timers 16 | # (this is really a test of the audio module) 17 | print('Testing sleep with speech') 18 | microbit.sleep(1) 19 | speech.say('hello world') 20 | microbit.sleep(1) 21 | 22 | def test_timing(): 23 | # test that speech takes the correct amount of time over many runs 24 | print('Testing timing of say function') 25 | for i in range(5): 26 | start = microbit.running_time() 27 | speech.say('hello world') 28 | microbit.sleep(1) 29 | stop = microbit.running_time() 30 | assert 800 < stop - start < 815 31 | 32 | try: 33 | test_funcs() 34 | test_sleep() 35 | test_timing() 36 | print('Speech test: PASS') 37 | except Exception as ae: 38 | raise 39 | -------------------------------------------------------------------------------- /tools/adduicr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Add a UICR region to the hex firmware for MicroPython on the micro:bit. 5 | 6 | Usage: ./adduicr.py [-o ] 7 | 8 | Output goes to stdout if no filename is given. 9 | ''' 10 | 11 | import sys 12 | import struct 13 | import argparse 14 | import hexlifyscript 15 | import makecombinedhex 16 | 17 | NRF_PAGE_SIZE_LOG2 = 10 18 | NRF_PAGE_SIZE = 1 << NRF_PAGE_SIZE_LOG2 19 | UICR_BASE_ADDR = 0x100010c0 20 | UICR_MAGIC_NUMBER = 0x17eeb07c 21 | 22 | if __name__ == '__main__': 23 | arg_parser = argparse.ArgumentParser(description='Add UICR region to hex firmware for the micro:bit.') 24 | arg_parser.add_argument('-o', '--output', default=sys.stdout, type=argparse.FileType('wt'), help='output file (default is stdout)') 25 | arg_parser.add_argument('firmware', nargs=1, help='input MicroPython firmware') 26 | arg_parser.add_argument('address', nargs=1, type=lambda x: int(x, 0), help='address in flash of the version string') 27 | args = arg_parser.parse_args() 28 | 29 | # read in the firmware 30 | with open(args.firmware[0], 'rt') as f: 31 | firmware = f.readlines() 32 | 33 | # print head of firmware 34 | for line in firmware[:-2]: 35 | print(line, end='', file=args.output) 36 | 37 | # make UICR data 38 | uicr_data = b'' 39 | uicr_data += struct.pack('H', UICR_BASE_ADDR >> 16)), file=args.output) 45 | for i in range(0, len(uicr_data), 16): 46 | chunk = uicr_data[i:min(i + 16, len(uicr_data))] 47 | print(hexlifyscript.make_ihex_record(UICR_BASE_ADDR + i, hexlifyscript.IHEX_TYPE_DATA, chunk), file=args.output) 48 | 49 | # print tail of firmware 50 | print(firmware[-2], end='', file=args.output) 51 | print(firmware[-1], end='', file=args.output) 52 | -------------------------------------------------------------------------------- /tools/hexlifyscript.js: -------------------------------------------------------------------------------- 1 | /* 2 | Turn a Python script into Intel HEX format to be concatenated at the 3 | end of the MicroPython firmware.hex. A simple header is added to the 4 | script. 5 | 6 | To execute from command line: node hexlifyscript.js 7 | */ 8 | 9 | // hexlifyScript: 10 | // - takes a Python script as a string 11 | // - returns hexlified string, with newlines between lines 12 | function hexlifyScript(script) { 13 | function hexlify(ar) { 14 | var result = ''; 15 | for (var i = 0; i < ar.length; ++i) { 16 | if (ar[i] < 16) { 17 | result += '0'; 18 | } 19 | result += ar[i].toString(16); 20 | } 21 | return result; 22 | } 23 | 24 | // add header, pad to multiple of 16 bytes 25 | data = new Uint8Array(4 + script.length + (16 - (4 + script.length) % 16)); 26 | data[0] = 77; // 'M' 27 | data[1] = 80; // 'P' 28 | data[2] = script.length & 0xff; 29 | data[3] = (script.length >> 8) & 0xff; 30 | for (var i = 0; i < script.length; ++i) { 31 | data[4 + i] = script.charCodeAt(i); 32 | } 33 | // TODO check data.length < 0x2000 34 | 35 | // convert to .hex format 36 | var addr = 0x3e000; // magic start address in flash 37 | var chunk = new Uint8Array(5 + 16); 38 | var output = []; 39 | output.push(':020000040003F7') // extended linear address, 0x0003 40 | for (var i = 0; i < data.length; i += 16, addr += 16) { 41 | chunk[0] = 16; // length of data section 42 | chunk[1] = (addr >> 8) & 0xff; // high byte of 16-bit addr 43 | chunk[2] = addr & 0xff; // low byte of 16-bit addr 44 | chunk[3] = 0; // type (data) 45 | for (var j = 0; j < 16; ++j) { 46 | chunk[4 + j] = data[i + j]; 47 | } 48 | var checksum = 0; 49 | for (var j = 0; j < 4 + 16; ++j) { 50 | checksum += chunk[j]; 51 | } 52 | chunk[4 + 16] = (-checksum) & 0xff; 53 | output.push(':' + hexlify(chunk).toUpperCase()) 54 | } 55 | 56 | return output.join('\n'); 57 | } 58 | 59 | // read script from file, hexlify, then print to console 60 | console.log(hexlifyScript(require('fs').readFileSync(process.argv[2], 'utf8'))); 61 | -------------------------------------------------------------------------------- /tools/hexlifyscript.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Turn a Python script into Intel HEX format to be concatenated at the 5 | end of the MicroPython firmware.hex. A simple header is added to the 6 | script. 7 | 8 | To execute from command line: ./hexlifyscript.py 9 | It also accepts data on standard input. 10 | ''' 11 | 12 | import struct 13 | import binascii 14 | import fileinput 15 | 16 | 17 | IHEX_TYPE_DATA = 0 18 | IHEX_TYPE_EXT_LIN_ADDR = 4 19 | 20 | SCRIPT_ADDR = 0x3e000 # magic start address in flash of script 21 | 22 | def make_ihex_record(addr, type, data): 23 | record = struct.pack('>BHB', len(data), addr & 0xffff, type) + data 24 | checksum = (-(sum(record))) & 0xff 25 | return ':%s%02X' % (str(binascii.hexlify(record), 'utf8').upper(), checksum) 26 | 27 | def hexlify_script(script): 28 | # add header, pad to multiple of 16 bytes 29 | data = b'MP' + struct.pack('> 16 == 3) # 0x0003 is hard coded in line below 37 | output.append(make_ihex_record(0, IHEX_TYPE_EXT_LIN_ADDR, b'\x00\x03')) 38 | for i in range(0, len(data), 16): 39 | chunk = data[i:min(i + 16, len(data))] 40 | output.append(make_ihex_record(addr, IHEX_TYPE_DATA, chunk)) 41 | addr += 16 42 | 43 | return '\n'.join(output) 44 | 45 | if __name__ == '__main__': 46 | # read script from a file and print out the hexlified version 47 | with fileinput.input(mode='rb') as lines: 48 | print(hexlify_script(b''.join(lines))) 49 | -------------------------------------------------------------------------------- /tools/makecombinedhex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | ''' 4 | Combine the MicroPython firmware with a Python script and produce a hex file 5 | ready for uploading to the micro:bit. 6 | 7 | Usage: ./makecombinedhex.py [-o ] 8 | 9 | Output goes to stdout if no filename is given. 10 | ''' 11 | 12 | import sys 13 | import argparse 14 | import hexlifyscript 15 | 16 | def get_largest_addr(hexfile): 17 | largest_addr = 0 18 | for line in hexfile: 19 | count = int(line[1:3], 16) 20 | addr = int(line[3:7], 16) 21 | type = int(line[7:9], 16) 22 | if count == 2 and type == 4: # ext linear addr 23 | page = int(line[9:13], 16) << 16 24 | elif type == 0: # data 25 | # only count pages in flash, not in the UICR 26 | if page < 0x10000000: 27 | largest_addr = max(largest_addr, page + addr + count) 28 | return largest_addr 29 | 30 | def find_uicr_line(hexfile): 31 | for i, line in enumerate(hexfile): 32 | # UICR from 0x10001000 so we expect an extended linear address record 33 | if ':020000041000EA' in line: 34 | return i 35 | return None 36 | 37 | if __name__ == '__main__': 38 | arg_parser = argparse.ArgumentParser(description='Produce combined hex firmware for the micro:bit.') 39 | arg_parser.add_argument('-o', '--output', default=sys.stdout, type=argparse.FileType('wt'), help='output file (default is stdout)') 40 | arg_parser.add_argument('firmware', nargs=1, help='input MicroPython firmware') 41 | arg_parser.add_argument('script', nargs=1, help='input Python script') 42 | args = arg_parser.parse_args() 43 | 44 | # read in the firmware 45 | with open(args.firmware[0], 'rt') as f: 46 | firmware = f.readlines() 47 | 48 | # check the firmware is not too large 49 | if get_largest_addr(firmware) > hexlifyscript.SCRIPT_ADDR: 50 | raise Exception('firmware overflows into script region') 51 | 52 | # hexlify the script 53 | with open(args.script[0], 'rb') as f: 54 | script = hexlifyscript.hexlify_script(f.read()) 55 | 56 | # print lines until UICR area or the start linear address record 57 | firmware_end = find_uicr_line(firmware) or len(firmware) - 2 58 | for line in firmware[:firmware_end]: 59 | print(line, end='', file=args.output) 60 | 61 | # print script 62 | print(script, file=args.output) 63 | 64 | # print rest of hex file 65 | for line in firmware[firmware_end:]: 66 | print(line, end='', file=args.output) 67 | -------------------------------------------------------------------------------- /tools/makeqstrhdr.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # This script generates the qstrdefs.generated.h file. You'll need to run 4 | # it if you change any code with "MP_QSTR_xxx" in it, or if you get an 5 | # error from the compiler about undefined MP_QSTR_xxx constants. 6 | # 7 | # Run it from the root directory, like this: 8 | # 9 | # $ ./tools/makeqstrhdr.sh 10 | 11 | MKDIR=mkdir 12 | CAT=cat 13 | SED=sed 14 | PYTHON=python 15 | 16 | INC="-I. -Iinc -Iinc/lib -Iinc/microbit -Isource -Iyotta_modules/microbit-dal/inc/platform -Iyotta_modules/microbit-dal/inc/types -Iyotta_modules/microbit-dal/inc/core -Iyotta_modules/microbit-dal/inc/drivers -Iyotta_modules/mbed-classic/hal -Iyotta_modules/mbed-classic/targets/cmsis -Iyotta_modules/mbed-classic/api -Iyotta_modules/nrf51-sdk/source/nordic_sdk/components/device -Iyotta_modules/nrf51-sdk/source/nordic_sdk/components/drivers_nrf/hal -I./yotta_modules/mbed-classic/targets/cmsis/TARGET_NORDIC/TARGET_MCU_NRF51822 -Iyotta_modules/mbed-classic/targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822 -I./yotta_modules/mbed-classic/targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822/TARGET_NRF51_MICROBIT -Iyotta_modules/ble" 17 | DEF="-DNRF51 -DYOTTA_BUILD_INFO_HEADER=" 18 | CC=arm-none-eabi-gcc 19 | CXX=arm-none-eabi-g++ 20 | CFLAGS="$INC $DEF -Wall -Wpointer-arith -Werror -std=c99 -nostdlib" 21 | CXXFLAGS="$INC $DEF -Wall" 22 | 23 | TOP=source 24 | GENHDRDIR=./inc/genhdr 25 | SRC_C=$(find source -name '*.c') 26 | SRC_CXX=$(find source -name '*.cpp') 27 | QSTR_EXTRA="inc/py/qstrdefs.h inc/microbit/qstrdefsport.h" 28 | 29 | mkdir -p $GENHDRDIR 30 | 31 | echo "Preprocessing the source files" 32 | $CC -E -DNO_QSTR $CFLAGS $SRC_C > $GENHDRDIR/qstr.i.last || exit 1 33 | $CXX -E -DNO_QSTR $CXXFLAGS $SRC_CXX >> $GENHDRDIR/qstr.i.last || exit 1 34 | 35 | echo "Extracting all qstrs" 36 | $PYTHON $TOP/py/makeqstrdefs.py split $GENHDRDIR/qstr.i.last $GENHDRDIR/qstr $GENHDRDIR/qstrdefs.collected.h || exit 1 37 | $PYTHON $TOP/py/makeqstrdefs.py cat $GENHDRDIR/qstr.i.last $GENHDRDIR/qstr $GENHDRDIR/qstrdefs.collected.h || exit 1 38 | 39 | echo "Generating qstr header" 40 | $CAT $QSTR_EXTRA $GENHDRDIR/qstrdefs.collected.h | $SED 's/^Q(.*)/"&"/' | $CC -E $CFLAGS - | $SED 's/^"\(Q(.*)\)"/\1/' > $GENHDRDIR/qstrdefs.preprocessed.h || exit 1 41 | $PYTHON $TOP/py/makeqstrdata.py $GENHDRDIR/qstrdefs.preprocessed.h > $GENHDRDIR/qstrdefs.generated.h || exit 1 42 | --------------------------------------------------------------------------------