1
+ /* ******************************************************************
2
+ SoftServo sketch for Adafruit Trinket. Increments values to change position on the servo
3
+ (0 = zero degrees, full = 180 degrees)
4
+
5
+ Required library is the Adafruit_SoftServo library
6
+ available at https://github.com/adafruit/Adafruit_SoftServo
7
+ The standard Arduino IDE servo library will not work with 8 bit
8
+ AVR microcontrollers like Trinket and Gemma due to differences
9
+ in available timer hardware and programming. We simply refresh
10
+ by piggy-backing on the timer0 millis() counter
11
+
12
+ Required hardware includes an Adafruit Trinket microcontroller
13
+ a servo motor, and a potentiometer (nominally 1Kohm to 100Kohm
14
+
15
+ As written, this is specifically for the Trinket although it should
16
+ be Gemma or other boards (Arduino Uno, etc.) with proper pin mappings
17
+
18
+ Trinket: USB+ Gnd Pin #0
19
+ Connection: Servo+ - Servo1
20
+
21
+ *******************************************************************/
22
+
23
+ #include < Adafruit_SoftServo.h> // SoftwareServo (works on non PWM pins)
24
+
25
+ #define SERVO1PIN 0 // Servo control line (orange) on Trinket Pin #0
26
+ int moveAmount = 1 ; // change this value to change speed of servo
27
+ int servoPos = 0 ; // variable for servo position
28
+
29
+ Adafruit_SoftServo myServo1; // create servo object
30
+
31
+ void setup () {
32
+ // Set up the interrupt that will refresh the servo for us automagically
33
+ OCR0A = 0xAF ; // any number is OK
34
+ TIMSK |= _BV (OCIE0A); // Turn on the compare interrupt (below!)
35
+
36
+ myServo1.attach (SERVO1PIN); // Attach the servo to pin 0 on Trinket
37
+ myServo1.write (90 ); // Tell servo to go to position per quirk
38
+ delay (15 ); // Wait 15ms for the servo to reach the position
39
+ }
40
+
41
+ void loop () {
42
+
43
+ myServo1.write (servoPos); // tell servo to go to position
44
+ servoPos = servoPos + moveAmount; // increment servo position (value between 0 and 180)
45
+ if (servoPos == 0 || servoPos == 180 ){
46
+ moveAmount = -moveAmount; // reverse incrementer at bounds
47
+ }
48
+ delay (15 ); // waits 15ms for the servo to reach the position
49
+ }
50
+
51
+ // We'll take advantage of the built in millis() timer that goes off
52
+ // to keep track of time, and refresh the servo every 20 milliseconds
53
+ // The SIGNAL(TIMER0_COMPA_vect) function is the interrupt that will be
54
+ // Called by the microcontroller every 2 milliseconds
55
+ volatile uint8_t counter = 0 ;
56
+ SIGNAL (TIMER0_COMPA_vect) {
57
+ // this gets called every 2 milliseconds
58
+ counter += 2 ;
59
+ // every 20 milliseconds, refresh the servos!
60
+ if (counter >= 20 ) {
61
+ counter = 0 ;
62
+ myServo1.refresh ();
63
+ }
64
+ }
0 commit comments