Revision 1828

View differences:

demos/hunter_prey/lib/src/libdragonfly/rangefinder.c
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * @file rangefinder.c
29
 * @brief Rangefinders
30
 *
31
 * Implementation of functions for rangefinder use.
32
 *
33
 * @author Colony Project, CMU Robotics Club
34
 **/
35

  
36
/*
37
  Authors: James Kong, Greg Tress, Emily Hart
38

  
39
  Last Modified: 5/12/10 by Emily
40
  - Added Butterworth filtering functions. As of right now, the filter should
41
    only be used if you really know what you are doing. These functions were
42
    designed to be used with a task scheduler, which is not currently complete.
43
    This implementation uses the RTC and runs massive computations in the RTC
44
    interrupt.
45

  
46
  Modified: 4/30/06 by James
47
  -Started log_distance conversion function !!!NOT COMPLETE!!!
48
  -Cleaning up comments
49

  
50
  -----------------
51
  rangefinder.c
52
  Using Sharp GP2D02 IR Rangefinder
53

  
54
  Vin is the input to the rangefinder, designated RANGE_CTRL.
55
  Vout is the output from the rangefinder, designated RANGE_IN# where # is the
56
  rangefinder you are reading from
57

  
58
  Expected Initial Conditions:
59
  Vin is high and Vout should read high.
60

  
61
  Usage:
62
  1.) Set Vin low. Vout should read low.
63
  2.) Wait for high on Vout.
64
  3.) Begin clocking Vin and reading 8 bits from Vout (MSB first).
65
  4.) Set Vin high for 2ms or more to turn off rangefinder
66

  
67
*/
68
#include <avr/pgmspace.h>
69
#include <avr/interrupt.h>
70

  
71
#include "rangefinder.h"
72
#include "analog.h"
73
#include "dio.h"
74
#include "time.h"
75

  
76
/*
77
  read_distance returns the 8-bit reading from the rangefinder
78
  parameters:
79
  range_id - dio pin set as the rangefinder Vout [i.e. RANGE_IN0]
80

  
81
  NOTE:
82
  The Sharp GD2D02 returns values on a decreasing logrithmic scale.
83
  So higher values correspond to closer distances.  Use linearize_distance to convert to normal centimeter scale.
84
  Also, when reading distances closer than 8cm, the Sharp GD2D02 will return lower values than the values at 8cm.
85
  At this point, we are only reading from one rangefinder [RANGE_IN0].
86
*/
87

  
88
// constants
89
/* Nasty IR approximation table
90
   I'm using this for the heck of it.  We can do whatever.
91

  
92
   Note the minimum value is .4V (20), and the maximum is 2.6V (133).
93
   Gives distance in mm.
94

  
95
   excel formula(valid for inputs 20-133):  ROUND(2353.6*(E2^(-1.1146))*10,0)
96

  
97
   This is only valid for the GP2D12, with objects directly ahead and more than
98
   10cm from the detector.  See the datasheet for more information.
99
*/
100

  
101
static int IR_dist_conversion[72] PROGMEM = {
102
	327,315,303,291,281,271,262,253,245,238,231,224,218,212,206,200,
103
	195,190,185,181,177,173,168,165,161,158,155,151,148,145,143,140,
104
	137,134,132,130,127,125,123,121,119,117,115,114,111,110,108,106,
105
	105,104,102,100,99,98,97,95,94,93,91,90,89,88,87,86,84,83,83,82,
106
	81,80,79,78
107
};
108

  
109
/* 1 if the filter is enabled, else 0 */
110
static int use_filter;
111
// VALUE - MIN_IR_LINEAR is stored so only 8 bits are needed
112
/* X values for the Butterworth filter, for each rangefinder */
113
static uint8_t butter_x[5][4];
114
/* Y values for the Butterworth filter, for each rangefinder */
115
static uint8_t butter_y[5][3];
116
/* How many consecutive -1s have been seen by each rangefinder */
117
static uint8_t neg_one_count[5];
118

  
119
/**
120
 * @defgroup rangefinder Rangefinder
121
 * @brief Functions for using the IR rangefinders
122
 * 
123
 * Functions for using the IR rangefinders.
124
 *
125
 * @{
126
 **/
127

  
128
/**
129
 * Initializes the rangefinders. This must be called before
130
 * range_read_distance. This function does not initialize the filter.
131
 *
132
 * @see range_read_distance
133
 **/
134
void range_init(void)
135
{
136
  digital_output(_PIN_B4,0);
137
  use_filter = 0;
138
}
139

  
140
/**
141
 * Initializes the rangefinders with an option to enable the Butterworth
142
 * filtering.
143
 *
144
 * As of 5/12/2010, the filter should only be used if you really know what you
145
 * are doing. It was designed to be used with a task scheduler, which is not
146
 * currently complete. This implementation uses the RTC and runs massive
147
 * computations in the RTC interrupt.
148
 *
149
 * @param filter 1 to enable the filter, 0 to leave it turned off
150
 **/
151
void range_init_filter(int filter)
152
{
153
    range_init();
154
    if(filter){
155
        use_filter = 1;
156
        butter_init();
157
    }
158
}
159

  
160
/**
161
 * Reads the distance measured by one of the rangefinders.
162
 * This distance is in arbitrary units.
163
 *
164
 * @param range_id the rangefinder to use. This should be one
165
 * of the constants IR1 - IR5.
166
 *
167
 * @return the distance measured by the rangefinder
168
 *
169
 * @see range_init
170
 **/
171
int range_read_distance(int range_id) {
172
  return linearize_distance(analog8(range_id));
173
}
174

  
175
/**
176
 * Transforms distance readings from logarithmic to linear scale.
177
 * This probably isn't the function you are looking for.
178
 *
179
 * Note: pgm_read_word() needs additional testing
180
 *
181
 * @param value the 8-bit analog value from rangefinder
182
 *
183
 * @return linearized distance reading from rangefinder (integer in [101,800])
184
 **/
