Tuesday, 27 November 2012

Raspberry Pi Powered Lego Car


Want to take your Raspberry Pi some old Lego and build a remote control Lego car?  Well read on as this is the place to find out how to do it!

[Note: This was my original, 2012 era blog post on my Raspberry Pi car.  Read on for basic details as to how I made it.  See here for my 2013 post on how to upgrade it!] 

Two things have happened recently that have contributed to my tinkering hobby.
  • Firstly - My Raspberry Pi arrived after a long (but worth it) wait.
  • Secondly - My two girls (8 and 5) have got in to Lego and so slowly but surely I've been bringing down old Lego that I had when I was a kid, got stored in my parent's loft when I grew up and then got transferred to my loft when my parents had a general chuck out.
The coolest Lego model I had when I was a kid was a the Lego 8860 car chassis.  I brought this down from my loft, dusted it off and over the course of 3 weekends my daughters and I built it.  Here's a picture of it after we'd finished:
The car has lots of great features like rack and pinion steering, movable/reclining seats, a gear box, a differential, rear suspension and even a engine with pistons.

I'm very proud of my childhood self as all the parts were pretty much still there.  A few missing parts were easily replaceable with bits from other sets.  

The only missing part that I couldn't replace was a tiny bevel sprocket from the differential.  However (as I learned) there's a sites on the internet where you can buy old bits.  I used this site for the missing sprocket and for some other stuff I needed (see below).

The final pages of the assembly guide show how you can modify the car to add motors.  I never did this as a kid as I didn't have any Lego motors.  However as an adult with a bit more disposable income and some eager children I bought a few Lego power functions motors (again from the site mentioned above).  They were OK but required a battery box to be hard wired to them that meant you had to crawl along next to the car as it went along which wasn't much fun.

This is where the Raspberry Pi came in.  What if we could control the whole thing with the Raspberry Pi and make a remote control car!  That would be very cool!

Here's a video of the end result.  I'll then tell you how we made it!





A bit of research on the Raspberry Pi forum and other sites showed that people had been able to use the GPIO on the Raspberry Pi to control motors.  However we needed to start off by working out how to use  the Pi to control stuff with the GPIO.

We started off by looking at some simple electronics and Python code to use the GPIO to turn an LED off and on. We used this tutorial to get us started, used a breadboard, and LED and a resistor and wrote some Python code to control the LED.  Here's what it looked like:

Here you can see the Raspberry Pi, main connecting cables and some jumper wires going to a bread board which has an LED and a resistor on it.

GPIO11 goes to the anode on the LED.  The LED cathode connects to a resistor (~330Ohm) which then connects to GPIO6 (Ground). 




My Pi memory card came with Raspbian Wheezy on it and this already had Python installed.  We added a USB WiFi module (just visible on the image above) and configured this using the tool on the X windows desktop.

We created this simple Python script to turn the LED off and on:

#Get the time module
import time

#Get rid of warnings
GPIO.setwarnings(False)

#Set mode of numbering of pins
GPIO.setmode(GPIO.BOARD)

#Set pin 11 as an output
GPIO.setup(11,GPIO.OUT)

#Loop, changing the state
while 1:
  #Now set it high
  GPIO.output(11,True)

  #Wait a sec!
  time.sleep(1)

  #Now set it low
  GPIO.output(11,False)

  #Wait a sec!
  time.sleep(1)

It was called gpio_1.py so you type sudo python gpio_1.py to run the script.

So in researching motor control, the general advice was that motors require too much voltage and current to be driven directly from the Raspberry Pi.  The most common advice was to use a motor controller chip and this pre-made board seemed to have everything we needed.  So I bought one!

The board is based on a L298N motor controller and can be used to control a pair of motors.  Features:
  • A pair of inputs that can be controlled by TTL logic levels (like the Raspberry Pi uses).
  • Connections for a 9Volt battery.
  • A pair of outputs to connect to the DC motors.
So if input 1 is high and input 2 is low, the motor turns in one direction.  Input 1 low and input 2 high turns the motor in the other direction.  So for example the script shown above would make the motor turn for a second, pause for, turn for a second and so on.

Next challenge, connect the motor controller to the Lego motors:

The Lego power functions motors have stack-able connectors.  This site describes the motors in more detail and shows the pin out for the connectors.  

The two central pins are used to control the forward and back motion of "medium" motors that I bought.  The image shows how you can gently prize the pins of the connectors back and insert a single core wire. A modified (with a knife!) Lego tile holds the wires in place.

The image below shows the test jig for the Raspberry Pi, motor controller and the motors:

Here you can see the Raspberry Pi (on the left), 4 jumper wires going from the GPIO to the motor controller inputs, a jumper wire going to the motor controller ground, a battery connector and then the connections to the motors.  a script not unlike the one shown above was used to test that both motors worked.  They did!!




A (hand drawn - sorry) schematic for the system is shown below:

The next challenge was making the Raspberry Pi "mobile". We already had a WiFi USB adapter for IP connectivity but the Raspberry Pi needs a) power from a 5V micro USB supply and b) a connection to a TV or monitor via HDMI or S video.  To get over the power issue we bought a 5V re-chargeable battery; the sort you can get to re-charge a mobile 'phone.  We bought a Powergen 5200mAh re-chargeable unit which seemed like it would do the job for this but was also small enough to fit in a pocket which might be useful for other tinkering...

We couldn't have a hulking great cable linking the Pi to a monitor so I simply installed PuTTY on my PC and enabled SSH on the Raspberry Pi via the start-up utility.  PuTTY enables you to have a remote terminal session on the Pi and, by fixing the IP address on my WiFi router config. I always know which address to SSH to.

The last thing to sort out was connecting the motors to the Lego car. The motor to drive the wheels was easy enough, we just removed the engine parts and inserted one of the motors (as per 1980s instructions).  The steering was trickier as we needed to gear down the motor else it would just spin wildly and not have enough torque to turn the wheels.  To do this we built a little Lego gearbox:

From the image you can see that there's 3 pairs of small cog - medium cog pairings which gears down the motor speed nicely.  It needs a bit of a tidy up but it does the job for now.
   






