Salted fish ZTMR example-trolley status

Salted fish ZTMR example-trolley status

After we can control the motor, we can do many things, such as fans and cars. This time, we use functions to define the status of the car for easy use.
function

Functions are organized, reusable, code segments used to implement single, or related functions. The function can improve the modularity of the application, and the code reuse rate. You already know that Python provides many built-in functions, such as print ().

Syntax
Python defines functions using the def keyword, the general format is as follows:

def 函数名(参数列表):
    函数体

Example
Let's use a function to output "Hello World!":
def holle ()print("hello world")
Description

Function code blocks begin with the def keyword, followed by the function identifier name and parentheses ().
Any incoming parameters and arguments must be placed between the parentheses, which can be used to define parameters.
The first line of the function can optionally use the document string-used to store the function description.
The contents of the function start with a colon and are indented.
return [expression] Ends the function, optionally returning a value to the caller. Return without expression is equivalent to returning None.

Example: Encapsulate your own print ()

def mprint(str):
	"打印任何传入的字符串"
	print(str)
	return
mprint("我是咸鱼")

Insert picture description here

Routine:

# 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占空比

Published 166 original articles · 22 praises · 10,000+ views

Guess you like

Origin blog.csdn.net/weixin_45020839/article/details/105506758