# micropython dev tools for linux

```python
import ys_pyboard

pyb = ys_pyboard.Pyboard('/dev/ttyACM0')
pyb.enter_raw_repl()

print("start:")
result = pyb.exec('print(1+1)')
print("get result:")
print(result)

#print(pyb.list_files_and_folders("."))
#pyb.upload_file("hi.py", "/main.py")
#pyb.upload_file("hi.py", "/test/hi.py")
#pyb.delete_file_or_folder("/test")

pyb.exit_raw_repl()
```

> If you want to handle files in sd card, use `open()` to read or write.

## thinking

So far, the chinese version pyboard 1.1 plus is the best. It has 60+ free pin for using, and it has built-in SD card loader. And when you connect your chip to computer, it will show you a storage where you can directly change the main.py in your flash storage or SD card storage to do the programming.

And pyboard has "DAC(digital_to_anolog_converter)", which can ouput a voltage in range (0v,3v) to a pin. so you can treat voltage as a byte(0 to 255) directly, so it speed up 8 times when doing communication. pico do not have DAC, which is bad.

## critical bugs

even comments in code will increase memory, and you can not use garbage.collect() to reduce the memory usage. after you import a module, you can not use del module to reduce memory usage.

it is like when you open a software, it takes more than 10mb plus memory, but when you close that software or application, the memory usage will not go down. so if you open and close some apps multiple times, the device simply go to died because memory is full.

> maybe you can try 'from machine import soft_reset; soft_reset();', but what is the point? reboot can solve all memory bugs?

```
2026: 我突然发现所有的micropython固件系统，都有一个bug，它连注释都算做内存占用，都要新增内存占用，并且用garbage.collect()都消除不了这种内存占用。代码注入执行越多，越容易内存耗尽而死机。

它是连代码本身也会增加内存消耗。"import xxx; del xxx;"并不会清除内存占用。

这个bug截止2026年，有7、8年了，都没有人发现。

> 据说是因为里面有个特别傻逼的qstr符号表，会把所有遇到的代码文本都永久性存储下来，删都删不掉，直接把内存撑爆，除非machine.soft_reset()。

> 这个bug最明显的功效是，假设你搞了个命令行终端程序，动态执行不同的py小程序，慢慢的设备就内存爆炸死机了。或者用户不停的打开并关闭很多界面app，每次打开一个应用程序，内存增加几十MB，关掉后内存也清除不了，然后手机就死机了。

> 比较明显的一个例子是这两行代码，运行一次内存少一点，特别是你在前面增加一个超长注释: from gc import mem_free, collect; print("Has memory of", mem_free()/1024, "KB.");
```

## fix /dev/ACM0 permission on linux

sudo usermod -a <username> -G dialout
sudo reboot

## power related
if you use the default frequency, it would waste a lot of power. and it would be hot.

so lower the frequency is a good start:

```
from machine import freq
freq(42000000) # low frequency saves more power, can be 21mhz. lower frequency when no input is a good method for offline project.
```

## docs for micropython1.16 (I think it is work for 1.15)
Timers
```
#RP2040's system timer peripheral provides a global microsecond timebase and generates interrupts for it. The software timer is available currently, and there are unlimited number of them (memory permitting). There is no need to specify the timer id (id=-1 is supported at the moment) as it will default to this.

from machine import Timer

a_timer = Timer(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
a_timer = Timer(period=1000, mode=Timer.PERIODIC, callback=lambda t:print(2))

import time
print(time.ticks_ms()) # get millisecond that passed since boot
```

Pins and interrupt
```
from machine import Pin

# create an output pin on pin #0
p0 = Pin(0, Pin.OUT)

# set the value low then high
p0.value(0)
p0.value(1)

# create an input pin on pin #2, with a pull up resistor
p2 = Pin(2, Pin.IN, Pin.PULL_UP)

# read and print the pin value
print(p2.value())

# reconfigure pin #0 in input mode with a pull down resistor
p0.init(p0.IN, p0.PULL_DOWN)

# configure an irq callback
p0.irq(lambda p:print(p))

#p0.irq(trigger=Pin.IRQ_FALLING, handler=irq_callback) #IRQ_RISING

#p0.irq(handler=None) #remove it
```