So all the bits were ready, we just needed to assemble the car and write some Python code to control the motors.  Here's the car with all the kit stacked on it:

The seats had to be removed but the RasPi plus battery sit nicely on one side and the motor controller and it's battery sit nicely on the other side.








The first script I wrote was this:

#These are the keyboard mappings
#q = Go forward
#a = Stop going forward or back
#z = Go back
#i= Go left
#o = Stop steering
#p = Go right

#Get the GPIO module
import RPi.GPIO as GPIO

#Get the time module
import time

#A routine to control a pair of pins
def ControlAPairOfPins(FirstPin,FirstState,SecondPin,SecondState):
  print "Controlling them pins"
  if FirstState == "1":
    GPIO.output(int(FirstPin),True)
  else:
    GPIO.output(int(FirstPin),False)

  if SecondState == "1":
    GPIO.output(int(SecondPin),True)
  else:
    GPIO.output(int(SecondPin),False)
  #Just retur
  return

####Main body of code

#Get rid of warnings
GPIO.setwarnings(False)

#Set the GPIO mode
GPIO.setmode(GPIO.BOARD)
#Set the pins to be outputs
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)

while True:
  MyChar = raw_input("Press a character:")
  print "You pressed: " + MyChar
  if MyChar == "q":
    ControlAPairOfPins("19","1","21","0")
    print "Forward"
  elif MyChar == "a":
    ControlAPairOfPins("19","0","21","0")
    print "Stop"
  elif MyChar == "z":
    ControlAPairOfPins("19","0","21","1")
    print ("Back")
  elif MyChar == "i":
    ControlAPairOfPins("11","1","13","0")
    print "Left"
  elif MyChar == "o":
    ControlAPairOfPins("11","0","13","0")
    print "Stop steering"
  elif MyChar == "p":
    ControlAPairOfPins("11","0","13","1")
    print "Right"
  else:
    print "Not a command"

So we used the keyboard (via SSH) to control the motors.  q,a,z made the car go forward, stop and back, (look at how they line up on a keyboard).  i,o,p made the car go left, stop steering and right (again look at the keyboard).  the raw_input() method is used to capture what the user types on the keyboard.  This is then mapped to the GPIO pins and whether they need to be high or low.  The ControlAPairOfPins() function is then called to set the state of the GPIO pins.  The code is a bit clunky but it worked and enabled us to control the motors via the SSH session.  The main downside was that raw_input()requires you to type enter after the character meaning it's a bit of a pain to remember the character, type it, press enter etc.

So we needed a better solution and this came from my old friend SL4A, (see previous posting).  Using this we could get an Android handset to communicate with the Raspberry Pi and control the motors.  SL4A gives access to all the Android sensors so we decided to use the position sensor, meaning we could tilt the handset forward and back (to make the car go forward and back) and left and right (to steer left and right).  a crazy idea but it just might work! 

First we needed to think about how the Android handset would communicate with the RasPi.  For my LightwaveRF kit I've sent command in UDP segments so I decided to do that again, (i.e. send from handset to Raspberry Pi using my home WiFi).  The protocol I decided on was simple.  Rather than typing q,a,z,i,o,p on the keyboard I would send this in UDP segments from the handset to the RasPi. The code to do this is below.  All I did was to import the socket module and put a socket listener within a while loop (rather than raw_input().  If the UDP socket receives a character then this is used to control a pair of pins.

#These are the keyboard mappings
#q = Go forward
#a = Stop going forward or back
#z = Go back
#i= Go left
#o = Stop steering
#p = Go right

#Get the GPIO module
import RPi.GPIO as GPIO

#Get the time module
import time

#Get the socket module
import socket

#Some IP constants for this, the server
UDP_IP = "192.168.0.5"
UDP_PORT= 8888

#A routine to control a pair of pins
def ControlAPairOfPins(FirstPin,FirstState,SecondPin,SecondState):
  print "Controlling them pins"
  if FirstState == "1":
    GPIO.output(int(FirstPin),True)
  else:
    GPIO.output(int(FirstPin),False)

  if SecondState == "1":
    GPIO.output(int(SecondPin),True)
  else:
    GPIO.output(int(SecondPin),False)
  #Just retur
  return

####Main body of code

#Get rid of warnings
GPIO.setwarnings(False)

#Set the GPIO mode
GPIO.setmode(GPIO.BOARD)
#Set the pins to be outputs
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(19,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)

#Set up the IP related details
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

#Tell the user we've started
print "UDP server started.  Waiting for response...."

while True:
  #Wait for a UDP command to be received
  print "Waiting for a UDP command"

  #Handles getting a UDP packet
  MyChar, addr = sock.recvfrom(1024) #buffer size is 1024

  #MyChar = raw_input("Press a character:")

  print "I received: " + MyChar

  if MyChar == "q":
    ControlAPairOfPins("19","1","21","0")
    print "Forward"
  elif MyChar == "a":
    ControlAPairOfPins("19","0","21","0")
    print "Stop"
  elif MyChar == "z":
    ControlAPairOfPins("19","0","21","1")
    print ("Back")
  elif MyChar == "i":
    ControlAPairOfPins("11","1","13","0")
    print "Left"
  elif MyChar == "o":
    ControlAPairOfPins("11","0","13","0")
    print "Stop steering"
  elif MyChar == "p":
    ControlAPairOfPins("11","0","13","1")
    print "Right"
  else:
    print "Not a command"

Looking at the handset side of things, we needed to learn how to detect the state of the handset sensors.  This simple tutorial shows how to do it.  The tutorial shows how to read all the sensors (magnometer, accelerometer, position sensor, light sensor) but I only wanted to use the position sensor. Running a line of code like this  s6 = droid.sensorsReadOrientation().result gives a result with 3 values which are [azimuth, pitch, roll].  From experimentation we observed that tilting the handset forward and back changed the pitch value and side to side changed the roll value (like an aeroplane I guess).

So all the Python script needed to do was read the position, check it against some thresholds and determine if it had changed.  If it had changed then I just needed to send the associated letter in a UDP segment.  here's the code:


