Chapter 13 Motor & Driver
p rint ('Program is starting ... ')
setup()
try:
loop()
e xcept KeyboardInterrupt:
destroy()
We have been familiar with reading ADC value. So, let’s learn directly subfunction def motor(ADC): first,
compare ADC value with 128 (value corresponding to midpoint). When the current ADC value is higher,
motoRPin1 outputs high level and motoRPin2 output low level to control motor to run with forward rotation
direction. When the current ADC value is lower, motoRPin1 outputs low level and motoRPin2 outputs high
level to control run with reversed direction. When the ADC value is equal to 128, make motoRPin1 and
motoRPin2 output low level, then the motor stops. And then determine PWM duty cycle according to the
difference between ADC value and 128. Because the absolute difference value stays within 0-128. We need
to use the map () subfunction mapping the difference value to range of 0-100. Finally print out the duty cycle.
def motor(ADC):
value = ADC - 128
if (value > 0):
GPIO.output(motoRPin1,GPIO.HIGH)
GPIO.output(motoRPin2,GPIO.LOW)
print ('Turn Forward...')
e lif (value < 0):
GPIO.output(motoRPin1,GPIO.LOW)
GPIO.output(motoRPin2,GPIO.HIGH)
print ('Turn Backward...')
e lse :
GPIO.output(motoRPin1,GPIO.LOW)
GPIO.output(motoRPin2,GPIO.LOW)
print ('Motor Stop...')
p. start(mapNUM(abs(value),0,128,0,100))
p rint ('The PWM duty cycle is %d%%\n'%(abs(value)*100/127)) #print PMW duty cycle.