Bruno Allaire-Lemay
/
APP1test
df
Fork of APP1 by
Accelerometer.cpp
- Committer:
- dupm2216
- Date:
- 2017-01-14
- Revision:
- 1:7becb0e903e3
- Child:
- 3:1a9d0f0a50bf
File content as of revision 1:7becb0e903e3:
#include "Accelerometer.hpp" Accelerometer::Accelerometer(I2C& device, const int slave_address) : device(device), slave_address(slave_address) { } void Accelerometer::write_register(const char register_address, const char new_value) { const int left_shifted_slave_address = slave_address << 1; char data[2]; data[0] = register_address; data[1] = new_value; const int write_return = device.write(left_shifted_slave_address, data, 2); if(write_return < 0) { printf("Write error: I2C error"); } } char Accelerometer::read_register(const char register_address) { char result; const int left_shifted_slave_address = slave_address << 1; const int write_return = device.write(left_shifted_slave_address, ®ister_address, 1, true); if(write_return < 0) { printf("Write error: I2C error"); } const int read_return = device.read(left_shifted_slave_address, &result, 1); if(read_return != 0) { printf("Read error: I2C error (nack)"); } return result; } //axis_data must be an array of 6 bytes void Accelerometer::read_all_axis(char* axis_data) { for(int i = 0; i < NUMBER_OF_DATA_REGISTERS; ++i) { const char current_register = OUT_X_MSB_REGISTER + i; axis_data[i] = read_register(current_register); } } void Accelerometer::print_all_axis_data() { char axis_data[NUMBER_OF_DATA_REGISTERS]; for(int i=0; i<NUMBER_OF_DATA_REGISTERS; i++) { axis_data[i] = 0; } read_all_axis(axis_data); printf("Register content: "); for(int i=0; i<NUMBER_OF_DATA_REGISTERS; i++) { const int current_data = (int)(axis_data[i]); printf("%d, ", current_data); } printf("\r\n"); } void Accelerometer::set_standby() { const char previous_ctrl_reg1 = read_register(CTRL_REG1_REGISTER_ADDRESS); const char new_ctrl_reg1_value = previous_ctrl_reg1 & ~(0x01); write_register(CTRL_REG1_REGISTER_ADDRESS, new_ctrl_reg1_value); } void Accelerometer::set_active() { const char previous_ctrl_reg1 = read_register(CTRL_REG1_REGISTER_ADDRESS); const char new_ctrl_reg1_value = previous_ctrl_reg1 | 0x01; write_register(CTRL_REG1_REGISTER_ADDRESS, new_ctrl_reg1_value); } void Accelerometer::init() { set_active(); }