L298n motor control with Raspberry pi

106 views Asked by At

I was trying to implement a single L298n motor driver with a 4WD robot using 2 motors connected to a Raspberry Pi. Now, I can turn on and off the L298n driver (the speed of both the motors remains the same) but cannot set a variable PWM for each of the motors, even if I try to put different speed values they remain the same.

NOTE: What I am trying to accomplish after getting proper motor control is that I want to control the driver from a virtual joystick.

My code follows:

import RPi.GPIO as GPIO
import time
import math
import smbus
import firebase_admin
from firebase_admin import credentials, db

# Initialize Firebase with the private key
cred = credentials.Certificate("/home/pi/Desktop/GCC/firebase_credentials.json")
firebase_admin.initialize_app(cred, {
    'databaseURL': '#################################'
})

# Reference to the Firebase Realtime Database for commands and sensor data
command_ref = db.reference('/command')
sensor_ref = db.reference('/Mobile')

#Board connect
GPIO.setmode(GPIO.BCM)

#forward
in1 = 20
in3 = 5
en1 = 12

#backward
in2 = 21
in4 = 19
en2 = 13

GPIO.setup(in1, GPIO.OUT)
GPIO.setup(in2, GPIO.OUT)
GPIO.setup(in3, GPIO.OUT)
GPIO.setup(in4, GPIO.OUT)
GPIO.setup(en1, GPIO.OUT)
GPIO.setup(en2, GPIO.OUT)

#duty cycles for l298n motor
p1 = GPIO.PWM(en1, 1000)
p2 = GPIO.PWM(en2, 1000)
p1.start(0)
p2.start(0)

motorSpeed1 = 0;
motorSpeed2 = 100;


def main():
    while True:
        data = command_ref.get()
        if data is not None:
            joystick_mode = data.get('joystick_mode', False)
            if joystick_mode:
                joystick_data = db.reference('/Joystick movement').get()
                x = joystick_data.get('xPercent')
                y = joystick_data.get('yPercent')
#                print("x {:.3f}, y {:.3f}".format(x,y))
                GPIO.output(in1, GPIO.LOW)
                GPIO.output(in2, GPIO.HIGH)
                GPIO.output(in3, GPIO.LOW)
                GPIO.output(in4, GPIO.HIGH)
                
                p1.ChangeDutyCycle(motorSpeed1)
                p2.ChangeDutyCycle(motorSpeed2)

                
                time.sleep(5)
                GPIO.output(in1, GPIO.LOW)
                GPIO.output(in2, GPIO.LOW)
                GPIO.output(in3, GPIO.LOW)
                GPIO.output(in4, GPIO.LOW)
                
                return

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Program stopped")
    finally:
        GPIO.cleanup()

I have tried checking on the hardware connections, which seems correct; how do I set the correct PWM?

0

There are 0 answers