├── .gitignore ├── README.md ├── doc └── README.md ├── examples ├── ble-advertiser │ ├── advertise.py │ └── sniffer.py ├── ble-conn-sniffing │ └── sniff_conn.py ├── esb-sample-sniff.py │ └── wireless-keyboard-sniff.py └── helloworld │ └── helloworld.py ├── micropython ├── .gitignore ├── 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 │ │ ├── devfaq.rst │ │ ├── flashfirmware.rst │ │ ├── hexformat.rst │ │ ├── installation.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 │ ├── 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 │ ├── digital_water.py │ ├── dodge_game.py │ ├── flame_simulation.py │ ├── flappybit.py │ ├── four_buttons.py │ ├── i_feel_today.py │ ├── led_dance.py │ ├── magic8.py │ ├── maze.py │ ├── music.py │ ├── neopixel_random.py │ ├── play_file.py │ ├── pomodoro.py │ ├── radio.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 ├── precompiled └── radiobit.hex └── tools ├── cheerson-cx10 ├── README.md └── cxp0wn.py ├── ubit-sniffer ├── README.md ├── middleware │ └── ubit-sniffer-mw.py └── ubit-sniffer.py └── wireless-keylogger ├── README.md └── msft-keylogger.py /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore Micropython build firmware 2 | micropython/build/ 3 | 4 | # ignore Micropython yotta_modules 5 | micropython/yotta_modules/ 6 | 7 | # ignore Micropython yotta_targets 8 | micropython/yotta_targets/ 9 | micropython/.yotta* 10 | 11 | # ignore compiled Python modules 12 | *.pyc 13 | 14 | # ignore our virtualenv 15 | venv 16 | -------------------------------------------------------------------------------- /examples/ble-advertiser/advertise.py: -------------------------------------------------------------------------------- 1 | """ 2 | BLE advertising example 3 | 4 | This example uses a little hack to send BLE scan responses 5 | in time: it sends it straight forward even if not required. 6 | """ 7 | from microbit import * 8 | import radio 9 | 10 | adv_pkt = bytes([0x40, 0x42, 0xd8, 0x2a, 0x41, 0x32, 0x65,0x02, 0x01, 0x1a, 0x09, 0x09])+b'DEFCON25' 11 | scan_rsp = bytes([0x44, 0x42, 0xd8, 0x2a, 0x41, 0x32, 0x65, 0x03, 0xff,0x12,0x13]) 12 | radio.on() 13 | radio.config(channel=38) 14 | radio.ble() 15 | while True: 16 | for i in range(37,40): 17 | radio.config(channel=i) 18 | radio.send(adv_pkt) 19 | radio.send(scan_rsp) 20 | sleep(50) 21 | -------------------------------------------------------------------------------- /examples/ble-advertiser/sniffer.py: -------------------------------------------------------------------------------- 1 | from microbit import * 2 | import radio 3 | 4 | radio.on() 5 | radio.config(channel=38) 6 | radio.ble() 7 | 8 | while True: 9 | pkt = radio.receive_bytes() 10 | if pkt is not None: 11 | if len(pkt) > 13: 12 | addr = '%02x:%02x:%02x:%02x:%02x:%02x' % ( 13 | pkt[13], pkt[12], pkt[11], pkt[10], pkt[9], pkt[8] 14 | ) 15 | advinfo = ' '.join(['%02x'%c for c in pkt[14:]]) 16 | print('+ %s > %s' % (addr, advinfo)) 17 | del advinfo 18 | del addr 19 | del pkt 20 | -------------------------------------------------------------------------------- /examples/ble-conn-sniffing/sniff_conn.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script simply loops on advertising channels and 3 | sniffs BLE connection requests. 4 | """ 5 | import radio 6 | from microbit import * 7 | 8 | radio.on() 9 | radio.ble() 10 | timeout = 50 11 | last = running_time() 12 | chan = 0 13 | 14 | while True: 15 | if (running_time() - last) >= timeout: 16 | chan = (chan+1)%3 17 | radio.config(channel=(chan+37)) 18 | last = running_time() 19 | p = radio.receive() 20 | if p is not None and p[5]&0x0F == 5 and p[6]==0x22: 21 | #print(' '.join(['%02x'%c for c in p])) 22 | payload = p[8:] 23 | pl = ' '.join(['%02x' % c for c in payload]) 24 | print(pl) 25 | # parse connect_req 26 | inita = ':'.join(['%02x'%c for c in payload[:6]]) 27 | adva = ':'.join(['%02x'%c for c in payload[6:12]]) 28 | aa = payload[12] | payload[13]<<8 | payload[14]<<16 |payload[15]<<24 29 | crcinit = (payload[16])|(payload[17]<<8)|(payload[18]<<16) 30 | hop_increment = (payload[33]&0x1f) 31 | hop_interval = payload[22] | payload[23]<<8 32 | 33 | print('[%08x] %s -> %s (CRCInit: %06x, hopInc: %d, hopInter: %d)' % (aa, inita, adva, crcinit, hop_increment, hop_interval)) 34 | -------------------------------------------------------------------------------- /examples/esb-sample-sniff.py/wireless-keyboard-sniff.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quick'n'dirty ESB sniffer listening on channel 74 at 2MBit/s 3 | """ 4 | import radio 5 | 6 | radio.on() 7 | radio.config(data_rate=radio.RATE_2MBIT, channel=74) 8 | radio.sniff_on() 9 | 10 | while True: 11 | pkt = radio.sniff() 12 | if pkt is not None: 13 | addr = ':'.join(['%2x'%c for c in pkt[:5]]) 14 | payload = ''.join(['%02x '%c for c in pkt[5:]]) 15 | print('%s > %s' % (addr, payload)) 16 | -------------------------------------------------------------------------------- /examples/helloworld/helloworld.py: -------------------------------------------------------------------------------- 1 | import microbit 2 | 3 | microbit.display.scroll('Hello world !') 4 | -------------------------------------------------------------------------------- /micropython/.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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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) $$(cat $(VER_ADDR_FILE)) -o $(HEX_FINAL) 16 | @size $(HEX_SRC:.hex=) 17 | 18 | yotta: $(MBIT_VER_FILE) 19 | @yt build 20 | 21 | $(MBIT_VER_FILE): FORCE 22 | python tools/makeversionhdr.py $(MBIT_VER_FILE) 23 | 24 | $(VER_ADDR_FILE): yotta 25 | @echo -n "0x" > $(VER_ADDR_FILE) 26 | @objdump -x $(HEX_SRC:.hex=) | grep microbit_version_string | cut -f 1 -d' ' >> $(VER_ADDR_FILE) 27 | 28 | deploy: $(HEX_FINAL) 29 | $(ECHO) "Deploying $<" 30 | @mount /dev/sdb 31 | @sleep 1s 32 | @cp $< /mnt/ 33 | @sleep 1s 34 | @umount /mnt 35 | 36 | serial: 37 | @picocom /dev/ttyACM0 -b 115200 38 | -------------------------------------------------------------------------------- /micropython/README.md: -------------------------------------------------------------------------------- 1 | MicroPython for the BBC micro:bit 2 | ================================= 3 | 4 | This is the source code for MicroPython running on the BBC micro:bit! 5 | 6 | To get involved with the micro:bit community join the Slack channel by signing up here: 7 | https://tech.microbit.org/get-involved/where-to-find/ 8 | 9 | Various things are in this repository, including: 10 | - Source code in source/ and inc/ directories. 11 | - Example Python programs in the examples/ directory. 12 | - Tools in the tools/ directory. 13 | 14 | The source code is a yotta application and needs yotta to build, along 15 | with an ARM compiler toolchain (eg arm-none-eabi-gcc and friends). 16 | 17 | Ubuntu users can install the needed packages using: 18 | ``` 19 | sudo add-apt-repository -y ppa:team-gcc-arm-embedded 20 | sudo add-apt-repository -y ppa:pmiller-opensource/ppa 21 | sudo apt-get update 22 | sudo apt-get install cmake ninja-build gcc-arm-none-eabi srecord libssl-dev 23 | pip3 install yotta 24 | ``` 25 | 26 | Once all packages are installed, use yotta and the provided Makefile to build. 27 | You might need need an Arm Mbed account to complete some of the yotta commands, 28 | if so, you could be prompted to create one as a part of the process. 29 | 30 | - Use target bbc-microbit-classic-gcc-nosd: 31 | 32 | ``` 33 | yt target bbc-microbit-classic-gcc-nosd 34 | ``` 35 | 36 | - Run yotta update to fetch remote assets: 37 | 38 | ``` 39 | yt up 40 | ``` 41 | 42 | - Start the build: 43 | 44 | ``` 45 | make all 46 | ``` 47 | 48 | The resulting firmware.hex file to flash onto the device can be 49 | found in the build/ directory from the root of the repository. 50 | 51 | The Makefile provided does some extra preprocessing of the source, 52 | adds version information to the UICR region, puts the resulting 53 | firmware at build/firmware.hex, and includes some convenience targets. 54 | 55 | How to use 56 | ========== 57 | 58 | Upon reset you will have a REPL on the USB CDC serial port, with baudrate 59 | 115200 (eg picocom /dev/ttyACM0 -b 115200). 60 | 61 | Then try: 62 | 63 | >>> import microbit 64 | >>> microbit.display.scroll('hello!') 65 | >>> microbit.button_a.is_pressed() 66 | >>> dir(microbit) 67 | 68 | Tab completion works and is very useful! 69 | 70 | Read our documentation here: 71 | 72 | https://microbit-micropython.readthedocs.io/en/latest/ 73 | 74 | You can also use the tools/pyboard.py script to run Python scripts directly 75 | from your PC, eg: 76 | 77 | $ ./tools/pyboard.py /dev/ttyACM0 examples/conway.py 78 | 79 | Be brave! Break things! Learn and have fun! 80 | -------------------------------------------------------------------------------- /micropython/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "microbit" : { 3 | "configfile" : "inc/microbit/MicroBitCustomConfig.h" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /micropython/docs/audio.rst: -------------------------------------------------------------------------------- 1 | Audio 2 | ******* 3 | 4 | .. py:module:: audio 5 | 6 | This module allows you play sounds from a speaker attached to the Microbit. 7 | In order to use the audio module you will need to provide a sound source. 8 | 9 | A sound source is an iterable (sequence, like list or tuple, or a generator) of 10 | frames, each of 32 samples. 11 | The ``audio`` modules plays samples at the rate of 7812.5 samples per second, 12 | which means that it can reproduce frequencies up to 3.9kHz. 13 | 14 | Functions 15 | ========= 16 | 17 | .. py:function:: play(source, wait=True, pin=pin0, return_pin=None) 18 | 19 | Play the source to completion. 20 | 21 | ``source`` is an iterable, each element of which must be an ``AudioFrame``. 22 | 23 | If ``wait`` is ``True``, this function will block until the source is exhausted. 24 | 25 | ``pin`` specifies which pin the speaker is connected to. 26 | 27 | ``return_pin`` specifies a differential pin to connect to the speaker 28 | instead of ground. 29 | 30 | Classes 31 | ======= 32 | 33 | .. py:class:: 34 | AudioFrame 35 | 36 | An ``AudioFrame`` object is a list of 32 samples each of which is a signed byte 37 | (whole number between -128 and 127). 38 | 39 | It takes just over 4 ms to play a single frame. 40 | 41 | Using audio 42 | =========== 43 | 44 | You will need a sound source, as input to the ``play`` function. You can generate your own, like in 45 | ``examples/waveforms.py``. 46 | 47 | 48 | Technical Details 49 | ================= 50 | 51 | .. note:: 52 | You don't need to understand this section to use the ``audio`` module. 53 | It is just here in case you wanted to know how it works. 54 | 55 | The ``audio`` module consumes samples at 7812.5 Hz, and uses linear interpolation to 56 | output a PWM signal at 32.5 kHz, which gives tolerable sound quality. 57 | 58 | The function ``play`` fully copies all data from each ``AudioFrame`` before it 59 | calls ``next()`` for the next frame, so a sound source can use the same ``AudioFrame`` 60 | repeatedly. 61 | 62 | The ``audio`` module has an internal 64 sample buffer from which it reads samples. 63 | When reading reaches the start or the mid-point of the buffer, it triggers a callback to 64 | fetch the next ``AudioFrame`` which is then copied into the buffer. 65 | This means that a sound source has under 4ms to compute the next ``AudioFrame``, 66 | and for reliable operation needs to take less 2ms (which is 32000 cycles, so should be plenty). 67 | 68 | 69 | Example 70 | ======= 71 | 72 | .. include:: ../examples/waveforms.py 73 | :code: python 74 | 75 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/comic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/comic.png -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/devguide/devfaq.rst: -------------------------------------------------------------------------------- 1 | .. _devfaq: 2 | 3 | ============= 4 | Developer FAQ 5 | ============= 6 | 7 | .. note:: 8 | 9 | This project is under active development. Please help other 10 | developers by adding tips, how-tos, and Q&A to this document. 11 | Thanks! 12 | 13 | Where do I get a copy of the DAL? A: Ask Nicholas Tollervey for details. 14 | -------------------------------------------------------------------------------- /micropython/docs/devguide/flashfirmware.rst: -------------------------------------------------------------------------------- 1 | .. _flashfirmware: 2 | 3 | ================= 4 | Flashing Firmware 5 | ================= 6 | 7 | Building firmware 8 | ----------------- 9 | Use yotta to build. 10 | 11 | Use target bbc-microbit-classic-gcc-nosd:: 12 | 13 | yt target bbc-microbit-classic-gcc-nosd 14 | 15 | Run yotta update to fetch remote assets:: 16 | 17 | yt up 18 | 19 | Start the build with either yotta:: 20 | 21 | yt build 22 | 23 | ...or use the Makefile:: 24 | 25 | make all 26 | 27 | The result is a microbit-micropython hex file (i.e. ``microbit-micropython.hex``) 28 | found in the build/bbc-microbit-classic-gcc-nosd/source from the root of the 29 | repository. 30 | 31 | The Makefile does some extra preprocessing of the source, which is needed only 32 | if you add new interned strings to ``qstrdefsport.h``. The Makefile also puts 33 | the resulting firmware at build/firmware.hex, and includes some convenience 34 | targets. 35 | 36 | Preparing firmware and a Python program 37 | --------------------------------------- 38 | 39 | tools/makecombined 40 | 41 | hexlify 42 | 43 | 44 | 45 | Flashing to the micro:bit 46 | ------------------------- 47 | 48 | 49 | 50 | 51 | **Installation Scenarios** 52 | 53 | * :ref:`Windows ` 54 | * :ref:`OS X ` 55 | * :ref:`Linux ` 56 | * :ref:`Debian and Ubuntu ` 57 | * :ref:`Red Hat Fedora/CentOS ` 58 | * :ref:`Raspberry Pi ` 59 | -------------------------------------------------------------------------------- /micropython/docs/devguide/installation.rst: -------------------------------------------------------------------------------- 1 | .. _install-dev: 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | This section will help you set up the tools and programs needed for 8 | developing programs and firmware to flash to the BBC micro:bit using MicroPython. 9 | 10 | Dependencies 11 | ------------ 12 | 13 | 14 | Development Environment 15 | ----------------------- 16 | 17 | You will need: 18 | 19 | * git 20 | * yotta 21 | 22 | Depending on your operating system, the installation instructions vary. Use 23 | the installation scenario that best suits your system. 24 | 25 | Yotta will require an ARM mbed account. It will walk you through signing up 26 | if you are not registered. 27 | 28 | Installation Scenarios 29 | ---------------------- 30 | 31 | * :ref:`Windows ` 32 | * :ref:`OS X ` 33 | * :ref:`Linux ` 34 | * :ref:`Debian and Ubuntu ` 35 | * :ref:`Red Hat Fedora/CentOS ` 36 | * :ref:`Raspberry Pi ` 37 | 38 | 39 | .. _microbit-windows: 40 | 41 | Windows 42 | ~~~~~~~ 43 | 44 | When installing `Yotta 45 | `_, make sure you have these components ticked to install. 46 | 47 | - python 48 | - gcc 49 | - cMake 50 | - ninja 51 | - Yotta 52 | - git-scm 53 | - mbed serial driver 54 | 55 | 56 | 57 | .. _microbit-osx: 58 | 59 | OS X 60 | ~~~~ 61 | 62 | 63 | .. _microbit-linux: 64 | 65 | Linux 66 | ~~~~~ 67 | 68 | These steps will cover the basic flavors of Linux and working with the 69 | micro:bit and MicroPython. See also the specific sections for Raspberry Pi, 70 | Debian/Ubuntu, and Red Hat Fedora/Centos. 71 | 72 | 73 | .. _microbit-debian-ubuntu: 74 | 75 | Debian and Ubuntu 76 | ^^^^^^^^^^^^^^^^^ 77 | 78 | :: 79 | 80 | sudo add-apt-repository -y ppa:team-gcc-arm-embedded 81 | sudo add-apt-repository -y ppa:pmiller-opensource/ppa 82 | sudo apt-get update 83 | sudo apt-get install cmake ninja-build gcc-arm-none-eabi srecord libssl-dev 84 | pip3 install yotta 85 | 86 | 87 | .. _microbit-redhat: 88 | 89 | Red Hat Fedora/CentOS 90 | ^^^^^^^^^^^^^^^^^^^^^ 91 | 92 | 93 | .. _microbit-rpi: 94 | 95 | Raspberry Pi 96 | ^^^^^^^^^^^^ 97 | 98 | 99 | 100 | .. _next-steps: 101 | 102 | Next steps 103 | ---------- 104 | 105 | Congratulations. You have installed your development environment and are ready to 106 | begin :ref:`flashing firmware ` to the micro:bit. 107 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/image-smile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/image-smile.png -------------------------------------------------------------------------------- /micropython/docs/microbit.rst: -------------------------------------------------------------------------------- 1 | Microbit Module 2 | *************** 3 | 4 | .. py:module:: microbit 5 | 6 | 7 | The ``microbit`` module gives you access to all the hardware that is built-in 8 | into your board. 9 | 10 | 11 | Functions 12 | ========= 13 | 14 | .. py:function:: panic(n) 15 | 16 | Enter a panic mode. Requires restart. Pass in an arbitrary integer <= 255 17 | to indicate a status:: 18 | 19 | microbit.panic(255) 20 | 21 | 22 | .. py:function:: reset() 23 | 24 | Restart the board. 25 | 26 | 27 | .. py:function:: sleep(n) 28 | 29 | Wait for ``n`` milliseconds. One second is 1000 milliseconds, so:: 30 | 31 | microbit.sleep(1000) 32 | 33 | will pause the execution for one second. ``n`` can be an integer or 34 | a floating point number. 35 | 36 | 37 | .. py:function:: running_time() 38 | 39 | Return the number of milliseconds since the board was switched on or 40 | restarted. 41 | 42 | 43 | .. py:function:: temperature() 44 | 45 | Return the temperature of the micro:bit in degrees Celcius. 46 | 47 | 48 | Attributes 49 | ========== 50 | 51 | .. toctree:: 52 | :maxdepth: 1 53 | 54 | button.rst 55 | pin.rst 56 | 57 | 58 | Classes 59 | ======= 60 | 61 | .. toctree:: 62 | :maxdepth: 1 63 | 64 | image.rst 65 | 66 | 67 | Modules 68 | ======= 69 | 70 | .. toctree:: 71 | :maxdepth: 1 72 | 73 | display.rst 74 | uart.rst 75 | spi.rst 76 | i2c.rst 77 | accelerometer.rst 78 | compass.rst 79 | -------------------------------------------------------------------------------- /micropython/docs/music-pins.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/music-pins.png -------------------------------------------------------------------------------- /micropython/docs/neopixel-croc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/neopixel-croc.png -------------------------------------------------------------------------------- /micropython/docs/neopixel.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/neopixel.gif -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/pinout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/pinout.png -------------------------------------------------------------------------------- /micropython/docs/pwm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/pwm.png -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/scroll-hello.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/scroll-hello.gif -------------------------------------------------------------------------------- /micropython/docs/speech-pitch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/speech-pitch.png -------------------------------------------------------------------------------- /micropython/docs/speech.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/speech.png -------------------------------------------------------------------------------- /micropython/docs/tutorials/binary_count.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/binary_count.gif -------------------------------------------------------------------------------- /micropython/docs/tutorials/blue-microbit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/blue-microbit.png -------------------------------------------------------------------------------- /micropython/docs/tutorials/dalek.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/dalek.jpg -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/tutorials/files.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/files.jpg -------------------------------------------------------------------------------- /micropython/docs/tutorials/fireflies.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/fireflies.gif -------------------------------------------------------------------------------- /micropython/docs/tutorials/firefly.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/firefly.gif -------------------------------------------------------------------------------- /micropython/docs/tutorials/happy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/happy.png -------------------------------------------------------------------------------- /micropython/docs/tutorials/matrioshka.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/matrioshka.jpg -------------------------------------------------------------------------------- /micropython/docs/tutorials/mb-firefly.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/mb-firefly.gif -------------------------------------------------------------------------------- /micropython/docs/tutorials/network.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/network.png -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/docs/tutorials/piezo_buzzer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/piezo_buzzer.jpg -------------------------------------------------------------------------------- /micropython/docs/tutorials/pin0-gnd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/pin0-gnd.png -------------------------------------------------------------------------------- /micropython/docs/tutorials/queen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/docs/tutorials/queen.jpg -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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) -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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]) -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | # The radio won't work unless it's switched on. 11 | radio.on() 12 | 13 | # Event loop. 14 | while True: 15 | # Button A sends a "flash" message. 16 | if button_a.was_pressed(): 17 | radio.send('flash') # a-ha 18 | # Read any incoming messages. 19 | incoming = radio.receive() 20 | if incoming == 'flash': 21 | # If there's an incoming "flash" message display 22 | # the firefly flash animation after a random short 23 | # pause. 24 | sleep(random.randint(50, 350)) 25 | display.show(flash, delay=100, wait=False) 26 | # Randomly re-broadcast the flash message after a 27 | # slight delay. 28 | if random.randint(0, 9) == 0: 29 | sleep(500) 30 | radio.send('flash') # a-ha 31 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/examples/speech.py: -------------------------------------------------------------------------------- 1 | import speech 2 | from microbit import sleep 3 | 4 | # The say method attempts to convert English into phonemes. 5 | speech.say("I can sing!") 6 | sleep(1000) 7 | speech.say("Listen to me!") 8 | sleep(1000) 9 | 10 | # Clearing the throat requires the use of phonemes. Changing 11 | # the pitch and speed also helps create the right effect. 12 | speech.pronounce("AEAE/HAEMM", pitch=200, speed=100) # Ahem 13 | sleep(1000) 14 | 15 | # Singing requires a phoneme with an annotated pitch for each syllable. 16 | solfa = [ 17 | "#115DOWWWWWW", # Doh 18 | "#103REYYYYYY", # Re 19 | "#94MIYYYYYY", # Mi 20 | "#88FAOAOAOAOR", # Fa 21 | "#78SOHWWWWW", # Soh 22 | "#70LAOAOAOAOR", # La 23 | "#62TIYYYYYY", # Ti 24 | "#58DOWWWWWW", # Doh 25 | ] 26 | 27 | # Sing the scale ascending in pitch. 28 | song = ''.join(solfa) 29 | speech.sing(song, speed=100) 30 | # Reverse the list of syllables. 31 | solfa.reverse() 32 | song = ''.join(solfa) 33 | # Sing the scale descending in pitch. 34 | speech.sing(song, speed=100) 35 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/inc/lib/iters.h: -------------------------------------------------------------------------------- 1 | 2 | #include "py/runtime.h" 3 | 4 | mp_obj_t microbit_repeat_iterator(mp_obj_t iterable); 5 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | 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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/module.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "microbit-micropython", 3 | "version": "1.0.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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/source/lib/sam/sam.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/source/lib/sam/sam.c -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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. -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/tests/sample.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/virtualabs/radiobit/f1578e003a3435b8c9ff4a805a08a55448e877dd/micropython/tests/sample.raw -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /micropython/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 | -------------------------------------------------------------------------------- /tools/cheerson-cx10/README.md: -------------------------------------------------------------------------------- 1 | Cheerson CX-10 hijacking firmware 2 | ================================= 3 | 4 | You need to wire your BBC Micro:Bit to a real remote controller as described in the presentation. 5 | Make sure to unsolder the original SoC to get it working. 6 | 7 | Program your BBC Micro:Bit with this python code and enjoy :) 8 | 9 | Please note this hack may not work on some versions of Cheerson CX-10 (like the green one), but it is 10 | mostly due to the default center values of the joysticks used. 11 | 12 | If you manage to get it working with other CX-10 versions, feel free to make a PR ! 13 | -------------------------------------------------------------------------------- /tools/cheerson-cx10/cxp0wn.py: -------------------------------------------------------------------------------- 1 | from microbit import * 2 | import radio 3 | 4 | def readhex(n): 5 | c = uart.read(2) 6 | if c is not None and len(c) == 2: 7 | return bytes([int(c,16)]) 8 | return None 9 | 10 | uart.init(baudrate=115200) 11 | 12 | radio.on() 13 | radio.cx() 14 | radio.config(channel=2) 15 | 16 | found = False 17 | txid = None 18 | aid = None 19 | channel = 3 20 | timeout = 24 21 | last=running_time() 22 | while not found: 23 | now = running_time() 24 | if (now - last)>24: 25 | channel += 1 26 | if channel > 80: 27 | channel = 3 28 | last = now 29 | radio.config(channel=channel) 30 | pkt = radio.receive() 31 | if pkt is not None: 32 | if pkt[0]==0x55: 33 | # check if current channel matches txid 34 | txid = list(pkt[1:5]) 35 | channels = [ 36 | (txid[0]&0x0f)+0x3, 37 | (txid[0]>>4)+0x16, 38 | (txid[1]&0x0f)+0x2d, 39 | (txid[1]>>4)+0x40 40 | ] 41 | if channel in channels: 42 | found = True 43 | aid = list(pkt[5:9]) 44 | 45 | channels = [ 46 | (txid[0]&0x0f)+0x3, 47 | (txid[0]>>4)+0x16, 48 | (txid[1]&0x0f)+0x2d, 49 | (txid[1]>>4)+0x40 50 | ] 51 | 52 | asked = False 53 | last_asked = running_time() 54 | b = b'' 55 | p = b'' 56 | 57 | # reinit radio 58 | counter = 0 59 | radio.config(channel=channels[counter]) 60 | radio.cx() 61 | 62 | t = 0x3c9 63 | l = running_time() 64 | 65 | t,r,e,a = 0,0,0,0 66 | ctl = 0 67 | 68 | display.show(Image.HAPPY) 69 | 70 | # sync 71 | pkt = None 72 | while pkt is None: 73 | pkt = radio.receive() 74 | next_at = running_time()+6 75 | 76 | while True: 77 | now = running_time() 78 | if now >= next_at: 79 | next_at = next_at + 6 80 | counter = (counter + 1)%4 81 | radio.config(channel=channels[counter]) 82 | radio.send(p) 83 | ctl = 0 84 | 85 | if ctl == 0: 86 | t = pin0.read_analog() 87 | t = int(2031 * (t/1023)) + 0x386 88 | r = pin4.read_analog() 89 | r = int(3000 * (r/1034)) 90 | ctl += 1 91 | elif ctl == 1: 92 | e = pin10.read_analog() 93 | e = int(3000 * (e/1023)) 94 | a = pin1.read_analog() 95 | a = int(3000 * (a/1023)) 96 | p = bytes([0x55] + txid + aid + [a&0xff, a>>8, e&0xff, e>>8, t&0xff, t>>8, r&0xff, r>>8, 0x00, 0x00]) 97 | ctl = 2 98 | -------------------------------------------------------------------------------- /tools/ubit-sniffer/README.md: -------------------------------------------------------------------------------- 1 | Micro:Bit ESB/SB/BLE/raw sniffer 2 | ================================ 3 | 4 | This tool comes into two parts: 5 | 6 | * the first one is a middleware you need to put in your Micro:Bit along with the Radiobit firmware 7 | * the second is a classic Python2.x (shame on me) CLI you may use to sniff 8 | 9 | This tool supports different data rates: 10 | 11 | * 2 MBit/s 12 | * 1 MBit/s 13 | * 250 Kbit/s 14 | * Bluetooth Low Energy specific data_rate 15 | 16 | Be careful while sniffing Bluetooth Low Energy communications, the provided channel is understood as a BLE channel number ! 17 | 18 | How to flash your Micro:Bit with the right middleware 19 | ----------------------------------------------------- 20 | 21 | Simply use *uflash*: 22 | 23 | ``` 24 | $ uflash -r precompiled/radiobit.hex tools/ubit-sniffer/middleware/ubit-sniffer-mw.py 25 | ``` 26 | -------------------------------------------------------------------------------- /tools/wireless-keylogger/README.md: -------------------------------------------------------------------------------- 1 | Wireless Keylogger for MS Wireless 800 Keyboard 2 | =============================================== 3 | 4 | Simply program your Micro:Bit with this python program, and you're good to go. 5 | 6 | Your Micro:Bit will show a little animation while searching for a compatible keyboard, and a smiley when one found. 7 | Then it will log everything in its memory. 8 | 9 | To extract the logged keystrokes, connect your Micro:Bit to your computer with a USB cable, launch *minicom* and press any button on the Micro:Bit. The data will be sent and then flushed. Reset your Micro:Bit and you can give it another run ;) 10 | --------------------------------------------------------------------------------