Thread
```
# this is a fake thread, if main process has no "sleep", this process will not go on. in another word, each time should only has one process is doing things.

import _thread
import time
from machine import Pin

# 1. Define the function to run in the new thread (blink LED on pin 2)
def thread_task():
    led = Pin(2, Pin.OUT)
    while True:
        led.toggle()
        time.sleep(0.5)

# 2. Start the new thread (required args tuple: () for no arguments)
_thread.start_new_thread(thread_task, ())

# 3. Main thread: keep running (prevents program exit)
while True:
    print("Main thread running...")
    time.sleep(1)

# pi pico thread has bugs, when you run loop in thread while using UART, bug will happen, it will break or not working properly. 
```

General board control
```
#The MicroPython REPL is on the USB serial port.
#Tab-completion is useful to find out what methods an object has Paste mode (ctrl-E) is useful to paste a large slab of Python code into the REPL.

import machine

machine.freq()          # get the current frequency of the CPU
machine.freq(240000000) # set the CPU frequency to 240 MHz
```

Delay and timing
```
import time

time.sleep(1)           # sleep for 1 second
time.sleep_ms(500)      # sleep for 500 milliseconds
time.sleep_us(10)       # sleep for 10 microseconds

start = time.ticks_ms() # get millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
```

Pins and GPIO
```
from machine import Pin

p0 = Pin(0, Pin.OUT)    # create output pin on GPIO0
p0.on()                 # set pin to "on" (high) level
p0.off()                # set pin to "off" (low) level
p0.value(1)             # set pin to on/high

p2 = Pin(2, Pin.IN)     # create input pin on GPIO2
print(p2.value())       # get value, 0 or 1

p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation
```

UART (serial bus)
```
from machine import UART, Pin

uart1 = UART(1, baudrate=9600, tx=Pin(33), rx=Pin(32))
uart1.write('hello')  # write 5 bytes
uart1.read(5)         # read up to 5 bytes

# complex
from machine import UART, Pin
uart1 = UART(0, baudrate=115200, tx=Pin(12), rx=Pin(13))
uart1.write(bytes([0x57, 0xAB, 0x12, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x80, 0x00, 0x20]))
while True:
    data = uart1.read()
    if data != None:
        print(data)
```

PWM (pulse width modulation)
```
from machine import Pin, PWM

pwm0 = PWM(Pin(0))      # create PWM object from a pin
pwm0.freq()             # get current frequency
pwm0.freq(1000)         # set frequency
pwm0.duty_u16()         # get current duty cycle, range 0-65535
pwm0.duty_u16(200)      # set duty cycle, range 0-65535
pwm0.deinit()           # turn off PWM on the pin
```

ADC (analog to digital conversion)
```
from machine import ADC, Pin

adc = ADC(Pin(32))          # create ADC object on ADC pin
adc.read_u16()              # read value, 0-65535 across voltage range 0.0v - 3.3v
```

Software SPI bus
```
from machine import Pin, SoftSPI

# construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))

spi.init(baudrate=200000) # set the baudrate

spi.read(10)            # read 10 bytes on MISO
spi.read(10, 0xff)      # read 10 bytes while outputting 0xff on MOSI

buf = bytearray(50)     # create a buffer
spi.readinto(buf)       # read into the given buffer (reads 50 bytes in this case)
spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI

spi.write(b'12345')     # write 5 bytes on MOSI

buf = bytearray(4)      # create a buffer
spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf
```

Hardware SPI bus
```
from machine import Pin, SPI

spi = SPI(1, 10000000)
spi = SPI(1, 10000000, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
spi = SPI(2, baudrate=80000000, polarity=0, phase=0, bits=8, firstbit=0, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
```

