Raphaël Drouin
/
I2C_comm
I2C_comm
main.cpp
- Committer:
- ShaolinPoutine
- Date:
- 2017-01-16
- Revision:
- 2:a83e46376681
- Parent:
- 1:7f23dfc59683
File content as of revision 2:a83e46376681:
#include "mbed.h" Serial pc(USBTX,USBRX); I2C accelero(p28, p27); SPI afficheurSPI(p5, p6, p7); DigitalOut afficheurSelect(p8); const char reg[] = {0x0d}; const int device = 0x3A; char data[1]; int radtodeg = 57; int16_t normal[3] = {0,0,1}; int printDecimalNumber(int i){ char chiffres[4]; if (i > 9999) { afficheurSelect = 0; afficheurSPI.write(0x76); afficheurSPI.write('e'); afficheurSPI.write('e'); afficheurSPI.write('e'); afficheurSPI.write('e'); wait(0.001); afficheurSelect = 1; } else { // Convert number to char list chiffres[0] = i / 1000; chiffres[1] = (i - int(chiffres[0]) * 1000) / 100; chiffres[2] = (i - int(chiffres[0]) * 1000 - int(chiffres[1]) * 100) / 10; chiffres[3] = i - int(chiffres[0]) * 1000 - int(chiffres[1]) * 100 - int(chiffres[2]) * 10; afficheurSelect= 0; afficheurSPI.write(0x76); afficheurSPI.write(0x77); afficheurSPI.write(0b00000010); for (int x = 0; x < 4; x++) { afficheurSPI.write(chiffres[x]); } wait(0.001); afficheurSelect = 1; } return 0; } int main() { afficheurSPI.frequency(100000); accelero.write(device,reg,1,true); accelero.read(device,data,1); pc.printf("Result : %d \r\n", data[0]); printDecimalNumber((int) data[0]); // Set 2g max char XYZ_DATA_CFG[2] = {0x0e, 0}; char value[1]; accelero.read(device, XYZ_DATA_CFG, 1, true); accelero.write(device, value, 1); value[0] = value[0] & 0xFC; XYZ_DATA_CFG[1] = value[0]; accelero.write(device, XYZ_DATA_CFG, 2); // Activate accelerometer char ctrlReg1[2] = {0x2a, 0}; accelero.write(device, ctrlReg1, 1, true); accelero.read(device, value, 1); value[0] = value[0] | 0x1; ctrlReg1[1] = value[0]; accelero.write(device, ctrlReg1, 2); char XYZ_Data = 0x01; char data[6]; int16_t x, y, z; int16_t buffer; int mean[32]; int angle; int iteration = 0; while(1) { accelero.write(device, &XYZ_Data, 1, true); accelero.read(device, data, 6); ((char*) &buffer)[0]= data[1]; //LSB ((char*) &buffer)[1]= data[0]; //MSB x = buffer >> 4; ((char*) &buffer)[0]= data[3]; //LSB ((char*) &buffer)[1]= data[2]; //MSB y = buffer >> 4; ((char*) &buffer)[0]= data[5]; //LSB ((char*) &buffer)[1]= data[4]; //MSB z = buffer >> 4; if (z > 1024) z = 1024; if (z < -1024) z = -1024; int theta = std::acos((double) z / (double) 1024) * radtodeg * 100; mean[iteration % 32] = theta >> 5; if (iteration % 16 == 0){ angle = 0; for (int i = 0; i < 32; i++){ angle += mean[i]; } printDecimalNumber(angle); } wait(0.006); iteration++; } }