Trying to use MPU6050 with ESP32C6 over Zigbee

Hey Guys,

I’m working on a project where I’m using two ESP32C6 as Zigbee modules. One is the Coordinator and the other is the Endpoint Device which is connected to a MPU6050.

My aim is to send the motion data from the Endpoint Device onto the coordinator.

I have connected the MPU6050 over i2c.

My issue is with the code that I’ve created. I’m trying to modify the example “Temperature Sensor” and “Thermostat” script to make it work for me, but I’m failing to do so.

Here’s the code for the EndPoint Device which is giving me a lot of errors, and I cannot find much help online.

#ifndef ZIGBEE_MODE_ED
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
#endif

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <ZigbeeCore.h>

#define BUTTON_PIN 9  // Boot/Reset Pin
#define ENDPOINT_NUMBER 1

Adafruit_MPU6050 mpu;

class ZigbeeMPU : public ZigbeeEP {
public:
    ZigbeeMPU(uint8_t endpoint) : ZigbeeEP(endpoint) {}

    void sendMPUData(float x, float y, float z) {
        char payload[64];
        snprintf(payload, sizeof(payload), "{\"AccelX\":%.2f, \"AccelY\":%.2f, \"AccelZ\":%.2f}", x, y, z);
        Zigbee.send(0x0001, (uint8_t *)payload, strlen(payload));  // Custom cluster ID
    }
};

ZigbeeMPU zbMPU(ENDPOINT_NUMBER);

void mpu_update(void *param) {
    for (;;) {
        sensors_event_t a, g, temp;
        mpu.getEvent(&a, &g, &temp);
        zbMPU.sendMPUData(a.acceleration.x, a.acceleration.y, a.acceleration.z);
        vTaskDelay(1000 / portTICK_PERIOD_MS);  // Delay for 1 second
    }
}

void setup() {
    Serial.begin(115200);
    while (!Serial) delay(10);

    // Initialize Button
    pinMode(BUTTON_PIN, INPUT);

    // Initialize MPU6050
    if (!mpu.begin()) {
        Serial.println("Failed to find MPU6050 sensor!");
        while (1) delay(10);
    }
    mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
    mpu.setGyroRange(MPU6050_RANGE_250_DEG);
    mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
    Serial.println("MPU6050 Initialized");

    // Initialize Zigbee
    zbMPU.setManufacturerAndModel("Motion_sensor", "ZigbeeMPU");
    Zigbee.addEndpoint(&zbMPU);
    Zigbee.begin();

    // Start Task for MPU6050 updates
    xTaskCreate(mpu_update, "mpu_update", 4096, NULL, 10, NULL);
}

void loop() {
    if (digitalRead(BUTTON_PIN) == LOW) {  // Button press detected
        delay(100);  // Debounce
        int startTime = millis();
        while (digitalRead(BUTTON_PIN) == LOW) {
            delay(50);
            if ((millis() - startTime) > 3000) {  // Factory reset
                Serial.println("Resetting Zigbee to factory settings...");
                Zigbee.factoryReset();
                ESP.restart();
            }
        }
    }
    delay(100);
}

Can someone please help me with it and point me towards the right direction please?

Thank You

P.S. Reason why I’m going with Zigbee is because later down the line I will be using multiple motion sensors, and I need to see which device is ahead of the other in real time. If Zigbee doesn’t work out for me, then I might end up switching to BLE.

Check whether the Zigbee stack is initialized successfully in the logs. Use Zigbee.setDebugLevel() (if available) to enable debugging.

HI there,

Seems like a good plan, not being Captain Obvious here but are you sure about
the steps , did you do them in this order ? and as @liaifat85 advises… without the stack right , you ain’t right…LOL :grin: :pinched_fingers:
I do it in this order, BTW.

  • Select your board from the Tools :: Board menu. E.g. ESP32C6 Dev Module
  • Select Tools :: Partition Scheme Zigbee 4MB with spiffs
  • Select Tools :: Zigbee Mode Zigbee ED (end device)
  • Select Tools :: Core Debug Level Verbose to get log output in the serial monitor

Have you compiled the example Demo for an End device? and did it work?
HTH
GL :slight_smile: PJ :v:

What BSP are you using?

Hi there,

So I figured , I better check if it still works, and as per usual it doesn’t
this code , this GIT hub example only works with BSP 3.0.0 Rc1 (alpha)

GOOD NEWS

The Seeed Wiki HERE examples do Compile and Work “Zigbee_On_Off_Light.ino”

#ifndef ZIGBEE_MODE_ED
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
#endif

#include "ZigbeeCore.h"
#include "ep/ZigbeeLight.h"

#define LED_PIN               LED_BUILTIN
#define BUTTON_PIN            9  // ESP32-C6/H2 Boot button
#define ZIGBEE_LIGHT_ENDPOINT 10

ZigbeeLight zbLight = ZigbeeLight(ZIGBEE_LIGHT_ENDPOINT);

/********************* RGB LED functions **************************/
void setLED(bool value) {
  digitalWrite(LED_PIN, value);
}

/********************* Arduino functions **************************/
void setup() {
  // Init LED and turn it OFF (if LED_PIN == RGB_BUILTIN, the rgbLedWrite() will be used under the hood)
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

  // Init button for factory reset
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  //Optional: set Zigbee device name and model
  zbLight.setManufacturerAndModel("Espressif", "ZBLightBulb");

  // Set callback function for light change
  zbLight.onLightChange(setLED);

  //Add endpoint to Zigbee Core
  log_d("Adding ZigbeeLight endpoint to Zigbee Core");
  Zigbee.addEndpoint(&zbLight);

  // When all EPs are registered, start Zigbee. By default acts as ZIGBEE_END_DEVICE
  log_d("Calling Zigbee.begin()");
  Zigbee.begin();
}

void loop() {
  // Checking button for factory reset
  if (digitalRead(BUTTON_PIN) == LOW) {  // Push button pressed
    // Key debounce handling
    delay(100);
    int startTime = millis();
    while (digitalRead(BUTTON_PIN) == LOW) {
      delay(50);
      if ((millis() - startTime) > 3000) {
        // If key pressed for more than 3secs, factory reset Zigbee and reboot
        Serial.printf("Resetting Zigbee to factory settings, reboot.\n");
        Zigbee.factoryReset();
      }
    }
  }
  delay(100);
}

Also set the Debug and Get a Veritable cornucopia of INFO! :smile: A literal Plethora of DATA :stuck_out_tongue:describing your world as the ESP32 See’s it.

here it is here:

[   140][V][esp32-hal-periman.c:235] perimanSetBusDeinit(): Dein=========== Before Setup Start ===========
Chip Info:
------------------------------------------
  Model             : ESP32-C6
  Package           : 1
  Revision          : 0.01
  Cores             : 1
  CPU Frequency     : 160 MHz
  XTAL Frequency    : 40 MHz
  Features Bitfield : 0x00000052
  Embedded Flash    : No
  Embedded PSRAM    : No
  2.4GHz WiFi       : Yes
  Classic BT        : No
  BT Low Energy     : Yes
  IEEE 802.15.4     : Yes
------------------------------------------
INTERNAL Memory Info:
------------------------------------------
  Total Size        :   455244 B ( 444.6 KB)
  Free Bytes        :   425960 B ( 416.0 KB)
  Allocated Bytes   :    22124 B (  21.6 KB)
  Minimum Free Bytes:   420980 B ( 411.1 KB)
  Largest Free Block:   393204 B ( 384.0 KB)
------------------------------------------
Flash Info:
------------------------------------------
Chip Size         :  4194304 B (4 MB)
  Block Size        :    65536 B (  64.0 KB)
  Sector Size       :     4096 B (   4.0 KB)
  Page Size         :      256 B (   0.2 KB)
  Bus Speed         : 40 MHz
  Bus Mode          : QIO
------------------------------------------
Partitions Info:
------------------------------------------
                nvs : addr: 0x00009000, size:    20.0 KB, type: DATA, subtype: NVS
            otadata : addr: 0x0000E000, size:     8.0 KB, type: DATA, subtype: OTA
               app0 : addr: 0x00010000, size:  1280.0 KB, type:  APP, subtype: OTA_0
               app1 : addr: 0x00150000, size:  1280.0 KB, type:  APP, subtype: OTA_1
             spiffs : addr: 0x00290000, size:  1388.0 KB, type: DATA, subtype: SPIFFS
         zb_storage : addr: 0x003EB000, size:    16.0 KB, type: DATA, subtype: FAT
             zb_fct : addr: 0x003EF000, size:     4.0 KB, type: DATA, subtype: FAT
           coredump : addr: 0x003F0000, size:    64.0 KB, type: DATA, subtype: COREDUMP
------------------------------------------
Software Info:
------------------------------------------
  Compile Date/Time : Dec  7 2024 13:53:35
  Compile Host OS   : windows
  ESP-IDF Version   : v5.1.4-972-g632e0c2a9f-dirty
  Arduino Version   : 3.0.6
------------------------------------------
Board Info:
------------------------------------------
 Arduino Board     : XIAO_ESP32C6
  Arduino Variant   : XIAO_ESP32C6
  Arduino FQBN      : esp32:esp32:XIAO_ESP32C6:UploadSpeed=921600,CDCOnBoot=cdc,CPUFreq=160,FlashFreq=80,FlashMode=qio,FlashSize=4M,PartitionScheme=zigbee,DebugLevel=verbose,EraseFlash=none,JTAGAdapter=default,ZigbeeMode=ed
============ Before Setup End ============
[  1322][V][esp32-hal-periman.c:235] perimanSetBusDeinit(): Deinit function for type GPIO (1) successfully set to 0x42003028
[  1322][V][esp32-hal-periman.c:160] perimanSetPinBus(): Pin 15 successfully set to type GPIO (1) with bus 0x10
[  1323][V][esp32-hal-periman.c:235] perimanSetBusDeinit(): Deinit function for type GPIO (1) successfully set to 0x42003028
[  1323][V][esp32-hal-periman.c:160] perimanSetPinBus(): Pin 9 successfully set to type GPIO (1) with bus 0xa
[  1324][D][sketch_dec7b.ino:35] setup(): Adding ZigbeeLight endpoint to Zigbee Core
[  1324][D][ZigbeeCore.cpp:63] addEndpoint(): Endpoint: 10, Device ID: 0x0100
[  1325][D][sketch_dec7b.ino:39] setup(): Calling Zigbee.begin()
[  1325][D][ZigbeeCore.cpp:94] zigbeeInit(): Initialize Zigbee stack
[  1374][D][ZigbeeCore.cpp:101] zigbeeInit(): Register all Zigbee EPs in list
[  1375][I][ZigbeeCore.cpp:109] zigbeeInit(): List of registered Zigbee EPs:
[  1376][I][ZigbeeCore.cpp:111] zigbeeInit(): Device type: On/Off Light Device, Endpoint: 10, Device ID: 0x0100
===========After Setup Start ============
INTERNAL Memory Info:
------------------------------------------
  Total Size        :   455244 B ( 444.6 KB)
  Free Bytes        : [  1379][V][ZigbeeCore.cpp:287] esp_zb_app_signal_handler(): ZDO signal: ZDO Config Ready (0x17), status: ESP_FAIL
[  1380][I][ZigbeeCore.cpp:179] esp_zb_app_signal_handler(): Zigbee stack initialized
[  1382][I][ZigbeeCore.cpp:185] esp_zb_app_signal_handler(): Device started up in  factory-reset mode
[  1382][I][ZigbeeCore.cpp:192] esp_zb_app_signal_handler(): Start network steering
  399636 B ( 390.3 KB) 
  Allocated Bytes   :    47832 B (  46.7 KB)
  Minimum Free Bytes:   399636 B ( 390.3 KB)
  Largest Free Block:   376820 B ( 368.0 KB)
------------------------------------------
GPIO Info:
------------------------------------------
  GPIO : BUS_TYPE[bus/unit][chan]
  --------------------------------------  
     3 : GPIO
     9 : GPIO
    12 : USB_DM
    13 : USB_DP
    14 : GPIO
    15 : GPIO
    16 : UART_TX[0]
    17 : UART_RX[0]
============ After Setup End =============
[  3609][I][ZigbeeCore.cpp:243] esp_zb_app_signal_handler(): Network steering was not successful (status: ESP_FAIL)
[  6836][I][ZigbeeCore.cpp:243] esp_zb_app_signal_handler(): Network steering was not successful (status: ESP_FAIL)

