1. 通用的板卡控制
import pyb
pyb.repl_uart(pyb.UART(1, 9600)) # duplicate REPL on UART(1)
pyb.wfi() # pause CPU, waiting for interrupt
pyb.freq() # get CPU and bus frequencies
pyb.freq(60000000) # set CPU freq to 60MHz
pyb.stop() # stop CPU, waiting for external interrupt
2. 延迟和定时
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 value of millisecond counter
delta = time.ticks_diff(time.ticks_ms(), start) # compute time difference
3. LEDs
from machine import Pin
led_y = Pin(16,Pin.OUT)
led_r = Pin(19,Pin.OUT)
led_g = Pin(18,Pin.OUT)
led_b = Pin(17,Pin.OUT)
4. 板上按键
import machine
key1 = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
key2 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
5. 管脚和GPIO
from pyb import Pin
p_out = Pin('X1', Pin.OUT_PP)
p_out.high()
p_out.low()
p_in = Pin('X2', Pin.IN, Pin.PULL_UP)
p_in.value() # get value, 0 or 1
6. 定时器
from pyb import Timer
tim = Timer(1, freq=1000)
tim.counter() # get counter value
tim.freq(0.5) # 0.5 Hz
tim.callback(lambda t: pyb.LED(1).toggle())
7. PWM
import machine
import utime
beep = machine.PWM(machine.Pin(22))
beep.freq(1000) #频率
while True:
beep.duty_u16(100) #改变占空比改变蜂鸣器的响度
8. ADC
from pyb import Pin, ADC
adc = ADC(Pin('X19'))
adc.read() # read value, 0-4095
9. UART
from pyb import UART
uart = UART(1, 9600)
uart.write('hello')
uart.read(5) # read up to 5 bytes
10. SPI总线
from pyb import SPI
spi = SPI(1, SPI.CONTROLLER, baudrate=200000, polarity=1, phase=0)
spi.send('hello')
spi.recv(5) # receive 5 bytes on the bus
spi.send_recv('hello') # send and receive 5 bytes
11. I2C总线
from machine import I2C
i2c = I2C('X', freq=400000) # create hardware I2c object
i2c = I2C(scl='X1', sda='X2', freq=100000) # create software I2C object
i2c.scan() # returns list of peripheral addresses
i2c.writeto(0x42, 'hello') # write 5 bytes to peripheral with address 0x42
i2c.readfrom(0x42, 5) # read 5 bytes from peripheral
i2c.readfrom_mem(0x42, 0x10, 2) # read 2 bytes from peripheral 0x42, peripheral memory 0x10
i2c.writeto_mem(0x42, 0x10, 'xy') # write 2 bytes to peripheral 0x42, peripheral memory 0x10
12. 姿态传感器
from pyb import Accel
accel = Accel()
print(accel.x(), accel.y(), accel.z(), accel.tilt())
13. WS2812B控制
14. 蜂鸣器的控制
from machine import Pin, PWM
from utime import sleep
buzzer = PWM(Pin(22))
buzzer.freq(500)
buzzer.duty_u16(1000)
sleep(1)
buzzer.duty_u16(0)