ESP32 MPU 6050 Web server Arduino code

              



#include 
  #include 
  #include 
  #include 
  #include 
  #include 
  #include 
  #include "SPIFFS.h"
  
  // Replace with your network credentials
  const char* ssid = "MAKERSPACE";
  const char* password = "12345678";
  
  // Create AsyncWebServer object on port 80
  AsyncWebServer server(80);
  
  // Create an Event Source on /events
  AsyncEventSource events("/events");
  
  // Json Variable to Hold Sensor Readings
  JSONVar readings;
  
  // Timer variables
  unsigned long lastTime = 0;  
  unsigned long lastTimeTemperature = 0;
  unsigned long lastTimeAcc = 0;
  unsigned long gyroDelay = 10;
  unsigned long temperatureDelay = 1000;
  unsigned long accelerometerDelay = 200;
  
  // Create a sensor object
  Adafruit_MPU6050 mpu;
  
  sensors_event_t a, g, temp;
  
  float gyroX, gyroY, gyroZ;
  float accX, accY, accZ;
  float temperature;
  
  //Gyroscope sensor deviation
  float gyroXerror = 0.07;
  float gyroYerror = 0.03;
  float gyroZerror = 0.01;
  
  // Init MPU6050
  void initMPU(){
    if (!mpu.begin()) {
      Serial.println("Failed to find MPU6050 chip");
      while (1) {
        delay(10);
      }
    }
    Serial.println("MPU6050 Found!");
  }
  
  void initSPIFFS() {
    if (!SPIFFS.begin()) {
      Serial.println("An error has occurred while mounting SPIFFS");
    }
    Serial.println("SPIFFS mounted successfully");
  }
  
  // Initialize WiFi
  void initWiFi() {
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    Serial.println("");
    Serial.print("Connecting to WiFi...");
    while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
      delay(1000);
    }
    Serial.println("");
    Serial.println(WiFi.localIP());
  }
  
  String getGyroReadings(){
    mpu.getEvent(&a, &g, &temp);
  
    float gyroX_temp = g.gyro.x;
    if(abs(gyroX_temp) > gyroXerror)  {
      gyroX += gyroX_temp/50.00;
    }
    
    float gyroY_temp = g.gyro.y;
    if(abs(gyroY_temp) > gyroYerror) {
      gyroY += gyroY_temp/70.00;
    }
  
    float gyroZ_temp = g.gyro.z;
    if(abs(gyroZ_temp) > gyroZerror) {
      gyroZ += gyroZ_temp/90.00;
    }
  
    readings["gyroX"] = String(gyroX);
    readings["gyroY"] = String(gyroY);
    readings["gyroZ"] = String(gyroZ);
  
    String jsonString = JSON.stringify(readings);
    return jsonString;
  }
  
  String getAccReadings() {
    mpu.getEvent(&a, &g, &temp);
    // Get current acceleration values
    accX = a.acceleration.x;
    accY = a.acceleration.y;
    accZ = a.acceleration.z;
    readings["accX"] = String(accX);
    readings["accY"] = String(accY);
    readings["accZ"] = String(accZ);
    String accString = JSON.stringify (readings);
    return accString;
  }
  
  String getTemperature(){
    mpu.getEvent(&a, &g, &temp);
    temperature = temp.temperature;
    return String(temperature);
  }
  
  void setup() {
    Serial.begin(115200);
    initWiFi();
    initSPIFFS();
    initMPU();
  
    // Handle Web Server
    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
      request->send(SPIFFS, "/index.html", "text/html");
    });
  
    server.serveStatic("/", SPIFFS, "/");
  
    server.on("/reset", HTTP_GET, [](AsyncWebServerRequest *request){
      gyroX=0;
      gyroY=0;
      gyroZ=0;
      request->send(200, "text/plain", "OK");
    });
  
    server.on("/resetX", HTTP_GET, [](AsyncWebServerRequest *request){
      gyroX=0;
      request->send(200, "text/plain", "OK");
    });
  
    server.on("/resetY", HTTP_GET, [](AsyncWebServerRequest *request){
      gyroY=0;
      request->send(200, "text/plain", "OK");
    });
  
    server.on("/resetZ", HTTP_GET, [](AsyncWebServerRequest *request){
      gyroZ=0;
      request->send(200, "text/plain", "OK");
    });
  
    // Handle Web Server Events
    events.onConnect([](AsyncEventSourceClient *client){
      if(client->lastId()){
        Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
      }
      // send event with message "hello!", id current millis
      // and set reconnect delay to 1 second
      client->send("hello!", NULL, millis(), 10000);
    });
    server.addHandler(&events);
  
    server.begin();
  }
  
  void loop() {
    if ((millis() - lastTime) > gyroDelay) {
      // Send Events to the Web Server with the Sensor Readings
      events.send(getGyroReadings().c_str(),"gyro_readings",millis());
      lastTime = millis();
    }
    if ((millis() - lastTimeAcc) > accelerometerDelay) {
      // Send Events to the Web Server with the Sensor Readings
      events.send(getAccReadings().c_str(),"accelerometer_readings",millis());
      lastTimeAcc = millis();
    }
    if ((millis() - lastTimeTemperature) > temperatureDelay) {
      // Send Events to the Web Server with the Sensor Readings
      events.send(getTemperature().c_str(),"temperature_reading",millis());
      lastTimeTemperature = millis();
    }
  }

                

                