185
int linearize_distance(int value) {
186
  if(value < MIN_IR_ADC8) {
187
    return -1;
188
  } else if(value > MAX_IR_ADC8) {
189
    return -1;
190
  } else {
191
    return pgm_read_word(&(IR_dist_conversion[value - MIN_IR_ADC8]));
192
  }
193
}
194

  
195
/**
196
 * Initializes the butterworth filter.
197
 **/
198
void butter_init(void)
199
{
200
    int i;
201
    // init -1 count to 3 for each rangefinder
202
    // this will cause them to restart the filter
203
    for(i=0; i<5; i++)
204
    {
205
        neg_one_count[i] = 3;
206
    }
207

  
208
    // set up the rtc to run butter_task periodically
209
    rtc_init(SIXTEENTH_SECOND, butter_task);
210
}
211

  
212
/*
213
 * Reads each rangefinder and sends its value through the Butterworth filter.
214
 * This task should be run frequently so that range_read_filtered_distance
215
 * returns fresh values
216
 */
217
void butter_task(void)
218
{
219
    butter_filter(IR1, range_read_distance(IR1));
220
    butter_filter(IR2, range_read_distance(IR2));
221
    butter_filter(IR3, range_read_distance(IR3));
222
    butter_filter(IR4, range_read_distance(IR4));
223
    butter_filter(IR5, range_read_distance(IR5));
224
}
225

  
226
/*
227
 * Butterworth helper function that takes a rangefinder ID and turns it into
228
 * an array index between 0 and 4.
229
 */
230
int get_range_index(int range_id){
231
    switch(range_id){
232
    case IR1:
233
        return 0;
234
    case IR2:
235
        return 1;
236
    case IR3:
237
        return 2;
238
    case IR4:
239
        return 3;
240
    case IR5:
241
        return 4;
242
    default: // should never happen
243
        return 0xff;
244
    }
245
}
246

  
247
/**
248
 * Puts the given value from the given rangefinder through the Butterworth
249
 * filter. This function should be called every time a new value is read from a
250
 * rangefinder.
251
 *
252
 * The Butterworth filter has a cutoff frequency of 5Hz and an order of 3
253
 *
254
 * @param range_id the rangefinder to use. This should be one of the constants
255
 * IR1 - IR5.
256
 * @param the value read from that rangefinder
257
 **/
258
void butter_filter(int range_id, int val)
259
{
260
    int range_index = get_range_index(range_id);
261
    // we have a non-error value
262
    if(val > -1 && val <= MAX_IR_LINEAR)
263
    {
264
      // we just passed two or fewer -1's: act as though none seen
265
      if(neg_one_count[range_index] < 3)
266
      {
267
        // shift the values of the arrays to the left
268
        int i;
269
        for(i=0; i<2; i++)
270
        {
271
          butter_x[range_index][i] = butter_x[range_index][i+1];
272
          butter_y[range_index][i] = butter_y[range_index][i+1];
273
        }
274
        butter_x[range_index][2] = butter_x[range_index][3];
275
        // add the new value to the X array
276
        butter_x[range_index][3] = val - MIN_IR_LINEAR;
277
      }
278
      // we just passed three or more -1 values: reset filter with new value
279
      else
280
      {
281
        int i;
282
        // fill x and y values with the new value
283
        for(i=0; i<3; i++)
284
        {
285
          butter_x[range_index][i] = val - MIN_IR_LINEAR;
286
          butter_y[range_index][i] = val - MIN_IR_LINEAR;
287
        }
288
        butter_x[range_index][3] = val - MIN_IR_LINEAR;
289
      }
290

  
291
      // reset the -1 count value
292
      neg_one_count[range_index] = 0;
293

  
294
      /*
295
       * butterworth filter the last values
296
       *
297
       * butterworth filter equation is
298
       * y(t) = x(t-3)/6 + x(t-2)/2 + x(t-1)/2 + x(t)/6 - y(t-2)/3
299
       *
300
       * values are multiplied by 16 before divisions, and divided by 16 at the
301
       * very end to mitigate rounding errors
302
       *
303
       * 8 is added before dividing by 16 so that numbers are rounded instead of
304
       * truncated
305
       */
306
      int16_t temp1 = (int16_t)butter_x[range_index][3] +
307
          (int16_t)butter_x[range_index][0] + (2*MIN_IR_LINEAR);
308
      int16_t temp2 = (int16_t)butter_x[range_index][2] +
309
          (int16_t)butter_x[range_index][1] + (2*MIN_IR_LINEAR);
310
      int16_t temp3 = (int16_t)butter_y[range_index][0] + MIN_IR_LINEAR;
311
      int16_t filtered_big = ((((temp1*8)-(temp3*16))/3)+(temp2*8)+8)/16;
312
      filtered_big -= MIN_IR_LINEAR;
313
      uint8_t filtered = filtered_big > 0xff ? 0xff : (uint8_t)filtered_big;
314

  
315
      butter_y[range_index][2] = filtered;
316
    }
317
    // -1 seen - don't want to store it
318
    else
319
    {
320
        // increment -1 count, preventing overflow
321
        neg_one_count[range_index] = neg_one_count[range_index] == 0xff ? 0xff :
322
            neg_one_count[range_index]+1;
323
    }
324
}
325

  
326
/**
327
 * Returns the most recent filtered reading of the rangefinder. The raw
328
 * rangefinder values have been run through a Butterworth filter.
329
 *
330
 * If the filter was not initialized in rangefinder_init, will return the
331
 * unfiltered value from the rangefinder.
332
 *
333
 * @param range_id the rangefinder to use. This should be one of the constants
334
 * IR1 - IR5.
335
 **/