Software I2C bus
```
from machine import Pin, SoftI2C

i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100000)

i2c.scan()              # scan for devices

i2c.readfrom(0x3a, 4)   # read 4 bytes from device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a

buf = bytearray(10)     # create a buffer with 10 bytes
i2c.writeto(0x3a, buf)  # write the given buffer to the slave
```

Hardware I2C bus
```
from machine import Pin, I2C

i2c = I2C(0)
i2c = I2C(1, scl=Pin(5), sda=Pin(4), freq=400000)
```

Real time clock (RTC)
```
from machine import RTC

rtc = RTC()
rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time
rtc.datetime() # get date and time
```

WDT (Watchdog timer)
```
from machine import WDT

# enable the WDT with a timeout of 5s (1s is the minimum)
wdt = WDT(timeout=5000)
wdt.feed()
```

Deep-sleep mode
```
import machine

# check if the device woke from a deep sleep
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
    print('woke from a deep sleep')

# put the device to sleep for 10 seconds
machine.deepsleep(10000)
```

OneWire driver
```
from machine import Pin
import onewire

ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12
ow.scan()               # return a list of devices on the bus
ow.reset()              # reset the bus
ow.readbyte()           # read a byte
ow.writebyte(0x12)      # write a byte on the bus
ow.write('123')         # write bytes on the bus
ow.select_rom(b'12345678') # select a specific device by its ROM code

# There is a specific driver for DS18S20 and DS18B20 devices
import time, ds18x20
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
    print(ds.read_temp(rom))
#Be sure to put a 4.7k pull-up resistor on the data line.  Note that the ``convert_temp()`` method must be called each time you want to sample the temperature.
```

NeoPixel and APA106 driver
```
from machine import Pin
from neopixel import NeoPixel

pin = Pin(0, Pin.OUT)   # set GPIO0 to output to drive NeoPixels
np = NeoPixel(pin, 8)   # create NeoPixel driver on GPIO0 for 8 pixels
np[0] = (255, 255, 255) # set the first pixel to white
np.write()              # write data to all pixels
r, g, b = np[0]         # get first pixel colour

#The APA106 driver extends NeoPixel, but internally uses a different colour order::
from apa106 import APA106
ap = APA106(pin, 8)
r, g, b = ap[0]
#APA102 (DotStar) uses a different driver as it has an additional clock pin.
```

## docs for micropython1.23

General board control
```
#The MicroPython REPL is on the USB serial port. Tab-completion is useful to find out what methods an object has. Paste mode (ctrl-E) is useful to paste a large slab of Python code into the REPL.

import machine

machine.freq()          # get the current frequency of the CPU
machine.freq(240000000) # set the CPU frequency to 240 MHz
```

Delay and timing
```
import time

time.sleep(1)           # sleep for 1 second
time.sleep_ms(500)      # sleep for 500 milliseconds
time.sleep_us(10)       # sleep for 10 microseconds
start = time.ticks_ms() # get millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
```

Timers
```
#RP2040’s system timer peripheral provides a global microsecond timebase and generates interrupts for it. The software timer is available currently, and there are unlimited number of them (memory permitting). There is no need to specify the timer id (id=-1 is supported at the moment) as it will default to this.

from machine import Timer

tim = Timer(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(1))
tim.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(2))
```

Pins and GPIO
```
from machine import Pin

p0 = Pin(0, Pin.OUT)    # create output pin on GPIO0
p0.on()                 # set pin to "on" (high) level
p0.off()                # set pin to "off" (low) level
p0.value(1)             # set pin to on/high

p2 = Pin(2, Pin.IN)     # create input pin on GPIO2
print(p2.value())       # get value, 0 or 1

p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation
```

Programmable IO (PIO)
```
#Example using PIO to blink an LED at 1Hz:

from machine import Pin
import rp2

@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def blink_1hz():
    # Cycles: 1 + 7 + 32 * (30 + 1) = 1000
    set(pins, 1)
    set(x, 31)                  [6]
    label("delay_high")
    nop()                       [29]
    jmp(x_dec, "delay_high")

    # Cycles: 1 + 7 + 32 * (30 + 1) = 1000
    set(pins, 0)
    set(x, 31)                  [6]
    label("delay_low")
    nop()                       [29]
    jmp(x_dec, "delay_low")

# Create and start a StateMachine with blink_1hz, outputting on Pin(25)
sm = rp2.StateMachine(0, blink_1hz, freq=2000, set_base=Pin(25))
sm.active(1)
```

UART (serial bus)
```
#There are two UARTs, UART0 and UART1. UART0 can be mapped to GPIO 0/1, 12/13 and 16/17, and UART1 to GPIO 4/5 and 8/9.

from machine import UART, Pin
uart1 = UART(1, baudrate=9600, tx=Pin(4), rx=Pin(5))
uart1.write('hello')  # write 5 bytes
uart1.read(5)         # read up to 5 bytes

#REPL over UART is disabled by default.
```

PWM (pulse width modulation)
```
#There are 8 independent PWM generators called slices, which each have two channels making it 16 PWM channels in total which can be clocked from 8Hz to 62.5Mhz at a machine.freq() of 125Mhz. The two channels of a slice run at the same frequency, but can have a different duty rate. The two channels are usually assigned to adjacent GPIO pin pairs with even/odd numbers. So GPIO0 and GPIO1 are at slice 0, GPIO2 and GPIO3 are at slice 1, and so on. A certain channel can be assigned to different GPIO pins (see Pinout). For instance slice 0, channel A can be assigned to both GPIO0 and GPIO16.

from machine import Pin, PWM

# create PWM object from a pin and set the frequency of slice 0
# and duty cycle for channel A
pwm0 = PWM(Pin(0), freq=2000, duty_u16=32768)
pwm0.freq()             # get the current frequency of slice 0
pwm0.freq(1000)         # set/change the frequency of slice 0
pwm0.duty_u16()         # get the current duty cycle of channel A, range 0-65535
pwm0.duty_u16(200)      # set the duty cycle of channel A, range 0-65535
pwm0.duty_u16(0)        # stop the output at channel A
print(pwm0)             # show the properties of the PWM object.
pwm0.deinit()           # turn off PWM of slice 0, stopping channels A and B
```

ADC (analog to digital conversion)
```
#RP2040 has five ADC channels in total, four of which are 12-bit SAR based ADCs: GP26, GP27, GP28 and GP29. The input signal for ADC0, ADC1, ADC2 and ADC3 can be connected with GP26, GP27, GP28, GP29 respectively (On Pico board, GP29 is connected to VSYS). The standard ADC range is 0-3.3V. The fifth channel is connected to the in-built temperature sensor and can be used for measuring the temperature.

from machine import ADC, Pin
adc = ADC(Pin(26))     # create ADC object on ADC pin
adc.read_u16()         # read value, 0-65535 across voltage range 0.0v - 3.3v
```

Software SPI bus
```
#Software SPI (using bit-banging) works on all pins, and is accessed via the machine.SoftSPI class:

from machine import Pin, SoftSPI

# construct a SoftSPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SoftSPI(baudrate=100_000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))

spi.init(baudrate=200000) # set the baudrate

spi.read(10)            # read 10 bytes on MISO
spi.read(10, 0xff)      # read 10 bytes while outputting 0xff on MOSI

buf = bytearray(50)     # create a buffer
spi.readinto(buf)       # read into the given buffer (reads 50 bytes in this case)
spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI

spi.write(b'12345')     # write 5 bytes on MOSI

buf = bytearray(4)      # create a buffer
spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf
```

Hardware SPI bus
```
#The RP2040 has 2 hardware SPI buses which is accessed via the machine.SPI class and has the same methods as software SPI above:

from machine import Pin, SPI

spi = SPI(1, 10_000_000)  # Default assignment: sck=Pin(10), mosi=Pin(11), miso=Pin(8)
spi = SPI(1, 10_000_000, sck=Pin(14), mosi=Pin(15), miso=Pin(12))
spi = SPI(0, baudrate=80_000_000, polarity=0, phase=0, bits=8, sck=Pin(6), mosi=Pin(7), miso=Pin(4))
```

Software I2C bus
```
#Software I2C (using bit-banging) works on all output-capable pins, and is accessed via the machine.SoftI2C class:

from machine import Pin, SoftI2C

i2c = SoftI2C(scl=Pin(5), sda=Pin(4), freq=100_000)

i2c.scan()              # scan for devices

i2c.readfrom(0x3a, 4)   # read 4 bytes from device with address 0x3a
i2c.writeto(0x3a, '12') # write '12' to device with address 0x3a

buf = bytearray(10)     # create a buffer with 10 bytes
i2c.writeto(0x3a, buf)  # write the given buffer to the peripheral
```

Hardware I2C bus
```
#The driver is accessed via the machine.I2C class and has the same methods as software I2C above:

from machine import Pin, I2C

i2c = I2C(0)   # default assignment: scl=Pin(9), sda=Pin(8)
i2c = I2C(1, scl=Pin(3), sda=Pin(2), freq=400_000)
```

I2S bus
```
from machine import I2S, Pin

i2s = I2S(0, sck=Pin(16), ws=Pin(17), sd=Pin(18), mode=I2S.TX, bits=16, format=I2S.STEREO, rate=44100, ibuf=40000) # create I2S object
i2s.write(buf)             # write buffer of audio samples to I2S device

i2s = I2S(1, sck=Pin(0), ws=Pin(1), sd=Pin(2), mode=I2S.RX, bits=16, format=I2S.MONO, rate=22050, ibuf=40000) # create I2S object
i2s.readinto(buf)          # fill buffer with audio samples from I2S device

#The ws pin number must be one greater than the sck pin number.

#The I2S class is currently available as a Technical Preview. During the preview period, feedback from users is encouraged. Based on this feedback, the I2S class API and implementation may be changed.

#Two I2S buses are supported with id=0 and id=1.
```

Real time clock (RTC)
```
from machine import RTC

rtc = RTC()
rtc.datetime((2017, 8, 23, 2, 12, 48, 0, 0)) # set a specific date and
                                             # time, eg. 2017/8/23 1:12:48
rtc.datetime() # get date and time
```

WDT (Watchdog timer)
```
#The RP2040 has a watchdog which is a countdown timer that can restart parts of the chip if it reaches zero.

from machine import WDT

# enable the WDT with a timeout of 5s (1s is the minimum)
wdt = WDT(timeout=5000)
wdt.feed()

#The maximum value for timeout is 8388 ms.
```

OneWire driver
```
#The OneWire driver is implemented in software and works on all pins:

from machine import Pin
import onewire

ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12
ow.scan()               # return a list of devices on the bus
ow.reset()              # reset the bus
ow.readbyte()           # read a byte
ow.writebyte(0x12)      # write a byte on the bus
ow.write('123')         # write bytes on the bus
ow.select_rom(b'12345678') # select a specific device by its ROM code

#There is a specific driver for DS18S20 and DS18B20 devices:
import time, ds18x20
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
ds.convert_temp()
time.sleep_ms(750)
for rom in roms:
    print(ds.read_temp(rom))
#Be sure to put a 4.7k pull-up resistor on the data line. Note that the convert_temp() method must be called each time you want to sample the temperature.
```

NeoPixel and APA106 driver
```
from machine import Pin
from neopixel import NeoPixel

pin = Pin(0, Pin.OUT)   # set GPIO0 to output to drive NeoPixels
np = NeoPixel(pin, 8)   # create NeoPixel driver on GPIO0 for 8 pixels
np[0] = (255, 255, 255) # set the first pixel to white
np.write()              # write data to all pixels
r, g, b = np[0]         # get first pixel colour

#The APA106 driver extends NeoPixel, but internally uses a different colour order:
from apa106 import APA106
ap = APA106(pin, 8)
r, g, b = ap[0]
#APA102 (DotStar) uses a different driver as it has an additional clock pin.
```

