rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 6:13 pm

I have a script of python which is about object detection once a particular class is identified the servo motor should work Iam using object detection using tensorflow and opencv , basically scripts works by opening the picamera and detecting objects

code for python script and servo give below :(link to entire code https://github.com/aswinr22/waste-model ... camera2.py)

Code: Select all

(boxes, scores, classes, num) = sess.run(
            [detection_boxes, detection_scores, detection_classes, num_detections],
            feed_dict={image_tensor: frame_expanded})
        # Draw the results of the detection (aka 'visulaize the results')
        vis_util.visualize_boxes_and_labels_on_image_array(
            frame,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8,
            min_score_thresh=0.40)

        for i in range (classes.size): # here is my classes id is retrieved
            if(classes[0][i] == 2 and scores[0][i]>0.5): # this is my condition , if class id =2 then servo should workThis is the servo code:

Code: Select all

import RPi.GPIO as GPIO
import time

servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)

p = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz
p.start(2.5) # Initialization
try:

    p.ChangeDutyCycle(5)
    time.sleep(4)
    p.ChangeDutyCycle(10)
    time.sleep(4)
except KeyboardInterrupt:
  p.stop()
  GPIO.cleanup()
  

How to combine these both code to work the servo whenever my class id =2 detected

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 6:55 pm

You could add a function to your code to do the servo moves. Instead of a function, I prefer to do things within a class - avoids the whole global rabbit hole. Below is a sample of what I mean (not tested). If you don't want to use the class, just initialize the servo pin somewhere in your camera code and place the servo motion control in a function - have fun with the globals if you do that ;-).

Code: Select all

# servo_control.py

import RPi.GPIO as GPIO
import time


class ServoControl:
    def __init__(self):
        self.servoPIN = 17
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.servoPIN, GPIO.OUT)
        self.p = GPIO.PWM(self.servoPIN, 50)  # GPIO 17 for PWM with 50Hz

    def move_servo(self):
        self.p.start(2.5)  # Initialization
        try:

            self.p.ChangeDutyCycle(5)
            time.sleep(4)
            self.p.ChangeDutyCycle(10)
            time.sleep(4)
        except KeyboardInterrupt:
            self.p.stop()
            GPIO.cleanup()


"""
To use this class:


from servo_control import ServoControl

# instantiate the class
the_servo_control = ServoControl()

# move the servo anytime you need to with this call
the_servo_control.move_servo()
"""

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 7:16 pm

yes i given the function inside for loop and all pin setups outside the loop but its gives me a run time error "Runtime error A PWM object already exists for this GPIO channel"

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 7:21 pm

The PWM object, in your case p

Code: Select all

p = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz
Should be established outside of the loop - it should only be done once. If that is what you are doing, perhaps if you provide the code that includes the servo integration in the camera, that might help for others to try and understand how things are configured.

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 8:08 pm

This is what i done , when i hit run it still running didn't produced the output

Code: Select all

	servoPIN = 17
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(servoPIN, GPIO.OUT)
        p = GPIO.PWM(servoPIN, 50)
        for i in range (classes.size):
            if(classes[0][i] == 2 and scores[0][i]>0.5):
              
             def move_servo():
                p.start(2.5)  # Initialization
                try:

                  p.ChangeDutyCycle(5)
                  time.sleep(4)
                  p.ChangeDutyCycle(10)
                  time.sleep(4)
                except KeyboardInterrupt:
                    p.stop()
                    GPIO.cleanup()
            move_servo()


User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 8:17 pm

I reordered your code somewhat. Having the function defined within the loop created a new PWM instance with each iteratation.

Code: Select all

import time

def move_servo(p):
    p.start(2.5)  # Initialization
    try:
        p.ChangeDutyCycle(5)
        time.sleep(4)
        p.ChangeDutyCycle(10)
        time.sleep(4)
    except KeyboardInterrupt:
        p.stop()


servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)

# p is instantiated once
p = GPIO.PWM(servoPIN, 50)

for i in range(classes.size):
    if classes[0][i] == 2 and scores[0][i] > 0.5:
        # pass p into the function
        move_servo(p)

# cliean up the gpio right before exiting the program.
GPIO.cleanup()

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 8:30 pm

No way its still p = GPIO.PWM(servoPIN, 50)
RuntimeError: A PWM object already exists for this GPIO channel

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Sun May 12, 2019 8:47 pm

I just ran the following code on my RPi.

Code: Select all

import time
import RPi.GPIO as GPIO

def move_servo(p):
    p.start(2.5)  # Initialization
    try:
        p.ChangeDutyCycle(5)
        time.sleep(4)
        p.ChangeDutyCycle(10)
        time.sleep(4)
    except KeyboardInterrupt:
        p.stop()



servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)

# p is instantiated once
p = GPIO.PWM(servoPIN, 50)

for i in range(2):
    if True:
        # pass p into the function
        move_servo(p)

# cliean up the gpio right before exiting the program.
GPIO.cleanup()
I removed

Code: Select all

if classes[0][i] == 2 and scores[0][i] > 0.5:
and substituted with:

Code: Select all

If True:
just to make my life simpler. Runs here without issue. Does this run for you? FYI - I have an LED connected and not a servo, but that should not make difference.

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Mon May 13, 2019 12:59 am

yes i ran your code it worked but when i ran it on my object detection script it shown the previous error
link to object detection script https://github.com/aswinr22/waste-model ... camera2.py (line 140-165)

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Mon May 13, 2019 1:55 am

The indentation is not correct, and when I run the file through PyCharm inspection there are 4 errors after I fixed the indentation. The move function should probably be moved to the top of your file and the GPIO.cleanup should probably be delayed until the end of your program.

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Mon May 13, 2019 2:02 am

never mind the indentation cuz i pasted it wrongly , indented perfectly in my pi

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Mon May 13, 2019 1:22 pm

The camera2.py script has several other errors in addition to the indentation issues that need to be addressed. In addition,the code possesses no cohesive structure, making it difficult to read and debug. Here are my suggestions:
1. Take a look at this article https://dbader.org/blog/how-to-structur ... n-programson structuring a Python program and refactor your program.
2. Using an IDE like Thonny (included with Raspbian), debug your program.http://innovaker.com/thonny-ide-debuggi ... t-projects
a. Look at the exception stack being generated to give you an idea of what lines of code brought the code to the exception.
b. Use the debugger to set breakpoints and/or single step through your code to find the error.

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Tue May 14, 2019 6:14 pm

Okay thank you, but servo code alone works perfectly does that mean there is something hapenning wrong when the servo code inside the for loop?

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Tue May 14, 2019 6:35 pm

Most likely. Put a breakpoint where the PWM mode is being set, and see if it occurs more than once, that is how you are getting the error.

rahulnpr18
Posts: 8
Joined: Sun May 12, 2019 6:08 pm

Re: How to run a servo motor if a particular condition is satisfied

Thu May 16, 2019 5:53 pm

The print statement inside if condition instead of servo code runs infinitely , maybe that's why the motor troubles isn't? then how can i rewrite to print only once .?
Untitled.jpg
Untitled.jpg (179.42 KiB) Viewed 387 times
This is the code that i have tried .

Code: Select all

s_class = classes[scores > 0.5]
        if(s_class)==2:
            print("E WASTE Detected")

User avatar
MrYsLab
Posts: 334
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to run a servo motor if a particular condition is satisfied

Thu May 16, 2019 11:07 pm

If you correct your code on Github and provide a link, I can take a look. You may also want to run your code through a PEP-8 (linter) tool that will point out where your code does not conform to the PEP8 standards - http://pep8online.com/

Return to “Python”