#All the import statemets
import socket           #For UDP
import time             #For time
import android          #Android environment

#Our Droid entity
droid = android.Android()

#Some constants related to IP
UDP_IP = '192.168.0.5'
UDP_PORT = 8888
INET_ADDR = (UDP_IP,UDP_PORT)

#Some constants relating to direction.  These come from what I originally did on a keyboard
MoveForward= "q"
MoveBack = "z"
MoveStop = "a"
SteerLeft = "i"
SteerRight = "p"
SteerStop = "o"

#Some constants relating to thresholds.  Can be used to tune sensitivity
ForwardThresh = 0.3     #> This means you're tilted forward
BackwardThresh = -0.3   #< This means you're tilted backwards
LeftThresh = -0.4       #< This means you're tilted left
RightThresh = 0.4       #> This means you're tilted right 

######################################
#Main part of the code
######################################

#Initialise the movement and steering state
MoveState = MoveStop
SteerState = SteerStop

#Use these variables to get the current state
CurrentMove = ""
CurrentSteer= ""

#Print port information
print "UDP target IP:", UDP_IP 
print "UDP target port:", UDP_PORT 

#Set up the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

#Start sensing the Android sensors. Has a timer to allow the sensors to spark up
droid.startSensingTimed(1, 250)
time.sleep(1)

#Loop, detecting state and sending UDP
while True:
  #Use a try statement and add some error handling as well
  try:  
    #Read the sensor state     
    s1 = droid.sensorsReadOrientation().result  
    
    #The result is a list made up of float variables.  Presented as a CSV on screen but we can mathematically manipulate
        
    #Set up the current states based upon the thresholds defined as constants - First for forward and back
    if s1[1] > ForwardThresh:
      CurrentMove = MoveForward
    elif s1[1] < BackwardThresh:
      CurrentMove = MoveBack
    else: CurrentMove = MoveStop

    #Now do it for left and right
    if s1[2] > RightThresh:
      CurrentSteer = SteerRight
    elif s1[2] < LeftThresh:
      CurrentSteer = SteerLeft
    else: CurrentSteer = SteerStop

    #So we've got the current state, now check with the overall logged state.  If it's changed, we do some UDP fun
    #First check the forward / back state
    if CurrentMove == MoveState:
      #Do nothing
      CurrentMove = CurrentMove    #Seems necessary other you get an error
    else:
      #Now we need to send UDP and update the overall state
      MoveState = CurrentMove
      sock.sendto(CurrentMove, INET_ADDR)
      print "Forward / back state changed.  Sent: " + CurrentMove      
    
    #Now the left / right state
    if CurrentSteer == SteerState:
      #Do nothing
      CurrentSteer = CurrentSteer    #Seems necessary other you get an error 
    else:
      #Now we need to send UDP and update the overall state
      SteerState = CurrentSteer
      sock.sendto(CurrentSteer, INET_ADDR)      
      print "Left / right state changed.  Sent: " + CurrentSteer
   
      #Chill for a sec
      time.sleep(1)
  except Exception, err: #Handle exceptions
    #Write a screen with the error
    print "Got us an exception: " + str(err)   
    time.sleep(1)


As the video shows it works OK.  It needs tuning to speed the car up, change the tilt sensitivity on the handset but overall it's good.  We now need to work out other ways of controlling the car with the Raspberry Pi.

