element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Python to Arduino to Motors...
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Verified Answer
  • Replies 22 replies
  • Subscribers 402 subscribers
  • Views 2465 views
  • Users 0 members are here
  • freetronics
  • immediate
  • raspberry
  • c
  • python
  • help
  • pi
  • pwm
  • support
  • control
  • rasppi
  • rpi
  • c++
  • motor
  • arduino
  • varible
Related

Python to Arduino to Motors...

wallarug
wallarug over 13 years ago

I have two reversable 12volt motors that I would like to control through PWM.  I want the speed to be constantly updated by the python code that will be sent through a TCP client-server.  I have the python piece of code working very well. I need some help with the Arduino Sketch please.  I have all the other pieces of code working except the Arduino Sketch.

 

I know everything about the hardware required (H-bridge, etc) but I need help with the sketch.

 

 

This is the Joystick Control and TCP client:

 

 

[code]import pygame

import socket

import sys

import os

pygame.init()

j = pygame.joystick.Joystick(0)

j.init()

 

print 'Initialized Joystick : %s' % j.get_name()

username = os.name

if username == "nt":

    username = "Windows"

print "Welcome commander, you are using " + username

 

 

 

 

a = 0

b = 0

aa = a

bb = b

 

 

 

 

 

 

 

 

i = raw_input("What do you want to detect?")

while i == "button":

    pygame.event.pump()

    #print j.get_axis(1)

    if j.get_button(1):

        print "Left"

    if j.get_button(0):

        print "Kill"

    if j.get_button(2):

        print "Right"

while i == "pos":

    pygame.event.pump()

    y = j.get_axis(1)   ######################################

    y = round(y,2)      # Increase to (x, 12) when using PWM!#

    x = j.get_axis(0)   #  @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@   #

    x = round(x,2)      # Increase to (y, 12) when using PWM!#

    z = j.get_axis(2)   ######################################

    z = round(z,1)

    #print(x,y,z)

  

    if y < 0:          ############################

        y = abs(y)     #New Y-axes inversion code!#

    elif y > 0:        ############################

        y = y*-1

 

 

#############################################

# Formulas for working out the speed of the #

# motor in certain areas of the Joystick!   #

#############################################

 

 

    f = 1

    sy = f*(y)

    sx = f*(x)

   

 

 

#############################################

## Whenever the ROBOT is moving and the     #

##  Co-ordinates are not (0,0)              #

#############################################

 

 

                               

    if x != 0 and y != 0:      

        sy = abs(sy)                    #######

        if y > abs(x) and y > 0:        # Top!#

                                        ############

            if -1 < x < 0:              # Top Left!#

                                        ############################################

                c = abs(x)              # Convert to percentage and positive value!#

                a = (sy) - (c)          ############################################

                b = (sy)

                                        #############

            elif 0 < x < 1:             # Top Right!#

                                        ############################################

                d = abs(x)              # Convert to percentage and positive value!#

                b = (sy) - (d)          ############################################

                a = (sy)

            else:

                a = abs(x)

                b = abs(x)

 

 

                                        ##########

        elif y < -abs(x) and y < 0:     # Bottom!#

                                        ###############

            if -1 < x < 0:              # Bottom Left!#

                                        ############################################

                c = abs(x)              # Convert to percentage and positive value!#

                a = (sy) - (c)          ############################################

                b = (sy)

                                        ################

            elif 0 < x < 1:             # Bottom Right!#

                                        ############################################

                d = abs(x)              # Convert to percentage and positive value!#

                b = (sy) - (d)          ############################################

                a = (sy)

            else:                       ############################################

                a = abs(sy)             # So that values "a" and "b" are regonised #

                b = abs(sy)             #  by python reader (I had problems)!      #

                                        ############################################

 

 

 

 

                                           

#################################

# Special formula for when you  #

#   leave the "allowed" area    #

#################################

 

 

        elif y < abs(x) and y > -abs(x): 

            if x < 0:

                b = abs(x)

                a = 0

            elif x > 0:

                a = abs(x)

                b = 0

            else:

                a = 0

                b = 0

 

 

 

 

 

 

##################################

# Special Formula for all values #

#  on the x-axis for immediate   #

#    turning.                    #

##################################

 

 

    elif y == 0:

        if x < 0:

            a = 0

            b = abs(sx)

        elif x > 0:

            a = abs(sx)

            b = 0

        else:

            a = 0

            b = 0

 

 

 

 

 

 

#######################################

#  Anything else that is not defined  #

#   (Only when x and y = 0)           #

#######################################

 

 

    elif x == 0:

        a = abs(sy)

        b = abs(sy)

 

 

    else:

        a = 0

        b = 0

       

              

 

 

######################################

### PWM convetion for AnalogueWrite()#

######################################

 

 

    PWM = 255

    a = PWM*a

    a = round(a,0)

    a = int(a)

    b = PWM*b

    b = round(b,0)

    b = int(b)

 

 

 

 

 

 

 

 

####################################

# Printing Output - Only used in   #

# development of Joystick Control. #

####################################

 

 

    #print (a,b)

 

 

########################

# TCP client is below. #

########################

 

 

    data = (a,b)

    HOST, PORT = "192.168.12.12", 9999

    #HOST2, PORT2 = "10.88.112.174", 9998 # Change to server when necessary

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect((HOST, PORT))              ## CIAN HAS CHANGED!!##

    ##sock.sendall(str(data) + "\n")

    ##print "Sent:     {}".format(data)

 

 

    if a != aa or b != bb:

        sock.sendall(str(data) + "\n")

        print "Sent:     {}".format(data)

##    elif a == aa and :

##        print (int(a),int(b))

 

 

    aa = a

    bb = b

 

 

 

 

#####################################################

