Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Thursday, August 13, 2015

Freedom!

A pretty short one today. I finally got my battery, so I can now run the Pi remotely, under its own power. Which mostly means I just sit at my computer, running it over things. I still wouldn't call it a robot, more of an R/C Tank. But it is getting there. While I don't have any real building today, I do have a bit of code. So...

Let us do this!
<!--more-->
A R/C Tank isn't any good without control, right? So how do I do it.
This is how:
import RPi.GPIO as GPIO
import time
import pygame
import sys
import pygame.camera
from pygame.locals import *

#Pin definition for drive control
in1_pin = 5 #Right back
in2_pin = 6 #Right forward
in3_pin = 12 #Left back
in4_pin = 13 #Left forward
enableA_pin = 16 #Right side
enableB_pin = 26 #Left side

#Setup pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(enableA_pin, GPIO.OUT)
GPIO.setup(enableB_pin, GPIO.OUT)
GPIO.setup(in1_pin, GPIO.OUT)
GPIO.setup(in2_pin, GPIO.OUT)
GPIO.setup(in3_pin, GPIO.OUT)
GPIO.setup(in4_pin, GPIO.OUT)

pwmA = GPIO.PWM(enableA_pin, 500) #Right side throttle
pwmB = GPIO.PWM(enableB_pin, 500) #Left side throttle
pwmA.start(0)
pwmB.start(0)


GPIO.output(in1_pin, False)
GPIO.output(in2_pin, False)
GPIO.output(in3_pin, False)
GPIO.output(in4_pin, False)

#drive commands
def forward():
    pwmA.ChangeDutyCycle(100)
    pwmB.ChangeDutyCycle(100)
    GPIO.output(in1_pin, False)
    GPIO.output(in2_pin, True)
    GPIO.output(in3_pin, False)
    GPIO.output(in4_pin, True)

def reverse():
    pwmA.ChangeDutyCycle(50)
    pwmB.ChangeDutyCycle(50)
    GPIO.output(in1_pin, True)
    GPIO.output(in2_pin, False)
    GPIO.output(in3_pin, True)
    GPIO.output(in4_pin, False)

def spinRight():
    pwmA.ChangeDutyCycle(100)
    pwmB.ChangeDutyCycle(100)
    GPIO.output(in1_pin, False)
    GPIO.output(in2_pin, True)
    GPIO.output(in3_pin, True)
    GPIO.output(in4_pin, False)

def turnRightForward():
    pwmA.ChangeDutyCycle(75)
    pwmB.ChangeDutyCycle(25)
    GPIO.output(in1_pin, False)
    GPIO.output(in2_pin, True)
    GPIO.output(in3_pin, False)
    GPIO.output(in4_pin, True)

def turnRightReverse():
    pwmA.ChangeDutyCycle(75)
    pwmB.ChangeDutyCycle(25)
    GPIO.output(in1_pin, True)
    GPIO.output(in2_pin, False)
    GPIO.output(in3_pin, True)
    GPIO.output(in4_pin, False)

def spinLeft():
    pwmA.ChangeDutyCycle(100)
    pwmB.ChangeDutyCycle(100)
    GPIO.output(in1_pin, True)
    GPIO.output(in2_pin, False)
    GPIO.output(in3_pin, False)
    GPIO.output(in4_pin, True)

def turnLeftForward():
    pwmA.ChangeDutyCycle(25)
    pwmB.ChangeDutyCycle(75)
    GPIO.output(in1_pin, False)
    GPIO.output(in2_pin, True)
    GPIO.output(in3_pin, False)
    GPIO.output(in4_pin, True)

def turnLeftReverse():
    pwmA.ChangeDutyCycle(25)
    pwmB.ChangeDutyCycle(75)
    GPIO.output(in1_pin, True)
    GPIO.output(in2_pin, False)
    GPIO.output(in3_pin, True)
    GPIO.output(in4_pin, False)

def stop():
    GPIO.output(in1_pin, False)
    GPIO.output(in2_pin, False)
    GPIO.output(in3_pin, False)
    GPIO.output(in4_pin, False)
    pwmA.ChangeDutyCycle(0)
    pwmB.ChangeDutyCycle(0)

#Setup window, set cam image to background
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("DaBot")
pygame.mouse.set_visible(8)
pygame.key.set_repeat(100, 100)
#cam = pygame.camera.Camera("/dev/video0", (384, 288))
#cam.start()
#background_image = cam.get_image() #pygame.image.load("eyes.jpg").convert()
#screen.blit(background_image, [0,0])
pygame.display.update()


try:
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == 273 or event.key == 278: #up arrow or Home
                    forward()
                elif event.key == pygame.K_s: #s key -> straight line test
                    forward()
                    time.sleep(3)
                    stop()
                elif event.key == pygame.K_p: #p key
                    GPIO.cleanup()
                    break
                elif event.key == 274 or event.key == 279: #down arrow or End
                    reverse()
                elif event.key == 276: #left arrow
                    spinLeft()
                elif event.key == 277: #Insert
                    turnLeftForward()
                elif event.key == 127: #Delete
                    turnLeftReverse()
                elif event.key == 275: #right arrow
                    spinRight()
                elif event.key == 280: #Page up
                    turnRightForward()
                elif event.key == 281: #Page down
                    turnRightReverse()
                else:
                    print (event.key)
#                im = get_image()
#                background_image = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
                background_image = pygame.image.load("eyes.jpg").convert()
                #background_image = pygame.transform.rotate(background_image, 90)
                screen.blit(background_image, [0,0])
                pygame.display.update()
            elif event.type == pygame.KEYUP:
                stop()
     
#    speed = int(cmd[1]) * 10
#    print(speed)
#    pwm.ChangeDutyCycle(speed)

except(KeyboardInterrupt, SystemExit()):
    GPIO.cleanup()
#    cam.stop()
 I left in the camera stuff this time. Most of it is commented out, but some isn't. I just wanted to show, basically, the works there. At a leter date, when I get a camera that works with pygame, I will return to it. For now, we are just interested in the movement.
For the most part, much of this will look fairly familiar. A couple of changes you may have noticed, are the Turn functions. Spin is great, turns on a dime, gets you where you are going, and tears the tracks right off the wheels. Which, of course, leaves the bot high and dry. I found that if the robot drives forward and turns instead of just spinning, it keeps the tracks on. I also added another set of forward/reverse keys. This allows you to move your whole hand up the the "turn" keys, lowering the chance of spinning or turning when you don't want to.

Those with a keen eye may have noticed pwmA and pwmB. These are the PWM pins. Remember way back when I said leave the jumpers in place on the enable pins? Well, I removed those. I then connected them to my PWM pins. Setting the PWM pins to 100 is the same as those jumpers. However, we can now set those to lower values, basically giving us a throttle. This is what makes the Turn functions a reality. Without PWM we are stuck either all on or all off. Now we can vary it. So, 75% on one side 25% on the other, abracadabra, we turn. Without losing our tracks. I also cut the reverse power to 50%. Why? Just to test. Later, I will add input variables to adjust the speed of the functions. But for now they are proof of concept.

I now have all the tools I need to make my robot drive itself. All I need is a way for it to know where it is going. A Distance Sensor. I have a sonic one on its way, I have the code written, I even have a cable spliced with resistors waiting for a quick connect. As soon as it gets here, I will be sure to update you all.

In the meantime, I wasn't super happy with pulling my cable out of my battery pack after I shut down the Raspberry Pi. So, since I had an extra switch from the motor battery pack, I decided to add it to a USB cable to give the Pi a switch as well. I will do an aside soon to show how to set that up.

Until then, keep building!

Monday, August 3, 2015

Almost from the beginning