I don’t have the Co-ordinator setup so disregard the Fail msg. I will set it up later and test again.
NOTE: BSP 3.0.6. is used and works.

here is what @liaifat85 is referring to , BTW :+1: it’s located in the lower part.
[ 1380][I][ZigbeeCore.cpp:179] esp_zb_app_signal_handler(): Zigbee stack initialized
[ 1382][I][ZigbeeCore.cpp:185] esp_zb_app_signal_handler(): Device started up in factory-reset mode
[ 1382][I][ZigbeeCore.cpp:192] esp_zb_app_signal_handler(): Start network steering
399636 B ( 390.3 KB)

HTH
GL :slight_smile: PJ :v:

after the Co-ordinator is connected you’ll get this log output:
[ 3722][I][ZigbeeCore.cpp:237] esp_zb_app_signal_handler(): Joined network successfully (Extended PAN ID: 54:32:04:ff:fe:11:f4:a8, PAN ID: 0x1c1a, Channel:21, Short Address: 0xb33c)

[ 25025][V][ZigbeeHandlers.cpp:37] zb_attribute_set_handler(): Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)

[ 27448][V][ZigbeeHandlers.cpp:37] zb_attribute_set_handler(): Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)

[ 29819][V][ZigbeeHandlers.cpp:37] zb_attribute_set_handler(): Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)

[ 32597][V][ZigbeeHandlers.cpp:37] zb_attribute_set_handler(): Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)

and… the boot button on the switch will light the LED on the Light Device, as per the demo example on the Wiki. :v:

Hey PJ_Glasso,

Thank you for helping me out. Yes, I’ve tried the demo first. I’ve used the “Zigbee_on_off_Light” and “Zigbee_on_off_Switch” example to test out if things work out properly. I did have to play with the parameters a bit to get things right, otherwise I wasn’t able to upload anything.

Other than what you’ve mentioned in your list, I did 3 things differently

  • My flash frequency was 40Mhz instead of 80mhz

  • My Core Debug was set to “None”

  • For Coordinator, my partition scheme was “Zigbee ZCZR 4MB with spiffs”, and for EP device it
    was “Zigbee 4MB with Spiffs”

All the demo’s work well. And I didn’t have any issues working with them… My issues arise when I’m modifying the existing code and integrate MPU6050 into it.

Basically, what I’m trying to achieve is get the MPU6050 to work with the ESP32C6, which will be the EP Device, and the CR should be able to receive the data. Once I am able to receive the data, I would like to plot it onto a graph in real time. I will be using 4 different EP devices later to compare the raw data that I’m getting from the motion sensors.

I will try whatever you’ve suggested. I’ll get back with my findings once I’m done.

Hi there,

Ok , So that looks correct, The issue is what the Arduino IDE and the ESP Lib supports (limited) when it comes to ZigBee as you’ll find i.e. No send data support for EP devices like in the ESP-IDF there is ZigBee Basics.h . You could try and substitute the Temperature for the IMU “x_data” as a test. with the limited abilities. Look at the LIB’s Keywords for a hint of what you can do.

HTH
GL :slight_smile: PJ :v:

FYI, if you move over to ESP-IDF you will have full access to the Zigbee Stack capabilities. No fault of Seeed but ESpresso wants folks to use their IDE not arduino’s (BS) Hense the limited support just enough to aggravate :rage:one.:face_with_symbols_over_mouth: It’s soon will be every chip for themselves, if it keeps going this way. :stuck_out_tongue_closed_eyes:

there is a guy named Fish on the Seeed Discord Server that is all in love with these alternative communication standards if anyone whats to reach out to him

Hi there,

Yea I see his code , is very good. I think I have it working here though. it’s a tad hacky but uses the current examples that COMPILE & RUN … LOL rare!
I’ll post it in a few minutes.

HTH
GL :slight_smile: PJ :v:

Hi there,

OK So I figured it out with some Open AI hep >>>>LOL :face_with_hand_over_mouth:

So I started with the LED light and Switch Examples The Boot button turns the Xiao C6 LED “LIGHT” On/Off " it’s the ZigBee (EndPoint) from the Switch which is the (coordinator).
Once they both worked and connected and I confirmed the ZigBee Stack was init’d and the connection was working (i could press the button and observe the LED go on & Off).
Next,
I opened the Temperature Sensor Example & the corresponding Thermostat Example.
I see that I could just stuff a IMU reading in there and see if that would work… Spoiler ALERT it Does… Sort off.
IMU sends 3 parameters X,Y,& Z and the Temp is C/F only one set so I opted for just sending the X axis IMU data.
So I busted out a Grove IMU (LIS3DHTR) and plugged it into the dev board I2C port (see picture) I ran a quick example from the Wiki to verify it works, THIS ONE and it does… it prints out the X, Y, Z. and works on the C6 AOK.
connected this way (see pic) I added the echo to the Sensor end and the Thermostat end prints it out the local serial port once received from the Zigbee Sensor end. You can push the boot button to get an instant reading otherwise it sends them every 10 seconds or unless the delta on X axis changes greater than by 2… Pretty slick.

This is a cludge because arduino ZigBee espresso LIBrary doesn’t bring a lot to the table if you get my drift. but the concept “OP’s” original does work and can be performed.
HTH now here is the code… I used to Fresh Xiao ESP32C6 with BSP 3.0.6 I opened the examples and pasted my edits in so not to mess with the links in the IDE and example files, (often creating a New Sketch will break it, better to cut and paste into the originals , IMHO!)
Anyway one Xiao is on com port 12 the other is on com port 14. I do a SAVE AS after everything is working and I’m satisfied it works.i.e ZigBee_temperature_Sensor.ino , is now ZigBee_temperature_Sensor_IMU.ino

fyi;
Someone with too much time on there hands can build a ZIgBee IMU sensor EndPoint and use this as a baseline for the Coordinator to Display it or just send it out the serial port as I am.

// Zigbee IMU send data demo modified from the Temp example by PJ Glasso
// all the same ZigBee caveats apply with the tools menu, etc.
// This will read a grove connected IMU sensor and send the X,Y,& Z data out of the Serial port locally 
// It will send the X axis data as the ZigBee temperature Sensor.
// Xiao ESP32C6 was used and BSP 3.0.6 installed.
//
// ZiGbee is Fast and efficiant so compatabilty and ease to build will be deciding factors, IMO
// GL 12/08/2024
//
#ifndef ZIGBEE_MODE_ED
#error "Zigbee coordinator mode is not selected in Tools->Zigbee mode"
#endif

#include "ZigbeeCore.h"
#include "ep/ZigbeeTempSensor.h"
#include <Wire.h>
#include "LIS3DHTR.h"

#define BUTTON_PIN                  9  // Boot button for C6/H2
#define IMU_SENSOR_ENDPOINT_NUMBER  10

// Initialize the LIS3DHTR sensor
LIS3DHTR<TwoWire> LIS;
#define WIRE Wire

// Define the Zigbee endpoint for the IMU sensor
ZigbeeTempSensor zbIMUSensor = ZigbeeTempSensor(IMU_SENSOR_ENDPOINT_NUMBER);

/************************ IMU sensor *****************************/
// Function to read IMU data and update Zigbee endpoint
static void imu_sensor_value_update(void *arg) {
  for (;;) {
    // Read accelerometer data from the LIS3DHTR sensor
    float ax = LIS.getAccelerationX(); // X-axis acceleration
    float ay = LIS.getAccelerationY(); // Y-axis acceleration
    float az = LIS.getAccelerationZ(); // Z-axis acceleration

    // Output IMU data to Serial (you can monitor it for debugging)
    Serial.print("IMU sensor X: "); Serial.print(ax);
    Serial.print(", Y: "); Serial.print(ay);
    Serial.print(", Z: "); Serial.println(az);

    // Update the IMU X-axis value in the Zigbee endpoint (replace "temperature" with IMU data context)
    zbIMUSensor.setTemperature(ax);  // Use X-axis acceleration for reporting

    // Uncomment below lines to experiment with Y and Z axes
    // zbIMUSensor.setTemperature(ay);  // Use Y-axis acceleration
    // zbIMUSensor.setTemperature(az);  // Use Z-axis acceleration

    delay(1000); // Delay between updates
  }
}

/********************* Arduino functions **************************/
void setup() {
  Serial.begin(115200);
  while (!Serial) {
    delay(10);
  }

  // Init button switch
  pinMode(BUTTON_PIN, INPUT);

  // Initialize the LIS3DHTR sensor
  Wire.begin();
  LIS.begin(WIRE, 0x19);  // Set I2C address of the sensor (0x19)
  LIS.openTemp();          // Turn off temperature detection (optional)
  delay(100);

  // Set the full-scale range and data rate for the LIS3DHTR sensor
  LIS.setFullScaleRange(LIS3DHTR_RANGE_2G);
  LIS.setOutputDataRate(LIS3DHTR_DATARATE_50HZ);  // Set output data rate

  // Optional: set Zigbee device name and model
  zbIMUSensor.setManufacturerAndModel("Espressif", "ZigbeeIMUSensor");

  // Set tolerance for IMU sensor values (previously used for temperature)
  zbIMUSensor.setTolerance(0.01);

  // Add endpoint to Zigbee Core
  Zigbee.addEndpoint(&zbIMUSensor);

  // When all EPs are registered, start Zigbee in End Device mode
  Zigbee.begin();

  // Start IMU sensor reading task
  xTaskCreate(imu_sensor_value_update, "imu_sensor_update", 2048, NULL, 10, NULL);

  // Set reporting interval for IMU measurements in seconds
  zbIMUSensor.setReporting(1, 0, 0.1); // Reporting every 0.1 seconds
}

void loop() {
  // Checking button for factory reset
  if (digitalRead(BUTTON_PIN) == LOW) {  // Push button pressed
    // Key debounce handling
    delay(100);
    int startTime = millis();
    while (digitalRead(BUTTON_PIN) == LOW) {
      delay(50);
      if ((millis() - startTime) > 3000) {
        // If key pressed for more than 3 secs, factory reset Zigbee and reboot
        Serial.printf("Resetting Zigbee to factory settings, reboot.\n");
        Zigbee.factoryReset();
      }
    }
    zbIMUSensor.reportTemperature(); // Trigger immediate reporting of the X-axis value
  }
  delay(100);
}

Serial OUTPUT;

ESP-ROM:esp32c6-20220919
Build:Sep 19 2022
rst:0xc (SW_CPU),boot:0x5f (SPI_FAST_FLASH_BOOT)
Saved PC:0x4001975a
SPIWP:0xee
mode:DIO, clock div:2
load:0x4086c410,len:0xcf8
load:0x4086e610,len:0x2e30
load:0x40875728,len:0x113c
entry 0x4086c410
[   268][I][esp32-hal-i2c.c:112] i2cInit(): Initializing I2C Master: sda=22 scl=23 freq=100000
[   276][W][Wire.cpp:296] begin(): Bus already started in Master Mode.
[  1273][I][ZigbeeCore.cpp:109] zigbeeInit(): List of registered Zigbee EPs:
[  1280][I][ZigbeeCore.cpp:111] zigbeeInit(): Device type: Temperature Sensor, Endpoint: 10, Device ID: 0x0302
IMU sensor X: 0.14, Y: 0.82, Z: 0.56
[  1370][I][ZigbeeCore.cpp:179] esp_zb_app_signal_handler(): Zigbee stack initialized
IMU sensor X: 0.14, Y: 0.82, Z: 0.55
IMU sensor X: 0.13, Y: 0.81, Z: 0.46
[  3726][I][ZigbeeCore.cpp:185] esp_zb_app_signal_handler(): Device started up in non factory-reset mode
[  3735][I][ZigbeeCore.cpp:198] esp_zb_app_signal_handler(): Device rebooted
IMU sensor X: 0.21, Y: 0.52, Z: 0.82
IMU sensor X: 0.22, Y: 0.51, Z: 0.85
IMU sensor X: 0.22, Y: 0.53, Z: 0.84
IMU sensor X: 0.22, Y: 0.52, Z: 0.82
IMU sensor X: 0.22, Y: 0.53, Z: 0.84
IMU sensor X: 0.23, Y: 0.51, Z: 0.75
IMU sensor X: 0.24, Y: 0.53, Z: 0.83
IMU sensor X: 0.23, Y: 0.53, Z: 0.83
IMU sensor X: -0.14, Y: 1.11, Z: 0.29
IMU sensor X: -0.14, Y: 0.06, Z: -0.92
IMU sensor X: -0.17, Y: 0.03, Z: -0.94
IMU sensor X: -0.24, Y: 0.52, Z: 0.88
IMU sensor X: 0.13, Y: 0.61, Z: 0.80
IMU sensor X: 0.16, Y: 0.61, Z: 0.78
IMU sensor X: 0.17, Y: 0.61, Z: 0.78
IMU sensor X: 0.18, Y: 0.62, Z: 0.78
IMU sensor X: 0.42, Y: 0.59, Z: 1.46
IMU sensor X: -0.18, Y: 0.13, Z: -0.92
IMU sensor X: -0.17, Y: 0.09, Z: -0.96
IMU sensor X: -0.20, Y: 0.15, Z: -0.95
IMU sensor X: 0.10, Y: 0.70, Z: 0.69
IMU sensor X: 0.08, Y: 0.72, Z: 0.70
IMU sensor X: 0.10, Y: 0.70, Z: 0.69

ThermoStat end…

// Zigbee IMU send data demo modified from the Arduino ZigBee Temp & Thermo example 
// all the same ZigBee caveats apply with the tools menu, etc.
// This will read a grove connected IMU sensor as Temperature DATA from the X Axis of the remote IMU , echos the data out to the Serial port locally 
// It will recieve the X axis data as the ZigBee temperature Sensor.
// Xiao ESP32C6 was used and BSP 3.0.6 installed.
// 
// GL 12/08/2024 by PJ Glasso
//

#ifndef ZIGBEE_MODE_ZCZR
#error "Zigbee coordinator mode is not selected in Tools->Zigbee mode"
#endif

#include "ZigbeeCore.h"
#include "ep/ZigbeeThermostat.h"
#include <Wire.h>
#include "LIS3DHTR.h"

#define BUTTON_PIN                 9  // Boot button for C6/H2
#define IMU_SENSOR_ENDPOINT_NUMBER 5

// Initialize the LIS3DHTR sensor
LIS3DHTR<TwoWire> LIS;
#define WIRE Wire

ZigbeeThermostat zbIMUSensor = ZigbeeThermostat(IMU_SENSOR_ENDPOINT_NUMBER);

// Save IMU data
float imu_x, imu_y, imu_z;  // X, Y, Z accelerations
float imu_max_val = 10.0;  // Maximum value for the accelerometer (example range)
float imu_min_val = -10.0; // Minimum value for the accelerometer (example range)
float imu_tolerance = 0.1; // Tolerance for accelerometer data

/****************** IMU sensor handling *******************/
void receiveSensorConfig(float min_val, float max_val, float tolerance) {
    Serial.printf("IMU sensor settings: min %.2f, max %.2f, tolerance %.2f\n", min_val, max_val, tolerance);
    imu_min_val = min_val;
    imu_max_val = max_val;
    imu_tolerance = tolerance;
}

void receiveIMUData(float x_acceleration) {
    // Update accelerometer data based on received value (default is X-axis)
    imu_x = x_acceleration;

    // Optionally fetch Y and Z values if needed
    imu_y = LIS.getAccelerationY();
    imu_z = LIS.getAccelerationZ();

    // Output IMU data to Serial
    Serial.printf("Received IMU data -> X: %.2f, Y: %.2f, Z: %.2f\n", imu_x, imu_y, imu_z);
}

/********************* Arduino functions **************************/
void setup() {
    Serial.begin(115200);
    while (!Serial) {
        delay(10);
    }

    Serial.println( __FILE__ " compiled on " __DATE__ " at " __TIME__);
    Serial.println();
    Serial.println("Processor came out of reset.");

    // Init button switch
    pinMode(BUTTON_PIN, INPUT);

    // Initialize the LIS3DHTR sensor
    Wire.begin();
    LIS.begin(WIRE, 0x19);  // Set I2C address of the sensor (0x19)
    LIS.openTemp();          // Turn off temperature detection (optional)
    delay(100);

    // Set the full-scale range and data rate for the LIS3DHTR sensor
    LIS.setFullScaleRange(LIS3DHTR_RANGE_2G);
    LIS.setOutputDataRate(LIS3DHTR_DATARATE_50HZ);  // Set output data rate

    // Set callback functions for IMU data and configuration receive
    zbIMUSensor.onTempRecieve(receiveIMUData);  // X-axis acceleration as default
    zbIMUSensor.onConfigRecieve(receiveSensorConfig);

    // Optional: set Zigbee device name and model
    zbIMUSensor.setManufacturerAndModel("Espressif", "ZigbeeIMUSensor");

    // Add endpoint to Zigbee Core
    Zigbee.addEndpoint(&zbIMUSensor);

    // Open network for 180 seconds after boot
    Zigbee.setRebootOpenNetwork(180);

    // Start Zigbee with ZIGBEE_COORDINATOR mode
    Zigbee.begin(ZIGBEE_COORDINATOR);

    Serial.println("Waiting for IMU sensor to bind to the coordinator...");

    // Wait for the sensor to bind
    while (!zbIMUSensor.isBound()) {
        Serial.print(".");
        delay(500);
    }
    Serial.println("\nIMU sensor bound successfully.");

    // Get IMU sensor configuration
    zbIMUSensor.getSensorSettings();
}

void loop() {
    // Handle button switch for testing reporting intervals
    if (digitalRead(BUTTON_PIN) == LOW) {  // Push button pressed
        // Key debounce handling
        while (digitalRead(BUTTON_PIN) == LOW) {
            delay(50);
        }

        // Set reporting interval for IMU sensor
        zbIMUSensor.setTemperatureReporting(0, 10, 2);  // Set reporting interval (example)
    }

    // Print IMU sensor data every 10 seconds
    static uint32_t last_print = 0;
    if (millis() - last_print > 10000) {
        last_print = millis();

        // Request and print IMU data to Serial
        receiveIMUData(imu_x);  // Using last received X-axis value
    }
}

Serial output, Note the X axis data and when I pick up the IMU in My hand and flip it over(upside_down)

C:\Users\Dude\AppData\Local\Temp\.arduinoIDE-unsaved2024118-29344-wxmxhc.b8mh\Zigbee_Thermostat\Zigbee_Thermostat.ino compiled on Dec  8 2024 at 17:59:36

Processor came out of reset.
Waiting for IMU sensor to bind to the coordinator...
.....................................
IMU sensor bound successfully.
IMU sensor settings: min -327.68, max -327.68, tolerance 0.01
Received IMU data -> X: 0.00, Y: 0.00, Z: 0.00
Received IMU data -> X: 0.21, Y: 1.03, Z: 1.03
Received IMU data -> X: -0.14, Y: 1.03, Z: 1.03
Received IMU data -> X: -0.14, Y: 0.00, Z: 0.00
Received IMU data -> X: -0.24, Y: 1.03, Z: 1.03
Received IMU data -> X: 0.13, Y: 1.03, Z: 1.03
Received IMU data -> X: 0.42, Y: 1.03, Z: 1.03
Received IMU data -> X: -0.18, Y: 1.03, Z: 1.03
Received IMU data -> X: -0.18, Y: 0.00, Z: 0.00
Received IMU data -> X: 0.10, Y: 1.03, Z: 1.03
Received IMU data -> X: -0.05, Y: 1.03, Z: 1.03


Closest thing to Plug & Play for an IMU and C6 Nice…! :v:

HTH
GL :slight_smile: PJ :+1:

Hey @PJ_Glasso,

Thanks for the info. I’ll try the other IDE and check it out. Also trying to use VS Code to see if I can make any progress.

Other than that, thank you so much for taking those extra steps to actually set things up and trying it out for me. I will work with your code and your instructions to see if I can make it work. I was also trying to work with bluetooth, but that just kept on giving me "Compilation error :1 ".

Tried whatever I could find online to fix that error, but nothig worked.

I guess I’ll go back to Zigbee and give it one more shot.

Again, thank you a lot!!!

Hey @cgwaltney,

Thank you for your response. I will get in touch with him and see if he can help.