// ADXL345 Register Definition #define POWER_CTL 0x2D #define _DATA_FORMAT 0x31 #define _BW_RATE 0x2C #define _DATAX0 0x32 #define _DATAX1 0x33 #define _DATAY0 0x34 #define _DATAY1 0x35 #define _DATAZ0 0x36 #define _DATAZ1 0x37 #define _FIFO_MODE 0x38 #define _SPEED 0x0F #define _ACCEL_ERROR 0x02 #define _ACCEL_ADDRESS 0x3A //alt A6 // 3A // LCD module connections sbit LCD_RS at RB4_bit; sbit LCD_EN at RB5_bit; sbit LCD_D4 at RB0_bit; sbit LCD_D5 at RB1_bit; sbit LCD_D6 at RB2_bit; sbit LCD_D7 at RB3_bit; sbit LCD_RS_Direction at TRISB4_bit; sbit LCD_EN_Direction at TRISB5_bit; sbit LCD_D4_Direction at TRISB0_bit; sbit LCD_D5_Direction at TRISB1_bit; sbit LCD_D6_Direction at TRISB2_bit; sbit LCD_D7_Direction at TRISB3_bit; int datax=0 ; unsigned char vypisX[16]; unsigned char vypisY[16]; unsigned char vypisZ[16]; int cteni[3] = {0, 0, 0}; unsigned short ADXL345_Read(unsigned short address) { unsigned short tmp = 0; I2C1_Start(); // issue I2C start signal I2C1_Wr(_ACCEL_ADDRESS); // send byte via I2C (device address + W) I2C1_Wr(address); // send byte (data address) I2C1_Start(); // issue I2C signal repeated start I2C1_Wr(_ACCEL_ADDRESS+1); // send byte (device address + R) tmp = I2C1_Rd(0); // Read the data (NO acknowledge) I2C1_Stop(); // issue I2C stop signal return tmp; } int Accel_ReadX(void) { char low_byte; int Out_x; Out_x = ADXL345_Read(_DATAX1); low_byte = ADXL345_Read(_DATAX0); Out_x = (Out_x << 8); Out_x = (Out_x | low_byte); return Out_x; } int Accel_ReadY(void) { char low_byte; int Out_y; Out_y = ADXL345_Read(_DATAY1); low_byte = ADXL345_Read(_DATAY0); Out_y = (Out_y << 8); Out_y = (Out_y | low_byte); return Out_y; } // Read Z Axis int Accel_ReadZ(void) { char low_byte; int Out_z; Out_z = ADXL345_Read(_DATAZ1); low_byte = ADXL345_Read(_DATAZ0); Out_z = (Out_z << 8); Out_z = (Out_z | low_byte); return Out_z; } // výpočet průměrné hodnoty void Accel_Average(void) { int i, sx, sy, sz; // součtové proménné sx = sy = sz = 0; // čtení posledních 16 vzorků for (i=0; i<16; i++) { sx += Accel_ReadX(); //součet vzorků sy += Accel_ReadY(); sz += Accel_ReadZ(); } //výsledný průměr po vydělení 16 cteni[0] = sx >>4; cteni[1] = sy >>4; cteni[2] = sz >>4; } void main() { ANSELB=0; ANSELC=0; PORTC = 0; PORTB = 0 ; TRISC=0; TRISB = 0 ; TRISD=1; I2C1_Init(100000) ; Lcd_Init(); Lcd_cmd(_LCD_CURSOR_OFF); I2C1_start(); I2C1_wr(0x3A); I2C1_wr(_DATA_FORMAT); I2C1_wr(0x01); I2C1_stop(); delay_ms(1); I2C1_start(); I2C1_wr(0x3A); I2C1_wr(_FIFO_MODE); I2C1_wr(0x40); I2C1_stop(); delay_ms(1); I2C1_start(); I2C1_wr(0x3A); I2C1_wr(_BW_RATE); I2C1_wr(0x0c); I2C1_stop(); delay_ms(1); I2C1_start(); I2C1_wr(0x3A); I2C1_wr(POWER_CTL); I2C1_wr(0x08); //Measurement mode I2C1_stop(); while(1) { Lcd_cmd(_LCD_CLEAR); Accel_Average(); IntToStr(cteni[0],vypisX); Lcd_out(1,2,vypisX) ; Lcd_out(1,1,"X :") ; IntToStr(cteni[1],vypisY); Lcd_out(2,2,vypisY) ; Lcd_out(2,1,"Y :") ; IntToStr(cteni[2],vypisZ); Lcd_out(1,10,vypisZ) ; Lcd_out(1,10,"Z :") ; delay_ms(150); } }