|
pyboardCN V2-驱动直流电机和编码器
[复制链接]
1,手上有个自己做的L293D驱动板原理图如下
2,想试下的pyboardCN V2-驱动直流电机和编码器
把p1接到X1
ina1接到A14
ina2寄到A15
E1A接到X2
E1B接到X3
ina1,ina2 控制电机的方向和启停
E1A,E1B是电机编码器的A,B相
对了电机如下图
3,pyb程序
- from pyb import Pin,Timer,ExtInt,UART
- from pid import PID
- import time
- import _thread
- uart=UART(1,115200)
- in1=Pin(Pin.cpu.A14,Pin.OUT)
- in2=Pin(Pin.cpu.A15,Pin.OUT)
- count1=0
- count2=0
- p = Pin('X1') # X1 has TIM2, CH1
- tim = Timer(2, freq=1000)
- ch = tim.channel(1, Timer.PWM, pin=p)
- d=50
- ch.pulse_width_percent(50)
- pidl= PID(p=0.05, i=0.05, imax=300)
- def stop():
- global in1,in2
- in1.value(1)
- in2.value(1)
- def callback1(p):
- global count1
- count1 =count1 +1
- def start():
- global in1,in2
- in1.value(0)
- in2.value(1)
- e1=pyb.ExtInt(Pin('X2'),pyb.ExtInt.IRQ_RISING_FALLING,pyb.Pin.PULL_UP,callback1)
- e2=pyb.ExtInt(Pin('X3'),pyb.ExtInt.IRQ_RISING_FALLING,pyb.Pin.PULL_UP,callback1)
- def getcount(long):
- global count1
- count1=0
- time.sleep_ms(long)
- print('count',count1)
- uart.write(str(count1))
- return(count1)
- def control(ms):
- l=getcount(ms)
- error=50*10-l
- output=pidl.get_pid(error,d)
- print('error',error)
- ch.pulse_width_percent(d+output)
- def autoprint(long):
- while(1):
- control(long)
- start()
- _thread.start_new_thread(autoprint,((50,)))
复制代码
4,这里用到编码器就涉及到了闭环,所以我想试试pid
看shell的数值不够直观就想把这些值输入电脑生产图表
pybv2使用串口把这些值输入电脑,这里用到了usbttl把
pybv2的串口1与usbttl相连.
5,电脑上usb程序
- import serial
- import re
- import matplotlib.pyplot as plt
- #plt.plot([32,30,25,50])
- plt.ylabel('count')
- u = serial.Serial()
- u.port = '/dev/ttyUSB0'
- u.baudrate = 115200
- u.parity = 'N'
- u.bytesize = 8
- u.stopbits = 1
- u.timeout = 0.6
- s=''
- count=0
- data=[]
- datax=[]
- try:
- u.open()
- u.setDTR(True)
- u.setRTS(True)
- except Exception, ex:
- print ex
- def read_command(str):
- s=re.search('CMTI:\s*"SM"\s*,\s*(\d+)',str)
- if(s):
- return s.group(1)
- else:
- return 'NONE'
- while(count <300):
- s=str(u.read_all())
- if len(s)>0:
- print(s)
- data.append(int(s))
- datax.append(500)
- count =count+1
- plt.plot(data)
- plt.plot(datax)
- plt.show()
复制代码
这里用到了 matplotlib.pyplot 生成图表如下图
|
|