// ESP32 Dev Module

#include "Wire.h"

/*
#include <BluetoothSerial.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
*/

const int MPU_addr=0x68; // I2C address of the MPU-6050 

// Sem dobimo vrednosti
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup() {
  Wire.begin();
  Serial.begin(9600);
  
  // Pocakaj na serijski port
  while (!Serial);
  delay(1000);
  
  Serial.println("Helllloooo. ☭");

  Wire.begin(21, 22, 100000); // sda, scl, clock speed
  check_I2c(MPU_addr);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  delay(30); // Ensure gyro has enough time to power up

  Serial.println("Here we go!");

  /*
  SerialBT.begin("MotionGlove");
  Serial.print("BT on");
  */
}

void loop() {
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp);
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  Serial.print("\n");

/*
  SerialBT.write(String("/accel/0/x/" + String(AcX) + "\n"));
  SerialBT.write(String("/accel/0/y/" + String(AcY) + "\n"));
  SerialBT.write(String("/accel/0/z/" + String(AcZ) + "\n"));
  SerialBT.write(String("/gy/0/x/" + String(GyX) + "\n"));
  SerialBT.write(String("/gy/0/y/" + String(GyY) + "\n"));
  SerialBT.write(String("/gy/0/z/" + String(GyZ) + "\n"));
  SerialBT.write(String("/tmp/0/val/" + String(Tmp) + "\n"));
*/
}

byte check_I2c(byte addr){
  Serial.println("Looking for sensor...");
  
  // We are using the return value of
  // the Write.endTransmisstion to see if
  // a device did acknowledge to the address.
  byte error;
  Wire.beginTransmission(addr);
  error = Wire.endTransmission();
   
  if (error == 0) {
    Serial.print(" Device Found at 0x");
    Serial.println(addr,HEX);
  } else {
    Serial.print(" No Device Found at 0x");
    Serial.println(addr,HEX);
  }
  return error;
}
