Pololu3piPlus32U4 library
Pololu3piPlus32U4Motors.cpp
1 // Copyright (C) Pololu Corporation. See www.pololu.com for details.
2 
4 #include <FastGPIO.h>
5 #include <avr/io.h>
6 
7 namespace Pololu3piPlus32U4
8 {
9 
10 #define PWM_L 10
11 #define PWM_R 9
12 #define DIR_L 16
13 #define DIR_R 15
14 
15 bool Motors::flipLeft = false;
16 bool Motors::flipRight = false;
17 
18 // initialize timer1 to generate the proper PWM outputs to the motor drivers
19 void Motors::init2()
20 {
21  FastGPIO::Pin<PWM_L>::setOutputLow();
22  FastGPIO::Pin<PWM_R>::setOutputLow();
23  FastGPIO::Pin<DIR_L>::setOutputLow();
24  FastGPIO::Pin<DIR_R>::setOutputLow();
25 
26  // Timer 1 configuration
27  // prescaler: clockI/O / 1
28  // outputs enabled
29  // phase-correct PWM
30  // top of 400
31  //
32  // PWM frequency calculation
33  // 16MHz / 1 (prescaler) / 2 (phase-correct) / 400 (top) = 20kHz
34  TCCR1A = 0b10100000;
35  TCCR1B = 0b00010001;
36  ICR1 = 400;
37  OCR1A = 0;
38  OCR1B = 0;
39 }
40 
41 void Motors::flipLeftMotor(bool flip)
42 {
43  flipLeft = flip;
44 }
45 
46 void Motors::flipRightMotor(bool flip)
47 {
48  flipRight = flip;
49 }
50 
51 void Motors::setLeftSpeed(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)
63  {
64  speed = 400;
65  }
66 
67  OCR1B = speed;
68 
69  FastGPIO::Pin<DIR_L>::setOutput(reverse ^ flipLeft);
70 }
71 
72 void Motors::setRightSpeed(int16_t speed)
73 {
74  init();
75 
76  bool reverse = 0;
77 
78  if (speed < 0)
79  {
80  speed = -speed; // Make speed a positive quantity.
81  reverse = 1; // Preserve the direction.
82  }
83  if (speed > 400)
84  {
85  speed = 400;
86  }
87 
88  OCR1A = speed;
89 
90  FastGPIO::Pin<DIR_R>::setOutput(reverse ^ flipRight);
91 }
92 
93 void Motors::setSpeeds(int16_t leftSpeed, int16_t rightSpeed)
94 {
95  setLeftSpeed(leftSpeed);
96  setRightSpeed(rightSpeed);
97 }
98 
99 }
static void setLeftSpeed(int16_t speed)
Sets the speed for the left motor.
static void flipRightMotor(bool flip)
Flips the direction of the right motor.
static void setSpeeds(int16_t leftSpeed, int16_t rightSpeed)
Sets the speeds for both motors.
static void flipLeftMotor(bool flip)
Flips the direction of the left motor.
static void setRightSpeed(int16_t speed)
Sets the speed for the right motor.
Top-level namespace for the Pololu3piPlus32U4 library.