I said I wouldn't start from the very beginning, skipping the learning GPIOs and what not. Apparently, I am also going to skip my ugly first steps into using an H-bridge controller. And it was ugly. I had tried making my own l298n controller, but wasn't able to get it working. I purchased a cheap l298n from China off of eBay.  When it finally arrived, I hooked up straight away to my two scavenged motors and a scavenged two AA battery pack. I could run one or the other, but not both. So, off to RadioShack to grab a power pack. From this I was able to get movement. I had always planned to run a tracked robot, and while I was at a local Hobby Town (they specialize in RC among other things), I found a Tamiya track set, as well as a Tamiya Double Gearbox. This allowed me to put together the above setup. I will discuss the gearbox and tracks in a later post. As you can see, I was still using a breakout and a breadboard. This is a great place to test on, but I scrapped it later in favor of cleaner wiring. You can also see some ribbon cable slapped in there. From my early days of computer building, I have plenty of these IDE cables lying around. However, these were just as messy, and when I finally received my male to female and female to female jumpers, I swapped them out. At some point I may come back to a full plug to easier add and remove my Pi.
The H-bridge is fairly easy to hook up. Choose 4 GPIO pins, in my case 17, 18, 21, and 22. Connect these to In 1,2,3, and 4. I left the jumpers on the enable pins, as I wasn't up to PWM for this yet. Then connect the ground of the H-bridge to the Pi AND your battery pack. Connect the batteries positive(red) to the VCC. I had attached the 5v, but a larger battery pack reset my Pi. Then connect the outs to your motors. One set to one motor, the other to the other motor. Order is less important here, but 1 and 4 to the left side of the motors and 2 and 3 to the other sides makes it easier to spin them correctly in the code.
At some point I should learn to make wiring diagrams, but at the moment, that is not today.

Here is my initial code to run things:
import RPi.GPIO as GPIO
import time

in1_pin = 17
in2_pin = 18
in3_pin = 22
in4_pin = 23
x = True

GPIO.setmode(GPIO.BCM)

GPIO.setup(in1_pin, GPIO.OUT)
GPIO.setup(in2_pin, GPIO.OUT)
GPIO.setup(in3_pin, GPIO.OUT)
GPIO.setup(in4_pin, GPIO.OUT)


GPIO.output(in1_pin, False)
GPIO.output(in2_pin, False)
GPIO.output(in3_pin, False)
GPIO.output(in4_pin, False)

def clockwise():
    GPIO.output(in1_pin, True)
    GPIO.output(in2_pin, False)
    GPIO.output(in3_pin, True)
    GPIO.output(in4_pin, False)
    print("Clockwise")

def counter_clockwise():
    GPIO.output(in1_pin, False)
    GPIO.output(in2_pin, True)
    GPIO.output(in3_pin, False)
    GPIO.output(in4_pin, True)
    print("Counter clockwise")

while x:
    cmd = raw_input("Command, f/r 0..9, E.g. f5 :")
    direction = cmd[0]
    if direction == "f": #"Forward"
        clockwise() #I used clockwise/counter to test direction, then match
    elif direction == "s": #Stop/exit loop
        x = False
    elif direction == "r": #"Reverse"
        counter_clockwise()
    else:
        print ("Invalid input")
    speed = int(cmd[1]) * 10
GPIO.cleanup() #Needed to release the GPIO and stop motors

Fairly simple. I used pins 17 and 18 for one side and 22 and 23 for the other. I then had a simple command input to move forward and back. As my code was an extension from a previous attempt to build my own bridge using just the L298n chip, I also had input for speed. I removed all of that code to nix confusion, but that part of the input is still there. At this point and for a bit longer, I won't be using PWM. I am going full on, full off, and just using the enable jumpers that came on the L298N bridge for 100% PWM. When I get my robot to working remotely, then I will worry about PWM. For right now, I am happy that I can move my wheels forward and back. Be sure to note which way the motors spin, so that you can later alter the code to make the robot move how you want. Mine is a little backwards, and 2 and 4 are forward, while 1 and 3 are backwards. The way to fix this in the hardware would be to switch the motor connections, but I have just chosen to code them that way.