Guest User

maxEmbedded.com Accelerometer Code

a guest
Jun 28th, 2013
214
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #ifndef F_CPU
  2. #define F_CPU 16000000UL
  3. #endif
  4.  
  5. #include <avr/io.h>
  6. #include <stdlib.h>     //include Library for 'itoa' function
  7. #include "lcd.h"        //include LCD Library
  8. #include <util/delay.h>
  9.  
  10. void adc_init(void)
  11. {
  12.     ADCSRA|=(1<<ADEN)|(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2); //ENABLE ADC, PRESCALER 128
  13.     ADMUX|=(1<<REFS0);      //PC0, AVcc AS REFERENCE VOLTAGE
  14. }
  15.  
  16. uint16_t adc_read(uint8_t ch)
  17. {
  18.     ch&=0b00000111;         //ANDing to limit input to 7
  19.     ADMUX = (ADMUX & 0xf8)|ch;  //Clear last 3 bits of ADMUX, OR with ch
  20.     ADCSRA|=(1<<ADSC);      //START CONVERSION
  21.     while((ADCSRA)&(1<<ADSC));  //WAIT UNTIL CONVERSION IS COMPLETE
  22.     return(ADC);        //RETURN ADC VALUE
  23. }
  24.  
  25. int main(void)
  26. {
  27.     uint16_t x,y,z;
  28.     char bufferx[10], buffery[10], bufferz[10]; //Initialize character arrays for each
  29.      
  30.     adc_init();         //INITIALIZE ADC
  31.     lcd_init(LCD_DISP_ON);  //INITIALIZE LCD
  32.     lcd_clrscr();       //CLEAR LCD SCREEN
  33.      
  34.     while(1)
  35.     {
  36.         lcd_home();         //LCD - GO TO HOME POSITION
  37.  
  38.         x=adc_read(0);      //READ ADC VALUE FROM CHANNEL 0
  39.         y=adc_read(1);      //READ ADC VALUE FROM CHANNEL 1
  40.         z=adc_read(2);      //READ ADC VALUE FROM CHANNEL 2
  41.  
  42.         itoa(x,bufferx,10);     //STORE THE ADC VALUES IN ARRAYS
  43.         itoa(y,buffery,10);
  44.         itoa(z,bufferz,10);
  45.  
  46.         lcd_puts("x=");     //DISPLAY THE RESULTS ON LCD
  47.         lcd_gotoxy(2,0);
  48.         lcd_puts(bufferx);
  49.  
  50.         lcd_gotoxy(0,1);
  51.         lcd_puts("y=");
  52.         lcd_gotoxy(2,1);
  53.         lcd_puts(buffery);
  54.  
  55.         lcd_gotoxy(6,0);
  56.         lcd_puts("z=");
  57.         lcd_gotoxy(6,1);
  58.         lcd_puts(bufferz);
  59.     }
  60. }
RAW Paste Data