336
int range_read_filtered_distance(int range_id){
337
    if(!use_filter){
338
        return range_read_distance(range_id);
339
    }
340

  
341
    int range_index = get_range_index(range_id);
342

  
343
    // haven't seen too many -1s recently - return filtered value
344
    if(neg_one_count[range_index] < 3)
345
    {
346
        return butter_y[range_index][2] + MIN_IR_LINEAR;
347
    }
348
    // have seen several -1s - return -1
349
    return -1;
350
}
351

  
352
/** @} **/ //end defgroup
demos/hunter_prey/lib/src/libdragonfly/serial.h
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * @file serial.h
29
 * @brief Contains declarations for serial input and output
30
 *
31
 * Contains definitions for serial input and output.
32
 *
33
 * @author Colony Project, CMU Robotics Club
34
 * Based on Tom Lauwer's Firefly Library
35
 *
36
 **/
37

  
38
/*
39
  serial.h - Contains definitions and function prototypes for the RS232 serial port
40
  author(s): pkv
41
  
42
  Directions:
43
  Call the initialization function for the serial port you wish to use.  Then, use
44
  either the provided functions or the stdio functions (fprintf, etc) to read and
45
  write characters to the serial ports.
46
  
47
  UART Mapping:
48
  usb_*() -> UART0
49
  xbee_*() -> UART1
50
  
51
  Options: (Add the following defines to your code to configure this library)
52
  #define USB_BAUD { 115200 | 9600 } <= pick ONE value from in here
53
  #define XBEE_BAUD { 115200 | 9600 } <= pick ONE value from in here
54
  #define USE_STDIO
55
  
56
  Note: If you enable USE_STDIO, the first init function that is called will 
57
  automatically be linked to stdin, stdout, and stderr.  To use the baud rate 
58
  commands, add something like the following to your code:
59
  
60
  #define FOO_BAUD 9600
61
  
62
  **UNLESS YOU KNOW WHAT YOU ARE DOING, PLEASE DO NOT CHANGE THIS FILE**
63
  Many, many other people use this file in their code.  If you change it, you will
64
  probably break all of their nice code.  You should not need to change anything in
65
  here, except to accomodate new hardware.
66
*/
67

  
68
#ifndef _SERIAL_H
69
#define _SERIAL_H
70

  
71
#include <inttypes.h>
72
#include <avr/pgmspace.h>
73

  
74
/**
75
 * @defgroup usb USB Input / Output
76
 * @brief Functions for USB input / output
77
 *
78
 * Low level functions for USB input and output.
79
 *
80
 * @{
81
 **/
82

  
83
// if no baud rate is defined for usb, default is set here
84
#ifndef USB_BAUD
85
/** @brief the USB baud rate **/
86
#define USB_BAUD 115200
87
#endif
88

  
89
/** @brief Initialize the USB **/
90
void usb_init(void);
91
/** @brief Print a character to USB **/
92
int usb_putc(char c);
93
/** @brief Read a character from USB **/
94
int usb_getc(void);
95
/** @brief Read a character from USB without blocking **/
96
int usb_getc_nb(char *c);
97
/** @brief Print a string to USB **/
98
int usb_puts(char *s);
99
/** @brief Print a string from program space to USB **/
100
void usb_puts_P (PGM_P s);
101
/** @brief Print an integer to USB **/
102
int usb_puti(int value);
103
/** @brief Determine a hexadecimal digit **/
104
uint8_t hex_digit (uint8_t value);
105
/** @brief Print a fixed width hexadecimal representation to USB **/
106
void usb_puth16 (uint16_t value);
107
/** @brief Print a fixed width hexadecimal representation to USB **/
108
void usb_puth8(uint8_t value);
109
/** @brief Alias for usb_puth16 **/
110
static inline void usb_puth (uint16_t value) { usb_puth16 (value); };
111

  
112

  
113
/** @} **/ //end addtogroup
114

  
115
/**
116
 * @defgroup xbee XBee Input / Output
117
 * @brief Functions for XBee input / output
118
 *
119
 * Low level functions for XBee input and output.
120
 *
121
 * @{
122
 **/
123

  
124
// if no baud rate is defined for usb, default is set here
125

  
126
// if no baud rate is defined for xbee, default is set here
127
#ifndef XBEE_BAUD
128
/** @brief the XBee baud rate **/
129
#define XBEE_BAUD 9600
130
#endif
131

  
132
/** @brief Initialize the XBee **/
133
void xbee_init(void);
134
/** @brief Print a character to the XBee **/
135
int xbee_putc(char c);
136
/** @brief Read a character from the XBee **/
137
int xbee_getc(void);
138
/** @brief Read a character from the XBee without blocking **/
139
int xbee_getc_nb(char *c);
140

  
141

  
142

  
143
/** @} **/ //end addtogroup
144

  
145
#endif
146

  
demos/hunter_prey/lib/src/libdragonfly/buzzer.h
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * @file buzzer.h
29
 * @brief Contains definitions for using the buzzer.
30
 *
31
 * Contains definitions for using the buzzer built into
32
 * the colony robots.
33
 *
34
 * @author Colony Project, CMU Robotics Club
35
 **/
36

  
37
#ifndef _BUZZER_H_
38
#define _BUZZER_H_
39

  
40
/**
41
 * @addtogroup buzzer
42
 * @{
43
 **/
44

  
45
//Musical note definitions
46
//Source: http://www.answers.com/topic/piano-key-frequencies
47
/** @brief Middle C **/
48
#define	C4	260 //Middle C
49
/** @brief C# **/
50
#define	C4s	277 //C sharp
51
/** @brief D **/
52
#define	D4	294
53
/** @brief D# **/
54
#define	D4s	311
55
/** @brief E **/
56
#define	E4	330
57
/** @brief F **/
58
#define	F4	349
59
/** @brief F# **/
60
#define	F4s	370
61
/** @brief G **/
62
#define	G4	392
63
/** @brief G# **/
64
#define	G4s	415
65
/** @brief A **/
66
#define	A4	440
67
/** @brief A# **/
68
#define	A4s	466
69
/** @brief B **/
70
#define	B4	494
71
/** @brief C **/
72
#define	C5	523
73

  
74
/** @brief Initialize the buzzer. **/
75
void buzzer_init(void);
76
/** @brief Set the value the buzzer plays. **/
77
void buzzer_set_val(unsigned int buzz_value);
78
/** @brief Set the frequency the buzzer plays. **/
79
void buzzer_set_freq(unsigned int buzz_freq);
80
/** @brief Play a frequency for a specified time. **/
81
void buzzer_chirp(unsigned int ms, unsigned int buzz_freq);
82
/** @brief Turn the buzzer off. **/
83
void buzzer_off(void); 
84

  
85
/** @} **/ //end addtogroup
86

  
87
#endif
88

  
demos/hunter_prey/lib/src/libdragonfly/eeprom.c
1
#include <avr/io.h>
2
#include "eeprom.h"
3

  
4
int eeprom_put_byte(unsigned int uiAddress, unsigned char ucData) {
5
    /* Wait for completion of previous write */
6
    while(EECR & (1<<EEWE));
7
    /* Set up address and data registers */
8
    EEAR = uiAddress;
9
    EEDR = ucData;
10
    /* Write logical one to EEMWE */
11
    EECR |= (1<<EEMWE);
12
    /* Start eeprom write by setting EEWE */
13
    EECR |= (1<<EEWE);
14
    
15
    return 0;
16
}
17

  
18
int eeprom_get_byte(unsigned int uiAddress, unsigned char *byte) {
19
    /* Wait for completion of previous write */
20
    while(EECR & (1<<EEWE));
21
    /* Set up address register */
22
    EEAR = uiAddress;
23
    /* Start eeprom read by writing EERE */
24
    EECR |= (1<<EERE);
25
    /* get data from data register */
26
    *byte=EEDR;
27
    
28
    return 0;
29
}
30

  
31

  
32
unsigned char get_robotid(void) {
33
    unsigned char c0, c1, c2;
34
    
35
    eeprom_get_byte(EEPROM_ROBOT_ID_ADDR, &c0);
36
    eeprom_get_byte(EEPROM_ROBOT_ID_ADDR+1, &c1);
37
    eeprom_get_byte(EEPROM_ROBOT_ID_ADDR+2, &c2);
38
    if(c0 == 'I' && c1 == 'D')
39
        return c2;
40
    else
41
        return 0xFF;
42
}
43

  
44
unsigned char get_bom_type(void) {
45
    unsigned char c0, c1, c2, c3;
46
    
47
    eeprom_get_byte(EEPROM_BOM_TYPE_ADDR, &c0);
48
    eeprom_get_byte(EEPROM_BOM_TYPE_ADDR+1, &c1);
49
    eeprom_get_byte(EEPROM_BOM_TYPE_ADDR+2, &c2);
50
    eeprom_get_byte(EEPROM_BOM_TYPE_ADDR+3, &c3);
51
    if(c0 == 'B' && c1 == 'O' && c2 == 'M')
52
        return c3;
53
    else
54
        return 0xFF;
55
}
demos/hunter_prey/lib/src/libdragonfly/reset.h
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * 
29
 * @file reset.h
30
 * @brief Contains function(s) for resetting the robots
31
 * 
32
 * @author Colony Project, CMU Robotics Club, James Kong
33
 */
34

  
35
#ifndef _RESET_H_
36
#define _RESET_H_
37

  
38
/**
39
 * @addtogroup reset
40
 * @{
41
 **/
42
 
43
/** @brief Reset the robot **/
44
void reset(void);
45

  
46
/**@}**/ //end group
47

  
48
#endif
49

  
demos/hunter_prey/lib/src/libdragonfly/rangefinder.h
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * @file rangefinder.h
29
 * @brief Contains rangefinder declarations and functions
30
 * 
31
 * Contains functions and definitions for the use of
32
 * IR rangefinders.
33
 *
34
 * @author Colony Project, CMU Robotics Club
35
 **/
36

  
37
#ifndef _RANGEFINDER_H_
38
#define _RANGEFINDER_H_
39

  
40
/**
41
 * @addtogroup rangefinder
42
 * @{
43
 **/
44

  
45
/** @brief IR Rangefinder 1 **/
46
#define IR1 6
47
/** @brief IR Rangefinder 2 **/
48
#define IR2 5
49
/** @brief IR Rangefinder 3 **/
50
#define IR3 4
51
/** @brief IR Rangefinder 4 **/
52
#define IR4 3
53
/** @brief IR Rangefinder 5 **/
54
#define IR5 2
55
/** @brief smallest meaningful rangefinder reading (logarithmic scale) **/
56
#define MIN_IR_ADC8 27
57
/** @brief largest meaningful rangefinder reading (logarithmic scale) **/
58
#define MAX_IR_ADC8 98
59
/** @brief smallest meaningful rangefinder reading (linear scale) **/
60
#define MIN_IR_LINEAR 78
61
/** @brief largest meaningful rangefinder reading (linear scale) **/
62
#define MAX_IR_LINEAR 327
63

  
64
/** @brief Initialize the rangefinders **/
65
void range_init(void);
66
/** @brief Initialize the rangefinders with option to use filtering **/
67
void range_init_filter(int filter);
68
/** @brief Read the distance from a rangefinder **/
69
int range_read_distance(int range_id);
70
/** @brief Convert logarithmic-scale distance readings to a linear scale **/
71
int linearize_distance(int value);
72
/** @brief Task that reads rangefinders and sends the values to the filter **/
73
void butter_task(void);
74
/** @brief Initialize the butterworth filter **/
75
void butter_init(void);
76
/** @brief Puts a raw rangefinder value through the Butterworth filter **/
77
void butter_filter(int range_id, int16_t val);
78
/** @brief Returns the most recent filtered reading of the rangefinder **/
79
int range_read_filtered_distance(int range_id);
80

  
81
/** @} **/ //end addtogroup
82

  
83
#endif
84

  
demos/hunter_prey/lib/src/libdragonfly/Makefile
1
############################
2
### Update this Section ####
3
############################
4

  
5
COLONYROOT = ../../..
6

  
7
# Target file name (without extension).
8
TARGET = libdragonfly
9

  
10
############################
11

  
12
CDEFS = 
13

  
14
# MCU name
15
MCU = atmega128
16

  
17

  
18
# Processor frequency.
19
#     This will define a symbol, F_CPU, in all source code files equal to the 
20
#     processor frequency. You can then use this symbol in your source code to 
21
#     calculate timings. Do NOT tack on a 'UL' at the end, this will be done
22
#     automatically to create a 32-bit value in your source code.
23
F_CPU = 16000000
24

  
25

  
26
# Output format. (can be srec, ihex, binary)
27
FORMAT = ihex
28

  
29

  
30
# List C source files here. (C dependencies are automatically generated.)
31
SRC = $(wildcard *.c)
32

  
33
# List Assembler source files here.
34
#     Make them always end in a capital .S.  Files ending in a lowercase .s
35
#     will not be considered source files but generated files (assembler
36
#     output from the compiler), and will be deleted upon "make clean"!
37
#     Even though the DOS/Win* filesystem matches both .s and .S the same,
38
#     it will preserve the spelling of the filenames, and gcc itself does
39
#     care about how the name is spelled on its command-line.
40
ASRC = 
41

  
42
# Optimization level, can be [0, 1, 2, 3, s]. 
43
#     0 = turn off optimization. s = optimize for size.
44
#     (Note: 3 is not always the best optimization level. See avr-libc FAQ.)
45
OPT = s
46

  
47
# Debugging format.
48
#     Native formats for AVR-GCC's -g are dwarf-2 [default] or stabs.
49
#     AVR Studio 4.10 requires dwarf-2.
50
#     AVR [Extended] COFF format requires stabs, plus an avr-objcopy run.
51
DEBUG = 
52
# dwarf-2
53

  
54
# List any extra directories to look for include files here.
55
#     Each directory must be seperated by a space.
56
#     Use forward slashes for directory separators.
57
#     For a directory that has spaces, enclose it in quotes.
58
EXTRAINCDIRS = 
59

  
60
# Compiler flag to set the C Standard level.
61
#     c89   = "ANSI" C
62
#     gnu89 = c89 plus GCC extensions
63
#     c99   = ISO C99 standard (not yet fully implemented)
64
#     gnu99 = c99 plus GCC extensions
65
CSTANDARD = -std=gnu99
66

  
67

  
68
# Place -D or -U options here
69
CDEFS += -DF_CPU=$(F_CPU)UL 
70

  
71
# Place -I options here
72

  
73

  
74
#---------------- Compiler Options ----------------
75
#  -g*:          generate debugging information
76
#  -O*:          optimization level
77
#  -f...:        tuning, see GCC manual and avr-libc documentation
78
#  -Wall...:     warning level
79
#  -Wa,...:      tell GCC to pass this to the assembler.
80
#    -adhlns...: create assembler listing
81
CFLAGS = -g$(DEBUG)
82
CFLAGS += $(CDEFS) $(CINCS)
83
CFLAGS += -O$(OPT)
84
CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums
85
CFLAGS += -Wall -Wstrict-prototypes
86
CFLAGS += -Wa,-adhlns=$(<:.c=.lst)
87
CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))
88
CFLAGS += $(CSTANDARD)
89

  
90

  
91
#---------------- Library Options ----------------
92
# Minimalistic printf version
93
PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min
94

  
95
# Floating point printf version (requires MATH_LIB = -lm below)
96
PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt
97

  
98
# If this is left blank, then it will use the Standard printf version.
99
PRINTF_LIB = 
100
#PRINTF_LIB = $(PRINTF_LIB_MIN)
101
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)
102

  
103
# Minimalistic scanf version
104
SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min
105

  
106
# Floating point + %[ scanf version (requires MATH_LIB = -lm below)
107
SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt
108

  
109
# If this is left blank, then it will use the Standard scanf version.
110
SCANF_LIB = 
111
#SCANF_LIB = $(SCANF_LIB_MIN)
112
#SCANF_LIB = $(SCANF_LIB_FLOAT)
113

  
114
MATH_LIB = -lm
115

  
116
#============================================================================
117

  
118

  
119
# Define programs and commands.
120
SHELL = sh
121
CC = avr-gcc
122
AR = avr-ar
123
OBJCOPY = avr-objcopy
124
OBJDUMP = avr-objdump
125
SIZE = avr-size
126
NM = avr-nm
127
AVRDUDE = avrdude
128
REMOVE = rm -f
129
REMOVEDIR = rm -rf
130
COPY = cp
131
DOXYGEN = doxygen
132
WINSHELL = cmd
133

  
134

  
135
# Define Messages
136
# English
137
MSG_ERRORS_NONE = Errors: none
138
MSG_BEGIN = -------- begin --------
139
MSG_END = --------  end  --------
140
MSG_COMPILING = Compiling:
141
MSG_CLEANING = Cleaning project:
142

  
143
# Define all object files.
144
OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) 
145

  
146
# Define all listing files.
147
LST = $(SRC:.c=.lst) $(ASRC:.S=.lst) 
148

  
149
# Compiler flags to generate dependency files.
150
GENDEPFLAGS = -MD -MP -MF .dep/$(@F).d
151

  
152
# Combine all necessary flags and optional flags.
153
# Add target processor to flags.
154
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)
155
ALL_ASFLAGS = rcs
156

  
157
# Default target.
158
all: begin build end
159

  
160
dist: all publish
161

  
162
publish:
163
	$(COPY) $(TARGET).a $(COLONYROOT)/lib/bin
164
	$(COPY) *.h $(COLONYROOT)/lib/include/$(TARGET)
165

  
166
.PHONY: docs
167
docs:
168
	$(DOXYGEN)
169
	$(COPY) docs/html/* $(COLONYROOT)/docs/$(TARGET)
170

  
171

  
172
build: $(OBJ)
173
	$(AR) $(ALL_ASFLAGS) $(TARGET).a $(OBJ)
174

  
175
# Eye candy.
176
# AVR Studio 3.x does not check make's exit code but relies on
177
# the following magic strings to be generated by the compile job.
178
begin:
179
	@echo
180
	@echo $(MSG_BEGIN)
181

  
182
end:
183
	@echo $(MSG_END)
184
	@echo
185

  
186
# Compile: create object files from C source files.
187
%.o : %.c
188
	@echo
189
	@echo $(MSG_COMPILING) $<
190
	$(CC) -c $(ALL_CFLAGS) $< -o $@ 
191

  
192

  
193
# Target: clean project.
194
clean: begin clean_list end
195

  
196
clean_list :
197
	@echo
198
	@echo $(MSG_CLEANING)
199
	$(REMOVE) $(TARGET).a
200
	$(REMOVE) $(OBJ)
201
	$(REMOVE) $(LST)
202
	$(REMOVE) $(SRC:.c=.s)
203
	$(REMOVE) $(SRC:.c=.d)
204
	$(REMOVEDIR) .dep
205

  
206

  
207

  
208
# Include the dependency files.
209
-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*)
210

  
demos/hunter_prey/lib/src/libdragonfly/eeprom.h
1
/**
2
 * @file eeprom.h
3
 * @brief handles eeprom storage for persistent data
4
 *
5
 * Contains functions and definitions for reading and writing to eeprom
6
 *
7
 * @author Colony Project, Brad Neuman
8
 */
9
 
10
 #ifndef _EEPROM_H_
11
 #define _EEPROM_H_
12
 
13
 #define EEPROM_ROBOT_ID_ADDR 0x10
14
 #define EEPROM_BOM_TYPE_ADDR 0x14
15
 
16
 /** @brief store a byte to eeproem
17
  *  @return 0 if success, nonzero on failure
18
  */
19
 int eeprom_put_byte(unsigned int addr, unsigned char byte);
20
 
21
 /** @brief reads a byte from eeprom
22
  *
23
  *  Pass it thge address and a pointer to a byte where the byte at the
24
  *  address will be stored
25
  *
26
  *  @return 0 if successful (byte is set to the eeprom value at addr), 
27
  *  nonzero if there was a problem
28
   */
29
 int eeprom_get_byte(unsigned int addr, unsigned char *byte);
30
 
31
 /** @brief get stored robot ID
32
  *
33
  *  checks that EEPROM has been programed with an ID and returns it
34
  *
35
  *  @return the robot id, if it is stored. If it returns 0xFF it is probably invalid
36
  */
37
 unsigned char get_robotid(void);
38
  
39
   /** @brief get stored robot ID
40
  *
41
  * checks that EEPROM has been programed with an BOM type and returns it
42
  *
43
  *  @return the robot bom type as defined in bom.h, if it is stored. If it returns 0xFF it is probably invalid
44
  */
45
 unsigned char get_bom_type(void);
46
 
47
 #endif
demos/hunter_prey/lib/src/libdragonfly/ring_buffer.h
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/** @file ring_buffer.h
28
 * @brief Ring Buffer
29
 *
30
 * Include macros to create a ring buffer. Originally written for 15-410.
31
 * Modified for use in ATMega128 serial driver
32
 *
33
 * @author Cornell Wright (cgwright)
34
 * @author Jason P. Winters (jpwinter)
35
 *
36
 **/
37

  
38
#ifndef _RING_BUFFER_H
39
#define _RING_BUFFER_H
40

  
41
/** @brief Creates the struct for a new ring buffer. This just expands to a
42
 *	structure definition and thus should be invoked in the global context.
43
 *
44
 *	@param struct_name Name of the ring buffer struct.
45
 *
46
 *	@param size The size of the buffer to create.
47
 *
48
 *	@param type The type of object that the queue is to hold.
49
 *
50
 *	@param ... Name or names of the instance or instances of the ring buffer(s)
51
 *	to be created.
52
 */
53
#define RING_BUFFER_NEW(struct_name, size, type, ...)	\
54
	struct struct_name {	\
55
		type queue[size];	\
56
		uint8_t start;			\
57
		uint8_t end;			\
58
		uint8_t buffer_size;			\
59
	} __VA_ARGS__
60

  
61

  
62
/** @brief Initializes the ring buffer, setting its size to the correct value
63
 *
64
 *	@param buf The ring buffer to initialize.
65
 *
66
 *  @param size The size of the ring buffer (in array elements)
67
 */
68
#define RING_BUFFER_INIT(buf, size) 			\
69
	do {										\
70
		(buf).buffer_size = size;				\
71
	} while(0)
72

  
73

  
74
/** @brief Sets the specified ring buffer to be empty.
75
 *
76
 *	@param buf The ring buffer to make empty.
77
 */
78
#define RING_BUFFER_CLEAR(buf)	\
79
	do {						\
80
		(buf).start = 0;		\
81
		(buf).end = 0;			\
82
	} while (0)
83

  
84
/** @brief Returns true if the ring buffer specified is empty.
85
 *
86
 *	@param buf The buffer to check emptiness of.
87
 */
