Code: Select all
#include <esp_event.h>
#include <driver/i2c.h>
void sendMessageTo(const unsigned char registerNumber, const unsigned char command,
unsigned char write, unsigned char* const readBuffer, size_t readBufferSize) {
i2c_cmd_handle_t cmdHandler = i2c_cmd_link_create();
i2c_master_start(cmdHandler);
i2c_master_write_byte(cmdHandler, (MPU6050Address << 1) | !write, 1);
printf("%s\n", !write ? "Reading" : "Writing");
i2c_master_write_byte(cmdHandler, registerNumber, 1);
if (write) {
i2c_master_write_byte(cmdHandler, command, 1);
} else {
printf("Going to read!\n");
for (unsigned char i = readBufferSize ; i != 0 ; i--) {
printf("Requesting another register with index of %d\n", i);
i2c_master_read_byte(cmdHandler, readBuffer+(readBufferSize-i),
(i-1) == 0 ? I2C_MASTER_NACK : I2C_MASTER_ACK);
// try the NACK and last_ACK
}
}
i2c_master_stop(cmdHandler);
i2c_master_cmd_begin(I2C_NUM_0, cmdHandler, pdMS_TO_TICKS(5));
i2c_cmd_link_delete(cmdHandler);
}
inline void init_master() { // this has to be called once!
i2c_config_t masterConfig;
masterConfig.mode = I2C_MODE_MASTER;
masterConfig.master.clk_speed = 100000;
masterConfig.sda_io_num = (gpio_num_t)12;
masterConfig.scl_io_num = (gpio_num_t)14;
masterConfig.scl_pullup_en = (gpio_pullup_t)1;
masterConfig.sda_pullup_en = (gpio_pullup_t)1;
ESP_ERROR_CHECK(i2c_param_config(I2C_NUM_0, &masterConfig));
ESP_ERROR_CHECK(i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0));
sendMessageTo(MPU6050ResetRegister, MPU6050DisableTempSensor, 1, 0, 0);
sendMessageTo(MPU6050AccelConfigRegister, 0, 1, 0, 0);
sendMessageTo(MPU6050GyroConfigRegister, 0, 1, 0, 0);
printf("The master has finsihed configuration!\n");
}
}
void setup(void);
void loop(void);
void app_main() {
setup();
for (; ;) {
loop();
}
}
struct timeval getCurrentTime() {
struct timeval t;
gettimeofday(&t, NULL);
return t;
}
void setup() {
init_master();
}
void loop() {
unsigned char* buffer = (unsigned char*)calloc(2, 1);
sendMessageTo(MPU6050XAccelOutputRegister, 0, 0, buffer, 2);
free(buffer);
printf("\n\n");
vTaskDelay(pdMS_TO_TICKS(100));
}