AStar32U4 library
AStar32U4Motors.cpp
1 // Copyright Pololu Corporation. For more information, see http://www.pololu.com/
2 
3 #include <AStar32U4Motors.h>
4 #include <FastGPIO.h>
5 #include <avr/io.h>
6 
7 #define PWM_M1 9
8 #define PWM_M2 10
9 #define DIR_M1 12
10 #define DIR_M2 IO_E2
11 
12 static bool _flipM1 = false;
13 static bool _flipM2 = false;
14 
15 // initialize timer1 to generate the proper PWM outputs to the motor drivers
16 void AStar32U4Motors::init2()
17 {
22 
23  // Timer 1 configuration
24  // prescaler: clockI/O / 1
25  // outputs enabled
26  // phase-correct PWM
27  // top of 400
28  //
29  // PWM frequency calculation
30  // 16MHz / 1 (prescaler) / 2 (phase-correct) / 400 (top) = 20kHz
31  TCCR1A = 0b10100000;
32  TCCR1B = 0b00010001;
33  ICR1 = 400;
34  OCR1A = 0;
35  OCR1B = 0;
36 }
37 
38 // enable/disable flipping of motor 1
39 void AStar32U4Motors::flipM1(bool flip)
40 {
41  _flipM1 = flip;
42 }
43 
44 // enable/disable flipping of motor 2
45 void AStar32U4Motors::flipM2(bool flip)
46 {
47  _flipM2 = flip;
48 }
49 
50 // set speed for motor 1; speed is a number between -400 and 400
51 void AStar32U4Motors::setM1Speed(int16_t speed)
52 {
53  init();
54 
55  bool reverse = 0;
56 
57  if (speed < 0)
58  {
59  speed = -speed; // Make speed a positive quantity.
60  reverse = 1; // Preserve the direction.
61  }
62  if (speed > 400) // Max PWM duty cycle.
63  {
64  speed = 400;
65  }
66 
67  OCR1A = speed;
68 
69  FastGPIO::Pin<DIR_M1>::setOutput(reverse ^ _flipM1);
70 }
71 
72 // set speed for motor 2; speed is a number between -400 and 400
73 void AStar32U4Motors::setM2Speed(int16_t speed)
74 {
75  init();
76 
77  bool reverse = 0;
78 
79  if (speed < 0)
80  {
81  speed = -speed; // Make speed a positive quantity.
82  reverse = 1; // Preserve the direction.
83  }
84  if (speed > 400) // Max PWM duty cycle.
85  {
86  speed = 400;
87  }
88 
89  OCR1B = speed;
90 
91  FastGPIO::Pin<DIR_M2>::setOutput(reverse ^ _flipM2);
92 }
93 
94 // set speed for both motors
95 void AStar32U4Motors::setSpeeds(int16_t m1Speed, int16_t m2Speed)
96 {
97  setM1Speed(m1Speed);
98  setM2Speed(m2Speed);
99 }
static void setOutput(bool value) __attribute__((always_inline))
Sets the pin as an output.
Definition: FastGPIO.h:260
static void setM2Speed(int16_t speed)
Sets the speed for motor 2.
static void setM1Speed(int16_t speed)
Sets the speed for motor 1.
static void flipM1(bool flip)
Flips the direction of motor 1.
static void setOutputLow() __attribute__((always_inline))
Configures the pin to be an output driving low.
Definition: FastGPIO.h:226
static void flipM2(bool flip)
Flips the direction of motor 2.
static void setSpeeds(int16_t m2Speed, int16_t m1Speed)
Sets the speed for both motors.