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
    About the element14 Community
  • 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 417 subscribers
  • Views 3178 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
  • wallarug
    0 wallarug over 13 years ago in reply to evan.stoddard

    I need to set the PWM frequency on my Ardunio to 65000Hz.  I am using PWM pins 5 and 6 (which is a good start) but I can't seem to find a conclusive way to increase the clock to that frequency.  Help please.

    • 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

    www.arduino.cc/playground/Code/PwmFrequency. Come on dude use your googlefu ;)

    • 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 was on that page when I wrote the previous post.  I tried that in IDE but that did not work.  The setPwmFrequency(#, #) does not work.

     

    EDIT:

     

    I am using Pins (6, 11) and Pins (5, 3) becasue the PWM did not work when the channels were set to LOW.

     

    The 'Clock' of Channels 6 and 5 are the same (so I have discovered).

     

    I am using LEDs to test the code and PWM.  I think this could be the problem.  The LEDs don't want to 'dim'.  I have the same problem when I am running light shows durring musicals.  I think I will test with some transistors and motors later, they might respond better to the PWM.

     

    BTW: Can you send the PWM directly to the motors?  From what I know, it is just turning a switch on and off very very fast and the Interpting of the singnal is done by the Ardunio ATMEGA.

              Can you confirm this information?

    • 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

    Where did you put it.  In the loop or set up

    • 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

    /*

    * Robot Motor Controller script with PWM speed control

    */

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

    int motorL[] = {3, 5};

    int motorR[] = {11, 6};

    int ledPin = 13;

    int Byte1 = 0;  //for incoming serial data

    int Byte2 = 0;  //for incoming serial data

    int Byte3 = 0;  //for incoming serial data

    int motor_a = 0;

    int motor_b = 0;

    int dir_y = 0;

    int motor_a_prev = 0;

    int motor_b_prev = 0;

     

     

     

     

    void setup() {

    Serial.begin(9600);  // opens serial port, sets data rate at 9600bps

    int i;

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

    pinMode(motorL[i], OUTPUT);

    pinMode(motorR[i], OUTPUT);

    pinMode(ledPin, OUTPUT);

    }

     

     

    }

     

     

    void loop() {

    digitalWrite(ledPin, HIGH);

     

     

    if(Serial.available()==3)

    {

      Byte1 = Serial.read(); // Incoming data from Serial connection

      motor_a = int(Byte1 & 0x0F);

      Byte2 = Serial.read(); // Incoming data from Serial connection

      motor_b = int(Byte2 & 0x0F);

      Byte3 = Serial.read(); // Incoming data from Serial connection

      dir_y = int(Byte3 & 0x0F);

     

      if (dir_y == 2) { //Motor Backwards

      digitalWrite(motorL[0], HIGH);

      digitalWrite(motorL[1], LOW);

      digitalWrite(motorR[0], HIGH);

      digitalWrite(motorR[1], LOW);

      analogWrite(3, motor_a);

      analogWrite(11, motor_b);

      }

      else if (dir_y == 1) {  //Motor Forwards and Single motor Turning

      digitalWrite(motorL[0], LOW);

      digitalWrite(motorL[1], HIGH);

      digitalWrite(motorR[0], LOW);

      digitalWrite(motorR[1], HIGH);

      analogWrite(5, motor_a);

      analogWrite(6, motor_b);

      }

     

    }

    else: {

     

    }

    Code so far.

     

    I put the command in the Setup()

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

    ValueError: chr() arg not in range(256)

    How can I fix this?  The numbers that I am producing ARE in the range of 0-255.  (does that mean including 0? and 255?)

     

    This is a problem in the TCP client which is sending the data.

    • 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

    Look at the tutorial again and instead of set up put it in the loop void

    • 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 should have mentioned that the above error was produce by python.  The PWM frequency problem has been solved.  I Accually just needed to ad some 470R Resistors into the circuit and then everything worked fine.

    The chr() command is in the python script and seems to be the only command that the Ardunio will interpret and then 'push' to the PWM channels.  I tried using int() and str() but they where not interpereted by the Ardunio once sent via the TCP.  I am going to try and divid by 16 in python and then Multiply by 16 in Ardunio.  This should fix the issue.  Would I put the 196 inside or outside of these brackets?

     

    if(Serial.available()==3)

    {

      Byte1 = Serial.read(); // Incoming data from Serial connection

      motor_a = int(Byte1);

      Byte2 = Serial.read(); // Incoming data from Serial connection

      motor_b = int(Byte2);

      Byte3 = Serial.read(); // Incoming data from Serial connection

      dir_y = int(Byte3);

    • 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

    inside the brackets and i have no idea about the python script.  I dont know python that well

    • 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

    Don't worry, I found the problem ( I think).  There was a double-up in the rules and this casued the values to multiple by 2.  This caused the values to fall outside of the range of 0 -256.  I solved the prblem by re-writing ALL of the rules so that each specific case was solved and there was NO double ups.  This didn't take to long but it was was well worth the fix.

     

    No issues with python or Ardunio any more.  I will see if I can upload something here later to show you how far it has come.

     

    LED issue was solved (I think I said this before) and now has 2k2 transistors in place of 470R, which means that You can see more different when PWMing.

     

    I'll get back here if/when I have more problems, but for now I think everything is working correctly.

     

    Thanks for all your help with the Arduino.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
<>
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 © 2026 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.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube