MicroPython 介绍(二)
MicroPython
以Python
为基础,可以运行在嵌入式环境。提供交互式的prompt
(REPL
),我们可以使用REPL
做一些Python
编程操作,REPL
支持历史命令,自动缩进,黏贴模式等,极大提高用户体验。
MicroPython
也致力于能够和正常的Python
(CPython
)兼容,这样就可以做到,学会 MicroPython
和CPython
其中任何一个,另一个也就会用了。
MicroPython
包含了CPython
的一些核心包,例如os
等,还有一些自己独有的包,例如用于驱动硬件的machine
等。
例子(摘自官网)
点亮LED
import pyb
# turn on an LED
pyb.LED(1).on()
# print some text to the serial console
print('Hello MicroPython!')
引脚电平切换
from machine import Pin
# create an I/O pin in output mode
p = Pin('X1', Pin.OUT)
# toggle the pin
p.high()
p.low()
IIC
from machine import Pin, I2C
# creat an I2C bus
i2c = I2C(scl=Pin('X1'), sda=Pin('X2'))
# scan for list of attached devices
dev_list = i2c.scan()
# write to and read from a device
i2c.writeto(0x42, b'4')
data = i2c.readfrom(0x42, 4)
# memory transactions
i2c.writeto_mem(0x42, 0x12, b'')
data = i2c.readfrom_mem(0x42, 0x12, 2)
数值类型
# full range of numeric types
# small integer (fits in a machine word)
>>> 123
123
# big integer
>>> 1 << 160
1461501637330902918203684832716283019655932542976
# floating point
>>> 1.23e6
1230000.0
# complex numbers
>>> (1 + 2j) * 4j
(-8+4j)
内嵌汇编
# MicroPython has an inline assembler
import micropython
# define a Thumb-code inline-assembler function
@micropython.asm_thumb
def asm_add(r0, r1):
add(r0, r0, r1)
# use it as a normal Python function
total = asm_add(1, 2)
OS操作
import os
# list root directory
print(os.listdir('/'))
# print current directory
print(os.getcwd())
# open and read a file from the SD card
with open('/sd/readme.txt') as f:
print(f.read())
主板配置(频率)
import machine
# set CPU frequency to 84MHz
machine.freq(84000000)