Controlling dc motor

Hello Guys,
Can anyone tell me how I can easily control the 2 dc motors speed using GPIO pins of Jetson Nano? As I’m working on the prototype of autonomous car. And I’m using this code but it’s behaving infinite like.
Thanks in advance.

import Jetson.GPIO as GPIO

FORWARD=1
BACKWARD=2
MIN_SPEED=0
MAX_SPEED=100

class Motor():
def init(self, pwmpin, forwardPin, backwardPin):
self.pwmpin=pwmpin
self.forwardPin=forwardPin
self.backwardPin=backwardPin
print(‘hello ans , Im here’)

    GPIO.setup([self.forwardPin, self.backwardPin], GPIO.OUT, initial=GPIO.LOW)
    self.pwm=GPIO.PWM(self.pwmpin,30)
    self.pwm.start(0)

def setDirection(self, direction):
    if direction==FORWARD:
        GPIO.output(self.backwardPin, GPIO.LOW)
        GPIO.output(self.forwardPin, GPIO.HIGH)
    else:
        GPIO.output(self.forwardPin, GPIO.LOW)
        GPIO.output(self.backwardPin, GPIO.HIGH)

def setSpeed(self, value):
    value=max(min(value, MAX_SPEED), MIN_SPEED)
    self.pwm.ChangeDutyCycle(value)

import traceback
import time
from motortest import Motor, FORWARD, BACKWARD

IN1=24
IN2=26
EN1=33

IN3=16
IN4=18
EN2=32

def main():
motorA=motorB=None
try:
GPIO.setmode(GPIO.BOARD)
motorA=Motor(EN1, IN1, IN2)
motorB=Motor(EN2, IN3, IN4)

    motorA.setDirection(FORWARD)
    motorB.setDirection(FORWARD)

    
    motorA.setSpeed(20)
    motorB.setSpeed(30)
    time.sleep(5) #is se phle wali instruction 10 sec tak running me ho ge, chaie wo kio loop bi ho.
    
    motorA.setDirection(BACKWARD)
    motorB.setDirection(BACKWARD)
    
    motorA.setSpeed(20)
    motorB.setSpeed(30)
    time.sleep(5)
    
    motorA.setSpeed(0)  #for stop
    motorB.setSpeed(0)
    
    #motorA.pwm.stop()
    #motorB.pwm.stop()

except:
    traceback.print_exc()
    print("exception")
finally:
    if motorA:
        motorA.pwm.stop()
    if motorB:
        motorB.pwm.stop()
    GPIO.cleanup()

if name==“main”:
main()

hello ansjaved67,

you may refer to Jetson GPIO, check simple_pwm.py for details on how to use PWM channels.
please also check this thread for using Nano PWM, thanks

1 Like