Skip to content

MPU6050 accelerometer

MPU6050 sensor

Screenshot

Read values(Ax) from a MPU6050 accelerometer and dump them to the serial port.

examples/C/MPU6050_UART_DEMO.c

/*
Scan the I2C bus for MPU6050 and send results via UART.
*/

#include <avr/kp.h>   // Include file for I/O operations


#define REG_CONTROL 0xF4
#define CMD_TEMP 0x2E

#define REG_RESULT_AX 0x3B

int main (void)
{

uint8_t addresses[20], found, res[10]={0,0,0,0,0,0,0,0,0,0},i=0;

uint8_t accel_range_commands[] = {0x1B, 0<<3};
uint8_t gyro_range_commands[] = {0x1C, 0<<3}; // gyro range
uint8_t power_on_commands[] = {0x6B, 0x00}; // Power on
char mystring[10];

i2c_init();
uart_init(38400);


for(;;)
    {

	found = i2c_scan(&addresses[0]); // i2c scan will store the addresses in `addresses`, and return total found sensors.

	for(i=0;i<found;i++){	
		uart_send_byte_ascii(addresses[i]); // send address
		uart_send_byte(','); // send comma.

		//MPU6050 detected at 104 (0x68). read values from ax and send over UART
		if(addresses[i] == 0x68){
				// write to 0x68 (bmp180 address) , 0xF4 and 0x2E
				i2c_write(0x68 , accel_range_commands, 2); // Gyro Range . 250
				i2c_write(0x68 , gyro_range_commands, 2); //  Accelerometer Range. 2
				i2c_write(0x68 , power_on_commands, 2); // Power ON
				delay_ms(10);
				for(;;){
					// read 2 bytes from the result register for Ax
					i2c_read(0x68, REG_RESULT_AX, &res[0],2);							itoa((res[0]<<8)|(res[1]), mystring, 10);  // Convert to decimal string
					uart_send_string(mystring);
					uart_send_byte('\n');

					//uart_send_byte_ascii(res[0]); // send MSB
					//uart_send_byte(',');
					//uart_send_byte_ascii(res[1]); // send LSB
					//uart_send_byte('\n');
					delay_ms(100);
				}

			}

		}
	if(found)
		uart_send_byte('\n');
          delay_ms(500);

  }

return 0;
}

Serial Monitor

Raw values are combined into a 16 bit signed integer and itoa function is used to convert them to a string before dumping into the serial port.

Click the gauge button, and select ASCII mode to view values in a gauge. you can also use the data logger