├── .gitignore ├── arduino ├── __init__.py ├── template.tpl ├── examples │ ├── 00_basic.py │ ├── 01_arduino_blink.py │ └── 02_nano_esp32_advanced.py └── arduino.py ├── package.json ├── install.sh ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.mpy 3 | -------------------------------------------------------------------------------- /arduino/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = "Ubi de Feo" 2 | __credits__ = ["Ubi de Feo", "Sebastian Romero"] 3 | __license__ = "MPL 2.0" 4 | __version__ = "0.4.0" 5 | __maintainer__ = "Arduino" 6 | 7 | from .arduino import * -------------------------------------------------------------------------------- /arduino/template.tpl: -------------------------------------------------------------------------------- 1 | # Code generated by Arduino Runtime for MicroPython 2 | from arduino import * 3 | 4 | def setup(): 5 | # your initialization code goes here 6 | # this code only runs once at start 7 | print('setup') 8 | 9 | def loop(): 10 | # code that needs to run repeatedly goes here 11 | print('loop') 12 | delay(1000) 13 | 14 | def cleanup(): 15 | # code to cleanup or reset things when the program stops goes here 16 | print('cleanup') 17 | 18 | # start your program 19 | start(setup, loop, cleanup) -------------------------------------------------------------------------------- /arduino/examples/00_basic.py: -------------------------------------------------------------------------------- 1 | # Code generated by Arduino Runtime for MicroPython 2 | from arduino import * 3 | 4 | def setup(): 5 | # your initialization code goes here 6 | # this code only runs once at start 7 | print('setup') 8 | 9 | def loop(): 10 | # code that needs to run repeatedly goes here 11 | print('loop') 12 | delay(1000) 13 | 14 | def cleanup(): 15 | # code to cleanup or reset things when the program stops goes here 16 | print('cleanup') 17 | 18 | # start your program 19 | start(setup, loop, cleanup) -------------------------------------------------------------------------------- /arduino/examples/01_arduino_blink.py: -------------------------------------------------------------------------------- 1 | # Any Arduino board 2 | # 3 | # Blinking LED 4 | # 5 | # Author: Ubi de Feo 6 | # 7 | # This example shows how to blink the onboard LED of an Arduino board. 8 | # The LED will stay on for 500ms and off for 500ms, then the cycle repeats 9 | # creating a blinking effect. 10 | # 11 | 12 | from arduino import * 13 | 14 | led = 'LED_BUILTIN' 15 | def setup(): 16 | print('starting my program') 17 | 18 | def loop(): 19 | print('loopy loop') 20 | digital_write(led, HIGH) 21 | delay(500) 22 | digital_write(led, LOW) 23 | delay(500) 24 | 25 | start(setup, loop) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "urls": [ 3 | ["arduino/__init__.py", "github:arduino/arduino-runtime-mpy/arduino/__init__.py"], 4 | ["arduino/arduino.py", "github:arduino/arduino-runtime-mpy/arduino/arduino.py"], 5 | ["arduino/template.tpl", "github:arduino/arduino-runtime-mpy/arduino/template.tpl"], 6 | ["arduino/examples/00_basic.py", "github:arduino/arduino-runtime-mpy/arduino/examples/00_basic.py"], 7 | ["arduino/examples/01_arduino_blink.py", "github:arduino/arduino-runtime-mpy/arduino/examples/01_arduino_blink.py"], 8 | ["arduino/examples/02_nano_esp32_advanced.py", "github:arduino/arduino-runtime-mpy/arduino/examples/02_nano_esp32_advanced.py"] 9 | ], 10 | "deps": [], 11 | "version": "0.4.0" 12 | } -------------------------------------------------------------------------------- /arduino/examples/02_nano_esp32_advanced.py: -------------------------------------------------------------------------------- 1 | # Arduino Nano ESP32 2 | # 3 | # Timers and free running loop 4 | # 5 | # Author: Ubi de Feo 6 | # 7 | # This example shows how to use the Timer class to create blinking LEDs and 8 | # periodic messages. It also shows how to use the free running loop to read 9 | # the state of a button and control the onboard red LED accordingly. 10 | # 11 | # It demonstrates how to use the start() function to run the setup() and loop() 12 | # functions and the cleanup() function when the program is interrupted. 13 | # The cleanup() function has the responsibility to reset the timers and turn 14 | # off the LEDs. 15 | # 16 | # Connect a button between pin D6 and VCC 17 | # The button needs to have a pull-down resistor (10k Ohm) connected to GND 18 | # 19 | 20 | from arduino import * 21 | from machine import Timer 22 | 23 | led_builtin = 'LED_BUILTIN' 24 | led_builtin_state = False 25 | led_red = 'LED_RED' 26 | 27 | button = 'D6' 28 | 29 | blink_timer = Timer(0) 30 | message_timer = Timer(1) 31 | 32 | def blink_me(_timer): 33 | global led_builtin_state 34 | print('blink') 35 | led_builtin_state = not led_builtin_state 36 | if led_builtin_state: 37 | digital_write(led_builtin, HIGH) 38 | else: 39 | digital_write(led_builtin, LOW) 40 | 41 | def timed_message(_timer): 42 | print('hello') 43 | 44 | def setup(): 45 | print('my first program') 46 | blink_timer.init(period = 500, mode = Timer.PERIODIC, callback = blink_me) 47 | message_timer.init(period = 2000, mode = Timer.PERIODIC, callback = timed_message) 48 | 49 | def loop(): 50 | if digital_read(button): 51 | digital_write(led_red, LOW) 52 | else: 53 | digital_write(led_red, HIGH) 54 | 55 | def cleanup(): 56 | print("*** cleaning up ***") 57 | blink_timer.deinit() 58 | message_timer.deinit() 59 | digital_write(led_builtin, LOW) 60 | digital_write(led_red, HIGH) 61 | 62 | start(setup, loop, cleanup) 63 | -------------------------------------------------------------------------------- /arduino/arduino.py: -------------------------------------------------------------------------------- 1 | from machine import Pin, ADC, PWM 2 | from time import sleep_ms, ticks_us 3 | from random import randrange 4 | from math import sin, cos, radians, floor, ceil 5 | from sys import exit 6 | 7 | OUTPUT = Pin.OUT 8 | INPUT = Pin.IN 9 | 10 | # Blocking by default to allow threads to run 11 | # If you're not using threads, you can set this to True 12 | NON_BLOCKING = False 13 | 14 | HIGH = 1 # Voltage level HIGH 15 | LOW = 0 # Voltage level LOW 16 | 17 | # UTILITY 18 | def map_float(x, in_min, in_max, out_min, out_max) -> int | float: 19 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 20 | 21 | def map_int(x, in_min, in_max, out_min, out_max) -> int: 22 | return int(map_float(x, in_min, in_max, out_min, out_max)) 23 | 24 | def random(low, high=None) -> int: 25 | if high == None: 26 | return randrange(0, low) 27 | else: 28 | return randrange(low, high) 29 | 30 | def constrain(val, min_val, max_val) -> int | float: 31 | return min(max_val, max(min_val, val)) 32 | 33 | def lerp(start, stop, amount) -> int | float: 34 | return start + amount * (stop - start) 35 | 36 | # IO 37 | def pin_mode(_pin, _mode) -> Pin: 38 | return Pin(_pin, _mode) 39 | 40 | def pinMode(_pin, _mode) -> Pin: 41 | return pin_mode(_pin, _mode) 42 | 43 | def digital_write(_pin, _signal) -> None: 44 | p = Pin(_pin, Pin.OUT) 45 | p.value(_signal) 46 | 47 | def digitalWrite(_pin, _signal) -> None: 48 | return digital_write(_pin, _signal) 49 | 50 | def digital_read(_pin) -> int: 51 | p = Pin(_pin, Pin.IN) 52 | return p.value() 53 | 54 | def digitalRead(_pin) -> int: 55 | return digital_read(_pin) 56 | 57 | def analog_read(_pin) -> int: 58 | p = ADC(Pin(_pin)) 59 | return p.read_u16() 60 | 61 | def analogRead(_pin) -> int: 62 | return analog_read(_pin) 63 | 64 | def analog_write(_pin, _duty_cycle) -> None: 65 | p = PWM(Pin(_pin)) 66 | duty = map_int(_duty_cycle, 0, 255, 0, 65535) 67 | p.duty_u16(floor(duty)) 68 | 69 | if(_duty_cycle == 0): 70 | p.deinit() 71 | 72 | def analogWrite(_pin, _duty_cycle) -> None: 73 | return analog_write(_pin, _duty_cycle) 74 | 75 | def delay(_ms) -> None: 76 | sleep_ms(_ms) 77 | 78 | 79 | # HELPERS 80 | 81 | def get_template_path(): 82 | return '/'.join(__file__.split('/')[:-1]) + '/template.tpl' 83 | 84 | def create_sketch(sketch_name = None, destination_path = '.', overwrite = False, source_path = None): 85 | if sketch_name is None: 86 | sketch_name = 'main' 87 | new_sketch_path = f'{destination_path}/{sketch_name}.py' 88 | try: 89 | open(new_sketch_path, 'r') 90 | if not overwrite: 91 | sketch_name = f'{sketch_name}_{ticks_us()}' 92 | except OSError: 93 | pass 94 | 95 | template_path = get_template_path() if source_path is None else source_path 96 | template_sketch = open(template_path, 'r') 97 | new_sketch_path = f'{destination_path}/{sketch_name}.py' 98 | 99 | with open(new_sketch_path, 'w') as f: 100 | sketch_line = None 101 | while sketch_line is not '': 102 | sketch_line = template_sketch.readline() 103 | f.write(sketch_line) 104 | f.close() 105 | template_sketch.close() 106 | return new_sketch_path 107 | 108 | def copy_sketch(source_path = '', destination_path = '.', name = None, overwrite = False): 109 | name = name or 'main' 110 | return create_sketch(sketch_name = name, destination_path = destination_path, overwrite = overwrite, source_path = source_path) 111 | 112 | # RUNTIME 113 | def start(setup=None, loop=None, cleanup = None, preload = None): 114 | if preload is not None: 115 | preload() 116 | if setup is not None: 117 | setup() 118 | try: 119 | while True: 120 | if loop is not None: 121 | loop() 122 | if not NON_BLOCKING: 123 | sleep_ms(1) 124 | except (Exception, KeyboardInterrupt) as e: 125 | if cleanup is not None: 126 | cleanup() 127 | if not isinstance(e, KeyboardInterrupt): 128 | raise e 129 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # MicroPython Package Installer 4 | # Created by: Ubi de Feo and Sebastian Romero 5 | # 6 | # Installs a MicroPython Package to a board using mpremote. 7 | # 8 | # This script accepts an optional argument to compile .py files to .mpy. 9 | # Simply run the script with the optional argument: 10 | # 11 | # ./install.sh mpy 12 | 13 | # Name to display during installation 14 | PKGNAME="Arduino Runtime for MicroPython" 15 | # Destination directory for the package on the board inside the library directory 16 | PKGDIR="arduino" 17 | # Source directory for the package on the host 18 | SRCDIR=$PKGDIR 19 | # Board library directory 20 | LIBDIR="lib" 21 | 22 | # File system operations such as "mpremote mkdir" or "mpremote rm" 23 | # will generate an error if the folder exists or if the file does not exist. 24 | # These errors can be ignored. 25 | # 26 | # Traceback (most recent call last): 27 | # File "", line 2, in 28 | # OSError: [Errno 17] EEXIST 29 | 30 | # Check if a directory exists 31 | # Returns 0 if directory exists, 1 if it does not 32 | function directory_exists { 33 | # Run mpremote and capture the error message 34 | error=$(mpremote fs ls $1) 35 | 36 | # Return error if error message contains "OSError: [Errno 2] ENOENT" 37 | if [[ $error == *"OSError: [Errno 2] ENOENT"* ]]; then 38 | return 1 39 | else 40 | return 0 41 | fi 42 | } 43 | 44 | # Copies a file to the board using mpremote 45 | # Only produces output if an error occurs 46 | function copy_file { 47 | echo "Copying $1 to $2" 48 | # Run mpremote and capture the error message 49 | error=$(mpremote cp $1 $2) 50 | 51 | # Print error message if return code is not 0 52 | if [ $? -ne 0 ]; then 53 | echo "Error: $error" 54 | fi 55 | } 56 | 57 | # Deletes a file from the board using mpremote 58 | # Only produces output if an error occurs 59 | function delete_file { 60 | echo "Deleting $1" 61 | # Run mpremote and capture the error message 62 | error=$(mpremote rm $1) 63 | 64 | # Print error message if return code is not 0 65 | if [ $? -ne 0 ]; then 66 | echo "Error: $error" 67 | fi 68 | } 69 | 70 | echo "Installing $PKGNAME" 71 | 72 | # If directories do not exist, create them 73 | if ! directory_exists "/${LIBDIR}"; then 74 | echo "Creating $LIBDIR on board" 75 | mpremote mkdir "${LIBDIR}" 76 | fi 77 | 78 | if ! directory_exists "/${LIBDIR}/${PKGDIR}"; then 79 | echo "Creating $LIBDIR/$PKGDIR on board" 80 | mpremote mkdir "/${LIBDIR}/${PKGDIR}" 81 | fi 82 | 83 | 84 | ext="py" 85 | if [ "$1" = "mpy" ]; then 86 | ext=$1 87 | echo ".py files will be compiled to .mpy" 88 | fi 89 | 90 | existing_files=$(mpremote fs ls ":/${LIBDIR}/${PKGDIR}") 91 | 92 | for filename in $SRCDIR/*; do 93 | f_name=`basename $filename` 94 | source_extension="${f_name##*.}" 95 | destination_extension=$source_extension 96 | 97 | # If examples are distributed within the package 98 | # ensures they are copied but not compiled to .mpy 99 | if [[ -d $filename && "$f_name" == "examples" ]]; then 100 | if ! directory_exists "/${LIBDIR}/${PKGDIR}/examples"; then 101 | echo "Creating $LIBDIR/$PKGDIR/examples on board" 102 | mpremote mkdir "/${LIBDIR}/${PKGDIR}/examples" 103 | fi 104 | 105 | for example_file in $filename/*; do 106 | example_f_name=`basename $example_file` 107 | example_source_extension="${example_f_name##*.}" 108 | example_destination_extension=$example_source_extension 109 | 110 | if [[ $existing_files == *"${example_f_name%.*}.$example_source_extension"* ]]; then 111 | delete_file ":/${LIBDIR}/$PKGDIR/examples/${example_f_name%.*}.$example_source_extension" 112 | fi 113 | 114 | if [ "$example_source_extension" = "py" ] && [[ $existing_files == *"${example_f_name%.*}.mpy"* ]]; then 115 | delete_file ":/${LIBDIR}/$PKGDIR/examples/${example_f_name%.*}.mpy" 116 | fi 117 | 118 | copy_file $filename/${example_f_name%.*}.$example_destination_extension ":/${LIBDIR}/$PKGDIR/examples/${example_f_name%.*}.$example_destination_extension" 119 | done 120 | continue 121 | fi 122 | 123 | if [[ "$ext" == "mpy" && "$source_extension" == "py" ]]; then 124 | echo "Compiling $SRCDIR/$f_name to $SRCDIR/${f_name%.*}.$ext" 125 | mpy-cross "$SRCDIR/$f_name" 126 | destination_extension=$ext 127 | fi 128 | 129 | # Make sure previous versions of the given file are deleted. 130 | if [[ $existing_files == *"${f_name%.*}.$source_extension"* ]]; then 131 | delete_file ":/${LIBDIR}/$PKGDIR/${f_name%.*}.$source_extension" 132 | fi 133 | 134 | # Check if source file has a .py extension and if a .mpy file exists on the board 135 | if [ "$source_extension" = "py" ] && [[ $existing_files == *"${f_name%.*}.mpy"* ]]; then 136 | delete_file ":/${LIBDIR}/$PKGDIR/${f_name%.*}.mpy" 137 | fi 138 | 139 | # Copy either the .py or .mpy file to the board depending on the chosen option 140 | copy_file $SRCDIR/${f_name%.*}.$destination_extension ":/${LIBDIR}/$PKGDIR/${f_name%.*}.$destination_extension" 141 | done 142 | 143 | if [ "$ext" == "mpy" ]; then 144 | echo "cleaning up mpy files" 145 | rm $SRCDIR/*.mpy 146 | fi 147 | 148 | echo "Done. Resetting target board ..." 149 | mpremote reset -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arduino Runtime for MicroPython 2 | 3 | A module to simplify and help writing MicroPython programs using the `setup()`/`loop()` paradigm. 4 | 5 | This module also wraps machine functions in easy-to-use methods. 6 | 7 | ## Installation 8 | 9 | ### mip (MicroPython Package Manager) 10 | 11 | This is the recommended method for boards which can connect to Internet. 12 | Run the following MicroPython script using your favourite editor: 13 | 14 | ```py 15 | import network 16 | import mip 17 | import time 18 | 19 | SSID = 'YOUR WIFI NETWORK NAME (must be 2.4GHz)' 20 | PWD = 'YOUR WIFI PASSWORD' 21 | 22 | interface = network.WLAN(network.STA_IF) 23 | interface.active(False) 24 | time.sleep(0.1) 25 | interface.active(True) 26 | 27 | def connect(ssid, pwd): 28 | interface.connect(ssid, pwd) 29 | # Network Connection Progress 30 | max_dot_cols = 20 31 | dot_col = 0 32 | print() 33 | print(f"Connecting to {ssid}") 34 | while not interface.isconnected(): 35 | if(dot_col % max_dot_cols == 0): 36 | print() 37 | print('.', end = '') 38 | dot_col +=1 39 | time.sleep_ms(100) 40 | print() 41 | print(f'{"C" if interface.isconnected() else "NOT c"}onnected to network') 42 | 43 | connect(SSID, PWD) 44 | mip.install('github:arduino/arduino-runtime-mpy') 45 | 46 | ``` 47 | 48 | ### mpremote mip 49 | 50 | You will need to have Python and `mpremote` installed on your system, [follow these instructions](https://docs.micropython.org/en/latest/reference/mpremote.html) to do so. 51 | 52 | Open a shell and run the following command: 53 | 54 | ```shell 55 | mpremote mip install "github:arduino/arduino-runtime-mpy" 56 | ``` 57 | 58 | ### Manual Installation 59 | 60 | Copy the folder `arduino` and its content into your board's `lib` folder using your preferred method. 61 | 62 | ## Usage 63 | 64 | The structure of a MicroPython program based on the Arduino Runtime for MicroPython will look as follows: 65 | 66 | ```py 67 | from arduino import * 68 | 69 | def setup(): 70 | print('starting my program') 71 | 72 | def loop(): 73 | print('loop') 74 | delay(1000) 75 | 76 | start(setup, loop) 77 | ``` 78 | 79 | The program above will define two main methods: `setup()` and `loop()`. 80 | `setup()` will be invoked once at the execution of the program, while `loop()` will be invoked over and over until the program is stopped. 81 | The stop condition might be caused by a system error or by manual trigger from the user during development/testing. 82 | The `start()` command is what causes these functions to be run as described above. 83 | 84 | Traditionally the example code above would be written as follows in MicroPython: 85 | 86 | ```py 87 | from time import sleep_ms 88 | 89 | print('starting my program') 90 | 91 | while True: 92 | print('loop') 93 | sleep_ms(1000) 94 | ``` 95 | 96 | Using the Arduino Runtime for MicroPython introduces some nice features, like the possibility to wrap user code in functions which can be tested during learning/development using the [REPL](https://docs.micropython.org/en/latest/reference/repl.html). 97 | 98 | To debug your application interactively you can use an approach in which you define `setup()` and `loop()` but omit the `start()` command. That way you can change variables or set the property of an object through the REPL and simply call `loop()` to see the results of their changes without "restarting" the complete script. 99 | 100 | We also introduced a new way of cleaning up and or resetting variables, objects, timers, leveraging a `cleanup()` method which will be called when the program is stopped or a system error occurs which stops the execution of the program. 101 | Please refer to the example ["nano_esp32_advanced.py"](./examples/02_nano_esp32_advanced.py). 102 | 103 | The runtime commands used in the example are explained in more detail below. 104 | 105 | ### setup() 106 | 107 | Is run **once** and should contain initialisation code. 108 | 109 | ### loop() 110 | 111 | Is run indefinitely until the program stops. 112 | 113 | ### cleanup() 114 | 115 | Is run **once** when the program stops. This happen either when the user manually stops the execution of the program or if an error in the user code is thrown. 116 | It should contain code such as resetting the value of variables, resetting peripherals, stopping timers, causing threads to stop running. 117 | 118 | A version of our initial program that leverages the `cleanup()` function would look like this: 119 | 120 | ```py 121 | from arduino import * 122 | 123 | def setup(): 124 | print('starting my program') 125 | 126 | def loop(): 127 | print('loop') 128 | delay(1000) 129 | 130 | def cleanup(): 131 | print('cleanup') 132 | 133 | start(setup, loop, cleanup) 134 | ``` 135 | 136 | > [!NOTE] 137 | > `cleanup()` is not invoked when the program stops because the hardware reset button on the board was pressed. 138 | 139 | ## Commands 140 | 141 | Here's a list of commands and wrappers that can be used in your Arduino MicroPython program. 142 | 143 | ### pin_mode(PIN_NUMBER/ID, MODE) 144 | 145 | This method is only provided as a mean to transition from Arduino C++ to MicroPython. In MicroPython a Pin object can be used directly instead. 146 | The following methods apply the required Pin direction on the fly. 147 | 148 | ```py 149 | pin_mode(3, INPUT) 150 | pin_mode('D7', INPUT) 151 | ``` 152 | 153 | Will set the direction of the specified Pin and allow writing to or reading from the physical pin. 154 | 155 | ### digital_read(PIN_NUMBER/ID) 156 | 157 | Reads a digital value from the pin with the specified number or ID. 158 | For example: 159 | 160 | ```py 161 | digital_read(12) 162 | digital_read('D7') 163 | digital_read('A3') 164 | ``` 165 | 166 | returns a value of `1` or `0` depending on the signal attached to the specified pins, for instance a button or a digital sensor. 167 | 168 | ### digital_write(PIN_NUMBER/ID, VALUE) 169 | 170 | Writes the digital value (`HIGH|LOW|True|False|1|0`) to the pin with Number or ID specified. 171 | For example: 172 | 173 | ```py 174 | digital_write(12, HIGH) 175 | digital_write('D7', 1) 176 | digital_write('A3', 0) 177 | ``` 178 | 179 | Sets the pin to the specified value. 180 | 181 | ### analog_read(PIN_NUMBER/ID) 182 | 183 | Reads the analog value for the Voltage applied to the pin with the specified number or ID. 184 | For example: 185 | 186 | ```py 187 | analog_read('A3') 188 | analog_read('D18') 189 | analog_read('2') 190 | ``` 191 | 192 | returns a value between `0` and the maximum resolution of the processor's ADC based on the Voltage applied to the specified Pin. 193 | Could be used to read the Voltage of a battery or any other analog source such as a potentiometer, light or moisture sensor to name a few. 194 | 195 | ### analog_write(PIN_NUMBER/ID, VALUE) 196 | 197 | Writes an analog value (PWM) to the pin with Number or ID specified, if the Pin supports it. 198 | VALUE should be between 0 and the maximum allowed PWM value 255. 199 | 200 | ```py 201 | analog_write(12, 255) 202 | analog_write('D7', 128) 203 | analog_write('A3', 64) 204 | ``` 205 | 206 | Will generate a pulse width modulated signal on the specified Pin. 207 | Can be used to control small motors with low current needs, servo motors or an LED's brightness. 208 | 209 | > [!IMPORTANT] 210 | > The numeric value for PIN_NUMBER is usually the processor's GPIO number, while values enclosed in quotes are "named pins" and are platform/implementation specific. A `ValueError` exception with label "invalid pin" is thrown if the pin number or ID is not valid. 211 | 212 | ### delay(MILLISECONDS) 213 | 214 | Will halt the execution of your program for the amount of **milliseconds** specified in the parameter. 215 | It is to be considered a code-blocking command. 216 | 217 | ```py 218 | delay(1000) # Delay the execution for 1 second 219 | ``` 220 | 221 | ## Utilities 222 | 223 | Some utility methods are provided and are still in development: 224 | 225 | * `map_float(x, in_min, in_max, out_min, out_max)` 226 | Remaps the value `x` from its input range to an output range as a float 227 | * `map_int(x, in_min, in_max, out_min, out_max)` 228 | same as `map_float` but always returns an integer 229 | * `random(low, high=None)` 230 | Returns a random number between `0` and `low` - 1 if no `high` is provided, otherwise a value between `low` and `high` - 1 231 | * `constrain(val, min_val, max_val)` 232 | Returns a capped value of the number `val` between `min_val` and `max_val` 233 | * `lerp(start, stop, amount)` 234 | Returns a linear interpolation (percentage) of `amount` between `start` and `stop` 235 | 236 | ## Convenience and scaffolding methods 237 | 238 | ### create_sketch(sketch_name = None, destination_path = '.', overwrite = False, source = None) 239 | 240 | Creates a new Python file (`.py`) with the specified name at the provided path. 241 | By default if a file with the same name is found, it will append a timestamp to the filename, but overwrite can be forced by setting that parameter to True. 242 | Providing a source path it will use that file's content, effectively copying the code from the source file to the newly created one. 243 | 244 | Examples: 245 | 246 | ```py 247 | create_sketch('my_arduino_sketch') 248 | create_sketch('my_arduino_sketch', 'tmp') 249 | create_sketch('main') 250 | ``` 251 | 252 | The method returns the Python file's full path. 253 | 254 | ### copy_sketch(source_path = '', destination_path = '.', name = None, overwrite = False) 255 | 256 | Wraps `create_sketch()` and provides a shortcut to copy a file to another path. 257 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------