##@@@@@@@@@@@@@@@@@@@@@@ END @@@@@@@@@@@@@@@@@@@@@ ##

#####################################################[/code]

 

 

This seems to work ok, I am working on getting the TCP Client quicker - so that is a bit of a mess right here.

 

 

This is how far I have gotten with the Arduino Sketch:

 

 

[code]/*

* Robot Motor Controller script with PWM speed control

*/

//---------------------- Motors

int motorL[] = {6, 7};

int motorR[] = {8, 9};

int ledPin = 13;

int motor_a = 0;

int motor_b = 0;

int dir_y = 5;

 

 

 

 

void setup() {

Serial.begin(9600);

int i;

for(i = 0; i < 2; i++){

pinMode(motorL[i], OUTPUT);

pinMode(motorR[i], OUTPUT);

pinMode(ledPin, OUTPUT);

}

 

 

}

 

 

void loop() {

drive_forward(); {

digitalWrite(motorL[0], HIGH);

digitalWrite(motorL[1], LOW);

digitalWrite(motorR[0], HIGH);

digitalWrite(motorR[1], LOW);

analogWrite(9, motor_a);

analogWrite(6, motor_b);

}

drive_backwards(); {

digitalWrite(motorL[0], LOW);

digitalWrite(motorL[1], HIGH);

digitalWrite(motorR[0], LOW);

digitalWrite(motorR[1], HIGH);

analogWrite(9, motor_a);

analogWrite(6, motor_b);

}

}

 

 

void if(y < 0) drive_foreward()

 

 

void if(y > 0) drive_backwards()[/code]

 

 

No surprise that it doesn't work.  I want it to read three values from the Python script which are the speed of the left motor (defined as "a"), speed of the right motor (defined as "b"), direction of motor (which is defined as "y" - when it is <0 it goes backwards or >0 goes forward).

 

 

For the [b]varying speed controls[/b], I will be using PWM (values between 0 -> 255) which uses the "analogWrite(Pin, value)" Syntax.  These values will be changing via the "a" and "b" values from the python script.

 

 

Is there anyway that you can help me with this.  I am really struggling.

 

 

Thanks in advance to anyone who can help.

  • Sign in to reply
  • Cancel
Parents
  • evan.stoddard
    0 evan.stoddard over 13 years ago

    First off, are you sure that the data is being sent to the arduino.  This is usually one of the biggest problems.  To do this we can send the data in the vars tobrough serial to make sure they are populated and recieveing the data from the python script.  I'm assuming you know how to do that.  If not use the samples in the arduino ide.  Check that first and let me know.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • wallarug
    0 wallarug over 13 years ago in reply to evan.stoddard

    I can't send the data to nothing.  I thought you needed to write the sketch first and then send data?

     

    I have tested through a TCP client/server and successfully sent the data to the host computer.  I cannot do anything else with that data though.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • evan.stoddard
    0 evan.stoddard over 13 years ago in reply to wallarug

    So how are you going to get data to the arduino.  I understand the whole tcp client and server but is the arduino going to have an ethernet shield are will it be plugged into the client or server through usb?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • wallarug
    0 wallarug over 13 years ago in reply to evan.stoddard

    client - TCP - server - USB - Ardunio.

     

    I am using a raspberry Pi as the server

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • evan.stoddard
    0 evan.stoddard over 13 years ago in reply to wallarug

    On the server first check to make sure that you are able to send data over to the arduino using python.  Make a sketch that repeats what has just been sent to it.

     

    Define a variable as recievedData and populate it with serial data then in then:

    -void loop() {

     

    serialWrite(recievedData);

    }

     

    If you are recieving data then you know you are good.  Next check to make sure that the math is being done right and operating the motors correctly.  To test this just put data into the variables with in the code instead of trying to send them.  This way you know that the math and motors work properly.   If thats all good then look at your python script and make sure that its sending serial commands to the arduino and that you are recieving those commands.  You should not only send those variables to the mathmatical operations and motor operation code but also write those to serial so you can view whats going on in the serial monitor.  Sorry if I'm not a huge help, I'm somewhat new to this and I don't really know python.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • evan.stoddard
    0 evan.stoddard over 13 years ago in reply to evan.stoddard

    Plus I don't think this is going to work:

     

    void if(y < 0) drive_foreward()

     

     

    void if(y > 0) drive_backwards()

     

    It should be like this:

     

     

     

    void loop() {

    if (y < 0) {

    digitalWrite(motorL[0], HIGH);

    digitalWrite(motorL[1], LOW);

    digitalWrite(motorR[0], HIGH);

    digitalWrite(motorR[1], LOW);

    analogWrite(9, motor_a);

    analogWrite(6, motor_b);

    }

    else if (y > 0) {

     

    digitalWrite(motorL[0], LOW);

    digitalWrite(motorL[1], HIGH);

    digitalWrite(motorR[0], LOW);

    digitalWrite(motorR[1], HIGH);

    analogWrite(9, motor_a);

    analogWrite(6, motor_b);

    }

    }

     

    That should work. 

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Reject Answer
    • Cancel
  • wallarug
    0 wallarug over 13 years ago in reply to evan.stoddard

    Thanks Evan,

     

    I will be using this example: http://www.aonsquared.co.uk/the_dark_pi_rises code as the bases for SENDING the data.

     

    My code is cleaner than his and also he is not changing the speed.

     

    I will test your example above but I would like to know if I need the setup() command or any others in the above example?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Reply
  • wallarug
    0 wallarug over 13 years ago in reply to evan.stoddard

    Thanks Evan,

     

    I will be using this example: http://www.aonsquared.co.uk/the_dark_pi_rises code as the bases for SENDING the data.

     

    My code is cleaner than his and also he is not changing the speed.

     

    I will test your example above but I would like to know if I need the setup() command or any others in the above example?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube