鹹魚ZTMR實例—小車狀態
可以控制馬達後,我們就能做很多事情了,比如風扇,和小車。這次我們用函數來定義小車狀態,方便使用。
函數
函數是組織好的,可重複使用的,用來實現單一,或相關聯功能的代碼段。函數能提高應用的模塊性,和代碼的重複利用率。你已經知道Python提供了許多內建函數,比如print()。
語法
Python 定義函數使用 def 關鍵字,一般格式如下:
def 函數名(參數列表):
函數體
實例
讓我們使用函數來輸出"Hello World!":
說明
函數代碼塊以 def 關鍵詞開頭,後接函數標識符名稱和圓括號 ()。
任何傳入參數和自變量必須放在圓括號中間,圓括號之間可以用於定義參數。
函數的第一行語句可以選擇性地使用文檔字符串—用於存放函數說明。
函數內容以冒號起始,並且縮進。
return [表達式] 結束函數,選擇性地返回一個值給調用方。不帶表達式的return相當於返回 None。
例:封裝個屬於自己的print()
def mprint(str):
"打印任何傳入的字符串"
print(str)
return
mprint("我是鹹魚")
例程:
# main.py -- put your code here!
from pyb import Pin, Timer,delay
from time import sleep_us,ticks_us,sleep
cs = Pin('B10',Pin.OUT_PP) #B10設置爲輸出引腳輸出高電平
cs(1)
ch1 =None
ch2 =None #初始化
AI1 = Pin('B12',Pin.OUT_PP) #右側馬達
AI2 = Pin('B13',Pin.OUT_PP)
BI1 = Pin('B14',Pin.OUT_PP) #左側馬達
BI2 = Pin('B15',Pin.OUT_PP)
#A電機(右)
p1 = Pin('B8')
tim1 = Timer(10, freq=120)
ch1 = tim1.channel(1, Timer.PWM, pin=p1)
#B電機(左)
p2 = Pin('B9')
tim2 = Timer(4, freq=120)
ch2 = tim2.channel(4, Timer.PWM, pin=p2)
#小車狀態
def go(speed): #直行狀態
ch1.pulse_width_percent(speed)
ch2.pulse_width_percent(speed)
AI1(0)
AI2(1)
BI1(1)
BI2(0)
def back(speed): #倒車
ch1.pulse_width_percent(speed)
ch2.pulse_width_percent(speed)
AI1(1)
AI2(0)
BI1(0)
BI2(1)
def stopo(): #停止
ch1.pulse_width_percent(0)
ch2.pulse_width_percent(0)
def spin_left(speed): #右旋
ch1.pulse_width_percent(0)#右
ch2.pulse_width_percent(speed)
AI1(1)
AI2(0)
BI1(1)
BI2(0)
def spin_right(speed):#左旋
ch1.pulse_width_percent(speed)
ch2.pulse_width_percent(0)
AI1(0)
AI2(1)
BI1(0)
BI2(1)
def left(speed): #右轉
ch1.pulse_width_percent(0)
ch2.pulse_width_percent(speed)
AI1(1)
AI2(0)
BI1(0)
BI2(0)
def right(speed): #左轉
ch1.pulse_width_percent(speed)
ch2.pulse_width_percent(0)
AI1(0)
AI2(0)
BI1(0)
BI2(1)
while True: #調用
back(40) #括號裏參數爲數字0~100 PWM佔空比