100 comments:

  1. Thanks for taking time for sharing this article, it was excellent and very informative. Its really very useful of all of users. I found a lot of information about Robot cars.Keep posting.
    Steering Rack

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. how many 9v batteries you use to power both motors and the pi and how do you control the speed of the motor? thanks...

    ReplyDelete
    Replies
    1. Hi Guanyu
      In terms of the batteries there were two involved.

      The Pi was powered by a 5V battery of the type you buy as an emergency charger for a mobile phone. I provided a link to this on the blog post. This is visible on some of the images and the video as a black and while rectangular unit.

      The motors were powered by a Eveready rechargeable PP3 battery. It's only about 200mAh but we got a good 30 mins of fun out of the car.

      In terms of speed control then I did not do any of this. The Power Functions Lego motors I have don't allow for this so basically they were on or off. However the connectors for Lego motors do have 4 pins and, according to the site I referenced, the outer 2 pins are for speed control so there must be a lego motor out there that can do this.

      I didn't investigate whether the motor controller can handle speed control (from memory it can) or whether the Pi can offer a suitable output.

      So what I ended up with is having the gearing on the car fairly low so as to be able to get it going. This in turn meant that the top speed isn't that fast. However this was supposed to be a fun / learning thing rather than the development of a super fast car.

      Regards
      Paul

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Thanks for the post. I got the following motor controller board
    http://www.amazon.com/SainSmart-Stepper-Controller-Mega2560-Duemilanove/dp/B00AJGM37I/ref=sr_1_1?ie=UTF8&qid=1364281967&sr=8-1&keywords=Dual+H+Bridge+L298N

    I think the board you got is similar to what i bought.

    I have a question regarding how you wired the battery to the motor controller board.
    I assume positive end of battery (+9v) was connected to vcc and the other end was connected to the ground of the controller. And the 5v was connected to the 5v pin of the raspberry pi. Is that correct?
    Looking at your picture, I could not quite figure out whether or not you connected the GPIO ground pin to the ground of the motor controller.
    Is that correct?

    ReplyDelete
    Replies
    1. Hi, Looking at the board you bought they appear to be similar (but not identical!). The L298N chip is the same.

      To clarify on the wiring:
      1)You DON'T need to wire the 5V input on the L298N board to the 5V output on the Raspberry Pi. The motors take all their power from the battery, (thus insulating the Pi from the high initial current load from the motor).
      2)You DO have to connect the Pi GPIO ground to the ground of the motor controller. This provides a common earth for the whole circuit (think of this as the return path for the current from the GPIO logic pins).
      3)The only other connections from the Pi GPIO are to the inputs on the board. These provide the logic levels to control motor direction.

      I believe that the board has two power supply inputs because it can drive motors that require different voltage inputs. For 5V motors use the 5V input (from a battery - not the Pi!). For voltages above this use the 12V input (as on my board - I assume this is the VCC on yours).

      Let me know if you've any other questions.

      Cheers, Paul

      Delete
  6. you controlled the robot with a smartphone?

    ReplyDelete
  7. Correct. The code running on the Raspberry Pi simply listens to a particular UDP port, and, when it receives packets with certain alphabetic letters in it, responds by switching the lego motors on and off (and setting the direction).

    This then gives you the basis to control the Lego car from any system that can detect a user input and then send the appropriate letters in UDP packets.
    -In my example I used a SL4A script on an Android handset to make decisions based upon outputs from the handset position sensor, (e.g. if tilted enough to the left then send a "i" character).
    -When testing the system I ran a Python script on a PC that simply registered keyboard presses and sent the letters to the Raspberry Pi.
    -You could use any other input you could imagine. For example Sl4A/Android has a great voice to text processing capability so you could control the car with speech commands.

    Let me know if you need more information.

    Cheers, Paul

    ReplyDelete
  8. Hello Paul,

    I didn't understand how to bring the motors to run.

    I know the two wires outside are for Voltage + and -.

    And the two wires inside are for the direction of the motors.

    allways when the first has a positive signal and the second a negative the motor drives in one direction .
    And when the first has anegative and the second has a positive , the motor runs/turns in the other direction.

    But how did you do this by an L298?
    Do you have another schematic where i can see the right connections?

    Thanks

    Willi Klein

    ReplyDelete
    Replies
    1. Hi Willi
      Good to hear from you.

      The Lego motor I have ("Lego Medium Motor") has 4 connections on the connection block but only uses the two inner ones. This site http://www.philohome.com/pf/pf.htm has an excellent description of what the connections are for. It shows how the inner ones (C1 and C2) are only used for this type of motor.

      It looks like the "Power Functions servo motor" is the one that requires the outer two connections.

      The image on my blog post shows a close up of how I connected some wires to C1 and C2 on the motor connection block by prising back the connectors and wedging the wires in.

      If you need to use the outer two connections for your motor then I guess you need to feed them directly from your 9V power supply.

      So the schematic on my blog is accurate! In simple terms:
      -Connect your 9V power supply to +12V and GND, (or the equivalent on your board).
      -Connect a common earth to the Raspberry Pi.
      -Connect the outputs to C1 and C2 on the Lego motors.
      -Connect the RasPi GPIO pins to the inputs.

      If you click on the "test jig" image you can just about make all this out.

      Then code on your RasPi does one of 3 things:
      -Both pins = 0 for motor off.
      -One pin at 1, one pin at 0 for motor on in one direction.
      -Reverse the above for the motor in the other direction.

      Hope this helps.

      Cheers, Paul

      Delete
  9. Thank you Paul for the quick Answer.

    Today I bought a new Lego Motor and made a lot of measurements.

    And I saw you are right, there are only C1 and C2 relevant, and so I understood how to use L298.

    But I have one Question are you from Germany, cause my English is very bad.

    I would like stearing the lego servo motor by raspi but I am no good programmer .

    I know one of the gpios is able do create PWM Signal but I dont understand how it has to

    look like vor this Lego Servo.

    Is it possible to mail to you in a normal way ?

    Thanks for your wonderful explanation.

    Cheers, Willi

    ReplyDelete
    Replies
    1. Hi Willi,
      I'm from England so my language skills are of course very poor! :-)

      In terms of programming and GPIO, this set of tutorials from Cambridge University are very good:
      http://www.cl.cam.ac.uk/freshers/raspberrypi/tutorials/turing-machine/two.html

      ...and this general guide that covers Scratch and Python is good too:
      http://downloads.raspberrypi.org/Raspberry_Pi_Education_Manual.pdf

      ...and if you don't like Python, this person has worked out how to control the GPIO pins using Scratch:
      http://cymplecy.wordpress.com/2012/08/26/scratch-controlling-the-gpio-on-a-raspberrypi/

      I'm not so sure about doing PWM using the Pi but I bet there's lots of information available on the internet! The Scratch GPIO control blog mentioned above talks about variable motor control so maybe that's using PWM.

      I don't check my email too often so it would be better to use this comments section to communicate.

      Cheers, Paul

      Delete
    2. Hello Paul,

      at thanks for the very quick answer.

      Your English is no problem it is very clear.

      My problem is my bad English, because I can't explain my problems in English as good as in German and I thought, you are out from Germany because of blogspot.de.

      I will follow the links, given by you.

      Thanks for them.
      But I,m not expired in SL4A and Python Scripts.

      Have I to install SL4A on my tablet or on the Raspi?

      If you are interested in another conclusion, you should look on www.robosphere.de.

      The author uses an Arduino at the Raspberry and another Motorshield with

      L293D and he uses a Webcam, I think it's very interesting ,too but in German.

      But your conclusion is much more interesting for me because you don't need another board.

      If I read right, the GPIO Output is only 3,3 Volts but normally the L298 works with 5 Volts, what do you think about a Transistor BC548 and two resistors to use 5Volts?

      Read you again

      Willi

      Delete
    3. Hi Willi
      In terms of SL4A, this is for Android handsets (maybe tablets as well). Sl4A stands for Scripting Language for Android. It's an Android application that allows you to write (relatively) simple scripts in languages like Python. This means you can get access to some of the Android APIs (e.g. location, battery, position sensor) without having to write full blown Android Java code. Here's a link:
      https://code.google.com/p/android-scripting/

      The L298 works fine with my Raspberry Pi and the 3.3V outputs. In terms of the transistors, I guess that this is an option. When I did research before making my Lego car, most of the advice I read was to use a motor controller board and the GPIO outputs.

      The robot is very cool! The Raspberry Pi foundation is going to launch a camera module soon so I may get one and add it to the car setup.

      Cheers, Paul

      Delete
  10. Hay Paul,

    thank`s for the link.

    It is possible to use a normal usb webcam on raspi, you`ve only to install and configure motion.

    It is easy.

    I would like the original raspicam too but I guess they`ve got a lot of problems about, cause it takes to long for my taste.

    So long

    Willi

    ReplyDelete
  11. Hello Paul,

    do you have a link of the schematic of your l298 shield.

    In my opinion a l298 needs two Voltages one for the logic 5V DC and one for the motorcircle.
    Because of this fact I think your shield has a stability on it for the 5Volt supply.
    And to look exactly I would like to study the schematic of the shield.

    Thanks

    Willi

    ReplyDelete
    Replies
    1. Hi Willi
      The only information I have is what is on the eBay site I bought it from (link below). If this is not enough then maybe you could contact the seller.

      http://www.ebay.co.uk/itm/Dual-H-Bridge-DC-Stepper-Motor-Drive-Controller-Board-Module-Arduino-L298N-236-/270969956726?pt=UK_BOI_Industrial_Automation_Control_ET&hash=item3f17116976&_uhb=1

      Cheers, Paul

      Delete
    2. Good evening Paul,

      yes it is how I thought, the 5 Volts are comming from the motorpower if the Jumpers are righ set.

      The 78M05 is responsible for the 5 Volt logic powersupply.

      Thanks

      Willi

      Delete
  12. hello Great Paul
    you do not need signal pwm in the code ???

    tell me please, android application is the same as that? http://www.wakdev.com/projets/roverpi/132-08-developpement-de-la-partie-client.html

    or you have another code, if yes can you send me the application ?
    in all cases thank you :)

    ReplyDelete
    Replies
    1. Hi Majdi,
      In terms of PWM, I didn't use this in the code. In fact, when I wrote the code I didn't know what PWM even was! In my approach the motor was either hard on or hard off. (This resulted in me needing to have the car in a very low gear).

      Since then I've learned a bit more. Someone has created a method to use Scratch on the RasPi to control the GPIO and this includes PWM. See here for more detail:
      http://cymplecy.wordpress.com/

      Using this I have now been able to use PWM with my Lego car. In a brief experiment I used Scratch with PWM to control the motor, causing the car to have smoother acceleration and for it to be in a slightly higher gear.

      I wrote the Android application myself (it using the SL4A scripting language for Android) and there is a full code listing on the page above. SL4A allows you to write simple scripts in languages like Python and make use of some of the Android APIs.

      Cheers, Paul

      Delete
  13. This comment has been removed by the author.

    ReplyDelete
  14. can you give me a link please i can'y find the code
    thanxs paul


    you use Ecplice ???

    ReplyDelete
  15. Hi Majdi
    What I do is not a full blown Android application (so a compiled apk file created in Eclipse) but rather a simple script.

    To create the scripts, you first download SL4A (Scripting Language for Android) to your handset and install it. You get it from here:
    https://code.google.com/p/android-scripting/

    This gives you a really great environment to create quick scripts that use some of the Android OS APIs (so location, the sensors etc).

    With SL4A installed on your device you can then choose to download a interpreter. I use Python, there are others like Ruby and PHP.

    Then to create a script you simply put a text file with a .py extension in the /sl4a/scripts directory. So for the handset code, this is all listed above (it's the final courier text code listing).

    To get this on the handset simply paste the code into a PC notepad and save as something like "handset_test_1.py". Connect the handset to your PC via USB as mass storage and copy the .py file to the /sl4a/scripts directory. Then run SL4A on the handset and select the script and run it.

    Cheers, Paul

    ReplyDelete

  16. i installed pydev in eclipse and write your code
    but i have a problem in (import android)

    ReplyDelete
  17. you can give me your e-mail, facebook or skype ?
    i like send you a video

    ReplyDelete
  18. Hi Majdi
    No need to use Eclipse. Just download and install SL4A on your Android handset and write the code in a simple text file. You can even edit the code on the device.

    Just Google SL4A and there's loads of information available.

    If you want to share a video, put it on YouTube and pass me a link in a comment.

    Cheers, Paul

    ReplyDelete
  19. i can't install sl4a_r6.apk
    i used windows 7
    what is the solution ??
    i used android virtual devices (eclipse)
    with software i can use to install SL4A
    what is Android Handset ?

    ReplyDelete
  20. Hi Majdi,
    I'm afraid I don't know much about Eclipse (I tried it but it was too slow and complicated for my simple needs. Perhaps you'll be able to find a forum that can help.

    A handset is another word for a phone. So when I say handset I mean a mobile phone. Mine is an HTC Desire HD.

    I've just installed the apk on my phone and transfer .py text files to it and run them through SL4A. Much quicker than Eclipse and writing Java code.

    Regards
    Paul

    ReplyDelete
  21. watch what i do
    please send me a video

    http://youtu.be/Fj6DjfkDhZU

    ReplyDelete
  22. Hopefully this will make it clear. I don't use Eclipse, I just write the code in a text file on my PC and transferit to my Android mobile phone to run it.

    http://youtu.be/S9bngAuTv-

    Cheers
    Paul

    ReplyDelete
  23. Try again
    http://www.youtube.com/watch?v=S9bngAuTv-o

    ReplyDelete
  24. hi paul
    please help me
    I write the code in a text file on my PC and transferit to my Android mobile phone (samsung S II) to run it, this error occurs
    ###########################
    Traceback (most recent call last):
    File "", line 4, in
    ImportError: No module named android
    ###########################
    u can send me the correctly code ?
    please upload your code in rapidshare.com and give me a link thanks

    ReplyDelete
  25. http://rapidshare.com/files/790837005/android_test.py

    The Python script is really, really simple. If you've got SL4A and the Python interpreter set up correctly then I'm not sure what is wrong.

    Assuming it still doesn't work when you use my code then I recommend you go on the SL4A forum and see if someone there can help.

    ReplyDelete
  26. i can't dowload this file
    you're disable the download option.

    ReplyDelete
  27. I don't know how to enable the file for download by others. Please let me know.

    ReplyDelete
  28. upload the file again in mediafire
    http://www.youtube.com/watch?v=cdfyb-pP1ik

    ReplyDelete
  29. Hi Majdi
    The code is listed here:

    #Start code
    import android

    droid = android.Android()

    name = droid.getInput("Hello!", "What is your name?")

    print name # name is a namedtuple
    droid.makeToast("Hello, %s" % name.result)

    #End code

    It really is very simple. I recommend you get on one of the SL4A forums or Stack Overload to ask for some help as I'm not sure what else I can do to help. This tutorial is useful:
    http://www.ibm.com/developerworks/opensource/library/mo-python-sl4a-1/

    ReplyDelete
  30. i have a another solution:
    *i have a android application for your car because i can add a webcam in your car
    what is your opinion ?

    ReplyDelete
  31. I like remote control cars and kids above 5 years also likes it. The presentation in above blog was awesome and might be useful to us for understanding the making of remote control cars.

    Lone Mountain Truck Leasing

    ReplyDelete
  32. Hi Paul,
    It was a really good tuto.
    Have you ever try with a stepper motor?

    ReplyDelete
  33. Hi,
    I've not tried with a stepper motor as yet but that's a good idea. It would be a good way to get more precision in to the steering of the car.

    I will add that to the list...

    Regards, Paul

    ReplyDelete
  34. Hi Paul,

    this is a really great example and i found what i want. but i have question. according to your implementation, is that possible to move the car while it is steering? and also can you please share the data sheet for which you have used to control the motors. my requirement is to steering the wheels while moving the car. simply i want to operate two motors at the same time.

    thank you
    chaithika.

    ReplyDelete
    Replies
    1. Hi Chaithika
      Yes it is possible to move the car and steer at the same time as the motors work independently.

      As I had it configured:
      -GPIO pins 11 and 13 controlled the first motor
      -GPIO pins 19 and 21 controlled the second motor

      So, if for example in your Python code you have set:

      11 high, 13 low, 19 high, 21 low

      ...then both motors will be running at the same time.

      The area of code that controls this is the "ControlAPairOfPins" routine.

      In terms of the motor controller, I don't have a data sheet but there's lots of information on the eBay site from which I bought it:
      http://www.ebay.co.uk/itm/Dual-H-Bridge-DC-Stepper-Motor-Drive-Controller-Board-Module-Arduino-L298N-236-/270969956726?pt=UK_BOI_Industrial_Automation_Control_ET&hash=item3f17116976&_uhb=1

      The chip is a L298N so you should be able to find a data sheet for this on the internet.

      Hope this helps

      Regards, Paul


      Delete
    2. Hi Paul,

      thank you for quick response. did u mean something like following code.

      -----
      elif MyChar == "r":
      ControlAPairOfPins("11","1","13","0")
      ControlAPairOfPins("19","1","21","0")
      print "move forward while steering to left"
      -----

      thank you
      chaithika

      Delete
    3. Hi Chaithika
      That's correct. The first command will get one motor turning and the second command will get the other motor turn. So if one controls motion and one controls steering you'll be able to steer and move at the same time.

      Regards, Paul

      Delete
  35. Thank you for this awesome post! Based on this I constructed my own RC Toy, well I need to get myself a battery and it will be more portable.

    http://www.youtube.com/watch?v=Zm5zKOmv3U4
    http://www.youtube.com/watch?v=Pymypps0L50

    ReplyDelete
    Replies
    1. Hi Michal,

      you have done a great work. will your car able to steering while moving.(are two motors work at the same time) ?

      thank you
      chaithika

      Delete
    2. Hi Michał
      Your car looks great. Much faster than mine!

      Thanks for the comment.

      Regards
      Paul

      Delete
    3. Hi Chaithika,

      Yes, they work independently.

      Regards,
      Michał

      Delete
  36. Hi Paul,
    I have used your first code above which you use to control the two lego motors connected to L298n board and Raspberry pi.

    have called this file gpiolego1.py. When I run the code I get the following error message,

    pi@raspberrypi ~ $ sudo python gpiolego1.py
    File "gpiolego1.py", line 17
    SyntaxError: Non-ASCII character '\xc2' in file gpiolego1.py on line 17, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
    pi@raspberrypi ~ $

    I do not understand what this error message means.
    I am using version 2.7.3 of Python.

    Regards,
    Mo.

    ReplyDelete
  37. Hi Mo
    Just counting the lines in my file, line 17 is:

    print "Controlling them pins"

    ...which is a pretty standard line of Python!

    Looking at this link:
    http://stackoverflow.com/questions/5228707/how-come-when-i-paste-
    this-in-vim-i-get-syntax-errors

    ...it appears to be something to do with space characters. Maybe a non-printing character has been created in your file through the copy and paste process. I recommend tidying up the code around this line, deleting all the indentation space characters before and after this line and then re-inserting them.

    Hope this helps.

    Cheers, Paul



    ReplyDelete
  38. Hi Paul,
    I am using your example above as a learning experience to control two lego motors via a L298n board, similar to your lego car above. I was also a big fan of technic lego back in the day.

    Firstly I want to be able to control a single motor. For the basic program I want the motor to turn a specified amount of time in one direction.

    All of my code works fine I think because I have print statements which print on the screen. But nothing happens to the motor.

    Pin 19 on RPi is connected to IN3 L298n board and Pin 21 connected to IN4. Pin 6 on RPi is connected to GND on the board. THe positive from battery is connected to VMS and the negative to GND on thje l298n board. I am using a external battery to power the lego motor.


    import RPi.GPIO as GPIO
    import time
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(19,GPIO.OUT)
    GPIO.setup(21,GPIO.OUT)

    print ('motor is turning')
    GPIO.output(19, True)
    GPIO.output(21, False)
    time.sleep(10)

    GPIO.output(19, False)
    GPIO.output(21, False)

    print ('Motor stopped')

    GPIO.cleanup()

    I would appreciate if you could help me getting a single motor to work.

    Thanks.
    Mo

    ReplyDelete
  39. Hi Mo,
    The code looks OK and your setup sounds OK. Here's what I'd do:

    1)Connect one of the L298 inputs to +3.3V (pin 1)and the other to pin 6 (0 Volts) and check if the motor turns. This will at least tell you if the motor controller works without using any code.

    2)Use an LED and resistor and connect them in series from pin 19 to 0V (use a bread board if you have one). This will tell you if the code works.

    So doing 1 and 2 above should give you some clues as to what is happening.

    ReplyDelete
  40. Hi Paul,
    I tried both of your methods above and the second one works. Therefore I think the code is correct and there is a problem with the L298 board.

    I also attached led/resistor using a bread board, one set to mortor A and the other led/resistor to motor B. When I ran the code nothing happened. I think the board is at fault.

    I will replace the board and see what happens.

    This is a very interesting project you did with a Technic Lego Car.
    I will keep the blog informed of my progress.
    I

    ReplyDelete
  41. Hi Paul,
    What is the differeence between these two L298n boards on ebay. Which board did you use?

    I currently have the following board,

    http://www.ebay.co.uk/itm/L298N-Stepper-DC-Motor-Dual-H-bridge-Driver-IC-Board-Controller-Regulator-Module-/271211608866

    I am thinking of buying the following board to replace my faulty board,

    http://www.ebay.co.uk/itm/Dual-H-Bridge-DC-Stepper-Motor-Drive-Controller-Board-Module-L298N-for-arduino-/251080674810

    I noticed the second has fewer ports where you can add the cables. Does this mean you can't control the speed of the motors etc. The direction is controlled by controlling the GPIO from the code.

    ReplyDelete
  42. Hi Mo
    This is the link to where I bought mine from:
    http://www.ebay.co.uk/itm/Dual-H-Bridge-DC-Stepper-Motor-Drive-Controller-Board-Module-Arduino-L298N-236-/270969956726?pt=UK_BOI_Industrial_Automation_Control_ET&hash=item3f17116976&_uhb=1

    I don't think that the board can do speed control. Someone has created an instance of Scratch for the Raspberry Pi that can do motor speed control using PWM (Pulse Width Modulation). See here:

    http://cymplecy.wordpress.com/

    I've not blogged about this but I've used this to do PWM control using my motor controller through software. You can set the motor speed to 10%, 20% etc and so I can have my Lego car in a higher gear, get smooth acceleration and a higher speed.

    You "write" the controlling code blocks in scratch but it calls upon an underlying Python script. Hence it would be easy to pull out the code segments that do PWM and replicate them.

    Cheers, Paul

    ReplyDelete
  43. I want to use arduino motor shield r3 with raspberry to control motors but i can't find any pinout of how to connect the same and use it with android.Any help

    ReplyDelete
  44. Hi Sid
    I'm afraid I've never used an Arduino of any type so can't advise. Does it use the same principles as the motor controller board I used? i.e. Logic levels from the RasPi control whether the motor is on or off. If this is the case then you probably just need to get the wiring right to get it to work (e.g. have a common earth).

    Cheers, Paul

    ReplyDelete
  45. Hi Paul,
    Thanks for your easy to follow tutorial. I bought the following starter kit,

    http://www.ebay.co.uk/itm/130944832051?ssPageName=STRK:MESELX:IT&_trksid=p3984.m1555.l2649

    It contained all the components required to get started.
    This is the first time that I got a PC to control something in the real world. I got the LED working. I have ordered myself a L298n board and will try controlling my Lego motors

    Thanks.

    ReplyDelete
  46. Hi Paul,
    based on your tutorial: http://www.youtube.com/watch?v=5K_Eyxi56tk

    If you are interested in my code answer me here :)

    thank you

    ReplyDelete
    Replies
    1. Hi RJ
      Your car looks really cool. I like the Android touch screen interface; much more complicated than mine!

      I'm not doing any projects like yours at the moment but if you could put the code on somewhere like GitHub I'll make a note of the link for future reference.

      Regards, Paul

      Delete
    2. Hello,

      this looks really great. I'm interested in your code :D

      Delete
  47. Hi Paul
    Just posting to say that this is an excellent article, have just got my pi mobile under the control my nexus 4, with a minimum headscratching, just the usual spurious characters from copy & pasting code, which forced me to actually understand the code.
    Have not used the original Lego chassis (the instructions are long lost), but have designed my own,
    I've also added a camera board with the intention of being able to drive it remotely, however I've not yet been able to get a stream going that is not without significant lag(approx 4 seconds), not much good taking avoiding action 4 seconds after impact.
    Thanks again for the great article.
    Richard

    ReplyDelete
  48. Hi Richard
    I'm glad article was useful for you. I've just got a camera board as well so it's a shame to hear about the delay. The HD video capture is excellent and it's fun for time elapse photography but the delay makes it poor for anything "real time".

    Regards, Paul

    ReplyDelete
  49. Paul,

    Thanks so much for posting this. I had no trouble following your instructions, and (once I'd sourced a L298N and a few other bits and bobs) had a very enjoyable couple of hours putting it all together.

    My wife obviously thinks I'm a bit crazy to appear so pleased to make a Lego motor spin one way and then the other, but this is what my pair of Lego motors have been waiting for! My 3 and a half year old will be amazed.

    Now all I need to do is decide what I'm going to build....

    Ade

    ReplyDelete
  50. this is one of the best blog i have ever seenlink wheel seo

    ReplyDelete
  51. Interesting and useful information that you have provided here on your post.

    Car dvd player & BMW GPS DVD player

    ReplyDelete
  52. Interesting and useful information that you have provided here on your post

    4ch DVR kit & Holden DVD player


    ReplyDelete
  53. Some great tips here even for those of us who've been banging out the posts for a while now. Mixing up the size and style of the posts is a very good point - keeps things more interesting. X.

    SEO

    ReplyDelete
  54. Amazing post ! I like it . Thanks for sharing this topics . For details lego storage bag .

    ReplyDelete
  55. I like lego and it is amazing to see a car on it.Lately i am fixing a old car and i change the transmission ,gear and other basic things in the car and it is almost done i can wait to see it working really well.

    ReplyDelete
  56. What kind of gear wheels are you using for the rear-wheel drive?

    ReplyDelete
    Replies
    1. Hi Baumi
      The original car had a differential on it. From this site:
      http://www.spareblocks.com/buy_replacement_lego_cogs_string_pulley_wheels.html

      ...it's the "Lego Technic differential casing - item no. Z19".

      It also uses 4 of the "Small diff cog - item no. Z18" from the listed above.

      Cheers
      Paul

      Delete
  57. I am very much pleased with the contents you have mentioned. I enjoyed every little bit part of it. It contains truly information. I want to thank you for this informative read; I really appreciate sharing this great.
    BSD

    ReplyDelete
  58. Hello Paul. Which Versions of SL4A and Python did you use? Can You post the APK-Files here. I tried "SL4A V6" and "Python3 for Android V5" and I do get several Syntax-Errors in the lines of print... I removed them but I still get an syntax-error in the Line "except Exception, err".

    thanks,

    Marco

    ReplyDelete
  59. We repair and replace ABS sensors, abs ring, abs pump for all makes and models in Reading, United Kingdom. We also

    provide free collection and Delivery service from your home or place of work.

    ReplyDelete
  60. HOW TO CREATE ACCOUNT IN BINANCE PLATFORM TO MAKE ANY TRANSACTION?

    Go to Binance Support Number +1 (856)-462-1192 and go to enroll on the upper right of the page. Enter your email address, mystery word, and referral number (you can use yur sidekick's referral code), check your Binance account through customer support gathering. After you have completed all methods then you can make any trade like trading, exchange or you can make in like manner remote portions.

    For more data visit us:- https://www.thecustomercentre.com/webexchanges/binance-support-number/

    ReplyDelete
  61. Is it true that you are not ready to expel the check mistake from Coinbase?
    In the event that you are ignorant of the check procedure and experiencing mistakes while actualizing the one at that point, you should take productive help from the group of executives who are accessible throughout the day and night to go to the client's inquiry. You should simply dial Coinbase Support Number+1 (856) 462-1192 without toll number and dispose of every one of your issues and issues in a jiffy. Connect and fix your set issue. Coinbase updates is a prerequisite, along these lines, you can take help while following the establishment procedure. https://www.thecustomercentre.com/webexchanges/coinbase-support-number/

    ReplyDelete
  62. This comment has been removed by the author.

    ReplyDelete
  63. Like!! I blog quite often and I genuinely thank you for your information. The article has truly peaked my interest.
    laboratory equipments

    ReplyDelete
  64. I am really impress with you for the selecting of new and unique topic and also well written article on it. Thanks for sharing with us.
    Student Visa Australia
    Skilled Visa Australia
    482 Visa Australia

    ReplyDelete
  65. Great Information sharing I am very happy to read this article. Thanks for giving us go through info. I appreciate your work.
    Best Fertility Centre In Hyderabad

    ReplyDelete
  66. Very nice blog !! If someone is looking for the carpet and duct and tile cleaning services. You can contact the most experienced and skilled cleaners. syringe filters

    ReplyDelete
  67. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    pest control services in Delhi
    pest control Gurgaon

    ReplyDelete
  68. Wow, I'm very impressed with the words, and it looks very good. All blog which you write has a knowledgeable content and many beginers learn many things from your writing. As I aslo write blog in which we provide information and services for any type of problem related to Norton Antivirus. If you face any type of problem related to Norton Antivirus you can use norton.com/setup or can visit our website.

    ReplyDelete
  69. i have just read your complete blog so i can say this is literally a informative content for me and also many peoples.so please keep posting this kind of content because its helps beginers and experienced also. we are also providing services for Norton Product key if you have issues to setup Norton Product key then you can visit our website or just call on toll free number +1-888-266-1754 our customer support executive always available to pick your call
    Norton Product key key

    ReplyDelete
  70. Is there a phone number for Bitcoin
    Is your bitcoin withdrawal transaction pending? Are you unaware of the methods and techniques to deal with this error? If yes, you can dial bitcoin toll-free number which is all the time working and users can contact anytime to get rid of the issues. The team is always there to help you out from every difficult situation. With the experts, you don’t have to worry and you can get fast and pertinent solutions in no time. The team is always punctual and ready to erase all sort of problems that occur and disturb the user’s work.

    bitcoin Number
    bitcoin Support Number
    bitcoin Support phone Number
    bitcoin phone Number
    bitcoin Customer Support Number
    bitcoin Customer Service Number
    bitcoin Customer care Number
    bitcoin Support phone Number
    bitcoin Support Number
    bitcoin Toll Free
    bitcoin help desk
    bitcoin wallet support phone number
    bitcoin phone support

    https://www.cryptocurrencyphonesupport.com/

    https://www.cryptocurrencyphonesupport.com/bitcoin-customer-support-phone-number/

    ReplyDelete
  71. What countries does Binance support
    Is your binance bitcoin withdrawal transaction pending? Are you unaware of the methods and techniques to deal with this error? If yes, you can dial binance toll-free number which is all the time working and users can contact anytime to get rid of the issues. The team is always there to help you out from every difficult situation. With the experts, you don’t have to worry and you can get fast and pertinent solutions in no time. The team is always punctual and ready to erase all sort of problems that occur and disturb the user’s work.
    binance Number
    binance Support Number
    binance Support phone Number
    binance phone Number
    binance Customer Support Number
    binance Customer Service Number
    binance Customer care Number
    binance Support phone Number
    binance Support Number
    binance Toll Free
    binance help desk
    binance wallet support phone number
    binance phone support

    https://www.blockchainphonesupport.com/exchange-binance/

    ReplyDelete
  72. Social Media Advertising is a must-have in your bucket if you really want to reach out to a targeted audience and that too real quick. And what is probably the best about it, that you get organic leads through it, no money no facade, only loyal following with little input and the right strategy from your side.

    ReplyDelete
  73. Thanks and I have a dandy proposal: How Much Is Home Renovation residential renovation contractors

    ReplyDelete
  74. Great and that i have a nifty provide: How Much Home Renovation Cost average cost to remodel a house

    ReplyDelete