88
#define RING_BUFFER_EMPTY(buf) ((buf).start == (buf).end)
89

  
90

  
91
/** @brief Returns true if the ring buffer specified is full.
92
 *
93
 *	@param buf The buffer to check fullness of.
94
 */
95
#define RING_BUFFER_FULL(buf)	\
96
		(((buf).end + 1) % (buf).buffer_size == (buf).start)
97

  
98

  
99
/** @brief Adds val to ring buffer buf. Note that val must be of the type
100
 *	used in creating the ring buffer to prevent the compiler from spewing
101
 *	confusing errors. Also, this assumes that the ring buffer is not full.
102
 *
103
 *	@param buf The ring buffer to add to.
104
 *	@param val The value to add.
105
 */
106
#define RING_BUFFER_ADD(buf, val)		\
107
	do {								\
108
		(buf).queue[(buf).end] = val;	\
109
		(buf).end = ((buf).end + 1) % (buf).buffer_size;	\
110
	} while (0)
111

  
112

  
113
/** @brief Removes the value at the head of the ring buffer and puts it in
114
 *	val_ret. Note that val_ret must be the same type used in creating the ring
115
 *	buffer to prevent the compiler from spewing confusing errors. Also, this
116
 *	assumes that the ring buffer is not empty.
117
 *
118
 *	@param buf The ring buffer to remove from.
119
 *	@param val_ret Where to put the value removed from the head of the ring
120
 *	buffer.
121
 */
122
#define RING_BUFFER_REMOVE(buf, val_ret)	\
123
	do {	\
124
		(val_ret) = (buf).queue[(buf).start];	\
125
		(buf).start = ((buf).start + 1) % (buf).buffer_size;	\
126
	} while (0)
127

  
128
/** @brief Checks the value at the head of the ring buffer without removing it
129
 *  and puts it into val_ret. Note that val_ret must be the same type used in
130
 *  creating the ring buffer to prevent the compiler from spewing confusing
131
 *  errors. Also, this assumes that the ring buffer is not empty.
132
 *
133
 *  @param buf The ring buffer to check from
134
 *  @param val_ret where to put the value checked from the head of the ring
135
 */
136
 #define RING_BUFFER_PEEK(buf, val_ret)  \
137
  do { \
138
    (val_ret) = (buf).queue[(buf).start]; \
139
  } while(0)
140

  
141
#endif /* _RING_BUFFER_H */
142

  
demos/hunter_prey/lib/src/libdragonfly/time.c
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * @file time.c
29
 * @brief Timer code
30
 *
31
 * Implementation of functions for timers.
32
 *
33
 * @author Colony Project, CMU Robotics Club
34
 **/
35

  
36
/*
37
  time.c
38
  anything that requires a delay
39
  mostly delay_ms
40

  
41
  author: Robotics Club, Colony Project
42

  
43
  Change Log:
44
  2.5.07 - Kevin
45
  Aaron fixed the orb/servo code and made them use timer3 but compare registers B and C. He hard set the prescaler
46
  to 8 so the RTC broke. Changed it so that we use a 8 prescaler which sets the compare match at 1/16th of a second.
47
  You now count how many 16ths of a second you want until you trigger your actual interrupt. Works. Changed defines
48
  for time so you can still call rtc_init with a scale but now it is defined in terms of actual time like second, quarter_second
49
  etc. Read that section in the time.h file for more information. Tested and works, though the clock drifts more than
50
  it used to
51
  1.30.07 - Kevin
52
  Modified the clock to run on timer3 on the Dragonfly. Works with decent accuracy. Using a prescaler of 256
53
  the timer counts up to a precomputer value which will trigger an interrupt and reset the timer. Multiples of
54
  256 change it by that multiple. Refer to the time.h file for all possible prescalers.
55
  The interrupt will call a specified function _rtc_func every pulse.
56
  All of it has been tested and it works.
57

  
58
*/
59
#include <avr/interrupt.h>
60
#include <util/delay.h>
61
#include "time.h"
62

  
63

  
64
/* Calculate how many cycles to delay for to get 1 ms. Based on F_CPU which should be defined by the makefile */
65
#ifdef F_CPU
66
#define WAIT_CYCLES ((F_CPU / 1000) / 10)
67
#else
68
#define WAIT_CYCLES (8000 / 10)
69
#endif
70

  
71
static volatile int _rtc_val = 0;
72
static volatile int _rtc_pulse = 0;
73
static volatile int _rtc_scale = 32;	//Defaults to 1 Second per pulse
74
static void (*_rtc_f)(void) = 0;
75

  
76

  
77

  
78
/**
79
 * @defgroup time Time
80
 * @brief Time functions
81
 * 
82
 * Functions dealing with time.
83
 * 
84
 * @{
85
 **/
86

  
87
/**
88
 * Delays for the specified number of milliseconds.
89
 * It depends on F_CPU to be defined in order to calculate how many cycles
90
 * it should delay. If it is not defined, a default clock of 8MHz is assumed.
91
 * 
92
 * We use _delay_loop_2 which will run assembly instructions that should be
93
 * 4 cycles long. Optimizations must be enabled for this to be true.
94
 * That function is called to ensure around 1ms per execution. To generate
95
 * multiple ms we run a for loop of how many milliseconds are desired.
96
 *
97
 * The error should be just the skew on the oscillator as the formula to 
98
 * calculate delay cycles should always be a whole number. The is some skew
99
 * in practice though it is unavoidable. Delaying for less than 1s should make
100
 * the error negligable.
101
 *
102
 * @param ms the number of milliseconds to delay for
103
 **/
104
void delay_ms(int ms) {
105
    for (; ms > 0; ms--) {
106
        _delay_loop_2(WAIT_CYCLES);
107
    }
108
}
109

  
110

  
111
/* 	Prescales defined in time.h. SECOND will give you 1 second.
112
	More scales are defined in the time.h file.
113
	rtc_func is the address to a function that you want called every clock tick. */
