def setup():
g lobal p
GPIO. setmode(GPIO.BOARD) # set mode for pin
GPIO. setup(motoRPin1,GPIO.OUT)
GPIO. setup(motoRPin2,GPIO.OUT)
GPIO. setup(enablePin,GPIO.OUT)
p = GPIO. PWM(enablePin,1000)# creat PWM
p. start(0)
#mapNUM function: map the value from a range of mapping to another range.
def mapNUM(value,fromLow,fromHigh,toLow,toHigh):
r eturn (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
#motor function: determine the direction and speed of the motor according to the ADC
value to be input.
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.
def loop():
w hile Tr ue:
value = analogRead(0)
print ('ADC Value : %d'%(value))
motor(value)
time.sleep(0.01)
def destroy():
bus. close()
GPIO. cleanup()
if __name__ == '__main__':