Skip to content

Commit 42b9d71

Browse files
committed
Added Servo examples
1 parent 466311c commit 42b9d71

File tree

4 files changed

+44
-0
lines changed

4 files changed

+44
-0
lines changed

05.Servos/ServoGetAngle/boot.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import pyb
2+

05.Servos/ServoGetAngle/main.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
servo = pyb.Servo(1) # id can be 1-4 (corresponds to pins X1 - X4)
2+
3+
while True:
4+
# generates a random 30-bit number
5+
# dividing so we get a smaller number to work with roughly 0 - 200
6+
random_angle = pyb.rng() // 5500000
7+
8+
# subtracting by 90 to bring range to roughly between -90 and 90
9+
# since many common servos have a range between -90 and 90 degrees
10+
random_angle -= 90
11+
12+
#set servo's position immediately to random_angle
13+
servo.angle(random_angle) # in degrees
14+
15+
pyb.delay(500) # wait half a second
16+
17+
print(servo.angle()) # prints the servo's current position
18+
19+
pyb.delay(500)

05.Servos/ServoSetAngle/boot.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import pyb
2+

05.Servos/ServoSetAngle/main.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
servo = pyb.Servo(1) # id can be 1-4 (corresponds to pins X1 - X4)
2+
3+
while True:
4+
5+
#set servo's position immediately
6+
servo.angle(90) # in degrees
7+
# many common servos have a range between -90 and 90 degrees
8+
9+
pyb.delay(500) # wait half a second
10+
11+
# change servo position to specified angle
12+
# and take a specified time to reach that angle
13+
servo.angle(-90, 2000) # 2000 millis = 2 seconds
14+
15+
pyb.delay(3000) # delaying by 3 seconds since it'll take two seconds for the motor to reach its final state
16+
17+
# the above statement makes the motor spin to -90 and then move on.
18+
# if your motors range does not hold -90, it could stall at this point
19+
# run servo.angle() to get your motor's position
20+
21+

0 commit comments

Comments
 (0)