Adding Software
Ok the hard part is over. Now we just need to actually write a script to cause these silly little wheels to turn.
Now as I alluded to, with tools like Claude, creating the actual code is very simple. I simply ask Claude to create one for me and it does. Yawn.
import RPi.GPIO as GPIO
import time
# Your wiring: RIGHT side on OUT1/OUT2, LEFT side on OUT3/OUT4
# IN1/IN2 drive the right side, IN3/IN4 drive the left side.
IN1, IN2 = 18, 17 # right side (OUT1/OUT2)
IN3, IN4 = 22, 27 # left side (OUT3/OUT4)
ENA, ENB = 25, 24
GPIO.setmode(GPIO.BCM)
GPIO.setup([IN1, IN2, IN3, IN4, ENA, ENB], GPIO.OUT)
GPIO.output(ENA, GPIO.HIGH)
GPIO.output(ENB, GPIO.HIGH)
def forward():
GPIO.output(IN1, GPIO.HIGH); GPIO.output(IN2, GPIO.LOW)
GPIO.output(IN3, GPIO.HIGH); GPIO.output(IN4, GPIO.LOW)
def stop():
GPIO.output([IN1, IN2, IN3, IN4], GPIO.LOW)
try:
print("Forward for 2 seconds...")
forward()
time.sleep(2)
stop()
print("Done.")
finally:
GPIO.cleanup()
print("GPIO cleaned up.")
But let's actually examine what is happening in the code. It's a very simple script, so this shouldn't take too long.
After loading in the necessary packages, we assign GPIO pin numbers based on which L298N they are connected to:
# Your wiring: RIGHT side on OUT1/OUT2, LEFT side on OUT3/OUT4
# IN1/IN2 drive the right side, IN3/IN4 drive the left side.
IN1, IN2 = 18, 17 # right side (OUT1/OUT2)
IN3, IN4 = 22, 27 # left side (OUT3/OUT4)
ENA, ENB = 25, 24
This is kind of ironic given my earlier complaint about the difference between the physical pin numbers and the GPIO numbers, which is actually called Broadcom (BCM) numbers. Anyways, the next line here chooses between which numbering scheme to use. Claude, in its machine like wisdom, choose to use the BCM numbers rather than the physical pin location numbers:
GPIO.setmode(GPIO.BCM)
We then set each of our assigned pins as output pins, meaning we can change their settings between HIGH and LOW:
GPIO.setup([IN1, IN2, IN3, IN4, ENA, ENB], GPIO.OUT)
GPIO.output(ENA, GPIO.HIGH)
GPIO.output(ENB, GPIO.HIGH)
Now it gets real simple. We create two functions. First, we create a forward function. We set IN1 and IN3 to HIGH and IN2 and IN4 to LOW, which of course makes the IN1 and IN3 terminals to positive and IN2 and IN4 to negative. That in turn creates a current in the wire, which causes the rotor to spin! And voila, the wheels go forward!
def forward():
GPIO.output(IN1, GPIO.HIGH); GPIO.output(IN2, GPIO.LOW)
GPIO.output(IN3, GPIO.HIGH); GPIO.output(IN4, GPIO.LOW)
def stop():
GPIO.output([IN1, IN2, IN3, IN4], GPIO.LOW)
And finally, we actually execute the function:
try:
print("Forward for 2 seconds...")
forward()
time.sleep(2)
stop()
print("Done.")
finally:
GPIO.cleanup()
print("GPIO cleaned up.")
A video of the magic moment