Uduino code

              



                // Uduino Default Board
#include
Uduino uduino("uduinoBoard"); // Declare and name your object

// Servo
#include 
#define MAXSERVOS 8


void setup()
{
  Serial.begin(9600);

#if defined (__AVR_ATmega32U4__) // Leonardo
  while (!Serial) {}
#elif defined(__PIC32MX__)
  delay(1000);
#endif

  uduino.addCommand("s", SetMode);
  uduino.addCommand("d", WritePinDigital);
  uduino.addCommand("a", WritePinAnalog);
  uduino.addCommand("rd", ReadDigitalPin);
  uduino.addCommand("r", ReadAnalogPin);
  uduino.addCommand("br", BundleReadPin);
  uduino.addCommand("b", ReadBundle);
  uduino.addInitFunction(DisconnectAllServos);
  uduino.addDisconnectedFunction(DisconnectAllServos);
}

void ReadBundle() {
  char *arg = NULL;
  char *number = NULL;
  number = uduino.next();
  int len = 0;
  if (number != NULL)
    len = atoi(number);
  for (int i = 0; i < len; i++) {
    uduino.launchCommand(arg);
  }
}

void SetMode() {
  int pinToMap = 100; //100 is never reached
  char *arg = NULL;
  arg = uduino.next();
  if (arg != NULL)
  {
    pinToMap = atoi(arg);
  }
  int type;
  arg = uduino.next();
  if (arg != NULL)
  {
    type = atoi(arg);
    PinSetMode(pinToMap, type);
  }
}

void PinSetMode(int pin, int type) {
  //TODO : vérifier que ça, ça fonctionne
  if (type != 4)
    DisconnectServo(pin);

  switch (type) {
    case 0: // Output
      pinMode(pin, OUTPUT);
      break;
    case 1: // PWM
      pinMode(pin, OUTPUT);
      break;
    case 2: // Analog
      pinMode(pin, INPUT);
      break;
    case 3: // Input_Pullup
      pinMode(pin, INPUT_PULLUP);
      break;
    case 4: // Servo
      SetupServo(pin);
      break;
  }
}

void WritePinAnalog() {
  int pinToMap = 100;
  char *arg = NULL;
  arg = uduino.next();
  if (arg != NULL)
  {
    pinToMap = atoi(arg);
  }

  int valueToWrite;
  arg = uduino.next();
  if (arg != NULL)
  {
    valueToWrite = atoi(arg);

    if (ServoConnectedPin(pinToMap)) {
      UpdateServo(pinToMap, valueToWrite);
    } else {
      analogWrite(pinToMap, valueToWrite);
    }
  }
}

void WritePinDigital() {
  int pinToMap = -1;
  char *arg = NULL;
  arg = uduino.next();
  if (arg != NULL)
    pinToMap = atoi(arg);

  int writeValue;
  arg = uduino.next();
  if (arg != NULL && pinToMap != -1)
  {
    writeValue = atoi(arg);
    digitalWrite(pinToMap, writeValue);
  }
}

void ReadAnalogPin() {
  int pinToRead = -1;
  char *arg = NULL;
  arg = uduino.next();
  if (arg != NULL)
  {
    pinToRead = atoi(arg);
    if (pinToRead != -1)
      printValue(pinToRead, analogRead(pinToRead));
  }
}

void ReadDigitalPin() {
  int pinToRead = -1;
  char *arg = NULL;
  arg = uduino.next();
  if (arg != NULL)
  {
    pinToRead = atoi(arg);
  }

  if (pinToRead != -1)
    printValue(pinToRead, digitalRead(pinToRead));
}

void BundleReadPin() {
  int pinToRead = -1;
  char *arg = NULL;
  arg = uduino.next();
  if (arg != NULL)
  {
    pinToRead = atoi(arg);
    if (pinToRead != -1) {
      if (pinToRead < 13)
        printValue(pinToRead, digitalRead(pinToRead));
      else
        printValue(pinToRead, analogRead(pinToRead));
    }
  }
}

Servo myservo;
void loop()
{
  uduino.update();
}

void printValue(int pin, int targetValue) {
  uduino.print(pin);
  uduino.print(" "); //<- Todo : Change that with Uduino delimiter
  uduino.println(targetValue);
  // TODO : Here we could put bundle read multiple pins if(Bundle) { ... add delimiter // } ...
}




/* SERVO CODE */
Servo servos[MAXSERVOS];
int servoPinMap[MAXSERVOS];
/*
  void InitializeServos() {
  for (int i = 0; i < MAXSERVOS - 1; i++ ) {
    servoPinMap[i] = -1;
    servos[i].detach();
  }
  }
*/
void SetupServo(int pin) {
  if (ServoConnectedPin(pin))
    return;

  int nextIndex = GetAvailableIndexByPin(-1);
  if (nextIndex == -1)
    nextIndex = 0;
  servos[nextIndex].attach(pin);
  servoPinMap[nextIndex] = pin;
}


void DisconnectServo(int pin) {
  servos[GetAvailableIndexByPin(pin)].detach();
  servoPinMap[GetAvailableIndexByPin(pin)] = 0;
}

bool ServoConnectedPin(int pin) {
  if (GetAvailableIndexByPin(pin) == -1) return false;
  else return true;
}

int GetAvailableIndexByPin(int pin) {
  for (int i = 0; i < MAXSERVOS - 1; i++ ) {
    if (servoPinMap[i] == pin) {
      return i;
    } else if (pin == -1 && servoPinMap[i] < 0) {
      return i; // return the first available index
    }
  }
  return -1;
}

void UpdateServo(int pin, int targetValue) {
  int index = GetAvailableIndexByPin(pin);
  servos[index].write(targetValue);
  delay(10);
}

void DisconnectAllServos() {
  for (int i = 0; i < MAXSERVOS; i++) {
    servos[i].detach();
    digitalWrite(servoPinMap[i], LOW);
    servoPinMap[i] = -1;
  }
}


Resources

  1. webserial visualizer
  2. MPU 6050 web server
  3. Piano Project
  4. Unity IMU
  5. Microphone control Unity Object
  6. Measure Sound level
  7. Unity Mic InputValues
  8. sound level measurement arduino
  9. LED arudino bluetooth
  10. MPU 6050 arduino tutorial
  11. Arduino Processing Visualization