Project

General

Profile

Statistics
| Revision:

root / branches / encoders / code / projects / libdragonfly / encoders.c @ 675

History | View | Annotate | Download (1.69 KB)

1
#include "encoders.h"
2
#include "spi.h"
3
#include <dragonfly_lib.h>
4
#include "ring_buffer.h"
5

    
6
unsigned short int left_data_buf;
7
unsigned short int right_data_buf;
8
char buf_index;
9

    
10
unsigned short int left_data;
11
unsigned short int right_data;
12

    
13
RING_BUFFER_NEW(enc_buffer, 16, short int, spi_send_buff, spi_rec_buff);
14

    
15
void encoders_init(void){
16
        spi_init(encoder_recv);
17
        buf_index = 0;
18
        left_data_buf = 0;
19
        right_data_buf= 0;
20
        left_data = -1;
21
        right_data = -1;
22
}
23

    
24
int encoder_read(char encoder){
25
        if(encoder==LEFT)
26
                return left_data;
27
        else if(encoder==RIGHT)
28
                return right_data;
29
        else return -1;
30
}
31

    
32
int encoder_change(char encoder){
33
        return 0;
34
}
35

    
36
char encoder_direction(char encoder){
37
        return 0;
38
}
39

    
40
//Full reads occur every 40 microseconds. This function should be called
41
//every 8 microseconds.
42
void encoder_recv(char data){
43
        if(buf_index < 2)
44
                right_data_buf |= (((short)data) << ((1-buf_index)*8)) & (0xF<<(1-buf_index));
45
        
46
        else if (buf_index == 2)
47
                left_data_buf |= (((short)data) << 9) & (0x7F << 9);
48
        
49
        else if (buf_index == 3)
50
                left_data_buf |= ((short)(data) << 1) & (0xFF<<1);
51
        
52
        else if (buf_index == 4)
53
                left_data_buf |= (data>>7) & 0x1;
54

    
55
        
56
        buf_index = (buf_index + 1) % 5;
57

    
58
        if(buf_index==0){
59
                if(left_data_buf & (OCF | COF | LIN)) 
60
                        left_data = INVALID;
61
                
62
                else if(((left_data_buf & MagINCn) > 0)  && ((left_data_buf & MagDECn) > 0)) 
63
                        left_data = MAGNET_FAILURE;
64
                
65
                else left_data = (left_data_buf>>5) & 1023;
66
                
67
                if(right_data_buf & (OCF | COF | LIN)) 
68
                        right_data = INVALID;
69
                
70
                else if ( ((left_data_buf & MagINCn) > 0)  && ((left_data_buf & MagDECn) > 0)) 
71
                        left_data = MAGNET_FAILURE;
72
                
73
                else right_data = (right_data_buf>>5) & 1023;
74
        
75
                                                        
76
                
77
                left_data_buf = 0;
78
                right_data_buf = 0;
79
        }
80
}