Project

General

Profile

Statistics
| Branch: | Revision:

root / forklift / code / motor.c @ 0bd4bb32

History | View | Annotate | Download (1016 Bytes)

1
#include <avr/io.h>
2
#include "motor.h"
3
#include <stdlib.h>
4
/*
5

6
motor controller
7

8
IN1: PD7
9
IN2: PD6
10
PWM: PB1
11

12

13
*/
14

    
15
int8_t motor_speed;
16

    
17

    
18

    
19
void motor_init(void)
20
{
21
  // WGM1 0b0101 (fast PWM, 8-bit)
22
  // COM1A 0b10 (clear OC1A on compare match, set on BOTTOM)
23
  // CS1 0b011 (64 prescaler)
24
  TCCR1A = _BV(WGM10) | _BV(COM1A1);
25
  TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10);
26
  OCR1AH = 0;
27
  
28
  // set IN1 (PD7), IN2 (PD6), and PWM (PB1) as output
29
  DDRD |= _BV(DDD7) | _BV(DDD6);
30
  DDRB |= _BV(DDB1);
31

    
32
  set_motor(0);
33
}
34

    
35
void set_motor(int8_t speed)
36
/* Speed must be between -127 and 127 */
37
{
38
  motor_speed = speed;
39
  OCR1AL = abs(speed)*2;
40
  if(speed>0) //go forwards
41
  {
42
          PORTD |= (1<<PD7);
43
        PORTD = PORTD & ~(1<<PD6);
44
  }        
45
  if(speed<0) //go backwards
46
  {
47
          PORTD |= (1<<PD6);
48
        PORTD = PORTD & ~(1<<PD7);
49
  }
50
  if(speed==0) // turn motor off
51
  {
52
        PORTD = PORTD & ~(1<<PD6);
53
        PORTD = PORTD & ~(1<<PD7);
54
  }
55
}
56

    
57
int8_t get_motor()
58
{
59
  return motor_speed;
60
}