In the previous part of the chapter, with our multiple attempts, we have been able to find the maximum positions for each of the servos. Now it's time to use these values. In this chapter, we will be programming the servos for what its absolute maximums are. In this program, we will make sure that servos will never need to travel even a degree beyond the defined parameters on both the sides. If the user gives a value beyond it, then it will simply choose to ignore the user inputs instead of causing self damage.
So, let's see how to get it done. There are some parts of this program, where the numeric values have been bold. These are the values that you need to replace with the values which we have noted in the previous section of this chapter. For example, for servo 1, the values noted down are 23 and 170 as the maximum values for either side. Hence, the change in the code will be from if a[0] < 160 and a[0] > 30 to ifa[0] < 170 and a[0] > 23. Similarly, for every servo, the same procedure has to be followed:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)
GPIO.setup(20,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
GPIO.setwarnings(False)
pwm1 = GPIO.PWM(14, 50)
pwm2 = GPIO.PWM(16, 50)
pwm3 = GPIO.PWM(18, 50)
pwm4 = GPIO.PWM(20, 50)
pwm5 = GPIO.PWM(21, 50)
pwm6 = GPIO.PWM(22, 50)
pwm1.start(cvt_angle(90))
pwm2.start(cvt_angle(90))
pwm3.start(cvt_angle(90))
pwm4.start(cvt_angle(90))
pwm5.start(cvt_angle(90))
pwm6.start(cvt_angle(90))
def cvt_angle(angle):
dc = float(angle/90) + 0.5
return dc
while True:
a = raw_input("enter a list of 6 values")
if a[0] < 160 and a[0] > 30:
pwm1.ChangeDutyCycle(cvt_angle(a[0]))
if a[1] < 160 and a[1] > 30:
pwm2.ChangeDutyCycle(cvt)angle(a[1]))
if a[0] < 160 and a[0] > 30:
pwm3.ChangeDutyCycle(cvt_angle(a[2]))
if a[0] < 160 and a[0] > 30:
pwm4.ChangeDutyCycle(cvt_angle(a[3]))
if a[0] < 160 and a[0] > 30:
pwm5.ChangeDutyCycle(cvt_angle(a[4]))
if a[0] < 160 and a[0] > 30:
pwm6.ChangeDutyCycle(cvt_angle(a[5]))}
Now, in this code, we have done something very rudimentary. You can safely say that all we have done is put the ChangeDutyCycle() function inside an if statement. This if statement will govern whether the servo will move or stay still in its own position. To some, it may seem very naive to have this program in a special section. But, trust me, it is not. This statement will now be used as a part of every program from here on. All the code written for the movement of the servos will have to check the final values going to the servos through this if statement; hence, a basic visualization of code is extremely necessary.
Now that the explanation is done, it's time for you to give different commands and see whether they are working within the safe working limits.