-
Notifications
You must be signed in to change notification settings - Fork 3
/
servo.py
63 lines (45 loc) · 1.42 KB
/
servo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# For Python 2.7
# Python script to control the servo
# There aren't any libraries to control PWM GPIO output in C/C++,
# so this script is being used temporarily until I can write a C++ class for it
import sys
import os
import time
import wiringpi
DELAY_PERIOD = 0.01
'''
Initializes a given PWM GPIO pin for output
'''
def init(pin):
# Use GPIO naming
wiringpi.wiringPiSetupGpio()
# Set mode for pin 18 to PWM
wiringpi.pinMode(pin, wiringpi.GPIO.PWM_OUTPUT)
# Set mode of PWM to milliseconds
wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
# Set clock
wiringpi.pwmSetClock(192)
wiringpi.pwmSetRange(2000)
'''
Outputs a pulse with a given width (in milliseconds) to PWM pin 18
Correct usage: sudo python servo.py <pulse_time>
'''
def main():
# Ensure that sudo permissions are enabled to prevent kernel crash
if(os.getuid() != 0):
print("Error: This program must be run as root.")
print("Correct usage: sudo python servo.py <pulse_time>")
print(" where <pulse_time> is in milliseconds")
exit()
# Ensure there are the correct number of arguments
if(len(sys.argv) != 2):
print("Error: Incorrect syntax.")
print("Correct usage: sudo python servo.py <pulse_time>")
print(" where <pulse_time> is in milliseconds")
exit()
# Init pin 18 for output
init(18)
# Output the given value to the servo
wiringpi.pwmWrite(18, int(sys.argv[1]))
print("Successfully wrote " + sys.argv[1] + " to pin 18")
main()