I am a total newbie with Python, I normally use Perl.
I have an Arduino wired up with some servos I use to control a web cam, the script in question works perfect, the servos receive the instruction and do what they should:
#!/usr/bin/env python
import serial
usbport = '/dev/ttyACM0'
# Set up serial baud rate
ser = serial.Serial(usbport, 9600, timeout=1)
def move(servo, angle):
'''Moves the specified servo to the supplied angle.
Arguments:
servo
the servo number to command, an integer from 1-4
angle
the desired servo angle, an integer from 0 to 180
(e.g.) >>> servo.move(2, 90)
... # "move servo #2 to 90 degrees"'''
if (0 <= angle <= 180):
ser.write(chr(255))
ser.write(chr(servo))
ser.write(chr(angle))
else:
print "Servo angle must be an integer between 0 and 180.\n"
Basically the command for the above script is:
python
import servo
servo.move(1, 180)
I have converted the script to accept command line input, however the program does not seem to work. can anyone figure out what I am doing wrong, here is my version:
#!/usr/bin/env python
import serial
import sys
try:
servo = int(sys.argv[1])
angle = int(sys.argv[2])
except IndexError:
print ('a servo and angle are required')
sys.exit(2)
# Set up serial baud rate
usbport = '/dev/ttyACM0'
ser = serial.Serial(usbport, 9600, timeout=1)
def move(servo, angle):
'''Moves the specified servo to the supplied angle.
Arguments:
servo
the servo number to command, an integer from 1-4
angle
the desired servo angle, an integer from 0 to 180
(e.g.) >>> servo.move(2, 90)
... # "move servo #2 to 90 degrees"'''
if (0 <= angle <= 180):
ser.write(chr(255))
ser.write(chr(servo))
ser.write(chr(angle))
else:
print "Servo angle must be an integer between 0 and 180. You typed:"
print servo
print angle
move(servo, angle)
Basically the command for the above script is:
servo.py 1 180
I know the script works as it should as if I tell it to do a 1 181 I get the error that the angle is out of range, so I’m totally puzzled as to why the info is not passed to the serial/arduino.
Many thanks for any help and sorry for the long winded post.
Gilbert
Why adapt the original script? Just use this:
I’m not sure whether this happened when pasting code into stackoverflow, but the indenting is flawed on multiple places. Please check this too 🙂