scoutece / paintboard / code / motor.c @ 1226c007
History | View | Annotate | Download (1.76 KB)
1 |
#include <avr/io.h> |
---|---|
2 |
#include "motor.h" |
3 |
#include <stdlib.h> |
4 |
|
5 |
/*
|
6 |
|
7 |
motor controller. Timer2 is set to phase-correct PWM mode, with 32 prescaler.
|
8 |
|
9 |
AIN1: PC0
|
10 |
AIN2: PC1
|
11 |
PWMA: PB3 (Timer2) (OCRA)
|
12 |
|
13 |
BIN1: PC2
|
14 |
BIN2: PC3
|
15 |
PWMB: PD3 (Timer2) (OCRB)
|
16 |
|
17 |
*/
|
18 |
|
19 |
int8_t motor1_speed; |
20 |
int8_t motor2_speed; |
21 |
|
22 |
void motor_init(void) |
23 |
{ |
24 |
|
25 |
// WGM2 0b001 (phase-correct PWM, 8-bit)
|
26 |
// COM2A 0b10 (clear OCR2A on compare match, set on BOTTOM)
|
27 |
// COM2B 0b10 (clear OCR2B on compare match, set on BOTTOM)
|
28 |
// CS2 0b011 (32 prescaler)
|
29 |
TCCR2A = _BV(WGM20) | _BV(COM2A1) |_BV(COM2B1); |
30 |
TCCR2B = _BV(CS21) | _BV(CS20); |
31 |
OCR2A = 0;
|
32 |
OCR2B = 0;
|
33 |
|
34 |
// set output pins
|
35 |
DDRC |= _BV(PC0) | _BV(PC1) | _BV(PC2) | _BV(PC3); |
36 |
DDRB |= _BV(PB3); |
37 |
DDRD |= _BV(PD3); |
38 |
|
39 |
set_motor1(0);
|
40 |
set_motor2(0);
|
41 |
} |
42 |
|
43 |
void set_motor1(int8_t speed)
|
44 |
/* Speed must be between -127 and 127 */
|
45 |
{ |
46 |
motor1_speed = speed; |
47 |
OCR2A = (uint8_t)abs(speed)*2;
|
48 |
if(speed>0) //go forwards |
49 |
{ |
50 |
PORTC |= (1<<PC0);
|
51 |
PORTC = PORTC & ~(1<<PC1);
|
52 |
} |
53 |
if(speed<0) //go backwards |
54 |
{ |
55 |
PORTC |= (1<<PC1);
|
56 |
PORTC = PORTC & ~(1<<PC0);
|
57 |
} |
58 |
if(speed==0) // turn motor off |
59 |
{ |
60 |
PORTC = PORTC & ~(1<<PC1);
|
61 |
PORTC = PORTC & ~(1<<PC0);
|
62 |
} |
63 |
} |
64 |
|
65 |
void set_motor2(int8_t speed)
|
66 |
/* Speed must be between -127 and 127 */
|
67 |
{ |
68 |
motor2_speed = speed; |
69 |
OCR2B = (uint8_t)abs(speed)*2;
|
70 |
if(speed>0) //go forwards |
71 |
{ |
72 |
PORTC |= (1<<PC2);
|
73 |
PORTC = PORTC & ~(1<<PC3);
|
74 |
} |
75 |
if(speed<0) //go backwards |
76 |
{ |
77 |
PORTC |= (1<<PC3);
|
78 |
PORTC = PORTC & ~(1<<PC2);
|
79 |
} |
80 |
if(speed==0) // turn motor off |
81 |
{ |
82 |
PORTC = PORTC & ~(1<<PC3);
|
83 |
PORTC = PORTC & ~(1<<PC2);
|
84 |
} |
85 |
} |
86 |
|
87 |
int8_t get_motor1() |
88 |
{ |
89 |
return motor1_speed;
|
90 |
} |
91 |
|
92 |
int8_t get_motor2() |
93 |
{ |
94 |
return motor2_speed;
|
95 |
} |