• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

Control servo motor with python in a Raspberry pi zero

Q&A Forum › Control servo motor with python in a Raspberry pi zero
0 Vote Up Vote Down
Bruno Santos asked 5 years ago

Hello,

i have a project of mine with a Telegram-Bot and the control of a ServoMotor.

However, my code in Python for the ServoMotor work only 1x time, then i need to restart the RPi Zero to work again…

Can someone take a look and help me with it.

https://pastebin.com/9KQEiKnL

10 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi Bruno.
In your code, you have the SetAngle() function that changes the duty cycle. You have defined the function but it is never called. That’s the problem. Also, you don’t have any part of your code that sets the angle variable.
Regards,
Sara

0 Vote Up Vote Down
Bruno Santos answered 5 years ago

Hello Sara,
thank you for your answer.
I was calling this function in another script with the Telegram-Bot:

import movexy

...

elif command.startswith('/move'):
        try:
            angle=command[6:]
            movexy.SetAngle(angle)
            bot.sendMessage(chat_id, angle + " enviado.")
        except:
            bot.sendMessage(chat_id, "rotacao " + angle + " falhou!")
            logger.error(traceback.format_exc())
            pass

And the works! But only one time… Then stops working, needed to restart the script or the RPi…

0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi Bruno.
To keep your code running, I think you need to add a while True statement somewhere so that the code keeps running unless you have some kind of callback functions that run automatically when some event happens.
Without further details, it is very difficult to find out what might be wrong.
Regards,
Sara

0 Vote Up Vote Down
Bruno Santos answered 5 years ago

Hi,

The while statement I have in this script… https://pastebin.com/XvuLQvYa
It is the script for my telegram bot… As I call the movexy.py in the command ‘/move’ + the angle.
Do you think that the while statement should be also in the movexy.py script?

0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi.
In that case, you probably don’t need another while statement.
After sending a command, if you send a different command afterwards, what happens?
 

0 Vote Up Vote Down
Bruno Santos answered 5 years ago

Hello,
All the other commands are working well… After the RPI start I receive a SMS saying that it is on! Then, by the first “/move 90” command, it will move to the position. By the second command it won’t move… But I still can send other command and the RPI will answer.
To do again the move, I need to reboot the RPI… That’s why I think that something is missing in the script movexy.py by I can’t figure it out.
For me it is the first time that I work with servo motors.. .
 

0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi Bruno.
Have you found out the problem?
Can you share the movexy function? I can’t access the function as it was removed from pastebin.
Regards,
Sara

0 Vote Up Vote Down
Bruno Santos answered 5 years ago

Hi,
Sorry for taking so long…
You can found the code at the link.
https://pastebin.com/dsNDFndV

0 Vote Up Vote Down
Sara Santos Staff answered 5 years ago

Hi Bruno.
I’m not sure, but I think your problem may be due the following lines:

finally:
    pwm.stop()
    GPIO.cleanup()

After moving the motor, you stop PWM. The next time you try to control the motor you won’t have PWM initialized.

So, I suggest that you move these lines to the setAngle() function:

pwm=GPIO.PWM(03,50)
pwm.start(0)

So, you’ll have something as follows:

GPIO.setmode(GPIO.BOARD)
GPIO.setup(03, GPIO.OUT)
GPIO.setwarnings(False)

angle=90

def SetAngle(angle):
    pwm=GPIO.PWM(03,50)
    pwm.start(0)
    try:
        angle = int(angle)
        duty = angle / 18 + 2
        GPIO.output(03, True)
        pwm.ChangeDutyCycle(duty)
        sleep(1)
        GPIO.output(03, False)
        pwm.ChangeDutyCycle(0)
    except:
        logger.error(traceback.format_exc())
        pass
    finally:
        pwm.stop()
        GPIO.cleanup()

Can you try this and see if it solves your problem?

I’m sorry for taking so long to get back to you.

Regards,

Sara

1 Vote Up Vote Down
Bruno Santos answered 5 years ago

Hello Sara,
Thank you for the answer and sorry for the delay feedback.

You were right! With your tip I was able to put it to work.

Than you a lot. You can see the changed code:

import traceback
import RPi.GPIO as GPIO
from time import sleep
import logging
logging.basicConfig(filename='./erros_Telegram.log', level=logging.ERROR,
format='%(asctime)s %(levelname)s &(name)s %(message)s')
logger=logging.getLogger(__name__)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(03, GPIO.OUT)
GPIO.setwarnings(False)

angle=0
def SetAngle(angle):
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(03, GPIO.OUT)
    pwm=GPIO.PWM(03,05)
    pwm.start(0)
    try:
        angle = int(angle)
        print(angle)
        duty = angle / 18 + 2
        GPIO.output(03, True)
        pwm.ChangeDutyCycle(duty)
        sleep(1)
        GPIO.output(03, False)
        pwm.ChangeDutyCycle(0)
        print("done")
    except:
        logger.error(traceback.format_exc())
        pass
    finally:
        pwm.stop()
        GPIO.cleanup()
SetAngle(angle)

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.