Using :
Wemos D1 mini pro
RTC DS1307 with Micro SD For WeMos D1 mini Data Logger DataLog Shield
MPU6050
I was not able to find the RTC and SD Card combine shield so they are separeted on the schematic.
I have tested the sketch before connecting the shield and I was able to send the accelerations to Influxdb.
Once I connected the RTC/SD Card shield, I'm not able to transfer the sketch. I's not connecting.
If I disconnect the shield, It loads the code.
I reconnect the shield and it's not able to communicate with the MPU6050.
I'm pretty shure it's related to MPU6050 AD0 and INT connection to D3 and D4.
When I deconnect those to wire, I'm able to upload the code to the bord but when I reconnect the wire, it still doesn’t work.
Any idea what it can be?
Here's my sketch:
> /* ============================================
>
> Source: https://github.com/tangophi/MPU6050_ESP8266_MQTT
>
> 2023-11-13
>
> the default sensitivity range for the accelerometer is +-2g which is equal to 16384*2, in which 16384 LSB is equal to the gravity acceleration 9.81m/s^2
>
> in the source code of mpu6050.cpp line 66 the range has been defined as follows
>
> setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
>
> by changing the number 2 into 4 the range is also changed into +-4g and the sensitivity accordingly to 8192 lbs.
>
> FS_SEL - Register 1B, Bits 3 and 4 (gyroscope sensitivity)
>
>
>
> Value written to FS_SEL - sensitivity:
>
> 0 - +-250
>
> 1 - +-500
>
> 2 - +-1000
>
> 3 - +-2000
>
>
>
> AFS_SEL - Register 1C, Bits 3 and 4 (accelerometer sensitivity)
>
>
>
> Value written to AFS_SEL - sensitivity:
>
> 0 - +-2
>
> 1 - +-4
>
> 2 - +-8
>
> 3 - +-16
>
>
>
>
>
>
>
> I2Cdev device library code is placed under the MIT license
>
> Copyright (c) 2012 Jeff Rowberg
>
>
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
>
> of this software and associated documentation files (the "Software"), to deal
>
> in the Software without restriction, including without limitation the rights
>
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
>
> copies of the Software, and to permit persons to whom the Software is
>
> furnished to do so, subject to the following conditions:
>
>
>
> The above copyright notice and this permission notice shall be included in
>
> all copies or substantial portions of the Software.
>
>
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
>
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
>
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
>
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
>
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
>
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
>
> THE SOFTWARE.
>
> ===============================================
>
> */
>
>
>
> /* This driver reads quaternion data from the MPU6060 and sends
>
> Open Sound Control messages.
>
>
>
> GY-521 NodeMCU
>
> MPU6050 devkit 1.0
>
> board Lolin Description
>
> ======= ========== ====================================================
>
> VCC VU (5V USB) Not available on all boards so use 3.3V if needed.
>
> GND G Ground
>
> SCL D1 (GPIO05) I2C clock
>
> SDA D2 (GPIO04) I2C data
>
> XDA not connected
>
> XCL not connected
>
> AD0 not connected
>
> //INT D8 (GPIO15) Interrupt pin
>
> INT
>
>
>
>
>
> */
>
>
>
> //#if defined(ESP8266)
>
> #include <ESP8266WiFi.h>
>
> //#else
>
> //#include <WiFi.h>
>
> //#endif
>
> //#include <DNSServer.h>
>
> #include <WiFiClient.h>
>
> #include <OSCMessage.h>
>
> //#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
>
> //#include <PubSubClient.h>
>
> #include <AsyncMqttClient.h> //2023-11-11
>
> #include <Ticker.h> //2023-11-11
>
> #include <ArduinoJson.h>
>
> #include "I2Cdev.h"
>
> #include <RTClib.h>
>
>
>
> #include "MPU6050_6Axis_MotionApps20.h"
>
> //#include "MPU6050.h" // not necessary if using MotionApps include file
>
>
>
> // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
>
> // is used in I2Cdev.h
>
> #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
>
> #include "Wire.h"
>
> #endif
>
>
>
> //I2C device adress
>
> #define DEVICE_RTC_ADDRESS 0x68 // I2C RTC DEVICE (confirmed with Dev6_I2C_Device_Scanner)
>
> #define DEVICE_MPU6050_ADDRESS 0x69 // I2C AHT DEVICE when AD0 is set to high (pin D4) (confirmed)
>
>
>
> RTC_DS3231 RTC;
>
>
>
> const char DEVICE_NAME[] = "ESP_MPU";
>
> const char mqtt_topic_csv[] = "/mpu6050_1/csv";
>
> const char mqtt_topic_json[] = "/mpu6050_1/json";
>
>
>
> #define WIFI_SSID "My_SSID"
>
> #define WIFI_PASSWORD "MY_PASSWORD"
>
>
>
> // IP address of your MQTT server
>
> #define MQTT_HOST IPAddress(111, 111, 11, 11) //Use your ip address
>
> #define MQTT_PORT 1883
>
>
>
> #define BUFFER_SIZE 200 //was 64
>
> #define BUFFER_THRESHOLD 48 // 75% of the buffer size - was 48
>
>
>
> char jsonBuffer[BUFFER_SIZE * 50]; // Adjust the size based on your data size
>
> char csvBuffer[BUFFER_SIZE * 50]; // Adjust the size based on your data size
>
> unsigned long startTime;
>
> unsigned long elapsedTime;
>
>
>
> // /mpu6050_1/csv
>
> //MQTT Topics //2023-11-11
>
> #define MQTT_PUB_MPU6050_CSV "mpu6050_1/csv"
>
> #define MQTT_PUB_MPU6050_JSON "mpu6050_1/json"
>
> unsigned long lastPublishTime_temp = 0; // Variable to store the last time the MQTT message was published
>
> AsyncMqttClient mqttClient;
>
> Ticker mqttReconnectTimer;
>
>
>
> WiFiEventHandler wifiConnectHandler;
>
> WiFiEventHandler wifiDisconnectHandler;
>
> Ticker wifiReconnectTimer;
>
>
>
> // Assuming mpu is an instance of MPU6050
>
> float sensitivity = 16384.0; // Sensitivity for +/- 2g full-scale range
>
>
>
> unsigned long previousMillis = 0;
>
> const long interval = 5000;
>
>
>
> void connectToWifi() {
>
> Serial.println("Connecting to Wi-Fi...");
>
> WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
>
> }
>
>
>
> void onWifiConnect(const WiFiEventStationModeGotIP& event) {
>
> Serial.println("Connected to Wi-Fi.");
>
> connectToMqtt();
>
> }
>
>
>
> void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
>
> Serial.println("Disconnected from Wi-Fi.");
>
> mqttReconnectTimer.detach();
>
> wifiReconnectTimer.once(2, connectToWifi);
>
> }
>
>
>
> void connectToMqtt() {
>
> Serial.println("Connecting to MQTT...");
>
> mqttClient.connect();
>
> }
>
>
>
> void onMqttConnect(bool sessionPresent) {
>
> Serial.println("Connected to MQTT.");
>
> Serial.print("Session present: ");
>
> Serial.println(sessionPresent);
>
> }
>
>
>
> void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
>
> Serial.println("Disconnected from MQTT.");
>
>
>
> if (WiFi.isConnected()) {
>
> mqttReconnectTimer.once(2, connectToMqtt);
>
> }
>
> }
>
>
>
> void onMqttPublish(uint16_t packetId) {
>
> Serial.print("Publish acknowledged.");
>
> Serial.print(" packetId: ");
>
> Serial.println(packetId);
>
> }
>
>
>
>
>
>
>
>
>
>
>
> // class default I2C address is 0x68
>
> // specific I2C addresses may be passed as a parameter here
>
> // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
>
> // AD0 high = 0x69
>
> MPU6050 mpu;
>
> //MPU6050 mpu(0x69); // <-- use for AD0 high
>
>
>
> /* =========================================================================
>
> NOTE: In addition to connection 5/3.3v, GND, SDA, and SCL, this sketch
>
> depends on the MPU-6050's INT pin being connected to the ESP8266 GPIO15
>
> pin.
>
> * ========================================================================= */
>
>
>
> // MPU control/status vars
>
> bool dmpReady = false; // set true if DMP init was successful
>
> uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
>
> uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
>
> uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
>
> uint16_t fifoCount; // count of all bytes currently in FIFO
>
> uint8_t fifoBuffer[64]; // FIFO storage buffer
>
>
>
> // orientation/motion vars
>
> Quaternion q; // [w, x, y, z] quaternion container
>
> VectorInt16 aa; // [x, y, z] accel sensor measurements
>
> VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
>
> VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
>
> VectorFloat gravity; // [x, y, z] gravity vector
>
> #ifdef OUTPUT_READABLE_EULER
>
> float euler[3]; // [psi, theta, phi] Euler angle container
>
> #endif
>
> #ifdef OUTPUT_READABLE_YAWPITCHROLL
>
> float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
>
> #endif
>
>
>
> // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
>
> // quaternion components in a [w, x, y, z] format (not best for parsing
>
> // on a remote host such as Processing or something though)
>
> //#define OUTPUT_READABLE_QUATERNION
>
>
>
> // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
>
> // (in degrees) calculated from the quaternions coming from the FIFO.
>
> // Note that Euler angles suffer from gimbal lock (for more info, see
>
> // http://en.wikipedia.org/wiki/Gimbal_lock)
>
> //#define OUTPUT_READABLE_EULER
>
>
>
> // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
>
> // pitch/roll angles (in degrees) calculated from the quaternions coming
>
> // from the FIFO. Note this also requires gravity vector calculations.
>
> // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
>
> // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
>
> //#define OUTPUT_READABLE_YAWPITCHROLL
>
>
>
> // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
>
> // components with gravity removed. This acceleration reference frame is
>
> // not compensated for orientation, so +X is always +X according to the
>
> // sensor, just without the effects of gravity. If you want acceleration
>
> // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
>
> #define OUTPUT_READABLE_REALACCEL
>
>
>
> // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
>
> // components with gravity removed and adjusted for the world frame of
>
> // reference (yaw is relative to initial orientation, since no magnetometer
>
> // is present in this case). Could be quite handy in some cases.
>
> //#define OUTPUT_READABLE_WORLDACCEL
>
>
>
> // uncomment "OUTPUT_TEAPOT_OSC" if you want output that matches the
>
> // format used for the InvenSense teapot demo
>
> //#define OUTPUT_TEAPOT_OSC
>
>
>
> //#define INTERRUPT_PIN 15 // use pin 15 on ESP8266
>
> #define INTERRUPT_PIN 0 // use pin D3 on ESP8266
>
> #define AD0_PIN 16 // use pin D4 on ESP8266
>
> //const int AD0_PIN = D4; // use pin D4 on ESP8266
>
>
>
>
>
>
>
> // ================================================================
>
> // === INTERRUPT DETECTION ROUTINE ===
>
> // ================================================================
>
>
>
> volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
>
> /*
>
> void dmpDataReady() {
>
> mpuInterrupt = true;
>
> }
>
> */
>
>
>
> // 2023-10-30
>
> void ICACHE_RAM_ATTR dmpDataReady() {
>
> mpuInterrupt = true;
>
> }
>
>
>
>
>
>
>
> bool mpu_setup()
>
> {
>
> /*
>
> // join I2C bus (I2Cdev library doesn't do this automatically)
>
> // ... (existing code)
>
>
>
> // initialize device
>
> Serial.println(F("Initializing I2C devices..."));
>
>
>
> if (!mpu.initialize()) {
>
> Serial.println(F("MPU6050 connection failed"));
>
> return false;
>
> }
>
>
>
>
>
> // verify connection
>
> Serial.println(F("Testing device connections..."));
>
>
>
> if (!mpu.testConnection()) {
>
> Serial.println(F("MPU6050 connection failed"));
>
> return false;
>
> }
>
>
>
> */
>
>
>
> //To change AD0 to high on MPU6050 from 0x68 to 0x69
>
> pinMode(AD0_PIN, OUTPUT); // sets the digital pin D7 as output
>
>
>
> // I2C Communication with MPU6050
>
> Wire.beginTransmission(DEVICE_MPU6050_ADDRESS);
>
>
>
>
>
> // join I2C bus (I2Cdev library doesn't do this automatically)
>
> #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
>
> Wire.begin();
>
> Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
>
> #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
>
> Fastwire::setup(400, true);
>
> #endif
>
>
>
> // initialize device
>
> Serial.println(F("Initializing I2C devices..."));
>
> mpu.initialize();
>
> pinMode(INTERRUPT_PIN, INPUT);
>
>
>
> // verify connection
>
> Serial.println(F("Testing device connections..."));
>
> Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
>
>
>
>
>
> // load and configure the DMP
>
> Serial.println(F("Initializing DMP..."));
>
> devStatus = mpu.dmpInitialize();
>
>
>
> // 2023-10-30: Calibration values found with MPU6050_calibration_Wemos_2023_10_31.ino
>
> // supply your own gyro offsets here, scaled for min sensitivity
>
> mpu.setXGyroOffset(97);
>
> mpu.setYGyroOffset(-58);
>
> mpu.setZGyroOffset(-2);
>
> mpu.setXAccelOffset(556);
>
> mpu.setYAccelOffset(-974);
>
> mpu.setZAccelOffset(1503);
>
>
>
>
>
> // make sure it worked (returns 0 if so)
>
> if (devStatus == 0) {
>
> // turn on the DMP, now that it's ready
>
> Serial.println(F("Enabling DMP..."));
>
> mpu.setDMPEnabled(true);
>
>
>
> // enable Arduino interrupt detection
>
> Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
>
> attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
>
> mpuIntStatus = mpu.getIntStatus();
>
>
>
> // set our DMP Ready flag so the main loop() function knows it's okay to use it
>
> Serial.println(F("DMP ready! Waiting for first interrupt..."));
>
> dmpReady = true;
>
>
>
> // get expected DMP packet size for later comparison
>
> packetSize = mpu.dmpGetFIFOPacketSize();
>
> Serial.print("packetSize: ");
>
> Serial.println(packetSize);
>
> } else {
>
> // ERROR!
>
> // 1 = initial memory load failed
>
> // 2 = DMP configuration updates failed
>
> // (if it's going to break, usually the code will be 1)
>
> Serial.print(F("DMP Initialization failed (code "));
>
> Serial.print(devStatus);
>
> Serial.println(F(")"));
>
> }
>
> return true; // MPU6050 initialization successful
>
>
>
> Wire.endTransmission();
>
> }
>
>
>
>
>
>
>
> void mpu_loop()
>
> {
>
>
>
> static char buf[50];
>
> static ArduinoJson::StaticJsonDocument<300> jsonDoc;
>
> static JsonObject root = jsonDoc.to<JsonObject>();
>
>
>
> static uint8_t bufferIndex = 0;
>
>
>
> //To change AD0 to high on MPU6050 from 0x68 to 0x69
>
> pinMode(AD0_PIN, OUTPUT); // sets the digital pin D7 as output
>
>
>
> // I2C Communication with RTC
>
> Wire.beginTransmission(DEVICE_RTC_ADDRESS);
>
> DateTime now = RTC.now();
>
> uint32_t timestamp = now.unixtime();
>
> // Get the current time in hours and minutes
>
> //float currentTime = now.hour() + (now.minute() / 60.0);
>
>
>
> Wire.endTransmission();
>
>
>
> // I2C Communication with MPU6050
>
> Wire.beginTransmission(DEVICE_MPU6050_ADDRESS);
>
>
>
> if (!dmpReady) return;
>
>
>
> if (!mpuInterrupt && fifoCount < packetSize) return;
>
>
>
> mpuInterrupt = false;
>
> mpuIntStatus = mpu.getIntStatus();
>
> fifoCount = mpu.getFIFOCount();
>
>
>
> if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
>
> mpu.resetFIFO();
>
> Serial.println(F("FIFO overflow!"));
>
> } else if (mpuIntStatus & 0x02) {
>
>
>
> while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
>
> mpu.getFIFOBytes(fifoBuffer, packetSize);
>
> fifoCount -= packetSize;
>
> // end of addition
>
>
>
>
>
> #ifdef OUTPUT_READABLE_QUATERNION
>
> // display quaternion values in easy matrix form: w x y z
>
> mpu.dmpGetQuaternion(&q, fifoBuffer);
>
> Serial.print("quat\t");
>
> Serial.print(q.w);
>
> Serial.print("\t");
>
> Serial.print(q.x);
>
> Serial.print("\t");
>
> Serial.print(q.y);
>
> Serial.print("\t");
>
> Serial.println(q.z);
>
> #endif
>
>
>
> #ifdef OUTPUT_TEAPOT_OSC
>
> #ifndef OUTPUT_READABLE_QUATERNION
>
> // display quaternion values in easy matrix form: w x y z
>
> mpu.dmpGetQuaternion(&q, fifoBuffer);
>
> #endif
>
> // Send OSC message
>
> OSCMessage msg("/imuquat");
>
> msg.add((float)q.w);
>
> msg.add((float)q.x);
>
> msg.add((float)q.y);
>
> msg.add((float)q.z);
>
>
>
> msg.empty();
>
> #endif
>
>
>
> #ifdef OUTPUT_READABLE_EULER
>
> // display Euler angles in degrees
>
> mpu.dmpGetQuaternion(&q, fifoBuffer);
>
> mpu.dmpGetEuler(euler, &q);
>
> Serial.print("euler\t");
>
> Serial.print(euler[0] * 180/M_PI);
>
> Serial.print("\t");
>
> Serial.print(euler[1] * 180/M_PI);
>
> Serial.print("\t");
>
> Serial.println(euler[2] * 180/M_PI);
>
> #endif
>
>
>
> #ifdef OUTPUT_READABLE_YAWPITCHROLL
>
> // display Euler angles in degrees
>
> mpu.dmpGetQuaternion(&q, fifoBuffer);
>
> mpu.dmpGetGravity(&gravity, &q);
>
> mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
>
> Serial.print("ypr\t");
>
> Serial.print(ypr[0] * 180/M_PI);
>
> Serial.print("\t");
>
> Serial.print(ypr[1] * 180/M_PI);
>
> Serial.print("\t");
>
> Serial.println(ypr[2] * 180/M_PI);
>
> #endif
>
>
>
> #ifdef OUTPUT_READABLE_REALACCEL
>
> // display real acceleration, adjusted to remove gravity
>
> mpu.dmpGetQuaternion(&q, fifoBuffer);
>
> mpu.dmpGetAccel(&aa, fifoBuffer);
>
> mpu.dmpGetGravity(&gravity, &q);
>
> mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
>
>
>
> /*
>
> //Serial.print("areal\t");
>
> Serial.print(elapsedTime);
>
> Serial.print("\t");
>
> Serial.print(aaReal.x);
>
> Serial.print("\t");
>
> Serial.print(aaReal.y);
>
> Serial.print("\t");
>
> Serial.println(aaReal.z);
>
>
>
>
>
> // Update JSON document with new sensor data
>
> jsonDoc["timestamp"] = elapsedTime;
>
> jsonDoc["X"] = aaReal.x;
>
> jsonDoc["Y"] = aaReal.y;
>
> jsonDoc["Z"] = aaReal.z;
>
>
>
> // 2023-11-12 addition from chatgpt
>
> // Serialize JSON document to a string and add it to the buffer
>
> serializeJson(jsonDoc, buf);
>
> strcat(jsonBuffer, buf);
>
> strcat(jsonBuffer, "\n"); // Add newline for better separation
>
> */
>
>
>
>
>
> // 2023-11-12 addition from chatgpt
>
> // Add CSV data to the buffer
>
> //sprintf(buf, "%lu,%d,%d,%d\n", elapsedTime, aaReal.x, aaReal.y, aaReal.z);
>
> //strcat(csvBuffer, buf);
>
>
>
> // Format the sensor data as a CSV string and store it in the 'buf' variable
>
> //sprintf(buf, "%lu,%d,%d,%d", elapsedTime, aaReal.x, aaReal.y, aaReal.z);
>
> //sprintf(buf, "sensor_data timestamp=%lu,x=%d,y=%d,z=%d", elapsedTime, aaReal.x, aaReal.y, aaReal.z);
>
>
>
> //sprintf(buf, "%lu,%d,%d,%d\n", elapsedTime, aaReal.x, aaReal.y, aaReal.z); //Si pas de RTC
>
> sprintf(buf, "%lu,%d,%d,%d\n", timestamp, aaReal.x, aaReal.y, aaReal.z); //Avec timestamp RTC
>
>
>
> // Explanation:
>
> // - %lu: Format specifier for an unsigned long integer (elapsedTime is an unsigned long)
>
> // - %d: Format specifier for a signed decimal integer (aaReal.x, aaReal.y, aaReal.z are integers)
>
> // - ,: Separator (comma in this case, as it's a CSV format)
>
> // - elapsedTime: The timestamp of the sensor data
>
> // - aaReal.x, aaReal.y, aaReal.z: Acceleration values along the X, Y, and Z axes
>
>
>
> // Add a newline character at the end
>
> //strcat(buf, "\n");
>
> strcat(csvBuffer, buf);
>
>
>
>
>
> #endif
>
>
>
> #ifdef OUTPUT_READABLE_WORLDACCEL
>
> // display initial world-frame acceleration, adjusted to remove gravity
>
> // and rotated based on known orientation from quaternion
>
> mpu.dmpGetQuaternion(&q, fifoBuffer);
>
> mpu.dmpGetAccel(&aa, fifoBuffer);
>
> mpu.dmpGetGravity(&gravity, &q);
>
> mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
>
> mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
>
>
>
> Serial.print("aworld\t");
>
> Serial.print(aaWorld.x);
>
> Serial.print("\t");
>
> Serial.print(aaWorld.y);
>
> Serial.print("\t");
>
> Serial.println(aaWorld.z);
>
>
>
> #endif
>
>
>
>
>
>
>
> bufferIndex++;
>
>
>
> // Get the current time
>
> unsigned long currentTime = millis();
>
>
>
> // Calculate the elapsed time since the start
>
> //elapsedTime = currentTime - startTime;
>
>
>
> // Check if the buffer is 75% full
>
> if (bufferIndex >= BUFFER_THRESHOLD) {
>
>
>
> // Add timestamp to the JSON message
>
> //jsonDoc["Timestamp"] = elapsedTime;
>
>
>
> // Serialize JSON document to a string and add it to the buffer
>
> //serializeJson(jsonDoc, buf);
>
> //strcat(jsonBuffer, buf);
>
> //strcat(jsonBuffer, "\n");
>
>
>
> // Format the linear acceleration data as a comma-separated string
>
> //snprintf(buf, sizeof(buf), "%d,%d,%d,%d", elapsedTime, aaReal.x, aaReal.y, aaReal.z);
>
>
>
> // Publish an MQTT CSV message
>
> uint16_t packetIdPub1 = mqttClient.publish(mqtt_topic_csv, 1, true, csvBuffer); // 2023-11-12 buf était csvBuffer
>
> Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", mqtt_topic_csv, packetIdPub1);
>
> Serial.printf("Message: %s \n", csvBuffer);
>
>
>
> // Publish an MQTT json message
>
> //uint16_t packetIdPub2 = mqttClient.publish(mqtt_topic_json, 1, true, buf);
>
> //Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", mqtt_topic_json, packetIdPub2);
>
> //Serial.printf("Message: %s \n", buf); // Use %s for string data
>
>
>
> // Reset the buffer and index
>
> //jsonBuffer[0] = '\0';
>
> //buf[0] = '\0';
>
> csvBuffer[0] = '\0';
>
> bufferIndex = 0;
>
>
>
> // Update the start time (uncomment to restart timestamp for every csv batch)
>
> //startTime = millis();
>
>
>
> }
>
>
>
> }
>
> Wire.endTransmission(); //MPU6050
>
> }
>
>
>
>
>
> void setup(void)
>
> {
>
> Serial.begin(115200);
>
> Serial.println(F("\nOrientation Sensor OSC output")); Serial.println();
>
>
>
>
>
> wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
>
> wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
>
>
>
>
>
> mqttClient.onConnect(onMqttConnect);
>
> mqttClient.onDisconnect(onMqttDisconnect);
>
> mqttClient.onPublish(onMqttPublish);
>
> mqttClient.setServer(MQTT_HOST, MQTT_PORT);
>
>
>
> connectToWifi();
>
>
>
> Serial.print(F("WiFi connected! IP address: "));
>
> Serial.println(WiFi.localIP());
>
>
>
>
>
>
>
> // I2C Communication with RTC
>
> Wire.beginTransmission(DEVICE_RTC_ADDRESS);
>
>
>
> //RTC.begin();
>
>
>
> if (! RTC.begin()) {
>
> Serial.println("Couldn't find RTC");
>
> Serial.flush();
>
> while (1) delay(10);
>
> }
>
>
>
> if (RTC.lostPower()) {
>
> Serial.println("RTC lost power, let's set the time!");
>
> // When time needs to be set on a new device, or after a power loss, the
>
> // following line sets the RTC to the date & time this sketch was compiled
>
> //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
>
> // This line sets the RTC with an explicit date & time, for example to set
>
> // January 21, 2014 at 3am you would call:
>
> // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
>
> RTC.adjust(DateTime(2023, 11, 27, 22, 43, 0));
>
> }
>
>
>
> // When time needs to be re-set on a previously configured device, the
>
> // following line sets the RTC to the date & time this sketch was compiled
>
> // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
>
> // This line sets the RTC with an explicit date & time, for example to set
>
> // January 21, 2014 at 3am you would call:
>
> // RTC.adjust(DateTime(2023, 07, 22, 1, 34, 0));
>
> /*
>
> // Check if the RTC module has been initialized
>
> if (!RTC.now().isValid()) {
>
> // Set the current date and time here if needed
>
> //RTC.adjust(DateTime(F(__DATE__), F(__Time__)));
>
> RTC.adjust(DateTime(2023, 7, 18, 20, 7, 0));
>
> }
>
> */
>
> Wire.endTransmission();
>
>
>
>
>
> // Retry MPU6050 initialization up to 5 times
>
> int maxRetries = 5;
>
> int retryCount = 0;
>
> while (!mpu_setup() && retryCount < maxRetries) {
>
> Serial.println(F("Retrying MPU6050 initialization in 5 seconds..."));
>
> delay(5000); // Wait for 5 seconds before retrying
>
> retryCount++;
>
> }
>
>
>
> if (retryCount == maxRetries) {
>
> Serial.println(F("MPU6050 initialization failed after maximum retries. Check your connections."));
>
> // You might want to handle this situation, e.g., by entering a safe state or rebooting.
>
> // For now, the program will continue, and you might get unexpected behavior.
>
> }
>
>
>
> // Initialize start time
>
> startTime = millis();
>
> }
>
>
>
>
>
>
>
> void loop(void)
>
> {
>
>
>
> /*
>
> if (WiFi.status() != WL_CONNECTED) {
>
> Serial.println();
>
> Serial.println("*** Disconnected from AP so rebooting ***");
>
> Serial.println();
>
> ESP.reset();
>
> mpu.resetFIFO();
>
> }
>
> */
>
>
>
>
>
> if (!mqttClient.connected()) {
>
> //reconnect();
>
> mpu.resetFIFO();
>
>
>
> }
>
>
>
>
>
> mpu_loop();
>
> delay(20);
>
> mpu.resetFIFO();
>
> }


