Page 1 of 1

Using button to activate servo not working, it just make a wierd sound...

Posted: Tue Jan 08, 2019 10:13 pm
by Gard1992
Hi there,

So i have this code, where i would like it to when i click the button it makes the servo turn to some to a certain degree and then go back to the inicial degree, and then when it does that when I click again it does it all over again. Like it was a door open and close, 0º and 90º. But for some reason with the switch it doesn't work it just makes this wierd sound and then it stops like how it should but witout turning. Here it it the code. After this code i have a version of the code where it only does the servo stuff without the switch and that one works like it should.

Code: Select all


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

SERVOPIN = 5
LED = 18
SWITCH = 20

GPIO.setup(SERVOPIN,GPIO.OUT)
GPIO.setup(LED, GPIO.OUT, initial=0)
GPIO.setup(SWITCH, GPIO.IN, pull_up_down=GPIO.PUD_UP)

p = GPIO.PWM(SERVOPIN, 50)        

p.start(6.3)

try:  

	while True:

		input_state = GPIO.input(SWITCH)
	
		if input_state == False:
			
			print("Open")
			p.ChangeDutyCycle(2.5)
			time.sleep(2)
			GPIO.output(LED, 1)

			time.sleep(3)

			print("Closed")
			p.ChangeDutyCycle(6.3)
			time.sleep(2)
			GPIO.output(LED, 0)
			
except KeyboardInterrupt:
	print("Exit");
finally:
	p.stop()	
	GPIO.cleanup()


Version without the switch [Working]:

Code: Select all


import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

SERVOPIN = 5

GPIO.setup(SERVOPIN,GPIO.OUT)

p = GPIO.PWM(SERVOPIN, 50)        

p.start(6.3)

print("Open")
p.ChangeDutyCycle(2.5)
time.sleep(2)

time.sleep(10)

print("Closed")
p.ChangeDutyCycle(6.3)
time.sleep(2) 

p.stop()
GPIO.cleanup()


Thanks for the help! :D

Re: Using button to activate servo not working, it just make a wierd sound...

Posted: Wed Jan 09, 2019 6:52 am
by OutoftheBOTS
Well your code looks fine.

When your switch pin gets connected to ground then it should enter the loop that moves the servo.

Please check your wiring that the switch is pulling the pin to ground when pressed.

Re: Using button to activate servo not working, it just make a wierd sound...

Posted: Wed Jan 09, 2019 11:14 am
by pcmanbob
Tested your code with the exact same setup on a pi2B running stretch lite using python 3 and it works just as your code suggests it should.

So I would check your hardware setup.

for reference

Image