好记性不如铅笔头

linux, 操作系统, 树莓派

树莓派学习笔记:使用L298N控制直流电机的速度

根据资料, 可以使用L298N的ENA,ENB端口进行直流电机的速度控制,方式为PWM。这里备注下代码,比较简单。

连线

树莓派GPIO3  == IN1

树莓派GPIO4  == IN2

树莓派GPIO5  == ENA

+3.5V            == VCC

测试代码

import RPi.GPIO as GPIO
import time


def speedCtrl(seconds, count, percent):
	print(seconds, count, percent);
	
	timeunit = 1.0/count;
	cnt = 0;
	while cnt < seconds:
		cnt = cnt + 1;
		times = 0;
		while times < count:
			times = times + 1;
			GPIO.output(GPIO_CTRL, GPIO.HIGH);
			time.sleep( timeunit * percent / 100 );
			GPIO.output(GPIO_CTRL, GPIO.LOW);
			time.sleep( timeunit * (1- percent/100) );

if __name__ == "__main__":
	GPIO_DATA1 = 22;
	GPIO_DATA2 = 23;
	GPIO_CTRL = 24;

	GPIO.setmode(GPIO.BCM);

	GPIO.setup(GPIO_DATA1,GPIO.OUT);
	GPIO.setup(GPIO_DATA2,GPIO.OUT);
	GPIO.output(GPIO_DATA1, GPIO.LOW);
	GPIO.output(GPIO_DATA2, GPIO.HIGH);

	GPIO.setup(GPIO_CTRL,GPIO.OUT);
	GPIO.output(GPIO_CTRL, GPIO.LOW);
	time.sleep(1);
	
	speedCtrl(5,10,0);
	speedCtrl(5,10,20);
	speedCtrl(5,10,40);
	speedCtrl(5,10,60);
	speedCtrl(5,10,80);
	speedCtrl(5,10,100);
	
	speedCtrl(5,1,40);
	speedCtrl(5,5,40);
	speedCtrl(5,10,40);
	speedCtrl(5,15,40);
	speedCtrl(5,20,40);	
	
	GPIO.cleanup();	

更新:

之前的函数有点问题,写个新的。

    def speedCtrl(seconds, count, percent):
        timeunit = 1.0/count;
        cnt = seconds * count;
        GPIO_HIGH = GPIO.HIGH;
        GPIO_LOW = GPIO.LOW;
        timeA = timeunit * percent / 100;
        timeB = timeunit * (1- percent/100);
        while cnt > 0:
            cnt = cnt - 1;
            if timeA > 0.0001:
                GPIO.output(GPIO_CTRL, GPIO_HIGH);
                time.sleep( timeA );
            if timeB > 0.0001:
                GPIO.output(GPIO_CTRL, GPIO_LOW);
                time.sleep( timeB );

 

Leave a Reply

5 × 3 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据