Project

General

Profile

Statistics
| Branch: | Revision:

root / forklift / code / motor.c @ 902fa82f

History | View | Annotate | Download (1.01 KB)

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

    
5
/*
6

7
motor controller
8

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

13

14
*/
15

    
16
int8_t motor_speed;
17

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

    
31
  set_motor(0);
32
}
33

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

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