OpenMV >> 6. 使用外设

常用函数

# 延时50ms
pyb.delay(50)

# 获取从启动开始计时的毫秒数
pyb.millis()

LED

from pyb import LED

led = LED(1) # 红led
led.toggle()
led.on()#亮
led.off()#灭

LED(1) -> 红LED
LED(2) -> 绿LED
LED(3) -> 蓝LED
LED(4) -> 红外LED,两个

IO

from pyb import Pin

p_out = Pin('P7', Pin.OUT_PP)#设置p_out为输出引脚
p_out.high()#设置p_out引脚为高
p_out.low()#设置p_out引脚为低

p_in = Pin('P7', Pin.IN, Pin.PULL_UP)#设置p_in为输入引脚,并开启上拉电阻
value = p_in.value() # get value, 0 or 1#读入p_in引脚的值

舵机

from pyb import Servo

s1 = Servo(1) # servo on position 1 (P7)
s1.angle(45) # move to 45 degrees
s1.angle(-60, 1500) # move to -60 degrees in 1500ms
s1.speed(50) # for continuous rotation servos

Servo(1) -> P7 (PD12)
Servo(2) -> P8 (PD13)
Servo(3) -> P9 (PD14)

IO中断

from pyb import Pin, ExtInt

callback = lambda e: print("intr")
ext = ExtInt(Pin('P7'), ExtInt.IRQ_RISING, Pin.PULL_NONE, callback)

定时器

from pyb import Timer

tim = Timer(4, freq=1000)
tim.counter() # get counter value
tim.freq(0.5) # 0.5 Hz
tim.callback(lambda t: pyb.LED(1).toggle())

Timer 1 Channel 3 Negative -> P0
Timer 1 Channel 2 Negative -> P1
Timer 1 Channel 1 Negative -> P2
Timer 2 Channel 3 Positive -> P4
Timer 2 Channel 4 Positive -> P5
Timer 2 Channel 1 Positive -> P6
Timer 4 Channel 1 Negative -> P7
Timer 4 Channel 2 Negative -> P8
Timer 4 Channel 3 Positive -> P9

PWM

from pyb import Pin, Timer

p = Pin('P7') # P7 has TIM4, CH1
tim = Timer(4, freq=1000)
ch = tim.channel(1, Timer.PWM, pin=p)
ch.pulse_width_percent(50)

ADC

from pyb import Pin, ADC

adc = ADC('P6')
adc.read() # read value, 0-4095

DAC

from pyb import Pin, DAC

dac = DAC('P6')
dac.write(120) # output between 0 and 255

UART

from pyb import UART

uart = UART(3, 9600)
uart.write('hello')
uart.read(5) # read up to 5 bytes

UART 3 RX -> P5 (PB11)
UART 3 TX -> P4 (PB10)
UART 1 RX -> P0 (PB15)
UART 1 TX -> P1 (PB14)

SPI

from pyb import SPI

spi = SPI(2, SPI.MASTER, baudrate=200000, polarity=1, phase=0)
spi.send('hello')
spi.recv(5) # receive 5 bytes on the bus
spi.send_recv('hello') # send a receive 5 bytes

I2C

from machine import I2C, Pin
i2c = I2C(sda=Pin('P5'),scl=Pin('P4'))

i2c.scan()
i2c.writeto(0x42, b'123')         # write 3 bytes to slave with 7-bit address 42
i2c.readfrom(0x42, 4)             # read 4 bytes from slave with 7-bit address 42

i2c.readfrom_mem(0x42, 8, 3)      # read 3 bytes from memory of slave 42,
                                # starting at memory-address 8 in the slave
i2c.writeto_mem(0x42, 2, b'\x10') # write 1 byte to memory of slave 42
                                # starting at address 2 in the slave

I2C 2 SCL (Serial Clock) -> P4 (PB10)
I2C 2 SDA (Serial Data) -> P5 (PB11)
I2C 4 SCL (Serial Clock) -> P7 (PD13)
I2C 4 SDA (Serial Data) -> P8 (PD12)

你可能感兴趣的:(Python,OpenMV)