114
/**
115
 * Initializes the real time clock. Prescales are defined in time.h.
116
 * For example, SECOND will give 1 second. The specified function is
117
 * called every clock tick. For the real time clock to activate,
118
 * interrupts must be enabled. (through sei() )
119
 *
120
 * @param prescale_opt the period with which the timer is triggered
121
 * @param rtc_func the function called when the timer is triggered
122
 *
123
 * @see rtc_get, rtc_reset
124
 *
125
 **/
126
void rtc_init(int prescale_opt, void (*rtc_func)(void)) {
127
	
128
  //Clear timer register for Timer 3
129
  TCNT3 = 0;
130
	
131
  /* 	This sets the Waveform Generation Module to CTC (Clear Timer on Compare) Mode (100)
132
	See page135 in Atmega128 Docs for more modes and explanations */
133
  TCCR3B |= _BV(WGM32);
134
	
135
  /* 	This sets the prescaler for the system clock (8MHz) ie: divides the clock by some number.
136
	Currently set to a prescaler of 8 because that is what the orb and servos use (they are on this timer as well)
137
	See page137 in Atemga128 Docs for all the available prescalers */
138
  TCCR3B |= _BV(CS31);
139
	
140
  /* 	Sets the two regsiters that we compare against. So the timer counts up to this number and
141
	then resets back to 0 and calls the compare match interrupt.
142
	8x10^6 / 8 = 1/16 Second. All values are based off of this number. Do not change it unless you
143
	are l337*/
144
		
145
  OCR3A = 0xF424;	
146

  
147
  /* 	Enable Output Compare A Interrupt. When OCR3A is met by the timer TCNT3 this interrupt will be
148
	triggerd. (See page140 in Atmega128 Docs for more information */
149
  ETIMSK |= _BV(OCIE3A);
150
	
151
  /*	Store the pointer to the function to be used in the interrupt */
152
  _rtc_f = rtc_func;
153
	
154
  /*	Store how many 1/16ths of a second you want to let by before triggering an interrupt */
155
  _rtc_scale = prescale_opt;
156
}
157

  
158
/**
159
 * Returns the time elapsed in seconds since the last call to
160
 * rtc_init or rtc_reset.
161
 *
162
 * @return the number of seconds since the last call to rtc_init or rtc_reset
163
 *
164
 * @see rtc_init, rtc_reset
165
 **/
166
int rtc_get(void) {
167
  return _rtc_val;
168
}
169

  
170
/**
171
 * Resets the real time clock counter to 0.
172
 *
173
 * @see rtc_init, rtc_get
174
 **/
175
void rtc_reset(void) {
176
  _rtc_val = 0;
177
}
178

  
179
/** @} **/ //end defgroup
180

  
181
/*	Called every pulse. Function in _rtc_f is called every _rtc_scale and also the counter is updated.
182
	Bascially, since the pulse is hard set at 1/16s  you want to count how many 16ths of a second have passed
183
	and when it reaches the amount of time you want, execute the code. */
184
SIGNAL(TIMER3_COMPA_vect) {
185

  
186
  if (_rtc_pulse ==  _rtc_scale) {
187
    //Increment the real time clock counter
188
    _rtc_val++;
189
		
190
    //Calls the function tied to the real time clock if defined
191
    if(_rtc_f != 0)
192
      _rtc_f();
193
		
194
    //Resets the pulse until the next scale is matched
195
    _rtc_pulse = 0;
196
  }	
197
	
198
  //Updates the amount of pulses seen since the last scale match
199
  _rtc_pulse++;
200
	
201
}
demos/hunter_prey/lib/src/libdragonfly/motor.c
1
/**
2
 * Copyright (c) 2007 Colony Project
3
 * 
4
 * Permission is hereby granted, free of charge, to any person
5
 * obtaining a copy of this software and associated documentation
6
 * files (the "Software"), to deal in the Software without
7
 * restriction, including without limitation the rights to use,
8
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following
11
 * conditions:
12
 * 
13
 * The above copyright notice and this permission notice shall be
14
 * included in all copies or substantial portions of the Software.
15
 * 
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 * OTHER DEALINGS IN THE SOFTWARE.
24
 **/
25

  
26

  
27
/**
28
 * @file motor.c
29
 * @brief Motors
30
 *
31
 * Implementation of functions for controlling the motors.
32
 *
33
 * @author Colony Project, CMU Robotics Club
34
 * Much of this is taken from FWR's library, author: Tom Lauwers
35
 **/
36

  
37
#include "motor.h"
38

  
39
/**
40
 * @defgroup motors Motors
41
 * @brief Functions for controlling the motors.
42
 * Functions for controlling the motors. Found in motor.h.
43
 * @{
44
 **/
45

  
46
/**
47
 * Initializes both motors so that they can be used with future
48
 * calls to motor1_set and motor2_set.
49
 *
50
 * @see motors_off, motor1_set, motor2_set
51
 **/
52
void motors_init( void ) {
53
  // Configure counter such that we use phase correct
54
  // PWM with 8-bit resolution
55
  PORTA &= 0x0F;
56
  DDRA |= 0xF0;
57
  DDRB |= 0x60;
58

  
59
  //timer 1A and 1B
60
  TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
61
  TCCR1B = _BV(WGM12) | _BV(CS10);
62
  //	TCCR1A = 0xA1;
63
  //	TCCR1B = 0x04;
64
  OCR1AH=0;
65
  OCR1AL=0;
66
  OCR1BH=0;
67
  OCR1BL=0;
68
}
69

  
70
/**
71
 * Sets the speed and direction of the left motor.
72
 * motors_init must be called before this function can be used.
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff