Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- File: main.c
- Version: 1.0.0
- Date: May. 11, 2006
- GP2D120 Distance Measurement Demo #1 on an ATMega8 AVR.
- ****************************************************************************
- Copyright (C) 2006 Micah Carrick <email@micahcarrick.com>
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- ****************************************************************************
- */
- #define F_CPU 8000000UL /* 8 MHz crystal clock */
- #define UART_BAUD_RATE 9600 /* UART Baud Rate */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <avr/io.h>
- #include <avr/pgmspace.h>
- #include <avr/interrupt.h>
- #include <util/delay.h>
- #include "gp2d120.h"
- #include "uart.h"
- /* initializes the ADC */
- void adc_init(void)
- {
- ADMUX = 0 | _BV(ADLAR); // channel 0, left-justified result
- ADCSRA = _BV(ADEN) | _BV(ADPS2);
- }
- /* starts an ADC conversion */
- void adc_start_conversion(void)
- {
- ADCSRA |= _BV(ADSC);
- }
- /* returns boolean value indicating if the ADC conversion is still in prgress */
- int adc_conversion_in_progress(void)
- {
- return !(ADCSRA & _BV(ADIF));
- }
- /* clears the ADC interrupt flag */
- void adc_clear_interrupt_flag(void)
- {
- ADCSRA |= _BV(ADIF);
- }
- int
- main (void)
- {
- uint8_t adc_value; /* gp2d120 ADC value */
- uint8_t distance; /* gp2d120 distance in cm */
- char buffer[4]; /* max '255\0' */
- uint8_t i; /* loop counter */
- /* initialize */
- uart_init( UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU) );
- sei();
- uart_puts_P("*** GP2D120 Test Application ***\n\r");
- adc_init();
- while (1)
- {
- /* get ADC value */
- adc_start_conversion();
- while (adc_conversion_in_progress());
- adc_value = ADCH;
- adc_clear_interrupt_flag();
- /* calculate the distance */
- distance = gp2d120_adc8_to_cm(adc_value);
- /* convert ADC value to ascii for UART */
- itoa (adc_value, buffer, 10);
- uart_putc('\t');
- uart_puts(buffer);
- /* convert distance to ascii for UART */
- itoa (distance, buffer, 10);
- uart_putc('\t');
- uart_puts(buffer);
- uart_puts_P("cm\n\r");
- /* long delay */
- for (i=0; i<20; i++) { _delay_ms(250); }
- }
- return (0);
- }
Add Comment
Please, Sign In to add comment